Example usage for java.io DataInputStream readLine

List of usage examples for java.io DataInputStream readLine

Introduction

In this page you can find the example usage for java.io DataInputStream readLine.

Prototype

@Deprecated
public final String readLine() throws IOException 

Source Link

Document

See the general contract of the readLine method of DataInput.

Usage

From source file:com.polyvi.xface.extension.filetransfer.XFileTransferExt.java

/**
 * ????XFileUploadResult/*from  www  .j  a v a 2 s.  c  o m*/
 * @param result        js
 * @param conn          Http
 */
private void setUploadResult(XFileUploadResult result, HttpURLConnection conn) {
    StringBuffer responseString = new StringBuffer("");
    DataInputStream inStream = null;
    try {
        inStream = new DataInputStream(conn.getInputStream());
        String line = null;
        while ((line = inStream.readLine()) != null) {
            responseString.append(line);
        }

        // XFileUploadResult?
        result.setResponseCode(conn.getResponseCode());
        result.setResponse(responseString.toString());
        inStream.close();
    } catch (FileNotFoundException e) {
        XLog.e(CLASS_NAME, e.toString());
    } catch (IOException e) {
        XLog.e(CLASS_NAME, e.toString());
    }
}

From source file:com.ephesoft.dcma.filebound.FileBoundExporter.java

@SuppressWarnings("deprecation")
private String fetchDocNameMapping(final String docName, final String batchClassIdentifier) {
    String returnValue = "";
    final String filePath = batchSchemaService.getBaseFolderLocation() + File.separator + batchClassIdentifier
            + File.separator + FileBoundConstants.MAPPING_FOLDER_NAME + File.separator
            + FileBoundConstants.PROPERTY_FILE_NAME;
    DataInputStream dataInputStream = null;
    FileInputStream fileInputStream = null;
    try {/* www  .ja  v  a  2  s  . c  o m*/
        fileInputStream = new FileInputStream(filePath);
        dataInputStream = new DataInputStream(fileInputStream);
        String eachLine = dataInputStream.readLine();
        while (eachLine != null) {
            if (eachLine.length() > 0) {
                final String[] keyValue = eachLine.split(FileBoundConstants.MAPPING_SEPERATOR);
                if (keyValue != null && keyValue.length > 0 && keyValue[0].equalsIgnoreCase(docName)) {
                    returnValue = keyValue[1];
                    break;
                }
            }
            eachLine = dataInputStream.readLine();
        }
    } catch (IOException e) {
        LOGGER.error("Error occured in reading from properties file.");
    } finally {
        try {
            if (dataInputStream != null) {
                dataInputStream.close();
            }
            if (fileInputStream != null) {
                fileInputStream.close();
            }
        } catch (IOException e) {
            LOGGER.debug("DataInputStream cannot be closed.");
        }
    }
    return returnValue;
}

From source file:com.polyvi.xface.extension.advancedfiletransfer.FileUploader.java

/**
 * ????/*  ww  w.  jav  a 2 s.  c om*/
 *
 * @param httpConnection
 *            :http
 * @return 1?? 0? -1??
 */
private int getResultCode(HttpURLConnection httpConnection) {
    DataInputStream dataInputStream = null;
    try {
        if (HttpURLConnection.HTTP_OK != httpConnection.getResponseCode()) {
            return RESULT_CODE_ERROR;
        }
        // ??RETURN_CODE:1
        dataInputStream = new DataInputStream(httpConnection.getInputStream());
        // ???response?
        String data = dataInputStream.readLine();
        int resultCode = Integer.valueOf(data.substring(data.indexOf(":") + 1));
        return (resultCode == RESULT_CODE_CHUNK_RECEIVED || resultCode == RESULT_CODE_FILE_RECEIVED)
                ? resultCode
                : RESULT_CODE_ERROR;
    } catch (Exception e) {
        e.printStackTrace();
        return RESULT_CODE_ERROR;
    } finally {
        try {
            if (null != dataInputStream) {
                dataInputStream.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

From source file:org.skt.runtime.html5apis.file.FileTransfer.java

/**
 * Uploads the specified file to the server URL provided using an HTTP multipart request.
 * @param source        Full path of the file on the file system
 * @param target        URL of the server to receive the file
 * @param args          JSON Array of args
 *
 * args[2] fileKey       Name of file request parameter
 * args[3] fileName      File name to be used on server
 * args[4] mimeType      Describes file content type
 * args[5] params        key:value pairs of user-defined parameters
 * @return FileUploadResult containing result of upload request
 *//*from w ww  .  ja v a  2  s  .  c  o  m*/
private PluginResult upload(String source, String target, JSONArray args) {
    Log.d(LOG_TAG, "upload " + source + " to " + target);

    HttpURLConnection conn = null;
    try {
        // Setup the options
        String fileKey = getArgument(args, 2, "file");
        String fileName = getArgument(args, 3, "image.jpg");
        String mimeType = getArgument(args, 4, "image/jpeg");
        JSONObject params = args.optJSONObject(5);
        if (params == null) {
            params = new JSONObject();
        }
        boolean trustEveryone = args.optBoolean(6);
        boolean chunkedMode = args.optBoolean(7) || args.isNull(7); //Always use chunked mode unless set to false as per API

        Log.d(LOG_TAG, "fileKey: " + fileKey);
        Log.d(LOG_TAG, "fileName: " + fileName);
        Log.d(LOG_TAG, "mimeType: " + mimeType);
        Log.d(LOG_TAG, "params: " + params);
        Log.d(LOG_TAG, "trustEveryone: " + trustEveryone);
        Log.d(LOG_TAG, "chunkedMode: " + chunkedMode);

        // Create return object
        FileUploadResult result = new FileUploadResult();

        // Get a input stream of the file on the phone
        FileInputStream fileInputStream = (FileInputStream) getPathFromUri(source);

        DataOutputStream dos = null;

        int bytesRead, bytesAvailable, bufferSize;
        long totalBytes;
        byte[] buffer;
        int maxBufferSize = 8096;

        //------------------ CLIENT REQUEST
        // open a URL connection to the server
        URL url = new URL(target);

        // Open a HTTP connection to the URL based on protocol
        if (url.getProtocol().toLowerCase().equals("https")) {
            // Using standard HTTPS connection. Will not allow self signed certificate
            if (!trustEveryone) {
                conn = (HttpsURLConnection) url.openConnection();
            }
            // Use our HTTPS connection that blindly trusts everyone.
            // This should only be used in debug environments
            else {
                // Setup the HTTPS connection class to trust everyone
                trustAllHosts();
                HttpsURLConnection https = (HttpsURLConnection) url.openConnection();
                // Save the current hostnameVerifier
                defaultHostnameVerifier = https.getHostnameVerifier();
                // Setup the connection not to verify hostnames
                https.setHostnameVerifier(DO_NOT_VERIFY);
                conn = https;
            }
        }
        // Return a standard HTTP connection
        else {
            conn = (HttpURLConnection) url.openConnection();
        }

        // Allow Inputs
        conn.setDoInput(true);

        // Allow Outputs
        conn.setDoOutput(true);

        // Don't use a cached copy.
        conn.setUseCaches(false);

        // Use a post method.
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + BOUNDARY);

        // Handle the other headers
        try {
            JSONObject headers = params.getJSONObject("headers");
            for (Iterator iter = headers.keys(); iter.hasNext();) {
                String headerKey = iter.next().toString();
                conn.setRequestProperty(headerKey, headers.getString(headerKey));
            }
        } catch (JSONException e1) {
            // No headers to be manipulated!
        }

        // Set the cookies on the response
        String cookie = CookieManager.getInstance().getCookie(target);
        if (cookie != null) {
            conn.setRequestProperty("Cookie", cookie);
        }

        /*
        * Store the non-file portions of the multipart data as a string, so that we can add it
        * to the contentSize, since it is part of the body of the HTTP request.
        */
        String extraParams = "";
        try {
            for (Iterator iter = params.keys(); iter.hasNext();) {
                Object key = iter.next();
                if (!String.valueOf(key).equals("headers")) {
                    extraParams += LINE_START + BOUNDARY + LINE_END;
                    extraParams += "Content-Disposition: form-data; name=\"" + key.toString() + "\";";
                    extraParams += LINE_END + LINE_END;
                    extraParams += params.getString(key.toString());
                    extraParams += LINE_END;
                }
            }
        } catch (JSONException e) {
            Log.e(LOG_TAG, e.getMessage(), e);
        }

        extraParams += LINE_START + BOUNDARY + LINE_END;
        extraParams += "Content-Disposition: form-data; name=\"" + fileKey + "\";" + " filename=\"";

        String midParams = "\"" + LINE_END + "Content-Type: " + mimeType + LINE_END + LINE_END;
        String tailParams = LINE_END + LINE_START + BOUNDARY + LINE_START + LINE_END;

        // Should set this up as an option
        if (chunkedMode) {
            conn.setChunkedStreamingMode(maxBufferSize);
        } else {
            int stringLength = extraParams.getBytes("UTF-8").length + midParams.getBytes("UTF-8").length
                    + tailParams.getBytes("UTF-8").length + fileName.getBytes("UTF-8").length;
            Log.d(LOG_TAG, "String Length: " + stringLength);
            int fixedLength = (int) fileInputStream.getChannel().size() + stringLength;
            Log.d(LOG_TAG, "Content Length: " + fixedLength);
            conn.setFixedLengthStreamingMode(fixedLength);
        }

        dos = new DataOutputStream(conn.getOutputStream());
        dos.write(extraParams.getBytes("UTF-8"));
        //We don't want to chagne encoding, we just want this to write for all Unicode.
        dos.write(fileName.getBytes("UTF-8"));
        dos.write(midParams.getBytes("UTF-8"));

        // create a buffer of maximum size
        bytesAvailable = fileInputStream.available();
        bufferSize = Math.min(bytesAvailable, maxBufferSize);
        buffer = new byte[bufferSize];

        // read file and write it into form...
        bytesRead = fileInputStream.read(buffer, 0, bufferSize);
        totalBytes = 0;

        while (bytesRead > 0) {
            totalBytes += bytesRead;
            result.setBytesSent(totalBytes);
            dos.write(buffer, 0, bufferSize);
            bytesAvailable = fileInputStream.available();
            bufferSize = Math.min(bytesAvailable, maxBufferSize);
            bytesRead = fileInputStream.read(buffer, 0, bufferSize);
        }

        // send multipart form data necesssary after file data...
        dos.write(tailParams.getBytes("UTF-8"));

        // close streams
        fileInputStream.close();
        dos.flush();
        dos.close();

        //------------------ read the SERVER RESPONSE
        StringBuffer responseString = new StringBuffer("");
        DataInputStream inStream;
        try {
            inStream = new DataInputStream(conn.getInputStream());
        } catch (FileNotFoundException e) {
            Log.e(LOG_TAG, e.toString(), e);
            throw new IOException("Received error from server");
        }

        String line;
        while ((line = inStream.readLine()) != null) {
            responseString.append(line);
        }
        Log.d(LOG_TAG, "got response from server");
        Log.d(LOG_TAG, responseString.toString());

        // send request and retrieve response
        result.setResponseCode(conn.getResponseCode());
        result.setResponse(responseString.toString());

        inStream.close();

        // Revert back to the proper verifier and socket factories
        if (trustEveryone && url.getProtocol().toLowerCase().equals("https")) {
            ((HttpsURLConnection) conn).setHostnameVerifier(defaultHostnameVerifier);
            HttpsURLConnection.setDefaultSSLSocketFactory(defaultSSLSocketFactory);
        }

        Log.d(LOG_TAG, "****** About to return a result from upload");
        return new PluginResult(PluginResult.Status.OK, result.toJSONObject());

    } catch (FileNotFoundException e) {
        JSONObject error = createFileTransferError(FILE_NOT_FOUND_ERR, source, target, conn);
        Log.e(LOG_TAG, error.toString(), e);
        return new PluginResult(PluginResult.Status.IO_EXCEPTION, error);
    } catch (MalformedURLException e) {
        JSONObject error = createFileTransferError(INVALID_URL_ERR, source, target, conn);
        Log.e(LOG_TAG, error.toString(), e);
        return new PluginResult(PluginResult.Status.IO_EXCEPTION, error);
    } catch (IOException e) {
        JSONObject error = createFileTransferError(CONNECTION_ERR, source, target, conn);
        Log.e(LOG_TAG, error.toString(), e);
        return new PluginResult(PluginResult.Status.IO_EXCEPTION, error);
    } catch (JSONException e) {
        Log.e(LOG_TAG, e.getMessage(), e);
        return new PluginResult(PluginResult.Status.JSON_EXCEPTION);
    } catch (Throwable t) {
        // Shouldn't happen, but will
        JSONObject error = createFileTransferError(CONNECTION_ERR, source, target, conn);
        Log.wtf(LOG_TAG, error.toString(), t);
        return new PluginResult(PluginResult.Status.IO_EXCEPTION, error);
    } finally {
        if (conn != null) {
            conn.disconnect();
        }
    }
}

From source file:org.siphon.d2js.EmbedSqlTranslator.java

private String getLineNear(String code, int pos) {

    DataInputStream inputStream = new DataInputStream(IOUtils.toInputStream(code));

    String line = null;/*from ww w .j av a2s  .c  o  m*/
    int lineHead = 0;
    int lineIndex = 0;
    try {
        while (inputStream.available() >= code.length() - pos) {
            lineHead = code.length() - inputStream.available();
            line = inputStream.readLine();
            lineIndex++;
        }
    } catch (IOException e) {
        // e.printStackTrace();
    }

    String s = "LN " + lineIndex + ":" + (pos - lineHead + 1) + " " + line;

    return s;
}

From source file:com.lines.activitys.SettingsActivity.java

/**
 * Delete the databases that already exist, and populate a new one with the
 * user's selected script//from www .  jav  a 2 s . c om
 * 
 * @param script
 *            - script file we are populating the database with
 * @throws IOException
 */
private void loadScript(String script) throws IOException {

    // Get adapters
    mDbAdapter = app.getPlayAdapter();
    mNDbAdapter = app.getNoteAdapter();

    // Reset tables for Script and Notes
    mDbAdapter.deleteTable();
    mNDbAdapter.deleteTable();

    String text = "";
    InputStream is;
    BufferedInputStream bis;
    DataInputStream dis;
    String line = null;
    int lineNo = -1;
    int actNo = 0;
    int pageNo = 1;

    // Add file extension back on
    script = script + ".txt";
    File file = new File(Environment.getExternalStorageDirectory() + "/learnyourlines/scripts/" + script);

    // Try to open the file, and alert the user if file doesn't exist
    try {
        is = new FileInputStream(file);
        bis = new BufferedInputStream(is);
        dis = new DataInputStream(bis);
    } catch (IOException e) {
        e.printStackTrace();
        return;
    }

    // Read line-by-line and pick out the relevent information
    while (dis.available() != 0) {

        lineNo++;

        line = dis.readLine();

        // Split line into array of words
        String words[] = line.split("\\s+");
        String firstWord = words[0];

        // Keep a count of which Act we're on
        if (firstWord.equals("FIRST") || firstWord.equals("SECOND") || firstWord.equals("THIRD")) {
            actNo++;
        }

        // Keep count of what page we're on (23 lines/page)
        if ((lineNo % 23) == 0 && lineNo != 0) {
            pageNo++;
        }

        // Check our firstWord is a character name
        if (isCharacter(firstWord)) {
            // If the first word doesn't contain a period (.) then we need
            // to take the second word as well as part of the character
            // name.
            if (!firstWord.contains(".")) {
                firstWord += " " + words[1];

                text = "";
                for (int j = 2; j < words.length; j++) {
                    text += words[j] + " ";
                }
                // If the second word is "and" then it is two characters
                // delievering a line and we need to get the other
                // characters name.
                if (words[1].equals("and")) {
                    firstWord += " " + words[2] + ".";

                    text = "";
                    for (int j = 3; j < words.length; j++) {
                        text += words[j] + " ";
                    }
                    // Handle the rest of the data that hasn't yet been
                    // filtered
                } else if (!words[1].contains(".")) {
                    firstWord = "STAGE.";

                    text = "";
                    for (int j = 0; j < words.length; j++) {
                        text += words[j] + " ";
                    }
                }
            }
            // If the firstWord isn't a character, then it is a stage
            // direction
        } else {
            firstWord = "STAGE.";

            text = "";
            for (int j = 0; j < words.length; j++) {
                text += words[j] + " ";
            }
        }

        // If we didn't manage to populate "text" from the previous if
        // statements, then do it here.
        if (text.equals("")) {
            for (int j = 1; j < words.length; j++) {
                text += words[j] + " ";
            }
        }

        // Once we have all the data picked out from current line in text
        // file, create a new row in the database. Filter out text we don't
        // want in our database.
        if (!isAllUpperCase(words[0])) {
            firstWord = firstWord.substring(0, firstWord.length() - 1);
            mDbAdapter.createPlay(lineNo, firstWord, text, actNo, pageNo, "N", "N", 0, 0, 0);
            // If we're not adding to the database, then we need to reduce
            // the line count.
        } else {
            lineNo--;
        }

        // Clear "text" before we read next line
        text = "";
    }

    // Cleanup
    is.close();
    bis.close();
    dis.close();

    finish();

}

From source file:com.intel.xdk.device.Device.java

public void getRemoteData(String requestUrl, String requestMethod, String requestBody,
        CallbackContext callbackContext) {
    try {//from ww  w . j av  a2 s . c o  m
        URL url = new URL(requestUrl);
        connection = (HttpURLConnection) url.openConnection();

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

        connection.setRequestMethod(requestMethod);

        //Write requestBody
        DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
        outputStream.writeBytes(requestBody);
        outputStream.flush();
        outputStream.close();

        //Get response code and response message
        int responseCode = connection.getResponseCode();
        String responseMessage = connection.getResponseMessage();

        //Get response Message
        DataInputStream inputStream = new DataInputStream(connection.getInputStream());
        if (responseCode == 200) {
            String temp;
            String responseBody = "";
            while ((temp = inputStream.readLine()) != null) {
                responseBody += temp;
            }
            callbackContext.success(responseBody);
        } else {
            callbackContext.error("Fail to get the response, response code: " + responseCode
                    + ", response message: " + responseMessage);
        }

        inputStream.close();
    } catch (IOException e) {
        Log.d("request", e.getMessage());
    }
}

From source file:com.intel.xdk.device.Device.java

public void getRemoteDataWithID(String requestUrl, String requestMethod, String requestBody, int uuid,
        String successCallback, String errorCallback) {
    try {//from  w  ww  . j  a  va 2 s  . c  o m
        URL url = new URL(requestUrl);
        connection = (HttpURLConnection) url.openConnection();

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

        connection.setRequestMethod(requestMethod);

        //Write requestBody
        DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
        outputStream.writeBytes(requestBody);
        outputStream.writeBytes("&uuid=" + uuid);
        outputStream.flush();
        outputStream.close();

        //Get response code and response message
        int responseCode = connection.getResponseCode();
        String responseMessage = connection.getResponseMessage();

        //Get response Message
        DataInputStream inputStream = new DataInputStream(connection.getInputStream());
        if (responseCode == 200) {
            String temp;
            String responseBody = "";
            while ((temp = inputStream.readLine()) != null) {
                responseBody += temp;
            }
            //callbackContext.success(responseBody);
            String js = "javascript:" + successCallback + "(" + uuid + ", '" + responseBody + "');";
            injectJS(js);
        } else {
            //callbackContext.error("Fail to get the response, response code: " + responseCode + ", response message: " + responseMessage);
            String js = "javascript:" + errorCallback + "(" + uuid + ", '" + "Fail to get the response" + "');";
            injectJS(js);
        }

        inputStream.close();
    } catch (IOException e) {
        Log.d("request", e.getMessage());
    }
}

From source file:com.intel.xdk.device.Device.java

public void getRemoteData(String requestUrl, String requestMethod, String requestBody, String successCallback,
        String errorCallback) {/* w w w.  j  a  v  a2s. com*/
    Log.d("getRemoteData", "url: " + requestUrl + ", method: " + requestMethod + ", body: " + requestBody);

    try {
        URL url = new URL(requestUrl);
        connection = (HttpURLConnection) url.openConnection();

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

        connection.setRequestMethod(requestMethod);

        //Write requestBody
        DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
        outputStream.writeBytes(requestBody);
        outputStream.flush();
        outputStream.close();

        //Get response code and response message
        int responseCode = connection.getResponseCode();
        String responseMessage = connection.getResponseMessage();

        //Get response Message
        DataInputStream inputStream = new DataInputStream(connection.getInputStream());
        if (responseCode == 200) {
            String temp;
            String responseBody = "";
            while ((temp = inputStream.readLine()) != null) {
                responseBody += temp;
            }
            //callbackContext.success(responseBody);
            String js = "javascript:" + successCallback + "('" + responseBody + "');";
            injectJS(js);
        } else {
            //callbackContext.error("Fail to get the response, response code: " + responseCode + ", response message: " + responseMessage);
            String js = "javascript:" + errorCallback + "(" + "'response code :" + responseCode + "');";
            injectJS(js);
        }

        inputStream.close();
    } catch (IOException e) {
        Log.d("request", e.getMessage());
    }
}

From source file:com.intel.xdk.device.Device.java

public void getRemoteDataWithID(String requestUrl, String requestMethod, String requestBody, int uuid,
        CallbackContext callbackContext) {
    try {//  w ww  .j a  v a  2 s  . c o m
        URL url = new URL(requestUrl);
        connection = (HttpURLConnection) url.openConnection();

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

        connection.setRequestMethod(requestMethod);

        //Write requestBody
        DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
        outputStream.writeBytes(requestBody);
        outputStream.writeBytes("&uuid=" + uuid);
        outputStream.flush();
        outputStream.close();

        //Get response code and response message
        int responseCode = connection.getResponseCode();
        String responseMessage = connection.getResponseMessage();

        //Get response Message
        DataInputStream inputStream = new DataInputStream(connection.getInputStream());
        if (responseCode == 200) {
            String temp;
            String responseBody = "";
            while ((temp = inputStream.readLine()) != null) {
                responseBody += temp;
            }
            callbackContext.success(uuid + ", " + responseBody);
            //String js = "javascript:" + successCallback + "(" + uuid + ", '" + responseBody + "');";
            //injectJS(js);
        } else {
            callbackContext.error(uuid + ", Fail to get the response, response code: " + responseCode
                    + ", response message: " + responseMessage);
            //String js = "javascript:" + errorCallback + "(" + uuid + ", '" + "Fail to get the response" + "');";
            //injectJS(js);
        }

        inputStream.close();
    } catch (IOException e) {
        Log.d("request", e.getMessage());
    }
}