Example usage for java.io BufferedReader read

List of usage examples for java.io BufferedReader read

Introduction

In this page you can find the example usage for java.io BufferedReader read.

Prototype

public int read() throws IOException 

Source Link

Document

Reads a single character.

Usage

From source file:org.opendaylight.usc.test.manager.UscServiceTest.java

public void test() {
    // creating a new URL with the request
    String restUrl = "http://localhost:8181/restconf/operations/usc:usc-topology";
    // String restUrl =
    // "http://localhost:8080/restconf/config/toaster:toaster";
    URL url;//from  w ww  .java2s.c o  m
    try {
        url = new URL(restUrl);
    } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return;
    }

    // attaching authentication information
    String authString = "admin:admin";
    byte[] authEncBytes = Base64.encodeBase64(authString.getBytes());
    String authStringEnc = new String(authEncBytes);

    // creating the URLConnection
    HttpURLConnection connection;
    try {
        connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        connection.setRequestProperty("Authorization", "Basic " + authStringEnc);
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setRequestProperty("Accept", "application/json");
        connection.connect();

        // getting the result, first check response code
        Integer httpResponseCode = connection.getResponseCode();
        if (httpResponseCode > 299)
            System.out.print("ResponseCode = " + httpResponseCode);
        // get the result string from the inputstream.
        InputStream is = connection.getInputStream();
        BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
        StringBuilder sb = new StringBuilder();
        int cp;
        while ((cp = rd.read()) != -1) {
            sb.append((char) cp);
        }
        System.out.print("Content = " + sb.toString());
        JSONTokener jt = new JSONTokener(sb.toString());
        try {
            @SuppressWarnings("unused")
            JSONObject json = new JSONObject(jt);
            // test that the resulting name and subnet matches what was
            // expected
            // in variables name1, subnet1
            // Assert.assertEquals(name1, json.getString("@name"));
            // Assert.assertEquals(subnet1, json.getString("@subnet"));
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        is.close();
        connection.disconnect();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:com.util.httpAccount.java

public Account getAccountObject(String tel) {
    String telefono = tel.replace("-", "");
    System.out.println("OBTENER SOLO UN ARRAY DE CADENA JSON");
    //String myURL = "http://192.168.5.44/app_dev.php/cus/getaccount/50241109321.json";
    String myURL = "http://192.168.5.44/app_dev.php/cus/getaccount/" + telefono + ".json";
    System.out.println("Requested URL:" + myURL);
    StringBuilder sb = new StringBuilder();
    URLConnection urlConn = null;
    InputStreamReader in = null;//from   w w  w  . j a v  a  2s.  co  m
    Account account = new Account();
    try {
        URL url = new URL(myURL);
        urlConn = url.openConnection();
        if (urlConn != null) {
            urlConn.setReadTimeout(60 * 1000);
            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();
                }
            }

            String jsonResult = sb.toString();
            // System.out.println(sb.toString());
            //System.out.println("\n\n--------------------OBTENEMOS OBJETO JSON NATIVO DE LA PAGINA, USAMOS EL ARRAY DATA---------------------------\n\n");
            JSONObject objJason = new JSONObject(jsonResult);
            JSONArray dataJson = new JSONArray();
            dataJson = objJason.getJSONArray("data");

            //System.out.println("objeto normal 1 "+dataJson.toString());
            //
            //
            // System.out.println("\n\n--------------------CREAMOS UN STRING JSON2 REEMPLAZANDO LOS CORCHETES QUE DAN ERROR---------------------------\n\n");
            String jsonString2 = dataJson.toString();
            String temp = dataJson.toString();
            temp = jsonString2.replace("[", "");
            jsonString2 = temp.replace("]", "");
            // System.out.println("new json string"+jsonString2);

            JSONObject objJson2 = new JSONObject(jsonString2);
            // System.out.println("el objeto simple json es " + objJson2.toString());

            // System.out.println("\n\n--------------------CREAMOS UN OBJETO JSON CON EL ARRAR ACCOUN---------------------------\n\n");
            String account1 = objJson2.optString("account");
            // System.out.println(account1);
            JSONObject objJson3 = new JSONObject(account1);
            //   System.out.println("el ULTIMO OBJETO SIMPLE ES  " + objJson3.toString());
            //   System.out.println("\n\n--------------------EMPEZAMOS A RECIBIR LOS PARAMETROS QUE HAY EN EL OBJETO JSON---------------------------\n\n");
            String firstName = objJson3.getString("first_name");
            System.out.println(firstName);
            System.out.println(objJson3.get("language_id"));
            //  System.out.println("\n\n--------------------TRATAMOS DE PASAR TODO EL ACCOUNT A OBJETO JAVA---------------------------\n\n");
            Gson gson = new Gson();
            account = gson.fromJson(objJson3.toString(), Account.class);
            //System.out.println(account.getFirst_name());
            // System.out.println(account.getCreation());
            account.setLanguaje_id(objJson3.get("language_id").toString());
            account.setId(objJson3.get("id").toString());
            account.setBalance(objJson3.get("balance").toString());
            System.out.println("el id del account es " + account.getId());

        } else {
            System.out.print("no se pudo conectar con el servidor");
            account = null;
        }

        in.close();
    } catch (Exception e) {
        e.printStackTrace();
        throw new RuntimeException("Exception while calling URL:" + myURL, e);
    }

    return account;
}

From source file:io.github.apfelcreme.LitePortals.Bungee.LitePortals.java

/**
 * returns the uuid of the player with the given uuid
 *
 * @param name a players name/*ww w  . jav a2  s .c  o  m*/
 * @return his uuid
 */
public UUID getUUIDByName(String name) {
    name = name.toUpperCase();
    if (uuidCache.containsKey(name)) {
        return uuidCache.get(name);
    } else if (getProxy().getPluginManager().getPlugin("UUIDDB") != null) {
        UUID uuid = UUID.fromString(UUIDDB.getInstance().getStorage().getUUIDByName(name, false));
        uuidCache.put(name, uuid);
        return uuid;
    } else {
        try {
            URL url = new URL(LitePortalsConfig.getInstance().getConfiguration().getString("uuidUrl")
                    .replace("{0}", name));
            BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
            StringBuilder json = new StringBuilder();
            int read;
            while ((read = in.read()) != -1) {
                json.append((char) read);
            }
            if (json.length() == 0) {
                return null;
            }
            JSONObject jsonObject = (JSONObject) (new JSONParser().parse(json.toString()));
            String id = jsonObject.get("id").toString();
            UUID uuid = UUID
                    .fromString(id.replaceAll("(\\w{8})(\\w{4})(\\w{4})(\\w{4})(\\w{12})", "$1-$2-$3-$4-$5"));
            uuidCache.put(name, uuid);
            return uuid;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    return null;
}

From source file:io.github.apfelcreme.LitePortals.Bungee.LitePortals.java

/**
 * returns the name of a player/*from  w w  w.j a v a 2 s  .  co m*/
 *
 * @param uuid a players uuid
 * @return his name
 */
public String getNameByUUID(UUID uuid) {
    if (uuidCache.containsValue(uuid)) {
        for (Map.Entry<String, UUID> entry : uuidCache.entrySet()) {
            if (entry.getValue().equals(uuid)) {
                return entry.getKey();
            }
        }
    } else if (getProxy().getPluginManager().getPlugin("UUIDDB") != null) {
        String name = UUIDDB.getInstance().getStorage().getNameByUUID(uuid);
        uuidCache.put(name.toUpperCase(), uuid);
        return name;
    } else {
        try {
            URL url = new URL(LitePortalsConfig.getInstance().getConfiguration().getString("nameUrl")
                    .replace("{0}", uuid.toString().replace("-", "")));
            BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
            StringBuilder json = new StringBuilder();
            int read;
            while ((read = in.read()) != -1) {
                json.append((char) read);
            }
            Object obj = new JSONParser().parse(json.toString());
            JSONArray jsonArray = (JSONArray) obj;
            String name = (String) ((JSONObject) jsonArray.get(jsonArray.size() - 1)).get("name");
            uuidCache.put(name.toUpperCase(), uuid);
            return name;
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
    return null;
}

From source file:org.apache.axis.transport.mail.MailSender.java

/**
 * Read from server using POP3//from w  ww  .j  a  va 2 s  .  co  m
 * @param msgContext
 * @throws Exception
 */
private void readUsingPOP3(String id, MessageContext msgContext) throws Exception {
    // Read the response back from the server
    String pop3Host = msgContext.getStrProp(MailConstants.POP3_HOST);
    String pop3User = msgContext.getStrProp(MailConstants.POP3_USERID);
    String pop3passwd = msgContext.getStrProp(MailConstants.POP3_PASSWORD);

    Reader reader;
    POP3MessageInfo[] messages = null;

    MimeMessage mimeMsg = null;
    POP3Client pop3 = new POP3Client();
    // We want to timeout if a response takes longer than 60 seconds
    pop3.setDefaultTimeout(60000);

    for (int i = 0; i < 12; i++) {
        pop3.connect(pop3Host);

        if (!pop3.login(pop3User, pop3passwd)) {
            pop3.disconnect();
            AxisFault fault = new AxisFault("POP3", "( Could not login to server.  Check password. )", null,
                    null);
            throw fault;
        }

        messages = pop3.listMessages();
        if (messages != null && messages.length > 0) {
            StringBuffer buffer = null;
            for (int j = 0; j < messages.length; j++) {
                reader = pop3.retrieveMessage(messages[j].number);
                if (reader == null) {
                    AxisFault fault = new AxisFault("POP3", "( Could not retrieve message header. )", null,
                            null);
                    throw fault;
                }

                buffer = new StringBuffer();
                BufferedReader bufferedReader = new BufferedReader(reader);
                int ch;
                while ((ch = bufferedReader.read()) != -1) {
                    buffer.append((char) ch);
                }
                bufferedReader.close();
                if (buffer.toString().indexOf(id) != -1) {
                    ByteArrayInputStream bais = new ByteArrayInputStream(buffer.toString().getBytes());
                    Properties prop = new Properties();
                    Session session = Session.getDefaultInstance(prop, null);

                    mimeMsg = new MimeMessage(session, bais);
                    pop3.deleteMessage(messages[j].number);
                    break;
                }
                buffer = null;
            }
        }
        pop3.logout();
        pop3.disconnect();
        if (mimeMsg == null) {
            Thread.sleep(5000);
        } else {
            break;
        }
    }

    if (mimeMsg == null) {
        pop3.logout();
        pop3.disconnect();
        AxisFault fault = new AxisFault("POP3", "( Could not retrieve message list. )", null, null);
        throw fault;
    }

    String contentType = mimeMsg.getContentType();
    String contentLocation = mimeMsg.getContentID();
    Message outMsg = new Message(mimeMsg.getInputStream(), false, contentType, contentLocation);

    outMsg.setMessageType(Message.RESPONSE);
    msgContext.setResponseMessage(outMsg);
    if (log.isDebugEnabled()) {
        log.debug("\n" + Messages.getMessage("xmlRecd00"));
        log.debug("-----------------------------------------------");
        log.debug(outMsg.getSOAPPartAsString());
    }
}

From source file:com.mirth.connect.connectors.jdbc.DatabaseReceiver.java

private String clobToString(Clob clob) throws Exception {
    StringBuilder stringBuilder = new StringBuilder();
    Reader reader = clob.getCharacterStream();
    BufferedReader bufferedReader = new BufferedReader(reader);
    int c;// w  w  w .  j ava 2s.  c om

    try {
        while ((c = bufferedReader.read()) != -1) {
            stringBuilder.append((char) c);
        }

        return stringBuilder.toString();
    } finally {
        IOUtils.closeQuietly(bufferedReader);
        IOUtils.closeQuietly(reader);
    }
}

From source file:dk.clarin.tools.workflow.java

/**
* Sends an HTTP GET request to a url/*  w ww  . j  ava 2  s .com*/
*
* @param endpoint - The URL of the server. (Example: " http://www.yahoo.com/search")
* @param requestString - all the request parameters (Example: "param1=val1&param2=val2"). Note: This method will add the question mark (?) to the request - DO NOT add it yourself
* @return - The response from the end point
*/

public static int sendRequest(String result, String endpoint, String requestString, bracmat BracMat,
        String filename, String jobID, boolean postmethod) {
    int code = 0;
    String message = "";
    //String filelist;
    if (endpoint.startsWith("http://") || endpoint.startsWith("https://")) {
        // Send a GET or POST request to the servlet
        try {
            // Construct data
            String requestResult = "";
            String urlStr = endpoint;
            if (postmethod) // HTTP POST
            {
                logger.debug("HTTP POST");
                StringReader input = new StringReader(requestString);
                StringWriter output = new StringWriter();
                URL endp = new URL(endpoint);

                HttpURLConnection urlc = null;
                try {
                    urlc = (HttpURLConnection) endp.openConnection();
                    try {
                        urlc.setRequestMethod("POST");
                    } catch (ProtocolException e) {
                        throw new Exception("Shouldn't happen: HttpURLConnection doesn't support POST??", e);
                    }
                    urlc.setDoOutput(true);
                    urlc.setDoInput(true);
                    urlc.setUseCaches(false);
                    urlc.setAllowUserInteraction(false);
                    urlc.setRequestProperty("Content-type", "text/xml; charset=" + "UTF-8");

                    OutputStream out = urlc.getOutputStream();

                    try {
                        Writer writer = new OutputStreamWriter(out, "UTF-8");
                        pipe(input, writer);
                        writer.close();
                    } catch (IOException e) {
                        throw new Exception("IOException while posting data", e);
                    } finally {
                        if (out != null)
                            out.close();
                    }
                } catch (IOException e) {
                    throw new Exception("Connection error (is server running at " + endp + " ?): " + e);
                } finally {
                    if (urlc != null) {
                        code = urlc.getResponseCode();

                        if (code == 200) {
                            got200(result, BracMat, filename, jobID, urlc.getInputStream());
                        } else {
                            InputStream in = urlc.getInputStream();
                            try {
                                Reader reader = new InputStreamReader(in);
                                pipe(reader, output);
                                reader.close();
                                requestResult = output.toString();
                            } catch (IOException e) {
                                throw new Exception("IOException while reading response", e);
                            } finally {
                                if (in != null)
                                    in.close();
                            }
                            logger.debug("urlc.getResponseCode() == {}", code);
                            message = urlc.getResponseMessage();
                            didnotget200(code, result, endpoint, requestString, BracMat, filename, jobID,
                                    postmethod, urlStr, message, requestResult);
                        }
                        urlc.disconnect();
                    } else {
                        code = 0;
                        didnotget200(code, result, endpoint, requestString, BracMat, filename, jobID,
                                postmethod, urlStr, message, requestResult);
                    }
                }
                //requestResult = output.toString();
                logger.debug("postData returns " + requestResult);
            } else // HTTP GET
            {
                logger.debug("HTTP GET");
                // Send data

                if (requestString != null && requestString.length() > 0) {
                    urlStr += "?" + requestString;
                }
                URL url = new URL(urlStr);
                URLConnection conn = url.openConnection();
                conn.connect();

                // Cast to a HttpURLConnection
                if (conn instanceof HttpURLConnection) {
                    HttpURLConnection httpConnection = (HttpURLConnection) conn;
                    code = httpConnection.getResponseCode();
                    logger.debug("httpConnection.getResponseCode() == {}", code);
                    message = httpConnection.getResponseMessage();
                    BufferedReader rd;
                    StringBuilder sb = new StringBuilder();
                    ;
                    //String line;
                    if (code == 200) {
                        got200(result, BracMat, filename, jobID, httpConnection.getInputStream());
                    } else {
                        // Get the error response
                        rd = new BufferedReader(new InputStreamReader(httpConnection.getErrorStream()));
                        int nextChar;
                        while ((nextChar = rd.read()) != -1) {
                            sb.append((char) nextChar);
                        }
                        rd.close();
                        requestResult = sb.toString();
                        didnotget200(code, result, endpoint, requestString, BracMat, filename, jobID,
                                postmethod, urlStr, message, requestResult);
                    }
                } else {
                    code = 0;
                    didnotget200(code, result, endpoint, requestString, BracMat, filename, jobID, postmethod,
                            urlStr, message, requestResult);
                }
            }
            logger.debug("Job " + jobID + " receives status code [" + code + "] from tool.");
        } catch (Exception e) {
            //jobs = 0; // No more jobs to process now, probably the tool is not reachable
            logger.warn("Job " + jobID + " aborted. Reason:" + e.getMessage());
            /*filelist =*/ BracMat.Eval("abortJob$(" + result + "." + jobID + ")");
        }
    } else {
        //jobs = 0; // No more jobs to process now, probably the tool is not integrated at all
        logger.warn("Job " + jobID + " aborted. Endpoint must start with 'http://' or 'https://'. (" + endpoint
                + ")");
        /*filelist =*/ BracMat.Eval("abortJob$(" + result + "." + jobID + ")");
    }
    return code;
}

From source file:com.dotmarketing.portlets.rules.actionlet.VisitorsTagsActionletFTest.java

/**
 * Test adding tags to visitor object//from w  ww . jav a2  s  .  co m
 * @throws Exception
 */
@Test
public void addTag1() throws Exception {

    sysuser = userAPI.getSystemUser();
    Host host = hostAPI.findDefaultHost(sysuser, false);

    // setting up the requirements for testing
    // a new cotent to create the persona linked to the visitor
    Contentlet personaContentlet = new Contentlet();
    personaContentlet.setStructureInode(PersonaAPI.DEFAULT_PERSONAS_STRUCTURE_INODE);
    personaContentlet.setHost(host.getIdentifier());
    personaContentlet.setLanguageId(languageAPI.getDefaultLanguage().getId());
    String name = "persona1" + UtilMethods.dateToHTMLDate(new Date(), "MMddyyyyHHmmss");
    personaContentlet.setProperty(PersonaAPI.NAME_FIELD, name);
    personaContentlet.setProperty(PersonaAPI.KEY_TAG_FIELD, name);
    personaContentlet.setProperty(PersonaAPI.TAGS_FIELD, "persona");
    personaContentlet.setProperty(PersonaAPI.DESCRIPTION_FIELD, "test to delete");
    personaContentlet = contentletAPI.checkin(personaContentlet, sysuser, false);
    contentletAPI.publish(personaContentlet, sysuser, false);

    Persona persona = new Persona(personaContentlet);

    // 4 test rules
    // test 1 : using a single tag
    createTagActionlet("testing");

    // test 2 : using a multiple tags
    createTagActionlet("persona,asia,china,nigeria");

    // test 3 : using a new tag (not from the tag manager)
    createTagActionlet("newtag");

    // test 4 : using multiple a new tags (not from the tag manager)
    createTagActionlet("new2tag,new3tag,new4tag");

    // environment setup
    // FOLDER
    Folder folder = folderAPI.createFolders("/tags-actionlet-" + System.currentTimeMillis(), host, sysuser,
            false);
    // TEMPLATE
    Template template = templateAPI.find(BLANK_TEMPLATE_INODE, sysuser, false);
    // PAGE
    String page = "tags-page-" + UtilMethods.dateToHTMLDate(new Date(), "MMddyyyyHHmmss");
    Contentlet pageContentlet = new Contentlet();
    pageContentlet.setStructureInode(HTMLPageAssetAPIImpl.DEFAULT_HTMLPAGE_ASSET_STRUCTURE_INODE);
    pageContentlet.setHost(host.getIdentifier());
    pageContentlet.setProperty(HTMLPageAssetAPIImpl.FRIENDLY_NAME_FIELD, page);
    pageContentlet.setProperty(HTMLPageAssetAPIImpl.URL_FIELD, page);
    pageContentlet.setProperty(HTMLPageAssetAPIImpl.TITLE_FIELD, page);
    pageContentlet.setProperty(HTMLPageAssetAPIImpl.CACHE_TTL_FIELD, "0");
    pageContentlet.setProperty(HTMLPageAssetAPIImpl.TEMPLATE_FIELD, template.getIdentifier());
    pageContentlet.setLanguageId(languageAPI.getDefaultLanguage().getId());
    pageContentlet.setFolder(folder.getInode());
    pageContentlet = contentletAPI.checkin(pageContentlet, sysuser, false);
    contentletAPI.publish(pageContentlet, sysuser, false);

    // Widget to show the tag
    String title = "personawidget" + UtilMethods.dateToHTMLDate(new Date(), "MMddyyyyHHmmss");
    String body = "<p>$visitor.accruedTags</p>";
    Contentlet widgetContentlet = new Contentlet();
    Structure contentst = StructureFactory.getStructureByVelocityVarName("webPageContent");
    Structure widgetst = StructureFactory.getStructureByVelocityVarName("SimpleWidget");
    widgetContentlet.setStructureInode(widgetst.getInode());
    widgetContentlet.setHost(host.getIdentifier());
    widgetContentlet.setProperty("widgetTitle", title);
    widgetContentlet.setLanguageId(languageAPI.getDefaultLanguage().getId());
    widgetContentlet.setProperty("code", body);
    widgetContentlet.setFolder(folder.getInode());
    widgetContentlet = contentletAPI.checkin(widgetContentlet, sysuser, false);
    contentletAPI.publish(widgetContentlet, sysuser, false);

    Container container = null;
    List<Container> containers = containerAPI.findContainersForStructure(contentst.getInode());
    for (Container c : containers) {
        if (c.getTitle().equals("Blank Container")) {
            container = c;
            break;
        }
    }

    MultiTree m = new MultiTree(pageContentlet.getIdentifier(), container.getIdentifier(),
            widgetContentlet.getIdentifier());
    MultiTreeFactory.saveMultiTree(m);

    // login
    CookieHandler.setDefault(new CookieManager());
    URL testUrl = new URL(baseUrl
            + "/c/portal_public/login?my_account_cmd=auth&my_account_login=admin@dotcms.com&password=admin&my_account_r_m=true");
    IOUtils.toString(testUrl.openStream(), "UTF-8");

    String url = baseUrl + folder.getPath() + page
            + "?mainFrame=true&livePage=0com.dotmarketing.htmlpage.language=1&host_id=" + host.getIdentifier()
            + "&com.dotmarketing.persona.id=" + persona.getIdentifier() + "&previewPage=2";
    testUrl = new URL(url);
    StringBuilder result = new StringBuilder();
    InputStreamReader isr = new InputStreamReader(testUrl.openStream());
    BufferedReader br = new BufferedReader(isr);
    int byteRead;
    while ((byteRead = br.read()) != -1) {
        result.append((char) byteRead);
    }
    br.close();

    // testing
    Assert.assertTrue("Expected tag 'testing' not found", result.toString().contains("testing"));

    Assert.assertTrue("Expected tag 'persona' not found", result.toString().contains("persona"));
    Assert.assertTrue("Expected tag 'asia' not found", result.toString().contains("asia"));
    Assert.assertTrue("Expected tag 'china' not found", result.toString().contains("china"));
    Assert.assertTrue("Expected tag 'nigeria' not found", result.toString().contains("nigeria"));

    Assert.assertTrue("Expected tag 'newtag' not found", result.toString().contains("newtag"));

    Assert.assertTrue("Expected tag 'new2tag' not found", result.toString().contains("new2tag"));
    Assert.assertTrue("Expected tag 'new3tag' not found", result.toString().contains("new3tag"));
    Assert.assertTrue("Expected tag 'new4tag' not found", result.toString().contains("new4tag"));

    Assert.assertFalse("Unexpected tag 'dollar' found", result.toString().contains("dollar"));

    // clean up
    contentletAPI.unpublish(personaContentlet, sysuser, false);
    contentletAPI.unpublish(widgetContentlet, sysuser, false);
    contentletAPI.unpublish(pageContentlet, sysuser, false);
    contentletAPI.archive(personaContentlet, sysuser, false);
    contentletAPI.archive(widgetContentlet, sysuser, false);
    contentletAPI.archive(pageContentlet, sysuser, false);
    contentletAPI.delete(personaContentlet, sysuser, false);
    contentletAPI.delete(widgetContentlet, sysuser, false);
    contentletAPI.delete(pageContentlet, sysuser, false);

    folderAPI.delete(folder, sysuser, false);
}

From source file:org.owasp.jbrofuzz.graph.canvas.ResponseSizeChart.java

private int calculateValue(final File inputFile) {

    if (inputFile.isDirectory()) {
        return -1;
    }/*from  w  ww  . jav  a  2 s.c  om*/

    long headerLength = 0L;

    BufferedReader inBuffReader = null;
    try {

        inBuffReader = new BufferedReader(new FileReader(inputFile));

        final StringBuffer one = new StringBuffer();
        int counter = 0;
        int got;
        while (((got = inBuffReader.read()) > 0) && (counter < MAX_CHARS)) {

            one.append((char) got);
            counter++;

        }
        inBuffReader.close();

        one.delete(0, 5);
        one.delete(one.indexOf("\n--"), one.length());

        headerLength = (one.indexOf(END_SIGNATURE) + END_SIGNATURE.length());

    } catch (final IOException e1) {

        return -2;

    } catch (final StringIndexOutOfBoundsException e2) {

        return -3;

    } catch (final NumberFormatException e3) {

        return -4;

    } finally {

        IOUtils.closeQuietly(inBuffReader);

    }

    return (int) (inputFile.length() - headerLength);
}

From source file:com.controller.CuotasController.java

@RequestMapping("cuotas.htm")
public ModelAndView getCuotas(HttpServletRequest request) {
    sesion = request.getSession();/*from w w w  .j ava  2s . c om*/
    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;
}