Example usage for java.io DataOutputStream flush

List of usage examples for java.io DataOutputStream flush

Introduction

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

Prototype

public void flush() throws IOException 

Source Link

Document

Flushes this data output stream.

Usage

From source file:com.ichi2.anki.SyncClient.java

public static void fullSyncFromLocal(String password, String username, String deckName, String deckPath) {
    URL url;/*  ww  w  .  jav  a2 s.c  o m*/
    try {
        Log.i(AnkiDroidApp.TAG, "Fullup");
        url = new URL(AnkiDroidProxy.SYNC_URL + "fullup");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();

        conn.setDoInput(true);
        conn.setDoOutput(true);
        conn.setUseCaches(false);
        conn.setRequestMethod("POST");

        conn.setRequestProperty("Connection", "close");
        conn.setRequestProperty("Charset", "UTF-8");
        // conn.setRequestProperty("Content-Length", "8494662");
        conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + MIME_BOUNDARY);
        conn.setRequestProperty("Host", AnkiDroidProxy.SYNC_HOST);

        DataOutputStream ds = new DataOutputStream(conn.getOutputStream());
        Log.i(AnkiDroidApp.TAG, "Pass");
        ds.writeBytes(TWO_HYPHENS + MIME_BOUNDARY + END);
        ds.writeBytes("Content-Disposition: form-data; name=\"p\"" + END + END + password + END);
        Log.i(AnkiDroidApp.TAG, "User");
        ds.writeBytes(TWO_HYPHENS + MIME_BOUNDARY + END);
        ds.writeBytes("Content-Disposition: form-data; name=\"u\"" + END + END + username + END);
        Log.i(AnkiDroidApp.TAG, "DeckName");
        ds.writeBytes(TWO_HYPHENS + MIME_BOUNDARY + END);
        ds.writeBytes("Content-Disposition: form-data; name=\"d\"" + END + END + deckName + END);
        Log.i(AnkiDroidApp.TAG, "Deck");
        ds.writeBytes(TWO_HYPHENS + MIME_BOUNDARY + END);
        ds.writeBytes("Content-Disposition: form-data; name=\"deck\";filename=\"deck\"" + END);
        ds.writeBytes("Content-Type: application/octet-stream" + END);
        ds.writeBytes(END);

        FileInputStream fStream = new FileInputStream(deckPath);
        byte[] buffer = new byte[Utils.CHUNK_SIZE];
        int length = -1;

        Deflater deflater = new Deflater(Deflater.BEST_SPEED);
        DeflaterOutputStream dos = new DeflaterOutputStream(ds, deflater);

        Log.i(AnkiDroidApp.TAG, "Writing buffer...");
        while ((length = fStream.read(buffer)) != -1) {
            dos.write(buffer, 0, length);
            Log.i(AnkiDroidApp.TAG, "Length = " + length);
        }
        dos.finish();
        fStream.close();

        ds.writeBytes(END);
        ds.writeBytes(TWO_HYPHENS + MIME_BOUNDARY + TWO_HYPHENS + END);
        Log.i(AnkiDroidApp.TAG, "Closing streams...");

        ds.flush();
        ds.close();

        // Ensure we got the HTTP 200 response code
        int responseCode = conn.getResponseCode();
        if (responseCode != 200) {
            Log.i(AnkiDroidApp.TAG, "Response code = " + responseCode);
            // throw new Exception(String.format("Received the response code %d from the URL %s", responseCode,
            // url));
        } else {
            Log.i(AnkiDroidApp.TAG, "Response code = 200");
        }

        // Read the response
        InputStream is = conn.getInputStream();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] bytes = new byte[1024];
        int bytesRead;
        while ((bytesRead = is.read(bytes)) != -1) {
            baos.write(bytes, 0, bytesRead);
        }
        byte[] bytesReceived = baos.toByteArray();
        baos.close();

        is.close();
        String response = new String(bytesReceived);

        Log.i(AnkiDroidApp.TAG, "Finished!");
    } catch (MalformedURLException e) {
        Log.i(AnkiDroidApp.TAG, "MalformedURLException = " + e.getMessage());
    } catch (IOException e) {
        Log.i(AnkiDroidApp.TAG, "IOException = " + e.getMessage());
    }
}

From source file:com.att.android.arodatacollector.main.AROCollectorService.java

/**
 * This method creates a SU enabled shell Sets the execute permission for
 * tcpdump and key.db Starts the tcpdump on Completion or abnormal
 * termination of tcpdump Shell is destroyed
 * /*from www  .java  2s . com*/
 * @throws IOException
 * @throws InterruptedException
 */

private void startTcpDump() throws IOException, InterruptedException {
    Log.d(TAG, "inside startTcpDump at timestamp " + System.currentTimeMillis());
    Process sh = null;
    DataOutputStream os = null;
    int shExitValue = 0;
    try {
        startCalTime = Calendar.getInstance();

        if (!AROCollectorUtils.isTcpDumpRunning()) {
            //only start tcpdump if it's not already running, to handle the case where the background
            //service was stopped and now restarting

            Log.i(TAG, "tcpdump is not running. Starting tcpdump in the shell now");

            sh = Runtime.getRuntime().exec("su");
            os = new DataOutputStream(sh.getOutputStream());
            String Command = "chmod 777 " + ARODataCollector.INTERNAL_DATA_PATH + TCPDUMPFILENAME + "\n";
            os.writeBytes(Command);
            Command = "chmod 777 " + ARODataCollector.INTERNAL_DATA_PATH + "key.db" + "\n";
            os.writeBytes(Command);

            //flurry timed event duration
            mApp.writeToFlurryAndLogEvent(flurryTimedEvent, "Flurry trace start",
                    startCalTime.getTime().toString(), "Trace Duration", true);

            /*Command = "." + ARODataCollector.INTERNAL_DATA_PATH + TCPDUMPFILENAME + " -w "
                  + TRACE_FOLDERNAME + "\n";*/

            Command = "." + ARODataCollector.INTERNAL_DATA_PATH + TCPDUMPFILENAME + " -i any -w "
                    + TRACE_FOLDERNAME + "\n";

            os.writeBytes(Command);
            Command = "exit\n";
            os.writeBytes(Command);
            os.flush();

            StreamClearer stdoutClearer = new StreamClearer(sh.getInputStream(), "stdout", true);
            new Thread(stdoutClearer).start();
            StreamClearer stderrClearer = new StreamClearer(sh.getErrorStream(), "stderr", true);
            new Thread(stderrClearer).start();

            shExitValue = sh.waitFor();
            if (DEBUG) {
                Log.i(TAG, "tcpdump waitFor returns exit value: " + shExitValue + " at "
                        + System.currentTimeMillis());
            }
        } else {
            Log.i(TAG, "timestamp " + System.currentTimeMillis() + ": tcpdump is already running");
        }

        //We will continue and block the thread untill we see valid instance of tcpdump running in shell
        //waitFor() does not seems to be working on ICS firmware 
        while (AROCollectorUtils.isTcpDumpRunning()) {
            continue;
        }
        if (DEBUG) {
            Log.d(TAG, "tcpdump process exit value: " + shExitValue);
            Log.i(TAG, "Coming out of startTcpDump at " + System.currentTimeMillis());
            logTcpdumpPid();
        }
        // Stopping the Video capture right after tcpdump coming out of
        // shell
        new Thread(new Runnable() {
            @Override
            public void run() {
                if (mVideoRecording && mApp.getAROVideoCaptureRunningFlag()) {
                    stopScreenVideoCapture();
                    stopDmesg();
                }
            }
        }).start();

        final Calendar endCalTime = Calendar.getInstance();

        FlurryAgent.endTimedEvent("Trace Duration");
        mApp.writeToFlurry(flurryTimedEvent, "Flurry trace end", endCalTime.getTime().toString(),
                "flurryTimedEvent", AROCollectorUtils.NOT_APPLICABLE, AROCollectorUtils.EMPTY_STRING);
        mApp.writeToFlurry(flurryTimedEvent, "calculated Flurry trace duration", getUpTime(endCalTime),
                "flurryTimedEvent", AROCollectorUtils.NOT_APPLICABLE, AROCollectorUtils.EMPTY_STRING);
        logFlurryEvents();
        DataCollectorTraceStop();
    } finally {
        try {
            mApp.setTcpDumpStartFlag(false);
            if (os != null) {
                os.close();
            }
            if (sh != null) {
                sh.destroy();
            }
        } catch (Exception e) {
            Log.e(TAG, "exception in startTcpDump DataOutputStream close", e);
        }
    }
}

From source file:org.openxdata.server.FormsServer.java

/**
 * Called when a new connection has been received. Failures are not handled
 * in this class as different servers (BT,SMS, etc) may want to handle them
 * differently./* w  w  w  . j av a2s . co  m*/
 * 
 * @param dis - the stream to read from.
 * @param dos - the stream to write to.
 */
public void processConnection(InputStream disParam, OutputStream dosParam) {

    ZOutputStream gzip = new ZOutputStream(dosParam, JZlib.Z_BEST_COMPRESSION);
    DataOutputStream zdos = new DataOutputStream(gzip);

    byte responseStatus = ResponseStatus.STATUS_ERROR;

    try {
        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            DataInputStream dis = new DataInputStream(disParam);

            String name = dis.readUTF();
            String password = dis.readUTF();
            String serializer = dis.readUTF();
            String locale = dis.readUTF();

            byte action = dis.readByte();

            User user = authenticationService.authenticate(name, password);
            if (user == null)
                responseStatus = ResponseStatus.STATUS_ACCESS_DENIED;
            else {
                DataOutputStream dosTemp = new DataOutputStream(baos);

                if (action == ACTION_DOWNLOAD_FORMS)
                    formDownloadService.downloadForms(dosTemp, serializer, locale);
                else if (action == ACTION_UPLOAD_DATA)
                    submitXforms(dis, dosTemp, serializer);
                else if (action == ACTION_DOWNLOAD_USERS)
                    formDownloadService.downloadUsers(dosTemp, serializer);
                else if (action == ACTION_DOWNLOAD_USERS_AND_FORMS)
                    downloadUsersAndForms(dis.readInt(), dosTemp, serializer, locale);
                else if (action == ACTION_DOWNLOAD_STUDY_LIST)
                    formDownloadService.downloadStudies(dosTemp, serializer, locale);
                else if (action == ACTION_DOWNLOAD_LANGUAGES)
                    formDownloadService.downloadLocales(dis, dosTemp, serializer);
                else if (action == ACTION_DOWNLOAD_MENU_TEXT)
                    formDownloadService.downloadMenuText(dis, dosTemp, serializer, locale);
                else if (action == ACTION_DOWNLOAD_STUDY_FORMS)
                    formDownloadService.downloadForms(dis.readInt(), zdos, serializer, locale);
                else if (action == ACTION_DOWNLOAD_USERS_AND_ALL_FORMS)
                    downloadUsersAndAllForms(dosTemp, serializer, locale);

                responseStatus = ResponseStatus.STATUS_SUCCESS;
            }

            zdos.writeByte(responseStatus);

            if (responseStatus == ResponseStatus.STATUS_SUCCESS) {
                zdos.write(baos.toByteArray());
            }
        } catch (Exception ex) {
            log.error(ex.getMessage(), ex);
            zdos.writeByte(responseStatus);
        } finally {
            zdos.flush();
            gzip.finish();
        }
    } catch (IOException e) {
        // this is for exceptions occurring in the catch or finally clauses.
        log.error(e.getMessage(), e);
    }
}

From source file:com.acc.android.network.operator.base.BaseHttpOperator.java

public static String post(String actionUrl, UploadData uploadData) {
    HttpURLConnection httpURLConnection = null;
    DataOutputStream dataOutputStream = null;
    InputStream inputStream = null;
    String resultString = null;//w  ww.j  a  v a  2  s  . c o  m
    // if (AppLibConstant.isUseLog()) {
    LogUtil.info("actionUrl", actionUrl);
    LogUtil.info("uploadData", uploadData);
    LogUtil.info("sessionStr", sessionStr);
    // }
    try {
        URL url = new URL(actionUrl);
        httpURLConnection = (HttpURLConnection) url.openConnection();
        // httpURLConnection.setRequestProperty("Cookie",
        // "JSESSIONID=320C57C083E7F678ED14B8974732225E");
        httpURLConnection.setDoInput(true);
        httpURLConnection.setDoOutput(true);
        httpURLConnection.setUseCaches(false);
        httpURLConnection.setRequestMethod("POST");
        httpURLConnection.setRequestProperty("Connection", "Keep-Alive");
        httpURLConnection.setRequestProperty("Charset", "UTF-8");
        httpURLConnection.setRequestProperty("Content-Type",
                UploadConstant.MULTIPART_FORM_DATA + ";boundary=" + UploadConstant.BOUNDARY);
        // httpURLConnection.setChunkedStreamingMode(0);
        sessonInject(httpURLConnection);
        dataOutputStream = new DataOutputStream(httpURLConnection.getOutputStream());
        addFormField(uploadData.getParamMap(), dataOutputStream);
        if (!ListUtil.isEmpty(uploadData.getUploadFiles())) {
            addUploadDataContent(uploadData.getUploadFiles(), dataOutputStream
            // , TAGSTRING
            );
        }
        dataOutputStream.writeBytes(UploadConstant.LINEEND);
        dataOutputStream.writeBytes(UploadConstant.TWOHYPHENS + UploadConstant.BOUNDARY
                + UploadConstant.TWOHYPHENS + UploadConstant.LINEEND);
        // try {
        dataOutputStream.flush();
        // } catch (Exception exception) {
        // if (dataOutputStream != null) {
        // dataOutputStream.close();
        // }
        // dataOutputStream = new DataOutputStream(
        // httpURLConnection.getOutputStream());
        // addFormField(uploadData.getParamMap(), dataOutputStream);
        // if (!ListUtil.isEmpty(uploadData.getUploadFiles())) {
        // addUploadDataContent(uploadData.getUploadFiles(),
        // dataOutputStream
        // // , TAGSTRING
        // );
        // }
        // dataOutputStream.writeBytes(UploadConstant.LINEEND);
        // dataOutputStream.writeBytes(UploadConstant.TWOHYPHENS
        // + UploadConstant.BOUNDARY + UploadConstant.TWOHYPHENS
        // + UploadConstant.LINEEND);
        // dataOutputStream.flush();
        // }
        inputStream = httpURLConnection.getInputStream();
        InputStreamReader isr = new InputStreamReader(inputStream, "utf-8");
        BufferedReader br = new BufferedReader(isr);
        resultString = br.readLine();
        // if (AppLibConstant.isUseLog()) {
        LogUtil.info("resultString", resultString);
        // }
        // LogUtil.systemOut(resultString);
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            if (dataOutputStream != null) {
                dataOutputStream.close();
            }
            if (inputStream != null) {
                inputStream.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (httpURLConnection != null) {
            httpURLConnection.disconnect();
        }
    }
    return resultString;
}

From source file:com.sandklef.coachapp.http.HttpAccess.java

public void uploadTrainingPhaseVideo(String clubUri, String videoUuid, String fileName)
        throws HttpAccessException, IOException {

    HttpURLConnection connection = null;
    DataOutputStream outputStream = null;
    DataInputStream inputStream = null;

    String pathToOurFile = fileName;
    String urlServer = urlBase + HttpSettings.API_VERSION + HttpSettings.PATH_SEPARATOR
            + HttpSettings.VIDEO_URL_PATH + HttpSettings.UUID_PATH + videoUuid + HttpSettings.PATH_SEPARATOR
            + HttpSettings.UPLOAD_PATH;//  w  w w .j  a  va 2  s.c  om

    Log.d(LOG_TAG, "Upload server url: " + urlServer);
    Log.d(LOG_TAG, "Upload file:       " + fileName);

    int bytesRead, bytesAvailable, bufferSize;
    byte[] buffer;

    FileInputStream fileInputStream = new FileInputStream(new File(pathToOurFile));

    URL url = new URL(urlServer);
    connection = (HttpURLConnection) url.openConnection();

    Log.d(LOG_TAG, "connection: " + connection + "  uploading data to video: " + videoUuid);

    // Allow Inputs & Outputs
    connection.setDoInput(true);
    connection.setDoOutput(true);
    connection.setUseCaches(false);
    connection.setRequestMethod(HttpSettings.HTTP_POST);

    //
    int timeout = LocalStorage.getInstance().getnetworkTimeout();
    Log.d(LOG_TAG, "timeout: " + timeout);
    connection.setConnectTimeout(timeout);
    connection.setReadTimeout(timeout);

    connection.setRequestProperty("X-Token", LocalStorage.getInstance().getLatestUserToken());
    connection.addRequestProperty("X-Instance", LocalStorage.getInstance().getCurrentClub());
    connection.setRequestProperty("Connection", "close");

    Log.d(LOG_TAG, " upload propoerties: " + connection.getRequestProperties());

    outputStream = new DataOutputStream(connection.getOutputStream());
    bytesAvailable = fileInputStream.available();
    bufferSize = Math.min(bytesAvailable, maxBufferSize);
    buffer = new byte[bufferSize];

    // Read file
    bytesRead = fileInputStream.read(buffer, 0, bufferSize);

    while (bytesRead > 0) {
        Log.d(LOG_TAG, " writing data to stream  (" + bytesRead + " / " + bytesAvailable + ")");
        outputStream.write(buffer, 0, bufferSize);
        Log.d(LOG_TAG, " writing data to stream  -");
        bytesAvailable = fileInputStream.available();
        Log.d(LOG_TAG, " writing data to stream  -");
        bufferSize = Math.min(bytesAvailable, maxBufferSize);
        bytesRead = fileInputStream.read(buffer, 0, bufferSize);
    }
    outputStream.flush();
    outputStream.close();

    // Responses from the server (code and message)
    fileInputStream.close();

    int serverResponseCode = 0;

    long before = System.currentTimeMillis();
    try {
        Log.d(LOG_TAG, " ... writing done, getting response code");
        serverResponseCode = connection.getResponseCode();
        Log.d(LOG_TAG, " ... writing done, getting response message");
        String serverResponseMessage = connection.getResponseMessage();
        Log.d(LOG_TAG, "ServerCode:" + serverResponseCode);
        Log.d(LOG_TAG, "serverResponseMessage:" + serverResponseMessage);
    } catch (java.net.SocketTimeoutException e) {
        Log.d(LOG_TAG, " ... getting response code, got an exception, print stacktrace");
        e.printStackTrace();
        throw new HttpAccessException("Network timeout reached", e, HttpAccessException.NETWORK_SLOW);
    }
    long after = System.currentTimeMillis();
    long diff = after - before;
    Log.d(LOG_TAG, "diff: " + diff + "ms   " + diff / 1000 + "s");

    if (diff > LocalStorage.getInstance().getnetworkTimeout()) {
        throw new HttpAccessException("Network timeout reached", HttpAccessException.NETWORK_SLOW);
    }

    if (serverResponseCode >= 409) {
        throw new HttpAccessException("Failed uploading trainingphase video, access denied",
                HttpAccessException.CONFLICT_ERROR);
    }

    if (serverResponseCode < 500 && serverResponseCode >= 400) {
        throw new HttpAccessException("Failed uploading trainingphase video, access denied",
                HttpAccessException.ACCESS_ERROR);
    }

    try {
        Log.d(LOG_TAG, " ... disconnecting");
        connection.disconnect();
    } catch (Exception e) {
        Log.d(LOG_TAG, " ... disconnecting, got an exception, print stacktrace");
        e.printStackTrace();
    }
}

From source file:net.minecraftforge.fml.repackage.com.nothome.delta.GDiffPatcher.java

/**
 * Patches to an output stream./*from w  w w .  ja  v a 2  s.c  o  m*/
 */
public void patch(SeekableSource source, InputStream patch, OutputStream out) throws IOException {

    DataOutputStream outOS = new DataOutputStream(out);
    DataInputStream patchIS = new DataInputStream(patch);

    // the magic string is 'd1 ff d1 ff' + the version number
    if (patchIS.readUnsignedByte() != 0xd1 || patchIS.readUnsignedByte() != 0xff
            || patchIS.readUnsignedByte() != 0xd1 || patchIS.readUnsignedByte() != 0xff
            || patchIS.readUnsignedByte() != 0x04) {

        throw new PatchException("magic string not found, aborting!");
    }

    while (true) {
        int command = patchIS.readUnsignedByte();
        if (command == EOF)
            break;
        int length;
        int offset;

        if (command <= DATA_MAX) {
            append(command, patchIS, outOS);
            continue;
        }

        switch (command) {
        case DATA_USHORT: // ushort, n bytes following; append
            length = patchIS.readUnsignedShort();
            append(length, patchIS, outOS);
            break;
        case DATA_INT: // int, n bytes following; append
            length = patchIS.readInt();
            append(length, patchIS, outOS);
            break;
        case COPY_USHORT_UBYTE:
            offset = patchIS.readUnsignedShort();
            length = patchIS.readUnsignedByte();
            copy(offset, length, source, outOS);
            break;
        case COPY_USHORT_USHORT:
            offset = patchIS.readUnsignedShort();
            length = patchIS.readUnsignedShort();
            copy(offset, length, source, outOS);
            break;
        case COPY_USHORT_INT:
            offset = patchIS.readUnsignedShort();
            length = patchIS.readInt();
            copy(offset, length, source, outOS);
            break;
        case COPY_INT_UBYTE:
            offset = patchIS.readInt();
            length = patchIS.readUnsignedByte();
            copy(offset, length, source, outOS);
            break;
        case COPY_INT_USHORT:
            offset = patchIS.readInt();
            length = patchIS.readUnsignedShort();
            copy(offset, length, source, outOS);
            break;
        case COPY_INT_INT:
            offset = patchIS.readInt();
            length = patchIS.readInt();
            copy(offset, length, source, outOS);
            break;
        case COPY_LONG_INT:
            long loffset = patchIS.readLong();
            length = patchIS.readInt();
            copy(loffset, length, source, outOS);
            break;
        default:
            throw new IllegalStateException("command " + command);
        }
    }
    outOS.flush();
}

From source file:edu.slu.action.ObjectAction.java

/**
 * Public API proxy to generate a new access token through Auth0.
 * /* w  ww.  j av  a 2 s.  c  o  m*/
 * @param refreshToken The refresh token given to the user on registration or generateNewRefreshToken
 * @return the Auth0 /oauth/token return's access_token property
 */
public void generateNewAccessToken() throws MalformedURLException, IOException, Exception {
    if (null != processRequestBody(request, false) && methodApproval(request, "token")) {
        System.out.println("Proxy generate an access token");
        JSONObject received = JSONObject.fromObject(content);
        JSONObject jsonReturn = new JSONObject();
        String authTokenURL = "https://cubap.auth0.com/oauth/token";
        JSONObject tokenRequestParams = new JSONObject();
        tokenRequestParams.element("grant_type", "refresh_token");
        tokenRequestParams.element("client_id", getRerumProperty("clientID"));
        tokenRequestParams.element("client_secret", getRerumProperty("rerumSecret"));
        tokenRequestParams.element("refresh_token", received.getString("refresh_token"));
        tokenRequestParams.element("redirect_uri", Constant.RERUM_BASE);
        try {
            URL auth0 = new URL(authTokenURL);
            HttpURLConnection connection = (HttpURLConnection) auth0.openConnection();
            connection.setRequestMethod("POST");
            connection.setConnectTimeout(5 * 1000);
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setRequestProperty("Content-Type", "application/json");
            connection.connect();
            DataOutputStream outStream = new DataOutputStream(connection.getOutputStream());
            //Pass in the user provided JSON for the body 
            outStream.writeBytes(tokenRequestParams.toString());
            outStream.flush();
            outStream.close();
            //Execute rerum server v1 request
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(connection.getInputStream(), "utf-8"));
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                //Gather rerum server v1 response
                sb.append(line);
            }
            reader.close();
            connection.disconnect();
            jsonReturn = JSONObject.fromObject(sb.toString());
            out = response.getWriter();
            response.setStatus(HttpServletResponse.SC_OK);
            out.write(mapper.writer().withDefaultPrettyPrinter().writeValueAsString(jsonReturn));
        } catch (java.net.SocketTimeoutException e) { //This specifically catches the timeout
            System.out.println("The Auth0 token endpoint is taking too long...");
            jsonReturn = new JSONObject();
            jsonReturn.element("error", "The Auth0 endpoint took too long");
            out = response.getWriter();
            response.setStatus(HttpServletResponse.SC_GATEWAY_TIMEOUT);
            out.write(mapper.writer().withDefaultPrettyPrinter().writeValueAsString(jsonReturn));
        } catch (IOException ex) {
            Logger.getLogger(ObjectAction.class.getName()).log(Level.SEVERE, null, ex);
            jsonReturn = new JSONObject();
            jsonReturn.element("error", "Couldn't access output stream");
            jsonReturn.element("msg", ex.toString());
            out = response.getWriter();
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            out.write(mapper.writer().withDefaultPrettyPrinter().writeValueAsString(jsonReturn));
        }
    }
}

From source file:edu.slu.action.ObjectAction.java

/**
* Public API proxy to generate a new refresh token through Auth0.
* 
* @param authCode An authorization code generated by the Auth0 /authorize call.
* @return the Auth0 /oauth/token return's refresh_token value
*//* w w  w  .ja  va 2s.c  o m*/
public void generateNewRefreshToken() throws MalformedURLException, IOException, Exception {
    if (null != processRequestBody(request, false) && methodApproval(request, "token")) {
        System.out.println("Proxy generate a refresh token");
        JSONObject received = JSONObject.fromObject(content);
        JSONObject jsonReturn = new JSONObject();
        String authTokenURL = "https://cubap.auth0.com/oauth/token";
        JSONObject tokenRequestParams = new JSONObject();

        tokenRequestParams.element("grant_type", "authorization_code");
        tokenRequestParams.element("client_id", getRerumProperty("clientID"));
        tokenRequestParams.element("code", received.getString("authorization_code"));
        tokenRequestParams.element("client_secret", getRerumProperty("rerumSecret"));
        tokenRequestParams.element("redirect_uri", Constant.RERUM_BASE);
        try {
            URL auth0 = new URL(authTokenURL);
            HttpURLConnection connection = (HttpURLConnection) auth0.openConnection();
            connection.setRequestMethod("POST");
            connection.setConnectTimeout(5 * 1000);
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setRequestProperty("Content-Type", "application/json; charset=utf-8");
            connection.connect();
            DataOutputStream outStream = new DataOutputStream(connection.getOutputStream());
            //Pass in the user provided JSON for the body 
            outStream.writeBytes(tokenRequestParams.toString());
            outStream.flush();
            outStream.close();
            //Execute rerum server v1 request
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(connection.getInputStream(), "utf-8"));
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                //Gather rerum server v1 response
                sb.append(line);
            }
            reader.close();
            connection.disconnect();
            jsonReturn = JSONObject.fromObject(sb.toString());
            out = response.getWriter();
            response.setStatus(HttpServletResponse.SC_OK);
            out.write(mapper.writer().withDefaultPrettyPrinter().writeValueAsString(jsonReturn));
        } catch (java.net.SocketTimeoutException e) { //This specifically catches the timeout
            System.out.println("The Auth0 token endpoint is taking too long...");
            jsonReturn = new JSONObject(); //We were never going to get a response, so return an empty object.
            jsonReturn.element("error", "The Auth0 endpoint took too long");
            out = response.getWriter();
            response.setStatus(HttpServletResponse.SC_GATEWAY_TIMEOUT);
            out.write(mapper.writer().withDefaultPrettyPrinter().writeValueAsString(jsonReturn));
        } catch (IOException ex) {
            Logger.getLogger(ObjectAction.class.getName()).log(Level.SEVERE, null, ex);
            jsonReturn = new JSONObject();
            jsonReturn.element("error", "Couldn't access output stream");
            jsonReturn.element("msg", ex.toString());
            out = response.getWriter();
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            out.write(mapper.writer().withDefaultPrettyPrinter().writeValueAsString(jsonReturn));
        }
    }
}

From source file:com.symbian.driver.core.controller.tasks.TEFTask.java

/**
 * @param aVisitor// w w  w  .j a v  a 2 s .c om
 * @param aTestExecuteScript
 * @param lExecuteOnDevice
 * @param aTask
 * @return The last execption raised when running UCC.
 * @throws JStatException
 */
private boolean runUCC(List<String> aArgs, Task aTask) {
    boolean lReturn = true;
    Socket lUccSocket = null;
    DataOutputStream lSocketOut = null;
    DataInputStream lSocketIn = null;
    int lRunNumber = 0;
    int lUccPort = -1;
    String lUccAddress = null;
    IDeviceComms.ISymbianProcess lProcess = null;

    try {
        String[] lUccSplit = TDConfig.getInstance().getPreference(TDConfig.UCC_IP_ADDRESS).split(":");
        lRunNumber = TDConfig.getInstance().getPreferenceInteger(TDConfig.RUN_NUMBER);

        lUccAddress = lUccSplit[0];
        lUccPort = Integer.parseInt(lUccSplit[1]);
    } catch (ParseException lParseException) {
        LOGGER.log(Level.SEVERE, "Could not get configuration for UCC.", lParseException);
        iExceptions.put(lParseException, ESeverity.ERROR);
        lReturn = false;
    } catch (NumberFormatException lNumberFormatException) {
        LOGGER.log(Level.SEVERE, "Could not parse the port number for UCC.", lNumberFormatException);
        iExceptions.put(lNumberFormatException, ESeverity.ERROR);
        lReturn = false;
    }

    if (lUccAddress == null || lUccAddress.equals("") || lUccPort < 0) {
        iExceptions.put(
                new UnknownHostException("Please specify a valid UCC address for example 192.168.0.1:3000"),
                ESeverity.ERROR);
        return false;
    }

    // Run the test
    try {
        LOGGER.info("Running UCC with:\n\tAddress: " + lUccAddress + "\n\tUCC Port:" + lUccPort);

        lUccSocket = new Socket(lUccAddress, lUccPort);
        lSocketOut = new DataOutputStream(lUccSocket.getOutputStream());
        lSocketIn = new DataInputStream(lUccSocket.getInputStream());

        LOGGER.fine("Starting UCC while still polling");
        lProcess = iDeviceProxy.createSymbianProcess();
        if (lProcess != null) {
            // run and don't wait
            if (!lProcess.runCommand(TEST_EXECUTE, aArgs, aTask.getTimeout() * 1000, false)) {
                iExceptions.put(new Exception("Failed to run TEF for UCC."), ESeverity.ERROR);
                lReturn = false;
            }

            // Tell UCC that the test has started.
            LOGGER.fine("Writing to UCC socket: " + lRunNumber);
            lSocketOut.writeInt(lRunNumber);
            lSocketOut.flush();

            int lUCCReply = lSocketIn.readInt();
            LOGGER.fine("UCC Reply: " + lUCCReply);
        }

    } catch (UnknownHostException lUnknownHostException) {
        LOGGER.log(Level.SEVERE, "Could not find UCC host", lUnknownHostException);
        iExceptions.put(lUnknownHostException, ESeverity.ERROR);
        return false;
    } catch (IOException lIOException) {
        LOGGER.log(Level.SEVERE,
                "IO Exception during UCC testing: " + lIOException.getMessage() + (lUccSocket != null
                        ? "\nUcc Socket Connected: " + lUccSocket.isConnected() + "\nUcc Socket InputShutdown: "
                                + lUccSocket.isInputShutdown() + "\nUcc Socket OutputShutdown:"
                                + lUccSocket.isOutputShutdown() + "\nUcc Socket Bound: " + lUccSocket.isBound()
                        : "\nUcc Socket is NULL"),
                lIOException);
        iExceptions.put(lIOException, ESeverity.ERROR);
        return false;
    } finally {

        // Close UCC
        if (lSocketOut != null) {
            try {
                LOGGER.log(Level.FINE, "Closing Socket Out.");
                lUccSocket.shutdownInput();
                lUccSocket.shutdownOutput();
                lSocketOut.close();
            } catch (IOException lIOException) {
                LOGGER.log(Level.SEVERE, "Could not close UCC Out socket.", lIOException);
                iExceptions.put(lIOException, ESeverity.ERROR);
            }
        }
        if (lSocketIn != null) {
            try {
                LOGGER.log(Level.FINE, "Closing Socket In.");
                lSocketIn.close();
            } catch (IOException lIOException) {
                LOGGER.log(Level.SEVERE, "Could not close UCC In socket.", lIOException);
                iExceptions.put(lIOException, ESeverity.ERROR);
            }
        }
        if (lUccSocket != null) {
            try {
                LOGGER.log(Level.FINE, "Closing Socket UCC.");
                lUccSocket.close();
            } catch (IOException lIOException) {
                LOGGER.log(Level.SEVERE, "Could not close UCC socket.", lIOException);
                iExceptions.put(lIOException, ESeverity.ERROR);
            }
        }

        if (!lUccSocket.isClosed()) {
            LOGGER.warning("Could not close the UCC sockets properly.");
        }

        lSocketOut = null;
        lSocketIn = null;
        lUccSocket = null;

        // Poll TEF Test
        if (!lProcess.join()) {
            iExceptions.put(new Exception("Coud not join UCC-TEF Process"), ESeverity.ERROR);
            lReturn = false;
        }

    }
    return lReturn;
}

From source file:com.android.launcher2.Launcher.java

private static void writeConfiguration(Context context, LocaleConfiguration configuration) {
    DataOutputStream out = null;
    try {//from   www . j  a va 2  s  . c om
        out = new DataOutputStream(context.openFileOutput(PREFERENCES, MODE_PRIVATE));
        out.writeUTF(configuration.locale);
        out.writeInt(configuration.mcc);
        out.writeInt(configuration.mnc);
        out.flush();
    } catch (FileNotFoundException e) {
        // Ignore
    } catch (IOException e) {
        //noinspection ResultOfMethodCallIgnored
        context.getFileStreamPath(PREFERENCES).delete();
    } finally {
        if (out != null) {
            try {
                out.close();
            } catch (IOException e) {
                // Ignore
            }
        }
    }
}