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:examples.tftp.java

public final static void main(String[] args) {
    boolean receiveFile = true, closed;
    int transferMode = TFTP.BINARY_MODE, argc;
    String arg, hostname, localFilename, remoteFilename;
    TFTPClient tftp;//from  w  ww  .j  a  v a 2  s  .  co m

    // Parse options
    for (argc = 0; argc < args.length; argc++) {
        arg = args[argc];
        if (arg.startsWith("-")) {
            if (arg.equals("-r"))
                receiveFile = true;
            else if (arg.equals("-s"))
                receiveFile = false;
            else if (arg.equals("-a"))
                transferMode = TFTP.ASCII_MODE;
            else if (arg.equals("-b"))
                transferMode = TFTP.BINARY_MODE;
            else {
                System.err.println("Error: unrecognized option.");
                System.err.print(USAGE);
                System.exit(1);
            }
        } else
            break;
    }

    // Make sure there are enough arguments
    if (args.length - argc != 3) {
        System.err.println("Error: invalid number of arguments.");
        System.err.print(USAGE);
        System.exit(1);
    }

    // Get host and file arguments
    hostname = args[argc];
    localFilename = args[argc + 1];
    remoteFilename = args[argc + 2];

    // Create our TFTP instance to handle the file transfer.
    tftp = new TFTPClient();

    // We want to timeout if a response takes longer than 60 seconds
    tftp.setDefaultTimeout(60000);

    // Open local socket
    try {
        tftp.open();
    } catch (SocketException e) {
        System.err.println("Error: could not open local UDP socket.");
        System.err.println(e.getMessage());
        System.exit(1);
    }

    // We haven't closed the local file yet.
    closed = false;

    // If we're receiving a file, receive, otherwise send.
    if (receiveFile) {
        FileOutputStream output = null;
        File file;

        file = new File(localFilename);

        // If file exists, don't overwrite it.
        if (file.exists()) {
            System.err.println("Error: " + localFilename + " already exists.");
            System.exit(1);
        }

        // Try to open local file for writing
        try {
            output = new FileOutputStream(file);
        } catch (IOException e) {
            tftp.close();
            System.err.println("Error: could not open local file for writing.");
            System.err.println(e.getMessage());
            System.exit(1);
        }

        // Try to receive remote file via TFTP
        try {
            tftp.receiveFile(remoteFilename, transferMode, output, hostname);
        } catch (UnknownHostException e) {
            System.err.println("Error: could not resolve hostname.");
            System.err.println(e.getMessage());
            System.exit(1);
        } catch (IOException e) {
            System.err.println("Error: I/O exception occurred while receiving file.");
            System.err.println(e.getMessage());
            System.exit(1);
        } finally {
            // Close local socket and output file
            tftp.close();
            try {
                output.close();
                closed = true;
            } catch (IOException e) {
                closed = false;
                System.err.println("Error: error closing file.");
                System.err.println(e.getMessage());
            }
        }

        if (!closed)
            System.exit(1);

    } else {
        // We're sending a file
        FileInputStream input = null;

        // Try to open local file for reading
        try {
            input = new FileInputStream(localFilename);
        } catch (IOException e) {
            tftp.close();
            System.err.println("Error: could not open local file for reading.");
            System.err.println(e.getMessage());
            System.exit(1);
        }

        // Try to send local file via TFTP
        try {
            tftp.sendFile(remoteFilename, transferMode, input, hostname);
        } catch (UnknownHostException e) {
            System.err.println("Error: could not resolve hostname.");
            System.err.println(e.getMessage());
            System.exit(1);
        } catch (IOException e) {
            System.err.println("Error: I/O exception occurred while sending file.");
            System.err.println(e.getMessage());
            System.exit(1);
        } finally {
            // Close local socket and input file
            tftp.close();
            try {
                input.close();
                closed = true;
            } catch (IOException e) {
                closed = false;
                System.err.println("Error: error closing file.");
                System.err.println(e.getMessage());
            }
        }

        if (!closed)
            System.exit(1);

    }

}

From source file:examples.tftp.java

public final static void main(String[] args) {
    boolean receiveFile = true, closed;
    int transferMode = TFTP.BINARY_MODE, argc;
    String arg, hostname, localFilename, remoteFilename;
    TFTPClient tftp;/*www . j  av  a2  s. c o  m*/

    // Parse options
    for (argc = 0; argc < args.length; argc++) {
        arg = args[argc];
        if (arg.startsWith("-")) {
            if (arg.equals("-r"))
                receiveFile = true;
            else if (arg.equals("-s"))
                receiveFile = false;
            else if (arg.equals("-a"))
                transferMode = TFTP.ASCII_MODE;
            else if (arg.equals("-b"))
                transferMode = TFTP.BINARY_MODE;
            else {
                System.err.println("Error: unrecognized option.");
                System.err.print(USAGE);
                System.exit(1);
            }
        } else
            break;
    }

    // Make sure there are enough arguments
    if (args.length - argc != 3) {
        System.err.println("Error: invalid number of arguments.");
        System.err.print(USAGE);
        System.exit(1);
    }

    // Get host and file arguments
    hostname = args[argc];
    localFilename = args[argc + 1];
    remoteFilename = args[argc + 2];

    // Create our TFTP instance to handle the file transfer.
    tftp = new TFTPClient();

    // We want to timeout if a response takes longer than 60 seconds
    tftp.setDefaultTimeout(60000);

    // Open local socket
    try {
        tftp.open();
    } catch (SocketException e) {
        System.err.println("Error: could not open local UDP socket.");
        System.err.println(e.getMessage());
        System.exit(1);
    }

    // We haven't closed the local file yet.
    closed = false;

    // If we're receiving a file, receive, otherwise send.
    if (receiveFile) {
        FileOutputStream output = null;
        File file;

        file = new File(localFilename);

        // If file exists, don't overwrite it.
        if (file.exists()) {
            System.err.println("Error: " + localFilename + " already exists.");
            System.exit(1);
        }

        // Try to open local file for writing
        try {
            output = new FileOutputStream(file);
        } catch (IOException e) {
            tftp.close();
            System.err.println("Error: could not open local file for writing.");
            System.err.println(e.getMessage());
            System.exit(1);
        }

        // Try to receive remote file via TFTP
        try {
            tftp.receiveFile(remoteFilename, transferMode, output, hostname);
        } catch (UnknownHostException e) {
            System.err.println("Error: could not resolve hostname.");
            System.err.println(e.getMessage());
            System.exit(1);
        } catch (IOException e) {
            System.err.println("Error: I/O exception occurred while receiving file.");
            System.err.println(e.getMessage());
            System.exit(1);
        } finally {
            // Close local socket and output file
            tftp.close();
            try {
                output.close();
                closed = true;
            } catch (IOException e) {
                closed = false;
                System.err.println("Error: error closing file.");
                System.err.println(e.getMessage());
            }
        }

        if (!closed)
            System.exit(1);

    } else {
        // We're sending a file
        FileInputStream input = null;

        // Try to open local file for reading
        try {
            input = new FileInputStream(localFilename);
        } catch (IOException e) {
            tftp.close();
            System.err.println("Error: could not open local file for reading.");
            System.err.println(e.getMessage());
            System.exit(1);
        }

        // Try to send local file via TFTP
        try {
            tftp.sendFile(remoteFilename, transferMode, input, hostname);
        } catch (UnknownHostException e) {
            System.err.println("Error: could not resolve hostname.");
            System.err.println(e.getMessage());
            System.exit(1);
        } catch (IOException e) {
            System.err.println("Error: I/O exception occurred while sending file.");
            System.err.println(e.getMessage());
            System.exit(1);
        } finally {
            // Close local socket and input file
            tftp.close();
            try {
                input.close();
                closed = true;
            } catch (IOException e) {
                closed = false;
                System.err.println("Error: error closing file.");
                System.err.println(e.getMessage());
            }
        }

        if (!closed)
            System.exit(1);

    }

}

From source file:Main.java

public static void main(String[] args) {
    String url = "jdbc:mySubprotocol:myDataSource";

    Connection con;/*w w  w. j  ava 2s  .  com*/
    Statement stmt;
    try {
        Class.forName("myDriver.ClassName");

    } catch (java.lang.ClassNotFoundException e) {
        System.err.print("ClassNotFoundException: ");
        System.err.println(e.getMessage());
    }

    try {
        con = DriverManager.getConnection(url, "myLogin", "myPassword");

        stmt = con.createStatement();

        Vector dataTypes = getDataTypes(con);

        String tableName;
        String columnName;
        String sqlType;
        String prompt = "Enter the new table name and hit Return: ";
        tableName = getInput(prompt);
        String createTableString = "create table " + tableName + " (";

        String commaAndSpace = ", ";
        boolean firstTime = true;
        while (true) {
            System.out.println("");
            prompt = "Enter a column name " + "(or nothing when finished) \nand hit Return: ";
            columnName = getInput(prompt);
            if (firstTime) {
                if (columnName.length() == 0) {
                    System.out.print("Need at least one column;");
                    System.out.println(" please try again");
                    continue;
                } else {
                    createTableString += columnName + " ";
                    firstTime = false;
                }
            } else if (columnName.length() == 0) {
                break;
            } else {
                createTableString += commaAndSpace + columnName + " ";
            }

            String localTypeName = null;
            String paramString = "";
            while (true) {
                System.out.println("");
                System.out.println("LIST OF TYPES YOU MAY USE:  ");
                boolean firstPrinted = true;
                int length = 0;
                for (int i = 0; i < dataTypes.size(); i++) {
                    DataType dataType = (DataType) dataTypes.get(i);
                    if (!dataType.needsToBeSet()) {
                        if (!firstPrinted)
                            System.out.print(commaAndSpace);
                        else
                            firstPrinted = false;
                        System.out.print(dataType.getSQLType());
                        length += dataType.getSQLType().length();
                        if (length > 50) {
                            System.out.println("");
                            length = 0;
                            firstPrinted = true;
                        }
                    }
                }
                System.out.println("");

                int index;
                prompt = "Enter a column type " + "from the list and hit Return:  ";
                sqlType = getInput(prompt);
                for (index = 0; index < dataTypes.size(); index++) {
                    DataType dataType = (DataType) dataTypes.get(index);
                    if (dataType.getSQLType().equalsIgnoreCase(sqlType) && !dataType.needsToBeSet()) {
                        break;
                    }
                }

                localTypeName = null;
                paramString = "";
                if (index < dataTypes.size()) { // there was a match
                    String params;
                    DataType dataType = (DataType) dataTypes.get(index);
                    params = dataType.getParams();
                    localTypeName = dataType.getLocalType();
                    if (params != null) {
                        prompt = "Enter " + params + ":  ";
                        paramString = "(" + getInput(prompt) + ")";
                    }
                    break;
                } else { // use the name as given
                    prompt = "Are you sure?  " + "Enter 'y' or 'n' and hit Return:  ";
                    String check = getInput(prompt) + " ";
                    check = check.toLowerCase().substring(0, 1);
                    if (check.equals("n"))
                        continue;
                    else {
                        localTypeName = sqlType;
                        break;
                    }
                }
            }

            createTableString += localTypeName + paramString;

        }

        createTableString += ")";
        System.out.println("");
        System.out.print("Your CREATE TABLE statement as ");
        System.out.println("sent to your DBMS:  ");
        System.out.println(createTableString);
        System.out.println("");

        stmt.executeUpdate(createTableString);

        stmt.close();
        con.close();

    } catch (SQLException ex) {
        System.err.println("SQLException: " + ex.getMessage());
    }
}

From source file:org.kuali.student.git.importer.ApplyManualBranchCleanup.java

/**
 * @param args/*from  w ww.  jav  a 2 s. c o  m*/
 */
public static void main(String[] args) {

    if (args.length < 4 || args.length > 7) {
        usage();
    }

    File inputFile = new File(args[0]);

    if (!inputFile.exists())
        usage();

    boolean bare = false;

    if (args[2].trim().equals("1")) {
        bare = true;
    }

    String remoteName = args[3].trim();

    String refPrefix = Constants.R_HEADS;

    if (args.length == 5)
        refPrefix = args[4].trim();

    String userName = null;
    String password = null;

    if (args.length == 6)
        userName = args[5].trim();

    if (args.length == 7)
        password = args[6].trim();

    try {

        Repository repo = GitRepositoryUtils.buildFileRepository(new File(args[1]).getAbsoluteFile(), false,
                bare);

        Git git = new Git(repo);

        RevWalk rw = new RevWalk(repo);

        ObjectInserter objectInserter = repo.newObjectInserter();

        BufferedReader fileReader = new BufferedReader(new FileReader(inputFile));

        String line = fileReader.readLine();

        int lineNumber = 1;

        BatchRefUpdate batch = repo.getRefDatabase().newBatchUpdate();

        List<RefSpec> branchesToDelete = new ArrayList<>();

        while (line != null) {

            if (line.startsWith("#") || line.length() == 0) {
                // skip over comments and blank lines
                line = fileReader.readLine();
                lineNumber++;

                continue;
            }

            String parts[] = line.trim().split(":");

            String branchName = parts[0];

            Ref branchRef = repo.getRef(refPrefix + "/" + branchName);

            if (branchRef == null) {
                log.warn("line: {}, No branch matching {} exists, skipping.", lineNumber, branchName);

                line = fileReader.readLine();
                lineNumber++;

                continue;
            }

            String tagName = null;

            if (parts.length > 1)
                tagName = parts[1];

            if (tagName != null) {

                if (tagName.equals("keep")) {
                    log.info("keeping existing branch for {}", branchName);

                    line = fileReader.readLine();
                    lineNumber++;

                    continue;
                }

                if (tagName.equals("tag")) {

                    /*
                     * Shortcut to say make the tag start with the same name as the branch.
                     */
                    tagName = branchName;
                }
                // create a tag

                RevCommit commit = rw.parseCommit(branchRef.getObjectId());

                ObjectId tag = GitRefUtils.insertTag(tagName, commit, objectInserter);

                batch.addCommand(new ReceiveCommand(null, tag, Constants.R_TAGS + tagName, Type.CREATE));

                log.info("converting branch {} into a tag {}", branchName, tagName);

            }

            if (remoteName.equals("local")) {
                batch.addCommand(
                        new ReceiveCommand(branchRef.getObjectId(), null, branchRef.getName(), Type.DELETE));
            } else {

                // if the branch is remote then remember its name so we can batch delete after we have the full list.
                branchesToDelete.add(new RefSpec(":" + Constants.R_HEADS + branchName));
            }

            line = fileReader.readLine();
            lineNumber++;

        }

        fileReader.close();

        // run the batch update
        batch.execute(rw, new TextProgressMonitor());

        if (!remoteName.equals("local")) {
            // push the tag to the remote right now

            log.info("pushing tags to {}", remoteName);

            PushCommand pushCommand = git.push().setRemote(remoteName).setPushTags()
                    .setProgressMonitor(new TextProgressMonitor());

            if (userName != null)
                pushCommand.setCredentialsProvider(new UsernamePasswordCredentialsProvider(userName, password));

            Iterable<PushResult> results = pushCommand.call();

            for (PushResult pushResult : results) {

                if (!pushResult.equals(Result.NEW)) {
                    log.warn("failed to push tag " + pushResult.getMessages());
                }
            }

            // delete the branches from the remote

            log.info("pushing branch deletes to remote: {}", remoteName);

            results = git.push().setRemote(remoteName).setRefSpecs(branchesToDelete)
                    .setProgressMonitor(new TextProgressMonitor()).call();
        }

        objectInserter.release();

        rw.release();

    } catch (Exception e) {

        log.error("unexpected Exception ", e);
    }
}

From source file:de.interactive_instruments.ShapeChange.Target.FeatureCatalogue.XsltWriter.java

/**
 * Parameter identifiers have a leading "-". Parameter values are separated
 * from the parameter identifier via a single space.
 * <ul>/* w  w w  .  j a v  a 2  s  .  c o m*/
 * <li>Parameter {@value #PARAM_xslTransformerFactory}: fully qualified name
 * of the XSLT processor implementation; NOTE: this parameter may not be
 * provided if the default implementation shall be used.</li>
 * <li>Parameter {@value #PARAM_hrefMappings}: list of key-value pairs
 * defining href mappings, structured using URL query syntax (i.e. using '='
 * to separate the key from the value, using '&' to separate pairs, and with
 * URL-encoded value (with UTF-8 character encoding); NOTE: this parameter
 * may not be provided if href mappings are not needed.</li>
 * <li>Parameter {@value #PARAM_transformationParameters}: list of key-value
 * pairs defining the transformation parameters, structured using URL query
 * syntax (i.e. using '=' to separate the key from the value, using '&' to
 * separate pairs, and with URL-encoded value (with UTF-8 character
 * encoding); NOTE: this parameter may not be provided if transformation
 * parameters are not needed.</li>
 * <li>Parameter {@value #PARAM_transformationSourcePath}: path to the
 * transformation source file (may be a relative path); NOTE: this is a
 * required parameter.</li>
 * <li>Parameter {@value #PARAM_xsltMainFileUri}: String representation of
 * the URI to the main XSLT file; NOTE: this is a required parameter.</li>
 * <li>Parameter {@value #PARAM_transformationTargetPath}: path to the
 * transformation target file (may be a relative path); NOTE: this is a
 * required parameter.</li>
 * </ul>
 */
public static void main(String[] args) {

    String xslTransformerFactory = null;
    String hrefMappingsString = null;
    String transformationParametersString = null;
    String transformationSourcePath = null;
    String xsltMainFileUriString = null;
    String transformationTargetPath = null;

    // identify parameters
    String arg = null;

    for (int i = 0; i < args.length; i++) {

        arg = args[i];

        if (arg.equals(PARAM_xslTransformerFactory)) {

            if (i + 1 == args.length || args[i + 1].startsWith("-")) {
                System.err.println("No value provided for invocation parameter " + PARAM_xslTransformerFactory);
                return;
            } else {
                xslTransformerFactory = args[i + 1];
                i++;
            }

        } else if (arg.equals(PARAM_hrefMappings)) {

            if (i + 1 == args.length || args[i + 1].startsWith("-")) {
                System.err.println("No value provided for invocation parameter " + PARAM_hrefMappings);
                return;
            } else {
                hrefMappingsString = args[i + 1];
                i++;
            }

        } else if (arg.equals(PARAM_transformationParameters)) {

            if (i + 1 == args.length || args[i + 1].startsWith("-")) {
                System.err.println(
                        "No value provided for invocation parameter " + PARAM_transformationParameters);
                return;
            } else {
                transformationParametersString = args[i + 1];
                i++;
            }

        } else if (arg.equals(PARAM_transformationSourcePath)) {

            if (i + 1 == args.length || args[i + 1].startsWith("-")) {
                System.err.println(
                        "No value provided for invocation parameter " + PARAM_transformationSourcePath);
                return;
            } else {
                transformationSourcePath = args[i + 1];
                i++;
            }

        } else if (arg.equals(PARAM_transformationTargetPath)) {

            if (i + 1 == args.length || args[i + 1].startsWith("-")) {
                System.err.println(
                        "No value provided for invocation parameter " + PARAM_transformationTargetPath);
                return;
            } else {
                transformationTargetPath = args[i + 1];
                i++;
            }

        } else if (arg.equals(PARAM_xsltMainFileUri)) {

            if (i + 1 == args.length || args[i + 1].startsWith("-")) {
                System.err.println("No value provided for invocation parameter " + PARAM_xsltMainFileUri);
                return;
            } else {
                xsltMainFileUriString = args[i + 1];
                i++;
            }
        }
    }

    try {

        // parse parameter values
        Map<String, URI> hrefMappings = new HashMap<String, URI>();

        List<NameValuePair> hrefMappingsList = URLEncodedUtils.parse(hrefMappingsString, ENCODING_CHARSET);
        for (NameValuePair nvp : hrefMappingsList) {

            hrefMappings.put(nvp.getName(), new URI(nvp.getValue()));
        }

        Map<String, String> transformationParameters = new HashMap<String, String>();

        List<NameValuePair> transParamList = URLEncodedUtils.parse(transformationParametersString,
                ENCODING_CHARSET);
        for (NameValuePair nvp : transParamList) {
            transformationParameters.put(nvp.getName(), nvp.getValue());
        }

        boolean invalidParameters = false;

        if (transformationSourcePath == null) {
            invalidParameters = true;
            System.err.println("Path to transformation source file was not provided.");
        }
        if (xsltMainFileUriString == null) {
            invalidParameters = true;
            System.err.println("Path to main XSLT file was not provided.");
        }
        if (transformationTargetPath == null) {
            invalidParameters = true;
            System.err.println("Path to transformation target file was not provided.");
        }

        if (!invalidParameters) {

            // set up and execute XSL transformation
            XsltWriter writer = new XsltWriter(xslTransformerFactory, hrefMappings, transformationParameters,
                    null);

            File transformationSource = new File(transformationSourcePath);
            URI xsltMainFileUri = new URI(xsltMainFileUriString);
            File transformationTarget = new File(transformationTargetPath);

            writer.xsltWrite(transformationSource, xsltMainFileUri, transformationTarget);
        }

    } catch (Exception e) {

        String m = e.getMessage();

        if (m != null) {
            System.err.println(m);
        } else {
            System.err.println("Exception occurred while processing the XSL transformation.");
        }
    }
}

From source file:TFTPExample.java

public static void main(String[] args) {
    boolean receiveFile = true, closed;
    int transferMode = TFTP.BINARY_MODE, argc;
    String arg, hostname, localFilename, remoteFilename;
    TFTPClient tftp;// ww  w .  j a va2  s.  c o m

    // Parse options
    for (argc = 0; argc < args.length; argc++) {
        arg = args[argc];
        if (arg.startsWith("-")) {
            if (arg.equals("-r")) {
                receiveFile = true;
            } else if (arg.equals("-s")) {
                receiveFile = false;
            } else if (arg.equals("-a")) {
                transferMode = TFTP.ASCII_MODE;
            } else if (arg.equals("-b")) {
                transferMode = TFTP.BINARY_MODE;
            } else {
                System.err.println("Error: unrecognized option.");
                System.err.print(USAGE);
                System.exit(1);
            }
        } else {
            break;
        }
    }

    // Make sure there are enough arguments
    if (args.length - argc != 3) {
        System.err.println("Error: invalid number of arguments.");
        System.err.print(USAGE);
        System.exit(1);
    }

    // Get host and file arguments
    hostname = args[argc];
    localFilename = args[argc + 1];
    remoteFilename = args[argc + 2];

    // Create our TFTP instance to handle the file transfer.
    tftp = new TFTPClient();

    // We want to timeout if a response takes longer than 60 seconds
    tftp.setDefaultTimeout(60000);

    // Open local socket
    try {
        tftp.open();
    } catch (SocketException e) {
        System.err.println("Error: could not open local UDP socket.");
        System.err.println(e.getMessage());
        System.exit(1);
    }

    // We haven't closed the local file yet.
    closed = false;

    // If we're receiving a file, receive, otherwise send.
    if (receiveFile) {
        FileOutputStream output = null;
        File file;

        file = new File(localFilename);

        // If file exists, don't overwrite it.
        if (file.exists()) {
            System.err.println("Error: " + localFilename + " already exists.");
            System.exit(1);
        }

        // Try to open local file for writing
        try {
            output = new FileOutputStream(file);
        } catch (IOException e) {
            tftp.close();
            System.err.println("Error: could not open local file for writing.");
            System.err.println(e.getMessage());
            System.exit(1);
        }

        // Try to receive remote file via TFTP
        try {
            tftp.receiveFile(remoteFilename, transferMode, output, hostname);
        } catch (UnknownHostException e) {
            System.err.println("Error: could not resolve hostname.");
            System.err.println(e.getMessage());
            System.exit(1);
        } catch (IOException e) {
            System.err.println("Error: I/O exception occurred while receiving file.");
            System.err.println(e.getMessage());
            System.exit(1);
        } finally {
            // Close local socket and output file
            tftp.close();
            try {
                if (output != null) {
                    output.close();
                }
                closed = true;
            } catch (IOException e) {
                closed = false;
                System.err.println("Error: error closing file.");
                System.err.println(e.getMessage());
            }
        }

        if (!closed) {
            System.exit(1);
        }

    } else {
        // We're sending a file
        FileInputStream input = null;

        // Try to open local file for reading
        try {
            input = new FileInputStream(localFilename);
        } catch (IOException e) {
            tftp.close();
            System.err.println("Error: could not open local file for reading.");
            System.err.println(e.getMessage());
            System.exit(1);
        }

        // Try to send local file via TFTP
        try {
            tftp.sendFile(remoteFilename, transferMode, input, hostname);
        } catch (UnknownHostException e) {
            System.err.println("Error: could not resolve hostname.");
            System.err.println(e.getMessage());
            System.exit(1);
        } catch (IOException e) {
            System.err.println("Error: I/O exception occurred while sending file.");
            System.err.println(e.getMessage());
            System.exit(1);
        } finally {
            // Close local socket and input file
            tftp.close();
            try {
                if (input != null) {
                    input.close();
                }
                closed = true;
            } catch (IOException e) {
                closed = false;
                System.err.println("Error: error closing file.");
                System.err.println(e.getMessage());
            }
        }

        if (!closed) {
            System.exit(1);
        }
    }
}

From source file:GetAppInfo.java

/**
 * @param args/* w  ww .  j a  v  a 2 s.c  o m*/
 */
public static void main(String[] args) {
    if (args.length != 4) {
        System.out.println("Usage :\n" + "java -jar this_jar_name confpath query_str startIndex numbers");
        System.exit(1);
    }
    String confpath = args[0];
    GetAppConfig conf = new GetAppConfig(confpath);
    String email = conf.getUserID();
    String password = conf.getPassword();
    String query = args[1];
    final int startIndex = Integer.parseInt(args[2]);
    final int numbers = Integer.parseInt(args[3]);
    String androidid = conf.getDeviceID();

    if (email.equals("")) {
        System.out.println("Error: Failed to get UserID.");
        System.exit(2);
    } else if (password.equals("")) {
        System.out.println("Error: Failed to get Password.");
        System.exit(3);
    } else if (androidid.equals("")) {
        System.out.println("Error: Failed to get DeviceID.");
        System.exit(4);
    }

    System.out.println("query: " + query);
    MarketSession session = new MarketSession();
    session.getContext().setAndroidId(androidid);

    Locale locale = new Locale("ja", "JP");
    session.setLocale(locale);
    session.setOperator("NTT DOCOMO", "44010");
    session.getContext().setDeviceAndSdkVersion("passion:8");

    try {
        session.login(email, password, androidid);
    } catch (Exception e) {
        System.out.println("Error: failed to login.: " + e.getMessage());
        System.exit(1);
    }

    AppsRequest appsRequest = AppsRequest.newBuilder().setQuery(query).setStartIndex(startIndex)
            .setEntriesCount(numbers).setWithExtendedInfo(true).build();

    Callback<AppsResponse> callback = new Callback<AppsResponse>() {
        @Override
        public void onResult(ResponseContext context, AppsResponse response) {
            int totalcnt, cnt;
            JsonFactory factory = new JsonFactory();
            try {
                JsonGenerator generator = factory.createGenerator(new FileWriter(new File("pkginfo.json")));
                generator.writeStartObject();
                //generator.setRootValueSeparator(new SerializedString("\n"));

                if (response != null) {
                    totalcnt = response.getEntriesCount();
                    cnt = response.getAppCount();
                    System.out.println("startIndex = " + startIndex);
                    System.out.println("entriesCount = " + numbers);
                    System.out.println("totalcount = " + totalcnt);
                    System.out.println("count = " + cnt);
                    generator.writeNumberField("startIndex", startIndex);
                    generator.writeNumberField("entriesCount", numbers);
                    generator.writeNumberField("total", totalcnt);
                    generator.writeNumberField("count", cnt);
                    generator.writeRaw("\n");
                } else {
                    cnt = -1;
                }
                generator.writeFieldName("dataset");
                generator.writeStartArray();

                if (cnt > 0) {
                    for (int i = 0; ((i < cnt) && (i < numbers)); i++) {
                        generator.writeStartObject();
                        generator.writeNumberField("num", i + startIndex);
                        System.out.println(
                                "------------------------------------------------------------------------------------");
                        int counter = i + startIndex;
                        System.out.println(counter + ":");
                        System.out.println(
                                "------------------------------------------------------------------------------------");
                        generator.writeStringField("title", response.getApp(i).getTitle());
                        generator.writeStringField("appType", "" + response.getApp(i).getAppType());
                        generator.writeStringField("category",
                                response.getApp(i).getExtendedInfo().getCategory());
                        generator.writeStringField("rating", response.getApp(i).getRating());
                        generator.writeNumberField("ratingCount", response.getApp(i).getRatingsCount());
                        generator.writeStringField("countText",
                                response.getApp(i).getExtendedInfo().getDownloadsCountText());
                        generator.writeStringField("creatorId", response.getApp(i).getCreatorId());
                        generator.writeStringField("id", response.getApp(i).getId());
                        generator.writeStringField("packageName", response.getApp(i).getPackageName());
                        generator.writeStringField("version", response.getApp(i).getVersion());
                        generator.writeNumberField("versionCode", response.getApp(i).getVersionCode());
                        generator.writeStringField("price", response.getApp(i).getPrice());
                        generator.writeNumberField("priceMicros", response.getApp(i).getPriceMicros());
                        generator.writeStringField("priceCurrency", response.getApp(i).getPriceCurrency());
                        generator.writeStringField("contactWebsite",
                                response.getApp(i).getExtendedInfo().getContactWebsite());
                        generator.writeNumberField("screenshotsCount",
                                response.getApp(i).getExtendedInfo().getScreenshotsCount());
                        generator.writeNumberField("installSize",
                                response.getApp(i).getExtendedInfo().getInstallSize());
                        generator.writeStringField("permissionIdList",
                                "" + response.getApp(i).getExtendedInfo().getPermissionIdList());
                        generator.writeStringField("promotoText",
                                response.getApp(i).getExtendedInfo().getPromoText());
                        generator.writeStringField("description",
                                response.getApp(i).getExtendedInfo().getDescription());

                        System.out.println("title: " + response.getApp(i).getTitle());
                        System.out.println("appType: " + response.getApp(i).getAppType());
                        System.out.println("category: " + response.getApp(i).getExtendedInfo().getCategory());
                        System.out.println("rating: " + response.getApp(i).getRating());
                        System.out.println("ratingsCount: " + response.getApp(i).getRatingsCount());
                        System.out
                                .println("count: " + response.getApp(i).getExtendedInfo().getDownloadsCount());
                        System.out.println(
                                "countText: " + response.getApp(i).getExtendedInfo().getDownloadsCountText());
                        System.out.println("creator: " + response.getApp(i).getCreator());
                        System.out.println("creatorId: " + response.getApp(i).getCreatorId());
                        System.out.println("id: " + response.getApp(i).getId());
                        System.out.println("packageName: " + response.getApp(i).getPackageName());
                        System.out.println("version: " + response.getApp(i).getVersion());
                        //System.out.println("contactEmail: " + response.getApp(i).getExtendedInfo().getContactEmail());
                        //System.out.println("contactPhone: " + response.getApp(i).getExtendedInfo().getContactPhone());
                        System.out.println(
                                "installSize: " + response.getApp(i).getExtendedInfo().getInstallSize());
                        generator.writeEndObject();
                        generator.writeRaw("\n");
                    }
                } else if (cnt == 0) {
                    System.out.println("no hit");
                } else {
                    System.out.println("Bad Reqeust");
                }

                generator.writeEndArray();
                generator.writeEndObject();
                generator.close();

            } catch (Exception e) {
                System.out.println("Error: pkginfo(): " + e.getMessage());
            }

        } // onResult()
    };
    session.append(appsRequest, callback);
    session.flush();
}

From source file:SelectorChat.java

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

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

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

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

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

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

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

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

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

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

    if (selection == null) {
        System.err.println("error: selection must be supplied");
        printUsage();
        System.exit(1);
    }

    // Start the JMS client for the "chat".
    SelectorChat chat = new SelectorChat();
    chat.chatter(broker, username, password, selection);

}

From source file:com.xiangzhurui.util.ftp.TFTPExample.java

public static void main(String[] args) {
    boolean receiveFile = true, closed;
    int transferMode = TFTP.BINARY_MODE, argc;
    String arg, hostname, localFilename, remoteFilename;
    TFTPClient tftp;//w w  w .ja v  a  2 s.  c  o  m

    // Parse options
    for (argc = 0; argc < args.length; argc++) {
        arg = args[argc];
        if (arg.startsWith("-")) {
            if (arg.equals("-r")) {
                receiveFile = true;
            } else if (arg.equals("-s")) {
                receiveFile = false;
            } else if (arg.equals("-a")) {
                transferMode = TFTP.ASCII_MODE;
            } else if (arg.equals("-b")) {
                transferMode = TFTP.BINARY_MODE;
            } else {
                System.err.println("Error: unrecognized option.");
                System.err.print(USAGE);
                System.exit(1);
            }
        } else {
            break;
        }
    }

    // Make sure there are enough arguments
    if (args.length - argc != 3) {
        System.err.println("Error: invalid number of arguments.");
        System.err.print(USAGE);
        System.exit(1);
    }

    // Get host and file arguments
    hostname = args[argc];
    localFilename = args[argc + 1];
    remoteFilename = args[argc + 2];

    // Create our TFTP instance to handle the file transfer.
    tftp = new TFTPClient();

    // We want to timeout if a response takes longer than 60 seconds
    tftp.setDefaultTimeout(60000);

    // Open local socket
    try {
        tftp.open();
    } catch (SocketException e) {
        System.err.println("Error: could not open local UDP socket.");
        System.err.println(e.getMessage());
        System.exit(1);
    }

    // We haven't closed the local file yet.
    closed = false;

    // If we're receiving a file, receive, otherwise send.
    if (receiveFile) {
        FileOutputStream output = null;
        File file;

        file = new File(localFilename);

        // If file exists, don't overwrite it.
        if (file.exists()) {
            System.err.println("Error: " + localFilename + " already exists.");
            System.exit(1);
        }

        // Try to open local file for writing
        try {
            output = new FileOutputStream(file);
        } catch (IOException e) {
            tftp.close();
            System.err.println("Error: could not open local file for writing.");
            System.err.println(e.getMessage());
            System.exit(1);
        }

        // Try to receive remote file via TFTP
        try {
            tftp.receiveFile(remoteFilename, transferMode, output, hostname);
        } catch (UnknownHostException e) {
            System.err.println("Error: could not resolve hostname.");
            System.err.println(e.getMessage());
            System.exit(1);
        } catch (IOException e) {
            System.err.println("Error: I/O exception occurred while receiving file.");
            System.err.println(e.getMessage());
            System.exit(1);
        } finally {
            // Close local socket and output file
            tftp.close();
            try {
                if (output != null) {
                    output.close();
                }
                closed = true;
            } catch (IOException e) {
                closed = false;
                System.err.println("Error: error closing file.");
                System.err.println(e.getMessage());
            }
        }

        if (!closed) {
            System.exit(1);
        }

    } else {
        // We're sending a file
        FileInputStream input = null;

        // Try to open local file for reading
        try {
            input = new FileInputStream(localFilename);
        } catch (IOException e) {
            tftp.close();
            System.err.println("Error: could not open local file for reading.");
            System.err.println(e.getMessage());
            System.exit(1);
        }

        // Try to send local file via TFTP
        try {
            tftp.sendFile(remoteFilename, transferMode, input, hostname);
        } catch (UnknownHostException e) {
            System.err.println("Error: could not resolve hostname.");
            System.err.println(e.getMessage());
            System.exit(1);
        } catch (IOException e) {
            System.err.println("Error: I/O exception occurred while sending file.");
            System.err.println(e.getMessage());
            System.exit(1);
        } finally {
            // Close local socket and input file
            tftp.close();
            try {
                if (input != null) {
                    input.close();
                }
                closed = true;
            } catch (IOException e) {
                closed = false;
                System.err.println("Error: error closing file.");
                System.err.println(e.getMessage());
            }
        }

        if (!closed) {
            System.exit(1);
        }

    }

}

From source file:com.board.games.handler.discuz.DiscuzPokerLoginServiceImpl.java

public static void main(String[] args) throws IOException, NoSuchAlgorithmException {
    String password = "lollol";
    String members_pass_salt = "bde24b";
    String members_pass_hash = "7ff84fb011b72abcff4bf75084478d7b";
    String escapePwdHTML = StringEscapeUtils.escapeHtml(password);
    System.out.println("escapeHTML = " + escapePwdHTML);

    //String pwdSha1 = getSha1(user.toLowerCase()+password);

    //log.debug("pwdSha1 = " + pwdSha1);
    System.out.println("members_pass_salt " + members_pass_salt);

    String pwdMD5 = getMD5(getMD5(password) + members_pass_salt);

    System.out.println("pwdMD5 = " + pwdMD5);

    if (pwdMD5 != null && members_pass_hash != null) {
        if (pwdMD5.equals(members_pass_hash)) {
            System.out.println("Password successfully matched");
        } else {//from w  ww .  ja va  2  s. c o m
            System.out.println("Failed");
        }
    }
}