Example usage for java.lang String indexOf

List of usage examples for java.lang String indexOf

Introduction

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

Prototype

public int indexOf(String str) 

Source Link

Document

Returns the index within this string of the first occurrence of the specified substring.

Usage

From source file:net.sf.freecol.FreeCol.java

/**
 * The entrypoint.// w  w w  .  j a  va 2s .  c  om
 *
 * @param args The command-line arguments.
 * @throws IOException 
 * @throws FontFormatException 
 */
public static void main(String[] args) throws FontFormatException, IOException {
    freeColRevision = FREECOL_VERSION;
    JarURLConnection juc;
    try {
        juc = getJarURLConnection(FreeCol.class);
    } catch (IOException ioe) {
        juc = null;
        System.err.println("Unable to open class jar: " + ioe.getMessage());
    }
    if (juc != null) {
        try {
            String revision = readVersion(juc);
            if (revision != null) {
                freeColRevision += " (Revision: " + revision + ")";
            }
        } catch (Exception e) {
            System.err.println("Unable to load Manifest: " + e.getMessage());
        }
        try {
            splashStream = getDefaultSplashStream(juc);
        } catch (Exception e) {
            System.err.println("Unable to open default splash: " + e.getMessage());
        }
    }

    // Java bug #7075600 causes BR#2554.  The workaround is to set
    // the following property.  Remove if/when they fix Java.
    System.setProperty("java.util.Arrays.useLegacyMergeSort", "true");

    // We can not even emit localized error messages until we find
    // the data directory, which might have been specified on the
    // command line.
    String dataDirectoryArg = findArg("--freecol-data", args);
    String err = FreeColDirectories.setDataDirectory(dataDirectoryArg);
    if (err != null)
        fatal(err); // This must not fail.

    // Now we have the data directory, establish the base locale.
    // Beware, the locale may change!
    String localeArg = findArg("--default-locale", args);
    if (localeArg == null) {
        locale = Locale.getDefault();
    } else {
        int index = localeArg.indexOf('.'); // Strip encoding if present
        if (index > 0)
            localeArg = localeArg.substring(0, index);
        locale = Messages.getLocale(localeArg);
    }
    Messages.loadMessageBundle(locale);

    // Now that we can emit error messages, parse the other
    // command line arguments.
    handleArgs(args);

    // Do the potentially fatal system checks as early as possible.
    if (javaCheck && JAVA_VERSION_MIN.compareTo(JAVA_VERSION) > 0) {
        fatal(StringTemplate.template("main.javaVersion").addName("%version%", JAVA_VERSION)
                .addName("%minVersion%", JAVA_VERSION_MIN));
    }
    if (memoryCheck && MEMORY_MAX < MEMORY_MIN * 1000000) {
        fatal(StringTemplate.template("main.memory").addAmount("%memory%", MEMORY_MAX).addAmount("%minMemory%",
                MEMORY_MIN));
    }

    // Having parsed the command line args, we know where the user
    // directories should be, so we can set up the rest of the
    // file/directory structure.
    String userMsg = FreeColDirectories.setUserDirectories();

    // Now we have the log file path, start logging.
    final Logger baseLogger = Logger.getLogger("");
    final Handler[] handlers = baseLogger.getHandlers();
    for (Handler handler : handlers) {
        baseLogger.removeHandler(handler);
    }
    String logFile = FreeColDirectories.getLogFilePath();
    try {
        baseLogger.addHandler(new DefaultHandler(consoleLogging, logFile));
        Logger freecolLogger = Logger.getLogger("net.sf.freecol");
        freecolLogger.setLevel(logLevel);
    } catch (FreeColException e) {
        System.err.println("Logging initialization failure: " + e.getMessage());
        e.printStackTrace();
    }
    Thread.setDefaultUncaughtExceptionHandler((Thread thread, Throwable e) -> {
        baseLogger.log(Level.WARNING, "Uncaught exception from thread: " + thread, e);
    });

    // Now we can find the client options, allow the options
    // setting to override the locale, if no command line option
    // had been specified.
    // We have users whose machines default to Finnish but play
    // FreeCol in English.
    // If the user has selected automatic language selection, do
    // nothing, since we have already set up the default locale.
    if (localeArg == null) {
        String clientLanguage = ClientOptions.getLanguageOption();
        Locale clientLocale;
        if (clientLanguage != null && !Messages.AUTOMATIC.equalsIgnoreCase(clientLanguage)
                && (clientLocale = Messages.getLocale(clientLanguage)) != locale) {
            locale = clientLocale;
            Messages.loadMessageBundle(locale);
            logger.info("Loaded messages for " + locale);
        }
    }

    // Now we have the user mods directory and the locale is now
    // stable, load the mods and their messages.
    Mods.loadMods();
    Messages.loadModMessageBundle(locale);

    // Report on where we are.
    if (userMsg != null)
        logger.info(Messages.message(userMsg));
    logger.info(getConfiguration().toString());

    // Ready to specialize into client or server.
    if (standAloneServer) {
        startServer();
    } else {
        startClient(userMsg);
    }
    startYourAddition();
}

From source file:com.joliciel.jochre.Jochre.java

public static void main(String[] args) throws Exception {
    Map<String, String> argMap = new HashMap<String, String>();

    for (String arg : args) {
        int equalsPos = arg.indexOf('=');
        String argName = arg.substring(0, equalsPos);
        String argValue = arg.substring(equalsPos + 1);
        argMap.put(argName, argValue);/*from   ww  w.ja  v  a 2  s  .  c o  m*/
    }

    Jochre jochre = new Jochre();
    jochre.execute(argMap);
}

From source file:org.jets3t.apps.uploader.Uploader.java

/**
 * Run the Uploader as a stand-alone application.
 *
 * @param args//from   w  w  w .  j  ava  2 s .c  om
 * @throws Exception
 */
public static void main(String args[]) throws Exception {
    JFrame ownerFrame = new JFrame("JetS3t Uploader");
    ownerFrame.addWindowListener(new WindowListener() {
        public void windowOpened(WindowEvent e) {
        }

        public void windowClosing(WindowEvent e) {
            e.getWindow().dispose();
        }

        public void windowClosed(WindowEvent e) {
        }

        public void windowIconified(WindowEvent e) {
        }

        public void windowDeiconified(WindowEvent e) {
        }

        public void windowActivated(WindowEvent e) {
        }

        public void windowDeactivated(WindowEvent e) {
        }
    });

    // Read arguments as properties of the form: <propertyName>'='<propertyValue>
    Properties argumentProperties = new Properties();
    if (args.length > 0) {
        for (int i = 0; i < args.length; i++) {
            String arg = args[i];
            int delimIndex = arg.indexOf("=");
            if (delimIndex >= 0) {
                String name = arg.substring(0, delimIndex);
                String value = arg.substring(delimIndex + 1);
                argumentProperties.put(name, value);
            } else {
                System.out.println("Ignoring property argument with incorrect format: " + arg);
            }
        }
    }

    new Uploader(ownerFrame, argumentProperties);
}

From source file:DcmQR.java

@SuppressWarnings("unchecked")
public static void main(String[] args) {
    CommandLine cl = parse(args);/* w ww.  ja  va2 s .c o 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:codesample.AuthenticationSample.java

/*****************************************************************************************************************
 *
 * The main method.//from www .  java  2  s . c  o m
 *
 * @param args Not used.
 * @throws IOException If it fails to create log files.
 *
 *****************************************************************************************************************
 */
public static void main(String[] args) throws IOException {
    // Return codes
    final int SUCCESS = 0;
    final int FAILURE = 1;

    int returnCode = SUCCESS;

    // Hostname to use when connecting to web service. Must contain the fully qualified domain name.
    String bwsHostname = "<bwsHostName>"; // e.g. bwsHostname = "server01.example.net".

    // Port to use when connecting to web service. The same port is used to access the
    // management console in BDS and UDS.  Default ports: BDS=38443, UDS=18082, UEM12=18084
    String bwsPort = "<bwsPort>"; // e.g. bwsPort = "18084".

    // Credential type used in the authentication process.
    CredentialType credentialType = new CredentialType();
    credentialType.setPASSWORD(true);
    credentialType.setValue("PASSWORD");

    /*
     * BWS Host certificate must be installed on the client machine before running this sample code, otherwise a
     * SSL/TLS secure channel error will be thrown. For more information, see the BlackBerry Web Services for
     * Enterprise Administration For Java Developers Getting Started Guide.
     *
     * To test authentication populate the methods below with the appropriate credentials and information
     */

    // Select which authentication methods you would like to test by setting the variables to true
    boolean useAD = true; // Active Directory
    boolean useLDAP = true; // LDAP

    try {
        if (bwsHostname.indexOf('.') < 1) {
            throw new Exception("Invalid bwsHostname format. Expected format is \"server01.example.net\"");
        }
        // bwsPort, if not null, must be a positive integer
        if (bwsPort != null) {
            int port = Integer.parseInt(bwsPort);

            if (port < 1) {
                throw new Exception("Invalid bwsPort. Expecting a positive integer string or null");
            }
        }

        returnCode = (demonstrateBlackBerryAdministrationServiceAuthentication(bwsHostname, bwsPort,
                credentialType)) ? SUCCESS : FAILURE;
        logMessage("");
        if (useAD && returnCode == SUCCESS) {
            returnCode = (demonstrateActiveDirectoryAuthentication(bwsHostname, bwsPort, credentialType))
                    ? SUCCESS
                    : FAILURE;
            logMessage("");
        }
        if (useLDAP && returnCode == SUCCESS) {
            returnCode = (demonstrateLDAPAuthentication(bwsHostname, bwsPort, credentialType)) ? SUCCESS
                    : FAILURE;
            logMessage("");
        }
    } catch (Exception e) {
        logMessage("Exception: \"%s\"%n", e.getMessage());
        e.printStackTrace();
        returnCode = FAILURE;
    }

    System.err.format("Exiting sample.%nPress Enter to exit%n");
    System.in.read();

    System.exit(returnCode);
}

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 av a  2 s.com*/
    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:main.DOORS_Service.java

/**
 * Login to the DWA server and perform some OSLC actions
 * @param args//w  ww  .jav  a2 s.  co  m
 * @throws ParseException 
 */
public static void main(String[] args) throws ParseException {

    Options options = new Options();

    options.addOption("url", true, "url");
    options.addOption("user", true, "user ID");
    options.addOption("password", true, "password");
    options.addOption("project", true, "project area");

    CommandLineParser cliParser = new GnuParser();

    //Parse the command line
    CommandLine cmd = cliParser.parse(options, args);

    if (!validateOptions(cmd)) {
        logger.severe(
                "Syntax:  java <class_name> -url https://<server>:port/<context>/ -user <user> -password <password> -project \"<project_area>\"");
        logger.severe(
                "Example: java DoorsOauthSample -url https://exmple.com:9443/dwa -user ADMIN -password ADMIN -project \"JKE Banking (Requirements Management)\"");
        return;
    }

    String webContextUrl = cmd.getOptionValue("url");
    String user = cmd.getOptionValue("user");
    String passwd = cmd.getOptionValue("password");
    String projectArea = cmd.getOptionValue("project");

    try {
        //STEP 1: Initialize a Jazz rootservices helper and indicate we're looking for the RequirementManagement catalog
        // The root services for DOORs is found at /public level
        JazzRootServicesHelper helper = new JazzRootServicesHelper(webContextUrl + "/public",
                OSLCConstants.OSLC_RM);

        //STEP 2: Create a new OSLC OAuth capable client
        OslcOAuthClient client = helper.initOAuthClient("JIRA", "JIRA");

        if (client != null) {
            //STEP 3: Try to access the context URL to trigger the OAuth dance and login
            try {
                client.getResource(webContextUrl, OSLCConstants.CT_RDF);
            } catch (OAuthRedirectException oauthE) {
                validateTokens(client,
                        oauthE.getRedirectURL() + "?oauth_token=" + oauthE.getAccessor().requestToken, user,
                        passwd, webContextUrl + "/j_acegi_security_check");
                // Try to access again
                ClientResponse response = client.getResource(webContextUrl, OSLCConstants.CT_RDF);
                response.getEntity(InputStream.class).close();
            }

            //STEP 4: Get our requirements collection that we want
            //TODO: Replace with option from startup
            String serviceProviderUrl = "http://usnx47:8080/dwa/rm/urn:rational::1-4d2b67b464226e12-M-0000048a";
            ClientResponse response = client.getResource(serviceProviderUrl,
                    "application/x-oslc-rm-requirement-collection-1.0+xml");
            //build the rdf
            Model rdfModel = ModelFactory.createDefaultModel();
            rdfModel.read(response.getEntity(InputStream.class), serviceProviderUrl);
            response.consumeContent();

            //get the statements
            List<Statement> reqs = rdfModel.getResource(serviceProviderUrl).listProperties().toList();
            HashMap<String, String> requirements = new HashMap<String, String>();
            for (Statement s : reqs) {

                String reqURI = s.getObject().toString();
                if (reqURI.contains("http")) {
                    response = client.getResource(reqURI, "application/x-oslc-rm-requirement-1.0+xml");
                    if (response.getStatusCode() == 200) {
                        InputStream in = response.getEntity(InputStream.class);
                        Model model = ModelFactory.createDefaultModel();

                        try {
                            model.read(in, reqURI);
                        } catch (Exception sa) {
                            System.out.println(reqURI);
                        }

                        //Properties to traverse on
                        Property attrDef = model
                                .createProperty("http://jazz.net/doors/xmlns/prod/jazz/doors/1.0/attrDef");
                        Property name = model
                                .createProperty("http://jazz.net/doors/xmlns/prod/jazz/doors/1.0/name");

                        //Flags we use for parsing
                        int count = 0;
                        boolean isText = false;
                        boolean isID = false;
                        boolean done = false;
                        //Text of the DOORS Object and its ID are what we are going to extract
                        String text = "";
                        String id = "";

                        //Look through all of the possible fields
                        StmtIterator statementIter = model.listStatements();
                        while (statementIter.hasNext() && done != true) {
                            Statement field = statementIter.next();
                            //Get the attrDef property to find out what kind of value we have
                            StmtIterator props = field.getSubject().listProperties(attrDef);
                            while (props.hasNext() && done != true) {
                                Statement kind = props.next();
                                RDFNode propertyNode = kind.getObject();
                                StmtIterator propIt = propertyNode.asResource().listProperties(name);
                                //Check all of the properties for our desired fields
                                while (propIt.hasNext()) {
                                    Statement node = propIt.next();
                                    if (node.getObject().isLiteral()) {
                                        if (node.getObject().toString().contains("Object+Text")
                                                && field.getObject().isLiteral()) {
                                            text = field.getLiteral().toString();
                                            text = text.substring(0, text.indexOf("^"));
                                            count++;

                                        }
                                        if (node.getObject().toString().contains("Absolute+Number")
                                                && field.getObject().isLiteral()) {
                                            id = field.getLiteral().toString();
                                            id = id.substring(0, id.indexOf("^"));
                                            count++;
                                        }

                                    }
                                }
                                if (count == 2) {
                                    if (!text.isEmpty()) {
                                        //System.out.println( "Req: " + id );
                                        //System.out.println( text );
                                        requirements.put(id, text);
                                        count = 0;
                                        done = true;
                                        break;
                                    }

                                }
                            }

                        }

                    }

                }
                response.consumeContent();
            }
            //check if already in JIRA
            //post to jira
            for (Entry<String, String> e : requirements.entrySet()) {

            }
        }

    } catch (Exception e) {
        logger.log(Level.SEVERE, e.getMessage(), e);
    }

}

From source file:GoogleImages.java

public static void main(String[] args) throws InterruptedException {
    String searchTerm = "s woman"; // term to search for (use spaces to separate terms)
    int offset = 40; // we can only 20 results at a time - use this to offset and get more!
    String fileSize = "50mp"; // specify file size in mexapixels (S/M/L not figured out yet)
    String source = null; // string to save raw HTML source code

    // format spaces in URL to avoid problems
    searchTerm = searchTerm.replaceAll(" ", "%20");

    // get Google image search HTML source code; mostly built from PhyloWidget example:
    // http://code.google.com/p/phylowidget/source/browse/trunk/PhyloWidget/src/org/phylowidget/render/images/ImageSearcher.java
    int offset2 = 0;
    Set urlsss = new HashSet<String>();
    while (offset2 < 600) {
        try {//  w  w w .j  av  a  2s.c o  m
            URL query = new URL("https://www.google.ru/search?start=" + offset2
                    + "&q=angry+woman&newwindow=1&client=opera&hs=bPE&source=lnms&tbm=isch&sa=X&ved=0ahUKEwiAgcKozIfNAhWoHJoKHSb_AUoQ_AUIBygB&biw=1517&bih=731&dpr=0.9#imgrc=G_1tH3YOPcc8KM%3A");
            HttpURLConnection urlc = (HttpURLConnection) query.openConnection(); // start connection...
            urlc.setInstanceFollowRedirects(true);
            urlc.setRequestProperty("User-Agent", "");
            urlc.connect();
            BufferedReader in = new BufferedReader(new InputStreamReader(urlc.getInputStream())); // stream in HTTP source to file
            StringBuffer response = new StringBuffer();
            char[] buffer = new char[1024];
            while (true) {
                int charsRead = in.read(buffer);
                if (charsRead == -1) {
                    break;
                }
                response.append(buffer, 0, charsRead);
            }
            in.close(); // close input stream (also closes network connection)
            source = response.toString();
        } // any problems connecting? let us know
        catch (Exception e) {
            e.printStackTrace();
        }

        // print full source code (for debugging)
        // println(source);
        // extract image URLs only, starting with 'imgurl'
        if (source != null) {
            //                System.out.println(source);
            int c = StringUtils.countMatches(source, "http://www.vmir.su");
            System.out.println(c);
            int index = source.indexOf("src=");
            System.out.println(source.subSequence(index, index + 200));
            while (index >= 0) {
                System.out.println(index);
                index = source.indexOf("src=", index + 1);
                if (index == -1) {
                    break;
                }
                String rr = source.substring(index,
                        index + 200 > source.length() ? source.length() : index + 200);

                if (rr.contains("\"")) {
                    rr = rr.substring(5, rr.indexOf("\"", 5));
                }
                System.out.println(rr);
                urlsss.add(rr);
            }
        }
        offset2 += 20;
        Thread.sleep(1000);
        System.out.println("off set = " + offset2);

    }

    System.out.println(urlsss);
    urlsss.forEach(new Consumer<String>() {

        public void accept(String s) {
            try {
                saveImage(s, "C:\\Users\\Java\\Desktop\\ang\\" + UUID.randomUUID().toString() + ".jpg");
            } catch (IOException ex) {
                Logger.getLogger(GoogleImages.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    });
    //            String[][] m = matchAll(source, "img height=\"\\d+\" src=\"([^\"]+)\"");

    // older regex, no longer working but left for posterity
    // built partially from: http://www.mkyong.com/regular-expressions/how-to-validate-image-file-extension-with-regular-expression
    // String[][] m = matchAll(source, "imgurl=(.*?\\.(?i)(jpg|jpeg|png|gif|bmp|tif|tiff))");    // (?i) means case-insensitive
    //            for (int i = 0; i < m.length; i++) {                                                          // iterate all results of the match
    //                println(i + ":\t" + m[i][1]);                                                         // print (or store them)**
    //            }
}

From source file:de.citec.csra.elancsv.parser.SimpleParser.java

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

    Options opts = new Options();
    opts.addOption("file", true, "Tab-separated ELAN export file to load.");
    opts.addOption("tier", true,
            "Tier to analyze. Optional: Append ::num to interpret annotations numerically.");
    opts.addOption("format", true,
            "How to read information from the file name. %V -> participant, %A -> annoatator, %C -> condition, e.g. \"%V - %A\"");
    opts.addOption("help", false, "Print this help and exit");

    CommandLineParser parser = new BasicParser();
    CommandLine cmd = parser.parse(opts, args);
    if (cmd.hasOption("help")) {
        helpExit(opts, "where OPTION includes:");
    }//from w  w  w .j av  a  2s  .  c om

    String infile = cmd.getOptionValue("file");
    if (infile == null) {
        helpExit(opts, "Error: no file given.");
    }

    String format = cmd.getOptionValue("format");
    if (format == null) {
        helpExit(opts, "Error: no format given.");
    }

    String tier = cmd.getOptionValue("tier");
    if (tier == null) {
        helpExit(opts, "Error: no tier given.");
    }

    //      TODO count values in annotations (e.g. search all robot occurrences)
    String[] tn = tier.split("::");
    boolean numeric = false;
    if (tn.length == 2 && tn[1].equals("num")) {
        numeric = true;
        tier = tn[0];
    }

    format = "^" + format + "$";
    format = format.replaceFirst("%V", "(?<V>.*?)");
    format = format.replaceFirst("%A", "(?<A>.*?)");
    format = format.replaceFirst("%C", "(?<C>.*?)");
    Pattern pa = Pattern.compile(format);

    Map<String, Participant> participants = new HashMap<>();
    BufferedReader br = new BufferedReader(new FileReader(infile));
    String line;
    int lineno = 0;
    while ((line = br.readLine()) != null) {
        String[] parts = line.split("\t");
        lineno++;
        if (parts.length < 5) {
            System.err.println("WARNING: line '" + lineno + "' too short '" + line + "'");
            continue;
        }
        Annotation a = new Annotation(Long.valueOf(parts[ElanFormat.START.field]),
                Long.valueOf(parts[ElanFormat.STOP.field]), Long.valueOf(parts[ElanFormat.DURATION.field]),
                parts[ElanFormat.VALUE.field]);
        String tname = parts[ElanFormat.TIER.field];
        String file = parts[ElanFormat.FILE.field].replaceAll(".eaf", "");

        Matcher m = pa.matcher(file);
        String vp = file;
        String condition = "?";
        String annotator = "?";
        String participantID = vp;

        if (m.find()) {
            vp = m.group("V");
            if (format.indexOf("<A>") > 0) {
                annotator = m.group("A");
            }

            if (format.indexOf("<C>") > 0) {
                condition = m.group("C");
            }
        }
        participantID = vp + ";" + annotator;

        if (!participants.containsKey(participantID)) {
            participants.put(participantID, new Participant(vp, condition, annotator));
        }
        Participant p = participants.get(participantID);

        if (!p.tiers.containsKey(tname)) {
            p.tiers.put(tname, new Tier(tname));
        }

        p.tiers.get(tname).annotations.add(a);

    }

    Map<String, Map<String, Number>> values = new HashMap<>();
    Set<String> rownames = new HashSet<>();

    String allCountKey = "c: all values";
    String allDurationKey = "d: all values";
    String allMeanKey = "m: all values";

    for (Map.Entry<String, Participant> e : participants.entrySet()) {
        //         System.out.println(e);
        Tier t = e.getValue().tiers.get(tier);
        String participantID = e.getKey();

        if (!values.containsKey(participantID)) {
            values.put(participantID, new HashMap<String, Number>());
        }
        Map<String, Number> row = values.get(participantID); //participant id

        if (t != null) {

            row.put(allCountKey, 0l);
            row.put(allDurationKey, 0l);
            row.put(allMeanKey, 0l);

            for (Annotation a : t.annotations) {

                long countAll = (long) row.get(allCountKey) + 1;
                long durationAll = (long) row.get(allDurationKey) + a.duration;
                long meanAll = durationAll / countAll;

                row.put(allCountKey, countAll);
                row.put(allDurationKey, durationAll);
                row.put(allMeanKey, meanAll);

                if (!numeric) {
                    String countKey = "c: " + a.value;
                    String durationKey = "d: " + a.value;
                    String meanKey = "m: " + a.value;

                    if (!row.containsKey(countKey)) {
                        row.put(countKey, 0l);
                    }
                    if (!row.containsKey(durationKey)) {
                        row.put(durationKey, 0l);
                    }
                    if (!row.containsKey(meanKey)) {
                        row.put(meanKey, 0d);
                    }

                    long count = (long) row.get(countKey) + 1;
                    long duration = (long) row.get(durationKey) + a.duration;
                    double mean = duration * 1.0 / count;

                    row.put(countKey, count);
                    row.put(durationKey, duration);
                    row.put(meanKey, mean);

                    rownames.add(countKey);
                    rownames.add(durationKey);
                    rownames.add(meanKey);
                } else {
                    String countKey = "c: " + t.name;
                    String sumKey = "s: " + t.name;
                    String meanKey = "m: " + t.name;

                    if (!row.containsKey(countKey)) {
                        row.put(countKey, 0l);
                    }
                    if (!row.containsKey(sumKey)) {
                        row.put(sumKey, 0d);
                    }
                    if (!row.containsKey(meanKey)) {
                        row.put(meanKey, 0d);
                    }

                    double d = 0;
                    try {
                        d = Double.valueOf(a.value);
                    } catch (NumberFormatException ex) {

                    }

                    long count = (long) row.get(countKey) + 1;
                    double sum = (double) row.get(sumKey) + d;
                    double mean = sum / count;

                    row.put(countKey, count);
                    row.put(sumKey, sum);
                    row.put(meanKey, mean);

                    rownames.add(countKey);
                    rownames.add(sumKey);
                    rownames.add(meanKey);
                }

            }
        }

    }

    ArrayList<String> list = new ArrayList(rownames);
    Collections.sort(list);
    StringBuilder header = new StringBuilder("ID;Annotator;");
    header.append(allCountKey);
    header.append(";");
    header.append(allDurationKey);
    header.append(";");
    header.append(allMeanKey);
    header.append(";");
    for (String l : list) {
        header.append(l);
        header.append(";");
    }
    System.out.println(header);

    for (Map.Entry<String, Map<String, Number>> e : values.entrySet()) {
        StringBuilder row = new StringBuilder(e.getKey());
        row.append(";");
        if (e.getValue().containsKey(allCountKey)) {
            row.append(e.getValue().get(allCountKey));
        } else {
            row.append("0");
        }
        row.append(";");
        if (e.getValue().containsKey(allDurationKey)) {
            row.append(e.getValue().get(allDurationKey));
        } else {
            row.append("0");
        }
        row.append(";");
        if (e.getValue().containsKey(allMeanKey)) {
            row.append(e.getValue().get(allMeanKey));
        } else {
            row.append("0");
        }
        row.append(";");
        for (String l : list) {
            if (e.getValue().containsKey(l)) {
                row.append(e.getValue().get(l));
            } else {
                row.append("0");
            }
            row.append(";");
        }
        System.out.println(row);
    }
}

From source file:tuit.java

@SuppressWarnings("ConstantConditions")
public static void main(String[] args) {
    System.out.println(licence);/*w ww. j a  v  a  2 s.  c om*/
    //Declare variables
    File inputFile;
    File outputFile;
    File tmpDir;
    File blastnExecutable;
    File properties;
    File blastOutputFile = null;
    //
    TUITPropertiesLoader tuitPropertiesLoader;
    TUITProperties tuitProperties;
    //
    String[] parameters = null;
    //
    Connection connection = null;
    MySQL_Connector mySQL_connector;
    //
    Map<Ranks, TUITCutoffSet> cutoffMap;
    //
    BLASTIdentifier blastIdentifier = null;
    //
    RamDb ramDb = null;

    CommandLineParser parser = new GnuParser();
    Options options = new Options();

    options.addOption(tuit.IN, "input<file>", true, "Input file (currently fasta-formatted only)");
    options.addOption(tuit.OUT, "output<file>", true, "Output file (in " + tuit.TUIT_EXT + " format)");
    options.addOption(tuit.P, "prop<file>", true, "Properties file (XML formatted)");
    options.addOption(tuit.V, "verbose", false, "Enable verbose output");
    options.addOption(tuit.B, "blast_output<file>", true, "Perform on a pre-BLASTed output");
    options.addOption(tuit.DEPLOY, "deploy", false, "Deploy the taxonomic databases");
    options.addOption(tuit.UPDATE, "update", false, "Update the taxonomic databases");
    options.addOption(tuit.USE_DB, "usedb", false, "Use RDBMS instead of RAM-based taxonomy");

    Option option = new Option(tuit.REDUCE, "reduce", true,
            "Pack identical (100% similar sequences) records in the given sample file");
    option.setArgs(Option.UNLIMITED_VALUES);
    options.addOption(option);
    option = new Option(tuit.COMBINE, "combine", true,
            "Combine a set of given reduction files into an HMP Tree-compatible taxonomy");
    option.setArgs(Option.UNLIMITED_VALUES);
    options.addOption(option);
    options.addOption(tuit.NORMALIZE, "normalize", false,
            "If used in combination with -combine ensures that the values are normalized by the root value");

    HelpFormatter formatter = new HelpFormatter();

    try {

        //Get TUIT directory
        final File tuitDir = new File(
                new File(tuit.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath())
                        .getParent());
        final File ramDbFile = new File(tuitDir, tuit.RAM_DB);

        //Setup logger
        Log.getInstance().setLogName("tuit.log");

        //Read command line
        final CommandLine commandLine = parser.parse(options, args, true);

        //Check if the REDUCE option is on
        if (commandLine.hasOption(tuit.REDUCE)) {

            final String[] fileList = commandLine.getOptionValues(tuit.REDUCE);
            for (String s : fileList) {
                final Path path = Paths.get(s);
                Log.getInstance().log(Level.INFO, "Processing " + path.toString() + "...");
                final NucleotideFastaSequenceReductor nucleotideFastaSequenceReductor = NucleotideFastaSequenceReductor
                        .fromPath(path);
                ReductorFileOperator.save(nucleotideFastaSequenceReductor,
                        path.resolveSibling(path.getFileName().toString() + ".rdc"));
            }

            Log.getInstance().log(Level.FINE, "Task done, exiting...");
            return;
        }

        //Check if COMBINE is on
        if (commandLine.hasOption(tuit.COMBINE)) {
            final boolean normalize = commandLine.hasOption(tuit.NORMALIZE);
            final String[] fileList = commandLine.getOptionValues(tuit.COMBINE);
            //TODO: implement a test for format here

            final List<TreeFormatter.TreeFormatterFormat.HMPTreesOutput> hmpTreesOutputs = new ArrayList<>();
            final TreeFormatter treeFormatter = TreeFormatter
                    .newInstance(new TreeFormatter.TuitLineTreeFormatterFormat());
            for (String s : fileList) {
                final Path path = Paths.get(s);
                Log.getInstance().log(Level.INFO, "Merging " + path.toString() + "...");
                treeFormatter.loadFromPath(path);
                final TreeFormatter.TreeFormatterFormat.HMPTreesOutput output = TreeFormatter.TreeFormatterFormat.HMPTreesOutput
                        .newInstance(treeFormatter.toHMPTree(normalize), s.substring(0, s.indexOf(".")));
                hmpTreesOutputs.add(output);
                treeFormatter.erase();
            }
            final Path destination;
            if (commandLine.hasOption(OUT)) {
                destination = Paths.get(commandLine.getOptionValue(tuit.OUT));
            } else {
                destination = Paths.get("merge.tcf");
            }
            CombinatorFileOperator.save(hmpTreesOutputs, treeFormatter, destination);
            Log.getInstance().log(Level.FINE, "Task done, exiting...");
            return;
        }

        if (!commandLine.hasOption(tuit.P)) {
            throw new ParseException("No properties file option found, exiting.");
        } else {
            properties = new File(commandLine.getOptionValue(tuit.P));
        }

        //Load properties
        tuitPropertiesLoader = TUITPropertiesLoader.newInstanceFromFile(properties);
        tuitProperties = tuitPropertiesLoader.getTuitProperties();

        //Create tmp directory and blastn executable
        tmpDir = new File(tuitProperties.getTMPDir().getPath());
        blastnExecutable = new File(tuitProperties.getBLASTNPath().getPath());

        //Check for deploy
        if (commandLine.hasOption(tuit.DEPLOY)) {
            if (commandLine.hasOption(tuit.USE_DB)) {
                NCBITablesDeployer.fastDeployNCBIDatabasesFromNCBI(connection, tmpDir);
            } else {
                NCBITablesDeployer.fastDeployNCBIRamDatabaseFromNCBI(tmpDir, ramDbFile);
            }

            Log.getInstance().log(Level.FINE, "Task done, exiting...");
            return;
        }
        //Check for update
        if (commandLine.hasOption(tuit.UPDATE)) {
            if (commandLine.hasOption(tuit.USE_DB)) {
                NCBITablesDeployer.updateDatabasesFromNCBI(connection, tmpDir);
            } else {
                //No need to specify a different way to update the database other than just deploy in case of the RAM database
                NCBITablesDeployer.fastDeployNCBIRamDatabaseFromNCBI(tmpDir, ramDbFile);
            }
            Log.getInstance().log(Level.FINE, "Task done, exiting...");
            return;
        }

        //Connect to the database
        if (commandLine.hasOption(tuit.USE_DB)) {
            mySQL_connector = MySQL_Connector.newDefaultInstance(
                    "jdbc:mysql://" + tuitProperties.getDBConnection().getUrl().trim() + "/",
                    tuitProperties.getDBConnection().getLogin().trim(),
                    tuitProperties.getDBConnection().getPassword().trim());
            mySQL_connector.connectToDatabase();
            connection = mySQL_connector.getConnection();
        } else {
            //Probe for ram database

            if (ramDbFile.exists() && ramDbFile.canRead()) {
                Log.getInstance().log(Level.INFO, "Loading RAM taxonomic map...");
                try {
                    ramDb = RamDb.loadSelfFromFile(ramDbFile);
                } catch (IOException ie) {
                    if (ie instanceof java.io.InvalidClassException)
                        throw new IOException("The RAM-based taxonomic database needs to be updated.");
                }

            } else {
                Log.getInstance().log(Level.SEVERE,
                        "The RAM database either has not been deployed, or is not accessible."
                                + "Please use the --deploy option and check permissions on the TUIT directory. "
                                + "If you were looking to use the RDBMS as a taxonomic reference, plese use the -usedb option.");
                return;
            }
        }

        if (commandLine.hasOption(tuit.B)) {
            blastOutputFile = new File(commandLine.getOptionValue(tuit.B));
            if (!blastOutputFile.exists() || !blastOutputFile.canRead()) {
                throw new Exception("BLAST output file either does not exist, or is not readable.");
            } else if (blastOutputFile.isDirectory()) {
                throw new Exception("BLAST output file points to a directory.");
            }
        }
        //Check vital parameters
        if (!commandLine.hasOption(tuit.IN)) {
            throw new ParseException("No input file option found, exiting.");
        } else {
            inputFile = new File(commandLine.getOptionValue(tuit.IN));
            Log.getInstance().setLogName(inputFile.getName().split("\\.")[0] + ".tuit.log");
        }
        //Correct the output file option if needed
        if (!commandLine.hasOption(tuit.OUT)) {
            outputFile = new File((inputFile.getPath()).split("\\.")[0] + tuit.TUIT_EXT);
        } else {
            outputFile = new File(commandLine.getOptionValue(tuit.OUT));
        }

        //Adjust the output level
        if (commandLine.hasOption(tuit.V)) {
            Log.getInstance().setLevel(Level.FINE);
            Log.getInstance().log(Level.INFO, "Using verbose output for the log");
        } else {
            Log.getInstance().setLevel(Level.INFO);
        }
        //Try all files
        if (inputFile != null) {
            if (!inputFile.exists() || !inputFile.canRead()) {
                throw new Exception("Input file either does not exist, or is not readable.");
            } else if (inputFile.isDirectory()) {
                throw new Exception("Input file points to a directory.");
            }
        }

        if (!properties.exists() || !properties.canRead()) {
            throw new Exception("Properties file either does not exist, or is not readable.");
        } else if (properties.isDirectory()) {
            throw new Exception("Properties file points to a directory.");
        }

        //Create blast parameters
        final StringBuilder stringBuilder = new StringBuilder();
        for (Database database : tuitProperties.getBLASTNParameters().getDatabase()) {
            stringBuilder.append(database.getUse());
            stringBuilder.append(" ");//Gonna insert an extra space for the last database
        }
        String remote;
        String entrez_query;
        if (tuitProperties.getBLASTNParameters().getRemote().getDelegate().equals("yes")) {
            remote = "-remote";
            entrez_query = "-entrez_query";
            parameters = new String[] { "-db", stringBuilder.toString(), remote, entrez_query,
                    tuitProperties.getBLASTNParameters().getEntrezQuery().getValue(), "-evalue",
                    tuitProperties.getBLASTNParameters().getExpect().getValue() };
        } else {
            if (!commandLine.hasOption(tuit.B)) {
                if (tuitProperties.getBLASTNParameters().getEntrezQuery().getValue().toUpperCase()
                        .startsWith("NOT")
                        || tuitProperties.getBLASTNParameters().getEntrezQuery().getValue().toUpperCase()
                                .startsWith("ALL")) {
                    parameters = new String[] { "-db", stringBuilder.toString(), "-evalue",
                            tuitProperties.getBLASTNParameters().getExpect().getValue(), "-negative_gilist",
                            TUITFileOperatorHelper.restrictToEntrez(tmpDir,
                                    tuitProperties.getBLASTNParameters().getEntrezQuery().getValue()
                                            .toUpperCase().replace("NOT", "OR"))
                                    .getAbsolutePath(),
                            "-num_threads", tuitProperties.getBLASTNParameters().getNumThreads().getValue() };
                } else if (tuitProperties.getBLASTNParameters().getEntrezQuery().getValue().toUpperCase()
                        .equals("")) {
                    parameters = new String[] { "-db", stringBuilder.toString(), "-evalue",
                            tuitProperties.getBLASTNParameters().getExpect().getValue(), "-num_threads",
                            tuitProperties.getBLASTNParameters().getNumThreads().getValue() };
                } else {
                    parameters = new String[] { "-db", stringBuilder.toString(), "-evalue",
                            tuitProperties.getBLASTNParameters().getExpect().getValue(),
                            /*"-gilist", TUITFileOperatorHelper.restrictToEntrez(
                            tmpDir, tuitProperties.getBLASTNParameters().getEntrezQuery().getValue()).getAbsolutePath(),*/ //TODO remove comment!!!!!
                            "-num_threads", tuitProperties.getBLASTNParameters().getNumThreads().getValue() };
                }
            }
        }
        //Prepare a cutoff Map
        if (tuitProperties.getSpecificationParameters() != null
                && tuitProperties.getSpecificationParameters().size() > 0) {
            cutoffMap = new HashMap<Ranks, TUITCutoffSet>(tuitProperties.getSpecificationParameters().size());
            for (SpecificationParameters specificationParameters : tuitProperties
                    .getSpecificationParameters()) {
                cutoffMap.put(Ranks.valueOf(specificationParameters.getCutoffSet().getRank()),
                        TUITCutoffSet.newDefaultInstance(
                                Double.parseDouble(
                                        specificationParameters.getCutoffSet().getPIdentCutoff().getValue()),
                                Double.parseDouble(specificationParameters.getCutoffSet()
                                        .getQueryCoverageCutoff().getValue()),
                                Double.parseDouble(
                                        specificationParameters.getCutoffSet().getAlpha().getValue())));
            }
        } else {
            cutoffMap = new HashMap<Ranks, TUITCutoffSet>();
        }
        final TUITFileOperatorHelper.OutputFormat format;
        if (tuitProperties.getBLASTNParameters().getOutputFormat().getFormat().equals("rdp")) {
            format = TUITFileOperatorHelper.OutputFormat.RDP_FIXRANK;
        } else {
            format = TUITFileOperatorHelper.OutputFormat.TUIT;
        }

        try (TUITFileOperator<NucleotideFasta> nucleotideFastaTUITFileOperator = NucleotideFastaTUITFileOperator
                .newInstance(format, cutoffMap);) {
            nucleotideFastaTUITFileOperator.setInputFile(inputFile);
            nucleotideFastaTUITFileOperator.setOutputFile(outputFile);
            final String cleanupString = tuitProperties.getBLASTNParameters().getKeepBLASTOuts().getKeep();
            final boolean cleanup;
            if (cleanupString.equals("no")) {
                Log.getInstance().log(Level.INFO, "Temporary BLAST files will be deleted.");
                cleanup = true;
            } else {
                Log.getInstance().log(Level.INFO, "Temporary BLAST files will be kept.");
                cleanup = false;
            }
            //Create blast identifier
            ExecutorService executorService = Executors.newSingleThreadExecutor();
            if (commandLine.hasOption(tuit.USE_DB)) {

                if (blastOutputFile == null) {
                    blastIdentifier = TUITBLASTIdentifierDB.newInstanceFromFileOperator(tmpDir,
                            blastnExecutable, parameters, nucleotideFastaTUITFileOperator, connection,
                            cutoffMap,
                            Integer.parseInt(
                                    tuitProperties.getBLASTNParameters().getMaxFilesInBatch().getValue()),
                            cleanup);

                } else {
                    try {
                        blastIdentifier = TUITBLASTIdentifierDB.newInstanceFromBLASTOutput(
                                nucleotideFastaTUITFileOperator, connection, cutoffMap, blastOutputFile,
                                Integer.parseInt(
                                        tuitProperties.getBLASTNParameters().getMaxFilesInBatch().getValue()),
                                cleanup);

                    } catch (JAXBException e) {
                        Log.getInstance().log(Level.SEVERE, "Error reading " + blastOutputFile.getName()
                                + ", please check input. The file must be XML formatted.");
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

            } else {
                if (blastOutputFile == null) {
                    blastIdentifier = TUITBLASTIdentifierRAM.newInstanceFromFileOperator(tmpDir,
                            blastnExecutable, parameters, nucleotideFastaTUITFileOperator, cutoffMap,
                            Integer.parseInt(
                                    tuitProperties.getBLASTNParameters().getMaxFilesInBatch().getValue()),
                            cleanup, ramDb);

                } else {
                    try {
                        blastIdentifier = TUITBLASTIdentifierRAM.newInstanceFromBLASTOutput(
                                nucleotideFastaTUITFileOperator, cutoffMap, blastOutputFile,
                                Integer.parseInt(
                                        tuitProperties.getBLASTNParameters().getMaxFilesInBatch().getValue()),
                                cleanup, ramDb);

                    } catch (JAXBException e) {
                        Log.getInstance().log(Level.SEVERE, "Error reading " + blastOutputFile.getName()
                                + ", please check input. The file must be XML formatted.");
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
            Future<?> runnableFuture = executorService.submit(blastIdentifier);
            runnableFuture.get();
            executorService.shutdown();
        }
    } catch (ParseException pe) {
        Log.getInstance().log(Level.SEVERE, (pe.getMessage()));
        formatter.printHelp("tuit", options);
    } catch (SAXException saxe) {
        Log.getInstance().log(Level.SEVERE, saxe.getMessage());
    } catch (FileNotFoundException fnfe) {
        Log.getInstance().log(Level.SEVERE, fnfe.getMessage());
    } catch (TUITPropertyBadFormatException tpbfe) {
        Log.getInstance().log(Level.SEVERE, tpbfe.getMessage());
    } catch (ClassCastException cce) {
        Log.getInstance().log(Level.SEVERE, cce.getMessage());
    } catch (JAXBException jaxbee) {
        Log.getInstance().log(Level.SEVERE,
                "The properties file is not well formatted. Please ensure that the XML is consistent with the io.properties.dtd schema.");
    } catch (ClassNotFoundException cnfe) {
        //Probably won't happen unless the library deleted from the .jar
        Log.getInstance().log(Level.SEVERE, cnfe.getMessage());
        //cnfe.printStackTrace();
    } catch (SQLException sqle) {
        Log.getInstance().log(Level.SEVERE,
                "A database communication error occurred with the following message:\n" + sqle.getMessage());
        //sqle.printStackTrace();
        if (sqle.getMessage().contains("Access denied for user")) {
            Log.getInstance().log(Level.SEVERE, "Please use standard database login: "
                    + NCBITablesDeployer.login + " and password: " + NCBITablesDeployer.password);
        }
    } catch (Exception e) {
        Log.getInstance().log(Level.SEVERE, e.getMessage());
        e.printStackTrace();
    } finally {
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException sqle) {
                Log.getInstance().log(Level.SEVERE, "Problem closing the database connection: " + sqle);
            }
        }
        Log.getInstance().log(Level.FINE, "Task done, exiting...");
    }
}