Example usage for java.net URL getPath

List of usage examples for java.net URL getPath

Introduction

In this page you can find the example usage for java.net URL getPath.

Prototype

public String getPath() 

Source Link

Document

Gets the path part of this URL .

Usage

From source file:net.bluehornreader.service.ServiceManager.java

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

    String webappPath = null;/*from www  .j av a 2s .com*/

    if (Utils.isInJar()) {
        if (args.length != 1 || isHelp(args)) {

            System.err.println("Usage:\njava -Dlog4j.configuration=file:<PATH>/log4j.properties "
                    + "-jar bluehorn-reader-<VERSION>.one-jar.jar <PATH>/config.properties");
            System.exit(1);
        }
    } else {
        if ((args.length != 2 && args.length != 1) || isHelp(args)) {
            System.err.println("Usage:\njava -Dlog4j.configuration=file:<PATH>/log4j.properties "
                    + "net.bluehornreader.service.ServiceManager <PATH>/config.properties <PATH>/webapp");
            System.exit(1);
        }

        if (args.length == 2) {
            webappPath = args[1];
        } else {
            URL url = ServiceManager.class.getClassLoader()
                    .getResource("net/bluehornreader/model/Article.class");
            if (url != null) {
                webappPath = url.getPath().replace("target/classes/net/bluehornreader/model/Article.class", "")
                        + "src/main/webapp";
                if (new File(webappPath).isDirectory()) {
                    LOG.info("Found webapp folder at " + webappPath);
                } else {
                    webappPath = null;
                }
            }

            if (webappPath == null) {
                System.err.println(
                        "Cannot locate the webapp folder. You'll have to specify it manually, as the second parameter.");
                System.exit(1);
            }
        }
    }

    if (webappPath == null) {
        webappPath = new File(".").getCanonicalPath(); // just to have a valid folder to pass
    }

    String configFileName = args[0];
    Config.setup(configFileName);
    final ServiceManager serviceManager = new ServiceManager(webappPath);

    Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
        @Override
        public void run() {
            LOG.info("***************************************************************************\n\n");
            LOG.info("Shutting down ServiceManager ...");
            serviceManager.shutdown();
        }
    }));
}

From source file:de.ipbhalle.metfusion.utilities.chemaxon.ChemAxonUtilities.java

public static void main(String[] args) {
    ChemAxonUtilities cau = new ChemAxonUtilities(true);
    URL url = cau.getClass().getResource("fcfp.xml");
    System.out.println("file -> " + url.getFile());
    System.out.println("path -> " + url.getPath());

    ECFP one = cau.generateECFPFromName("O=P(c1ccccc1)(c2ccccc2)C");
    ECFP two = cau.generateECFPFromName("O=P4(C1C3C2CC1C4C23)c5ccccc5");
    System.out.println("tan test -> " + (1 - one.getTanimoto(two)));

    ECFPParameters params = new ECFPParameters(new File(url.getFile()));
    ECFPFeatureLookup lookup = new ECFPFeatureLookup(params);
    MolHandler mh = null;/*from   w ww.jav  a 2 s. co m*/
    try {
        mh = new MolHandler("O=P(c1ccccc1)(c2ccccc2)C");
        Molecule m = mh.getMolecule();
        lookup.processMolecule(m);
        int[] arr = one.toIntArray();
        for (int i = 0; i < arr.length; i++) {
            for (ECFPFeature f : lookup.getFeaturesFromIdentifier(arr[i])) {
                //System.out.println(f.getSubstructure().toFormat("SMARTS"));
                try {
                    System.out.println(MolExporter.exportToFormat(f.getSubstructure(), "SMARTS"));
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    } catch (MolFormatException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    SmilesParser sp = new SmilesParser(DefaultChemObjectBuilder.getInstance());
    try {
        Fingerprinter fp = new Fingerprinter();

        IAtomContainer ac1 = sp.parseSmiles("O=P(c1ccccc1)(c2ccccc2)C");
        IAtomContainer ac2 = sp.parseSmiles("O=P4(C1C3C2CC1C4C23)c5ccccc5");
        float tan = Tanimoto.calculate(fp.getFingerprint(ac1), fp.getFingerprint(ac2));
        System.out.println("CDK tanimoto -> " + tan);
    } catch (InvalidSmilesException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (CDKException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    ChemAxonUtilities cau2 = new ChemAxonUtilities(false);
    ECFP test = cau2.generateECFPFromMol(new File("/vol/massbank/Cache/PB/mol/PB000122.mol"));
    ECFP test2 = cau2.generateECFPFromMol(new File("/vol/massbank/Cache/PB/mol/PB000126.mol"));
    System.out.println("tanimoto dissimilarity -> " + test.getTanimoto(test2));
    System.out.println("tanimoto similarity -> " + (1 - test.getTanimoto(test2)));
}

From source file:com.xx_dev.speed_test.SpeedTestClient.java

public static void main(String[] args) {
    EventLoopGroup group = new NioEventLoopGroup();
    try {/*from w ww  .  j  av a  2  s .  c  o  m*/

        URL url = new URL(args[0]);

        boolean isSSL = false;
        String host = url.getHost();
        int port = 80;
        if (StringUtils.equals(url.getProtocol(), "https")) {
            port = 443;
            isSSL = true;
        }

        if (url.getPort() > 0) {
            port = url.getPort();
        }

        String path = url.getPath();
        if (StringUtils.isNotBlank(url.getQuery())) {
            path += "?" + url.getQuery();
        }

        PrintWriter resultPrintWriter = null;
        if (StringUtils.isNotBlank(args[1])) {
            String resultFile = args[1];

            resultPrintWriter = new PrintWriter(
                    new OutputStreamWriter(new FileOutputStream(resultFile, false), "UTF-8"));
        }

        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class)
                .handler(new SpeedTestHttpClientChannelInitializer(isSSL, resultPrintWriter));

        // Make the connection attempt.
        Channel ch = b.connect(host, port).sync().channel();

        // Prepare the HTTP request.
        HttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, path);
        request.headers().set(HttpHeaders.Names.HOST, host);
        request.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.CLOSE);
        //request.headers().set(HttpHeaders.Names.ACCEPT_ENCODING, HttpHeaders.Values.GZIP);

        // Send the HTTP request.
        ch.writeAndFlush(request);

        // Wait for the server to close the connection.
        ch.closeFuture().sync();

        if (resultPrintWriter != null) {
            resultPrintWriter.close();
        }

    } catch (InterruptedException e) {
        logger.error(e.getMessage(), e);
    } catch (FileNotFoundException e) {
        logger.error(e.getMessage(), e);
    } catch (UnsupportedEncodingException e) {
        logger.error(e.getMessage(), e);
    } catch (MalformedURLException e) {
        logger.error(e.getMessage(), e);
    } finally {
        group.shutdownGracefully();
    }
}

From source file:com.bytelightning.opensource.pokerface.PokerFaceApp.java

public static void main(String[] args) {
    if (JavaVersionAsFloat() < (1.8f - Float.MIN_VALUE)) {
        System.err.println("PokerFace requires at least Java v8 to run.");
        return;/* ww w  .ja  va  2  s.  c om*/
    }
    // Configure the command line options parser
    Options options = new Options();
    options.addOption("h", false, "help");
    options.addOption("listen", true, "(http,https,secure,tls,ssl,CertAlias)=Address:Port for https.");
    options.addOption("keystore", true, "Filepath for PokerFace certificate keystore.");
    options.addOption("storepass", true, "The store password of the keystore.");
    options.addOption("keypass", true, "The key password of the keystore.");
    options.addOption("target", true, "Remote Target requestPattern=targetUri"); // NOTE: targetUri may contain user-info and if so will be interpreted as the alias of a cert to be presented to the remote target
    options.addOption("servercpu", true, "Number of cores the server should use.");
    options.addOption("targetcpu", true, "Number of cores the http targets should use.");
    options.addOption("trustany", false, "Ignore certificate identity errors from target servers.");
    options.addOption("files", true, "Filepath to a directory of static files.");
    options.addOption("config", true, "Path for XML Configuration file.");
    options.addOption("scripts", true, "Filepath for root scripts directory.");
    options.addOption("library", true, "JavaScript library to load into global context.");
    options.addOption("watch", false, "Dynamically watch scripts directory for changes.");
    options.addOption("dynamicTargetScripting", false,
            "WARNING! This option allows scripts to redirect requests to *any* other remote server.");

    CommandLine cmdLine = null;
    // parse the command line.
    try {
        CommandLineParser parser = new PosixParser();
        cmdLine = parser.parse(options, args);
        if (args.length == 0 || cmdLine.hasOption('h')) {
            HelpFormatter formatter = new HelpFormatter();
            formatter.setWidth(120);
            formatter.printHelp(PokerFaceApp.class.getSimpleName(), options);
            return;
        }
    } catch (ParseException exp) {
        System.err.println("Parsing failed.  Reason: " + exp.getMessage());
        return;
    } catch (Exception ex) {
        ex.printStackTrace(System.err);
        return;
    }

    XMLConfiguration config = new XMLConfiguration();
    try {
        if (cmdLine.hasOption("config")) {
            Path tmp = Utils.MakePath(cmdLine.getOptionValue("config"));
            if (!Files.exists(tmp))
                throw new FileNotFoundException("Configuration file does not exist.");
            if (Files.isDirectory(tmp))
                throw new FileNotFoundException("'config' path is not a file.");
            // This is a bit of a pain, but but let's make sure we have a valid configuration file before we actually try to use it.
            config.setEntityResolver(new DefaultEntityResolver() {
                @Override
                public InputSource resolveEntity(String publicId, String systemId) throws SAXException {
                    InputSource retVal = super.resolveEntity(publicId, systemId);
                    if ((retVal == null) && (systemId != null)) {
                        try {
                            URL entityURL;
                            if (systemId.endsWith("/PokerFace_v1Config.xsd"))
                                entityURL = PokerFaceApp.class.getResource("/PokerFace_v1Config.xsd");
                            else
                                entityURL = new URL(systemId);
                            URLConnection connection = entityURL.openConnection();
                            connection.setUseCaches(false);
                            InputStream stream = connection.getInputStream();
                            retVal = new InputSource(stream);
                            retVal.setSystemId(entityURL.toExternalForm());
                        } catch (Throwable e) {
                            return retVal;
                        }
                    }
                    return retVal;
                }

            });
            config.setSchemaValidation(true);
            config.setURL(tmp.toUri().toURL());
            config.load();
            if (cmdLine.hasOption("listen"))
                System.out.println("IGNORING 'listen' option because a configuration file was supplied.");
            if (cmdLine.hasOption("target"))
                System.out.println("IGNORING 'target' option(s) because a configuration file was supplied.");
            if (cmdLine.hasOption("scripts"))
                System.out.println("IGNORING 'scripts' option because a configuration file was supplied.");
            if (cmdLine.hasOption("library"))
                System.out.println("IGNORING 'library' option(s) because a configuration file was supplied.");
        } else {
            String[] serverStrs;
            String[] addr = { null };
            String[] port = { null };
            serverStrs = cmdLine.getOptionValues("listen");
            if (serverStrs == null)
                throw new MissingOptionException("No listening addresses specified specified");
            for (int i = 0; i < serverStrs.length; i++) {
                String addrStr;
                String alias = null;
                String protocol = null;
                Boolean https = null;
                int addrPos = serverStrs[i].indexOf('=');
                if (addrPos >= 0) {
                    if (addrPos < 2)
                        throw new IllegalArgumentException("Invalid http argument.");
                    else if (addrPos + 1 >= serverStrs[i].length())
                        throw new IllegalArgumentException("Invalid http argument.");
                    addrStr = serverStrs[i].substring(addrPos + 1, serverStrs[i].length());
                    String[] types = serverStrs[i].substring(0, addrPos).split(",");
                    for (String type : types) {
                        if (type.equalsIgnoreCase("http"))
                            break;
                        else if (type.equalsIgnoreCase("https") || type.equalsIgnoreCase("secure"))
                            https = true;
                        else if (type.equalsIgnoreCase("tls") || type.equalsIgnoreCase("ssl"))
                            protocol = type.toUpperCase();
                        else
                            alias = type;
                    }
                } else
                    addrStr = serverStrs[i];
                ParseAddressString(addrStr, addr, port, alias != null ? 443 : 80);
                config.addProperty("server.listen(" + i + ")[@address]", addr[0]);
                config.addProperty("server.listen(" + i + ")[@port]", port[0]);
                if (alias != null)
                    config.addProperty("server.listen(" + i + ")[@alias]", alias);
                if (protocol != null)
                    config.addProperty("server.listen(" + i + ")[@protocol]", protocol);
                if (https != null)
                    config.addProperty("server.listen(" + i + ")[@secure]", https);
            }
            String servercpu = cmdLine.getOptionValue("servercpu");
            if (servercpu != null)
                config.setProperty("server[@cpu]", servercpu);
            String clientcpu = cmdLine.getOptionValue("targetcpu");
            if (clientcpu != null)
                config.setProperty("targets[@cpu]", clientcpu);

            // Configure static files
            if (cmdLine.hasOption("files")) {
                Path tmp = Utils.MakePath(cmdLine.getOptionValue("files"));
                if (!Files.exists(tmp))
                    throw new FileNotFoundException("Files directory does not exist.");
                if (!Files.isDirectory(tmp))
                    throw new FileNotFoundException("'files' path is not a directory.");
                config.setProperty("files.rootDirectory", tmp.toAbsolutePath().toUri());
            }

            // Configure scripting
            if (cmdLine.hasOption("scripts")) {
                Path tmp = Utils.MakePath(cmdLine.getOptionValue("scripts"));
                if (!Files.exists(tmp))
                    throw new FileNotFoundException("Scripts directory does not exist.");
                if (!Files.isDirectory(tmp))
                    throw new FileNotFoundException("'scripts' path is not a directory.");
                config.setProperty("scripts.rootDirectory", tmp.toAbsolutePath().toUri());
                config.setProperty("scripts.dynamicWatch", cmdLine.hasOption("watch"));
                String[] libraries = cmdLine.getOptionValues("library");
                if (libraries != null) {
                    for (int i = 0; i < libraries.length; i++) {
                        Path lib = Utils.MakePath(libraries[i]);
                        if (!Files.exists(lib))
                            throw new FileNotFoundException(
                                    "Script library does not exist [" + libraries[i] + "].");
                        if (Files.isDirectory(lib))
                            throw new FileNotFoundException(
                                    "Script library is not a file [" + libraries[i] + "].");
                        config.setProperty("scripts.library(" + i + ")", lib.toAbsolutePath().toUri());
                    }
                }
            } else if (cmdLine.hasOption("watch"))
                System.out.println("IGNORING 'watch' option as no 'scripts' directory was specified.");
            else if (cmdLine.hasOption("library"))
                System.out.println("IGNORING 'library' option as no 'scripts' directory was specified.");
        }
        String keyStorePath = cmdLine.getOptionValue("keystore");
        if (keyStorePath != null)
            config.setProperty("keystore", keyStorePath);
        String keypass = cmdLine.getOptionValue("keypass");
        if (keypass != null)
            config.setProperty("keypass", keypass);
        String storepass = cmdLine.getOptionValue("storepass");
        if (storepass != null)
            config.setProperty("storepass", keypass);
        if (cmdLine.hasOption("trustany"))
            config.setProperty("targets[@trustAny]", true);

        config.setProperty("scripts.dynamicTargetScripting", cmdLine.hasOption("dynamicTargetScripting"));

        String[] targetStrs = cmdLine.getOptionValues("target");
        if (targetStrs != null) {
            for (int i = 0; i < targetStrs.length; i++) {
                int uriPos = targetStrs[i].indexOf('=');
                if (uriPos < 2)
                    throw new IllegalArgumentException("Invalid target argument.");
                else if (uriPos + 1 >= targetStrs[i].length())
                    throw new IllegalArgumentException("Invalid target argument.");
                String patternStr = targetStrs[i].substring(0, uriPos);
                String urlStr = targetStrs[i].substring(uriPos + 1, targetStrs[i].length());
                String alias;
                try {
                    URL url = new URL(urlStr);
                    alias = url.getUserInfo();
                    String scheme = url.getProtocol();
                    if ((!"http".equals(scheme)) && (!"https".equals(scheme)))
                        throw new IllegalArgumentException("Invalid target uri scheme.");
                    int port = url.getPort();
                    if (port < 0)
                        port = url.getDefaultPort();
                    urlStr = scheme + "://" + url.getHost() + ":" + port + url.getPath();
                    String ref = url.getRef();
                    if (ref != null)
                        urlStr += "#" + ref;
                } catch (MalformedURLException ex) {
                    throw new IllegalArgumentException("Malformed target uri");
                }
                config.addProperty("targets.target(" + i + ")[@pattern]", patternStr);
                config.addProperty("targets.target(" + i + ")[@url]", urlStr);
                if (alias != null)
                    config.addProperty("targets.target(" + i + ")[@alias]", alias);
            }
        }
        //         config.save(System.out);
    } catch (Throwable e) {
        e.printStackTrace(System.err);
        return;
    }
    // If we get here, we have a possibly valid configuration.
    try {
        final PokerFace p = new PokerFace();
        p.config(config);
        if (p.start()) {
            PokerFace.Logger.warn("Started!");
            Runtime.getRuntime().addShutdownHook(new Thread() {
                public void run() {
                    try {
                        PokerFace.Logger.warn("Initiating shutdown...");
                        p.stop();
                        PokerFace.Logger.warn("Shutdown completed!");
                    } catch (Throwable e) {
                        PokerFace.Logger.error("Failed to shutdown cleanly!");
                        e.printStackTrace(System.err);
                    }
                }
            });
        } else {
            PokerFace.Logger.error("Failed to start!");
            System.exit(-1);
        }
    } catch (Throwable e) {
        e.printStackTrace(System.err);
    }
}

From source file:com.sforce.dataset.DatasetUtilMain.java

public static void main(String[] args) {

    printBanner();/*from  w  w w. j av  a  2 s  .c  o  m*/

    DatasetUtilParams params = new DatasetUtilParams();

    if (args.length > 0)
        params.server = false;

    System.out.println("");
    System.out.println("DatsetUtils called with {" + args.length + "} Params:");

    for (int i = 0; i < args.length; i++) {
        if ((i & 1) == 0) {
            System.out.print("{" + args[i] + "}");
        } else {
            if (i > 0 && args[i - 1].equalsIgnoreCase("--p"))
                System.out.println(":{*******}");
            else
                System.out.println(":{" + args[i] + "}");
        }

        if (i > 0 && args[i - 1].equalsIgnoreCase("--server")) {
            if (args[i] != null && args[i].trim().equalsIgnoreCase("false"))
                params.server = false;
            else if (args[i] != null && args[i].trim().equalsIgnoreCase("true"))
                params.server = true;
        }
    }
    System.out.println("");

    if (!printlneula(params.server)) {
        System.out.println(
                "You do not have permission to use this software. Please delete it from this computer");
        System.exit(-1);
    }

    String action = null;

    if (args.length >= 2) {
        for (int i = 1; i < args.length; i = i + 2) {
            if (args[i - 1].equalsIgnoreCase("--help") || args[i - 1].equalsIgnoreCase("-help")
                    || args[i - 1].equalsIgnoreCase("help")) {
                printUsage();
            } else if (args[i - 1].equalsIgnoreCase("--u")) {
                params.username = args[i];
            } else if (args[i - 1].equalsIgnoreCase("--p")) {
                params.password = args[i];
            } else if (args[i - 1].equalsIgnoreCase("--sessionId")) {
                params.sessionId = args[i];
            } else if (args[i - 1].equalsIgnoreCase("--token")) {
                params.token = args[i];
            } else if (args[i - 1].equalsIgnoreCase("--endpoint")) {
                params.endpoint = args[i];
            } else if (args[i - 1].equalsIgnoreCase("--action")) {
                action = args[i];
            } else if (args[i - 1].equalsIgnoreCase("--operation")) {
                if (args[i] != null) {
                    if (args[i].equalsIgnoreCase("overwrite")) {
                        params.Operation = args[i];
                    } else if (args[i].equalsIgnoreCase("upsert")) {
                        params.Operation = args[i];
                    } else if (args[i].equalsIgnoreCase("append")) {
                        params.Operation = args[i];
                    } else if (args[i].equalsIgnoreCase("delete")) {
                        params.Operation = args[i];
                    } else {
                        System.out.println("Invalid Operation {" + args[i]
                                + "} Must be Overwrite or Upsert or Append or Delete");
                        System.exit(-1);
                    }
                }
            } else if (args[i - 1].equalsIgnoreCase("--debug")) {
                params.debug = true;
                DatasetUtilConstants.debug = true;
            } else if (args[i - 1].equalsIgnoreCase("--ext")) {
                DatasetUtilConstants.ext = true;
            } else if (args[i - 1].equalsIgnoreCase("--inputFile")) {
                String tmp = args[i];
                if (tmp != null) {
                    File tempFile = new File(tmp);
                    if (tempFile.exists()) {
                        params.inputFile = tempFile.toString();
                    } else {
                        System.out.println("File {" + args[i] + "} does not exist");
                        System.exit(-1);
                    }
                }
            } else if (args[i - 1].equalsIgnoreCase("--dataset")) {
                params.dataset = args[i];
            } else if (args[i - 1].equalsIgnoreCase("--datasetLabel")) {
                params.datasetLabel = args[i];
            } else if (args[i - 1].equalsIgnoreCase("--app")) {
                params.app = args[i];
            } else if (args[i - 1].equalsIgnoreCase("--useBulkAPI")) {
                if (args[i] != null && args[i].trim().equalsIgnoreCase("true"))
                    params.useBulkAPI = true;
            } else if (args[i - 1].equalsIgnoreCase("--uploadFormat")) {
                if (args[i] != null && args[i].trim().equalsIgnoreCase("csv"))
                    params.uploadFormat = "csv";
                else if (args[i] != null && args[i].trim().equalsIgnoreCase("binary"))
                    params.uploadFormat = "binary";
            } else if (args[i - 1].equalsIgnoreCase("--rowLimit")) {
                if (args[i] != null && !args[i].trim().isEmpty())
                    params.rowLimit = (new BigDecimal(args[i].trim())).intValue();
            } else if (args[i - 1].equalsIgnoreCase("--rootObject")) {
                params.rootObject = args[i];
            } else if (args[i - 1].equalsIgnoreCase("--fileEncoding")) {
                params.fileEncoding = args[i];
            } else if (args[i - 1].equalsIgnoreCase("--server")) {
                if (args[i] != null && args[i].trim().equalsIgnoreCase("true"))
                    params.server = true;
                else if (args[i] != null && args[i].trim().equalsIgnoreCase("false"))
                    params.server = false;
            } else if (args[i - 1].equalsIgnoreCase("--codingErrorAction")) {
                if (args[i] != null) {
                    if (args[i].equalsIgnoreCase("IGNORE")) {
                        params.codingErrorAction = CodingErrorAction.IGNORE;
                    } else if (args[i].equalsIgnoreCase("REPORT")) {
                        params.codingErrorAction = CodingErrorAction.REPORT;
                    } else if (args[i].equalsIgnoreCase("REPLACE")) {
                        params.codingErrorAction = CodingErrorAction.REPLACE;
                    }
                }
            } else {
                printUsage();
                System.out.println("\nERROR: Invalid argument: " + args[i - 1]);
                System.exit(-1);
            }
        } //end for

        if (params.username != null) {
            if (params.endpoint == null || params.endpoint.isEmpty()) {
                params.endpoint = DatasetUtilConstants.defaultEndpoint;
            }
        }
    }

    if (params.server) {
        System.out.println();
        System.out.println("\n*******************************************************************************");
        try {
            DatasetUtilServer datasetUtilServer = new DatasetUtilServer();
            datasetUtilServer.init(args, true);
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("Server ended, exiting JVM.....");
        System.out.println("*******************************************************************************\n");
        System.out.println("QUITAPP");
        System.exit(0);
    }

    if (params.sessionId == null) {
        if (params.username == null || params.username.trim().isEmpty()) {
            params.username = getInputFromUser("Enter salesforce username: ", true, false);
        }

        if (params.username.equals("-1")) {
            params.sessionId = getInputFromUser("Enter salesforce sessionId: ", true, false);
            params.username = null;
            params.password = null;
        } else {
            if (params.password == null || params.password.trim().isEmpty()) {
                params.password = getInputFromUser("Enter salesforce password: ", true, true);
            }
        }
    }

    if (params.sessionId != null && !params.sessionId.isEmpty()) {
        while (params.endpoint == null || params.endpoint.trim().isEmpty()) {
            params.endpoint = getInputFromUser("Enter salesforce instance url: ", true, false);
            if (params.endpoint == null || params.endpoint.trim().isEmpty())
                System.out.println("\nERROR: endpoint must be specified when sessionId is specified");
        }

        while (params.endpoint.toLowerCase().contains("login.salesforce.com")
                || params.endpoint.toLowerCase().contains("test.salesforce.com")
                || params.endpoint.toLowerCase().contains("test")
                || params.endpoint.toLowerCase().contains("prod")
                || params.endpoint.toLowerCase().contains("sandbox")) {
            System.out.println("\nERROR: endpoint must be the actual serviceURL and not the login url");
            params.endpoint = getInputFromUser("Enter salesforce instance url: ", true, false);
        }
    } else {
        if (params.endpoint == null || params.endpoint.isEmpty()) {
            params.endpoint = getInputFromUser("Enter salesforce instance url (default=prod): ", false, false);
            if (params.endpoint == null || params.endpoint.trim().isEmpty()) {
                params.endpoint = DatasetUtilConstants.defaultEndpoint;
            }
        }
    }

    try {
        if (params.endpoint.equalsIgnoreCase("PROD") || params.endpoint.equalsIgnoreCase("PRODUCTION")) {
            params.endpoint = DatasetUtilConstants.defaultEndpoint;
        } else if (params.endpoint.equalsIgnoreCase("TEST") || params.endpoint.equalsIgnoreCase("SANDBOX")) {
            params.endpoint = DatasetUtilConstants.defaultEndpoint.replace("login", "test");
        }

        URL uri = new URL(params.endpoint);
        String protocol = uri.getProtocol();
        String host = uri.getHost();
        if (protocol == null || !protocol.equalsIgnoreCase("https")) {
            if (host == null || !(host.toLowerCase().endsWith("internal.salesforce.com")
                    || host.toLowerCase().endsWith("localhost"))) {
                System.out.println("\nERROR: Invalid endpoint. UNSUPPORTED_CLIENT: HTTPS Required in endpoint");
                System.exit(-1);
            }
        }

        if (uri.getPath() == null || uri.getPath().isEmpty() || uri.getPath().equals("/")) {
            uri = new URL(uri.getProtocol(), uri.getHost(), uri.getPort(),
                    DatasetUtilConstants.defaultSoapEndPointPath);
        }
        params.endpoint = uri.toString();
    } catch (MalformedURLException e) {
        e.printStackTrace();
        System.out.println("\nERROR: endpoint is not a valid URL");
        System.exit(-1);
    }

    PartnerConnection partnerConnection = null;
    if (params.username != null || params.sessionId != null) {
        try {
            partnerConnection = DatasetUtils.login(0, params.username, params.password, params.token,
                    params.endpoint, params.sessionId, params.debug);
        } catch (ConnectionException e) {
            e.printStackTrace();
            System.exit(-1);
        } catch (MalformedURLException e) {
            e.printStackTrace();
            System.exit(-1);
        }
    }

    if (args.length == 0 || action == null) {
        //         System.out.println("\n*******************************************************************************");               
        ////         FileListenerUtil.startAllListener(partnerConnection);
        //         try {
        //            Thread.sleep(1000);
        //         } catch (InterruptedException e) {
        //         }
        //         System.out.println("*******************************************************************************\n");   
        //         System.out.println();         

        //         System.out.println("\n*******************************************************************************");               
        //           try {
        //              DatasetUtilServer datasetUtilServer = new DatasetUtilServer();
        //            datasetUtilServer.init(args, false);
        //         } catch (Exception e) {
        //            e.printStackTrace();
        //         }
        //         System.out.println("*******************************************************************************\n");   
        //         System.out.println();         

        while (true) {
            action = getActionFromUser();
            if (action == null || action.isEmpty()) {
                System.exit(-1);
            }
            params = new DatasetUtilParams();
            getRequiredParams(action, partnerConnection, params);
            @SuppressWarnings("unused")
            boolean status = doAction(action, partnerConnection, params);
            //            if(status)
            //            {
            //               if(action.equalsIgnoreCase("load") && params.debug)
            //                  createListener(partnerConnection, params);
            //            }
        }
    } else {
        doAction(action, partnerConnection, params);
    }

}

From source file:ProxyAuthenticator.java

private static String getOutputFileName(URL url) {
    String[] urlParts = url.getPath().split("/");
    return "c:/temp/" + urlParts[urlParts.length - 1];
}

From source file:Main.java

public static String getPathFromUrl(String url) {
    URL iurl;
    try {// ww w  .  ja  v  a 2  s  .  c  o  m
        iurl = new URL(url);
        return iurl.getPath();

    } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return "";
    }
}

From source file:Main.java

/**
 * @deprecated/*from   w  w  w  .  jav  a2s.c  o m*/
 */
public static String shortNameForURL(String url) {
    if (url == null || "".equals(url))
        return "(None)";

    try {
        URL u = new URL(url);
        String rsrcName = u.getPath();
        String query = u.getQuery();
        boolean hasParams = (query != null && !"".equals(query));

        if (hasParams)
            return rsrcName + " (with parameters)";
        else
            return rsrcName;
    } catch (Exception e) {
        ;
    }

    if (url.indexOf("&") > 0)
        return url.substring(0, url.indexOf("&"));

    return url;
}

From source file:fi.johannes.kata.ocr.utils.ResourceGetter.java

public static String getPathAsString(String fileName) {
    URL url = getUrl(fileName);
    if (url.getPath().startsWith("/")) {
        return url.getPath().substring(1);
    }/*from  w  w w. j  a va2s  . c o m*/
    return url.getPath();
}

From source file:javarestart.WebClassLoaderRegistry.java

public static WebClassLoader resolveClassLoader(URL url) {
    if (url.getPath().endsWith("/..")) {
        return null;
    }//  w ww .j a  va2s.co m
    WebClassLoader cl = null;
    URL baseURL = normalizeURL(url);
    try {
        URL rootURL = new URL(baseURL, "/");
        while (((cl = associatedClassloaders.get(baseURL)) == null) && !baseURL.equals(rootURL)) {
            baseURL = new URL(baseURL, "..");
        }
    } catch (MalformedURLException e) {
    }

    if (cl == null) {
        try {
            JSONObject desc = Utils.getJSON(new URL(url.getProtocol(), url.getHost(), url.getPort(),
                    url.getPath() + "?getAppDescriptor"));
            if (desc != null) {
                cl = new WebClassLoader(url, desc);
            }
        } catch (Exception e) {
        }
    }
    associatedClassloaders.put(normalizeURL(url), cl);
    if (cl != null) {
        URL clURL = normalizeURL(cl.getBaseURL());
        associatedClassloaders.put(clURL, cl);
        classloaders.put(clURL, cl);
    }
    return cl;
}