Example usage for java.net URLConnection setDoInput

List of usage examples for java.net URLConnection setDoInput

Introduction

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

Prototype

public void setDoInput(boolean doinput) 

Source Link

Document

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

Usage

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

private void sendDocuments(final String docs) {
    try {/* w w w .  j  a va  2 s . com*/
        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:fr.gael.drb.impl.http.HttpNode.java

@SuppressWarnings({ "unchecked", "rawtypes" })
@Override//from w ww .  ja v  a  2  s  .c o m
public Object getImpl(Class api) {
    if (api.isAssignableFrom(InputStream.class)) {
        try {
            URLConnection urlConnect = this.url.openConnection();

            if (this.url.getUserInfo() != null) {
                // HTTP Basic Authentication.
                String userpass = this.url.getUserInfo();
                String basicAuth = "Basic " + new String(new Base64().encode(userpass.getBytes()));
                urlConnect.setRequestProperty("Authorization", basicAuth);
            }

            urlConnect.setDoInput(true);
            urlConnect.setUseCaches(false);

            return urlConnect.getInputStream();
        } catch (IOException e) {
            return null;
        }
    }
    return null;
}

From source file:screenieup.ImgurUpload.java

/**
 * Connect to image host./*  w w w  .j  a va  2s .  c  om*/
 * @return the connection
 */
private URLConnection connect() {
    URLConnection conn = null;
    try {
        System.out.println("Connecting to imgur...");
        // opens connection and sends data
        URL url = new URL(IMGUR_POST_URI);
        conn = url.openConnection();
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setRequestProperty("Authorization", "Client-ID " + IMGUR_API_KEY);
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

    } catch (MalformedURLException ex) {
        Logger.getLogger(ImgurUpload.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(ImgurUpload.class.getName()).log(Level.SEVERE, null, ex);
    }
    return conn;
}

From source file:org.infoglue.common.util.RemoteCacheUpdater.java

/**
 * This method post information to an URL and returns a string.It throws
 * an exception if anything goes wrong./*from  w w w  . j a  va  2  s. com*/
 * (Works like most 'doPost' methods)
 * 
 * @param urlAddress The address of the URL you would like to post to.
 * @param inHash The parameters you would like to post to the URL.
 * @return The result of the postToUrl method as a string.
 * @exception java.lang.Exception
 */

private String postToUrl(String urlAddress, Hashtable inHash) throws Exception {
    URL url = new URL(urlAddress);
    URLConnection urlConn = url.openConnection();
    urlConn.setConnectTimeout(3000);
    urlConn.setReadTimeout(3000);
    urlConn.setAllowUserInteraction(false);
    urlConn.setDoOutput(true);
    urlConn.setDoInput(true);
    urlConn.setUseCaches(false);
    urlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    PrintWriter printout = new PrintWriter(urlConn.getOutputStream(), true);
    String argString = "";
    if (inHash != null) {
        argString = toEncodedString(inHash);
    }
    printout.print(argString);
    printout.flush();
    printout.close();
    InputStream inStream = null;
    inStream = urlConn.getInputStream();
    InputStreamReader inStreamReader = new InputStreamReader(inStream);
    BufferedReader buffer = new BufferedReader(inStreamReader);
    StringBuffer strbuf = new StringBuffer();
    String line;
    while ((line = buffer.readLine()) != null) {
        strbuf.append(line);
    }
    String readData = strbuf.toString();
    buffer.close();
    return readData;
}

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

public static String stringOfUrl(String addr, HttpServletRequest request, HttpServletResponse response) {
    if (localCookie)
        CookieHandler.setDefault(cm);
    try {/*from   w ww .  j  a  v a  2 s  .co  m*/
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        URL url = new URL(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");
        } else if (DEBUG_MODE)
            System.out.println("Infinit.e Cookie Value is Null");
        IOUtils.copy(urlConnection.getInputStream(), output);
        String newCookie = getConnectionInfiniteCookie(urlConnection);
        if (newCookie != null && response != null) {
            setBrowserInfiniteCookie(response, newCookie, request.getServerPort());
        }

        String toReturn = output.toString();
        output.close();
        return toReturn;
    } catch (IOException e) {
        return null;
    }
}

From source file:org.wso2.es.integration.common.utils.AssetsRESTClient.java

/**
 * This method sends a request to publisher logout api to invalidate the given sessionID
 *
 * @param sessionId String of valid session ID
 *///from ww  w .  j a  v a  2 s  .c om
private void logOut(String sessionId) throws IOException {
    URLConnection urlConn = null;
    String logoutEndpoint = getBaseUrl() + PUBLISHER_APIS_LOGOUT_ENDPOINT;
    //construct APIs session invalidate endpoint
    try {
        URL endpointUrl = new URL(logoutEndpoint);
        urlConn = endpointUrl.openConnection();
        urlConn.setDoInput(true);
        urlConn.setDoOutput(true);
        urlConn.setUseCaches(false);

        if (LOG.isDebugEnabled()) {
            LOG.debug("Invalidating session: " + sessionId);
        }
        urlConn.setRequestProperty(COOKIE, JSESSIONID + "=" + sessionId + ";");
        //send SessionId Cookie
        //send POST output.
        urlConn.getOutputStream().flush();
    } catch (MalformedURLException e) {
        LOG.error(getLogoutErrorMassage(logoutEndpoint), e);
        throw e;
    } catch (IOException e) {
        LOG.error(getLogoutErrorMassage(logoutEndpoint), e);
        throw e;
    } finally {
        if (urlConn != null) {
            try {
                urlConn.getOutputStream().close();//will close the connection as well
            } catch (IOException e) {
                LOG.error("Failed to close OutPutStream", e);
            }
        }
    }
}

From source file:org.apache.fop.apps.FOURIResolver.java

/**
 * Called by the processor through {@link FOUserAgent} when it encounters an
 * uri in an external-graphic element. (see also
 * {@link javax.xml.transform.URIResolver#resolve(String, String)} This
 * resolver will allow URLs without a scheme, i.e. it assumes 'file:' as the
 * default scheme. It also allows relative URLs with scheme, e.g.
 * file:../../abc.jpg which is not strictly RFC compliant as long as the
 * scheme is the same as the scheme of the base URL. If the base URL is null
 * a 'file:' URL referencing the current directory is used as the base URL.
 * If the method is successful it will return a Source of type
 * {@link javax.xml.transform.stream.StreamSource} with its SystemID set to
 * the resolved URL used to open the underlying InputStream.
 *
 * @param href//  ww  w.j av a2s . c  o m
 *            An href attribute, which may be relative or absolute.
 * @param base
 *            The base URI against which the first argument will be made
 *            absolute if the absolute URI is required.
 * @return A {@link javax.xml.transform.Source} object, or null if the href
 *         cannot be resolved.
 * @throws javax.xml.transform.TransformerException
 *             Never thrown by this implementation.
 * @see javax.xml.transform.URIResolver#resolve(String, String)
 */
public Source resolve(String href, String base) throws TransformerException {
    Source source = null;

    // data URLs can be quite long so evaluate early and don't try to build a File
    // (can lead to problems)
    source = commonURIResolver.resolve(href, base);

    // Custom uri resolution
    if (source == null && uriResolver != null) {
        source = uriResolver.resolve(href, base);
    }

    // Fallback to default resolution mechanism
    if (source == null) {
        URL absoluteURL = null;
        int hashPos = href.indexOf('#');
        String fileURL;
        String fragment;
        if (hashPos >= 0) {
            fileURL = href.substring(0, hashPos);
            fragment = href.substring(hashPos);
        } else {
            fileURL = href;
            fragment = null;
        }
        File file = new File(fileURL);
        if (file.canRead() && file.isFile()) {
            try {
                if (fragment != null) {
                    absoluteURL = new URL(file.toURI().toURL().toExternalForm() + fragment);
                } else {
                    absoluteURL = file.toURI().toURL();
                }
            } catch (MalformedURLException mfue) {
                handleException(mfue, "Could not convert filename '" + href + "' to URL", throwExceptions);
            }
        } else {
            // no base provided
            if (base == null) {
                // We don't have a valid file protocol based URL
                try {
                    absoluteURL = new URL(href);
                } catch (MalformedURLException mue) {
                    try {
                        // the above failed, we give it another go in case
                        // the href contains only a path then file: is
                        // assumed
                        absoluteURL = new URL("file:" + href);
                    } catch (MalformedURLException mfue) {
                        handleException(mfue, "Error with URL '" + href + "'", throwExceptions);
                    }
                }

                // try and resolve from context of base
            } else {
                URL baseURL = null;
                try {
                    baseURL = new URL(base);
                } catch (MalformedURLException mfue) {
                    handleException(mfue, "Error with base URL '" + base + "'", throwExceptions);
                }

                /*
                 * This piece of code is based on the following statement in
                 * RFC2396 section 5.2:
                 *
                 * 3) If the scheme component is defined, indicating that
                 * the reference starts with a scheme name, then the
                 * reference is interpreted as an absolute URI and we are
                 * done. Otherwise, the reference URI's scheme is inherited
                 * from the base URI's scheme component.
                 *
                 * Due to a loophole in prior specifications [RFC1630], some
                 * parsers allow the scheme name to be present in a relative
                 * URI if it is the same as the base URI scheme.
                 * Unfortunately, this can conflict with the correct parsing
                 * of non-hierarchical URI. For backwards compatibility, an
                 * implementation may work around such references by
                 * removing the scheme if it matches that of the base URI
                 * and the scheme is known to always use the <hier_part>
                 * syntax.
                 *
                 * The URL class does not implement this work around, so we
                 * do.
                 */
                assert (baseURL != null);
                String scheme = baseURL.getProtocol() + ":";
                if (href.startsWith(scheme) && "file:".equals(scheme)) {
                    href = href.substring(scheme.length());
                    int colonPos = href.indexOf(':');
                    int slashPos = href.indexOf('/');
                    if (slashPos >= 0 && colonPos >= 0 && colonPos < slashPos) {
                        href = "/" + href; // Absolute file URL doesn't
                        // have a leading slash
                    }
                }
                try {
                    absoluteURL = new URL(baseURL, href);
                } catch (MalformedURLException mfue) {
                    handleException(mfue, "Error with URL; base '" + base + "' " + "href '" + href + "'",
                            throwExceptions);
                }
            }
        }

        if (absoluteURL != null) {
            String effURL = absoluteURL.toExternalForm();
            try {
                URLConnection connection = absoluteURL.openConnection();
                connection.setAllowUserInteraction(false);
                connection.setDoInput(true);
                updateURLConnection(connection, href);
                connection.connect();
                return new StreamSource(connection.getInputStream(), effURL);
            } catch (FileNotFoundException fnfe) {
                // Note: This is on "debug" level since the caller is
                // supposed to handle this
                log.debug("File not found: " + effURL);
            } catch (java.io.IOException ioe) {
                log.error("Error with opening URL '" + effURL + "': " + ioe.getMessage());
            }
        }
    }
    return source;
}

From source file:org.infoglue.igide.helper.http.HTTPTextDocumentListenerEngine.java

private void listen() {
    String errorMessage;//from  ww  w  .ja va 2 s.  c o m
    boolean error;
    errorMessage = "";
    error = false;
    try {
        Logger.logConsole("Starting listen thread");
        URLConnection urlConn = url.openConnection();
        urlConn.setConnectTimeout(3000);
        urlConn.setRequestProperty("Connection", "Keep-Alive");
        urlConn.setReadTimeout(0);
        urlConn.setDoInput(true);
        urlConn.setDoOutput(true);
        urlConn.setUseCaches(false);
        urlConn.setAllowUserInteraction(false);
        if (urlConn.getHeaderFields().toString().indexOf("401 Unauthorized") > -1) {
            Logger.logConsole("User has no access to the CMS - closing connection");
            throw new AccessControlException("User has no access to the CMS - closing connection");
        }
        String boundary = urlConn.getHeaderField("boundary");
        DataInputStream input = new DataInputStream(urlConn.getInputStream());
        StringBuffer buf = new StringBuffer();
        if (listener != null)
            listener.onConnection(url);
        String str = null;
        while ((str = input.readLine()) != null) {
            if (str.indexOf("XMLNotificationWriter.ping") == -1) {
                if (str.equals(boundary)) {
                    String message = buf.toString();

                    // By checking there is more in the String than the XML declaration we assume the message is valid
                    if (message != null
                            && !message.replace("<?xml version=\"1.0\" encoding=\"UTF-8\"?>", "").equals("")) {
                        if (listener != null)
                            listener.recieveDocument(buf.toString());
                        else
                            Logger.logConsole((new StringBuilder("NEW DOCUMENT!!\r\n")).append(buf.toString())
                                    .append("\r\n").toString());
                    }
                    buf = new StringBuffer();
                } else {
                    buf.append(str);
                }
            }
        }
        input.close();
    } catch (MalformedURLException me) {
        error = true;
        errorMessage = (new StringBuilder("Faulty CMS-url:")).append(url).toString();
        if (listener != null)
            listener.onException(me);
        else
            System.err.println((new StringBuilder("MalformedURLException: ")).append(me).toString());
        final String errorMessageFinal = errorMessage;
        Logger.logConsole(
                (new StringBuilder("The connection was shut. Was it an error:")).append(error).toString());
        if (!error) {
            if (System.currentTimeMillis() - lastRetry > 20000L) {
                Logger.logConsole("Trying to restart the listener as it was a while since last...");
                lastRetry = System.currentTimeMillis();
                listen();
            }
        } else {
            try {
                if (listener != null)
                    listener.onEndConnection(url);
            } catch (Exception e) {
                Logger.logConsole(
                        (new StringBuilder("Error ending connection:")).append(e.getMessage()).toString());
            }
            Display.getDefault().asyncExec(new Runnable() {

                public void run() {
                    MessageDialog.openError(viewer.getControl().getShell(), "Error",
                            (new StringBuilder()).append(errorMessageFinal).toString());
                }
            });
        }
    } catch (IOException ioe) {
        error = true;
        errorMessage = "Got an I/O-Exception talking to the CMS. Check that it is started and in valid state.";
        Logger.logConsole((new StringBuilder("ioe: ")).append(ioe.getMessage()).toString());
        if (listener != null)
            listener.onException(ioe);
        else
            Logger.logConsole((new StringBuilder("TextDocumentListener cannot connect to: "))
                    .append(url.toExternalForm()).toString());
        final String errorMessageFinal = errorMessage;
        Logger.logConsole(
                (new StringBuilder("The connection was shut. Was it an error:")).append(error).toString());
        if (!error) {
            if (System.currentTimeMillis() - lastRetry > 20000L) {
                Logger.logConsole("Trying to restart the listener as it was a while since last...");
                lastRetry = System.currentTimeMillis();
                listen();
            }
        } else {
            try {
                if (listener != null)
                    listener.onEndConnection(url);
            } catch (Exception e) {
                Logger.logConsole(
                        (new StringBuilder("Error ending connection:")).append(e.getMessage()).toString());
            }
            Display.getDefault().asyncExec(new Runnable() {

                public void run() {
                    MessageDialog.openError(viewer.getControl().getShell(), "Error",
                            (new StringBuilder()).append(errorMessageFinal).toString());
                }
            });
        }
    } catch (AccessControlException ace) {
        error = true;
        errorMessage = "The user you tried to connect with did not have the correct access rights. Check that he/she has roles etc enough to access the CMS";
        Logger.logConsole((new StringBuilder("ioe: ")).append(ace.getMessage()).toString());
        if (listener != null)
            listener.onException(ace);
        else
            Logger.logConsole((new StringBuilder()).append(ace.getMessage()).toString());
        final String errorMessageFinal = errorMessage;
        Logger.logConsole(
                (new StringBuilder("The connection was shut. Was it an error:")).append(error).toString());
        if (!error) {
            if (System.currentTimeMillis() - lastRetry > 20000L) {
                Logger.logConsole("Trying to restart the listener as it was a while since last...");
                lastRetry = System.currentTimeMillis();
                listen();
            }
        } else {
            try {
                if (listener != null)
                    listener.onEndConnection(url);
            } catch (Exception e) {
                Logger.logConsole(
                        (new StringBuilder("Error ending connection:")).append(e.getMessage()).toString());
            }
            Display.getDefault().asyncExec(new Runnable() {

                public void run() {
                    MessageDialog.openError(viewer.getControl().getShell(), "Error",
                            (new StringBuilder()).append(errorMessageFinal).toString());
                }
            });
        }
    } catch (Exception exception) {
        final String errorMessageFinal = errorMessage;
        Logger.logConsole(
                (new StringBuilder("The connection was shut. Was it an error:")).append(error).toString());
        if (!error) {
            if (System.currentTimeMillis() - lastRetry > 20000L) {
                Logger.logConsole("Trying to restart the listener as it was a while since last...");
                lastRetry = System.currentTimeMillis();
                listen();
            }
        } else {
            try {
                if (listener != null)
                    listener.onEndConnection(url);
            } catch (Exception e) {
                Logger.logConsole(
                        (new StringBuilder("Error ending connection:")).append(e.getMessage()).toString());
            }
            Display.getDefault().asyncExec(new Runnable() {

                public void run() {
                    MessageDialog.openError(viewer.getControl().getShell(), "Error",
                            (new StringBuilder()).append(errorMessageFinal).toString());
                }
            });
        }
    } catch (Throwable e) {
        final String errorMessageFinal = errorMessage;
        Logger.logConsole(
                (new StringBuilder("The connection was shut. Was it an error:")).append(error).toString());
        if (!error) {
            if (System.currentTimeMillis() - lastRetry > 20000L) {
                Logger.logConsole("Trying to restart the listener as it was a while since last...");
                lastRetry = System.currentTimeMillis();
                listen();
            }
        } else {
            try {
                if (listener != null)
                    listener.onEndConnection(url);
            } catch (Exception e2) {
                Logger.logConsole(
                        (new StringBuilder("Error ending connection:")).append(e2.getMessage()).toString());
            }
            Display.getDefault().asyncExec(new Runnable() {

                public void run() {
                    MessageDialog.openError(viewer.getControl().getShell(), "Error",
                            (new StringBuilder()).append(errorMessageFinal).toString());
                }
            });
        }
    }
}

From source file:net.pms.configuration.DownloadPlugins.java

private boolean downloadFile(String url, String dir, String name) throws Exception {
    URL u = new URL(url);
    ensureCreated(dir);/*  w w  w  .j a  v a2 s.c  o  m*/
    String fName = extractFileName(url, name);

    LOGGER.debug("fetch file " + url);
    if (updateLabel != null) {
        updateLabel.setText(Messages.getString("NetworkTab.47") + ": " + fName);
    }

    File f = new File(dir + File.separator + fName);
    if (f.exists()) {
        // no need to download it twice
        return true;
    }
    URLConnection connection = u.openConnection();
    connection.setDoInput(true);
    connection.setDoOutput(true);
    try (InputStream in = connection.getInputStream(); FileOutputStream out = new FileOutputStream(f)) {
        byte[] buf = new byte[4096];
        int len;

        while ((len = in.read(buf)) != -1) {
            out.write(buf, 0, len);
        }

        out.flush();
    } catch (Exception e) {
        LOGGER.warn("Plugin download error: " + e);
    }

    if (fName.endsWith(".zip")) {
        for (String prop : props) {
            if (prop.equalsIgnoreCase("unzip")) {
                unzip(f, dir);
            }
        }
    }

    // If we got down here add the jar to the list (if it is a jar)
    if (f.getAbsolutePath().endsWith(".jar")) {
        jars.add(f.toURI().toURL());
    }
    return true;
}

From source file:roommateapp.info.net.FileDownloader.java

/**
 * Parallel execution/*ww w.ja va  2s .  c  o m*/
 */
@SuppressLint("UseValueOf")
@Override
protected Object doInBackground(Object... params) {

    if (!this.isHolidayFile) {

        /* Progressbar einblenden */
        this.ac.runOnUiThread(new Runnable() {
            public void run() {
                toggleProgressbar();
            }
        });
    }

    boolean success = true;
    String eingabe = (String) params[0];

    if (eingabe != null) {

        try {
            URL url = new URL(eingabe);

            // Get filename
            String fileName = eingabe;
            StringTokenizer tokenizer = new StringTokenizer(fileName, "/", false);
            int tokens = tokenizer.countTokens();
            for (int i = 0; i < tokens; i++) {
                fileName = tokenizer.nextToken();
            }

            // Create file
            this.downloadedFile = new File(this.roommateDirectory, fileName);

            // Download and write file
            try {
                // Password and username if it's HTACCESS
                String authData = new String(Base64.encode((username + ":" + pw).getBytes(), Base64.NO_WRAP));

                URLConnection urlcon = url.openConnection();

                // Authorisation if it's a userfile
                if (eingabe.startsWith(RoommateConfig.URL)) {
                    urlcon.setRequestProperty("Authorization", "Basic " + authData);
                    urlcon.setDoInput(true);
                }
                InputStream inputstream = urlcon.getInputStream();
                ByteArrayBuffer baf = new ByteArrayBuffer(50);

                int current = 0;

                while ((current = inputstream.read()) != -1) {
                    baf.append((byte) current);
                }

                FileOutputStream fos = new FileOutputStream(this.downloadedFile);
                fos.write(baf.toByteArray());
                fos.close();

            } catch (IOException e) {
                success = false;
                e.printStackTrace();
            }
        } catch (MalformedURLException e) {
            success = false;
            e.printStackTrace();
        }
    } else {
        success = false;
    }
    return new Boolean(success);
}