Example usage for java.lang String equals

List of usage examples for java.lang String equals

Introduction

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

Prototype

public boolean equals(Object anObject) 

Source Link

Document

Compares this string to the specified object.

Usage

From source file:com.cloudbees.sdk.Bees.java

public static void main(String[] args) {
    reportTime("Bees");

    boolean verbose = isVerbose(args);
    if (verbose || isHelp(args) || isPluginCmd(args)) {
        System.out.println("# CloudBees SDK version: " + BOOTSTRAP_VERSION);
        System.out.println("# CloudBees Driver version: " + version);
        if (verbose)
            System.out.println(System.getProperties());
    }/*w w w  .  j  av a  2  s. c  om*/
    try {
        new Bees().run(args);
    } catch (BeesClientException e) {
        System.err.println();
        String errCode = e.getError().getErrorCode();
        if (errCode != null && errCode.equals("AuthFailure")) {
            if (e.getError().getMessage() != null)
                System.err.println("ERROR: " + e.getError().getMessage());
            else
                System.err.println("ERROR: Authentication failure, please check credentials!");
        } else
            System.err.println("ERROR: " + e.getMessage());
        //            e.printStackTrace();
        System.exit(2);
    } catch (UnrecognizedOptionException e) {
        System.err.println();
        System.err.println("ERROR: " + e.getMessage());
        System.exit(2);
    } catch (IllegalArgumentException e) {
        System.err.println();
        System.err.println("ERROR: " + e.getMessage());
        System.exit(2);
    } catch (BeesSecurityException e) {
        System.err.println();
        System.err.println("ERROR: " + e.getMessage());
        System.exit(2);
    } catch (Throwable e) {
        System.err.println();
        System.err.println("ERROR: " + e.getMessage());
        if (isVerbose(args))
            e.printStackTrace();
        System.exit(2);
    }
}

From source file:Lab2.java

/**
 * @param args the command line arguments
 *//*from  w w w. j  a v a2 s  .  c o m*/
public static void main(String[] args) {
    Preprocessor p = new Preprocessor();
    p.parse();
    Query q;
    boolean cont = true;
    Scanner input = new Scanner(System.in);
    String yesOrNo;
    String oOrC;
    ArrayList<Document> scores;

    System.out.println("Would you like to use cosine similarity or okapi to score queries? (C/O)");
    oOrC = input.nextLine();
    while (cont) {
        System.out.println("Enter a query: ");
        /**
         * We don't need the query class, we can just stem it and stopword it then make a document out of it.
         */
        q = new Query(input.nextLine());

        if (oOrC.equals("O") || oOrC.equals("o")) {
            scores = p.calcQueryOkapiScore(q);
        } else {
            scores = p.calcQueryCosineSimilarity(q);
        }

        System.out.println("Documents returned from cosine similarity analysis on query are: ");
        for (Document doc : scores) {
            System.out.println("Text :" + doc.origUtterance);
        }

        System.out.println("Would you like to enter another? Y/N");
        yesOrNo = input.nextLine();
        if (yesOrNo.equals("N") || yesOrNo.equals("n")) {
            cont = false;
        }
    }
}

From source file:net.cyllene.hackerrank.downloader.HackerrankDownloader.java

public static void main(String[] args) {
    // Parse arguments and set up the defaults
    DownloaderSettings.cmd = parseArguments(args);

    if (DownloaderSettings.cmd.hasOption("help")) {
        printHelp();//w  w w  .jav  a2  s. c  o  m
        System.exit(0);
    }

    if (DownloaderSettings.cmd.hasOption("verbose")) {
        DownloaderSettings.beVerbose = true;
    }

    /**
     * Output directory logic:
     * 1) if directory exists, ask for -f option to overwrite, quit with message
     * 2) if -f flag is set, check if user has access to a parent directory
     * 3) if no access, quit with error
     * 4) if everything is OK, remember the path
     */
    String sDesiredPath = DownloaderSettings.outputDir;
    if (DownloaderSettings.cmd.hasOption("directory")) {
        sDesiredPath = DownloaderSettings.cmd.getOptionValue("d", DownloaderSettings.outputDir);
    }
    if (DownloaderSettings.beVerbose) {
        System.out.println("Checking output dir: " + sDesiredPath);
    }
    Path desiredPath = Paths.get(sDesiredPath);
    if (Files.exists(desiredPath) && Files.isDirectory(desiredPath)) {
        if (!DownloaderSettings.cmd.hasOption("f")) {
            System.out.println("I wouldn't like to overwrite existing directory: " + sDesiredPath
                    + ", set the --force flag if you are sure. May lead to data loss, be careful.");
            System.exit(0);
        } else {
            System.out.println(
                    "WARNING!" + System.lineSeparator() + "--force flag is set. Overwriting directory: "
                            + sDesiredPath + System.lineSeparator() + "WARNING!");
        }
    }
    if ((Files.exists(desiredPath) && !Files.isWritable(desiredPath))
            || !Files.isWritable(desiredPath.getParent())) {
        System.err
                .println("Fatal error: " + sDesiredPath + " cannot be created or modified. Check permissions.");
        // TODO: use Exceptions instead of system.exit
        System.exit(1);
    }
    DownloaderSettings.outputDir = sDesiredPath;

    Integer limit = DownloaderSettings.ITEMS_TO_DOWNLOAD;
    if (DownloaderSettings.cmd.hasOption("limit")) {
        try {
            limit = ((Number) DownloaderSettings.cmd.getParsedOptionValue("l")).intValue();
        } catch (ParseException e) {
            System.out.println("Incorrect limit: " + e.getMessage() + System.lineSeparator()
                    + "Using default value: " + limit);
        }
    }

    Integer offset = DownloaderSettings.ITEMS_TO_SKIP;
    if (DownloaderSettings.cmd.hasOption("offset")) {
        try {
            offset = ((Number) DownloaderSettings.cmd.getParsedOptionValue("o")).intValue();
        } catch (ParseException e) {
            System.out.println("Incorrect offset: " + e.getMessage() + " Using default value: " + offset);
        }
    }

    DownloaderCore dc = DownloaderCore.INSTANCE;

    List<HRChallenge> challenges = new LinkedList<>();

    // Download everything first
    Map<String, List<Integer>> structure = null;
    try {
        structure = dc.getStructure(offset, limit);
    } catch (IOException e) {
        System.err.println("Fatal Error: could not get data structure.");
        e.printStackTrace();
        System.exit(1);
    }

    challengesLoop: for (Map.Entry<String, List<Integer>> entry : structure.entrySet()) {
        String challengeSlug = entry.getKey();
        HRChallenge currentChallenge = null;
        try {
            currentChallenge = dc.getChallengeDetails(challengeSlug);
        } catch (IOException e) {
            System.err.println("Error: could not get challenge info for: " + challengeSlug);
            if (DownloaderSettings.beVerbose) {
                e.printStackTrace();
            }
            continue challengesLoop;
        }

        submissionsLoop: for (Integer submissionId : entry.getValue()) {
            HRSubmission submission = null;
            try {
                submission = dc.getSubmissionDetails(submissionId);
            } catch (IOException e) {
                System.err.println("Error: could not get submission info for: " + submissionId);
                if (DownloaderSettings.beVerbose) {
                    e.printStackTrace();
                }
                continue submissionsLoop;
            }

            // TODO: probably should move filtering logic elsewhere(getStructure, maybe)
            if (submission.getStatus().equalsIgnoreCase("Accepted")) {
                currentChallenge.getSubmissions().add(submission);
            }
        }

        challenges.add(currentChallenge);
    }

    // Now dump all data to disk
    try {
        for (HRChallenge currentChallenge : challenges) {
            if (currentChallenge.getSubmissions().isEmpty())
                continue;

            final String sChallengePath = DownloaderSettings.outputDir + "/" + currentChallenge.getSlug();
            final String sSolutionPath = sChallengePath + "/accepted_solutions";
            final String sDescriptionPath = sChallengePath + "/problem_description";

            Files.createDirectories(Paths.get(sDescriptionPath));
            Files.createDirectories(Paths.get(sSolutionPath));

            // FIXME: this should be done the other way
            String plainBody = currentChallenge.getDescriptions().get(0).getBody();
            String sFname;
            if (!plainBody.equals("null")) {
                sFname = sDescriptionPath + "/english.txt";
                if (DownloaderSettings.beVerbose) {
                    System.out.println("Writing to: " + sFname);
                }

                Files.write(Paths.get(sFname), plainBody.getBytes(StandardCharsets.UTF_8.name()));
            }

            String htmlBody = currentChallenge.getDescriptions().get(0).getBodyHTML();
            String temporaryHtmlTemplate = "<html></body>" + htmlBody + "</body></html>";

            sFname = sDescriptionPath + "/english.html";
            if (DownloaderSettings.beVerbose) {
                System.out.println("Writing to: " + sFname);
            }
            Files.write(Paths.get(sFname), temporaryHtmlTemplate.getBytes(StandardCharsets.UTF_8.name()));

            for (HRSubmission submission : currentChallenge.getSubmissions()) {
                sFname = String.format("%s/%d.%s", sSolutionPath, submission.getId(), submission.getLanguage());
                if (DownloaderSettings.beVerbose) {
                    System.out.println("Writing to: " + sFname);
                }

                Files.write(Paths.get(sFname),
                        submission.getSourceCode().getBytes(StandardCharsets.UTF_8.name()));
            }

        }
    } catch (IOException e) {
        System.err.println("Fatal Error: couldn't dump data to disk.");
        System.exit(1);
    }
}

From source file:com.cisco.dvbu.ps.common.scriptutil.ScriptUtil.java

public static void main(String[] args) {

    if (args == null || args.length <= 1) {
        throw new ValidationException("Invalid Arguments");
    }//from  ww  w.j  av a 2s .  co m

    try {
        boolean validMethod = false;
        Class<ScriptUtil> scriptUtilClass = ScriptUtil.class;
        Method[] methods = scriptUtilClass.getMethods();
        for (int i = 0; i < methods.length; i++) {
            String name = methods[i].getName();
            if (name.equals(args[0])) {
                validMethod = true;
                try {
                    String[] methodArgs = new String[args.length - 1];
                    for (int j = 0; j < methodArgs.length; j++) {
                        methodArgs[j] = args[j + 1];
                    }
                    if (logger.isDebugEnabled()) {
                        logger.debug(" Invoking method " + args[0] + " With args" + methodArgs);
                    }

                    Object returnValue = methods[i].invoke(scriptUtilClass, (Object[]) methodArgs);
                    if (logger.isDebugEnabled()) {
                        logger.debug(" Result from invoking method " + args[0] + " " + returnValue);
                    }

                } catch (IllegalArgumentException e) {
                    logger.error("Error while invoking method " + args[0], e);
                    throw new ValidationException(e.getMessage(), e);
                } catch (IllegalAccessException e) {
                    logger.error("Error while invoking method " + args[0], e);
                    throw new ValidationException(e.getMessage(), e);
                } catch (InvocationTargetException e) {
                    logger.error("Error while invoking method " + args[0], e);
                    throw new ValidationException(e.getMessage(), e);
                } catch (Throwable e) {
                    throw new ValidationException(e.getMessage(), e);
                }
            }
        }

        if (!validMethod) {
            logger.error("Passed in method " + args[0] + " does not exist");
            throw new ValidationException("Passed in method  " + args[0] + " does not exist ");
        }

    } catch (CompositeException e) {
        logger.error("Error occured while executing ", e);
        throw e;
    }
}

From source file:com.lfv.lanzius.Main.java

public static void main(String[] args) {

    /*/*ww w.  j a  v  a  2 s  .co m*/
     * debug levels:
     * error - Runtime errors or unexpected conditions. Expect these to be immediately visible on a status console. See also Internationalization.
     * warn  - Use of deprecated APIs, poor use of API, 'almost' errors, other runtime situations that are undesirable or unexpected, but not necessarily "wrong". Expect these to be immediately visible on a status console. See also Internationalization.
     * info  - Interesting runtime events (startup/shutdown). Expect these to be immediately visible on a console, so be conservative and keep to a minimum. See also Internationalization.
     * debug - detailed information on the flow through the system. Expect these to be written to logs only.
     */

    Log log = null;
    DOMConfigurator conf = new DOMConfigurator();
    DOMConfigurator.configure("data/properties/loggingproperties.xml");
    System.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.Log4JLogger");

    try {
        if (args.length >= 1) {
            // Help
            if (args[0].startsWith("-h")) {
                printUsage();
                return;
            }
            // List devices
            else if (args[0].startsWith("-l")) {
                AudioTest.listDevices();
                return;
            }
            // Test seleted device
            else if (args[0].startsWith("-d")) {
                System.setProperty("org.apache.commons.logging.Log",
                        "org.apache.commons.logging.impl.SimpleLog");
                System.setProperty("org.apache.commons.logging.simplelog.defaultlog", "warn");
                try {
                    String option = "all";
                    if (args.length >= 4)
                        option = args[3];

                    if (option.equals("loop:direct"))
                        AudioTest.testDevicesDirect(Integer.parseInt(args[1]), Integer.parseInt(args[2]));
                    else {
                        if (option.indexOf("debug") != -1)
                            System.setProperty("org.apache.commons.logging.simplelog.defaultlog", "debug");

                        AudioTest.testDevices(Integer.parseInt(args[1]), Integer.parseInt(args[2]), option,
                                (args.length >= 5) ? args[4] : null, (args.length >= 6) ? args[5] : null,
                                (args.length >= 7) ? args[6] : null);
                    }
                } catch (Exception ex) {
                    System.out.println();
                    System.out.println(Config.VERSION);
                    System.out.println();
                    System.out.println("Usage:");
                    System.out.println(
                            "  yada.jar -d output_device input_device <option> <jitter_buffer> <output_buffer> <input_buffer>");
                    System.out.println("  option:");
                    System.out.println("    all(default)");
                    System.out.println("    clip");
                    System.out.println("    loop:jspeex");
                    System.out.println("    loop:null");
                    System.out.println("    loop:direct");
                    System.out.println("    loopdebug:jspeex");
                    System.out.println("    loopdebug:null");
                    System.out.println("  jitter_buffer:");
                    System.out.println("    size of jitter buffer in packets (1-20)");
                    System.out.println("  output_buffer:");
                    System.out.println("    size of output buffer in packets (1.0-4.0)");
                    System.out.println("  input_buffer:");
                    System.out.println("    size of input buffer in packets (1.0-4.0)");
                    System.out.println();
                    if (AudioTest.showStackTrace && !(ex instanceof ArrayIndexOutOfBoundsException))
                        ex.printStackTrace();
                }
                //System.out.println("Exiting...");
                return;
            } else if (args[0].startsWith("-m")) {
                System.setProperty("org.apache.commons.logging.Log",
                        "org.apache.commons.logging.impl.SimpleLog");
                System.setProperty("org.apache.commons.logging.simplelog.defaultlog", "warn");
                try {
                    AudioTest.testMicrophoneLevel(Integer.parseInt(args[1]));
                } catch (Exception ex) {
                    System.out.println();
                    System.out.println(Config.VERSION);
                    System.out.println();
                    System.out.println("Usage:");
                    System.out.println("  yada.jar -m input_device");
                    System.out.println();
                    if (AudioTest.showStackTrace && !(ex instanceof ArrayIndexOutOfBoundsException))
                        ex.printStackTrace();
                }
                return;
            } else if (args[0].startsWith("-s")) {
                Packet.randomSeed = 9182736455L ^ System.currentTimeMillis();
                if (args.length > 2 && args[1].startsWith("-configuration")) {
                    String configFilename = args[2];
                    if (args.length > 4 && args[3].startsWith("-exercise")) {
                        String exerciseFilename = args[4];

                        LanziusServer.start(configFilename, exerciseFilename);
                    } else {
                        LanziusServer.start(configFilename);
                    }
                } else {
                    LanziusServer.start();
                }
                return;
            } else if (args[0].startsWith("-f")) {
                System.setProperty("org.apache.commons.logging.Log",
                        "org.apache.commons.logging.impl.SimpleLog");
                System.setProperty(
                        "org.apache.commons.logging.simplelog.log.com.lfv.lanzius.application.FootSwitchController",
                        "debug");
                try {
                    System.out.println("Starting footswitch controller test using device " + args[1]);
                    try {
                        boolean inverted = false;
                        if (args.length >= 3)
                            inverted = args[2].toLowerCase().startsWith("inv");
                        FootSwitchController c = new FootSwitchController(null, args[1],
                                Constants.PERIOD_FTSW_CONNECTED, inverted);
                        c.start();
                        Thread.sleep(30000);
                    } catch (UnsatisfiedLinkError err) {
                        if (args.length > 1)
                            System.out.println("UnsatisfiedLinkError: " + err.getMessage());
                        else
                            throw new ArrayIndexOutOfBoundsException();
                        System.out.println("Missing ftsw library (ftsw.dll or libftsw.so)");
                        if (!args[1].equalsIgnoreCase("ftdi"))
                            System.out
                                    .println("Missing rxtxSerial library (rxtxSerial.dll or librxtxSerial.so)");
                        if (AudioTest.showStackTrace)
                            err.printStackTrace();
                    }
                } catch (Exception ex) {
                    if (ex instanceof NoSuchPortException)
                        System.out.println("The serial port " + args[1] + " does not exist!");
                    else if (ex instanceof PortInUseException)
                        System.out.println("The serial port " + args[1] + " is already in use!");
                    System.out.println();
                    System.out.println(Config.VERSION);
                    System.out.println();
                    System.out.println("Usage:");
                    System.out.println("  yada.jar -f interface <invert>");
                    System.out.println("  interface:");
                    System.out.println("    ftdi");
                    System.out.println("    comport (COMx or /dev/ttyx)");
                    System.out.println("  invert:");
                    System.out.println("    true");
                    System.out.println("    false (default)");
                    System.out.println();
                    if (AudioTest.showStackTrace && !(ex instanceof ArrayIndexOutOfBoundsException))
                        ex.printStackTrace();
                }
                return;
            } else if (args[0].startsWith("-c")) {
                Packet.randomSeed = 7233103157L ^ System.currentTimeMillis();
                if (args.length >= 2) {
                    try {
                        int id = Integer.valueOf(args[1]);
                        if (id <= 0)
                            throw new NumberFormatException();
                        Controller c = Controller.getInstance();
                        if (args.length >= 3) {
                            if (args[2].equalsIgnoreCase("test")) {
                                c.setAutoTester(true);
                            }
                        }
                        c.init(id);
                        return;
                    } catch (NumberFormatException ex) {
                        printUsage();
                    }
                } else {
                    Controller.getInstance().init(0);
                }
            } else
                printUsage();
        } else
            printUsage();
    } catch (Throwable t) {
        if (log == null)
            log = LogFactory.getLog(Main.class);
        log.error("Unhandled exception or error", t);
    }
}

From source file:net.cloudkit.enterprises.ws.SuperPassQueryTest.java

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

    List<String> params = new ArrayList<>();
    // System.out.println(SuperPassQueryTest.class.getResource("/list.dat").toURI());
    Path path = Paths.get(SuperPassQueryTest.class.getResource("/list.dat").toURI());
    try (BufferedReader reader = Files.newBufferedReader(path, Charset.forName("UTF-8"))) {
        // System.out.println(reader.readLine().length());
        String line;// ww w  .  ja v  a2s . c o m
        while ((line = reader.readLine()) != null) {
            // System.out.println("TEXT LINE:" + line);
            params.add(line);
        }
    }

    Path succeededFile = Paths.get(SuperPassQueryTest.class.getResource("/succeeded.dat").toURI());
    BufferedWriter succeededWriter = Files.newBufferedWriter(succeededFile, StandardCharsets.UTF_8,
            StandardOpenOption.APPEND);
    Path failedFile = Paths.get(SuperPassQueryTest.class.getResource("/failed.dat").toURI());
    BufferedWriter failedWriter = Files.newBufferedWriter(failedFile, StandardCharsets.UTF_8,
            StandardOpenOption.APPEND);

    for (String param : params) {
        try {
            /*
            StringTokenizer stringTokenizer = new StringTokenizer(param, ",");
            while(stringTokenizer.hasMoreTokens()){
            System.out.println("COUNT:" + stringTokenizer.countTokens());
            System.out.println("VALUE:" + stringTokenizer.nextToken());
            System.out.println("COUNT:" + stringTokenizer.countTokens());
            }
            */

            System.out.println("QUERY PARAMS:" + param);
            String[] paramArray = param.split(",");
            // System.out.println("VALUE:" + paramArray[0]);
            // System.out.println("VALUE:" + paramArray[1]);
            // System.out.println("VALUE:" + paramArray[2]);

            String value_1 = paramArray[0];
            String value_2 = paramArray[1];
            String value_3 = paramArray[2];

            String serviceName = "eport.superpass.spdec.DecQueryListService";
            byte[] requestContext = ("<?xml version=\"1.0\" encoding=\"utf-8\" standalone=\"yes\"?>\n"
                    + "<RequestContext>\n" + "    <Group name=\"SystemInfo\">\n"
                    + "        <Key name=\"NAME_FULL\">???</Key>\n"
                    + "        <Key name=\"ClientId\">5300001976914</Key>\n"
                    + "        <Key name=\"CertNo\">df630b</Key>\n"
                    + "        <Key name=\"SaicSysNo\">766350979</Key>\n"
                    + "        <Key name=\"DEP_IN_CODE\">5300</Key>\n"
                    + "        <Key name=\"REG_CO_CGAC\">4403180237</Key>\n"
                    + "        <Key name=\"ENT_SEQ_NO\">000000000000315537</Key>\n"
                    + "        <Key name=\"ENT_TYPE\">3</Key>\n"
                    + "        <Key name=\"IcCode\">8930000011040</Key>\n"
                    + "        <Key name=\"OperatorName\">?</Key>\n"
                    + "        <Key name=\"DEP_CODE_CHG\">5305</Key>\n"
                    + "        <Key name=\"SessionId\">AE2533938D521A9972186B07BBBEB244</Key>\n"
                    + "    </Group>\n" + "    <Group name=\"DataPresentation\">\n"
                    + "        <Key name=\"SignatureAlgorithm\"/>\n"
                    + "        <Key name=\"EncryptAlgorithm\"/>\n"
                    + "        <Key name=\"CompressAlgorithm\"/>\n" + "    </Group>\n"
                    + "    <Group name=\"Default\">\n"
                    + "        <Key name=\"clientSystemId\">0400620001</Key>\n"
                    + "        <Key name=\"needWebInvoke\">True</Key>\n" + "    </Group>\n"
                    + "</RequestContext>").getBytes();

            byte[] requestData = ("<?xml version=\"1.0\"?>\n"
                    + "<DecQueryListRequest xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">\n"
                    + "  <OperType>0</OperType>\n" + "  <DecType>\n" + "    <TrnType>0</TrnType>\n"
                    + "    <IEFlag>" + value_3 + "</IEFlag>\n" + "    <DecSubType />\n" + "  </DecType>\n"
                    + "  <CopeCode>766350979</CopeCode>\n" + "  <AgentCode>4403180237</AgentCode>\n"
                    + "  <SeqNo>" + value_1 + "</SeqNo>\n" + "  <UserType>0</UserType>\n"
                    + "</DecQueryListRequest>").getBytes();

            Holder<byte[]> responseData = new Holder<>();

            // <?xml version="1.0" encoding="UTF-8" standalone="no"?><ResponseContext><ResponseCode>0</ResponseCode><ResponseMessage>success</ResponseMessage><ServiceResponseCode>0</ServiceResponseCode><ServiceResponseMessage>?</ServiceResponseMessage><ExceptionDetail/><Group name="DataPresentation"><Key name="CompressAlgorithm"/><Key name="SignatureAlgorithm"/><Key name="EncryptAlgorithm"/></Group></ResponseContext>
            // <?xml version="1.0" encoding="UTF-8" standalone="yes"?><DecQueryListResponse><QueryResponseData><EntryId>531820161181010544</EntryId><SeqNo>000000001139524197</SeqNo><BillNo>2016051920160523</BillNo><IEDate>20160621</IEDate><TradeMode>0615</TradeMode><ItemsNum>19</ItemsNum><TrafName></TrafName><Status>O</Status><AgentName>???</AgentName><IEFlag>I</IEFlag><CustomsCode>5318</CustomsCode><DeclTrnRel>0</DeclTrnRel><RetExplain>;?</RetExplain><NoticeDate>2016-06-29</NoticeDate><TradeName>()??</TradeName><ExtendField><DecDeclareSysType>2</DecDeclareSysType><TrnSysType>1</TrnSysType><AssureExamRet>0</AssureExamRet><RelatedDocumentType>  </RelatedDocumentType><DeclareSeqNo>                  </DeclareSeqNo><ExtendField53>P</ExtendField53><ExtendField>21                                                   P</ExtendField></ExtendField><EntryType>M</EntryType></QueryResponseData></DecQueryListResponse>
            // String responseContext = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?><ResponseContext><ResponseCode>0</ResponseCode><ResponseMessage>success</ResponseMessage><ServiceResponseCode>0</ServiceResponseCode><ServiceResponseMessage>?</ServiceResponseMessage><ExceptionDetail/><Group name=\"DataPresentation\"><Key name=\"CompressAlgorithm\"/><Key name=\"SignatureAlgorithm\"/><Key name=\"EncryptAlgorithm\"/></Group></ResponseContext>";
            // String queryListResponse = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><DecQueryListResponse><QueryResponseData><EntryId>531820161181010544</EntryId><SeqNo>000000001139524197</SeqNo><BillNo>2016051920160523</BillNo><IEDate>20160621</IEDate><TradeMode>0615</TradeMode><ItemsNum>19</ItemsNum><TrafName></TrafName><Status>O</Status><AgentName>???</AgentName><IEFlag>I</IEFlag><CustomsCode>5318</CustomsCode><DeclTrnRel>0</DeclTrnRel><RetExplain>;?</RetExplain><NoticeDate>2016-06-29</NoticeDate><TradeName>()??</TradeName><ExtendField><DecDeclareSysType>2</DecDeclareSysType><TrnSysType>1</TrnSysType><AssureExamRet>0</AssureExamRet><RelatedDocumentType>  </RelatedDocumentType><DeclareSeqNo>                  </DeclareSeqNo><ExtendField53>P</ExtendField53><ExtendField>21                                                   P</ExtendField></ExtendField><EntryType>M</EntryType></QueryResponseData></DecQueryListResponse>";

            String responseContext = new String(
                    superPass.service(serviceName, requestContext, requestData, responseData));
            String queryListResponse = new String(responseData.value);
            System.out.println("RESPONSE_CONTEXT:" + responseContext);
            System.out.println("QUERY_LIST_RESPONSE:" + queryListResponse);

            String serviceResponseCode = parsingReceiptStatus(responseContext);
            System.out.println("SERVICE_RESPONSE_CODE:" + serviceResponseCode);
            if (serviceResponseCode.equals("0")) {
                String data = parsingReceiptData(queryListResponse);
                System.out.println("DATA:" + data);
                succeededWriter.write(data);
                succeededWriter.flush();
            } else {
                failedWriter.write(param + "\n");
                failedWriter.flush();
            }
            Thread.sleep(6 * 1000);
        } catch (Exception e) {
            failedWriter.write(param + "\n");
            failedWriter.flush();
        }
    }
    succeededWriter.close();
    failedWriter.close();
}

From source file:EchoClient.java

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

        Socket kkSocket = null;//from ww  w.j a v  a2 s.c o  m
        PrintWriter out = null;
        BufferedReader in = null;

        try {
            kkSocket = new Socket("taranis", 4444);
            out = new PrintWriter(kkSocket.getOutputStream(), true);
            in = new BufferedReader(new InputStreamReader(kkSocket.getInputStream()));
        } catch (UnknownHostException e) {
            System.err.println("Don't know about host: taranis.");
            System.exit(1);
        } catch (IOException e) {
            System.err.println("Couldn't get I/O for the connection to: taranis.");
            System.exit(1);
        }

        BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
        String fromServer;
        String fromUser;

        while ((fromServer = in.readLine()) != null) {
            System.out.println("Server: " + fromServer);
            if (fromServer.equals("Bye."))
                break;

            fromUser = stdIn.readLine();
            if (fromUser != null) {
                System.out.println("Client: " + fromUser);
                out.println(fromUser);
            }
        }

        out.close();
        in.close();
        stdIn.close();
        kkSocket.close();
    }

From source file:QueueRoundTrip.java

public static void main(String argv[]) {
    // Values to be read from parameters
    String broker = DEFAULT_BROKER_NAME;
    String username = DEFAULT_USER_NAME;
    String password = DEFAULT_PASSWORD;
    int numTests = DEFAULT_NUM_TESTS;

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

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

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

                if (arg.equals("-p")) {
                    if (i == argv.length - 1 || argv[i + 1].startsWith("-")) {
                        System.err.println("error: missing password");
                        System.exit(1);
                    }
                    password = argv[++i];
                    continue;
                }
                if (arg.equals("-n")) {
                    if (i == argv.length - 1 || argv[i + 1].startsWith("-")) {
                        System.err.println("error: missing number of test to run.");
                        System.exit(1);
                    }
                    numTests = (new Integer(argv[++i])).intValue();
                    continue;
                }

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

    // create the payload
    byte charToWrite = (0x30);
    for (int i = 0; i < msgSize; i++) {
        msgBody[i] = charToWrite;
        charToWrite = (byte) ((int) charToWrite + (int) 0x01);
        if (charToWrite == (0x39)) {
            charToWrite = (0x30);
        }
    }

    // Start the JMS client for the test.
    QueueRoundTrip queueRoundTripper = new QueueRoundTrip();
    queueRoundTripper.QueueRoundTripper(broker, username, password, numTests);

}

From source file:org.callimachusproject.rdfa.test.RDFaGenerationTest.java

public static void main(String[] args) {
    try {/*from w w  w.  j a va2s  .com*/

        for (int i = 0; i < args.length; i++) {
            String arg = args[i];
            if (arg.equals("-verbose"))
                verbose = true;
            // just show the generated queries (don't run the test)
            else if (arg.equals("-rdf"))
                show_rdf = true;
            else if (arg.equals("-sparql"))
                show_sparql = true;
            else if (arg.equals("-xml"))
                show_xml = true;
            else if (arg.equals("-results"))
                show_results = true;
            //else if (arg.equals("-legacy")) test_set = "legacy";
            //else if (arg.equals("-construct")) test_set = "construct";
            else if (arg.equals("-select"))
                test_set = "select";
            //else if (arg.equals("-fragment")) test_set = "fragment";
            else if (arg.equals("-data"))
                test_set = "data";
            else if (!arg.startsWith("-"))
                test_dir = arg;
        }

        // run the dynamically generated test-cases
        System.exit(TestRunner.run(RDFaGenerationTest.suite()).wasSuccessful() ? 0 : 1);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:br.usp.poli.lta.cereda.spa2run.Main.java

public static void main(String[] args) {

    Utils.printBanner();/*w  w  w .j  a va  2  s.c o m*/
    CommandLineParser parser = new DefaultParser();

    try {
        CommandLine line = parser.parse(Utils.getOptions(), args);
        List<Spec> specs = Utils.fromFilesToSpecs(line.getArgs());
        List<Metric> metrics = Utils.fromFilesToMetrics(line);
        Utils.setMetrics(metrics);
        Utils.resetCalculations();
        AdaptiveAutomaton automaton = Utils.getAutomatonFromSpecs(specs);

        System.out.println("SPA generated successfully:");
        System.out.println("- " + specs.size() + " submachine(s) found.");
        if (!Utils.detectEpsilon(automaton)) {
            System.out.println("- No empty transitions.");
        }
        if (!metrics.isEmpty()) {
            System.out.println("- " + metrics.size() + " metric(s) found.");
        }

        System.out.println("\nStarting shell, please wait...\n" + "(press CTRL+C or type `:quit'\n"
                + "to exit the application)\n");

        String query = "";
        Scanner scanner = new Scanner(System.in);
        String prompt = "[%d] query> ";
        String result = "[%d] result> ";
        int counter = 1;
        do {

            try {
                String term = String.format(prompt, counter);
                System.out.print(term);
                query = scanner.nextLine().trim();
                if (!query.equals(":quit")) {
                    boolean accept = automaton.recognize(Utils.toSymbols(query));
                    String type = automaton.getRecognitionPaths().size() == 1 ? " (deterministic)"
                            : " (nondeterministic)";
                    System.out.println(String.format(result, counter) + accept + type);

                    if (!metrics.isEmpty()) {
                        System.out.println(StringUtils.repeat(" ", String.format("[%d] ", counter).length())
                                + Utils.prettyPrintMetrics());
                    }

                    System.out.println();

                }
            } catch (Exception exception) {
                System.out.println();
                Utils.printException(exception);
                System.out.println();
            }

            counter++;
            Utils.resetCalculations();

        } while (!query.equals(":quit"));
        System.out.println("That's all folks!");

    } catch (ParseException nothandled) {
        Utils.printHelp();
    } catch (Exception exception) {
        Utils.printException(exception);
    }
}