Example usage for java.io OutputStreamWriter write

List of usage examples for java.io OutputStreamWriter write

Introduction

In this page you can find the example usage for java.io OutputStreamWriter write.

Prototype

public void write(int c) throws IOException 

Source Link

Document

Writes a single character.

Usage

From source file:actuatorapp.ActuatorApp.java

public ActuatorApp() throws IOException, JSONException {
    //Takes a sting with a relay name "RELAYLO1-10FAD.relay1"
    //Actuator a = new Actuator("RELAYLO1-12854.relay1");    
    //Starts the virtualhub that is needed to connect to the actuators
    Process process = new ProcessBuilder("src\\actuatorapp\\VirtualHub.exe").start();
    //{"yocto_addr":"10FAD","payload":{"value":true},"type":"control"}

    api = new Socket("10.42.72.25", 8082);
    OutputStreamWriter osw = new OutputStreamWriter(api.getOutputStream(), StandardCharsets.UTF_8);
    InputStreamReader isr = new InputStreamReader(api.getInputStream(), StandardCharsets.UTF_8);

    //Sends JSON authentication to CommandAPI
    JSONObject secret = new JSONObject();
    secret.put("type", "authenticate");
    secret.put("secret", "testpass");
    osw.write(secret.toString() + "\r\n");
    osw.flush();//w  w  w  . j a v a 2 s.c o m
    System.out.println("sent");

    //Waits and recieves JSON authentication response
    BufferedReader br = new BufferedReader(isr);
    JSONObject response = new JSONObject(br.readLine());
    System.out.println(response.toString());
    if (!response.getBoolean("success")) {
        System.err.println("Invalid API secret");
        System.exit(1);
    }

    try {
        while (true) {
            //JSON object will contain message from the server
            JSONObject type = getCommand(br);
            //Forward the command to be processed (will find out which actuators to turn on/off)
            commandFromApi(type);
        }
    } catch (Exception e) {
        System.out.println("Error listening to api");
    }

}

From source file:com.google.wave.api.AbstractRobotServlet.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    this.req = req;
    // RobotMessageBundleImpl events = deserializeEvents(req);
    //    /*  w ww. j a  v a 2s. co  m*/
    // // Log All Events
    // for (Event event : events.getEvents()) {
    // log(event.getType().toString() + " [" +
    // event.getWavelet().getWaveId() + " " +
    // event.getWavelet().getWaveletId());
    // try {
    // log(" " + event.getBlip().getBlipId() + "] [" +
    // event.getBlip().getDocument().getText().replace("\n", "\\n") + "]");
    // } catch(NullPointerException npx) {
    // log("] [null]");
    // }
    // }

    // processEvents(events);
    // events.getOperations().setVersion(getVersion());
    // serializeOperations(events.getOperations(), resp);

    String events = getRequestBody(req);
    log("Events: " + events);

    JSONSerializer serializer = getJSONSerializer();
    EventMessageBundle eventsBundle = null;
    String proxyingFor = "";

    try {
        JSONObject jsonObject = new JSONObject(events);
        proxyingFor = jsonObject.getString("proxyingFor");
    } catch (JSONException jsonx) {
        jsonx.printStackTrace();
    }

    log(proxyingFor);

    String port = "";
    try {
        port = new JSONObject(proxyingFor).getString("port");
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    String data = "events=" + URLEncoder.encode(events, "UTF-8");
    // Send the request

    log("port = " + port);

    URL url = new URL("http://jem.thewe.net/" + port + "/wave");
    URLConnection conn = url.openConnection();
    log("no timeout");
    //conn.setReadTimeout(10000);
    //conn.setConnectTimeout(10000);
    conn.setDoOutput(true);
    OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());

    // write parameters
    log("Sending: " + data);
    writer.write(data);

    writer.flush();

    // Get the response
    StringBuffer answer = new StringBuffer();
    BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    String line;
    while ((line = reader.readLine()) != null) {
        answer.append(line);
    }

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

    log("Answer: " + answer.toString());

    serializeOperations(answer.toString(), resp);
}

From source file:squash.deployment.lambdas.utils.CloudFormationResponder.java

/**
 *  Sends the custom resource response to the Cloudformation service.
 *  /*from www .  j  ava 2s .  com*/
 *  <p>The response is returned indirectly to Cloudformation via the
 *     presigned Url it provided in its request.
 *  
 *  @param status whether the call succeeded - must be either SUCCESS or FAILED.
 *  @param logger a CloudwatchLogs logger.
 *  @throws IllegalStateException when the responder is uninitialised.
 */
public void sendResponse(String status, LambdaLogger logger) {
    if (!initialised) {
        throw new IllegalStateException("The responder has not been initialised");
    }

    try {
        rootNode.put("Status", status);
        rootNode.put("RequestId", requestParameters.get("RequestId"));
        rootNode.put("StackId", requestParameters.get("StackId"));
        rootNode.put("LogicalResourceId", requestParameters.get("LogicalResourceId"));
        rootNode.put("PhysicalResourceId", physicalResourceId);
    } catch (Exception e) {
        // Can do nothing more than log the error and return. Must rely on
        // CloudFormation timing-out since it won't get a response from us.
        logger.log("Exception caught whilst constructing response: " + e.toString());
        return;
    }

    // Send the response to CloudFormation via the provided presigned S3 URL
    logger.log("About to send response to presigned URL: " + requestParameters.get("ResponseURL"));
    try {
        URL url = new URL(requestParameters.get("ResponseURL"));
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoOutput(true);
        connection.setRequestMethod("PUT");
        OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());

        mapper.writeTree(generator, rootNode);
        String output = cloudFormationJsonResponse.toString(StandardCharsets.UTF_8.name());

        logger.log("Response about to be sent: " + output);
        out.write(output);
        out.close();
        logger.log("Sent response to presigned URL");
        int responseCode = connection.getResponseCode();
        logger.log("Response Code returned from presigned URL: " + responseCode);
    } catch (IOException e) {
        // Can do nothing more than log the error and return.
        logger.log("Exception caught whilst replying to presigned URL: " + e.toString());
        return;
    }
}

From source file:com.novartis.opensource.yada.adaptor.RESTAdaptor.java

/**
 * Gets the input stream from the {@link URLConnection} and stores it in 
 * the {@link YADAQueryResult} in {@code yq}
 * @see com.novartis.opensource.yada.adaptor.Adaptor#execute(com.novartis.opensource.yada.YADAQuery)
 *///from   w  w w  . j av  a2s .  c om
@Override
public void execute(YADAQuery yq) throws YADAAdaptorExecutionException {
    boolean isPostPutPatch = this.method.equals(YADARequest.METHOD_POST)
            || this.method.equals(YADARequest.METHOD_PUT) || this.method.equals(YADARequest.METHOD_PATCH);
    resetCountParameter(yq);
    int rows = yq.getData().size() > 0 ? yq.getData().size() : 1;
    /*
     * Remember:
     * A row is an set of YADA URL parameter values, e.g.,
     * 
     *  x,y,z in this:      
     *    ...yada/q/queryname/p/x,y,z
     *  so 1 row
     *    
     *  or each of {col1:x,col2:y,col3:z} and {col1:a,col2:b,col3:c} in this:
     *    ...j=[{qname:queryname,DATA:[{col1:x,col2:y,col3:z},{col1:a,col2:b,col3:c}]}]
     *  so 2 rows
     */
    for (int row = 0; row < rows; row++) {
        String result = "";

        // creates result array and assigns it
        yq.setResult();
        YADAQueryResult yqr = yq.getResult();

        String urlStr = yq.getUrl(row);

        for (int i = 0; i < yq.getParamCount(row); i++) {
            Matcher m = PARAM_URL_RX.matcher(urlStr);
            if (m.matches()) {
                String param = yq.getVals(row).get(i);
                urlStr = urlStr.replaceFirst(PARAM_SYMBOL_RX, m.group(1) + param);
            }
        }

        l.debug("REST url w/params: [" + urlStr + "]");
        try {
            URL url = new URL(urlStr);
            URLConnection conn = null;

            if (this.hasProxy()) {
                String[] proxyStr = this.proxy.split(":");
                Proxy proxySvr = new Proxy(Proxy.Type.HTTP,
                        new InetSocketAddress(proxyStr[0], Integer.parseInt(proxyStr[1])));
                conn = url.openConnection(proxySvr);
            } else {
                conn = url.openConnection();
            }

            // basic auth
            if (url.getUserInfo() != null) {
                //TODO issue with '@' sign in pw, must decode first
                String basicAuth = "Basic " + new String(new Base64().encode(url.getUserInfo().getBytes()));
                conn.setRequestProperty("Authorization", basicAuth);
            }

            // cookies
            if (yq.getCookies() != null && yq.getCookies().size() > 0) {
                String cookieStr = "";
                for (HttpCookie cookie : yq.getCookies()) {
                    cookieStr += cookie.getName() + "=" + cookie.getValue() + ";";
                }
                conn.setRequestProperty("Cookie", cookieStr);
            }

            if (yq.getHttpHeaders() != null && yq.getHttpHeaders().length() > 0) {
                l.debug("Processing custom headers...");
                @SuppressWarnings("unchecked")
                Iterator<String> keys = yq.getHttpHeaders().keys();
                while (keys.hasNext()) {
                    String name = keys.next();
                    String value = yq.getHttpHeaders().getString(name);
                    l.debug("Custom header: " + name + " : " + value);
                    conn.setRequestProperty(name, value);
                    if (name.equals(X_HTTP_METHOD_OVERRIDE) && value.equals(YADARequest.METHOD_PATCH)) {
                        l.debug("Resetting method to [" + YADARequest.METHOD_POST + "]");
                        this.method = YADARequest.METHOD_POST;
                    }
                }
            }

            HttpURLConnection hConn = (HttpURLConnection) conn;
            if (!this.method.equals(YADARequest.METHOD_GET)) {
                hConn.setRequestMethod(this.method);
                if (isPostPutPatch) {
                    //TODO make YADA_PAYLOAD case-insensitive and create an alias for it, e.g., ypl
                    // NOTE: YADA_PAYLOAD is a COLUMN NAME found in a JSONParams DATA object.  It 
                    //       is not a YADA param
                    String payload = yq.getDataRow(row).get(YADA_PAYLOAD)[0];
                    hConn.setDoOutput(true);
                    OutputStreamWriter writer;
                    writer = new OutputStreamWriter(conn.getOutputStream());
                    writer.write(payload.toString());
                    writer.flush();
                }
            }

            // debug
            Map<String, List<String>> map = conn.getHeaderFields();
            for (Map.Entry<String, List<String>> entry : map.entrySet()) {
                l.debug("Key : " + entry.getKey() + " ,Value : " + entry.getValue());
            }

            try (BufferedReader in = new BufferedReader(new InputStreamReader(hConn.getInputStream()))) {
                String inputLine;
                while ((inputLine = in.readLine()) != null) {
                    result += String.format("%1s%n", inputLine);
                }
            }
            yqr.addResult(row, result);
        } catch (MalformedURLException e) {
            String msg = "Unable to access REST source due to a URL issue.";
            throw new YADAAdaptorExecutionException(msg, e);
        } catch (IOException e) {
            String msg = "Unable to read REST response.";
            throw new YADAAdaptorExecutionException(msg, e);
        }
    }
}

From source file:de.uni_koeln.spinfo.maalr.services.editor.server.EditorServiceImpl.java

private void write(OutputStreamWriter writer, LemmaVersion version, Set<String> fields) throws IOException {
    for (String field : fields) {
        String value = version.getEntryValue(field);
        if (value != null)
            writer.write(value.trim());
        writer.write("\t");
    }//from   www  .  j a v a  2 s  .  co m
}

From source file:com.github.davidcarboni.encryptedfileupload.StreamingTest.java

private byte[] newRequest() throws IOException {
    final ByteArrayOutputStream baos = new ByteArrayOutputStream();
    final OutputStreamWriter osw = new OutputStreamWriter(baos, "US-ASCII");
    int add = 16;
    int num = 0;//  w w  w.j  av a 2 s  .com
    for (int i = 0; i < 16384; i += add) {
        if (++add == 32) {
            add = 16;
        }
        osw.write(getHeader("field" + (num++)));
        osw.flush();
        for (int j = 0; j < i; j++) {
            baos.write((byte) j);
        }
        osw.write("\r\n");
    }
    osw.write(getFooter());
    osw.close();
    return baos.toByteArray();
}

From source file:io.github.gsteckman.rpi_rest.SubscriptionManager.java

/**
 * Sends the provided message to the host and port specified in the URL object.
 * /*from w  w w  .  ja  v  a2  s  .  co  m*/
 * @param url
 *            Provides the host and port to which the message is sent via TCP.
 * @param message
 *            The message to send, including all headers and message body.
 * @throws IOException
 *             If an exception occured writing to the socket.
 */
private void sendNotify(final URL url, final String message) throws IOException {
    Socket sock = new Socket(url.getHost(), url.getPort());
    OutputStreamWriter out = new OutputStreamWriter(sock.getOutputStream());
    out.write(message);
    out.close();
    sock.close();
}

From source file:com.personalserver.HomeCommandHandler.java

@Override
public void handle(HttpRequest httpRequest, HttpResponse httpResponse, HttpContext httpContext)
        throws HttpException, IOException {

    this.mHost = httpRequest.getFirstHeader("Host").getValue();
    System.out.println("Host : " + mHost);
    HttpEntity entity = new EntityTemplate(new ContentProducer() {
        public void writeTo(final OutputStream outstream) throws IOException {
            OutputStreamWriter writer = new OutputStreamWriter(outstream, "UTF-8");
            String html = "<html><head></head>" + "<body><center><h1>Welcome to Personal Server<h1></center>"
                    + "<p>to browse file click <a href=\"http://" + mHost + "/dir\">here</a></p>"
                    + "</body></html>";

            // html = AssetsUtils.readHtmlForName(mContext, "home");

            writer.write(html);
            writer.flush();/*from w  ww  .java 2  s.co  m*/
        }
    });

    httpResponse.setHeader("Content-Type", "text/html");
    httpResponse.setEntity(entity);
}

From source file:com.mitre.holdshort.AlertLogger.java

public void writeDataToFtpServer(LoggedAlert currentAlert) {
    try {//w w w  .j a  v a 2 s .c  o  m
        alertFTPClient.changeWorkingDirectory("/data");
        OutputStream os = alertFTPClient.storeFileStream(airport + "_" + System.currentTimeMillis() + ".dat");
        OutputStreamWriter osw = new OutputStreamWriter(os);
        osw.write(currentAlert.getAlertString());
        osw.close();
        logOldAlerts();
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

From source file:org.yawlfoundation.yawl.engine.interfce.Interface_Client.java

/**
 * Submits data on a HTTP connection/*from   ww  w  .  j  a  va  2s. c  om*/
 * @param connection a valid, open HTTP connection
 * @param data the data to submit
 * @throws IOException when there's some kind of communication problem
 */
private void sendData(HttpURLConnection connection, String data) throws IOException {
    OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
    out.write(data);
    out.close();
}