Java Code Examples for org.apache.commons.logging.Log#warn()

The following examples show how to use org.apache.commons.logging.Log#warn() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: DeferredLog.java    From java-cfenv with Apache License 2.0 6 votes vote down vote up
private static void logTo(Log log, LogLevel level, Object message,
						  Throwable throwable) {
	switch (level) {
		case TRACE:
			log.trace(message, throwable);
			return;
		case DEBUG:
			log.debug(message, throwable);
			return;
		case INFO:
			log.info(message, throwable);
			return;
		case WARN:
			log.warn(message, throwable);
			return;
		case ERROR:
			log.error(message, throwable);
			return;
		case FATAL:
			log.fatal(message, throwable);
			return;
	}
}
 
Example 2
Source File: MappingUtils.java    From elasticsearch-hadoop with Apache License 2.0 6 votes vote down vote up
public static void validateMapping(Collection<String> fields, Mapping mapping, FieldPresenceValidation validation, Log log) {
    if (mapping == null || fields == null || fields.isEmpty() || validation == null || FieldPresenceValidation.IGNORE == validation) {
        return;
    }

    List[] results = findTypos(fields, mapping);

    if (results == null) {
        return;
    }

    String message = String.format("Field(s) [%s] not found in the Elasticsearch mapping specified; did you mean [%s]?",
            removeDoubleBrackets(results[0]), removeDoubleBrackets(results[1]));
    if (validation == FieldPresenceValidation.WARN) {
        log.warn(message);
    }
    else {
        throw new EsHadoopIllegalArgumentException(message);
    }
}
 
Example 3
Source File: LoggerModuleComponent.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
protected void executeInternal() throws Throwable
{
    String moduleId = super.getModuleId();
    String name = super.getName();
    Log logger = LogFactory.getLog(moduleId + "." + name);
    switch (logLevel)
    {
    case INFO:
        logger.info(message);
        break;
    case WARN:
        logger.warn(message);
        break;
    case ERROR:
        logger.error(message);
        break;
    }
}
 
Example 4
Source File: Log4jConfigurerTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
private void doTestInitLogging(String location, boolean refreshInterval) throws FileNotFoundException {
	if (refreshInterval) {
		Log4jConfigurer.initLogging(location, 10);
	}
	else {
		Log4jConfigurer.initLogging(location);
	}

	Log log = LogFactory.getLog(this.getClass());
	log.debug("debug");
	log.info("info");
	log.warn("warn");
	log.error("error");
	log.fatal("fatal");

	assertTrue(MockLog4jAppender.loggingStrings.contains("debug"));
	assertTrue(MockLog4jAppender.loggingStrings.contains("info"));
	assertTrue(MockLog4jAppender.loggingStrings.contains("warn"));
	assertTrue(MockLog4jAppender.loggingStrings.contains("error"));
	assertTrue(MockLog4jAppender.loggingStrings.contains("fatal"));

	Log4jConfigurer.shutdownLogging();
	assertTrue(MockLog4jAppender.closeCalled);
}
 
Example 5
Source File: CommonsLoggerTest.java    From netty4.0.27Learn with Apache License 2.0 5 votes vote down vote up
@Test
public void testWarn() {
    Log mock =
        createStrictMock(Log.class);

    mock.warn("a");
    replay(mock);

    InternalLogger logger = new CommonsLogger(mock, "foo");
    logger.warn("a");
    verify(mock);
}
 
Example 6
Source File: RestService.java    From elasticsearch-hadoop with Apache License 2.0 5 votes vote down vote up
/**
 * Create one {@link PartitionDefinition} per shard for each requested index.
 */
static List<PartitionDefinition> findShardPartitions(Settings settings, MappingSet mappingSet, Map<String, NodeInfo> nodes,
                                                     List<List<Map<String, Object>>> shards, Log log) {
    Mapping resolvedMapping = mappingSet == null ? null : mappingSet.getResolvedView();
    List<PartitionDefinition> partitions = new ArrayList<PartitionDefinition>(shards.size());
    PartitionDefinition.PartitionDefinitionBuilder partitionBuilder = PartitionDefinition.builder(settings, resolvedMapping);
    for (List<Map<String, Object>> group : shards) {
        String index = null;
        int shardId = -1;
        List<String> locationList = new ArrayList<String> ();
        for (Map<String, Object> replica : group) {
            ShardInfo shard = new ShardInfo(replica);
            index = shard.getIndex();
            shardId = shard.getName();
            if (nodes.containsKey(shard.getNode())) {
                locationList.add(nodes.get(shard.getNode()).getPublishAddress());
            }
        }
        if (index == null) {
            // Could not find shards for this partition. Continue anyway?
            if (settings.getIndexReadAllowRedStatus()) {
                log.warn("Shard information is missing from an index and will not be reached during job execution. " +
                        "Assuming shard is unavailable and cluster is red! Continuing with read operation by " +
                        "skipping this shard! This may result in incomplete data retrieval!");
            } else {
                throw new IllegalStateException("Could not locate shard information for one of the read indices. " +
                        "Check your cluster status to see if it is unstable!");
            }
        } else {
            PartitionDefinition partition = partitionBuilder.build(index, shardId, locationList.toArray(new String[0]));
            partitions.add(partition);
        }
    }
    return partitions;
}
 
Example 7
Source File: CommonsLoggingListener.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
/** @see com.puppycrawl.tools.checkstyle.api.AuditListener */
public void addError(AuditEvent aEvt)
{
    final SeverityLevel severityLevel = aEvt.getSeverityLevel();
    if (mInitialized && !SeverityLevel.IGNORE.equals(severityLevel)) {
        final Log log = mLogFactory.getInstance(aEvt.getSourceName());

        final String fileName = aEvt.getFileName();
        final String message = aEvt.getMessage();

        // avoid StringBuffer.expandCapacity
        final int bufLen = message.length() + BUFFER_CUSHION;
        final StringBuffer sb = new StringBuffer(bufLen);

        sb.append("Line: ").append(aEvt.getLine());
        if (aEvt.getColumn() > 0) {
            sb.append(" Column: ").append(aEvt.getColumn());
        }
        sb.append(" Message: ").append(message);

        if (aEvt.getSeverityLevel().equals(SeverityLevel.WARNING)) {
            log.warn(sb.toString());
        }
        else if (aEvt.getSeverityLevel().equals(SeverityLevel.INFO)) {
            log.info(sb.toString());
        }
        else {
            log.error(sb.toString());
        }
    }
}
 
Example 8
Source File: HeartBeat.java    From elasticsearch-hadoop with Apache License 2.0 5 votes vote down vote up
HeartBeat(final Progressable progressable, Configuration cfg, TimeValue lead, final Log log) {
    Assert.notNull(progressable, "a valid progressable is required to report status to Hadoop");
    TimeValue tv = HadoopCfgUtils.getTaskTimeout(cfg);

    Assert.isTrue(tv.getSeconds() <= 0 || tv.getSeconds() > lead.getSeconds(), "Hadoop timeout is shorter than the heartbeat");

    this.progressable = progressable;
    long cfgMillis = (tv.getMillis() > 0 ? tv.getMillis() : 0);
    // the task is simple hence the delay = timeout - lead, that is when to start the notification right before the timeout
    this.delay = new TimeValue(Math.abs(cfgMillis - lead.getMillis()), TimeUnit.MILLISECONDS);
    this.log = log;

    String taskId;
    TaskID taskID = HadoopCfgUtils.getTaskID(cfg);

    if (taskID == null) {
        log.warn("Cannot determine task id...");
        taskId = "<unknown>";
        if (log.isTraceEnabled()) {
            log.trace("Current configuration is " + HadoopCfgUtils.asProperties(cfg));
        }
    }
    else {
        taskId = "" + taskID;
    }

    id = taskId;
}
 
Example 9
Source File: CompatUtils.java    From elasticsearch-hadoop with Apache License 2.0 5 votes vote down vote up
static void warnSchemaRDD(Object rdd, Log log) {
    if (rdd != null && SCHEMA_RDD_LIKE_CLASS != null) {
        if (SCHEMA_RDD_LIKE_CLASS.isAssignableFrom(rdd.getClass())) {
            log.warn("basic RDD saveToEs() called on a Spark SQL SchemaRDD; typically this is a mistake(as the SQL schema will be ignored). Use 'org.elasticsearch.spark.sql' package instead");
        }
    }
}
 
Example 10
Source File: TestConfigurationLogger.java    From commons-configuration with Apache License 2.0 5 votes vote down vote up
/**
 * Tests whether an exception can be logged on warn level.
 */
@Test
public void testWarnWithException()
{
    final Log log = EasyMock.createMock(Log.class);
    final Throwable ex = new Exception("Test exception");
    log.warn(MSG, ex);
    EasyMock.replay(log);
    final ConfigurationLogger logger = new ConfigurationLogger(log);

    logger.warn(MSG, ex);
    EasyMock.verify(log);
}
 
Example 11
Source File: TestConfigurationLogger.java    From commons-configuration with Apache License 2.0 5 votes vote down vote up
/**
 * Tests whether warn logging is possible.
 */
@Test
public void testWarn()
{
    final Log log = EasyMock.createMock(Log.class);
    log.warn(MSG);
    EasyMock.replay(log);
    final ConfigurationLogger logger = new ConfigurationLogger(log);

    logger.warn(MSG);
    EasyMock.verify(log);
}
 
Example 12
Source File: RMServerUtils.java    From hadoop with Apache License 2.0 5 votes vote down vote up
/**
 * Utility method to verify if the current user has access based on the
 * passed {@link AccessControlList}
 * @param authorizer the {@link AccessControlList} to check against
 * @param method the method name to be logged
 * @param module like AdminService or NodeLabelManager
 * @param LOG the logger to use
 * @return {@link UserGroupInformation} of the current user
 * @throws IOException
 */
public static UserGroupInformation verifyAdminAccess(
    YarnAuthorizationProvider authorizer, String method, String module,
    final Log LOG)
    throws IOException {
  UserGroupInformation user;
  try {
    user = UserGroupInformation.getCurrentUser();
  } catch (IOException ioe) {
    LOG.warn("Couldn't get current user", ioe);
    RMAuditLogger.logFailure("UNKNOWN", method, "",
        "AdminService", "Couldn't get current user");
    throw ioe;
  }

  if (!authorizer.isAdmin(user)) {
    LOG.warn("User " + user.getShortUserName() + " doesn't have permission" +
        " to call '" + method + "'");

    RMAuditLogger.logFailure(user.getShortUserName(), method, "", module,
      RMAuditLogger.AuditConstants.UNAUTHORIZED_USER);

    throw new AccessControlException("User " + user.getShortUserName() +
            " doesn't have permission" +
            " to call '" + method + "'");
  }
  if (LOG.isTraceEnabled()) {
    LOG.trace(method + " invoked by user " + user.getShortUserName());
  }
  return user;
}
 
Example 13
Source File: NodeRef.java    From alfresco-data-model with GNU Lesser General Public License v3.0 5 votes vote down vote up
private static void logNodeRefError(String nodeRefId, Log logger)
{
    if (logger.isWarnEnabled())
    {
        StringBuilder msg = new StringBuilder();
        msg.append("Target Node: ").append(nodeRefId);
        msg.append(" is not a valid NodeRef and has been ignored.");
        logger.warn(msg.toString());
    }
}
 
Example 14
Source File: MapperPrefixSuffix.java    From GraphiteReceiver with Apache License 2.0 5 votes vote down vote up
public MapperPrefixSuffix(String path) throws FileNotFoundException {
    Log logger = LogFactory.getLog(MapperPrefixSuffix.class);
    this.hostnameMap = new File(path);
    if(this.hostnameMap.exists()) {
        if(this.hostnameMap.length() == 0) {
            logger.warn("hostname map no exist or is empty");
        }
    } else {
        throw new FileNotFoundException();
    }

}
 
Example 15
Source File: PhysicalExec.java    From tajo with Apache License 2.0 4 votes vote down vote up
protected void warn(Log log, String message) {
  log.warn("[" + context.getTaskId() + "] " + message);
}
 
Example 16
Source File: MethodUtils.java    From commons-beanutils with Apache License 2.0 4 votes vote down vote up
/**
 * Try to make the method accessible
 * @param method The source arguments
 */
private static void setMethodAccessible(final Method method) {
    try {
        //
        // XXX Default access superclass workaround
        //
        // When a public class has a default access superclass
        // with public methods, these methods are accessible.
        // Calling them from compiled code works fine.
        //
        // Unfortunately, using reflection to invoke these methods
        // seems to (wrongly) to prevent access even when the method
        // modifier is public.
        //
        // The following workaround solves the problem but will only
        // work from sufficiently privileges code.
        //
        // Better workarounds would be gratefully accepted.
        //
        if (!method.isAccessible()) {
            method.setAccessible(true);
        }

    } catch (final SecurityException se) {
        // log but continue just in case the method.invoke works anyway
        final Log log = LogFactory.getLog(MethodUtils.class);
        if (!loggedAccessibleWarning) {
            boolean vulnerableJVM = false;
            try {
                final String specVersion = System.getProperty("java.specification.version");
                if (specVersion.charAt(0) == '1' &&
                        (specVersion.charAt(2) == '0' ||
                         specVersion.charAt(2) == '1' ||
                         specVersion.charAt(2) == '2' ||
                         specVersion.charAt(2) == '3')) {

                    vulnerableJVM = true;
                }
            } catch (final SecurityException e) {
                // don't know - so display warning
                vulnerableJVM = true;
            }
            if (vulnerableJVM) {
                log.warn(
                    "Current Security Manager restricts use of workarounds for reflection bugs "
                    + " in pre-1.4 JVMs.");
            }
            loggedAccessibleWarning = true;
        }
        log.debug("Cannot setAccessible on method. Therefore cannot use jvm access bug workaround.", se);
    }
}
 
Example 17
Source File: PhysicalExec.java    From incubator-tajo with Apache License 2.0 4 votes vote down vote up
protected void warn(Log log, String message) {
  log.warn("[" + context.getTaskId() + "] " + message);
}
 
Example 18
Source File: RestService.java    From elasticsearch-hadoop with Apache License 2.0 4 votes vote down vote up
/**
 * Partitions the query based on the max number of documents allowed per partition {@link Settings#getMaxDocsPerPartition()}.
 */
static List<PartitionDefinition> findSlicePartitions(RestClient client, Settings settings, MappingSet mappingSet,
                                                     Map<String, NodeInfo> nodes, List<List<Map<String, Object>>> shards, Log log) {
    QueryBuilder query = QueryUtils.parseQueryAndFilters(settings);
    Integer maxDocsPerPartition = settings.getMaxDocsPerPartition();
    Assert.notNull(maxDocsPerPartition, "Attempting to find slice partitions but maximum documents per partition is not set.");
    Resource readResource = new Resource(settings, true);
    Mapping resolvedMapping = mappingSet == null ? null : mappingSet.getResolvedView();
    PartitionDefinition.PartitionDefinitionBuilder partitionBuilder = PartitionDefinition.builder(settings, resolvedMapping);

    List<PartitionDefinition> partitions = new ArrayList<PartitionDefinition>(shards.size());
    for (List<Map<String, Object>> group : shards) {
        String index = null;
        int shardId = -1;
        List<String> locationList = new ArrayList<String> ();
        for (Map<String, Object> replica : group) {
            ShardInfo shard = new ShardInfo(replica);
            index = shard.getIndex();
            shardId = shard.getName();
            if (nodes.containsKey(shard.getNode())) {
                locationList.add(nodes.get(shard.getNode()).getPublishAddress());
            }
        }
        String[] locations = locationList.toArray(new String[0]);
        if (index == null) {
            // Could not find shards for this partition. Continue anyway?
            if (settings.getIndexReadAllowRedStatus()) {
                log.warn("Shard information is missing from an index and will not be reached during job execution. " +
                        "Assuming shard is unavailable and cluster is red! Continuing with read operation by " +
                        "skipping this shard! This may result in incomplete data retrieval!");
            } else {
                throw new IllegalStateException("Could not locate shard information for one of the read indices. " +
                        "Check your cluster status to see if it is unstable!");
            }
        } else {
            // TODO applyAliasMetaData should be called in order to ensure that the count are exact (alias filters and routing may change the number of documents)
            long numDocs;
            if (readResource.isTyped()) {
                numDocs = client.count(index, readResource.type(), Integer.toString(shardId), query);
            } else {
                numDocs = client.countIndexShard(index, Integer.toString(shardId), query);
            }
            int numPartitions = (int) Math.max(1, numDocs / maxDocsPerPartition);
            for (int i = 0; i < numPartitions; i++) {
                PartitionDefinition.Slice slice = new PartitionDefinition.Slice(i, numPartitions);
                partitions.add(partitionBuilder.build(index, shardId, slice, locations));
            }
        }
    }
    return partitions;
}
 
Example 19
Source File: Issues200Test.java    From commons-jexl with Apache License 2.0 4 votes vote down vote up
@Test
public void test279() throws Exception {
    final Log logger = null;//LogFactory.getLog(Issues200Test.class);
    Object result;
    JexlScript script;
    JexlContext ctxt = new Context279();
    String[] srcs = new String[]{
        "var z = null; identity(z[0]);",
         "var z = null; z.0;",
         "var z = null; z.foo();",
        "z['y']['z']",
        "z.y.any()",
         "identity(z.any())",
         "z[0]",
         "z.0",
         "z.foo()",
         "z.y[0]",
         "z.y[0].foo()",
         "z.y.0",
         "z.y.foo()",
         "var z = { 'y' : [42] }; z.y[1]",
         "var z = { 'y' : [42] }; z.y.1",
         "var z = { 'y' : [-42] }; z.y[1].foo()",
         "var z = { 'y' : [42] }; z.y.1.foo()",
         "var z = { 'y' : [null, null] }; z.y[1].foo()",
         "var z = { 'y' : [null, null] }; z.y.1.foo()"
    };
    for (int i = 0; i < 2; ++i) {
        for (boolean strict : new boolean[]{true, false}) {
            JexlEngine jexl = new JexlBuilder().safe(false).strict(strict).create();
            for (String src : srcs) {
                script = jexl.createScript(src);
                try {
                    result = script.execute(ctxt);
                    if (strict) {
                        if (logger != null) {
                            logger.warn(ctxt.has("z") + ": " + src + ": no fail, " + result);
                        }
                        Assert.fail("should have failed: " + src);
                    }
                    // not reachable
                    Assert.assertNull("non-null result ?!", result);
                } catch (JexlException.Variable xvar) {
                    if (logger != null) {
                        logger.warn(ctxt.has("z") + ": " + src + ": fail, " + xvar);
                    }
                    if (!strict) {
                        Assert.fail(src + ", should not have thrown " + xvar);
                    } else {
                        Assert.assertTrue(src + ": " + xvar.toString(), xvar.toString().contains("z"));
                    }
                } catch (JexlException.Property xprop) {
                    if (logger != null) {
                        logger.warn(ctxt.has("z") + ": " + src + ": fail, " + xprop);
                    }
                    if (!strict) {
                        Assert.fail(src + ", should not have thrown " + xprop);
                    } else {
                        Assert.assertTrue(src + ": " + xprop.toString(), xprop.toString().contains("1"));
                    }
                }
            }
        }
        ctxt.set("z.y", null);
    }
}
 
Example 20
Source File: VfsLog.java    From commons-vfs with Apache License 2.0 3 votes vote down vote up
/**
 * warning.
 *
 * @param vfsLog The base component Logger to use.
 * @param commonslog The class specific Logger
 * @param message The message to log.
 * @param t The exception, if any.
 */
public static void warn(final Log vfsLog, final Log commonslog, final String message, final Throwable t) {
    if (vfsLog != null) {
        vfsLog.warn(message, t);
    } else if (commonslog != null) {
        commonslog.warn(message, t);
    }
}