Example usage for java.lang String toCharArray

List of usage examples for java.lang String toCharArray

Introduction

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

Prototype

public char[] toCharArray() 

Source Link

Document

Converts this string to a new character array.

Usage

From source file:ch.swisscom.mid.verifier.MobileIdCmsVerifier.java

public static void main(String[] args) {

    if (args == null || args.length < 1) {
        System.out.println("Usage: ch.swisscom.mid.verifier.MobileIdCmsVerifier [OPTIONS]");
        System.out.println();/*from   w  w w .  j  a v  a 2s. com*/
        System.out.println("Options:");
        System.out.println(
                "  -cms=VALUE or -stdin   - base64 encoded CMS/PKCS7 signature string, either as VALUE or via standard input");
        System.out.println(
                "  -jks=VALUE             - optional path to truststore file (default is 'jks/truststore.jks')");
        System.out.println("  -jkspwd=VALUE          - optional truststore password (default is 'secret')");
        System.out.println();
        System.out.println("Example:");
        System.out.println("  java ch.swisscom.mid.verifier.MobileIdCmsVerifier -cms=MIII...");
        System.out.println("  echo -n MIII... | java ch.swisscom.mid.verifier.MobileIdCmsVerifier -stdin");
        System.exit(1);
    }

    try {

        MobileIdCmsVerifier verifier = null;

        String jks = "jks/truststore.jks";
        String jkspwd = "secret";

        String param;
        for (int i = 0; i < args.length; i++) {
            param = args[i].toLowerCase();
            if (param.contains("-jks=")) {
                jks = args[i].substring(args[i].indexOf("=") + 1).trim();
            } else if (param.contains("-jkspwd=")) {
                jkspwd = args[i].substring(args[i].indexOf("=") + 1).trim();
            } else if (param.contains("-cms=")) {
                verifier = new MobileIdCmsVerifier(args[i].substring(args[i].indexOf("=") + 1).trim());
            } else if (param.contains("-stdin")) {
                BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
                String stdin;
                if ((stdin = in.readLine()) != null && stdin.length() != 0)
                    verifier = new MobileIdCmsVerifier(stdin.trim());
            }
        }

        KeyStore keyStore = KeyStore.getInstance("JKS");
        keyStore.load(new FileInputStream(jks), jkspwd.toCharArray());

        // If you are behind a Proxy..
        // System.setProperty("proxyHost", "10.185.32.54");
        // System.setProperty("proxyPort", "8079");
        // or set it via VM arguments: -DproxySet=true -DproxyHost=10.185.32.54 -DproxyPort=8079

        // Print Issuer/SubjectDN/SerialNumber of all x509 certificates that can be found in the CMSSignedData
        verifier.printAllX509Certificates();

        // Print Signer's X509 Certificate Details
        System.out.println("X509 SignerCert SerialNumber: " + verifier.getX509SerialNumber());
        System.out.println("X509 SignerCert Issuer: " + verifier.getX509IssuerDN());
        System.out.println("X509 SignerCert Subject DN: " + verifier.getX509SubjectDN());
        System.out.println("X509 SignerCert Validity Not Before: " + verifier.getX509NotBefore());
        System.out.println("X509 SignerCert Validity Not After: " + verifier.getX509NotAfter());
        System.out.println("X509 SignerCert Validity currently valid: " + verifier.isCertCurrentlyValid());

        System.out.println("User's unique Mobile ID SerialNumber: " + verifier.getMIDSerialNumber());

        // Print signed content (should be equal to the DTBS Message of the Signature Request)
        System.out.println("Signed Data: " + verifier.getSignedData());

        // Verify the signature on the SignerInformation object
        System.out.println("Signature Valid: " + verifier.isVerified());

        // Validate certificate path against trust anchor incl. OCSP revocation check
        System.out.println("X509 SignerCert Valid (Path+OCSP): " + verifier.isCertValid(keyStore));

    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.tremolosecurity.openunison.util.OpenUnisonUtils.java

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

    logger = org.apache.logging.log4j.LogManager.getLogger(OpenUnisonUtils.class.getName());

    Options options = new Options();
    options.addOption("unisonXMLFile", true, "The full path to the Unison xml file");
    options.addOption("keystorePath", true, "The full path to the Unison keystore");
    options.addOption("chainName", true, "The name of the authentication chain");
    options.addOption("mechanismName", true, "The name of the authentication mechanism for SAML2");
    options.addOption("idpName", true, "The name of the identity provider application");
    options.addOption("pathToMetaData", true, "The full path to the saml2 metadata file");
    options.addOption("createDefault", false, "If set, add default parameters");
    options.addOption("action", true,
            "export-sp-metadata, import-sp-metadata, export-secretkey, print-secretkey, import-idp-metadata, export-idp-metadata, clear-dlq, import-secretkey, create-secretkey");
    options.addOption("urlBase", true, "Base URL, no URI; https://host:port");
    options.addOption("alias", true, "Key alias");
    options.addOption("newKeystorePath", true, "Path to the new keystore");
    options.addOption("newKeystorePassword", true, "Password for the new keystore");
    options.addOption("help", false, "Prints this message");
    options.addOption("signMetadataWithKey", true, "Signs the metadata with the specified key");
    options.addOption("dlqName", true, "The name of the dead letter queue");
    options.addOption("upgradeFrom106", false, "Updates workflows from 1.0.6");
    options.addOption("secretkey", true, "base64 encoded secret key");
    options.addOption("envFile", true, "Environment variables for parmaterized configs");

    CommandLineParser parser = new DefaultParser();
    CommandLine cmd = parser.parse(options, args, true);

    if (args.length == 0 || cmd.hasOption("help")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("OpenUnisonUtils", options);
    }/*from  ww w.j a  va2s. co m*/

    logger.info("Loading Unison Configuration");
    String unisonXMLFile = loadOption(cmd, "unisonXMLFile", options);
    TremoloType ttRead = loadTremoloType(unisonXMLFile, cmd, options);

    String action = loadOption(cmd, "action", options);
    TremoloType ttWrite = null;
    if (action.equalsIgnoreCase("import-sp-metadata") || action.equalsIgnoreCase("import-idp-metadata")) {
        ttWrite = loadTremoloType(unisonXMLFile);
    }

    logger.info("Configuration loaded");

    logger.info("Loading the keystore...");
    String ksPath = loadOption(cmd, "keystorePath", options);

    KeyStore ks = loadKeyStore(ksPath, ttRead);

    logger.info("...loaded");

    if (action.equalsIgnoreCase("import-sp-metadata")) {

        importMetaData(options, cmd, unisonXMLFile, ttRead, ttWrite, ksPath, ks);
    } else if (action.equalsIgnoreCase("export-sp-metadata")) {
        exportSPMetaData(options, cmd, ttRead, ks);

    } else if (action.equalsIgnoreCase("print-secretkey")) {
        printSecreyKey(options, cmd, ttRead, ks);
    } else if (action.equalsIgnoreCase("import-secretkey")) {
        importSecreyKey(options, cmd, ttRead, ks, ksPath);
    } else if (action.equalsIgnoreCase("create-secretkey")) {
        Security.addProvider(new BouncyCastleProvider());
        logger.info("Creating AES-256 secret key");
        String alias = loadOption(cmd, "alias", options);
        logger.info("Alias : '" + alias + "'");
        KeyGenerator kg = KeyGenerator.getInstance("AES", "BC");
        kg.init(256, new SecureRandom());
        SecretKey sk = kg.generateKey();
        ks.setKeyEntry(alias, sk, ttRead.getKeyStorePassword().toCharArray(), null);
        logger.info("Saving key");
        ks.store(new FileOutputStream(ksPath), ttRead.getKeyStorePassword().toCharArray());
        logger.info("Finished");
    } else if (action.equalsIgnoreCase("export-secretkey")) {
        logger.info("Export Secret Key");

        logger.info("Loading key");
        String alias = loadOption(cmd, "alias", options);
        SecretKey key = (SecretKey) ks.getKey(alias, ttRead.getKeyStorePassword().toCharArray());
        logger.info("Loading new keystore path");
        String pathToNewKeystore = loadOption(cmd, "newKeystorePath", options);
        logger.info("Loading new keystore password");
        String ksPassword = loadOption(cmd, "newKeystorePassword", options);

        KeyStore newKS = KeyStore.getInstance("PKCS12");
        newKS.load(null, ttRead.getKeyStorePassword().toCharArray());
        newKS.setKeyEntry(alias, key, ksPassword.toCharArray(), null);
        newKS.store(new FileOutputStream(pathToNewKeystore), ksPassword.toCharArray());
        logger.info("Exported");
    } else if (action.equalsIgnoreCase("import-idp-metadata")) {
        importIdpMetadata(options, cmd, unisonXMLFile, ttRead, ttWrite, ksPath, ks);

    } else if (action.equalsIgnoreCase("export-idp-metadata")) {
        exportIdPMetadata(options, cmd, ttRead, ks);
    } else if (action.equalsIgnoreCase("clear-dlq")) {
        logger.info("Getting the DLQ Name...");
        String dlqName = loadOption(cmd, "dlqName", options);
        QueUtils.emptyDLQ(ttRead, dlqName);
    } else if (action.equalsIgnoreCase("upgradeFrom106")) {
        logger.info("Upgrading OpenUnison's configuration from 1.0.6");

        String backupFileName = unisonXMLFile + ".bak";

        logger.info("Backing up to '" + backupFileName + "'");

        BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(unisonXMLFile)));
        PrintWriter out = new PrintWriter(new FileOutputStream(backupFileName));
        String line = null;
        while ((line = in.readLine()) != null) {
            out.println(line);
        }
        out.flush();
        out.close();
        in.close();

        ByteArrayOutputStream bout = new ByteArrayOutputStream();
        AddChoiceToTasks.convert(new FileInputStream(unisonXMLFile), bout);
        FileOutputStream fsout = new FileOutputStream(unisonXMLFile);
        fsout.write(bout.toByteArray());
        fsout.flush();
        fsout.close();

    }

}

From source file:DcmSnd.java

@SuppressWarnings("unchecked")
public static void main(String[] args) {
    CommandLine cl = parse(args);/*  www .j a v a  2  s  . c  om*/
    DcmSnd dcmsnd = new DcmSnd();
    final List<String> argList = cl.getArgList();
    String remoteAE = argList.get(0);
    String[] calledAETAddress = split(remoteAE, '@');
    dcmsnd.setCalledAET(calledAETAddress[0]);
    if (calledAETAddress[1] == null) {
        dcmsnd.setRemoteHost("127.0.0.1");
        dcmsnd.setRemotePort(104);
    } else {
        String[] hostPort = split(calledAETAddress[1], ':');
        dcmsnd.setRemoteHost(hostPort[0]);
        dcmsnd.setRemotePort(toPort(hostPort[1]));
    }
    if (cl.hasOption("L")) {
        String localAE = cl.getOptionValue("L");
        String[] localPort = split(localAE, ':');
        if (localPort[1] != null) {
            dcmsnd.setLocalPort(toPort(localPort[1]));
        }
        String[] callingAETHost = split(localPort[0], '@');
        dcmsnd.setCalling(callingAETHost[0]);
        if (callingAETHost[1] != null) {
            dcmsnd.setLocalHost(callingAETHost[1]);
        }
    }
    dcmsnd.setOfferDefaultTransferSyntaxInSeparatePresentationContext(cl.hasOption("ts1"));
    dcmsnd.setSendFileRef(cl.hasOption("fileref"));
    if (cl.hasOption("username")) {
        String username = cl.getOptionValue("username");
        UserIdentity userId;
        if (cl.hasOption("passcode")) {
            String passcode = cl.getOptionValue("passcode");
            userId = new UserIdentity.UsernamePasscode(username, passcode.toCharArray());
        } else {
            userId = new UserIdentity.Username(username);
        }
        userId.setPositiveResponseRequested(cl.hasOption("uidnegrsp"));
        dcmsnd.setUserIdentity(userId);
    }
    dcmsnd.setStorageCommitment(cl.hasOption("stgcmt"));
    String remoteStgCmtAE = null;
    if (cl.hasOption("stgcmtae")) {
        try {
            remoteStgCmtAE = cl.getOptionValue("stgcmtae");
            String[] aet_hostport = split(remoteStgCmtAE, '@');
            String[] host_port = split(aet_hostport[1], ':');
            dcmsnd.setStgcmtCalledAET(aet_hostport[0]);
            dcmsnd.setRemoteStgcmtHost(host_port[0]);
            dcmsnd.setRemoteStgcmtPort(toPort(host_port[1]));
        } catch (Exception e) {
            exit("illegal argument of option -stgcmtae");
        }
    }
    if (cl.hasOption("connectTO"))
        dcmsnd.setConnectTimeout(parseInt(cl.getOptionValue("connectTO"),
                "illegal argument of option -connectTO", 1, Integer.MAX_VALUE));
    if (cl.hasOption("reaper"))
        dcmsnd.setAssociationReaperPeriod(parseInt(cl.getOptionValue("reaper"),
                "illegal argument of option -reaper", 1, Integer.MAX_VALUE));
    if (cl.hasOption("rspTO"))
        dcmsnd.setDimseRspTimeout(parseInt(cl.getOptionValue("rspTO"), "illegal argument of option -rspTO", 1,
                Integer.MAX_VALUE));
    if (cl.hasOption("acceptTO"))
        dcmsnd.setAcceptTimeout(parseInt(cl.getOptionValue("acceptTO"), "illegal argument of option -acceptTO",
                1, Integer.MAX_VALUE));
    if (cl.hasOption("releaseTO"))
        dcmsnd.setReleaseTimeout(parseInt(cl.getOptionValue("releaseTO"),
                "illegal argument of option -releaseTO", 1, Integer.MAX_VALUE));
    if (cl.hasOption("soclosedelay"))
        dcmsnd.setSocketCloseDelay(parseInt(cl.getOptionValue("soclosedelay"),
                "illegal argument of option -soclosedelay", 1, 10000));
    if (cl.hasOption("shutdowndelay"))
        dcmsnd.setShutdownDelay(parseInt(cl.getOptionValue("shutdowndelay"),
                "illegal argument of option -shutdowndelay", 1, 10000));
    if (cl.hasOption("rcvpdulen"))
        dcmsnd.setMaxPDULengthReceive(
                parseInt(cl.getOptionValue("rcvpdulen"), "illegal argument of option -rcvpdulen", 1, 10000)
                        * KB);
    if (cl.hasOption("sndpdulen"))
        dcmsnd.setMaxPDULengthSend(
                parseInt(cl.getOptionValue("sndpdulen"), "illegal argument of option -sndpdulen", 1, 10000)
                        * KB);
    if (cl.hasOption("sosndbuf"))
        dcmsnd.setSendBufferSize(
                parseInt(cl.getOptionValue("sosndbuf"), "illegal argument of option -sosndbuf", 1, 10000) * KB);
    if (cl.hasOption("sorcvbuf"))
        dcmsnd.setReceiveBufferSize(
                parseInt(cl.getOptionValue("sorcvbuf"), "illegal argument of option -sorcvbuf", 1, 10000) * KB);
    if (cl.hasOption("bufsize"))
        dcmsnd.setTranscoderBufferSize(
                parseInt(cl.getOptionValue("bufsize"), "illegal argument of option -bufsize", 1, 10000) * KB);
    dcmsnd.setPackPDV(!cl.hasOption("pdv1"));
    dcmsnd.setTcpNoDelay(!cl.hasOption("tcpdelay"));
    if (cl.hasOption("async"))
        dcmsnd.setMaxOpsInvoked(
                parseInt(cl.getOptionValue("async"), "illegal argument of option -async", 0, 0xffff));
    if (cl.hasOption("lowprior"))
        dcmsnd.setPriority(CommandUtils.LOW);
    if (cl.hasOption("highprior"))
        dcmsnd.setPriority(CommandUtils.HIGH);
    System.out.println("Scanning files to send");
    long t1 = System.currentTimeMillis();
    for (int i = 1, n = argList.size(); i < n; ++i)
        dcmsnd.addFile(new File(argList.get(i)));
    long t2 = System.currentTimeMillis();
    if (dcmsnd.getNumberOfFilesToSend() == 0) {
        System.exit(2);
    }
    System.out.println("\nScanned " + dcmsnd.getNumberOfFilesToSend() + " files in " + ((t2 - t1) / 1000F)
            + "s (=" + ((t2 - t1) / dcmsnd.getNumberOfFilesToSend()) + "ms/file)");
    dcmsnd.configureTransferCapability();
    if (cl.hasOption("tls")) {
        String cipher = cl.getOptionValue("tls");
        if ("NULL".equalsIgnoreCase(cipher)) {
            dcmsnd.setTlsWithoutEncyrption();
        } else if ("3DES".equalsIgnoreCase(cipher)) {
            dcmsnd.setTls3DES_EDE_CBC();
        } else if ("AES".equalsIgnoreCase(cipher)) {
            dcmsnd.setTlsAES_128_CBC();
        } else {
            exit("Invalid parameter for option -tls: " + cipher);
        }
        if (cl.hasOption("nossl2")) {
            dcmsnd.disableSSLv2Hello();
        }
        dcmsnd.setTlsNeedClientAuth(!cl.hasOption("noclientauth"));

        if (cl.hasOption("keystore")) {
            dcmsnd.setKeyStoreURL(cl.getOptionValue("keystore"));
        }
        if (cl.hasOption("keystorepw")) {
            dcmsnd.setKeyStorePassword(cl.getOptionValue("keystorepw"));
        }
        if (cl.hasOption("keypw")) {
            dcmsnd.setKeyPassword(cl.getOptionValue("keypw"));
        }
        if (cl.hasOption("truststore")) {
            dcmsnd.setTrustStoreURL(cl.getOptionValue("truststore"));
        }
        if (cl.hasOption("truststorepw")) {
            dcmsnd.setTrustStorePassword(cl.getOptionValue("truststorepw"));
        }
        try {
            dcmsnd.initTLS();
        } catch (Exception e) {
            System.err.println("ERROR: Failed to initialize TLS context:" + e.getMessage());
            System.exit(2);
        }
    }
    try {
        dcmsnd.start();
    } catch (Exception e) {
        System.err.println("ERROR: Failed to start server for receiving " + "Storage Commitment results:"
                + e.getMessage());
        System.exit(2);
    }
    try {
        t1 = System.currentTimeMillis();
        try {
            dcmsnd.open();
        } catch (Exception e) {
            System.err.println("ERROR: Failed to establish association:" + e.getMessage());
            System.exit(2);
        }
        t2 = System.currentTimeMillis();
        System.out.println("Connected to " + remoteAE + " in " + ((t2 - t1) / 1000F) + "s");

        t1 = System.currentTimeMillis();
        dcmsnd.send();
        t2 = System.currentTimeMillis();
        prompt(dcmsnd, (t2 - t1) / 1000F);
        if (dcmsnd.isStorageCommitment()) {
            t1 = System.currentTimeMillis();
            if (dcmsnd.commit()) {
                t2 = System.currentTimeMillis();
                System.out.println(
                        "Request Storage Commitment from " + remoteAE + " in " + ((t2 - t1) / 1000F) + "s");
                System.out.println("Waiting for Storage Commitment Result..");
                try {
                    DicomObject cmtrslt = dcmsnd.waitForStgCmtResult();
                    t1 = System.currentTimeMillis();
                    promptStgCmt(cmtrslt, ((t1 - t2) / 1000F));
                } catch (InterruptedException e) {
                    System.err.println("ERROR:" + e.getMessage());
                }
            }
        }
        dcmsnd.close();
        System.out.println("Released connection to " + remoteAE);
        if (remoteStgCmtAE != null) {
            t1 = System.currentTimeMillis();
            try {
                dcmsnd.openToStgcmtAE();
            } catch (Exception e) {
                System.err.println("ERROR: Failed to establish association:" + e.getMessage());
                System.exit(2);
            }
            t2 = System.currentTimeMillis();
            System.out.println("Connected to " + remoteStgCmtAE + " in " + ((t2 - t1) / 1000F) + "s");
            t1 = System.currentTimeMillis();
            if (dcmsnd.commit()) {
                t2 = System.currentTimeMillis();
                System.out.println("Request Storage Commitment from " + remoteStgCmtAE + " in "
                        + ((t2 - t1) / 1000F) + "s");
                System.out.println("Waiting for Storage Commitment Result..");
                try {
                    DicomObject cmtrslt = dcmsnd.waitForStgCmtResult();
                    t1 = System.currentTimeMillis();
                    promptStgCmt(cmtrslt, ((t1 - t2) / 1000F));
                } catch (InterruptedException e) {
                    System.err.println("ERROR:" + e.getMessage());
                }
            }
            dcmsnd.close();
            System.out.println("Released connection to " + remoteStgCmtAE);
        }
    } finally {
        dcmsnd.stop();
    }
}

From source file:mod.org.dcm4che2.tool.DcmSnd.java

@SuppressWarnings("unchecked")
public static void main(String[] args) {
    CommandLine cl = parse(args);/*from   ww w . j a  v  a  2 s .c om*/
    DcmSnd dcmsnd = new DcmSnd(cl.hasOption("device") ? cl.getOptionValue("device") : "DCMSND");
    final List<String> argList = cl.getArgList();
    String remoteAE = argList.get(0);
    String[] calledAETAddress = split(remoteAE, '@');
    dcmsnd.setCalledAET(calledAETAddress[0]);
    if (calledAETAddress[1] == null) {
        dcmsnd.setRemoteHost("127.0.0.1");
        dcmsnd.setRemotePort(104);
    } else {
        String[] hostPort = split(calledAETAddress[1], ':');
        dcmsnd.setRemoteHost(hostPort[0]);
        dcmsnd.setRemotePort(toPort(hostPort[1]));
    }
    if (cl.hasOption("L")) {
        String localAE = cl.getOptionValue("L");
        String[] localPort = split(localAE, ':');
        if (localPort[1] != null) {
            dcmsnd.setLocalPort(toPort(localPort[1]));
        }
        String[] callingAETHost = split(localPort[0], '@');
        dcmsnd.setCalling(callingAETHost[0]);
        if (callingAETHost[1] != null) {
            dcmsnd.setLocalHost(callingAETHost[1]);
        }
    }
    dcmsnd.setOfferDefaultTransferSyntaxInSeparatePresentationContext(cl.hasOption("ts1"));
    dcmsnd.setSendFileRef(cl.hasOption("fileref"));
    if (cl.hasOption("username")) {
        String username = cl.getOptionValue("username");
        UserIdentity userId;
        if (cl.hasOption("passcode")) {
            String passcode = cl.getOptionValue("passcode");
            userId = new UserIdentity.UsernamePasscode(username, passcode.toCharArray());
        } else {
            userId = new UserIdentity.Username(username);
        }
        userId.setPositiveResponseRequested(cl.hasOption("uidnegrsp"));
        dcmsnd.setUserIdentity(userId);
    }
    dcmsnd.setStorageCommitment(cl.hasOption("stgcmt"));
    String remoteStgCmtAE = null;
    if (cl.hasOption("stgcmtae")) {
        try {
            remoteStgCmtAE = cl.getOptionValue("stgcmtae");
            String[] aet_hostport = split(remoteStgCmtAE, '@');
            String[] host_port = split(aet_hostport[1], ':');
            dcmsnd.setStgcmtCalledAET(aet_hostport[0]);
            dcmsnd.setRemoteStgcmtHost(host_port[0]);
            dcmsnd.setRemoteStgcmtPort(toPort(host_port[1]));
        } catch (Exception e) {
            exit("illegal argument of option -stgcmtae");
        }
    }
    if (cl.hasOption("set")) {
        String[] vals = cl.getOptionValues("set");
        for (int i = 0; i < vals.length; i++, i++) {
            dcmsnd.addCoerceAttr(Tag.toTag(vals[i]), vals[i + 1]);
        }
    }
    if (cl.hasOption("setuid")) {
        dcmsnd.setSuffixUID(cl.getOptionValues("setuid"));
    }
    if (cl.hasOption("connectTO"))
        dcmsnd.setConnectTimeout(parseInt(cl.getOptionValue("connectTO"),
                "illegal argument of option -connectTO", 1, Integer.MAX_VALUE));
    if (cl.hasOption("reaper"))
        dcmsnd.setAssociationReaperPeriod(parseInt(cl.getOptionValue("reaper"),
                "illegal argument of option -reaper", 1, Integer.MAX_VALUE));
    if (cl.hasOption("rspTO"))
        dcmsnd.setDimseRspTimeout(parseInt(cl.getOptionValue("rspTO"), "illegal argument of option -rspTO", 1,
                Integer.MAX_VALUE));
    if (cl.hasOption("acceptTO"))
        dcmsnd.setAcceptTimeout(parseInt(cl.getOptionValue("acceptTO"), "illegal argument of option -acceptTO",
                1, Integer.MAX_VALUE));
    if (cl.hasOption("releaseTO"))
        dcmsnd.setReleaseTimeout(parseInt(cl.getOptionValue("releaseTO"),
                "illegal argument of option -releaseTO", 1, Integer.MAX_VALUE));
    if (cl.hasOption("soclosedelay"))
        dcmsnd.setSocketCloseDelay(parseInt(cl.getOptionValue("soclosedelay"),
                "illegal argument of option -soclosedelay", 1, 10000));
    if (cl.hasOption("shutdowndelay"))
        dcmsnd.setShutdownDelay(parseInt(cl.getOptionValue("shutdowndelay"),
                "illegal argument of option -shutdowndelay", 1, 10000));
    if (cl.hasOption("anonymize"))
        dcmsnd.setAnonymize(Long.parseLong(cl.getOptionValue("anonymize")));
    if (cl.hasOption("rcvpdulen"))
        dcmsnd.setMaxPDULengthReceive(
                parseInt(cl.getOptionValue("rcvpdulen"), "illegal argument of option -rcvpdulen", 1, 10000)
                        * KB);
    if (cl.hasOption("sndpdulen"))
        dcmsnd.setMaxPDULengthSend(
                parseInt(cl.getOptionValue("sndpdulen"), "illegal argument of option -sndpdulen", 1, 10000)
                        * KB);
    if (cl.hasOption("sosndbuf"))
        dcmsnd.setSendBufferSize(
                parseInt(cl.getOptionValue("sosndbuf"), "illegal argument of option -sosndbuf", 1, 10000) * KB);
    if (cl.hasOption("sorcvbuf"))
        dcmsnd.setReceiveBufferSize(
                parseInt(cl.getOptionValue("sorcvbuf"), "illegal argument of option -sorcvbuf", 1, 10000) * KB);
    if (cl.hasOption("bufsize"))
        dcmsnd.setTranscoderBufferSize(
                parseInt(cl.getOptionValue("bufsize"), "illegal argument of option -bufsize", 1, 10000) * KB);
    if (cl.hasOption("batchsize"))
        dcmsnd.setBatchSize(Integer.parseInt(cl.getOptionValue("batchsize")));
    dcmsnd.setPackPDV(!cl.hasOption("pdv1"));
    dcmsnd.setTcpNoDelay(!cl.hasOption("tcpdelay"));
    if (cl.hasOption("async"))
        dcmsnd.setMaxOpsInvoked(
                parseInt(cl.getOptionValue("async"), "illegal argument of option -async", 0, 0xffff));
    if (cl.hasOption("lowprior"))
        dcmsnd.setPriority(CommandUtils.LOW);
    if (cl.hasOption("highprior"))
        dcmsnd.setPriority(CommandUtils.HIGH);
    System.out.println("Scanning files to send");
    long t1 = System.currentTimeMillis();
    for (int i = 1, n = argList.size(); i < n; ++i)
        dcmsnd.addFile(new File(argList.get(i)));
    long t2 = System.currentTimeMillis();
    if (dcmsnd.getNumberOfFilesToSend() == 0) {
        System.exit(2);
    }
    System.out.println("\nScanned " + dcmsnd.getNumberOfFilesToSend() + " files in " + ((t2 - t1) / 1000F)
            + "s (=" + ((t2 - t1) / dcmsnd.getNumberOfFilesToSend()) + "ms/file)");
    dcmsnd.configureTransferCapability();
    if (cl.hasOption("tls")) {
        String cipher = cl.getOptionValue("tls");
        if ("NULL".equalsIgnoreCase(cipher)) {
            dcmsnd.setTlsWithoutEncyrption();
        } else if ("3DES".equalsIgnoreCase(cipher)) {
            dcmsnd.setTls3DES_EDE_CBC();
        } else if ("AES".equalsIgnoreCase(cipher)) {
            dcmsnd.setTlsAES_128_CBC();
        } else {
            exit("Invalid parameter for option -tls: " + cipher);
        }

        if (cl.hasOption("tls1")) {
            dcmsnd.setTlsProtocol(TLS1);
        } else if (cl.hasOption("ssl3")) {
            dcmsnd.setTlsProtocol(SSL3);
        } else if (cl.hasOption("no_tls1")) {
            dcmsnd.setTlsProtocol(NO_TLS1);
        } else if (cl.hasOption("no_ssl3")) {
            dcmsnd.setTlsProtocol(NO_SSL3);
        } else if (cl.hasOption("no_ssl2")) {
            dcmsnd.setTlsProtocol(NO_SSL2);
        }
        dcmsnd.setTlsNeedClientAuth(!cl.hasOption("noclientauth"));

        if (cl.hasOption("keystore")) {
            dcmsnd.setKeyStoreURL(cl.getOptionValue("keystore"));
        }
        if (cl.hasOption("keystorepw")) {
            dcmsnd.setKeyStorePassword(cl.getOptionValue("keystorepw"));
        }
        if (cl.hasOption("keypw")) {
            dcmsnd.setKeyPassword(cl.getOptionValue("keypw"));
        }
        if (cl.hasOption("truststore")) {
            dcmsnd.setTrustStoreURL(cl.getOptionValue("truststore"));
        }
        if (cl.hasOption("truststorepw")) {
            dcmsnd.setTrustStorePassword(cl.getOptionValue("truststorepw"));
        }
        try {
            dcmsnd.initTLS();
        } catch (Exception e) {
            System.err.println("ERROR: Failed to initialize TLS context:" + e.getMessage());
            System.exit(2);
        }
    }
    while (dcmsnd.getLastSentFile() < dcmsnd.getNumberOfFilesToSend()) {
        try {
            dcmsnd.start();
        } catch (Exception e) {
            System.err.println("ERROR: Failed to start server for receiving " + "Storage Commitment results:"
                    + e.getMessage());
            System.exit(2);
        }
        try {
            t1 = System.currentTimeMillis();
            try {
                dcmsnd.open();
            } catch (Exception e) {
                System.err.println("ERROR: Failed to establish association:" + e.getMessage());
                System.exit(2);
            }
            t2 = System.currentTimeMillis();
            System.out.println("Connected to " + remoteAE + " in " + ((t2 - t1) / 1000F) + "s");

            t1 = System.currentTimeMillis();
            dcmsnd.send();
            t2 = System.currentTimeMillis();
            prompt(dcmsnd, (t2 - t1) / 1000F);
            if (dcmsnd.isStorageCommitment()) {
                t1 = System.currentTimeMillis();
                if (dcmsnd.commit()) {
                    t2 = System.currentTimeMillis();
                    System.out.println(
                            "Request Storage Commitment from " + remoteAE + " in " + ((t2 - t1) / 1000F) + "s");
                    System.out.println("Waiting for Storage Commitment Result..");
                    try {
                        DicomObject cmtrslt = dcmsnd.waitForStgCmtResult();
                        t1 = System.currentTimeMillis();
                        promptStgCmt(cmtrslt, ((t1 - t2) / 1000F));
                    } catch (InterruptedException e) {
                        System.err.println("ERROR:" + e.getMessage());
                    }
                }
            }
            dcmsnd.close();
            System.out.println("Released connection to " + remoteAE);
            if (remoteStgCmtAE != null) {
                t1 = System.currentTimeMillis();
                try {
                    dcmsnd.openToStgcmtAE();
                } catch (Exception e) {
                    System.err.println("ERROR: Failed to establish association:" + e.getMessage());
                    System.exit(2);
                }
                t2 = System.currentTimeMillis();
                System.out.println("Connected to " + remoteStgCmtAE + " in " + ((t2 - t1) / 1000F) + "s");
                t1 = System.currentTimeMillis();
                if (dcmsnd.commit()) {
                    t2 = System.currentTimeMillis();
                    System.out.println("Request Storage Commitment from " + remoteStgCmtAE + " in "
                            + ((t2 - t1) / 1000F) + "s");
                    System.out.println("Waiting for Storage Commitment Result..");
                    try {
                        DicomObject cmtrslt = dcmsnd.waitForStgCmtResult();
                        t1 = System.currentTimeMillis();
                        promptStgCmt(cmtrslt, ((t1 - t2) / 1000F));
                    } catch (InterruptedException e) {
                        System.err.println("ERROR:" + e.getMessage());
                    }
                }
                dcmsnd.close();
                System.out.println("Released connection to " + remoteStgCmtAE);
            }
        } finally {
            dcmsnd.stop();
        }
    }
}

From source file:com.upload.DcmSnd.java

@SuppressWarnings("unchecked")
public static void main(String[] args) {
    CommandLine cl = parse(args);//w  w  w  . ja  va 2 s .  com
    DcmSnd dcmsnd = new DcmSnd(cl.hasOption("device") ? cl.getOptionValue("device") : "DCMSND");
    final List<String> argList = cl.getArgList();
    String remoteAE = argList.get(0);
    String[] calledAETAddress = split(remoteAE, '@');
    dcmsnd.setCalledAET(calledAETAddress[0]);
    if (calledAETAddress[1] == null) {
        dcmsnd.setRemoteHost("127.0.0.1");
        dcmsnd.setRemotePort(104);
    } else {
        String[] hostPort = split(calledAETAddress[1], ':');
        dcmsnd.setRemoteHost(hostPort[0]);
        dcmsnd.setRemotePort(toPort(hostPort[1]));
    }
    if (cl.hasOption("L")) {
        String localAE = cl.getOptionValue("L");
        String[] localPort = split(localAE, ':');
        if (localPort[1] != null) {
            dcmsnd.setLocalPort(toPort(localPort[1]));
        }
        String[] callingAETHost = split(localPort[0], '@');
        dcmsnd.setCalling(callingAETHost[0]);
        if (callingAETHost[1] != null) {
            dcmsnd.setLocalHost(callingAETHost[1]);
        }
    }
    dcmsnd.setOfferDefaultTransferSyntaxInSeparatePresentationContext(cl.hasOption("ts1"));
    dcmsnd.setSendFileRef(cl.hasOption("fileref"));
    if (cl.hasOption("username")) {
        String username = cl.getOptionValue("username");
        UserIdentity userId;
        if (cl.hasOption("passcode")) {
            String passcode = cl.getOptionValue("passcode");
            userId = new UserIdentity.UsernamePasscode(username, passcode.toCharArray());
        } else {
            userId = new UserIdentity.Username(username);
        }
        userId.setPositiveResponseRequested(cl.hasOption("uidnegrsp"));
        dcmsnd.setUserIdentity(userId);
    }
    dcmsnd.setStorageCommitment(cl.hasOption("stgcmt"));
    String remoteStgCmtAE = null;
    if (cl.hasOption("stgcmtae")) {
        try {
            remoteStgCmtAE = cl.getOptionValue("stgcmtae");
            String[] aet_hostport = split(remoteStgCmtAE, '@');
            String[] host_port = split(aet_hostport[1], ':');
            dcmsnd.setStgcmtCalledAET(aet_hostport[0]);
            dcmsnd.setRemoteStgcmtHost(host_port[0]);
            dcmsnd.setRemoteStgcmtPort(toPort(host_port[1]));
        } catch (Exception e) {
            exit("illegal argument of option -stgcmtae");
        }
    }
    if (cl.hasOption("set")) {
        String[] vals = cl.getOptionValues("set");
        for (int i = 0; i < vals.length; i++, i++) {
            dcmsnd.addCoerceAttr(Tag.toTag(vals[i]), vals[i + 1]);
        }
    }
    if (cl.hasOption("setuid")) {
        dcmsnd.setSuffixUID(cl.getOptionValues("setuid"));
    }
    if (cl.hasOption("connectTO"))
        dcmsnd.setConnectTimeout(parseInt(cl.getOptionValue("connectTO"),
                "illegal argument of option -connectTO", 1, Integer.MAX_VALUE));
    if (cl.hasOption("reaper"))
        dcmsnd.setAssociationReaperPeriod(parseInt(cl.getOptionValue("reaper"),
                "illegal argument of option -reaper", 1, Integer.MAX_VALUE));
    if (cl.hasOption("rspTO"))
        dcmsnd.setDimseRspTimeout(parseInt(cl.getOptionValue("rspTO"), "illegal argument of option -rspTO", 1,
                Integer.MAX_VALUE));
    if (cl.hasOption("acceptTO"))
        dcmsnd.setAcceptTimeout(parseInt(cl.getOptionValue("acceptTO"), "illegal argument of option -acceptTO",
                1, Integer.MAX_VALUE));
    if (cl.hasOption("releaseTO"))
        dcmsnd.setReleaseTimeout(parseInt(cl.getOptionValue("releaseTO"),
                "illegal argument of option -releaseTO", 1, Integer.MAX_VALUE));
    if (cl.hasOption("soclosedelay"))
        dcmsnd.setSocketCloseDelay(parseInt(cl.getOptionValue("soclosedelay"),
                "illegal argument of option -soclosedelay", 1, 10000));
    if (cl.hasOption("shutdowndelay"))
        dcmsnd.setShutdownDelay(parseInt(cl.getOptionValue("shutdowndelay"),
                "illegal argument of option -shutdowndelay", 1, 10000));
    if (cl.hasOption("anonymize"))
        dcmsnd.setAnonymize(Long.parseLong(cl.getOptionValue("anonymize")));
    if (cl.hasOption("rcvpdulen"))
        dcmsnd.setMaxPDULengthReceive(
                parseInt(cl.getOptionValue("rcvpdulen"), "illegal argument of option -rcvpdulen", 1, 10000)
                        * KB);
    if (cl.hasOption("sndpdulen"))
        dcmsnd.setMaxPDULengthSend(
                parseInt(cl.getOptionValue("sndpdulen"), "illegal argument of option -sndpdulen", 1, 10000)
                        * KB);
    if (cl.hasOption("sosndbuf"))
        dcmsnd.setSendBufferSize(
                parseInt(cl.getOptionValue("sosndbuf"), "illegal argument of option -sosndbuf", 1, 10000) * KB);
    if (cl.hasOption("sorcvbuf"))
        dcmsnd.setReceiveBufferSize(
                parseInt(cl.getOptionValue("sorcvbuf"), "illegal argument of option -sorcvbuf", 1, 10000) * KB);
    if (cl.hasOption("bufsize"))
        dcmsnd.setTranscoderBufferSize(
                parseInt(cl.getOptionValue("bufsize"), "illegal argument of option -bufsize", 1, 10000) * KB);
    if (cl.hasOption("batchsize"))
        dcmsnd.setBatchSize(Integer.parseInt(cl.getOptionValue("batchsize")));
    dcmsnd.setPackPDV(!cl.hasOption("pdv1"));
    dcmsnd.setTcpNoDelay(!cl.hasOption("tcpdelay"));
    if (cl.hasOption("async"))
        dcmsnd.setMaxOpsInvoked(
                parseInt(cl.getOptionValue("async"), "illegal argument of option -async", 0, 0xffff));
    if (cl.hasOption("lowprior"))
        dcmsnd.setPriority(CommandUtils.LOW);
    if (cl.hasOption("highprior"))
        dcmsnd.setPriority(CommandUtils.HIGH);
    System.out.println("Scanning files to send");
    long t1 = System.currentTimeMillis();
    for (int i = 1, n = argList.size(); i < n; ++i)
        dcmsnd.addFile(new File(argList.get(i)));
    long t2 = System.currentTimeMillis();
    if (dcmsnd.getNumberOfFilesToSend() == 0) {
        // System.exit(2);
    }
    System.out.println("\nScanned " + dcmsnd.getNumberOfFilesToSend() + " files in " + ((t2 - t1) / 1000F)
            + "s (=" + ((t2 - t1) / dcmsnd.getNumberOfFilesToSend()) + "ms/file)");
    dcmsnd.configureTransferCapability();
    if (cl.hasOption("tls")) {
        String cipher = cl.getOptionValue("tls");
        if ("NULL".equalsIgnoreCase(cipher)) {
            dcmsnd.setTlsWithoutEncyrption();
        } else if ("3DES".equalsIgnoreCase(cipher)) {
            dcmsnd.setTls3DES_EDE_CBC();
        } else if ("AES".equalsIgnoreCase(cipher)) {
            dcmsnd.setTlsAES_128_CBC();
        } else {
            exit("Invalid parameter for option -tls: " + cipher);
        }

        if (cl.hasOption("tls1")) {
            dcmsnd.setTlsProtocol(TLS1);
        } else if (cl.hasOption("ssl3")) {
            dcmsnd.setTlsProtocol(SSL3);
        } else if (cl.hasOption("no_tls1")) {
            dcmsnd.setTlsProtocol(NO_TLS1);
        } else if (cl.hasOption("no_ssl3")) {
            dcmsnd.setTlsProtocol(NO_SSL3);
        } else if (cl.hasOption("no_ssl2")) {
            dcmsnd.setTlsProtocol(NO_SSL2);
        }
        dcmsnd.setTlsNeedClientAuth(!cl.hasOption("noclientauth"));

        if (cl.hasOption("keystore")) {
            dcmsnd.setKeyStoreURL(cl.getOptionValue("keystore"));
        }
        if (cl.hasOption("keystorepw")) {
            dcmsnd.setKeyStorePassword(cl.getOptionValue("keystorepw"));
        }
        if (cl.hasOption("keypw")) {
            dcmsnd.setKeyPassword(cl.getOptionValue("keypw"));
        }
        if (cl.hasOption("truststore")) {
            dcmsnd.setTrustStoreURL(cl.getOptionValue("truststore"));
        }
        if (cl.hasOption("truststorepw")) {
            dcmsnd.setTrustStorePassword(cl.getOptionValue("truststorepw"));
        }
        try {
            dcmsnd.initTLS();
        } catch (Exception e) {
            System.err.println("ERROR: Failed to initialize TLS context:" + e.getMessage());
            // System.exit(2);
        }
    }
    while (dcmsnd.getLastSentFile() < dcmsnd.getNumberOfFilesToSend()) {
        try {
            dcmsnd.start();
        } catch (Exception e) {
            System.err.println("ERROR: Failed to start server for receiving " + "Storage Commitment results:"
                    + e.getMessage());
            //  System.exit(2);
        }
        try {
            t1 = System.currentTimeMillis();
            try {
                dcmsnd.open();
            } catch (Exception e) {
                System.err.println("ERROR: Failed to establish association:" + e.getMessage());
                // System.exit(2);
            }
            t2 = System.currentTimeMillis();
            System.out.println("Connected to " + remoteAE + " in " + ((t2 - t1) / 1000F) + "s");

            t1 = System.currentTimeMillis();
            dcmsnd.send();
            t2 = System.currentTimeMillis();
            prompt(dcmsnd, (t2 - t1) / 1000F);
            if (dcmsnd.isStorageCommitment()) {
                t1 = System.currentTimeMillis();
                if (dcmsnd.commit()) {
                    t2 = System.currentTimeMillis();
                    System.out.println(
                            "Request Storage Commitment from " + remoteAE + " in " + ((t2 - t1) / 1000F) + "s");
                    System.out.println("Waiting for Storage Commitment Result..");
                    try {
                        DicomObject cmtrslt = dcmsnd.waitForStgCmtResult();
                        t1 = System.currentTimeMillis();
                        promptStgCmt(cmtrslt, ((t1 - t2) / 1000F));
                    } catch (InterruptedException e) {
                        System.err.println("ERROR:" + e.getMessage());
                    }
                }
            }
            dcmsnd.close();
            System.out.println("Released connection to " + remoteAE);
            if (remoteStgCmtAE != null) {
                t1 = System.currentTimeMillis();
                try {
                    dcmsnd.openToStgcmtAE();
                } catch (Exception e) {
                    System.err.println("ERROR: Failed to establish association:" + e.getMessage());
                    // System.exit(2);
                }
                t2 = System.currentTimeMillis();
                System.out.println("Connected to " + remoteStgCmtAE + " in " + ((t2 - t1) / 1000F) + "s");
                t1 = System.currentTimeMillis();
                if (dcmsnd.commit()) {
                    t2 = System.currentTimeMillis();
                    System.out.println("Request Storage Commitment from " + remoteStgCmtAE + " in "
                            + ((t2 - t1) / 1000F) + "s");
                    System.out.println("Waiting for Storage Commitment Result..");
                    try {
                        DicomObject cmtrslt = dcmsnd.waitForStgCmtResult();
                        t1 = System.currentTimeMillis();
                        promptStgCmt(cmtrslt, ((t1 - t2) / 1000F));
                    } catch (InterruptedException e) {
                        System.err.println("ERROR:" + e.getMessage());
                    }
                }
                dcmsnd.close();
                System.out.println("Released connection to " + remoteStgCmtAE);
            }
        } finally {
            dcmsnd.stop();
        }
    }
}

From source file:RyaClientExample.java

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

    final String accumuloUsername = "root";
    final String accumuloPassword = "password";

    MiniAccumuloCluster cluster = null;/*  w w  w . j  ava2 s .c  o m*/
    MiniFluo fluo = null;
    Sail ryaSail = null;

    try {
        // Setup a Mini Accumulo Cluster to host the Rya instance.
        log.info("Setting up the Mini Accumulo Cluster used by this example.");
        final File miniDataDir = Files.createTempDir();
        final MiniAccumuloConfig cfg = new MiniAccumuloConfig(miniDataDir, accumuloPassword);
        cluster = new MiniAccumuloCluster(cfg);
        cluster.start();

        // Setup a Mini Fluo application that will be used to incrementally update the PCJ indicies.
        log.info("Setting up the Mini Fluo application used by this example.");
        final String fluoAppName = "demoInstance_pcjUpdater";
        fluo = makeMiniFluo(accumuloUsername, accumuloPassword, cluster.getInstanceName(),
                cluster.getZooKeepers(), fluoAppName);

        // Give the root user the 'U' authorizations.
        final Connector connector = cluster.getConnector(accumuloUsername, accumuloPassword);
        connector.securityOperations().changeUserAuthorizations("root", new Authorizations("U"));

        // Setup a Rya Client that is able to interact with the mini cluster.
        final AccumuloConnectionDetails connectionDetails = new AccumuloConnectionDetails(accumuloUsername,
                accumuloPassword.toCharArray(), cluster.getInstanceName(), cluster.getZooKeepers());

        final RyaClient ryaClient = AccumuloRyaClientFactory.build(connectionDetails, connector);

        // Install an instance of Rya that has all of the secondary indexers turned on.
        final String ryaInstanceName = "demoInstance_";
        final InstallConfiguration installConfig = InstallConfiguration.builder().setEnableTableHashPrefix(true)
                .setEnableEntityCentricIndex(true).setEnableGeoIndex(true).setEnableFreeTextIndex(true)
                .setEnableTemporalIndex(true).setEnablePcjIndex(true).setFluoPcjAppName(fluoAppName).build();

        ryaClient.getInstall().install(ryaInstanceName, installConfig);

        // Add a PCJ index.
        final String sparql = "SELECT ?patron ?employee " + "WHERE { " + "?patron <http://talksTo> ?employee. "
                + "?employee <http://worksAt> <http://CoffeeShop>. " + "}";

        // Load some statements into the Rya instance.

        final AccumuloIndexingConfiguration conf = AccumuloIndexingConfiguration.builder().setAuths("U")
                .setAccumuloUser(accumuloUsername).setAccumuloPassword(accumuloPassword)
                .setAccumuloInstance(cluster.getInstanceName()).setAccumuloZooKeepers(cluster.getZooKeepers())
                .setRyaPrefix(ryaInstanceName).setPcjUpdaterFluoAppName(fluoAppName).build();

        ryaSail = RyaSailFactory.getInstance(conf);

        final ValueFactory vf = ryaSail.getValueFactory();
        final List<Statement> statements = Lists.newArrayList(
                vf.createStatement(vf.createURI("http://Eve"), vf.createURI("http://talksTo"),
                        vf.createURI("http://Charlie")),
                vf.createStatement(vf.createURI("http://David"), vf.createURI("http://talksTo"),
                        vf.createURI("http://Alice")),
                vf.createStatement(vf.createURI("http://Alice"), vf.createURI("http://worksAt"),
                        vf.createURI("http://CoffeeShop")),
                vf.createStatement(vf.createURI("http://Bob"), vf.createURI("http://worksAt"),
                        vf.createURI("http://CoffeeShop")),
                vf.createStatement(vf.createURI("http://George"), vf.createURI("http://talksTo"),
                        vf.createURI("http://Frank")),
                vf.createStatement(vf.createURI("http://Frank"), vf.createURI("http://worksAt"),
                        vf.createURI("http://CoffeeShop")),
                vf.createStatement(vf.createURI("http://Eve"), vf.createURI("http://talksTo"),
                        vf.createURI("http://Bob")),
                vf.createStatement(vf.createURI("http://Charlie"), vf.createURI("http://worksAt"),
                        vf.createURI("http://CoffeeShop")));

        SailConnection ryaConn = ryaSail.getConnection();
        log.info("");
        log.info("Loading the following statements:");
        ryaConn.begin();
        for (final Statement statement : statements) {
            log.info("    " + statement.toString());
            ryaConn.addStatement(statement.getSubject(), statement.getPredicate(), statement.getObject());
        }
        log.info("");
        ryaConn.close();
        fluo.waitForObservers();

        // Execute the SPARQL query and print the results.
        log.info("Executing the following query: ");
        prettyLogSparql(sparql);
        log.info("");

        final ParsedQuery parsedQuery = new SPARQLParser().parseQuery(sparql, null);
        ryaConn = ryaSail.getConnection();
        final CloseableIteration<? extends BindingSet, QueryEvaluationException> result = ryaConn
                .evaluate(parsedQuery.getTupleExpr(), null, null, false);

        log.info("Results:");
        while (result.hasNext()) {
            log.info("    " + result.next());
        }
        log.info("");

    } finally {
        if (ryaSail != null) {
            log.info("Shutting down the Rya Sail instance.");
            ryaSail.shutDown();
        }

        if (fluo != null) {
            try {
                log.info("Shutting down the Mini Fluo instance.");
                fluo.close();
            } catch (final Exception e) {
                log.error("Could not shut down the Mini Fluo instance.", e);
            }
        }

        if (cluster != null) {
            log.info("Sutting down the Mini Accumulo Cluster.");
            cluster.stop();
        }
    }
}

From source file:DcmQR.java

@SuppressWarnings("unchecked")
public static void main(String[] args) {
    CommandLine cl = parse(args);// ww w  .  j a  v  a2 s.  co m
    DcmQR dcmqr = new DcmQR();
    final List<String> argList = cl.getArgList();
    String remoteAE = argList.get(0);
    String[] calledAETAddress = split(remoteAE, '@');
    dcmqr.setCalledAET(calledAETAddress[0], cl.hasOption("reuseassoc"));
    if (calledAETAddress[1] == null) {
        dcmqr.setRemoteHost("127.0.0.1");
        dcmqr.setRemotePort(104);
    } else {
        String[] hostPort = split(calledAETAddress[1], ':');
        dcmqr.setRemoteHost(hostPort[0]);
        dcmqr.setRemotePort(toPort(hostPort[1]));
    }
    if (cl.hasOption("L")) {
        String localAE = cl.getOptionValue("L");
        String[] localPort = split(localAE, ':');
        if (localPort[1] != null) {
            dcmqr.setLocalPort(toPort(localPort[1]));
        }
        String[] callingAETHost = split(localPort[0], '@');
        dcmqr.setCalling(callingAETHost[0]);
        if (callingAETHost[1] != null) {
            dcmqr.setLocalHost(callingAETHost[1]);
        }
    }
    if (cl.hasOption("username")) {
        String username = cl.getOptionValue("username");
        UserIdentity userId;
        if (cl.hasOption("passcode")) {
            String passcode = cl.getOptionValue("passcode");
            userId = new UserIdentity.UsernamePasscode(username, passcode.toCharArray());
        } else {
            userId = new UserIdentity.Username(username);
        }
        userId.setPositiveResponseRequested(cl.hasOption("uidnegrsp"));
        dcmqr.setUserIdentity(userId);
    }
    if (cl.hasOption("connectTO"))
        dcmqr.setConnectTimeout(parseInt(cl.getOptionValue("connectTO"),
                "illegal argument of option -connectTO", 1, Integer.MAX_VALUE));
    if (cl.hasOption("reaper"))
        dcmqr.setAssociationReaperPeriod(parseInt(cl.getOptionValue("reaper"),
                "illegal argument of option -reaper", 1, Integer.MAX_VALUE));
    if (cl.hasOption("cfindrspTO"))
        dcmqr.setDimseRspTimeout(parseInt(cl.getOptionValue("cfindrspTO"),
                "illegal argument of option -cfindrspTO", 1, Integer.MAX_VALUE));
    if (cl.hasOption("cmoverspTO"))
        dcmqr.setRetrieveRspTimeout(parseInt(cl.getOptionValue("cmoverspTO"),
                "illegal argument of option -cmoverspTO", 1, Integer.MAX_VALUE));
    if (cl.hasOption("cgetrspTO"))
        dcmqr.setRetrieveRspTimeout(parseInt(cl.getOptionValue("cgetrspTO"),
                "illegal argument of option -cgetrspTO", 1, Integer.MAX_VALUE));
    if (cl.hasOption("acceptTO"))
        dcmqr.setAcceptTimeout(parseInt(cl.getOptionValue("acceptTO"), "illegal argument of option -acceptTO",
                1, Integer.MAX_VALUE));
    if (cl.hasOption("releaseTO"))
        dcmqr.setReleaseTimeout(parseInt(cl.getOptionValue("releaseTO"),
                "illegal argument of option -releaseTO", 1, Integer.MAX_VALUE));
    if (cl.hasOption("soclosedelay"))
        dcmqr.setSocketCloseDelay(parseInt(cl.getOptionValue("soclosedelay"),
                "illegal argument of option -soclosedelay", 1, 10000));
    if (cl.hasOption("rcvpdulen"))
        dcmqr.setMaxPDULengthReceive(
                parseInt(cl.getOptionValue("rcvpdulen"), "illegal argument of option -rcvpdulen", 1, 10000)
                        * KB);
    if (cl.hasOption("sndpdulen"))
        dcmqr.setMaxPDULengthSend(
                parseInt(cl.getOptionValue("sndpdulen"), "illegal argument of option -sndpdulen", 1, 10000)
                        * KB);
    if (cl.hasOption("sosndbuf"))
        dcmqr.setSendBufferSize(
                parseInt(cl.getOptionValue("sosndbuf"), "illegal argument of option -sosndbuf", 1, 10000) * KB);
    if (cl.hasOption("sorcvbuf"))
        dcmqr.setReceiveBufferSize(
                parseInt(cl.getOptionValue("sorcvbuf"), "illegal argument of option -sorcvbuf", 1, 10000) * KB);
    if (cl.hasOption("filebuf"))
        dcmqr.setFileBufferSize(
                parseInt(cl.getOptionValue("filebuf"), "illegal argument of option -filebuf", 1, 10000) * KB);
    dcmqr.setPackPDV(!cl.hasOption("pdv1"));
    dcmqr.setTcpNoDelay(!cl.hasOption("tcpdelay"));
    dcmqr.setMaxOpsInvoked(cl.hasOption("async")
            ? parseInt(cl.getOptionValue("async"), "illegal argument of option -async", 0, 0xffff)
            : 1);
    dcmqr.setMaxOpsPerformed(cl.hasOption("cstoreasync")
            ? parseInt(cl.getOptionValue("cstoreasync"), "illegal argument of option -cstoreasync", 0, 0xffff)
            : 0);
    if (cl.hasOption("C"))
        dcmqr.setCancelAfter(
                parseInt(cl.getOptionValue("C"), "illegal argument of option -C", 1, Integer.MAX_VALUE));
    if (cl.hasOption("lowprior"))
        dcmqr.setPriority(CommandUtils.LOW);
    if (cl.hasOption("highprior"))
        dcmqr.setPriority(CommandUtils.HIGH);
    if (cl.hasOption("cstore")) {
        String[] storeTCs = cl.getOptionValues("cstore");
        for (String storeTC : storeTCs) {
            String cuid;
            String[] tsuids;
            int colon = storeTC.indexOf(':');
            if (colon == -1) {
                cuid = storeTC;
                tsuids = DEF_TS;
            } else {
                cuid = storeTC.substring(0, colon);
                String ts = storeTC.substring(colon + 1);
                try {
                    tsuids = TS.valueOf(ts).uids;
                } catch (IllegalArgumentException e) {
                    tsuids = ts.split(",");
                }
            }
            try {
                cuid = CUID.valueOf(cuid).uid;
            } catch (IllegalArgumentException e) {
                // assume cuid already contains UID
            }
            dcmqr.addStoreTransferCapability(cuid, tsuids);
        }
        if (cl.hasOption("cstoredest"))
            dcmqr.setStoreDestination(cl.getOptionValue("cstoredest"));
    }
    dcmqr.setCGet(cl.hasOption("cget"));
    if (cl.hasOption("cmove"))
        dcmqr.setMoveDest(cl.getOptionValue("cmove"));
    if (cl.hasOption("evalRetrieveAET"))
        dcmqr.setEvalRetrieveAET(true);
    if (cl.hasOption("P"))
        dcmqr.setQueryLevel(QueryRetrieveLevel.PATIENT);
    else if (cl.hasOption("S"))
        dcmqr.setQueryLevel(QueryRetrieveLevel.SERIES);
    else if (cl.hasOption("I"))
        dcmqr.setQueryLevel(QueryRetrieveLevel.IMAGE);
    else
        dcmqr.setQueryLevel(QueryRetrieveLevel.STUDY);
    if (cl.hasOption("noextneg"))
        dcmqr.setNoExtNegotiation(true);
    if (cl.hasOption("rel"))
        dcmqr.setRelationQR(true);
    if (cl.hasOption("datetime"))
        dcmqr.setDateTimeMatching(true);
    if (cl.hasOption("fuzzy"))
        dcmqr.setFuzzySemanticPersonNameMatching(true);
    if (!cl.hasOption("P")) {
        if (cl.hasOption("retall"))
            dcmqr.addPrivate(UID.PrivateStudyRootQueryRetrieveInformationModelFIND);
        if (cl.hasOption("blocked"))
            dcmqr.addPrivate(UID.PrivateBlockedStudyRootQueryRetrieveInformationModelFIND);
        if (cl.hasOption("vmf"))
            dcmqr.addPrivate(UID.PrivateVirtualMultiframeStudyRootQueryRetrieveInformationModelFIND);
    }
    if (cl.hasOption("q")) {
        String[] matchingKeys = cl.getOptionValues("q");
        for (int i = 1; i < matchingKeys.length; i++, i++)
            dcmqr.addMatchingKey(Tag.toTagPath(matchingKeys[i - 1]), matchingKeys[i]);
    }
    if (cl.hasOption("r")) {
        String[] returnKeys = cl.getOptionValues("r");
        for (int i = 0; i < returnKeys.length; i++)
            dcmqr.addReturnKey(Tag.toTagPath(returnKeys[i]));
    }

    dcmqr.configureTransferCapability(cl.hasOption("ivrle"));

    int repeat = cl.hasOption("repeat")
            ? parseInt(cl.getOptionValue("repeat"), "illegal argument of option -repeat", 1, Integer.MAX_VALUE)
            : 0;
    int interval = cl.hasOption("repeatdelay")
            ? parseInt(cl.getOptionValue("repeatdelay"), "illegal argument of option -repeatdelay", 1,
                    Integer.MAX_VALUE)
            : 0;
    boolean closeAssoc = cl.hasOption("closeassoc");

    if (cl.hasOption("tls")) {
        String cipher = cl.getOptionValue("tls");
        if ("NULL".equalsIgnoreCase(cipher)) {
            dcmqr.setTlsWithoutEncyrption();
        } else if ("3DES".equalsIgnoreCase(cipher)) {
            dcmqr.setTls3DES_EDE_CBC();
        } else if ("AES".equalsIgnoreCase(cipher)) {
            dcmqr.setTlsAES_128_CBC();
        } else {
            exit("Invalid parameter for option -tls: " + cipher);
        }
        if (cl.hasOption("nossl2")) {
            dcmqr.disableSSLv2Hello();
        }
        dcmqr.setTlsNeedClientAuth(!cl.hasOption("noclientauth"));
        if (cl.hasOption("keystore")) {
            dcmqr.setKeyStoreURL(cl.getOptionValue("keystore"));
        }
        if (cl.hasOption("keystorepw")) {
            dcmqr.setKeyStorePassword(cl.getOptionValue("keystorepw"));
        }
        if (cl.hasOption("keypw")) {
            dcmqr.setKeyPassword(cl.getOptionValue("keypw"));
        }
        if (cl.hasOption("truststore")) {
            dcmqr.setTrustStoreURL(cl.getOptionValue("truststore"));
        }
        if (cl.hasOption("truststorepw")) {
            dcmqr.setTrustStorePassword(cl.getOptionValue("truststorepw"));
        }
        long t1 = System.currentTimeMillis();
        try {
            dcmqr.initTLS();
        } catch (Exception e) {
            System.err.println("ERROR: Failed to initialize TLS context:" + e.getMessage());
            System.exit(2);
        }
        long t2 = System.currentTimeMillis();
        LOG.info("Initialize TLS context in {} s", Float.valueOf((t2 - t1) / 1000f));
    }
    try {
        dcmqr.start();
    } catch (Exception e) {
        System.err.println(
                "ERROR: Failed to start server for receiving " + "requested objects:" + e.getMessage());
        System.exit(2);
    }
    try {
        long t1 = System.currentTimeMillis();
        try {
            dcmqr.open();
        } catch (Exception e) {
            LOG.error("Failed to establish association:", e);
            System.exit(2);
        }
        long t2 = System.currentTimeMillis();
        LOG.info("Connected to {} in {} s", remoteAE, Float.valueOf((t2 - t1) / 1000f));

        for (;;) {
            List<DicomObject> result = dcmqr.query();
            long t3 = System.currentTimeMillis();
            LOG.info("Received {} matching entries in {} s", Integer.valueOf(result.size()),
                    Float.valueOf((t3 - t2) / 1000f));
            if (dcmqr.isCMove() || dcmqr.isCGet()) {
                if (dcmqr.isCMove())
                    dcmqr.move(result);
                else
                    dcmqr.get(result);
                long t4 = System.currentTimeMillis();
                LOG.info("Retrieved {} objects (warning: {}, failed: {}) in {}s",
                        new Object[] { Integer.valueOf(dcmqr.getTotalRetrieved()),
                                Integer.valueOf(dcmqr.getWarning()), Integer.valueOf(dcmqr.getFailed()),
                                Float.valueOf((t4 - t3) / 1000f) });
            }
            if (repeat == 0 || closeAssoc) {
                try {
                    dcmqr.close();
                } catch (InterruptedException e) {
                    LOG.error(e.getMessage(), e);
                }
                LOG.info("Released connection to {}", remoteAE);
            }
            if (repeat-- == 0)
                break;
            Thread.sleep(interval);
            long t4 = System.currentTimeMillis();
            dcmqr.open();
            t2 = System.currentTimeMillis();
            LOG.info("Reconnect or reuse connection to {} in {} s", remoteAE, Float.valueOf((t2 - t4) / 1000f));
        }
    } catch (IOException e) {
        LOG.error(e.getMessage(), e);
    } catch (InterruptedException e) {
        LOG.error(e.getMessage(), e);
    } catch (ConfigurationException e) {
        LOG.error(e.getMessage(), e);
    } finally {
        dcmqr.stop();
    }
}

From source file:mod.org.dcm4che2.tool.DcmQR.java

@SuppressWarnings("unchecked")
public static void main(String[] args) {
    CommandLine cl = parse(args);/*from w  w  w  . j  a  v  a  2s  .  c  om*/
    DcmQR dcmqr = new DcmQR(cl.hasOption("device") ? cl.getOptionValue("device") : "DCMQR");
    final List<String> argList = cl.getArgList();
    String remoteAE = argList.get(0);
    String[] calledAETAddress = split(remoteAE, '@');
    dcmqr.setCalledAET(calledAETAddress[0], cl.hasOption("reuseassoc"));
    if (calledAETAddress[1] == null) {
        dcmqr.setRemoteHost("127.0.0.1");
        dcmqr.setRemotePort(104);
    } else {
        String[] hostPort = split(calledAETAddress[1], ':');
        dcmqr.setRemoteHost(hostPort[0]);
        dcmqr.setRemotePort(toPort(hostPort[1]));
    }
    if (cl.hasOption("L")) {
        String localAE = cl.getOptionValue("L");
        String[] localPort = split(localAE, ':');
        if (localPort[1] != null) {
            dcmqr.setLocalPort(toPort(localPort[1]));
        }
        String[] callingAETHost = split(localPort[0], '@');
        dcmqr.setCalling(callingAETHost[0]);
        if (callingAETHost[1] != null) {
            dcmqr.setLocalHost(callingAETHost[1]);
        }
    }
    if (cl.hasOption("username")) {
        String username = cl.getOptionValue("username");
        UserIdentity userId;
        if (cl.hasOption("passcode")) {
            String passcode = cl.getOptionValue("passcode");
            userId = new UserIdentity.UsernamePasscode(username, passcode.toCharArray());
        } else {
            userId = new UserIdentity.Username(username);
        }
        userId.setPositiveResponseRequested(cl.hasOption("uidnegrsp"));
        dcmqr.setUserIdentity(userId);
    }
    if (cl.hasOption("connectTO"))
        dcmqr.setConnectTimeout(parseInt(cl.getOptionValue("connectTO"),
                "illegal argument of option -connectTO", 1, Integer.MAX_VALUE));
    if (cl.hasOption("reaper"))
        dcmqr.setAssociationReaperPeriod(parseInt(cl.getOptionValue("reaper"),
                "illegal argument of option -reaper", 1, Integer.MAX_VALUE));
    if (cl.hasOption("cfindrspTO"))
        dcmqr.setDimseRspTimeout(parseInt(cl.getOptionValue("cfindrspTO"),
                "illegal argument of option -cfindrspTO", 1, Integer.MAX_VALUE));
    if (cl.hasOption("cmoverspTO"))
        dcmqr.setRetrieveRspTimeout(parseInt(cl.getOptionValue("cmoverspTO"),
                "illegal argument of option -cmoverspTO", 1, Integer.MAX_VALUE));
    if (cl.hasOption("cgetrspTO"))
        dcmqr.setRetrieveRspTimeout(parseInt(cl.getOptionValue("cgetrspTO"),
                "illegal argument of option -cgetrspTO", 1, Integer.MAX_VALUE));
    if (cl.hasOption("acceptTO"))
        dcmqr.setAcceptTimeout(parseInt(cl.getOptionValue("acceptTO"), "illegal argument of option -acceptTO",
                1, Integer.MAX_VALUE));
    if (cl.hasOption("releaseTO"))
        dcmqr.setReleaseTimeout(parseInt(cl.getOptionValue("releaseTO"),
                "illegal argument of option -releaseTO", 1, Integer.MAX_VALUE));
    if (cl.hasOption("soclosedelay"))
        dcmqr.setSocketCloseDelay(parseInt(cl.getOptionValue("soclosedelay"),
                "illegal argument of option -soclosedelay", 1, 10000));
    if (cl.hasOption("rcvpdulen"))
        dcmqr.setMaxPDULengthReceive(
                parseInt(cl.getOptionValue("rcvpdulen"), "illegal argument of option -rcvpdulen", 1, 10000)
                        * KB);
    if (cl.hasOption("sndpdulen"))
        dcmqr.setMaxPDULengthSend(
                parseInt(cl.getOptionValue("sndpdulen"), "illegal argument of option -sndpdulen", 1, 10000)
                        * KB);
    if (cl.hasOption("sosndbuf"))
        dcmqr.setSendBufferSize(
                parseInt(cl.getOptionValue("sosndbuf"), "illegal argument of option -sosndbuf", 1, 10000) * KB);
    if (cl.hasOption("sorcvbuf"))
        dcmqr.setReceiveBufferSize(
                parseInt(cl.getOptionValue("sorcvbuf"), "illegal argument of option -sorcvbuf", 1, 10000) * KB);
    if (cl.hasOption("filebuf"))
        dcmqr.setFileBufferSize(
                parseInt(cl.getOptionValue("filebuf"), "illegal argument of option -filebuf", 1, 10000) * KB);
    dcmqr.setPackPDV(!cl.hasOption("pdv1"));
    dcmqr.setTcpNoDelay(!cl.hasOption("tcpdelay"));
    dcmqr.setMaxOpsInvoked(cl.hasOption("async")
            ? parseInt(cl.getOptionValue("async"), "illegal argument of option -async", 0, 0xffff)
            : 1);
    dcmqr.setMaxOpsPerformed(cl.hasOption("cstoreasync")
            ? parseInt(cl.getOptionValue("cstoreasync"), "illegal argument of option -cstoreasync", 0, 0xffff)
            : 0);
    if (cl.hasOption("C"))
        dcmqr.setCancelAfter(
                parseInt(cl.getOptionValue("C"), "illegal argument of option -C", 1, Integer.MAX_VALUE));
    if (cl.hasOption("lowprior"))
        dcmqr.setPriority(CommandUtils.LOW);
    if (cl.hasOption("highprior"))
        dcmqr.setPriority(CommandUtils.HIGH);
    if (cl.hasOption("cstore")) {
        String[] storeTCs = cl.getOptionValues("cstore");
        for (String storeTC : storeTCs) {
            String cuid;
            String[] tsuids;
            int colon = storeTC.indexOf(':');
            if (colon == -1) {
                cuid = storeTC;
                tsuids = DEF_TS;
            } else {
                cuid = storeTC.substring(0, colon);
                String ts = storeTC.substring(colon + 1);
                try {
                    tsuids = TS.valueOf(ts).uids;
                } catch (IllegalArgumentException e) {
                    tsuids = ts.split(",");
                }
            }
            try {
                cuid = CUID.valueOf(cuid).uid;
            } catch (IllegalArgumentException e) {
                // assume cuid already contains UID
            }
            dcmqr.addStoreTransferCapability(cuid, tsuids);
        }
        if (cl.hasOption("cstoredest"))
            dcmqr.setStoreDestination(cl.getOptionValue("cstoredest"));
    }
    dcmqr.setCFind(!cl.hasOption("nocfind"));
    dcmqr.setCGet(cl.hasOption("cget"));
    if (cl.hasOption("cmove"))
        dcmqr.setMoveDest(cl.getOptionValue("cmove"));
    if (cl.hasOption("evalRetrieveAET"))
        dcmqr.setEvalRetrieveAET(true);
    dcmqr.setQueryLevel(cl.hasOption("P") ? QueryRetrieveLevel.PATIENT
            : cl.hasOption("S") ? QueryRetrieveLevel.SERIES
                    : cl.hasOption("I") ? QueryRetrieveLevel.IMAGE : QueryRetrieveLevel.STUDY);
    if (cl.hasOption("noextneg"))
        dcmqr.setNoExtNegotiation(true);
    if (cl.hasOption("rel"))
        dcmqr.setRelationQR(true);
    if (cl.hasOption("datetime"))
        dcmqr.setDateTimeMatching(true);
    if (cl.hasOption("fuzzy"))
        dcmqr.setFuzzySemanticPersonNameMatching(true);
    if (!cl.hasOption("P")) {
        if (cl.hasOption("retall"))
            dcmqr.addPrivate(UID.PrivateStudyRootQueryRetrieveInformationModelFIND);
        if (cl.hasOption("blocked"))
            dcmqr.addPrivate(UID.PrivateBlockedStudyRootQueryRetrieveInformationModelFIND);
        if (cl.hasOption("vmf"))
            dcmqr.addPrivate(UID.PrivateVirtualMultiframeStudyRootQueryRetrieveInformationModelFIND);
    }
    if (cl.hasOption("cfind")) {
        String[] cuids = cl.getOptionValues("cfind");
        for (int i = 0; i < cuids.length; i++)
            dcmqr.addPrivate(cuids[i]);
    }
    if (!cl.hasOption("nodefret"))
        dcmqr.addDefReturnKeys();
    if (cl.hasOption("r")) {
        String[] returnKeys = cl.getOptionValues("r");
        for (int i = 0; i < returnKeys.length; i++)
            dcmqr.addReturnKey(Tag.toTagPath(returnKeys[i]));
    }
    if (cl.hasOption("q")) {
        String[] matchingKeys = cl.getOptionValues("q");
        for (int i = 1; i < matchingKeys.length; i++, i++)
            dcmqr.addMatchingKey(Tag.toTagPath(matchingKeys[i - 1]), matchingKeys[i]);
    }

    dcmqr.configureTransferCapability(cl.hasOption("ivrle"));

    int repeat = cl.hasOption("repeat")
            ? parseInt(cl.getOptionValue("repeat"), "illegal argument of option -repeat", 1, Integer.MAX_VALUE)
            : 0;
    int interval = cl.hasOption("repeatdelay")
            ? parseInt(cl.getOptionValue("repeatdelay"), "illegal argument of option -repeatdelay", 1,
                    Integer.MAX_VALUE)
            : 0;
    boolean closeAssoc = cl.hasOption("closeassoc");

    if (cl.hasOption("tls")) {
        String cipher = cl.getOptionValue("tls");
        if ("NULL".equalsIgnoreCase(cipher)) {
            dcmqr.setTlsWithoutEncyrption();
        } else if ("3DES".equalsIgnoreCase(cipher)) {
            dcmqr.setTls3DES_EDE_CBC();
        } else if ("AES".equalsIgnoreCase(cipher)) {
            dcmqr.setTlsAES_128_CBC();
        } else {
            exit("Invalid parameter for option -tls: " + cipher);
        }
        if (cl.hasOption("tls1")) {
            dcmqr.setTlsProtocol(TLS1);
        } else if (cl.hasOption("ssl3")) {
            dcmqr.setTlsProtocol(SSL3);
        } else if (cl.hasOption("no_tls1")) {
            dcmqr.setTlsProtocol(NO_TLS1);
        } else if (cl.hasOption("no_ssl3")) {
            dcmqr.setTlsProtocol(NO_SSL3);
        } else if (cl.hasOption("no_ssl2")) {
            dcmqr.setTlsProtocol(NO_SSL2);
        }
        dcmqr.setTlsNeedClientAuth(!cl.hasOption("noclientauth"));
        if (cl.hasOption("keystore")) {
            dcmqr.setKeyStoreURL(cl.getOptionValue("keystore"));
        }
        if (cl.hasOption("keystorepw")) {
            dcmqr.setKeyStorePassword(cl.getOptionValue("keystorepw"));
        }
        if (cl.hasOption("keypw")) {
            dcmqr.setKeyPassword(cl.getOptionValue("keypw"));
        }
        if (cl.hasOption("truststore")) {
            dcmqr.setTrustStoreURL(cl.getOptionValue("truststore"));
        }
        if (cl.hasOption("truststorepw")) {
            dcmqr.setTrustStorePassword(cl.getOptionValue("truststorepw"));
        }
        long t1 = System.currentTimeMillis();
        try {
            dcmqr.initTLS();
        } catch (Exception e) {
            System.err.println("ERROR: Failed to initialize TLS context:" + e.getMessage());
            System.exit(2);
        }
        long t2 = System.currentTimeMillis();
        LOG.info("Initialize TLS context in {} s", Float.valueOf((t2 - t1) / 1000f));
    }
    try {
        dcmqr.start();
    } catch (Exception e) {
        System.err.println(
                "ERROR: Failed to start server for receiving " + "requested objects:" + e.getMessage());
        System.exit(2);
    }
    try {
        long t1 = System.currentTimeMillis();
        try {
            dcmqr.open();
        } catch (Exception e) {
            LOG.error("Failed to establish association:", e);
            System.exit(2);
        }
        long t2 = System.currentTimeMillis();
        LOG.info("Connected to {} in {} s", remoteAE, Float.valueOf((t2 - t1) / 1000f));

        for (;;) {
            List<DicomObject> result;
            if (dcmqr.isCFind()) {
                result = dcmqr.query();
                long t3 = System.currentTimeMillis();
                LOG.info("Received {} matching entries in {} s", Integer.valueOf(result.size()),
                        Float.valueOf((t3 - t2) / 1000f));
                t2 = t3;
            } else {
                result = Collections.singletonList(dcmqr.getKeys());
            }
            if (dcmqr.isCMove() || dcmqr.isCGet()) {
                if (dcmqr.isCMove())
                    dcmqr.move(result);
                else
                    dcmqr.get(result);
                long t4 = System.currentTimeMillis();
                LOG.info("Retrieved {} objects (warning: {}, failed: {}) in {}s",
                        new Object[] { Integer.valueOf(dcmqr.getTotalRetrieved()),
                                Integer.valueOf(dcmqr.getWarning()), Integer.valueOf(dcmqr.getFailed()),
                                Float.valueOf((t4 - t2) / 1000f) });
            }
            if (repeat == 0 || closeAssoc) {
                try {
                    dcmqr.close();
                } catch (InterruptedException e) {
                    LOG.error(e.getMessage(), e);
                }
                LOG.info("Released connection to {}", remoteAE);
            }
            if (repeat-- == 0)
                break;
            Thread.sleep(interval);
            long t4 = System.currentTimeMillis();
            dcmqr.open();
            t2 = System.currentTimeMillis();
            LOG.info("Reconnect or reuse connection to {} in {} s", remoteAE, Float.valueOf((t2 - t4) / 1000f));
        }
    } catch (IOException e) {
        LOG.error(e.getMessage(), e);
    } catch (InterruptedException e) {
        LOG.error(e.getMessage(), e);
    } catch (ConfigurationException e) {
        LOG.error(e.getMessage(), e);
    } finally {
        dcmqr.stop();
    }
}

From source file:de.burlov.amazon.s3.dirsync.CLI.java

/**
 * @param args/*from w w  w. j  a va 2s  .co m*/
 */
@SuppressWarnings("static-access")
public static void main(String[] args) {
    Logger.getLogger("").setLevel(Level.OFF);
    Logger deLogger = Logger.getLogger("de");
    deLogger.setLevel(Level.INFO);
    Handler handler = new ConsoleHandler();
    handler.setFormatter(new VerySimpleFormatter());
    deLogger.addHandler(handler);
    deLogger.setUseParentHandlers(false);
    //      if (true)
    //      {
    //         LogFactory.getLog(CLI.class).error("test msg", new Exception("test extception"));
    //         return;
    //      }
    Options opts = new Options();
    OptionGroup gr = new OptionGroup();

    /*
     * Befehlsgruppe initialisieren
     */
    gr = new OptionGroup();
    gr.setRequired(true);
    gr.addOption(OptionBuilder.withArgName("up|down").hasArg()
            .withDescription("Upload/Download changed or new files").create(CMD_UPDATE));
    gr.addOption(OptionBuilder.withArgName("up|down").hasArg()
            .withDescription("Upload/Download directory snapshot").create(CMD_SNAPSHOT));
    gr.addOption(OptionBuilder.withDescription("Delete remote folder").create(CMD_DELETE_DIR));
    gr.addOption(OptionBuilder.withDescription("Delete a bucket").create(CMD_DELETE_BUCKET));
    gr.addOption(OptionBuilder.create(CMD_HELP));
    gr.addOption(OptionBuilder.create(CMD_VERSION));
    gr.addOption(OptionBuilder.withDescription("Prints summary for stored data").create(CMD_SUMMARY));
    gr.addOption(OptionBuilder.withDescription("Clean up orphaned objekts").create(CMD_CLEANUP));
    gr.addOption(OptionBuilder.withDescription("Changes encryption password").withArgName("new password")
            .hasArg().create(CMD_CHANGE_PASSWORD));
    gr.addOption(OptionBuilder.withDescription("Lists all buckets").create(CMD_LIST_BUCKETS));
    gr.addOption(OptionBuilder.withDescription("Lists raw objects in a bucket").create(CMD_LIST_BUCKET));
    gr.addOption(OptionBuilder.withDescription("Lists files in remote folder").create(CMD_LIST_DIR));
    opts.addOptionGroup(gr);
    /*
     * Parametergruppe initialisieren
     */
    opts.addOption(OptionBuilder.withArgName("key").isRequired(false).hasArg().withDescription("S3 access key")
            .create(OPT_S3S_KEY));
    opts.addOption(OptionBuilder.withArgName("secret").isRequired(false).hasArg()
            .withDescription("Secret key for S3 account").create(OPT_S3S_SECRET));
    opts.addOption(OptionBuilder.withArgName("bucket").isRequired(false).hasArg().withDescription(
            "Optional bucket name for storage. If not specified then an unique bucket name will be generated")
            .create(OPT_BUCKET));
    // opts.addOption(OptionBuilder.withArgName("US|EU").hasArg().
    // withDescription(
    // "Where the new bucket should be created. Default US").create(
    // OPT_LOCATION));
    opts.addOption(OptionBuilder.withArgName("path").isRequired(false).hasArg()
            .withDescription("Local directory path").create(OPT_LOCAL_DIR));
    opts.addOption(OptionBuilder.withArgName("name").isRequired(false).hasArg()
            .withDescription("Remote directory name").create(OPT_REMOTE_DIR));
    opts.addOption(OptionBuilder.withArgName("password").isRequired(false).hasArg()
            .withDescription("Encryption password").create(OPT_ENC_PASSWORD));
    opts.addOption(OptionBuilder.withArgName("patterns").hasArgs()
            .withDescription("Comma separated exclude file patterns like '*.tmp,*/dir/*.tmp'")
            .create(OPT_EXCLUDE_PATTERNS));
    opts.addOption(OptionBuilder.withArgName("patterns").hasArgs().withDescription(
            "Comma separated include patterns like '*.java'. If not specified, then all files in specified local directory will be included")
            .create(OPT_INCLUDE_PATTERNS));

    if (args.length == 0) {
        printUsage(opts);
        return;
    }

    CommandLine cmd = null;
    try {
        cmd = new GnuParser().parse(opts, args);
        if (cmd.hasOption(CMD_HELP)) {
            printUsage(opts);
            return;
        }
        if (cmd.hasOption(CMD_VERSION)) {
            System.out.println("s3dirsync version " + Version.CURRENT_VERSION);
            return;
        }
        String awsKey = cmd.getOptionValue(OPT_S3S_KEY);
        String awsSecret = cmd.getOptionValue(OPT_S3S_SECRET);
        String bucket = cmd.getOptionValue(OPT_BUCKET);
        String bucketLocation = cmd.getOptionValue(OPT_LOCATION);
        String localDir = cmd.getOptionValue(OPT_LOCAL_DIR);
        String remoteDir = cmd.getOptionValue(OPT_REMOTE_DIR);
        String password = cmd.getOptionValue(OPT_ENC_PASSWORD);
        String exclude = cmd.getOptionValue(OPT_EXCLUDE_PATTERNS);
        String include = cmd.getOptionValue(OPT_INCLUDE_PATTERNS);

        if (StringUtils.isBlank(awsKey) || StringUtils.isBlank(awsSecret)) {
            System.out.println("S3 account data required");
            return;
        }

        if (StringUtils.isBlank(bucket)) {
            bucket = awsKey + ".dirsync";
        }

        if (cmd.hasOption(CMD_DELETE_BUCKET)) {
            if (StringUtils.isBlank(bucket)) {
                System.out.println("Bucket name required");
                return;
            }
            int deleted = S3Utils.deleteBucket(awsKey, awsSecret, bucket);
            System.out.println("Deleted objects: " + deleted);
            return;
        }
        if (cmd.hasOption(CMD_LIST_BUCKETS)) {
            for (String str : S3Utils.listBuckets(awsKey, awsSecret)) {
                System.out.println(str);
            }
            return;
        }
        if (cmd.hasOption(CMD_LIST_BUCKET)) {
            if (StringUtils.isBlank(bucket)) {
                System.out.println("Bucket name required");
                return;
            }
            for (String str : S3Utils.listObjects(awsKey, awsSecret, bucket)) {
                System.out.println(str);
            }
            return;
        }
        if (StringUtils.isBlank(password)) {
            System.out.println("Encryption password required");
            return;
        }
        char[] psw = password.toCharArray();
        DirSync ds = new DirSync(awsKey, awsSecret, bucket, bucketLocation, psw);
        ds.setExcludePatterns(parseSubargumenths(exclude));
        ds.setIncludePatterns(parseSubargumenths(include));
        if (cmd.hasOption(CMD_SUMMARY)) {
            ds.printStorageSummary();
            return;
        }
        if (StringUtils.isBlank(remoteDir)) {
            System.out.println("Remote directory name required");
            return;
        }
        if (cmd.hasOption(CMD_DELETE_DIR)) {
            ds.deleteFolder(remoteDir);
            return;
        }
        if (cmd.hasOption(CMD_LIST_DIR)) {
            Folder folder = ds.getFolder(remoteDir);
            if (folder == null) {
                System.out.println("No such folder found: " + remoteDir);
                return;
            }
            for (Map.Entry<String, FileInfo> entry : folder.getIndexData().entrySet()) {
                System.out.println(entry.getKey() + " ("
                        + FileUtils.byteCountToDisplaySize(entry.getValue().getLength()) + ")");
            }
            return;
        }
        if (cmd.hasOption(CMD_CLEANUP)) {
            ds.cleanUp();
            return;
        }
        if (cmd.hasOption(CMD_CHANGE_PASSWORD)) {
            String newPassword = cmd.getOptionValue(CMD_CHANGE_PASSWORD);
            if (StringUtils.isBlank(newPassword)) {
                System.out.println("new password required");
                return;
            }
            char[] chars = newPassword.toCharArray();
            ds.changePassword(chars);
            newPassword = null;
            Arrays.fill(chars, ' ');
            return;
        }
        if (StringUtils.isBlank(localDir)) {
            System.out.println(OPT_LOCAL_DIR + " argument required");
            return;
        }
        String direction = "";
        boolean up = false;
        boolean snapshot = false;
        if (StringUtils.isNotBlank(cmd.getOptionValue(CMD_UPDATE))) {
            direction = cmd.getOptionValue(CMD_UPDATE);
        } else if (StringUtils.isNotBlank(cmd.getOptionValue(CMD_SNAPSHOT))) {
            direction = cmd.getOptionValue(CMD_SNAPSHOT);
            snapshot = true;
        }
        if (StringUtils.isBlank(direction)) {
            System.out.println("Operation direction required");
            return;
        }
        up = StringUtils.equalsIgnoreCase(OPT_UP, direction);
        File baseDir = new File(localDir);
        if (!baseDir.exists() && !baseDir.mkdirs()) {
            System.out.println("Invalid local directory: " + baseDir.getAbsolutePath());
            return;
        }
        ds.syncFolder(baseDir, remoteDir, up, snapshot);

    } catch (DirSyncException e) {
        System.out.println(e.getMessage());
        e.printStackTrace();
    } catch (ParseException e) {
        System.out.println(e.getMessage());
        printUsage(opts);

    } catch (Exception e) {
        e.printStackTrace(System.err);
    }
}

From source file:Manifest.java

public static void main(String[] args) throws Exception {
    // Set the default values of the command-line arguments
    boolean verify = false; // Verify manifest or create one?
    String manifestfile = "MANIFEST"; // Manifest file name
    String digestAlgorithm = "MD5"; // Algorithm for message digests
    String signername = null; // Signer. No sig. by default
    String signatureAlgorithm = "DSA"; // Algorithm for digital sig.
    String password = null; // Private keys are protected
    File keystoreFile = null; // Where are keys stored
    String keystoreType = null; // What kind of keystore
    String keystorePassword = null; // How to access keystore
    List filelist = new ArrayList(); // The files to digest

    // Parse the command-line arguments, overriding the defaults above
    for (int i = 0; i < args.length; i++) {
        if (args[i].equals("-v"))
            verify = true;//from   w  ww.j a va2s.com
        else if (args[i].equals("-m"))
            manifestfile = args[++i];
        else if (args[i].equals("-da") && !verify)
            digestAlgorithm = args[++i];
        else if (args[i].equals("-s") && !verify)
            signername = args[++i];
        else if (args[i].equals("-sa") && !verify)
            signatureAlgorithm = args[++i];
        else if (args[i].equals("-p"))
            password = args[++i];
        else if (args[i].equals("-keystore"))
            keystoreFile = new File(args[++i]);
        else if (args[i].equals("-keystoreType"))
            keystoreType = args[++i];
        else if (args[i].equals("-keystorePassword"))
            keystorePassword = args[++i];

        else if (!verify)
            filelist.add(args[i]);
        else
            throw new IllegalArgumentException(args[i]);
    }

    // If certain arguments weren't supplied, get default values.
    if (keystoreFile == null) {
        File dir = new File(System.getProperty("user.home"));
        keystoreFile = new File(dir, ".keystore");
    }
    if (keystoreType == null)
        keystoreType = KeyStore.getDefaultType();
    if (keystorePassword == null)
        keystorePassword = password;

    if (!verify && signername != null && password == null) {
        System.out.println("Use -p to specify a password.");
        return;
    }

    // Get the keystore we'll use for signing or verifying signatures
    // If no password was provided, then assume we won't be dealing with
    // signatures, and skip the keystore.
    KeyStore keystore = null;
    if (keystorePassword != null) {
        keystore = KeyStore.getInstance(keystoreType);
        InputStream in = new BufferedInputStream(new FileInputStream(keystoreFile));
        keystore.load(in, keystorePassword.toCharArray());
    }

    // If -v was specified or no file were given, verify a manifest
    // Otherwise, create a new manifest for the specified files
    if (verify || (filelist.size() == 0))
        verify(manifestfile, keystore);
    else
        create(manifestfile, digestAlgorithm, signername, signatureAlgorithm, keystore, password, filelist);
}