Hye. I do not know why the Json file data is in very long numbers . I did google on how to read or to convert but i cant find it .
the code :
public static String characters[] ={"a","s","d","f","g","h","j","k","l","q","w","e","r","t","y","u","i","o","p","z","x","c","v","b","n","m"};
static Set<String> honeyWordSet = new HashSet<String>();
public static void generateHoneywords()
{
Random rn = new Random();
StringBuffer word = null;
while(honeyWordSet.size()<101)
{
word = new StringBuffer("");
int numOfChar = 0;
do
{
numOfChar = rn.nextInt(10);
}while(numOfChar<1);
for(int j=0;j<numOfChar;j++)
{
word.append(characters[rn.nextInt(characters.length)]);
}
honeyWordSet.add(word.toString());
}
try
{
ObjectMapper mapper = new ObjectMapper();
Map<String, Object> map = mapper.readValue(
new File("jsonFiles\\honeyWord.json"),
new TypeReference<Map<String, Object>>() {
});
for(Object obj : honeyWordSet)
{
map.put(obj.toString(), "");
}
mapper.writeValue(new File("jsonFiles\\honeyWord.json"), map);
}
catch(Exception e)
{
e.printStackTrace();
}
}
this the password of only 11 characters and when it is in json file , it become this long and i do not know how to read or convert it into characters . do the honeywords even successful ?
{
"password":
{"1":"70682930466663424031633987195811742589048303033286246995265263751152227528040",
"2":"88802133142308152475235386639891850783867613742545017627734579091864714529274",
"3":"77044523958204133748269546403028532501526864842254089627589521382689534716884",
"4":"113492302589409959817526131876347993996825827444440850435946334757636904815969",
"5":"91634880152443617534842621287039938041581081254914058002978601050179556493499",
"6":"41789555638182490504480050404782832255306254702785469397392735598495731403077",
"7":"77192224159977635473426980559151056575052583226217544606649626090165685301539",
"8":"107763495085302273747458393013408732609403066244716270716686466222930271749415",
"9":"51946338038242917578331882905973383336531776777297488598702974224296580020506",
"10":"85110112177512606543858375459297335339239818511701266034254858362091911608971",
"11":"73269189142166684209325577062514786983019191154169834309660168458666001346810",
"12":"73156569697674755343634566103724041451079384421332857450856494193159381684698",
"13":"108991649772298152043643302386517965908573452354267517199577281734443595966514",
"14":"103218584326081094673548050085606147092617983259240563762028264068035877000891",
"15":"35640613886241200026418217328422061636534287249966444867910277776917351260845",
"16":"77192224159977635473426980559151056575052583226217544606649626090165685301539",
"17":"20553885541631119247001227156676802314981306735372789521402284493774173915265",
"18":"50243977471952517172155509992929227707259745184556108795150213914029337799858",
"19":"85201461088932565530158869031891990127412955203087590241988738533258350146502"},
"index":8
}
My String looks like this
http://localhost:8080/HospitalServer/files/file?id=34&firstname=alex&lastname=ozouf&age=33&firstname=kevin&lastname=gerfild&age=27
I use this code to parse the parameters
final Map<String, List<String>> query_pairs = new LinkedHashMap<String, List<String>>();
final String[] pairs = query.split("&");
for (String pair : pairs) {
final int idx = pair.indexOf("=");
final String key = idx > 0 ? URLDecoder.decode(pair.substring(0, idx), "UTF-8") : pair;
if (!query_pairs.containsKey(key)) {
query_pairs.put(key, new LinkedList<String>());
}
final String value = idx > 0 && pair.length() > idx + 1 ? URLDecoder.decode(pair.substring(idx + 1), "UTF-8") : null;
query_pairs.get(key).add(value);
}
System.out.println(query_pairs);
The result is
{id=[34], firstname=[alex, kevin], lastname=[ozouf, gerfild], age=[33, 27]}
The result is not too bad but I want to group the parameters by person.
{id=[34], 1=[alex,ozouf,33 ], 2=[kevin, gerfild,27]}
I can create it from the previous result but I have the feeling that the job is done twice. What do you think I shall do ?
Here's how you can do it without using any library:
import java.util.Map;
import java.util.HashMap;
public class MyUrlParser {
private static final String SEPARATOR = ",";
public static void main(String[] args) {
final String URL = "http://localhost:8080/HospitalServer/files/file?id=34&firstname=alex&lastname=ozouf&age=33&firstname=kevin&lastname=gerfild&age=27";
MyUrlParser mup = new MyUrlParser();
try {
Map<String, String> parsed = mup.parse(URL);
System.out.println(parsed);
} catch (Exception e) {
System.err.println(e.getMessage());
}
}
public Map<String, String> parse(String url) throws Exception {
Map<String, String> retMap = new HashMap<>();
int queryStringPos = url.indexOf("?");
if (-1 == queryStringPos) {
throw new Exception("Invalid URL");
}
String queryString = url.substring(queryStringPos + 1);
String[] parameters = queryString.split("&");
if (parameters.length > 0) {
retMap.put("id", parameters[0]);
int personCounter = 0;
for (int minSize = 4; minSize <= parameters.length; minSize += 3) {
StringBuilder person = new StringBuilder();
person.append(parameters[minSize-3]);
person.append(SEPARATOR);
person.append(parameters[minSize-2]);
person.append(SEPARATOR);
person.append(parameters[minSize-1]);
personCounter++;
retMap.put("person" + personCounter, person.toString());
}
}
return retMap;
}
}
This is my code. I am not able to write it back to a csv. I have figured out that the problem is with the header matching in the if loop. The values are being read correctly nut the if loop is not getting satisfied when the headers are getting matched. Any help is much appreciated. Thanks.
public class FactsChecker {
public static void main(String[] args) {
run();
}
static void run()
{
Map <String,String> csvMap = new HashMap<String,String>();
String csvPath = "resource/Sample.csv";
String outputPath = "resource/Output.csv";
String[] headers;
try{
CsvReader csvreader = new CsvReader("resource/Sample.csv");
csvreader.readHeaders();
headers = csvreader.getHeaders();
String[] values;
String key = null;
String value = null;
while (csvreader.readRecord()){`
values = csvreader.getValues();
System.out.println(headers[0]);
for (int i = 0; i < headers.length; i++) {
if (headers[i].equals("FCT_NAME")) {
key = values[i];
}
if (headers[i].equals("FCT_TYPE")) {
value = values[i];
}
}
csvMap.put(key,value);
}
for (Map.Entry<String, String> entry : csvMap.entrySet())
{
System.out.println(entry.getKey() + "/" + entry.getValue());
}
Map<String,Entry> entryMap= new HashMap<String, Entry>();
for (String factKey:csvMap.keySet()){
Entry entry = new Entry();
entry.setFactName(factKey);
String factType = csvMap.get(factKey);
System.out.println(factKey);
entry.setFactType(factType);
entryMap.put(factKey, entry);
}
CsvWriter writer = new CsvWriter(outputPath);
for(String key1 : entryMap.keySet()){
Entry entry = entryMap.get(key1);
writer.writeRecord(new String[]{entry.getFactName(),entry.getFactType()});
}
writer.close();
}
catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
try using contains instead of equals in case there is trailing or leading white space
I also faced the same issue .Try the below. Just remove this appended character from your header when you read it from csv and then compare.
if(headers[i].startswith("\uFEFF"){
headers[i].replace("\uFEFF","");
}
http://m.people.com/img/ic?width=474&height=269&fsize=999000&format=jpg&url=http%3A%2F%2Fimg2.timeinc.net%2Fpeople%2Fi%2F2011%2Fnews%2F110425%2Fgwyneth-paltrow-300.jpg
This is my url.How can I extract image name Fgwyneth-paltrow-300.jpg from the URL in java.
Thanks
First we want to decode the URL and get the url parameter. We can do that using BalusC's great code for parsing query Strings. Then we just have to split that URL by / and take the last part.
String url ="http://m.people.com/img/ic?width=474&height=269&fsize=999000&format=jpg&url=http%3A%2F%2Fimg2.timeinc.net%2Fpeople%2Fi%2F2011%2Fnews%2F110425%2Fgwyneth-paltrow-300.jpg";
Map<String, List<String>> params = new HashMap<String, List<String>>();
String[] urlParts = url.split("\\?");
if (urlParts.length > 1) {
String query = urlParts[1];
for (String param : query.split("&")) {
String[] pair = param.split("=");
String key;
try
{
key = URLDecoder.decode(pair[0], "UTF-8");
} catch (UnsupportedEncodingException e)
{
key = URLDecoder.decode(pair[0]);
}
String value;
try
{
value = URLDecoder.decode(pair[1], "UTF-8");
} catch (UnsupportedEncodingException e)
{
value = URLDecoder.decode(pair[1]);
}
List<String> values = params.get(key);
if (values == null) {
values = new ArrayList<String>();
params.put(key, values);
}
values.add(value);
}
}
String img = params.get("url").get(0);
String[] parts = img.split("/");
String imgName = parts[parts.length - 1];
System.out.println(imgName);
I have a Map with my data and want to build a query string with it, just like I would with http_build_query on PHP. I'm not sure if this code is the best implementation of it or if I'm forgetting something?
public String toQueryString(Map<?, ?> data) throws UnsupportedEncodingException {
StringBuffer queryString = new StringBuffer();
for (Entry<?, ?> pair : data.entrySet()) {
queryString.append ( URLEncoder.encode ( (String) pair.getKey (), "UTF-8" ) + "=" );
queryString.append ( URLEncoder.encode ( (String) pair.getValue (), "UTF-8" ) + "&" );
}
if (queryString.length () > 0) {
queryString.deleteCharAt ( queryString.length () - 1 );
}
return queryString.toString ();
}
look at the QueryStringBuilder class and its test class :
private String httpBuildQuery(Map<String, String> data)
throws UnsupportedEncodingException {
QueryStringBuilder builder = new QueryStringBuilder();
for (Entry<String, String> pair : data.entrySet()) {
builder.addQueryParameter(pair.getKey(), pair.getValue());
}
return builder.encode("UTF-8");
}
The true power of PHP http_build_query function is its ability to get associative array and translate it into URL string. The following code do similar thing and it allows url params to be constructed as multi level Map that include nested Map and Collections.With some more work this a support for Array can also be added.
Test methods are shown below.
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.*;
/**
* Class: URLBuilder
* User: Gilad Tiram
* Date: 6/12/13
* Time: 4:02 PM
* <p/>
* <p/>
* Utility that helps to build URL String
*/
public class URLBuilder {
/**
* Build URL string from Map of params. Nested Map and Collection is also supported
*
* #param params Map of params for constructing the URL Query String
* #param encoding encoding type. If not set the "UTF-8" is selected by default
* #return String of type key=value&...key=value
* #throws java.io.UnsupportedEncodingException
* if encoding isnot supported
*/
public static String httpBuildQuery(Map<String, Object> params, String encoding) {
if (isEmpty(encoding)) {
encoding = "UTF-8";
}
StringBuilder sb = new StringBuilder();
for (Map.Entry<String, Object> entry : params.entrySet()) {
if (sb.length() > 0) {
sb.append('&');
}
String name = entry.getKey();
Object value = entry.getValue();
if (value instanceof Map) {
List<String> baseParam = new ArrayList<String>();
baseParam.add(name);
String str = buildUrlFromMap(baseParam, (Map) value, encoding);
sb.append(str);
} else if (value instanceof Collection) {
List<String> baseParam = new ArrayList<String>();
baseParam.add(name);
String str = buildUrlFromCollection(baseParam, (Collection) value, encoding);
sb.append(str);
} else {
sb.append(encodeParam(name));
sb.append("=");
sb.append(encodeParam(value));
}
}
return sb.toString();
}
private static String buildUrlFromMap(List<String> baseParam, Map<Object, Object> map, String encoding) {
StringBuilder sb = new StringBuilder();
String token;
//Build string of first level - related with params of provided Map
for (Map.Entry<Object, Object> entry : map.entrySet()) {
if (sb.length() > 0) {
sb.append('&');
}
String name = String.valueOf(entry.getKey());
Object value = entry.getValue();
if (value instanceof Map) {
List<String> baseParam2 = new ArrayList<String>(baseParam);
baseParam2.add(name);
String str = buildUrlFromMap(baseParam2, (Map) value, encoding);
sb.append(str);
} else if (value instanceof List) {
List<String> baseParam2 = new ArrayList<String>(baseParam);
baseParam2.add(name);
String str = buildUrlFromCollection(baseParam2, (List) value, encoding);
sb.append(str);
} else {
token = getBaseParamString(baseParam) + "[" + name + "]=" + encodeParam(value);
sb.append(token);
}
}
return sb.toString();
}
private static String buildUrlFromCollection(List<String> baseParam, Collection coll, String encoding) {
StringBuilder sb = new StringBuilder();
String token;
if (!(coll instanceof List)) {
coll = new ArrayList(coll);
}
List arrColl = (List) coll;
//Build string of first level - related with params of provided Map
for (int i = 0; i < arrColl.size(); i++) {
if (sb.length() > 0) {
sb.append('&');
}
Object value = (Object) arrColl.get(i);
if (value instanceof Map) {
List<String> baseParam2 = new ArrayList<String>(baseParam);
baseParam2.add(String.valueOf(i));
String str = buildUrlFromMap(baseParam2, (Map) value, encoding);
sb.append(str);
} else if (value instanceof List) {
List<String> baseParam2 = new ArrayList<String>(baseParam);
baseParam2.add(String.valueOf(i));
String str = buildUrlFromCollection(baseParam2, (List) value, encoding);
sb.append(str);
} else {
token = getBaseParamString(baseParam) + "[" + i + "]=" + encodeParam(value);
sb.append(token);
}
}
return sb.toString();
}
private static String getBaseParamString(List<String> baseParam) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < baseParam.size(); i++) {
String s = baseParam.get(i);
if (i == 0) {
sb.append(s);
} else {
sb.append("[" + s + "]");
}
}
return sb.toString();
}
/**
* Check if String is either empty or null
*
* #param str string to check
* #return true if string is empty. Else return false
*/
public static boolean isEmpty(String str) {
return str == null || str.length() == 0;
}
private static String encodeParam(Object param) {
try {
return URLEncoder.encode(String.valueOf(param), "UTF-8");
} catch (UnsupportedEncodingException e) {
return URLEncoder.encode(String.valueOf(param));
}
}
/* ========================================================================= */
/* Test functions */
/* ========================================================================= */
public static void main(String[] args) {
//basicTest();
//testWithMap();
//testWithList();
//testWithNestedMap();
//testWithNestedList();
testCompound();
}
private static void basicTest() {
Map<String, Object> params = new LinkedHashMap<String, Object>();
params.put("a", "1");
params.put("b", "2");
params.put("c", "3");
System.out.println(httpBuildQuery(params, "UTF-8"));
}
private static void testWithMap() {
Map<String, Object> params = new LinkedHashMap<String, Object>();
params.put("a", "1");
params.put("b", "2");
Map<String, Object> cParams = new LinkedHashMap<String, Object>();
cParams.put("c1", "c1val");
cParams.put("c2", "c2val");
params.put("c", cParams);
System.out.println(httpBuildQuery(params, "UTF-8"));
}
private static void testWithNestedMap() {
Map<String, Object> params = new LinkedHashMap<String, Object>();
params.put("a", "1");
params.put("b", "2");
Map<String, Object> cParamsLevel1 = new LinkedHashMap<String, Object>();
cParamsLevel1.put("cL1-1", "cLevel1-1val");
cParamsLevel1.put("cL1-2", "cLevel1-2val");
Map<String, Object> cParamsLevel2 = new LinkedHashMap<String, Object>();
cParamsLevel2.put("cL2-1", "cLevel2-1val");
cParamsLevel2.put("cL2-2", "cLevel2-2val");
cParamsLevel1.put("cL1-3", cParamsLevel2);
params.put("c", cParamsLevel1);
System.out.println(httpBuildQuery(params, "UTF-8"));
}
private static void testWithList() {
Map<String, Object> params = new LinkedHashMap<String, Object>();
params.put("a", "1");
params.put("b", "2");
List<Object> cParams = new ArrayList<Object>();
cParams.add("c1val");
cParams.add("c2val");
params.put("c", cParams);
System.out.println(httpBuildQuery(params, "UTF-8"));
}
private static void testWithNestedList() {
Map<String, Object> params = new LinkedHashMap<String, Object>();
params.put("a", "1");
params.put("b", "2");
List<Object> cParamsLevel1 = new ArrayList<Object>();
cParamsLevel1.add("cL1-val1");
cParamsLevel1.add("cL12-val2");
List<Object> cParamsLevel2 = new ArrayList<Object>();
cParamsLevel2.add("cL2-val1");
cParamsLevel2.add("cL2-val2");
cParamsLevel1.add(cParamsLevel2);
params.put("c", cParamsLevel1);
System.out.println(httpBuildQuery(params, "UTF-8"));
}
private static void testCompound() {
Map<String, Object> params = new LinkedHashMap<String, Object>();
//flat
params.put("a", "1");
params.put("b", "2");
//Map level 1
Map<String, Object> cParamsLevel1 = new LinkedHashMap<String, Object>();
cParamsLevel1.put("cL1-1", "cLevel1-1val");
cParamsLevel1.put("cL1-2", "cLevel1-2val");
//Map level 2
Map<String, Object> cParamsLevel2 = new LinkedHashMap<String, Object>();
cParamsLevel2.put("cL2-1", "cLevel2-1val");
cParamsLevel2.put("cL2-2", "cLevel2-2val");
cParamsLevel1.put("cL1-3", cParamsLevel2);
params.put("c", cParamsLevel1);
//List level 1
List<Object> dParamsLevel1 = new ArrayList<Object>();
dParamsLevel1.add("dL1-val1");
dParamsLevel1.add("dL12-val2");
//List level 2
List<Object> dParamsLevel2 = new ArrayList<Object>();
dParamsLevel2.add("dL2-val1");
dParamsLevel2.add("dL2-val2");
dParamsLevel1.add(dParamsLevel2);
params.put("d", dParamsLevel1);
System.out.println(httpBuildQuery(params, "UTF-8"));
}
}
For easy test of your results append the string resulted by tests as query String of real url that point to this PHP. Example
http://localhost/test.php?a=1&b=2&c[cL1-1]=cLevel1-1val&c[cL1-2]=cLevel1-2val&c[cL1-3][cL2-1]=cLevel2-1val&c[cL1-3][cL2-2]=cLevel2-2val&d[0]=dL1-val1&d[1]=dL12-val2&d[2][0]=dL2-val1&d[2][1]=dL2-val2
<?php
var_dump($_REQUEST);
?>
You'd probably want to check the "Accept" request header for the encodings supported by the client before forcing UTF-8 (even though it's probably the best choice).
This should be the easiest (and most reliable) solution:
protected static String httpBuildQuery(List<? extends NameValuePair> parameters, String encoding) {
return URLEncodedUtils.format(parameters, encoding).replace("*", "%2A");
}
Example usage:
List<NameValuePair> params = new ArrayList<NameValuePair>;
params.add(new BasicNameValuePair("key", "value"));
String queryString = httpBuildQuery(myParamList, "UTF-8");
Java not encoding the asterisk (+) while PHP does encode it %2A should be the only difference.
Looks OK, with these caveats:
make the parameter a Map<String, String> rather than casting key and value to String.
the hardcoded encoding looks suspicious. UTF-8 is not a given, it has to match the encoding defined in the header of the HTTP request. So the code should ensure that they do - at least define it as a constant somewhere and refer to that both here and wherever the request encoding is set.
Edit: It seems that I was wrong about the encoding; HTTP GET parameters are not subject to an encoding header, and did not traditionally have a well-defined encoding at all. RFC 3988 does seem to mandate UTF-8, but that sounds rather brittle to me, so unless you have tight control over the server and can ensure that it does indeed use UTF-8 as well, I'd use POST requests for any data that's not in the 7bit ASCII range.