Example usage for java.lang String equals

List of usage examples for java.lang String equals

Introduction

In this page you can find the example usage for java.lang String equals.

Prototype

public boolean equals(Object anObject) 

Source Link

Document

Compares this string to the specified object.

Usage

From source file:com.vmware.photon.controller.core.Main.java

public static void main(String[] args) throws Throwable {
    try {//from  w w w  .  j  ava 2s.  co  m
        LoggingFactory.bootstrap();

        logger.info("args: " + Arrays.toString(args));

        ArgumentParser parser = ArgumentParsers.newArgumentParser("PhotonControllerCore").defaultHelp(true)
                .description("Photon Controller Core");
        parser.addArgument("config-file").help("photon controller configuration file");
        parser.addArgument("--manual").type(Boolean.class).setDefault(false)
                .help("If true, create default deployment.");

        Namespace namespace = parser.parseArgsOrFail(args);

        PhotonControllerConfig photonControllerConfig = getPhotonControllerConfig(namespace);
        DeployerConfig deployerConfig = photonControllerConfig.getDeployerConfig();

        new LoggingFactory(photonControllerConfig.getLogging(), "photon-controller-core").configure();

        SSLContext sslContext;
        if (deployerConfig.getDeployerContext().isAuthEnabled()) {
            sslContext = SSLContext.getInstance(KeyStoreUtils.THRIFT_PROTOCOL);
            TrustManagerFactory tmf = null;

            tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
            KeyStore keyStore = KeyStore.getInstance("JKS");
            InputStream in = FileUtils
                    .openInputStream(new File(deployerConfig.getDeployerContext().getKeyStorePath()));
            keyStore.load(in, deployerConfig.getDeployerContext().getKeyStorePassword().toCharArray());
            tmf.init(keyStore);
            sslContext.init(null, tmf.getTrustManagers(), null);
        } else {
            KeyStoreUtils.generateKeys("/thrift/");
            sslContext = KeyStoreUtils.acceptAllCerts(KeyStoreUtils.THRIFT_PROTOCOL);
        }

        ThriftModule thriftModule = new ThriftModule(sslContext);
        PhotonControllerXenonHost xenonHost = startXenonHost(photonControllerConfig, thriftModule,
                deployerConfig, sslContext);

        if ((Boolean) namespace.get("manual")) {
            DefaultDeployment.createDefaultDeployment(photonControllerConfig.getXenonConfig().getPeerNodes(),
                    deployerConfig, xenonHost);
        }

        // Creating a temp configuration file for apife with modification to some named sections in photon-controller-config
        // so that it can match the Configuration class of dropwizard.
        File apiFeTempConfig = File.createTempFile("apiFeTempConfig", ".tmp");
        File source = new File(args[0]);
        FileInputStream fis = new FileInputStream(source);
        BufferedReader in = new BufferedReader(new InputStreamReader(fis));

        FileWriter fstream = new FileWriter(apiFeTempConfig, true);
        BufferedWriter out = new BufferedWriter(fstream);

        String aLine = null;
        while ((aLine = in.readLine()) != null) {
            if (aLine.equals("apife:")) {
                aLine = aLine.replace("apife:", "server:");
            }
            out.write(aLine);
            out.newLine();
        }
        in.close();
        out.close();

        // This approach can be simplified once the apife container is gone, but for the time being
        // it expects the first arg to be the string "server".
        String[] apiFeArgs = new String[2];
        apiFeArgs[0] = "server";
        apiFeArgs[1] = apiFeTempConfig.getAbsolutePath();
        ApiFeService.setupApiFeConfigurationForServerCommand(apiFeArgs);
        ApiFeService.addServiceHost(xenonHost);
        ApiFeService.setSSLContext(sslContext);

        ApiFeService apiFeService = new ApiFeService();
        apiFeService.run(apiFeArgs);
        apiFeTempConfig.deleteOnExit();

        LocalApiClient localApiClient = apiFeService.getInjector().getInstance(LocalApiClient.class);
        xenonHost.setApiClient(localApiClient);

        // in the non-auth enabled scenario we need to be able to accept any self-signed certificate
        if (!deployerConfig.getDeployerContext().isAuthEnabled()) {
            KeyStoreUtils.acceptAllCerts(KeyStoreUtils.THRIFT_PROTOCOL);
        }

        Runtime.getRuntime().addShutdownHook(new Thread() {
            @Override
            public void run() {
                logger.info("Shutting down");
                xenonHost.stop();
                logger.info("Done");
                LoggingFactory.detachAndStop();
            }
        });
    } catch (Exception e) {
        logger.error("Failed to start photon controller ", e);
        throw e;
    }
}

From source file:TransactedTalk.java

/** Main program entry point. */
public static void main(String argv[]) {

    // Is there anything to do?
    if (argv.length == 0) {
        printUsage();// w  ww .ja  va2s  .co m
        System.exit(1);
    }

    // Values to be read from parameters
    String broker = DEFAULT_BROKER_NAME;
    String username = null;
    String password = DEFAULT_PASSWORD;
    String qSender = null;
    String qReceiver = null;

    // Check parameters
    for (int i = 0; i < argv.length; i++) {
        String arg = argv[i];

        // Options
        if (!arg.startsWith("-")) {
            System.err.println("error: unexpected argument - " + arg);
            printUsage();
            System.exit(1);
        } else {
            if (arg.equals("-b")) {
                if (i == argv.length - 1 || argv[i + 1].startsWith("-")) {
                    System.err.println("error: missing broker name:port");
                    System.exit(1);
                }
                broker = argv[++i];
                continue;
            }

            if (arg.equals("-u")) {
                if (i == argv.length - 1 || argv[i + 1].startsWith("-")) {
                    System.err.println("error: missing user name");
                    System.exit(1);
                }
                username = argv[++i];
                continue;
            }

            if (arg.equals("-p")) {
                if (i == argv.length - 1 || argv[i + 1].startsWith("-")) {
                    System.err.println("error: missing password");
                    System.exit(1);
                }
                password = argv[++i];
                continue;
            }

            if (arg.equals("-qr")) {
                if (i == argv.length - 1 || argv[i + 1].startsWith("-")) {
                    System.err.println("error: missing receive queue parameter");
                    System.exit(1);
                }
                qReceiver = argv[++i];
                continue;
            }

            if (arg.equals("-qs")) {
                if (i == argv.length - 1 || argv[i + 1].startsWith("-")) {
                    System.err.println("error: missing send queue parameter");
                    System.exit(1);
                }
                qSender = argv[++i];
                continue;
            }

            if (arg.equals("-h")) {
                printUsage();
                System.exit(1);
            }
        }
    }

    // Check values read in.
    if (username == null) {
        System.err.println("error: user name must be supplied");
        printUsage();
        System.exit(1);
    }

    if (qReceiver == null && qSender == null) {
        System.err.println("error: receive queue, or send queue, must be supplied");
        printUsage();
        System.exit(1);
    }

    // Start the JMS client for the "Talk".
    TransactedTalk tranTalk = new TransactedTalk();
    tranTalk.talker(broker, username, password, qReceiver, qSender);

}

From source file:de.bruse.c2x.cli.Main.java

public static void main(String[] args) {
    CommandLineParser parser = new GnuParser();
    Options options = new Options();

    Option input = new Option("i", INPUT, HAS_ARGS, "CityGML file to be converted.");
    input.setArgs(ONE);/*from w w  w . j a v a2 s. co  m*/
    input.setArgName(INPUT);
    input.setRequired(Boolean.TRUE);
    options.addOption(input);

    Option levelOfDetail = new Option("l", LEVEL_OF_DETAIL, HAS_ARGS,
            "Level of detail to be converted. Possible values are LOD1 and LOD2.");
    levelOfDetail.setArgs(ONE);
    levelOfDetail.setArgName(LEVEL_OF_DETAIL);
    levelOfDetail.setRequired(Boolean.TRUE);
    options.addOption(levelOfDetail);

    Option geometryType = new Option("t", GEOMETRY_TYPE, HAS_ARGS,
            "Geometry type to be converted. Possible values are SOLID and MULTI_SURFACE.");
    geometryType.setArgs(ONE);
    geometryType.setArgName(GEOMETRY_TYPE);
    geometryType.setRequired(Boolean.TRUE);
    options.addOption(geometryType);

    Option output = new Option("o", OUTPUT, HAS_ARGS, "File path of the output file.");
    output.setArgs(ONE);
    output.setArgName(OUTPUT);
    output.setRequired(Boolean.FALSE);
    options.addOption(output);

    Option targetFormat = new Option("f", FORMAT, HAS_ARGS,
            "Format of the output file. Possible values are X3D and COLLADA.");
    targetFormat.setArgs(ONE);
    targetFormat.setArgName(FORMAT);
    targetFormat.setRequired(Boolean.TRUE);
    options.addOption(targetFormat);

    Option split = new Option("s", SPLIT, NO_ARGS, "Generate one scene node for each building (X3D only).");
    split.setArgName(SPLIT);
    split.setRequired(Boolean.FALSE);
    options.addOption(split);

    Option validate = new Option("v", VALIDATE, NO_ARGS, "Validate the CityGML file.");
    validate.setArgName(VALIDATE);
    validate.setRequired(Boolean.FALSE);
    options.addOption(validate);

    try {
        CommandLine line = parser.parse(options, args);
        if (line.hasOption(INPUT) && line.hasOption(LEVEL_OF_DETAIL) && line.hasOption(GEOMETRY_TYPE)
                && line.hasOption(FORMAT)) {
            String inputValue = line.getOptionValue(INPUT);
            String levelOfDetailValue = line.getOptionValue(LEVEL_OF_DETAIL);
            String geometryTypeValue = line.getOptionValue(GEOMETRY_TYPE);
            String targetFormatValue = line.getOptionValue(FORMAT);
            String outputValue = line.getOptionValue(OUTPUT);
            LevelOfDetail lod = LevelOfDetail.valueOf(levelOfDetailValue);
            GeometryType type = GeometryType.valueOf(geometryTypeValue);
            if (Objects.isNull(lod) || Objects.isNull(type)
                    || (!targetFormatValue.equals(X3D) && !targetFormatValue.equals(COLLADA))) {
                printHelp(options);
            } else {
                if (line.hasOption(VALIDATE)) {
                    triggerValidation(inputValue);
                }
                if (targetFormatValue.equals(X3D)) {
                    boolean splitValue = false;
                    if (line.hasOption(SPLIT)) {
                        splitValue = true;
                    }
                    if (Objects.isNull(outputValue) || outputValue.isEmpty()) {
                        outputValue = inputValue + X3D_FILE_EXT;
                    }
                    triggerX3DConversion(inputValue, lod, type, outputValue, splitValue);
                } else if (targetFormatValue.equals(COLLADA)) {
                    if (Objects.isNull(outputValue) || outputValue.isEmpty()) {
                        outputValue = inputValue + COLLADA_FILE_EXT;
                    }
                    triggerColladaConversion(inputValue, lod, type, outputValue);
                }
                System.out.println("Conversion succeeded.");
            }
        } else {
            printHelp(options);
        }
    } catch (ParseException | IllegalArgumentException e) {
        printHelp(options);
    } catch (ValidationException e) {
        System.out.println("Input file is invalid. Operation canceled.\n" + e.getMessage());
    } catch (ConversionException e) {
        String message = "Failed to convert CityGML.";
        if (Objects.nonNull(e.getMessage())) {
            message += " " + e.getMessage();
        }
        System.out.println(message);
    } catch (IOException e) {
        System.out.println("Failed to read from file '" + input + "'.");
    }
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    ZipFile zf = new ZipFile("a.zip");
    Enumeration e = zf.entries();
    while (e.hasMoreElements()) {
        ZipEntry ze = (ZipEntry) e.nextElement();
        String name = ze.getName();

        long uncompressedSize = ze.getSize();
        long compressedSize = ze.getCompressedSize();
        long crc = ze.getCrc();
        int method = ze.getMethod();
        String comment = ze.getComment();

        System.out.println(name + " was stored at " + new Date(ze.getTime()));
        if (method == ZipEntry.STORED) {
            System.out.println("with a size of  " + uncompressedSize + " bytes");
        } else if (method == ZipEntry.DEFLATED) {
            System.out.println("from " + uncompressedSize + " bytes to " + compressedSize);
        } else {//from   ww  w.  jav  a2s  . co  m
            System.out.println("from " + uncompressedSize + " bytes to " + compressedSize);
        }
        System.out.println("Its CRC is " + crc);
        if (comment != null && !comment.equals("")) {
            System.out.println(comment);
        }
        if (ze.isDirectory()) {
            System.out.println(name + " is a directory");
        }
    }
}

From source file:org.opcfoundation.ua.examples.BigCertificateExample.java

public static void main(String[] args) throws Exception {
    // Create Logger
    Logger myLogger = LoggerFactory.getLogger(BigCertificateExample.class);

    ///// Server Application /////////////      
    Application serverApplication = new Application();
    MyServerExample2 myServer = new MyServerExample2(serverApplication);

    // Attach listener (debug logger) to each binding
    DebugLogger debugLogger = new DebugLogger(myLogger);
    for (EndpointServer b : myServer.getEndpointBindings().getEndpointServers())
        b.addConnectionListener(debugLogger);
    //////////////////////////////////////      

    //////////////  CLIENT  //////////////
    // Load Client's Application Instance Certificate from file
    KeyPair myClientOpcTcpKeyPair = ExampleKeys.getKeyPair("client", CLIENT_KEY_SIZE);
    KeyPair myClientHttpsKeyPair = ExampleKeys.getKeyPair("https_client", CLIENT_KEY_SIZE);
    // Create Client Application
    Application myClientApplication = new Application();
    myClientApplication.getHttpsSettings().setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    myClientApplication.getHttpsSettings().setCertificateValidator(CertificateValidator.ALLOW_ALL);
    myClientApplication.getHttpsSettings().setKeyPair(myClientHttpsKeyPair);
    myClientApplication.addApplicationInstanceCertificate(myClientOpcTcpKeyPair);
    // Create Client
    Client myClient = new Client(myClientApplication);
    //////////////////////////////////////      

    // Get Endpoints like this
    SecureChannel secureChannel = myClient.createSecureChannel(URL, URL, SecurityMode.NONE, null);
    ChannelService chan = new ChannelService(secureChannel);
    EndpointDescription[] endpoints;// w  w w. j  av a  2s.c o  m
    try {
        GetEndpointsRequest req = new GetEndpointsRequest(null, URL, new String[0], new String[0]);
        GetEndpointsResponse res = chan.GetEndpoints(req);
        endpoints = res.getEndpoints();
    } finally {
        secureChannel.close();
        secureChannel.dispose();
    }

    SessionChannel myChannel = null;
    try {
        // Select policy according to initial parameters
        String proto = UriUtil.getTransportProtocol(URL);
        endpoints = EndpointUtil.select(endpoints, CLIENT_KEY_SIZE, CLIENT_KEY_SIZE);
        endpoints = EndpointUtil.select(endpoints, null, proto, null, null, null);
        if (proto.equals("https")) {
            endpoints = EndpointUtil.selectByMessageSecurityMode(endpoints, MessageSecurityMode.None);
            myClient.getApplicationHttpsSettings().setHttpsSecurityPolicies(httpsSecurityPolicies);
        } else
            endpoints = EndpointUtil.selectByMessageSecurityMode(endpoints, MessageSecurityMode.SignAndEncrypt);
        if (endpoints.length == 0) {
            throw new IllegalArgumentException("No suitable endpoint found from " + URL);
        }

        /////////  DISCOVER SERVERS  /////////
        // Discover server applications
        //         ApplicationDescription[] servers = myClient.discoverApplications( new URI("https://localhost:6001/") );
        //         // Choose one application
        //         ApplicationDescription server = servers[0];
        // Connect the application         
        myChannel = myClient.createSessionChannel(endpoints[0]);
        //         myChannel = myClient.createSessionChannel( server );
        // Activate session
        myChannel.activate();
        //////////////////////////////////////

        /////////////  EXECUTE  //////////////      
        CallRequest callRequest = new CallRequest();
        CallMethodRequest methodRequest = new CallMethodRequest();
        callRequest.setMethodsToCall(new CallMethodRequest[] { methodRequest });
        methodRequest.setMethodId(MyServerExample2.LIST_SOLVERS);
        CallResponse res = myChannel.Call(callRequest);
        System.out.println(res);
        //////////////////////////////////////
    }

    finally {
        /////////////  SHUTDOWN  /////////////
        // Close client's channel
        if (myChannel != null)
            myChannel.close();
        // Close the server by unbinding all endpoints 
        myServer.getApplication().close();
        //////////////////////////////////////      
    }

}

From source file:SelectorTalk.java

/** Main program entry point. */
public static void main(String argv[]) {

    // Is there anything to do?
    if (argv.length == 0) {
        printUsage();//  w w  w . j  a va 2 s .c om
        System.exit(1);
    }

    // Values to be read from parameters
    String broker = DEFAULT_BROKER_NAME;
    String username = null;
    String password = DEFAULT_PASSWORD;
    String qSender = null;
    String qReceiver = null;
    String selection = null;

    // Check parameters
    for (int i = 0; i < argv.length; i++) {
        String arg = argv[i];

        // Options
        if (!arg.startsWith("-")) {
            System.err.println("error: unexpected argument - " + arg);
            printUsage();
            System.exit(1);
        } else {
            if (arg.equals("-b")) {
                if (i == argv.length - 1 || argv[i + 1].startsWith("-")) {
                    System.err.println("error: missing broker name:port");
                    System.exit(1);
                }
                broker = argv[++i];
                continue;
            }

            if (arg.equals("-u")) {
                if (i == argv.length - 1 || argv[i + 1].startsWith("-")) {
                    System.err.println("error: missing user name");
                    System.exit(1);
                }
                username = argv[++i];
                continue;
            }

            if (arg.equals("-p")) {
                if (i == argv.length - 1 || argv[i + 1].startsWith("-")) {
                    System.err.println("error: missing password");
                    System.exit(1);
                }
                password = argv[++i];
                continue;
            }

            if (arg.equals("-qr")) {
                if (i == argv.length - 1 || argv[i + 1].startsWith("-")) {
                    System.err.println("error: missing receive queue parameter");
                    System.exit(1);
                }
                qReceiver = argv[++i];
                continue;
            }

            if (arg.equals("-qs")) {
                if (i == argv.length - 1 || argv[i + 1].startsWith("-")) {
                    System.err.println("error: missing send queue parameter");
                    System.exit(1);
                }
                qSender = argv[++i];
                continue;
            }

            if (arg.equals("-s")) {
                if (i == argv.length - 1 || argv[i + 1].startsWith("-")) {
                    System.err.println("error: missing selectiion");
                    System.exit(1);
                }
                selection = argv[++i];
                continue;
            }

            if (arg.equals("-h")) {
                printUsage();
                System.exit(1);
            }
        }
    }

    // Check values read in.
    if (username == null) {
        System.err.println("error: user name must be supplied");
        printUsage();
        System.exit(1);
    }

    if (qReceiver == null && qSender == null) {
        System.err.println("error: receive queue, or send queue, must be supplied");
        printUsage();
        System.exit(1);
    }

    if (selection == null) {
        System.err.println("error: selection must be supplied (e.g. -s SALES)\n");
        printUsage();
        System.exit(1);
    }

    // Start the JMS client for the "Talk".
    SelectorTalk talk = new SelectorTalk();
    talk.talker(broker, username, password, qReceiver, qSender, selection);

}

From source file:com.amazonaws.services.kinesis.leases.impl.LeaseCoordinatorExerciser.java

public static void main(String[] args) throws InterruptedException, DependencyException, InvalidStateException,
        ProvisionedThroughputException, IOException {

    int numCoordinators = 9;
    int numLeases = 73;
    int leaseDurationMillis = 10000;
    int epsilonMillis = 100;

    AWSCredentialsProvider creds = new DefaultAWSCredentialsProviderChain();
    AmazonDynamoDBClient ddb = new AmazonDynamoDBClient(creds);

    ILeaseManager<KinesisClientLease> leaseManager = new KinesisClientLeaseManager("nagl_ShardProgress", ddb);

    if (leaseManager.createLeaseTableIfNotExists(10L, 50L)) {
        LOG.info("Waiting for newly created lease table");
        if (!leaseManager.waitUntilLeaseTableExists(10, 300)) {
            LOG.error("Table was not created in time");
            return;
        }//from   w  ww. j  a va  2s .  c o m
    }

    CWMetricsFactory metricsFactory = new CWMetricsFactory(creds, "testNamespace", 30 * 1000, 1000);
    final List<LeaseCoordinator<KinesisClientLease>> coordinators = new ArrayList<LeaseCoordinator<KinesisClientLease>>();
    for (int i = 0; i < numCoordinators; i++) {
        String workerIdentifier = "worker-" + Integer.toString(i);

        LeaseCoordinator<KinesisClientLease> coord = new LeaseCoordinator<KinesisClientLease>(leaseManager,
                workerIdentifier, leaseDurationMillis, epsilonMillis, metricsFactory);

        coordinators.add(coord);
    }

    leaseManager.deleteAll();

    for (int i = 0; i < numLeases; i++) {
        KinesisClientLease lease = new KinesisClientLease();
        lease.setLeaseKey(Integer.toString(i));
        lease.setCheckpoint(new ExtendedSequenceNumber("checkpoint"));
        leaseManager.createLeaseIfNotExists(lease);
    }

    final JFrame frame = new JFrame("Test Visualizer");
    frame.setPreferredSize(new Dimension(800, 600));
    final JPanel panel = new JPanel(new GridLayout(coordinators.size() + 1, 0));
    final JLabel ticker = new JLabel("tick");
    panel.add(ticker);
    frame.getContentPane().add(panel);

    final Map<String, JLabel> labels = new HashMap<String, JLabel>();
    for (final LeaseCoordinator<KinesisClientLease> coord : coordinators) {
        JPanel coordPanel = new JPanel();
        coordPanel.setLayout(new BoxLayout(coordPanel, BoxLayout.X_AXIS));
        final Button button = new Button("Stop " + coord.getWorkerIdentifier());
        button.setMaximumSize(new Dimension(200, 50));
        button.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent arg0) {
                if (coord.isRunning()) {
                    coord.stop();
                    button.setLabel("Start " + coord.getWorkerIdentifier());
                } else {
                    try {
                        coord.start();
                    } catch (LeasingException e) {
                        LOG.error(e);
                    }
                    button.setLabel("Stop " + coord.getWorkerIdentifier());
                }
            }

        });
        coordPanel.add(button);

        JLabel label = new JLabel();
        coordPanel.add(label);
        labels.put(coord.getWorkerIdentifier(), label);
        panel.add(coordPanel);
    }

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    new Thread() {

        // Key is lease key, value is green-ness as a value from 0 to 255.
        // Great variable name, huh?
        private Map<String, Integer> greenNesses = new HashMap<String, Integer>();

        // Key is lease key, value is last owning worker
        private Map<String, String> lastOwners = new HashMap<String, String>();

        @Override
        public void run() {
            while (true) {
                for (LeaseCoordinator<KinesisClientLease> coord : coordinators) {
                    String workerIdentifier = coord.getWorkerIdentifier();

                    JLabel label = labels.get(workerIdentifier);

                    List<KinesisClientLease> asgn = new ArrayList<KinesisClientLease>(coord.getAssignments());
                    Collections.sort(asgn, new Comparator<KinesisClientLease>() {

                        @Override
                        public int compare(KinesisClientLease arg0, KinesisClientLease arg1) {
                            return arg0.getLeaseKey().compareTo(arg1.getLeaseKey());
                        }

                    });

                    StringBuilder builder = new StringBuilder();
                    builder.append("<html>");
                    builder.append(workerIdentifier).append(":").append(asgn.size()).append("          ");

                    for (KinesisClientLease lease : asgn) {
                        String leaseKey = lease.getLeaseKey();
                        String lastOwner = lastOwners.get(leaseKey);

                        // Color things green when they switch owners, decay the green-ness over time.
                        Integer greenNess = greenNesses.get(leaseKey);
                        if (greenNess == null || lastOwner == null
                                || !lastOwner.equals(lease.getLeaseOwner())) {
                            greenNess = 200;
                        } else {
                            greenNess = Math.max(0, greenNess - 20);
                        }
                        greenNesses.put(leaseKey, greenNess);
                        lastOwners.put(leaseKey, lease.getLeaseOwner());

                        builder.append(String.format("<font color=\"%s\">%03d</font>",
                                String.format("#00%02x00", greenNess), Integer.parseInt(leaseKey))).append(" ");
                    }
                    builder.append("</html>");

                    label.setText(builder.toString());
                    label.revalidate();
                    label.repaint();
                }

                if (ticker.getText().equals("tick")) {
                    ticker.setText("tock");
                } else {
                    ticker.setText("tick");
                }

                try {
                    Thread.sleep(200);
                } catch (InterruptedException e) {
                }
            }
        }

    }.start();

    frame.pack();
    frame.setVisible(true);

    for (LeaseCoordinator<KinesisClientLease> coord : coordinators) {
        coord.start();
    }
}

From source file:com.act.lcms.db.io.ExportStandardIonResultsFromDB.java

public static void main(String[] args) throws Exception {
    Options opts = new Options();
    for (Option.Builder b : OPTION_BUILDERS) {
        opts.addOption(b.build());//from w  w w .  j av  a  2  s . c  o  m
    }

    CommandLine cl = null;
    try {
        CommandLineParser parser = new DefaultParser();
        cl = parser.parse(opts, args);
    } catch (ParseException e) {
        System.err.format("Argument parsing failed: %s\n", e.getMessage());
        HELP_FORMATTER.printHelp(ExportStandardIonResultsFromDB.class.getCanonicalName(), HELP_MESSAGE, opts,
                null, true);
        System.exit(1);
    }

    if (cl.hasOption("help")) {
        HELP_FORMATTER.printHelp(ExportStandardIonResultsFromDB.class.getCanonicalName(), HELP_MESSAGE, opts,
                null, true);
        return;
    }

    try (DB db = DB.openDBFromCLI(cl)) {
        List<String> chemicalNames = new ArrayList<>();
        if (cl.hasOption(OPTION_CONSTRUCT)) {
            // Extract the chemicals in the pathway and their product masses, then look up info on those chemicals
            List<Pair<ChemicalAssociatedWithPathway, Double>> productMasses = Utils
                    .extractMassesForChemicalsAssociatedWithConstruct(db, cl.getOptionValue(OPTION_CONSTRUCT));

            for (Pair<ChemicalAssociatedWithPathway, Double> pair : productMasses) {
                chemicalNames.add(pair.getLeft().getChemical());
            }
        }

        if (cl.hasOption(OPTION_CHEMICALS)) {
            chemicalNames.addAll(Arrays.asList(cl.getOptionValues(OPTION_CHEMICALS)));
        }

        if (chemicalNames.size() == 0) {
            System.err.format("No chemicals can be found from the input query.\n");
            System.exit(-1);
        }

        List<String> standardIonHeaderFields = new ArrayList<String>() {
            {
                add(STANDARD_ION_HEADER_FIELDS.CHEMICAL.name());
                add(STANDARD_ION_HEADER_FIELDS.BEST_ION_FROM_ALGO.name());
                add(STANDARD_ION_HEADER_FIELDS.MANUAL_PICK.name());
                add(STANDARD_ION_HEADER_FIELDS.AUTHOR.name());
                add(STANDARD_ION_HEADER_FIELDS.DIAGNOSTIC_PLOTS.name());
                add(STANDARD_ION_HEADER_FIELDS.NOTE.name());
            }
        };

        String outAnalysis;
        if (cl.hasOption(OPTION_OUTPUT_PREFIX)) {
            outAnalysis = cl.getOptionValue(OPTION_OUTPUT_PREFIX) + "." + TSV_FORMAT;
        } else {
            outAnalysis = String.join("-", chemicalNames) + "." + TSV_FORMAT;
        }

        File lcmsDir = new File(cl.getOptionValue(OPTION_DIRECTORY));
        if (!lcmsDir.isDirectory()) {
            System.err.format("File at %s is not a directory\n", lcmsDir.getAbsolutePath());
            HELP_FORMATTER.printHelp(LoadPlateCompositionIntoDB.class.getCanonicalName(), HELP_MESSAGE, opts,
                    null, true);
            System.exit(1);
        }

        String plottingDirectory = cl.getOptionValue(OPTION_PLOTTING_DIR);

        TSVWriter<String, String> resultsWriter = new TSVWriter<>(standardIonHeaderFields);
        resultsWriter.open(new File(outAnalysis));

        // For each chemical, create a TSV row and a corresponding diagnostic plot
        for (String chemicalName : chemicalNames) {
            List<String> graphLabels = new ArrayList<>();
            List<Double> yMaxList = new ArrayList<>();

            String outData = plottingDirectory + "/" + chemicalName + ".data";
            String outImg = plottingDirectory + "/" + chemicalName + ".pdf";

            // For each diagnostic plot, open a new file stream.
            try (FileOutputStream fos = new FileOutputStream(outData)) {

                List<StandardIonResult> getResultByChemicalName = StandardIonResult.getByChemicalName(db,
                        chemicalName);

                if (getResultByChemicalName != null && getResultByChemicalName.size() > 0) {

                    // PART 1: Get the best metlin ion across all standard ion results for a given chemical
                    String bestGlobalMetlinIon = AnalysisHelper
                            .scoreAndReturnBestMetlinIonFromStandardIonResults(getResultByChemicalName,
                                    new HashMap<>(), true, true);

                    // PART 2: Plot all the graphs related to the chemical. The plots are structured as follows:
                    //
                    // Page 1: All graphs (water, MeOH, Yeast) for Global ion picked (best ion among ALL standard ion runs for
                    // the given chemical) by the algorithm
                    // Page 2: All graphs for M+H
                    // Page 3: All graphs for Local ions picked (best ion within a SINGLE standard ion run) + negative controls
                    // for Yeast.
                    //
                    // Each page is demarcated by a blank graph.

                    // Arrange results based on media
                    Map<String, List<StandardIonResult>> categories = StandardIonResult
                            .categorizeListOfStandardWellsByMedia(db, getResultByChemicalName);

                    // This set contains all the best metlin ions corresponding to all the standard ion runs.
                    Set<String> bestLocalIons = new HashSet<>();
                    bestLocalIons.add(bestGlobalMetlinIon);
                    bestLocalIons.add(DEFAULT_ION);

                    for (StandardIonResult result : getResultByChemicalName) {
                        bestLocalIons.add(result.getBestMetlinIon());
                    }

                    // We sort the best local ions are follows:
                    // 1) Global best ion spectra 2) M+H spectra 3) Local best ion spectra
                    List<String> bestLocalIonsArray = new ArrayList<>(bestLocalIons);
                    Collections.sort(bestLocalIonsArray, new Comparator<String>() {
                        @Override
                        public int compare(String o1, String o2) {
                            if (o1.equals(bestGlobalMetlinIon) && !o2.equals(bestGlobalMetlinIon)) {
                                return -1;
                            } else if (o1.equals(DEFAULT_ION) && !o2.equals(bestGlobalMetlinIon)) {
                                return -1;
                            } else {
                                return 1;
                            }
                        }
                    });

                    // This variable stores the index of the array at which all the remaining spectra are contained in one
                    // page. This happens right after the M+H ion spectra.
                    Integer combineAllSpectraIntoPageThreeFromIndex = 0;
                    for (int i = 0; i < bestLocalIonsArray.size(); i++) {
                        if (bestLocalIonsArray.get(i).equals(DEFAULT_ION)) {
                            combineAllSpectraIntoPageThreeFromIndex = i + 1;
                        }
                    }

                    for (int i = 0; i < bestLocalIonsArray.size(); i++) {

                        String ion = bestLocalIonsArray.get(i);
                        for (Map.Entry<String, List<StandardIonResult>> mediaToListOfIonResults : categories
                                .entrySet()) {

                            for (StandardIonResult result : mediaToListOfIonResults.getValue()) {

                                // For every standard ion result, we plot the best global metlin ion and M+H. These plots are in the
                                // pages 1 and 2. For all page 3 (aka miscellaneous spectra), we only plot the best local ion
                                // corresponding to it's spectra and not some other graph's spectra. In the below condition,
                                // we reach the page 3 case with not the same best ion as the spectra, in which case we just continue
                                // and not draw anything on the page.
                                if (i >= combineAllSpectraIntoPageThreeFromIndex
                                        && !(result.getBestMetlinIon().equals(ion))) {
                                    continue;
                                }

                                StandardWell positiveWell = StandardWell.getInstance().getById(db,
                                        result.getStandardWellId());
                                String positiveControlChemical = positiveWell.getChemical();

                                ScanData<StandardWell> encapsulatedDataForPositiveControl = AnalysisHelper
                                        .getScanDataForWell(db, lcmsDir, positiveWell, positiveControlChemical,
                                                positiveControlChemical);

                                Set<String> singletonSet = Collections.singleton(ion);
                                String additionalInfo = generateAdditionalLabelInformation(positiveWell, result,
                                        ion);

                                List<String> labels = AnalysisHelper
                                        .writeScanData(fos, lcmsDir, MAX_INTENSITY,
                                                encapsulatedDataForPositiveControl, false, false, singletonSet)
                                        .stream().map(label -> label + additionalInfo)
                                        .collect(Collectors.toList());

                                yMaxList.add(encapsulatedDataForPositiveControl.getMs1ScanResults()
                                        .getMaxIntensityForIon(ion));

                                List<String> negativeLabels = null;
                                // Only do the negative control in the miscellaneous page (page 3) and if the well is in yeast media.
                                if (mediaToListOfIonResults.getKey()
                                        .equals(StandardWell.MEDIA_TYPE.YEAST.name())
                                        && (i >= combineAllSpectraIntoPageThreeFromIndex
                                                && (result.getBestMetlinIon().equals(ion)))) {
                                    //TODO: Change the representative negative well to one that displays the highest noise in the future.
                                    // For now, we just use the first index among the negative wells.
                                    int representativeIndex = 0;
                                    StandardWell representativeNegativeControlWell = StandardWell.getInstance()
                                            .getById(db, result.getNegativeWellIds().get(representativeIndex));

                                    ScanData encapsulatedDataForNegativeControl = AnalysisHelper
                                            .getScanDataForWell(db, lcmsDir, representativeNegativeControlWell,
                                                    positiveWell.getChemical(),
                                                    representativeNegativeControlWell.getChemical());

                                    String negativePlateAdditionalInfo = generateAdditionalLabelInformation(
                                            representativeNegativeControlWell, null, null);

                                    negativeLabels = AnalysisHelper.writeScanData(fos, lcmsDir, MAX_INTENSITY,
                                            encapsulatedDataForNegativeControl, false, false, singletonSet)
                                            .stream().map(label -> label + negativePlateAdditionalInfo)
                                            .collect(Collectors.toList());

                                    yMaxList.add(encapsulatedDataForNegativeControl.getMs1ScanResults()
                                            .getMaxIntensityForIon(ion));
                                }

                                graphLabels.addAll(labels);

                                if (negativeLabels != null) {
                                    graphLabels.addAll(negativeLabels);
                                }
                            }
                        }

                        // Add a blank graph to demarcate pages.
                        if (i < combineAllSpectraIntoPageThreeFromIndex) {
                            graphLabels.addAll(AnalysisHelper.writeScanData(fos, lcmsDir, 0.0, BLANK_SCAN,
                                    false, false, new HashSet<>()));
                            yMaxList.add(0.0d);
                        }
                    }

                    // We need to pass the yMax values as an array to the Gnuplotter.
                    Double fontScale = null;
                    if (cl.hasOption(FONT_SCALE)) {
                        try {
                            fontScale = Double.parseDouble(cl.getOptionValue(FONT_SCALE));
                        } catch (IllegalArgumentException e) {
                            System.err.format("Argument for font-scale must be a floating point number.\n");
                            System.exit(1);
                        }
                    }

                    Double[] yMaxes = yMaxList.toArray(new Double[yMaxList.size()]);
                    Gnuplotter plotter = fontScale == null ? new Gnuplotter() : new Gnuplotter(fontScale);
                    plotter.plot2D(outData, outImg, graphLabels.toArray(new String[graphLabels.size()]), "time",
                            null, "intensity", "pdf", null, null, yMaxes, outImg + ".gnuplot");

                    Map<String, String> row = new HashMap<>();
                    row.put(STANDARD_ION_HEADER_FIELDS.CHEMICAL.name(), chemicalName);
                    row.put(STANDARD_ION_HEADER_FIELDS.BEST_ION_FROM_ALGO.name(), bestGlobalMetlinIon);
                    row.put(STANDARD_ION_HEADER_FIELDS.DIAGNOSTIC_PLOTS.name(), outImg);

                    resultsWriter.append(row);
                    resultsWriter.flush();
                }
            }
        }

        resultsWriter.flush();
        resultsWriter.close();
    }
}

From source file:asm.FindCallers.java

public static void main(String... args) {

    OutputStream os = null;//w  w  w . ja va 2s  .  c  om

    try {
        FindAnnotationWalker w = new FindAnnotationWalker();

        FindCallers cl = w.walk(args[0], args[1]);

        for (Annotated a : cl.annotated)
            System.out.println(a);

        System.out.println("Start CSV");

        os = new FileOutputStream(args[2]);

        for (Annotated a : cl.annotated) {
            if (!a.isPublic) {
                String line = String.format("%s\t%s\t%s\t%s\t%s\t%s\n", "no", "", "", a.className, a.name,
                        a.getTarget());

                os.write(line.getBytes("UTF-8"));
            }
        }

        for (Invocation i : cl.invocations) {
            if (cl.annotatedMap.containsKey(i.getTarget())) {
                for (Annotated a : cl.annotatedMap.get(i.getTarget())) {
                    String ok = "";

                    if (i.sourceClassName.endsWith("Cmd") || i.sourceClassName.endsWith("Test")
                            || i.sourceClassName.contains("/test/")) {
                        ok = "ok";
                    }

                    if (i.sourceClassName.equals(a.className)) {
                        ok = "no";
                    }

                    if (ok.equals("") && i.sourceBaseName.equals(a.baseName)
                            && !i.sourceClassName.equals(a.className)) {
                        /* Source and dest are different and they are both have the 
                         * same parent, so they obviously one isn't a child of the other
                         */
                        ok = "ok";
                    }

                    String line = String.format("%s\t%s\t%s\t%s\t%s\t%s\n", ok, i.sourceClassName,
                            i.sourceMethodName, a.className, a.name, a.getTarget());

                    os.write(line.getBytes("UTF-8"));
                }
            }
        }

        System.out.println("Done CSV");
    } catch (Throwable e) {
        e.printStackTrace();
    } finally {
        IOUtils.closeQuietly(os);
    }

}

From source file:com.seanmadden.fast.ldap.main.Main.java

/**
 * The Main Event./*from w w  w .j a v a2  s  .com*/
 * 
 * @param args
 */
@SuppressWarnings("static-access")
public static void main(String[] args) {
    BasicConfigurator.configure();
    log.debug("System initializing");
    try {
        Logger.getRootLogger().addAppender(
                new FileAppender(new PatternLayout(PatternLayout.TTCC_CONVERSION_PATTERN), "log.log"));
    } catch (IOException e1) {
        log.error("Unable to open the log file..?");
    }

    /*
     * Initialize the configuration engine.
     */
    XMLConfiguration config = new XMLConfiguration();
    config.setListDelimiter('|');

    /*
     * Initialize the Command-Line parsing engine.
     */
    CommandLineParser parser = new PosixParser();
    Options opts = new Options();
    opts.addOption(OptionBuilder.withLongOpt("config-file").hasArg()
            .withDescription("The configuration file to load").withArgName("config.xml").create("c"));

    opts.addOption(OptionBuilder.withLongOpt("profile").hasArg().withDescription("The profile to use")
            .withArgName("Default").create("p"));

    opts.addOption(OptionBuilder.withLongOpt("password").hasArg().withDescription("Password to connect with")
            .withArgName("password").create("P"));

    opts.addOption(OptionBuilder.withLongOpt("debug").hasArg(false).create('d'));

    opts.addOption(OptionBuilder.withLongOpt("verbose").hasArg(false).create('v'));

    File configurationFile = new File("config.xml");

    try {
        // Parse the command-line options
        CommandLine cmds = parser.parse(opts, args);

        if (!cmds.hasOption('p')) {
            Logger.getRootLogger().addAppender(new GuiErrorAlerter(Level.ERROR));
        }

        Logger.getRootLogger().setLevel(Level.ERROR);
        if (cmds.hasOption('v')) {
            Logger.getRootLogger().setLevel(Level.INFO);
        }
        if (cmds.hasOption('d')) {
            Logger.getRootLogger().setLevel(Level.DEBUG);
        }

        log.debug("Enabling configuration file parsing");
        // The user has given us a file to parse.
        if (cmds.hasOption("c")) {
            configurationFile = new File(cmds.getOptionValue("c"));
        }
        log.debug("Config file: " + configurationFile);

        // Load the configuration file
        if (configurationFile.exists()) {
            config.load(configurationFile);
        } else {
            log.error("Cannot find config file");
        }

        /*
         * Convert the profiles into memory
         */
        Vector<ConnectionProfile> profs = new Vector<ConnectionProfile>();
        List<?> profList = config.configurationAt("Profiles").configurationsAt("Profile");
        for (Object p : profList) {
            SubnodeConfiguration profile = (SubnodeConfiguration) p;
            String name = profile.getString("[@name]");
            String auth = profile.getString("LdapAuthString");
            String server = profile.getString("LdapServerString");
            String group = profile.getString("LdapGroupsLocation");
            ConnectionProfile prof = new ConnectionProfile(name, server, auth, group);
            profs.add(prof);
        }
        ConnectionProfile prof = null;
        if (!cmds.hasOption('p')) {
            /*
             * Deploy the profile selector, to select a profile
             */
            ProfileSelector profSel = new ProfileSelector(profs);
            prof = profSel.getSelection();
            if (prof == null) {
                return;
            }
            /*
             * Empty the profiles and load a clean copy - then save it back
             * to the file
             */
            config.clearTree("Profiles");
            for (ConnectionProfile p : profSel.getProfiles()) {
                config.addProperty("Profiles.Profile(-1)[@name]", p.getName());
                config.addProperty("Profiles.Profile.LdapAuthString", p.getLdapAuthString());
                config.addProperty("Profiles.Profile.LdapServerString", p.getLdapServerString());
                config.addProperty("Profiles.Profile.LdapGroupsLocation", p.getLdapGroupsString());
            }
            config.save(configurationFile);
        } else {
            for (ConnectionProfile p : profs) {
                if (p.getName().equals(cmds.getOptionValue('p'))) {
                    prof = p;
                    break;
                }
            }
        }

        log.info("User selected " + prof);

        String password = "";
        if (cmds.hasOption('P')) {
            password = cmds.getOptionValue('P');
        } else {
            password = PasswordPrompter.promptForPassword("Password?");
        }

        if (password.equals("")) {
            return;
        }

        LdapInterface ldap = new LdapInterface(prof.getLdapServerString(), prof.getLdapAuthString(),
                prof.getLdapGroupsString(), password);

        /*
         * Gather options information from the configuration engine for the
         * specified report.
         */
        Hashtable<String, Hashtable<String, ReportOption>> reportDataStructure = new Hashtable<String, Hashtable<String, ReportOption>>();
        List<?> repConfig = config.configurationAt("Reports").configurationsAt("Report");
        for (Object p : repConfig) {
            SubnodeConfiguration repNode = (SubnodeConfiguration) p;

            // TODO Do something with the report profile.
            // Allowing the user to deploy "profiles" is a nice feature
            // String profile = repNode.getString("[@profile]");

            String reportName = repNode.getString("[@report]");
            Hashtable<String, ReportOption> reportOptions = new Hashtable<String, ReportOption>();
            reportDataStructure.put(reportName, reportOptions);
            // Loop through the options and add each to the table.
            for (Object o : repNode.configurationsAt("option")) {
                SubnodeConfiguration option = (SubnodeConfiguration) o;
                String name = option.getString("[@name]");
                String type = option.getString("[@type]");
                String value = option.getString("[@value]");

                ReportOption ro = new ReportOption();
                ro.setName(name);

                if (type.toLowerCase().equals("boolean")) {
                    ro.setBoolValue(Boolean.parseBoolean(value));
                } else if (type.toLowerCase().equals("integer")) {
                    ro.setIntValue(Integer.valueOf(value));
                } else {
                    // Assume a string type here then.
                    ro.setStrValue(value);
                }
                reportOptions.put(name, ro);
                log.debug(ro);
            }
        }
        System.out.println(reportDataStructure);

        /*
         * At this point, we now need to deploy the reports window to have
         * the user pick a report and select some happy options to allow
         * that report to work. Let's go.
         */
        /*
         * Deploy the Reports selector, to select a report
         */
        Reports.getInstance().setLdapConnection(ldap);
        ReportsWindow reports = new ReportsWindow(Reports.getInstance().getAllReports(), reportDataStructure);
        Report report = reports.getSelection();
        if (report == null) {
            return;
        }
        /*
         * Empty the profiles and load a clean copy - then save it back to
         * the file
         */
        config.clearTree("Reports");
        for (Report r : Reports.getInstance().getAllReports()) {
            config.addProperty("Reports.Report(-1)[@report]", r.getClass().getCanonicalName());
            config.addProperty("Reports.Report[@name]", "Standard");
            for (ReportOption ro : r.getOptions().values()) {
                config.addProperty("Reports.Report.option(-1)[@name]", ro.getName());
                config.addProperty("Reports.Report.option[@type]", ro.getType());
                config.addProperty("Reports.Report.option[@value]", ro.getStrValue());
            }
        }
        config.save(configurationFile);
        ProgressBar bar = new ProgressBar();
        bar.start();
        report.execute();
        ASCIIFormatter format = new ASCIIFormatter();
        ReportResult res = report.getResult();
        format.format(res, new File(res.getForName() + "_" + res.getReportName() + ".txt"));
        bar.stop();

        JOptionPane.showMessageDialog(null,
                "The report is at " + res.getForName() + "_" + res.getReportName() + ".txt", "Success",
                JOptionPane.INFORMATION_MESSAGE);

    } catch (ParseException e) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("FAST Ldap Searcher", opts);
    } catch (ConfigurationException e) {
        e.printStackTrace();
        log.fatal("OH EM GEES!  Configuration errors.");
    } catch (Exception e) {
        e.printStackTrace();
    }

}