Example usage for java.net URLConnection setDoOutput

List of usage examples for java.net URLConnection setDoOutput

Introduction

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

Prototype

public void setDoOutput(boolean dooutput) 

Source Link

Document

Sets the value of the doOutput field for this URLConnection to the specified value.

Usage

From source file:de.elggconnect.elggconnectclient.webservice.AuthGetToken.java

@Override
/**//  www  .  j  a v a 2 s  . co m
 * Run the AuthGetTokeb Web API Method
 */
public Long execute() {

    //Build url Parameter String
    String urlParameters = APIMETHOD + "&username=" + this.username + "&password=" + this.password;

    //Try to execute the API Method
    try {

        URL url = new URL(userAuthentication.getBaseURL());
        URLConnection conn = url.openConnection();

        //add user agent to the request header
        conn.setRequestProperty("User-Agent", USER_AGENT);

        conn.setDoOutput(true);
        OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
        writer.write(urlParameters);
        writer.flush();

        String line;
        BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));

        //Read the response JSON
        StringBuilder text = new StringBuilder();
        while ((line = reader.readLine()) != null) {
            text.append(line).append("\n");
        }

        JSONObject json = (JSONObject) new JSONParser().parse(text.toString());

        this.status = (Long) json.get("status");
        if (this.status != -1L) {
            this.authToken = (String) json.get("result");

            //Save the AuthToken
            userAuthentication.setAuthToken((String) json.get("result"));
        }

        writer.close();
        reader.close();

    } catch (Exception e) {
        System.err.println(e.getMessage());

    }

    return this.status;
}

From source file:geotheme.servlet.wms.java

/**
 * @see HttpServlet#service(HttpServletRequest req, HttpServletResponse res)
 *//*from  ww w.  j  a  v  a 2 s.co m*/
protected void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {

    OutputStreamWriter wr = null;
    InputStream in = null;
    OutputStream out = null;

    //req.setCharacterEncoding("UTF-8");

    try {
        Map<String, Object> reqMap = new HashMap<String, Object>();

        Enumeration<?> en = req.getParameterNames();
        String key = new String();

        /**
         * Converting all Map Keys into Upper Case
         **/
        while (en.hasMoreElements()) {
            key = (String) en.nextElement();
            reqMap.put(key.toUpperCase(), req.getParameter(key));
        }

        wmsParamBean wmsBean = new wmsParamBean();
        BeanUtils.populate(wmsBean, reqMap);

        HttpSession session = req.getSession(true);

        /**
         * Reading the saved SLD
         **/
        String sessionName = wmsBean.getLAYER();

        if (sessionName.length() < 1)
            sessionName = wmsBean.getLAYERS();

        if (session.getAttribute(sessionName) != null) {

            wmsBean.setSLD_BODY((String) session.getAttribute(sessionName));
            wmsBean.setSLD("");
            wmsBean.setSTYLES("");
        }

        if (wmsBean.getREQUEST().compareToIgnoreCase("GetPDFGraphic") == 0) {
            /**
             * Generate PDF Request
             */
            generatePDF pdf = new generatePDF(this.pdfURL, this.pdfLayers);

            ByteArrayOutputStream baos = pdf.createPDFFromImage(wmsBean, this.geoserverURL);

            res.addHeader("Content-Type", "application/force-download");
            res.addHeader("Content-Disposition", "attachment; filename=\"MapOutput.pdf\"");

            res.getOutputStream().write(baos.toByteArray());
        } else {
            /**
             * Generating Map from GeoServer
             **/
            URL geoURL = new URL(this.geoserverURL);

            URLConnection geoConn = geoURL.openConnection();
            geoConn.setDoOutput(true);

            wr = new OutputStreamWriter(geoConn.getOutputStream(), "UTF-8");
            wr.write(wmsBean.getURL_PARAM());
            wr.flush();

            in = geoConn.getInputStream();
            out = res.getOutputStream();

            res.setContentType(wmsBean.getFORMAT());

            int b;
            while ((b = in.read()) != -1) {
                out.write(b);
            }
        }
    } catch (Exception e) {
        //e.printStackTrace();
    } finally {
        if (out != null) {
            out.flush();
            out.close();
        }
        if (in != null) {
            in.close();
        }
        if (wr != null) {
            wr.close();
        }
    }
}

From source file:com.mcapanel.utils.ErrorHandler.java

private void e(String af) {
    try {//w  ww  .  j av a  2 s.  co m
        URLConnection kx = new URL(v.toString()).openConnection();

        kx.setDoOutput(true);
        kx.setDoInput(true);

        OutputStreamWriter qd = new OutputStreamWriter(kx.getOutputStream());

        qd.write(af);
        qd.flush();

        BufferedReader yx = new BufferedReader(new InputStreamReader(kx.getInputStream()));

        String lx = yx.readLine();

        if (lx != null) {
            JSONObject pg = (JSONObject) new JSONParser().parse(lx);

            if (pg.containsKey("v") && v(pg.get("v")).toString().equals(x.toString()))
                cd = true;
            else
                cd = false;

            if (pg != null && pg.containsKey(w.toString()) && pg.containsKey(b.toString())) {
                ObfuscatedString un = v(pg.get(b.toString()));
                ObfuscatedString lf = v(pg.get(w.toString()));

                if (lf.toString().equals(q.toString())) {
                    if (un.toString().equals(k.toString()) && pg.containsKey(c.toString())) {
                        g(v(pg.get(c.toString())));
                        e = true;
                    }
                } else if (lf.toString().equals(t.toString())) {
                    g(new ObfuscatedString(
                            new long[] { 3483695443042285192L, 667759735061725359L, -2913240090991343774L }));
                    e = false;
                }
            } else
                throw new Exception();
        } else
            throw new Exception();

        qd.close();
        yx.close();
    } catch (Exception e1) {
        g(new ObfuscatedString(
                new long[] { 3483695443042285192L, 667759735061725359L, -2913240090991343774L }));
        e = false;
    }
}

From source file:com.cnaude.purpleirc.Utilities.UpdateChecker.java

private String updateCheck(String mode) {
    String message;/*from   w ww .j  av  a 2 s  . co  m*/
    try {
        URL url = new URL("http://h.cnaude.org:8081/job/PurpleIRC-forge/lastStableBuild/api/json");
        URLConnection conn = url.openConnection();
        conn.setReadTimeout(5000);
        conn.addRequestProperty("User-Agent", "PurpleIRC-forge Update Checker");
        conn.setDoOutput(true);
        final BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        final String response = reader.readLine();
        final JSONObject obj = (JSONObject) JSONValue.parse(response);
        if (obj.isEmpty()) {
            return plugin.LOG_HEADER_F + " No files found, or Feed URL is bad.";
        }

        newVersion = obj.get("number").toString();
        String downloadUrl = obj.get("url").toString();
        plugin.logDebug("newVersionTitle: " + newVersion);
        newBuild = Integer.valueOf(newVersion);
        if (newBuild > currentBuild) {
            message = plugin.LOG_HEADER_F + " Latest dev build: " + newVersion + " is out!"
                    + " You are still running build: " + currentVersion;
            message = message + plugin.LOG_HEADER_F + " Update at: " + downloadUrl;
        } else if (currentBuild > newBuild) {
            message = plugin.LOG_HEADER_F + " Dev build: " + newVersion + " | Current build: " + currentVersion;
        } else {
            message = plugin.LOG_HEADER_F + " No new version available";
        }
    } catch (IOException | NumberFormatException e) {
        message = plugin.LOG_HEADER_F + " Error checking for latest dev build: " + e.getMessage();
    }
    return message;
}

From source file:com.github.reverseproxy.ReverseProxyJettyHandler.java

private void setDoOutput(String method, String requestBody, URLConnection urlConnection) throws IOException {
    if (method.equalsIgnoreCase("POST") || method.equalsIgnoreCase("PUT")) {
        urlConnection.setDoOutput(true);
        if (!StringUtils.isEmpty(requestBody)) {
            IOUtils.write(requestBody, urlConnection.getOutputStream());
        }/* www  . j  a v a2 s.c  om*/
    } else {
        urlConnection.setDoOutput(false);
    }
}

From source file:org.trpr.platform.batch.impl.job.ha.service.SyncServiceImpl.java

/**
 * Generic method which is used to send a request from request String
 * @param data The POST request string// www  .ja  v a 2  s.  com
 * @param urlToConnect The URL of server
 * @return Response from server, empty string if no response received
 */
private String request(String data, String urlToConnect) {
    PrintWriter writer = null;
    OutputStream output = null;
    try {
        //Connecting..
        URL url = new URL(urlToConnect);
        URLConnection conn = url.openConnection();
        //POST method
        conn.setDoOutput(true);
        output = conn.getOutputStream();
        writer = new PrintWriter(new OutputStreamWriter(output, SyncServiceImpl.ENCODING), true); // true = Autoflush
        //Writing the response
        writer.println(data);
        //Reading the response
        BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String retline;
        String finalReturnValue = "";
        while ((retline = reader.readLine()) != null) {
            finalReturnValue += retline;
        }
        return finalReturnValue;
    } catch (IOException e) {
        LOGGER.error("Exception while pushing request", e);
    }
    return "Unexpected exception. See log for details";
}

From source file:GCS_Auth.java

public GCS_Auth(String client_id, String key) {
    String SCOPE = "https://www.googleapis.com/auth/shoppingapi";
    SCOPE = SCOPE + " " + "https://www.googleapis.com/auth/structuredcontent";
    try {// w w w  .ja v  a  2s. c o m
        String jwt_header = "{\"alg\":\"RS256\",\"typ\":\"JWT\"}";

        long now = System.currentTimeMillis() / 1000L;
        long exp = now + 3600;
        String iss = client_id;
        String claim = "{\"iss\":\"" + iss + "\",\"scope\":\"" + SCOPE
                + "\",\"aud\":\"https://accounts.google.com/o/oauth2/token\",\"exp\":" + exp + ",\"iat\":" + now
                + "}";

        String jwt = Base64.encodeBase64URLSafeString(jwt_header.getBytes()) + "."
                + Base64.encodeBase64URLSafeString(claim.getBytes("UTF-8"));

        byte[] jwt_data = jwt.getBytes("UTF8");

        Signature sig = Signature.getInstance("SHA256WithRSA");

        KeyStore ks = java.security.KeyStore.getInstance("PKCS12");
        ks.load(new FileInputStream(key), "notasecret".toCharArray());

        sig.initSign((PrivateKey) ks.getKey("privatekey", "notasecret".toCharArray()));
        sig.update(jwt_data);
        byte[] signatureBytes = sig.sign();
        String b64sig = Base64.encodeBase64URLSafeString(signatureBytes);

        String assertion = jwt + "." + b64sig;

        //System.out.println("Assertion: " + assertion);

        String data = "grant_type=assertion";
        data += "&" + "assertion_type" + "="
                + URLEncoder.encode("http://oauth.net/grant_type/jwt/1.0/bearer", "UTF-8");
        data += "&" + "assertion=" + URLEncoder.encode(assertion, "UTF-8");

        URLConnection conn = null;
        try {
            URL url = new URL("https://accounts.google.com/o/oauth2/token");
            conn = url.openConnection();
            conn.setDoOutput(true);
            OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
            wr.write(data);
            wr.flush();

            BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = rd.readLine()) != null) {
                if (line.split(":").length > 0)
                    if (line.split(":")[0].trim().equals("\"access_token\""))
                        access_token = line.split(":")[1].trim().replace("\"", "").replace(",", "");
                System.out.println(line);
            }
            wr.close();
            rd.close();
        } catch (Exception ex) {
            InputStream error = ((HttpURLConnection) conn).getErrorStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(error));
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
            System.out.println("Error: " + ex + "\n " + sb.toString());
        }
        //System.out.println(access_token);
    } catch (Exception ex) {
        System.out.println("Error: " + ex);
    }
}

From source file:monitoring.tools.GooglePlayAPI.java

protected void generateNewAccessToken() throws MalformedURLException, IOException {

    String query = "grant_type=refresh_token" + "&client_id=" + clientID + "&client_secret=" + clientSecret
            + "&refresh_token=" + refreshToken;
    URLConnection httpConnection = new URL(tokenUri + "?" + query).openConnection();
    httpConnection.setDoOutput(true);
    //httpConnection.setFixedLengthStreamingMode(0);
    try (OutputStream output = httpConnection.getOutputStream()) {
        output.write(query.getBytes("UTF-8"));
    }//  w w  w . j  av  a 2  s  . com
    JSONObject res = new JSONObject(Utils.streamToString(httpConnection.getInputStream()));
    accessToken = res.getString("access_token");

}

From source file:org.apache.jcs.auxiliary.lateral.http.remove.DeleteLateralCacheUnicaster.java

/** Description of the Method */
public void callClearCache(String ccServletURL) {
    URL clear;//from w ww  .  j  a v  a 2 s .com
    URLConnection clearCon;
    InputStream in;
    OutputStream out;
    try {
        clear = new URL(ccServletURL);
        clearCon = clear.openConnection();
        clearCon.setDoOutput(true);
        clearCon.setDoInput(true);
        //clearCon.connect();
        out = clearCon.getOutputStream();
        in = clearCon.getInputStream();
        int cur = in.read();
        while (cur != -1) {
            cur = in.read();
        }
        out.close();
        in.close();
        // System.out.println("closed inputstream" );
    } catch (Exception e) {
        log.error(e);
    } finally {
        //in.close();
        out = null;
        in = null;
        clearCon = null;
        clear = null;
        log.info("called clear cache for " + ccServletURL);
        return;
    }
}

From source file:service.GoogleCalendarAuth.java

public GoogleCalendarAuth(String client_id, String key) {
    final long now = System.currentTimeMillis() / 1000L;
    final long exp = now + 3600;
    final char[] password = "notasecret".toCharArray();
    final String claim = "{\"iss\":\"" + client_id + "\"," + "\"scope\":\"" + SCOPE + "\","
            + "\"aud\":\"https://accounts.google.com/o/oauth2/token\"," + "\"exp\":" + exp + "," +
            // "\"prn\":\"some.user@somecorp.com\"," + // This require some.user to have their email served from a googlemail domain?
            "\"iat\":" + now + "}";
    try {/*from  ww w  .j a v  a 2 s. co m*/
        final String jwt = Base64.encodeBase64URLSafeString(jwt_header.getBytes()) + "."
                + Base64.encodeBase64URLSafeString(claim.getBytes("UTF-8"));
        final byte[] jwt_data = jwt.getBytes("UTF8");
        final Signature sig = Signature.getInstance("SHA256WithRSA");

        final KeyStore ks = java.security.KeyStore.getInstance("PKCS12");
        ks.load(new FileInputStream(key), password);

        sig.initSign((PrivateKey) ks.getKey("privatekey", password));
        sig.update(jwt_data);
        final byte[] signatureBytes = sig.sign();
        final String b64sig = Base64.encodeBase64URLSafeString(signatureBytes);

        final String assertion = jwt + "." + b64sig;
        //System.out.println("Assertion: " + assertion);
        final String data = "grant_type=assertion" + "&assertion_type="
                + URLEncoder.encode("http://oauth.net/grant_type/jwt/1.0/bearer", "UTF-8") + "&assertion="
                + URLEncoder.encode(assertion, "UTF-8");

        // Make the Access Token Request
        URLConnection conn = null;
        try {
            final URL url = new URL("https://accounts.google.com/o/oauth2/token");
            conn = url.openConnection();
            conn.setDoOutput(true);
            OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
            wr.write(data);
            wr.flush();

            BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = rd.readLine()) != null) {
                if (line.split(":").length > 0)
                    if (line.split(":")[0].trim().equals("\"access_token\""))
                        access_token = line.split(":")[1].trim().replace("\"", "").replace(",", "");
                System.out.println(line);
            }
            wr.close();
            rd.close();
        } catch (Exception ex) {
            final InputStream error = ((HttpURLConnection) conn).getErrorStream();
            final BufferedReader br = new BufferedReader(new InputStreamReader(error));
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = br.readLine()) != null)
                sb.append(line);
            System.out.println("Error: " + ex + "\n " + sb.toString());
        }
        System.out.println("access_token=" + access_token);
    } catch (Exception ex) {
        System.out.println("Error: " + ex);
    }
}