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:cloudMe.CloudMeAPI.java

private String getResponse(HttpResponse response) {
    try {/*from  ww w .j a  va2s .c o  m*/
        DataInputStream stream = new DataInputStream(response.getEntity().getContent());
        StringBuffer buf = new StringBuffer();
        String tmp;
        while ((tmp = stream.readLine()) != null) {
            buf.append(tmp);
        }
        stream.close();
        return buf.toString();
    } catch (IOException e) {
        return "IOException: " + e.getMessage();
    }
}

From source file:net.jradius.webservice.WebServiceListener.java

private Map<String, String> getHeaders(DataInputStream reader) throws IOException {
    LinkedHashMap<String, String> map = new LinkedHashMap<String, String>();
    String line;/*  w ww  .ja va2s.co m*/
    do {
        line = reader.readLine().trim();
        if (line != null && line.length() > 0) {
            String[] parts = line.split(":", 2);
            if (parts != null && parts.length == 2) {
                map.put(parts[0].toLowerCase().trim(), parts[1].trim());
            } else
                break;
        } else
            break;
    } while (true);

    return map;
}

From source file:net.jradius.webservice.WebServiceListener.java

public JRadiusEvent parseRequest(ListenerRequest listenerRequest, ByteBuffer byteBuffer,
        InputStream inputStream) throws IOException, WebServiceException {
    DataInputStream reader = new DataInputStream(inputStream);
    WebServiceRequest request = new WebServiceRequest();

    String line = null;//from   www.ja v  a 2 s  .  com

    try {
        line = reader.readLine();
    } catch (SocketException e) {
        return null;
    }

    if (line == null)
        throw new WebServiceException("Invalid relay request");

    StringTokenizer tokens = new StringTokenizer(line);
    String method = tokens.nextToken();
    String uri = tokens.nextToken();
    String httpVersion = tokens.nextToken();

    if ("GET".equals(method))
        request.setMethod(WebServiceRequest.GET);
    else if ("POST".equals(method))
        request.setMethod(WebServiceRequest.POST);
    else if ("PUT".equals(method))
        request.setMethod(WebServiceRequest.PUT);
    else
        throw new WebServiceException("Does not handle HTTP request method: " + method);

    request.setHttpVersion(httpVersion);

    try {
        request.setUri(new URI(uri));
    } catch (URISyntaxException e) {
        throw new WebServiceException(e.getMessage());
    }

    Map<String, String> headers = getHeaders(reader);
    request.setHeaderMap(headers);

    String clen = headers.get("content-length");
    if (clen != null) {
        request.setContent(getContent(reader, Integer.parseInt(clen)));
    }

    return request;
}

From source file:BA.Server.FileUpload.java

/** 
 * Handles the HTTP <code>POST</code> method.
 * @param request servlet request//  w w w . ja  v  a  2 s . c  om
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@SuppressWarnings("unchecked")
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    PrintWriter outp = resp.getWriter();

    PrintWriter writer = null;

    try {
        writer = resp.getWriter();
    } catch (IOException ex) {
        log(FileUpload.class.getName() + "has thrown an exception: " + ex.getMessage());
    }

    StringBuffer buff = new StringBuffer();

    File file1 = (File) req.getAttribute("file");

    if (file1 == null || !file1.exists()) {
        System.out.println("File does not exist");
    } else if (file1.isDirectory()) {
        System.out.println("File is a directory");
    }

    else {
        File outputFile = new File("/tmp/" + req.getParameter("file"));
        file1.renameTo(outputFile);

        FileInputStream f = new FileInputStream(outputFile);

        // Here BufferedInputStream is added for fast reading.
        BufferedInputStream bis = new BufferedInputStream(f);
        DataInputStream dis = new DataInputStream(bis);
        int i = 0;
        String result = "";

        writer.write("<html>");
        writer.write("<head><script type='text/javascript'>");
        while (dis.available() != 0) {
            String current = dis.readLine();

            if (((String) req.getParameter("uploadType")).equals("equations")) {
                if (FormulaTester.testInput(current) == -1) {
                    writer.write("window.opener.addTabExt(\"" + current + "\" , \"" + req.getParameter("file")
                            + "\");");
                }
            } else {
                writer.write("window.opener.addMacroExt(\"" + current + "\");");
            }
            i++;

        }

        writer.write("this.close();</script></head>");
        writer.write("</script></head>");
        writer.write("<body>");
        writer.write("</body>");
        writer.write("</html>");

        writer.flush();
        writer.close();

        dis.close();
        bis.close();
        f.close();
        outputFile.delete();

    }
}

From source file:com.acme.io.JsonLoader.java

/**
 * Get a schema for the data to be loaded.  
 * @param location Location as returned by 
 * {@link LoadFunc#relativeToAbsolutePath(String, org.apache.hadoop.fs.Path)}
 * @param job The {@link Job} object - this should be used only to obtain 
 * cluster properties through {@link Job#getConfiguration()} and not to
 * set/query any runtime job information.  
 * @return schema for the data to be loaded. This schema should represent
 * all tuples of the returned data.  If the schema is unknown or it is
 * not possible to return a schema that represents all returned data,
 * then null should be returned. The schema should not be affected by
 * pushProjection, ie. getSchema should always return the original schema
 * even after pushProjection/*from w  ww .  ja  v a  2 s .c  o  m*/
 * @throws IOException if an exception occurs while determining the schema
 */
public ResourceSchema getSchema(String location, Job job) throws IOException {
    // Open the schema file and read the schema
    // Get an HDFS handle.
    FileSystem fs = FileSystem.get(job.getConfiguration());
    DataInputStream in = fs.open(new Path(location + "/_schema"));
    String line = in.readLine();
    in.close();

    // Parse the schema
    ResourceSchema s = new ResourceSchema(Utils.getSchemaFromString(line));
    if (s == null) {
        throw new IOException("Unable to parse schema found in file " + location + "/_schema");
    }

    // Now that we have determined the schema, store it in our
    // UDFContext properties object so we have it when we need it on the
    // backend
    UDFContext udfc = UDFContext.getUDFContext();
    Properties p = udfc.getUDFProperties(this.getClass(), new String[] { udfcSignature });
    p.setProperty("pig.jsonloader.schema", line);

    return s;
}

From source file:com.maverick.ssl.https.HttpsURLConnection.java

void readResponse(PushbackInputStream in) throws IOException {
    DataInputStream data = new DataInputStream(in);
    String line;//  w w  w  .j a  va2  s  .  co  m
    while (((line = data.readLine()) != null) && (line.length() > 0)) {
        headers.addElement(line);
        int index = line.indexOf(':');
        if (index >= 0) {
            String key = line.substring(0, index);
            String value = line.substring(index + 1).trim();
            headerKeys.addElement(key);
            headerValues.put(key.toLowerCase(), value);
        } else {
            // If the first line back is not a header, the unread as the
            // rest is going to be content
            if (headerValues.size() == 0) {

                // This is a response code
                if (line.startsWith("HTTP/")) { //$NON-NLS-1$
                    try {
                        int idx = line.indexOf(' ');
                        while (line.charAt(++idx) == ' ') {
                            ;
                        }
                        responseMessage = line.substring(idx + 4);
                        responseCode = Integer.parseInt(line.substring(idx, idx + 3));
                    } catch (Throwable t) {
                        responseCode = 200;
                    }
                } else {
                    // Just content
                    responseCode = 200;
                    byte[] unread = line.getBytes();
                    in.unread(unread);
                    break;
                }

            }
        }
    }
}

From source file:com.phonegap.FileTransfer.java

/**
 * Uploads the specified file to the server URL provided using an HTTP 
 * multipart request. //  ww w  .  j  a v a2  s .c o  m
 * @param file      Full path of the file on the file system
 * @param server        URL of the server to receive the file
 * @param fileKey       Name of file request parameter
 * @param fileName      File name to be used on server
 * @param mimeType      Describes file content type
 * @param params        key:value pairs of user-defined parameters
 * @return FileUploadResult containing result of upload request
 */
public FileUploadResult upload(String file, String server, final String fileKey, final String fileName,
        final String mimeType, JSONObject params, boolean trustEveryone) throws IOException, SSLException {
    // Create return object
    FileUploadResult result = new FileUploadResult();

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

    HttpURLConnection conn = null;
    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(server);

    // 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 conneciton
    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=" + BOUNDRY);

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

    dos = new DataOutputStream(conn.getOutputStream());

    // Send any extra parameters
    try {
        for (Iterator iter = params.keys(); iter.hasNext();) {
            Object key = iter.next();
            dos.writeBytes(LINE_START + BOUNDRY + LINE_END);
            dos.writeBytes("Content-Disposition: form-data; name=\"" + key.toString() + "\"; ");
            dos.writeBytes(LINE_END + LINE_END);
            dos.writeBytes(params.getString(key.toString()));
            dos.writeBytes(LINE_END);
        }
    } catch (JSONException e) {
        Log.e(LOG_TAG, e.getMessage(), e);
    }

    dos.writeBytes(LINE_START + BOUNDRY + LINE_END);
    dos.writeBytes("Content-Disposition: form-data; name=\"" + fileKey + "\";" + " filename=\"" + fileName
            + "\"" + LINE_END);
    dos.writeBytes("Content-Type: " + mimeType + LINE_END);
    dos.writeBytes(LINE_END);

    // 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.writeBytes(LINE_END);
    dos.writeBytes(LINE_START + BOUNDRY + LINE_START + LINE_END);

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

    //------------------ read the SERVER RESPONSE
    StringBuffer responseString = new StringBuffer("");
    DataInputStream inStream = new DataInputStream(conn.getInputStream());
    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();
    conn.disconnect();

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

    return result;
}

From source file:org.openengsb.itests.util.AbstractExamTestHelper.java

@SuppressWarnings("deprecation")
protected boolean isUrlReachable(String url) {
    URL downloadUrl;//from www  . java  2  s.  c  om
    InputStream is = null;
    DataInputStream dataInputStream;
    try {
        downloadUrl = new URL(url);
        is = downloadUrl.openStream();
        dataInputStream = new DataInputStream(new BufferedInputStream(is));
        while (dataInputStream.readLine() != null) {
            return true;
        }
    } catch (Exception e) {
        // well... what should we say; this could happen...
    } finally {
        try {
            if (is != null) {
                is.close();
            }
        } catch (IOException ioe) {
        }
    }
    return false;
}

From source file:dmsl.smartbill.GoogleShoppingAPIHelperClass.java

/**
 * Sends an HTTP request to Google API for Shopping and retrieves a JSON
 * String of a product, based on the barcode number given in the search
 * criteria.// ww w  . jav  a  2 s  .  c o  m
 * 
 * @param barcodeContents
 *            The product's barcode which we use to find that product.
 * @return The JSON String that holds information about the product.
 */
private String getJsonStringFromGoogleShopping(String barcodeContents) {
    URL u;
    InputStream is = null;
    DataInputStream dis = null;
    String s;
    StringBuilder sb = new StringBuilder();
    String jsonString = null;
    try {
        u = new URL("https://www.googleapis.com/shopping/search/v1/public/products?key=" + SHOPPING_API_KEY
                + "&country=US&restrictBy=gtin:" + barcodeContents + "&startIndex=1&maxResults=1");
        is = u.openStream();
        dis = new DataInputStream(new BufferedInputStream(is));
        while ((s = dis.readLine()) != null) {
            sb = sb.append(s + "\n");
        }
    } catch (MalformedURLException mue) {
        mue.printStackTrace();
    } catch (IOException ioe) {
        ioe.printStackTrace();
    } finally {
        if (is != null) {
            try {
                is.close();
            } catch (IOException ioe) {
                ioe.printStackTrace();
            }
        }
    }

    jsonString = sb.toString();
    return jsonString;
}

From source file:com.gmail.nagamatu.radiko.installer.RadikoInstallerActivity.java

private void login() {
    try {// ww  w. j  a  va  2 s  .  c  o  m
        final HttpPost request = new HttpPost(URL_LOGIN);
        request.addHeader("Content-type", "application/x-www-form-urlencoded");
        request.setEntity(new UrlEncodedFormEntity(getParams(), HTTP.UTF_8));
        final HttpResponse response = mClient.execute(request);
        final HttpEntity entity = response.getEntity();
        if (response.getStatusLine().getStatusCode() >= 400) {
            updateMessage(R.string.error_download, response.getStatusLine().getReasonPhrase());
            return;
        }
        final InputStream in = entity.getContent();
        try {
            final DataInputStream din = new DataInputStream(in);
            String line;
            while ((line = din.readLine()) != null) {
                mLoginInfo.clear();
                final String ss[] = line.split("=");
                mLoginInfo.put(ss[0], ss[1]);
            }
        } finally {
            in.close();
        }
        updateMessage(R.string.request_market, null);
        apiRequest();
    } catch (Exception e) {
        updateMessage(R.string.error_download, e.toString());
    }
}