Example usage for java.net URLConnection setRequestProperty

List of usage examples for java.net URLConnection setRequestProperty

Introduction

In this page you can find the example usage for java.net URLConnection setRequestProperty.

Prototype

public void setRequestProperty(String key, String value) 

Source Link

Document

Sets the general request property.

Usage

From source file:com.techventus.server.voice.Voice.java

/**
 * Place a call./*from w w w . ja  v  a  2  s  . c  om*/
 * 
 * @param originNumber
 *            the origin number
 * @param destinationNumber
 *            the destination number
 * @param phoneType
 *            the phone type, this is a number such as 1,2,7 formatted as a String
 * @return the raw response string received from Google Voice.
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 */
public String call(String originNumber, String destinationNumber, String phoneType) throws IOException {
    String out = "";
    StringBuffer calldata = new StringBuffer();

    // POST /voice/call/connect/ 
    // outgoingNumber=[number to call]
    // &forwardingNumber=[forwarding number]
    // &subscriberNumber=undefined
    // &phoneType=[phone type from google]
    // &remember=0
    // &_rnr_se=[pull from page]

    calldata.append("outgoingNumber=");
    calldata.append(URLEncoder.encode(destinationNumber, enc));
    calldata.append("&forwardingNumber=");
    calldata.append(URLEncoder.encode(originNumber, enc));
    calldata.append("&subscriberNumber=undefined");
    calldata.append("&phoneType=");
    calldata.append(URLEncoder.encode(phoneType, enc));
    calldata.append("&remember=0");
    calldata.append("&_rnr_se=");
    calldata.append(URLEncoder.encode(rnrSEE, enc));

    URL callURL = new URL("https://www.google.com/voice/b/0/call/connect/");

    URLConnection callconn = callURL.openConnection();
    callconn.setRequestProperty("Authorization", "GoogleLogin auth=" + authToken);
    callconn.setRequestProperty("User-agent", USER_AGENT);

    callconn.setDoOutput(true);
    OutputStreamWriter callwr = new OutputStreamWriter(callconn.getOutputStream());

    callwr.write(calldata.toString());
    callwr.flush();

    BufferedReader callrd = new BufferedReader(new InputStreamReader(callconn.getInputStream()));

    String line;
    while ((line = callrd.readLine()) != null) {
        out += line + "\n\r";

    }

    callwr.close();
    callrd.close();

    if (out.equals("")) {
        throw new IOException("No Response Data Received.");
    }

    return out;

}

From source file:org.apache.jsp.sources_jsp.java

public String callRestfulApi(String addr, HttpServletRequest request, HttpServletResponse response) {
       if (localCookie)
           CookieHandler.setDefault(cm);

       try {//from  w  w w .  j  a  v a  2 s  . c  om
           ByteArrayOutputStream output = new ByteArrayOutputStream();
           URL url = new URL(API_ROOT + addr);
           URLConnection urlConnection = url.openConnection();
           String cookieVal = getBrowserInfiniteCookie(request);
           if (cookieVal != null) {
               urlConnection.addRequestProperty("Cookie", "infinitecookie=" + cookieVal);
               urlConnection.setDoInput(true);
               urlConnection.setDoOutput(true);
               urlConnection.setRequestProperty("Accept-Charset", "UTF-8");
           }
           IOUtils.copy(urlConnection.getInputStream(), output);
           String newCookie = getConnectionInfiniteCookie(urlConnection);
           if (newCookie != null && response != null) {
               setBrowserInfiniteCookie(response, newCookie, request.getServerPort());
           }
           return output.toString();
       } catch (IOException e) {
           System.out.println(e.getMessage());
           return null;
       }
   }

From source file:org.apache.jsp.sources_jsp.java

private String postToRestfulApi(String addr, String data, HttpServletRequest request,
           HttpServletResponse response) {
       if (localCookie)
           CookieHandler.setDefault(cm);
       String result = "";
       try {/*from  w ww  .ja v a 2s  . c om*/
           URLConnection connection = new URL(API_ROOT + addr).openConnection();
           String cookieVal = getBrowserInfiniteCookie(request);
           if (cookieVal != null) {
               connection.addRequestProperty("Cookie", "infinitecookie=" + cookieVal);
               connection.setDoInput(true);
           }
           connection.setDoOutput(true);
           connection.setRequestProperty("Accept-Charset", "UTF-8");

           // Post JSON string to URL
           OutputStream os = connection.getOutputStream();
           byte[] b = data.getBytes("UTF-8");
           os.write(b);

           // Receive results back from API
           InputStream is = connection.getInputStream();
           result = IOUtils.toString(is, "UTF-8");

           String newCookie = getConnectionInfiniteCookie(connection);
           if (newCookie != null && response != null) {
               setBrowserInfiniteCookie(response, newCookie, request.getServerPort());
           }
       } catch (Exception e) {
           //System.out.println("Exception: " + e.getMessage());
       }
       return result;
   }

From source file:ch.unifr.pai.twice.widgets.mpproxy.server.JettyProxy.java

public ProcessResult loadFromProxy(HttpServletRequest request, HttpServletResponse response, String uri,
        String servletPath, String proxyPath) throws ServletException, IOException {
    //System.out.println("LOAD "+uri); 
    //System.out.println("LOAD "+proxyPath);

    if ("CONNECT".equalsIgnoreCase(request.getMethod())) {
        handleConnect(request, response);

    } else {//from  w ww  .  ja v  a 2s  .c  om
        URL url = new URL(uri);

        URLConnection connection = url.openConnection();
        connection.setAllowUserInteraction(false);

        // Set method
        HttpURLConnection http = null;
        if (connection instanceof HttpURLConnection) {
            http = (HttpURLConnection) connection;
            http.setRequestMethod(request.getMethod());
            http.setInstanceFollowRedirects(false);
        }

        // check connection header
        String connectionHdr = request.getHeader("Connection");
        if (connectionHdr != null) {
            connectionHdr = connectionHdr.toLowerCase();
            if (connectionHdr.equals("keep-alive") || connectionHdr.equals("close"))
                connectionHdr = null;
        }

        // copy headers
        boolean xForwardedFor = false;
        boolean hasContent = false;
        Enumeration enm = request.getHeaderNames();
        while (enm.hasMoreElements()) {
            // TODO could be better than this!
            String hdr = (String) enm.nextElement();
            String lhdr = hdr.toLowerCase();

            if (_DontProxyHeaders.contains(lhdr))
                continue;
            if (connectionHdr != null && connectionHdr.indexOf(lhdr) >= 0)
                continue;

            if ("content-type".equals(lhdr))
                hasContent = true;

            Enumeration vals = request.getHeaders(hdr);
            while (vals.hasMoreElements()) {
                String val = (String) vals.nextElement();
                if (val != null) {
                    connection.addRequestProperty(hdr, val);
                    xForwardedFor |= "X-Forwarded-For".equalsIgnoreCase(hdr);
                }
            }
        }

        // Proxy headers
        connection.setRequestProperty("Via", "1.1 (jetty)");
        if (!xForwardedFor)
            connection.addRequestProperty("X-Forwarded-For", request.getRemoteAddr());

        // a little bit of cache control
        String cache_control = request.getHeader("Cache-Control");
        if (cache_control != null
                && (cache_control.indexOf("no-cache") >= 0 || cache_control.indexOf("no-store") >= 0))
            connection.setUseCaches(false);

        // customize Connection

        try {
            connection.setDoInput(true);

            // do input thang!
            InputStream in = request.getInputStream();
            if (hasContent) {
                connection.setDoOutput(true);
                IOUtils.copy(in, connection.getOutputStream());
            }

            // Connect
            connection.connect();
        } catch (Exception e) {
            e.printStackTrace();
        }

        InputStream proxy_in = null;

        // handler status codes etc.
        int code = 500;
        if (http != null) {
            proxy_in = http.getErrorStream();

            code = http.getResponseCode();
            response.setStatus(code, http.getResponseMessage());
        }

        if (proxy_in == null) {
            try {
                proxy_in = connection.getInputStream();
            } catch (Exception e) {
                e.printStackTrace();
                proxy_in = http.getErrorStream();
            }
        }

        // clear response defaults.
        response.setHeader("Date", null);
        response.setHeader("Server", null);

        // set response headers
        int h = 0;
        String hdr = connection.getHeaderFieldKey(h);
        String val = connection.getHeaderField(h);
        while (hdr != null || val != null) {
            String lhdr = hdr != null ? hdr.toLowerCase() : null;
            if (hdr != null && val != null && !_DontProxyHeaders.contains(lhdr)) {
                if (hdr.equalsIgnoreCase("Location")) {
                    val = Rewriter.translateCleanUrl(val, servletPath, proxyPath);
                }
                response.addHeader(hdr, val);

            }

            h++;
            hdr = connection.getHeaderFieldKey(h);
            val = connection.getHeaderField(h);

        }

        boolean isGzipped = connection.getContentEncoding() != null
                && connection.getContentEncoding().contains("gzip");
        response.addHeader("Via", "1.1 (jetty)");
        // boolean process = connection.getContentType() == null
        // || connection.getContentType().isEmpty()
        // || connection.getContentType().contains("html");
        boolean process = connection.getContentType() != null && connection.getContentType().contains("text");
        if (proxy_in != null) {
            if (!process) {
                IOUtils.copy(proxy_in, response.getOutputStream());
                proxy_in.close();
            } else {
                InputStream in;
                if (isGzipped && proxy_in != null && proxy_in.available() > 0) {
                    in = new GZIPInputStream(proxy_in);
                } else {
                    in = proxy_in;
                }
                ByteArrayOutputStream byteArrOS = new ByteArrayOutputStream();
                IOUtils.copy(in, byteArrOS);
                in.close();
                if (in != proxy_in)
                    proxy_in.close();
                String charset = response.getCharacterEncoding();
                if (charset == null || charset.isEmpty()) {
                    charset = "ISO-8859-1";
                }
                String originalContent = new String(byteArrOS.toByteArray(), charset);
                byteArrOS.close();
                return new ProcessResult(originalContent, connection.getContentType(), charset, isGzipped);
            }
        }

    }
    return null;
}

From source file:osu.beatmapdownloader.JFrame.java

public boolean downloadSong(String idMap, int prio, String Directory) {
       String fileName = null;/*from   www. j a  va  2  s . c o  m*/
       try {
           String url = "";
           if (model.get(prio).toString().contains("Blood")) {
               url = "http://bloodcat.com/osu/d/" + idMap;
               L_server.setText("Bloodcat Server");
           } else {
               if (C_OsuServer.isSelected() && model.get(0).toString().contains("Osu")) {
                   if (C_noVideo.isSelected())
                       url = "http://osu.ppy.sh/d/" + idMap + "n";
                   else
                       url = "http://osu.ppy.sh/d/" + idMap;
                   L_server.setText("Osu! Server");
               }
           }
           long start = System.nanoTime();
           long totalRead = 0;
           final double NANOS_PER_SECOND = 1000000000.0;
           final double BYTES_PER_MIB = 1024 * 1024;
           URLConnection request = null;
           request = new URL(url).openConnection();
           request.setRequestProperty("Cookie", url.contains("ppy") ? Cookie : "");
           request.setRequestProperty("User-Agent",
                   "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.4; en-US; rv:1.9.2.2) Gecko/20100316 Firefox/3.6.2");
           InputStream in = request.getInputStream();
           String raw = request.getHeaderField("Content-Disposition");
           fileName = raw.split("=")[1].replaceAll("\"", "").replaceAll("; filename*", "");
           request.getContentLength();
           double size = request.getContentLength();
           File aux = File.createTempFile(fileName.replaceAll("\\*", "").replaceAll(";", ""), ".osz");
           L_FileName.setText(fileName.replaceAll("\\*", "").replaceAll(";", ""));
           FileOutputStream out = new FileOutputStream(aux);
           byte[] buffer = new byte[1024];
           int len = in.read(buffer);
           L_totalSize.setText((String) new DecimalFormat("#.##").format(size * 0.000001) + " Mb");
           int bytes = 0;
           Pro_ProgressBar.setMinimum(0);
           Pro_ProgressBar.setMaximum((int) (size / 1000));
           long acu = 0;
           while (len != -1) {
               bytes++;
               out.write(buffer, 0, len);
               len = in.read(buffer);
               if (len == 1024) {
                   acu += len;
                   BigDecimal a = new BigDecimal(acu * 0.000001);
                   BigDecimal roundOff = a.setScale(2, BigDecimal.ROUND_HALF_EVEN);
                   L_fileValue.setText(roundOff + "");
               }
               Pro_ProgressBar.setValue(bytes);
               totalRead += len;
               BigDecimal a = new BigDecimal(
                       ((NANOS_PER_SECOND / BYTES_PER_MIB * totalRead / (System.nanoTime() - start + 1)) * 1000));
               BigDecimal speed = a.setScale(2, BigDecimal.ROUND_HALF_EVEN);
               //String speed = new DecimalFormat("#.##").format(((NANOS_PER_SECOND / BYTES_PER_MIB * totalRead / (System.nanoTime() - start + 1)) * 1000));
               L_Second.setText(speed + "");
               BigDecimal b = new BigDecimal((((size * 0.000001) - (acu * 0.000001)) * 0.1)
                       / (((NANOS_PER_SECOND / BYTES_PER_MIB * totalRead / (System.nanoTime() - start + 1))
                               * 1000))
                       * 10000);
               BigDecimal speed_total = b.setScale(2, BigDecimal.ROUND_HALF_EVEN);
               L_seconds.setText(speed_total + "");
               if (Thread.interrupted()) {
                   in.close();
                   out.close();
                   aux.deleteOnExit();
                   throw new InterruptedException();
               }
           }
           in.close();
           out.close();
           FileUtils.copyFile(aux,
                   new File(Directory + File.separator + fileName.replaceAll("\\*", "").replaceAll(";", "")));
           aux.deleteOnExit();
           return true;
       } catch (Exception e) {
           errorFatal("DOWNLOADING");
           errorFatal(e.toString());
           errorFatal("--------------------------------------");
           prio++;
           errorConection++;
           L_Trying.setText(errorConection + "");
           int limitTry = 3;
           if (errorConection >= limitTry) {
               Errors++;
               L_Errors.setText(Errors + "");
               errorDownload("-The connection to this Beatmap was failed, '" + errorConection
                       + "' times, it was skipped.");
               errorDownload("--The filename is '" + fileName + "', with the id '" + idMap + "'. ");
               errorDownload("----------------------");
           } else {
               if (model.getSize() == prio)
                   prio = 0;
               downloadSong(idMap, prio, Directory);
           }
           return false;
       }
   }

From source file:org.sbs.util.download.MultiThreadDownload.java

/**
 * //from w  w w .  j ava2s.  c o m
 * @param url
 * @param path
 * @param fileName
 * @return
 * @throws DownLoadException
 */
@SuppressWarnings("unchecked")
public File downLoad(final URL url, String path, String fileName) throws DownLoadException {
    // ??
    this.downLen = -1;
    this.contentLen = 0;
    this.date = new Date();
    this.finished = false;
    try {
        URLConnection con = url.openConnection();
        //?
        this.contentLen = con.getContentLength();
        //??
        if (StringUtils.isBlank(fileName)) {
            fileName = StringUtils.substringAfterLast(url.getPath(), "/");
        }
        //
        File _path = new File(path);
        if (!_path.exists()) {
            _path.mkdirs();
        }
        final File file = new File(path + File.separator + fileName);
        if (file.exists())
            file.delete();
        if (this.threadNum == 0 && this.blockSize > 0) {
            this.threadNum = (int) (contentLen / blockSize);
            if (this.threadNum == 0) {
                this.threadNum = 1;
            }
        }
        long subLen = contentLen / threadNum;
        List<Future<DownLoadBean>> result = Lists.newArrayList();
        for (int i = 0; i < threadNum; i++) {
            final int pos = (int) (i * subLen);
            final int end = (int) ((i + 1) * subLen) - 1;
            final int current = pos;
            Future<DownLoadBean> f = (Future<DownLoadBean>) pool.submit(new Callable<DownLoadBean>() {
                int $pos = pos;
                int $end = end;
                int $current = current;

                @Override
                public DownLoadBean call() throws Exception {
                    //buff
                    BufferedInputStream bis = null;
                    RandomAccessFile fos = null;
                    byte[] buf = new byte[BUFFER_SIZE];
                    URLConnection con = null;
                    try {
                        con = url.openConnection();
                        con.setAllowUserInteraction(true);
                        //???startPosendPos
                        con.setRequestProperty("Range", "bytes=" + $pos + "-" + $end);
                        fos = new RandomAccessFile(file, "rw");
                        //startPos
                        fos.seek($pos);
                        //????curPos???endPos
                        //endPos?
                        bis = new BufferedInputStream(con.getInputStream());
                        while ($current < $end) {
                            int len = bis.read(buf, 0, BUFFER_SIZE);
                            if (len == -1) {
                                break;
                            }
                            fos.write(buf, 0, len);
                            $current = $current + len;
                            if ($current - 1 > $end) {
                                throw new DownLoadException(
                                        "????");
                            }
                            addLen(len);
                        }
                        bis.close();
                        fos.close();
                    } catch (IOException ex) {
                        /* ?????
                        StringBuffer sb = new StringBuffer();
                        sb.append($pos).append("\t").append($current).append("\t").append($end).append("\n");
                         FileUtils.write(new File(file.getAbsolutePath()+".pos"), sb, true);
                         */
                        throw new RuntimeException(ex);
                    }
                    log.debug(this.hashCode() + ":??[" + $pos + "," + $end + "]");
                    return new DownLoadBean($pos, $end, $current);
                }
            });
            result.add(f);
        }
        Long resultTotal = 0L;
        for (Future<DownLoadBean> f : result) {
            DownLoadBean dInfo = f.get();
            resultTotal += dInfo.getCurrent() - dInfo.getPos();
        }
        // ?
        if (contentLen > resultTotal + 1) {
            // ???
            FileUtils.write(new File(down_error_log_file), url.toString() + "\n", true);
            throw new DownLoadException("?");
        } else {
            finished = true;
            return file;
        }
    } catch (IOException | InterruptedException | ExecutionException e) {
        // 
        try {
            FileUtils.write(new File(down_error_log_file), url.toString() + "\n", true);
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        e.printStackTrace();
    }
    return null;
}

From source file:org.sakaiproject.component.app.help.HelpManagerImpl.java

/**
 * Get Document.//  ww  w.  ja v  a 2  s.c o  m
 * @param resource
 * @return document
 * @throws IOException
 * @throws MalformedURLException
 */
protected Document getDocument(ResourceBean resource) throws IOException, MalformedURLException {

    Document doc = new Document();
    if (resource.getContexts() != null) {
        for (String context : resource.getContexts()) {
            doc.add(new Field("context", "\"" + context + "\"", Field.Store.YES, Field.Index.NOT_ANALYZED));
        }
    }

    URL urlResource;
    URLConnection urlConnection = null;
    //For local file override

    String sakaiHomePath = serverConfigurationService.getSakaiHomePath();
    String localHelpPath = sakaiHomePath + serverConfigurationService.getString("help.localpath", "/help/");
    File localFile = new File(localHelpPath + resource.getLocation());
    boolean localFileIsFile = false;
    if (localFile.isFile()) {
        LOG.debug("Local help file overrides: " + resource.getLocation());
        localFileIsFile = true;
    }
    StringBuilder sb = new StringBuilder();
    if (resource.getLocation() == null || resource.getLocation().startsWith("/")) {
        // handle REST content
        if (!getRestConfiguration().getOrganization().equals("sakai")) {
            urlResource = new URL(getRestConfiguration().getRestUrlInDomain() + resource.getDocId() + "?domain="
                    + getRestConfiguration().getRestDomain());
            urlConnection = urlResource.openConnection();

            String basicAuthUserPass = getRestConfiguration().getRestCredentials();
            String encoding = Base64.encodeBase64(basicAuthUserPass.getBytes("utf-8")).toString();
            urlConnection.setRequestProperty("Authorization", "Basic " + encoding);

            BufferedReader br = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()), 512);
            try {
                int readReturn = 0;
                char[] cbuf = new char[512];
                while ((readReturn = br.read(cbuf, 0, 512)) != -1) {
                    sb.append(cbuf, 0, readReturn);
                }
            } finally {
                br.close();
            }

            // if document is coming from corpus then get document name from xml and assign to resource
            String resourceName = getRestConfiguration().getResourceNameFromCorpusDoc(sb.toString());
            resource.setName(resourceName);
            storeResource(resource);
        } else if (!"".equals(EXTERNAL_URL)) {
            // handle external help location
            urlResource = new URL(EXTERNAL_URL + resource.getLocation());
        } else {
            // Add the home folder file reading here
            if (localFileIsFile) {
                urlResource = localFile.toURI().toURL();
            } else {
                // handle classpath location
                urlResource = getClass().getResource(resource.getLocation());
            }
        }
    } else {
        // handle external location specified in reg file
        urlResource = new URL(resource.getLocation());
    }

    if (urlResource == null) {
        return null;
    }

    if (resource.getLocation() != null) {
        String resLocation = resource.getLocation();
        if (localFileIsFile) {
            resLocation = localFile.getPath();
        }
        doc.add(new Field("location", resLocation, Field.Store.YES, Field.Index.NOT_ANALYZED));
    }

    //doc.add(Field.Keyword("id", resource.getId().toString()));
    doc.add(new Field("id", resource.getId().toString(), Field.Store.YES, Field.Index.NOT_ANALYZED));

    if (getRestConfiguration().getOrganization().equals("sakai")) {
        Reader reader = new BufferedReader(new InputStreamReader(urlResource.openStream()));
        try {
            int readReturn = 0;
            char[] cbuf = new char[512];
            while ((readReturn = reader.read(cbuf, 0, 512)) != -1) {
                sb.append(cbuf, 0, readReturn);
            }
        } finally {
            reader.close();
        }
    }
    //doc.add(Field.Text("content", sb.toString()));
    doc.add(new Field("content", sb.toString(), Field.Store.YES, Field.Index.ANALYZED));

    return doc;
}

From source file:net.lightbody.bmp.proxy.jetty.http.handler.ProxyHandler.java

public void handle(String pathInContext, String pathParams, HttpRequest request, HttpResponse response)
        throws HttpException, IOException {
    URI uri = request.getURI();//  w  w  w.  j a va2s . c om

    // Is this a CONNECT request?
    if (HttpRequest.__CONNECT.equalsIgnoreCase(request.getMethod())) {
        response.setField(HttpFields.__Connection, "close"); // TODO Needed for IE????
        handleConnect(pathInContext, pathParams, request, response);
        return;
    }

    try {
        // Do we proxy this?
        URL url = isProxied(uri);
        if (url == null) {
            if (isForbidden(uri))
                sendForbid(request, response, uri);
            return;
        }

        if (log.isDebugEnabled())
            log.debug("PROXY URL=" + url);

        URLConnection connection = url.openConnection();
        connection.setAllowUserInteraction(false);

        // Set method
        HttpURLConnection http = null;
        if (connection instanceof HttpURLConnection) {
            http = (HttpURLConnection) connection;
            http.setRequestMethod(request.getMethod());
            http.setInstanceFollowRedirects(false);
        }

        // check connection header
        String connectionHdr = request.getField(HttpFields.__Connection);
        if (connectionHdr != null && (connectionHdr.equalsIgnoreCase(HttpFields.__KeepAlive)
                || connectionHdr.equalsIgnoreCase(HttpFields.__Close)))
            connectionHdr = null;

        // copy headers
        boolean xForwardedFor = false;
        boolean hasContent = false;
        Enumeration enm = request.getFieldNames();
        while (enm.hasMoreElements()) {
            // TODO could be better than this!
            String hdr = (String) enm.nextElement();

            if (_DontProxyHeaders.containsKey(hdr) || !_chained && _ProxyAuthHeaders.containsKey(hdr))
                continue;
            if (connectionHdr != null && connectionHdr.indexOf(hdr) >= 0)
                continue;

            if (HttpFields.__ContentType.equals(hdr))
                hasContent = true;

            Enumeration vals = request.getFieldValues(hdr);
            while (vals.hasMoreElements()) {
                String val = (String) vals.nextElement();
                if (val != null) {
                    connection.addRequestProperty(hdr, val);
                    xForwardedFor |= HttpFields.__XForwardedFor.equalsIgnoreCase(hdr);
                }
            }
        }

        // Proxy headers
        if (!_anonymous)
            connection.setRequestProperty("Via", "1.1 (jetty)");
        if (!xForwardedFor)
            connection.addRequestProperty(HttpFields.__XForwardedFor, request.getRemoteAddr());

        // a little bit of cache control
        String cache_control = request.getField(HttpFields.__CacheControl);
        if (cache_control != null
                && (cache_control.indexOf("no-cache") >= 0 || cache_control.indexOf("no-store") >= 0))
            connection.setUseCaches(false);

        // customize Connection
        customizeConnection(pathInContext, pathParams, request, connection);

        try {
            connection.setDoInput(true);

            // do input thang!
            InputStream in = request.getInputStream();
            if (hasContent) {
                connection.setDoOutput(true);
                IO.copy(in, connection.getOutputStream());
            }

            // Connect
            connection.connect();
        } catch (Exception e) {
            LogSupport.ignore(log, e);
        }

        InputStream proxy_in = null;

        // handler status codes etc.
        int code = HttpResponse.__500_Internal_Server_Error;
        if (http != null) {
            proxy_in = http.getErrorStream();

            code = http.getResponseCode();
            response.setStatus(code);
            response.setReason(http.getResponseMessage());
        }

        if (proxy_in == null) {
            try {
                proxy_in = connection.getInputStream();
            } catch (Exception e) {
                LogSupport.ignore(log, e);
                proxy_in = http.getErrorStream();
            }
        }

        // clear response defaults.
        response.removeField(HttpFields.__Date);
        response.removeField(HttpFields.__Server);

        // set response headers
        int h = 0;
        String hdr = connection.getHeaderFieldKey(h);
        String val = connection.getHeaderField(h);
        while (hdr != null || val != null) {
            if (hdr != null && val != null && !_DontProxyHeaders.containsKey(hdr)
                    && (_chained || !_ProxyAuthHeaders.containsKey(hdr)))
                response.addField(hdr, val);
            h++;
            hdr = connection.getHeaderFieldKey(h);
            val = connection.getHeaderField(h);
        }
        if (!_anonymous)
            response.setField("Via", "1.1 (jetty)");

        // Handled
        request.setHandled(true);
        if (proxy_in != null)
            IO.copy(proxy_in, response.getOutputStream());

    } catch (Exception e) {
        log.warn(e.toString());
        LogSupport.ignore(log, e);
        if (!response.isCommitted())
            response.sendError(HttpResponse.__400_Bad_Request);
    }
}

From source file:action.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*www.ja va 2s  . com*/
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    HttpSession session = request.getSession();
    String form_action = (String) request.getParameter("form_action");
    if (form_action == null) {
        form_action = "";
    }
    PrintWriter out = response.getWriter();
    if (form_action.equalsIgnoreCase("cekauth")) {
        StringBuffer sb = new StringBuffer();
        String line = null;
        LinkedHashMap record = new LinkedHashMap();
        try {
            BufferedReader reader = request.getReader();
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
            Object obj = JSONValue.parse(sb.toString());
            JSONObject obj1 = (JSONObject) obj;
            String admin = "N";
            String icw = "N";
            String email = obj1.get("email").toString();
            String first_name = obj1.get("first_name").toString();
            String gender = obj1.get("gender").toString();
            String id = obj1.get("id").toString();
            String last_name = obj1.get("last_name").toString();
            String link = obj1.get("link").toString();
            String name = obj1.get("name").toString();
            String verified = obj1.get("verified").toString();

            DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
            Key linkKey = KeyFactory.createKey("userTable", "user");
            // Run an ancestor query to ensure we see the most up-to-date
            // view of the Greetings belonging to the selected Guestbook.

            Filter posisinama = new FilterPredicate("link", FilterOperator.EQUAL, link.toLowerCase());
            // Run an ancestor query to ensure we see the most up-to-date
            // view of the Greetings belonging to the selected Guestbook.
            Query query = new Query("userTable", linkKey).setFilter(posisinama);
            List<Entity> userTables = datastore.prepare(query).asList(FetchOptions.Builder.withLimit(1));
            Date date = new Date();

            if (userTables.isEmpty()) {
                Entity userTable = new Entity("userTable", linkKey);
                userTable.setProperty("email", email);
                userTable.setProperty("first_name", first_name);
                userTable.setProperty("gender", gender);
                userTable.setProperty("id", id);
                userTable.setProperty("last_name", last_name);
                userTable.setProperty("link", link.toLowerCase());
                userTable.setProperty("name", name);
                userTable.setProperty("verified", verified);
                userTable.setProperty("lastLogin", date);
                if (email.equalsIgnoreCase("khairul.anshar@gmail.com")
                        || id.equalsIgnoreCase("112525777678499279265")
                        || id.equalsIgnoreCase("10152397276159760")
                        || name.equalsIgnoreCase("Khairul Anshar")) {
                    userTable.setProperty("admin", "Y");
                    userTable.setProperty("icw", "Y");
                } else {
                    userTable.setProperty("admin", admin);
                    userTable.setProperty("icw", "N");
                }
                userTable.setProperty("imported", "N");
                datastore.put(userTable);
            } else {
                for (Entity userTable : userTables) {
                    admin = userTable.getProperty("admin").toString();
                    try {
                        icw = userTable.getProperty("icw").toString();
                    } catch (Exception e) {
                        userTable.setProperty("icw", "N");
                        icw = "N";
                    }
                    userTable.setProperty("lastLogin", date);
                    datastore.put(userTable);
                }
            }
            if (email.equalsIgnoreCase("khairul.anshar@gmail.com")
                    || id.equalsIgnoreCase("112525777678499279265") || id.equalsIgnoreCase("10152397276159760")
                    || name.equalsIgnoreCase("Khairul Anshar")) {
                admin = "Y";
                icw = "Y";
            }
            obj1.put("admin", admin);
            obj1.put("icw", icw);
            session.setAttribute("userAccount", obj1);
            record.put("userAccount", obj1);
        } catch (Exception e) {
        }

        response.setContentType("text/html;charset=UTF-8");
        out.print(JSONValue.toJSONString(record));
        out.flush();

    }
    if (form_action.equalsIgnoreCase("getiframeData")) {
        StringBuffer sb = new StringBuffer();
        String line = null;
        LinkedHashMap record = new LinkedHashMap();
        try {
            BufferedReader reader = request.getReader();
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
            Object obj = JSONValue.parse(sb.toString());
            //JSONArray records = (JSONArray) obj;
            JSONObject obj1 = (JSONObject) obj;
            String src = obj1.get("src").toString();

            final URL url = new URL(src);
            final URLConnection urlConnection = url.openConnection();
            urlConnection.setDoOutput(true);
            urlConnection.setRequestProperty("Content-Type", "application/json; charset=utf-8");
            urlConnection.connect();
            final InputStream inputStream = urlConnection.getInputStream();
            InputStreamReader is = new InputStreamReader(inputStream);
            StringBuilder sb1 = new StringBuilder();
            BufferedReader br = new BufferedReader(is);
            String read = br.readLine();
            while (read != null) {
                sb1.append(read);
                read = br.readLine();
            }
            record.put("data", sb1.toString());
            record.put("status", "OK");
        } catch (Exception e) {
            record.put("status", "error");
            record.put("errormsg", e.toString());
        }
        response.setContentType("text/html;charset=UTF-8");
        out.print(JSONValue.toJSONString(record));
        out.flush();
    }
    if (form_action.equalsIgnoreCase("postCommentPosisi")) {
        StringBuffer sb = new StringBuffer();
        String line = null;
        LinkedHashMap record = new LinkedHashMap();
        try {
            BufferedReader reader = request.getReader();
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
            Object obj = JSONValue.parse(sb.toString());
            //JSONArray records = (JSONArray) obj;
            JSONObject obj1 = (JSONObject) obj;
            JSONObject userAccount = (JSONObject) session.getAttribute("userAccount");
            String dept = obj1.get("dept").toString();
            String star = obj1.get("star").toString();
            String comment = obj1.get("comment").toString();
            String id = userAccount.get("id").toString();
            String name = userAccount.get("name").toString();
            String link = userAccount.get("link").toString();
            postData2(name, dept, "", star, comment, id, "AlasanStarCalonPosisi", "dept", dept, link);

            record.put("status", "OK");
        } catch (Exception e) {
            record.put("status", "error");
            record.put("errormsg", e.toString());
        }
        response.setContentType("text/html;charset=UTF-8");
        out.print(JSONValue.toJSONString(record));
        out.flush();
    }
    if (form_action.equalsIgnoreCase("postLikeComment")) {
        StringBuffer sb = new StringBuffer();
        String line = null;
        LinkedHashMap record = new LinkedHashMap();
        try {
            BufferedReader reader = request.getReader();
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
            Object obj = JSONValue.parse(sb.toString());
            //JSONArray records = (JSONArray) obj;
            JSONObject obj1 = (JSONObject) obj;
            String id = obj1.get("id").toString();
            String star = obj1.get("star").toString();

            JSONObject userAccount = (JSONObject) session.getAttribute("userAccount");
            String name = userAccount.get("name").toString();
            String link = userAccount.get("link").toString();
            postData11("AlasanStarLike", "id", id, star, link, name);
            record.put("status", "OK");
        } catch (Exception e) {
            record.put("status", "error");
            record.put("errormsg", e.toString());
        }
        response.setContentType("text/html;charset=UTF-8");
        out.print(JSONValue.toJSONString(record));
        out.flush();
    }
    if (form_action.equalsIgnoreCase("getLikeComment")) {
        StringBuffer sb = new StringBuffer();
        String line = null;
        LinkedHashMap record = new LinkedHashMap();
        String idx_ = "";
        try {
            BufferedReader reader = request.getReader();
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
            Object obj = JSONValue.parse(sb.toString());
            //JSONArray records = (JSONArray) obj;
            JSONObject obj1 = (JSONObject) obj;
            idx_ = obj1.get("id").toString();
            DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
            LinkedHashMap record11 = new LinkedHashMap();
            String link_ = "";
            try {
                JSONObject userAccount = (JSONObject) session.getAttribute("userAccount");
                link_ = userAccount.get("link").toString();
            } catch (Exception e) {
            }
            Key guestbookKey = KeyFactory.createKey("id", idx_);
            // Run an ancestor query to ensure we see the most up-to-date
            // view of the Greetings belonging to the selected Guestbook.
            Query query = new Query("AlasanStarLike", guestbookKey).addSort("date",
                    Query.SortDirection.DESCENDING);
            //List<Entity> AlasanStars = datastore.prepare(query);
            PreparedQuery pq = datastore.prepare(query);
            JSONArray obj11 = new JSONArray();
            JSONArray obj11p = new JSONArray();
            JSONArray obj11n = new JSONArray();
            int i = 0;
            int ip = 0;
            int in = 0;
            double total = 0;
            double totalp = 0;
            double totaln = 0;
            for (Entity AlasanStar : pq.asIterable()) {
                LinkedHashMap record1 = new LinkedHashMap();
                String date = AlasanStar.getProperty("date").toString();
                String star = AlasanStar.getProperty("star").toString();
                String name = AlasanStar.getProperty("user").toString();
                String link = AlasanStar.getProperty("link").toString();
                record1.put("date", date);
                record1.put("star", star);
                record1.put("name", name);
                record1.put("link", link);
                obj11.add(record1);
                i++;
                double d = Double.parseDouble(star);
                total = total + d;
                if (d >= 0) {
                    obj11p.add(record1);
                    ip++;
                    totalp = totalp + d;
                } else {
                    obj11n.add(record1);
                    in++;
                    totaln = totaln + d;
                }
                if (link_.equalsIgnoreCase(link)) {
                    record11.put("date", date);
                    record11.put("star", star);
                    record11.put("name", name);
                    record11.put("link", link);
                }
            }
            double avg = total / i;
            if (i == 0) {
                avg = 0;
            }
            DecimalFormat df = new DecimalFormat("#.##");
            record.put("total", total);
            record.put("totalp", totalp);
            record.put("totaln", totaln);
            record.put("avg", df.format(avg));
            //record.put("AlasanStars", obj11);
            record.put("AlasanStarsp", obj11p);
            record.put("AlasanStarsn", obj11n);
            record.put("AlasanStar", record11);
            record.put("status", "OK");
        } catch (Exception e) {
            record.put("status", "error");
            record.put("errormsg", e.toString());
        }
        response.setContentType("text/html;charset=UTF-8");
        out.print(JSONValue.toJSONString(record));
        out.flush();
    }
    if (form_action.equalsIgnoreCase("getMyCommentPosisi")) {
        StringBuffer sb = new StringBuffer();
        String line = null;
        LinkedHashMap record = new LinkedHashMap();
        String dept = "";
        DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
        LinkedHashMap record1 = new LinkedHashMap();

        try {
            BufferedReader reader = request.getReader();
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
            Object obj = JSONValue.parse(sb.toString());
            //JSONArray records = (JSONArray) obj;
            JSONObject obj1 = (JSONObject) obj;
            dept = obj1.get("dept").toString();
            String link_ = "";
            try {
                JSONObject userAccount = (JSONObject) session.getAttribute("userAccount");
                link_ = userAccount.get("link").toString();
            } catch (Exception e) {
            }
            LinkedHashMap record11 = new LinkedHashMap();
            Key guestbookKey = KeyFactory.createKey("dept", dept);
            Query query = new Query("AlasanStarCalonPosisi", guestbookKey).addSort("date",
                    Query.SortDirection.DESCENDING);
            PreparedQuery pq = datastore.prepare(query);
            JSONArray obj11 = new JSONArray();
            JSONArray obj11p = new JSONArray();
            JSONArray obj11n = new JSONArray();
            int i = 0;
            int ip = 0;
            int in = 0;
            double total = 0;
            double totalp = 0;
            double totaln = 0;
            for (Entity AlasanStar : pq.asIterable()) {
                record1 = new LinkedHashMap();
                String id = AlasanStar.getProperty("user").toString();
                //DateTime dateTime = AlasanStar.getProperties().getDateTimeValue();
                Date time = (Date) AlasanStar.getProperty("date");
                String date = time.toString();//AlasanStar.getProperty("date").toString();
                String star = AlasanStar.getProperty("star").toString();
                String comment = AlasanStar.getProperty("comment").toString();
                comment = comment.replaceAll("\n", "<br/>");
                String name = AlasanStar.getProperty("name").toString();
                String link = AlasanStar.getProperty("link").toString();
                String id__ = AlasanStar.getKey().toString();
                record1.put("id_", id__);
                record1.put("id", id);
                record1.put("date", date);
                record1.put("star", star);
                record1.put("comment", comment);
                record1.put("name", name);
                record1.put("link", link);
                obj11.add(record1);
                i++;
                double d = Double.parseDouble(star);
                total = total + d;
                if (d >= 0) {
                    obj11p.add(record1);
                    ip++;
                    totalp = totalp + d;
                } else {
                    obj11n.add(record1);
                    in++;
                    totaln = totaln + d;
                }
                if (link_.equalsIgnoreCase(link)) {
                    record11.put("id_", id__);
                    record11.put("id", id);
                    record11.put("date", date);
                    record11.put("star", star);
                    record11.put("comment", comment);
                    record11.put("name", name);
                    record11.put("link", link);
                }
            }
            double avg = total / i;
            if (i == 0) {
                avg = 0;
            }
            DecimalFormat df = new DecimalFormat("#.##");
            record.put("total", total);
            record.put("totalp", totalp);
            record.put("totaln", totaln);
            record.put("avg", df.format(avg));
            //record.put("AlasanStars", obj11);
            record.put("AlasanStarsp", obj11p);
            record.put("AlasanStarsn", obj11n);
            record.put("AlasanStar", record11);
            record.put("status", "OK");
        } catch (Exception e) {
            record.put("status", "error");
            record.put("errormsg", e.toString());
        }
        response.setContentType("text/html;charset=UTF-8");
        out.print(JSONValue.toJSONString(record));
        out.flush();
    }
    if (form_action.equalsIgnoreCase("postComment")) {
        StringBuffer sb = new StringBuffer();
        String line = null;
        LinkedHashMap record = new LinkedHashMap();
        try {
            BufferedReader reader = request.getReader();
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
            Object obj = JSONValue.parse(sb.toString());
            //JSONArray records = (JSONArray) obj;
            JSONObject obj1 = (JSONObject) obj;
            JSONObject userAccount = (JSONObject) session.getAttribute("userAccount");
            String dept = obj1.get("dept").toString();
            String namaCalon = obj1.get("namaCalon").toString();
            String star = obj1.get("star").toString();
            String comment = obj1.get("comment").toString();
            String id = userAccount.get("id").toString();
            String name = userAccount.get("name").toString();
            String link = userAccount.get("link").toString();
            postData2(name, dept, namaCalon, star, comment, id, "AlasanStarCalon", dept, namaCalon, link);
            record.put("status", "OK");
        } catch (Exception e) {
            record.put("status", "error");
            record.put("errormsg", e.toString());
        }
        response.setContentType("text/html;charset=UTF-8");
        out.print(JSONValue.toJSONString(record));
        out.flush();
    }
    if (form_action.equalsIgnoreCase("getMyComment")) {
        StringBuffer sb = new StringBuffer();
        String line = null;
        LinkedHashMap record = new LinkedHashMap();
        String dept = "";
        String namaCalon = "";
        try {
            BufferedReader reader = request.getReader();
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
            Object obj = JSONValue.parse(sb.toString());
            //JSONArray records = (JSONArray) obj;
            JSONObject obj1 = (JSONObject) obj;
            dept = obj1.get("dept").toString();
            namaCalon = obj1.get("namaCalon").toString();
            DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
            String link_ = "";
            LinkedHashMap record11 = new LinkedHashMap();
            try {
                JSONObject userAccount = (JSONObject) session.getAttribute("userAccount");
                link_ = userAccount.get("link").toString();
            } catch (Exception e) {
            }
            Key guestbookKey = KeyFactory.createKey(dept, namaCalon);
            Query query = new Query("AlasanStarCalon", guestbookKey).addSort("date",
                    Query.SortDirection.DESCENDING);
            PreparedQuery pq = datastore.prepare(query);
            JSONArray obj11 = new JSONArray();
            JSONArray obj11p = new JSONArray();
            JSONArray obj11n = new JSONArray();
            int i = 0;
            int ip = 0;
            int in = 0;
            double total = 0;
            double totalp = 0;
            double totaln = 0;
            for (Entity AlasanStar : pq.asIterable()) {
                LinkedHashMap record1 = new LinkedHashMap();
                String id = AlasanStar.getProperty("user").toString();
                Date time = (Date) AlasanStar.getProperty("date");
                String date = time.toString();//AlasanStar.getProperty("date").toString();
                String star = AlasanStar.getProperty("star").toString();
                String comment = AlasanStar.getProperty("comment").toString();
                comment = comment.replaceAll("\n", "<br/>");
                String name = AlasanStar.getProperty("name").toString();
                String link = AlasanStar.getProperty("link").toString();
                String id__ = AlasanStar.getKey().toString();
                record1.put("id_", id__);
                record1.put("id", id);
                record1.put("date", date);
                record1.put("star", star);
                record1.put("comment", comment);
                record1.put("name", name);
                record1.put("link", link);
                obj11.add(record1);
                i++;
                double d = Double.parseDouble(star);
                total = total + d;
                if (d >= 0) {
                    obj11p.add(record1);
                    ip++;
                    totalp = totalp + d;
                } else {
                    obj11n.add(record1);
                    in++;
                    totaln = totaln + d;
                }
                if (link_.equalsIgnoreCase(link)) {
                    record11.put("id_", id__);
                    record11.put("id", id);
                    record11.put("date", date);
                    record11.put("star", star);
                    record11.put("comment", comment);
                    record11.put("name", name);
                    record11.put("link", link);
                }
            }
            double avg = total / i;
            if (i == 0) {
                avg = 0;
            }
            DecimalFormat df = new DecimalFormat("#.##");
            record.put("total", total);
            record.put("totalp", totalp);
            record.put("totaln", totaln);
            record.put("avg", df.format(avg));
            record.put("AlasanStarsp", obj11p);
            record.put("AlasanStarsn", obj11n);
            record.put("AlasanStar", record11);
            record.put("status", "OK");
        } catch (Exception e) {
            record.put("status", "error");
            record.put("errormsg", e.toString());
        }
        response.setContentType("text/html;charset=UTF-8");
        out.print(JSONValue.toJSONString(record));
        out.flush();
    }
    if (form_action.equalsIgnoreCase("getAlasanStarCalon")) {
        StringBuffer sb = new StringBuffer();
        String line = null;
        LinkedHashMap record = new LinkedHashMap();
        try {
            BufferedReader reader = request.getReader();
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
            Object obj = JSONValue.parse(sb.toString());
            //JSONArray records = (JSONArray) obj;
            JSONObject obj1 = (JSONObject) obj;
            JSONObject userAccount = (JSONObject) session.getAttribute("userAccount");
            String dept = obj1.get("dept").toString();
            String namaCalon = obj1.get("namaCalon").toString();
            DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
            Key guestbookKey = KeyFactory.createKey(dept, namaCalon);
            // Run an ancestor query to ensure we see the most up-to-date
            // view of the Greetings belonging to the selected Guestbook.
            Query query = new Query("AlasanStarCalon", guestbookKey).addSort("date",
                    Query.SortDirection.DESCENDING);
            //List<Entity> AlasanStars = datastore.prepare(query);
            PreparedQuery pq = datastore.prepare(query);
            JSONArray obj11 = new JSONArray();
            int i = 0;
            double total = 0;
            for (Entity AlasanStar : pq.asIterable()) {
                LinkedHashMap record1 = new LinkedHashMap();
                String id = AlasanStar.getProperty("user").toString();
                String date = AlasanStar.getProperty("date").toString();
                String star = AlasanStar.getProperty("star").toString();
                String comment = AlasanStar.getProperty("comment").toString();
                comment = comment.replaceAll("\n", "<br/>");
                String name = AlasanStar.getProperty("name").toString();
                String link = AlasanStar.getProperty("link").toString();
                String id__ = AlasanStar.getKey().toString();
                record1.put("id_", id__);
                record1.put("id", id);
                record1.put("date", date);
                record1.put("star", star);
                record1.put("comment", comment);
                record1.put("name", name);
                record1.put("link", link);
                obj11.add(record1);
                i++;
                double d = Double.parseDouble(star);
                total = total + d;
            }
            double avg = total / i;
            if (i == 0) {
                avg = 0;
            }
            DecimalFormat df = new DecimalFormat("#.##");
            record.put("total", total);
            record.put("avg", df.format(avg));
            record.put("AlasanStars", obj11);
            record.put("status", "OK");
        } catch (Exception e) {
            record.put("status", "error");
            record.put("errormsg", e.toString());
        }
        response.setContentType("text/html;charset=UTF-8");
        out.print(JSONValue.toJSONString(record));
        out.flush();
    }

    if (form_action.equalsIgnoreCase("postUsulan")) {
        StringBuffer sb = new StringBuffer();
        String line = null;
        LinkedHashMap record = new LinkedHashMap();
        try {
            BufferedReader reader = request.getReader();
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
            Object obj = JSONValue.parse(sb.toString());
            //JSONArray records = (JSONArray) obj;
            JSONObject obj1 = (JSONObject) obj;
            String dept = obj1.get("dept").toString();
            String usulan = obj1.get("usulan").toString();

            JSONObject userAccount = (JSONObject) session.getAttribute("userAccount");
            String id = userAccount.get("id").toString();
            String name = userAccount.get("name").toString();
            String email = userAccount.get("email").toString();
            String link = userAccount.get("link").toString();
            Key usulanCalonKey = KeyFactory.createKey("dept", dept);
            Date date = new Date();
            Entity usulanCalon = new Entity("usulanCalon", usulanCalonKey);
            usulanCalon.setProperty("user", id);
            usulanCalon.setProperty("name", name);
            usulanCalon.setProperty("email", email);
            usulanCalon.setProperty("link", link);
            usulanCalon.setProperty("date", date);
            usulanCalon.setProperty("usulan", usulan);
            DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
            usulanCalon.setProperty("imported", "N");
            datastore.put(usulanCalon);
            record.put("status", "OK");
        } catch (Exception e) {
            record.put("status", "error");
            record.put("errormsg", e.toString());
        }
        response.setContentType("text/html;charset=UTF-8");
        out.print(JSONValue.toJSONString(record));
        out.flush();
    }

    if (form_action.equalsIgnoreCase("getSet1")) {
        StringBuffer sb = new StringBuffer();
        String line = null;
        LinkedHashMap record = new LinkedHashMap();
        try {
            BufferedReader reader = request.getReader();
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
            Object obj = JSONValue.parse(sb.toString());
            //JSONArray records = (JSONArray) obj;
            JSONObject obj1 = (JSONObject) obj;
            String input = obj1.get("input").toString();
            String type = obj1.get("type").toString();
            DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
            Key typeKey = KeyFactory.createKey("posisi", type.toLowerCase().replaceAll(" ", ""));
            // Run an ancestor query to ensure we see the most up-to-date
            // view of the Greetings belonging to the selected Guestbook.
            Query query = new Query("posisi", typeKey).addSort("date", Query.SortDirection.ASCENDING);
            //List<Entity> AlasanStars = datastore.prepare(query);
            PreparedQuery pq = datastore.prepare(query);
            JSONArray obj11 = new JSONArray();
            String id = "";
            try {
                JSONObject userAccount = (JSONObject) session.getAttribute("userAccount");
                id = userAccount.get("id").toString();
            } catch (Exception ex1) {
            }
            for (Entity typeEntity : pq.asIterable()) {
                String reviewed = typeEntity.getProperty("reviewed").toString();
                if (reviewed.equalsIgnoreCase("Y")) {
                    LinkedHashMap record1 = new LinkedHashMap();
                    String posisi = typeEntity.getProperty("posisi").toString();
                    String nama = typeEntity.getProperty("nama").toString();
                    String link = typeEntity.getProperty("link").toString();
                    String date = typeEntity.getProperty("date").toString();
                    record1.put("posisi", posisi);
                    record1.put("nama", nama);
                    record1.put("link", link);
                    record1.put("date", date);
                    String detail1 = "";
                    try {
                        Text detail0 = (Text) typeEntity.getProperty("detail");
                        detail1 = detail0.getValue();
                    } catch (Exception e) {
                        detail1 = "";
                    }
                    record1.put("detail", detail1);
                    obj11.add(record1);
                } else {
                    String user = typeEntity.getProperty("user").toString();
                    if (user.equalsIgnoreCase(id)) {
                        LinkedHashMap record1 = new LinkedHashMap();
                        String posisi = typeEntity.getProperty("posisi").toString();
                        String nama = typeEntity.getProperty("nama").toString();
                        String link = typeEntity.getProperty("link").toString();
                        String date = typeEntity.getProperty("date").toString();
                        record1.put("posisi", posisi);
                        record1.put("nama", nama);
                        record1.put("link", link);
                        record1.put("date", date);
                        String detail1 = "";
                        try {
                            Text detail0 = (Text) typeEntity.getProperty("detail");
                            detail1 = detail0.getValue();
                        } catch (Exception e) {
                            detail1 = "";
                        }
                        record1.put("detail", detail1);
                        obj11.add(record1);
                    }
                }
            }
            record.put("records", obj11);
            record.put("status", "OK");
        } catch (Exception e) {
            record.put("status", "error");
            record.put("errormsg", e.toString());
        }
        response.setContentType("text/html;charset=UTF-8");
        out.print(JSONValue.toJSONString(record));
        out.flush();
    }
    if (form_action.equalsIgnoreCase("setSet1")) {
        StringBuffer sb = new StringBuffer();
        String line = null;
        LinkedHashMap record = new LinkedHashMap();
        try {

            JSONObject userAccount = (JSONObject) session.getAttribute("userAccount");
            String id = userAccount.get("id").toString();
            String nama = userAccount.get("name").toString();
            String email = userAccount.get("email").toString();
            String link = userAccount.get("link").toString();
            String admin = userAccount.get("admin").toString();

            BufferedReader reader = request.getReader();
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
            Object obj = JSONValue.parse(sb.toString());
            //JSONArray records = (JSONArray) obj;
            JSONObject obj1 = (JSONObject) obj;
            String input = obj1.get("input").toString();
            String type = obj1.get("type").toString();
            String value = obj1.get("value").toString();
            String detail = obj1.get("value1").toString();
            Key typeKey = KeyFactory.createKey("posisi", type.toLowerCase().replaceAll(" ", ""));
            Filter posisinama = new FilterPredicate("posisi", FilterOperator.EQUAL, value);
            // Run an ancestor query to ensure we see the most up-to-date
            // view of the Greetings belonging to the selected Guestbook.
            Query query = new Query("posisi", typeKey).setFilter(posisinama);
            //Query query = new Query("posisi", typeKey);//.addSort("date", Query.SortDirection.DESCENDING);
            //List<Entity> AlasanStars = datastore.prepare(query);
            DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
            PreparedQuery pq = datastore.prepare(query);
            boolean found = pq.asIterable().iterator().hasNext();

            if (found) {
                if (admin.equalsIgnoreCase("Y")) {
                    for (Entity psosisiEntity : pq.asList(FetchOptions.Builder.withLimit(1))) {
                        Date date = new Date();
                        psosisiEntity.setProperty("date", date);
                        psosisiEntity.setProperty("detail", new Text(detail));
                        datastore.put(psosisiEntity);
                    }
                }
            }

            if (!found) {
                Date date = new Date();
                Entity psosisiEntity = new Entity("posisi", typeKey);
                psosisiEntity.setProperty("user", id);
                psosisiEntity.setProperty("link", link);
                psosisiEntity.setProperty("nama", nama);
                psosisiEntity.setProperty("email", email);
                psosisiEntity.setProperty("date", date);
                psosisiEntity.setProperty("posisi", value);
                psosisiEntity.setProperty("detail", new Text(detail));
                if (email.equalsIgnoreCase("khairul.anshar@gmail.com")
                        || id.equalsIgnoreCase("112525777678499279265")
                        || id.equalsIgnoreCase("10152397276159760") || nama.equalsIgnoreCase("Khairul Anshar")
                        || admin.equalsIgnoreCase("Y")) {
                    psosisiEntity.setProperty("reviewed", "Y");
                    psosisiEntity.setProperty("nama", "Kawal Menteri");
                    psosisiEntity.setProperty("link", "https://www.facebook.com/KawalMenteri");
                } else {
                    psosisiEntity.setProperty("reviewed", "N");
                }
                psosisiEntity.setProperty("imported", "N");
                datastore.put(psosisiEntity);
            }

            query = new Query("posisi", typeKey).addSort("date", Query.SortDirection.ASCENDING);
            pq = datastore.prepare(query);
            JSONArray obj11 = new JSONArray();

            for (Entity typeEntity : pq.asIterable()) {
                String reviewed = typeEntity.getProperty("reviewed").toString();
                if (reviewed.equalsIgnoreCase("Y")) {
                    LinkedHashMap record1 = new LinkedHashMap();
                    String posisi = typeEntity.getProperty("posisi").toString();
                    String nama1 = typeEntity.getProperty("nama").toString();
                    String link1 = typeEntity.getProperty("link").toString();
                    String date = typeEntity.getProperty("date").toString();
                    record1.put("posisi", posisi);
                    record1.put("nama", nama1);
                    record1.put("link", link1);
                    record1.put("date", date);
                    String detail1 = "";
                    try {
                        Text detail0 = (Text) typeEntity.getProperty("detail");
                        detail1 = detail0.getValue();
                    } catch (Exception e) {
                        detail1 = "";
                    }
                    record1.put("detail", detail1);
                    obj11.add(record1);
                } else {
                    String user = typeEntity.getProperty("user").toString();
                    if (user.equalsIgnoreCase(id) || (email.equalsIgnoreCase("khairul.anshar@gmail.com")
                            || id.equalsIgnoreCase("112525777678499279265")
                            || id.equalsIgnoreCase("10152397276159760")
                            || nama.equalsIgnoreCase("Khairul Anshar") || admin.equalsIgnoreCase("Y"))) {
                        LinkedHashMap record1 = new LinkedHashMap();
                        String posisi = typeEntity.getProperty("posisi").toString();
                        String nama1 = typeEntity.getProperty("nama").toString();
                        String link1 = typeEntity.getProperty("link").toString();
                        String date = typeEntity.getProperty("date").toString();
                        record1.put("posisi", posisi);
                        record1.put("nama", nama1);
                        record1.put("link", link1);
                        record1.put("date", date);
                        String detail1 = "";
                        try {
                            Text detail0 = (Text) typeEntity.getProperty("detail");
                            detail1 = detail0.getValue();
                        } catch (Exception e) {
                            detail1 = "";
                        }
                        record1.put("detail", detail1);
                        obj11.add(record1);
                    }
                }
            }

            record.put("records", obj11);
            record.put("status", "OK");
        } catch (Exception e) {
            record.put("status", "error");
            record.put("errormsg", e.toString());
        }
        response.setContentType("text/html;charset=UTF-8");
        out.print(JSONValue.toJSONString(record));
        out.flush();
    }

    if (form_action.equalsIgnoreCase("getSet2")) {
        StringBuffer sb = new StringBuffer();
        String line = null;
        LinkedHashMap record = new LinkedHashMap();
        try {
            BufferedReader reader = request.getReader();
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
            Object obj = JSONValue.parse(sb.toString());
            //JSONArray records = (JSONArray) obj;
            JSONObject obj1 = (JSONObject) obj;
            String input = obj1.get("input").toString();
            String input0 = obj1.get("input0").toString();
            String type0 = obj1.get("type0").toString();
            DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
            Key typeKey = KeyFactory.createKey("kandidat" + type0, input);
            // Run an ancestor query to ensure we see the most up-to-date
            // view of the Greetings belonging to the selected Guestbook.
            Query query = new Query("kandidat", typeKey).addSort("date", Query.SortDirection.ASCENDING);
            //List<Entity> AlasanStars = datastore.prepare(query);
            PreparedQuery pq = datastore.prepare(query);
            JSONArray obj11 = new JSONArray();
            String id = "";
            String nama = "";
            String email = "";
            String link = "";
            String admin = "";
            String icw = "";
            try {
                JSONObject userAccount = (JSONObject) session.getAttribute("userAccount");
                id = userAccount.get("id").toString();
                nama = userAccount.get("name").toString();
                email = userAccount.get("email").toString();
                link = userAccount.get("link").toString();
                admin = userAccount.get("admin").toString();
                icw = userAccount.get("icw").toString();
            } catch (Exception ex1) {
            }
            for (Entity typeEntity : pq.asIterable()) {
                String reviewed = typeEntity.getProperty("reviewed").toString();
                if (reviewed.equalsIgnoreCase("Y")) {
                    LinkedHashMap record1 = new LinkedHashMap();
                    String kandidat = typeEntity.getProperty("kandidat").toString();
                    String desc = typeEntity.getProperty("desc").toString();
                    Text detail0 = (Text) typeEntity.getProperty("detail");
                    String detail = detail0.getValue();
                    String nama1 = typeEntity.getProperty("nama").toString();
                    String link1 = typeEntity.getProperty("link").toString();
                    String date = typeEntity.getProperty("date").toString();
                    String icwcomment = "";
                    try {
                        icwcomment = typeEntity.getProperty("icwcomment").toString();
                    } catch (Exception e) {
                        icwcomment = "";
                    }
                    record1.put("key", "kandidat" + type0);
                    record1.put("val", input);
                    record1.put("kandidat", kandidat);
                    record1.put("desc", desc);
                    record1.put("detail", detail);
                    record1.put("nama", nama1);
                    record1.put("link", link1);
                    record1.put("date", date);
                    record1.put("icwcomment", icwcomment);
                    obj11.add(record1);
                } else {
                    String user = typeEntity.getProperty("user").toString();
                    if (user.equalsIgnoreCase(id) || (email.equalsIgnoreCase("khairul.anshar@gmail.com")
                            || id.equalsIgnoreCase("112525777678499279265")
                            || id.equalsIgnoreCase("10152397276159760")
                            || nama.equalsIgnoreCase("Khairul Anshar") || admin.equalsIgnoreCase("Y"))) {
                        LinkedHashMap record1 = new LinkedHashMap();
                        String kandidat = typeEntity.getProperty("kandidat").toString();
                        String desc = typeEntity.getProperty("desc").toString();
                        Text detail0 = (Text) typeEntity.getProperty("detail");
                        String detail = detail0.getValue();
                        String nama1 = typeEntity.getProperty("nama").toString();
                        String link1 = typeEntity.getProperty("link").toString();
                        String date = typeEntity.getProperty("date").toString();
                        record1.put("key", "kandidat" + type0);
                        record1.put("val", input);
                        record1.put("kandidat", kandidat);
                        record1.put("desc", desc);
                        record1.put("detail", detail);
                        record1.put("nama", nama1);
                        record1.put("link", link1);
                        record1.put("date", date);
                        String icwcomment = "";

                        if (email.equalsIgnoreCase("khairul.anshar@gmail.com")
                                || id.equalsIgnoreCase("112525777678499279265")
                                || id.equalsIgnoreCase("10152397276159760")
                                || nama.equalsIgnoreCase("Khairul Anshar") || admin.equalsIgnoreCase("Y")
                                || icw.equalsIgnoreCase("Y")) {
                            try {
                                icwcomment = typeEntity.getProperty("icwcomment").toString();
                            } catch (Exception e) {
                                icwcomment = "";
                            }
                        }
                        record1.put("icwcomment", icwcomment);
                        obj11.add(record1);
                    }
                }
            }
            record.put("records", obj11);
            record.put("status", "OK");
        } catch (Exception e) {
            record.put("status", "error");
            record.put("errormsg", e.toString());
        }
        response.setContentType("text/html;charset=UTF-8");
        out.print(JSONValue.toJSONString(record));
        out.flush();
    }
    if (form_action.equalsIgnoreCase("setIcwComment")) {
        StringBuffer sb = new StringBuffer();
        String line = null;
        LinkedHashMap record = new LinkedHashMap();
        try {
            JSONObject userAccount = (JSONObject) session.getAttribute("userAccount");
            String icw = userAccount.get("icw").toString();
            if (icw.equalsIgnoreCase("N")) {

            } else {
                BufferedReader reader = request.getReader();
                while ((line = reader.readLine()) != null) {
                    sb.append(line);
                }
                Object obj = JSONValue.parse(sb.toString());
                //JSONArray records = (JSONArray) obj;
                JSONObject obj1 = (JSONObject) obj;

                String input = obj1.get("input").toString();
                String input0 = obj1.get("input0").toString();
                String type0 = obj1.get("type0").toString();
                String value = obj1.get("value").toString();
                String menteri = obj1.get("menteri").toString();
                String kandidat = obj1.get("kandidat").toString();
                Key typeKey = KeyFactory.createKey("kandidat" + type0, input);
                // Run an ancestor query to ensure we see the most up-to-date
                // view of the Greetings belonging to the selected Guestbook.

                Filter namaKandidat = new FilterPredicate("kandidat", FilterOperator.EQUAL, kandidat);
                // Run an ancestor query to ensure we see the most up-to-date
                // view of the Greetings belonging to the selected Guestbook.
                Query query = new Query("kandidat", typeKey).setFilter(namaKandidat);
                //Query query = new Query("posisi", typeKey);//.addSort("date", Query.SortDirection.DESCENDING);
                //List<Entity> AlasanStars = datastore.prepare(query);
                DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();

                for (Entity psosisiEntity : datastore.prepare(query)
                        .asList(FetchOptions.Builder.withLimit(1))) {
                    psosisiEntity.setProperty("icwcomment", value);
                    datastore.put(psosisiEntity);
                }

            }
            record.put("status", "OK");
        } catch (Exception e) {
            record.put("status", "error");
            record.put("errormsg", e.toString());
        }
        response.setContentType("text/html;charset=UTF-8");
        out.print(JSONValue.toJSONString(record));
        out.flush();
    }
    if (form_action.equalsIgnoreCase("setSet2")) {
        StringBuffer sb = new StringBuffer();
        String line = null;
        LinkedHashMap record = new LinkedHashMap();
        try {
            JSONObject userAccount = (JSONObject) session.getAttribute("userAccount");
            String id = userAccount.get("id").toString();
            String nama = userAccount.get("name").toString();
            String email = userAccount.get("email").toString();
            String link = userAccount.get("link").toString();
            String admin = userAccount.get("admin").toString();
            String icw = userAccount.get("icw").toString();

            BufferedReader reader = request.getReader();
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
            Object obj = JSONValue.parse(sb.toString());
            //JSONArray records = (JSONArray) obj;
            JSONObject obj1 = (JSONObject) obj;

            String input = obj1.get("input").toString();
            String input0 = obj1.get("input0").toString();
            String type0 = obj1.get("type0").toString();
            String value = obj1.get("value").toString();
            String value1 = obj1.get("value1").toString();
            String value2 = obj1.get("value2").toString();
            String menteri = obj1.get("menteri").toString();
            Key typeKey = KeyFactory.createKey("kandidat" + type0, input);
            // Run an ancestor query to ensure we see the most up-to-date
            // view of the Greetings belonging to the selected Guestbook.

            Filter namaKandidat = new FilterPredicate("kandidat", FilterOperator.EQUAL, value);
            // Run an ancestor query to ensure we see the most up-to-date
            // view of the Greetings belonging to the selected Guestbook.
            Query query = new Query("kandidat", typeKey).setFilter(namaKandidat);
            //Query query = new Query("posisi", typeKey);//.addSort("date", Query.SortDirection.DESCENDING);
            //List<Entity> AlasanStars = datastore.prepare(query);
            DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
            PreparedQuery pq = datastore.prepare(query);
            boolean found = pq.asIterable().iterator().hasNext();

            if (found) {
                if (admin.equalsIgnoreCase("Y")) {
                    for (Entity psosisiEntity : pq.asList(FetchOptions.Builder.withLimit(1))) {
                        Date date = new Date();
                        psosisiEntity.setProperty("date", date);
                        psosisiEntity.setProperty("detail", new Text(value2));
                        datastore.put(psosisiEntity);
                    }
                }
            }

            if (!found) {

                Date date = new Date();
                Entity psosisiEntity = new Entity("kandidat", typeKey);
                psosisiEntity.setProperty("user", id);
                psosisiEntity.setProperty("link", link);
                psosisiEntity.setProperty("nama", nama);
                psosisiEntity.setProperty("email", email);
                psosisiEntity.setProperty("date", date);
                psosisiEntity.setProperty("kandidat", value);
                psosisiEntity.setProperty("desc", value1);
                psosisiEntity.setProperty("posisi", menteri);
                psosisiEntity.setProperty("detail", new Text(value2));
                psosisiEntity.setProperty("icwcomment", "");

                if (email.equalsIgnoreCase("khairul.anshar@gmail.com")
                        || id.equalsIgnoreCase("112525777678499279265")
                        || id.equalsIgnoreCase("10152397276159760") || nama.equalsIgnoreCase("Khairul Anshar")
                        || admin.equalsIgnoreCase("Y")) {
                    psosisiEntity.setProperty("reviewed", "Y");
                    psosisiEntity.setProperty("nama", "Kawal Menteri");
                    psosisiEntity.setProperty("link", "https://www.facebook.com/KawalMenteri");
                } else {
                    psosisiEntity.setProperty("reviewed", "N");
                }
                psosisiEntity.setProperty("imported", "N");
                datastore.put(psosisiEntity);
            }

            query = new Query("kandidat", typeKey).addSort("date", Query.SortDirection.ASCENDING);
            pq = datastore.prepare(query);
            JSONArray obj11 = new JSONArray();

            for (Entity typeEntity : pq.asIterable()) {
                String reviewed = typeEntity.getProperty("reviewed").toString();
                if (reviewed.equalsIgnoreCase("Y")) {
                    LinkedHashMap record1 = new LinkedHashMap();
                    String kandidat = typeEntity.getProperty("kandidat").toString();
                    String desc = typeEntity.getProperty("desc").toString();
                    Text detail0 = (Text) typeEntity.getProperty("detail");
                    String detail = detail0.getValue();
                    String nama1 = typeEntity.getProperty("nama").toString();
                    String link1 = typeEntity.getProperty("link").toString();
                    String date = typeEntity.getProperty("date").toString();
                    String icwcomment = "";
                    try {
                        icwcomment = typeEntity.getProperty("icwcomment").toString();
                    } catch (Exception e) {
                        icwcomment = "";
                    }
                    record1.put("key", "kandidat" + type0);
                    record1.put("val", input);
                    record1.put("kandidat", kandidat);
                    record1.put("desc", desc);
                    record1.put("detail", detail);
                    record1.put("nama", nama1);
                    record1.put("link", link1);
                    record1.put("date", date);
                    record1.put("icwcomment", icwcomment);
                    obj11.add(record1);
                } else {
                    String user = typeEntity.getProperty("user").toString();
                    if (user.equalsIgnoreCase(id) || (email.equalsIgnoreCase("khairul.anshar@gmail.com")
                            || id.equalsIgnoreCase("112525777678499279265")
                            || id.equalsIgnoreCase("10152397276159760")
                            || nama.equalsIgnoreCase("Khairul Anshar") || admin.equalsIgnoreCase("Y"))) {
                        LinkedHashMap record1 = new LinkedHashMap();
                        String kandidat = typeEntity.getProperty("kandidat").toString();
                        String desc = typeEntity.getProperty("desc").toString();
                        Text detail0 = (Text) typeEntity.getProperty("detail");
                        String detail = detail0.getValue();
                        String nama1 = typeEntity.getProperty("nama").toString();
                        String link1 = typeEntity.getProperty("link").toString();
                        String date = typeEntity.getProperty("date").toString();
                        record1.put("key", "kandidat" + type0);
                        record1.put("val", input);
                        record1.put("kandidat", kandidat);
                        record1.put("desc", desc);
                        record1.put("detail", detail);
                        record1.put("nama", nama1);
                        record1.put("link", link1);
                        record1.put("date", date);
                        String icwcomment = "";

                        if (email.equalsIgnoreCase("khairul.anshar@gmail.com")
                                || id.equalsIgnoreCase("112525777678499279265")
                                || id.equalsIgnoreCase("10152397276159760")
                                || nama.equalsIgnoreCase("Khairul Anshar") || admin.equalsIgnoreCase("Y")
                                || icw.equalsIgnoreCase("Y")) {
                            try {
                                icwcomment = typeEntity.getProperty("icwcomment").toString();
                            } catch (Exception e) {
                                icwcomment = "";
                            }
                        }
                        record1.put("icwcomment", icwcomment);
                        obj11.add(record1);
                    }
                }
            }

            record.put("records", obj11);
            record.put("status", "OK");
        } catch (Exception e) {
            record.put("status", "error");
            record.put("errormsg", e.toString());
        }
        response.setContentType("text/html;charset=UTF-8");
        out.print(JSONValue.toJSONString(record));
        out.flush();
    }
}

From source file:com.amalto.workbench.utils.Util.java

public static String getResponseFromURL(String url, TreeObject treeObj) throws Exception {
    InputStreamReader doc = null;
    try {//from  w  ww .j  a v  a2  s . c  om
        Encoder encoder = Base64.getEncoder();
        StringBuffer buffer = new StringBuffer();
        String credentials = encoder.encodeToString((new String(treeObj.getServerRoot().getUsername() + ":"//$NON-NLS-1$
                + treeObj.getServerRoot().getPassword()).getBytes()));

        URL urlCn = new URL(url);
        URLConnection conn = urlCn.openConnection();
        conn.setAllowUserInteraction(true);
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setRequestProperty("Authorization", "Basic " + credentials);//$NON-NLS-1$//$NON-NLS-2$
        conn.setRequestProperty("Expect", "100-continue");//$NON-NLS-1$//$NON-NLS-2$

        doc = new InputStreamReader(conn.getInputStream());
        BufferedReader reader = new BufferedReader(doc);
        String line = reader.readLine();
        while (line != null) {
            buffer.append(line);
            line = reader.readLine();
        }

        return buffer.toString();
    } finally {
        if (doc != null) {
            doc.close();
        }
    }
}