Example usage for org.apache.http.util EncodingUtils getAsciiString

List of usage examples for org.apache.http.util EncodingUtils getAsciiString

Introduction

In this page you can find the example usage for org.apache.http.util EncodingUtils getAsciiString.

Prototype

public static String getAsciiString(byte[] bArr) 

Source Link

Usage

From source file:com.android.internal.http.multipart.MultipartTest.java

public void testParts() throws Exception {
    StringBuffer filebuffer = new StringBuffer();
    String filepartStr = "this is file part";
    filebuffer.append(filepartStr);//from www.j a  va2  s . c o  m
    File upload = File.createTempFile("Multipart", "test");

    FileWriter outFile = new FileWriter(upload);
    BufferedWriter out = new BufferedWriter(outFile);
    try {
        out.write(filebuffer.toString());
        out.flush();
    } finally {
        out.close();
    }

    Part[] parts = new Part[3];
    parts[0] = new StringPart("stringpart", "PART1!!");
    parts[1] = new FilePart(upload.getName(), upload);
    parts[2] = new StringPart("stringpart", "PART2!!");

    MultipartEntity me = new MultipartEntity(parts);
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    me.writeTo(os);
    Header h = me.getContentType();
    String boundry = EncodingUtils.getAsciiString(me.getMultipartBoundary());
    StringBuffer contentType = new StringBuffer("multipart/form-data");
    contentType.append("; boundary=");
    contentType.append(boundry);
    assertEquals("Multipart content type error", contentType.toString(), h.getValue());
    final String CRLF = "\r\n";
    StringBuffer output = new StringBuffer();

    output.append("--");
    output.append(boundry);
    output.append(CRLF);

    output.append("Content-Disposition: form-data; name=\"stringpart\"");
    output.append(CRLF);
    output.append("Content-Type: text/plain; charset=US-ASCII");
    output.append(CRLF);
    output.append("Content-Transfer-Encoding: 8bit");
    output.append(CRLF);
    output.append(CRLF);
    output.append("PART1!!");
    output.append(CRLF);

    output.append("--");
    output.append(boundry);
    output.append(CRLF);

    output.append("Content-Disposition: form-data; name=\"");
    output.append(upload.getName());
    output.append("\"; filename=\"");
    output.append(upload.getName());
    output.append("\"");

    output.append(CRLF);
    output.append("Content-Type: application/octet-stream; charset=ISO-8859-1");
    output.append(CRLF);
    output.append("Content-Transfer-Encoding: binary");
    output.append(CRLF);
    output.append(CRLF);
    output.append(filepartStr);
    output.append(CRLF);

    output.append("--");
    output.append(boundry);
    output.append(CRLF);

    output.append("Content-Disposition: form-data; name=\"stringpart\"");
    output.append(CRLF);
    output.append("Content-Type: text/plain; charset=US-ASCII");
    output.append(CRLF);
    output.append("Content-Transfer-Encoding: 8bit");
    output.append(CRLF);
    output.append(CRLF);
    output.append("PART2!!");
    output.append(CRLF);

    output.append("--");
    output.append(boundry);
    output.append("--");
    output.append(CRLF);
    // System.out.print(output.toString());
    assertEquals("Multipart content error", output.toString(), os.toString());

    // System.out.print(os.toString());
}

From source file:edu.northwestern.cbits.purple_robot_manager.http.BasicAuthTokenExtractor.java

public String extract(final HttpRequest request) throws HttpException {
    String auth = null;/*from  w w w  . j a  v  a2  s . c  om*/
    final Header h = request.getFirstHeader(AUTH.WWW_AUTH_RESP);

    if (h != null) {
        final String s = h.getValue();

        if (s != null) {
            auth = s.trim();
        }
    }

    if (auth != null) {
        final int i = auth.indexOf(' ');

        if (i == -1) {
            throw new ProtocolException("Invalid Authorization header: " + auth);
        }

        final String authscheme = auth.substring(0, i);

        if (authscheme.equalsIgnoreCase("basic")) {
            final String s = auth.substring(i + 1).trim();

            try {
                final byte[] credsRaw = EncodingUtils.getAsciiBytes(s);
                final BinaryDecoder codec = new Base64();
                auth = EncodingUtils.getAsciiString(codec.decode(credsRaw));
            } catch (final DecoderException ex) {
                throw new ProtocolException("Malformed BASIC credentials");
            }
        }
    }
    return auth;
}

From source file:com.jfrog.bintray.client.impl.util.URIUtil.java

/**
 * Escape and encode a given string with allowed characters not to be
 * escaped and a given charset.//  w w  w.  j a  v a  2s. c o m
 *
 * @param unescaped a string
 * @param allowed   allowed characters not to be escaped
 * @param charset   the charset
 * @return the escaped string
 */
public static String encode(String unescaped, BitSet allowed, String charset) throws HttpException {
    byte[] rawdata = URLCodec.encodeUrl(allowed, EncodingUtils.getBytes(unescaped, charset));
    return EncodingUtils.getAsciiString(rawdata);
}

From source file:com.basho.riak.client.http.util.Multipart.java

/**
 * Parses a multipart message or a multipart subpart of a multipart message.
 * /*  ww w. j a v a2s  . c o m*/
 * @return A list of the parts parsed into headers and body of this
 *         multipart message
 */
public static List<Multipart.Part> parse(Map<String, String> headers, byte[] body) {
    if (headers == null || body == null || body.length == 0)
        return null;

    if (!(body.length >= 2 && body[0] == '\r' && body[1] == '\n')) {
        // In order to parse the multipart efficiently, we want to treat the
        // first boundary identically to the others, so make sure that the
        // first boundary is preceded by a '\r\n' like the others
        byte[] newBody = new byte[body.length + 2];
        newBody[0] = '\r';
        newBody[1] = '\n';
        System.arraycopy(body, 0, newBody, 2, body.length);
        body = newBody;
    }

    String boundary = "\r\n--" + getBoundary(headers.get(Constants.HDR_CONTENT_TYPE));
    byte[] boundaryBytes = CharsetUtils.asBytes(boundary, CharsetUtils.ISO_8859_1);
    int boundarySize = boundary.length();
    if ("\r\n--".equals(boundary))
        return null;

    // While this parsing could be more efficiently done in one pass with a
    // hand written FSM, hopefully this method is more readable/intuitive.
    List<Part> parts = new ArrayList<Part>();
    int pos = indexOf(body, boundaryBytes, 0);
    if (pos != -1) {
        while (pos < body.length) {
            // first char of part
            int start = pos + boundarySize;
            // last char of part + 1
            int end = indexOf(body, boundaryBytes, start);
            // end of header section + 1
            int headerEnd = indexOf(body, HEADER_DELIM, pos);
            // start of body section
            int bodyStart = headerEnd + HEADER_DELIM.length;

            // check for end boundary, which is (boundary + "--")
            if (body.length >= (start + 2) && body[start] == '-' && body[start + 1] == '-') {
                break;
            }

            if (end == -1) {
                end = body.length;
            }

            if (headerEnd == -1) {
                headerEnd = body.length;
                bodyStart = end;
            }

            if (bodyStart > end) {
                bodyStart = end;
            }

            Map<String, String> partHeaders = parseHeaders(
                    EncodingUtils.getAsciiString(copyOfRange(body, start, headerEnd)));
            parts.add(new Part(partHeaders, copyOfRange(body, bodyStart, end)));

            pos = end;
        }
    }

    return parts;
}

From source file:com.android.internal.http.multipart.MultipartEntity.java

@Override
public Header getContentType() {
    StringBuffer buffer = new StringBuffer(MULTIPART_FORM_CONTENT_TYPE);
    buffer.append("; boundary=");
    buffer.append(EncodingUtils.getAsciiString(getMultipartBoundary()));
    return new BasicHeader(HTTP.CONTENT_TYPE, buffer.toString());

}

From source file:local.apache.MultipartEntity.java

@Override
public Header getContentType() {
    final StringBuffer buffer = new StringBuffer(MULTIPART_FORM_CONTENT_TYPE);
    buffer.append("; boundary=");
    buffer.append(EncodingUtils.getAsciiString(getMultipartBoundary()));
    return new BasicHeader(HTTP.CONTENT_TYPE, buffer.toString());

}

From source file:com.jobs.lib_v1.net.http.multipart.MultipartEntity.java

@Override
public Header getContentType() {
    StringBuffer buffer = new StringBuffer(MULTIPART_FORM_CONTENT_TYPE);
    buffer.append("; boundary=");
    buffer.append(EncodingUtils.getAsciiString(getMultipartBoundary()));
    return new BasicHeader(HTTP.CONTENT_TYPE, buffer.toString());
}

From source file:info.ajaxplorer.client.http.RestRequest.java

private HttpResponse issueRequest(URI uri, Map<String, String> postParameters, File file, String fileName,
        AjxpFileBody fileBody) throws Exception {
    URI originalUri = new URI(uri.toString());
    if (RestStateHolder.getInstance().getSECURE_TOKEN() != null) {
        uri = new URI(
                uri.toString().concat("&secure_token=" + RestStateHolder.getInstance().getSECURE_TOKEN()));
    }//from  ww w.j  a v  a  2 s  . co m
    //Log.d("RestRequest", "Issuing request : " + uri.toString());
    HttpResponse response = null;
    try {
        HttpRequestBase request;

        if (postParameters != null || file != null) {
            request = new HttpPost();
            if (file != null) {

                if (fileBody == null) {
                    if (fileName == null)
                        fileName = file.getName();
                    fileBody = new AjxpFileBody(file, fileName);
                    ProgressListener origPL = this.uploadListener;
                    Map<String, String> caps = RestStateHolder.getInstance().getServer()
                            .getRemoteCapacities(this);
                    this.uploadListener = origPL;
                    int maxUpload = 0;
                    if (caps != null && caps.containsKey(Server.capacity_UPLOAD_LIMIT))
                        maxUpload = new Integer(caps.get(Server.capacity_UPLOAD_LIMIT));
                    maxUpload = Math.min(maxUpload, 60000000);
                    if (maxUpload > 0 && maxUpload < file.length()) {
                        fileBody.chunkIntoPieces(maxUpload);
                        if (uploadListener != null) {
                            uploadListener.partTransferred(fileBody.getCurrentIndex(),
                                    fileBody.getTotalChunks());
                        }
                    }
                } else {
                    if (uploadListener != null) {
                        uploadListener.partTransferred(fileBody.getCurrentIndex(), fileBody.getTotalChunks());
                    }
                }
                MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
                reqEntity.addPart("userfile_0", fileBody);

                if (fileName != null && !EncodingUtils
                        .getAsciiString(EncodingUtils.getBytes(fileName, "US-ASCII")).equals(fileName)) {
                    reqEntity.addPart("urlencoded_filename",
                            new StringBody(java.net.URLEncoder.encode(fileName, "UTF-8")));
                }
                if (fileBody != null && !fileBody.getFilename().equals(fileBody.getRootFilename())) {
                    reqEntity.addPart("appendto_urlencoded_part",
                            new StringBody(java.net.URLEncoder.encode(fileBody.getRootFilename(), "UTF-8")));
                }
                if (postParameters != null) {
                    Iterator<Map.Entry<String, String>> it = postParameters.entrySet().iterator();
                    while (it.hasNext()) {
                        Map.Entry<String, String> entry = it.next();
                        reqEntity.addPart(entry.getKey(), new StringBody(entry.getValue()));
                    }
                }
                if (uploadListener != null) {
                    CountingMultipartRequestEntity countingEntity = new CountingMultipartRequestEntity(
                            reqEntity, uploadListener);
                    ((HttpPost) request).setEntity(countingEntity);
                } else {
                    ((HttpPost) request).setEntity(reqEntity);
                }
            } else {
                List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(postParameters.size());
                Iterator<Map.Entry<String, String>> it = postParameters.entrySet().iterator();
                while (it.hasNext()) {
                    Map.Entry<String, String> entry = it.next();
                    nameValuePairs.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
                }
                ((HttpPost) request).setEntity(new UrlEncodedFormEntity(nameValuePairs));
            }
        } else {
            request = new HttpGet();
        }

        request.setURI(uri);
        if (this.httpUser.length() > 0 && this.httpPassword.length() > 0) {
            request.addHeader("Ajxp-Force-Login", "true");
        }
        response = httpClient.executeInContext(request);
        if (isAuthenticationRequested(response)) {
            sendMessageToHandler(MessageListener.MESSAGE_WHAT_STATE, STATUS_REFRESHING_AUTH);
            this.discardResponse(response);
            this.authenticate();
            if (loginStateChanged) {
                // RELOAD
                loginStateChanged = false;
                sendMessageToHandler(MessageListener.MESSAGE_WHAT_STATE, STATUS_LOADING_DATA);
                if (fileBody != null)
                    fileBody.resetChunkIndex();
                return this.issueRequest(originalUri, postParameters, file, fileName, fileBody);
            }
        } else if (fileBody != null && fileBody.isChunked() && !fileBody.allChunksUploaded()) {
            this.discardResponse(response);
            this.issueRequest(originalUri, postParameters, file, fileName, fileBody);
        }
    } catch (ClientProtocolException e) {
        sendMessageToHandler(MessageListener.MESSAGE_WHAT_ERROR, e.getMessage());
        e.printStackTrace();
    } catch (IOException e) {
        sendMessageToHandler(MessageListener.MESSAGE_WHAT_ERROR, e.getMessage());
        e.printStackTrace();
    } catch (AuthenticationException e) {
        sendMessageToHandler(MessageListener.MESSAGE_WHAT_ERROR, e.getMessage());
        throw e;
    } catch (Exception e) {
        sendMessageToHandler(MessageListener.MESSAGE_WHAT_ERROR, e.getMessage());
        e.printStackTrace();
    } finally {
        uploadListener = null;
    }
    return response;
}

From source file:com.kentdisplays.synccardboarddemo.Page.java

/**
 * Decodes an input stream from a file into Path objects that can be used to draw the page.
 *//*from  ww  w .  jav  a 2 s. c  o m*/
private static ArrayList<Path> pathsFromSamplePageInputStream(InputStream inputStream) {
    ArrayList<Path> paths = new ArrayList<Path>();
    try {
        // Retrieve a byte array from the sample page.
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len;
        while ((len = inputStream.read(buffer)) > -1) {
            baos.write(buffer, 0, len);
        }
        baos.flush();
        byte[] byteArray = baos.toByteArray();

        // Decode the path data from the sample page.
        String rawString = EncodingUtils.getAsciiString(byteArray);
        int startIndex = rawString.indexOf("<</Length 13 0 R/Filter /FlateDecode>>") + 46;
        int endIndex = rawString.indexOf("endstream", startIndex) - 1;
        byte[] flateEncodedByteArray = Arrays.copyOfRange(byteArray, startIndex, endIndex);
        net.sf.andpdf.nio.ByteBuffer flateEncodedBuffer = net.sf.andpdf.nio.ByteBuffer
                .NEW(flateEncodedByteArray);
        net.sf.andpdf.nio.ByteBuffer decodedBuffer = FlateDecode.decode(null, flateEncodedBuffer, null);
        String decodedString = new String(decodedBuffer.array(), "UTF-8");

        // Break every line of the decoded string into usable objects.
        String[] stringArray = decodedString.split("\\r?\\n");
        for (int i = 0; i < stringArray.length; i++) {
            String[] components = stringArray[i].split(" ");
            Path path = new Path();
            path.y1 = Float.valueOf(components[2]);
            path.x1 = Float.valueOf(components[3]);
            path.y2 = Float.valueOf(components[5]);
            path.x2 = Float.valueOf(components[6]);
            path.width = Float.valueOf(components[0]);
            paths.add(path);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

    return paths;
}