Example usage for java.lang StringBuilder append

List of usage examples for java.lang StringBuilder append

Introduction

In this page you can find the example usage for java.lang StringBuilder append.

Prototype

@Override
    public StringBuilder append(double d) 

Source Link

Usage

From source file:at.newmedialab.ldpath.backend.linkeddata.LDQuery.java

public static void main(String[] args) {
    Options options = buildOptions();//from   ww  w  .  j av a 2  s.  com

    CommandLineParser parser = new PosixParser();
    try {
        CommandLine cmd = parser.parse(options, args);

        Level logLevel = Level.WARN;

        if (cmd.hasOption("loglevel")) {
            String logLevelName = cmd.getOptionValue("loglevel");
            if ("DEBUG".equals(logLevelName.toUpperCase())) {
                logLevel = Level.DEBUG;
            } else if ("INFO".equals(logLevelName.toUpperCase())) {
                logLevel = Level.INFO;
            } else if ("WARN".equals(logLevelName.toUpperCase())) {
                logLevel = Level.WARN;
            } else if ("ERROR".equals(logLevelName.toUpperCase())) {
                logLevel = Level.ERROR;
            } else {
                log.error("unsupported log level: {}", logLevelName);
            }
        }

        if (logLevel != null) {
            for (String logname : new String[] { "at", "org", "net", "com" }) {

                ch.qos.logback.classic.Logger logger = (ch.qos.logback.classic.Logger) LoggerFactory
                        .getLogger(logname);
                logger.setLevel(logLevel);
            }
        }

        String format = null;
        if (cmd.hasOption("format")) {
            format = cmd.getOptionValue("format");
        }

        GenericSesameBackend backend;
        if (cmd.hasOption("store")) {
            backend = new LDPersistentBackend(new File(cmd.getOptionValue("store")));
        } else {
            backend = new LDMemoryBackend();
        }

        Resource context = null;
        if (cmd.hasOption("context")) {
            context = backend.getRepository().getValueFactory().createURI(cmd.getOptionValue("context"));
        }

        if (backend != null && context != null) {
            LDPath<Value> ldpath = new LDPath<Value>(backend);

            if (cmd.hasOption("path")) {
                String path = cmd.getOptionValue("path");

                for (Value v : ldpath.pathQuery(context, path, null)) {
                    System.out.println(v.stringValue());
                }
            } else if (cmd.hasOption("program")) {
                File file = new File(cmd.getOptionValue("program"));

                Map<String, Collection<?>> result = ldpath.programQuery(context, new FileReader(file));

                for (String field : result.keySet()) {
                    StringBuilder line = new StringBuilder();
                    line.append(field);
                    line.append(" = ");
                    line.append("{");
                    for (Iterator it = result.get(field).iterator(); it.hasNext();) {
                        line.append(it.next().toString());
                        if (it.hasNext()) {
                            line.append(", ");
                        }
                    }
                    line.append("}");
                    System.out.println(line);

                }
            }
        }

        if (backend instanceof LDPersistentBackend) {
            ((LDPersistentBackend) backend).shutdown();
        }

    } catch (ParseException e) {
        System.err.println("invalid arguments");
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("LDQuery", options, true);
    } catch (LDPathParseException e) {
        System.err.println("path or program could not be parsed");
        e.printStackTrace();
    } catch (FileNotFoundException e) {
        System.err.println("file or program could not be found");
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("LDQuery", options, true);
    } catch (IOException e) {
        System.err.println("could not access cache data directory");
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("LDQuery", options, true);
    }

}

From source file:com.lsq.httpclient.netpay.BasicInfo.java

public static void main(String[] args) throws Exception {
    //   final PrivateKey hzfPriKey = CryptoUtil.getRSAPrivateKeyByFileSuffix("F://test/pkcs8_rsa_private_key_2048.pem", "pem", null, "RSA");
    //   final PublicKey yhPubKey = CryptoUtil.getRSAPublicKeyByFileSuffix("F://??/rsa_public_key_2048.pem", "pem", "RSA");
    ////  w w  w .ja v a 2  s  .  c o  m
    //   final String url = "http://localhost:8080/interfaceWeb/basicInfo";
    //   final String url = "https://testapp.sicpay.com:11008/interfaceWeb/basicInfo";   

    //?
    //   final String url = "http://120.31.132.120:8082/interfaceWeb/basicInfo";
    //       final PublicKey yhPubKey = CryptoUtil.getRSAPublicKeyByFileSuffix("C:\\document\\key\\000158120120\\GHT_ROOT.pem", "pem", "RSA");
    //        final PrivateKey hzfPriKey = CryptoUtil.getRSAPrivateKeyByFileSuffix("C:\\document\\key\\000000153990021\\000000153990021.pem", "pem", null, "RSA");
    //   final PrivateKey hzfPriKey = CryptoUtil.getRSAPrivateKeyByFileSuffix("C:/document/key/000000158120121/000000158120121.pem", "pem", null, "RSA");
    //   final PrivateKey hzfPriKey = CryptoUtil.getRSAPrivateKeyByFileSuffix("D:/key/000000152110003.pem", "pem", null, "RSA");
    //   final PrivateKey hzfPriKey = CryptoUtil.getRSAPrivateKeyByFileSuffix("D:/key/test_pkcs8_rsa_private_key_2048.pem", "pem", null, "RSA");
    //   PublicKey yhPubKey = TestUtil.getPublicKey();
    //   PrivateKey hzfPriKey = TestUtil.getPrivateKey();

    //    final String url = "http://epay.gaohuitong.com:8083/interfaceWeb/basicInfo";

    //        final String url = "http://gpay.gaohuitong.com:8086/interfaceWeb2/basicInfo";
    //       final PublicKey yhPubKey = CryptoUtil.getRSAPublicKeyByFileSuffix("C:/document/key/549440155510001/GHT_ROOT.pem", "pem", "RSA");
    //    final PrivateKey hzfPriKey = CryptoUtil.getRSAPrivateKeyByFileSuffix("C:/document/key/549440155510001/549440155510001.pem", "pem", null, "RSA");

    //    final String url = "https://portal.sicpay.com:8087/interfaceWeb/basicInfo";

    final String url = TestUtil.interface_url + "basicInfo";

    final PublicKey yhPubKey = TestUtil.getPublicKey();
    final PrivateKey hzfPriKey = TestUtil.getPrivateKey();

    int i = 0;
    //   int j = 0;
    while (i < 1) {
        i++;
        try {
            HttpClient4Util httpClient4Util = new HttpClient4Util();
            StringBuilder sBuilder = new StringBuilder();
            sBuilder.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
            sBuilder.append("<merchant>");
            sBuilder.append("<head>");
            sBuilder.append("<version>2.0.0</version>");
            //         sBuilder.append("<agencyId>549440155510001</agencyId>");
            sBuilder.append("<agencyId>" + TestUtil.merchantId + "</agencyId>");
            sBuilder.append("<msgType>01</msgType>");
            sBuilder.append("<tranCode>100001</tranCode>");
            sBuilder.append("<reqMsgId>" + DateFormatUtils.format(new Date(), "yyyyMMddHHmmss") + i + i
                    + "</reqMsgId>");
            sBuilder.append("<reqDate>" + DateFormatUtils.format(new Date(), "yyyyMMddHHmmss") + "</reqDate>");
            sBuilder.append("</head>");
            sBuilder.append("<body>");

            sBuilder.append("<handleType>0</handleType>");
            sBuilder.append("<merchantName>LIBTEST1</merchantName>");
            sBuilder.append("<shortName>UNCLE HENRY(A)</shortName>");
            sBuilder.append("<city>344344</city>");
            sBuilder.append(
                    "<merchantAddress>UNIT C 15/FHUA CHIAO COMM CTR 678 NATHAN RD MONGKOK KL</merchantAddress>");
            sBuilder.append("<servicePhone>13250538964</servicePhone>");
            sBuilder.append("<orgCode></orgCode>");
            sBuilder.append("<merchantType>01</merchantType>");
            sBuilder.append("<category>5399</category>");
            sBuilder.append("<corpmanName>?</corpmanName>");
            sBuilder.append("<corpmanId>440103198112214218</corpmanId>");
            sBuilder.append("<corpmanPhone>13926015921</corpmanPhone>");
            sBuilder.append("<corpmanMobile>13926015921</corpmanMobile>");
            sBuilder.append("<corpmanEmail>>zhanglibo@sicpay.com</corpmanEmail>");
            sBuilder.append("<bankCode>105</bankCode>");
            sBuilder.append("<bankName></bankName>");
            sBuilder.append("<bankaccountNo>6250502002603958</bankaccountNo>");
            sBuilder.append("<bankaccountName>?</bankaccountName>");
            sBuilder.append("<autoCus>0</autoCus>");
            sBuilder.append("<remark></remark>");
            sBuilder.append("<licenseNo>91440184355798892G</licenseNo>");
            //         sBuilder.append("<taxRegisterNo></taxRegisterNo>");
            //         sBuilder.append("<subMerchantNo></subMerchantNo>");
            //         sBuilder.append("<inviteMerNo></inviteMerNo>");
            //         sBuilder.append("<county></county>");
            //         sBuilder.append("<appid>wx04df48e919ef7b28</appid>");
            //         sBuilder.append("<pid>2015062600009243</pid>");
            //         sBuilder.append("<childEnter>1</childEnter>");
            //         sBuilder.append("<ghtEnter>0</ghtEnter>");
            //         sBuilder.append("<addrType>BUSINESS_ADDRESS</addrType>");
            //         sBuilder.append("<contactType>LEGAL_PERSON</contactType>");
            //         sBuilder.append("<mcc>200101110640354</mcc>");
            //         sBuilder.append("<licenseType>NATIONAL_LEGAL_MERGE</licenseType>");
            //         sBuilder.append("<authPayDir>http://epay.gaohuitong.com/channel/|http://test.pengjv.com/channel/</authPayDir>");
            //         sBuilder.append("<scribeAppid>wx04df48e919ef7b28</scribeAppid>");
            //         sBuilder.append("<contactMan></contactMan>");
            //         sBuilder.append("<telNo>18675857506</telNo>");
            //         sBuilder.append("<mobilePhone>18675857506</mobilePhone>");
            //         sBuilder.append("<email>CSC@sicpay.com</email>");
            //         sBuilder.append("<licenseBeginDate>20150826</licenseBeginDate>");
            //         sBuilder.append("<licenseEndDate>20991231</licenseEndDate>");
            //         sBuilder.append("<licenseRange>?????????????</licenseRange>");

            sBuilder.append("</body>");
            sBuilder.append("</merchant>");

            String plainXML = sBuilder.toString();
            byte[] plainBytes = plainXML.getBytes("UTF-8");
            String keyStr = "4D22R4846VFJ8HH4";
            byte[] keyBytes = keyStr.getBytes("UTF-8");
            byte[] base64EncryptDataBytes = Base64.encodeBase64(
                    CryptoUtil.AESEncrypt(plainBytes, keyBytes, "AES", "AES/ECB/PKCS5Padding", null));
            String encryptData = new String(base64EncryptDataBytes, "UTF-8");
            byte[] base64SingDataBytes = Base64
                    .encodeBase64(CryptoUtil.digitalSign(plainBytes, hzfPriKey, "SHA1WithRSA"));
            String signData = new String(base64SingDataBytes, "UTF-8");
            byte[] base64EncyrptKeyBytes = Base64
                    .encodeBase64(CryptoUtil.RSAEncrypt(keyBytes, yhPubKey, 2048, 11, "RSA/ECB/PKCS1Padding"));
            String encrtptKey = new String(base64EncyrptKeyBytes, "UTF-8");
            List<NameValuePair> nvps = new LinkedList<NameValuePair>();
            nvps.add(new BasicNameValuePair("encryptData", encryptData));
            nvps.add(new BasicNameValuePair("encryptKey", encrtptKey));
            //         nvps.add(new BasicNameValuePair("agencyId", "549440155510001"));
            nvps.add(new BasicNameValuePair("agencyId", TestUtil.merchantId));
            nvps.add(new BasicNameValuePair("signData", signData));
            nvps.add(new BasicNameValuePair("tranCode", "100001"));
            //         nvps.add(new BasicNameValuePair("callBack","http://localhost:801/callback/ghtBindCard.do"));
            //          byte[] retBytes = httpClient4Util.doPost("http://localhost:8080/quickInter/channel/commonSyncInter.do", null, nvps, null);
            byte[] retBytes = httpClient4Util.doPost(url, null, nvps, null);
            //         byte[] retBytes =httpClient4Util.doPost("http://epay.gaohuitong.com:8082/quickInter/channel/commonSyncInter.do", null, nvps, null);
            //           byte[] retBytes = httpClient4Util.doPost("http://192.168.80.113:8080/quickInter/channel/commonSyncInter.do", null, nvps, null);

            String response = new String(retBytes, "UTF-8");
            System.out.println(" ||" + new String(retBytes, "UTF-8") + "||");
            TestEncype t = new TestEncype();
            System.out.println(": ||" + t.respDecryption(response) + "||");
            System.out.println("i" + i);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

From source file:FileCompressor.java

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

    String file = "D:\\XJad.rar.txt";
    BufferedReader reader = new BufferedReader(new FileReader(file));
    BufferedWriter writer = new BufferedWriter(new FileWriter(file + "_out.txt"));
    StringBuilder content = new StringBuilder();
    String tmp;//from   ww  w .  jav a 2s .  co m

    while ((tmp = reader.readLine()) != null) {
        content.append(tmp);
        content.append(System.getProperty("line.separator"));
    }

    FileCompressor f = new FileCompressor();
    writer.write(f.compress(content.toString()));

    writer.close();
    reader.close();

    reader = new BufferedReader(new FileReader(file + "_out.txt"));
    StringBuilder content2 = new StringBuilder();

    while ((tmp = reader.readLine()) != null) {
        content2.append(tmp);
        content2.append(System.getProperty("line.separator"));
    }

    String decompressed = f.decompress(content2.toString());
    String c = content.toString();
    System.out.println(decompressed.equals(c));
}

From source file:esg.gateway.client.ESGAccessLogClient.java

public static void main(String[] args) {
    String serviceHost = null;/*from   www.j a v  a  2 s .c  o  m*/
    long startTime = 0;
    long endTime = Long.MAX_VALUE;

    try {
        serviceHost = args[0];
        startTime = Long.parseLong(args[1]);
        endTime = Long.parseLong(args[2]);
    } catch (Throwable t) {
        log.error(t.getMessage());
    }

    try {
        ESGAccessLogClient client = new ESGAccessLogClient();
        if (client.setEndpoint(serviceHost).ping()) {
            List<String[]> results = null;
            results = client.fetchAccessLogData(startTime, endTime);

            System.out.println("---results:[" + (results.size() - 1) + "]---");
            for (String[] record : results) {
                StringBuilder sb = new StringBuilder();
                for (String column : record) {
                    sb.append("[" + column + "] ");
                }
                System.out.println(sb.toString());
            }
        }
        System.out.println("-----------------");
    } catch (Throwable t) {
        log.error(t);
        t.printStackTrace();
    }
}

From source file:Naive.java

public static void main(String[] args) throws Exception {
    // Basic access authentication setup
    String key = "CHANGEME: YOUR_API_KEY";
    String secret = "CHANGEME: YOUR_API_SECRET";
    String version = "preview1"; // CHANGEME: the API version to use
    String practiceid = "000000"; // CHANGEME: the practice ID to use

    // Find the authentication path
    Map<String, String> auth_prefix = new HashMap<String, String>();
    auth_prefix.put("v1", "oauth");
    auth_prefix.put("preview1", "oauthpreview");
    auth_prefix.put("openpreview1", "oauthopenpreview");

    URL authurl = new URL("https://api.athenahealth.com/" + auth_prefix.get(version) + "/token");

    HttpURLConnection conn = (HttpURLConnection) authurl.openConnection();
    conn.setRequestMethod("POST");

    // Set the Authorization request header
    String auth = Base64.encodeBase64String((key + ':' + secret).getBytes());
    conn.setRequestProperty("Authorization", "Basic " + auth);

    // Since this is a POST, the parameters go in the body
    conn.setDoOutput(true);//from  ww w  .j  a  va 2s  .  c o  m
    String contents = "grant_type=client_credentials";
    DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
    wr.writeBytes(contents);
    wr.flush();
    wr.close();

    // Read the response
    BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    StringBuilder sb = new StringBuilder();
    String line;
    while ((line = rd.readLine()) != null) {
        sb.append(line);
    }
    rd.close();

    // Decode from JSON and save the token for later
    String response = sb.toString();
    JSONObject authorization = new JSONObject(response);
    String token = authorization.get("access_token").toString();

    // GET /departments
    HashMap<String, String> params = new HashMap<String, String>();
    params.put("limit", "1");

    // Set up the URL, method, and Authorization header
    URL url = new URL("https://api.athenahealth.com/" + version + "/" + practiceid + "/departments" + "?"
            + urlencode(params));
    conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod("GET");
    conn.setRequestProperty("Authorization", "Bearer " + token);

    rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    sb = new StringBuilder();
    while ((line = rd.readLine()) != null) {
        sb.append(line);
    }
    rd.close();

    response = sb.toString();
    JSONObject departments = new JSONObject(response);
    System.out.println(departments.toString());

    // POST /appointments/{appointmentid}/notes
    params = new HashMap<String, String>();
    params.put("notetext", "Hello from Java!");

    url = new URL("https://api.athenahealth.com/" + version + "/" + practiceid + "/appointments/1/notes");
    conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Authorization", "Bearer " + token);

    // POST parameters go in the body
    conn.setDoOutput(true);
    contents = urlencode(params);
    wr = new DataOutputStream(conn.getOutputStream());
    wr.writeBytes(contents);
    wr.flush();
    wr.close();

    rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    sb = new StringBuilder();
    while ((line = rd.readLine()) != null) {
        sb.append(line);
    }
    rd.close();

    response = sb.toString();
    JSONObject note = new JSONObject(response);
    System.out.println(note.toString());
}

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

public static void main(String[] args) throws Exception {
    final Display display = new Display();
    final Shell shell = new Shell(display);
    shell.setText("Snippet 375");
    shell.setLayout(new GridLayout(1, false));

    final StringBuilder sb = new StringBuilder();
    final Random random = new Random(2546);
    for (int i = 0; i < 200; i++) {
        sb.append("Very very long text about ").append(random.nextInt(2000)).append("\t");
        if (i % 10 == 0) {
            sb.append("\n");
        }//w  w w. j a va  2  s . co  m
    }

    // H SCROLL
    final Label lbl1 = new Label(shell, SWT.NONE);
    lbl1.setLayoutData(new GridData(GridData.BEGINNING, GridData.CENTER, true, false));
    lbl1.setText("Horizontal Scroll");

    final StyledText txt1 = new StyledText(shell, SWT.MULTI | SWT.BORDER | SWT.H_SCROLL);
    txt1.setLayoutData(new GridData(GridData.FILL, GridData.FILL, true, true));
    txt1.setText(sb.toString());
    txt1.setMouseNavigatorEnabled(true);

    // V_SCROLL
    final Label lbl2 = new Label(shell, SWT.NONE);
    lbl2.setLayoutData(new GridData(GridData.BEGINNING, GridData.CENTER, true, false));
    lbl2.setText("Vertical Scroll");

    final StyledText txt2 = new StyledText(shell, SWT.MULTI | SWT.BORDER | SWT.V_SCROLL);
    txt2.setLayoutData(new GridData(GridData.FILL, GridData.FILL, true, true));
    txt2.setText(sb.toString());
    txt2.setMouseNavigatorEnabled(true);

    // H SCROLL & V_SCROLL
    final Label lbl3 = new Label(shell, SWT.NONE);
    lbl3.setLayoutData(new GridData(GridData.BEGINNING, GridData.CENTER, true, false));
    lbl3.setText("Horizontal and Vertical Scroll");

    final StyledText txt3 = new StyledText(shell, SWT.MULTI | SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL);
    txt3.setLayoutData(new GridData(GridData.FILL, GridData.FILL, true, true));

    txt3.setText(sb.toString());
    txt3.setMouseNavigatorEnabled(true);

    final Button enableDisableButton = new Button(shell, SWT.PUSH);
    enableDisableButton.setLayoutData(new GridData(GridData.END, GridData.FILL, true, false));
    enableDisableButton.setText("Disable Mouse Navigation");
    enableDisableButton.addListener(SWT.Selection, e -> {
        if (txt3.getMouseNavigatorEnabled()) {
            enableDisableButton.setText("Enable Mouse Navigation");
        } else {
            enableDisableButton.setText("Disable Mouse Navigation");
        }
        txt3.setMouseNavigatorEnabled(!txt3.getMouseNavigatorEnabled());
    });

    // Disabled Scroll at start
    final Label lbl4 = new Label(shell, SWT.NONE);
    lbl4.setLayoutData(new GridData(GridData.BEGINNING, GridData.CENTER, true, false));
    lbl4.setText("No scroll at start");

    final StyledText txt4 = new StyledText(shell, SWT.MULTI | SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL);
    final GridData gd = new GridData(GridData.FILL, GridData.FILL, true, true);
    gd.minimumHeight = 100;
    txt4.setLayoutData(gd);

    txt4.setText("Disabled scroll");
    txt4.setMouseNavigatorEnabled(true);

    // Disabled Scroll
    final Label lbl5 = new Label(shell, SWT.NONE);
    lbl5.setLayoutData(new GridData(GridData.BEGINNING, GridData.CENTER, true, false));
    lbl5.setText("No scroll");

    final StyledText txt5 = new StyledText(shell, SWT.MULTI | SWT.BORDER);
    final GridData gd5 = new GridData(GridData.FILL, GridData.FILL, true, true);
    gd5.minimumHeight = 100;
    txt5.setLayoutData(gd5);

    txt5.setText("No scroll");
    txt5.setMouseNavigatorEnabled(true);

    shell.setSize(800, 600);
    shell.open();

    while (!shell.isDisposed()) {
        if (!display.readAndDispatch()) {
            display.sleep();
        }
    }

    display.dispose();
}

From source file:de.zazaz.iot.bosch.indego.util.IndegoMqttAdapter.java

public static void main(String[] args) {
    System.setProperty("log4j.configurationFile", "log4j2-indegoMqttAdapter-normal.xml");

    Options options = new Options();

    StringBuilder commandList = new StringBuilder();
    for (DeviceCommand cmd : DeviceCommand.values()) {
        if (commandList.length() > 0) {
            commandList.append(", ");
        }/*from ww  w . j a v  a 2s  .c o m*/
        commandList.append(cmd.toString());
    }

    options.addOption(Option //
            .builder("c") //
            .longOpt("config") //
            .desc("The configuration file to use") //
            .required() //
            .hasArg() //
            .build());
    options.addOption(Option //
            .builder("d") //
            .longOpt("debug") //
            .desc("Logs more details") //
            .build());
    options.addOption(Option //
            .builder("?") //
            .longOpt("help") //
            .desc("Prints this help") //
            .build());

    CommandLineParser parser = new DefaultParser();
    CommandLine cmds = null;
    try {
        cmds = parser.parse(options, args);
    } catch (ParseException ex) {
        System.err.println(ex.getMessage());
        System.err.println();
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(IndegoMqttAdapter.class.getName(), options);
        System.exit(1);
        return;
    }

    if (cmds.hasOption("?")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(CmdLineTool.class.getName(), options);
        return;
    }

    if (cmds.hasOption("d")) {
        System.setProperty("log4j.configurationFile", "log4j2-indegoMqttAdapter-debug.xml");
    }

    String configFileName = cmds.getOptionValue('c');
    File configFile = new File(configFileName);

    if (!configFile.exists()) {
        System.err.println(String.format("The specified config file (%s) does not exist", configFileName));
        System.err.println();
        System.exit(2);
        return;
    }

    Properties properties = new Properties();
    try (InputStream in = new FileInputStream(configFile)) {
        properties.load(in);
    } catch (IOException ex) {
        System.err.println(ex.getMessage());
        System.err.println(String.format("Was not able to load the properties file (%s)", configFileName));
        System.err.println();
    }

    MqttIndegoAdapterConfiguration config = new MqttIndegoAdapterConfiguration();
    config.setIndegoBaseUrl(properties.getProperty("indego.mqtt.device.base-url"));
    config.setIndegoUsername(properties.getProperty("indego.mqtt.device.username"));
    config.setIndegoPassword(properties.getProperty("indego.mqtt.device.password"));
    config.setMqttBroker(properties.getProperty("indego.mqtt.broker.connection"));
    config.setMqttClientId(properties.getProperty("indego.mqtt.broker.client-id"));
    config.setMqttUsername(properties.getProperty("indego.mqtt.broker.username"));
    config.setMqttPassword(properties.getProperty("indego.mqtt.broker.password"));
    config.setMqttTopicRoot(properties.getProperty("indego.mqtt.broker.topic-root"));
    config.setPollingIntervalMs(Integer.parseInt(properties.getProperty("indego.mqtt.polling-interval-ms")));

    MqttIndegoAdapter adapter = new MqttIndegoAdapter(config);
    adapter.startup();
}

From source file:com.genentech.retrival.tabExport.TABExporter.java

public static void main(String[] args) throws ParseException, JDOMException, IOException {
    long start = System.currentTimeMillis();
    int nStruct = 0;

    // create command line Options object
    Options options = new Options();
    Option opt = new Option("sqlFile", true, "sql-xml file");
    opt.setRequired(true);//from  www . j  a va2 s  .co  m
    options.addOption(opt);

    opt = new Option("sqlName", true, "name of SQL element in xml file");
    opt.setRequired(true);
    options.addOption(opt);

    opt = new Option("o", true, "output file");
    opt.setRequired(false);
    options.addOption(opt);

    opt = new Option("newLineReplacement", true,
            "If given newlines in fields will be replaced by this string.");
    options.addOption(opt);

    opt = new Option("noHeader", false, "Do not output header line");
    options.addOption(opt);

    CommandLineParser parser = new BasicParser();
    CommandLine cmd = null;
    try {
        cmd = parser.parse(options, args);
    } catch (Exception e) {
        System.err.println(e.getMessage());
        exitWithHelp(options);
    }
    args = cmd.getArgs();

    String outFile = cmd.getOptionValue("o");
    String sqlFile = cmd.getOptionValue("sqlFile");
    String sqlName = cmd.getOptionValue("sqlName");
    String newLineReplacement = cmd.getOptionValue("newLineReplacement");

    args = cmd.getArgs();

    try {
        PrintStream out = System.out;
        if (outFile != null)
            out = new PrintStream(outFile);

        SQLStatement stmt = SQLStatement.createFromFile(new File(sqlFile), sqlName);
        Object[] sqlArgs = args;
        if (stmt.getParamTypes().length != args.length) {
            System.err.printf(
                    "\nWarining sql statement needs %d parameters but got only %d. Filling up with NULLs.\n",
                    stmt.getParamTypes().length, args.length);
            sqlArgs = new Object[stmt.getParamTypes().length];
            System.arraycopy(args, 0, sqlArgs, 0, args.length);
        }

        Selecter sel = Selecter.factory(stmt);
        if (!sel.select(sqlArgs)) {
            System.err.println("No rows returned!");
            System.exit(0);
        }

        String[] fieldNames = sel.getFieldNames();
        if (fieldNames.length == 0) {
            System.err.println("Query did not return any columns");
            exitWithHelp(options);
        }

        if (!cmd.hasOption("noHeader")) {
            StringBuilder sb = new StringBuilder(200);
            for (String f : fieldNames)
                sb.append(f).append('\t');
            if (sb.length() > 1)
                sb.setLength(sb.length() - 1); // chop last \t
            String header = sb.toString();

            out.println(header);
        }

        StringBuilder sb = new StringBuilder(200);
        while (sel.hasNext()) {
            Record sqlRec = sel.next();
            sb.setLength(0);

            for (int i = 0; i < fieldNames.length; i++) {
                String fld = sqlRec.getStrg(i);
                if (newLineReplacement != null)
                    fld = NEWLinePattern.matcher(fld).replaceAll(newLineReplacement);

                sb.append(fld).append('\t');
            }

            if (sb.length() > 1)
                sb.setLength(sb.length() - 1); // chop last \t
            String row = sb.toString();

            out.println(row);

            nStruct++;
        }

    } catch (Exception e) {
        throw new Error(e);
    } finally {
        System.err.printf("TABExporter: Exported %d records in %dsec\n", nStruct,
                (System.currentTimeMillis() - start) / 1000);
    }
}

From source file:de.zazaz.iot.bosch.indego.util.IndegoIftttAdapter.java

public static void main(String[] args) {
    System.setProperty("log4j.configurationFile", "log4j2-indegoIftttAdapter-normal.xml");

    Options options = new Options();

    StringBuilder commandList = new StringBuilder();
    for (DeviceCommand cmd : DeviceCommand.values()) {
        if (commandList.length() > 0) {
            commandList.append(", ");
        }//from  w  w  w  . java2 s  . co m
        commandList.append(cmd.toString());
    }

    options.addOption(Option //
            .builder("c") //
            .longOpt("config") //
            .desc("The configuration file to use") //
            .required() //
            .hasArg() //
            .build());
    options.addOption(Option //
            .builder("d") //
            .longOpt("debug") //
            .desc("Logs more details") //
            .build());
    options.addOption(Option //
            .builder("?") //
            .longOpt("help") //
            .desc("Prints this help") //
            .build());

    CommandLineParser parser = new DefaultParser();
    CommandLine cmds = null;
    try {
        cmds = parser.parse(options, args);
    } catch (ParseException ex) {
        System.err.println(ex.getMessage());
        System.err.println();
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(IndegoIftttAdapter.class.getName(), options);
        System.exit(1);
        return;
    }

    if (cmds.hasOption("?")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(CmdLineTool.class.getName(), options);
        return;
    }

    if (cmds.hasOption("d")) {
        System.setProperty("log4j.configurationFile", "log4j2-indegoIftttAdapter-debug.xml");
    }

    String configFileName = cmds.getOptionValue('c');
    File configFile = new File(configFileName);

    if (!configFile.exists()) {
        System.err.println(String.format("The specified config file (%s) does not exist", configFileName));
        System.err.println();
        System.exit(2);
        return;
    }

    Properties properties = new Properties();
    try (InputStream in = new FileInputStream(configFile)) {
        properties.load(in);
    } catch (IOException ex) {
        System.err.println(ex.getMessage());
        System.err.println(String.format("Was not able to load the properties file (%s)", configFileName));
        System.err.println();
    }

    IftttIndegoAdapterConfiguration config = new IftttIndegoAdapterConfiguration();
    config.setIftttMakerKey(properties.getProperty("indego.ifttt.maker.key"));
    config.setIftttIgnoreServerCertificate(
            Integer.parseInt(properties.getProperty("indego.ifttt.maker.ignore-server-certificate")) != 0);
    config.setIftttReceiverPort(Integer.parseInt(properties.getProperty("indego.ifttt.maker.receiver-port")));
    config.setIftttReceiverSecret(properties.getProperty("indego.ifttt.maker.receiver-secret"));
    config.setIftttOfflineEventName(properties.getProperty("indego.ifttt.maker.eventname-offline"));
    config.setIftttOnlineEventName(properties.getProperty("indego.ifttt.maker.eventname-online"));
    config.setIftttErrorEventName(properties.getProperty("indego.ifttt.maker.eventname-error"));
    config.setIftttErrorClearedEventName(properties.getProperty("indego.ifttt.maker.eventname-error-cleared"));
    config.setIftttStateChangeEventName(properties.getProperty("indego.ifttt.maker.eventname-state-change"));
    config.setIndegoBaseUrl(properties.getProperty("indego.ifttt.device.base-url"));
    config.setIndegoUsername(properties.getProperty("indego.ifttt.device.username"));
    config.setIndegoPassword(properties.getProperty("indego.ifttt.device.password"));
    config.setPollingIntervalMs(Integer.parseInt(properties.getProperty("indego.ifttt.polling-interval-ms")));

    IftttIndegoAdapter adapter = new IftttIndegoAdapter(config);
    adapter.startup();
}

From source file:de.tudarmstadt.ukp.csniper.resbuild.stuff.BncCheckDocuments.java

public static void main(String[] args) throws IOException {
    boolean enabled = false;

    for (File f : FileUtils.listFiles(new File(BASE), new String[] { "xml" }, true)) {
        BufferedInputStream bis = null;
        try {/*from   w  ww  .j a  v a 2 s .com*/
            bis = new BufferedInputStream(new FileInputStream(f));
            int c;
            StringBuilder sb = new StringBuilder();
            while ((c = bis.read()) != '>') {
                if (enabled) {
                    if (c == '"') {
                        enabled = false;
                        break;
                    } else {
                        sb.append((char) c);
                    }
                }
                if (c == '"') {
                    enabled = true;
                }
            }
            String name = f.getName().substring(0, 3);
            String id = sb.toString();
            if (!name.equals(id)) {
                System.out.println("Name is [" + name + "], but ID is [" + id + "].");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            IOUtils.closeQuietly(bis);
        }
    }
}