下面列出了怎么用java.util.logging.Level的API类实例代码及写法,或者点击链接到github查看源代码。
@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);
}
}
/**
* 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);
}
}
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;
}
@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);
}
/**
* 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;
}
@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);
}
@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);
}
}
@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;
}
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;
}
}
/**
* 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() + ")");
}
}
}
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();
}
/** 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");
}
}
/**
* 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;
}
}
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;
}
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();
}
}
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);
}
}
@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());
}
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();
}
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;
}
}
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);
}
}
}
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");
}
}
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});
}
}
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);
}
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());
}
}
}
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;
}
@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();
}
public int getColumnCount()
{
logger.logp( Level.FINEST,
QueryResults.class.getName( ),
"getColumnCount","");
return doGetColumnCount( );
}
/**
* 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;
}
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);
}
}
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;
}