下面列出了java.util.logging.Logger#warning ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* @return the maximum delay to find OSGi services.
* <p>
* If the ROBCONF_IT_TIMEOUT environment variable is set, we return its
* values. Otherwise, the default timeout is returned (30s).
* </p>
*/
public static long getTimeout() {
long result = 30000;
Logger logger = Logger.getLogger( ItUtils.class.getName());
String envValue = System.getenv( "ROBOCONF_IT_TIMEOUT" );
try {
if( envValue != null ) {
logger.info( "Env variable ROBOCONF_IT_TIMEOUT is defined and will be used." );
result = Long.parseLong( envValue );
}
} catch( NumberFormatException e ) {
logger.warning( "The timeout for integration tests could not be read from ENV variables. " + e.getMessage());
}
return result;
}
/**
* Activate cluster.
*
* @param cfg Client configuration.
* @throws GridClientException If failed to activate.
*/
@Override public Object execute(GridClientConfiguration cfg, Logger logger) throws Exception {
logger.warning("Command deprecated. Use " + SET_STATE.toString() + " instead.");
try (GridClient client = Command.startClient(cfg)) {
GridClientClusterState state = client.state();
state.state(ACTIVE, false);
logger.info("Cluster activated");
}
catch (Throwable e) {
logger.severe("Failed to activate cluster.");
throw e;
}
return null;
}
/**
* Executes a command on the VM and logs the output.
* @param logger a logger (not null)
* @param command a command to execute (not null, not empty)
* @param workingDir the working directory for the command
* @param environmentVars a map containing environment variables (can be null)
* @param applicationName the roboconf application name (null if not specified)
* @param scopedInstancePath the roboconf scoped instance path (null if not specified)
* @throws IOException if a new process could not be created
* @throws InterruptedException if the new process encountered a process
*/
public static int executeCommand(
final Logger logger,
final String[] command,
final File workingDir,
final Map<String,String> environmentVars,
final String applicationName,
final String scopedInstancePath)
throws IOException, InterruptedException {
ExecutionResult result = executeCommandWithResult( logger, command, workingDir, environmentVars, applicationName, scopedInstancePath);
if( ! Utils.isEmptyOrWhitespaces( result.getNormalOutput()))
logger.fine( result.getNormalOutput());
if( ! Utils.isEmptyOrWhitespaces( result.getErrorOutput()))
logger.warning( result.getErrorOutput());
return result.getExitValue();
}
/**
* Lazy instantiation of the codecs
*
* @param codecEnum
* The codec to instantiate
* @return The codec object or null if not found
*/
private static Codec getInstance(CodecEnum codecEnum) {
Codec codecInstance = null;
try {
Class<? extends Codec> clazz = codecClasses.get(codecEnum);
if (clazz == null) {
Logger logger = Logger.getLogger("lancoder");
logger.warning("Unsupported codec: " + codecEnum.getPrettyName() + "\n");
} else {
Constructor<? extends Codec> cons = clazz.getDeclaredConstructor();
cons.setAccessible(true); // Constructor is protected
codecInstance = cons.newInstance();
codecInstances.put(codecEnum, codecInstance);
}
} catch (Exception e) {
e.printStackTrace();
}
return codecInstance;
}
/**
* Deactivate cluster.
*
* @param clientCfg Client configuration.
* @throws Exception If failed to deactivate.
*/
@Override public Object execute(GridClientConfiguration clientCfg, Logger logger) throws Exception {
logger.warning("Command deprecated. Use " + SET_STATE.toString() + " instead.");
try (GridClient client = Command.startClient(clientCfg)) {
client.state().state(ClusterState.INACTIVE, forceDeactivation);
logger.info("Cluster deactivated");
}
catch (Exception e) {
logger.severe("Failed to deactivate cluster.");
throw e;
}
return null;
}
protected static @Nullable ItemStack[] readFile(@NotNull InventorySerializer itsSerializer, @NotNull File file, @NotNull Logger logger)
{
if(file.exists())
{
try(FileInputStream fis = new FileInputStream(file))
{
int version = fis.read();
byte[] out = new byte[(int) (file.length() - 1)];
int readCount = fis.read(out);
if(file.length() - 1 != readCount) logger.warning("Problem reading file, read " + readCount + " of " + (file.length() - 1) + " bytes.");
return itsSerializer.deserialize(out, version);
}
catch(Exception e)
{
e.printStackTrace();
}
}
return null;
}
public void testWeCanGetLast1000If1500Logged() throws Exception {
Logger log = Logger.getLogger(Installer.UI_LOGGER_NAME);
for (int i = 0; i < 1500; i++) {
log.warning("" + i);
}
List<LogRecord> arr = Installer.getLogs();
assertEquals("Has 1000 records", 1000, arr.size());
Iterator<LogRecord> it = arr.iterator();
for (int i = 500; i < 1500; i++) {
LogRecord r = it.next();
assertEquals("The right name", i, Integer.parseInt(r.getMessage()));
}
}
public void loglevel(Level l, Logger logger, String message) {
LogTest test = LogTest.valueOf("LEV_"+l.getName());
switch(test) {
case LEV_SEVERE:
logger.severe(message);
break;
case LEV_WARNING:
logger.warning(message);
break;
case LEV_INFO:
logger.info(message);
break;
case LEV_CONFIG:
logger.config(message);
break;
case LEV_FINE:
logger.fine(message);
break;
case LEV_FINER:
logger.finer(message);
break;
case LEV_FINEST:
logger.finest(message);
break;
}
}
public void logMessage(PrefixType type, String msg) {
Logger logger = Bukkit.getServer().getLogger();
switch (type) {
case INFO: logger.info(prefix.get(type)+ msg); break;
case WARNING: logger.warning(prefix.get(type) + msg); break;
case ERROR: logger.severe(prefix.get(type) + msg); break;
default:
break;
}
}
/**
* Retrieves a request body.
*
* @param entity Entity to extract the body from.
* @param logger Logger.
* @return Text representation of the body.
*/
private String getRequestBody(Representation entity, Logger logger) {
if (entity == null) {
return null;
}
// check the body of the event to be sent
if (!entity.getMediaType().equals(MediaType.APPLICATION_JSON)){
logger.warning("Invalid request body - must be a valid JSON.");
throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST,
"Invalid request body - must be a valid JSON.");
}
// get the json
String eventJsonString = null;
try {
eventJsonString = entity.getText();
} catch (IOException e) {
logger.info(e.getMessage());
throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST,
"Invalid request body");
}
return eventJsonString;
}
private String findVersion(Logger logger) throws MojoExecutionException {
final Set<Artifact> artifacts = this.helper.resolve(
MAVEN_COMPILER_PLUGIN_GROUPID,
MAVEN_COMPILER_PLUGIN_ARTIFACTID);
final Artifact pluginArtifact = Iterables.find(artifacts, it -> MAVEN_COMPILER_PLUGIN_ARTIFACTID.equals(it.getArtifactId())
&& MAVEN_COMPILER_PLUGIN_GROUPID.equals(it.getGroupId()));
if (pluginArtifact != null) {
return pluginArtifact.getVersion();
}
logger.warning(MessageFormat.format(Messages.MavenBatchCompiler_0, DEFAULT_COMPILER_VERSION));
return DEFAULT_COMPILER_VERSION;
}
public int hash(Logger log, Identifiable<?> identifiable) {
if (technicalId == null) {
if (identifiable.isIdSet()) {
technicalId = identifiable.getId();
} else {
technicalId = new java.rmi.dgc.VMID();
log.warning("DEVELOPER: hashCode is not safe." //
+ "If you encounter this message you should take the time to carefuly " //
+ "review the equals/hashCode methods for: " + identifiable.getClass().getCanonicalName() //
+ " You may consider using a business key.");
}
}
return technicalId.hashCode();
}
@BeforeClass
public static void prepareDockerEnv() throws Exception {
final Logger logger = Logger.getLogger( DockerHandlerWithContainerTest.class.getName());
try {
// Is Docker installed?
DockerTestUtils.checkDockerIsInstalled();
// Prepare the environment
DockerClient docker = buildDockerClient();
File baseDir = new File( Thread.currentThread().getContextClassLoader().getResource( "./image/alpine" ).getFile());
Assert.assertTrue( baseDir.exists());
String builtImageId = docker.buildImageCmd(baseDir)
.withNoCache( true ).withTags( new HashSet<>( Arrays.asList( TAG )))
.exec( new RoboconfBuildImageResultCallback())
.awaitImageId();
logger.finest( "Built image ID: " + builtImageId );
List<Image> images = docker.listImagesCmd().exec();
images = images == null ? new ArrayList<Image>( 0 ) : images;
Image img = DockerUtils.findImageByTag( TAG, images );
Assert.assertNotNull( img );
dockerImageId = img.getId();
docker.close();
} catch( IOException | InterruptedException e ) {
logger.warning( "Tests are skipped because Docker is not installed or misconfigured." );
Utils.logException( logger, e );
dockerIsInstalled = false;
Assume.assumeNoException( e );
}
}
/**
* @param f
* @param ctx
* @param logger
*/
private static void readRule( File f, AutonomicApplicationContext ctx, Logger logger ) {
RuleParser parser = new RuleParser( f );
if( RoboconfErrorHelpers.containsCriticalErrors( parser.getParsingErrors())) {
logger.warning( "Critical errors were found for rule " + parser.getRule().getRuleName());
} else {
Rule rule = parser.getRule();
ctx.ruleNameToRule.put( rule.getRuleName(), rule );
}
}
/**
* Retrieves a request body.
*
* @param entity Entity to extract the body from.
* @param logger Logger.
* @return Text representation of the body.
*/
private String getRequestBody(Representation entity, Logger logger) {
if (entity == null) {
return null;
}
// check the body of the event to be sent
if (!entity.getMediaType().equals(MediaType.APPLICATION_JSON)){
logger.warning("Invalid request body - must be a valid JSON.");
throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST,
"Invalid request body - must be a valid JSON.");
}
// get the json
String eventJsonString = null;
try {
eventJsonString = entity.getText();
} catch (IOException e) {
logger.info(e.getMessage());
throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST,
"Invalid request body");
}
return eventJsonString;
}
/**
* Retrieves a request body.
*
* @param entity Entity to extract the body from.
* @param logger Logger.
* @return Text representation of the body.
*/
private String getRequestBody(Representation entity, Logger logger) {
if (entity == null) {
return null;
}
// check the body of the event to be sent
if (!entity.getMediaType().equals(MediaType.APPLICATION_JSON)){
logger.warning("Invalid request body - must be a valid JSON.");
throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST,
"Invalid request body - must be a valid JSON.");
}
// get the json
String eventJsonString = null;
try {
eventJsonString = entity.getText();
} catch (IOException e) {
logger.info(e.getMessage());
throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST,
"Invalid request body");
}
return eventJsonString;
}
/**
* Retrieves a request body.
*
* @param entity Entity to extract the body from.
* @param logger Logger.
* @return Text representation of the body.
*/
private String getRequestBody(Representation entity, Logger logger) {
if (entity == null) {
return null;
}
// check the body of the event to be sent
if (!entity.getMediaType().equals(MediaType.APPLICATION_JSON)){
logger.warning("Invalid request body - must be a valid JSON.");
throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST,
"Invalid request body - must be a valid JSON.");
}
// get the json
String eventJsonString = null;
try {
eventJsonString = entity.getText();
} catch (IOException e) {
logger.info(e.getMessage());
throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST,
"Invalid request body");
}
return eventJsonString;
}
void test(String[] args) {
final String name = "myLogger";
final String message = "myMessage";
final AtomicInteger getHandlerCount = new AtomicInteger(0);
final AtomicLong lastSequenceNumber = new AtomicLong(-1L);
final AtomicInteger lastThreadID = new AtomicInteger(-1);
final Logger logger = new Logger(name, null) {
public Handler[] getHandlers() {
getHandlerCount.getAndIncrement();
return super.getHandlers();
}};
equal(logger.getName(), name);
equal(logger.getResourceBundle(), null);
equal(logger.getFilter(), null);
equal(logger.getLevel(), null);
check(logger.isLoggable(Level.WARNING));
logger.addHandler(new Handler() {
public void close() {}
public void flush() {}
public void publish(LogRecord l) {
equal(l.getLoggerName(), name);
equal(l.getMessage(), message);
equal(l.getResourceBundle(), null);
equal(l.getSourceClassName(), "LoggerSubclass");
equal(l.getSourceMethodName(), "test");
equal(l.getThrown(), null);
equal(l.getLevel(), Level.WARNING);
if (lastSequenceNumber.get() != -1) {
equal(lastSequenceNumber.get() + 1,
l.getSequenceNumber());
equal(lastThreadID.get(),
l.getThreadID());
equal((int) Thread.currentThread().getId(),
l.getThreadID());
}
lastSequenceNumber.set(l.getSequenceNumber());
lastThreadID.set(l.getThreadID());
}});
for (int i = 1; i < 4; i++) {
logger.warning(message); // Should invoke getHandlers()
equal(i, getHandlerCount.get());
}
}
/**
* Constructor, initialises necessary objects. All parameters are mandatory, failure to include them can lead
* to a swift end of application.
*
* @param config Configuration object.
* @param logger Java logger.
*/
public CommunicationManager(XMLConfiguration config, Logger logger, MessageCounter messageCounter){
logger.config("OGWAPI version: " + OGWAPI_VERSION);
this.descriptorPool = Collections.synchronizedMap(new HashMap<String, ConnectionDescriptor>());
this.nmConnector = new NeighbourhoodManagerConnector(config, logger);
// load the configuration for the pageSize param
pageSize = config.getInt(CONFIG_PARAM_PAGE_SIZE, CONFIG_DEF_PAGE_SIZE);
this.sessionExpiration = 0;
this.config = config;
this.logger = logger;
this.messageCounter = messageCounter;
// load the configuration for the session recovery policy
String sessionRecoveryPolicyString = config.getString(CONFIG_PARAM_SESSIONRECOVERY, CONFIG_DEF_SESSIONRECOVERY);
translateSessionRecoveryConf(sessionRecoveryPolicyString);
if (sessionRecoveryPolicy == SESSIONRECOVERYPOLICY_INT_ERROR) {
// wrong configuration parameter entered - set it to default
logger.warning("Wrong parameter entered for " + CONFIG_PARAM_SESSIONRECOVERY + " in the configuration file: "
+ sessionRecoveryPolicyString + ". Setting to default: " + CONFIG_DEF_SESSIONRECOVERY);
translateSessionRecoveryConf(CONFIG_DEF_SESSIONRECOVERY);
} else {
logger.config("The session recovery policy is set to " + sessionRecoveryPolicyString + ".");
}
// timer for session checking - N/A if the session recovery is set to none
if (sessionRecoveryPolicy != SESSIONRECOVERYPOLICY_INT_NONE) {
int checkInterval;
switch(sessionRecoveryPolicy) {
case SESSIONRECOVERYPOLICY_INT_PASSIVE:
checkInterval = SESSIONRECOVERY_CHECKINTERVAL_PASSIVE;
sessionExpiration = config.getInt(CONFIG_PARAM_SESSIONEXPIRATION, CONFIG_DEF_SESSIONEXPIRATION);
// if somebody put there too small number, we will turn it to default
if (sessionExpiration < SESSIONEXPIRATION_MINIMAL_VALUE) {
logger.warning("Wrong parameter entered for " + CONFIG_PARAM_SESSIONEXPIRATION + " in the configuration file: "
+ sessionRecoveryPolicyString + ". Setting to default: " + CONFIG_DEF_SESSIONEXPIRATION);
sessionExpiration = CONFIG_DEF_SESSIONEXPIRATION;
}
sessionExpiration = sessionExpiration * 1000;
logger.config("Session expiration is set to " + sessionExpiration + "ms");
break;
case SESSIONRECOVERYPOLICY_INT_PROACTIVE:
checkInterval = SESSIONRECOVERY_CHECKINTERVAL_PROACTIVE;
break;
default:
// if something goes wrong, don't let the timer stand in our way
checkInterval = Integer.MAX_VALUE;
}
Timer timerForSessionRecovery = new Timer();
timerForSessionRecovery.schedule(new TimerTask() {
@Override
public void run() {
recoverSessions();
}
}, checkInterval, checkInterval);
}
}
void test(String[] args) {
final String name = "myLogger";
final String message = "myMessage";
final AtomicInteger getHandlerCount = new AtomicInteger(0);
final AtomicLong lastSequenceNumber = new AtomicLong(-1L);
final AtomicInteger lastThreadID = new AtomicInteger(-1);
final Logger logger = new Logger(name, null) {
public Handler[] getHandlers() {
getHandlerCount.getAndIncrement();
return super.getHandlers();
}};
equal(logger.getName(), name);
equal(logger.getResourceBundle(), null);
equal(logger.getFilter(), null);
equal(logger.getLevel(), null);
check(logger.isLoggable(Level.WARNING));
logger.addHandler(new Handler() {
public void close() {}
public void flush() {}
public void publish(LogRecord l) {
equal(l.getLoggerName(), name);
equal(l.getMessage(), message);
equal(l.getResourceBundle(), null);
equal(l.getSourceClassName(), "LoggerSubclass");
equal(l.getSourceMethodName(), "test");
equal(l.getThrown(), null);
equal(l.getLevel(), Level.WARNING);
if (lastSequenceNumber.get() != -1) {
equal(lastSequenceNumber.get() + 1,
l.getSequenceNumber());
equal(lastThreadID.get(),
l.getThreadID());
equal((int) Thread.currentThread().getId(),
l.getThreadID());
}
lastSequenceNumber.set(l.getSequenceNumber());
lastThreadID.set(l.getThreadID());
}});
for (int i = 1; i < 4; i++) {
logger.warning(message); // Should invoke getHandlers()
equal(i, getHandlerCount.get());
}
}