output and actual url is different shown in navigation compare to console - java

currently I'm facing an issue where the URL that are outputted in the console is different from the actual URL display in the nav bar. I look at the value that I had regex, it was correct but when put into IE, it is different. The URL in the nav bar would be only a=test instead of a=test&c=import&f=&uid=user1 which is what is shown in the console. May I know how to solve this? Thanks.
Here is the codes for it.
UserID user = new UserID();
public static void main(String[] args) {
String newUrl = replaceUserID(url);
System.out.print("cmd.exe /c start iexplore -k " + newUrl);
try{
Process p = Runtime.getRuntime().exec("cmd.exe /c start iexplore " + newUrl);
try{
p.waitFor();
}
catch( InterruptedException ie ){
System.out.println("InterruptedException " + ie.getMessage());
}
InputStream err = p.getErrorStream();
int ctr = 0;
if ( (ctr = err.available()) > 0 ){
byte[] buf = new byte[ctr];
System.out.println("Process failed with error:\n" + new String(buf, 0, ctr));
}
}
catch(IOException ioe)
{
System.out.println("InterruptedException " + ioe.getMessage());
}
}
public static String checkUserID(){
String username = System.getenv("USERNAME"); //grab user login id for windows
return username;
}
public static String replaceUserID(String oldUrl) {
String params = "http://example.com?a=test&c=import&f=&uid=userid";
String username = checkUserID();
try {
Pattern p = Pattern.compile("uid=([^&%]+)");
Matcher m = p.matcher(params);
while (m.find()) {
// System.out.println(m.group(1).toString());
if(m.group(1).toString() != username) {
//replace url paremeters with correct userID.
String newUrl = params.replace(m.group(1).toString(), username);
return newUrl;
}
else {
System.out.println("The username is the same");
return params;
}
}
} catch (PatternSyntaxException ex) {
// error handling
ex.printStackTrace();
}
return oldUrl;
}

& has a special meaning to the command line (concat commands, see here: How do I run two commands in one line in Windows CMD?).
You need to escape the url or maybe the entire command. If I remember correctly you need to put double quotes around it: "...iexplore -k \"" + newUrl + "\""

Related

Is it possible to write a generic interactive ProcessBuilder client based on commands and breakpoints as input?

I need to write a generic interactive ProcessBuilder client based on commands and breakpoints to interact with the same python script several times.
The idea is that each (n+1) command (except n=0 ofc) will wait to read in the output stream the (n-1) breakpoint.
The client's output will be the output stream from the first command to the last one.
Ex of script:
def show_menu():
print('Select an option:' + '\n')
print('[1] Fullname')
print('[2] Username')
print('[3] Password')
def app_start():
show_menu()
try:
choice = int(input('\n' + 'Your selection: '))
app_start()
except KeyboardInterrupt:
sys.exit(0)
else:
if choice == 1:
input = input("Enter your fullname")
print(f'Your fullname is: {input}')
if choice == 2:
input = input("Enter your Username")
print(f'Your username is: {input}')
if choice == 3:
input = input("Enter your password: ")
print(f'Your password is : {input}')
def main():
app_start()
# Start Here
if __name__ == "__main__":
main()
Example of input to the Process builder client:
[
{
"cmd": "python3 C:\\pathToScript\\script.py",
"breakpoint": "Your selection:"
},
{
"cmd": "3\n",
"breakpoint": "Enter your password: "
},
{
"cmd": "John Doe\n",
"breakpoint": "Your password is: "
}
]
The Output of the client for this case will be:
[1] Fullname
[2] Username
[3] Password
Your selection: 3
Enter your password password123
Your password is: password123
Thanks in advance for any help, I'm new to Java and newer to ProcessBuilder :).
This seems to be working just fine, putting the thread to sleep for 100 ms is prob only a good idea for scripts that don't take long to execute though. If anyone sees caveats on this approach please feel free to leave a comment.
String actionCommands = "[\n" +
" {\n" +
" \"cmd\": \"python3 C:\\pathToScript\\script.py\" +
" \"breakpoint\": \"Your selection:\"\n" +
" },\n" +
" {\n" +
" \"cmd\": \"3\\n\",\n" +
" \"breakpoint\": \"Enter your password:\"\n" +
" },\n" +
" {\n" +
" \"cmd\": \"password123\\n\",\n" +
" \"breakpoint\": \"Your password is: \"\n" +
" }\n" +
" ]";
org.json.JSONArray arrayCmds = new org.json.JSONArray(actionCommands);
System.out.printf("arrayCmds %s\n", arrayCmds.toString());
Process process = null;
org.json.JSONObject objInit = arrayCmds.getJSONObject(0);
String cmdInit = objInit.getString("cmd");
ProcessBuilder processBuilder1 = new ProcessBuilder(cmdInit.split(" "));
processBuilder1.redirectErrorStream(true);
try {
process = processBuilder1.start();
Thread inThread = new Thread((Runnable) new In(process.getInputStream()));
inThread.start();
processBuilder1.inheritIO();
BufferedReader inputStream = new BufferedReader(new InputStreamReader(process.getInputStream()));
BufferedReader errStream = new BufferedReader(new InputStreamReader(process.getErrorStream()));
OutputStream writeTo = process.getOutputStream();
for (int i = 1 ; i < arrayCmds.length(); i++) {
org.json.JSONObject obj = arrayCmds.getJSONObject(i);
org.json.JSONObject objBrkPt = arrayCmds.getJSONObject(i-1);
String cmd = obj.getString("cmd");
String breakpoint = objBrkPt.getString("breakpoint");
Thread.sleep(100);
while (((inputStream.readLine())!=null && inputStream.readLine()!=breakpoint))
{
writeTo.write(cmd.getBytes());
writeTo.flush();
break;
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
This is the implementation of the In class
public class In implements Runnable {
private InputStream is;
private List<String> out = new ArrayList<String>();
public In(InputStream is) {
this.is = is;
}
public List<String> output() {
return out;
}
#Override
public void run() {
byte[] b = new byte[1024];
int size = 0;
try {
while ((size = is.read(b)) != -1) {
out.add(new String(b));
System.err.println(new String(b));
}
is.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
there is something wront with implementation as it fails randomly in capturing the last part of the stream that contains the pwd

Runtime.exec() the executable library not work in non root

i have a code :
private static String writeCommandToConsole(Process proc, String command, boolean ignoreError) throws Exception {
byte[] tmpArray = new byte[1024];
proc.getOutputStream().write((command + "\n").getBytes());
proc.getOutputStream().flush();
int bytesRead;
if (proc.getErrorStream().available() > 0) {
if ((bytesRead = proc.getErrorStream().read(tmpArray)) > 1) {
Log.e(LOG_TAG, new String(tmpArray, 0, bytesRead));
if (!ignoreError)
throw new Exception(new String(tmpArray, 0, bytesRead));
}
}
if (proc.getInputStream().available() > 0) {
bytesRead = proc.getInputStream().read(tmpArray);
Log.i(LOG_TAG, new String(tmpArray, 0, bytesRead));
}
return new String(tmpArray);
}
public static void Changes(Context con, int fNums, String fNames, int is, boolean bools, String strs) {
final String fNum = String.valueOf(fNums);
final String fName = fNames;
final String i = String.valueOf(is);
final String str = strs;
final String bool = bools ? "true" : "false";
final String path = pathExecutable + " " + fNum + " \"" + fName + "\" " + i + " " + bool + " \"" + str + "\"";
new Thread(new Runnable() {
#Override
public void run() {
try {
if (isRoot) {
Process proc = Runtime.getRuntime().exec(new String[]{"su"});
writeCommandToConsole(proc, path, true);
} else {
Process proc = Runtime.getRuntime().exec(path);
proc.wait();
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}).start();
}
for root is work well (my phone is rooted) .. but for non root it not work (use parallel space, virtualXposed,etc in non root phone) .. in non root only work in virtual machine which have a root (vmos,x8 sabdbox etc).
i was try use processBuilder but have a same result .. executable lib seem not get into the target ..
how to write a correct runtime.exec to make it work on non root phone (use parallel space or any cloner without virtual machine with root include) ? or is it any way to make it posible to run executable lib without su command ?
solved .. i change non root command into
Process proc = Runtime.getRuntime().exec(new String[]{"sh"});
writeCommandToConsole(proc, path, true);
and it run well in some virtual app ..

Reading text between quotation marks

Here's a piece of text I'm trying to work with:
lat="52.336575" lon="6.381008">< time>2016-12-19T12:12:27Z< /time>< name>Foto 8 </name>< desc>Dag 4 E&F
Geb 1.4
Hakhoutstoof < /desc>< /wpt>
I'm trying to extract the coördinates between the "" and put the values between the "" into a string, but I can't get it to work...
Here's my code (so far):
public void openFile() {
Chooser = new JFileChooser("C:\\Users\\danie\\Desktop\\");
Chooser.setAcceptAllFileFilterUsed(false);
Chooser.setDialogTitle("Open file");
Chooser.addChoosableFileFilter(new FileNameExtensionFilter("*.gpx",
"gpx"));
int returnVal = Chooser.showOpenDialog(null);
try {
Dummy = new Scanner(Chooser.getSelectedFile());
} catch (FileNotFoundException E) {
System.out.println("Error: " + E);
}
}
public void createDummy() {
Dummy.useDelimiter("<wpt");
if (Dummy.hasNext()) {
String Meta = Dummy.next();
}
Dummy.useDelimiter("\\s[<wpt]\\s|\\s[</wpt>]\\s");
try {
while (Dummy.hasNext()) {
String Test = Dummy.next();
DummyFile = new File("Dummy.txt");
Output = new PrintWriter(DummyFile);
Output.print(Test);
Output.println();
Output.flush();
Output.close();
}
Reader = new FileReader(DummyFile);
Buffer = new BufferedReader(Reader);
TestFile = new File("C:\\Users\\danie\\Desktop\\Test.txt");
Writer = new PrintWriter(TestFile);
String Final;
while ((Final = Buffer.readLine()) != null) {
String WPTS[] = Final.split("<wpt");
for (String STD:WPTS) {
Writer.println(STD);
Writer.flush();
Writer.close();
}
}
} catch (IOException EXE) {
System.out.println("Error: " + EXE);
}
Dummy.close();
}
}
I'm really new to Java :(
I think the following code will do the trick ...
the "string" is only used to test the regex
final String string = "lat=\"52.336575\" lon=\"6.381008\">< time>2016-12-19T12:12:27Z< /time>< name>Foto 8 </name>< desc>Dag 4 E&F \nGeb 1.4 \n" + "Hakhoutstoof < /desc>< /wpt>";
final String latitudeRegex = "(?<=lat=\")[0-9]+\\.[0-9]*";
final Pattern latitudePattern = Pattern.compile(latitudeRegex);
final Matcher latitudeMatcher = latitudePattern.matcher(string);
//finds the next (in this case first) subsequence matching the given regex
latitudeMatcher.find();
String latitudeString = latitudeMatcher.group();
double lat = Double.parseDouble(latitudeString); //group returns the match matched by previous match
System.out.println("lat: " + lat);
to get the longitude, just replace lat by lon in the regex
this site is very useful for creating a regex
https://regex101.com/
you can even create the java code at this site

How to Execute Batch File Remotely in java?

I have to execute batch file present at remote machine from my local machine.
I am connecting through ftp to remote machine and try to execute batch file remotely.but not able to do that also not getiing any exception .below is my code
public static void main(String[] args) throws SocketException, IOException,
InterruptedException {
static String server = "192.168.2.133";
static int port = 21;
static String user = "kamal";
static String pass = "12345";
static FTPClient ftpClient;
// TODO Auto-generated method stub
ftpClient = new FTPClient();
ftpClient.connect(server, port);
ftpClient.login(user, pass);
ftpClient.enterLocalPassiveMode();
ftpClient.changeWorkingDirectory("/");
System.out.println(ftpClient.isConnected());
// ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
System.out.println("ftpClient.printWorkingDirectory() "
+ ftpClient.printWorkingDirectory());
String[] str = ftpClient.listNames(ftpClient.printWorkingDirectory());
for (String string : str) {
System.out.println(string);
}
// ftpClient.changeWorkingDirectory(ftpClient.printWorkingDirectory().concat("demo"));
System.out.println("ftpClient.printWorkingDirectory() "
+ ftpClient.printWorkingDirectory());
String psCommand = "C:/Users/kamlesh.kumar/Downloads/PSTools/PsExec.exe //"
+ server + " -u " + user + " -p " + pass;
psCommand = psCommand + " " + "MEF.bat";
// psCommand = psCommand + " " + commandToRunOnRemoteMachine + " " +
// parameters;
String[] cmd = new String[5];
cmd[0] = "cmd.exe";
cmd[1] = "/C";
cmd[2] = psCommand;
cmd[3] = "";
cmd[4] = "";
// Run remote command
// ftpClient.changeWorkingDirectory(ftpClient.printWorkingDirectory().concat("\\\\192.168.2.135\\demo\\demo"));
// System.out.println(ftpClient.printWorkingDirectory());
File f = new File(ftpClient.printWorkingDirectory());
Process p = null;
try {
p = Runtime.getRuntime().exec(cmd, null, f);
} catch (Exception e) {
System.out.println(e.toString());
e.printStackTrace();
}
int exitStatus = 0;
try {
exitStatus = p.waitFor();
System.out.println("exitStatus in try " + exitStatus);
} catch (Exception e) {
System.out.println("exitStatus" + exitStatus);
System.out.println(e.toString());
e.printStackTrace();
} finally {
System.out.println("exitStatus in finally " + exitStatus);
}
if (exitStatus == 0) {
System.out.println("Done");
}
}
You can get PSEXEC from https://technet.microsoft.com/en-us/sysinternals/pxexec.aspx and what I have done before was make a batch file that would copy the file you want ran on the remote pc to that PC then use PSEXEC to execute it remotly and also delete that file that was made. I do not know if that is what you're looking for but it might be sufficient.
set remotecpu="computer you're sending it to"
robocopy "localpcdrive\location1\scripts\script you want ran" \\%remotecpu%\c$\temp_folder
psexec \\%remotecpu% -u "username" -p "password" -i -d "C:\temp_folder\path to\script you want ran"
And if I am not mistaken that will execute the file for you then just do a del command and remove the temp_folder your script is under. Or use something fancy like
If Exist "%SystemDrive%\temp_folder" (RD/S/Q "%SystemDrive%\temp_folder")

How to find closer maven repository close to my home

I am wondering how to find the maven repository close to my home?
Actually, the listing at http://docs.codehaus.org/display/MAVENUSER/Mirrors+Repositories is problematic. Is Central in San Francisco, California or in St. Louis, Missouri? (I guess this is an inadvertent lesson on why code, or even xml, should not be commented). To make things more confusing, the owner of the domain (according to http://whois.net/whois/maven.org) is in Fulton, MD.
Maybe the question was not "Where are the repositories?" (which esaj answered), but really:
"How can I find the maven repository closest to my home?"
That question bugged me, too.
On the other hand, does it really matter, given how fast packets travel across the world?
But it still bugged me.
There are two ways to find out which host is the closest:
Open a browser, go to http://freegeoip.net, and type in the hostname. If you know where you are, then you can go to GoogleMaps, get directions, and check the distance.
Open a terminal window, and ping the hostname to find the average round trip transit time in milliseconds. This will give you the electronic distance, which is really more important for file transfer times.
Repeat for each hostname (i.e. about 40 times, if you're looking at the download sites for Maven itself)
Sort by the distance measured by the GoogleMaps directions, or by the transit time.
For 40 hosts you could probably do that manually in 20 tedious minutes, but a true professional would rather spend a few hours writing the Selenium and java code that could do it in 5 minutes.
In my copious amounts of spare time, I threw together only half the job (i.e. no Selenium):
public class ClosestUrlFinder {
/**
* Find out where a hostname is.
* Adapted from http://www.mkyong.com/java/how-to-send-http-request-getpost-in-java/
* Send HTTP GET requests to: freegeoip.net/{format}/{ip_or_hostname}
* The API supports both HTTP and HTTPS.
* Supported formats are csv, xml or json.
* E.G. http://freegeoip.net/xml/www.poolsaboveground.com
* returns <Response><Ip>207.58.184.93</Ip><CountryCode>US</CountryCode>
* <CountryName>United States</CountryName><RegionCode>VA</RegionCode><RegionName>Virginia</RegionName>
* <City>Mclean</City><ZipCode>22101</ZipCode>
* <Latitude>38.9358</Latitude><Longitude>-77.1621</Longitude>
* <MetroCode>511</MetroCode><AreaCode>703</AreaCode></Response>
* #param urlOrHostname
* #return
*/
public String getUrlLocation(String urlOrHostname) {
String USER_AGENT = "Mozilla/5.0";
BufferedReader in = null;
URL urlObject;
StringBuilder response = null;
try {
urlObject = new URL("http://freegeoip.net/xml/" + urlOrHostname);
HttpURLConnection connection = (HttpURLConnection) urlObject.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("User-Agent", USER_AGENT);
int responseCode = connection.getResponseCode();
System.out.println("\nSending 'GET' request to URL : " + urlOrHostname);
System.out.println("Response Code : " + responseCode);
in = new BufferedReader( new InputStreamReader(connection.getInputStream()));
String inputLine;
response = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (in != null) {
try { in.close(); }
catch (IOException e) {
e.printStackTrace();
}
}
}
//System.out.println(response.toString());
return response.toString();
}
/*
* Fixed version of code from http://stackoverflow.com/questions/11506321/java-code-to-ping-an-ip-address
*/
public String runDosCommand(List<String> command)
{
String string = "", result = "";
ProcessBuilder pBuilder = new ProcessBuilder(command);
Process process;
try {
process = pBuilder.start();
BufferedReader stdInput = new BufferedReader(new InputStreamReader(process.getInputStream()));
BufferedReader stdError = new BufferedReader(new InputStreamReader(process.getErrorStream()));
//System.out.println("Standard output of the command:");
while ((string = stdInput.readLine()) != null)
{
System.out.println(string);
result = result + "\n" + string;
}
while ((string = stdError.readLine()) != null)
{
System.out.println("stdError: "+ string);
result = result + "\nstdError: " + string;
}
} catch (IOException e) {
System.out.println("Error with command "+command);
e.printStackTrace();
}
return result;
}
public String pingUrl(String url) {
List<String> command = new ArrayList<String>();
String averagePingTime = "0", geoText = "", loss = "";
command.add("ping");
command.add("-n");
command.add("2");
url = url.replace("ftp://", "");
url = Utils.first(url.replace("/", " "));
url = Utils.first(url.replace(":", " "));
command.add(url);
System.out.println("command is: "+command);
String pingResult = runDosCommand(command);
String timeoutString = "Request timed out";
String timeout = Utils.grep(timeoutString, pingResult);
String noHostString = "Ping request could not find host";
String noHost = Utils.grep(noHostString, pingResult);
String unreachableString = "Destination net unreachable";
String unreachable = Utils.grep(unreachableString, pingResult);
if (Utils.isNullOrEmptyString(timeout) && Utils.isNullOrEmptyString(noHost)
&& Utils.isNullOrEmptyString(unreachable)) {
String lostString = "Lost =";
loss = Utils.grep(lostString, pingResult);
int index = loss.indexOf(lostString);
loss = loss.substring(index);
if (!loss.equals("Lost = 0 (0% loss),")) {
System.out.println("Non-zero loss for " + url);
averagePingTime = "0";
} else {
String replyString = "Reply from";
String replyFrom = Utils.grep(replyString, pingResult);
String ipAddress = Utils.nth(replyFrom, 3);
System.out.println("reply Ip="+ipAddress.replace(":", ""));
String averageString = "Average =";
averagePingTime = Utils.grep(averageString, pingResult);
index = averagePingTime.indexOf(averageString);
averagePingTime = averagePingTime.substring(index);
averagePingTime = Utils.last(averagePingTime).replace("ms", "");
String xml = getUrlLocation(url);
//System.out.println("xml="+xml);
geoText = extractTextFromXML(xml);
System.out.println("geoText="+geoText);
}
} else {
averagePingTime = "0";
System.out.println("Error. Either could not find host, Request timed out, or unreachable network for " + url);;
}
System.out.println("Results for " + url + " are: " + loss + " " + averagePingTime + " miliseconds.");
return url + " " + averagePingTime + " " + geoText ;
}
public ArrayList<Entry<String,Integer>> pingManyUrls() {
ArrayList<Entry<String,Integer>> mirrorTimeList = new ArrayList<>();
String[] urls = Utils.readTextFile("resources/MavenUrls.txt").split("\\s+");
System.out.println("Start pingManyUrls with "+urls.length + " urls.");
for (String url : urls) {
url = url.trim();
System.out.println("************************************\npingManyUrls: Check Url " + url);
if (arrayListContainsKey(url, mirrorTimeList)) {
System.out.println("Key " + url + " already in array.");
} else {
String pingInfo = pingUrl(url);
String averagePingString = Utils.nth(pingInfo, 2);
if (!averagePingString.equals("0")) {
int averagePingMilliseconds = Integer.parseInt(averagePingString);
pingInfo = Utils.rest(pingInfo); //chop the first term (the url)
pingInfo = Utils.rest(pingInfo); // chop the 2nd term (the time)
url = url + " " + pingInfo;
System.out.println(" Adding Key " + url + " " + averagePingMilliseconds + " to array.");
Entry<String,Integer> urlTimePair = new java.util.AbstractMap.SimpleEntry<>(url, averagePingMilliseconds);
mirrorTimeList.add(urlTimePair);
} else { System.out.println("Url " + url + " has a problem and therefore will be not be included."); }
}
}
Collections.sort(mirrorTimeList, new Comparator<Entry<String,Integer>>() {
#Override
public int compare (Entry<String,Integer> pair1, Entry<String,Integer> pair2) {
return pair1.getValue().compareTo(pair2.getValue());
}
});
return mirrorTimeList;
}
public boolean arrayListContainsKey(String key, ArrayList<Entry<String,Integer>> arrayList) {
for (Entry<String,Integer> keyValuePair : arrayList) {
//System.out.println(keyValuePair.getKey() + " =? " + key);
if (key.equalsIgnoreCase(keyValuePair.getKey())) { return true; }
}
return false;
}
public String extractFirstTagContents(Element parentElement, String tagname) {
NodeList list = parentElement.getElementsByTagName(tagname);
if (list != null && list.getLength()>0) {
String contents = list.item(0).getTextContent();
System.out.println("Tagname=" + tagname + " contents="+contents);
return contents;
}
return "";
}
public String extractTextFromXML(String xml) {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder;
String content = "";
try {
builder = factory.newDocumentBuilder();
Document document = builder.parse(new InputSource(new StringReader(xml)));
Element rootElement = document.getDocumentElement();
content = rootElement.getTextContent();
//System.out.println("content="+content);
// String city = extractFirstTagContents(rootElement, "City");
// String state = extractFirstTagContents(rootElement, "RegionName");
// String zipCode = extractFirstTagContents(rootElement, "ZipCode");
// String country = extractFirstTagContents(rootElement, "CountryName");
// String latitude = extractFirstTagContents(rootElement, "Latitude");
// String longitude = extractFirstTagContents(rootElement, "Longitude");
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SAXException saxex) {
// TODO Auto-generated catch block
saxex.printStackTrace();
} catch (IOException ioex) {
// TODO Auto-generated catch block
ioex.printStackTrace();
}
return content;
}
public static void main(String[] args) {
System.out.println("Starting ClosestUrlFinder");
ClosestUrlFinder ping = new ClosestUrlFinder();
ArrayList<Entry<String,Integer>> mirrorList = ping.pingManyUrls();
System.out.println("Final Results, sorted by trip travel time (out of "+mirrorList.size()+" successful pings).");
for (Entry<String,Integer> urlTime : mirrorList) {
System.out.println(urlTime.getKey() + " " + urlTime.getValue());
}
}
} // End of Class
Where the data in MavenUrls.txt is:
apache.claz.org
apache.cs.utah.edu
apache.mesi.com.ar
apache.mirrors.hoobly.com
apache.mirrors.lucidnetworks.net
apache.mirrors.pair.com
apache.mirrors.tds.net
apache.osuosl.org
apache.petsads.us
apache.spinellicreations.com
apache.tradebit.com
download.nextag.com
ftp.osuosl.org
ftp://mirror.reverse.net/pub/apache/
mirror.cc.columbia.edu/pub/software/apache/
mirror.cogentco.com/pub/apache/
mirror.metrocast.net/apache/
mirror.nexcess.net/apache/
mirror.olnevhost.net/pub/apache/
mirror.reverse.net/pub/apache/
mirror.sdunix.com/apache/
mirror.symnds.com/software/Apache/
mirror.tcpdiag.net/apache/
mirrors.gigenet.com/apache/
mirrors.ibiblio.org/apache/
mirrors.sonic.net/apache/
psg.mtu.edu/pub/apache/
supergsego.com/apache/
www.bizdirusa.com
www.bizdirusa.com/mirrors/apache/
www.carfab.com/apachesoftware/
www.dsgnwrld.com/am/
www.eng.lsu.edu/mirrors/apache/
www.gtlib.gatech.edu/pub/apache/
www.interior-dsgn.com/apache/
www.motorlogy.com/apache/
www.picotopia.org/apache/
www.poolsaboveground.com/apache/
www.trieuvan.com/apache/
www.webhostingjams.com/mirror/apache/
And my Utils class includes the following:
/**
* Given a string of words separated by spaces, returns the first word.
* #param string
* #return
*/
public static String first(String string) {
if (isNullOrEmptyString(string)) { return ""; }
string = string.trim();
int index = string.indexOf(" "); //TODO: shouldn't this be "\\s+" to handle double spaces and tabs? That means regexp version of indexOf
if (index<0) { return string; }
return string.substring(0, index);
}
/**
* Given a string of words separated by spaces, returns the rest of the string after the first word.
* #param string
* #return
*/
public static String rest(String string) {
if (isNullOrEmptyString(string)) { return ""; }
string = string.trim();
int index = string.indexOf(" "); //TODO: shouldn't this be "\\s+" to handle double spaces and tabs? That means regexp version of indexOf
if (index<0) { return ""; }
return string.substring(index+1);
}
public static String grep(String regexp, String multiLineStringToSearch) {
String result = "";
//System.out.println("grep for '"+ regexp + "'");
String[] lines = multiLineStringToSearch.split("\\n");
//System.out.println("grep input string contains "+ lines.length + " lines.");
Pattern pattern = Pattern.compile(regexp);
for (String line : lines) {
Matcher matcher = pattern.matcher(line);
if (matcher.find()) {
//System.out.println("grep found match="+ line);
result = result + "\n" + line;
}
}
return result.trim();
}
/**
* Given the path and name of a plain text (ascii) file,
* reads it and returns the contents as a string.
* #param filePath
* #return
*/
public static String readTextFile(String filePath) {
BufferedReader reader;
String result = "";
int counter = 0;
try {
reader = new BufferedReader(new FileReader(filePath));
String line = "";
StringBuilder stringBuilder = new StringBuilder();
String lineSeparator = System.getProperty("line.separator");
while ((line = reader.readLine()) != null) {
counter = counter + 1;
stringBuilder.append(line);
stringBuilder.append(lineSeparator);
}
reader.close();
result = stringBuilder.toString();
logger.info("readTextFile: Read "+filePath+" with "+ counter + " lines, "+result.length()+" characters.");
return result;
} catch (FileNotFoundException e) {
logger.fatal("readTextFile: Could not find file "+filePath+".");
e.printStackTrace();
} catch (IOException e) {
logger.fatal("readTextFile: Could not read file "+filePath+".");
e.printStackTrace();
}
return "";
}
public static boolean isNullOrEmptyString(String s) {
return (s==null || s.equals(""));
}
/**
* Given a string of words separated by one or more whitespaces, returns the Nth word.
* #param string
* #return
*/
public static String nth(String string, int n) {
string = string.trim();
String[] splitstring = string.split("\\s+");
String result = "";
if (splitstring.length<n) { return ""; }
else {
result = splitstring[n - 1];
}
return result.trim();
}
/**
* Given a string of words separated by spaces, returns the last word.
* #param string
* #return
*/
public static String last(String string) {
return string.substring(string.trim().lastIndexOf(" ")+1, string.trim().length());
}
Enjoy!
Here's there official central repository mirror listing (as xml-file) and here's another list of central repository mirrors.

Categories