Example usage for java.util.logging Level OFF

List of usage examples for java.util.logging Level OFF

Introduction

In this page you can find the example usage for java.util.logging Level OFF.

Prototype

Level OFF

To view the source code for java.util.logging Level OFF.

Click Source Link

Document

OFF is a special level that can be used to turn off logging.

Usage

From source file:org.exoplatform.wcm.connector.viewer.PDFViewerRESTService.java

private Document buildDocumentImage(File input, String name) {
    Document document = new Document();

    // Turn off Log of org.icepdf.core.pobjects.Document to avoid printing error stack trace in case viewing
    // a PDF file which use new Public Key Security Handler.
    // TODO: Remove this statement after IcePDF fix this
    Logger.getLogger(Document.class.toString()).setLevel(Level.OFF);

    // Capture the page image to file
    try {//from  w  w w .j a  va  2 s  . c o m
        // cut the file name if name is too long, because OS allows only file with name < 250 characters
        name = reduceFileNameSize(name);
        document.setInputStream(new BufferedInputStream(new FileInputStream(input)), name);
    } catch (PDFException ex) {
        if (LOG.isDebugEnabled()) {
            LOG.error("Error parsing PDF document " + ex);
        }
    } catch (PDFSecurityException ex) {
        if (LOG.isDebugEnabled()) {
            LOG.error("Error encryption not supported " + ex);
        }
    } catch (FileNotFoundException ex) {
        if (LOG.isDebugEnabled()) {
            LOG.error("Error file not found " + ex);
        }
    } catch (IOException ex) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Error handling PDF document: {} {}", name, ex.toString());
        }
    }

    return document;
}

From source file:edu.illinois.cs.cogcomp.temporal.normalizer.main.TemporalNormalizerBenchmark.java

/**
 * Normalize the dataset using our Chunker for temporal phrases extraction
 * @param outputFolder/*from  w  w w .ja  v a2s  . c o  m*/
 * @param verbose
 * @throws Exception
 */
public void testTemporalChunker(String outputFolder, boolean verbose) throws Exception {
    TextAnnotationBuilder tab = new TokenizerTextAnnotationBuilder(new StatefulTokenizer(false, false));

    ResourceManager nerRm = new TemporalChunkerConfigurator().getDefaultConfig();
    IOUtilities.existsInClasspath(TemporalChunkerAnnotator.class, nerRm.getString("modelDirPath"));
    java.util.logging.Logger.getLogger("HeidelTimeStandalone").setLevel(Level.OFF);

    List<TextAnnotation> taList = new ArrayList<>();
    long preprocessTime = System.currentTimeMillis();
    POSAnnotator annotator = new POSAnnotator();

    for (int j = 0; j < testText.size(); j++) {
        TextAnnotation ta = tab.createTextAnnotation("corpus", "id", testText.get(j));
        try {
            annotator.getView(ta);
        } catch (AnnotatorException e) {
            fail("AnnotatorException thrown!\n" + e.getMessage());
        }
        taList.add(ta);
    }

    if (verbose) {
        System.out.println("Start");
    }
    long startTime = System.currentTimeMillis();
    File outDir = new File(outputFolder);
    if (!outDir.exists()) {
        outDir.mkdir();
    }

    for (int j = 0; j < testText.size(); j++) {

        tca.addDocumentCreationTime(DCTs.get(j));
        TextAnnotation ta = taList.get(j);

        try {
            tca.addView(ta);
        } catch (AnnotatorException e) {
            fail("Exception while adding TIMEX3 VIEW " + e.getStackTrace());
        }

        String outputFileName = "./" + outputFolder + "/" + docIDs.get(j) + ".tml";
        if (verbose) {
            System.out.println(docIDs.get(j));
            for (TimexChunk tc : tca.getTimex()) {
                System.out.println(tc.toTIMEXString());
            }
            System.out.println("\n");
        }
        tca.write2Text(outputFileName, docIDs.get(j), testText.get(j));
        tca.deleteTimex();
    }
    long endTime = System.currentTimeMillis();
    long totalTime = endTime - startTime;
    if (verbose) {
        System.out.println("Process time: " + totalTime);
        System.out.println("Preprocess + process time: " + (endTime - preprocessTime));
    }
}

From source file:net.sourceforge.czt.gnast.Gnast.java

/**
 * Parses the arguments from the command line.
 *
 * @return a configured GnAST builder if parsing was successful;
 *         {@code null} otherwise./*from w  ww . j a v a2 s .c om*/
 * @throws NullPointerException if {@code args} is {@code null}
 */
@SuppressWarnings("static-access")
private static GnastBuilder parseArguments(String[] args) {

    Options argOptions = new Options();

    OptionGroup verboseOptions = new OptionGroup();
    verboseOptions.addOption(OptionBuilder.withLongOpt("verbose")
            .withDescription("Verbose; display verbose debugging messages").create("v"));
    verboseOptions.addOption(OptionBuilder.withLongOpt("vverbose")
            .withDescription("Very verbose; more verbose debugging messages").create("vv"));
    verboseOptions.addOption(OptionBuilder.withLongOpt("vvverbose")
            .withDescription("Very very verbose; even more verbose debugging messages").create("vvv"));
    argOptions.addOptionGroup(verboseOptions);

    argOptions.addOption(OptionBuilder.withLongOpt("finalizers")
            .withDescription("Add AST finalisers. WARNING: ASTs will consume more memory!").create("f"));

    argOptions.addOption(OptionBuilder.withArgName("dir").hasArg().withLongOpt("destination")
            .withDescription("Generated files go into this directory").create("d"));

    argOptions.addOption(OptionBuilder.withArgName("dir1 dir2").hasArgs().withValueSeparator(',')
            .withLongOpt("templates").withDescription("Additional template directories").create("t"));

    argOptions.addOption(OptionBuilder.withArgName("file").hasArg().withLongOpt("mapping")
            .withDescription("XML type mapping properties file").create("m"));

    argOptions.addOption(OptionBuilder.withArgName("dir").hasArg().withLongOpt("source").withDescription(
            "The directory with all ZML schema files. The requested project namespace must be present, as well as all its parents.")
            .create("s"));

    argOptions.addOption(OptionBuilder.withArgName("url").hasArg().withLongOpt("namespace")
            .withDescription("The namespace of the project to be generated.").create("n"));

    // use GNU parser that allows longer option name (e.g. `-vvv`)
    CommandLineParser parser = new GnuParser();
    CommandLine line;
    try {
        // parse the command line arguments
        line = parser.parse(argOptions, args);
    } catch (ParseException exp) {
        // oops, something went wrong
        System.err.println(exp.getMessage());

        // automatically generate the help statement
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("gnast", argOptions, true);

        return null;
    }

    Level verbosity = line.hasOption("v") ? Level.INFO
            : (line.hasOption("vv") ? Level.FINE : (line.hasOption("vvv") ? Level.FINER : Level.OFF));

    String[] templates = line.getOptionValues("t");
    List<URL> templateDirs = new ArrayList<URL>();
    for (String path : templates) {
        templateDirs.add(toURL(path));
    }

    return new GnastBuilder().verbosity(verbosity).finalizers(line.hasOption("f"))
            .destination(toFile(line.getOptionValue("d"))).templates(templateDirs)
            .mapping(toURL(line.getOptionValue("m"))).sourceSchemas(schemaDirToURL(line.getOptionValue("s")))
            .namespace(line.getOptionValue("n"));
}

From source file:pt.ua.tm.neji.cli.Main.java

public static void main(String[] args) {
    //        installUncaughtExceptionHandler();

    int NUM_THREADS = Runtime.getRuntime().availableProcessors() - 1;
    NUM_THREADS = NUM_THREADS > 0 ? NUM_THREADS : 1;

    CommandLineParser parser = new GnuParser();
    Options options = new Options();
    options.addOption("h", "help", false, "Print this usage information.");

    options.addOption("i", "input", true, "Folder with corpus files.");
    options.addOption("o", "output", true, "Folder to save the annotated corpus files.");
    options.addOption("f", "input-filter", true, "Wildcard to filter files in input folder");

    options.addOption("p", "parser", true, "Folder that contains the parsing tool.");

    Option o = new Option("m", "models", true, "Folder that contains the ML models.");
    o.setArgs(Integer.MAX_VALUE);
    options.addOption(o);/*from   w  ww. java  2 s.  c  om*/

    options.addOption("d", "dictionaires", true, "Folder that contains the dictionaries.");

    options.addOption("if", "input-format", true, "BIOC, RAW or XML");
    o = new Option("of", "output-formats", true, "A1, B64, BIOC, CONLL, JSON, NEJI or XML");
    o.setArgs(Integer.MAX_VALUE);
    options.addOption(o);

    options.addOption("ptool", "parsing-tool", true, "GDEP or OPENNLP (GDEP is set by default)");

    options.addOption("plang", "parsing-language", true,
            "DANISH, DUTCH, ENGLISH, FRENCH, GERMAN, PORTUGUESE or SWEDISH (ENGLISH is set by default)");

    options.addOption("plvl", "parsing-level", true,
            "TOKENIZATION, POS, LEMMATIZATION, CHUNKING or DEPENDENCY (TOKENIZATION is set by default)");

    options.addOption("pcls", "processor-class", true, "Full name of pipeline processor class.");

    options.addOption("custom", "custom-modules", true,
            "Names of custom modules to be used in order, separated by pipes. If a specified module are not a reader or a writer, it will be executed after dictionary and model processing.");

    options.addOption("x", "xml-tags", true, "XML tags to be considered, separated by commas.");

    options.addOption("v", "verbose", false, "Verbose mode.");
    options.addOption("s", "server", false, "Generate server.");
    options.addOption("c", "compressed", false, "If files are compressed using GZip.");
    options.addOption("noids", "include-no-ids", false, "If annotations without IDs should be included.");
    options.addOption("t", "threads", true,
            "Number of threads. By default, if more than one core is available, it is the number of cores minus 1.");

    options.addOption("fp", "false-positives-filter", true, "File that contains the false positive terms.");
    options.addOption("gn", "semantic-groups-normalization", true,
            "File that contains the semantic groups normalization terms.");

    CommandLine commandLine = null;
    try {
        // Parse the program arguments
        commandLine = parser.parse(options, args);
    } catch (ParseException ex) {
        logger.error("There was a problem processing the input arguments.", ex);
        return;
    }

    // Show help text
    if (commandLine.hasOption('h')) {
        printHelp(options, "");
        return;
    }

    // No options
    if (commandLine.getOptions().length == 0) {
        printHelp(options, "");
        return;
    }

    // Generate server from dictionary, model and parser parameters
    boolean generateServer = false;
    if (commandLine.hasOption('s')) {
        generateServer = true;
    }

    // Get corpus folder for input
    String folderCorpusIn = null;
    if (commandLine.hasOption('i')) {
        folderCorpusIn = commandLine.getOptionValue('i');
        File test = new File(folderCorpusIn);
        if (!test.isDirectory() || !test.canRead()) {
            logger.error("The specified path is not a folder or is not readable.");
            return;
        }
        folderCorpusIn = test.getAbsolutePath();
        folderCorpusIn += File.separator;
    } else {
        printHelp(options, "Please specify the input corpus folder.");
        return;
    }

    String inputFolderWildcard = null;
    if (commandLine.hasOption("f")) {
        inputFolderWildcard = commandLine.getOptionValue("f");
    }

    // Get Input format
    InputFormat inputFormat;
    if (commandLine.hasOption("if")) {
        inputFormat = InputFormat.valueOf(commandLine.getOptionValue("if"));
    } else {
        printHelp(options, "Please specify the input format.");
        return;
    }

    // Get corpus folder for output
    String folderCorpusOut = null;
    if (commandLine.hasOption('o')) {
        folderCorpusOut = commandLine.getOptionValue('o');
        File test = new File(folderCorpusOut);
        if (!test.isDirectory() || !test.canWrite()) {
            logger.error("The specified path is not a folder or is not writable.");
            return;
        }
        folderCorpusOut = test.getAbsolutePath();
        folderCorpusOut += File.separator;
    } else {
        printHelp(options, "Please specify the output corpus folder.");
        return;
    }

    // Get Output format
    List<OutputFormat> outputFormats = new ArrayList<>();
    if (commandLine.hasOption("of")) {
        String[] command = commandLine.getOptionValues("of");
        for (String s : command) {
            OutputFormat f = OutputFormat.valueOf(s);
            if (f.equals(OutputFormat.A1) || f.equals(OutputFormat.JSON) || f.equals(OutputFormat.NEJI)) {
                if (inputFormat.equals(InputFormat.XML)) {
                    logger.error("XML input format only supports XML and CoNLL output formats, "
                            + "since other formats are based on character positions.");
                    return;
                }
            }
            outputFormats.add(f);
        }
    } else {
        printHelp(options, "Please specify the output formats (in case of multiple formats, "
                + "separate them with a \"\\|\").");
        return;
    }

    // Get XML tags
    String[] xmlTags = null;
    if (inputFormat.equals(InputFormat.XML)) {
        if (commandLine.hasOption("x")) {
            xmlTags = commandLine.getOptionValue("x").split(",");
        } else {
            printHelp(options, "Please specify XML tags to be used.");
            return;
        }
    }

    // Get models folder
    String modelsFolder = null;
    if (commandLine.hasOption('m')) {
        modelsFolder = commandLine.getOptionValue('m');

        File test = new File(modelsFolder);
        if (!test.isDirectory() || !test.canRead()) {
            logger.error("The specified models path is not a folder or is not readable.");
            return;
        }
        modelsFolder = test.getAbsolutePath();
        modelsFolder += File.separator;
    }

    // Get dictionaries folder
    String dictionariesFolder = null;
    if (commandLine.hasOption('d')) {
        dictionariesFolder = commandLine.getOptionValue('d');

        File test = new File(dictionariesFolder);
        if (!test.isDirectory() || !test.canRead()) {
            logger.error("The specified dictionaries path is not a folder or is not readable.");
            return;
        }
        dictionariesFolder = test.getAbsolutePath();
        dictionariesFolder += File.separator;
    }

    // Get parser folder
    String parserFolder = null;
    if (commandLine.hasOption("p")) {
        parserFolder = commandLine.getOptionValue("p");

        File test = new File(parserFolder);
        if (!test.isDirectory() || !test.canRead()) {
            logger.error("The specified parser path is not a folder or is not readable.");
            return;
        }
        parserFolder = test.getAbsolutePath();
        parserFolder += File.separator;
    }

    // Get processing modules
    String modulesCommandLine = "";
    if (commandLine.hasOption("custom")) {
        modulesCommandLine = commandLine.getOptionValue("custom");
    }

    // Get verbose mode
    boolean verbose = commandLine.hasOption('v');
    Constants.verbose = verbose;

    if (Constants.verbose) {
        MalletLogger.getGlobal().setLevel(Level.INFO);
        // Redirect sout
        LoggingOutputStream los = new LoggingOutputStream(LoggerFactory.getLogger("stdout"), false);
        System.setOut(new PrintStream(los, true));

        // Redirect serr
        los = new LoggingOutputStream(LoggerFactory.getLogger("sterr"), true);
        System.setErr(new PrintStream(los, true));
    } else {
        MalletLogger.getGlobal().setLevel(Level.OFF);
    }

    // Redirect JUL to SLF4
    SLF4JBridgeHandler.removeHandlersForRootLogger();
    SLF4JBridgeHandler.install();

    // Get compressed mode
    boolean compressed = false;
    if (commandLine.hasOption('c')) {
        compressed = true;
    }

    // Get threads
    String threadsText = null;
    if (commandLine.hasOption('t')) {
        threadsText = commandLine.getOptionValue('t');
        NUM_THREADS = Integer.parseInt(threadsText);
        if (NUM_THREADS <= 0 || NUM_THREADS > 32) {
            logger.error("Illegal number of threads. Must be between 1 and 32.");
            return;
        }
    }

    // Load pipeline processor
    Class processor = FileProcessor.class;
    if (commandLine.hasOption("pcls")) {
        String processorName = commandLine.getOptionValue("pcls");
        try {
            processor = Class.forName(processorName);
        } catch (ClassNotFoundException ex) {
            logger.error("Could not load pipeline processor \"" + processorName + "\"");
            return;
        }
    }

    // Load parsing tool
    ParserTool parsingTool = ParserTool.GDEP;
    if (commandLine.hasOption("ptool")) {
        String parsingToolName = commandLine.getOptionValue("ptool");
        try {
            parsingTool = ParserTool.valueOf(parsingToolName);
        } catch (IllegalArgumentException ex) {
            logger.error("Invalid parsing tool \"" + parsingToolName + "\". " + "Must be one of "
                    + StringUtils.join(ParserTool.values(), ", "));
            return;
        }
    }

    // Load parsing language
    ParserLanguage parsingLanguage = ParserLanguage.ENGLISH;
    if (commandLine.hasOption("plang")) {
        String parsingLanguageName = commandLine.getOptionValue("plang");
        try {
            parsingLanguage = ParserLanguage.valueOf(parsingLanguageName);
        } catch (IllegalArgumentException ex) {
            logger.error("Invalid parsing language \"" + parsingLanguageName + "\". " + "Must be one of "
                    + StringUtils.join(ParserLanguage.values(), ", "));
            return;
        }
    }

    // Load parsing level
    ParserLevel parsingLevel = ParserLevel.TOKENIZATION;
    if (commandLine.hasOption("plvl")) {
        String parsingLevelName = commandLine.getOptionValue("plvl");
        try {
            parsingLevel = ParserLevel.valueOf(parsingLevelName);
        } catch (IllegalArgumentException ex) {
            logger.error("Invalid parsing level \"" + parsingLevelName + "\". " + "Must be one of "
                    + StringUtils.join(ParserLevel.values(), ", "));
            return;
        }
    } else {
        // Set model parsing level if ML will be used to annotate and no parsing level has been setted
        if (modelsFolder != null) {
            try {
                parsingLevel = getModelsParsingLevel(modelsFolder);
            } catch (NejiException ex) {
                logger.error("Could not load models parsing level.");
                return;
            }
        }
    }

    // Get if annotations without ids should be included
    boolean includeAnnotationsWithoutIDs = false;
    if (commandLine.hasOption("noids")) {
        includeAnnotationsWithoutIDs = true;
    }

    // Get false positives filter
    byte[] fpByteArray = null;
    if (commandLine.hasOption("fp")) {
        String fpPath = commandLine.getOptionValue("fp");

        File test = new File(fpPath);
        if (!test.isFile() || !test.canRead()) {
            logger.error("The specified false positives path is not a file or is not readable.");
            return;
        }

        fpPath = test.getAbsolutePath();
        fpPath += File.separator;
        try {
            fpByteArray = IOUtils.toByteArray(new FileInputStream(new File(fpPath)));
        } catch (IOException ex) {
            logger.error("There was a problem loading the false positives " + "file.", ex);
            return;
        }
    }

    // Get semantic groups normalization
    byte[] groupsNormByteArray = null;
    if (commandLine.hasOption("gn")) {
        String gnPath = commandLine.getOptionValue("gn");

        File test = new File(gnPath);
        if (!test.isFile() || !test.canRead()) {
            logger.error(
                    "The specified semantic groups normalization path " + "is not a file or is not readable.");
            return;
        }

        gnPath = test.getAbsolutePath();
        gnPath += File.separator;
        try {
            groupsNormByteArray = IOUtils.toByteArray(new FileInputStream(new File(gnPath)));
        } catch (IOException ex) {
            logger.error("There was a problem loading the semantic groups " + "normalization file.", ex);
            return;
        }
    }

    // Context is built through a descriptor first, so that the pipeline can be validated before any processing
    ContextConfiguration descriptor = null;
    try {
        descriptor = new ContextConfiguration.Builder().withInputFormat(inputFormat)
                .withOutputFormats(outputFormats).withParserTool(parsingTool)
                .withParserLanguage(parsingLanguage).withParserLevel(parsingLevel).parseCLI(modulesCommandLine)
                .build();

        descriptor.setFalsePositives(fpByteArray);
        descriptor.setSemanticGroupsNormalization(groupsNormByteArray);
    } catch (NejiException ex) {
        ex.printStackTrace();
        System.exit(1);
    }

    if (generateServer) {
        try {
            generateServer(descriptor, modelsFolder, dictionariesFolder, includeAnnotationsWithoutIDs);

        } catch (IOException ex) {
            ex.printStackTrace();
            System.exit(1);
        }
    } else {
        boolean storeDocuments = false;

        Context context = new Context(descriptor, modelsFolder, // Models
                dictionariesFolder, // Dictionaries folder
                parserFolder // Parser folder
        );

        try {
            BatchExecutor batchExecutor = new FileBatchExecutor(folderCorpusIn, folderCorpusOut, compressed,
                    NUM_THREADS, inputFolderWildcard, storeDocuments, includeAnnotationsWithoutIDs);

            if (xmlTags == null) {
                batchExecutor.run(processor, context);
            } else {
                batchExecutor.run(processor, context, new Object[] { xmlTags });
            }

        } catch (Exception ex) {
            logger.error("There was a problem running the batch.", ex);
        }
    }
}

From source file:de.uni_koblenz.jgralab.utilities.rsa2tg.Rsa2Tg.java

/**
 * Processes an XMI-file to a TG-file as schema or a schema in a grUML
 * graph. For all command line options see
 * {@link Rsa2Tg#processCommandLineOptions(String[])}.
 * /*  w  ww .  ja  v a 2 s.c  om*/
 * @param args
 *            {@link String} array of command line options.
 * @throws IOException
 */
public static void main(String[] args) throws IOException {

    System.out.println("RSA to TG");
    System.out.println("=========");
    JGraLab.setLogLevel(Level.OFF);

    // Retrieving all command line options
    CommandLine cli = processCommandLineOptions(args);

    assert cli != null : "No CommandLine object has been generated!";
    // All XMI input files
    File input = new File(cli.getOptionValue('i'));

    Rsa2Tg r = new Rsa2Tg();

    r.setUseFromRole(cli.hasOption(OPTION_USE_ROLE_NAME));
    r.setRemoveUnusedDomains(cli.hasOption(OPTION_REMOVE_UNUSED_DOMAINS));
    r.setKeepEmptyPackages(cli.hasOption(OPTION_KEEP_EMPTY_PACKAGES));
    r.setUseNavigability(cli.hasOption(OPTION_USE_NAVIGABILITY));
    r.setRemoveComments(cli.hasOption(OPTION_REMOVE_COMMENTS));
    r.setIgnoreUnknownStereotypes(cli.hasOption(OPTION_IGNORE_UNKNOWN_STEREOTYPES));

    // apply options
    r.setFilenameSchema(cli.getOptionValue(OPTION_FILENAME_SCHEMA));
    r.setFilenameSchemaGraph(cli.getOptionValue(OPTION_FILENAME_SCHEMA_GRAPH));
    r.setFilenameDot(cli.getOptionValue(OPTION_FILENAME_DOT));
    r.setFilenameValidation(cli.getOptionValue(OPTION_FILENAME_VALIDATION));

    // If no output option is selected, Rsa2Tg will write at least the
    // schema file.
    boolean noOutputOptionSelected = !cli.hasOption(OPTION_FILENAME_SCHEMA)
            && !cli.hasOption(OPTION_FILENAME_SCHEMA_GRAPH) && !cli.hasOption(OPTION_FILENAME_DOT)
            && !cli.hasOption(OPTION_FILENAME_VALIDATION);
    if (noOutputOptionSelected) {
        System.out
                .println("No output option has been selected. " + "A TG-file for the Schema will be written.");

        // filename have to be set
        r.setFilenameSchema(createFilename(input));
    }

    try {
        System.out.println("processing: " + input.getPath() + "\n");
        r.process(input.getPath());
    } catch (Exception e) {
        System.err.println("An Exception occured while processing " + input + ".");
        System.err.println(e.getMessage());
        e.printStackTrace();
    }

    System.out.println("Fini.");
}

From source file:io.hummer.util.ws.AbstractNode.java

@SuppressWarnings("all")
public static void deploy(final Object service, String url, Handler<?>... handler)
        throws AbstractNodeException {

    long t1 = System.currentTimeMillis();

    try {// www. j  a  va 2s . c om

        URL u = new URL(url);

        if (strUtil.isEmpty(System.getProperty(SYSPROP_HTTP_SERVER_PROVIDER_CLASS))) {
            System.setProperty(SYSPROP_HTTP_SERVER_PROVIDER_CLASS, JettyHttpServerProvider.class.getName());
        }

        ContextHandlerCollection chc = new ContextHandlerCollection();

        // disable log output from Metro and Jetty
        java.util.logging.Logger.getAnonymousLogger().getParent().setLevel(Level.WARNING);
        Class<?> cls3 = org.eclipse.jetty.server.Server.class;
        Class<?> cls4 = org.eclipse.jetty.server.AbstractConnector.class;
        org.apache.log4j.Level lev3 = Logger.getLogger(cls3).getLevel();
        org.apache.log4j.Level lev4 = Logger.getLogger(cls4).getLevel();
        Logger.getLogger(cls3).setLevel(org.apache.log4j.Level.WARN);
        Logger.getLogger(cls4).setLevel(org.apache.log4j.Level.WARN);

        JettyHttpServer httpServer = httpServers.get(u.getPort());
        Server server = servers.get(u.getPort());
        if (httpServer == null) {
            org.eclipse.jetty.util.log.Log.setLog(new Slf4jLog());
            server = new Server(u.getPort());

            SelectChannelConnector connector = new SelectChannelConnector();
            connector.setPort(u.getPort());
            connector.setAcceptQueueSize(1000);
            connector.setThreadPool(new ExecutorThreadPool(GlobalThreadPool.getExecutorService()));
            server.setConnectors(new Connector[] { connector });

            server.setHandler(chc);

            httpServer = new JettyHttpServer(server, true);

            httpServers.put(u.getPort(), httpServer);
            servers.put(u.getPort(), server);

            if (!server.isStarted())
                server.start();
        }

        JettyHttpContext wsContext1 = (JettyHttpContext) httpServer.createContext(u.getPath());
        Endpoint endpoint = Endpoint.create(service);
        if (service instanceof AbstractNode) {
            if (((AbstractNode) service).endpoint != null)
                logger.warn("AbstractNode " + service + " has apparently been double-deployed, "
                        + "because there already exists an endpoint for this instance.");
            ((AbstractNode) service).endpoint = endpoint;
        }

        // add JAX-WS handlers (e.g., needed for TeCoS invocation intercepting...)
        List<Handler> handlers = endpoint.getBinding().getHandlerChain();
        handlers.addAll(Arrays.asList(handler));
        endpoint.getBinding().setHandlerChain(handlers);
        if (service instanceof AbstractNode) {
            AbstractNode a = (AbstractNode) service;
            for (Handler h : handlers)
                if (!a.activeHandlers.contains(h))
                    a.activeHandlers.add(h);
        }

        Class<?> cls1 = org.eclipse.jetty.util.component.AbstractLifeCycle.class;
        Class<?> cls2 = org.eclipse.jetty.server.handler.ContextHandler.class;
        org.apache.log4j.Level lev1 = Logger.getLogger(cls1).getLevel();
        org.apache.log4j.Level lev2 = Logger.getLogger(cls2).getLevel();
        try {
            String bindUrl = u.getProtocol() + "://0.0.0.0:" + u.getPort() + u.getPath();
            if (u.getQuery() != null) {
                bindUrl += "?" + u.getQuery();
            }
            Logger.getLogger(cls1).setLevel(org.apache.log4j.Level.OFF);
            Logger.getLogger(cls2).setLevel(org.apache.log4j.Level.WARN);
            logger.info("Binding service to " + bindUrl);
            endpoint.publish(bindUrl);
        } catch (Exception e) {
            if (e instanceof BindException || (e.getCause() != null && e.getCause() instanceof BindException)
                    || (e.getCause() != null && e.getCause().getCause() != null
                            && e.getCause().getCause() instanceof BindException)) {
                /** we expect a BindException here, just swallow */
            } else {
                logger.warn("Unexpected error.", e);
            }
        } finally {
            Logger.getLogger(cls1).setLevel(lev1);
            Logger.getLogger(cls2).setLevel(lev2);
            Logger.getLogger(cls3).setLevel(lev3);
            Logger.getLogger(cls4).setLevel(lev4);
        }

        Field f = endpoint.getClass().getDeclaredField("actualEndpoint");
        f.setAccessible(true);

        // DO NOT do this (the two lines below), because HttpEndpoint creates some nasty 
        // compile-time dependencies with respect to JAXWS-RT. At runtime, we can (hopefully) 
        // assume that this class is present, in all newer Sun JVM implementations..
        //HttpEndpoint httpEndpoint = (HttpEndpoint)f.get(e1);
        //httpEndpoint.publish(wsContext1);
        Object httpEndpoint = f.get(endpoint);
        httpEndpoint.getClass().getMethod("publish", Object.class).invoke(httpEndpoint, wsContext1);

        Endpoint e2 = Endpoint.create(new CrossdomainXML());
        JettyHttpContext wsContext2 = (JettyHttpContext) httpServer.createContext("/crossdomain.xml");
        e2.publish(wsContext2);

        // Also deploy as RESTful service..
        if (service instanceof AbstractNode) {
            AbstractNode node = (AbstractNode) service;
            if (node.isRESTfulService()) {
                String path = u.getPath();
                if (!path.contains("/"))
                    path = "/";
                path = "/rest";
                String wadlURL = netUtil.getUrlBeforePath(u) + path + "/application.wadl";
                if (logger.isDebugEnabled())
                    logger.debug("Deploying node as RESTful service: " + wadlURL);
                JettyHttpContext wsContext3 = (JettyHttpContext) httpServer.createContext(path);

                ResourceConfig rc = new PackagesResourceConfig(service.getClass().getPackage().getName(),
                        AbstractNode.class.getPackage().getName());
                HttpHandler h = RuntimeDelegate.getInstance().createEndpoint(rc, HttpHandler.class);
                wsContext3.setHandler(h);
                node.setWadlURL(wadlURL);
            }
            deployedNodes.put(url, node);
        }

        final HttpHandler h = wsContext1.getHandler();
        wsContext1.setHandler(new HttpHandler() {
            public void handle(com.sun.net.httpserver.HttpExchange ex) throws IOException {

                if (!ex.getRequestMethod().equals("OPTIONS")) {
                    addCORSHeaders(ex);
                    h.handle(ex);
                    //System.out.println(ex.getRequestMethod() + ": " + ex.getResponseHeaders() + " - " + new HashMap<>(ex.getResponseHeaders()));
                    return;
                }

                if (ex.getRequestMethod().equals("OPTIONS")) {
                    addCORSHeaders(ex);
                    ex.sendResponseHeaders(200, -1);
                    ex.getResponseBody().close();
                    return;
                }
                //System.out.println(new HashMap<>(ex.getResponseHeaders()));
            }
        });

        // add shutdown task for this node
        if (service instanceof AbstractNode) {
            Runtime.getRuntime().addShutdownHook(new Thread() {
                public void run() {
                    try {
                        Runnable r = ((AbstractNode) service).getTerminateTask(null);
                        if (r != null)
                            r.run();
                    } catch (Exception e) {
                    }
                }
            });
        }

    } catch (Exception e) {
        throw new AbstractNodeException(e);
    }

    long diff = System.currentTimeMillis() - t1;
    logger.info("Deployment took " + diff + "ms");

}

From source file:org.exoplatform.wcm.connector.viewer.PDFViewerRESTService.java

private File buildFileImage(File input, String path, String pageNumber, String strRotation, String strScale) {
    Document document = buildDocumentImage(input, path);

    // Turn off Log of org.icepdf.core.pobjects.Stream to not print error stack trace in case
    // viewing a PDF file including CCITT (Fax format) images
    // TODO: Remove these statement and comments after IcePDF fix ECMS-3765
    Logger.getLogger(Stream.class.toString()).setLevel(Level.OFF);

    // save page capture to file.
    float scale = 1.0f;
    try {/*  w  ww . j a v  a  2 s.c  o  m*/
        scale = Float.parseFloat(strScale);
        // maximum scale support is 300%
        if (scale > 3.0f) {
            scale = 3.0f;
        }
    } catch (NumberFormatException e) {
        scale = 1.0f;
    }
    float rotation = 0.0f;
    try {
        rotation = Float.parseFloat(strRotation);
    } catch (NumberFormatException e) {
        rotation = 0.0f;
    }
    int maximumOfPage = document.getNumberOfPages();
    int pageNum = 1;
    try {
        pageNum = Integer.parseInt(pageNumber);
    } catch (NumberFormatException e) {
        pageNum = 1;
    }
    if (pageNum >= maximumOfPage)
        pageNum = maximumOfPage;
    else if (pageNum < 1)
        pageNum = 1;
    // Paint each pages content to an image and write the image to file
    BufferedImage image = (BufferedImage) document.getPageImage(pageNum - 1, GraphicsRenderingHints.SCREEN,
            Page.BOUNDARY_CROPBOX, rotation, scale);
    RenderedImage rendImage = image;
    File file = null;
    try {
        file = File.createTempFile("imageCapture1_" + pageNum, ".png");
        /*
        file.deleteOnExit();
          PM Comment : I removed this line because each deleteOnExit creates a reference in the JVM for future removal
          Each JVM reference takes 1KB of system memory and leads to a memleak
        */
        ImageIO.write(rendImage, "png", file);
    } catch (IOException e) {
        if (LOG.isErrorEnabled()) {
            LOG.error(e);
        }
    } finally {
        image.flush();
        // clean up resources
        document.dispose();
    }
    return file;
}

From source file:pt.ua.tm.neji.test.LexEBIReader.java

private Matcher getSpeciesDictionaryMatcher() {
    String linnaeusPath = "resources/lexicons/species/";

    logger.info("Loading LINNAEUS...");
    // Load species lexicon
    String variantMatcher = linnaeusPath + "dict-species-proxy.tsv";
    String ignoreCase = "true";
    String ppStopTerms = linnaeusPath + "stoplist.tsv";
    String ppAcrProbs = linnaeusPath + "synonyms-acronyms.tsv";
    String ppSpeciesFreqs = linnaeusPath + "species-frequency.tsv";

    ArgParser ap = new ArgParser(new String[] { "--variantMatcher", variantMatcher, "--ignoreCase", ignoreCase,
            "--ppStopTerms", ppStopTerms, "--ppAcrProbs", ppAcrProbs, "--ppSpeciesFreqs", ppSpeciesFreqs,
            "--postProcessing" });

    java.util.logging.Logger l = Loggers.getDefaultLogger(ap);
    if (Constants.verbose) {
        l.setLevel(Level.INFO);//from w  ww  .  ja  va2  s  .c  o m
    } else {
        l.setLevel(Level.OFF);
    }

    logger.info("Done!");
    return EntityTagger.getMatcher(ap, l);
}

From source file:io.github.agentsoz.abmjadex.super_central.ABMSimStarter.java

private static void parsingArguments(String[] args, Options options) {
    //flags//from  w  w w.j  ava  2  s  .  c  o m
    boolean isRunningCO = true;
    boolean isForced = false; //Overwrite any existing CO xml file
    boolean isRunningSC = true;
    boolean isLogToConsole = false;
    Level logLevel = Level.INFO;

    Properties prop = null;
    CommandLine line = null;
    BasicParser parser = new BasicParser();
    ArrayList<String> argsList = new ArrayList<String>();

    //Initialize argsList with args
    for (int i = 0; i < args.length; i++) {
        argsList.add(args[i]);
    }

    //Update 04/17/2013
    String[] specificArgs = packageOptionSpecific(args);

    try {
        // parse the command line arguments
        //line = parser.parse(options, args );
        //Update 04/17/2013
        line = parser.parse(options, specificArgs);

        //Commandline required -prop argument to be filled with valid properties file location
        if (line.hasOption(HELP)) {
            //Remove app specific arguments from total arguments
            int helpIndex = argsList.indexOf("-" + HELP);
            if (helpIndex == -1)
                helpIndex = argsList.indexOf("-" + HELP_LONG);
            argsList.remove(helpIndex);

            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("Jadex-ABMS", options);
        }

        if (line.hasOption(PROP)) {
            //Remove app specific arguments from total arguments
            int propIndex = argsList.indexOf("-" + PROP);
            if (propIndex == -1)
                propIndex = argsList.indexOf("-" + PROP_LONG);
            argsList.remove(propIndex + 1);
            argsList.remove(propIndex);

            String propertiesLoc = line.getOptionValue(PROP).replace("\\", "/").replace("\\\\", "/");
            prop = new Properties();

            try {
                prop.load(new FileInputStream(propertiesLoc));
                //Parsing options value into local flags------------------------
                if (line.hasOption(MODE)) {
                    String mode = line.getOptionValue(MODE);
                    if (mode.equalsIgnoreCase(CO_ONLY)) {
                        isRunningSC = false;
                    } else if (mode.equalsIgnoreCase(SC_CO)) {
                        //Default value is to run an SC and a CO
                    } else if (mode.equalsIgnoreCase(SC_ONLY)) {
                        isRunningCO = false;
                    } else {
                        throw new ParseException("Wrong argument for -mode.");
                    }

                    //Remove app specific arguments from total arguments
                    int modeIndex = argsList.indexOf("-" + MODE);
                    argsList.remove(modeIndex + 1);
                    argsList.remove(modeIndex);
                }

                if (line.hasOption(FORCED)) {
                    isForced = true;
                    //Remove app specific arguments from total arguments
                    int modeIndex = argsList.indexOf("-" + FORCED);
                    if (modeIndex == -1)
                        modeIndex = argsList.indexOf("-" + FORCED_LONG);
                    argsList.remove(modeIndex);
                }

                if (line.hasOption(GUI)) {
                    String guiMode = line.getOptionValue(GUI);
                    if (!guiMode.equalsIgnoreCase("true") && !guiMode.equalsIgnoreCase("false"))
                        throw new ParseException("Wrong argument for -gui.");
                } else {
                    argsList.add("-" + GUI);
                    int guiIndex = argsList.indexOf("-" + GUI);
                    argsList.add(guiIndex + 1, "false");
                }

                if (line.hasOption(LOG_CONSOLE)) {
                    isLogToConsole = true;
                    //Remove app specific arguments from total arguments
                    int logCIndex = argsList.indexOf("-" + LOG_CONSOLE);
                    argsList.remove(logCIndex);
                }

                if (line.hasOption(LOG_LVL)) {
                    String level = line.getOptionValue(LOG_LVL);
                    if (level.equalsIgnoreCase("INFO")) {
                        logLevel = Level.INFO;
                    } else if (level.equalsIgnoreCase("ALL")) {
                        logLevel = Level.ALL;
                    } else if (level.equalsIgnoreCase("CONFIG")) {
                        logLevel = Level.CONFIG;
                    } else if (level.equalsIgnoreCase("FINE")) {
                        logLevel = Level.FINE;
                    } else if (level.equalsIgnoreCase("FINER")) {
                        logLevel = Level.FINER;
                    } else if (level.equalsIgnoreCase("FINEST")) {
                        logLevel = Level.FINEST;
                    } else if (level.equalsIgnoreCase("OFF")) {
                        logLevel = Level.OFF;
                    } else if (level.equalsIgnoreCase("SEVERE")) {
                        logLevel = Level.SEVERE;
                    } else if (level.equalsIgnoreCase("WARNING")) {
                        logLevel = Level.WARNING;
                    } else {
                        throw new ParseException("argument for loglvl unknown");
                    }
                    //Remove app specific arguments from total arguments
                    int logLvlIndex = argsList.indexOf("-" + LOG_LVL);
                    argsList.remove(logLvlIndex + 1);
                    argsList.remove(logLvlIndex);
                }

                //Setup logger
                try {
                    ABMBDILoggerSetter.initialized(prop, isLogToConsole, logLevel);
                    ABMBDILoggerSetter.setup(LOGGER);
                } catch (IOException e) {
                    e.printStackTrace();
                    LOGGER.severe(e.getMessage());
                    throw new RuntimeException("Problems with creating logfile");
                }

                //Translate argsList into array------------------------------
                String[] newargs = new String[argsList.size()];
                for (int i = 0; i < argsList.size(); i++) {
                    newargs[i] = argsList.get(i);
                }

                //Running the system----------------------------------------
                if (isRunningSC == true) {
                    runSC(prop);
                }

                if (isRunningCO == true) {
                    runCO(prop, newargs, isForced);
                }

            } catch (IOException e) {
                e.printStackTrace();
                LOGGER.severe(e.getMessage());
            }
        } else {
            throw new ParseException("-prop <properties_location> is a required option");
        }

    } catch (ParseException exp) {
        LOGGER.severe("Unexpected exception:" + exp.getMessage());

        //If its not working print out help info
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("Jadex-ABMS", options);
    }
}

From source file:yt_server_side.YT_Server_Side.java

public ArrayList<Tile> getRecommendedPlaylistTiles(String url) {
    System.out.println("Attempting to generate recomended tiles...");
    ArrayList<Tile> tiles = new ArrayList();

    try {// ww w  .  j av  a2s  .  c o m
        WebClient wc = new WebClient();

        //<editor-fold defaultstate="collapsed" desc="Turn off HtmlUnit logging">
        LogFactory.getFactory().setAttribute("org.apache.commons.logging.Log",
                "org.apache.commons.logging.impl.NoOpLog");

        java.util.logging.Logger.getLogger("com.gargoylesoftware.htmlunit").setLevel(Level.OFF);
        java.util.logging.Logger.getLogger("org.apache.commons.httpclient").setLevel(Level.OFF);

        wc.getOptions().setCssEnabled(false);

        wc.setIncorrectnessListener(new IncorrectnessListener() {
            @Override
            public void notify(String string, Object o) {
            }
        });
        wc.setCssErrorHandler(new ErrorHandler() {
            @Override
            public void warning(CSSParseException csspe) throws CSSException {
            }

            @Override
            public void error(CSSParseException csspe) throws CSSException {
            }

            @Override
            public void fatalError(CSSParseException csspe) throws CSSException {
            }
        });
        wc.setJavaScriptErrorListener(new JavaScriptErrorListener() {

            @Override
            public void scriptException(InteractivePage ip, ScriptException se) {
            }

            @Override
            public void timeoutError(InteractivePage ip, long l, long l1) {
            }

            @Override
            public void malformedScriptURL(InteractivePage ip, String string, MalformedURLException murle) {
            }

            @Override
            public void loadScriptError(InteractivePage ip, URL url, Exception excptn) {
            }
        });
        wc.setHTMLParserListener(new HTMLParserListener() {
            @Override
            public void error(String string, URL url, String string1, int i, int i1, String string2) {
            }

            @Override
            public void warning(String string, URL url, String string1, int i, int i1, String string2) {
            }
        });

        wc.getOptions().setThrowExceptionOnFailingStatusCode(false);
        wc.getOptions().setThrowExceptionOnScriptError(false);
        //</editor-fold>

        HtmlPage yt = wc.getPage(url);

        //span[@class='yt-thumb-clip']//img
        yt.getByXPath("//tr[@class='pl-video yt-uix-tile ']").forEach(tr -> {

            System.out.println("TR");

            String songName = ((HtmlElement) tr).getAttribute("data-title");
            String songUrl = "https://www.youtube.com/watch?v="
                    + ((HtmlElement) tr).getAttribute("data-video-id");
            HtmlImage hi = ((HtmlElement) tr).getFirstByXPath(".//td[3]//img");
            String imgUrl = hi.getAttribute("data-thumb");

            tiles.add(new Tile(urlToJpg(imgUrl), songName, songUrl));

        });

    } catch (IOException io) {
        io.printStackTrace(System.out);
    }

    System.out.println("Finished getting recomeded playlists.");
    return tiles;
}