Example usage for java.net URLDecoder decode

List of usage examples for java.net URLDecoder decode

Introduction

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

Prototype

@Deprecated
public static String decode(String s) 

Source Link

Document

Decodes a x-www-form-urlencoded string.

Usage

From source file:com.quackware.handsfreemusic.YouTubeUtility.java

public static String calculateYouTubeUrl(String youtubeVideoId)
        throws IOException, ClientProtocolException, UnsupportedEncodingException {
    HttpClient client = new DefaultHttpClient();
    HttpGet getMethod = new HttpGet(YOUTUBE_VIDEO_INFORMATION_URL + youtubeVideoId);
    HttpResponse response = null;/*  w w  w. ja  v  a2  s  .  c o  m*/

    response = client.execute(getMethod);

    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    String infoStr = null;
    response.getEntity().writeTo(bos);
    infoStr = new String(bos.toString("UTF-8"));

    String[] args = infoStr.split("&");
    Map<String, String> argMap = new HashMap<String, String>();
    for (int i = 0; i < args.length; i++) {
        String[] argValStrArr = args[i].split("=");
        if (argValStrArr != null) {
            if (argValStrArr.length >= 2) {
                argMap.put(argValStrArr[0], URLDecoder.decode(argValStrArr[1]));
            }
        }
    }
    String tokenStr = null;
    try {
        tokenStr = URLDecoder.decode(argMap.get("token"));
    } catch (Exception ex) {
        return null;
    }
    String uriStr = "http://www.youtube.com/get_video?video_id=" + youtubeVideoId + "&t="
            + URLEncoder.encode(tokenStr) + "&fmt=18";
    return uriStr;
}

From source file:com.captix.scan.social.facebook.Util.java

@SuppressWarnings("deprecation")
public static Bundle decodeUrl(String s) {
    Bundle params = new Bundle();
    if (s != null) {
        String array[] = s.split("&");
        for (String parameter : array) {
            String v[] = parameter.split("=");
            params.putString(URLDecoder.decode(v[0]), URLDecoder.decode(v[1]));
        }//from   w w w.jav a 2s.c  o  m
    }
    return params;
}

From source file:com.rajaram.bookmark.controller.BookmarkController.java

/**
 * <P>// w ww .  j  av a  2s.c  o m
 * Upload single bookmark file.
 * </P>
 * 
 * @param userName
 * @param file
 * @return 
 */
@RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
@ApiOperation(httpMethod = "POST", value = "Upload and extract data "
        + "from the bookmark file and stores the extracted data to the"
        + " bookmark SQL table.", produces = ("application/json,application/xml"))
public @ResponseBody Response uploadFileHandler(
        @ApiParam(name = "userName", value = "user name", required = true) @RequestParam String userName,
        @ApiParam(name = "file", value = "file", required = true) @RequestParam MultipartFile file) {
    userName = URLDecoder.decode(userName);
    Response response = new Response();
    InputStream fileIn = null;

    try {
        fileIn = file.getInputStream();
    } catch (IOException ex) {
        Logger.getLogger(BookmarkController.class.getName()).log(Level.SEVERE, null, ex);
        response.setMessage("Error reading bookmark file. Error message : " + ex.getMessage());
        return response;
    }

    List<Bookmark> bookmarks = bookmarkOperation.extractNetscapeBookmarks(fileIn);

    try {
        bookmarkService.insertBookmarks(userName, bookmarks);
        response.setMessage("Bookmark data is stored in the database");
    } catch (DataAccessException ex) {

        response.setMessage("Error storing bookmark data. Error message : " + ex.getMessage());
    }
    return response;
}

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

/**
 * This methos is the implementation of the HTPP request and sends the response.
 *///from  ww w . j  a v  a 2  s .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:com.wbtech.ums.common.NetworkUitlity.java

public static String Post(String url, String data) {

    CommonUtil.printLog("ums", url);

    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost(url);
    try {//from  w ww .  j ava2s . c  o m
        StringEntity se = new StringEntity("content=" + data, HTTP.UTF_8);
        CommonUtil.printLog("postdata", "content=" + data);
        se.setContentType("application/x-www-form-urlencoded");
        httppost.setEntity(se);
        HttpResponse response = httpclient.execute(httppost);
        int status = response.getStatusLine().getStatusCode();
        CommonUtil.printLog("ums", status + "");
        String returnXML = EntityUtils.toString(response.getEntity());
        Log.d("returnString", URLDecoder.decode(returnXML));
        return URLDecoder.decode(returnXML);

    } catch (Exception e) {
        CommonUtil.printLog("ums", e.toString());
    }
    return null;
}

From source file:org.data.support.beans.factory.xml.ResourceEntityResolver.java

@Override
public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException {
    InputSource source = super.resolveEntity(publicId, systemId);
    if (source == null && systemId != null) {
        String resourcePath = null;
        try {/*from  w  w w  . java  2s. co  m*/
            String decodedSystemId = URLDecoder.decode(systemId);
            String givenUrl = new URL(decodedSystemId).toString();
            String systemRootUrl = new File("").toURL().toString();
            // Try relative to resource base if currently in system root.
            if (givenUrl.startsWith(systemRootUrl)) {
                resourcePath = givenUrl.substring(systemRootUrl.length());
            }
        } catch (Exception ex) {
            // Typically a MalformedURLException or AccessControlException.
            if (logger.isDebugEnabled()) {
                logger.debug("Could not resolve XML entity [" + systemId + "] against system root URL", ex);
            }
            // No URL (or no resolvable URL) -> try relative to resource base.
            resourcePath = systemId;
        }
        if (resourcePath != null) {
            if (logger.isTraceEnabled()) {
                logger.trace(
                        "Trying to locate XML entity [" + systemId + "] as resource [" + resourcePath + "]");
            }
            Resource resource = this.resourceLoader.getResource(resourcePath);
            source = new InputSource(resource.getInputStream());
            source.setPublicId(publicId);
            source.setSystemId(systemId);
            if (logger.isDebugEnabled()) {
                logger.debug("Found XML entity [" + systemId + "]: " + resource);
            }
        }
    }
    return source;
}

From source file:com.personalserver.DirCommandHandler.java

private HttpEntity getEntityFromUri(String uri, HttpResponse response) {
    String contentType = "text/html";
    String filepath = FOLDER_SHARE_PATH;

    if (uri.equalsIgnoreCase("/") || uri.length() <= 0) {
        filepath = FOLDER_SHARE_PATH + "/";
    } else {//  ww  w  .jav a  2  s.  c o m
        filepath = FOLDER_SHARE_PATH + "/" + URLDecoder.decode(uri);
    }

    System.out.println("request uri : " + uri);
    System.out.println("FOLDER SHARE PATH : " + FOLDER_SHARE_PATH);
    System.out.println("filepath : " + filepath);

    final File file = new File(filepath);

    HttpEntity entity = null;

    if (file.isDirectory()) {
        entity = new EntityTemplate(new ContentProducer() {
            public void writeTo(final OutputStream outstream) throws IOException {
                OutputStreamWriter writer = new OutputStreamWriter(outstream, "UTF-8");
                String resp = getDirListingHTML(file);

                writer.write(resp);
                writer.flush();
            }
        });

        response.setHeader("Content-Type", contentType);
    } else if (file.exists()) {
        contentType = URLConnection.guessContentTypeFromName(file.getAbsolutePath());

        entity = new FileEntity(file, contentType);

        response.setHeader("Content-Type", contentType);
    } else {
        entity = new EntityTemplate(new ContentProducer() {
            public void writeTo(final OutputStream outstream) throws IOException {
                OutputStreamWriter writer = new OutputStreamWriter(outstream, "UTF-8");
                String resp = "<html>" + "<head><title>ERROR : NOT FOUND</title></head>" + "<body>"
                        + "<center><h1>FILE OR DIRECTORY NOT FOUND !</h1></center>"
                        + "<p>Sorry, file or directory you request not available<br />"
                        + "Contact your administrator<br />" + "</p>" + "</body></html>";

                writer.write(resp);
                writer.flush();
            }
        });
        response.setHeader("Content-Type", "text/html");
    }

    return entity;
}

From source file:com.renren.api.connect.android.Util.java

/**
 * &?URL???key-value?/* ww w.j av a 2  s  .co m*/
 * 
 * @param s
 * @return
 */
public static Bundle decodeUrl(String s) {
    Bundle params = new Bundle();
    if (s != null) {
        params.putString("url", s);
        String array[] = s.split("&");
        for (String parameter : array) {
            String v[] = parameter.split("=");
            if (v.length > 1) {
                params.putString(v[0], URLDecoder.decode(v[1]));
            }
        }
    }
    return params;
}

From source file:org.openmrs.module.sdmxhdintegration.web.controller.KeyFamilyAttributesDialogController.java

@RequestMapping("/module/sdmxhdintegration/keyFamilyAttributesDialog")
public void showForm(ModelMap model, @RequestParam("messageId") Integer messageId,
        @RequestParam("attachmentLevel") String attachmentLevel,
        @RequestParam("keyFamilyId") String keyFamilyId,
        @RequestParam(value = "columnName", required = false) String columnName) throws IOException,
        XMLStreamException, ExternalRefrenceNotFoundException, ValidationException, SchemaValidationException {
    attachmentLevel = URLDecoder.decode(attachmentLevel);
    if (columnName != null) {
        columnName = URLDecoder.decode(columnName);
    }//from www .  ja  v a  2 s  .c o m

    SDMXHDService sdmxhdService = Context.getService(SDMXHDService.class);
    SDMXHDMessage sdmxhdMessage = sdmxhdService.getMessage(messageId);

    // get OMRS DSD
    DataSetDefinitionService dss = Context.getService(DataSetDefinitionService.class);
    SDMXHDCohortIndicatorDataSetDefinition omrsDSD = Utils.getOMRSDataSetDefinition(sdmxhdMessage, keyFamilyId);

    String path = Context.getAdministrationService().getGlobalProperty("sdmxhdintegration.messageUploadDir");
    ZipFile zf = new ZipFile(path + File.separator + sdmxhdMessage.getZipFilename());
    SDMXHDParser parser = new SDMXHDParser();
    org.jembi.sdmxhd.SDMXHDMessage sdmxhdData = parser.parse(zf);
    DSD sdmxhdDSD = sdmxhdData.getDsd();

    Map<String, List<SimpleCode>> codelistValues = new HashMap<String, List<SimpleCode>>();

    // get mandatory attributes
    List<Attribute> mandAttributes = sdmxhdDSD.getAttributes(attachmentLevel, Attribute.MANDATORY);

    // set the mandatory attributes datatypes
    Map<String, String> mandAttrDataTypes = new HashMap<String, String>();

    for (Attribute a : mandAttributes) {
        if (a.getCodelist() != null) {
            // Get codelist from DSD
            CodeList codeList = sdmxhdDSD.getCodeList(a.getCodelist());

            // Extract code values
            List<SimpleCode> codeValues = new ArrayList<SimpleCode>();
            for (Code c : codeList.getCodes()) {
                codeValues.add(new SimpleCode(c.getValue(), c.getDescription().getDefaultStr()));
            }

            // Add to master map
            codelistValues.put(a.getConceptRef(), codeValues);

            mandAttrDataTypes.put(a.getConceptRef(), "Coded");
        } else if (a.getTextFormat().getTextType().equalsIgnoreCase("String")) {
            mandAttrDataTypes.put(a.getConceptRef(), "String");
        } else if (a.getTextFormat().getTextType().equalsIgnoreCase("Date")) {
            mandAttrDataTypes.put(a.getConceptRef(), "Date");
        }
    }

    // get conditional attributes
    List<Attribute> condAttributes = sdmxhdDSD.getAttributes(attachmentLevel, Attribute.CONDITIONAL);

    // set the conditional attributes datatypes
    Map<String, String> condAttrDataTypes = new HashMap<String, String>();
    for (Attribute a : condAttributes) {
        if (a.getCodelist() != null) {
            // Get codelist from DSD
            CodeList codeList = sdmxhdDSD.getCodeList(a.getCodelist());

            // Extract code values
            List<SimpleCode> codeValues = new ArrayList<SimpleCode>();
            for (Code c : codeList.getCodes()) {
                codeValues.add(new SimpleCode(c.getValue(), c.getDescription().getDefaultStr()));
            }

            // Add to master map
            codelistValues.put(a.getConceptRef(), codeValues);

            condAttrDataTypes.put(a.getConceptRef(), "Coded");
        } else if (a.getTextFormat().getTextType().equalsIgnoreCase("String")) {
            condAttrDataTypes.put(a.getConceptRef(), "String");
        } else if (a.getTextFormat().getTextType().equalsIgnoreCase("Date")) {
            condAttrDataTypes.put(a.getConceptRef(), "Date");
        }
    }

    // get attribute values for the attachment level
    Map<String, String> attributeValues = null;
    if (attachmentLevel.equals("Dataset")) {
        attributeValues = omrsDSD.getDataSetAttachedAttributes();
    } else if (attachmentLevel.equals("Series")) {
        attributeValues = omrsDSD.getSeriesAttachedAttributes().get(columnName);
    } else if (attachmentLevel.equals("Observation")) {
        attributeValues = omrsDSD.getObsAttachedAttributes().get(columnName);
    }

    model.addAttribute("mandAttributes", mandAttributes);
    model.addAttribute("condAttributes", condAttributes);

    model.addAttribute("mandAttrDataTypes", mandAttrDataTypes);
    model.addAttribute("condAttrDataTypes", condAttrDataTypes);

    model.addAttribute("attributeValues", attributeValues);
    model.addAttribute("codelistValues", codelistValues);

    model.addAttribute("messageId", messageId);
    model.addAttribute("keyFamilyId", keyFamilyId);
    model.addAttribute("attachmentLevel", attachmentLevel);
}

From source file:com.iStudy.Study.Renren.Util.java

/**
 * &?URL???key-value?// w  ww  .  j  ava 2s .  com
 * 
 * @param s
 * @return
 */
@SuppressWarnings("deprecation")
public static Bundle decodeUrl(String s) {
    Bundle params = new Bundle();
    if (s != null) {
        params.putString("url", s);
        String array[] = s.split("&");
        for (String parameter : array) {
            String v[] = parameter.split("=");
            if (v.length > 1) {
                params.putString(v[0], URLDecoder.decode(v[1]));
            }
        }
    }
    return params;
}