Example usage for java.io DataOutputStream writeBytes

List of usage examples for java.io DataOutputStream writeBytes

Introduction

In this page you can find the example usage for java.io DataOutputStream writeBytes.

Prototype

public final void writeBytes(String s) throws IOException 

Source Link

Document

Writes out the string to the underlying output stream as a sequence of bytes.

Usage

From source file:TaxSvc.TaxSvc.java

public GetTaxResult GetTax(GetTaxRequest req) {

    //Create URL//  w  w  w  . j a  va2 s .c  om
    String taxget = svcURL + "/1.0/tax/get";
    URL url;

    HttpURLConnection conn;
    try {
        //Connect to URL with authorization header, request content.
        url = new URL(taxget);
        conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setUseCaches(false);
        conn.setAllowUserInteraction(false);

        String encoded = "Basic " + new String(Base64.encodeBase64((accountNum + ":" + license).getBytes())); //Create auth content
        conn.setRequestProperty("Authorization", encoded); //Add authorization header
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

        ObjectMapper mapper = new ObjectMapper();
        mapper.setSerializationInclusion(Include.NON_NULL); //Tells the serializer to only include those parameters that are not null
        String content = mapper.writeValueAsString(req);
        //System.out.println(content);   //Uncomment to see the content of the request object
        conn.setRequestProperty("Content-Length", Integer.toString(content.length()));

        DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
        wr.writeBytes(content);
        wr.flush();
        wr.close();

        conn.disconnect();

        if (conn.getResponseCode() != 200) //If we didn't get a success back, print out the error.
        {
            GetTaxResult res = mapper.readValue(conn.getErrorStream(), GetTaxResult.class); //Deserializes the response
            return res;
        }

        else //Otherwise, print out the total tax calculated
        {
            mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
            GetTaxResult res = mapper.readValue(conn.getInputStream(), GetTaxResult.class); //Deserializes the response
            return res;
        }

    } catch (IOException e) {
        e.printStackTrace();
        return null;

    }
}

From source file:org.apache.hadoop.mapred.TestMiniMRMapRedDebugScript.java

/**
 * Launches failed map task and debugs the failed task
 * @param conf configuration for the mapred job
 * @param inDir input path// w w  w  .ja  va 2s  .c  o m
 * @param outDir output path
 * @param debugDir debug directory where script is present
 * @param debugCommand The command to execute script
 * @param input Input text
 * @return the output of debug script 
 * @throws IOException
 */
public String launchFailMapAndDebug(JobConf conf, Path inDir, Path outDir, Path debugDir, String debugScript,
        String input) throws IOException {

    // set up the input file system and write input text.
    FileSystem inFs = inDir.getFileSystem(conf);
    FileSystem outFs = outDir.getFileSystem(conf);
    outFs.delete(outDir, true);
    if (!inFs.mkdirs(inDir)) {
        throw new IOException("Mkdirs failed to create " + inDir.toString());
    }
    {
        // write input into input file
        DataOutputStream file = inFs.create(new Path(inDir, "part-0"));
        file.writeBytes(input);
        file.close();
    }

    // configure the mapred Job for failing map task.
    conf.setJobName("failmap");
    conf.setMapperClass(MapClass.class);
    conf.setReducerClass(IdentityReducer.class);
    conf.setNumMapTasks(1);
    conf.setNumReduceTasks(0);
    conf.setMapDebugScript(debugScript);
    FileInputFormat.setInputPaths(conf, inDir);
    FileOutputFormat.setOutputPath(conf, outDir);
    String TEST_ROOT_DIR = new Path(System.getProperty("test.build.data", "/tmp")).toString().replace(' ', '+');
    conf.set("test.build.data", TEST_ROOT_DIR);

    // copy debug script to cache from local file system.
    FileSystem debugFs = debugDir.getFileSystem(conf);
    Path scriptPath = new Path(debugDir, "testscript.txt");
    Path cachePath = new Path("/cacheDir");
    if (!debugFs.mkdirs(cachePath)) {
        throw new IOException("Mkdirs failed to create " + cachePath.toString());
    }
    debugFs.copyFromLocalFile(scriptPath, cachePath);

    URI uri = debugFs.getUri().resolve(cachePath + "/testscript.txt#testscript");
    DistributedCache.createSymlink(conf);
    DistributedCache.addCacheFile(uri, conf);

    RunningJob job = null;
    // run the job. It will fail with IOException.
    try {
        job = new JobClient(conf).submitJob(conf);
    } catch (IOException e) {
        LOG.info("Running Job failed", e);
    }

    JobID jobId = job.getID();
    // construct the task id of first map task of failmap
    TaskAttemptID taskId = new TaskAttemptID(new TaskID(jobId, true, 0), 0);
    // wait for the job to finish.
    while (!job.isComplete())
        ;

    // return the output of debugout log.
    return readTaskLog(TaskLog.LogName.DEBUGOUT, taskId, false);
}

From source file:mzb.NameNodeConnector.java

private OutputStream checkAndMarkRunningBalancer() throws IOException {
    try {/*from   w  ww .j a  v  a2s  .  c o  m*/
        final DataOutputStream out = fs.create(BALANCER_ID_PATH);
        out.writeBytes(InetAddress.getLocalHost().getHostName());
        out.flush();
        return out;
    } catch (RemoteException e) {
        if (AlreadyBeingCreatedException.class.getName().equals(e.getClassName())) {
            return null;
        } else {
            throw e;
        }
    }
}

From source file:org.apache.hadoop.mapred.TestTaskFail.java

public RunningJob launchJob(JobConf conf, Path inDir, Path outDir, String input) throws IOException {
    // set up the input file system and write input text.
    FileSystem inFs = inDir.getFileSystem(conf);
    FileSystem outFs = outDir.getFileSystem(conf);
    outFs.delete(outDir, true);/*from   w  w  w.j  a v a  2 s  .  co m*/
    if (!inFs.mkdirs(inDir)) {
        throw new IOException("Mkdirs failed to create " + inDir.toString());
    }
    {
        // write input into input file
        DataOutputStream file = inFs.create(new Path(inDir, "part-0"));
        file.writeBytes(input);
        file.close();
    }

    // configure the mapred Job
    conf.setMapperClass(MapperClass.class);
    conf.setReducerClass(IdentityReducer.class);
    conf.setNumReduceTasks(0);
    FileInputFormat.setInputPaths(conf, inDir);
    FileOutputFormat.setOutputPath(conf, outDir);
    conf.setSpeculativeExecution(false);
    String TEST_ROOT_DIR = new Path(System.getProperty("test.build.data", "/tmp")).toString().replace(' ', '+');
    conf.set("test.build.data", TEST_ROOT_DIR);
    // return the RunningJob handle.
    return new JobClient(conf).submitJob(conf);
}

From source file:mendhak.teamcity.stash.api.StashClient.java

private String PostBuildStatusToStash(String targetURL, String body, String authHeader) {

    HttpURLConnection connection = null;
    try {//from w ww.j  av a 2  s  . co  m

        Logger.LogInfo("Sending build status to " + targetURL);
        Logger.LogInfo("With body: " + body);
        Logger.LogInfo("Auth header: " + authHeader);

        connection = GetConnection(targetURL);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/json");

        connection.setRequestProperty("Content-Length", String.valueOf(body.getBytes().length));
        connection.setRequestProperty("Authorization", "Basic " + authHeader);

        connection.setUseCaches(false);
        connection.setDoInput(true);
        connection.setDoOutput(true);

        DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
        wr.writeBytes(body);
        wr.flush();
        wr.close();

        InputStream is = connection.getInputStream();
        BufferedReader rd = new BufferedReader(new InputStreamReader(is));
        String line;
        StringBuilder response = new StringBuilder();
        while ((line = rd.readLine()) != null) {
            response.append(line);
            response.append("\r\n");
        }
        rd.close();
        return response.toString();

    } catch (Exception e) {

        Logger.LogError("Could not send data to Stash. ", e);
    } finally {

        if (connection != null) {
            connection.disconnect();
        }
    }

    return null;

}

From source file:org.apache.hadoop.mapred.TestChildTaskDirs.java

public void testChildDirCleanup() throws Exception {
    LOG.info("Testing if the dirs created by the child process is cleaned up properly");

    if (!shouldRun()) {
        return;/*  w w  w .  j  ava  2  s .  c  om*/
    }

    // start the cluster
    startCluster();

    // make sure that only one tracker is configured
    if (mrCluster.getNumTaskTrackers() != 1) {
        throw new Exception("Cluster started with " + mrCluster.getNumTaskTrackers() + " instead of 1");
    }

    // configure a job
    JobConf jConf = getClusterConf();
    jConf.setJobName("Mkdir job");
    jConf.setMapperClass(CreateDir.class);
    jConf.setNumMapTasks(1);
    jConf.setNumReduceTasks(0);

    FileSystem fs = FileSystem.get(jConf);
    Path inDir = new Path("in");
    Path outDir = new Path("out");
    if (fs.exists(outDir)) {
        fs.delete(outDir, true);
    }
    if (!fs.exists(inDir)) {
        fs.mkdirs(inDir);
    }
    String input = "The quick brown fox";
    DataOutputStream file = fs.create(new Path(inDir, "part-0"));
    file.writeBytes(input);
    file.close();

    jConf.setInputFormat(TextInputFormat.class);
    jConf.setOutputKeyClass(LongWritable.class);
    jConf.setOutputValueClass(Text.class);

    FileInputFormat.setInputPaths(jConf, inDir);
    FileOutputFormat.setOutputPath(jConf, outDir);

    // set inline cleanup queue in TT
    mrCluster.getTaskTrackerRunner(0).getTaskTracker().directoryCleanupThread = new InlineCleanupQueue();

    JobClient jobClient = new JobClient(jConf);
    RunningJob job = jobClient.submitJob(jConf);

    JobID id = job.getID();

    // wait for the job to finish
    job.waitForCompletion();

    JobInProgress jip = mrCluster.getJobTrackerRunner().getJobTracker().getJob(id);
    String attemptId = jip.getTasks(TaskType.MAP)[0].getTaskStatuses()[0].getTaskID().toString();

    String taskTrackerLocalDir = mrCluster.getTaskTrackerRunner(0).getLocalDir();

    String taskDir = TaskTracker.getLocalTaskDir(id.toString(), attemptId);
    Path taskDirPath = new Path(taskTrackerLocalDir, taskDir);
    LOG.info("Checking task dir " + taskDirPath);
    FileSystem localFS = FileSystem.getLocal(jConf);
    assertFalse("task dir still exists", localFS.exists(taskDirPath));
}

From source file:org.apache.hadoop.mapred.TestMapProgress.java

private void createInputFile(Path rootDir) throws IOException {
    if (fs.exists(rootDir)) {
        fs.delete(rootDir, true);/* w ww  .j a v  a 2s.  c  o  m*/
    }

    String str = "The quick brown fox\n" + "The brown quick fox\n" + "The fox brown quick\n";
    DataOutputStream inpFile = fs.create(new Path(rootDir, "part-0"));
    inpFile.writeBytes(str);
    inpFile.close();
}

From source file:com.cbagroup.sit.CreditTransfer.java

public String sendPOST() throws IOException, NoSuchAlgorithmException {
    String key = "api_key=cbatest123";
    //String url = "http://developer.cbagroup.com/api/CreditTransfer?api_key=cbatest123";
    String url = "http://developer.cbagroup.com/api/CreditTransfer?" + key;
    URL object = new URL(url);
    HttpURLConnection con = (HttpURLConnection) object.openConnection();

    //add reuqest header
    con.setRequestMethod("POST");
    //con.setRequestProperty("User-Agent", USER_AGENT);
    con.setRequestProperty("Accept", "application/json");

    String urlParameters = "BankCode=Kenya&" + "BranchCode=COMBAPI&" + "Country=COMBAPI&"
            + "TranType=CreditTransfer&" + "Reference=Impalapay&" + "Currency=10.25&" + "Account=pay&"
            + "Amount=10.22&" + "Narration=payment&" + "Transaction Date=1.2.2017&";

    // Send post request
    con.setDoOutput(true);//  www . j ava2  s .co  m
    DataOutputStream wr = new DataOutputStream(con.getOutputStream());
    wr.writeBytes(urlParameters);
    wr.flush();
    wr.close();

    int responseCode = con.getResponseCode();
    System.out.println("\nSending 'POST' request to URL : " + url);
    System.out.println("Post parameters : " + urlParameters);
    System.out.println("Response Code : " + responseCode);

    BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
    String inputLine;
    StringBuffer response = new StringBuffer();

    while ((inputLine = in.readLine()) != null) {
        response.append(inputLine);
    }

    in.close();

    //print result
    System.out.println(response.toString());

    //////////start  ////////////////////
    String result = response.toString();

    JSONParser parser = new JSONParser();

    try {

        Object obj = parser.parse(result);

        JSONObject jsonObject = (JSONObject) obj;
        //System.out.println(jsonObject);

        long ResCode = (long) jsonObject.get("Response Code");
        System.out.println();
        System.out.println("Response Code : " + ResCode);
        System.out.println();

        if (ResCode == 1) {

            System.out.println("#########################################################");
            System.out.println("Fred hack Fail");
            System.out.println();

            long ResCode1 = (long) jsonObject.get("Response Code");
            System.out.println();
            System.out.println("Response Code : " + ResCode1);
            System.out.println();

            String Ref = (String) jsonObject.get("Reference");
            System.out.println();
            System.out.println("Reference : " + Ref);
            System.out.println();

            String Des = (String) jsonObject.get("Description");
            System.out.println();
            System.out.println("Description : " + Des);
            System.out.println();

        } else {

            System.out.println("#########################################################");
            System.out.println("Fred hack Success");
            System.out.println();

            long ResCode1 = (long) jsonObject.get("Response Code");
            System.out.println();
            System.out.println("Response Code : " + ResCode1);
            System.out.println();

            String Ref = (String) jsonObject.get("Reference");
            System.out.println();
            System.out.println("Reference : " + Ref);
            System.out.println();

            String Des = (String) jsonObject.get("Description");
            System.out.println();
            System.out.println("Description : " + Des);
            System.out.println();

        }

        //         long age = (Long) jsonObject.get("Description");
        //         System.out.println(age);

        // loop array
        //         JSONArray msg = (JSONArray) jsonObject.get("messages");
        //         Iterator<String> iterator = msg.iterator();
        //         while (iterator.hasNext()) {
        //             System.out.println(iterator.next());
        //}

    } catch (ParseException e) {
        e.printStackTrace();
    }
    return response.toString();
}

From source file:com.cbagroup.sit.Transact.java

public String sendPOST() throws IOException, NoSuchAlgorithmException {

    String key = "api_key=cbatest123";
    //String url = "http://developer.cbagroup.com/api/CreditTransfer?api_key=cbatest123";
    String url = "http://developer.cbagroup.com/api/Transact?" + key;
    URL object = new URL(url);
    HttpURLConnection con = (HttpURLConnection) object.openConnection();

    //add reuqest header
    con.setRequestMethod("POST");
    //con.setRequestProperty("User-Agent", USER_AGENT);
    con.setRequestProperty("Accept", "application/json");

    String urlParameters = "Country=Kenya&" + "TranType=Transact&" + "Reference=COMBAPI&" + "Currency=kes&"
            + "Account=1.2.2013&" + "Amount=10.25&" + "Narration=pay&" + "TransactionDate=1.2.2013&";

    // Send post request
    con.setDoOutput(true);//from   w ww . ja  va 2s. c  o m
    DataOutputStream wr = new DataOutputStream(con.getOutputStream());
    wr.writeBytes(urlParameters);
    wr.flush();
    wr.close();

    int responseCode = con.getResponseCode();
    System.out.println("\nSending 'POST' request to URL : " + url);
    System.out.println("Post parameters : " + urlParameters);
    System.out.println("Response Code : " + responseCode);

    BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
    String inputLine;
    StringBuffer response = new StringBuffer();

    while ((inputLine = in.readLine()) != null) {
        response.append(inputLine);
    }

    in.close();

    //print result
    System.out.println(response.toString());

    ////////// start  ////////////////////
    String result = response.toString();

    JSONParser parser = new JSONParser();

    try {

        Object obj = parser.parse(result);

        JSONObject jsonObject = (JSONObject) obj;
        //System.out.println(jsonObject);

        long ResCode = (long) jsonObject.get("Response Code");
        System.out.println();
        System.out.println("Response Code : " + ResCode);
        System.out.println();

        if (ResCode == 1) {

            System.out.println("#########################################################");
            System.out.println("Fred hack Fail");
            System.out.println();

            long ResCode1 = (long) jsonObject.get("Response Code");
            System.out.println();
            System.out.println("Response Code : " + ResCode1);
            System.out.println();

            String Ref = (String) jsonObject.get("Reference");
            System.out.println();
            System.out.println("Reference : " + Ref);
            System.out.println();

            String Des = (String) jsonObject.get("Description");
            System.out.println();
            System.out.println("Description : " + Des);
            System.out.println();

        } else {

            System.out.println("#########################################################");
            System.out.println("Fred hack Success");
            System.out.println();

            long ResCode1 = (long) jsonObject.get("Response Code");
            System.out.println();
            System.out.println("Response Code : " + ResCode1);
            System.out.println();

            String Ref = (String) jsonObject.get("Reference");
            System.out.println();
            System.out.println("Reference : " + Ref);
            System.out.println();

            String Des = (String) jsonObject.get("Description");
            System.out.println();
            System.out.println("Description : " + Des);
            System.out.println();

        }

        //            long age = (Long) jsonObject.get("Description");
        //            System.out.println(age);

        // loop array
        //            JSONArray msg = (JSONArray) jsonObject.get("messages");
        //            Iterator<String> iterator = msg.iterator();
        //            while (iterator.hasNext()) {
        //                System.out.println(iterator.next());
        //}

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

    return response.toString();
}

From source file:org.openmrs.module.dhisreport.scheduler.PostToDhisTask.java

private int sendPost(String urlParameters) throws Exception {

    String url = "http://localhost:8081/openmrs18/module/dhisreport/executeReport.form";
    url = Context.getAdministrationService().getGlobalProperty("dhisreport.SchedulerURL");

    final String USER_AGENT = "Mozilla/5.0";

    URL obj = new URL(url);
    HttpURLConnection con = (HttpURLConnection) obj.openConnection();

    // add reuqest header
    con.setRequestMethod("POST");
    con.setRequestProperty("User-Agent", USER_AGENT);
    con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
    con.setRequestProperty("Host", "localhost:8081");

    DHIS2ReportingService service = Context.getService(DHIS2ReportingService.class);
    String dhisurl = Context.getAdministrationService().getGlobalProperty("dhisreport.dhis2URL");
    String dhisusername = Context.getAdministrationService().getGlobalProperty("dhisreport.dhis2UserName");
    String dhispassword = Context.getAdministrationService().getGlobalProperty("dhisreport.dhis2Password");
    HttpDhis2Server server = service.getDhis2Server();

    URL urltemp = null;//from w w  w  .ja v a2  s  .c o m
    try {
        urltemp = new URL(dhisurl);
    } catch (MalformedURLException e) {
        e.printStackTrace();
    }

    server.setUrl(urltemp);
    server.setUsername(dhisusername);
    server.setPassword(dhispassword);

    // String urlParameters =
    // "sn=C02G8416DRJM&cn=&locale=&caller=&num=12345";

    // Send post request
    con.setDoOutput(true);
    DataOutputStream wr = new DataOutputStream(con.getOutputStream());
    wr.writeBytes(urlParameters);
    wr.flush();
    wr.close();

    int responseCode = con.getResponseCode();
    // System.out.println( "\nSending 'POST' request to URL : " + url );
    //System.out.println( "Post parameters : " + urlParameters );
    //System.out.println( "Response Code : " + responseCode );

    BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
    String inputLine;
    StringBuffer response = new StringBuffer();

    while ((inputLine = in.readLine()) != null) {
        response.append(inputLine);
    }
    in.close();

    // print result
    //        System.out.println( response.toString() );
    return responseCode;

}