Java 类java.util.logging.Logger 实例源码

项目:rapidminer    文件:LogService.java   
private LogService(Logger logger) {
    super(logger);

    // setup a log file if the execution mode can access the filesystem (e.g. not for RA)
    // we want our logfile to look the same regardless of any user settings, so ignore
    // a possible user logging property config file
    if (RapidMiner.getExecutionMode().canAccessFilesystem()) {
        try {
            FileHandler logFileHandler = new FileHandler(FileSystemService.getLogFile().getAbsolutePath(), false);
            logFileHandler.setLevel(Level.ALL);
            logFileHandler.setFormatter(new SimpleFormatter());
            LogService.getRoot().addHandler(logFileHandler);
        } catch (IOException e) {
            LogService.getRoot().log(Level.WARNING, "com.rapidminer.logservice.logfile.failed_to_init", e.getMessage());
        }
    }
}
项目:websocket-chat    文件:ChatServer.java   
@OnMessage
public void msgReceived(ChatMessage msg, Session s) {
    if (msg.getMsg().equals(LOGOUT_MSG)) {
        try {
            s.close();
            return;
        } catch (IOException ex) {
            Logger.getLogger(ChatServer.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    Predicate<Session> filterCriteria = null;
    if (!msg.isPrivate()) {
        //for ALL (except self)
        filterCriteria = (session) -> !session.getUserProperties().get("user").equals(user);
    } else {
        String privateRecepient = msg.getRecepient();
        //private IM
        filterCriteria = (session) -> privateRecepient.equals(session.getUserProperties().get("user"));
    }

    s.getOpenSessions().stream()
            .filter(filterCriteria)
            //.forEach((session) -> session.getAsyncRemote().sendText(msgContent));
            .forEach((session) -> session.getAsyncRemote().sendObject(new Reply(msg.getMsg(), user, msg.isPrivate())));

}
项目:incubator-netbeans    文件:DelayScanRegistry.java   
/**
 * Delays given task if neccessary - e.g. projects are currently openning - and reschedules the task if indexing is running
 * This method waits for projects to open and thus blocks the current thread.
 * @param task task to be delayed
 * @param logger 
 * @param logMessagePrefix
 * @return true if the task was rescheduled
 */
public boolean isDelayed (RequestProcessor.Task task, Logger logger, String logMessagePrefix) {
    boolean rescheduled = false;
    DelayedScan scan = getRegisteredScan(task);
    Future<Project[]> projectOpenTask = OpenProjects.getDefault().openProjects();
    if (!projectOpenTask.isDone()) {
        try {
            projectOpenTask.get();
        } catch (Exception ex) {
            // not interested
        }
    }
    if (IndexingBridge.getInstance().isIndexingInProgress()
            && (BLOCK_INDEFINITELY || scan.waitingLoops * WAITING_PERIOD < MAX_WAITING_TIME)) {
        // do not steal disk from openning projects and indexing tasks
        Level level = ++scan.waitingLoops < 10 ? Level.FINE : Level.INFO;
        logger.log(level, "{0}: Scanning in progress, trying again in {1}ms", new Object[]{logMessagePrefix, WAITING_PERIOD}); //NOI18N
        task.schedule(WAITING_PERIOD); // try again later
        rescheduled = true;
    } else {
        scan.waitingLoops = 0;
    }
    return rescheduled;
}
项目:incubator-netbeans    文件:Utils.java   
/**
 * Helper method to get an array of Strings from preferences.
 *
 * @param prefs storage
 * @param key key of the String array
 * @return List<String> stored List of String or an empty List if the key was not found (order is preserved)
 */
public static List<String> getStringList(Preferences prefs, String key) {
    List<String> retval = new ArrayList<String>();
    try {
        String[] keys = prefs.keys();
        for (int i = 0; i < keys.length; i++) {
            String k = keys[i];
            if (k != null && k.startsWith(key)) {
                int idx = Integer.parseInt(k.substring(k.lastIndexOf('.') + 1));
                retval.add(idx + "." + prefs.get(k, null));
            }
        }
        List<String> rv = new ArrayList<String>(retval.size());
        rv.addAll(retval);
        for (String s : retval) {
            int pos = s.indexOf('.');
            int index = Integer.parseInt(s.substring(0, pos));
            rv.set(index, s.substring(pos + 1));
        }
        return rv;
    } catch (Exception ex) {
        Logger.getLogger(Utils.class.getName()).log(Level.INFO, null, ex);
        return new ArrayList<String>(0);
    }
}
项目:incubator-netbeans    文件:RepositoryUpdater2Test.java   
@Override
protected void setUp() throws Exception {
    TopLogging.initializeQuietly();

    super.setUp();

    this.clearWorkDir();
    final File _wd = this.getWorkDir();
    workDir = FileUtil.toFileObject(_wd);

    FileObject cache = workDir.createFolder("cache");
    CacheFolder.setCacheFolder(cache);
    RootsListener.setUseAsyncListneres(false);

    ruSync = new RepositoryUpdaterTest.TestHandler();
    final Logger logger = Logger.getLogger(RepositoryUpdater.class.getName() + ".tests");
    logger.setLevel(Level.FINEST);
    logger.addHandler(ruSync);

    RepositoryUpdaterTest.waitForRepositoryUpdaterInit();
}
项目:NGSI-LD_Wrapper    文件:Main.java   
/**
 * Main method.
 * @param args
 * @throws IOException
 */
public static void main(String[] args) throws IOException {
    Logger log = Logger.getLogger(Main.class.getName());

    log.log(Level.WARNING,"Starting server .....");

    Logger log2 = Logger.getLogger("org.glassfish");
    log2.setLevel(Level.ALL);
    log2.addHandler(new java.util.logging.ConsoleHandler());

    final HttpServer server = startServer();
    System.out.println(String.format("Jersey app started with WADL available at "
            + "%sapplication.wadl\nHit enter to stop it...", BASE_URI));
    System.in.read();
    server.stop();
}
项目:jTransactions    文件:TinyTxLogger.java   
public TinyTxLogger(Class<?> targetClass) {
    if (targetClass == null)
        throw new AssertionError("TinyTxLogger error: targetClass can not be null.");
    try {
        Class<?> logFactoryClass = Class.forName("org.apache.commons.logging.LogFactory");
        Method method = logFactoryClass.getMethod("getLog", Class.class);
        commonLogger = method.invoke(logFactoryClass, targetClass);
        commonLoggerInfoMethod = commonLogger.getClass().getMethod("info", Object.class);
        commonLoggerWarnMethod = commonLogger.getClass().getMethod("warn", Object.class);
        commonLoggerErrorMethod = commonLogger.getClass().getMethod("error", Object.class);
    } catch (Exception e) {
        // do nothing
    }

    if (commonLogger == null || commonLoggerWarnMethod == null) {
        if (firstRun)
            System.err.println("TinyTxLogger failed to load org.apache.commons.logging.LogFactory. Use JDK logger.");// NOSONAR
        jdkLogger = Logger.getLogger(targetClass.getName());// use JDK log
    } else if (firstRun)
        System.out.println("org.apache.commons.logging.LogFactory loaded, DbProLogger use it as logger.");// NOSONAR
}
项目:tcp    文件:ConnectionConfiguration.java   
public static Connection conectar(){
Connection con = null;
      Statement st = null;
      ResultSet rs = null;
      try {Class.forName("org.postgresql.Driver");}
      catch (ClassNotFoundException e) {e.printStackTrace();}
      String url = "";
      String user = "postgres";
      String password = "postgres";

      try {con = DriverManager.getConnection("jdbc:postgresql://pg01.stp.gov.py/tablero2015v3?useUnicode=true&characterEncoding=UTF-8&user=postgres&password=postgres");}
      catch (SQLException ex) {
          Logger lgr = Logger.getLogger(SqlHelper.class.getName());
          lgr.log(Level.SEVERE, ex.getMessage(), ex);
      } 
      return con;
 }
项目:alvisnlp    文件:TomapProjector.java   
@Override
protected void fillTrie(Logger logger, Trie<Attribution> trie, Corpus corpus) throws IOException, ModuleException {
    try {
        CandidateClassifier classifier = tomapClassifier.readClassifier(this, logger);
        Collection<Candidate> candidates = readCandidates(logger);
        for (Candidate cand : candidates) {
            List<Attribution> attributions = classifier.classify(cand);
            if (attributions.isEmpty()) {
                continue;
            }
            CharSequence key = getCandidateKey(cand);
            for (Attribution attr : attributions) {
                trie.addEntry(key, attr);
            }
        }
    }
    catch (SAXException|ParserConfigurationException e) {
        rethrow(e);
    }
}
项目:incubator-netbeans    文件:Installer.java   
private boolean checkUserName(ReportPanel panel) {
    checkingResult = true;
    try {
        String login = URLEncoder.encode(panel.getUserName(), "UTF-8");
        String encryptedPasswd = URLEncoder.encode(PasswdEncryption.encrypt(new String(panel.getPasswdChars())), "UTF-8");
        char[] array = new char[100];
        URL checkingServerURL = new URL(NbBundle.getMessage(Installer.class, "CHECKING_SERVER_URL", login, encryptedPasswd));
        URLConnection connection = checkingServerURL.openConnection();
        connection.setRequestProperty("User-Agent", "NetBeans");
        connection.setReadTimeout(20000);
        Reader reader = new InputStreamReader(connection.getInputStream());
        int length = reader.read(array);
        checkingResult = Boolean.valueOf(new String(array, 0, length));
    } catch (UnsupportedEncodingException ex) {
        Exceptions.printStackTrace(ex);
    } catch (Exception exception) {
        Logger.getLogger(Installer.class.getName()).log(Level.INFO, "Checking password failed", exception); // NOI18N
    }
    return checkingResult;
}
项目:incubator-netbeans    文件:Utils.java   
/**
 * Stores a List of Strings into Preferences node under the given key.
 *
 * @param prefs storage
 * @param key key of the String array
 * @param value List of Strings to write (order will be preserved)
 */
public static void put(Preferences prefs, String key, List<String> value) {
    try {
        String[] keys = prefs.keys();
        for (int i = 0; i < keys.length; i++) {
            String k = keys[i];
            if (k != null && k.startsWith(key + ".")) {
                prefs.remove(k);
            }
        }
        int idx = 0;
        for (String s : value) {
            prefs.put(key + "." + idx++, s);
        }
    } catch (BackingStoreException ex) {
        Logger.getLogger(Utils.class.getName()).log(Level.INFO, null, ex);
    }
}
项目:NeverLag    文件:WMI4Java.java   
public List<String> listProperties(String wmiClass) throws WMIException {
    List<String> foundPropertiesList = new ArrayList<>();
    try {
        String rawData = getWMIStub().listProperties(wmiClass, this.namespace, this.computerName);

        String[] dataStringLines = rawData.split(NEWLINE_REGEX);

        for (final String line : dataStringLines) {
            if (!line.isEmpty()) {
                foundPropertiesList.add(line.trim());
            }
        }

        List<String> notAllowed = Arrays.asList("Equals", "GetHashCode", "GetType", "ToString");
        foundPropertiesList.removeAll(notAllowed);

        return foundPropertiesList;
    } catch (Exception ex) {
        Logger.getLogger(WMI4Java.class.getName()).log(Level.SEVERE, GENERIC_ERROR_MSG, ex);
        throw new WMIException(ex);
    }
}
项目:G2Dj    文件:OggStreamer.java   
@Override public void run() 
{
    playback();  

    while (update())
    {
        try {Thread.sleep(sleepTime);} 
        catch (InterruptedException ex) {Logger.getLogger(OggStreamer.class.getName()).log(Level.SEVERE, null, ex);}

    }

    Debug.log("playback has ended");
    canStart = true;
    m_OggDecoder.reset();

}
项目:ProjectAres    文件:MobsModule.java   
public static MobsModule parse(MapModuleContext context, Logger logger, Document doc) throws InvalidXMLException {
    FilterParser filterParser = context.needModule(FilterParser.class);
    Element mobsEl = doc.getRootElement().getChild("mobs");
    Filter mobsFilter = StaticFilter.DENY;
    if(mobsEl != null) {
        if(context.getProto().isNoOlderThan(ProtoVersions.FILTER_FEATURES)) {
            mobsFilter = filterParser.parseProperty(mobsEl, "filter");
        } else {
            Element filterEl = XMLUtils.getUniqueChild(mobsEl, "filter");
            if(filterEl != null) {
                mobsFilter = filterParser.parseElement(filterEl);
            }
        }
    }
    return new MobsModule(mobsFilter);
}
项目:Dr-Assistant    文件:DrugGetway.java   
public boolean save(Drug drug) {
    if (dbll.isValid(drug)) {
        if (dbll.isUnique(drug, 0)) {
            con = connection.geConnection();
            try {
                pst = con.prepareStatement("insert into drug values(?,?,?,?,?)");
                pst.setString(1, null);
                pst.setString(2, drug.getName());
                pst.setString(3, drug.getGenricName());
                pst.setString(4, drug.getNote());
                pst.setString(5, drug.getCreatedAt());
                pst.executeUpdate();
                pst.close();
                con.close();
                connection.con.close();
                return true;
            } catch (SQLException ex) {
                Logger.getLogger(DrugGetway.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

    }
    return false;
}
项目:openjdk-jdk10    文件:GenericConstructor.java   
/** Create an instance of type T using the constructor that
 * matches the given arguments if possible.  The constructor
 * is cached, so an instance of GenericClass should always be
 * used for the same types of arguments.  If a call fails,
 * a check is made to see if a different constructor could
 * be used.
 * @param args The constructor arguments.
 * @return A new instance of the object.
 */
public synchronized T create( Object... args ) {
    synchronized(lock) {
        T result = null ;

        for (int ctr=0; ctr<=1; ctr++) {
            getConstructor() ;
            if (constructor == null) {
                break ;
            }

            try {
                result = resultType.cast( constructor.newInstance( args ) ) ;
                break ;
            } catch (Exception exc) {
                // There are 4 checked exceptions here with identical handling.
                // Ignore FindBugs complaints.
                constructor = null ;
                Logger.getLogger("com.sun.org.glassfish.gmbal.util").
                    log(Level.WARNING, "Error invoking constructor", exc );
            }
        }

        return result ;
    }
}
项目:incubator-netbeans    文件:AnnotationTypeActionsFolder.java   
/** Factory method for AnnotationTypeActionsFolder instance. */
public static boolean readActions(AnnotationType type, String subFolder) {

    FileObject f = FileUtil.getConfigFile(FOLDER + subFolder);
    if (f == null) {
        return false;
    }

    try {
        DataObject d = DataObject.find(f);
        DataFolder df = (DataFolder)d.getCookie(DataFolder.class);
        if (df != null) {
            AnnotationTypeActionsFolder folder;
            folder = new AnnotationTypeActionsFolder(type, df);
            return true;
        }
    } catch (org.openide.loaders.DataObjectNotFoundException ex) {
        Logger.getLogger("global").log(Level.INFO,null, ex);
        return false;
    }
    return false;
}
项目:incubator-netbeans    文件:WebQuickSearchProviderImpl.java   
private static Runnable createAction( final String url ) {
    return new Runnable() {
        public void run() {
            String extendedUrl = appendId( url );
            try {
                HtmlBrowser.URLDisplayer displayer = HtmlBrowser.URLDisplayer.getDefault();
                if (displayer != null) {
                    displayer.showURL(new URL(extendedUrl));
                }
            } catch (Exception e) {
                StatusDisplayer.getDefault().setStatusText(
                        NbBundle.getMessage(WebQuickSearchProviderImpl.class, "Err_CannotDisplayURL", extendedUrl) ); //NOI18N
                Toolkit.getDefaultToolkit().beep();
                Logger.getLogger(WebQuickSearchProviderImpl.class.getName()).log(Level.FINE, null, e);
            }
        }
    };
}
项目:incubator-netbeans    文件:SplitSubModel.java   
public boolean addModeAroundEditor(ModeImpl mode, String side) {
    if(mode == null || mode.getState() == Constants.MODE_STATE_SEPARATED) {
        Logger.getLogger(SplitSubModel.class.getName()).log(Level.WARNING, null,
                          new java.lang.IllegalArgumentException("Mode=" +
                                                                 mode));
        return false;
    }

    Node modeNode = getModeNode(mode);

    if(DEBUG) {
        debugLog(""); // NOI18N
        debugLog(""); // NOI18N
        debugLog("=========================================="); // NOI18N
        debugLog("Adding mode to around=" + mode); // NOI18N
        debugLog("side=" + side); // NOI18N
    }

    return addNodeToTreeAroundEditor(modeNode, side);
}
项目:incubator-netbeans    文件:RetainedSetByClass.java   
public void perform() {
    Heap heap = context.getHeap();
    @SuppressWarnings("unchecked")
    List<JavaClass> classes = heap.getAllClasses();

    // TODO access to progress
    //        BoundedRangeModel progress = context.getProgress();
    //        progress.setMaximum(classes.size());
    Histogram<Histogram.Entry> hist = new Histogram<Histogram.Entry>();

    for (JavaClass cls : classes) {
        Logger.getLogger(RetainedSetByClass.class.getName()).log(Level.FINE, "Executing rule on class {0}.", cls); // NOI18N
        performClass(cls, hist);

        if (context.isInterruped()) {
            return;
        }

        // TODO access to progress
        //            progress.setValue(progress.getValue()+1);
    }

    summary(hist);
}
项目:ThingML-Tradfri    文件:LightBulb.java   
public void setColor(String color) {
      try {
              JSONObject json = new JSONObject();
              JSONObject settings = new JSONObject();
              JSONArray array = new JSONArray();
              array.put(settings);
              json.put(TradfriConstants.LIGHT, array);
              settings.put(TradfriConstants.COLOR, color);
              settings.put(TradfriConstants.TRANSITION_TIME, 5);
              String payload = json.toString();
gateway.set(TradfriConstants.DEVICES + "/" + this.getId(), payload); 

          } catch (JSONException ex) {
              Logger.getLogger(TradfriGateway.class.getName()).log(Level.SEVERE, null, ex);
          }
      this.color = color;
  }
项目:incubator-netbeans    文件:FolderBasedController.java   
@Override
protected void setCurrentSubcategory(String subpath) {
    for (Entry<String, OptionsPanelController> e : getMimeType2delegates().entrySet()) {
        if (subpath.startsWith(e.getKey())) {
            panel.setCurrentMimeType(e.getKey());
            subpath = subpath.substring(e.getKey().length());

            if (subpath.length() > 0 && subpath.startsWith("/")) {
                e.getValue().setSubcategory(subpath.substring(1));
            }

            return ;
        }
    }

    Logger.getLogger(FolderBasedController.class.getName()).log(Level.WARNING, "setCurrentSubcategory: cannot open: {0}", subpath);
}
项目:MuslimMateAndroid    文件:Place.java   
public static Place jsonToPontoReferencia(JSONObject pontoReferencia) {
    try {
        Place result = new Place();
        JSONObject geometry = (JSONObject) pontoReferencia.get("geometry");
        JSONObject location = (JSONObject) geometry.get("location");
        result.setLatitude((Double) location.get("lat"));
        result.setLongitude((Double) location.get("lng"));
        result.setIcon(pontoReferencia.getString("icon"));
        result.setName(pontoReferencia.getString("name"));
        //result.setVicinity(pontoReferencia.getString("vicinity"));
        result.setId(pontoReferencia.getString("id"));
        return result;
    } catch (JSONException ex) {
        Logger.getLogger(Place.class.getName()).log(Level.SEVERE, null, ex);
    }
    return null;
}
项目:JRediClients    文件:RedissonTestRunListener.java   
@Override
public void testRunStarted(Description description) throws Exception {
    super.testRunStarted(description);
    Runtime.getRuntime().addShutdownHook(new Thread(() -> {
        running.set(Boolean.FALSE);
    }));
    new Thread(() -> {
        final RuntimeMXBean runtimeBean = ManagementFactory.getRuntimeMXBean();
        final AtomicLong u = new AtomicLong(runtimeBean.getUptime());
        while (running.get()) {
            try {
                long upTime = runtimeBean.getUptime();
                if (upTime >= u.get() + 10000) {
                    u.set(upTime);
                    System.out.printf("Test Up Time    = %.3f (s)%n", upTime / 1000d);
                    System.out.printf("Heap Usage      = %.3f (MB)%n", ManagementFactory.getMemoryMXBean().getHeapMemoryUsage().getUsed() / 1024d / 1024d);
                    System.out.printf("None Heap Usage = %.3f (MB)%n", ManagementFactory.getMemoryMXBean().getNonHeapMemoryUsage().getUsed() / 1024d / 1024d);
                    System.out.println("=============================");
                }
                Thread.currentThread().sleep(10000l);
            } catch (InterruptedException ex) {
                Logger.getLogger(RedissonTestRunListener.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }).start();
}
项目:incubator-netbeans    文件:InstallerReadPageTest.java   
@RandomlyFails // NB-Core-Build #7964
public void testSendLogWithException() throws Exception {
    Logger uiLogger = Logger.getLogger(Installer.UI_LOGGER_NAME);
    LogRecord log1 = new LogRecord(Level.SEVERE, "TESTING MESSAGE");
    LogRecord log2 = new LogRecord(Level.SEVERE, "TESTING MESSAGE");
    LogRecord log3 = new LogRecord(Level.SEVERE, "NO EXCEPTION LOG");
    LogRecord log4 = new LogRecord(Level.INFO, "INFO");
    Throwable t1 = new NullPointerException("TESTING THROWABLE");
    Throwable t2 = new UnknownError("TESTING ERROR");
    log1.setThrown(t1);
    log2.setThrown(t2);
    log4.setThrown(t2);
    Installer installer = Installer.findObject(Installer.class, true);
    assertNotNull(installer);
    installer.restored();
    uiLogger.log(log1);
    uiLogger.log(log2);
    uiLogger.log(log3);
    UIHandler.waitFlushed();
    if (Installer.getThrown() == null) {
        fail("Exception should be found in the log");
    }

    doEncodingTest("UTF-8", "<meta http-equiv='Content-Type' content='text/html; charset=utf-8'></meta>");
}
项目:incubator-netbeans    文件:TimeType.java   
private synchronized static Date doParse (String sVal) {
    Date dVal = null;
    for (DateFormat format : TIME_PARSING_FORMATS) {
        try {
            dVal = format.parse (sVal);
            break;
        } catch (ParseException ex) {
            Logger.getLogger (TimeType.class.getName ()).log (Level.FINEST, ex.getLocalizedMessage () , ex);
        }
    }
    return dVal;
}
项目:Cognizant-Intelligent-Test-Scripter    文件:CommonMethods.java   
@Action(object = ObjectType.BROWSER, desc = "Take screenshot of the current page and store it in the location [<Input>]", input = InputType.YES)
public void saveScreenshot() {
    try {
        String strFullpath = Data;
        File scrFile = getDriverControl().createScreenShot();
        FileUtils.copyFile(scrFile, new File(strFullpath));
        Report.updateTestLog(Action, "Screenshot is taken and saved in this path -'"
                + strFullpath + "'", Status.PASS);
    } catch (IOException e) {
        Report.updateTestLog(Action, e.getMessage(), Status.FAIL);
        Logger.getLogger(CommonMethods.class.getName()).log(Level.SEVERE, null, e);
    }

}
项目:openjdk-jdk10    文件:LoggingDeadlock3.java   
public void run() {
  for (int cnt = 0; cnt < ITER_CNT * 8; cnt++) {
    Logger.getLogger("com.sun.Hello"+cnt/10);
    if (cnt % 1000  == 0) out.print("1");
    if (cnt % 10000 == 0) out.println();
  }
}
项目:AeroStory    文件:EventScriptManager.java   
public void init() {
    for (EventEntry entry : events.values()) {
        try {
            ((ScriptEngine) entry.iv).put("em", entry.em);
            entry.iv.invokeFunction("init", (Object) null);
        } catch (ScriptException | NoSuchMethodException ex) {
            Logger.getLogger(EventScriptManager.class.getName()).log(Level.SEVERE, null, ex);
            System.out.println("Error on script: " + entry.em.getName());
        }
    }
}
项目:incubator-netbeans    文件:ViewUtils.java   
/**
 * Log msg with FINE level or dump a stack if the logger has FINEST level.
 *
 * @param logger
 * @param msg message to log
 */
public static void log(Logger logger, String msg) {
    if (logger.isLoggable(Level.FINEST)) {
        logger.log(Level.INFO, "Cause of " + msg, new Exception());
    } else {
        logger.fine(msg);
    }
}
项目:incubator-netbeans    文件:KeyringSupport.java   
/**
 * package-private for tests
 */
static String getKeyringKeyHashed (String keyPrefix, String keyToHash) {
    String keyPart = ""; //NOI18N
    if (keyToHash != null) {
        try {
            keyPart = Utils.getHash("SHA-1", keyToHash.getBytes()); //NOI18N
        } catch (NoSuchAlgorithmException ex) {
            Logger.getLogger(KeyringSupport.class.getName()).log(Level.INFO, null, ex);
            keyPart = keyToHash;
        }
    }
    return keyPrefix + keyPart;
}
项目:incubator-netbeans    文件:ExceptionsTest.java   
public void testLogLevel() {
    Exception e = new IOException("Help");

    Exception result = Exceptions.attachSeverity(e, Level.FINE);
    assertSame(e, result);

    class H extends Handler {
        int cnt;

        @Override
        public void publish(LogRecord record) {
            assertEquals("Fine is the level", Level.FINE, record.getLevel());
            cnt++;
        }

        @Override
        public void flush() {
        }

        @Override
        public void close() throws SecurityException {
        }

    }

    H h = new H();
    h.setLevel(Level.ALL);
    Logger L = Logger.getLogger("");
    L.setLevel(Level.ALL);
    L.addHandler(h);

    Exceptions.printStackTrace(e);
    L.removeHandler(h);
    assertEquals("Called once", 1, h.cnt);
}
项目:incubator-netbeans    文件:DBConnectionDrop.java   
/**
 * Post-processing after placement of the dragged connection.
 *
 * @param componentId ID of the corresponding component.
 * @param droppedOverId ID of a component the new component has been dropped over.
 */
@Override
public void componentAdded(String componentId, String droppedOverId) {
    try {
        FileObject formFile = FormEditor.getFormDataObject(model).getFormFile();
        project = FileOwnerQuery.getOwner(formFile);

        // Make sure persistence.xml file exists
        FileObject persistenceXML = J2EEUtils.getPersistenceXML(project, true);

        // Initializes persistence unit and persistence descriptor
        PersistenceUnit unit = J2EEUtils.initPersistenceUnit(persistenceXML, connection.getDatabaseConnection());

        // Initializes project's classpath
        J2EEUtils.updateProjectForUnit(formFile, unit, connection.getJDBCDriver());

        RADComponent entityManager = model.getMetaComponent(componentId);
        entityManager.getPropertyByName("persistenceUnit").setValue(unit.getName()); // NOI18N
        J2EEUtils.renameComponent(entityManager, true, unit.getName() + "EntityManager", "entityManager"); // NOI18N
    } catch (IOException ioex) {
        Logger.getLogger(DBConnectionDrop.class.getName()).log(Level.INFO, null, ioex);
    } catch (InvalidPersistenceXmlException ipxex) {
        Logger.getLogger(DBConnectionDrop.class.getName()).log(Level.INFO, null, ipxex);
    } catch (IllegalAccessException iaex) {
        Logger.getLogger(DBConnectionDrop.class.getName()).log(Level.INFO, null, iaex);
    } catch (InvocationTargetException itex) {
        Logger.getLogger(DBConnectionDrop.class.getName()).log(Level.INFO, null, itex);
    }
}
项目:incubator-netbeans    文件:Wrapping1.java   
public void test() {
    try (FileReader fr1 = new FileReader("");FileReader fr2 = new FileReader("")) {
        fr1.read();
    } catch (IOException | NullPointerException ex) {
        Logger.getLogger(Wrapping1.class.getName()).log(Level.SEVERE, null, ex);
    }

}
项目:Mastering-Microservices-with-Java-9-Second-Edition    文件:AbstractRestaurantControllerTests.java   
/**
 * Test method for add method
 */
@Test
public void validAdd() {
    Logger.getGlobal().info("Start validAdd test");
    RestaurantVO restaurant = new RestaurantVO();
    restaurant.setId("999");
    restaurant.setName("Test Restaurant");

    ResponseEntity<Restaurant> restaurants = restaurantController.add(restaurant);
    Assert.assertEquals(HttpStatus.CREATED, restaurants.getStatusCode());
    Logger.getGlobal().info("End validAdd test");
}
项目:Cognizant-Intelligent-Test-Scripter    文件:Emulators.java   
private void load() {
    File emFile = new File(getLocation());
    if (emFile.exists()) {
        try {
            emulators = objMapper.readValue(emFile, objMapper.getTypeFactory().constructCollectionType(List.class, Emulator.class));
        } catch (IOException ex) {
            Logger.getLogger(Emulators.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}
项目:SpanEE    文件:TracesResource.java   
@GET
public String all() {
    try {
        Thread.sleep(500);
    } catch (InterruptedException ex) {
        Logger.getLogger(TracesResource.class.getName()).log(Level.SEVERE, null, ex);
    }
    return "all traces";
}
项目:Cognizant-Intelligent-Test-Scripter    文件:Basic.java   
/**
 * Opens the openNotifications
 *
 * @see AppiumDriver#hideKeyboard()
 */
@Action(object = ObjectType.BROWSER, desc = "Open the Notifications(android)")
public void openNotifications() {
    try {
        ((AndroidDriver) Driver).openNotifications();
        Report.updateTestLog(Action, "Notification Opened", Status.PASS);
    } catch (Exception ex) {
        Report.updateTestLog(Action, ex.getMessage(), Status.DEBUG);
        Logger.getLogger(Basic.class.getName()).log(Level.SEVERE, null, ex);
    }
}
项目:incubator-netbeans    文件:BusyIcon.java   
@Override
public void paintIcon( Component c, Graphics g, int x, int y ) {
    if( g instanceof Graphics2D ) {
        Graphics2D g2d = ( Graphics2D ) g;
        try {
            g2d.translate( x, y );
            paintMethod.invoke( painter, g, c, x, y );
        } catch( Exception ex ) {
            Logger.getLogger( BusyIcon.class.getName() ).log( Level.FINE, null, ex );
        }
        g2d.translate( -x, -y );
    }
}
项目:lokalized-java    文件:LoggingUtils.java   
/**
 * Overrides the system's root logger level.
 * <p>
 * This is for internal testing and debugging only!
 *
 * @param level the level to use, not null
 */
@Nonnull
public static void setRootLoggerLevel(@Nonnull Level level) {
  Objects.requireNonNull(level);

  Logger rootLogger = Logger.getLogger("");

  for (Handler handler : rootLogger.getHandlers())
    handler.setLevel(Level.FINEST);

  rootLogger.setLevel(level);
}