Example usage for java.util List add

List of usage examples for java.util List add

Introduction

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

Prototype

boolean add(E e);

Source Link

Document

Appends the specified element to the end of this list (optional operation).

Usage

From source file:com.sangupta.keepwalking.MergeRepo.java

/**
 * @param args//  www . java 2s.  com
 * @throws IOException 
 */
public static void main(String[] args) throws IOException {
    if (args.length != 3) {
        usage();
        return;
    }

    final String previousRepo = args[0];
    final String newerRepo = args[1];
    final String mergedRepo = args[2];

    final File previous = new File(previousRepo);
    final File newer = new File(newerRepo);
    final File merged = new File(mergedRepo);

    if (!(previous.exists() && previous.isDirectory())) {
        System.out.println("The previous version does not exists or is not a directory.");
        return;
    }

    if (!(newer.exists() && newer.isDirectory())) {
        System.out.println("The newer version does not exists or is not a directory.");
        return;
    }

    final IOFileFilter directoryFilter = FileFilterUtils.makeCVSAware(FileFilterUtils.makeSVNAware(null));

    final Collection<File> olderFiles = FileUtils.listFiles(previous, TrueFileFilter.TRUE, directoryFilter);
    final Collection<File> newerFiles = FileUtils.listFiles(newer, TrueFileFilter.TRUE, directoryFilter);

    // build a list of unique paths
    System.out.println("Reading files from older version...");
    List<String> olderPaths = new ArrayList<String>();
    for (File oldFile : olderFiles) {
        olderPaths.add(getRelativePath(oldFile, previous));
    }

    System.out.println("Reading files from newer version...");
    List<String> newerPaths = new ArrayList<String>();
    for (File newerFile : newerFiles) {
        newerPaths.add(getRelativePath(newerFile, newer));
    }

    // find which files have been removed from Perforce depot
    List<String> filesRemoved = new ArrayList<String>(olderPaths);
    filesRemoved.removeAll(newerPaths);
    System.out.println("Files removed in newer version: " + filesRemoved.size());
    for (String removed : filesRemoved) {
        System.out.print("    ");
        System.out.println(removed);
    }

    // find which files have been added in Perforce depot
    List<String> filesAdded = new ArrayList<String>(newerPaths);
    filesAdded.removeAll(olderPaths);
    System.out.println("Files added in newer version: " + filesAdded.size());
    for (String added : filesAdded) {
        System.out.print("    ");
        System.out.println(added);
    }

    // find which files are common 
    // now check if they have modified or not
    newerPaths.retainAll(olderPaths);
    List<String> modified = checkModifiedFiles(newerPaths, previous, newer);
    System.out.println("Files modified in newer version: " + modified.size());
    for (String modify : modified) {
        System.out.print("    ");
        System.out.println(modify);
    }

    // clean any previous existence of merged repo
    System.out.println("Cleaning any previous merged repositories...");
    if (merged.exists() && merged.isDirectory()) {
        FileUtils.deleteDirectory(merged);
    }

    System.out.println("Merging from newer to older repository...");
    // copy the original SVN repo to merged
    FileUtils.copyDirectory(previous, merged);

    // now remove all files that need to be
    for (String removed : filesRemoved) {
        File toRemove = new File(merged, removed);
        toRemove.delete();
    }

    // now add all files that are new in perforce
    for (String added : filesAdded) {
        File toAdd = new File(newer, added);
        File destination = new File(merged, added);
        FileUtils.copyFile(toAdd, destination);
    }

    // now over-write modified files
    for (String changed : modified) {
        File change = new File(newer, changed);
        File destination = new File(merged, changed);
        destination.delete();
        FileUtils.copyFile(change, destination);
    }

    System.out.println("Done merging.");
}

From source file:ee.ria.xroad.common.signature.BatchSignerIntegrationTest.java

/**
 * Main program entry point.//from   w  w w . j a v a  2  s.c o  m
 * @param args command-line arguments
 * @throws Exception in case of any errors
 */
public static void main(String[] args) throws Exception {
    if (args.length == 0) {
        printUsage();

        return;
    }

    ActorSystem actorSystem = ActorSystem.create("Proxy", ConfigFactory.load().getConfig("proxy"));
    SignerClient.init(actorSystem);

    Thread.sleep(SIGNER_INIT_DELAY); // wait for signer client to connect

    BatchSigner.init(actorSystem);

    X509Certificate subjectCert = TestCertUtil.getConsumer().cert;
    X509Certificate issuerCert = TestCertUtil.getCaCert();
    X509Certificate signerCert = TestCertUtil.getOcspSigner().cert;
    PrivateKey signerKey = TestCertUtil.getOcspSigner().key;

    List<String> messages = new ArrayList<>();

    for (String arg : args) {
        messages.add(FileUtils.readFileToString(new File(arg)));
    }

    latch = new CountDownLatch(messages.size());

    Date thisUpdate = new DateTime().plusDays(1).toDate();
    final OCSPResp ocsp = OcspTestUtils.createOCSPResponse(subjectCert, issuerCert, signerCert, signerKey,
            CertificateStatus.GOOD, thisUpdate, null);

    for (final String message : messages) {
        new Thread(() -> {
            try {
                byte[] hash = hash(message);
                log.info("File: {}, hash: {}", message, hash);

                MessagePart hashPart = new MessagePart(MessageFileNames.MESSAGE, SHA512_ID,
                        calculateDigest(SHA512_ID, message.getBytes()), message.getBytes());

                List<MessagePart> hashes = Collections.singletonList(hashPart);

                SignatureBuilder builder = new SignatureBuilder();
                builder.addPart(hashPart);

                builder.setSigningCert(subjectCert);
                builder.addOcspResponses(Collections.singletonList(ocsp));

                log.info("### Calculating signature...");

                SignatureData signatureData = builder.build(
                        new SignerSigningKey(KEY_ID, CryptoUtils.CKM_RSA_PKCS_NAME), CryptoUtils.SHA512_ID);

                synchronized (sigIdx) {
                    log.info("### Created signature: {}", signatureData.getSignatureXml());

                    log.info("HashChainResult: {}", signatureData.getHashChainResult());
                    log.info("HashChain: {}", signatureData.getHashChain());

                    toFile("message-" + sigIdx + ".xml", message);

                    String sigFileName = signatureData.getHashChainResult() != null ? "batch-sig-" : "sig-";

                    toFile(sigFileName + sigIdx + ".xml", signatureData.getSignatureXml());

                    if (signatureData.getHashChainResult() != null) {
                        toFile("hash-chain-" + sigIdx + ".xml", signatureData.getHashChain());
                        toFile("hash-chain-result.xml", signatureData.getHashChainResult());
                    }

                    sigIdx++;
                }

                try {
                    verify(signatureData, hashes, message);

                    log.info("Verification successful (message hash: {})", hash);
                } catch (Exception e) {
                    log.error("Verification failed (message hash: {})", hash, e);
                }
            } catch (Exception e) {
                log.error("Error", e);
            } finally {
                latch.countDown();
            }
        }).start();
    }

    latch.await();
    actorSystem.shutdown();
}

From source file:be.ugent.maf.cellmissy.gui.controller.MSDGenerator.java

public static void main(String[] args) {
    // get the application context
    ApplicationContext context = ApplicationContextProvider.getInstance().getApplicationContext();
    // get the services we need
    ExperimentService experimentService = (ExperimentService) context.getBean("experimentService");
    ProjectService projectService = (ProjectService) context.getBean("projectService");
    WellService wellService = (WellService) context.getBean("wellService");
    SingleCellConditionPreProcessor singleCellConditionPreProcessor = (SingleCellConditionPreProcessor) context
            .getBean("singleCellConditionPreProcessor");
    SingleCellConditionOperator singleCellConditionOperator = (SingleCellConditionOperator) context
            .getBean("singleCellConditionOperator");
    // get all the experiments from DB
    Project project = projectService.findById(4L);
    List<Experiment> experiments = experimentService.findExperimentsByProjectId(project.getProjectid());
    // root folder
    File folder = new File("C:\\Users\\Paola\\Desktop\\benchmark\\cellmissy");

    for (Experiment experiment : experiments) {
        if (experiment.getExperimentNumber() == 1) {
            List<List<TrackDataHolder>> biologicalConditions = new ArrayList<>();
            double instrumentConversionFactor = experiment.getInstrument().getConversionFactor();
            double magnificationValue = experiment.getMagnification().getMagnificationValue();
            double conversionFactor = instrumentConversionFactor * magnificationValue / 10;
            // fetch the migration data
            System.out//from ww w  . ja v a2s.c o m
                    .println("fetching data for project: " + project + ", experiment: " + experiment + " ...");
            for (PlateCondition plateCondition : experiment.getPlateConditionList()) {
                List<Well> wells = new ArrayList<>();
                for (Well well : plateCondition.getWellList()) {
                    Well fetchedWell = wellService.fetchMigrationData(well.getWellid());
                    wells.add(fetchedWell);
                }
                plateCondition.setWellList(wells);
            }

            for (PlateCondition plateCondition : experiment.getPlateConditionList()) {
                // create a new object to hold pre-processing results
                SingleCellConditionDataHolder singleCellConditionDataHolder = new SingleCellConditionDataHolder(
                        plateCondition);
                System.out.println("****************computations started for condition: " + plateCondition);
                // do the computations

                singleCellConditionPreProcessor.generateDataHolders(singleCellConditionDataHolder);
                singleCellConditionPreProcessor.generateDataStructure(singleCellConditionDataHolder);
                singleCellConditionPreProcessor.preProcessStepsAndCells(singleCellConditionDataHolder,
                        conversionFactor, experiment.getExperimentInterval());
                singleCellConditionPreProcessor
                        .generateRawTrackCoordinatesMatrix(singleCellConditionDataHolder);
                singleCellConditionPreProcessor
                        .generateShiftedTrackCoordinatesMatrix(singleCellConditionDataHolder);
                singleCellConditionOperator.operateOnStepsAndCells(singleCellConditionDataHolder);

                List<TrackDataHolder> trackDataHolders = singleCellConditionDataHolder.getTrackDataHolders();
                biologicalConditions.add(trackDataHolders);
            }

            try (BufferedWriter bufferedWriter = new BufferedWriter(
                    new FileWriter(new File(folder, "bench_msd.txt")))) {
                // header of the file
                bufferedWriter.append("traj_id" + " " + "t_lag" + " " + "msd");
                bufferedWriter.newLine();
                for (List<TrackDataHolder> conditionTracks : biologicalConditions) {
                    for (TrackDataHolder trackDataHolder : conditionTracks) {
                        StepCentricDataHolder stepCentricDataHolder = trackDataHolder
                                .getStepCentricDataHolder();
                        double[][] msd = stepCentricDataHolder.getMSD();
                        for (int i = 0; i < msd.length; i++) {
                            bufferedWriter.append("" + stepCentricDataHolder.getTrack().getTrackid());
                            bufferedWriter.append(" ");
                            bufferedWriter.append("" + msd[i][0]);
                            bufferedWriter.append(" ");
                            bufferedWriter.append("" + msd[i][1]);
                            bufferedWriter.newLine();
                        }
                    }
                }
                System.out.println("txt file succ. created!");
            } catch (IOException ex) {
            }
        }
    }
}

From source file:kafka.benchmark.AdvertisingTopology.java

public static void main(final String[] args) throws Exception {
    Options opts = new Options();
    opts.addOption("conf", true, "Path to the config file.");

    CommandLineParser parser = new DefaultParser();
    CommandLine cmd = parser.parse(opts, args);
    String configPath = cmd.getOptionValue("conf");
    Map<?, ?> conf = Utils.findAndReadConfigFile(configPath, true);

    Map<String, ?> benchmarkParams = getKafkaConfs(conf);

    LOG.info("conf: {}", conf);
    LOG.info("Parameters used: {}", benchmarkParams);

    KStreamBuilder builder = new KStreamBuilder();
    //        builder.addStateStore(
    //                Stores.create("config-params")
    //                .withStringKeys().withStringValues()
    //                .inMemory().maxEntries(10).build(), "redis");

    String topicsArr[] = { (String) benchmarkParams.get("topic") };
    KStream<String, ?> source1 = builder.stream(topicsArr);

    Properties props = new Properties();
    props.putAll(benchmarkParams);//from w  w  w. j a va2s  .c o  m
    //        props.put(StreamsConfig.APPLICATION_ID_CONFIG, "kafka-benchmarks");
    //        props.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
    ////        props.put(StreamsConfig.ZOOKEEPER_CONNECT_CONFIG, "localhost:2181");
    props.put(StreamsConfig.KEY_SERDE_CLASS_CONFIG, Serdes.String().getClass().getName());
    props.put(StreamsConfig.VALUE_SERDE_CLASS_CONFIG, Serdes.String().getClass().getName());

    // setting offset reset to earliest so that we can re-run the demo code with the same pre-loaded data
    //        props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");

    source1
            // Parse the String as JSON
            .mapValues(input -> {
                JSONObject obj = new JSONObject(input.toString());
                //System.out.println(obj.toString());
                String[] tuple = { obj.getString("user_id"), obj.getString("page_id"), obj.getString("ad_id"),
                        obj.getString("ad_type"), obj.getString("event_type"), obj.getString("event_time"),
                        obj.getString("ip_address") };
                return tuple;
            })

            // Filter the records if event type is "view"
            .filter(new Predicate<String, String[]>() {
                @Override
                public boolean test(String key, String[] value) {
                    return value[4].equals("view"); // "event_type"
                }
            })

            // project the event
            .mapValues(input -> {
                String[] arr = (String[]) input;
                return new String[] { arr[2], arr[5] }; // "ad_id" and "event_time"
            })

            // perform join with redis data
            .transformValues(new RedisJoinBolt(benchmarkParams)).filter((key, value) -> value != null)

            // create key from value
            .map((key, value) -> {
                String[] arr = (String[]) value;
                return new KeyValue<String, String[]>(arr[0], arr);
            })

            // process campaign
            .aggregateByKey(new Initializer<List<String[]>>() {
                @Override
                public List<String[]> apply() {
                    return new ArrayList<String[]>();
                }
            }, new Aggregator<String, String[], List<String[]>>() {
                @Override
                public List<String[]> apply(String aggKey, String[] value, List<String[]> aggregate) {
                    aggregate.add(value);
                    return aggregate;
                }
            },
                    // UnlimitedWindows.of("kafka-test-unlim"),
                    // HoppingWindows.of("kafka-test-hopping").with(12L).every(5L),
                    TumblingWindows.of("kafka-test-tumbling").with(WINDOW_SIZE), strSerde, arrSerde)
            .toStream().process(new CampaignProcessor(benchmarkParams));

    KafkaStreams streams = new KafkaStreams(builder, props);
    streams.start();
}

From source file:net.landora.justintv.JustinTVAPI.java

public static void main(String[] args) throws Exception {
    List<JustinArchive> archives = readArchives("tsmtournaments", 64);
    Map<String, List<JustinArchive>> groups = new HashMap<String, List<JustinArchive>>();
    for (int i = 0; i < archives.size(); i++) {
        JustinArchive archive = archives.get(i);
        List<JustinArchive> group = groups.get(archive.getBroadcastId());
        if (group == null) {
            group = new ArrayList<JustinArchive>(archive.getBroadcastPart());
            groups.put(archive.getBroadcastId(), group);
        }/*  w  w  w.  j av  a 2s .com*/
        group.add(archive);
    }

    BroadcastSorter sorter = new BroadcastSorter();

    for (List<JustinArchive> group : groups.values()) {
        Collections.sort(group, sorter);

        JustinArchive base = group.get(group.size() - 1);

        StringBuffer cmd = new StringBuffer();
        cmd.append("mkvmerge -o \"");
        cmd.append(base.getBroadcastId());
        cmd.append(" - ");
        cmd.append(base.getTitle());
        cmd.append("\" ");

        for (int i = 0; i < group.size(); i++) {
            JustinArchive archive = group.get(i);
            if (i > 0)
                cmd.append("+ ");

            cmd.append(archive.getId());
            cmd.append(".mkv ");
        }
        System.out.println(cmd);
    }
}

From source file:com.mirth.connect.server.launcher.MirthLauncher.java

public static void main(String[] args) {
    try {//from  w  ww. j a va 2  s  .  c o  m
        try {
            uninstallPendingExtensions();
            installPendingExtensions();
        } catch (Exception e) {
            logger.error("Error uninstalling or installing pending extensions.", e);
        }

        Properties mirthProperties = new Properties();
        String includeCustomLib = null;

        try {
            mirthProperties.load(new FileInputStream(new File(MIRTH_PROPERTIES_FILE)));
            includeCustomLib = mirthProperties.getProperty(PROPERTY_INCLUDE_CUSTOM_LIB);
            createAppdataDir(mirthProperties);
        } catch (Exception e) {
            logger.error("Error creating the appdata directory.", e);
        }

        ManifestFile mirthServerJar = new ManifestFile("server-lib/mirth-server.jar");
        ManifestFile mirthClientCoreJar = new ManifestFile("server-lib/mirth-client-core.jar");
        ManifestDirectory serverLibDir = new ManifestDirectory("server-lib");
        serverLibDir.setExcludes(new String[] { "mirth-client-core.jar" });

        List<ManifestEntry> manifestList = new ArrayList<ManifestEntry>();
        manifestList.add(mirthServerJar);
        manifestList.add(mirthClientCoreJar);
        manifestList.add(serverLibDir);

        // We want to include custom-lib if the property isn't found, or if it equals "true"
        if (includeCustomLib == null || Boolean.valueOf(includeCustomLib)) {
            manifestList.add(new ManifestDirectory("custom-lib"));
        }

        ManifestEntry[] manifest = manifestList.toArray(new ManifestEntry[manifestList.size()]);

        // Get the current server version
        JarFile mirthClientCoreJarFile = new JarFile(mirthClientCoreJar.getName());
        Properties versionProperties = new Properties();
        versionProperties.load(mirthClientCoreJarFile
                .getInputStream(mirthClientCoreJarFile.getJarEntry("version.properties")));
        String currentVersion = versionProperties.getProperty("mirth.version");

        List<URL> classpathUrls = new ArrayList<URL>();
        addManifestToClasspath(manifest, classpathUrls);
        addExtensionsToClasspath(classpathUrls, currentVersion);
        URLClassLoader classLoader = new URLClassLoader(classpathUrls.toArray(new URL[classpathUrls.size()]));
        Class<?> mirthClass = classLoader.loadClass("com.mirth.connect.server.Mirth");
        Thread mirthThread = (Thread) mirthClass.newInstance();
        mirthThread.setContextClassLoader(classLoader);
        mirthThread.start();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:simauthenticator.SimAuthenticator.java

/**
 * @param args the command line arguments
 *///  www. j  a v a2s  .com
public static void main(String[] args) throws Exception {

    cliOpts = new Options();
    cliOpts.addOption("U", "url", true, "Connection URL");
    cliOpts.addOption("u", "user", true, "User name");
    cliOpts.addOption("p", "password", true, "User password");
    cliOpts.addOption("d", "domain", true, "Domain name");
    cliOpts.addOption("v", "verbose", false, "Verbose output");
    cliOpts.addOption("k", "keystore", true, "KeyStore path");
    cliOpts.addOption("K", "keystorepass", true, "KeyStore password");
    cliOpts.addOption("h", "help", false, "Print help info");

    CommandLineParser clip = new GnuParser();
    cmd = clip.parse(cliOpts, args);

    if (cmd.hasOption("help")) {
        help();
        return;
    } else {
        boolean valid = init(args);
        if (!valid) {
            return;
        }
    }

    HttpClientContext clientContext = HttpClientContext.create();

    KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
    char[] keystorePassword = passwk.toCharArray();
    FileInputStream kfis = null;
    try {
        kfis = new FileInputStream(keyStorePath);
        ks.load(kfis, keystorePassword);
    } finally {
        if (kfis != null) {
            kfis.close();
        }
    }

    SSLContext sslContext = SSLContexts.custom().useSSL().loadTrustMaterial(ks).build();
    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext);

    HttpClientBuilder httpClientBuilder = HttpClientBuilder.create().setSslcontext(sslContext)
            .setSSLSocketFactory(sslsf).setUserAgent(userAgent);
    ;

    cookieStore = new BasicCookieStore();
    /* BasicClientCookie cookie = new BasicClientCookie("SIM authenticator", "Utility for getting event details");
     cookie.setVersion(0);
     cookie.setDomain(".astelit.ukr");
     cookie.setPath("/");
     cookieStore.addCookie(cookie);*/

    CloseableHttpClient client = httpClientBuilder.build();

    try {

        NTCredentials creds = new NTCredentials(usern, passwu, InetAddress.getLocalHost().getHostName(),
                domain);
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(AuthScope.ANY, creds);
        HttpClientContext context = HttpClientContext.create();
        context.setCredentialsProvider(credsProvider);
        context.setCookieStore(cookieStore);
        HttpGet httpget = new HttpGet(eventUrl);
        if (verbose) {
            System.out.println("executing request " + httpget.getRequestLine());
        }
        HttpResponse response = client.execute(httpget, context);
        HttpEntity entity = response.getEntity();

        HttpPost httppost = new HttpPost(eventUrl);
        List<Cookie> cookies = cookieStore.getCookies();

        if (verbose) {
            System.out.println("----------------------------------------------");
            System.out.println(response.getStatusLine());
            System.out.print("Initial set of cookies: ");
            if (cookies.isEmpty()) {
                System.out.println("none");
            } else {
                for (int i = 0; i < cookies.size(); i++) {
                    System.out.println("- " + cookies.get(i).toString());
                }
            }
        }

        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair("usernameInput", usern));
        nvps.add(new BasicNameValuePair("passwordInput", passwu));
        nvps.add(new BasicNameValuePair("domainInput", domain));
        //nvps.add(new BasicNameValuePair("j_username", domain + "\\" + usern));
        //nvps.add(new BasicNameValuePair("j_password", ipAddr + ";" + passwu));
        if (entity != null && verbose) {
            System.out.println("Responce content length: " + entity.getContentLength());

        }

        //System.out.println(EntityUtils.toString(entity));

        httppost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));

        HttpResponse afterPostResponse = client.execute(httppost, context);
        HttpEntity afterPostEntity = afterPostResponse.getEntity();
        cookies = cookieStore.getCookies();
        if (entity != null && verbose) {
            System.out.println("----------------------------------------------");
            System.out.println(afterPostResponse.getStatusLine());
            System.out.println("Responce content length: " + afterPostEntity.getContentLength());
            System.out.print("After POST set of cookies: ");
            if (cookies.isEmpty()) {
                System.out.println("none");
            } else {
                for (int i = 0; i < cookies.size(); i++) {
                    System.out.println("- " + cookies.get(i).toString());
                }
            }
        }

        System.out.println(EntityUtils.toString(afterPostEntity));
        EntityUtils.consume(entity);
        EntityUtils.consume(afterPostEntity);

    } finally {

        client.getConnectionManager().shutdown();
    }

}

From source file:org.sbq.batch.mains.ActivityEmulator.java

public static void main(String[] vars) throws IOException {
    System.out.println("ActivityEmulator - STARTED.");
    ActivityEmulator activityEmulator = new ActivityEmulator();
    activityEmulator.begin();/*from ww w .java  2  s .c  o m*/
    System.out.println("Enter your command: >");
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    String command = null;
    while (!"stop".equals(command = in.readLine())) {
        if ("status".equals(command)) {
            List<String> onlineUsers = new LinkedList<String>();
            for (Map.Entry<String, AtomicBoolean> entry : activityEmulator.getUserStatusByLogin().entrySet()) {
                if (entry.getValue().get()) {
                    onlineUsers.add(entry.getKey());
                }
            }
            System.out.println("Users online: " + Arrays.toString(onlineUsers.toArray()));
            System.out.println("Number of cycles left: " + activityEmulator.getBlockingQueue().size());

        }
        System.out.println("Enter your command: >");
    }
    activityEmulator.stop();
    System.out.println("ActivityEmulator - STOPPED.");
}

From source file:drmaas.sandbox.http.LoginTest.java

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

    //1. For SSL/*from w w  w.j  a v  a2 s  .  c om*/
    DefaultHttpClient base = new DefaultHttpClient();
    SSLContext ctx = SSLContext.getInstance("TLS");

    X509TrustManager tm = new X509TrustManager() {
        public void checkClientTrusted(X509Certificate[] xcs, String string) throws CertificateException {
        }

        public void checkServerTrusted(X509Certificate[] xcs, String string) throws CertificateException {
        }

        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }
    };

    X509HostnameVerifier verifier = new X509HostnameVerifier() {

        @Override
        public void verify(String string, SSLSocket ssls) throws IOException {
        }

        @Override
        public void verify(String string, X509Certificate xc) throws SSLException {
        }

        @Override
        public void verify(String string, String[] strings, String[] strings1) throws SSLException {
        }

        @Override
        public boolean verify(String string, SSLSession ssls) {
            return true;
        }
    };

    ctx.init(null, new TrustManager[] { tm }, null);
    SSLSocketFactory ssf = new SSLSocketFactory(ctx, verifier);
    ClientConnectionManager ccm = base.getConnectionManager();
    SchemeRegistry sr = ccm.getSchemeRegistry();
    sr.register(new Scheme("https", 443, ssf));
    DefaultHttpClient httpclient = new DefaultHttpClient(ccm, base.getParams());
    httpclient.setRedirectStrategy(new LaxRedirectStrategy());

    try {
        HttpPost httpost;
        HttpResponse response;
        HttpEntity entity;
        List<Cookie> cookies;
        BufferedReader rd;
        String line;
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();

        //log in
        httpost = new HttpPost("myloginurl");

        nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair("login", "Log In"));
        nvps.add(new BasicNameValuePair("os_username", "foo"));
        nvps.add(new BasicNameValuePair("os_password", "foobar"));
        nvps.add(new BasicNameValuePair("os_cookie", "true"));
        nvps.add(new BasicNameValuePair("os_destination", ""));

        httpost.setEntity(new UrlEncodedFormEntity(nvps));
        response = httpclient.execute(httpost);
        System.out.println(response.toString());
        rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
        line = "";
        while ((line = rd.readLine()) != null) {
            System.out.println(line);
        }

    } finally {
        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        httpclient.getConnectionManager().shutdown();
    }
}

From source file:alluxio.master.journal.JournalUpgrader.java

/**
 * Reads a journal via/*from   w  ww .  j  a v a 2s.com*/
 * {@code java -cp \
 * assembly/server/target/alluxio-assembly-server-<ALLUXIO-VERSION>-jar-with-dependencies.jar \
 * alluxio.master.journal.JournalUpgrader -master BlockMaster}.
 *
 * @param args arguments passed to the tool
 */
public static void main(String[] args) {
    if (!parseInputArgs(args)) {
        usage();
        System.exit(EXIT_FAILED);
    }
    if (sHelp) {
        usage();
        System.exit(EXIT_SUCCEEDED);
    }

    List<String> masters = new ArrayList<>();
    for (MasterFactory factory : ServiceUtils.getMasterServiceLoader()) {
        masters.add(factory.getName());
    }

    for (String master : masters) {
        Upgrader upgrader = new Upgrader(master);
        try {
            upgrader.upgrade();
        } catch (IOException e) {
            LOG.error("Failed to upgrade the journal for {}.", master, e);
            System.exit(EXIT_FAILED);
        }
    }
}