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:org.eclipse.swt.snippets.Snippet336.java

public static void main(String[] args) {
    display = new Display();
    shell = new Shell(display);
    shell.setText("Snippet 336");
    shell.setLayout(new GridLayout());
    TabFolder folder = new TabFolder(shell, SWT.NONE);
    folder.setLayoutData(new GridData(GridData.FILL_BOTH));

    //Progress tab
    TabItem item = new TabItem(folder, SWT.NONE);
    item.setText("Progress");
    Composite composite = new Composite(folder, SWT.NONE);
    composite.setLayout(new GridLayout());
    item.setControl(composite);/*from w w  w  .  j  a  v  a 2s .  com*/
    Listener listener = event -> {
        Button button = (Button) event.widget;
        if (!button.getSelection())
            return;
        TaskItem item1 = getTaskBarItem();
        if (item1 != null) {
            int state = ((Integer) button.getData()).intValue();
            item1.setProgressState(state);
        }
    };
    Group group = new Group(composite, SWT.NONE);
    group.setText("State");
    group.setLayout(new GridLayout());
    group.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
    Button button;
    String[] stateLabels = { "SWT.DEFAULT", "SWT.INDETERMINATE", "SWT.NORMAL", "SWT.ERROR", "SWT.PAUSED" };
    int[] states = { SWT.DEFAULT, SWT.INDETERMINATE, SWT.NORMAL, SWT.ERROR, SWT.PAUSED };
    for (int i = 0; i < states.length; i++) {
        button = new Button(group, SWT.RADIO);
        button.setText(stateLabels[i]);
        button.setData(Integer.valueOf(states[i]));
        button.addListener(SWT.Selection, listener);
        if (i == 0)
            button.setSelection(true);
    }
    group = new Group(composite, SWT.NONE);
    group.setText("Value");
    group.setLayout(new GridLayout(2, false));
    group.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
    Label label = new Label(group, SWT.NONE);
    label.setText("Progress");
    final Scale scale = new Scale(group, SWT.NONE);
    scale.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
    scale.addListener(SWT.Selection, event -> {
        TaskItem item1 = getTaskBarItem();
        if (item1 != null)
            item1.setProgress(scale.getSelection());
    });

    //Overlay text tab
    item = new TabItem(folder, SWT.NONE);
    item.setText("Text");
    composite = new Composite(folder, SWT.NONE);
    composite.setLayout(new GridLayout());
    item.setControl(composite);
    group = new Group(composite, SWT.NONE);
    group.setText("Enter a short text:");
    group.setLayout(new GridLayout(2, false));
    group.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
    final Text text = new Text(group, SWT.BORDER | SWT.SINGLE);
    GridData data = new GridData(GridData.FILL_HORIZONTAL);
    data.horizontalSpan = 2;
    text.setLayoutData(data);
    button = new Button(group, SWT.PUSH);
    button.setText("Set");
    button.addListener(SWT.Selection, event -> {
        TaskItem item1 = getTaskBarItem();
        if (item1 != null)
            item1.setOverlayText(text.getText());
    });
    button = new Button(group, SWT.PUSH);
    button.setText("Clear");
    button.addListener(SWT.Selection, event -> {
        text.setText("");
        TaskItem item1 = getTaskBarItem();
        if (item1 != null)
            item1.setOverlayText("");
    });

    //Overlay image tab
    item = new TabItem(folder, SWT.NONE);
    item.setText("Image");
    composite = new Composite(folder, SWT.NONE);
    composite.setLayout(new GridLayout());
    item.setControl(composite);
    Listener listener3 = event -> {
        Button button1 = (Button) event.widget;
        if (!button1.getSelection())
            return;
        TaskItem item1 = getTaskBarItem();
        if (item1 != null) {
            String text1 = button1.getText();
            Image image = null;
            if (!text1.equals("NONE"))
                image = new Image(display, Snippet336.class.getResourceAsStream(text1));
            Image oldImage = item1.getOverlayImage();
            item1.setOverlayImage(image);
            if (oldImage != null)
                oldImage.dispose();
        }
    };
    group = new Group(composite, SWT.NONE);
    group.setText("Images");
    group.setLayout(new GridLayout());
    group.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
    button = new Button(group, SWT.RADIO);
    button.setText("NONE");
    button.addListener(SWT.Selection, listener3);
    button.setSelection(true);
    String[] images = { "eclipse.png", "pause.gif", "run.gif", "warning.gif" };
    for (int i = 0; i < images.length; i++) {
        button = new Button(group, SWT.RADIO);
        button.setText(images[i]);
        button.addListener(SWT.Selection, listener3);
    }
    shell.pack();
    shell.open();
    while (!shell.isDisposed()) {
        if (!display.readAndDispatch())
            display.sleep();
    }
    display.dispose();
}

From source file:HttpGet.java

public static void main(String[] args) {
    SocketChannel server = null; // Channel for reading from server
    FileOutputStream outputStream = null; // Stream to destination file
    WritableByteChannel destination; // Channel to write to it

    try { // Exception handling and channel closing code follows this block

        // Parse the URL. Note we use the new java.net.URI, not URL here.
        URI uri = new URI(args[0]);

        // Now query and verify the various parts of the URI
        String scheme = uri.getScheme();
        if (scheme == null || !scheme.equals("http"))
            throw new IllegalArgumentException("Must use 'http:' protocol");

        String hostname = uri.getHost();

        int port = uri.getPort();
        if (port == -1)
            port = 80; // Use default port if none specified

        String path = uri.getRawPath();
        if (path == null || path.length() == 0)
            path = "/";

        String query = uri.getRawQuery();
        query = (query == null) ? "" : '?' + query;

        // Combine the hostname and port into a single address object.
        // java.net.SocketAddress and InetSocketAddress are new in Java 1.4
        SocketAddress serverAddress = new InetSocketAddress(hostname, port);

        // Open a SocketChannel to the server
        server = SocketChannel.open(serverAddress);

        // Put together the HTTP request we'll send to the server.
        String request = "GET " + path + query + " HTTP/1.1\r\n" + // The request
                "Host: " + hostname + "\r\n" + // Required in HTTP 1.1
                "Connection: close\r\n" + // Don't keep connection open
                "User-Agent: " + HttpGet.class.getName() + "\r\n" + "\r\n"; // Blank
                                                                            // line
                                                                            // indicates
                                                                            // end of
                                                                            // request
                                                                            // headers

        // Now wrap a CharBuffer around that request string
        CharBuffer requestChars = CharBuffer.wrap(request);

        // Get a Charset object to encode the char buffer into bytes
        Charset charset = Charset.forName("ISO-8859-1");

        // Use the charset to encode the request into a byte buffer
        ByteBuffer requestBytes = charset.encode(requestChars);

        // Finally, we can send this HTTP request to the server.
        server.write(requestBytes);// w w w .  java2  s  . c  o  m

        // Set up an output channel to send the output to.
        if (args.length > 1) { // Use a specified filename
            outputStream = new FileOutputStream(args[1]);
            destination = outputStream.getChannel();
        } else
            // Or wrap a channel around standard out
            destination = Channels.newChannel(System.out);

        // Allocate a 32 Kilobyte byte buffer for reading the response.
        // Hopefully we'll get a low-level "direct" buffer
        ByteBuffer data = ByteBuffer.allocateDirect(32 * 1024);

        // Have we discarded the HTTP response headers yet?
        boolean skippedHeaders = false;
        // The code sent by the server
        int responseCode = -1;

        // Now loop, reading data from the server channel and writing it
        // to the destination channel until the server indicates that it
        // has no more data.
        while (server.read(data) != -1) { // Read data, and check for end
            data.flip(); // Prepare to extract data from buffer

            // All HTTP reponses begin with a set of HTTP headers, which
            // we need to discard. The headers end with the string
            // "\r\n\r\n", or the bytes 13,10,13,10. If we haven't already
            // skipped them then do so now.
            if (!skippedHeaders) {
                // First, though, read the HTTP response code.
                // Assume that we get the complete first line of the
                // response when the first read() call returns. Assume also
                // that the first 9 bytes are the ASCII characters
                // "HTTP/1.1 ", and that the response code is the ASCII
                // characters in the following three bytes.
                if (responseCode == -1) {
                    responseCode = 100 * (data.get(9) - '0') + 10 * (data.get(10) - '0')
                            + 1 * (data.get(11) - '0');

                    // If there was an error, report it and quit
                    // Note that we do not handle redirect responses.
                    if (responseCode < 200 || responseCode >= 300) {
                        System.err.println("HTTP Error: " + responseCode);
                        System.exit(1);
                    }
                }

                // Now skip the rest of the headers.
                try {
                    for (;;) {
                        if ((data.get() == 13) && (data.get() == 10) && (data.get() == 13)
                                && (data.get() == 10)) {
                            skippedHeaders = true;
                            break;
                        }
                    }
                } catch (BufferUnderflowException e) {
                    // If we arrive here, it means we reached the end of
                    // the buffer and didn't find the end of the headers.
                    // There is a chance that the last 1, 2, or 3 bytes in
                    // the buffer were the beginning of the \r\n\r\n
                    // sequence, so back up a bit.
                    data.position(data.position() - 3);
                    // Now discard the headers we have read
                    data.compact();
                    // And go read more data from the server.
                    continue;
                }
            }

            // Write the data out; drain the buffer fully.
            while (data.hasRemaining())
                destination.write(data);

            // Now that the buffer is drained, put it into fill mode
            // in preparation for reading more data into it.
            data.clear(); // data.compact() also works here
        }
    } catch (Exception e) { // Report any errors that arise
        System.err.println(e);
        System.err.println("Usage: java HttpGet <URL> [<filename>]");
    } finally { // Close the channels and output file stream, if needed
        try {
            if (server != null && server.isOpen())
                server.close();
            if (outputStream != null)
                outputStream.close();
        } catch (IOException e) {
        }
    }
}

From source file:TopicReplier.java

/** Main program entry point. */
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;
    String mode = DEFAULT_MODE;//from  w w w  .j a  v a 2  s .c om

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

        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("-m")) {
            if (i == argv.length - 1 || argv[i + 1].startsWith("-")) {
                System.err.println("error: missing mode");
                System.exit(1);
            }
            mode = argv[++i];
            if (!(mode.equals("uppercase") || mode.equals("lowercase"))) {
                System.err.println("error: mode must be 'uppercase' or 'lowercase'");
                System.exit(1);
            }
            continue;
        }

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

        // Invalid argument
        System.err.println("error: unexpected argument: " + arg);
        printUsage();
        System.exit(1);
    }

    // Start the JMS client for the "chat".
    TopicReplier replier = new TopicReplier();
    replier.start(broker, username, password, mode);
}

From source file:Text2FormatStorageMR.java

@SuppressWarnings("deprecation")
public static void main(String[] args) throws Exception {

    if (args.length != 2) {
        System.out.println("FormatFileMR <input> <output>");
        System.exit(-1);/*from ww  w.  j ava 2s . c o  m*/
    }

    JobConf conf = new JobConf(FormatStorageMR.class);

    conf.setJobName("Text2FormatMR");

    conf.setNumMapTasks(1);
    conf.setNumReduceTasks(4);

    conf.setOutputKeyClass(LongWritable.class);
    conf.setOutputValueClass(Unit.Record.class);

    conf.setMapperClass(TextFileTestMapper.class);
    conf.setReducerClass(FormatFileTestReducer.class);

    conf.setInputFormat(TextInputFormat.class);
    conf.setOutputFormat(FormatStorageOutputFormat.class);
    conf.set("mapred.output.compress", "flase");

    Head head = new Head();
    initHead(head);

    head.toJobConf(conf);

    FileInputFormat.setInputPaths(conf, args[0]);
    Path outputPath = new Path(args[1]);
    FileOutputFormat.setOutputPath(conf, outputPath);

    FileSystem fs = outputPath.getFileSystem(conf);
    fs.delete(outputPath, true);

    JobClient jc = new JobClient(conf);
    RunningJob rj = null;
    rj = jc.submitJob(conf);

    String lastReport = "";
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss,SSS");
    long reportTime = System.currentTimeMillis();
    long maxReportInterval = 3 * 1000;
    while (!rj.isComplete()) {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
        }

        int mapProgress = Math.round(rj.mapProgress() * 100);
        int reduceProgress = Math.round(rj.reduceProgress() * 100);

        String report = " map = " + mapProgress + "%,  reduce = " + reduceProgress + "%";

        if (!report.equals(lastReport) || System.currentTimeMillis() >= reportTime + maxReportInterval) {

            String output = dateFormat.format(Calendar.getInstance().getTime()) + report;
            System.out.println(output);
            lastReport = report;
            reportTime = System.currentTimeMillis();
        }
    }

    System.exit(0);

}

From source file:com.dict.crawl.NewsNationalGeographicCrawler.java

public static void main(String[] args) throws Exception {
    /*string,crawlPath??crawlPath,
      ????crawlPath//from   ww  w . j a v  a2  s.com
    */

    NewsNationalGeographicCrawler crawler = new NewsNationalGeographicCrawler("data/NewsNationalGeographic");
    crawler.setThreads(2);
    crawler.addSeed("http://ngm.nationalgeographic.com/");

    if (BaseCrawler.isNormalTime()) {

        crawler.addSeed("http://ngm.nationalgeographic.com/archives");
        crawler.addSeed("http://ngm.nationalgeographic.com/featurehub");
        //
        //}

        String jsonUrl = "http://news.nationalgeographic.com/bin/services/news/public/query/content.json?pageSize=20&page=0&contentTypes=news/components/pagetypes/article,news/components/pagetypes/simple-article,news/components/pagetypes/photo-gallery";

        URL urls = new URL(jsonUrl);
        HttpURLConnection urlConnection = (HttpURLConnection) urls.openConnection();
        InputStream is = urlConnection.getInputStream();
        Reader rd = new InputStreamReader(is, "utf-8");
        JsonArray json = new JsonParser().parse(rd).getAsJsonArray();
        for (JsonElement jOb : json) {
            String url = jOb.getAsJsonObject().get("page").getAsJsonObject().get("url").getAsString();
            if (url != null && !url.equals(""))
                crawler.addSeed(url);
        }

    }

    //        crawler.addSeed("http://news.nationalgeographic.com/2016/01/160118-mummies-world-bog-egypt-science/");
    //        List<Map<String, Object>> urls = crawler.jdbcTemplate.queryForList("SELECT id,title,url FROM parser_page where host like '%news.national%' ORDER by id desc;");
    //        for(int i = 0; i < urls.size(); i++) {
    //            String url = (String) urls.get(i).get("url");
    //            String title = (String) urls.get(i).get("title");
    ////            int id = (int) urls.get(i).get("id");
    //            crawler.addSeed(url);
    //        }

    //        Config
    Config.WAIT_THREAD_END_TIME = 1000 * 60 * 5;//???kill
    //        Config.TIMEOUT_CONNECT = 1000*10;
    //        Config.TIMEOUT_READ = 1000*30;
    Config.requestMaxInterval = 1000 * 60 * 20;//??-?>hung

    //requester??http??requester?http/socks?
    HttpRequesterImpl requester = (HttpRequesterImpl) crawler.getHttpRequester();
    AntiAntiSpiderHelper.defaultUserAgent(requester);

    //        requester.setUserAgent("Mozilla/5.0 (X11; Linux i686; rv:33.0) Gecko/20100101 Firefox/33.0");
    //        requester.setCookie("CNZZDATA1950488=cnzz_eid%3D739324831-1432460954-null%26ntime%3D1432460954; wdcid=44349d3f2aa96e51; vjuids=-53d395da8.14eca7eed44.0.f17be67e; CNZZDATA3473518=cnzz_eid%3D1882396923-1437965756-%26ntime%3D1440635510; pt_37a49e8b=uid=FuI4KYEfVz5xq7L4nzPd1w&nid=1&vid=r4AhSBmxisCiyeolr3V2Ow&vn=1&pvn=1&sact=1440639037916&to_flag=0&pl=t4NrgYqSK5M357L2nGEQCw*pt*1440639015734; _ga=GA1.3.1121158748.1437970841; __auc=c00a6ac114d85945f01d9c30128; CNZZDATA1975683=cnzz_eid%3D250014133-1432460541-null%26ntime%3D1440733997; CNZZDATA1254041250=2000695407-1442220871-%7C1442306691; pt_7f0a67e8=uid=6lmgYeZ3/jSObRMeK-t27A&nid=0&vid=lEKvEtZyZdd0UC264UyZnQ&vn=2&pvn=1&sact=1442306703728&to_flag=0&pl=7GB3sYS/PJDo1mY0qeu2cA*pt*1442306703728; 7NSx_98ef_saltkey=P05gN8zn; 7NSx_98ef_lastvisit=1444281282; IframeBodyHeight=256; NTVq_98ef_saltkey=j5PydYru; NTVq_98ef_lastvisit=1444282735; NTVq_98ef_atarget=1; NTVq_98ef_lastact=1444286377%09api.php%09js; 7NSx_98ef_sid=hZyDwc; __utmt=1; __utma=155578217.1121158748.1437970841.1443159326.1444285109.23; __utmb=155578217.57.10.1444285109; __utmc=155578217; __utmz=155578217.1439345650.3.2.utmcsr=travel.chinadaily.com.cn|utmccn=(referral)|utmcmd=referral|utmcct=/; CNZZDATA3089622=cnzz_eid%3D1722311508-1437912344-%26ntime%3D1444286009; wdlast=1444287704; vjlast=1437916393.1444285111.11; 7NSx_98ef_lastact=1444287477%09api.php%09chinadaily; pt_s_3bfec6ad=vt=1444287704638&cad=; pt_3bfec6ad=uid=bo87MAT/HC3hy12HDkBg1A&nid=0&vid=erwHQyFKxvwHXYc4-r6n-w&vn=28&pvn=2&sact=1444287708079&to_flag=0&pl=kkgvLoEHXsCD2gs4VJaWQg*pt*1444287704638; pt_t_3bfec6ad=?id=3bfec6ad.bo87MAT/HC3hy12HDkBg1A.erwHQyFKxvwHXYc4-r6n-w.kkgvLoEHXsCD2gs4VJaWQg.nZJ9Aj/bgfNDIKBXI5TwRQ&stat=167.132.1050.1076.1body%20div%3Aeq%288%29%20ul%3Aeq%280%29%20a%3Aeq%282%29.0.0.1595.3441.146.118&ptif=4");
    //?? Mozilla/5.0 (X11; Linux i686; rv:34.0) Gecko/20100101 Firefox/34.0
    //c requester.setProxy("
    /*
            
    //??
    RandomProxyGenerator proxyGenerator=new RandomProxyGenerator();
    proxyGenerator.addProxy("127.0.0.1",8080,Proxy.Type.SOCKS);
    requester.setProxyGenerator(proxyGenerator);
    */

    /*??*/
    //        crawler.setResumable(true);
    crawler.setResumable(false);

    crawler.start(2);
}

From source file:com.phloc.html.supplementary.main.MainReadHTMLElementList.java

public static void main(final String[] args) throws Exception {
    s_aLogger.info("Extracting the information on all available HTML5 elements!");

    s_aLogger.info("Reading HTML");
    final byte[] aElementContent = Request.Get(BASE_URL + "elements.html").execute().returnContent().asBytes();

    s_aLogger.info("Converting to XML");
    final InputStream aIS = new NonBlockingByteArrayInputStream(aElementContent);
    final NonBlockingByteArrayOutputStream aOS = new NonBlockingByteArrayOutputStream();

    final XmlSerializer serializer = new XmlSerializer(aOS);
    final HtmlParser parser = new HtmlParser(XmlViolationPolicy.ALTER_INFOSET);
    parser.setErrorHandler(LoggingSAXErrorHandler.getInstance());
    parser.setContentHandler(serializer);
    parser.setLexicalHandler(serializer);
    parser.parse(new InputSource(aIS));
    StreamUtils.close(aOS);//from   w  w  w. ja  v a  2  s . co  m

    s_aLogger.info("Converting to MicroNode");
    final IMicroDocument aDoc = MicroReader.readMicroXML(aOS.toByteArray());

    // /html/body/div[3]/div/ul
    final IMicroElement eUL = aDoc.getDocumentElement().getFirstChildElement(EHTMLElement.BODY)
            .getAllChildElements(EHTMLElement.DIV).get(2).getFirstChildElement(EHTMLElement.DIV)
            .getFirstChildElement(EHTMLElement.UL);

    final List<Element> aElements = new ArrayList<Element>();
    for (final IMicroElement eLI : eUL.getAllChildElements(EHTMLElement.LI)) {
        final IMicroElement eA = eLI.getFirstChildElement(EHTMLElement.A);
        final String sHref = eA.getAttribute(CHTMLAttributes.HREF);
        final IMicroElement eSectionName = eA.getAllChildElements(EHTMLElement.SPAN).get(1);

        String sElementName = null;
        String sAttributeName = null;
        String sEqualsValue = null;
        String sShortDesc = null;
        for (final IMicroElement eSpan : eSectionName.getAllChildElements(EHTMLElement.SPAN)) {
            final String sClass = eSpan.getAttribute(CHTMLAttributes.CLASS);
            final String sContent = eSpan.getTextContent().trim();
            if (sClass.equals("element"))
                sElementName = sContent;
            else if (sClass.equals("elem-qualifier")) {
                for (final IMicroElement eChildSpan : eSpan.getAllChildElements(EHTMLElement.SPAN)) {
                    final String sChildClass = eChildSpan.getAttribute(CHTMLAttributes.CLASS);
                    final String sChildContent = eChildSpan.getTextContent().trim();
                    if (sChildClass.equals("attribute-name"))
                        sAttributeName = sChildContent;
                    else if (sChildClass.equals("equals-value"))
                        sEqualsValue = sChildContent;
                    else
                        s_aLogger.error("Illegal child span of '" + sElementName + "' with class '"
                                + sChildClass + "'");
                }
            } else if (sClass.equals("shortdesc"))
                sShortDesc = sContent;
            else
                s_aLogger.error("Illegal span in '" + sElementName + "' with class '" + sClass + "'");
        }

        aElements.add(new Element(sHref, sElementName, sAttributeName, sEqualsValue, sShortDesc));
    }

    s_aLogger.info("Writing result toc.xml");
    final IMicroDocument aElementsDoc = new MicroDocument();
    final IMicroElement eRoot = aElementsDoc.appendElement("elements");
    for (final Element aElement : aElements)
        eRoot.appendChild(aElement.getAsMicroXML());
    SimpleFileIO.writeFile(new File(PATH_TOC_XML), MicroWriter.getXMLString(aElementsDoc),
            XMLWriterSettings.DEFAULT_XML_CHARSET_OBJ);

    s_aLogger.info("Done");
}

From source file:ECToken3.java

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

    if (args.length == 1 && args[0].equals("--version")) {
        System.out.println("EC Token encryption and decryption utility.  Version: 3.0.0\n");
        System.exit(0);//w w  w  .j  a v a2 s.  co  m
    }

    int arg_offset = 0;
    if (args.length != 3) {
        usage();
    }

    String action = args[arg_offset + 0];
    String key = args[arg_offset + 1];
    String input = args[arg_offset + 2];
    String outString = "";
    if (action.equals("encrypt")) {
        outString = ECToken3.encryptv3(key, input);
    } else if (action.equals("decrypt")) {
        outString = ECToken3.decryptv3(key, input);
    }
    System.out.println(outString);
}

From source file:com.joliciel.talismane.terminology.Main.java

public static void main(String[] args) throws Exception {
    String termFilePath = null;//w w w . j  av a 2  s.co  m
    String outFilePath = null;
    Command command = Command.extract;
    int depth = -1;
    String databasePropertiesPath = null;
    String projectCode = null;

    Map<String, String> argMap = TalismaneConfig.convertArgs(args);

    String logConfigPath = argMap.get("logConfigFile");
    if (logConfigPath != null) {
        argMap.remove("logConfigFile");
        Properties props = new Properties();
        props.load(new FileInputStream(logConfigPath));
        PropertyConfigurator.configure(props);
    }

    Map<String, String> innerArgs = new HashMap<String, String>();
    for (Entry<String, String> argEntry : argMap.entrySet()) {
        String argName = argEntry.getKey();
        String argValue = argEntry.getValue();

        if (argName.equals("command"))
            command = Command.valueOf(argValue);
        else if (argName.equals("termFile"))
            termFilePath = argValue;
        else if (argName.equals("outFile"))
            outFilePath = argValue;
        else if (argName.equals("depth"))
            depth = Integer.parseInt(argValue);
        else if (argName.equals("databaseProperties"))
            databasePropertiesPath = argValue;
        else if (argName.equals("projectCode"))
            projectCode = argValue;
        else
            innerArgs.put(argName, argValue);
    }
    if (termFilePath == null && databasePropertiesPath == null)
        throw new TalismaneException("Required argument: termFile or databasePropertiesPath");

    if (termFilePath != null) {
        String currentDirPath = System.getProperty("user.dir");
        File termFileDir = new File(currentDirPath);
        if (termFilePath.lastIndexOf("/") >= 0) {
            String termFileDirPath = termFilePath.substring(0, termFilePath.lastIndexOf("/"));
            termFileDir = new File(termFileDirPath);
            termFileDir.mkdirs();
        }
    }

    long startTime = new Date().getTime();
    try {
        TerminologyServiceLocator terminologyServiceLocator = TerminologyServiceLocator.getInstance();
        TerminologyService terminologyService = terminologyServiceLocator.getTerminologyService();
        TerminologyBase terminologyBase = null;

        if (projectCode == null)
            throw new TalismaneException("Required argument: projectCode");

        File file = new File(databasePropertiesPath);
        FileInputStream fis = new FileInputStream(file);
        Properties dataSourceProperties = new Properties();
        dataSourceProperties.load(fis);
        terminologyBase = terminologyService.getPostGresTerminologyBase(projectCode, dataSourceProperties);

        if (command.equals(Command.analyse) || command.equals(Command.extract)) {
            if (depth < 0)
                throw new TalismaneException("Required argument: depth");

            if (command.equals(Command.analyse)) {
                innerArgs.put("command", "analyse");
            } else {
                innerArgs.put("command", "process");
            }

            TalismaneFrench talismaneFrench = new TalismaneFrench();
            TalismaneConfig config = new TalismaneConfig(innerArgs, talismaneFrench);

            PosTagSet tagSet = TalismaneSession.getPosTagSet();
            Charset outputCharset = config.getOutputCharset();

            TermExtractor termExtractor = terminologyService.getTermExtractor(terminologyBase);
            termExtractor.setMaxDepth(depth);
            termExtractor.setOutFilePath(termFilePath);
            termExtractor.getIncludeChildren().add(tagSet.getPosTag("P"));
            termExtractor.getIncludeChildren().add(tagSet.getPosTag("P+D"));
            termExtractor.getIncludeChildren().add(tagSet.getPosTag("CC"));

            termExtractor.getIncludeWithParent().add(tagSet.getPosTag("DET"));

            if (outFilePath != null) {
                if (outFilePath.lastIndexOf("/") >= 0) {
                    String outFileDirPath = outFilePath.substring(0, outFilePath.lastIndexOf("/"));
                    File outFileDir = new File(outFileDirPath);
                    outFileDir.mkdirs();
                }
                File outFile = new File(outFilePath);
                outFile.delete();
                outFile.createNewFile();

                Writer writer = new BufferedWriter(
                        new OutputStreamWriter(new FileOutputStream(outFilePath), outputCharset));
                TermAnalysisWriter termAnalysisWriter = new TermAnalysisWriter(writer);
                termExtractor.addTermObserver(termAnalysisWriter);
            }

            Talismane talismane = config.getTalismane();
            talismane.setParseConfigurationProcessor(termExtractor);
            talismane.process();
        } else if (command.equals(Command.list)) {

            List<Term> terms = terminologyBase.getTermsByFrequency(2);
            for (Term term : terms) {
                LOG.debug("Term: " + term.getText());
                LOG.debug("Frequency: " + term.getFrequency());
                LOG.debug("Heads: " + term.getHeads());
                LOG.debug("Expansions: " + term.getExpansions());
                LOG.debug("Contexts: " + term.getContexts());
            }
        }
    } finally {
        long endTime = new Date().getTime();
        long totalTime = endTime - startTime;
        LOG.info("Total time: " + totalTime);
    }
}

From source file:in.sc.main.ABC.java

public static void main(String[] args) {
    List list = new ArrayList();
    list.add("1");
    list.add("2");
    list.add("3");
    Collections.reverse(list);//from w  ww .j a  v a 2  s .c o m
    list.iterator();
    for (Object obj : reverse(list)) {
        System.out.print(obj + ", ");
    }

    D x = (D) new D();
    if (x instanceof I) {
        System.out.println("I");
    }
    if (x instanceof J) {
        System.out.println("J");
    }
    if (x instanceof C) {
        System.out.println("C");
    }
    if (x instanceof D) {
        System.out.println("D");
    }
    xyz x1 = new xyz("Test");
    int x2 = 111;

    Rank abc = Rank.FIRST;
    System.out.println("" + abc.SECOND);
    final int j = 2;
    switch (x2) {
    case 1:
        System.out.println("1");
        break;
    case 10:
        System.out.println("10");
        break;
    case j:
        System.out.println("2");
        break;
    case 5:
        System.out.println("5");
        break;
    default:
        System.out.println("Default");
        break;
    }
    String str1 = "lower", str2 = "LOWER", str3 = "UPPER";
    str1.toUpperCase();
    str1.replace("LOWER", "UPPER");
    System.out
            .println((str1.equals(str2)) + " " + (str1.equals(str3)) + "  " + str1 + "  " + str2 + "  " + str3);
    for (int i = 0; i < 3; i++) {
        System.out.println("" + i);
        switch (i) {
        case 0:
            break;
        case 1:
            System.out.println("one");
        case 2:
            System.out.println("two");
        case 3:
            System.out.println("three");
        }
    }
    System.out.println("done");
    ABC a = new ABC("a", "b");
    ABC b = new ABC(a);
}

From source file:io.mapzone.controller.um.xauth.CrackStationEncryptor.java

/**
 * Tests the basic functionality of the PasswordHash class
 *///from   w  w  w  .j ava  2 s.  c o  m
public static void main(String[] args) throws Exception {
    // Print out 10 hashes
    Timer timer = new Timer();
    for (int i = 0; i < 10; i++) {
        System.out.println("Hash: " + PasswordHash.createHash("p\r\nassw0Rd!"));
    }
    System.out.println("10 hashes created. (" + timer.elapsedTime() + "ms)");

    // Test password validation
    timer.start();
    boolean failure = false;
    System.out.println("Running tests...");
    for (int i = 0; i < 10; i++) {
        String password = "" + i;
        String hash = PasswordHash.createHash(password);
        String secondHash = PasswordHash.createHash(password);
        if (hash.equals(secondHash)) {
            System.out.println("FAILURE: TWO HASHES ARE EQUAL!");
            failure = true;
        }
        String wrongPassword = "" + (i + 1);
        if (PasswordHash.validatePassword(wrongPassword, hash)) {
            System.out.println("FAILURE: WRONG PASSWORD ACCEPTED!");
            failure = true;
        }
        if (!PasswordHash.validatePassword(password, hash)) {
            System.out.println("FAILURE: GOOD PASSWORD NOT ACCEPTED!");
            failure = true;
        }
    }
    if (failure) {
        System.out.println("TESTS FAILED!");
    } else {
        System.out.println("TESTS PASSED!");
    }
    System.out.println("10(x2) hashes checked. (" + timer.elapsedTime() + "ms)");
}