Java Code Examples for java.util.logging.Logger

The following are top voted examples for showing how to use java.util.logging.Logger. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: rapidminer   File: LogService.java   View source code 7 votes vote down vote up
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());
		}
	}
}
 
Example 2
Project: websocket-chat   File: ChatServer.java   View source code 7 votes vote down vote up
@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())));

}
 
Example 3
Project: incubator-netbeans   File: DelayScanRegistry.java   View source code 6 votes vote down vote up
/**
 * 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;
}
 
Example 4
Project: incubator-netbeans   File: Utils.java   View source code 6 votes vote down vote up
/**
 * 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);
    }
}
 
Example 5
Project: incubator-netbeans   File: RepositoryUpdater2Test.java   View source code 6 votes vote down vote up
@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();
}
 
Example 6
Project: NGSI-LD_Wrapper   File: Main.java   View source code 6 votes vote down vote up
/**
 * 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();
}
 
Example 7
Project: jTransactions   File: TinyTxLogger.java   View source code 6 votes vote down vote up
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
}
 
Example 8
Project: tcp   File: ConnectionConfiguration.java   View source code 6 votes vote down vote up
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;
 }
 
Example 9
Project: alvisnlp   File: TomapProjector.java   View source code 6 votes vote down vote up
@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);
	}
}
 
Example 10
Project: incubator-netbeans   File: Installer.java   View source code 6 votes vote down vote up
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;
}
 
Example 11
Project: incubator-netbeans   File: Utils.java   View source code 6 votes vote down vote up
/**
 * 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);
    }
}
 
Example 12
Project: NeverLag   File: WMI4Java.java   View source code 6 votes vote down vote up
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);
	}
}
 
Example 13
Project: G2Dj   File: OggStreamer.java   View source code 6 votes vote down vote up
@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();
    
}
 
Example 14
Project: ProjectAres   File: MobsModule.java   View source code 6 votes vote down vote up
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);
}
 
Example 15
Project: Dr-Assistant   File: DrugGetway.java   View source code 6 votes vote down vote up
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;
}
 
Example 16
Project: openjdk-jdk10   File: GenericConstructor.java   View source code 6 votes vote down vote up
/** 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 ;
    }
}
 
Example 17
Project: incubator-netbeans   File: AnnotationTypeActionsFolder.java   View source code 6 votes vote down vote up
/** 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;
}
 
Example 18
Project: incubator-netbeans   File: WebQuickSearchProviderImpl.java   View source code 6 votes vote down vote up
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);
            }
        }
    };
}
 
Example 19
Project: incubator-netbeans   File: SplitSubModel.java   View source code 6 votes vote down vote up
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);
}
 
Example 20
Project: incubator-netbeans   File: RetainedSetByClass.java   View source code 6 votes vote down vote up
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);
}
 
Example 21
Project: ThingML-Tradfri   File: LightBulb.java   View source code 6 votes vote down vote up
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;
  }
 
Example 22
Project: incubator-netbeans   File: FolderBasedController.java   View source code 6 votes vote down vote up
@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);
}
 
Example 23
Project: MuslimMateAndroid   File: Place.java   View source code 6 votes vote down vote up
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;
}
 
Example 24
Project: JRediClients   File: RedissonTestRunListener.java   View source code 6 votes vote down vote up
@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();
}
 
Example 25
Project: incubator-netbeans   File: InstallerReadPageTest.java   View source code 6 votes vote down vote up
@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>");
}
 
Example 26
Project: incubator-netbeans   File: TimeType.java   View source code 5 votes vote down vote up
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;
}
 
Example 27
Project: Cognizant-Intelligent-Test-Scripter   File: CommonMethods.java   View source code 5 votes vote down vote up
@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);
    }

}
 
Example 28
Project: openjdk-jdk10   File: LoggingDeadlock3.java   View source code 5 votes vote down vote up
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();
  }
}
 
Example 29
Project: AeroStory   File: EventScriptManager.java   View source code 5 votes vote down vote up
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());
        }
    }
}
 
Example 30
Project: incubator-netbeans   File: ViewUtils.java   View source code 5 votes vote down vote up
/**
 * 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);
    }
}
 
Example 31
Project: incubator-netbeans   File: KeyringSupport.java   View source code 5 votes vote down vote up
/**
 * 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;
}
 
Example 32
Project: incubator-netbeans   File: ExceptionsTest.java   View source code 5 votes vote down vote up
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);
}
 
Example 33
Project: incubator-netbeans   File: DBConnectionDrop.java   View source code 5 votes vote down vote up
/**
 * 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);
    }
}
 
Example 34
Project: incubator-netbeans   File: Wrapping1.java   View source code 5 votes vote down vote up
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);
    }

}
 
Example 35
Project: Mastering-Microservices-with-Java-9-Second-Edition   File: AbstractRestaurantControllerTests.java   View source code 5 votes vote down vote up
/**
 * 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");
}
 
Example 36
Project: Cognizant-Intelligent-Test-Scripter   File: Emulators.java   View source code 5 votes vote down vote up
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);
        }
    }
}
 
Example 37
Project: SpanEE   File: TracesResource.java   View source code 5 votes vote down vote up
@GET
public String all() {
    try {
        Thread.sleep(500);
    } catch (InterruptedException ex) {
        Logger.getLogger(TracesResource.class.getName()).log(Level.SEVERE, null, ex);
    }
    return "all traces";
}
 
Example 38
Project: Cognizant-Intelligent-Test-Scripter   File: Basic.java   View source code 5 votes vote down vote up
/**
 * 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);
    }
}
 
Example 39
Project: incubator-netbeans   File: BusyIcon.java   View source code 5 votes vote down vote up
@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 );
    }
}
 
Example 40
Project: lokalized-java   File: LoggingUtils.java   View source code 5 votes vote down vote up
/**
 * 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);
}