Java Code Examples for java.util.logging.Level

The following examples show how to use java.util.logging.Level. These examples are extracted from open source projects.
Example 1
Project: reef   File: MesosRemoteManagerCodec.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public byte[] encode(final EvaluatorControl evaluatorControl) {
  try {
    LOG.log(Level.FINEST, "Before Encoding: {0}", evaluatorControl.toString());
    final ByteArrayOutputStream out = new ByteArrayOutputStream();
    final BinaryEncoder encoder = EncoderFactory.get().binaryEncoder(out, null);
    final DatumWriter<EvaluatorControl> writer = new SpecificDatumWriter<>(EvaluatorControl.getClassSchema());
    writer.write(evaluatorControl, encoder);
    encoder.flush();
    out.close();
    LOG.log(Level.FINEST, "After Encoding");
    return out.toByteArray();
  } catch (final IOException ex) {
    throw new RemoteRuntimeException(ex);
  }
}
 
Example 2
Project: openjdk-8   File: XmlFactory.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Returns properly configured (e.g. security features) factory
 * - securityProcessing == is set based on security processing property, default is true
 */
public static XPathFactory createXPathFactory(boolean disableSecureProcessing) throws IllegalStateException {
    try {
        XPathFactory factory = XPathFactory.newInstance();
        if (LOGGER.isLoggable(Level.FINE)) {
            LOGGER.log(Level.FINE, "XPathFactory instance: {0}", factory);
        }
        factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, !isXMLSecurityDisabled(disableSecureProcessing));
        return factory;
    } catch (XPathFactoryConfigurationException ex) {
        LOGGER.log(Level.SEVERE, null, ex);
        throw new IllegalStateException( ex);
    } catch (AbstractMethodError er) {
        LOGGER.log(Level.SEVERE, null, er);
        throw new IllegalStateException(Messages.INVALID_JAXP_IMPLEMENTATION.format(), er);
    }
}
 
Example 3
Project: diirt   File: NumberColorMaps.java    License: MIT License 6 votes vote down vote up
private static List<NumberColorMap> loadMapsFromLocal() {
    List<NumberColorMap> maps = new ArrayList<>();
    File path = new File(Configuration.getDirectory(), "graphene/colormaps");
    // If maps are not there, create them first
    if (!path.exists()) {
        path.mkdirs();

        log.log(Level.CONFIG, "Creating path graphene/colormaps under DIIRT_HOME ");
        initializeColorMapDirectory(path);
    }
    // Load maps from local directory
    log.log(Level.CONFIG, "Loading ColorMaps from directory: " + path);
    for (File file : path.listFiles()) {

        log.log(Level.CONFIG, "Loading ColorMap from file: " + file);
        try {
            maps.add(load(file));
        } catch (RuntimeException ex) {
            log.log(Level.WARNING, ex.getMessage());
        }

    }

    return maps;
}
 
Example 4
Project: copybara   File: ProfilerTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testListenerLogging() {
  // Keep a strong reference to the Logger we use to capture log records for the duration of the
  // test to avoid any potential race conditions with the weak referencing used by the JDK
  //
  // TODO: This could be migrated to use the package level logger name, which would be less
  // fragile against code being moved around.
  Logger loggerUnderTest = Logger.getLogger(LogProfilerListener.class.getCanonicalName());

  TestLogHandler assertingHandler = new TestLogHandler();
  assertingHandler.setLevel(Level.FINE);
  loggerUnderTest.addHandler(assertingHandler);

  profiler = new Profiler(ticker);
  profiler.init(ImmutableList.of(new LogProfilerListener()));
  try (ProfilerTask ignore = profiler.start("testListenerLogging")) {
    // do something
  }
  LogRecord record = assertingHandler.getStoredLogRecords().get(0);
  assertThat(record.getMessage()).contains("testListenerLogging");
  assertThat(record.getSourceClassName()).contains(this.getClass().getName());

  loggerUnderTest.removeHandler(assertingHandler);
}
 
Example 5
Project: vespa   File: SimpleDocumentProcessor.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Simple process() that follows the official guidelines for
 * looping over {@link DocumentOperation}s, and then calls the appropriate,
 * overloaded process() depending on the type of base.
 * <p>
 * Declared as final, so if you want to handle everything yourself
 * you should of course extend DocumentProcessor instead of
 * SimpleDocumentProcessor and just go about as usual.
 * <p>
 * It is important to note that when iterating over the {@link DocumentOperation}s in
 * {@link com.yahoo.docproc.Processing#getDocumentOperations()}, an exception thrown
 * from any of the process() methods provided by this class will be thrown straight
 * out of this here. This means that failing one document will fail the
 * entire batch.
 *
 * @param processing the Processing to process.
 * @return Progress.DONE, unless a subclass decides to throw an exception
 */
@Override
public final Progress process(Processing processing) {
    int initialSize = processing.getDocumentOperations().size();
    for (DocumentOperation op : processing.getDocumentOperations()) {
        try {
            if (op instanceof DocumentPut) {
                process((DocumentPut) op);
            } else if (op instanceof DocumentUpdate) {
                process((DocumentUpdate) op);
            } else if (op instanceof DocumentRemove) {
                process((DocumentRemove) op);
            }
        } catch (RuntimeException e) {
            if (log.isLoggable(Level.FINE) && initialSize != 1) {
                log.log(Level.FINE,
                        "Processing of document failed, from processing.getDocumentOperations() containing " +
                        initialSize + " DocumentOperation(s).", e);
            }
            throw e;
        }
    }

    return Progress.DONE;
}
 
Example 6
Project: netbeans   File: IndexQueryImpl.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Set<MethodElement> getAllMethods(TypeElement typeElement) {
    final long start = (LOG.isLoggable(Level.FINE)) ? System.currentTimeMillis() : 0;
    final Set<TypeMemberElement> typeMembers =
            getInheritedTypeMembers(typeElement, new LinkedHashSet<TypeElement>(),
            new LinkedHashSet<TypeMemberElement>(getDeclaredMethods(typeElement)),
            EnumSet.of(PhpElementKind.CLASS, PhpElementKind.IFACE, PhpElementKind.TRAIT),
            EnumSet.of(PhpElementKind.METHOD));
    final Set<MethodElement> retval = new HashSet<>();
    for (TypeMemberElement member : typeMembers) {
        if (member instanceof MethodElement) {
            retval.add((MethodElement) member);
        }
    }
    if (LOG.isLoggable(Level.FINE)) {
        logQueryTime("Set<MethodElement> getAllMethods", NameKind.exact(typeElement.getFullyQualifiedName()), start); //NOI18N
    }
    return Collections.unmodifiableSet(retval);
}
 
Example 7
Project: JSAT   File: SparseMatrix.java    License: GNU General Public License v3.0 6 votes vote down vote up
@Override
public void mutableAdd(final double c, ExecutorService threadPool)
{
    final CountDownLatch latch = new CountDownLatch(rows.length);
    for(final SparseVector row : rows)
    {
        threadPool.submit(new Runnable()
        {
            @Override
            public void run()
            {
                row.mutableAdd(c);
                latch.countDown();
            }
        });
    }
    try
    {
        latch.await();
    }
    catch (InterruptedException ex)
    {
        Logger.getLogger(SparseMatrix.class.getName()).log(Level.SEVERE, null, ex);
    }
}
 
Example 8
Project: swellrt   File: SolrWaveIndexerImpl.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public ListenableFuture<Void> onWaveInit(final WaveletName waveletName) {

  ListenableFutureTask<Void> task = ListenableFutureTask.create(new Callable<Void>() {

    @Override
    public Void call() throws Exception {
      ReadableWaveletData waveletData;
      try {
        waveletData = waveletDataProvider.getReadableWaveletData(waveletName);
        updateIndex(waveletData);
      } catch (WaveServerException e) {
        LOG.log(Level.SEVERE, "Failed to initialize index for " + waveletName, e);
        throw e;
      }
      return null;
    }
  });
  executor.execute(task);
  return task;
}
 
Example 9
Project: bazel-buildfarm   File: RedisShardSubscriber.java    License: Apache License 2.0 6 votes vote down vote up
void onOperationChange(String channel, OperationChange operationChange) {
  // FIXME indicate lag/clock skew for OOB timestamps
  switch (operationChange.getTypeCase()) {
    case TYPE_NOT_SET:
      // FIXME present nice timestamp
      logger.log(
          Level.SEVERE,
          format(
              "OperationChange oneof type is not set from %s at %s",
              operationChange.getSource(), operationChange.getEffectiveAt()));
      break;
    case RESET:
      resetOperation(channel, operationChange.getReset());
      break;
    case EXPIRE:
      terminateExpiredWatchers(
          channel,
          toInstant(operationChange.getEffectiveAt()),
          operationChange.getExpire().getForce());
      break;
  }
}
 
Example 10
Project: proarc   File: DesaElement.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
 * Generates children of this element
 *
 */
@Override
public void fillChildren() throws MetsExportException {
    Node node = MetsUtils.xPathEvaluateNode(relsExt, "*[local-name()='RDF']/*[local-name()='Description']");
    NodeList hasPageNodes = node.getChildNodes();
    for (int a = 0; a < hasPageNodes.getLength(); a++) {
        if (MetsUtils.hasReferenceXML(hasPageNodes.item(a).getNodeName())) {
            Node rdfResourceNode = hasPageNodes.item(a).getAttributes().getNamedItem("rdf:resource");
            String fileName = rdfResourceNode.getNodeValue();

            DigitalObject object = null;
            if (desaContext.getFedoraClient() != null) {
                object = MetsUtils.readRelatedFoXML(fileName, desaContext.getFedoraClient());
            } else {
                object = MetsUtils.readRelatedFoXML(desaContext.getPath(), fileName);
            }
            DesaElement child = new DesaElement(object, this, desaContext, true);
            this.children.add(child);
            LOG.log(Level.FINE, "Child found for:" + getOriginalPid() + "(" + getElementType() + ") - " + child.getOriginalPid() + "(" + child.getElementType() + ")");
        }
    }
}
 
Example 11
Project: netbeans   File: MergePanel.java    License: Apache License 2.0 6 votes vote down vote up
private void addEmptyLines(StyledDocument doc, int line, int numLines) {
    int lastOffset = doc.getEndPosition().getOffset();
    int totLines = org.openide.text.NbDocument.findLineNumber(doc, lastOffset);
    //int totLines = doc.getDefaultRootElement().getElementIndex(lastOffset);
    int offset = lastOffset;
    if (line <= totLines) {
        offset = org.openide.text.NbDocument.findLineOffset(doc, line);
        //offset = doc.getDefaultRootElement().getElement(line).getStartOffset();
    } else {
        offset = lastOffset - 1;
        Logger logger = Logger.getLogger(MergePanel.class.getName());
        logger.log(Level.WARNING, "line({0}) > totLines({1}): final offset({2})", new Object[] {line, totLines, offset}); //NOI18N
        logger.log(Level.INFO, null, new Exception());
    }
    //int endOffset = doc.getEndPosition().getOffset();
    //if (offset > endOffset) offset = endOffset;
    String insStr = strCharacters('\n', numLines);
    //System.out.println("addEmptyLines = '"+insStr+"'");
    try {
        doc.insertString(offset, insStr, null);
    } catch (BadLocationException e) {
        org.openide.ErrorManager.getDefault().notify(e);
    }
    //initScrollBars();
}
 
Example 12
Project: tigase-extension   File: CheckmobiCLIVerifyProvider.java    License: GNU General Public License v3.0 6 votes vote down vote up
/** Parameters <code>proof</code> is ignored. */
@Override
public boolean endVerification(XMPPResourceConnection session, RegistrationRequest request, String proof) throws IOException, TigaseDBException {
    CheckmobiValidationClient client = CheckmobiValidationClient.callerID(apiKey);

    if (log.isLoggable(Level.FINEST)) {
        log.finest("Checking verification status from CheckMobi: " + request);
    }

    CheckmobiRequest myRequest = (CheckmobiRequest) request;
    StatusResult result = client.status(myRequest.getId());
    if (result != null) {
        if (result.getStatus() == StatusResult.STATUS_SUCCESS) {
            return result.isValidated();
        }
        else {
            throw new IOException("verification did not start (" + result.getError() + ")");
        }
    }
    else {
        throw new IOException("Unknown response");
    }
}
 
Example 13
Project: SubServers-2   File: Metrics.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Gets the first bStat Metrics class.
 *
 * @return The first bStats metrics class.
 */
private Class<?> getFirstBStatsClass() {
    Path configPath = new File(plugin.dir, "plugins").toPath().resolve("bStats");
    configPath.toFile().mkdirs();
    File tempFile = new File(configPath.toFile(), "temp.txt");

    try {
        String className = readFile(tempFile);
        if (className != null) {
            try {
                // Let's check if a class with the given name exists.
                return Class.forName(className);
            } catch (ClassNotFoundException ignored) { }
        }
        writeFile(tempFile, getClass().getName());
        return getClass();
    } catch (IOException e) {
        if (logFailedRequests) {
            plugin.getLogger().log(Level.WARNING, "Failed to get first bStats class!", e);
        }
        return null;
    }
}
 
Example 14
Project: netbeans   File: SpringWebModuleExtender.java    License: Apache License 2.0 5 votes vote down vote up
private boolean isWebXmlValid(WebModule webModule) {
    FileObject webXml = webModule.getDeploymentDescriptor();
    if (webXml == null) {
        return true;
    }
    WebApp webApp = null;
    try {
        webApp = DDProvider.getDefault().getDDRoot(webXml);
    } catch (IOException ex) {
        LOGGER.log(Level.INFO, "Can't read web.xml file: " + webXml.getPath(), ex);
    }
    return webApp != null && webApp.getStatus() == WebApp.STATE_VALID;
}
 
Example 15
Project: jmonkeyengine   File: BulletDebugAppState.java    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private void updateGhosts() {
    HashMap<PhysicsGhostObject, Spatial> oldObjects = ghosts;
    ghosts = new HashMap<PhysicsGhostObject, Spatial>();
    Collection<PhysicsGhostObject> current = space.getGhostObjectList();
    //create new map
    for (Iterator<PhysicsGhostObject> it = current.iterator(); it.hasNext();) {
        PhysicsGhostObject physicsObject = it.next();
        //copy existing spatials
        if (oldObjects.containsKey(physicsObject)) {
            Spatial spat = oldObjects.get(physicsObject);
            ghosts.put(physicsObject, spat);
            oldObjects.remove(physicsObject);
        } else {
            if (filter == null || filter.displayObject(physicsObject)) {
                logger.log(Level.FINE, "Create new debug GhostObject");
                //create new spatial
                Node node = new Node(physicsObject.toString());
                node.addControl(new BulletGhostObjectDebugControl(this, physicsObject));
                ghosts.put(physicsObject, node);
                physicsDebugRootNode.attachChild(node);
            }
        }
    }
    //remove leftover spatials
    for (Map.Entry<PhysicsGhostObject, Spatial> entry : oldObjects.entrySet()) {
        PhysicsGhostObject object = entry.getKey();
        Spatial spatial = entry.getValue();
        spatial.removeFromParent();
    }
}
 
Example 16
Project: BotLibre   File: SerializedMemory.java    License: Eclipse Public License 1.0 5 votes vote down vote up
public void shutdown() throws MemoryStorageException {
	super.shutdown();
	long start = System.currentTimeMillis();
	File file = new File(storageDir, storageFileName);
	getBot().log(this, "Saving memory to file", Level.INFO, file);
	try {
		List<Vertex> vertices = new ArrayList<Vertex>(((BasicNetwork)getLongTermMemory()).getVerticesById().values());
		// Flatten objects to avoid stack overflow.
		List<Relationship> relationships = new ArrayList<Relationship>(vertices.size());
		for (Vertex vertex : vertices) {
			for (Iterator<Relationship> iterator = vertex.allRelationships(); iterator.hasNext(); ) {
				relationships.add(iterator.next());
			}
		}
		FileOutputStream fileStream = new FileOutputStream(file);
		ObjectOutputStream objectStream = new ObjectOutputStream(fileStream);
		objectStream.writeObject(vertices);
		objectStream.writeObject(relationships);
		objectStream.flush();
		objectStream.close();
		fileStream.flush();
		fileStream.close();
		long time = System.currentTimeMillis() - start;
		getBot().log(this, "Memory saved", Level.INFO, getLongTermMemory().size(), file.length(), time);
	} catch (IOException exception) {
		throw new MemoryStorageException(exception);
	}
}
 
Example 17
Project: wow-auctions   File: AuctionDataItemReader.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Override
public void close() throws Exception {
    AuctionFile fileToProcess = getContext().getFileToProcess();
    fileToProcess.setFileStatus(FileStatus.PROCESSED);
    woWBusiness.updateAuctionFile(fileToProcess);

    if (in != null) {
        in.close();
    }

    getLogger(this.getClass().getName()).log(Level.INFO, "Finished file " +
                                                         getContext().getFileToProcess().getFileName() +
                                                         " for Realm " +
                                                         getContext().getRealm().getRealmDetail());
}
 
Example 18
Project: jpexs-decompiler   File: SWFDecompilerPlugin.java    License: GNU General Public License v3.0 5 votes vote down vote up
public static boolean fireActionListParsed(ActionList actions, SWF swf) throws InterruptedException {
    for (SWFDecompilerListener listener : listeners) {
        try {
            listener.actionListParsed(actions, swf);
        } catch (ThreadDeath | InterruptedException ex) {
            throw ex;
        } catch (Throwable e) {
            logger.log(Level.SEVERE, "Failed to call plugin method actionListParsed.", e);
        }
    }
    return !listeners.isEmpty();
}
 
Example 19
Project: jstackfx   File: Query.java    License: Apache License 2.0 5 votes vote down vote up
protected Class determineFieldClass(final String fieldName) {
    try {
        final BeanInfo beanInfo = Introspector.getBeanInfo(this.clazz);
        final PropertyDescriptor[] descriptors = beanInfo.getPropertyDescriptors();
        final PropertyDescriptor fieldDescriptor = Arrays.stream(descriptors).filter(descriptor -> descriptor.getName().equals(fieldName)).findFirst().orElse(null);

        return fieldDescriptor.getReadMethod().getReturnType();

    } catch (IntrospectionException e) {
        if (LOGGER.isLoggable(Level.FINE)) {
            LOGGER.log(Level.WARNING, "Error determining the field [" + fieldName + "] class", e);
        }
        return null;
    }
}
 
Example 20
Project: procamcalib   File: MainFrame.java    License: GNU General Public License v2.0 5 votes vote down vote up
private void calibrationLoadMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_calibrationLoadMenuItemActionPerformed
    JFileChooser fc = new JFileChooser();
    if (calibrationFile != null) {
        fc.setSelectedFile(calibrationFile);
    } else {
        fc.setSelectedFile(DEFAULT_CALIBRATION_FILE);
    }
    int returnVal = fc.showOpenDialog(this);
    if (returnVal == JFileChooser.APPROVE_OPTION) {
        File file = fc.getSelectedFile();
        try {
            if (!file.exists()) {
                throw new Exception("File does not exist.");
            }

            if (calibrationWorker == null) {
                calibrationWorker = new MyCalibrationWorker(null);
            }
            calibrationWorker.readParameters(file);
            calibrationFile = file;
            statusLabel.setText("Calibration data loaded.");
        } catch (Exception ex) {
            Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE,
                    "Could not load calibration data from \"" + file + "\"", ex);
        }
    }

}
 
Example 21
Project: jdk8u-jdk   File: RequiredModelMBean.java    License: GNU General Public License v2.0 5 votes vote down vote up
public void sendNotification(String ntfyText)
    throws MBeanException, RuntimeOperationsException {
    if (MODELMBEAN_LOGGER.isLoggable(Level.FINER)) {
        MODELMBEAN_LOGGER.logp(Level.FINER,
                RequiredModelMBean.class.getName(),
            "sendNotification(String)","Entry");
    }

    if (ntfyText == null)
        throw new RuntimeOperationsException(new
            IllegalArgumentException("notification message must not "+
                                     "be null"),
            "Exception occurred trying to send a text notification "+
            "from a ModelMBean");

    Notification myNtfyObj = new Notification("jmx.modelmbean.generic",
                                              this, 1, ntfyText);
    sendNotification(myNtfyObj);
    if (MODELMBEAN_LOGGER.isLoggable(Level.FINER)) {
        MODELMBEAN_LOGGER.logp(Level.FINER,
                RequiredModelMBean.class.getName(),
            "sendNotification(String)","Notification sent");
        MODELMBEAN_LOGGER.logp(Level.FINER,
                RequiredModelMBean.class.getName(),
            "sendNotification(String)","Exit");
    }
}
 
Example 22
Project: SPADE   File: AuditEventReader.java    License: GNU General Public License v3.0 5 votes vote down vote up
private void printStats(){
	long currentTime = System.currentTimeMillis();
	float overallTime = (float) (currentTime - startTime) / 1000; // # in secs
	float intervalTime = (float) (currentTime - lastReportedTime) / 1000; // # in secs
	if(overallTime > 0 && intervalTime > 0){
		float overallRecordVolume = (float) recordCount / overallTime; // # records/sec
		float intervalRecordVolume = (float) (recordCount - lastReportedRecordCount) / intervalTime; // # records/sec
		logger.log(Level.INFO, "Overall rate: {0} records/sec in {1} seconds. Interval rate: {2} records/sec in {3} seconds.", 
				new Object[]{overallRecordVolume, overallTime, intervalRecordVolume, intervalTime});
	}
}
 
Example 23
Project: jdk8u_jdk   File: DefaultMBeanServerInterceptor.java    License: GNU General Public License v2.0 5 votes vote down vote up
public void addNotificationListener(ObjectName name,
                                    NotificationListener listener,
                                    NotificationFilter filter,
                                    Object handback)
        throws InstanceNotFoundException {

    // ------------------------------
    // ------------------------------
    if (MBEANSERVER_LOGGER.isLoggable(Level.FINER)) {
        MBEANSERVER_LOGGER.logp(Level.FINER,
                DefaultMBeanServerInterceptor.class.getName(),
                "addNotificationListener", "ObjectName = " + name);
    }

    DynamicMBean instance = getMBean(name);
    checkMBeanPermission(instance, null, name, "addNotificationListener");

    NotificationBroadcaster broadcaster =
            getNotificationBroadcaster(name, instance,
                                       NotificationBroadcaster.class);

    // ------------------
    // Check listener
    // ------------------
    if (listener == null) {
        throw new RuntimeOperationsException(new
            IllegalArgumentException("Null listener"),"Null listener");
    }

    NotificationListener listenerWrapper =
        getListenerWrapper(listener, name, instance, true);
    broadcaster.addNotificationListener(listenerWrapper, filter, handback);
}
 
Example 24
Project: BotLibre   File: AIMLParser.java    License: Eclipse Public License 1.0 5 votes vote down vote up
public void checkSupportedChildren(Element element, Collection<String> tags, Network network) {
	NodeList list = element.getChildNodes();
	for (int index2 = 0;  index2 < list.getLength(); index2++) {
		Node child = list.item(index2);
		String name = child.getNodeName().toLowerCase();
		if ((child.getNodeType() != Node.TEXT_NODE)
					&& (child.getNodeType() != Node.COMMENT_NODE) && !tags.contains(name)) {
			network.getBot().log(this, "Unsupported " + element.getNodeName() + " child", Level.WARNING, name, child.getTextContent());
		}
	}
}
 
Example 25
Project: proarc   File: OaiCatalog.java    License: GNU General Public License v3.0 5 votes vote down vote up
private Client createClient() {
    ClientBuilder builder = ClientBuilder.newBuilder();
    if (user != null) {
        builder.register(HttpAuthenticationFeature.basic(user, password));
    }
    if (LOG.isLoggable(Level.FINEST)) {
        builder.register(new LoggingFeature(LOG));
    }
    Client client = builder
            .property(ClientProperties.FOLLOW_REDIRECTS, true)
            .property(ClientProperties.CONNECT_TIMEOUT, 2 * 60 * 1000) // 2 min
            .property(ClientProperties.READ_TIMEOUT, 1 * 60 * 1000) // 1 min
            .build();
    return client;
}
 
Example 26
Project: JsDroidCmd   File: NanoHTTPD.java    License: Mozilla Public License 2.0 5 votes vote down vote up
@Override
public void clear() {
    for (TempFile file : this.tempFiles) {
        try {
            file.delete();
        } catch (Exception ignored) {
            NanoHTTPD.LOG.log(Level.WARNING, "could not delete file ", ignored);
        }
    }
    this.tempFiles.clear();
}
 
Example 27
Project: birt   File: ResultMetaData.java    License: Eclipse Public License 1.0 5 votes vote down vote up
public int getColumnCount()
{
 logger.logp( Level.FINEST,
QueryResults.class.getName( ),
"getColumnCount","");       
    return doGetColumnCount( );
}
 
Example 28
Project: Quelea   File: LabelGrabber.java    License: GNU General Public License v3.0 5 votes vote down vote up
/**
 * Get a label from the language file.
 * <p/>
 * @param key the key to use to get the label.
 * @return the textual string in the appropriate language.
 */
public String getLabel(String key) {
    String ret = labels.getProperty(key);
    if (ret == null) {
        ret = engLabels.getProperty(key);
        if (english) { //Only a warning for the default english lang file - others will probably have stuff missing.
            LOGGER.log(Level.WARNING, "Missing label in language file: {0}", key);
        }
        if (ret == null) {
            return key;
        }
    }
    return ret;
}
 
Example 29
Project: netbeans   File: AsynchChildren.java    License: Apache License 2.0 5 votes vote down vote up
protected @Override void addNotify() {
    logger.log (Level.FINER, "addNotify on {0}", new Object[] { this });
    if ((!initialized && task.isFinished()) || cancelled) {
        cancelled = false;
        Node n = factory.getWaitNode();
        if (n != null) {
            setKeys (new Object[] { n });
        }
        task.schedule(0);
    }
}
 
Example 30
Project: Holograms   File: HologramEntityControllerImpl.java    License: MIT License 5 votes vote down vote up
private EntityNameable spawnNameable(HologramLine line, Location location, boolean lock) {
    WorldServer nmsWorld = ((CraftWorld) location.getWorld()).getHandle();
    EntityNameable armorStand = new EntityNameable(nmsWorld, line);
    armorStand.setPosition(location.getX(), location.getY(), location.getZ());
    if (!addEntityToWorld(nmsWorld, armorStand)) {
        plugin.getLogger().log(Level.WARNING, "Failed to spawn hologram entity in world " + location.getWorld().getName()
                + " at x:" + location.getX() + " y:" + location.getY() + " z:" + location.getZ());
    }
    if (lock) {
        armorStand.setLockTick(true);
    }
    return armorStand;
}
 
Example 31
Project: baratine   File: BaseRunner.java    License: GNU General Public License v2.0 5 votes vote down vote up
protected void setLoggingLevels() throws Exception
{
  LogConfigs logConfigs = getTestClass().getAnnotation(LogConfigs.class);
  LogConfig[] logs = null;

  if (logConfigs != null)
    logs = logConfigs.value();

  if (logs == null) {
    List<LogConfig> temp = new ArrayList<>();
    Annotation[] annotations = getTestClass().getAnnotations();
    for (Annotation annotation : annotations) {
      if (annotation instanceof LogConfig) {
        temp.add((LogConfig) annotation);
      }
    }
    logs = temp.toArray(new LogConfig[temp.size()]);
  }

  for (LogConfig config : logs) {
    Logger log = Logger.getLogger(config.value());

    _loggers.add(log); //GC protect

    Level level = Level.parse(config.level());
    log.setLevel(level);

    Handler handler = getHandler(config);

    if (handler == null)
      continue;

    if (handler.getLevel().intValue() > level.intValue())
      handler.setLevel(level);

    log.addHandler(handler);
  }
}
 
Example 32
Project: vespa   File: SessionRepository.java    License: Apache License 2.0 5 votes vote down vote up
private void synchronizeOnNew(List<Long> sessionList) {
    for (long sessionId : sessionList) {
        RemoteSession session = remoteSessionCache.getSession(sessionId);
        if (session == null) continue; // session might have been deleted after getting session list
        log.log(Level.FINE, () -> session.logPre() + "Confirming upload for session " + sessionId);
        session.confirmUpload();
    }
}
 
Example 33
Project: cxf   File: SSLUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static String getTruststorePassword(String trustStorePassword,
                                         Logger log) {
    final String logMsg;
    if (trustStorePassword != null) {
        logMsg = "TRUST_STORE_PASSWORD_SET";
    } else {
        trustStorePassword =
            SystemPropertyAction.getProperty("javax.net.ssl.trustStorePassword");
        logMsg = trustStorePassword != null
                 ? "TRUST_STORE_PASSWORD_SYSTEM_PROPERTY_SET"
                 : "TRUST_STORE_PASSWORD_NOT_SET";
    }
    LogUtils.log(log, Level.FINE, logMsg);
    return trustStorePassword;
}
 
Example 34
Project: Quelea   File: TimerDisplayable.java    License: GNU General Public License v3.0 5 votes vote down vote up
/**
 * Parse some XML representing this object and return the object it
 * represents.
 * <p>
 *
 * @param node the XML node representing this object.
 * @return the object as defined by the XML.
 */
public static TimerDisplayable parseXML(Node node) {
    NodeList list = node.getChildNodes();

    int i = 0;
    String name = "";
    int duration = -1;
    Calendar timeToFinish = null;
    String pretext, posttext, theme;
    if (list.getLength() == 5) {
        i = 1;
        name = list.item(0).getTextContent();
    }

    try {
        duration = Integer.parseInt(list.item(i).getTextContent());
    } catch (NumberFormatException e) {
        try {
            SimpleDateFormat ft = new SimpleDateFormat("HH:mm");
            Calendar now = Calendar.getInstance();
            Calendar time = Calendar.getInstance();
            time.setTime(ft.parse(list.item(i).getTextContent()));
            time.set(now.get(Calendar.YEAR), now.get(Calendar.MONTH), now.get(Calendar.DATE));
            timeToFinish = time;
        } catch (NumberFormatException | ParseException | DOMException ex) {
            LoggerUtils.getLogger().log(Level.WARNING, "Could not parse datetime for timer");
        }
    }
    pretext = list.item(i + 1).getTextContent();
    posttext = list.item(i + 2).getTextContent();
    theme = list.item(i + 3).getTextContent();
    ThemeDTO tempTheme = ThemeDTO.fromString(theme);
    if (duration != -1) {
        return new TimerDisplayable(name, duration, pretext, posttext, tempTheme);
    } else {
        return new TimerDisplayable(name, timeToFinish, pretext, posttext, tempTheme);
    }
}
 
Example 35
Project: netbeans   File: OptionsImpl.java    License: Apache License 2.0 5 votes vote down vote up
private void clearStaticHashSet(Class clazz, String fieldName) {
    try {
        Field f = clazz.getDeclaredField(fieldName);
        f.setAccessible(true);
        HashSet s = (HashSet)f.get(null);
        s.clear();
    } catch (Exception e) {
        LOGGER.log(Level.INFO, e.getMessage(), e);
    }
}
 
Example 36
Project: editorconfig-netbeans   File: FileInfo.java    License: MIT License 5 votes vote down vote up
public Caret getCaret() {
  Runnable runner = new Runnable() {
    @Override
    public void run() {
      NbDocument.runAtomic(cookie.getDocument(), new Runnable() {
        @Override
        public void run() {
          JEditorPane pane = cookie.getOpenedPanes()[0];
          if (pane != null) {
            currentCaret = pane.getCaret();
          } else {
            LOG.log(Level.SEVERE, "Could not get JEditorPane for Document");
          }
        }
      });
    }
  };
  if (SwingUtilities.isEventDispatchThread()) {
    runner.run();
  } else {
    try {
      SwingUtilities.invokeAndWait(runner);
    } catch (InterruptedException | InvocationTargetException ex) {
      LOG.log(Level.SEVERE, "Could not determine actual caret in editor.", ex);
    }
  }
  return currentCaret;
}
 
Example 37
Project: netbeans   File: FXMLTemplateAttributesProvider.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Map<String, ?> attributesFor(DataObject template, DataFolder target, String name) {
    FileObject templateFO = template.getPrimaryFile();
    if (!JFXProjectProperties.FXML_EXTENSION.equals(templateFO.getExt()) || templateFO.isFolder()) {
        return null;
    }
    
    FileObject targetFO = target.getPrimaryFile();
    Map<String,Object> result = new HashMap<String,Object>();
    
    ClassPath cp = ClassPath.getClassPath(targetFO, ClassPath.SOURCE);
    if (cp == null) {
        LOG.log(
            Level.WARNING,
            "No classpath was found for folder: {0}",   // NOI18N
            FileUtil.getFileDisplayName(targetFO));
    } else if (cp.findOwnerRoot(targetFO) == null) {
        LOG.log(
            Level.WARNING,
            "Folder {0} is not on its classpath: {1}",  // NOI18N
            new Object[] {
                FileUtil.getFileDisplayName(targetFO),
                cp.toString(ClassPath.PathConversionMode.PRINT)
            });
    }
    else {
        result.put("package", cp.getResourceName(targetFO, '.', false)); // NOI18N
    }
    
    return result;
}
 
Example 38
Project: Cognizant-Intelligent-Test-Scripter   File: FileLogger.java    License: Apache License 2.0 5 votes vote down vote up
private void backupLog() {
    try {
        File bkp = new File(logBackupLoc);
        if (!bkp.exists()) {
            bkp.mkdirs();
        }
        String filename = "log-" + getdatetimeString() + ".txt";
        Files.move(new File(logfile).toPath(), new File(bkp, filename).toPath());
    } catch (IOException ex) {
        java.util.logging.Logger.getLogger(FileLogger.class.getName()).log(Level.SEVERE, null, ex);
    }
}
 
Example 39
Project: mars-sim   File: MarsProject.java    License: GNU General Public License v3.0 5 votes vote down vote up
/**
 * The starting method for the application
 *
 * @param args the command line arguments
 */
public static void main(String[] args) throws IOException, InterruptedException, URISyntaxException {

	Logger.getLogger("").setLevel(Level.FINE);

	MarsProject.args = args;

	/*
	 * [landrus, 27.11.09]: Read the logging configuration from the classloader, so
	 * that this gets webstart compatible. Also create the logs dir in user.home
	 */
	new File(System.getProperty("user.home"), ".mars-sim" + File.separator + "logs").mkdirs();

	try {
		LogManager.getLogManager().readConfiguration(MarsProject.class.getResourceAsStream(LOGGING_PROPERTIES));
	} catch (IOException e) {
		logger.log(Level.WARNING, "Could not load logging properties", e);
		try {
			LogManager.getLogManager().readConfiguration();
		} catch (IOException e1) {
			logger.log(Level.WARNING, "Could read logging default config", e);
		}
	}

	// general text antialiasing
	System.setProperty("swing.aatext", "true");
	System.setProperty("awt.useSystemAAFontSettings", "lcd"); // for newer VMs

	// starting the simulation
	new MarsProject(args);
}
 
Example 40
Project: cxf   File: HandlerChainInvoker.java    License: Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
private boolean invokeReversedHandleFault(MessageContext ctx) {
    boolean continueProcessing = true;

    try {
        int index = invokedHandlers.size() - 2;
        while (index >= 0 && continueProcessing) {
            Handler<? extends MessageContext> h = invokedHandlers.get(index);
            if (h instanceof LogicalHandler) {
                LogicalHandler<LogicalMessageContext> lh = (LogicalHandler<LogicalMessageContext>)h;
                continueProcessing = lh.handleFault(logicalMessageContext);
            } else {
                Handler<MessageContext> ph = (Handler<MessageContext>)h;
                continueProcessing = ph.handleFault(protocolMessageContext);
            }

            if (!continueProcessing) {
                invokeReversedClose();
                break;
            }
            index--;
        }
    } catch (RuntimeException e) {
        LOG.log(Level.WARNING, "HANDLER_RAISED_RUNTIME_EXCEPTION", e);
        invokeReversedClose();
        continueProcessing = false;
        closed = true;

        throw e;
    }
    invokeReversedClose();
    return continueProcessing;
}