Example usage for java.net URLConnection getOutputStream

List of usage examples for java.net URLConnection getOutputStream

Introduction

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

Prototype

public OutputStream getOutputStream() throws IOException 

Source Link

Document

Returns an output stream that writes to this connection.

Usage

From source file:com.senseidb.servlet.AbstractSenseiClientServlet.java

private void handleJMXRequest(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {
    InputStream is = null;//from  w  ww  .  j  a v  a  2  s. co m
    OutputStream os = null;
    try {
        String myPath = req.getRequestURI().substring(req.getServletPath().length() + 11);
        URL adminUrl = null;
        if (myPath.indexOf('/') > 0) {
            adminUrl = new URL(
                    new StringBuilder(URLDecoder.decode(myPath.substring(0, myPath.indexOf('/')), "UTF-8"))
                            .append("/admin/jmx").append(myPath.substring(myPath.indexOf('/'))).toString());
        } else {
            adminUrl = new URL(
                    new StringBuilder(URLDecoder.decode(myPath, "UTF-8")).append("/admin/jmx").toString());
        }

        URLConnection conn = adminUrl.openConnection();

        byte[] buffer = new byte[8192]; // 8k
        int len = 0;

        InputStream ris = req.getInputStream();

        while ((len = ris.read(buffer)) > 0) {
            if (!conn.getDoOutput()) {
                conn.setDoOutput(true);
                os = conn.getOutputStream();
            }
            os.write(buffer, 0, len);
        }
        if (os != null)
            os.flush();

        is = conn.getInputStream();
        OutputStream ros = resp.getOutputStream();

        while ((len = is.read(buffer)) > 0) {
            ros.write(buffer, 0, len);
        }
        ros.flush();
    } catch (Exception e) {
        throw new ServletException(e.getMessage(), e);
    } finally {
        if (is != null)
            is.close();
        if (os != null)
            os.close();
    }
}

From source file:com.redhat.rhn.frontend.action.common.DownloadFile.java

@Override
protected StreamInfo getStreamInfo(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    String path = "";
    Map params = (Map) request.getAttribute(PARAMS);
    String type = (String) params.get(TYPE);
    if (type.equals(DownloadManager.DOWNLOAD_TYPE_KICKSTART)) {
        return getStreamInfoKickstart(mapping, form, request, response, path);
    } else if (type.equals(DownloadManager.DOWNLOAD_TYPE_COBBLER)) {
        String url = ConfigDefaults.get().getCobblerServerUrl() + (String) params.get(URL_STRING);
        KickstartHelper helper = new KickstartHelper(request);
        String data = "";
        if (helper.isProxyRequest()) {
            data = KickstartManager.getInstance().renderKickstart(helper.getKickstartHost(), url);
        } else {/*from   w  ww.jav a 2s  .co m*/
            data = KickstartManager.getInstance().renderKickstart(url);
        }
        setTextContentInfo(response, data.length());
        return getStreamForText(data.getBytes());
    } else if (type.equals(DownloadManager.DOWNLOAD_TYPE_COBBLER_API)) {
        // read data from POST body
        String postData = new String();
        String line = null;
        BufferedReader reader = request.getReader();
        while ((line = reader.readLine()) != null) {
            postData += line;
        }

        // Send data
        URL url = new URL(ConfigDefaults.get().getCobblerServerUrl() + "/cobbler_api");
        URLConnection conn = url.openConnection();
        conn.setDoOutput(true);
        OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
        // this will write POST /download//cobbler_api instead of
        // POST /cobbler_api, but cobbler do not mind
        wr.write(postData, 0, postData.length());
        wr.flush();
        conn.connect();

        // Get the response
        String output = new String();
        BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        while ((line = rd.readLine()) != null) {
            output += line;
        }
        wr.close();

        KickstartHelper helper = new KickstartHelper(request);
        if (helper.isProxyRequest()) {
            // Search/replacing all instances of cobbler host with host
            // we pass in, for use with Spacewalk Proxy.
            output = output.replaceAll(ConfigDefaults.get().getCobblerHost(), helper.getForwardedHost());
        }

        setXmlContentInfo(response, output.length());
        return getStreamForXml(output.getBytes());
    } else {
        Long fileId = (Long) params.get(FILEID);
        Long userid = (Long) params.get(USERID);
        User user = UserFactory.lookupById(userid);
        if (type.equals(DownloadManager.DOWNLOAD_TYPE_PACKAGE)) {
            Package pack = PackageFactory.lookupByIdAndOrg(fileId, user.getOrg());
            setBinaryContentInfo(response, pack.getPackageSize().intValue());
            path = Config.get().getString(ConfigDefaults.MOUNT_POINT) + "/" + pack.getPath();
            return getStreamForBinary(path);
        } else if (type.equals(DownloadManager.DOWNLOAD_TYPE_SOURCE)) {
            Package pack = PackageFactory.lookupByIdAndOrg(fileId, user.getOrg());
            List<PackageSource> src = PackageFactory.lookupPackageSources(pack);
            if (!src.isEmpty()) {
                setBinaryContentInfo(response, src.get(0).getPackageSize().intValue());
                path = Config.get().getString(ConfigDefaults.MOUNT_POINT) + "/" + src.get(0).getPath();
                return getStreamForBinary(path);
            }
        } else if (type.equals(DownloadManager.DOWNLOAD_TYPE_REPO_LOG)) {
            Channel c = ChannelFactory.lookupById(fileId);
            ChannelManager.verifyChannelAdmin(user, fileId);
            StringBuilder output = new StringBuilder();
            for (String fileName : ChannelManager.getLatestSyncLogFiles(c)) {
                RandomAccessFile file = new RandomAccessFile(fileName, "r");
                long fileLength = file.length();
                if (fileLength > DOWNLOAD_REPO_LOG_LENGTH) {
                    file.seek(fileLength - DOWNLOAD_REPO_LOG_LENGTH);
                    // throw away text till end of the actual line
                    file.readLine();
                } else {
                    file.seek(0);
                }
                String line;
                while ((line = file.readLine()) != null) {
                    output.append(line);
                    output.append("\n");
                }
                file.close();
                if (output.length() > DOWNLOAD_REPO_LOG_MIN_LENGTH) {
                    break;
                }
            }

            setTextContentInfo(response, output.length());
            return getStreamForText(output.toString().getBytes());
        } else if (type.equals(DownloadManager.DOWNLOAD_TYPE_CRASHFILE)) {
            CrashFile crashFile = CrashManager.lookupCrashFileByUserAndId(user, fileId);
            String crashPath = crashFile.getCrash().getStoragePath();
            setBinaryContentInfo(response, (int) crashFile.getFilesize());
            path = Config.get().getString(ConfigDefaults.MOUNT_POINT) + "/" + crashPath + "/"
                    + crashFile.getFilename();
            return getStreamForBinary(path);

        }
    }

    throw new UnknownDownloadTypeException(
            "The specified download type " + type + " is not currently supported");

}

From source file:net.sf.jabref.importer.fileformat.FreeCiteImporter.java

public ParserResult importEntries(String text) {
    // URLencode the string for transmission
    String urlencodedCitation = null;
    try {/*  w ww.  j  a  va 2 s.c o m*/
        urlencodedCitation = URLEncoder.encode(text, StandardCharsets.UTF_8.name());
    } catch (UnsupportedEncodingException e) {
        LOGGER.warn("Unsupported encoding", e);
    }

    // Send the request
    URL url;
    URLConnection conn;
    try {
        url = new URL("http://freecite.library.brown.edu/citations/create");
        conn = url.openConnection();
    } catch (MalformedURLException e) {
        LOGGER.warn("Bad URL", e);
        return new ParserResult();
    } catch (IOException e) {
        LOGGER.warn("Could not download", e);
        return new ParserResult();
    }
    try {
        conn.setRequestProperty("accept", "text/xml");
        conn.setDoOutput(true);
        OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());

        String data = "citation=" + urlencodedCitation;
        // write parameters
        writer.write(data);
        writer.flush();
    } catch (IllegalStateException e) {
        LOGGER.warn("Already connected.", e);
    } catch (IOException e) {
        LOGGER.warn("Unable to connect to FreeCite online service.", e);
        return ParserResult
                .fromErrorMessage(Localization.lang("Unable to connect to FreeCite online service."));
    }
    // output is in conn.getInputStream();
    // new InputStreamReader(conn.getInputStream())
    List<BibEntry> res = new ArrayList<>();

    XMLInputFactory factory = XMLInputFactory.newInstance();
    try {
        XMLStreamReader parser = factory.createXMLStreamReader(conn.getInputStream());
        while (parser.hasNext()) {
            if ((parser.getEventType() == XMLStreamConstants.START_ELEMENT)
                    && "citation".equals(parser.getLocalName())) {
                parser.nextTag();

                StringBuilder noteSB = new StringBuilder();

                BibEntry e = new BibEntry();
                // fallback type
                EntryType type = BibtexEntryTypes.INPROCEEDINGS;

                while (!((parser.getEventType() == XMLStreamConstants.END_ELEMENT)
                        && "citation".equals(parser.getLocalName()))) {
                    if (parser.getEventType() == XMLStreamConstants.START_ELEMENT) {
                        String ln = parser.getLocalName();
                        if ("authors".equals(ln)) {
                            StringBuilder sb = new StringBuilder();
                            parser.nextTag();

                            while (parser.getEventType() == XMLStreamConstants.START_ELEMENT) {
                                // author is directly nested below authors
                                assert "author".equals(parser.getLocalName());

                                String author = parser.getElementText();
                                if (sb.length() == 0) {
                                    // first author
                                    sb.append(author);
                                } else {
                                    sb.append(" and ");
                                    sb.append(author);
                                }
                                assert parser.getEventType() == XMLStreamConstants.END_ELEMENT;
                                assert "author".equals(parser.getLocalName());
                                parser.nextTag();
                                // current tag is either begin:author or
                                // end:authors
                            }
                            e.setField(FieldName.AUTHOR, sb.toString());
                        } else if (FieldName.JOURNAL.equals(ln)) {
                            // we guess that the entry is a journal
                            // the alternative way is to parse
                            // ctx:context-objects / ctx:context-object / ctx:referent / ctx:metadata-by-val / ctx:metadata / journal / rft:genre
                            // the drawback is that ctx:context-objects is NOT nested in citation, but a separate element
                            // we would have to change the whole parser to parse that format.
                            type = BibtexEntryTypes.ARTICLE;
                            e.setField(ln, parser.getElementText());
                        } else if ("tech".equals(ln)) {
                            type = BibtexEntryTypes.TECHREPORT;
                            // the content of the "tech" field seems to contain the number of the technical report
                            e.setField(FieldName.NUMBER, parser.getElementText());
                        } else if (FieldName.DOI.equals(ln) || "institution".equals(ln) || "location".equals(ln)
                                || FieldName.NUMBER.equals(ln) || "note".equals(ln)
                                || FieldName.TITLE.equals(ln) || FieldName.PAGES.equals(ln)
                                || FieldName.PUBLISHER.equals(ln) || FieldName.VOLUME.equals(ln)
                                || FieldName.YEAR.equals(ln)) {
                            e.setField(ln, parser.getElementText());
                        } else if ("booktitle".equals(ln)) {
                            String booktitle = parser.getElementText();
                            if (booktitle.startsWith("In ")) {
                                // special treatment for parsing of
                                // "In proceedings of..." references
                                booktitle = booktitle.substring(3);
                            }
                            e.setField("booktitle", booktitle);
                        } else if ("raw_string".equals(ln)) {
                            // raw input string is ignored
                        } else {
                            // all other tags are stored as note
                            noteSB.append(ln);
                            noteSB.append(':');
                            noteSB.append(parser.getElementText());
                            noteSB.append(Globals.NEWLINE);
                        }
                    }
                    parser.next();
                }

                if (noteSB.length() > 0) {
                    String note;
                    if (e.hasField("note")) {
                        // "note" could have been set during the parsing as FreeCite also returns "note"
                        note = e.getFieldOptional("note").get().concat(Globals.NEWLINE)
                                .concat(noteSB.toString());
                    } else {
                        note = noteSB.toString();
                    }
                    e.setField("note", note);
                }

                // type has been derived from "genre"
                // has to be done before label generation as label generation is dependent on entry type
                e.setType(type);

                // autogenerate label (BibTeX key)
                LabelPatternUtil.makeLabel(
                        JabRefGUI.getMainFrame().getCurrentBasePanel().getBibDatabaseContext().getMetaData(),
                        JabRefGUI.getMainFrame().getCurrentBasePanel().getDatabase(), e, Globals.prefs);

                res.add(e);
            }
            parser.next();
        }
        parser.close();
    } catch (IOException | XMLStreamException ex) {
        LOGGER.warn("Could not parse", ex);
        return new ParserResult();
    }

    return new ParserResult(res);
}

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  2s  .  c o m
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.gephi.streaming.impl.StreamingControllerImpl.java

private void sendEvent(final StreamingEndpoint endpoint, GraphEvent event) {
    logger.log(Level.FINE, "Sending event {0}", event.toString());
    try {//from  w  w w  . j a v  a  2s  .  com
        URL url = new URL(endpoint.getUrl(), endpoint.getUrl().getFile() + "?operation=updateGraph&format="
                + endpoint.getStreamType().getType());

        URLConnection connection = url.openConnection();

        // Workaround for Bug https://issues.apache.org/jira/browse/CODEC-89
        String base64Encoded = Base64
                .encodeBase64String((endpoint.getUser() + ":" + endpoint.getPassword()).getBytes());
        base64Encoded = base64Encoded.replaceAll("\r\n?", "");

        connection.setRequestProperty("Authorization", "Basic " + base64Encoded);

        connection.setDoOutput(true);
        connection.connect();

        StreamWriterFactory writerFactory = Lookup.getDefault().lookup(StreamWriterFactory.class);

        OutputStream out = null;
        try {
            out = connection.getOutputStream();
        } catch (UnknownServiceException e) {
            // protocol doesn't support output
            return;
        }
        StreamWriter writer = writerFactory.createStreamWriter(endpoint.getStreamType(), out);
        writer.handleGraphEvent(event);
        out.flush();
        out.close();
        connection.getInputStream().close();

    } catch (IOException ex) {
        logger.log(Level.FINE, null, ex);
    }
}

From source file:org.n52.wps.server.request.strategy.WCS111XMLEmbeddedBase64OutputReferenceStrategy.java

@Override
public ReferenceInputStream fetchData(InputType input) throws ExceptionReport {

    String dataURLString = input.getReference().getHref();

    String schema = input.getReference().getSchema();
    String encoding = input.getReference().getEncoding();
    String mimeType = input.getReference().getMimeType();

    try {/*from   w  w  w .  j  a  va  2  s .c  o  m*/
        URL dataURL = new URL(dataURLString);
        // Do not give a direct inputstream.
        // The XML handlers cannot handle slow connections
        URLConnection conn = dataURL.openConnection();
        conn.setRequestProperty("Accept-Encoding", "gzip");
        conn.setRequestProperty("Content-type", "multipart/mixed");
        //Handling POST with referenced document
        if (input.getReference().isSetBodyReference()) {
            String bodyReference = input.getReference().getBodyReference().getHref();
            URL bodyReferenceURL = new URL(bodyReference);
            URLConnection bodyReferenceConn = bodyReferenceURL.openConnection();
            bodyReferenceConn.setRequestProperty("Accept-Encoding", "gzip");
            InputStream referenceInputStream = retrievingZippedContent(bodyReferenceConn);
            IOUtils.copy(referenceInputStream, conn.getOutputStream());
        }
        //Handling POST with inline message
        else if (input.getReference().isSetBody()) {
            conn.setDoOutput(true);

            input.getReference().getBody().save(conn.getOutputStream());
        }
        InputStream inputStream = retrievingZippedContent(conn);

        BufferedReader bRead = new BufferedReader(new InputStreamReader(inputStream));

        String line = "";

        //boundary between different content types
        String boundary = "";

        boolean boundaryFound = false;

        boolean encodedImagepart = false;

        String encodedImage = "";

        //e.g. base64
        String contentTransferEncoding = "";

        String imageContentType = "";

        int boundaryCount = 0;

        while ((line = bRead.readLine()) != null) {

            if (line.contains("boundary")) {
                boundary = line.substring(line.indexOf("\"") + 1, line.lastIndexOf("\""));
                boundaryFound = true;
                continue;
            }
            if (boundaryFound) {
                if (line.contains(boundary)) {
                    boundaryCount++;
                    continue;
                }
            }

            if (encodedImagepart) {
                encodedImage = encodedImage.concat(line);
            }
            //is the image always the third part?!
            else if (boundaryCount == 2) {
                if (line.contains("Content-Type")) {
                    imageContentType = line.substring(line.indexOf(":") + 1).trim();
                } else if (line.contains("Content-Transfer-Encoding")) {
                    contentTransferEncoding = line.substring(line.indexOf(":") + 1).trim();
                } else if (line.contains("Content-ID")) {
                    /*   just move further one line (which is hopefully empty)
                     *    and start parsing the encoded image             
                     */
                    line = bRead.readLine();
                    encodedImagepart = true;
                }
            }

        }

        return new ReferenceInputStream(
                new Base64InputStream(new ByteArrayInputStream(encodedImage.getBytes())), imageContentType,
                null); // encoding is null since encoding was removed
    } catch (RuntimeException e) {
        throw new ExceptionReport("Error occured while parsing XML", ExceptionReport.NO_APPLICABLE_CODE, e);
    } catch (MalformedURLException e) {
        String inputID = input.getIdentifier().getStringValue();
        throw new ExceptionReport(
                "The inputURL of the execute is wrong: inputID: " + inputID + " | dataURL: " + dataURLString,
                ExceptionReport.INVALID_PARAMETER_VALUE);
    } catch (IOException e) {
        String inputID = input.getIdentifier().getStringValue();
        throw new ExceptionReport("Error occured while receiving the complexReferenceURL: inputID: " + inputID
                + " | dataURL: " + dataURLString, ExceptionReport.INVALID_PARAMETER_VALUE);
    }
}

From source file:com.controller.CuotasController.java

@RequestMapping("cuotas.htm")
public ModelAndView getCuotas(HttpServletRequest request) {
    sesion = request.getSession();/*from   w w  w  .jav a 2 s  .  c o m*/
    ModelAndView mav = new ModelAndView();
    String mensaje = null;
    Detalles detalle = (Detalles) sesion.getAttribute("cuenta");

    String country = detalle.getCiudad();
    String amount = "5";
    String myURL = "http://192.168.5.39/app_dev.php/public/get/rates";
    // System.out.println("Requested URL:" + myURL);
    StringBuilder sb = new StringBuilder();
    URLConnection urlConn = null;
    InputStreamReader in = null;
    try {
        URL url = new URL(myURL);
        urlConn = url.openConnection();
        if (urlConn != null) {
            urlConn.setReadTimeout(60 * 1000);
            urlConn.setDoOutput(true);
            String data = URLEncoder.encode("country", "UTF-8") + "=" + URLEncoder.encode(country, "UTF-8");
            data += "&" + URLEncoder.encode("amount", "UTF-8") + "=" + URLEncoder.encode(amount, "UTF-8");

            System.out.println("los Datos a enviar por POST son " + data);

            try ( //obtenemos el flujo de escritura
                    OutputStreamWriter wr = new OutputStreamWriter(urlConn.getOutputStream())) {
                //escribimos
                wr.write(data);
                wr.flush();
                //cerramos la conexin
            }
        }
        if (urlConn != null && urlConn.getInputStream() != null) {
            in = new InputStreamReader(urlConn.getInputStream(), Charset.defaultCharset());

            BufferedReader bufferedReader = new BufferedReader(in);
            if (bufferedReader != null) {
                int cp;
                while ((cp = bufferedReader.read()) != -1) {
                    sb.append((char) cp);
                }
                bufferedReader.close();
            }
        }
        in.close();
    } catch (Exception e) {
        e.printStackTrace();
        throw new RuntimeException("Exception while calling URL:" + myURL, e);
    }
    String resultado = sb.toString();

    if (sesion.getAttribute("usuario") == null) {

        mav.setViewName("login/login");

    } else {
        sesionUser = sesion.getAttribute("usuario").toString();
        //Detalles detalle = (Detalles) sesion.getAttribute("cuenta");
        mav.addObject("country", detalle.getCiudad());
        mav.addObject("resultado", resultado);

        if (sesion.getAttribute("tipoUsuario").toString().compareTo("Administrador") == 0) {
            mav.setViewName("viewsAdmin/cuotasAdmin");
            System.out.println("el usuario es administrador");
        } else {
            mav.setViewName("panel/cuotas");
        }
    }
    return mav;
}

From source file:com.controller.CuotasController.java

@RequestMapping("cuotasAdmin.htm")
public ModelAndView getCuotasAdmin(HttpServletRequest request) {
    sesion = request.getSession();// ww w .j a  v a 2s.c  o m
    ModelAndView mav = new ModelAndView();
    String mensaje = null;
    Detalles detalle = (Detalles) sesion.getAttribute("cuenta");

    String country = detalle.getCiudad();
    String amount = "5";
    String myURL = "http://192.168.5.39/app_dev.php/public/get/rates";
    // System.out.println("Requested URL:" + myURL);
    StringBuilder sb = new StringBuilder();
    URLConnection urlConn = null;
    InputStreamReader in = null;
    try {
        URL url = new URL(myURL);
        urlConn = url.openConnection();
        if (urlConn != null) {
            urlConn.setReadTimeout(60 * 1000);
            urlConn.setDoOutput(true);
            String data = URLEncoder.encode("country", "UTF-8") + "=" + URLEncoder.encode(country, "UTF-8");
            data += "&" + URLEncoder.encode("amount", "UTF-8") + "=" + URLEncoder.encode(amount, "UTF-8");

            System.out.println("los Datos a enviar por POST son " + data);

            try ( //obtenemos el flujo de escritura
                    OutputStreamWriter wr = new OutputStreamWriter(urlConn.getOutputStream())) {
                //escribimos
                wr.write(data);
                wr.flush();
                //cerramos la conexin
            }
        }
        if (urlConn != null && urlConn.getInputStream() != null) {
            in = new InputStreamReader(urlConn.getInputStream(), Charset.defaultCharset());

            BufferedReader bufferedReader = new BufferedReader(in);
            if (bufferedReader != null) {
                int cp;
                while ((cp = bufferedReader.read()) != -1) {
                    sb.append((char) cp);
                }
                bufferedReader.close();
            }
        }
        in.close();
    } catch (Exception e) {
        e.printStackTrace();
        throw new RuntimeException("Exception while calling URL:" + myURL, e);
    }
    String resultado = sb.toString();

    if (sesion.getAttribute("usuario") == null) {

        mav.setViewName("login/login");

    } else {
        sesionUser = sesion.getAttribute("usuario").toString();
        //Detalles detalle = (Detalles) sesion.getAttribute("cuenta");
        mav.addObject("country", detalle.getCiudad());
        mav.addObject("resultado", resultado);

        if (sesion.getAttribute("tipoUsuario").toString().compareTo("Administrador") == 0) {
            mav.setViewName("viewsAdmin/cuotasAdmin");
            System.out.println("el usuario es administrador");
        } else {
            mav.setViewName("panel/cuotas");
        }
    }
    return mav;
}

From source file:com.controller.CuotasController.java

@RequestMapping(value = "postCuotas.htm", method = RequestMethod.POST)
public ModelAndView postCuotas(HttpServletRequest request) {

    sesion = request.getSession();/*from   w  w  w.j a  va2s  .  c om*/
    String country = request.getParameter("country");
    String amount = request.getParameter("amount");

    Detalles detalle = (Detalles) sesion.getAttribute("cuenta");
    System.out.print(detalle.getCiudad());

    String myURL = "http://192.168.5.39/app_dev.php/public/get/rates";
    // System.out.println("Requested URL:" + myURL);
    StringBuilder sb = new StringBuilder();
    URLConnection urlConn = null;
    InputStreamReader in = null;
    try {
        URL url = new URL(myURL);
        urlConn = url.openConnection();
        if (urlConn != null) {
            urlConn.setReadTimeout(60 * 1000);
            urlConn.setDoOutput(true);
            String data = URLEncoder.encode("country", "UTF-8") + "=" + URLEncoder.encode(country, "UTF-8");
            data += "&" + URLEncoder.encode("amount", "UTF-8") + "=" + URLEncoder.encode(amount, "UTF-8");

            System.out.println("los Datos a enviar por POST son " + data);

            try ( //obtenemos el flujo de escritura
                    OutputStreamWriter wr = new OutputStreamWriter(urlConn.getOutputStream())) {
                //escribimos
                wr.write(data);
                wr.flush();
                //cerramos la conexin
            }
        }
        if (urlConn != null && urlConn.getInputStream() != null) {
            in = new InputStreamReader(urlConn.getInputStream(), Charset.defaultCharset());

            BufferedReader bufferedReader = new BufferedReader(in);
            if (bufferedReader != null) {
                int cp;
                while ((cp = bufferedReader.read()) != -1) {
                    sb.append((char) cp);
                }
                bufferedReader.close();
            }
        }
        in.close();
    } catch (Exception e) {
        e.printStackTrace();
        throw new RuntimeException("Exception while calling URL:" + myURL, e);
    }
    String resultado = sb.toString();

    ModelAndView mav = new ModelAndView();
    if (sesion.getAttribute("usuario") == null) {

        mav.setViewName("login/login");

    } else {
        sesionUser = sesion.getAttribute("usuario").toString();
        //Detalles detalle = (Detalles) sesion.getAttribute("cuenta");
        mav.addObject("country", detalle.getCiudad());
        mav.addObject("resultado", resultado);

        if (sesion.getAttribute("tipoUsuario").toString().compareTo("Administrador") == 0) {
            mav.setViewName("viewsAdmin/cuotasAdmin");
            System.out.println("el usuario es administrador");
        } else {
            mav.setViewName("panel/cuotas");
        }
    }
    return mav;

}

From source file:org.latticesoft.util.common.FileUtil.java

/**
 * Uploads a file content to an url//from w ww  .  ja v  a  2 s. co  m
 * @param url the url to upload to
 * @param input filename the input file to read from
 */
public static void uploadToURL(URL url, String inputFilename) {
    if (url == null || inputFilename == null) {
        return;
    }
    InputStream is = null;
    OutputStream os = null;
    Reader r = null;
    BufferedReader br = null;
    PrintWriter pw = null;
    String line = null;
    URLConnection conn = null;
    try {
        conn = url.openConnection();
        conn.connect();
        os = conn.getOutputStream();
        is = FileUtil.getInputStream(inputFilename);
        r = new InputStreamReader(is);
        br = new BufferedReader(r);
        pw = new PrintWriter(os);
        do {
            line = br.readLine();
            if (line != null) {
                pw.println(line);
            }
        } while (line != null);
    } catch (Exception e) {
        if (log.isErrorEnabled()) {
            log.error(e);
        }
    } finally {
        try {
            br.close();
        } catch (Exception e) {
        }
        try {
            r.close();
        } catch (Exception e) {
        }
        try {
            is.close();
        } catch (Exception e) {
        }
        try {
            pw.close();
        } catch (Exception e) {
        }
        try {
            os.close();
        } catch (Exception e) {
        }
    }
}