Example usage for java.net HttpURLConnection getResponseMessage

List of usage examples for java.net HttpURLConnection getResponseMessage

Introduction

In this page you can find the example usage for java.net HttpURLConnection getResponseMessage.

Prototype

public String getResponseMessage() throws IOException 

Source Link

Document

Gets the HTTP response message, if any, returned along with the response code from a server.

Usage

From source file:de.mpg.mpdl.inge.dataacquisition.DataHandlerBean.java

/**
 * Handlers the http request to fetch a file from an external source.
 * /*from w  w  w  . j  a va2  s. com*/
 * @param importSource
 * @param fulltext
 * @return byte[] of the fetched file
 * @throws SourceNotAvailableException
 * @throws RuntimeException
 */
private byte[] fetchFile(FullTextVO fulltext)
        throws SourceNotAvailableException, RuntimeException, AccessException, FormatNotAvailableException {
    URLConnection conn = null;
    byte[] input = null;
    try {
        conn = ProxyHelper.openConnection(fulltext.getFtUrl());
        HttpURLConnection httpConn = (HttpURLConnection) conn;
        int responseCode = httpConn.getResponseCode();
        switch (responseCode) {
        case 503:
            // request was not processed by source
            this.logger.warn("Import source " + this.currentSource.getName() + "did not provide data in format "
                    + fulltext.getFtLabel());
            throw new FormatNotAvailableException(fulltext.getFtLabel());
        case 302:
            String alternativeLocation = conn.getHeaderField("Location");
            fulltext.setFtUrl(new URL(alternativeLocation));
            return fetchFile(fulltext);
        case 200:
            this.logger.info("Source responded with 200.");
            GetMethod method = new GetMethod(fulltext.getFtUrl().toString());
            HttpClient client = new HttpClient();
            ProxyHelper.executeMethod(client, method);
            input = method.getResponseBody();
            httpConn.disconnect();
            break;
        case 403:
            throw new AccessException("Access to url " + this.currentSource.getName() + " is restricted.");
        default:
            throw new RuntimeException("An error occurred during importing from external system: "
                    + responseCode + ": " + httpConn.getResponseMessage());
        }
    } catch (AccessException e) {
        this.logger.error("Access denied.", e);
        throw new AccessException(this.currentSource.getName());
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    // bmc needs transformation from xml to html
    if (this.currentSource.getName().equalsIgnoreCase("BioMed Central")
            && fulltext.getFtFormat().equalsIgnoreCase("text/html")) {
        Format from = new Format("bmc_fulltext_xml", "application/xml", "*");
        Format to = new Format("bmc_fulltext_html", "text/html", "*");
        TransformationBean transformer = new TransformationBean();

        try {
            input = transformer.transform(input, from, to, "escidoc");
        } catch (Exception e) {
            this.logger.error("Could not transform BMC fulltext", e);
        }
    } else if (this.currentSource.getName().equalsIgnoreCase("PubMedCentral")
            && fulltext.getFtFormat().equalsIgnoreCase("application/pdf")) {
        // pmc pdf is generated from oai-pmh-xml
        Format from = new Format("pmc_fulltext_xml", "application/xml", "*");
        Format to = new Format("pmc_fulltext_xslfo", "text/xsl", "*");
        TransformationBean transformer = new TransformationBean();
        byte[] xslFo = null;
        try {
            xslFo = transformer.transform(input, from, to, "escidoc");

        } catch (Exception e) {
            this.logger.error("Could not transform PMC fulltext", e);
        }
        // Step 1: Construct a FopFactory
        FopFactory fopFactory = FopFactory.newInstance();

        // Step 2: Set up output stream.
        ByteArrayOutputStream outputPdf = new ByteArrayOutputStream();

        try {
            // Trying to load FOP-Configuration from the pubman.properties
            fopFactory.setUserConfig(new File(
                    PropertyReader.getProperty("escidoc.dataacquisition.resources.fop.configuration")));
        } catch (Exception e) {
            try {
                logger.info("FopFactory configuration couldn't be loaded from '"
                        + PropertyReader.getProperty("escidoc.dataacquisition.resources.fop.configuration")
                        + "'", e);

                // loading in-EAR configuration an fonts
                String dataaquisitionUrl = DataHandlerBean.class.getClassLoader().getResource("dataaquisition/")
                        .toString();
                logger.info("Trying to load FopFactory from: '" + dataaquisitionUrl + "apache-fop-config.xml'");
                fopFactory.setUserConfig(dataaquisitionUrl + "apache-fop-config.xml");
                fopFactory.setBaseURL(dataaquisitionUrl);
                fopFactory.getFontManager().setFontBaseURL(dataaquisitionUrl + "fonts/");
                if (logger.isDebugEnabled()) {
                    logger.debug(fopFactory.getBaseURL());
                    logger.debug(fopFactory.getFontManager().getFontBaseURL());
                }
            } catch (Exception exception) {
                logger.error("FopFactory configuration wasn't loaded correctly", exception);
            }
        }

        try {
            // Step 3: Construct fop with desired output format
            Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, outputPdf);

            SortedMap map = (new org.apache.fop.tools.fontlist.FontListGenerator()).listFonts(fopFactory,
                    MimeConstants.MIME_PDF, new org.apache.fop.fonts.FontEventAdapter(
                            new org.apache.fop.events.DefaultEventBroadcaster()));

            // Step 4: Setup JAXP using identity transformer
            TransformerFactory factory = TransformerFactory.newInstance("net.sf.saxon.TransformerFactoryImpl",
                    null);
            Transformer xmlTransformer = factory.newTransformer(); // identity transformer

            // Step 5: Setup input and output for XSLT transformation
            Source src = new StreamSource((InputStream) (new ByteArrayInputStream(xslFo)));

            // Resulting SAX events (the generated FO) must be piped through to FOP
            Result res = new SAXResult(fop.getDefaultHandler());

            // Step 6: Start XSLT transformation and FOP processing
            xmlTransformer.transform(src, res);

            // setting pdf as result
            input = outputPdf.toByteArray();
        } catch (Exception e) {
            logger.error("Error when trying to transform xsl-FO to PDF (Apache-FOP): ", e);
        } finally {
            // Clean-up
            try {
                outputPdf.close();
            } catch (IOException e) {
                logger.error("Couldn't close outputPdf-Stream", e);
            }
        }
    }

    return input;
}

From source file:de.mpg.escidoc.services.dataacquisition.DataHandlerBean.java

/**
 * Handlers the http request to fetch a file from an external source.
 * /*from w  w  w  .j  a va  2s  .  c  o m*/
 * @param importSource
 * @param fulltext
 * @return byte[] of the fetched file
 * @throws SourceNotAvailableException
 * @throws RuntimeException
 */
private byte[] fetchFile(FullTextVO fulltext)
        throws SourceNotAvailableException, RuntimeException, AccessException, FormatNotAvailableException {
    URLConnection conn = null;
    byte[] input = null;
    try {
        conn = ProxyHelper.openConnection(fulltext.getFtUrl());
        HttpURLConnection httpConn = (HttpURLConnection) conn;
        int responseCode = httpConn.getResponseCode();
        switch (responseCode) {
        case 503:
            // request was not processed by source
            this.logger.warn("Import source " + this.currentSource.getName() + "did not provide data in format "
                    + fulltext.getFtLabel());
            throw new FormatNotAvailableException(fulltext.getFtLabel());
        case 302:
            String alternativeLocation = conn.getHeaderField("Location");
            fulltext.setFtUrl(new URL(alternativeLocation));
            return fetchFile(fulltext);
        case 200:
            this.logger.info("Source responded with 200.");
            GetMethod method = new GetMethod(fulltext.getFtUrl().toString());
            HttpClient client = new HttpClient();
            ProxyHelper.executeMethod(client, method);
            input = method.getResponseBody();
            httpConn.disconnect();
            break;
        case 403:
            throw new AccessException("Access to url " + this.currentSource.getName() + " is restricted.");
        default:
            throw new RuntimeException("An error occurred during importing from external system: "
                    + responseCode + ": " + httpConn.getResponseMessage());
        }
    } catch (AccessException e) {
        this.logger.error("Access denied.", e);
        throw new AccessException(this.currentSource.getName());
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    // bmc needs transformation from xml to html
    if (this.currentSource.getName().equalsIgnoreCase("BioMed Central")
            && fulltext.getFtFormat().equalsIgnoreCase("text/html")) {
        Format from = new Format("bmc_fulltext_xml", "application/xml", "*");
        Format to = new Format("bmc_fulltext_html", "text/html", "*");
        TransformationBean transformer = new TransformationBean();

        try {
            input = transformer.transform(input, from, to, "escidoc");
        } catch (Exception e) {
            this.logger.error("Could not transform BMC fulltext", e);
        }
    } else if (this.currentSource.getName().equalsIgnoreCase("PubMedCentral")
            && fulltext.getFtFormat().equalsIgnoreCase("application/pdf")) {
        // pmc pdf is generated from oai-pmh-xml
        Format from = new Format("pmc_fulltext_xml", "application/xml", "*");
        Format to = new Format("pmc_fulltext_xslfo", "text/xsl", "*");
        TransformationBean transformer = new TransformationBean();
        byte[] xslFo = null;
        try {
            xslFo = transformer.transform(input, from, to, "escidoc");

        } catch (Exception e) {
            this.logger.error("Could not transform PMC fulltext", e);
        }
        // Step 1: Construct a FopFactory
        FopFactory fopFactory = FopFactory.newInstance();

        // Step 2: Set up output stream.
        ByteArrayOutputStream outputPdf = new ByteArrayOutputStream();

        try {
            // Trying to load FOP-Configuration from the pubman.properties
            fopFactory.setUserConfig(new File(
                    PropertyReader.getProperty("escidoc.dataacquisition.resources.fop.configuration")));
        } catch (Exception e) {
            try {
                logger.info("FopFactory configuration couldn't be loaded from '"
                        + PropertyReader.getProperty("escidoc.dataacquisition.resources.fop.configuration")
                        + "'", e);

                // loading in-EAR configuration an fonts
                String dataaquisitionUrl = DataHandlerBean.class.getClassLoader().getResource("dataaquisition/")
                        .toString();
                logger.info("Trying to load FopFactory from: '" + dataaquisitionUrl + "apache-fop-config.xml'");
                fopFactory.setUserConfig(dataaquisitionUrl + "apache-fop-config.xml");
                fopFactory.setBaseURL(dataaquisitionUrl);
                fopFactory.getFontManager().setFontBaseURL(dataaquisitionUrl + "fonts/");
                if (logger.isDebugEnabled()) {
                    logger.debug(fopFactory.getBaseURL());
                    logger.debug(fopFactory.getFontManager().getFontBaseURL());
                }
            } catch (Exception exception) {
                logger.error("FopFactory configuration wasn't loaded correctly", exception);
            }
        }

        try {
            // Step 3: Construct fop with desired output format
            Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, outputPdf);

            SortedMap map = (new org.apache.fop.tools.fontlist.FontListGenerator()).listFonts(fopFactory,
                    MimeConstants.MIME_PDF, new org.apache.fop.fonts.FontEventAdapter(
                            new org.apache.fop.events.DefaultEventBroadcaster()));

            // Step 4: Setup JAXP using identity transformer
            TransformerFactory factory = TransformerFactory.newInstance("net.sf.saxon.TransformerFactoryImpl",
                    null);
            Transformer xmlTransformer = factory.newTransformer(); // identity transformer

            // Step 5: Setup input and output for XSLT transformation
            Source src = new StreamSource((InputStream) (new ByteArrayInputStream(xslFo)));

            // Resulting SAX events (the generated FO) must be piped through to FOP
            Result res = new SAXResult(fop.getDefaultHandler());

            // Step 6: Start XSLT transformation and FOP processing
            xmlTransformer.transform(src, res);

            // setting pdf as result
            input = outputPdf.toByteArray();
        } catch (Exception e) {
            logger.error("Error when trying to transform xsl-FO to PDF (Apache-FOP): ", e);
        } finally {
            //Clean-up
            try {
                outputPdf.close();
            } catch (IOException e) {
                logger.error("Couldn't close outputPdf-Stream", e);
            }
        }
    }

    return input;
}

From source file:website.openeng.async.Connection.java

/**
 * Downloads any missing media files according to the mediaURL deckvar.
 *
 * @param data//w w  w.  j ava 2  s.c  o m
 * @return The return type contains data.resultType and an array of Integer in data.data. data.data[0] is the number
 *         of total missing media, data.data[1] is the number of downloaded ones.
 */
private Payload doInBackgroundDownloadMissingMedia(Payload data) {
    Timber.i("DownloadMissingMedia");
    HashMap<String, String> missingPaths = new HashMap<String, String>();
    HashMap<String, String> missingSums = new HashMap<String, String>();

    data.result = (Decks) data.data[0]; // pass it to the return object so we close the deck in the deck picker
    String syncName = "";// deck.getDeckName();

    data.success = false;
    data.data = new Object[] { 0, 0, 0 };
    // if (!deck.hasKey("mediaURL")) {
    // data.success = true;
    // return data;
    // }
    String urlbase = "";// deck.getVar("mediaURL");
    if (urlbase.equals("")) {
        data.success = true;
        return data;
    }

    String mdir = "";// deck.mediaDir(true);
    int totalMissing = 0;
    int missing = 0;
    int grabbed = 0;

    Cursor cursor = null;
    try {
        cursor = null;// deck.getDB().getDatabase().rawQuery("SELECT filename, originalPath FROM media", null);
        String path = null;
        String f = null;
        while (cursor.moveToNext()) {
            f = cursor.getString(0);
            path = mdir + "/" + f;
            File file = new File(path);
            if (!file.exists()) {
                missingPaths.put(f, path);
                missingSums.put(f, cursor.getString(1));
                Timber.d("Missing file: %s", f);
            }
        }
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }

    totalMissing = missingPaths.size();
    data.data[0] = totalMissing;
    if (totalMissing == 0) {
        data.success = true;
        return data;
    }
    publishProgress(Boolean.FALSE, totalMissing, 0, syncName);

    URL url = null;
    HttpURLConnection connection = null;
    String path = null;
    String sum = null;
    int readbytes = 0;
    byte[] buf = new byte[4096];
    for (String file : missingPaths.keySet()) {

        try {
            android.net.Uri uri = android.net.Uri.parse(Uri.encode(urlbase, ":/@%") + Uri.encode(file));
            url = new URI(uri.toString()).toURL();
            connection = (HttpURLConnection) url.openConnection();
            connection.connect();
            if (connection.getResponseCode() == 200) {
                path = missingPaths.get(file);
                InputStream is = connection.getInputStream();
                BufferedInputStream bis = new BufferedInputStream(is, 4096);
                FileOutputStream fos = new FileOutputStream(path);
                while ((readbytes = bis.read(buf, 0, 4096)) != -1) {
                    fos.write(buf, 0, readbytes);
                    Timber.d("Downloaded %d file: %s", readbytes, path);
                }
                fos.close();

                // Verify with checksum
                sum = missingSums.get(file);
                if (true) {// sum.equals("") || sum.equals(Utils.fileChecksum(path))) {
                    grabbed++;
                } else {
                    // Download corrupted, delete file
                    Timber.i("Downloaded media file %s failed checksum.", path);
                    File f = new File(path);
                    f.delete();
                    missing++;
                }
            } else {
                Timber.e("Connection error (" + connection.getResponseCode() + ") while retrieving media file "
                        + urlbase + file);
                Timber.e("Connection message: " + connection.getResponseMessage());
                if (missingSums.get(file).equals("")) {
                    // Ignore and keep going
                    missing++;
                } else {
                    data.success = false;
                    data.data = new Object[] { file };
                    return data;
                }
            }
            connection.disconnect();
        } catch (URISyntaxException e) {
            Timber.e(e, "doInBackgroundDownloadMissingMedia URISyntaxException");
        } catch (MalformedURLException e) {
            Timber.e(e, "MalformedURLException while download media file " + path);
            if (missingSums.get(file).equals("")) {
                // Ignore and keep going
                missing++;
            } else {
                data.success = false;
                data.data = new Object[] { file };
                return data;
            }
        } catch (IOException e) {
            Timber.e(e, "IOException while download media file " + path);
            if (missingSums.get(file).equals("")) {
                // Ignore and keep going
                missing++;
            } else {
                data.success = false;
                data.data = new Object[] { file };
                return data;
            }
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
        }
        publishProgress(Boolean.TRUE, totalMissing, grabbed + missing, syncName);
    }

    data.data[1] = grabbed;
    data.data[2] = missing;
    data.success = true;
    return data;
}

From source file:com.centurylink.mdw.util.HttpHelper.java

/**
 * Populates the response member.  Closes the connection.
 *//*from   www  .  j a  v  a2  s . co  m*/
private void readInput(HttpURLConnection connection) throws IOException {
    InputStream is = null;
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    try {
        byte[] buffer = new byte[2048];
        try {
            is = connection.getInputStream();
            while (maxBytes == -1 || baos.size() < maxBytes) {
                int bytesRead = is.read(buffer);
                if (bytesRead == -1)
                    break;
                baos.write(buffer, 0, bytesRead);
            }
            response = baos.toByteArray();
            if (followHtmlHeadMetaRefresh && getResponse().indexOf("http-equiv") > 0) {
                try {
                    redirect = parseResponseForHtmlMetaEquiv(getResponse());
                    if (redirect != null)
                        response = new HttpHelper(this, redirect).getBytes();
                } catch (Exception ex) {
                    throw new IllegalArgumentException("Unparseable response: " + ex.getMessage(), ex);
                }

            }
        } catch (IOException ex) {
            InputStream eis = null;
            try {
                eis = connection.getErrorStream();
                while (maxBytes == -1 || baos.size() < maxBytes) {
                    int bytesRead = eis.read(buffer);
                    if (bytesRead == -1)
                        break;
                    baos.write(buffer, 0, bytesRead);
                }
                response = baos.toByteArray();
            } catch (Exception ex2) {
                // throw original exception
            } finally {
                if (eis != null) {
                    eis.close();
                }
            }
            throw ex;
        }
    } finally {
        if (is != null)
            is.close();
        connection.disconnect();
        responseCode = connection.getResponseCode();
        responseMessage = connection.getResponseMessage();
        headers = new HashMap<String, String>();
        for (String headerKey : connection.getHeaderFields().keySet()) {
            if (headerKey == null)
                headers.put("HTTP", connection.getHeaderField(headerKey));
            else
                headers.put(headerKey, connection.getHeaderField(headerKey));
        }
    }
}

From source file:com.orange.labs.sdk.RestUtils.java

public void uploadRequest(URL url, File file, String folderIdentifier, final Map<String, String> headers,
        final OrangeListener.Success<JSONObject> success, final OrangeListener.Progress progress,
        final OrangeListener.Error failure) {

    // open a URL connection to the Server
    FileInputStream fileInputStream = null;
    try {// w  w w  . j a v  a  2  s. c om
        fileInputStream = new FileInputStream(file);

        // Open a HTTP connection to the URL
        HttpURLConnection conn = (HttpsURLConnection) url.openConnection();

        // Allow Inputs & Outputs
        conn.setDoInput(true);
        conn.setDoOutput(true);

        // Don't use a Cached Copy
        conn.setUseCaches(false);

        conn.setRequestMethod("POST");

        //
        // Define headers
        //

        // Create an unique boundary
        String boundary = "UploadBoundary";

        conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
        for (String key : headers.keySet()) {
            conn.setRequestProperty(key.toString(), headers.get(key));
        }

        //
        // Write body part
        //
        DataOutputStream dos = new DataOutputStream(conn.getOutputStream());

        int bytesAvailable = fileInputStream.available();

        String marker = "\r\n--" + boundary + "\r\n";

        dos.writeBytes(marker);
        dos.writeBytes("Content-Disposition: form-data; name=\"description\"\r\n\r\n");

        // Create JSonObject :
        JSONObject params = new JSONObject();
        params.put("name", file.getName());
        params.put("size", String.valueOf(bytesAvailable));
        params.put("folder", folderIdentifier);

        dos.writeBytes(params.toString());

        dos.writeBytes(marker);
        dos.writeBytes(
                "Content-Disposition: form-data; name=\"file\"; filename=\"" + file.getName() + "\"\r\n");
        dos.writeBytes("Content-Type: image/jpeg\r\n\r\n");

        int progressValue = 0;
        int bytesRead = 0;
        byte buf[] = new byte[1024];
        BufferedInputStream bufInput = new BufferedInputStream(fileInputStream);
        while ((bytesRead = bufInput.read(buf)) != -1) {
            // write output
            dos.write(buf, 0, bytesRead);
            dos.flush();
            progressValue += bytesRead;
            // update progress bar
            progress.onProgress((float) progressValue / bytesAvailable);
        }

        dos.writeBytes(marker);

        //
        // Responses from the server (code and message)
        //
        int serverResponseCode = conn.getResponseCode();
        String serverResponseMessage = conn.getResponseMessage();

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

        if (serverResponseCode == 200 || serverResponseCode == 201) {
            BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));

            String response = "";
            String line;
            while ((line = rd.readLine()) != null) {
                Log.i("FileUpload", "Response: " + line);
                response += line;
            }
            rd.close();
            JSONObject object = new JSONObject(response);
            success.onResponse(object);
        } else {
            BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getErrorStream()));
            String response = "";
            String line;
            while ((line = rd.readLine()) != null) {
                Log.i("FileUpload", "Error: " + line);
                response += line;
            }
            rd.close();
            JSONObject errorResponse = new JSONObject(response);
            failure.onErrorResponse(new CloudAPIException(serverResponseCode, errorResponse));
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (ProtocolException e) {
        e.printStackTrace();
    } catch (JSONException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:de.sjka.logstash.osgi.internal.LogstashSender.java

private void process(LogEntry logEntry) {
    if (logEntry.getLevel() <= getLogLevelConfig()) {
        if (!"true".equals(getConfig(LogstashConfig.ENABLED))) {
            return;
        }// w  w  w .  j ava  2s  .c o  m
        ;
        for (ILogstashFilter logstashFilter : logstashFilters) {
            if (!logstashFilter.apply(logEntry)) {
                return;
            }
        }
        String request = getConfig(LogstashConfig.URL);
        if (!request.endsWith("/")) {
            request += "/";
        }
        HttpURLConnection conn = null;
        try {
            JSONObject values = serializeLogEntry(logEntry);

            String payload = values.toJSONString();
            byte[] postData = payload.getBytes(StandardCharsets.UTF_8);

            String username = getConfig(LogstashConfig.USERNAME);
            String password = getConfig(LogstashConfig.PASSWORD);

            String authString = username + ":" + password;
            byte[] authEncBytes = Base64.encodeBase64(authString.getBytes());
            String authStringEnc = new String(authEncBytes);

            URL url = new URL(request);

            conn = (HttpURLConnection) url.openConnection();
            if (request.startsWith("https") && "true".equals(getConfig(LogstashConfig.SSL_NO_CHECK))) {
                if (sslSocketFactory != null) {
                    ((HttpsURLConnection) conn).setSSLSocketFactory(sslSocketFactory);
                    ((HttpsURLConnection) conn).setHostnameVerifier(new HostnameVerifier() {
                        @Override
                        public boolean verify(String hostname, SSLSession session) {
                            return true;
                        }
                    });
                }
            }
            conn.setDoOutput(true);
            conn.setInstanceFollowRedirects(false);
            conn.setRequestMethod("PUT");
            conn.setRequestProperty("Content-Type", "application/json");
            conn.setRequestProperty("charset", "utf-8");
            conn.setReadTimeout(30 * SECONDS);
            conn.setConnectTimeout(30 * SECONDS);
            if (username != null && !"".equals(username)) {
                conn.setRequestProperty("Authorization", "Basic " + authStringEnc);
            }
            conn.setUseCaches(false);
            try (DataOutputStream wr = new DataOutputStream(conn.getOutputStream())) {
                wr.write(postData);
                wr.flush();
                wr.close();
            }
            if (conn.getResponseCode() != 200) {
                throw new IOException(
                        "Got response " + conn.getResponseCode() + " - " + conn.getResponseMessage());
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            if (conn != null) {
                conn.disconnect();
            }
        }
    }

}

From source file:com.google.ytd.SubmitActivity.java

private String uploadMetaData(String filePath, boolean retry) throws IOException {
    String uploadUrl = INITIAL_UPLOAD_URL;

    HttpURLConnection urlConnection = getGDataUrlConnection(uploadUrl);
    urlConnection.setRequestMethod("POST");
    urlConnection.setDoOutput(true);/*from  ww  w .  j  a v  a2s. c o m*/
    urlConnection.setRequestProperty("Content-Type", "application/atom+xml");
    urlConnection.setRequestProperty("Slug", filePath);
    String atomData;

    String title = getTitleText();
    String description = getDescriptionText();
    String category = DEFAULT_VIDEO_CATEGORY;
    this.tags = DEFAULT_VIDEO_TAGS;

    if (!Util.isNullOrEmpty(this.getTagsText())) {
        this.tags = this.getTagsText();
    }

    if (this.videoLocation == null) {
        String template = Util.readFile(this, R.raw.gdata).toString();
        atomData = String.format(template, title, description, category, this.tags);
    } else {
        String template = Util.readFile(this, R.raw.gdata_geo).toString();
        atomData = String.format(template, title, description, category, this.tags, videoLocation.getLatitude(),
                videoLocation.getLongitude());
    }

    OutputStreamWriter outStreamWriter = new OutputStreamWriter(urlConnection.getOutputStream());
    outStreamWriter.write(atomData);
    outStreamWriter.close();

    int responseCode = urlConnection.getResponseCode();
    if (responseCode < 200 || responseCode >= 300) {
        // The response code is 40X
        if ((responseCode + "").startsWith("4") && retry) {
            Log.d(LOG_TAG, "retrying to fetch auth token for " + youTubeName);
            this.clientLoginToken = authorizer.getFreshAuthToken(youTubeName, clientLoginToken);
            // Try again with fresh token
            return uploadMetaData(filePath, false);
        } else {
            throw new IOException(String.format("response code='%s' (code %d)" + " for %s",
                    urlConnection.getResponseMessage(), responseCode, urlConnection.getURL()));
        }
    }

    return urlConnection.getHeaderField("Location");
}

From source file:jetbrains.buildServer.vmgr.agent.Utils.java

public String executeAPI(String jSON, String apiUrl, String url, boolean requireAuth, String user,
        String password, String requestMethod, BuildProgressLogger logger, boolean dynamicUserId,
        String buildID, String workPlacePath) throws Exception {

    try {/* w w w .  j  ava  2  s . c o  m*/

        boolean notInTestMode = true;
        if (logger == null) {
            notInTestMode = false;
        }

        String apiURL = url + "/rest" + apiUrl;

        if (notInTestMode) {
            logger.message("vManager vAPI - Trying to call vAPI '" + "/rest" + apiUrl + "'");
        }
        String input = jSON;
        HttpURLConnection conn = getVAPIConnection(apiURL, requireAuth, user, password, requestMethod,
                dynamicUserId, buildID, workPlacePath, logger);

        if ("PUT".equals(requestMethod) || "POST".equals(requestMethod)) {
            OutputStream os = conn.getOutputStream();
            os.write(input.getBytes());
            os.flush();
        }

        if (conn.getResponseCode() != HttpURLConnection.HTTP_OK
                && conn.getResponseCode() != HttpURLConnection.HTTP_NO_CONTENT
                && conn.getResponseCode() != HttpURLConnection.HTTP_ACCEPTED
                && conn.getResponseCode() != HttpURLConnection.HTTP_CREATED
                && conn.getResponseCode() != HttpURLConnection.HTTP_PARTIAL
                && conn.getResponseCode() != HttpURLConnection.HTTP_RESET) {
            String reason = "";
            if (conn.getResponseCode() == 503)
                reason = "vAPI process failed to connect to remote vManager server.";
            if (conn.getResponseCode() == 401)
                reason = "Authentication Error";
            if (conn.getResponseCode() == 415)
                reason = "The server is refusing to service the request because the entity of the request is in a format not supported by the requested resource for the requested method.  Check if you selected the right request method (GET/POST/DELETE/PUT).";
            if (conn.getResponseCode() == 405)
                reason = "The method specified in the Request-Line is not allowed for the resource identified by the Request-URI. The response MUST include an Allow header containing a list of valid methods for the requested resource.  Check if you selected the right request method (GET/POST/DELETE/PUT).";
            if (conn.getResponseCode() == 412)
                reason = "vAPI requires vManager 'Integration Server' license.";
            String errorMessage = "Failed : HTTP error code : " + conn.getResponseCode() + " (" + reason + ")";
            if (notInTestMode) {
                logger.message(errorMessage);
                logger.message(conn.getResponseMessage());
            }

            System.out.println(errorMessage);
            return errorMessage;
        }

        BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));

        StringBuilder result = new StringBuilder();
        String output;
        while ((output = br.readLine()) != null) {
            result.append(output);
        }

        conn.disconnect();

        // Flush the output into workspace
        String fileOutput = workPlacePath + File.separator + buildID + File.separator + "vapi.output";

        FileWriter writer = new FileWriter(fileOutput);

        writer.append(result.toString());
        writer.flush();
        writer.close();

        String textOut = "API Call Success: Output was saved into: " + fileOutput;

        if (notInTestMode) {
            logger.message(textOut);
        } else {

            System.out.println(textOut);
        }

        return "success";

    } catch (Exception e) {
        e.printStackTrace();
        logger.error("Failed: Error: " + e.getMessage());
        return e.getMessage();
    }
}

From source file:com.google.ytd.picasa.PicasaApiHelper.java

public String getResumableUploadUrl(com.google.ytd.model.PhotoEntry photoEntry, String title,
        String description, String albumId, Double latitude, Double longitude) throws IllegalArgumentException {
    LOG.info(String.format("Resumable upload request.\nTitle: %s\nDescription: %s\nAlbum: %s", title,
            description, albumId));/*from   ww w  .  j a v  a2s. c  o m*/

    // Picasa API resumable uploads are not currently documented publicly, but they're essentially
    // the same as what YouTube API offers:
    // http://code.google.com/apis/youtube/2.0/developers_guide_protocol_resumable_uploads.html
    // The Java client library does offer support for resumable uploads, but its use of threads
    // and some other assumptions makes it unsuitable for our purposes.
    try {
        URL url = new URL(String.format(RESUMABLE_UPLOADS_URL_FORMAT, albumId));
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoOutput(true);
        connection.setConnectTimeout(CONNECT_TIMEOUT);
        connection.setReadTimeout(READ_TIMEOUT);
        connection.setRequestMethod("POST");

        // Set all the GData request headers. These strings should probably be moved to CONSTANTS.
        connection.setRequestProperty("Content-Type", "application/atom+xml;charset=UTF-8");
        connection.setRequestProperty("Authorization",
                String.format("AuthSub token=\"%s\"", adminConfigDao.getAdminConfig().getPicasaAuthSubToken()));
        connection.setRequestProperty("GData-Version", "2.0");
        connection.setRequestProperty("Slug", photoEntry.getOriginalFileName());
        connection.setRequestProperty("X-Upload-Content-Type", photoEntry.getFormat());
        connection.setRequestProperty("X-Upload-Content-Length",
                String.valueOf(photoEntry.getOriginalFileSize()));

        // If we're given lat/long then create the element to geotag the picture; otherwise, pass in
        // and empty string for no geotag.
        String geoRss = "";
        if (latitude != null && longitude != null) {
            geoRss = String.format(GEO_RSS_XML_FORMAT, latitude, longitude);
            LOG.info("Geo RSS XML: " + geoRss);
        }

        String atomXml = String.format(UPLOAD_ENTRY_XML_FORMAT, StringEscapeUtils.escapeXml(title),
                StringEscapeUtils.escapeXml(description), geoRss);

        OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
        writer.write(atomXml);
        writer.close();

        if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
            String uploadUrl = connection.getHeaderField("Location");
            if (util.isNullOrEmpty(uploadUrl)) {
                throw new IllegalArgumentException("No Location header found in HTTP response.");
            } else {
                LOG.info("Resumable upload URL is " + uploadUrl);

                return uploadUrl;
            }
        } else {
            LOG.warning(String.format("HTTP POST to %s returned status %d (%s).", url.toString(),
                    connection.getResponseCode(), connection.getResponseMessage()));
        }
    } catch (MalformedURLException e) {
        LOG.log(Level.WARNING, "", e);

        throw new IllegalArgumentException(e);
    } catch (IOException e) {
        LOG.log(Level.WARNING, "", e);
    }

    return null;
}

From source file:de.mpg.escidoc.services.dataacquisition.DataHandlerBean.java

/**
 * Fetches an OAI record for given record identifier.
 * //from   www. j  a  va2s. co  m
 * @param sourceURL
 * @return itemXML
 * @throws IdentifierNotRecognisedException
 * @throws SourceNotAvailableException
 * @throws RuntimeException
 */
private String fetchOAIRecord(MetadataVO md) throws SourceNotAvailableException, AccessException,
        IdentifierNotRecognisedException, RuntimeException {
    String itemXML = "";
    URLConnection conn;
    Date retryAfter;
    InputStreamReader isReader;
    BufferedReader bReader;
    try {
        conn = ProxyHelper.openConnection(md.getMdUrl());
        HttpURLConnection httpConn = (HttpURLConnection) conn;
        int responseCode = httpConn.getResponseCode();
        switch (responseCode) {
        case 503:
            String retryAfterHeader = conn.getHeaderField("Retry-After");
            if (retryAfterHeader != null) {
                SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z");
                retryAfter = dateFormat.parse(retryAfterHeader);
                this.logger.debug("Source responded with 503, retry after " + retryAfter + ".");
                throw new SourceNotAvailableException(retryAfter);
            } else {
                this.logger.debug(
                        "Source responded with 503, retry after " + this.currentSource.getRetryAfter() + ".");
                throw new SourceNotAvailableException(this.currentSource.getRetryAfter());
            }
        case 302:
            String alternativeLocation = conn.getHeaderField("Location");
            md.setMdUrl(new URL(alternativeLocation));
            this.currentSource = this.sourceHandler.updateMdEntry(this.currentSource, md);
            return fetchOAIRecord(md);
        case 200:
            this.logger.info("Source responded with 200");
            break;
        case 403:
            throw new AccessException("Access to url " + this.currentSource.getName() + " is restricted.");
        default:
            throw new RuntimeException("An error occurred during importing from external system: "
                    + responseCode + ": " + httpConn.getResponseMessage());
        }

        // Get itemXML
        isReader = new InputStreamReader(md.getMdUrl().openStream(), this.enc);
        bReader = new BufferedReader(isReader);
        String line = "";
        while ((line = bReader.readLine()) != null) {
            itemXML += line + "\n";
        }
        httpConn.disconnect();
    } catch (AccessException e) {
        this.logger.error("Access denied.", e);
        throw new AccessException(this.currentSource.getName());
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    return itemXML;
}