How can I split a flat string based on 0102**? string tokenizer is working for only **. Is there any way to split based on 0102**? Please suggest
Here is my complete method
private String handleCibil(InterfaceRequestVO ifmReqDto, String szExtIntType) throws MalformedURLException, org.apache.axis.AxisFault, RemoteException {
/* Declaration and initiliazation */
ConfVO confvo = ifmReqDto.getExtConfVo();
String szResponse = null;
String cibilResponse = null;
String errorResponse = null;
String endpointURL = null;
long timeOut = confvo.getBurMgr().getBurInfo(szExtIntType).getTimeOut();
endpointURL = formWebServiceURL(confvo, szExtIntType);
URL url = new URL(endpointURL);
log.debug("Input xml for cibil "+ifmReqDto.getIfmReqXML());
BasicHttpStub stub= new BasicHttpStub(url,new org.apache.axis.client.Service());
szResponse = stub.executeXMLString(ifmReqDto.getIfmReqXML());
//szResponse=szResponse.replaceAll("&", "&");
log.debug("szResponse "+szResponse);
/* Validate if the obtained response is as expected by IFM */
try {
extDao = new ExtInterfaceXMLTransDAO(ifmReqDto.getSemCallNo(), ifmReqDto.getIdService());
extDao.updateRqstRespXML10g(ifmReqDto.getInterfaceReqNum(), szResponse, GGIConstants.IFM_RESPONSE);
//log.debug("CIBIL_RESPONSE_XPATH " + GGIConstants.CIBIL_RESPONSE_XPATH);
Document xmlDocument = DocumentHelper.parseText(szResponse);
String xPath = GGIConstants.RESPONSE_XPATH;
List<Node> nodes = xmlDocument.selectNodes(xPath);
for (Node node : nodes) {
String keyValue = node.valueOf(GGIConstants.RESPONSE_XPATH_KEY);
// log.debug("keyValue : " + keyValue);
if (keyValue.equalsIgnoreCase(GGIConstants.RESPONSE_XPATH_KEY_VALUE)) {
// log.debug("node value : " + node.getText());
cibilResponse = node.getText();
}
}
log.debug("cibilResponse " + cibilResponse);
String errorResponseXPATH = GGIConstants.CIBIL_ERROR_RESPONSE_XPATH;
List<Node> errorResponseNode = xmlDocument.selectNodes(errorResponseXPATH);
for (Node node : errorResponseNode) {
errorResponse = node.getText();
}
log.debug("errorResponse " + errorResponse);
if(cibilResponse!=null && cibilResponse.length()>0)
{
StringTokenizer cibilResponseResults = new StringTokenizer(cibilResponse,"**");
String tempResponse="";
ArrayList probableMatchList = new ArrayList();
while (cibilResponseResults.hasMoreElements()) {
tempResponse = (String) cibilResponseResults.nextElement();
if(tempResponse.length()>=80)
{
String memberRefNo = tempResponse.substring(69, 80).replaceAll(" ", "");
log.debug("memberRefNo " + memberRefNo);
if (memberRefNo.length() > 0) {
if (Integer.parseInt(memberRefNo) > 0) {
cibilResponse = tempResponse;
cibilResponse = cibilResponse+"**";
}
else
{
probableMatchList.add(tempResponse+"**");
}
}
else
{
probableMatchList.add(tempResponse+"**");
}
}
else
{
cibilResponse = tempResponse+"**";
}
}
log.debug("After finding the Member reference number cibilResponse " + cibilResponse);
log.debug("After finding the Probable reference list " + probableMatchList);
// TKN 008
cibilResponse=StringEscapeUtils.unescapeXml(cibilResponse).replaceAll("[^\\x20-\\x7e]","");
ifmReqDto.setIfmTransformedResult(cibilResponse);
ifmReqDto.setProbableMatchList(probableMatchList);
}
if (errorResponse!=null && errorResponse.length()>0) {
throw new GenericInterfaceException(errorResponse
+ " for the seq_request " + ifmReqDto.getSeqRequest() + " Seq_Interface_req is >> "
+ ifmReqDto.getInterfaceReqNum(),
GGIConstants.SEND_REQUEST_CONSTANT + Strings.padStart(String.valueOf(ifmReqDto.getIdService()), 2, GGIConstants.DEFAULT_NUMBER_STRING)
+ GGIConstants.CIBIL_ERROR_CODE);
}
else if (cibilResponse==null || StringUtils.isEmpty(cibilResponse) ) {
throw new GenericInterfaceException("Cibil TUEF response is empty >> cibil Service "
+ "for the seq_request " + ifmReqDto.getSeqRequest() + "Seq_Interface_req is >> "
+ ifmReqDto.getInterfaceReqNum(),
GGIConstants.SEND_REQUEST_CONSTANT + Strings.padStart(String.valueOf(ifmReqDto.getIdService()), 2, GGIConstants.DEFAULT_NUMBER_STRING)
+ GGIConstants.INTERFACE_ERROR_RESPONSE);
}
/* Setting Instinct response to ifmReqDto object */
} catch (SQLException e) {
log.error("SQLException while connecting to DataBase. Exception message is ", e);
throw new GenericInterfaceException("SQLException >> Instinct Service "
+ "for the seq_request " + ifmReqDto.getSeqRequest() + "Seq_Interface_req is >> "
+ ifmReqDto.getInterfaceReqNum(),
GGIConstants.SEND_REQUEST_CONSTANT + Strings.padStart(String.valueOf(ifmReqDto.getIdService()), 2, GGIConstants.DEFAULT_NUMBER_STRING)
+ GGIConstants.DB_OPERATION_ERROR);
} catch (GenericInterfaceException exp) {
log.error("Exception occured while valid:", exp);
throw exp;
} catch (Exception exp) {
log.error("Exception occured while valid:", exp);
throw new GenericInterfaceException("GeneralException >> Instinct Service "
+ "for the seq_request " + ifmReqDto.getSeqRequest() + "Seq_Interface_req is >> "
+ ifmReqDto.getInterfaceReqNum(),
GGIConstants.SEND_REQUEST_CONSTANT + Strings.padStart(String.valueOf(ifmReqDto.getIdService()), 2, GGIConstants.DEFAULT_NUMBER_STRING)
+ GGIConstants.UNKNOWN_ERROR);
}
return szResponse;
}
I recommend checking out the Java documentation, it provides a really good reference to start with. The .split method uses a regex to split up a string based on a delimiter.
String[] tokens = myString.split("0102\\*\\*");
For now I suspect that you forgot to escape * in split regex.
Try maybe
String[] resutl = yourString.split("0102\\*\\*");
In case you want * to represent any character then use . instead of *
String[] resutl = yourString.split("0102..");
In case you want * to represent any digit use \\d instead
String[] resutl = yourString.split("0102\\d\\d");
String string = "blabla0102**dada";
String[] parts = string.split("0102\\*\\*");
String part1 = parts[0]; // blabla
String part2 = parts[1]; // dada
Here we have a String: "blabla0102**dada", we call it string. Every String object has a method split(), using this we can split a string on anything we desire.
Do you mean literally split by "0102**"? Couldn't you use regex for that?
String[] tokens = "My text 0102** hello!".split("0102\\*\\*");
System.out.println(tokens[0]);
System.out.println(tokens[1]);
Related
How can I check for an empty Optional array of strings in Java?
In the case is empty I would like to return a message.
#PostMapping("/users")
#ResponseBody
public String saveUsers(#RequestParam Optional<String>[] paramArray) {
System.out.println("param " + paramArray);
String msg = "";
int i = 0;
if (paramArray is empty) {
msg = "paramArray is empty";
} else {
for (Optional<String> paramArrayItem : paramArray) {
msg += "param[" + i + "]" + paramArrayItem + "\n";
i++;
}
}
return msg;
}
Optional<String>[] is an array of Optional<String> elements.
You'd rather want to have optional array of strings, so you need to change paramArray type to Optional<String[]>.
#PostMapping("/users")
#ResponseBody
public String saveUsers(#RequestParam Optional<String[]> paramArray) {
System.out.println("param " + paramArray);
String msg = "";
int i = 0;
if (paramArray.isEmpty()) {
msg = "paramArray is empty";
} else {
for (String paramArrayItem : paramArray.get()) {
msg += "param[" + i + "]" + paramArrayItem + "\n";
i++;
}
}
return msg;
}
Currently, I'm am trying to parse from MealMaster files, but I am having an issue where Ingredients are being parsed as:
"Inch thick" due to the next line not having a quantity or unit, and carrying on from the previous
Also, I'm finding ingredients that are listed as "ingredient1 or ingredient2" and I'm not sure how to catagorise these in the parser
Here is an example of a file I'm parsing from and my code below
https://pastebin.com/fhkRczya
public void readIngredients() {
try {
Remover remover = new Remover();
ArrayList<Ingredient> ing = new ArrayList<Ingredient>();
while(!( "".equals(line.trim()))) {
parsedIngredients = line + "\n";
if(!line.contains("---") && !line.contains(":")) {
Ingredient currentIng = splitLine();
if(currentIng.getQuantity().length() == 0 && !ing.isEmpty()) {
Ingredient lastIng = ing.get(ing.size()-1);
if (currentIng.getName().toLowerCase().contains("inch") ) {
//System.out.println(currentIng.getName());
lastIng.setOther(lastIng.getOther() + "," + currentIng.getQuantity() + "," +currentIng.getName());
//System.out.println("OTher " + lastIng.getOther());
}else{
String lastIngName = lastIng.getName();
String addName = lastIngName + " " + currentIng.getName();
lastIng.setName(addName);
lastIng = remover.removeTo(unitWords,lastIng);
lastIng = remover.removeCustomWords(lastIng);
}
}else if (currentIng.getName().startsWith("-") || currentIng.getName().startsWith("For") ){
if(ing.size()>0) {
Ingredient lastIng = ing.get(ing.size()-1);
lastIng.setOther(currentIng.getQuantity() + " " + currentIng.getName());
}
}else {
currentIng = remover.removeTo(unitWords,currentIng);
currentIng = remover.removeCustomWords(currentIng);
//currentIng.setName(currentIng.getName().replace(",", ""));
System.out.println(currentIng.getName());
ing.add(currentIng);
}
}
line = reader.readLine();
}
for(int i = 0; i < ing.size();i++) {
removeCommaColon(ing.get(i));
}
for(int i = 0; i<ing.size();i++) {
ingredientsString = ingredientsString + ing.get(i).getName() + "|" + currentRecipe.getTitle() + " \n";
//ingredientsString = ingredientsString + currentRecipe.getTitle() + "\n";
}
currentRecipe.setIngredients(ing);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try {
String hour = (String) comboBox.getSelectedItem();
String filename = fileName.getText();
String date = ((JTextField)dateChooser.getDateEditor().getUiComponent()).getText();
String text = txtKeyword.getText();
String newline = "\n";
String directory = Directory.getText();
File path = new File(directory);
File[] faFiles = path.listFiles();
for(File file: faFiles){
**if(file.getName().contains(filename + "-" + date + "[" + hour + "]") == true == true || file.getName().contains(filename + "-" + date) || file.getName().contains(filename)){**
String line = null;
Reader reader = new InputStreamReader(new FileInputStream(file), "utf-8");
BufferedReader br = new BufferedReader(reader);
while ((line = br.readLine()) != null) {
if(line.contains(text)){
jTextArea1.append(line + newline);
btnClear.setEnabled(true);
btnExport.setEnabled(true);
}
}
br.close();
}
}
}
catch(Exception e){
}
Here is my question. I'm trying to use input and loop method to search for a file. The above code works but my problem is lets say I try to find 2 different text files
1. billing-20140527[09].txt has
a)XGMS,2014-05-27 10:08:04,122,PLAYER_VERIFY,VERIFY to LBA,0x580000,0xC0000,253040.
b)XGMS,2034-05-27 30:08:04,122,PLAYER_VERIFY,VERIFY to LBA,0x580000,0xC0000,253040.
2. billing-20140527[10].txt has
a)XCGS,2014-05-27 10:08:04,122,PLAYER_VERIFY,VERIFY to LBA,0x580000,0xC0000,253040.
b)HELO
**I try to find the number 1 in both text files, if lets say I input the text file name is
billing, I can find the number 1 in both text file and output them:**
a) XGMS,2014-05-27 10:08:04,122,PLAYER_VERIFY,VERIFY to LBA,0x580000,0xC0000,253040.
b) XCGS,2014-05-27 10:08:04,122,PLAYER_VERIFY,VERIFY to LBA,0x580000,0xC0000,253040.
**However, if I specify the text file name: billing-20140527[09].txt and find the number 1 inside the text file, it will only output:
a) XGMS,2014-05-27 10:08:04,122,PLAYER_VERIFY,VERIFY to LBA,0x580000,0xC0000,253040.**
Can anyone help me with this? Guide or help?
I would work with the BufferedReader. Because it reads a whole line. And then you can split the line by a delimiter (lets say a space " " ). In your case I would write a split-method which receives a String and search for the regex you want.
private void doSearch(File f2) throws IOException,
fileHandler.FileException {
File[] children = f2.listFiles();
if (children != null && searching)
for (int i = 0; i < children.length; i++) {
if (g.isReady()) {
g.setReady(false);
if (!searching) {
g.setReady(true);
break;
} else if (isDirectory(children[i])) {
g.getActualDirectoryInhalt().setText(children[i].getPath()
.substring(g.root.getText().length()));
counterDirectories++;
doSearch(children[i]);
} else if (advancedSearch && !filterSpecified(children[i])) {
raiseCounterForDirectorySize(children[i]);
continue;
} else if (checkFile(children[i])) {
counterFiles++;
searchThroughFile(children[i], this.regex);
raiseCounterForDirectorySize(children[i]);
} else {
g.getTextAreaUnreachable().setText(
g.getTextAreaUnreachable().getText() + f2
+ "\n");
raiseCounterForDirectorySize(children[i]);
}
} else {
doSearch(children[i]);
}
g.setReady(true);
}
}
And here's the other method:
public static void searchThroughFile(File f2, String regex) throws IOException,
fileHandler.FileException {
try {
InputStream is = new BufferedInputStream(new FileInputStream(f2));
String mimeType = URLConnection.guessContentTypeFromStream(is);
ArrayList<String> linesFromFile = fileHandler.FileReaderer
.readFileIntoStringArrayList(f2);
String line = null;
if (f2.getAbsolutePath().contains(regex)) {
g.getTextAreaAdvanced()
.setText(
g.getTextAreaAdvanced().getText()
+ f2.getPath() + "\n");
}
if (linesFromFile.size() != 0) {
for (int i = 0; i < linesFromFile.size(); i++) {
line = linesFromFile.get(i);
Pattern MY_Pattern = Pattern.compile(regex);
Matcher m = MY_Pattern.matcher(line);
if (!searching) {
break;
}
MarkOne: if (!g.isReady()) {
break MarkOne;
} else {
g.setReady(false);
}
while (m.find() && searching) {
counterFoundPattern++;
g.getFoundFilesInhalt().setText(counterFoundPattern + "");
if (mimeType != null) {
g.getTextAreaAdvanced().setText(
g.getTextAreaAdvanced().getText()
+ f2.getPath() + " " + m.group()
+ " " + mimeType + " " + i+1 + "\n");
} else {
g.getTextAreaAdvanced().setText(
g.getTextAreaAdvanced().getText()
+ f2.getPath() + " " + m.group()
+ " " + i+1 + "\n");
}
}
g.setReady(true);
}
}
} catch (IOException e) {
MarkOne: if (!g.isReady()) {
break MarkOne;
} else {
g.setReady(false);
}
g.getTabpane().setForegroundAt(2, Color.RED);
g.getTextAreaException().setText(
g.getTextAreaException().getText() + e + "\n");
g.setReady(true);
} catch (OutOfMemoryError oute) {
MarkOne: if (!g.isReady()) {
break MarkOne;
} else {
g.setReady(false);
}
g.getTextAreaException().setText(
g.getTextAreaException().getText() + "\n"
+ "Fatal Error encured! The File will be skipped!"
+ "\n" + f2.getAbsolutePath());
g.getTabpane().setSelectedIndex(2);
g.setReady(true);
return;
}
}
I created a button that allows to create a zip file., the function that zips the file works correctly, but when I call her via the button (in the JS file) it crashes and it gives a blank page (I think I do not manage the output stream)
would please an idea
here is my code:
Button
isc.ToolStripButton.create({
ID: "BooksApp_GetXmlImage_Button"
,autoDraw:false
,icon: getUIIcon("icon_xml_16")
,prompt: getUIMsg("book_report_get_xml",4)
,showHover:true
,hoverStyle:"book_hover_style"
,click : function () {
BooksApp_Action_loadFile("objx");
// isc.say("test");
}
});
function to call the zipfile() method:
function BooksApp_Action_loadFile(p_UsedFormat) {
var tmpBookID = BooksApp_Application.FP_BookID;
var tmpIDs = BooksApp_Application.FP_fct_getSelectedPOVIDs();
var tmpUsr_ID = FPIUser.FP_fct_getID();
var tmpFormat = p_UsedFormat;
var showInWindow=false;
books_objects.exportData(
{
r_book_idnum : tmpBookID
,sBook_ID : tmpBookID
,sPOV_IDs : tmpIDs
,sUser_ID : tmpUsr_ID
,sFormat : tmpFormat
}
,{ operationId: "customExport"
,exportDisplay: (showInWindow ? "window" : "download") }
,function (dsResponse, data, dsRequest) {
//Never called
BooksApp_Action_Log("BooksApp_Action_loadFile:"+data);
}
);
}
customExport() function
public static String customExport(RPCManager rpc,
HttpServletResponse response) throws Exception {
String sReturn = _Return_OK;
try {
// setting doCustomResponse() notifies the RPCManager that we'll
// bypass RPCManager.send
// and instead write directly to the servletResponse output stream
rpc.doCustomResponse();
RequestContext.setNoCacheHeaders(response);
writeServerDebug("customExport : start");
DSRequest req = rpc.getDSRequest();
List<?> results = req.execute().getDataList();
String sReqData = (String) req.getParameter("exportDisplay");
String sReqData_sBook_ID = "" + req.getCriteriaValue("sBook_ID");
String sReqData_sPOV_IDs = "" + req.getCriteriaValue("sPOV_IDs");
String sReqData_sUser_ID = "" + req.getCriteriaValue("sUser_ID");
String sReqData_sFormat = "" + req.getCriteriaValue("sFormat");
StringBuilder content = new StringBuilder("get (sReqData:"
+ sReqData + ",sBook_ID:" + sReqData_sBook_ID
+ ",sPOV_IDs:" + sReqData_sPOV_IDs + ",sUser_ID:"
+ sReqData_sUser_ID + ",sFormat:" + sReqData_sFormat + ")"
+ results.size() + " line(s):");
for (Iterator<?> i = results.iterator(); i.hasNext();) {
Map<?, ?> record = (Map<?, ?>) i.next();
content.append("\n" + Books.Column_IDNum + ":"
+ record.get(Books.Column_IDNum));
content.append("\n" + Books.Column_Name + ":"
+ record.get(Books.Column_Name));
}
writeServerDebug("The content is \n" + content.toString());
// Create the new Office Engine
OfficeEngine myOfficeEngine = new OfficeEngine();
boolean bIsConnected = myOfficeEngine._RepositoryBridge
.connectSourceDataBase(false);
if (bIsConnected) {
//Connected to the repository, so get the files
if (sReqData_sFormat.equalsIgnoreCase("pdf") || sReqData_sFormat.equalsIgnoreCase("pptx")) {
//The book end user format
String sReturnPptx = myOfficeEngine.performGeneratePptx(
req.getHttpServletRequest(), response,
sReqData_sBook_ID, sReqData_sPOV_IDs,
sReqData_sUser_ID, sReqData_sFormat);
writeServerDebug("customExport call performGeneratePptx, return is "
+ sReturnPptx);
}
else {
AppZip appZip = new AppZip();
appZip.ZipFile(" ", " ");
String r = "sReturn_OK";;
return r;
}
//Free the connection to repository
myOfficeEngine._RepositoryBridge.freeConnectionSource();
} else {
response.setContentType("text/plain");
response.addHeader("content-disposition",
"attachment; filename=book.txt");
ServletOutputStream os = response.getOutputStream();
os.print(content.toString());
os.flush();
}
} catch (Exception e) {
writeServerDebug("ERROR:" + e.getLocalizedMessage());
sReturn = Repository._Return_KO;
}
return sReturn;
}
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.