Java Code Examples for java.net.URLDecoder

The following code examples are extracted from open source projects. You can click to vote up the examples that are useful to you.

Example 1

From project 3Dto2DApplet, under directory /src/java/nl/dannyarends/generic/.

Source file: Utils.java

  15 
vote

public static final String toFile(URL url) throws UnsupportedEncodingException {
  if (url.getProtocol().indexOf("file") < 0)   return null;
  String result=url.getPath();
  if (result.charAt(0) == '/' && File.separatorChar == '\\')   result=result.substring(1);
  return URLDecoder.decode(result,ISO_8859_1);
}
 

Example 2

From project action-core, under directory /src/main/java/com/ning/metrics/action/endpoint/.

Source file: HdfsBrowser.java

  15 
vote

@GET @Produces(MediaType.APPLICATION_JSON) @Path("/viewer") @Timed public Response prettyPrintOneLine(@QueryParam("object") final String object) throws IOException {
  final ByteArrayOutputStream out=new ByteArrayOutputStream();
  final ObjectMapper mapper=new ObjectMapper();
  final String objectURIDecoded=URLDecoder.decode(object,"UTF-8");
  final byte[] objectBase64Decoded=Base64.decodeBase64(objectURIDecoded.getBytes());
  mapper.configure(SerializationFeature.INDENT_OUTPUT,true);
  final LinkedHashMap map=mapper.readValue(new String(objectBase64Decoded),LinkedHashMap.class);
  mapper.writeValue(out,map);
  return Response.ok().entity(new String(out.toByteArray())).build();
}
 

Example 3

From project activemq-apollo, under directory /apollo-util/src/main/scala/org/apache/activemq/apollo/util/.

Source file: URISupport.java

  15 
vote

public static Map<String,String> parseQuery(String uri) throws URISyntaxException {
  try {
    Map<String,String> rc=new HashMap<String,String>();
    if (uri != null) {
      String[] parameters=uri.split("&");
      for (int i=0; i < parameters.length; i++) {
        int p=parameters[i].indexOf("=");
        if (p >= 0) {
          String name=URLDecoder.decode(parameters[i].substring(0,p),"UTF-8");
          String value=URLDecoder.decode(parameters[i].substring(p + 1),"UTF-8");
          rc.put(name,value);
        }
 else {
          rc.put(parameters[i],null);
        }
      }
    }
    return rc;
  }
 catch (  UnsupportedEncodingException e) {
    throw (URISyntaxException)new URISyntaxException(e.toString(),"Invalid encoding").initCause(e);
  }
}
 

Example 4

From project activiti-explorer, under directory /src/main/java/org/activiti/explorer/util/.

Source file: UriUtility.java

  15 
vote

private static String decode(final String content,final String encoding){
  try {
    return URLDecoder.decode(content,encoding != null ? encoding : "UTF-8");
  }
 catch (  UnsupportedEncodingException problem) {
    throw new IllegalArgumentException(problem);
  }
}
 

Example 5

From project airlift, under directory /jaxrs/src/main/java/io/airlift/jaxrs/testing/.

Source file: MockUriInfo.java

  15 
vote

private static String urlDecode(String value){
  try {
    return URLDecoder.decode(value,"UTF-8");
  }
 catch (  UnsupportedEncodingException e) {
    throw new IllegalArgumentException(e);
  }
}
 

Example 6

From project ALP, under directory /workspace/alp-reporter/src/main/java/com/lohika/alp/reporter/helpers/.

Source file: Resources.java

  15 
vote

/** 
 * Copy own project resources to outside destination. <p> Works for regular files and JAR packages
 * @param clazz any java class that lives in the same place as the resources you want
 * @param path project resources path. Should end with "/", but not start with one
 * @param destination outside destination
 * @throws IOException
 */
public void copy(Class<?> clazz,String path,File destination) throws IOException {
  URL dirURL=clazz.getClassLoader().getResource(path);
  if (dirURL != null && dirURL.getProtocol().equals("file")) {
    logger.debug("Resources to copy is stored in file system " + dirURL);
    copy(new File(dirURL.getPath()),destination);
    return;
  }
  if (dirURL == null) {
    String me=clazz.getName().replace(".","/") + ".class";
    dirURL=clazz.getClassLoader().getResource(me);
  }
  logger.debug("Resources to copy is stored in jar " + dirURL);
  if (dirURL.getProtocol().equals("jar")) {
    String jarPath=dirURL.getPath().substring(5,dirURL.getPath().indexOf("!"));
    JarFile jar=new JarFile(URLDecoder.decode(jarPath,"UTF-8"));
    copy(jar,path,destination);
    return;
  }
  throw new UnsupportedOperationException("Cannot copy files from URL " + dirURL);
}
 

Example 7

From project amber, under directory /oauth-2.0/common/src/main/java/org/apache/amber/oauth2/common/utils/.

Source file: OAuthUtils.java

  15 
vote

public static String decodePercent(String s){
  try {
    return URLDecoder.decode(s,ENCODING);
  }
 catch (  java.io.UnsupportedEncodingException wow) {
    throw new RuntimeException(wow.getMessage(),wow);
  }
}
 

Example 8

From project AmDroid, under directory /httpclientandroidlib/src/ch/boye/httpclientandroidlib/client/utils/.

Source file: URLEncodedUtils.java

  15 
vote

private static String decode(final String content,final String encoding){
  try {
    return URLDecoder.decode(content,encoding != null ? encoding : HTTP.DEFAULT_CONTENT_CHARSET);
  }
 catch (  UnsupportedEncodingException problem) {
    throw new IllegalArgumentException(problem);
  }
}
 

Example 9

From project android-joedayz, under directory /Proyectos/AndroidTwitter/src/com/mycompany/android/.

Source file: TwitterApp.java

  15 
vote

private String getVerifier(String callbackUrl){
  String verifier="";
  try {
    callbackUrl=callbackUrl.replace("twitterapp","http");
    URL url=new URL(callbackUrl);
    String query=url.getQuery();
    String array[]=query.split("&");
    for (    String parameter : array) {
      String v[]=parameter.split("=");
      if (URLDecoder.decode(v[0]).equals(oauth.signpost.OAuth.OAUTH_VERIFIER)) {
        verifier=URLDecoder.decode(v[1]);
        break;
      }
    }
  }
 catch (  MalformedURLException e) {
    e.printStackTrace();
  }
  return verifier;
}
 

Example 10

From project Android-Simple-Social-Sharing, under directory /SimpleSocialSharing/src/com/nostra13/socialsharing/facebook/extpack/com/facebook/android/.

Source file: Util.java

  15 
vote

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]));
    }
  }
  return params;
}
 

Example 11

From project android-tether, under directory /facebook/src/com/facebook/android/.

Source file: Util.java

  15 
vote

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]));
    }
  }
  return params;
}
 

Example 12

From project android_external_oauth, under directory /core/src/main/java/net/oauth/.

Source file: OAuth.java

  15 
vote

public static String decodePercent(String s){
  try {
    return URLDecoder.decode(s,ENCODING);
  }
 catch (  java.io.UnsupportedEncodingException wow) {
    throw new RuntimeException(wow.getMessage(),wow);
  }
}
 

Example 13

From project android_packages_apps_Gallery2, under directory /src/com/android/gallery3d/data/.

Source file: UriSource.java

  15 
vote

@Override public MediaObject createMediaObject(Path path){
  String segment[]=path.split();
  if (segment.length != 3) {
    throw new RuntimeException("bad path: " + path);
  }
  String uri=URLDecoder.decode(segment[1]);
  String type=URLDecoder.decode(segment[2]);
  return new UriImage(mApplication,path,Uri.parse(uri),type);
}
 

Example 14

From project ANNIS, under directory /annis-gui/src/main/java/annis/gui/.

Source file: MainApp.java

  15 
vote

@Override public void onRequestStart(HttpServletRequest request,HttpServletResponse response){
  String origURI=request.getRequestURI();
  String parameters=origURI.replaceAll(".*?/Cite(/)?","");
  if (!"".equals(parameters) && !origURI.equals(parameters)) {
    try {
      String decoded=URLDecoder.decode(parameters,"UTF-8");
      getWindowSearch().evaluateCitation(decoded);
      try {
        response.sendRedirect(getURL().toString());
      }
 catch (      IOException ex) {
        log.error(null,ex);
      }
    }
 catch (    UnsupportedEncodingException ex) {
      log.error(null,ex);
    }
  }
}
 

Example 15

From project archive-commons, under directory /archive-commons/src/test/java/org/archive/url/.

Source file: URLParserTest.java

  15 
vote

public void testParse() throws URIException, UnsupportedEncodingException {
  System.out.format("O(%s) E(%s)\n","%66",URLDecoder.decode("%66","UTF-8"));
  dumpParse("http://www.archive.org/index.html#foo");
  dumpParse("http://www.archive.org/");
  dumpParse("http://www.archive.org");
  dumpParse("http://www.archive.org?");
  dumpParse("http://www.archive.org:8080/index.html?query#foo");
  dumpParse("http://www.archive.org:8080/index.html?#foo");
  dumpParse("http://www.archive.org:8080?#foo");
  dumpParse("http://b?her.ch:8080?#foo");
  dumpParse("dns:b?her.ch");
}
 

Example 16

From project ardverk-commons, under directory /src/main/java/org/ardverk/utils/.

Source file: StringUtils.java

  15 
vote

public static String decodeURL(String value,String encoding){
  try {
    return URLDecoder.decode(value,encoding);
  }
 catch (  UnsupportedEncodingException err) {
    throw new IllegalArgumentException("UnsupportedEncodingException",err);
  }
}
 

Example 17

From project ardverk-dht, under directory /components/core/src/main/java/org/ardverk/dht/rsrc/.

Source file: KeyUtils.java

  15 
vote

private static String decode(String value){
  try {
    return URLDecoder.decode(value,StringUtils.UTF8);
  }
 catch (  UnsupportedEncodingException err) {
    throw new IllegalArgumentException("UnsupportedEncodingException",err);
  }
}
 

Example 18

From project asterisk-java, under directory /src/main/java/org/asteriskjava/manager/event/.

Source file: AsyncAgiEvent.java

  15 
vote

private List<String> decode(String s){
  final List<String> result=new ArrayList<String>();
  if (s == null) {
    return result;
  }
  try {
    final String decodedString=URLDecoder.decode(s,"ISO-8859-1");
    result.addAll(Arrays.asList(decodedString.split("\n")));
  }
 catch (  UnsupportedEncodingException e) {
    throw new RuntimeException("This JDK does not support ISO-8859-1 encoding",e);
  }
  return result;
}
 

Example 19

From project autopsy, under directory /Core/src/org/sleuthkit/autopsy/ingest/.

Source file: IngestModuleLoader.java

  15 
vote

private Set<URL> getJarPaths(String modulesDir){
  Set<URL> urls=new HashSet<URL>();
  final File modulesDirF=new File(modulesDir);
  FilenameFilter jarFilter=new FilenameFilter(){
    @Override public boolean accept(    File dir,    String name){
      return dir.equals(modulesDirF) && name.endsWith(".jar");
    }
  }
;
  File[] dirJars=modulesDirF.listFiles(jarFilter);
  if (dirJars != null) {
    for (int i=0; i < dirJars.length; ++i) {
      String urlPath="file:/" + dirJars[i].getAbsolutePath();
      try {
        urlPath=URLDecoder.decode(urlPath,ENCODING);
      }
 catch (      UnsupportedEncodingException ex) {
        logger.log(Level.SEVERE,"Could not decode file path. ",ex);
      }
      try {
        urls.add(new URL(urlPath));
        logger.log(Level.INFO,"JAR: " + urlPath);
      }
 catch (      MalformedURLException ex) {
        logger.log(Level.WARNING,"Invalid URL: " + urlPath,ex);
      }
    }
  }
  return urls;
}
 

Example 20

From project avro, under directory /lang/java/mapred/src/main/java/org/apache/avro/mapred/.

Source file: AvroOutputFormat.java

  15 
vote

static <T>void configureDataFileWriter(DataFileWriter<T> writer,JobConf job) throws UnsupportedEncodingException {
  if (FileOutputFormat.getCompressOutput(job)) {
    int level=job.getInt(DEFLATE_LEVEL_KEY,DEFAULT_DEFLATE_LEVEL);
    String codecName=job.get(AvroJob.OUTPUT_CODEC,DEFLATE_CODEC);
    CodecFactory factory=codecName.equals(DEFLATE_CODEC) ? CodecFactory.deflateCodec(level) : CodecFactory.fromString(codecName);
    writer.setCodec(factory);
  }
  writer.setSyncInterval(job.getInt(SYNC_INTERVAL_KEY,DEFAULT_SYNC_INTERVAL));
  for (  Map.Entry<String,String> e : job) {
    if (e.getKey().startsWith(AvroJob.TEXT_PREFIX))     writer.setMeta(e.getKey().substring(AvroJob.TEXT_PREFIX.length()),e.getValue());
    if (e.getKey().startsWith(AvroJob.BINARY_PREFIX))     writer.setMeta(e.getKey().substring(AvroJob.BINARY_PREFIX.length()),URLDecoder.decode(e.getValue(),"ISO-8859-1").getBytes("ISO-8859-1"));
  }
}
 

Example 21

From project avro-utils, under directory /src/main/java/com/tomslabs/grid/avro/.

Source file: TextTypedBytesToAvroOutputFormat.java

  15 
vote

public RecordWriter<TypedBytesWritable,TypedBytesWritable> getRecordWriter(FileSystem ignore,JobConf job,String name,Progressable prog) throws IOException {
  boolean isMapOnly=job.getNumReduceTasks() == 0;
  Schema schema=isMapOnly ? AvroJob.getMapOutputSchema(job) : AvroJob.getOutputSchema(job);
  final DataFileWriter<GenericRecord> writer=new DataFileWriter<GenericRecord>(new GenericDatumWriter<GenericRecord>(schema));
  if (FileOutputFormat.getCompressOutput(job)) {
    int level=job.getInt(DEFLATE_LEVEL_KEY,DEFAULT_DEFLATE_LEVEL);
    writer.setCodec(CodecFactory.deflateCodec(level));
  }
  for (  Map.Entry<String,String> e : job) {
    if (e.getKey().startsWith(AvroJob.TEXT_PREFIX))     writer.setMeta(e.getKey().substring(AvroJob.TEXT_PREFIX.length()),e.getValue());
    if (e.getKey().startsWith(AvroJob.BINARY_PREFIX))     writer.setMeta(e.getKey().substring(AvroJob.BINARY_PREFIX.length()),URLDecoder.decode(e.getValue(),"ISO-8859-1").getBytes("ISO-8859-1"));
  }
  Path path=FileOutputFormat.getTaskOutputPath(job,name + EXT);
  writer.create(schema,path.getFileSystem(job).create(path));
  return new AvroRecordWriter(writer,schema);
}
 

Example 22

From project beanvalidation-tck, under directory /tests/src/main/java/org/hibernate/beanvalidation/tck/util/.

Source file: ArtifactDumper.java

  15 
vote

private static ArrayList<File> findDirectoriesContainingClassesOfPackage(String packageName){
  ArrayList<File> directories=new ArrayList<File>();
  try {
    ClassLoader cld=Thread.currentThread().getContextClassLoader();
    String path=packageName.replace('.','/');
    Enumeration<URL> resources=cld.getResources(path);
    while (resources.hasMoreElements()) {
      directories.add(new File(URLDecoder.decode(resources.nextElement().getPath(),"UTF-8")));
    }
  }
 catch (  Exception e) {
    throw new RuntimeException(e.getMessage(),e);
  }
  return directories;
}
 

Example 23

From project boilerpipe, under directory /boilerpipe-core/src/main/de/l3s/boilerpipe/sax/.

Source file: HTMLDocument.java

  15 
vote

public static String restoreTextEncodedImageTags(String htmlDataString,String encoding){
  Pattern PAT_IMAGE_TAG=Pattern.compile("#img#(.*?)#/img#");
  boolean repeat=true;
  while (repeat) {
    repeat=false;
    Matcher matcher=PAT_IMAGE_TAG.matcher(htmlDataString);
    if (matcher.find()) {
      repeat=true;
      String imageAttributes=matcher.group(1);
      try {
        imageAttributes=URLDecoder.decode(imageAttributes,encoding);
      }
 catch (      UnsupportedEncodingException e) {
        e.printStackTrace();
        imageAttributes=URLDecoder.decode(imageAttributes);
      }
      String decodedImageTag="<img " + imageAttributes + ">";
      htmlDataString=matcher.replaceFirst(decodedImageTag);
    }
  }
  return htmlDataString;
}
 

Example 24

From project bpm-console, under directory /server/war/src/main/java/org/jboss/bpm/console/server/.

Source file: ProcessMgmtFacade.java

  15 
vote

@POST @Path("tokens/{id}/transition") @Produces("application/json") public Response signalExecution(@PathParam("id") String id,@QueryParam("signal") String signalName){
  try {
    id=URLDecoder.decode(id,"UTF-8");
  }
 catch (  UnsupportedEncodingException e) {
    e.printStackTrace();
  }
  log.debug("Signal token " + id + " -> "+ signalName);
  if ("default transition".equals(signalName))   signalName=null;
  getProcessManagement().signalExecution(id,signalName);
  return Response.ok().type("application/json").build();
}
 

Example 25

From project brix-cms, under directory /brix-core/src/main/java/org/brixcms/web/.

Source file: BrixRequestCycleProcessor.java

  15 
vote

private static String extractWorkspaceFromReferer(String refererURL){
  int i=refererURL.indexOf('?');
  if (i != -1 && i != refererURL.length() - 1) {
    String param=refererURL.substring(i + 1);
    String params[]=Strings.split(param,'&');
    for (    String s : params) {
      try {
        s=URLDecoder.decode(s,"utf-8");
      }
 catch (      UnsupportedEncodingException e) {
        throw new RuntimeException(e);
      }
      if (s.startsWith(WORKSPACE_PARAM + "=")) {
        String value=s.substring(WORKSPACE_PARAM.length() + 1);
        if (value.length() > 0) {
          return value;
        }
      }
    }
  }
  return null;
}
 

Example 26

From project brut.apktool, under directory /apktool-lib/src/test/java/brut/androlib/.

Source file: TestUtils.java

  15 
vote

public static void copyResourceDir(Class class_,String dirPath,Directory out) throws BrutException {
  if (class_ == null) {
    class_=Class.class;
  }
  URL dirURL=class_.getClassLoader().getResource(dirPath);
  if (dirURL != null && dirURL.getProtocol().equals("file")) {
    DirUtil.copyToDir(new FileDirectory(dirURL.getFile()),out);
    return;
  }
  if (dirURL == null) {
    String className=class_.getName().replace(".","/") + ".class";
    dirURL=class_.getClassLoader().getResource(className);
  }
  if (dirURL.getProtocol().equals("jar")) {
    String jarPath;
    try {
      jarPath=URLDecoder.decode(dirURL.getPath().substring(5,dirURL.getPath().indexOf("!")),"UTF-8");
    }
 catch (    UnsupportedEncodingException ex) {
      throw new BrutException(ex);
    }
    DirUtil.copyToDir(new FileDirectory(jarPath),out);
  }
}
 

Example 27

From project camel-beanstalk, under directory /src/main/java/com/osinka/camel/beanstalk/.

Source file: ConnectionSettings.java

  15 
vote

public ConnectionSettings(final String host,final int port,final String tube){
  this.host=host;
  this.port=port;
  final Scanner scanner=new Scanner(tube);
  scanner.useDelimiter("\\+");
  final ArrayList<String> buffer=new ArrayList<String>();
  while (scanner.hasNext()) {
    final String tubeRaw=scanner.next();
    try {
      buffer.add(URLDecoder.decode(tubeRaw,"UTF-8"));
    }
 catch (    UnsupportedEncodingException e) {
      buffer.add(tubeRaw);
    }
  }
  this.tubes=buffer.toArray(new String[0]);
  scanner.close();
}
 

Example 28

From project Carolina-Digital-Repository, under directory /admin/src/main/java/edu/unc/lib/dl/ui/.

Source file: AbstractItemListingController.java

  15 
vote

private void getBreadcrumbs(HttpServletRequest request,DeleteObjectDAO dao){
  dao.getBreadcrumbs().clear();
  IrUrlInfo irUrlInfo=new IrUrlInfo();
  UtilityMethods.populateIrUrlInfo(irUrlInfo,request);
  PID pathPid=null;
  try {
    pathPid=tripleStoreQueryService.fetchByRepositoryPath(URLDecoder.decode(irUrlInfo.getFedoraUrl(),Constants.UTF_8));
    if (pathPid == null) {
      logger.debug("getBreadcrumbs pathPid is NULL");
    }
 else {
      logger.debug("getBreadcrumbs pathPid is " + pathPid.getPid() + " "+ pathPid.getURI());
    }
  }
 catch (  UnsupportedEncodingException e) {
    e.printStackTrace();
  }
  List<PathInfo> pathList=tripleStoreQueryService.lookupRepositoryPathInfo(pathPid);
  PathInfoResponse pathInfoResponse=uiWebService.getBreadcrumbs(pathPid.getPid(),"test");
  if ((pathInfoResponse.getPaths().size() - 1) > 0) {
    for (int i=1; i < pathInfoResponse.getPaths().size(); i++) {
      PathInfoDao pidao=new PathInfoDao();
      pidao.setLabel(pathInfoResponse.getPaths().get(i).getLabel());
      pidao.setPid(pathInfoResponse.getPaths().get(i).getPid());
      pidao.setPath(deleteObjectUrl + pathInfoResponse.getPaths().get(i).getPath());
      dao.getBreadcrumbs().add(pidao);
    }
  }
}
 

Example 29

From project Catroid-maven-playground, under directory /src/main/java/at/tugraz/ist/catroid/ui/.

Source file: MainMenuActivity.java

  15 
vote

private String getProjectName(String zipUrl){
  int projectNameIndex=zipUrl.lastIndexOf(PROJECTNAME_TAG) + PROJECTNAME_TAG.length();
  String projectName=zipUrl.substring(projectNameIndex);
  projectName=URLDecoder.decode(projectName);
  return projectName;
}
 

Example 30

From project caustic, under directory /implementation/javanet/src/net/caustic/util/.

Source file: JavaNetDecoder.java

  15 
vote

public String decode(String stringToDecode){
  try {
    return URLDecoder.decode(stringToDecode,encoding);
  }
 catch (  UnsupportedEncodingException e) {
    throw new RuntimeException("Encoding should have been supported.");
  }
}
 

Example 31

From project chililog-server, under directory /src/main/java/org/chililog/server/workbench/.

Source file: StaticFileRequestHandler.java

  15 
vote

/** 
 * Converts the request URI to a file path
 * @param uri
 * @return
 * @throws UnsupportedEncodingException
 */
private String convertUriToPhysicalFilePath(String uri) throws UnsupportedEncodingException {
  try {
    uri=URLDecoder.decode(uri,"UTF-8");
  }
 catch (  UnsupportedEncodingException e) {
    uri=URLDecoder.decode(uri,"ISO-8859-1");
  }
  int idx=uri.indexOf('/',1);
  if (idx < 0) {
    return null;
  }
  uri=uri.substring(idx);
  if (StringUtils.isBlank(uri)) {
    return null;
  }
  idx=uri.indexOf('?');
  if (idx > 0) {
    uri=uri.substring(0,idx);
  }
  uri=uri.replace('/',File.separatorChar);
  if (uri.contains(File.separator + ".") || uri.contains("." + File.separator) || uri.startsWith(".")|| uri.endsWith(".")) {
    return null;
  }
  return AppProperties.getInstance().getWorkbenchStaticFilesDirectory() + uri;
}
 

Example 32

From project ChkBugReport, under directory /src/com/sonyericsson/chkbugreport/.

Source file: Gui.java

  15 
vote

@Override public boolean importData(TransferSupport support){
  DataFlavor selDf=null;
  for (  DataFlavor df : support.getDataFlavors()) {
    if (df.isMimeTypeEqual("text/uri-list")) {
      if ("java.lang.String".equals(df.getParameter("class"))) {
        selDf=df;
        break;
      }
    }
  }
  if (selDf != null) {
    String path;
    try {
      path=(String)support.getTransferable().getTransferData(selDf);
      URL url=new URL(path);
      if (url.getProtocol().equals("file")) {
        loadFile(URLDecoder.decode(url.getPath(),"UTF-8"));
        return true;
      }
    }
 catch (    Exception e) {
      e.printStackTrace();
    }
  }
  return false;
}
 

Example 33

From project CineShowTime-Android, under directory /Libraries/CineShowTime/src/com/binomed/showtime/android/layout/view/.

Source file: PageProjectionView.java

  15 
vote

/** 
 * @param movie
 * @throws Exception
 */
public void fillViews(MovieBean movie) throws Exception {
  SharedPreferences prefs=PreferenceManager.getDefaultSharedPreferences(getContext());
  TheaterBean theater=model.getTheater();
  if (theater != null) {
    theaterTitle.setText(theater.getTheaterName());
    LocalisationBean place=theater.getPlace();
    if (place != null) {
      try {
        theaterAddress.setText(URLDecoder.decode(place.getSearchQuery(),CineShowTimeEncodingUtil.getEncoding()));
      }
 catch (      Exception e) {
        Log.e(TAG,"error decoding address",e);
      }
    }
  }
  List<ProjectionBean> projectionList=null;
  distanceTime=prefs.getBoolean(this.getResources().getString(R.string.preference_loc_key_time_direction),false);
  Long distanceTimeLong=null;
  if (theater != null) {
    projectionList=theater.getMovieMap().get(movie.getId());
    if (distanceTime && (theater.getPlace() != null)) {
      distanceTimeLong=theater.getPlace().getDistanceTime();
    }
  }
  projectionAdapter=new ProjectionListAdapter(getContext(),movie,projectionList,CineShowtimeDateNumberUtil.getMinTime(projectionList,distanceTimeLong),this);
  movieProjectionTimeList.setAdapter(projectionAdapter);
  prepareQuickActionBar();
}
 

Example 34

From project CloudReports, under directory /src/main/java/cloudreports/utils/.

Source file: FileIO.java

  15 
vote

/** 
 * List directory contents for a resource folder. Not recursive. This is basically a brute-force implementation. Works for regular files and also JARs.
 * @author Greg Briggs
 * @param clazz Any java class that lives in the same place as the resources you want.
 * @param path Should end with "/", but not start with one.
 * @return Just the name of each member item, not the full paths.
 * @throws URISyntaxException 
 * @throws IOException 
 */
public static String[] getResourceListing(Class clazz,String path) throws URISyntaxException, IOException {
  URL dirURL=clazz.getClassLoader().getResource(path);
  if (dirURL != null && dirURL.getProtocol().equals("file")) {
    return new File(dirURL.toURI()).list();
  }
  if (dirURL == null) {
    String me=clazz.getName().replace(".","/") + ".class";
    dirURL=clazz.getClassLoader().getResource(me);
  }
  if (dirURL.getProtocol().equals("jar")) {
    String jarPath=dirURL.getPath().substring(5,dirURL.getPath().indexOf("!"));
    JarFile jar=new JarFile(URLDecoder.decode(jarPath,"UTF-8"));
    Enumeration<JarEntry> entries=jar.entries();
    Set<String> result=new HashSet<String>();
    while (entries.hasMoreElements()) {
      String name=entries.nextElement().getName();
      if (name.startsWith(path)) {
        String entry=name.substring(path.length());
        int checkSubdir=entry.indexOf("/");
        if (checkSubdir >= 0) {
          entry=entry.substring(0,checkSubdir);
        }
        result.add(entry);
      }
    }
    return result.toArray(new String[result.size()]);
  }
  throw new UnsupportedOperationException("Cannot list files for URL " + dirURL);
}
 

Example 35

From project Coffee-Framework, under directory /coffeeframework-core/src/main/java/coffee/resources/.

Source file: ClassPathResourceLoader.java

  15 
vote

public List<String> retrieveAvailableResources() throws IOException {
  ArrayList<String> list=new ArrayList<String>();
  ClassLoader classLoader=getClassLoader();
  Enumeration<URL> resources=classLoader.getResources(DEFAULT_RESOURCE_PATH);
  while (resources.hasMoreElements()) {
    URL resource=resources.nextElement();
    String fileName=resource.getFile();
    String fileNameDecoded=URLDecoder.decode(fileName,"UTF-8");
    File file=new File(fileNameDecoded);
    if (!file.exists())     continue;
    list.addAll(retrieveAvailableResources(file,DEFAULT_RESOURCE_PATH));
  }
  return list;
}
 

Example 36

From project cogroo4, under directory /lang/pt_br/cogroo-addon/src/org/cogroo/addon/addon/conf/.

Source file: AddOnConfiguration.java

  15 
vote

/** 
 * @param url
 * @return the expanded URL
 */
protected String expandURL(String url){
  try {
    url=url.substring(20);
    String str=URLDecoder.decode(url,"utf-8");
    Object obj=context.getValueByName("/singletons/com.sun.star.util.theMacroExpander");
    XMacroExpander expander=(XMacroExpander)UnoRuntime.queryInterface(XMacroExpander.class,obj);
    String res=expander.expandMacros(str);
    return res;
  }
 catch (  Exception e) {
    e.printStackTrace();
  }
  return "";
}
 

Example 37

From project collector, under directory /src/main/java/com/ning/metrics/collector/events/parsing/.

Source file: UrlDecodingTokenizer.java

  15 
vote

public Token next() throws EventParsingException {
  try {
    final Token baseToken=baseTokenizer.next();
    if (baseToken.isEmpty()) {
      return baseToken;
    }
 else {
      final String value=URLDecoder.decode(baseToken.getValue(),"UTF-8");
      return new Token(value,baseToken.getType());
    }
  }
 catch (  UnsupportedEncodingException e) {
    throw new EventParsingException("error URL decoding token",e);
  }
}
 

Example 38

From project com.idega.content, under directory /src/java/com/idega/content/themes/helpers/business/impl/.

Source file: ThemesHelperImpl.java

  15 
vote

public String decode(String value,boolean fullyDecode){
  if (value == null) {
    return null;
  }
  while (value.indexOf(ThemesConstants.SPACE_ENCODED) != -1) {
    value=value.replace(ThemesConstants.SPACE_ENCODED,ThemesConstants.PLUS);
  }
  if (fullyDecode) {
    try {
      value=URLDecoder.decode(value,CoreConstants.ENCODING_UTF8);
    }
 catch (    UnsupportedEncodingException e) {
      e.printStackTrace();
      return value;
    }
  }
  return value;
}
 

Example 39

From project CommitCoin, under directory /src/com/google/bitcoin/uri/.

Source file: BitcoinURI.java

  15 
vote

/** 
 * @param params The network parameters or null
 * @param nameValuePairTokens The tokens representing the name value pairs (assumed to beseparated by '=' e.g. 'amount=0.2')
 */
private void parseParameters(NetworkParameters params,String addressToken,String[] nameValuePairTokens){
  try {
    Address address=new Address(params,addressToken);
    putWithValidation(FIELD_ADDRESS,address);
  }
 catch (  final AddressFormatException e) {
    throw new BitcoinURIParseException("Bad address",e);
  }
  for (int i=0; i < nameValuePairTokens.length; i++) {
    String[] tokens=nameValuePairTokens[i].split("=");
    if (tokens.length != 2 || "".equals(tokens[0])) {
      throw new BitcoinURIParseException("Malformed Bitcoin URI - cannot parse name value pair '" + nameValuePairTokens[i] + "'");
    }
    String nameToken=tokens[0].toLowerCase();
    String valueToken=tokens[1];
    if (FIELD_AMOUNT.equals(nameToken)) {
      try {
        BigInteger amount=Utils.toNanoCoins(valueToken);
        putWithValidation(FIELD_AMOUNT,amount);
      }
 catch (      NumberFormatException e) {
        throw new OptionalFieldValidationException("'" + valueToken + "' value is not a valid amount",e);
      }
    }
 else {
      if (nameToken.startsWith("req-")) {
        throw new RequiredFieldValidationException("'" + nameToken + "' is required but not known, this URI is not valid");
      }
 else {
        try {
          putWithValidation(nameToken,URLDecoder.decode(valueToken,"UTF-8"));
        }
 catch (        UnsupportedEncodingException e) {
          throw new RuntimeException(e);
        }
      }
    }
  }
}
 

Example 40

From project convertcsv, under directory /ConvertCSV/src/org/openintents/convertcsv/common/.

Source file: ConvertCsvBaseActivity.java

  15 
vote

@Override protected void onActivityResult(int requestCode,int resultCode,Intent data){
  super.onActivityResult(requestCode,resultCode,data);
  Log.i(TAG,"onActivityResult");
switch (requestCode) {
case REQUEST_CODE_PICK_FILE:
    if (resultCode == RESULT_OK && data != null) {
      String filename=data.getDataString();
      try {
        filename=URLDecoder.decode(filename,"UTF-8");
      }
 catch (      UnsupportedEncodingException e) {
        e.printStackTrace();
      }
      if (filename != null) {
        if (filename.startsWith("file://")) {
          filename=filename.substring(7);
        }
        mEditText.setText(filename);
      }
    }
  break;
}
}
 

Example 41

From project core_4, under directory /impl/src/main/java/org/richfaces/util/.

Source file: Util.java

  15 
vote

public static Map<String,String> parseResourceParameters(String resourceName){
  Map<String,String> params=new HashMap<String,String>();
  Matcher matcher=RESOURCE_PARAMS.matcher(resourceName);
  if (matcher.find()) {
    String paramsString=matcher.group(1);
    String[] paramsSplit=RESOURCE_PARAMS_SPLIT_PATTERN.split(paramsString);
    try {
      for (      String param : paramsSplit) {
        String[] pair=param.split(EQUALS_SIGN);
        String key=URLDecoder.decode(pair[0],"UTF-8").trim();
        String value=URLDecoder.decode(pair[1],"UTF-8").trim();
        if (key != null && value != null && key.trim().length() > 0 && value.trim().length() > 0) {
          params.put(key,value);
        }
      }
    }
 catch (    UnsupportedEncodingException e) {
      RESOURCE_LOGGER.debug("Cannot parse resource parameters");
    }
  }
  return params;
}
 

Example 42

From project cp-common-utils, under directory /src/com/clarkparsia/common/base/.

Source file: Strings2.java

  15 
vote

/** 
 * URL decode the given string using the given Charset
 * @param theString the string to decode
 * @param theCharset the charset to decode the string using
 * @return the string decoded with the given charset
 */
public static String urlDecode(String theString,Charset theCharset){
  try {
    return URLDecoder.decode(theString,theCharset.displayName());
  }
 catch (  UnsupportedEncodingException e) {
    return null;
  }
}
 

Example 43

From project crawler4j, under directory /src/main/java/edu/uci/ics/crawler4j/url/.

Source file: URLCanonicalizer.java

  15 
vote

/** 
 * Percent-encode values according the RFC 3986. The built-in Java URLEncoder does not encode according to the RFC, so we make the extra replacements.
 * @param string Decoded string.
 * @return Encoded string per RFC 3986.
 */
private static String percentEncodeRfc3986(String string){
  try {
    string=string.replace("+","%2B");
    string=URLDecoder.decode(string,"UTF-8");
    string=URLEncoder.encode(string,"UTF-8");
    return string.replace("+","%20").replace("*","%2A").replace("%7E","~");
  }
 catch (  Exception e) {
    return string;
  }
}
 

Example 44

From project crunch, under directory /crunch/src/main/java/org/apache/crunch/util/.

Source file: DistCache.java

  15 
vote

/** 
 * Finds the path to a jar that contains the class provided, if any. There is no guarantee that the jar returned will be the first on the classpath to contain the file. This method is basically lifted out of Hadoop's  {@link org.apache.hadoop.mapred.JobConf} class.
 * @param jarClass The class the jar file should contain.
 * @return The path to a jar file that contains the class, or <code>null</code> if no such jarexists.
 * @throws IOException If there is a problem searching for the jar file.
 */
public static String findContainingJar(Class jarClass) throws IOException {
  ClassLoader loader=jarClass.getClassLoader();
  String classFile=jarClass.getName().replaceAll("\\.","/") + ".class";
  for (Enumeration itr=loader.getResources(classFile); itr.hasMoreElements(); ) {
    URL url=(URL)itr.nextElement();
    if ("jar".equals(url.getProtocol())) {
      String toReturn=url.getPath();
      if (toReturn.startsWith("file:")) {
        toReturn=toReturn.substring("file:".length());
      }
      toReturn=toReturn.replaceAll("\\+","%2B");
      toReturn=URLDecoder.decode(toReturn,"UTF-8");
      return toReturn.replaceAll("!.*$","");
    }
  }
  return null;
}
 

Example 45

From project css-x-fire, under directory /src/com/github/cssxfire/webserver/.

Source file: HttpRequest.java

  15 
vote

private static Map<String,String> getQueryMap(String query) throws MalformedQueryException {
  Map<String,String> map=new HashMap<String,String>();
  try {
    int i=query.indexOf('?');
    if (i == -1) {
      return map;
    }
    query=query.substring(i + 1);
    String[] params=query.split("&");
    for (    String param : params) {
      int ix=param.indexOf('=');
      String name=param.substring(0,ix);
      name=URLDecoder.decode(name,"utf-8");
      String value=param.substring(ix + 1);
      value=URLDecoder.decode(value,"utf-8");
      map.put(name,value);
    }
    return map;
  }
 catch (  Exception e) {
    throw new MalformedQueryException(query);
  }
}
 

Example 46

From project curator, under directory /curator-client/src/main/java/com/netflix/curator/ensemble/exhibitor/.

Source file: ExhibitorEnsembleProvider.java

  15 
vote

private static Map<String,String> decodeExhibitorList(String str) throws UnsupportedEncodingException {
  Map<String,String> values=Maps.newHashMap();
  for (  String spec : str.split("&")) {
    String[] parts=spec.split("=");
    if (parts.length == 2) {
      values.put(parts[0],URLDecoder.decode(parts[1],"UTF-8"));
    }
  }
  return values;
}
 

Example 47

From project danbooru-gallery-android, under directory /src/tw/idv/palatis/danboorugallery/.

Source file: ViewImageActivity.java

  15 
vote

public File getOutputFile(URL url){
  File downloaddir;
  if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED))   downloaddir=new File(android.os.Environment.getExternalStorageDirectory(),D.SAVEDIR);
 else   return null;
  downloaddir=new File(downloaddir,host.name);
  if (!downloaddir.exists())   downloaddir.mkdirs();
  String filename=url.getPath();
  filename=filename.substring(filename.lastIndexOf('/'));
  if (filename == "")   filename=URLEncoder.encode(url.toExternalForm());
  return new File(downloaddir,URLDecoder.decode(filename));
}
 

Example 48

From project Danroth, under directory /src/main/java/org/yaml/snakeyaml/util/.

Source file: UriEncoder.java

  15 
vote

public static String decode(String buff){
  try {
    return URLDecoder.decode(buff,"UTF-8");
  }
 catch (  UnsupportedEncodingException e) {
    throw new YAMLException(e);
  }
}
 

Example 49

From project DiscogsForAndroid, under directory /src/com/discogs/activities/.

Source file: ImageActivity.java

  15 
vote

@Override protected void onCreate(Bundle savedInstanceState){
  super.onCreate(savedInstanceState);
  setContentView(LayoutInflater.from(this).inflate(R.layout.layout_progressbar,null));
  Bundle extras=getIntent().getExtras();
  final String title=(String)extras.get("title");
  final String url=(String)extras.get("url");
  this.mTitle=URLDecoder.decode(title);
  setTitle(mTitle);
  Thread thread=new Thread(new Runnable(){
    @Override public void run(){
      HTTPRequestHelper hTTPRequestHelper=new HTTPRequestHelper(new ResponseHandler<String>(){
        @Override public String handleResponse(        HttpResponse response) throws ClientProtocolException, IOException {
          HttpEntity entity=response.getEntity();
          InputStream inputStream=entity.getContent();
          bitmap=BitmapFactory.decodeStream(inputStream);
          handler.post(new Runnable(){
            @Override public void run(){
              TouchImageView imageView=new TouchImageView(ImageActivity.this);
              imageView.setImageBitmap(bitmap);
              setContentView(imageView);
              getActionBarHelper().setRefreshActionItemState(false);
              loading=false;
            }
          }
);
          return null;
        }
      }
);
      hTTPRequestHelper.performGet(url);
    }
  }
);
  thread.start();
}
 

Example 50

From project dmix, under directory /LastFM-java/src/de/umass/util/.

Source file: StringUtilities.java

  15 
vote

/** 
 * Decodes an URL encoded String <code>s</code> using the UTF-8 character encoding.
 * @param s an encoded String
 * @return the decoded String
 */
public static String decode(String s){
  if (s == null)   return null;
  try {
    return URLDecoder.decode(s,"UTF-8");
  }
 catch (  UnsupportedEncodingException e) {
  }
  return null;
}
 

Example 51

From project dolphin, under directory /com.sysdeo.eclipse.tomcat/src/com/sysdeo/eclipse/tomcat/editors/.

Source file: ListFieldEditor.java

  15 
vote

/** 
 * Splits the given string into a list of strings. This method is the converse of <code>createList</code>. <p> Subclasses must implement this method. </p>
 * @param stringList the string
 * @return an array of <code>String</code>
 * @see #createList
 */
protected String[] parseString(String stringList){
  StringTokenizer st=new StringTokenizer(stringList,TomcatPluginResources.PREF_PAGE_LIST_SEPARATOR);
  ArrayList v=new ArrayList();
  while (st.hasMoreTokens()) {
    v.add(URLDecoder.decode(st.nextToken()));
  }
  return (String[])v.toArray(new String[v.size()]);
}
 

Example 52

From project dragon, under directory /hadoop-dragon-core/src/main/java/org/apache/hadoop/realtime/.

Source file: DragonJob.java

  15 
vote

/** 
 * Find a jar that contains a class of the same name, if any. It will return a jar file, even if that is not the first thing on the class path that has a class with the same name.
 * @param my_class the class to find.
 * @return a jar file that contains the class
 */
private static String findContainingJar(Class<?> my_class){
  ClassLoader loader=my_class.getClassLoader();
  String class_file=my_class.getName().replaceAll("\\.","/") + ".class";
  try {
    for (Enumeration itr=loader.getResources(class_file); itr.hasMoreElements(); ) {
      URL url=(URL)itr.nextElement();
      if ("jar".equals(url.getProtocol())) {
        String toReturn=url.getPath();
        if (toReturn.startsWith("file:")) {
          toReturn=toReturn.substring("file:".length());
        }
        toReturn=toReturn.replaceAll("\\+","%2B");
        toReturn=URLDecoder.decode(toReturn,"UTF-8");
        return toReturn.replaceAll("!.*$","");
      }
    }
  }
 catch (  IOException e) {
    throw new RuntimeException(e);
  }
  return null;
}
 

Example 53

From project droidkit, under directory /src/org/droidkit/net/.

Source file: HttpUtils.java

  15 
vote

public static Bundle decodeParams(String query){
  Bundle params=new Bundle();
  if (query != null) {
    String[] parts=query.split("&");
    for (    String param : parts) {
      String[] item=param.split("=");
      params.putString(URLDecoder.decode(item[0]),URLDecoder.decode(item[1]));
    }
  }
  return params;
}
 

Example 54

From project droolsjbpm-tools, under directory /drools-eclipse/org.guvnor.tools/src/org/guvnor/tools/utils/webdav/.

Source file: StreamProcessingUtils.java

  15 
vote

public static Map<String,ResourceProperties> parseListing(String base,InputStream is) throws Exception {
  Map<String,ResourceProperties> res=new HashMap<String,ResourceProperties>();
  DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
  factory.setNamespaceAware(true);
  DocumentBuilder parser=factory.newDocumentBuilder();
  Document doc=parser.parse(is);
  NodeList nl=doc.getElementsByTagNameNS(DAV_NS,"response");
  for (int i=0; i < nl.getLength(); i++) {
    Element oneElem=(Element)nl.item(i);
    NodeList resName=oneElem.getElementsByTagNameNS(DAV_NS,"href");
    assert(resName.getLength() == 1);
    String bareName=extractOverlap(base,URLDecoder.decode(resName.item(0).getTextContent(),"UTF-8"));
    if (bareName.trim().length() > 0) {
      ResourceProperties props=new ResourceProperties();
      NodeList propList=oneElem.getElementsByTagNameNS(DAV_NS,"resourcetype");
      assert(propList.getLength() == 1);
      NodeList resTypeList=((Element)propList.item(0)).getElementsByTagNameNS(DAV_NS,"collection");
      assert(resTypeList.getLength() < 2);
      if (resTypeList.getLength() == 1) {
        props.setDirectory(true);
      }
      propList=oneElem.getElementsByTagNameNS(DAV_NS,"creationdate");
      if (propList.getLength() > 0) {
        props.setCreationDate(propList.item(0).getTextContent());
      }
      propList=oneElem.getElementsByTagNameNS(DAV_NS,"getlastmodified");
      if (propList.getLength() > 0) {
        props.setLastModifiedDate(propList.item(0).getTextContent());
      }
      String normBase=base.trim().endsWith("/") ? base.trim() : base.trim() + "/";
      props.setBase(normBase);
      res.put(bareName,props);
    }
  }
  return res;
}
 

Example 55

From project dungbeetle, under directory /src/com/facebook/android/.

Source file: Util.java

  15 
vote

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]));
    }
  }
  return params;
}
 

Example 56

From project dynjs, under directory /src/main/java/org/dynjs/runtime/builtins/.

Source file: DecodeUri.java

  15 
vote

@Override public Object call(ExecutionContext context,Object self,Object... args){
  String uri=Types.toString(context,args[0]);
  try {
    return URLDecoder.decode(uri,"UTF-8");
  }
 catch (  UnsupportedEncodingException e) {
    throw new ThrowException(context,context.createUriError("uable to decode uri '" + uri + "'"));
  }
}
 

Example 57

From project eclim, under directory /org.eclim.core/java/org/eclim/plugin/core/util/.

Source file: XmlUtils.java

  15 
vote

/** 
 * Adds the supplied SAXException as an Error.
 * @param ex The SAXException.
 */
private void addError(SAXParseException ex,boolean warning){
  String location=ex.getSystemId();
  if (location != null) {
    if (location.startsWith("file://")) {
      location=location.substring("file://".length());
    }
 else     if (location.startsWith("file:")) {
      location=location.substring("file:".length());
    }
  }
  if (location != null && WIN_BUG.matcher(location).matches()) {
    location=location.substring(1);
  }
  if (location == null) {
    location=filename;
  }
  try {
    errors.add(new Error(ex.getMessage(),URLDecoder.decode(location,"utf-8"),ex.getLineNumber(),ex.getColumnNumber(),warning));
  }
 catch (  Exception e) {
    throw new RuntimeException(e);
  }
}
 

Example 58

From project ecoadapters, under directory /ecoadapters/src/main/java/com/inadco/ecoadapters/.

Source file: EcoUtil.java

  15 
vote

private static Properties parseQuery(String query) throws IOException {
  Properties props=new Properties();
  for (StringTokenizer st=new StringTokenizer(query,"&"); st.hasMoreTokens(); ) {
    String paramStr=st.nextToken().trim();
    if (paramStr.length() == 0)     continue;
    int pos=paramStr.indexOf('=');
    String paramName=pos >= 0 ? paramStr.substring(0,pos) : paramStr;
    paramName=URLDecoder.decode(paramName,NET_ENCODING);
    String paramValue=pos >= 0 ? URLDecoder.decode(paramStr.substring(pos + 1),NET_ENCODING) : null;
    props.put(paramName,paramValue);
  }
  return props;
}
 

Example 59

From project edg-examples, under directory /carmart-single/src/main/java/com/redhat/datagrid/carmart/session/.

Source file: CarManager.java

  15 
vote

public static String decode(String key){
  try {
    return URLDecoder.decode(key,"UTF-8");
  }
 catch (  UnsupportedEncodingException e) {
    throw new RuntimeException(e);
  }
}
 

Example 60

From project egit-github, under directory /org.eclipse.egit.github.core/src/org/eclipse/egit/github/core/util/.

Source file: UrlUtils.java

  15 
vote

/** 
 * URL-decode value using 'ISO-8859-1' character set
 * @param value
 * @return encoded value
 */
public static String decode(final String value){
  try {
    return URLDecoder.decode(value,CHARSET_ISO_8859_1);
  }
 catch (  UnsupportedEncodingException e) {
    throw new IllegalArgumentException(e);
  }
}
 

Example 61

From project ElasticSearchExample, under directory /src/main/java/de/jetwick/ese/util/.

Source file: Helper.java

  15 
vote

public static String urlDecode(String str){
  try {
    return URLDecoder.decode(str,UTF8);
  }
 catch (  UnsupportedEncodingException ex) {
    return str;
  }
}
 

Example 62

From project entando-core-engine, under directory /src/main/java/com/agiletec/apsadmin/system/dispatcher/.

Source file: Struts2ServletDispatcher.java

  15 
vote

/** 
 * Look for a static resource in the classpath.
 * @param name The resource name
 * @param packagePrefix The package prefix to use to locate the resource
 * @return The inputstream of the resource
 * @throws IOException If there is a problem locating the resource
 */
protected InputStream findInputStream(String name,String packagePrefix) throws IOException {
  String resourcePath;
  if (packagePrefix.endsWith("/") && name.startsWith("/")) {
    resourcePath=packagePrefix + name.substring(1);
  }
 else {
    resourcePath=packagePrefix + name;
  }
  resourcePath=URLDecoder.decode(resourcePath,encoding);
  return ClassLoaderUtil.getResourceAsStream(resourcePath,getClass());
}
 

Example 63

From project etherpad, under directory /infrastructure/net.appjet.common/util/.

Source file: HttpServletRequestFactory.java

  15 
vote

private String decodeUTF8(String s){
  try {
    return URLDecoder.decode(s,"UTF-8");
  }
 catch (  java.io.UnsupportedEncodingException e) {
    System.err.println("Unsupported character encoding! UTF-8");
    return s;
  }
}
 

Example 64

From project eucalyptus, under directory /clc/modules/axis2-transport/src/edu/ucsb/eucalyptus/transport/query/.

Source file: WalrusQuerySecurityHandler.java

  15 
vote

private UserInfo getUserInfo(String accessKeyID,String signature,String data,boolean decode) throws QuerySecurityException {
  signature=signature.replaceAll("=","");
  String queryKey=findQueryKey(accessKeyID);
  String authSig=checkSignature(queryKey,data);
  if (decode) {
    try {
      authSig=URLDecoder.decode(authSig,"UTF-8");
    }
 catch (    Exception ex) {
      throw new QuerySecurityException(ex.getMessage());
    }
  }
  if (!authSig.equals(signature))   throw new QuerySecurityException("User authentication failed. Could not verify signature");
  return findUserId(accessKeyID);
}
 

Example 65

From project facebook-android-sdk, under directory /facebook/src/com/facebook/android/.

Source file: Util.java

  15 
vote

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("=");
      if (v.length == 2) {
        params.putString(URLDecoder.decode(v[0]),URLDecoder.decode(v[1]));
      }
    }
  }
  return params;
}
 

Example 66

From project fanfoudroid, under directory /src/com/ch_linghu/fanfoudroid/fanfou/.

Source file: WeiboResponse.java

  15 
vote

protected static String getString(String name,JSONObject json,boolean decode){
  String returnValue=null;
  try {
    returnValue=json.getString(name);
    if (decode) {
      try {
        returnValue=URLDecoder.decode(returnValue,"UTF-8");
      }
 catch (      UnsupportedEncodingException ignore) {
      }
    }
  }
 catch (  JSONException ignore) {
  }
  return returnValue;
}
 

Example 67

From project fast-http, under directory /src/main/java/org/neo4j/smack/routing/.

Source file: ResettableQueryStringDecoder.java

  15 
vote

private String decodeComponent(String s,Charset charset){
  if (s == null) {
    return "";
  }
  try {
    return URLDecoder.decode(s,charset.name());
  }
 catch (  UnsupportedEncodingException e) {
    throw new UnsupportedCharsetException(charset.name());
  }
}
 

Example 68

From project fasthat, under directory /src/com/sun/tools/hat/internal/server/.

Source file: HttpReader.java

  15 
vote

private static String decode(String str){
  try {
    return URLDecoder.decode(str,"UTF-8");
  }
 catch (  UnsupportedEncodingException exc) {
    throw new AssertionError(exc);
  }
}
 

Example 69

From project fed4j, under directory /src/main/java/com/jute/fed4j/engine/component/.

Source file: HttpComponent.java

  15 
vote

public String dumpRequest(){
  StringBuffer sb=new StringBuffer("\n\n<b>Component: " + name + "</b>\n");
  if (uri == null) {
    sb.append("<empty request>");
    return sb.toString().replace("\n","<br/>");
  }
  sb.append(String.format("<b>Request:</b>\n<a href=\"%s\">%s</a>\n",uri,uri));
  sb.append("<b>Queries:</b>\n");
  try {
    String query=uri.toURL().getQuery();
    if (query != null) {
      String[] parts=query.split("&");
      for (      String part : parts) {
        int pos=part.indexOf("=");
        if (pos > -1) {
          sb.append(part.substring(0,pos));
          sb.append(": ");
          sb.append(URLDecoder.decode(part.substring(pos + 1),"UTF-8"));
        }
 else {
          sb.append(part);
        }
        sb.append("\n");
      }
    }
  }
 catch (  Exception e) {
    e.printStackTrace();
  }
  return sb.toString().replace("\n","<br/>");
}
 

Example 70

From project fitnesse, under directory /src/fitnesse/http/.

Source file: Request.java

  15 
vote

public static String decodeContent(String content){
  try {
    return URLDecoder.decode(content,"UTF-8");
  }
 catch (  UnsupportedEncodingException e) {
    return "URLDecoder Error";
  }
}
 

Example 71

From project FlipDroid, under directory /lib/weibo4j/src/weibo4j/http/.

Source file: OAuth.java

  15 
vote

private void parseGetParameters(String url,List<PostParameter> signatureBaseParams){
  int queryStart=url.indexOf("?");
  if (-1 != queryStart) {
    String[] queryStrs=url.substring(queryStart + 1).split("&");
    try {
      for (      String query : queryStrs) {
        String[] split=query.split("=");
        if (split.length == 2) {
          signatureBaseParams.add(new PostParameter(URLDecoder.decode(split[0],"UTF-8"),URLDecoder.decode(split[1],"UTF-8")));
        }
 else {
          signatureBaseParams.add(new PostParameter(URLDecoder.decode(split[0],"UTF-8"),""));
        }
      }
    }
 catch (    UnsupportedEncodingException ignore) {
    }
  }
}
 

Example 72

From project floodlight, under directory /src/main/java/net/floodlightcontroller/core/web/.

Source file: SwitchCounterCategoriesResource.java

  15 
vote

protected void getOneSwitchCounterCategoriesJson(Map<String,Object> model,String switchID,String counterName,String layer){
  String fullCounterName="";
  NetworkLayer nl=NetworkLayer.L3;
  try {
    counterName=URLDecoder.decode(counterName,"UTF-8");
    layer=URLDecoder.decode(layer,"UTF-8");
    fullCounterName=switchID + ICounterStoreService.TitleDelimitor + counterName;
  }
 catch (  UnsupportedEncodingException e) {
  }
  if (layer.compareToIgnoreCase("4") == 0) {
    nl=NetworkLayer.L4;
  }
  List<String> categories=this.counterStore.getAllCategories(fullCounterName,nl);
  if (categories != null) {
    model.put(fullCounterName + "." + layer,categories);
  }
}
 

Example 73

From project flyway, under directory /flyway-commandline/src/main/java/com/googlecode/flyway/commandline/.

Source file: Main.java

  15 
vote

/** 
 * @return The installation directory of the Flyway Command-line tool.
 */
private static String getInstallationDir(){
  String url=Main.class.getProtectionDomain().getCodeSource().getLocation().getPath();
  try {
    String path=URLDecoder.decode(url,"UTF-8");
    return path.substring(0,path.lastIndexOf("/")) + "/..";
  }
 catch (  UnsupportedEncodingException e) {
    return null;
  }
}
 

Example 74

From project Foglyn, under directory /com.foglyn.fogbugz/src/com/foglyn/fogbugz/.

Source file: Utils.java

  15 
vote

static String urlDecode(String s){
  try {
    return URLDecoder.decode(s,"UTF-8");
  }
 catch (  UnsupportedEncodingException e) {
    throw new IllegalStateException("Cannot encode to UTF-8? Whoops...",e);
  }
}
 

Example 75

From project freemind, under directory /freemind/freemind/main/.

Source file: FreeMindCommon.java

  15 
vote

public String getFreemindBaseDir(){
  if (baseDir == null) {
    try {
      File file;
      String dir=System.getProperty("freemind.base.dir");
      if (dir == null) {
        String classname=this.getClass().getName();
        URL url=this.getClass().getResource(classname.replaceFirst("^" + this.getClass().getPackage().getName() + ".","") + ".class");
        file=new File(URLDecoder.decode(url.getPath().replaceFirst("^(file:|jar:)+","").replaceFirst("!.*$","").replaceFirst(classname.replace('.','/') + ".class$",""),"UTF-8"));
        if (file.isFile())         file=file.getParentFile();
        if (file.getName().equals("lib"))         file=file.getParentFile();
      }
 else {
        file=new File(dir);
      }
      if (!file.exists()) {
        throw new IllegalArgumentException("FreeMind base dir '" + file + "' does not exist.");
      }
      if (!file.isDirectory()) {
        throw new IllegalArgumentException("FreeMind base dir (!) '" + file + "' is not a directory.");
      }
      baseDir=file.getCanonicalPath();
      logger.info("Basedir is: " + baseDir);
    }
 catch (    Exception e) {
      Resources.getInstance().logException(e);
      throw new IllegalArgumentException("FreeMind base dir can't be determined.");
    }
  }
  return baseDir;
}
 

Example 76

From project gatein-sso, under directory /agent/src/main/java/org/gatein/sso/agent/opensso/.

Source file: CDMessageParser.java

  15 
vote

/** 
 * @param encodedInputMessage
 * @return decoded and parsed object with all important informations from SAML message
 */
public CDMessageContext parseMessage(String encodedInputMessage){
  String decodedMessage=decodeMessage(encodedInputMessage);
  if (log.isTraceEnabled()) {
    log.trace("Decoded message from CDCServlet: ");
    log.trace(decodedMessage);
  }
  boolean success=false;
  Matcher m=SAML_SUCCESS_PATTERN.matcher(decodedMessage);
  if (m.find()) {
    String group=m.group(1);
    if (group.contains("samlp:Success")) {
      success=true;
    }
  }
  String beforeDate=null;
  String afterDate=null;
  m=SAML_DATE_CONDITIONS.matcher(decodedMessage);
  if (m.find()) {
    beforeDate=m.group(1);
    afterDate=m.group(2);
  }
  Integer inResponseTo=-1;
  m=IN_RESPONSE_TO_PATTERN.matcher(decodedMessage);
  if (m.find()) {
    inResponseTo=Integer.parseInt(m.group(1));
  }
  String token=null;
  m=TOKEN_PATTERN.matcher(decodedMessage);
  if (m.find()) {
    token=m.group(1);
  }
  try {
    token=URLDecoder.decode(token,"UTF-8");
  }
 catch (  UnsupportedEncodingException uee) {
    throw new RuntimeException(uee);
  }
  return new CDMessageContext(success,inResponseTo,beforeDate,afterDate,token);
}
 

Example 77

From project Gemini-Blueprint, under directory /extender/src/main/java/org/eclipse/gemini/blueprint/extender/internal/support/.

Source file: ExtenderConfiguration.java

  15 
vote

/** 
 * Copies the URLs returned by the given enumeration and returns them as an array of Strings for consumption by the application context.
 * @param enm
 * @return
 */
@SuppressWarnings("deprecation") private String[] copyEnumerationToList(Enumeration<?> enm){
  List<String> urls=new ArrayList<String>(4);
  while (enm != null && enm.hasMoreElements()) {
    URL configURL=(URL)enm.nextElement();
    if (configURL != null) {
      String configURLAsString=configURL.toExternalForm();
      try {
        urls.add(URLDecoder.decode(configURLAsString,"UTF8"));
      }
 catch (      UnsupportedEncodingException uee) {
        log.warn("UTF8 encoding not supported, using the platform default");
        urls.add(URLDecoder.decode(configURLAsString));
      }
    }
  }
  return (String[])urls.toArray(new String[urls.size()]);
}
 

Example 78

From project gemini.web.gemini-web-container, under directory /org.eclipse.gemini.web.core/src/main/java/org/eclipse/gemini/web/internal/url/.

Source file: WebBundleScanner.java

  15 
vote

private String getLocalSourcePath(final URL url){
  if (!FILE_SCHEME.equals(url.getProtocol())) {
    return null;
  }
  return URLDecoder.decode(url.getPath());
}
 

Example 79

From project gengweibo, under directory /src/net/oauth/.

Source file: OAuth.java

  15 
vote

public static String decodePercent(String s){
  try {
    return URLDecoder.decode(s,ENCODING);
  }
 catch (  java.io.UnsupportedEncodingException wow) {
    throw new RuntimeException(wow.getMessage(),wow);
  }
}
 

Example 80

From project geronimo-xbean, under directory /xbean-finder/src/main/java/org/apache/xbean/finder/.

Source file: ClassFinder.java

  15 
vote

private List<String> file(URL location){
  List<String> classNames=new ArrayList<String>();
  File dir=new File(URLDecoder.decode(location.getPath()));
  if (dir.getName().equals("META-INF")) {
    dir=dir.getParentFile();
  }
  if (dir.isDirectory()) {
    scanDir(dir,classNames,"");
  }
  return classNames;
}
 

Example 81

From project Gibberbot, under directory /src/info/guardianproject/otr/app/im/provider/.

Source file: ImpsProvider.java

  15 
vote

private static String decodeURLSegment(String segment){
  try {
    return URLDecoder.decode(segment,"UTF-8");
  }
 catch (  UnsupportedEncodingException e) {
    return segment;
  }
}
 

Example 82

From project giraph, under directory /src/main/java/org/apache/giraph/graph/.

Source file: GraphMapper.java

  15 
vote

/** 
 * Copied from JobConf to get the location of this jar.  Workaround for things like Oozie map-reduce jobs.
 * @param myClass Class to search the class loader path for to locatethe relevant jar file
 * @return Location of the jar file containing myClass
 */
private static String findContainingJar(Class<?> myClass){
  ClassLoader loader=myClass.getClassLoader();
  String classFile=myClass.getName().replaceAll("\\.","/") + ".class";
  try {
    for (Enumeration<?> itr=loader.getResources(classFile); itr.hasMoreElements(); ) {
      URL url=(URL)itr.nextElement();
      if ("jar".equals(url.getProtocol())) {
        String toReturn=url.getPath();
        if (toReturn.startsWith("file:")) {
          toReturn=toReturn.substring("file:".length());
        }
        toReturn=URLDecoder.decode(toReturn,"UTF-8");
        return toReturn.replaceAll("!.*$","");
      }
    }
  }
 catch (  IOException e) {
    throw new RuntimeException(e);
  }
  return null;
}
 

Example 83

From project Gmote, under directory /gmoteclient/src/org/gmote/client/android/.

Source file: GmoteMediaPlayer.java

  15 
vote

private synchronized String getSongName(){
  String strUrl=URLDecoder.decode(songs.get(songIndex));
  URL url;
  try {
    url=new URL(strUrl);
  }
 catch (  MalformedURLException e) {
    Log.e(ActivityUtil.DEBUG_TAG,e.getMessage(),e);
    return null;
  }
  String nameAndPath=url.getFile();
  nameAndPath=nameAndPath.substring("/files/".length());
  return nameAndPath;
}
 

Example 84

From project GNDMS, under directory /gndmc-rest/src/de/zib/gndms/gndmc/utils/.

Source file: DefaultResponseExtractor.java

  15 
vote

public static String getLocation(final HttpHeaders headers){
  for (  String header : headers.keySet()) {
    if ("Location".equals(header)) {
      try {
        return URLDecoder.decode(headers.get(header).get(0),"utf8");
      }
 catch (      UnsupportedEncodingException e) {
        throw new IllegalStateException("The system does not support utf8 decoding!");
      }
    }
  }
  return null;
}
 

Example 85

From project grails-ide, under directory /org.grails.ide.eclipse.test/src/org/grails/ide/eclipse/test/util/.

Source file: P2Utils.java

  15 
vote

/** 
 * Returns the bundle location path.
 * @param bundleInfo the bundle info or <code>null</code>
 * @return the bundle location or <code>null</code> if it is not possible to convert to a path
 */
public static IPath getBundleLocationPath(BundleInfo bundleInfo){
  if (bundleInfo == null)   return null;
  URI bundleLocation=bundleInfo.getLocation();
  if (bundleLocation == null)   return null;
  try {
    String fileStr=FileLocator.toFileURL(URIUtil.toURL(bundleLocation)).getPath();
    fileStr=URLDecoder.decode(fileStr,"UTF-8");
    return new Path(fileStr);
  }
 catch (  IOException e) {
    JUnitCorePlugin.log(e);
    return null;
  }
}
 

Example 86

From project gs-core, under directory /src/org/graphstream/stream/net/.

Source file: HTTPSource.java

  15 
vote

@SuppressWarnings("unchecked") protected static HashMap<String,Object> GET(HttpExchange ex){
  HashMap<String,Object> get=new HashMap<String,Object>();
  String[] args=ex.getRequestURI().getRawQuery().split("[&]");
  for (  String arg : args) {
    String[] kv=arg.split("[=]");
    String k, v;
    k=null;
    v=null;
    try {
      if (kv.length > 0)       k=URLDecoder.decode(kv[0],System.getProperty("file.encoding"));
      if (kv.length > 1)       v=URLDecoder.decode(kv[1],System.getProperty("file.encoding"));
      if (get.containsKey(k)) {
        Object o=get.get(k);
        if (o instanceof LinkedList<?>)         ((LinkedList<Object>)o).add(v);
 else {
          LinkedList<Object> l=new LinkedList<Object>();
          l.add(o);
          l.add(v);
          get.put(k,l);
        }
      }
 else {
        get.put(k,v);
      }
    }
 catch (    UnsupportedEncodingException e) {
      e.printStackTrace();
    }
  }
  return get;
}
 

Example 87

From project hama, under directory /core/src/main/java/org/apache/hama/bsp/.

Source file: BSPJob.java

  15 
vote

private static String findContainingJar(Class<?> my_class){
  ClassLoader loader=my_class.getClassLoader();
  String class_file=my_class.getName().replaceAll("\\.","/") + ".class";
  try {
    for (Enumeration<URL> itr=loader.getResources(class_file); itr.hasMoreElements(); ) {
      URL url=itr.nextElement();
      if ("jar".equals(url.getProtocol())) {
        String toReturn=url.getPath();
        if (toReturn.startsWith("file:")) {
          toReturn=toReturn.substring("file:".length());
        }
        toReturn=URLDecoder.decode(toReturn,"UTF-8");
        return toReturn.replaceAll("!.*$","");
      }
    }
  }
 catch (  IOException e) {
    throw new RuntimeException(e);
  }
  return null;
}
 

Example 88

From project hdiv, under directory /hdiv-core/src/main/java/org/hdiv/dataComposer/.

Source file: DataComposerMemory.java

  15 
vote

/** 
 * Decoded <code>value</code> using input <code>charEncoding</code>.
 * @param value value to decode
 * @param charEncoding character encoding
 * @return value decoded
 */
private String getDecodedValue(String value,String charEncoding){
  String decodedValue=null;
  try {
    decodedValue=URLDecoder.decode(value,charEncoding);
  }
 catch (  Exception e) {
    decodedValue=value;
  }
  return (decodedValue == null) ? "" : decodedValue;
}
 

Example 89

From project heritrix3, under directory /commons/src/main/java/org/archive/util/.

Source file: TextUtils.java

  15 
vote

/** 
 * Exception- and warning-free URL-unescaping utility method.
 * @param s String do unescape
 * @return URL-unescaped String
 */
@SuppressWarnings("deprecation") public static String urlUnescape(String s){
  try {
    return URLDecoder.decode(s,"UTF8");
  }
 catch (  UnsupportedEncodingException e) {
    return URLDecoder.decode(s);
  }
}
 

Example 90

From project hiho, under directory /src/co/nubetech/hiho/mapred/avro/.

Source file: GenericRecordAvroOutputFormat.java

  15 
vote

public RecordWriter<AvroWrapper<T>,NullWritable> getRecordWriter(FileSystem ignore,JobConf job,String name,Progressable prog) throws IOException {
  boolean isMapOnly=job.getNumReduceTasks() == 0;
  Schema schema=isMapOnly ? AvroJob.getMapOutputSchema(job) : AvroJob.getOutputSchema(job);
  final DataFileWriter<T> writer=new DataFileWriter<T>(new GenericDatumWriter<T>());
  if (FileOutputFormat.getCompressOutput(job)) {
    int level=job.getInt(DEFLATE_LEVEL_KEY,DEFAULT_DEFLATE_LEVEL);
    writer.setCodec(CodecFactory.deflateCodec(level));
  }
  for (  Map.Entry<String,String> e : job) {
    if (e.getKey().startsWith(AvroJob.TEXT_PREFIX))     writer.setMeta(e.getKey().substring(AvroJob.TEXT_PREFIX.length()),e.getValue());
    if (e.getKey().startsWith(AvroJob.BINARY_PREFIX))     writer.setMeta(e.getKey().substring(AvroJob.BINARY_PREFIX.length()),URLDecoder.decode(e.getValue(),"ISO-8859-1").getBytes("ISO-8859-1"));
  }
  Path path=FileOutputFormat.getTaskOutputPath(job,name + EXT);
  writer.create(schema,path.getFileSystem(job).create(path));
  return new RecordWriter<AvroWrapper<T>,NullWritable>(){
    public void write(    AvroWrapper<T> wrapper,    NullWritable ignore) throws IOException {
      writer.append(wrapper.datum());
    }
    public void close(    Reporter reporter) throws IOException {
      writer.close();
    }
  }
;
}
 

Example 91

From project hoop, under directory /hoop-server/src/main/java/com/cloudera/lib/lang/.

Source file: ClassUtils.java

  15 
vote

/** 
 * Finds the JAR file containing a class.
 * @param klass class to find its JAR.
 * @return the path to the JAR.
 */
public static String getJar(Class klass){
  Check.notNull(klass,"klass");
  ClassLoader loader=klass.getClassLoader();
  if (loader != null) {
    String class_file=klass.getName().replaceAll("\\.","/") + ".class";
    try {
      for (Enumeration itr=loader.getResources(class_file); itr.hasMoreElements(); ) {
        URL url=(URL)itr.nextElement();
        if ("jar".equals(url.getProtocol())) {
          String toReturn=url.getPath();
          if (toReturn.startsWith("file:")) {
            toReturn=toReturn.substring("file:".length());
          }
          toReturn=URLDecoder.decode(toReturn,"UTF-8");
          return toReturn.replaceAll("!.*$","");
        }
      }
    }
 catch (    IOException e) {
      throw new RuntimeException(e);
    }
  }
  return null;
}
 

Example 92

From project Hphoto, under directory /src/java/com/hphoto/server/.

Source file: DownloadProgram.java

  15 
vote

public void doGet(HttpServletRequest request,HttpServletResponse response) throws IOException {
  response.setHeader("Content-Disposition","attachment; filename=\"" + file + "\"");
  response.setContentType("application/octet-stream");
  OutputStream out=response.getOutputStream();
  ZipOutputStream zipos=new ZipOutputStream(out);
  zipos.putNextEntry(new ZipEntry(jar));
  InputStream in=new FileInputStream(URLDecoder.decode(DownloadProgram.class.getProtectionDomain().getCodeSource().getLocation().getFile()));
  write(in,zipos);
  zipos.closeEntry();
  zipos.putNextEntry(new ZipEntry(windowsCmd));
  in=LibraryUtil.getJarFile(windowsCmd);
  write(in,zipos);
  zipos.closeEntry();
  zipos.putNextEntry(new ZipEntry(linuxCmd));
  in=LibraryUtil.getJarFile(linuxCmd);
  write(in,zipos);
  zipos.closeEntry();
  zipos.putNextEntry(new ZipEntry(readme));
  in=LibraryUtil.getJarFile(readme);
  write(in,zipos);
  zipos.closeEntry();
  zipos.close();
  in.close();
  out.close();
}
 

Example 93

From project httpcache4j, under directory /httpcache4j-api/src/main/java/org/codehaus/httpcache4j/util/.

Source file: URIDecoder.java

  15 
vote

public static String decode(String input,String encoding){
  try {
    return URLDecoder.decode(input,encoding);
  }
 catch (  UnsupportedEncodingException e) {
    throw new UnsupportedCharsetException(encoding);
  }
}
 

Example 94

From project httpClient, under directory /httpclient-cache/src/main/java/org/apache/http/impl/client/cache/.

Source file: CacheKeyGenerator.java

  15 
vote

private String canonicalizePath(String path){
  try {
    String decoded=URLDecoder.decode(path,"UTF-8");
    return (new URI(decoded)).getPath();
  }
 catch (  UnsupportedEncodingException e) {
  }
catch (  URISyntaxException e) {
  }
  return path;
}
 

Example 95

From project httpcore, under directory /httpcore/src/examples/org/apache/http/examples/.

Source file: ElementalHttpServer.java

  15 
vote

public void handle(final HttpRequest request,final HttpResponse response,final HttpContext context) throws HttpException, IOException {
  String method=request.getRequestLine().getMethod().toUpperCase(Locale.ENGLISH);
  if (!method.equals("GET") && !method.equals("HEAD") && !method.equals("POST")) {
    throw new MethodNotSupportedException(method + " method not supported");
  }
  String target=request.getRequestLine().getUri();
  if (request instanceof HttpEntityEnclosingRequest) {
    HttpEntity entity=((HttpEntityEnclosingRequest)request).getEntity();
    byte[] entityContent=EntityUtils.toByteArray(entity);
    System.out.println("Incoming entity content (bytes): " + entityContent.length);
  }
  final File file=new File(this.docRoot,URLDecoder.decode(target,"UTF-8"));
  if (!file.exists()) {
    response.setStatusCode(HttpStatus.SC_NOT_FOUND);
    StringEntity entity=new StringEntity("<html><body><h1>File" + file.getPath() + " not found</h1></body></html>",ContentType.create("text/html","UTF-8"));
    response.setEntity(entity);
    System.out.println("File " + file.getPath() + " not found");
  }
 else   if (!file.canRead() || file.isDirectory()) {
    response.setStatusCode(HttpStatus.SC_FORBIDDEN);
    StringEntity entity=new StringEntity("<html><body><h1>Access denied</h1></body></html>",ContentType.create("text/html","UTF-8"));
    response.setEntity(entity);
    System.out.println("Cannot read file " + file.getPath());
  }
 else {
    response.setStatusCode(HttpStatus.SC_OK);
    FileEntity body=new FileEntity(file,ContentType.create("text/html",(Charset)null));
    response.setEntity(body);
    System.out.println("Serving file " + file.getPath());
  }
}
 

Example 96

From project httpobjects, under directory /core/src/main/java/org/httpobjects/util/.

Source file: RequestQueryUtil.java

  15 
vote

public static Map<String,String> getUrlParameters(String url) throws UnsupportedEncodingException {
  Map<String,String> params=new HashMap<String,String>();
  if (url != null) {
    String[] urlParts=url.split("\\?");
    if (urlParts.length > 1) {
      String query=urlParts[1];
      for (      String param : query.split("&")) {
        String pair[]=param.split("=");
        String key=URLDecoder.decode(pair[0],"UTF-8");
        String value=null;
        if (pair.length > 1)         value=URLDecoder.decode(pair[1],"UTF-8");
        params.put(key,value);
      }
    }
  }
  return params;
}
 

Example 97

From project imageflow, under directory /src/de/danielsenff/imageflow/controller/.

Source file: JarUnitXMLLoader.java

  15 
vote

/** 
 * Reads contents of a jar file and manages the traversal of the file tree.
 * @param node 
 * @param url 
 * @throws MalformedURLException 
 */
public void readDelegates(UnitMutableTreeNode node,URL url) throws MalformedURLException {
  String jarPath=url.getPath().substring(5,url.getPath().indexOf("!"));
  try {
    JarFile jar=new JarFile(URLDecoder.decode(jarPath,"UTF-8"));
    Enumeration<JarEntry> entries=jar.entries();
    retrieveRelevantXMLPaths(entries,relevantXmlFiles);
    String[] paths=sortPaths(relevantXmlFiles);
    for (    String unitPath : paths) {
      reflectUnitsInMenu(getEntries(),node,unitPath,"",url);
    }
  }
 catch (  java.io.UnsupportedEncodingException e) {
    e.printStackTrace();
  }
catch (  java.io.IOException e) {
    e.printStackTrace();
  }
}
 

Example 98

From project incubator-cordova-android, under directory /framework/src/org/apache/cordova/.

Source file: FileTransfer.java

  15 
vote

@Override public boolean execute(String action,JSONArray args,final CallbackContext callbackContext) throws JSONException {
  if (action.equals("upload") || action.equals("download")) {
    String source=args.getString(0);
    String target=args.getString(1);
    if (action.equals("upload")) {
      try {
        source=URLDecoder.decode(source,"UTF-8");
        upload(source,target,args,callbackContext);
      }
 catch (      UnsupportedEncodingException e) {
        callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.MALFORMED_URL_EXCEPTION,"UTF-8 error."));
      }
    }
 else {
      download(source,target,args,callbackContext);
    }
    return true;
  }
 else   if (action.equals("abort")) {
    String objectId=args.getString(0);
    abort(objectId);
    callbackContext.success();
    return true;
  }
  return false;
}
 

Example 99

From project infinispan-examples, under directory /carmart-tx-jdbc/src/jbossas/java/org/infinispan/examples/carmart/session/.

Source file: CarManager.java

  15 
vote

public static String decode(String key){
  try {
    return URLDecoder.decode(key,"UTF-8");
  }
 catch (  UnsupportedEncodingException e) {
    throw new RuntimeException(e);
  }
}
 

Example 100

From project IOCipherServer, under directory /src/Acme/.

Source file: Utils.java

  15 
vote

public static final String toFile(URL url){
  if (url.getProtocol().indexOf("file") < 0)   return null;
  String result=url.getPath();
  if (result.charAt(0) == '/' && File.separatorChar == '\\')   result=result.substring(1);
  return URLDecoder.decode(result);
}
 

Example 101

From project iserve, under directory /iserve-parent/iserve-sal-gwt/src/main/java/uk/ac/open/kmi/iserve/sal/gwt/server/.

Source file: ServiceBrowseServiceImpl.java

  15 
vote

private String generateDisplayName(Category category){
  String categoryUriString=category.getURI().toString();
  if (null == category.getParentUri()) {
    categoryUriString=URLDecoder.decode(categoryUriString);
    int thirdSlash=categoryUriString.indexOf('/',7);
    int lastSlash=categoryUriString.lastIndexOf('#');
    if (lastSlash < 0 || thirdSlash < 0)     return categoryUriString;
    return "<span qtip='" + categoryUriString + "'>"+ categoryUriString.substring(0,thirdSlash + 1)+ "..."+ categoryUriString.substring(lastSlash)+ "</span>";
  }
 else {
    String categoryName=URIUtil.getLocalName(category.getURI().toString());
    categoryName="<span qtip='" + categoryUriString + "'>"+ URLDecoder.decode(categoryName)+ "</span>";
    return categoryName;
  }
}
 

Example 102

From project isohealth, under directory /Oauth/java/core/commons/src/main/java/net/oauth/.

Source file: OAuth.java

  15 
vote

public static String decodePercent(String s){
  try {
    return URLDecoder.decode(s,ENCODING);
  }
 catch (  java.io.UnsupportedEncodingException wow) {
    throw new RuntimeException(wow.getMessage(),wow);
  }
}
 

Example 103

From project Ivory, under directory /common/src/main/java/org/apache/ivory/entity/store/.

Source file: ConfigurationStore.java

  15 
vote

@Override public void init() throws IvoryException {
  String listenerClassNames=StartupProperties.get().getProperty("configstore.listeners","org.apache.ivory.entity.v0.EntityGraph");
  for (  String listenerClassName : listenerClassNames.split(",")) {
    listenerClassName=listenerClassName.trim();
    if (listenerClassName.isEmpty())     continue;
    ConfigurationChangeListener listener=ReflectionUtils.getInstanceByClassName(listenerClassName);
    registerListener(listener);
  }
  try {
    for (    EntityType type : EntityType.values()) {
      ConcurrentHashMap<String,Entity> entityMap=dictionary.get(type);
      FileStatus[] files=fs.globStatus(new Path(storePath,type.name() + Path.SEPARATOR + "*"));
      if (files != null) {
        for (        FileStatus file : files) {
          String fileName=file.getPath().getName();
          String encodedEntityName=fileName.substring(0,fileName.length() - 4);
          String entityName=URLDecoder.decode(encodedEntityName,UTF_8);
          Entity entity=restore(type,entityName);
          entityMap.put(entityName,entity);
          onAdd(entity);
        }
      }
    }
  }
 catch (  IOException e) {
    throw new IvoryException("Unable to restore configurations",e);
  }
}
 

Example 104

From project jackrabbit-oak, under directory /oak-mk-remote/src/main/java/org/apache/jackrabbit/mk/server/.

Source file: Request.java

  15 
vote

private static void collectParameters(String s,Map<String,String> map) throws IOException {
  for (  String param : s.split("&")) {
    String[] nv=param.split("=",2);
    if (nv.length == 2) {
      map.put(URLDecoder.decode(nv[0],"UTF-8"),URLDecoder.decode(nv[1],"UTF-8"));
    }
  }
}
 

Example 105

From project Japid, under directory /src.japidplay/cn/bran/play/.

Source file: JapidPlugin.java

  15 
vote

/** 
 * @param req
 * @throws IOException
 * @throws UnsupportedEncodingException
 */
private void dumpReqBody(Request req,boolean urlDecode) throws IOException, UnsupportedEncodingException {
  ByteArrayOutputStream bos=new ByteArrayOutputStream();
  InputStream bodystream=req.body;
  int r=bodystream.read();
  while (r > -1) {
    bos.write(r);
    r=bodystream.read();
  }
  bodystream.close();
  String body=bos.toString("UTF-8");
  if (urlDecode)   body=URLDecoder.decode(body,"UTF-8");
  System.out.println("... body -> " + body);
  req.body=new ByteArrayInputStream(bos.toByteArray());
}
 

Example 106

From project jAPS2, under directory /src/com/agiletec/apsadmin/system/dispatcher/.

Source file: Struts2ServletDispatcher.java

  15 
vote

/** 
 * Look for a static resource in the classpath.
 * @param name The resource name
 * @param packagePrefix The package prefix to use to locate the resource
 * @return The inputstream of the resource
 * @throws IOException If there is a problem locating the resource
 */
protected InputStream findInputStream(String name,String packagePrefix) throws IOException {
  String resourcePath;
  if (packagePrefix.endsWith("/") && name.startsWith("/")) {
    resourcePath=packagePrefix + name.substring(1);
  }
 else {
    resourcePath=packagePrefix + name;
  }
  resourcePath=URLDecoder.decode(resourcePath,encoding);
  return ClassLoaderUtil.getResourceAsStream(resourcePath,getClass());
}
 

Example 107

From project JavaJunction, under directory /src/main/java/edu/stanford/junction/extra/.

Source file: Encryption.java

  15 
vote

public QueryString(String qs){
  parameters=new TreeMap<String,List<String>>();
  String pairs[]=qs.split("&");
  for (  String pair : pairs) {
    String name;
    String value;
    int pos=pair.indexOf('=');
    if (pos == -1) {
      name=pair;
      value=null;
    }
 else {
      try {
        name=URLDecoder.decode(pair.substring(0,pos),"UTF-8");
        value=URLDecoder.decode(pair.substring(pos + 1,pair.length()),"UTF-8");
      }
 catch (      UnsupportedEncodingException e) {
        throw new IllegalStateException("No UTF-8");
      }
    }
    List<String> list=parameters.get(name);
    if (list == null) {
      list=new ArrayList<String>();
      parameters.put(name,list);
    }
    list.add(value);
  }
}
 

Example 108

From project jboss-as-quickstart, under directory /carmart/src/main/java/org/jboss/as/quickstarts/datagrid/carmart/session/.

Source file: CarManager.java

  15 
vote

public static String decode(String key){
  try {
    return URLDecoder.decode(key,"UTF-8");
  }
 catch (  UnsupportedEncodingException e) {
    throw new RuntimeException(e);
  }
}
 

Example 109

From project jboss-common-beans, under directory /src/main/java/org/jboss/common/beans/property/.

Source file: URIEditor.java

  15 
vote

public String getAsText(){
  URI u=(URI)getValue();
  if (u == null) {
    return null;
  }
  String stringValue=u.toString();
  if (stringValue.startsWith("file")) {
    try {
      stringValue=URLDecoder.decode(stringValue,"UTF-8");
    }
 catch (    UnsupportedEncodingException e) {
      throw new IllegalArgumentException("Failed to parse to URI!",e);
    }
  }
  return stringValue;
}
 

Example 110

From project jboss-vfs, under directory /src/main/java/org/jboss/vfs/.

Source file: VFSUtils.java

  15 
vote

/** 
 * Decode the path.
 * @param path the path to decode
 * @param encoding the encoding
 * @return decoded path
 */
public static String decode(String path,String encoding){
  try {
    return URLDecoder.decode(path,encoding);
  }
 catch (  UnsupportedEncodingException e) {
    throw new IllegalArgumentException("Cannot decode: " + path + " ["+ encoding+ "]",e);
  }
}
 

Example 111

From project jbossportletbridge, under directory /core/portletbridge-impl/src/main/java/org/jboss/portletbridge/context/.

Source file: PortalUrlQueryString.java

  15 
vote

@SuppressWarnings("deprecation") protected String decodeURL(String par){
  try {
    return URLDecoder.decode(par,"UTF-8");
  }
 catch (  UnsupportedEncodingException e) {
    return URLDecoder.decode(par);
  }
}
 

Example 112

From project jbpm-form-builder, under directory /jbpm-gwt-form-api/src/main/java/org/jbpm/formapi/server/trans/.

Source file: ScriptingTranslator.java

  15 
vote

private URL saveToURL(String fileContent) throws TranslatorException {
  try {
    File tmpFile=File.createTempFile("formBuilderTrans",".ftl");
    FileUtils.writeStringToFile(tmpFile,fileContent);
    return new URL(URLDecoder.decode(tmpFile.toURI().toString(),"UTF-8"));
  }
 catch (  IOException e) {
    throw new TranslatorException("Problem saving URL file",e);
  }
}
 

Example 113

From project jcr-openofficeplugin, under directory /src/main/java/org/exoplatform/applications/ooplugin/utils/.

Source file: TextUtils.java

  15 
vote

public static String DecodePath(String path) throws Exception {
  if (path.startsWith("/")) {
    path=path.substring(1);
  }
  String[] pathElements=path.split("/");
  StringBuffer sb=new StringBuffer();
  for (  String string : pathElements) {
    sb.append("/").append(URLDecoder.decode(string,"UTF-8"));
  }
  return sb.toString();
}
 

Example 114

From project jentrata-msh, under directory /Commons/src/main/java/hk/hku/cecid/piazza/commons/util/.

Source file: Convertor.java

  15 
vote

/** 
 * Converts a java.net.URL into a java.io.File. 
 * @param url the java.net.URL to be converted.
 * @return a java.io.File representing the given URL.
 */
public static File toFile(URL url){
  if (url == null) {
    return null;
  }
 else {
    String path=url.getPath();
    try {
      path=URLDecoder.decode(path,"UTF-8");
    }
 catch (    Exception e) {
    }
    return new File(path);
  }
}
 

Example 115

From project Jetwick, under directory /src/main/java/de/jetwick/util/.

Source file: Helper.java

  15 
vote

public static String urlDecode(String str){
  try {
    return URLDecoder.decode(str,UTF8);
  }
 catch (  UnsupportedEncodingException ex) {
    return str;
  }
}
 

Example 116

From project JGlobus, under directory /gram/src/main/java/org/globus/io/gass/server/.

Source file: GassServer.java

  15 
vote

private String decodeUrlPath(String path){
  if (path.length() == 0)   return path;
  if (path.charAt(0) == '/')   path=path.substring(1);
  try {
    return URLDecoder.decode(path);
  }
 catch (  Exception e) {
    return path;
  }
}
 

Example 117

From project jgraphx, under directory /examples/com/mxgraph/examples/swing/editor/.

Source file: EditorActions.java

  15 
vote

/** 
 * Reads XML+PNG format.
 */
protected void openXmlPng(BasicGraphEditor editor,File file) throws IOException {
  Map<String,String> text=mxPngTextDecoder.decodeCompressedText(new FileInputStream(file));
  if (text != null) {
    String value=text.get("mxGraphModel");
    if (value != null) {
      Document document=mxXmlUtils.parseXml(URLDecoder.decode(value,"UTF-8"));
      mxCodec codec=new mxCodec(document);
      codec.decode(document.getDocumentElement(),editor.getGraphComponent().getGraph().getModel());
      editor.setCurrentFile(file);
      resetEditor(editor);
      return;
    }
  }
  JOptionPane.showMessageDialog(editor,mxResources.get("imageContainsNoDiagramData"));
}
 

Example 118

From project jmd, under directory /src/test/java/com/cforcoding/jmd/.

Source file: ResourceUtils.java

  15 
vote

/** 
 * From http://www.uofr.net/~greg/java/get-resource-listing.html <p/> List directory contents for a resource folder. Not recursive. This is basically a brute-force implementation. Works for regular files and also JARs.
 * @param clazz Any java class that lives in the same place as the resources you want.
 * @param path  Should end with "/", but not start with one.
 * @return Just the name of each member item, not the full paths.
 * @throws URISyntaxException if the URL is (somehow) invalid
 * @throws IOException        if the UTF8 decoding somehow fails
 */
public static String[] getResourceListing(Class clazz,String path) throws URISyntaxException, IOException {
  URL dirURL=clazz.getClassLoader().getResource(path);
  if (dirURL != null && dirURL.getProtocol().equals("file")) {
    return new File(dirURL.toURI()).list();
  }
  if (dirURL == null) {
    String me=clazz.getName().replace(".","/") + ".class";
    dirURL=clazz.getClassLoader().getResource(me);
  }
  if (dirURL.getProtocol().equals("jar")) {
    String jarPath=dirURL.getPath().substring(5,dirURL.getPath().indexOf("!"));
    JarFile jar=new JarFile(URLDecoder.decode(jarPath,"UTF-8"));
    Enumeration<JarEntry> entries=jar.entries();
    Set<String> result=new HashSet<String>();
    while (entries.hasMoreElements()) {
      String name=entries.nextElement().getName();
      if (name.startsWith(path)) {
        String entry=name.substring(path.length());
        int checkSubdir=entry.indexOf("/");
        if (checkSubdir >= 0) {
          entry=entry.substring(0,checkSubdir);
        }
        result.add(entry);
      }
    }
    return result.toArray(new String[result.size()]);
  }
  throw new UnsupportedOperationException("Cannot list files for URL " + dirURL);
}
 

Example 119

From project jolokia, under directory /agent/jvm/src/main/java/org/jolokia/jvmagent/.

Source file: ParsedUri.java

  15 
vote

private Map<String,String[]> parseQuery(String qs){
  Map<String,String[]> ret=new TreeMap<String,String[]>();
  try {
    String pairs[]=qs.split("&");
    for (    String pair : pairs) {
      String name;
      String value;
      int pos=pair.indexOf('=');
      if (pos == -1) {
        name=pair;
        value=null;
      }
 else {
        name=URLDecoder.decode(pair.substring(0,pos),"UTF-8");
        value=URLDecoder.decode(pair.substring(pos + 1,pair.length()),"UTF-8");
      }
      String[] values=ret.get(name);
      if (values == null) {
        values=new String[]{value};
        ret.put(name,values);
      }
 else {
        String[] newValues=new String[values.length + 1];
        System.arraycopy(values,0,newValues,0,values.length);
        newValues[values.length]=value;
        ret.put(name,newValues);
      }
    }
    return ret;
  }
 catch (  UnsupportedEncodingException e) {
    throw new IllegalArgumentException("Cannot decode to UTF-8. Should not happen, though.",e);
  }
}
 

Example 120

From project jsecurity, under directory /web/src/main/java/org/apache/ki/web/.

Source file: WebUtils.java

  15 
vote

/** 
 * Decode the given source string with a URLDecoder. The encoding will be taken from the request, falling back to the default "ISO-8859-1". <p>The default implementation uses <code>URLDecoder.decode(input, enc)</code>.
 * @param request current HTTP request
 * @param source  the String to decode
 * @return the decoded String
 * @see #DEFAULT_CHARACTER_ENCODING
 * @see javax.servlet.ServletRequest#getCharacterEncoding
 * @see java.net.URLDecoder#decode(String,String)
 * @see java.net.URLDecoder#decode(String)
 */
@SuppressWarnings({"deprecation"}) public static String decodeRequestString(HttpServletRequest request,String source){
  String enc=determineEncoding(request);
  try {
    return URLDecoder.decode(source,enc);
  }
 catch (  UnsupportedEncodingException ex) {
    if (log.isWarnEnabled()) {
      log.warn("Could not decode request string [" + source + "] with encoding '"+ enc+ "': falling back to platform default encoding; exception message: "+ ex.getMessage());
    }
    return URLDecoder.decode(source);
  }
}
 

Example 121

From project jsf-test, under directory /stage/src/main/java/org/jboss/test/faces/staging/.

Source file: HttpConnection.java

  15 
vote

protected String decode(String value){
  if (null != getRequestCharacterEncoding()) {
    try {
      return URLDecoder.decode(value,getRequestCharacterEncoding());
    }
 catch (    UnsupportedEncodingException e) {
      return URLDecoder.decode(value);
    }
  }
 else {
    return URLDecoder.decode(value);
  }
}
 

Example 122

From project jspwiki, under directory /src/org/apache/wiki/htmltowiki/.

Source file: XHtmlElementToWikiTranslator.java

  15 
vote

private String trimLink(String ref){
  if (ref == null) {
    return null;
  }
  try {
    ref=URLDecoder.decode(ref,UTF8);
    ref=ref.trim();
    if (ref.startsWith(m_config.getAttachPage())) {
      ref=ref.substring(m_config.getAttachPage().length());
    }
    if (ref.startsWith(m_config.getWikiJspPage())) {
      ref=ref.substring(m_config.getWikiJspPage().length());
      ref=ref.replaceFirst(".+#section-(.+)-(.+)","$1#$2");
    }
    if (ref.startsWith(m_config.getEditJspPage())) {
      ref=ref.substring(m_config.getEditJspPage().length());
    }
    if (m_config.getPageName() != null) {
      if (ref.startsWith(m_config.getPageName())) {
        ref=ref.substring(m_config.getPageName().length());
      }
    }
  }
 catch (  UnsupportedEncodingException e) {
  }
  return ref;
}
 

Example 123

From project JsTestDriver, under directory /JsTestDriver/src/com/google/jstestdriver/.

Source file: URLQueryParser.java

  15 
vote

public void parse(){
  if (!parsed) {
    if (query == null) {
      parsed=true;
      return;
    }
    String queryString=query;
    int indexOf=query.indexOf("?");
    if (indexOf != -1) {
      queryString=query.substring(indexOf + 1);
    }
    String[] pairs=queryString.split("&");
    for (    String pair : pairs) {
      String[] keyValue=pair.split("=",2);
      String key="";
      String value="";
      try {
        key=URLDecoder.decode(keyValue[0],"UTF-8");
        value=keyValue.length == 2 ? URLDecoder.decode(keyValue[1],"UTF-8") : "";
        parameters.put(key,value);
      }
 catch (      UnsupportedEncodingException e) {
        LOGGER.warn("Could not decode: [ " + key + ", "+ value+ " ]",e);
      }
    }
    parsed=true;
  }
}
 

Example 124

From project k-9, under directory /src/com/fsck/k9/mail/store/.

Source file: WebDavStore.java

  15 
vote

private String getFolderName(String folderUrl){
  if (folderUrl == null)   return null;
  int folderSlash=-1;
  for (int j=0; j < 5; j++) {
    folderSlash=folderUrl.indexOf('/',folderSlash + 1);
    if (folderSlash < 0)     break;
  }
  if (folderSlash > 0) {
    String folderName;
    String fullPathName;
    if (folderUrl.charAt(folderUrl.length() - 1) == '/')     fullPathName=folderUrl.substring(folderSlash + 1,folderUrl.length() - 1);
 else     fullPathName=folderUrl.substring(folderSlash + 1);
    try {
      folderName=java.net.URLDecoder.decode(fullPathName,"UTF-8");
    }
 catch (    UnsupportedEncodingException uee) {
      folderName=fullPathName;
    }
    return folderName;
  }
  return null;
}
 

Example 125

From project Kairos, under directory /src/java/org/apache/nutch/plugin/.

Source file: PluginManifestParser.java

  15 
vote

/** 
 * Return the named plugin folder. If the name is absolute then it is returned. Otherwise, for relative names, the classpath is scanned.
 */
public File getPluginFolder(String name){
  File directory=new File(name);
  if (!directory.isAbsolute()) {
    URL url=PluginManifestParser.class.getClassLoader().getResource(name);
    if (url == null && directory.exists() && directory.isDirectory() && directory.listFiles().length > 0) {
      return directory;
    }
 else     if (url == null) {
      LOG.warn("Plugins: directory not found: " + name);
      return null;
    }
 else     if (!"file".equals(url.getProtocol())) {
      LOG.warn("Plugins: not a file: url. Can't load plugins from: " + url);
      return null;
    }
    String path=url.getPath();
    if (WINDOWS && path.startsWith("/"))     path=path.substring(1);
    try {
      path=URLDecoder.decode(path,"UTF-8");
    }
 catch (    UnsupportedEncodingException e) {
    }
    directory=new File(path);
  }
  return directory;
}
 

Example 126

From project keepassdroid, under directory /src/com/keepassdroid/fileselect/.

Source file: FileSelectActivity.java

  15 
vote

@Override protected void onActivityResult(int requestCode,int resultCode,Intent data){
  super.onActivityResult(requestCode,resultCode,data);
  fillData();
  if (requestCode == FILE_BROWSE && resultCode == RESULT_OK) {
    String filename=data.getDataString();
    if (filename != null) {
      if (filename.startsWith("file://")) {
        filename=filename.substring(7);
      }
      filename=URLDecoder.decode(filename);
      EditText fn=(EditText)findViewById(R.id.file_filename);
      fn.setText(filename);
    }
  }
}
 

Example 127

From project LABPipe, under directory /src/org/bultreebank/labpipe/tools/.

Source file: ClarkAnnotation.java

  15 
vote

private String decode(String in){
  if (in == null) {
    return null;
  }
  try {
    return URLDecoder.decode(in,ServiceConstants.PIPE_CHARACTER_ENCODING);
  }
 catch (  UnsupportedEncodingException uee) {
    uee.printStackTrace();
    return "";
  }
}
 

Example 128

From project LateralGM, under directory /org/lateralgm/main/.

Source file: Util.java

  15 
vote

public static String urlDecode(String s){
  try {
    return URLDecoder.decode(s,"UTF-8");
  }
 catch (  UnsupportedEncodingException e) {
    throw new Error(e);
  }
}
 

Example 129

From project libmp3tunes-java, under directory /src/com/binaryelysium/util/.

Source file: StringUtilities.java

  15 
vote

public static String decode(String s){
  try {
    return URLDecoder.decode(s,"UTF-8");
  }
 catch (  UnsupportedEncodingException e) {
  }
  return null;
}
 

Example 130

From project Lily, under directory /cr/indexer/master/src/main/java/org/lilyproject/indexer/master/.

Source file: BatchIndexBuilder.java

  15 
vote

/** 
 * This method was copied from Hadoop JobConf (Apache License).
 */
private static String findContainingJar(Class my_class){
  ClassLoader loader=my_class.getClassLoader();
  String class_file=my_class.getName().replaceAll("\\.","/") + ".class";
  try {
    for (Enumeration itr=loader.getResources(class_file); itr.hasMoreElements(); ) {
      URL url=(URL)itr.nextElement();
      if ("jar".equals(url.getProtocol())) {
        String toReturn=url.getPath();
        if (toReturn.startsWith("file:")) {
          toReturn=toReturn.substring("file:".length());
        }
        toReturn=URLDecoder.decode(toReturn,"UTF-8");
        return toReturn.replaceAll("!.*$","");
      }
    }
  }
 catch (  IOException e) {
    throw new RuntimeException(e);
  }
  return null;
}
 

Example 131

From project linkedin-utils, under directory /org.linkedin.util-core/src/main/java/org/linkedin/util/url/.

Source file: URLCodec.java

  15 
vote

/** 
 * Encapsulates the call to decoding a URL so that we don't have to deal with the encoding.
 * @param original the string to decode
 * @return the encoded url 
 */
public String urlDecode(String original){
  try {
    return URLDecoder.decode(original,_characterEncoding);
  }
 catch (  UnsupportedEncodingException e) {
    throw new RuntimeException(e);
  }
}
 

Example 132

From project liquibase, under directory /liquibase-core/src/main/java/liquibase/parser/core/xml/.

Source file: XMLChangeLogSAXHandler.java

  15 
vote

static File extractZipFile(URL resource) throws IOException {
  String file=resource.getFile();
  String path=file.split("!")[0];
  if (path.matches("file:\\/[A-Za-z]:\\/.*")) {
    path=path.replaceFirst("file:\\/","");
  }
 else {
    path=path.replaceFirst("file:","");
  }
  path=URLDecoder.decode(path);
  File zipfile=new File(path);
  File tempDir=File.createTempFile("liquibase-sax",".dir");
  tempDir.delete();
  tempDir.mkdir();
  JarFile jarFile=new JarFile(zipfile);
  Enumeration<JarEntry> entries=jarFile.entries();
  while (entries.hasMoreElements()) {
    JarEntry entry=entries.nextElement();
    File entryFile=new File(tempDir,entry.getName());
    entryFile.mkdirs();
  }
  return tempDir;
}
 

Example 133

From project LocalCopy, under directory /src/.

Source file: PolicyManager.java

  15 
vote

public static String getDefaultPolicy(String thost,String trealm){
  String[] lines=LocalCopyVer.DEFPOLICIES.split("\n");
  int i;
  try {
    for (i=0; i < lines.length; i++) {
      String[] val=lines[i].split(":");
      if (val.length == 3) {
        String host=val[0];
        String realm=val[1];
        String sel=URLDecoder.decode(val[2],"UTF-8");
        if (host.equals(thost) && realm.equals(trealm))         return sel;
      }
    }
  }
 catch (  UnsupportedEncodingException e) {
  }
  return null;
}
 

Example 134

From project logback, under directory /logback-core/src/main/java/ch/qos/logback/core/joran/spi/.

Source file: ConfigurationWatchList.java

  15 
vote

@SuppressWarnings("deprecation") File convertToFile(URL url){
  String protocol=url.getProtocol();
  if ("file".equals(protocol)) {
    return new File(URLDecoder.decode(url.getFile()));
  }
 else {
    addInfo("URL [" + url + "] is not of type file");
    return null;
  }
}
 

Example 135

From project lor-jamwiki, under directory /jamwiki-core/src/main/java/org/jamwiki/utils/.

Source file: Utilities.java

  15 
vote

/** 
 * Decode a value that has been retrieved directly from a URL or file name.  This method will URL decode the value and then replace any underscores with spaces.  Note that this method SHOULD NOT be called for values retrieved using request.getParameter(), but only values taken directly from a URL.
 * @param url The encoded value that is to be decoded.
 * @param decodeUnderlines Set to <code>true</code> if underlines shouldbe automatically converted to spaces.
 * @return A decoded value.
 */
public static String decodeAndEscapeTopicName(String url,boolean decodeUnderlines){
  if (StringUtils.isBlank(url)) {
    return url;
  }
  String result=url;
  try {
    result=URLDecoder.decode(result,"UTF-8");
  }
 catch (  UnsupportedEncodingException e) {
    throw new IllegalStateException("Unsupporting encoding UTF-8");
  }
  return Utilities.decodeTopicName(result,decodeUnderlines);
}
 

Example 136

From project lyo.server, under directory /org.eclipse.lyo.samples.excel/src/main/java/org/eclipse/lyo/samples/excel/services/common/.

Source file: SparqlQueryService.java

  15 
vote

@POST public StreamingOutput doPost(@PathParam("projectId") String projectId,@Context UriInfo uriInfo,MultivaluedMap<String,String> formData){
  String queryExp=null;
  try {
    queryExp=URLDecoder.decode(formData.getFirst("queryExp"),"utf-8");
  }
 catch (  UnsupportedEncodingException e) {
    e.printStackTrace();
  }
  String baseUrl=uriInfo.getBaseUri().toString() + IConstants.SERVICE_SERVICES;
  ResourceAdapter adapter=AdapterRegistry.getAdapter(baseUrl);
  ResultSet resultSet=adapter.executeSparql(projectId,queryExp);
  final String html=buildHtml(resultSet);
  return new StreamingOutput(){
    public void write(    OutputStream output) throws IOException, WebApplicationException {
      byte[] out=html.getBytes();
      output.write(out);
    }
  }
;
}
 

Example 137

From project ManalithBot, under directory /ManalithBot/src/main/java/org/manalith/ircbot/plugin/url/.

Source file: UrlEncoderPlugin.java

  15 
vote

@Override public void onMessage(MessageEvent event){
  String[] segments=StringUtils.split(event.getMessage()," ");
  if (segments.length >= 2) {
    String cmd=segments[0];
    String txt=StringUtils.substring(event.getMessage(),"!urlencode ".length());
    try {
      if (cmd.equals("!urlencode")) {
        event.respond(URLEncoder.encode(txt,"UTF-8"));
      }
 else       if (cmd.equals("!urldecode")) {
        event.respond(URLDecoder.decode(txt,"UTF-8"));
      }
    }
 catch (    UnsupportedEncodingException e) {
      logger.error(e);
    }
  }
 else   if (segments.length == 1) {
    String cmd=segments[0];
    if (cmd.equals("!urlencode") || cmd.equals("!urldecode"))     event.respond("!urlencode [url] ??? !urldecode [url]");
  }
}
 

Example 138

From project maven-shared, under directory /file-management/src/test/java/org/apache/maven/shared/model/fileset/util/.

Source file: FileSetUtilsTest.java

  15 
vote

/** 
 * @param directoryName
 * @return
 * @throws IOException
 */
private File setupTestDirectory(String directoryName) throws IOException {
  System.out.println("Setting up directory for test: " + directoryName);
  URL sourceResource=getClass().getClassLoader().getResource(directoryName);
  if (sourceResource == null) {
    Assert.fail("Source directory for test: " + directoryName + " cannot be found.");
  }
  File sourceDir=new File(URLDecoder.decode(sourceResource.getPath(),"UTF-8"));
  String basedir=System.getProperty("basedir",System.getProperty("user.dir"));
  String testBase=System.getProperty("testBase","target/test-directories");
  File testDir=new File(basedir,testBase + "/" + directoryName);
  testDir.mkdirs();
  FileUtils.copyDirectoryStructure(sourceDir,testDir);
  testDirectories.add(testDir);
  return testDir;
}
 

Example 139

From project maven-wagon, under directory /wagon-provider-test/src/main/java/org/apache/maven/wagon/http/.

Source file: HttpWagonTestCase.java

  15 
vote

public void handle(String target,HttpServletRequest request,HttpServletResponse response,int dispatch) throws IOException, ServletException {
  Request base_request=request instanceof Request ? (Request)request : HttpConnection.getCurrentConnection().getRequest();
  if (base_request.isHandled() || !"PUT".equals(base_request.getMethod())) {
    return;
  }
  base_request.setHandled(true);
  File file=new File(resourceBase,URLDecoder.decode(request.getPathInfo()));
  file.getParentFile().mkdirs();
  FileOutputStream out=new FileOutputStream(file);
  ServletInputStream in=request.getInputStream();
  try {
    IOUtil.copy(in,out);
  }
  finally {
    in.close();
    out.close();
  }
  putCallNumber++;
  DeployedResource deployedResource=new DeployedResource();
  deployedResource.httpMethod=request.getMethod();
  deployedResource.requestUri=request.getRequestURI();
  deployedResource.transferEncoding=request.getHeader("Transfer-Encoding");
  deployedResource.contentLength=request.getHeader("Content-Length");
  deployedResources.add(deployedResource);
  response.setStatus(HttpServletResponse.SC_CREATED);
  handlerRequestResponses.add(new HandlerRequestResponse(request.getMethod(),((Response)response).getStatus(),request.getRequestURI()));
}