BrightSide Workbench Full Report + Source Code
URLUtil.java
Go to the documentation of this file.
1 /*
2  * TurrĂ³ i Cutiller Foundation. License notice.
3  * Copyright (C) 2015 Lluis TurrĂ³ Cutiller <http://www.turro.org/>
4  *
5  * This program is free software: you can redistribute it and/or modify
6  * it under the terms of the GNU Affero General Public License as published by
7  * the Free Software Foundation, either version 3 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13  * GNU Affero General Public License for more details.
14  *
15  * You should have received a copy of the GNU Affero General Public License
16  * along with this program. If not, see <http://www.gnu.org/licenses/>.
17  */
18 
19 package org.turro.http;
20 
21 import java.net.MalformedURLException;
22 import java.net.URI;
23 import java.net.URISyntaxException;
24 import java.net.URL;
25 import java.util.logging.Level;
26 import java.util.logging.Logger;
27 import org.turro.string.Strings;
28 import org.apache.hc.core5.net.URIBuilder;
29 import org.turro.elephant.context.ElephantContext;
30 
35 public class URLUtil {
36 
37  public static String checkAppServer(String server, boolean secured) {
38  try {
39  URIBuilder url = new URIBuilder(server);
40  if(url.getScheme() == null) {
41  if(secured) url.setScheme("https"); else url.setScheme("http");
42  }
43  if(url.getHost() == null) {
44  String[] path = splitPath(url.getPath());
45  url.setHost(path[0]);
46  if(path.length > 1) {
47  url.setPath("/" + path[1]);
48  } else {
49  url.setPath(null);
50  }
51  } else {
52  String[] path = splitPath(url.getPath());
53  if(path != null && path.length > 0) {
54  url.setPath("/" + path[0]);
55  } else {
56  url.setPath(null);
57  }
58  }
59  url.removeQuery();
60  return url.build().toString();
61  } catch (URISyntaxException ex) {
62  Logger.getLogger(URLUtil.class.getName()).log(Level.SEVERE, ElephantContext.logMsg(null), ex);
63  return null;
64  }
65  }
66 
67  public static String[] splitPath(String path) {
68  if(!Strings.isBlank(path)) {
69  path = path.replaceFirst("^[\\/ ]+", "");
70  path = path.replaceFirst("[\\/ ]+$", "");
71  return path.split("\\/");
72  } else {
73  return null;
74  }
75  }
76 
77  public static String absolute(String appServer, String path) throws URISyntaxException, MalformedURLException {
78  URI url = new URI(path);
79  if(url.isAbsolute()) {
80  return path;
81  } else {
82  return new URL(new URL(appServer), path).toString();
83  }
84  }
85 
86 }
static String absolute(String appServer, String path)
Definition: URLUtil.java:77
static String[] splitPath(String path)
Definition: URLUtil.java:67
static String checkAppServer(String server, boolean secured)
Definition: URLUtil.java:37