Example usage for java.net URLDecoder URLDecoder

List of usage examples for java.net URLDecoder URLDecoder

Introduction

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

Prototype

URLDecoder

Source Link

Usage

From source file:Main.java

public static String getDecodeString(String str) {
    java.net.URLDecoder ud = new URLDecoder();
    try {//from  www.  j  ava  2s  .co m
        str = ud.decode(str, "utf-8");
    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return str;
}

From source file:com.web.server.WebServer.java

/**
 * This methos is the implementation of the HTPP request and sends the response.
 */// www.  java  2s .c  o  m
public void run() {
    byte[] response;
    byte[] content;
    byte[] uploadData = null;
    HttpHeaderClient httpHeaderClient = null;
    InputStream istream = null;
    OutputStream ostream = null;
    HttpHeaderServer serverParam = new HttpHeaderServer();
    StringBuffer buffer = new StringBuffer();
    String value;
    char c;
    String endvalue = "\r\n\r\n";
    String urlFormEncoded;
    int responseCode;
    try {
        ////System.out.println("value=");
        istream = socket.getInputStream();
        BufferedInputStream bistr = new BufferedInputStream(istream);
        //socket.setReceiveBufferSize(10000);
        //System.out.println("value1=");
        int availbleStream;
        int totalBytRead = 0;
        int ch;
        ByteArrayOutputStream bytout = new ByteArrayOutputStream();
        ByteArrayOutputStream contentout = new ByteArrayOutputStream();
        //System.out.println(istream.available());
        int bytesRead;
        int endbytIndex = 0;
        int contentbytIndex = 0;
        boolean httpHeaderEndFound = false;
        byte[] byt;
        while ((ch = bistr.read()) != -1) {
            bytout.write(ch);
            if (!httpHeaderEndFound && (char) ch == endvalue.charAt(endbytIndex)) {
                endbytIndex++;
                if (endbytIndex == endvalue.length()) {
                    byt = bytout.toByteArray();
                    value = new String(ObtainBytes(byt, 0, byt.length - 4));
                    //System.out.println(value);
                    httpHeaderClient = parseHttpHeaders(value);
                    httpHeaderEndFound = true;
                    bytout.close();
                    endbytIndex = 0;
                    if (httpHeaderClient.getContentLength() == null)
                        break;
                }
            } else {
                endbytIndex = 0;
            }
            if (httpHeaderClient != null && httpHeaderEndFound) {
                contentout.write(ch);
                contentbytIndex++;
                if (httpHeaderClient.getContentLength() != null
                        && contentbytIndex >= Integer.parseInt(httpHeaderClient.getContentLength())) {
                    break;
                }
            }
            totalBytRead++;
        }
        /*while(totalBytRead==0){
           while((ch = bistr.read())!=-1){
              System.out.println((char)ch);
              ////System.out.println("availableStream="+availbleStream);
              bytarrayOutput.write(ch);
              totalBytRead++;
           }
        }*/
        if (totalBytRead == 0) {
            System.out.println("Since byte is 0 sock and istream os closed");
            //istream.close();
            socket.close();
            return;
        }
        //istream.read(bt,0,9999999);
        System.out.println("bytes read");
        byte[] contentByte = contentout.toByteArray();
        contentout.close();
        //System.out.println("String="+new String(bt));
        /*int index=containbytes(bt,endvalue.getBytes());
        if(index==-1)index=totalBytRead;
        value=new String(ObtainBytes(bt,0,index));*/
        System.out.println("value2=");

        ConcurrentHashMap<String, HttpCookie> httpCookies = httpHeaderClient.getCookies();
        HttpSessionServer session = null;
        if (httpCookies != null) {
            Iterator<String> cookieNames = httpCookies.keySet().iterator();
            for (; cookieNames.hasNext();) {
                String cookieName = cookieNames.next();
                //System.out.println(cookieName+" "+httpCookies.get(cookieName).getValue());
                if (cookieName.equals("SERVERSESSIONID")) {
                    session = (HttpSessionServer) sessionObjects.get(httpCookies.get(cookieName).getValue());
                    httpHeaderClient.setSession(session);
                    //break;
                }
            }
        }
        //System.out.println("Session="+session);
        if (session == null) {
            HttpCookie cookie = new HttpCookie();
            cookie.setKey("SERVERSESSIONID");
            cookie.setValue(UUID.randomUUID().toString());
            httpCookies.put("SERVERSESSIONID", cookie);
            session = new HttpSessionServer();
            sessionObjects.put(cookie.getValue(), session);
            httpHeaderClient.setSession(session);
        }
        if (httpHeaderClient.getContentType() != null
                && httpHeaderClient.getContentType().equals(HttpHeaderParamNames.MULTIPARTFORMDATAVALUE)) {
            ////System.out.println(new String(uploadData));
            ConcurrentHashMap paramMap = new MultipartFormData().parseContent(contentByte, httpHeaderClient);
            httpHeaderClient.setParameters(paramMap);
            ////logger.info(uploadData);
        } else if (httpHeaderClient.getContentType() != null
                && httpHeaderClient.getContentType().equals(HttpHeaderParamNames.URLENCODED)) {
            urlFormEncoded = new String(contentByte);
            ConcurrentHashMap paramMap = parseUrlEncoded(urlFormEncoded);
            httpHeaderClient.setParameters(paramMap);
        }
        ////logger.info(serverconfig.getDeploydirectory()+httpHeaderClient.getResourceToObtain());
        ////System.out.println("value3=");

        ////logger.info(new String(bt));
        serverParam.setContentType("text/html");
        URLDecoder decoder = new URLDecoder();
        System.out.println("content Length= " + socket);
        responseCode = 200;
        File file = new File(deployDirectory + decoder.decode(httpHeaderClient.getResourceToObtain()));
        FileContent fileContent = (FileContent) cache.get(httpHeaderClient.getResourceToObtain());
        if (fileContent != null && file.lastModified() == fileContent.getLastModified()) {
            System.out.println("In cache");
            content = (byte[]) fileContent.getContent();
        } else {
            content = ObtainContentExecutor(deployDirectory, httpHeaderClient.getResourceToObtain(),
                    httpHeaderClient, serverdigester, urlClassLoaderMap, servletMapping, session);
            System.out.println("content Length2= " + content);
            if (content == null) {
                //System.out.println("In caching content");
                content = obtainContent(
                        deployDirectory + decoder.decode(httpHeaderClient.getResourceToObtain()));
                if (content != null) {
                    fileContent = new FileContent();
                    fileContent.setContent(content);
                    fileContent.setFileName(httpHeaderClient.getResourceToObtain());
                    fileContent.setLastModified(file.lastModified());
                    cache.put(httpHeaderClient.getResourceToObtain(), fileContent);
                }
            }
            ////System.out.println("value4=");

        }

        if (content == null) {
            responseCode = 404;
            content = ("<html><body><H1>The Request resource " + httpHeaderClient.resourceToObtain
                    + " Not Found</H1><body></html>").getBytes();
        }
        ////System.out.println("content Length3= ");
        serverParam.setContentLength("" + (content.length + 4));
        if (httpHeaderClient.getResourceToObtain().endsWith(".ico")) {
            serverParam.setContentType("image/png");
        }
        ////System.out.println("value5=");

        ////System.out.println("content Length4= ");
        response = formHttpResponseHeader(responseCode, serverParam, content, httpHeaderClient.getCookies());
        ////System.out.println("value6=");
        ostream = socket.getOutputStream();
        //logger.info("Response="+new String(response));
        //System.out.println("value6=");
        //logger.info("Response="+new String(response));
        ////System.out.println("content "+"Response="+new String(response));
        ostream.write(response);
        ostream.flush();
        ostream.close();
        socket.close();
    } catch (IOException e) {
        Socket socket;
        e.printStackTrace();

        //logger.error(e);
        try {
            socket = new Socket("localhost", shutdownPort);
            OutputStream outputStream = socket.getOutputStream();
            outputStream.write("shutdown WebServer\r\n\r\n".getBytes());
            outputStream.close();
        } catch (Exception ex) {

            ex.printStackTrace();
        }
        e.printStackTrace();
    } catch (NumberFormatException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

From source file:org.adl.samplerte.server.LMSManifestHandler.java

License:asdf

/****************************************************************************
 ** //www.  j  a  v a  2s .  c  o  m
 ** Method: updateDB() Input: none Output: none Description: This method
 * takes the relevant information from the populated parser structure and
 * writes it to a related database. This is done so that the JSP coding is
 * more straight forward.
 ** 
 ** Side Effects: none
 ** 
 ***************************************************************************/
protected void updateDB() {
    if (DebugIndicator.ON) {
        System.out.println("******  LMSManifestHandler:updateDB()  *********");
    }
    try {

        int t = 1;
        List<Scoinfo> list = scoinfoService.findAllScoinfo();
        try {
            System.out.println("----" + list.size());
            if (list != null && list.size() > 0) {
                t = list.get(list.size() - 1).getScoId() + 1;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        courseID = t + "";

        ADLItem tempItem = new ADLItem();

        // Loop through each item in the course adding it to the
        // database
        for (int i = 0; i < items.size(); i++) {
            tempItem = (org.adl.parsers.dom.ADLItem) items.elementAt(i);

            // Decode the URL before inserting into the database
            URLDecoder urlDecoder = new URLDecoder();
            String alteredLocation = new String();

            // If its external, don't concatenate to the local Web root.
            if ((tempItem.getLaunchLocation().startsWith("http://"))
                    || (tempItem.getLaunchLocation().startsWith("https://"))) {
                alteredLocation = URLDecoder.decode(tempItem.getLaunchLocation());
            } else {
                // Create the altered location (with decoded url)
                alteredLocation = "/scorm/CourseImports/" + courseID + "/"
                        + URLDecoder.decode(tempItem.getLaunchLocation());
            }

            // Insert into the database
            Courseinfo cInfo = null;
            try {
                System.out.println("courseName=" + courseTitle + "\n-----" + courseinfoService);
                cInfo = courseinfoService.findByCourseId(Integer.parseInt(courseTitle)).get(0);
                System.out.println("findCourseName=" + cInfo.getCourseName());
            } catch (Exception e) {
                e.printStackTrace();
                System.out.println("error=" + e.getMessage());
                return;
            }
            System.out.println("------------");
            Timestamp uploadTime = new Timestamp(System.currentTimeMillis());
            System.out.println("isTest=" + isTest);

            Userinfo userinfo = ActionSupport.getSessionUser();
            Scoinfo scoinfo = new Scoinfo(cInfo, tempItem.getTitle(), uploadTime, userinfo.getUserName(),
                    alteredLocation, 0, Integer.parseInt(isTest));
            scoinfoService.saveScoinfo(scoinfo);
            System.out.println("asdfsadf");

        } // Ends looping throught the item list

    } catch (Exception se) {
        if (DebugIndicator.ON) {

            se.printStackTrace();
        }
    }
}

From source file:com.web.server.WebServer.java

/**
 * This method parses the encoded url /*from  w ww . j a va 2  s .  c om*/
 * @param urlEncoded
 * @return
 */
public static ConcurrentHashMap parseUrlEncoded(String urlEncoded) {
    ConcurrentHashMap ParamValue = new ConcurrentHashMap();
    URLDecoder urlDecoder = new URLDecoder();
    StringTokenizer paramGroup = new StringTokenizer(urlDecoder.decode(urlEncoded), "&");

    while (paramGroup.hasMoreTokens()) {

        StringTokenizer token = new StringTokenizer(paramGroup.nextToken(), "=");
        String key = "";
        String value = "";
        if (token.hasMoreTokens())
            key = token.nextToken();
        if (token.hasMoreTokens())
            value = token.nextToken();
        ParamValue.put(key, value);

    }
    return ParamValue;
}

From source file:com.temenos.interaction.core.rim.HTTPHypermediaRIM.java

@SuppressWarnings("static-access")
private void decodeQueryParams(MultivaluedMap<String, String> queryParameters) {

    try {/*from w w w  . ja  v  a2s  . c om*/

        if (queryParameters == null) {
            return;
        }

        URLDecoder ud = new URLDecoder();

        for (String key : queryParameters.keySet()) {
            List<String> values = queryParameters.get(key);
            if (values != null) {
                List<String> newValues = new ArrayList<String>();
                for (String value : values) {
                    if (value != null)
                        newValues.add(ud.decode(value, "UTF-8"));
                }
                queryParameters.put(key, newValues);
            }
        }

    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.web.server.WebServer.java

/**
 * This method obtains the url parameters
 * @param url/* w w  w.  ja  va2  s.  co m*/
 * @param params
 * @return string
 */
public String ObtainUrlAndParams(String url, ConcurrentHashMap params) {

    URLDecoder decoder = new URLDecoder();
    url = decoder.decode(url);
    if (url.indexOf("?") > -1) {
        String paramaters = url.substring(url.indexOf("?") + 1);
        StringTokenizer paramGroup = new StringTokenizer(paramaters, "&");

        while (paramGroup.hasMoreTokens()) {

            StringTokenizer value = new StringTokenizer(paramGroup.nextToken(), "=");
            String param = null;
            if (value.hasMoreTokens()) {
                param = value.nextToken();
            }
            String paramValue = null;
            if (value.hasMoreTokens()) {
                paramValue = value.nextToken();
            }
            if (param != null && paramValue != null) {
                if (params.get(param) != null) {
                    if (params.get(param) instanceof String[]) {
                        String[] parameters = (String[]) params.get(param);
                        String[] paramValues = new String[parameters.length + 1];
                        for (int paramcount = 0; paramcount < parameters.length; paramcount++) {
                            paramValues[paramcount] = parameters[paramcount];
                        }
                        paramValues[parameters.length] = paramValue;
                        params.put(param, paramValues);
                    } else if (params.get(param) instanceof String) {
                        String[] paramValues = new String[2];
                        paramValues[0] = (String) params.get(param);
                        paramValues[1] = paramValue;
                        params.put(param, paramValues);
                    }
                } else {
                    params.put(param, paramValue);
                }
            }
        }
    }
    if (url.indexOf("?") != -1) {
        return url.substring(0, url.indexOf("?"));
    }
    return url;
}