Example usage for java.lang String substring

List of usage examples for java.lang String substring

Introduction

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

Prototype

public String substring(int beginIndex, int endIndex) 

Source Link

Document

Returns a string that is a substring of this string.

Usage

From source file:com.heliosdecompiler.appifier.Appifier.java

public static void main(String[] args) throws Throwable {
    if (args.length == 0) {
        System.out.println("An input JAR must be specified");
        return;//from  w  w  w .  j a v a 2s. c  o  m
    }

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

    if (!in.exists()) {
        System.out.println("Input not found");
        return;
    }

    String outName = args[0];
    outName = outName.substring(0, outName.length() - ".jar".length()) + "-appified.jar";

    File out = new File(outName);

    if (out.exists()) {
        if (!out.delete()) {
            System.out.println("Could not delete out file");
            return;
        }
    }

    try (ZipOutputStream outstream = new ZipOutputStream(new FileOutputStream(out));
            ZipFile zipFile = new ZipFile(in)) {

        {
            ZipEntry systemHook = new ZipEntry("com/heliosdecompiler/appifier/SystemHook.class");
            outstream.putNextEntry(systemHook);
            outstream.write(SystemHookDump.dump());
            outstream.closeEntry();
        }

        Enumeration<? extends ZipEntry> enumeration = zipFile.entries();

        while (enumeration.hasMoreElements()) {
            ZipEntry next = enumeration.nextElement();

            if (!next.isDirectory()) {
                ZipEntry result = new ZipEntry(next.getName());
                outstream.putNextEntry(result);
                if (next.getName().endsWith(".class")) {
                    byte[] classBytes = IOUtils.toByteArray(zipFile.getInputStream(next));
                    outstream.write(transform(classBytes));
                } else {
                    IOUtils.copy(zipFile.getInputStream(next), outstream);
                }
                outstream.closeEntry();
            }
        }
    }
}

From source file:ScheduleCampaign.java

public static void main(String[] args) {
    System.out.println("Executing Schedule Campaign");
    try {/*from  w ww.jav a2  s .  c o  m*/
        URL marketoSoapEndPoint = new URL("CHANGE ME" + "?WSDL");
        String marketoUserId = "CHANGE ME";
        String marketoSecretKey = "CHANGE ME";

        QName serviceName = new QName("http://www.marketo.com/mktows/", "MktMktowsApiService");
        MktMktowsApiService service = new MktMktowsApiService(marketoSoapEndPoint, serviceName);
        MktowsPort port = service.getMktowsApiSoapPort();

        // Create Signature
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
        String text = df.format(new Date());
        String requestTimestamp = text.substring(0, 22) + ":" + text.substring(22);
        String encryptString = requestTimestamp + marketoUserId;

        SecretKeySpec secretKey = new SecretKeySpec(marketoSecretKey.getBytes(), "HmacSHA1");
        Mac mac = Mac.getInstance("HmacSHA1");
        mac.init(secretKey);
        byte[] rawHmac = mac.doFinal(encryptString.getBytes());
        char[] hexChars = Hex.encodeHex(rawHmac);
        String signature = new String(hexChars);

        // Set Authentication Header
        AuthenticationHeader header = new AuthenticationHeader();
        header.setMktowsUserId(marketoUserId);
        header.setRequestTimestamp(requestTimestamp);
        header.setRequestSignature(signature);

        // Create Request
        ParamsScheduleCampaign request = new ParamsScheduleCampaign();

        request.setProgramName("Trav-Demo-Program");
        request.setCampaignName("Batch Campaign Example");

        // Create setCampaignRunAt timestamp
        GregorianCalendar gc = new GregorianCalendar();
        gc.setTimeInMillis(new Date().getTime());

        DatatypeFactory factory = DatatypeFactory.newInstance();
        ObjectFactory objectFactory = new ObjectFactory();
        JAXBElement<XMLGregorianCalendar> setCampaignRunAtValue = objectFactory
                .createParamsScheduleCampaignCampaignRunAt(factory.newXMLGregorianCalendar(gc));
        request.setCampaignRunAt(setCampaignRunAtValue);

        request.setCloneToProgramName("TestProgramCloneFromSOAP");

        ArrayOfAttrib aoa = new ArrayOfAttrib();

        Attrib attrib = new Attrib();
        attrib.setName("{{my.message}}");
        attrib.setValue("Updated message");

        aoa.getAttribs().add(attrib);

        JAXBElement<ArrayOfAttrib> arrayOfAttrib = objectFactory
                .createParamsScheduleCampaignProgramTokenList(aoa);
        request.setProgramTokenList(arrayOfAttrib);

        SuccessScheduleCampaign result = port.scheduleCampaign(request, header);

        JAXBContext context = JAXBContext.newInstance(SuccessScheduleCampaign.class);
        Marshaller m = context.createMarshaller();
        m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        m.marshal(result, System.out);

    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.tonygalati.sprites.SpriteGenerator.java

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

    //        if (args.length != 3)
    //        {//from w ww .  j  a  v a 2  s .  c  om
    //           System.out.print("Usage: com.tonygalati.sprites.SpriteGenerator {path to images} {margin between images in px} {output file}\n");
    //           System.out.print("Note: The max height should only be around 32,767px due to Microsoft GDI using a 16bit signed integer to store dimensions\n");
    //           System.out.print("going beyond this dimension is possible with this tool but the generated sprite image will not work correctly with\n");
    //           System.out.print("most browsers.\n\n");
    //           return;
    //        }

    //        Integer margin = Integer.parseInt(args[1]);
    Integer margin = Integer.parseInt("1");
    String spriteFile = "icons-" + RandomStringUtils.randomAlphanumeric(10) + ".png";
    SpriteCSSGenerator cssGenerator = new SpriteCSSGenerator();

    ClassLoader classLoader = SpriteGenerator.class.getClassLoader();
    URL folderPath = classLoader.getResource(NAIC_SMALL_ICON);
    if (folderPath != null) {
        File imageFolder = new File(folderPath.getPath());

        // Read images
        ArrayList<BufferedImage> imageList = new ArrayList<BufferedImage>();
        Integer yCoordinate = null;

        for (File f : imageFolder.listFiles()) {
            if (f.isFile()) {
                String fileName = f.getName();
                String ext = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());

                if (ext.equals("png")) {
                    System.out.println("adding file " + fileName);
                    BufferedImage image = ImageIO.read(f);
                    imageList.add(image);

                    if (yCoordinate == null) {
                        yCoordinate = 0;
                    } else {
                        yCoordinate += (image.getHeight() + margin);
                    }

                    // add to cssGenerator
                    cssGenerator.addSpriteCSS(fileName.substring(0, fileName.indexOf(".")), 0, yCoordinate);
                }
            }
        }

        // Find max width and total height
        int maxWidth = 0;
        int totalHeight = 0;

        for (BufferedImage image : imageList) {
            totalHeight += image.getHeight() + margin;

            if (image.getWidth() > maxWidth)
                maxWidth = image.getWidth();
        }

        System.out.format("Number of images: %s, total height: %spx, width: %spx%n", imageList.size(),
                totalHeight, maxWidth);

        // Create the actual sprite
        BufferedImage sprite = new BufferedImage(maxWidth, totalHeight, BufferedImage.TYPE_INT_ARGB);

        int currentY = 0;
        Graphics g = sprite.getGraphics();
        for (BufferedImage image : imageList) {
            g.drawImage(image, 0, currentY, null);
            currentY += image.getHeight() + margin;
        }

        System.out.format("Writing sprite: %s%n", spriteFile);
        ImageIO.write(sprite, "png", new File(spriteFile));
        File cssFile = cssGenerator.getFile(spriteFile);
        System.out.println(cssFile.getAbsolutePath() + " created");
    } else {
        System.err.println("Could not find folder: " + NAIC_SMALL_ICON);

    }

}

From source file:com.glaf.core.startup.MultiDBNativeCmdStartup.java

public static void main(String[] args) {
    String url = "jdbc:sqlserver://127.0.0.1:1433;databaseName=pMagic2013";
    System.out.println(url.substring(url.lastIndexOf("=") + 1, url.length()));
    url = "jdbc:jtds:sqlserver://127.0.0.1:1433/pMagic2013";
    System.out.println(url.substring(url.lastIndexOf("/") + 1, url.length()));
}

From source file:MainClass.java

public static void main(String args[]) {
    String secondString = "1, 2, 3, 4, 5, 6, 7, 8";

    String output = "String split at commas: [";

    String[] results = secondString.split(",\\s*"); // split on commas

    for (String string : results)
        output += "\"" + string + "\", ";

    output = output.substring(0, output.length() - 2) + "]";
    System.out.println(output);/*ww w  .j a  v  a2s. c  o m*/

}

From source file:com.msopentech.odatajclient.engine.performance.PerfTestReporter.java

public static void main(final String[] args) throws Exception {
    // 1. check input directory
    final File reportdir = new File(args[0] + File.separator + "target" + File.separator + "surefire-reports");
    if (!reportdir.isDirectory()) {
        throw new IllegalArgumentException("Expected directory, got " + args[0]);
    }//w w  w . jav  a2 s  . co  m

    // 2. read test data from surefire output
    final File[] xmlReports = reportdir.listFiles(new FilenameFilter() {

        @Override
        public boolean accept(final File dir, final String name) {
            return name.endsWith("-output.txt");
        }
    });

    final Map<String, Map<String, Double>> testData = new TreeMap<String, Map<String, Double>>();

    for (File xmlReport : xmlReports) {
        final BufferedReader reportReader = new BufferedReader(new FileReader(xmlReport));
        try {
            while (reportReader.ready()) {
                String line = reportReader.readLine();
                final String[] parts = line.substring(0, line.indexOf(':')).split("\\.");

                final String testClass = parts[0];
                if (!testData.containsKey(testClass)) {
                    testData.put(testClass, new TreeMap<String, Double>());
                }

                line = reportReader.readLine();

                testData.get(testClass).put(parts[1],
                        Double.valueOf(line.substring(line.indexOf(':') + 2, line.indexOf('['))));
            }
        } finally {
            IOUtils.closeQuietly(reportReader);
        }
    }

    // 3. build XSLX output (from template)
    final HSSFWorkbook workbook = new HSSFWorkbook(new FileInputStream(args[0] + File.separator + "src"
            + File.separator + "test" + File.separator + "resources" + File.separator + XLS));

    for (Map.Entry<String, Map<String, Double>> entry : testData.entrySet()) {
        final Sheet sheet = workbook.getSheet(entry.getKey());

        int rows = 0;

        for (Map.Entry<String, Double> subentry : entry.getValue().entrySet()) {
            final Row row = sheet.createRow(rows++);

            Cell cell = row.createCell(0);
            cell.setCellValue(subentry.getKey());

            cell = row.createCell(1);
            cell.setCellValue(subentry.getValue());
        }
    }

    final FileOutputStream out = new FileOutputStream(
            args[0] + File.separator + "target" + File.separator + XLS);
    try {
        workbook.write(out);
    } finally {
        IOUtils.closeQuietly(out);
    }
}

From source file:org.eclipse.swt.snippets.Snippet111.java

public static void main(String[] args) {
    final Display display = new Display();
    final Color black = display.getSystemColor(SWT.COLOR_BLACK);
    Shell shell = new Shell(display);
    shell.setText("Snippet 111");
    shell.setLayout(new FillLayout());
    final Tree tree = new Tree(shell, SWT.BORDER);
    for (int i = 0; i < 16; i++) {
        TreeItem itemI = new TreeItem(tree, SWT.NONE);
        itemI.setText("Item " + i);
        for (int j = 0; j < 16; j++) {
            TreeItem itemJ = new TreeItem(itemI, SWT.NONE);
            itemJ.setText("Item " + j);
        }//from   ww  w  . jav  a 2  s  . co m
    }
    final TreeItem[] lastItem = new TreeItem[1];
    final TreeEditor editor = new TreeEditor(tree);
    tree.addListener(SWT.Selection, event -> {
        final TreeItem item = (TreeItem) event.item;
        if (item != null && item == lastItem[0]) {
            boolean showBorder = true;
            final Composite composite = new Composite(tree, SWT.NONE);
            if (showBorder)
                composite.setBackground(black);
            final Text text = new Text(composite, SWT.NONE);
            final int inset = showBorder ? 1 : 0;
            composite.addListener(SWT.Resize, e1 -> {
                Rectangle rect1 = composite.getClientArea();
                text.setBounds(rect1.x + inset, rect1.y + inset, rect1.width - inset * 2,
                        rect1.height - inset * 2);
            });
            Listener textListener = e2 -> {
                switch (e2.type) {
                case SWT.FocusOut:
                    item.setText(text.getText());
                    composite.dispose();
                    break;
                case SWT.Verify:
                    String newText = text.getText();
                    String leftText = newText.substring(0, e2.start);
                    String rightText = newText.substring(e2.end, newText.length());
                    GC gc = new GC(text);
                    Point size = gc.textExtent(leftText + e2.text + rightText);
                    gc.dispose();
                    size = text.computeSize(size.x, SWT.DEFAULT);
                    editor.horizontalAlignment = SWT.LEFT;
                    Rectangle itemRect = item.getBounds(), rect2 = tree.getClientArea();
                    editor.minimumWidth = Math.max(size.x, itemRect.width) + inset * 2;
                    int left = itemRect.x, right = rect2.x + rect2.width;
                    editor.minimumWidth = Math.min(editor.minimumWidth, right - left);
                    editor.minimumHeight = size.y + inset * 2;
                    editor.layout();
                    break;
                case SWT.Traverse:
                    switch (e2.detail) {
                    case SWT.TRAVERSE_RETURN:
                        item.setText(text.getText());
                        //FALL THROUGH
                    case SWT.TRAVERSE_ESCAPE:
                        composite.dispose();
                        e2.doit = false;
                    }
                    break;
                }
            };
            text.addListener(SWT.FocusOut, textListener);
            text.addListener(SWT.Traverse, textListener);
            text.addListener(SWT.Verify, textListener);
            editor.setEditor(composite, item);
            text.setText(item.getText());
            text.selectAll();
            text.setFocus();
        }
        lastItem[0] = item;
    });
    shell.pack();
    shell.open();
    while (!shell.isDisposed()) {
        if (!display.readAndDispatch())
            display.sleep();
    }
    display.dispose();
}

From source file:jk.kamoru.test.IMAPMail.java

public static void main(String[] args) {
    /*        if (args.length < 3)
            {// w  w w .ja  va 2  s.co  m
    System.err.println(
        "Usage: IMAPMail <imap server hostname> <username> <password> [TLS]");
    System.exit(1);
            }
    */
    String server = "imap.handysoft.co.kr";
    String username = "namjk24@handysoft.co.kr";
    String password = "22222";

    String proto = (args.length > 3) ? args[3] : null;

    IMAPClient imap;

    if (proto != null) {
        System.out.println("Using secure protocol: " + proto);
        imap = new IMAPSClient(proto, true); // implicit
        // enable the next line to only check if the server certificate has expired (does not check chain):
        //            ((IMAPSClient) imap).setTrustManager(TrustManagerUtils.getValidateServerCertificateTrustManager());
        // OR enable the next line if the server uses a self-signed certificate (no checks)
        //            ((IMAPSClient) imap).setTrustManager(TrustManagerUtils.getAcceptAllTrustManager());
    } else {
        imap = new IMAPClient();
    }
    System.out.println("Connecting to server " + server + " on " + imap.getDefaultPort());

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

    File imap_log_file = new File("IMAMP-UNSEEN");
    try {
        System.out.println(imap_log_file.getAbsolutePath());
        PrintStream ps = new PrintStream(imap_log_file);
        // suppress login details
        imap.addProtocolCommandListener(new PrintCommandListener(ps, true));
    } catch (FileNotFoundException e1) {
        imap.addProtocolCommandListener(new PrintCommandListener(System.out, true));
    }

    try {
        imap.connect(server);
    } catch (IOException e) {
        throw new RuntimeException("Could not connect to server.", e);
    }

    try {
        if (!imap.login(username, password)) {
            System.err.println("Could not login to server. Check password.");
            imap.disconnect();
            System.exit(3);
        }

        imap.setSoTimeout(6000);

        //            imap.capability();

        //            imap.select("inbox");

        //            imap.examine("inbox");

        imap.status("inbox", new String[] { "UNSEEN" });

        //            imap.logout();
        imap.disconnect();

        List<String> imap_log = FileUtils.readLines(imap_log_file);
        for (int i = 0; i < imap_log.size(); i++) {
            System.out.println(i + ":" + imap_log.get(i));
        }
        String unseenText = imap_log.get(4);
        unseenText = unseenText.substring(unseenText.indexOf('(') + 1, unseenText.indexOf(')'));
        int unseenCount = Integer.parseInt(unseenText.split(" ")[1]);

        System.out.println(unseenCount);
        //imap_log.indexOf("UNSEEN ")
    } catch (IOException e) {
        System.out.println(imap.getReplyString());
        e.printStackTrace();
        System.exit(10);
        return;
    }
}

From source file:org.glowroot.benchmark.ResultFormatter.java

public static void main(String[] args) throws IOException {
    File resultFile = new File(args[0]);

    Scores scores = new Scores();
    double baselineStartupTime = -1;
    double glowrootStartupTime = -1;

    ObjectMapper mapper = new ObjectMapper();
    String content = Files.toString(resultFile, Charsets.UTF_8);
    content = content.replaceAll("\n", " ");
    ArrayNode results = (ArrayNode) mapper.readTree(content);
    for (JsonNode result : results) {
        String benchmark = result.get("benchmark").asText();
        benchmark = benchmark.substring(0, benchmark.lastIndexOf('.'));
        ObjectNode primaryMetric = (ObjectNode) result.get("primaryMetric");
        double score = primaryMetric.get("score").asDouble();
        if (benchmark.equals(StartupBenchmark.class.getName())) {
            baselineStartupTime = score;
            continue;
        } else if (benchmark.equals(StartupWithGlowrootBenchmark.class.getName())) {
            glowrootStartupTime = score;
            continue;
        }/*from  w  ww.ja v a  2  s.  co  m*/
        ObjectNode scorePercentiles = (ObjectNode) primaryMetric.get("scorePercentiles");
        double score50 = scorePercentiles.get("50.0").asDouble();
        double score95 = scorePercentiles.get("95.0").asDouble();
        double score99 = scorePercentiles.get("99.0").asDouble();
        double score999 = scorePercentiles.get("99.9").asDouble();
        double score9999 = scorePercentiles.get("99.99").asDouble();
        double allocatedBytes = getAllocatedBytes(result);
        if (benchmark.equals(ServletBenchmark.class.getName())) {
            scores.baselineResponseTimeAvg = score;
            scores.baselineResponseTime50 = score50;
            scores.baselineResponseTime95 = score95;
            scores.baselineResponseTime99 = score99;
            scores.baselineResponseTime999 = score999;
            scores.baselineResponseTime9999 = score9999;
            scores.baselineAllocatedBytes = allocatedBytes;
        } else if (benchmark.equals(ServletWithGlowrootBenchmark.class.getName())) {
            scores.glowrootResponseTimeAvg = score;
            scores.glowrootResponseTime50 = score50;
            scores.glowrootResponseTime95 = score95;
            scores.glowrootResponseTime99 = score99;
            scores.glowrootResponseTime999 = score999;
            scores.glowrootResponseTime9999 = score9999;
            scores.glowrootAllocatedBytes = allocatedBytes;
        } else {
            throw new AssertionError(benchmark);
        }
    }
    System.out.println();
    printScores(scores);
    if (baselineStartupTime != -1) {
        System.out.println("STARTUP");
        System.out.format("%25s%14s%14s%n", "", "baseline", "glowroot");
        printLine("Startup time (avg)", "ms", baselineStartupTime, glowrootStartupTime);
    }
    System.out.println();
}

From source file:SyncCustomObjects.java

public static void main(String[] args) {
    System.out.println("Executing Sync Custom Objects");
    try {//www. ja  v a 2s  .  co m
        URL marketoSoapEndPoint = new URL("CHANGE ME" + "?WSDL");
        String marketoUserId = "CHANGE ME";
        String marketoSecretKey = "CHANGE ME";

        QName serviceName = new QName("http://www.marketo.com/mktows/", "MktMktowsApiService");
        MktMktowsApiService service = new MktMktowsApiService(marketoSoapEndPoint, serviceName);
        MktowsPort port = service.getMktowsApiSoapPort();

        // Create Signature
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
        String text = df.format(new Date());
        String requestTimestamp = text.substring(0, 22) + ":" + text.substring(22);
        String encryptString = requestTimestamp + marketoUserId;

        SecretKeySpec secretKey = new SecretKeySpec(marketoSecretKey.getBytes(), "HmacSHA1");
        Mac mac = Mac.getInstance("HmacSHA1");
        mac.init(secretKey);
        byte[] rawHmac = mac.doFinal(encryptString.getBytes());
        char[] hexChars = Hex.encodeHex(rawHmac);
        String signature = new String(hexChars);

        // Set Authentication Header
        AuthenticationHeader header = new AuthenticationHeader();
        header.setMktowsUserId(marketoUserId);
        header.setRequestTimestamp(requestTimestamp);
        header.setRequestSignature(signature);

        // Create Request
        ParamsSyncCustomObjects request = new ParamsSyncCustomObjects();
        request.setObjTypeName("RoadShow");
        JAXBElement<SyncOperationEnum> operation = new ObjectFactory()
                .createParamsSyncCustomObjectsOperation(SyncOperationEnum.UPSERT);
        request.setOperation(operation);

        ArrayOfCustomObj customObjects = new ArrayOfCustomObj();

        CustomObj customObj = new CustomObj();

        ArrayOfAttribute arrayOfKeyAttributes = new ArrayOfAttribute();
        Attribute attr = new Attribute();
        attr.setAttrName("MKTOID");
        attr.setAttrValue("1090177");

        Attribute attr2 = new Attribute();
        attr2.setAttrName("rid");
        attr2.setAttrValue("rid1");

        arrayOfKeyAttributes.getAttributes().add(attr);
        arrayOfKeyAttributes.getAttributes().add(attr2);

        JAXBElement<ArrayOfAttribute> keyAttributes = new ObjectFactory()
                .createCustomObjCustomObjKeyList(arrayOfKeyAttributes);
        customObj.setCustomObjKeyList(keyAttributes);
        ArrayOfAttribute arrayOfValueAttributes = new ArrayOfAttribute();

        Attribute city = new Attribute();
        city.setAttrName("city");
        city.setAttrValue("SanMateo");

        Attribute zip = new Attribute();
        zip.setAttrName("zip");
        zip.setAttrValue("94404");

        Attribute state = new Attribute();
        state.setAttrName("state");
        state.setAttrValue("California");

        arrayOfValueAttributes.getAttributes().add(city);
        arrayOfValueAttributes.getAttributes().add(state);
        arrayOfValueAttributes.getAttributes().add(zip);

        JAXBElement<ArrayOfAttribute> valueAttributes = new ObjectFactory()
                .createCustomObjCustomObjAttributeList(arrayOfValueAttributes);
        customObj.setCustomObjAttributeList(valueAttributes);

        customObjects.getCustomObjs().add(customObj);

        SuccessSyncCustomObjects result = port.syncCustomObjects(request, header);

        JAXBContext context = JAXBContext.newInstance(SuccessSyncCustomObjects.class);
        Marshaller m = context.createMarshaller();
        m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        m.marshal(result, System.out);

    } catch (Exception e) {
        e.printStackTrace();
    }
}