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:org.asimba.auth.smsotp.distributor.mollie.MollieOTPDistributor.java

/**
 * Distribute the OTP to the user<br/>
 * Requires a configured attribute to be present in the User's Attributes()-collection to
 * establish the phonenr to send the OneTimePassword to!<br/>
 * Updates Otp-instance to reflect the result of distributing the password (timessent, timesent)
 * //w  w  w  .j  a  va2 s.  co  m
 * Sources inspired by A-Select SMS AuthSP
 */
public int distribute(OTP oOtp, IUser oUser) throws OAException, OTPDistributorException {
    // Are we operational?
    if (!_bStarted) {
        throw new OAException(SystemErrors.ERROR_NOT_INITIALIZED);
    }

    String sMsg;
    String sRecipient;
    IAttributes oUserAttributes;
    int returncode = 15;

    // Establish the phonenr to send message to
    oUserAttributes = oUser.getAttributes();
    if (!oUserAttributes.contains(_sPhonenrAttribute)) {
        _oLogger.error("Unknown phonenr for user " + oUser.getID() + "; missing attribute '"
                + _sPhonenrAttribute + "'");
        throw new OTPDistributorException(returncode);
    }

    sRecipient = (String) oUserAttributes.get(_sPhonenrAttribute);

    // Establish message
    sMsg = getMessageForPwd(oOtp.getValue());

    // Establish URL
    StringBuffer sbData = new StringBuffer();

    try {
        ArrayList<String> params = new ArrayList<String>();

        // Depend on Apache Commons Lang for join
        params.add(StringUtils.join(new String[] { "gebruikersnaam", URLEncoder.encode(_sUsername, "UTF-8") },
                "="));

        params.add(
                StringUtils.join(new String[] { "wachtwoord", URLEncoder.encode(_sPassword, "UTF-8") }, "="));

        params.add(
                StringUtils.join(new String[] { "afzender", URLEncoder.encode(_sSenderName, "UTF-8") }, "="));

        params.add(StringUtils.join(new String[] { "bericht", URLEncoder.encode(sMsg, "UTF-8") }, "="));

        params.add(
                StringUtils.join(new String[] { "ontvangers", URLEncoder.encode(sRecipient, "UTF-8") }, "="));

        String sCGIString = StringUtils.join(params, "&");

        returncode++; // 16

        URLConnection oURLConnection = _oURL.openConnection();
        returncode++; // 17

        oURLConnection.setDoOutput(true);

        OutputStreamWriter oWriter = new OutputStreamWriter(oURLConnection.getOutputStream());
        oWriter.write(sCGIString);
        oWriter.flush();
        returncode++; // 18

        // Get the response
        BufferedReader oReader = new BufferedReader(new InputStreamReader(oURLConnection.getInputStream()));
        String sLine;

        if ((sLine = oReader.readLine()) != null) {
            returncode = Integer.parseInt(sLine);
        }

        if (returncode != 0) {
            _oLogger.error("Mollie could not send sms, returncode from Mollie: " + returncode + ".");
            throw new OTPDistributorException(returncode);
        }

        returncode++; // 19
        oWriter.close();
        oReader.close();
    } catch (NumberFormatException e) {
        _oLogger.error("Sending SMS, using \'" + _oURL.toString() + ", data=" + sbData.toString()
                + "\' failed due to number format exception!" + e.getMessage());
        throw new OTPDistributorException(returncode);
    }

    catch (Exception e) {
        _oLogger.error("Sending SMS, using \'" + _oURL.toString() + ", data=" + sbData.toString()
                + "\' failed (return code=" + returncode + ")! " + e.getMessage());
        throw new OTPDistributorException(returncode);
    }

    _oLogger.info("Sending to user " + oUser.getID() + " password with value " + oOtp.getValue());

    oOtp.registerSent(Long.valueOf(System.currentTimeMillis()));

    return returncode;
}

From source file:org.jab.docsearch.utils.NetUtils.java

/**
 * Gets URL size (content)//  w w  w  .  j  av  a  2s  .  c  o m
 *
 * @param url  URL for connect
 * @return     size in bytes of a url or 0 if broken or timed out connection
 */
public long getURLSize(final String url) {
    try {
        URL tmpURL = new URL(url);
        URLConnection conn = tmpURL.openConnection();

        // set connection parameter
        conn.setDoInput(true);
        conn.setDoOutput(false);
        conn.setUseCaches(false);
        conn.setRequestProperty("User-Agent", USER_AGENT);

        // connect
        conn.connect();

        long contentLength = conn.getContentLength();

        if (logger.isDebugEnabled()) {
            logger.debug("getURLSize() content lentgh=" + contentLength + " of URL='" + url + "'");
        }

        return contentLength;
    } catch (IOException ioe) {
        logger.error("getURLSize() failed for URL='" + url + "'", ioe);
        return 0;
    }
}

From source file:org.jab.docsearch.utils.NetUtils.java

/**
 * Gets URL modified date as long//from ww w  .jav a 2s .com
 *
 * @param url  URL to connect
 * @return         date of URLs modification or 0 if an error occurs
 */
public long getURLModifiedDate(final String url) {
    try {
        URL tmpURL = new URL(url);
        URLConnection conn = tmpURL.openConnection();

        // set connection parameter
        conn.setDoInput(true);
        conn.setDoOutput(false);
        conn.setUseCaches(false);
        conn.setRequestProperty("User-Agent", USER_AGENT);

        // connect
        conn.connect();

        long modifiedDate = conn.getLastModified();

        if (logger.isDebugEnabled()) {
            logger.debug("getURLModifiedDate() modified date=" + modifiedDate + " of URL='" + url + "'");
        }

        return modifiedDate;
    } catch (IOException ioe) {
        logger.error("getURLModifiedDate() failed for URL='" + url + "'", ioe);
        return 0;
    }
}

From source file:org.bireme.interop.fromJson.Json2Couch.java

private void sendDocuments(final String docs) {
    try {/*from  w  w w  . j  a v  a  2 s .c o  m*/
        assert docs != null;

        final URLConnection connection = url.openConnection();
        connection.setRequestProperty("CONTENT-TYPE", "application/json");
        connection.setRequestProperty("Accept", "application/json");
        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.connect();

        try (OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream())
        //final String udocs = URLEncoder.encode(docs, "UTF-8");
        ) {
            out.write(docs);
        }

        try (InputStreamReader reader = new InputStreamReader(connection.getInputStream())) {
            final List<String> msgs = getBadDocuments(reader);

            for (String msg : msgs) {
                System.err.println("write error: " + msg);
            }
        }
    } catch (IOException ex) {
        Logger.getLogger(Json2Couch.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:org.LexGrid.LexBIG.caCore.test.rest.RESTTest.java

private String callRestfulService(String putString) throws Exception {
    URL url = new URL(serviceEndPoint + putString);
    URLConnection urlc = url.openConnection();
    urlc.setDoInput(true);/*from  w  ww  . jav  a2s . co m*/
    urlc.setDoOutput(true);

    PrintStream ps = new PrintStream(urlc.getOutputStream());
    ps.close();

    //retrieve result
    BufferedReader br = new BufferedReader(new InputStreamReader(urlc.getInputStream()));
    String str;
    StringBuffer sb = new StringBuffer();
    while ((str = br.readLine()) != null) {
        sb.append(str);
        sb.append("\n");
    }
    br.close();
    return sb.toString();
}

From source file:net.sf.jabref.logic.net.URLDownload.java

private URLConnection openConnection() throws IOException {
    URLConnection connection = source.openConnection();
    for (Map.Entry<String, String> entry : parameters.entrySet()) {
        connection.setRequestProperty(entry.getKey(), entry.getValue());
    }//from  w ww.  j  a va  2s . c  o  m
    if (!postData.isEmpty()) {
        connection.setDoOutput(true);
        try (DataOutputStream wr = new DataOutputStream(connection.getOutputStream())) {
            wr.writeBytes(postData);
        }

    }
    // this does network i/o: GET + read returned headers
    connection.connect();

    return connection;
}

From source file:nl.welteninstituut.tel.la.importers.fitbit.FitbitTask.java

public String postUrl(String url, String data, String authorization) {
    StringBuilder result = new StringBuilder();

    try {//ww  w . j a v  a 2  s.  com
        URLConnection conn = new URL(url).openConnection();
        // conn.setConnectTimeout(30);
        conn.setDoOutput(true);

        if (authorization != null)
            conn.setRequestProperty("Authorization",
                    "Basic " + new String(new Base64().encode(authorization.getBytes())));
        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) {
            result.append(line);
        }
        wr.close();
        rd.close();

    } catch (Exception e) {
    }

    return result.toString();
}

From source file:org.intermine.api.mines.HttpRequester.java

@Override
public BufferedReader requestURL(final String urlString, final ContentType contentType) {
    BufferedReader reader = null;
    OutputStreamWriter writer = null;
    // TODO: when all friendly mines support mimetype formats then we can remove this.
    String suffix = "?format=" + contentType.getFormat();
    try {/*from  w  w w  .ja v a2 s .  c  om*/
        URL url = new URL(StringUtils.substringBefore(urlString, "?") + suffix);
        URLConnection conn = url.openConnection();
        conn.addRequestProperty("Accept", contentType.getMimeType());
        conn.setConnectTimeout(timeout * 1000); // conn accepts millisecond timeout.
        if (urlString.contains("?")) {
            // POST
            String queryString = StringUtils.substringAfter(urlString, "?");
            conn.setDoOutput(true);
            writer = new OutputStreamWriter(conn.getOutputStream());
            writer.write(queryString);
            writer.flush();
            LOG.info("FriendlyMine URL (POST) " + urlString);
        }
        reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    } catch (Exception e) {
        throw new RuntimeException("Unable to access " + urlString + " exception: " + e.getMessage());
    } finally {
        if (writer != null) {
            try {
                writer.close();
            } catch (IOException e) {
                LOG.error("Error sending POST request", e);
            }
        }
    }
    return reader;
}

From source file:org.jab.docsearch.utils.NetUtils.java

/**
 * Downloads URL to file//from  w ww .j av  a  2s . c  o m
 *
 * Content type, content length, last modified and md5 will be set in SpiderUrl
 *
 * @param spiderUrl  URL to download
 * @param file       URL content downloads to this file
 * @return           true if URL successfully downloads to a file
 */
public boolean downloadURLToFile(final SpiderUrl spiderUrl, final String file) {

    boolean downloadOk = false;
    BufferedInputStream inputStream = null;
    BufferedOutputStream outputStream = null;
    try {
        // if the file downloads - save it and return true
        URL url = new URL(spiderUrl.getUrl());
        URLConnection conn = url.openConnection();

        // set connection parameter
        conn.setDoInput(true);
        conn.setDoOutput(false);
        conn.setUseCaches(false);
        conn.setRequestProperty("User-Agent", USER_AGENT);

        // connect
        conn.connect();

        // content type
        spiderUrl.setContentType(getContentType(conn));

        // open streams
        inputStream = new BufferedInputStream(conn.getInputStream());
        outputStream = new BufferedOutputStream(new FileOutputStream(file));

        // copy data from URL to file
        long size = 0;
        int readed = 0;
        while ((readed = inputStream.read()) != -1) {
            size++;
            outputStream.write(readed);
        }

        // set values
        spiderUrl.setContentType(getContentType(conn));
        spiderUrl.setSize(size);

        downloadOk = true;
    } catch (IOException ioe) {
        logger.fatal("downloadURLToFile() failed for URL='" + spiderUrl.getUrl() + "'", ioe);
        downloadOk = false;
    } finally {
        IOUtils.closeQuietly(outputStream);
        IOUtils.closeQuietly(inputStream);
    }

    // set values
    if (downloadOk) {
        spiderUrl.setMd5(FileUtils.getMD5Sum(file));
    }

    return downloadOk;
}

From source file:org.phaidra.apihooks.APIRESTHooksImpl.java

/**
 * Runs the hook if enabled in fedora.fcfg.
 *
 * @param method The name of the method that calls the hook
 * @param pid The PID that is being accessed
 * @param params Method parameters, depend on the method called
 * @return String Hook verdict. Begins with "OK" if it's ok to proceed.
 * @throws APIHooksException If the remote call went wrong
 *//*from   w  w w . j  a v  a  2  s .c  om*/
public String runHook(String method, DOWriter w, Context context, String pid, Object[] params)
        throws APIHooksException {
    String rval = null;

    // Only do this if the method is enabled in fedora.fcfg
    if (getParameter(method) == null) {
        log.debug("runHook: method |" + method + "| not configured, not calling webservice");
        return "OK";
    }

    Iterator i = context.subjectAttributes();
    String attrs = "";
    while (i.hasNext()) {
        String name = "";
        try {
            name = (String) i.next();
            String[] value = context.getSubjectValues(name);
            for (int j = 0; j < value.length; j++) {
                attrs += "&attr=" + URLEncoder.encode(name + "=" + value[j], "UTF-8");
                log.debug("runHook: will send |" + name + "=" + value[j] + "| as subject attribute");
            }
        } catch (NullPointerException ex) {
            log.debug(
                    "runHook: caught NullPointerException while trying to retrieve subject attribute " + name);
        } catch (UnsupportedEncodingException ex) {
            log.debug("runHook: caught UnsupportedEncodingException while trying to encode subject attribute "
                    + name);
        }
    }
    String paramstr = "";
    try {
        for (int j = 0; j < params.length; j++) {
            paramstr += "&param" + Integer.toString(j) + "=";
            if (params[j] != null) {
                String p = params[j].toString();
                paramstr += URLEncoder.encode(p, "UTF-8");
            }
        }
    } catch (UnsupportedEncodingException ex) {
        log.debug("runHook: caught UnsupportedEncodingException while trying to encode a parameter");
    }

    String loginId = context.getSubjectValue(Constants.SUBJECT.LOGIN_ID.uri);

    log.debug("runHook: called for method=|" + method + "|, pid=|" + pid + "|");
    try {
        // TODO: timeout? retries?
        URL url;
        URLConnection urlConn;
        DataOutputStream printout;
        BufferedReader input;

        url = new URL(getParameter("restmethod"));
        urlConn = url.openConnection();
        urlConn.setDoInput(true);
        urlConn.setDoOutput(true);
        urlConn.setUseCaches(false);
        urlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        printout = new DataOutputStream(urlConn.getOutputStream());
        String content = "method=" + URLEncoder.encode(method, "UTF-8") + "&username="
                + URLEncoder.encode(loginId, "UTF-8") + "&pid=" + URLEncoder.encode(pid, "UTF-8") + paramstr
                + attrs;
        printout.writeBytes(content);
        printout.flush();
        printout.close();

        // Get response data.
        input = new BufferedReader(new InputStreamReader(urlConn.getInputStream(), "UTF-8"));
        String str;
        rval = "";
        while (null != ((str = input.readLine()))) {
            rval += str + "\n";
        }
        input.close();

        String ct = urlConn.getContentType();
        if (ct.startsWith("text/xml")) {
            log.debug("runHook: successful REST invocation for method |" + method + "|, returning: " + rval);
        } else if (ct.startsWith("text/plain")) {
            log.debug("runHook: successful REST invocation for method |" + method
                    + "|, but hook returned an error: " + rval);
            throw new Exception(rval);
        } else {
            throw new Exception("Invalid content type " + ct);
        }
    } catch (Exception ex) {
        log.error("runHook: error calling REST hook: " + ex.toString());
        throw new APIHooksException("Error calling REST hook: " + ex.toString(), ex);
    }

    return processResults(rval, w, context);
}