Example usage for java.util List size

List of usage examples for java.util List size

Introduction

In this page you can find the example usage for java.util List size.

Prototype

int size();

Source Link

Document

Returns the number of elements in this list.

Usage

From source file:hk.hku.cecid.corvus.http.AS2EnvelopQuerySender.java

/**
 * The main method is for CLI mode./*from   w  w  w. j a  va 2 s .com*/
 */
public static void main(String[] args) {
    try {
        java.io.PrintStream out = System.out;

        if (args.length < 2) {
            out.println("Usage: as2-envelop [config-xml] [log-path]");
            out.println();
            out.println("Example: as2-envelop ./config/as2-envelop/as2-request.xml ./logs/as2-envelop.log");
            System.exit(1);
        }

        out.println("------------------------------------------------------");
        out.println("       AS2 Envelop Queryer       ");
        out.println("------------------------------------------------------");

        // Initialize the logger.
        out.println("Initialize logger .. ");
        // The logger path is specified at the last argument.
        FileLogger logger = new FileLogger(new File(args[args.length - 1]));

        // Initialize the query parameter.
        out.println("Importing AS2 administrative sending parameters ... ");
        AS2AdminData acd = DataFactory.getInstance()
                .createAS2AdminDataFromXML(new PropertyTree(new File(args[0]).toURI().toURL()));

        boolean historyQueryNeeded = false;
        AS2MessageHistoryRequestData queryData = new AS2MessageHistoryRequestData();
        if (acd.getMessageIdCriteria() == null || acd.getMessageIdCriteria().trim().equals("")) {

            historyQueryNeeded = true;

            // print command prompt
            out.println("No messageID was specified!");
            out.println("Start querying message repositry ...");

            String endpoint = acd.getEnvelopQueryEndpoint();
            String host = endpoint.substring(0, endpoint.indexOf("/corvus"));
            host += "/corvus/httpd/as2/msg_history";
            queryData.setEndPoint(host);
        } /*
            If the user has entered message id but no messagebox, 
            using the messageid as serach criteria and as 
            user to chose his target message
          */
        else if (acd.getMessageBoxCriteria() == null || acd.getMessageBoxCriteria().trim().equals("")) {

            historyQueryNeeded = true;

            // print command prompt
            out.println("Message Box value haven't specified.");
            out.println("Start query message whcih matched with messageID: " + acd.getMessageIdCriteria());

            String endpoint = acd.getEnvelopQueryEndpoint();
            String host = endpoint.substring(0, endpoint.indexOf("/corvus"));
            host += "/corvus/httpd/as2/msg_history";

            queryData.setEndPoint(host);
            queryData.setMessageId(acd.getMessageIdCriteria());
        }
        //Debug Message
        System.out.println("history Endpoint: " + queryData.getEndPoint());
        System.out.println("Repositry Endpoint: " + acd.getEnvelopQueryEndpoint());

        if (historyQueryNeeded) {
            List msgList = listAvailableMessage(queryData, logger);

            if (msgList == null || msgList.size() == 0) {
                out.println();
                out.println();
                out.println("No stream data found in repositry...");
                out.println("Please view log for details .. ");
                return;
            }

            int selection = promptForSelection(msgList);

            if (selection == -1) {
                return;
            }

            String messageID = (String) ((List) msgList.get(selection)).get(0);
            String messageBox = (String) ((List) msgList.get(selection)).get(1);
            acd.setMessageIdCriteria(messageID);
            acd.setMessageBoxCriteria(messageBox.toUpperCase());
            out.println();
            out.println();
            out.println("Start download targeted message envelop ...");
        }

        // Initialize the sender.
        out.println("Initialize AS2 HTTP data service client... ");
        AS2EnvelopQuerySender sender = new AS2EnvelopQuerySender(logger, acd);

        out.println("Sending    AS2 HTTP Envelop Query request ... ");
        sender.run();

        out.println();
        out.println("                    Sending Done:                   ");
        out.println("----------------------------------------------------");
        out.println("The Message Envelope : ");
        InputStream eins = sender.getEnvelopStream();
        if (eins.available() == 0) {
            out.println("No stream data found.");
            out.println("The message envelop does not exist for message id " + sender.getMessageIdToDownload()
                    + " and message box " + sender.getMessageBoxToDownload());
        } else
            IOHandler.pipe(sender.getEnvelopStream(), out);

        out.println("Please view log for details .. ");
    } catch (Exception e) {
        e.printStackTrace(System.err);
    }
}

From source file:net.itransformers.postDiscoverer.core.ReportManager.java

public static void main(String[] args) throws IOException {

    File projectDir = new File(".");
    File scriptPath = new File("postDiscoverer/src/main/resources/postDiscoverer/conf/groovy/");

    ResourceManagerFactory resourceManagerFactory = new XmlResourceManagerFactory(
            "iDiscover/resourceManager/xmlResourceManager/src/main/resources/xmlResourceManager/conf/xml/resource.xml");
    Map<String, String> resourceManagerParams = new HashMap<>();
    resourceManagerParams.put("projectPath", projectDir.getAbsolutePath());
    ResourceManager resourceManager = resourceManagerFactory.createResourceManager("xml",
            resourceManagerParams);/* w ww .  ja va 2s.  c  om*/

    Map<String, String> params = new HashMap<String, String>();
    params.put("protocol", "telnet");
    params.put("deviceName", "R1");
    params.put("deviceType", "CISCO");
    params.put("address", "10.17.1.5");
    params.put("port", "23");

    ResourceType resource = resourceManager.findFirstResourceBy(params);
    List connectParameters = resource.getConnectionParams();

    for (int i = 0; i < connectParameters.size(); i++) {
        ConnectionParamsType connParamsType = (ConnectionParamsType) connectParameters.get(i);

        String connectionType = connParamsType.getConnectionType();
        if (connectionType.equalsIgnoreCase(params.get("protocol"))) {

            for (ParamType param : connParamsType.getParam()) {
                params.put(param.getName(), param.getValue());
            }

        }
    }

    File postDiscoveryConfing = new File(
            projectDir + "/postDiscoverer/src/main/resources/postDiscoverer/conf/xml/reportGenerator.xml");
    if (!postDiscoveryConfing.exists()) {
        System.out.println("File missing: " + postDiscoveryConfing.getAbsolutePath());
        return;
    }

    ReportGeneratorType reportGenerator = null;

    FileInputStream is = new FileInputStream(postDiscoveryConfing);
    try {
        reportGenerator = JaxbMarshalar.unmarshal(ReportGeneratorType.class, is);
    } catch (JAXBException e) {
        logger.info(e); //To change body of catch statement use File | Settings | File Templates.
    } finally {
        is.close();
    }

    ReportManager reportManager = new ReportManager(reportGenerator, scriptPath.getPath(), projectDir,
            "postDiscoverer/conf/xslt/table_creator.xslt");
    StringBuffer report = null;

    HashMap<String, Object> groovyExecutorParams = new HashMap<String, Object>();

    for (String s : params.keySet()) {
        groovyExecutorParams.put(s, params.get(s));
    }

    try {
        report = reportManager.reportExecutor(
                new File("/Users/niau/Projects/Projects/netTransformer10/version1/post-discovery"),
                groovyExecutorParams);
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
    } catch (SAXException e) {
        e.printStackTrace();
    }
    if (report != null) {
        System.out.println(report.toString());

    } else {
        System.out.println("Report generation failed!");

    }
}

From source file:cn.jumper.study.http.ClientFormLogin.java

public static void main(String[] args) throws Exception {
    BasicCookieStore cookieStore = new BasicCookieStore();
    CloseableHttpClient httpclient = HttpClients.custom().setDefaultCookieStore(cookieStore).build();

    HttpHost proxy = new HttpHost("192.168.10.3", 8080, "http");

    RequestConfig config = RequestConfig.custom().setProxy(proxy).build();

    try {//from  w ww  .j  a  v a  2  s  .c  o  m
        HttpGet httpget = new HttpGet("http://www.ksf-food.com/admin/Login.asp");
        httpget.setConfig(config);
        CloseableHttpResponse response1 = httpclient.execute(httpget);
        try {
            HttpEntity entity = response1.getEntity();

            System.out.println("Login form get: " + response1.getStatusLine());
            EntityUtils.consume(entity);

            System.out.println("Initial set of cookies:");
            List<Cookie> cookies = cookieStore.getCookies();
            if (cookies.isEmpty()) {
                System.out.println("None");
            } else {
                for (int i = 0; i < cookies.size(); i++) {
                    System.out.println("- " + cookies.get(i).toString());
                }
            }
        } finally {
            response1.close();
        }

        String code = "";
        try {
            HttpUriRequest httpgetCode = RequestBuilder.get()
                    .setUri("http://www.ksf-food.com/admin/inc/checkcode.asp").setConfig(config).build();

            /*
             * HttpGet httpgetCode = new HttpGet(
             * "http://www.qufuev.com/admin/inc/checkcode.asp");
             * httpgetCode.setConfig(config);
             */

            System.out.println("Executing request " + httpgetCode.getRequestLine());
            System.out.println("========================================================");
            System.out.println("==httpget header ==");
            for (Header header : httpgetCode.getAllHeaders()) {
                System.out.println(header.getName() + ":" + header.getValue());
            }
            System.out.println("==httpget header ==");

            ResponseHandler<String> responseHandler = new ResponseHandler<String>() {
                public String handleResponse(final HttpResponse response)
                        throws ClientProtocolException, IOException {
                    int status = response.getStatusLine().getStatusCode();
                    if (status >= 200 && status < 300) {
                        HttpEntity entity = response.getEntity();
                        System.out.println("==respons header ==");
                        for (Header header : response.getAllHeaders()) {
                            System.out.println(header.getName() + ":" + header.getValue());
                        }
                        System.out.println("==respons header ==");
                        String fileName = System.currentTimeMillis() + "";
                        DataOutputStream dataOutputStream = new DataOutputStream(
                                new FileOutputStream("d://test//e3//" + fileName + ".jpg"));
                        dataOutputStream.write(EntityUtils.toByteArray(entity));
                        dataOutputStream.close();
                        return ImageTest.getAllOcr("d://test//e3//" + fileName + ".jpg");
                    } else {
                        throw new ClientProtocolException("Unexpected response status: " + status);
                    }
                }

            };
            code = httpclient.execute(httpgetCode, responseHandler);
            System.out.println("ClientFormLogin.main()-CheckCode:" + code);
            System.out.println("----------------------------------------");
        } catch (IOException e) {
            e.printStackTrace();
        }

        HttpUriRequest login = RequestBuilder.post()
                .setUri(new URI("http://www.ksf-food.com/admin/Admin_ChkLogin.asp"))
                .addParameter("UserName", "username").addParameter("Password", "password")
                .addParameter("CheckCode", code).setConfig(config).build();

        System.out.println("========================================================");
        System.out.println("==httpget header ==");
        for (Header header : login.getAllHeaders()) {
            System.out.println(header.getName() + ":" + header.getValue());
        }

        CloseableHttpResponse response2 = httpclient.execute(login);
        try {
            HttpEntity entity = response2.getEntity();

            System.out.println("Login form post: " + response2.getStatusLine());
            // EntityUtils.consume(entity);
            System.out.println("ClientFormLogin.main():\\n" + EntityUtils.toString(entity, "GBK"));

            System.out.println("Post logon cookies:");
            List<Cookie> cookies = cookieStore.getCookies();
            if (cookies.isEmpty()) {
                System.out.println("None");
            } else {
                for (int i = 0; i < cookies.size(); i++) {
                    System.out.println("- " + cookies.get(i).toString());
                }
            }
        } finally {
            response2.close();
        }
    } finally {
        httpclient.close();
    }
}

From source file:io.s4.tools.loadgenerator.LoadGenerator.java

public static void main(String args[]) {
    Options options = new Options();
    boolean warmUp = false;

    options.addOption(/*from  ww  w  . j av  a  2 s  .c  o  m*/
            OptionBuilder.withArgName("rate").hasArg().withDescription("Rate (events per second)").create("r"));

    options.addOption(OptionBuilder.withArgName("display_rate").hasArg()
            .withDescription("Display Rate at specified second boundary").create("d"));

    options.addOption(OptionBuilder.withArgName("adapter_address").hasArg()
            .withDescription("Address of client adapter").create("a"));

    options.addOption(OptionBuilder.withArgName("listener_application_name").hasArg()
            .withDescription("Listener application name").create("g"));

    options.addOption(
            OptionBuilder.withArgName("sleep_overhead").hasArg().withDescription("Sleep overhead").create("o"));

    options.addOption(new Option("w", "Warm-up"));

    CommandLineParser parser = new GnuParser();

    CommandLine line = null;
    try {
        // parse the command line arguments
        line = parser.parse(options, args);
    } catch (ParseException exp) {
        // oops, something went wrong
        System.err.println("Parsing failed.  Reason: " + exp.getMessage());
        System.exit(1);
    }

    int expectedRate = 250;
    if (line.hasOption("r")) {
        try {
            expectedRate = Integer.parseInt(line.getOptionValue("r"));
        } catch (Exception e) {
            System.err.println("Bad expected rate specified " + line.getOptionValue("r"));
            System.exit(1);
        }
    }

    int displayRateIntervalSeconds = 20;
    if (line.hasOption("d")) {
        try {
            displayRateIntervalSeconds = Integer.parseInt(line.getOptionValue("d"));
        } catch (Exception e) {
            System.err.println("Bad display rate value specified " + line.getOptionValue("d"));
            System.exit(1);
        }
    }

    int updateFrequency = 0;
    if (line.hasOption("f")) {
        try {
            updateFrequency = Integer.parseInt(line.getOptionValue("f"));
        } catch (Exception e) {
            System.err.println("Bad query udpdate frequency specified " + line.getOptionValue("f"));
            System.exit(1);
        }
        System.out.printf("Update frequency is %d\n", updateFrequency);
    }

    String clientAdapterAddress = null;
    String clientAdapterHost = null;
    int clientAdapterPort = -1;
    if (line.hasOption("a")) {
        clientAdapterAddress = line.getOptionValue("a");
        String[] parts = clientAdapterAddress.split(":");
        if (parts.length != 2) {
            System.err.println("Bad adapter address specified " + clientAdapterAddress);
            System.exit(1);
        }
        clientAdapterHost = parts[0];

        try {
            clientAdapterPort = Integer.parseInt(parts[1]);
        } catch (NumberFormatException nfe) {
            System.err.println("Bad adapter address specified " + clientAdapterAddress);
            System.exit(1);
        }
    }

    long sleepOverheadMicros = -1;
    if (line.hasOption("o")) {
        try {
            sleepOverheadMicros = Long.parseLong(line.getOptionValue("o"));
        } catch (NumberFormatException e) {
            System.err.println("Bad sleep overhead specified " + line.getOptionValue("o"));
            System.exit(1);
        }
        System.out.printf("Specified sleep overhead is %d\n", sleepOverheadMicros);
    }

    if (line.hasOption("w")) {
        warmUp = true;
    }

    List loArgs = line.getArgList();
    if (loArgs.size() < 1) {
        System.err.println("No input file specified");
        System.exit(1);
    }

    String inputFilename = (String) loArgs.get(0);

    LoadGenerator loadGenerator = new LoadGenerator();
    loadGenerator.setInputFilename(inputFilename);
    loadGenerator.setDisplayRateInterval(displayRateIntervalSeconds);
    loadGenerator.setExpectedRate(expectedRate);
    loadGenerator.setClientAdapterHost(clientAdapterHost);
    loadGenerator.setClientAdapterPort(clientAdapterPort);
    loadGenerator.run();

    System.exit(0);
}

From source file:frankhassanabad.com.github.Jasperize.java

/**
 * Main method to call through Java in order to take a LinkedInProfile on disk and load it.
 *
 * @param args command line arguments where the options are stored
 * @throws FileNotFoundException Thrown if any file its expecting cannot be found.
 * @throws JRException  If there's generic overall Jasper issues.
 * @throws ParseException If there's command line parsing issues.
 *///  ww  w.j  a v a2s . c  o  m
public static void main(String[] args) throws IOException, JRException, ParseException {

    Options options = new Options();
    options.addOption("h", "help", false, "Shows the help documentation");
    options.addOption("v", "version", false, "Shows the help documentation");
    options.addOption("cl", "coverLetter", false, "Utilizes a cover letter defined in coverletter.xml");
    options.addOption("sig", true, "Picture of your signature to add to the cover letter.");
    CommandLineParser parser = new GnuParser();
    CommandLine cmd = parser.parse(options, args);
    if (cmd.hasOption("h")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("Jasperize [OPTIONS] [InputJrxmlFile] [OutputExportFile]", options);
        System.exit(0);
    }
    if (cmd.hasOption("v")) {
        System.out.println("Version:" + version);
        System.exit(0);
    }
    boolean useCoverLetter = cmd.hasOption("cl");
    String signatureLocation = cmd.getOptionValue("sig");
    BufferedImage signatureImage = null;
    if (signatureLocation != null) {
        signatureImage = ImageIO.read(new File(signatureLocation));
        ;
    }

    @SuppressWarnings("unchecked")
    List<String> arguments = cmd.getArgList();

    final String jrxmlFile;
    final String jasperOutput;
    if (arguments.size() == 2) {
        jrxmlFile = arguments.get(0);
        jasperOutput = arguments.get(1);
        System.out.println("*Detected* the command line arguments of:");
        System.out.println("    [InputjrxmlFile] " + jrxmlFile);
        System.out.println("    [OutputExportFile] " + jasperOutput);
    } else if (arguments.size() == 3) {
        jrxmlFile = arguments.get(1);
        jasperOutput = arguments.get(2);
        System.out.println("*Detected* the command line arguments of:");
        System.out.println("    [InputjrxmlFile] " + jrxmlFile);
        System.out.println("    [OutputExportFile] " + jasperOutput);
    } else {
        System.out.println("Using the default arguments of:");
        jrxmlFile = "data/jasperTemplates/resume1.jrxml";
        jasperOutput = "data/jasperOutput/linkedInResume.pdf";
        System.out.println("    [InputjrxmlFile] " + jrxmlFile);
        System.out.println("    [OutputExportFile] " + jasperOutput);
    }

    final String compiledMasterFile;
    final String outputType;
    final String jrPrintFile;
    //Split the inputFile
    final String[] inputSplit = jrxmlFile.split("\\.");
    if (inputSplit.length != 2 || !(inputSplit[1].equalsIgnoreCase("jrxml"))) {
        //Error
        System.out.println("Your [InputjrxmlFile] (1st argument) should have a jrxml extension like such:");
        System.out.println("    data/jasperTemplates/resume1.jrxml");
        System.exit(1);
    }
    //Split the outputFile
    final String[] outputSplit = jasperOutput.split("\\.");
    if (outputSplit.length != 2) {
        //Error
        System.out.println("Your [OutputExportFile] (2nd argument) should have a file extension like such:");
        System.out.println("    data/jasperOutput/linkedInResume.pdf");
        System.exit(1);
    }

    File inputFile = new File(inputSplit[0]);
    String inputFileName = inputFile.getName();
    String inputFileParentPath = inputFile.getParent();

    File outputFile = new File(outputSplit[0]);
    String outputFileParentPath = outputFile.getParent();

    System.out.println("Compiling report(s)");
    compileAllJrxmlTemplateFiles(inputFileParentPath, outputFileParentPath);
    System.out.println("Done compiling report(s)");

    compiledMasterFile = outputFileParentPath + File.separator + inputFileName + ".jasper";
    jrPrintFile = outputFileParentPath + File.separator + inputFileName + ".jrprint";

    System.out.println("Filling report: " + compiledMasterFile);
    Reporting.fill(compiledMasterFile, useCoverLetter, signatureImage);
    System.out.println("Done filling reports");
    outputType = outputSplit[1];
    System.out.println("Creating output export file of: " + jasperOutput);
    if (outputType.equalsIgnoreCase("pdf")) {
        Reporting.pdf(jrPrintFile, jasperOutput);
    }
    if (outputType.equalsIgnoreCase("pptx")) {
        Reporting.pptx(jrPrintFile, jasperOutput);
    }
    if (outputType.equalsIgnoreCase("docx")) {
        Reporting.docx(jrPrintFile, jasperOutput);
    }
    if (outputType.equalsIgnoreCase("odt")) {
        Reporting.odt(jrPrintFile, jasperOutput);
    }
    if (outputType.equalsIgnoreCase("xhtml")) {
        Reporting.xhtml(jrPrintFile, jasperOutput);
    }
    System.out.println("Done creating output export file of: " + jasperOutput);
}

From source file:com.cyberway.issue.crawler.extractor.ExtractorTool.java

public static void main(String[] args) throws Exception {
    Options options = new Options();
    options.addOption(new Option("h", "help", false, "Prints this message and exits."));
    StringBuffer defaultExtractors = new StringBuffer();
    for (int i = 0; i < DEFAULT_EXTRACTORS.length; i++) {
        if (i > 0) {
            defaultExtractors.append(", ");
        }/*from   w  ww. j  a  v a 2  s.c  o m*/
        defaultExtractors.append(DEFAULT_EXTRACTORS[i]);
    }
    options.addOption(new Option("e", "extractor", true,
            "List of comma-separated extractor class names. " + "Run in order listed. "
                    + "If no extractors listed, runs following: " + defaultExtractors.toString() + "."));
    options.addOption(
            new Option("s", "scratch", true, "Directory to write scratch files to. Default: '/tmp'."));
    PosixParser parser = new PosixParser();
    CommandLine cmdline = parser.parse(options, args, false);
    List cmdlineArgs = cmdline.getArgList();
    Option[] cmdlineOptions = cmdline.getOptions();
    HelpFormatter formatter = new HelpFormatter();
    // If no args, print help.
    if (cmdlineArgs.size() <= 0) {
        usage(formatter, options, 0);
    }

    // Now look at options passed.
    String[] extractors = DEFAULT_EXTRACTORS;
    String scratch = null;
    for (int i = 0; i < cmdlineOptions.length; i++) {
        switch (cmdlineOptions[i].getId()) {
        case 'h':
            usage(formatter, options, 0);
            break;

        case 'e':
            String value = cmdlineOptions[i].getValue();
            if (value == null || value.length() <= 0) {
                // Allow saying NO extractors so we can see
                // how much it costs just reading through
                // ARCs.
                extractors = new String[0];
            } else {
                extractors = value.split(",");
            }
            break;

        case 's':
            scratch = cmdlineOptions[i].getValue();
            break;

        default:
            throw new RuntimeException("Unexpected option: " + +cmdlineOptions[i].getId());
        }
    }

    ExtractorTool tool = new ExtractorTool(extractors, scratch);
    for (Iterator i = cmdlineArgs.iterator(); i.hasNext();) {
        tool.extract((String) i.next());
    }
}

From source file:edu.mit.lib.mama.Mama.java

public static void main(String[] args) {

    Properties props = findConfig(args);
    DBI dbi = new DBI(props.getProperty("dburl"), props);
    // Advanced instrumentation/metrics if requested
    if (System.getenv("MAMA_DB_METRICS") != null) {
        dbi.setTimingCollector(new InstrumentedTimingCollector(metrics));
    }/*w ww  .  ja  va  2s.  c om*/
    // reassign default port 4567
    if (System.getenv("MAMA_SVC_PORT") != null) {
        port(Integer.valueOf(System.getenv("MAMA_SVC_PORT")));
    }
    // if API key given, use exception monitoring service
    if (System.getenv("HONEYBADGER_API_KEY") != null) {
        reporter = new HoneybadgerReporter();
    }

    get("/ping", (req, res) -> {
        res.type("text/plain");
        res.header("Cache-Control", "must-revalidate,no-cache,no-store");
        return "pong";
    });

    get("/metrics", (req, res) -> {
        res.type("application/json");
        res.header("Cache-Control", "must-revalidate,no-cache,no-store");
        ObjectMapper objectMapper = new ObjectMapper()
                .registerModule(new MetricsModule(TimeUnit.SECONDS, TimeUnit.MILLISECONDS, true));
        try (ServletOutputStream outputStream = res.raw().getOutputStream()) {
            objectMapper.writer().withDefaultPrettyPrinter().writeValue(outputStream, metrics);
        }
        return "";
    });

    get("/shutdown", (req, res) -> {
        boolean auth = false;
        try {
            if (!isNullOrEmpty(System.getenv("MAMA_SHUTDOWN_KEY")) && !isNullOrEmpty(req.queryParams("key"))
                    && System.getenv("MAMA_SHUTDOWN_KEY").equals(req.queryParams("key"))) {
                auth = true;
                return "Shutting down";
            } else {
                res.status(401);
                return "Not authorized";
            }
        } finally {
            if (auth) {
                stop();
            }
        }
    });

    get("/item", (req, res) -> {
        if (isNullOrEmpty(req.queryParams("qf")) || isNullOrEmpty(req.queryParams("qv"))) {
            halt(400, "Must supply field and value query parameters 'qf' and 'qv'");
        }
        itemReqs.mark();
        Timer.Context context = respTime.time();
        try (Handle hdl = dbi.open()) {
            if (findFieldId(hdl, req.queryParams("qf")) != -1) {
                List<String> results = findItems(hdl, req.queryParams("qf"), req.queryParams("qv"),
                        req.queryParamsValues("rf"));
                if (results.size() > 0) {
                    res.type("application/json");
                    return "{ " + jsonValue("field", req.queryParams("qf"), true) + ",\n"
                            + jsonValue("value", req.queryParams("qv"), true) + ",\n" + jsonValue("items",
                                    results.stream().collect(Collectors.joining(",", "[", "]")), false)
                            + "\n" + " }";
                } else {
                    res.status(404);
                    return "No items found for: " + req.queryParams("qf") + "::" + req.queryParams("qv");
                }
            } else {
                res.status(404);
                return "No such field: " + req.queryParams("qf");
            }
        } catch (Exception e) {
            if (null != reporter)
                reporter.reportError(e);
            res.status(500);
            return "Internal system error: " + e.getMessage();
        } finally {
            context.stop();
        }
    });

    awaitInitialization();
}

From source file:cc.osint.graphd.client.ProtographClient.java

public static void main(String[] args) throws Exception {
    if (args.length != 2) {
        System.err.println("Usage: " + ProtographClient.class.getSimpleName() + " <host> <port>");
        return;//ww w  .  ja  v  a 2  s  .  com
    }
    String host = args[0];
    int port = Integer.parseInt(args[1]);
    ProtographClient client = new ProtographClient(host, port);

    // Read commands from the stdin.
    ConsoleReader reader = new ConsoleReader();
    for (;;) {
        String line = reader.readLine();
        if (line == null) {
            break;
        }

        // Sends the received line to the server.
        //client.send(line + "\r\n");
        List<JSONObject> results = client.exec(line.trim() + "\n");
        if (null == results) {
            log.info("no result!");
        } else {
            if (results.size() == 0) {
                log.info("OK");
            } else {
                int c = 0;
                for (JSONObject result : results) {
                    c++;
                    log.info(c + ": " + result.toString(4));
                }
            }
        }

        // If user typed the 'bye' command, wait until the server closes
        // the connection.
        if (line.toLowerCase().equals("bye")) {
            client.disconnect();
            break;
        }
    }
    client.disconnect();
}

From source file:de.tudarmstadt.ukp.experiments.dip.wp1.documents.Step5LinguisticPreprocessing.java

public static void main(String[] args) throws Exception {
    // input dir - list of xml query containers
    // step4-boiler-plate/
    File inputDir = new File(args[0]);

    // output dir
    File outputDir = new File(args[1]);
    if (!outputDir.exists()) {
        outputDir.mkdirs();/*from  w  ww.j a  va 2s  . c om*/
    }

    // iterate over query containers
    for (File f : FileUtils.listFiles(inputDir, new String[] { "xml" }, false)) {
        QueryResultContainer queryResultContainer = QueryResultContainer
                .fromXML(FileUtils.readFileToString(f, "utf-8"));

        for (QueryResultContainer.SingleRankedResult rankedResults : queryResultContainer.rankedResults) {
            //                System.out.println(rankedResults.plainText);

            if (rankedResults.plainText != null) {
                String[] lines = StringUtils.split(rankedResults.plainText, "\n");

                // collecting all cleaned lines
                List<String> cleanLines = new ArrayList<>(lines.length);
                // collecting line tags
                List<String> lineTags = new ArrayList<>(lines.length);

                for (String line : lines) {
                    // get the tag
                    String tag = null;
                    Matcher m = OPENING_TAG_PATTERN.matcher(line);

                    if (m.find()) {
                        tag = m.group(1);
                    }

                    if (tag == null) {
                        throw new IllegalArgumentException("No html tag found for line:\n" + line);
                    }

                    // replace the tag at the beginning and the end
                    String noTagText = line.replaceAll("^<\\S+>", "").replaceAll("</\\S+>$", "");

                    // do some html cleaning
                    noTagText = noTagText.replaceAll("&nbsp;", " ");

                    noTagText = noTagText.trim();

                    // add to the output
                    if (!noTagText.isEmpty()) {
                        cleanLines.add(noTagText);
                        lineTags.add(tag);
                    }
                }

                if (cleanLines.isEmpty()) {
                    // the document is empty
                    System.err.println("Document " + rankedResults.clueWebID + " in query "
                            + queryResultContainer.qID + " is empty");
                } else {
                    // now join them back to paragraphs
                    String text = StringUtils.join(cleanLines, "\n");

                    // create JCas
                    JCas jCas = JCasFactory.createJCas();
                    jCas.setDocumentText(text);
                    jCas.setDocumentLanguage("en");

                    // annotate WebParagraph
                    SimplePipeline.runPipeline(jCas,
                            AnalysisEngineFactory.createEngineDescription(WebParagraphAnnotator.class));

                    // fill the original tag information
                    List<WebParagraph> webParagraphs = new ArrayList<>(
                            JCasUtil.select(jCas, WebParagraph.class));

                    // they must be the same size as original ones
                    if (webParagraphs.size() != lineTags.size()) {
                        throw new IllegalStateException(
                                "Different size of annotated paragraphs and original lines");
                    }

                    for (int i = 0; i < webParagraphs.size(); i++) {
                        WebParagraph p = webParagraphs.get(i);
                        // get tag
                        String tag = lineTags.get(i);

                        p.setOriginalHtmlTag(tag);
                    }

                    SimplePipeline.runPipeline(jCas,
                            AnalysisEngineFactory.createEngineDescription(StanfordSegmenter.class,
                                    // only on existing WebParagraph annotations
                                    StanfordSegmenter.PARAM_ZONE_TYPES, WebParagraph.class.getCanonicalName()));

                    // now convert to XMI
                    ByteArrayOutputStream byteOutputStream = new ByteArrayOutputStream();
                    XmiCasSerializer.serialize(jCas.getCas(), byteOutputStream);

                    // encode to base64
                    String encoded = new BASE64Encoder().encode(byteOutputStream.toByteArray());

                    rankedResults.originalXmi = encoded;
                }
            }
        }

        // and save the query to output dir
        File outputFile = new File(outputDir, queryResultContainer.qID + ".xml");
        FileUtils.writeStringToFile(outputFile, queryResultContainer.toXML(), "utf-8");
        System.out.println("Finished " + outputFile);
    }

}

From source file:com.continuent.tungsten.common.security.KeystoreManagerCtrl.java

/**
 * Password Manager entry point/*  w  w  w. j a  v  a2  s. c om*/
 * 
 * @param argv
 * @throws Exception
 */
public static void main(String argv[]) throws Exception {
    keystoreManager = new KeystoreManagerCtrl();

    // --- Options ---
    CommandLine line = null;

    try {
        CommandLineParser parser = new GnuParser();
        // --- Parse the command line arguments ---

        // --- Help
        line = parser.parse(keystoreManager.helpOptions, argv, true);
        if (line.hasOption(_HELP)) {
            DisplayHelpAndExit(EXIT_CODE.EXIT_OK);
        }

        // --- Program command line options
        line = parser.parse(keystoreManager.options, argv);

        // --- Compulsory arguments : Get options ---
        if (line.hasOption(_KEYSTORE_LOCATION))
            keystoreManager.keystoreLocation = line.getOptionValue(_KEYSTORE_LOCATION);

        if (line.hasOption(_KEY_ALIAS))
            keystoreManager.keyAlias = line.getOptionValue(_KEY_ALIAS);

        if (line.hasOption(_KEY_TYPE)) {
            String keyType = line.getOptionValue(_KEY_TYPE);
            // This will throw an exception if the type is not recognised
            KEYSTORE_TYPE certificateTYpe = KEYSTORE_TYPE.fromString(keyType);
            keystoreManager.keyType = certificateTYpe;
        }

        if (line.hasOption(_KEYSTORE_PASSWORD))
            keystoreManager.keystorePassword = line.getOptionValue(_KEYSTORE_PASSWORD);
        if (line.hasOption(_KEY_PASSWORD))
            keystoreManager.keyPassword = line.getOptionValue(_KEY_PASSWORD);

    } catch (ParseException exp) {
        logger.error(exp.getMessage());
        DisplayHelpAndExit(EXIT_CODE.EXIT_ERROR);
    } catch (Exception e) {
        // Workaround for Junit test
        if (e.toString().contains("CheckExitCalled")) {
            throw e;
        } else
        // Normal behaviour
        {
            logger.error(e.getMessage());
            Exit(EXIT_CODE.EXIT_ERROR);
        }

    }

    // --- Perform commands ---

    // ######### Check password ##########
    if (line.hasOption(_CHECK)) {
        try {
            if (keystoreManager.keystorePassword == null || keystoreManager.keyPassword == null) {
                // --- Get passwords from stdin if not given on command line
                List<String> listPrompts = Arrays.asList("Keystore password:",
                        MessageFormat.format("Password for key {0}:", keystoreManager.keyAlias));
                List<String> listUserInput = keystoreManager.getUserInputFromStdin(listPrompts);

                if (listUserInput.size() == listPrompts.size()) {
                    keystoreManager.keystorePassword = listUserInput.get(0);
                    keystoreManager.keyPassword = listUserInput.get(1);
                } else {
                    throw new NoSuchElementException();
                }
            }
            try {
                // --- Check that all keys in keystore use the keystore
                // password
                logger.info(MessageFormat.format("Using keystore:{0}", keystoreManager.keystoreLocation));

                SecurityHelper.checkKeyStorePasswords(keystoreManager.keystoreLocation, keystoreManager.keyType,
                        keystoreManager.keystorePassword, keystoreManager.keyAlias,
                        keystoreManager.keyPassword);
                logger.info(MessageFormat.format("OK : Identical password for Keystore and key={0}",
                        keystoreManager.keyAlias));
            } catch (UnrecoverableKeyException uke) {
                logger.error(MessageFormat.format("At least 1 key has a wrong password.{0}", uke.getMessage()));
                Exit(EXIT_CODE.EXIT_ERROR);
            } catch (Exception e) {
                logger.error(MessageFormat.format("{0}", e.getMessage()));
                Exit(EXIT_CODE.EXIT_ERROR);
            }

        } catch (NoSuchElementException nse) {
            logger.error(nse.getMessage());
            Exit(EXIT_CODE.EXIT_ERROR);
        } catch (Exception e) {
            logger.error(MessageFormat.format("Error while running the program: {0}", e.getMessage()));
            Exit(EXIT_CODE.EXIT_ERROR);
        }
    }

    Exit(EXIT_CODE.EXIT_OK);
}