├── CrunchbaseWrapper
├── .classpath
├── .project
├── .settings
│ ├── .jsdtscope
│ ├── org.apache.ivyde.eclipse.prefs
│ ├── org.eclipse.jdt.core.prefs
│ ├── org.eclipse.ltk.core.refactoring.prefs
│ ├── org.eclipse.m2e.core.prefs
│ ├── org.eclipse.wst.common.component
│ ├── org.eclipse.wst.common.project.facet.core.xml
│ ├── org.eclipse.wst.jsdt.ui.superType.container
│ ├── org.eclipse.wst.jsdt.ui.superType.name
│ ├── org.eclipse.wst.validation.prefs
│ └── org.eclipse.wst.ws.service.policy.prefs
├── WebContent
│ ├── META-INF
│ │ └── MANIFEST.MF
│ ├── WEB-INF
│ │ └── lib
│ │ │ ├── commons-codec-1.6.jar
│ │ │ ├── commons-csv-1.0.jar
│ │ │ ├── commons-lang3-3.3.2.jar
│ │ │ ├── httpclient-4.2.6.jar
│ │ │ ├── httpclient-cache-4.2.6.jar
│ │ │ ├── httpcore-4.2.5.jar
│ │ │ ├── jackson-annotations-2.3.0.jar
│ │ │ ├── jackson-core-2.3.3.jar
│ │ │ ├── jackson-databind-2.3.3.jar
│ │ │ ├── jcl-over-slf4j-1.7.6.jar
│ │ │ ├── jena-arq-2.13.0.jar
│ │ │ ├── jena-core-2.13.0.jar
│ │ │ ├── jena-iri-1.1.2.jar
│ │ │ ├── jena-tdb-1.1.2.jar
│ │ │ ├── jsonld-java-0.7.0.jar
│ │ │ ├── libthrift-0.9.2.jar
│ │ │ ├── log4j-1.2.17.jar
│ │ │ ├── okhttp-2.5.0.jar
│ │ │ ├── okio-1.6.0.jar
│ │ │ ├── slf4j-api-1.7.6.jar
│ │ │ ├── slf4j-log4j12-1.7.6.jar
│ │ │ ├── xercesImpl-2.11.0.jar
│ │ │ └── xml-apis-1.4.01.jar
│ ├── context.jsonld
│ ├── html
│ │ ├── authentication.html
│ │ ├── facebook.json
│ │ ├── facebook.jsonld
│ │ └── facebook.nt
│ ├── index.html
│ ├── ontology.owl
│ ├── organization-mappings.nt
│ ├── people-mappings.nt
│ ├── vocab.rdf
│ └── void.ttl
├── build
│ └── classes
│ │ ├── org
│ │ └── json
│ │ │ ├── CDL.class
│ │ │ ├── Cookie.class
│ │ │ ├── CookieList.class
│ │ │ ├── HTTP.class
│ │ │ ├── HTTPTokener.class
│ │ │ ├── JSONArray.class
│ │ │ ├── JSONException.class
│ │ │ ├── JSONML.class
│ │ │ ├── JSONObject$Null.class
│ │ │ ├── JSONObject.class
│ │ │ ├── JSONString.class
│ │ │ ├── JSONStringer.class
│ │ │ ├── JSONTokener.class
│ │ │ ├── JSONWriter.class
│ │ │ ├── Property.class
│ │ │ ├── XML.class
│ │ │ └── XMLTokener.class
│ │ ├── servlets
│ │ ├── Authenticate.class
│ │ ├── CrunchbaseWrapper.class
│ │ └── Listener.class
│ │ └── utilities
│ │ ├── Authentication.class
│ │ ├── JSONHelper.class
│ │ ├── JSONLDHelper.class
│ │ ├── MappingUtility.class
│ │ ├── SPARQLLoader.class
│ │ └── URIEncoder.class
└── src
│ ├── org
│ └── json
│ │ ├── CDL.java
│ │ ├── Cookie.java
│ │ ├── CookieList.java
│ │ ├── HTTP.java
│ │ ├── HTTPTokener.java
│ │ ├── JSONArray.java
│ │ ├── JSONException.java
│ │ ├── JSONML.java
│ │ ├── JSONObject.java
│ │ ├── JSONString.java
│ │ ├── JSONStringer.java
│ │ ├── JSONTokener.java
│ │ ├── JSONWriter.java
│ │ ├── Property.java
│ │ ├── XML.java
│ │ └── XMLTokener.java
│ ├── servlets
│ ├── Authenticate.java
│ ├── CrunchbaseWrapper.java
│ └── Listener.java
│ └── utilities
│ ├── Authentication.java
│ ├── JSONHelper.java
│ ├── JSONLDHelper.java
│ ├── MappingUtility.java
│ ├── SPARQLLoader.java
│ └── URIEncoder.java
├── README.md
└── crawling
└── CsvReader.java
/CrunchbaseWrapper/.classpath:
--------------------------------------------------------------------------------
1 |
2 |
No or wrong API key given
10 |This is a wrapper for CrunchBase and every request to this service is redirected to Crunchbase. 11 | As the CrunchBase API access is limited, you have to use an API key to use this service. If you have a key, please provide it in the user field and keep the password field empty.
12 | 13 | 14 |If you are a researcher, you can apply for a free key here. 15 | Please visit CrunchBase for more information.
16 | 17 | 18 | 19 | -------------------------------------------------------------------------------- /CrunchbaseWrapper/WebContent/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 |10 | A Linked Data API wrapping the REST API of CrunchBase, a database about technology companies and startups. 11 |
12 |13 | This service maps every request to Crunchbase. There also exist mappings of organizations and mappings of people in Crunchbase to DBpedia. 14 |
15 |17 | To use our Linked Data API for Crunchbase, you have to authenticate to Crunchbase. 18 | To do so, enter your api key here (put the key in the username field and keep the password field empty). 19 | If you are not authenticated, only triples concerning the mapping to DBpedia are returned due to the licensing model of Crunchbase. 20 |
21 | 22 |curl -v -H "Accept:text/turtle" --header "Authorization: Basic {Base64-encoded key}" http://linked-crunchbase.org/api/organizations/facebook#id
43 | Please take note of the CrunchBase Terms of Service concerning the licensing of Crunchbase data. 44 |
45 | 46 |The source-code is available on Github.
47 | 48 |33 | * Each row of text represents a row in a table or a data record. Each row 34 | * ends with a NEWLINE character. Each row contains one or more values. 35 | * Values are separated by commas. A value can contain any character except 36 | * for comma, unless is is wrapped in single quotes or double quotes. 37 | *
38 | * The first row usually contains the names of the columns. 39 | *
40 | * A comma delimited list can be converted into a JSONArray of JSONObjects.
41 | * The names for the elements in the JSONObjects can be taken from the names
42 | * in the first row.
43 | * @author JSON.org
44 | * @version 2015-05-01
45 | */
46 | public class CDL {
47 |
48 | /**
49 | * Get the next value. The value can be wrapped in quotes. The value can
50 | * be empty.
51 | * @param x A JSONTokener of the source text.
52 | * @return The value string, or null if empty.
53 | * @throws JSONException if the quoted string is badly formed.
54 | */
55 | private static String getValue(JSONTokener x) throws JSONException {
56 | char c;
57 | char q;
58 | StringBuffer sb;
59 | do {
60 | c = x.next();
61 | } while (c == ' ' || c == '\t');
62 | switch (c) {
63 | case 0:
64 | return null;
65 | case '"':
66 | case '\'':
67 | q = c;
68 | sb = new StringBuffer();
69 | for (;;) {
70 | c = x.next();
71 | if (c == q) {
72 | break;
73 | }
74 | if (c == 0 || c == '\n' || c == '\r') {
75 | throw x.syntaxError("Missing close quote '" + q + "'.");
76 | }
77 | sb.append(c);
78 | }
79 | return sb.toString();
80 | case ',':
81 | x.back();
82 | return "";
83 | default:
84 | x.back();
85 | return x.nextTo(',');
86 | }
87 | }
88 |
89 | /**
90 | * Produce a JSONArray of strings from a row of comma delimited values.
91 | * @param x A JSONTokener of the source text.
92 | * @return A JSONArray of strings.
93 | * @throws JSONException
94 | */
95 | public static JSONArray rowToJSONArray(JSONTokener x) throws JSONException {
96 | JSONArray ja = new JSONArray();
97 | for (;;) {
98 | String value = getValue(x);
99 | char c = x.next();
100 | if (value == null ||
101 | (ja.length() == 0 && value.length() == 0 && c != ',')) {
102 | return null;
103 | }
104 | ja.put(value);
105 | for (;;) {
106 | if (c == ',') {
107 | break;
108 | }
109 | if (c != ' ') {
110 | if (c == '\n' || c == '\r' || c == 0) {
111 | return ja;
112 | }
113 | throw x.syntaxError("Bad character '" + c + "' (" +
114 | (int)c + ").");
115 | }
116 | c = x.next();
117 | }
118 | }
119 | }
120 |
121 | /**
122 | * Produce a JSONObject from a row of comma delimited text, using a
123 | * parallel JSONArray of strings to provides the names of the elements.
124 | * @param names A JSONArray of names. This is commonly obtained from the
125 | * first row of a comma delimited text file using the rowToJSONArray
126 | * method.
127 | * @param x A JSONTokener of the source text.
128 | * @return A JSONObject combining the names and values.
129 | * @throws JSONException
130 | */
131 | public static JSONObject rowToJSONObject(JSONArray names, JSONTokener x)
132 | throws JSONException {
133 | JSONArray ja = rowToJSONArray(x);
134 | return ja != null ? ja.toJSONObject(names) : null;
135 | }
136 |
137 | /**
138 | * Produce a comma delimited text row from a JSONArray. Values containing
139 | * the comma character will be quoted. Troublesome characters may be
140 | * removed.
141 | * @param ja A JSONArray of strings.
142 | * @return A string ending in NEWLINE.
143 | */
144 | public static String rowToString(JSONArray ja) {
145 | StringBuilder sb = new StringBuilder();
146 | for (int i = 0; i < ja.length(); i += 1) {
147 | if (i > 0) {
148 | sb.append(',');
149 | }
150 | Object object = ja.opt(i);
151 | if (object != null) {
152 | String string = object.toString();
153 | if (string.length() > 0 && (string.indexOf(',') >= 0 ||
154 | string.indexOf('\n') >= 0 || string.indexOf('\r') >= 0 ||
155 | string.indexOf(0) >= 0 || string.charAt(0) == '"')) {
156 | sb.append('"');
157 | int length = string.length();
158 | for (int j = 0; j < length; j += 1) {
159 | char c = string.charAt(j);
160 | if (c >= ' ' && c != '"') {
161 | sb.append(c);
162 | }
163 | }
164 | sb.append('"');
165 | } else {
166 | sb.append(string);
167 | }
168 | }
169 | }
170 | sb.append('\n');
171 | return sb.toString();
172 | }
173 |
174 | /**
175 | * Produce a JSONArray of JSONObjects from a comma delimited text string,
176 | * using the first row as a source of names.
177 | * @param string The comma delimited text.
178 | * @return A JSONArray of JSONObjects.
179 | * @throws JSONException
180 | */
181 | public static JSONArray toJSONArray(String string) throws JSONException {
182 | return toJSONArray(new JSONTokener(string));
183 | }
184 |
185 | /**
186 | * Produce a JSONArray of JSONObjects from a comma delimited text string,
187 | * using the first row as a source of names.
188 | * @param x The JSONTokener containing the comma delimited text.
189 | * @return A JSONArray of JSONObjects.
190 | * @throws JSONException
191 | */
192 | public static JSONArray toJSONArray(JSONTokener x) throws JSONException {
193 | return toJSONArray(rowToJSONArray(x), x);
194 | }
195 |
196 | /**
197 | * Produce a JSONArray of JSONObjects from a comma delimited text string
198 | * using a supplied JSONArray as the source of element names.
199 | * @param names A JSONArray of strings.
200 | * @param string The comma delimited text.
201 | * @return A JSONArray of JSONObjects.
202 | * @throws JSONException
203 | */
204 | public static JSONArray toJSONArray(JSONArray names, String string)
205 | throws JSONException {
206 | return toJSONArray(names, new JSONTokener(string));
207 | }
208 |
209 | /**
210 | * Produce a JSONArray of JSONObjects from a comma delimited text string
211 | * using a supplied JSONArray as the source of element names.
212 | * @param names A JSONArray of strings.
213 | * @param x A JSONTokener of the source text.
214 | * @return A JSONArray of JSONObjects.
215 | * @throws JSONException
216 | */
217 | public static JSONArray toJSONArray(JSONArray names, JSONTokener x)
218 | throws JSONException {
219 | if (names == null || names.length() == 0) {
220 | return null;
221 | }
222 | JSONArray ja = new JSONArray();
223 | for (;;) {
224 | JSONObject jo = rowToJSONObject(names, x);
225 | if (jo == null) {
226 | break;
227 | }
228 | ja.put(jo);
229 | }
230 | if (ja.length() == 0) {
231 | return null;
232 | }
233 | return ja;
234 | }
235 |
236 |
237 | /**
238 | * Produce a comma delimited text from a JSONArray of JSONObjects. The
239 | * first row will be a list of names obtained by inspecting the first
240 | * JSONObject.
241 | * @param ja A JSONArray of JSONObjects.
242 | * @return A comma delimited text.
243 | * @throws JSONException
244 | */
245 | public static String toString(JSONArray ja) throws JSONException {
246 | JSONObject jo = ja.optJSONObject(0);
247 | if (jo != null) {
248 | JSONArray names = jo.names();
249 | if (names != null) {
250 | return rowToString(names) + toString(names, ja);
251 | }
252 | }
253 | return null;
254 | }
255 |
256 | /**
257 | * Produce a comma delimited text from a JSONArray of JSONObjects using
258 | * a provided list of names. The list of names is not included in the
259 | * output.
260 | * @param names A JSONArray of strings.
261 | * @param ja A JSONArray of JSONObjects.
262 | * @return A comma delimited text.
263 | * @throws JSONException
264 | */
265 | public static String toString(JSONArray names, JSONArray ja)
266 | throws JSONException {
267 | if (names == null || names.length() == 0) {
268 | return null;
269 | }
270 | StringBuffer sb = new StringBuffer();
271 | for (int i = 0; i < ja.length(); i += 1) {
272 | JSONObject jo = ja.optJSONObject(i);
273 | if (jo != null) {
274 | sb.append(rowToString(jo.toJSONArray(names)));
275 | }
276 | }
277 | return sb.toString();
278 | }
279 | }
280 |
--------------------------------------------------------------------------------
/CrunchbaseWrapper/src/org/json/Cookie.java:
--------------------------------------------------------------------------------
1 | package org.json;
2 |
3 | /*
4 | Copyright (c) 2002 JSON.org
5 |
6 | Permission is hereby granted, free of charge, to any person obtaining a copy
7 | of this software and associated documentation files (the "Software"), to deal
8 | in the Software without restriction, including without limitation the rights
9 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 | copies of the Software, and to permit persons to whom the Software is
11 | furnished to do so, subject to the following conditions:
12 |
13 | The above copyright notice and this permission notice shall be included in all
14 | copies or substantial portions of the Software.
15 |
16 | The Software shall be used for Good, not Evil.
17 |
18 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
21 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
23 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
24 | SOFTWARE.
25 | */
26 |
27 | /**
28 | * Convert a web browser cookie specification to a JSONObject and back.
29 | * JSON and Cookies are both notations for name/value pairs.
30 | * @author JSON.org
31 | * @version 2014-05-03
32 | */
33 | public class Cookie {
34 |
35 | /**
36 | * Produce a copy of a string in which the characters '+', '%', '=', ';'
37 | * and control characters are replaced with "%hh". This is a gentle form
38 | * of URL encoding, attempting to cause as little distortion to the
39 | * string as possible. The characters '=' and ';' are meta characters in
40 | * cookies. By convention, they are escaped using the URL-encoding. This is
41 | * only a convention, not a standard. Often, cookies are expected to have
42 | * encoded values. We encode '=' and ';' because we must. We encode '%' and
43 | * '+' because they are meta characters in URL encoding.
44 | * @param string The source string.
45 | * @return The escaped result.
46 | */
47 | public static String escape(String string) {
48 | char c;
49 | String s = string.trim();
50 | int length = s.length();
51 | StringBuilder sb = new StringBuilder(length);
52 | for (int i = 0; i < length; i += 1) {
53 | c = s.charAt(i);
54 | if (c < ' ' || c == '+' || c == '%' || c == '=' || c == ';') {
55 | sb.append('%');
56 | sb.append(Character.forDigit((char)((c >>> 4) & 0x0f), 16));
57 | sb.append(Character.forDigit((char)(c & 0x0f), 16));
58 | } else {
59 | sb.append(c);
60 | }
61 | }
62 | return sb.toString();
63 | }
64 |
65 |
66 | /**
67 | * Convert a cookie specification string into a JSONObject. The string
68 | * will contain a name value pair separated by '='. The name and the value
69 | * will be unescaped, possibly converting '+' and '%' sequences. The
70 | * cookie properties may follow, separated by ';', also represented as
71 | * name=value (except the secure property, which does not have a value).
72 | * The name will be stored under the key "name", and the value will be
73 | * stored under the key "value". This method does not do checking or
74 | * validation of the parameters. It only converts the cookie string into
75 | * a JSONObject.
76 | * @param string The cookie specification string.
77 | * @return A JSONObject containing "name", "value", and possibly other
78 | * members.
79 | * @throws JSONException
80 | */
81 | public static JSONObject toJSONObject(String string) throws JSONException {
82 | String name;
83 | JSONObject jo = new JSONObject();
84 | Object value;
85 | JSONTokener x = new JSONTokener(string);
86 | jo.put("name", x.nextTo('='));
87 | x.next('=');
88 | jo.put("value", x.nextTo(';'));
89 | x.next();
90 | while (x.more()) {
91 | name = unescape(x.nextTo("=;"));
92 | if (x.next() != '=') {
93 | if (name.equals("secure")) {
94 | value = Boolean.TRUE;
95 | } else {
96 | throw x.syntaxError("Missing '=' in cookie parameter.");
97 | }
98 | } else {
99 | value = unescape(x.nextTo(';'));
100 | x.next();
101 | }
102 | jo.put(name, value);
103 | }
104 | return jo;
105 | }
106 |
107 |
108 | /**
109 | * Convert a JSONObject into a cookie specification string. The JSONObject
110 | * must contain "name" and "value" members.
111 | * If the JSONObject contains "expires", "domain", "path", or "secure"
112 | * members, they will be appended to the cookie specification string.
113 | * All other members are ignored.
114 | * @param jo A JSONObject
115 | * @return A cookie specification string
116 | * @throws JSONException
117 | */
118 | public static String toString(JSONObject jo) throws JSONException {
119 | StringBuilder sb = new StringBuilder();
120 |
121 | sb.append(escape(jo.getString("name")));
122 | sb.append("=");
123 | sb.append(escape(jo.getString("value")));
124 | if (jo.has("expires")) {
125 | sb.append(";expires=");
126 | sb.append(jo.getString("expires"));
127 | }
128 | if (jo.has("domain")) {
129 | sb.append(";domain=");
130 | sb.append(escape(jo.getString("domain")));
131 | }
132 | if (jo.has("path")) {
133 | sb.append(";path=");
134 | sb.append(escape(jo.getString("path")));
135 | }
136 | if (jo.optBoolean("secure")) {
137 | sb.append(";secure");
138 | }
139 | return sb.toString();
140 | }
141 |
142 | /**
143 | * Convert
35 | * A JSONStringer instance provides a
51 | * The first method called must be
55 | * This can sometimes be easier than using a JSONObject to build a string.
56 | * @author JSON.org
57 | * @version 2008-09-18
58 | */
59 | public class JSONStringer extends JSONWriter {
60 | /**
61 | * Make a fresh JSONStringer. It can be used to build one JSON text.
62 | */
63 | public JSONStringer() {
64 | super(new StringWriter());
65 | }
66 |
67 | /**
68 | * Return the JSON text. This method is used to obtain the product of the
69 | * JSONStringer instance. It will return
36 | * A JSONWriter instance provides a
51 | * The first method called must be
55 | * This can sometimes be easier than using a JSONObject to build a string.
56 | * @author JSON.org
57 | * @version 2011-11-24
58 | */
59 | public class JSONWriter {
60 | private static final int maxdepth = 200;
61 |
62 | /**
63 | * The comma flag determines if a comma should be output before the next
64 | * value.
65 | */
66 | private boolean comma;
67 |
68 | /**
69 | * The current mode. Values:
70 | * 'a' (array),
71 | * 'd' (done),
72 | * 'i' (initial),
73 | * 'k' (key),
74 | * 'o' (object).
75 | */
76 | protected char mode;
77 |
78 | /**
79 | * The object/array stack.
80 | */
81 | private final JSONObject stack[];
82 |
83 | /**
84 | * The stack top index. A value of 0 indicates that the stack is empty.
85 | */
86 | private int top;
87 |
88 | /**
89 | * The writer that will receive the output.
90 | */
91 | protected Writer writer;
92 |
93 | /**
94 | * Make a fresh JSONWriter. It can be used to build one JSON text.
95 | */
96 | public JSONWriter(Writer w) {
97 | this.comma = false;
98 | this.mode = 'i';
99 | this.stack = new JSONObject[maxdepth];
100 | this.top = 0;
101 | this.writer = w;
102 | }
103 |
104 | /**
105 | * Append a value.
106 | * @param string A string value.
107 | * @return this
108 | * @throws JSONException If the value is out of sequence.
109 | */
110 | private JSONWriter append(String string) throws JSONException {
111 | if (string == null) {
112 | throw new JSONException("Null pointer");
113 | }
114 | if (this.mode == 'o' || this.mode == 'a') {
115 | try {
116 | if (this.comma && this.mode == 'a') {
117 | this.writer.write(',');
118 | }
119 | this.writer.write(string);
120 | } catch (IOException e) {
121 | throw new JSONException(e);
122 | }
123 | if (this.mode == 'o') {
124 | this.mode = 'k';
125 | }
126 | this.comma = true;
127 | return this;
128 | }
129 | throw new JSONException("Value out of sequence.");
130 | }
131 |
132 | /**
133 | * Begin appending a new array. All values until the balancing
134 | * %
hh sequences to single characters, and
144 | * convert plus to space.
145 | * @param string A string that may contain
146 | * +
(plus) and
147 | * %
hh sequences.
148 | * @return The unescaped string.
149 | */
150 | public static String unescape(String string) {
151 | int length = string.length();
152 | StringBuilder sb = new StringBuilder(length);
153 | for (int i = 0; i < length; ++i) {
154 | char c = string.charAt(i);
155 | if (c == '+') {
156 | c = ' ';
157 | } else if (c == '%' && i + 2 < length) {
158 | int d = JSONTokener.dehexchar(string.charAt(i + 1));
159 | int e = JSONTokener.dehexchar(string.charAt(i + 2));
160 | if (d >= 0 && e >= 0) {
161 | c = (char)(d * 16 + e);
162 | i += 2;
163 | }
164 | }
165 | sb.append(c);
166 | }
167 | return sb.toString();
168 | }
169 | }
170 |
--------------------------------------------------------------------------------
/CrunchbaseWrapper/src/org/json/CookieList.java:
--------------------------------------------------------------------------------
1 | package org.json;
2 |
3 | /*
4 | Copyright (c) 2002 JSON.org
5 |
6 | Permission is hereby granted, free of charge, to any person obtaining a copy
7 | of this software and associated documentation files (the "Software"), to deal
8 | in the Software without restriction, including without limitation the rights
9 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 | copies of the Software, and to permit persons to whom the Software is
11 | furnished to do so, subject to the following conditions:
12 |
13 | The above copyright notice and this permission notice shall be included in all
14 | copies or substantial portions of the Software.
15 |
16 | The Software shall be used for Good, not Evil.
17 |
18 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
21 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
23 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
24 | SOFTWARE.
25 | */
26 |
27 | import java.util.Iterator;
28 |
29 | /**
30 | * Convert a web browser cookie list string to a JSONObject and back.
31 | * @author JSON.org
32 | * @version 2014-05-03
33 | */
34 | public class CookieList {
35 |
36 | /**
37 | * Convert a cookie list into a JSONObject. A cookie list is a sequence
38 | * of name/value pairs. The names are separated from the values by '='.
39 | * The pairs are separated by ';'. The names and the values
40 | * will be unescaped, possibly converting '+' and '%' sequences.
41 | *
42 | * To add a cookie to a cooklist,
43 | * cookielistJSONObject.put(cookieJSONObject.getString("name"),
44 | * cookieJSONObject.getString("value"));
45 | * @param string A cookie list string
46 | * @return A JSONObject
47 | * @throws JSONException
48 | */
49 | public static JSONObject toJSONObject(String string) throws JSONException {
50 | JSONObject jo = new JSONObject();
51 | JSONTokener x = new JSONTokener(string);
52 | while (x.more()) {
53 | String name = Cookie.unescape(x.nextTo('='));
54 | x.next('=');
55 | jo.put(name, Cookie.unescape(x.nextTo(';')));
56 | x.next();
57 | }
58 | return jo;
59 | }
60 |
61 | /**
62 | * Convert a JSONObject into a cookie list. A cookie list is a sequence
63 | * of name/value pairs. The names are separated from the values by '='.
64 | * The pairs are separated by ';'. The characters '%', '+', '=', and ';'
65 | * in the names and values are replaced by "%hh".
66 | * @param jo A JSONObject
67 | * @return A cookie list string
68 | * @throws JSONException
69 | */
70 | public static String toString(JSONObject jo) throws JSONException {
71 | boolean b = false;
72 | Iterator{
43 | * Method: "POST" (for example),
44 | * "Request-URI": "/" (for example),
45 | * "HTTP-Version": "HTTP/1.1" (for example)
46 | * }
47 | * A response header will contain
48 | * {
49 | * "HTTP-Version": "HTTP/1.1" (for example),
50 | * "Status-Code": "200" (for example),
51 | * "Reason-Phrase": "OK" (for example)
52 | * }
53 | * In addition, the other parameters in the header will be captured, using
54 | * the HTTP field names as JSON names, so that
55 | * Date: Sun, 26 May 2002 18:06:04 GMT
56 | * Cookie: Q=q2=PPEAsg--; B=677gi6ouf29bn&b=2&f=s
57 | * Cache-Control: no-cache
58 | * become
59 | * {...
60 | * Date: "Sun, 26 May 2002 18:06:04 GMT",
61 | * Cookie: "Q=q2=PPEAsg--; B=677gi6ouf29bn&b=2&f=s",
62 | * "Cache-Control": "no-cache",
63 | * ...}
64 | * It does no further checking or conversion. It does not parse dates.
65 | * It does not do '%' transforms on URLs.
66 | * @param string An HTTP header string.
67 | * @return A JSONObject containing the elements and attributes
68 | * of the XML string.
69 | * @throws JSONException
70 | */
71 | public static JSONObject toJSONObject(String string) throws JSONException {
72 | JSONObject jo = new JSONObject();
73 | HTTPTokener x = new HTTPTokener(string);
74 | String token;
75 |
76 | token = x.nextToken();
77 | if (token.toUpperCase().startsWith("HTTP")) {
78 |
79 | // Response
80 |
81 | jo.put("HTTP-Version", token);
82 | jo.put("Status-Code", x.nextToken());
83 | jo.put("Reason-Phrase", x.nextTo('\0'));
84 | x.next();
85 |
86 | } else {
87 |
88 | // Request
89 |
90 | jo.put("Method", token);
91 | jo.put("Request-URI", x.nextToken());
92 | jo.put("HTTP-Version", x.nextToken());
93 | }
94 |
95 | // Fields
96 |
97 | while (x.more()) {
98 | String name = x.nextTo(':');
99 | x.next(':');
100 | jo.put(name, x.nextTo('\0'));
101 | x.next();
102 | }
103 | return jo;
104 | }
105 |
106 |
107 | /**
108 | * Convert a JSONObject into an HTTP header. A request header must contain
109 | * {
110 | * Method: "POST" (for example),
111 | * "Request-URI": "/" (for example),
112 | * "HTTP-Version": "HTTP/1.1" (for example)
113 | * }
114 | * A response header must contain
115 | * {
116 | * "HTTP-Version": "HTTP/1.1" (for example),
117 | * "Status-Code": "200" (for example),
118 | * "Reason-Phrase": "OK" (for example)
119 | * }
120 | * Any other members of the JSONObject will be output as HTTP fields.
121 | * The result will end with two CRLF pairs.
122 | * @param jo A JSONObject
123 | * @return An HTTP header string.
124 | * @throws JSONException if the object does not contain enough
125 | * information.
126 | */
127 | public static String toString(JSONObject jo) throws JSONException {
128 | Iterator<[ [ ]]>
are ignored.
246 | * @param string The source string.
247 | * @return A JSONArray containing the structured data from the XML string.
248 | * @throws JSONException
249 | */
250 | public static JSONArray toJSONArray(String string) throws JSONException {
251 | return toJSONArray(new XMLTokener(string));
252 | }
253 |
254 |
255 | /**
256 | * Convert a well-formed (but not necessarily valid) XML string into a
257 | * JSONArray using the JsonML transform. Each XML tag is represented as
258 | * a JSONArray in which the first element is the tag name. If the tag has
259 | * attributes, then the second element will be JSONObject containing the
260 | * name/value pairs. If the tag contains children, then strings and
261 | * JSONArrays will represent the child content and tags.
262 | * Comments, prologs, DTDs, and <[ [ ]]>
are ignored.
263 | * @param x An XMLTokener.
264 | * @return A JSONArray containing the structured data from the XML string.
265 | * @throws JSONException
266 | */
267 | public static JSONArray toJSONArray(XMLTokener x) throws JSONException {
268 | return (JSONArray)parse(x, true, null);
269 | }
270 |
271 |
272 | /**
273 | * Convert a well-formed (but not necessarily valid) XML string into a
274 | * JSONObject using the JsonML transform. Each XML tag is represented as
275 | * a JSONObject with a "tagName" property. If the tag has attributes, then
276 | * the attributes will be in the JSONObject as properties. If the tag
277 | * contains children, the object will have a "childNodes" property which
278 | * will be an array of strings and JsonML JSONObjects.
279 |
280 | * Comments, prologs, DTDs, and <[ [ ]]>
are ignored.
281 | * @param x An XMLTokener of the XML source text.
282 | * @return A JSONObject containing the structured data from the XML string.
283 | * @throws JSONException
284 | */
285 | public static JSONObject toJSONObject(XMLTokener x) throws JSONException {
286 | return (JSONObject)parse(x, false, null);
287 | }
288 |
289 |
290 | /**
291 | * Convert a well-formed (but not necessarily valid) XML string into a
292 | * JSONObject using the JsonML transform. Each XML tag is represented as
293 | * a JSONObject with a "tagName" property. If the tag has attributes, then
294 | * the attributes will be in the JSONObject as properties. If the tag
295 | * contains children, the object will have a "childNodes" property which
296 | * will be an array of strings and JsonML JSONObjects.
297 |
298 | * Comments, prologs, DTDs, and <[ [ ]]>
are ignored.
299 | * @param string The XML source text.
300 | * @return A JSONObject containing the structured data from the XML string.
301 | * @throws JSONException
302 | */
303 | public static JSONObject toJSONObject(String string) throws JSONException {
304 | return toJSONObject(new XMLTokener(string));
305 | }
306 |
307 |
308 | /**
309 | * Reverse the JSONML transformation, making an XML text from a JSONArray.
310 | * @param ja A JSONArray.
311 | * @return An XML string.
312 | * @throws JSONException
313 | */
314 | public static String toString(JSONArray ja) throws JSONException {
315 | int i;
316 | JSONObject jo;
317 | String key;
318 | IteratorJSONString
interface allows a toJSONString()
4 | * method so that a class can change the behavior of
5 | * JSONObject.toString()
, JSONArray.toString()
,
6 | * and JSONWriter.value(
Object)
. The
7 | * toJSONString
method will be used instead of the default behavior
8 | * of using the Object's toString()
method and quoting the result.
9 | */
10 | public interface JSONString {
11 | /**
12 | * The toJSONString
method allows a class to produce its own JSON
13 | * serialization.
14 | *
15 | * @return A strictly syntactically correct JSON text.
16 | */
17 | public String toJSONString();
18 | }
19 |
--------------------------------------------------------------------------------
/CrunchbaseWrapper/src/org/json/JSONStringer.java:
--------------------------------------------------------------------------------
1 | package org.json;
2 |
3 | /*
4 | Copyright (c) 2006 JSON.org
5 |
6 | Permission is hereby granted, free of charge, to any person obtaining a copy
7 | of this software and associated documentation files (the "Software"), to deal
8 | in the Software without restriction, including without limitation the rights
9 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 | copies of the Software, and to permit persons to whom the Software is
11 | furnished to do so, subject to the following conditions:
12 |
13 | The above copyright notice and this permission notice shall be included in all
14 | copies or substantial portions of the Software.
15 |
16 | The Software shall be used for Good, not Evil.
17 |
18 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
21 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
23 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
24 | SOFTWARE.
25 | */
26 |
27 | import java.io.StringWriter;
28 |
29 | /**
30 | * JSONStringer provides a quick and convenient way of producing JSON text.
31 | * The texts produced strictly conform to JSON syntax rules. No whitespace is
32 | * added, so the results are ready for transmission or storage. Each instance of
33 | * JSONStringer can produce one JSON text.
34 | * value
method for appending
36 | * values to the
37 | * text, and a key
38 | * method for adding keys before values in objects. There are array
39 | * and endArray
methods that make and bound array values, and
40 | * object
and endObject
methods which make and bound
41 | * object values. All of these methods return the JSONWriter instance,
42 | * permitting cascade style. For example,
43 | * myString = new JSONStringer()
44 | * .object()
45 | * .key("JSON")
46 | * .value("Hello, World!")
47 | * .endObject()
48 | * .toString();
which produces the string
49 | * {"JSON":"Hello, World!"}
50 | * array
or object
.
52 | * There are no methods for adding commas or colons. JSONStringer adds them for
53 | * you. Objects and arrays can be nested up to 20 levels deep.
54 | * null
if there was a
70 | * problem in the construction of the JSON text (such as the calls to
71 | * array
were not properly balanced with calls to
72 | * endArray
).
73 | * @return The JSON text.
74 | */
75 | public String toString() {
76 | return this.mode == 'd' ? this.writer.toString() : null;
77 | }
78 | }
79 |
--------------------------------------------------------------------------------
/CrunchbaseWrapper/src/org/json/JSONTokener.java:
--------------------------------------------------------------------------------
1 | package org.json;
2 |
3 | import java.io.BufferedReader;
4 | import java.io.IOException;
5 | import java.io.InputStream;
6 | import java.io.InputStreamReader;
7 | import java.io.Reader;
8 | import java.io.StringReader;
9 |
10 | /*
11 | Copyright (c) 2002 JSON.org
12 |
13 | Permission is hereby granted, free of charge, to any person obtaining a copy
14 | of this software and associated documentation files (the "Software"), to deal
15 | in the Software without restriction, including without limitation the rights
16 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
17 | copies of the Software, and to permit persons to whom the Software is
18 | furnished to do so, subject to the following conditions:
19 |
20 | The above copyright notice and this permission notice shall be included in all
21 | copies or substantial portions of the Software.
22 |
23 | The Software shall be used for Good, not Evil.
24 |
25 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
26 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
27 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
28 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
29 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
30 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
31 | SOFTWARE.
32 | */
33 |
34 | /**
35 | * A JSONTokener takes a source string and extracts characters and tokens from
36 | * it. It is used by the JSONObject and JSONArray constructors to parse
37 | * JSON source strings.
38 | * @author JSON.org
39 | * @version 2014-05-03
40 | */
41 | public class JSONTokener {
42 |
43 | private long character;
44 | private boolean eof;
45 | private long index;
46 | private long line;
47 | private char previous;
48 | private Reader reader;
49 | private boolean usePrevious;
50 |
51 |
52 | /**
53 | * Construct a JSONTokener from a Reader.
54 | *
55 | * @param reader A reader.
56 | */
57 | public JSONTokener(Reader reader) {
58 | this.reader = reader.markSupported()
59 | ? reader
60 | : new BufferedReader(reader);
61 | this.eof = false;
62 | this.usePrevious = false;
63 | this.previous = 0;
64 | this.index = 0;
65 | this.character = 1;
66 | this.line = 1;
67 | }
68 |
69 |
70 | /**
71 | * Construct a JSONTokener from an InputStream.
72 | * @param inputStream The source.
73 | */
74 | public JSONTokener(InputStream inputStream) throws JSONException {
75 | this(new InputStreamReader(inputStream));
76 | }
77 |
78 |
79 | /**
80 | * Construct a JSONTokener from a string.
81 | *
82 | * @param s A source string.
83 | */
84 | public JSONTokener(String s) {
85 | this(new StringReader(s));
86 | }
87 |
88 |
89 | /**
90 | * Back up one character. This provides a sort of lookahead capability,
91 | * so that you can test for a digit or letter before attempting to parse
92 | * the next number or identifier.
93 | */
94 | public void back() throws JSONException {
95 | if (this.usePrevious || this.index <= 0) {
96 | throw new JSONException("Stepping back two steps is not supported");
97 | }
98 | this.index -= 1;
99 | this.character -= 1;
100 | this.usePrevious = true;
101 | this.eof = false;
102 | }
103 |
104 |
105 | /**
106 | * Get the hex value of a character (base16).
107 | * @param c A character between '0' and '9' or between 'A' and 'F' or
108 | * between 'a' and 'f'.
109 | * @return An int between 0 and 15, or -1 if c was not a hex digit.
110 | */
111 | public static int dehexchar(char c) {
112 | if (c >= '0' && c <= '9') {
113 | return c - '0';
114 | }
115 | if (c >= 'A' && c <= 'F') {
116 | return c - ('A' - 10);
117 | }
118 | if (c >= 'a' && c <= 'f') {
119 | return c - ('a' - 10);
120 | }
121 | return -1;
122 | }
123 |
124 | public boolean end() {
125 | return this.eof && !this.usePrevious;
126 | }
127 |
128 |
129 | /**
130 | * Determine if the source string still contains characters that next()
131 | * can consume.
132 | * @return true if not yet at the end of the source.
133 | */
134 | public boolean more() throws JSONException {
135 | this.next();
136 | if (this.end()) {
137 | return false;
138 | }
139 | this.back();
140 | return true;
141 | }
142 |
143 |
144 | /**
145 | * Get the next character in the source string.
146 | *
147 | * @return The next character, or 0 if past the end of the source string.
148 | */
149 | public char next() throws JSONException {
150 | int c;
151 | if (this.usePrevious) {
152 | this.usePrevious = false;
153 | c = this.previous;
154 | } else {
155 | try {
156 | c = this.reader.read();
157 | } catch (IOException exception) {
158 | throw new JSONException(exception);
159 | }
160 |
161 | if (c <= 0) { // End of stream
162 | this.eof = true;
163 | c = 0;
164 | }
165 | }
166 | this.index += 1;
167 | if (this.previous == '\r') {
168 | this.line += 1;
169 | this.character = c == '\n' ? 0 : 1;
170 | } else if (c == '\n') {
171 | this.line += 1;
172 | this.character = 0;
173 | } else {
174 | this.character += 1;
175 | }
176 | this.previous = (char) c;
177 | return this.previous;
178 | }
179 |
180 |
181 | /**
182 | * Consume the next character, and check that it matches a specified
183 | * character.
184 | * @param c The character to match.
185 | * @return The character.
186 | * @throws JSONException if the character does not match.
187 | */
188 | public char next(char c) throws JSONException {
189 | char n = this.next();
190 | if (n != c) {
191 | throw this.syntaxError("Expected '" + c + "' and instead saw '" +
192 | n + "'");
193 | }
194 | return n;
195 | }
196 |
197 |
198 | /**
199 | * Get the next n characters.
200 | *
201 | * @param n The number of characters to take.
202 | * @return A string of n characters.
203 | * @throws JSONException
204 | * Substring bounds error if there are not
205 | * n characters remaining in the source string.
206 | */
207 | public String next(int n) throws JSONException {
208 | if (n == 0) {
209 | return "";
210 | }
211 |
212 | char[] chars = new char[n];
213 | int pos = 0;
214 |
215 | while (pos < n) {
216 | chars[pos] = this.next();
217 | if (this.end()) {
218 | throw this.syntaxError("Substring bounds error");
219 | }
220 | pos += 1;
221 | }
222 | return new String(chars);
223 | }
224 |
225 |
226 | /**
227 | * Get the next char in the string, skipping whitespace.
228 | * @throws JSONException
229 | * @return A character, or 0 if there are no more characters.
230 | */
231 | public char nextClean() throws JSONException {
232 | for (;;) {
233 | char c = this.next();
234 | if (c == 0 || c > ' ') {
235 | return c;
236 | }
237 | }
238 | }
239 |
240 |
241 | /**
242 | * Return the characters up to the next close quote character.
243 | * Backslash processing is done. The formal JSON format does not
244 | * allow strings in single quotes, but an implementation is allowed to
245 | * accept them.
246 | * @param quote The quoting character, either
247 | * "
(double quote) or
248 | * '
(single quote).
249 | * @return A String.
250 | * @throws JSONException Unterminated string.
251 | */
252 | public String nextString(char quote) throws JSONException {
253 | char c;
254 | StringBuilder sb = new StringBuilder();
255 | for (;;) {
256 | c = this.next();
257 | switch (c) {
258 | case 0:
259 | case '\n':
260 | case '\r':
261 | throw this.syntaxError("Unterminated string");
262 | case '\\':
263 | c = this.next();
264 | switch (c) {
265 | case 'b':
266 | sb.append('\b');
267 | break;
268 | case 't':
269 | sb.append('\t');
270 | break;
271 | case 'n':
272 | sb.append('\n');
273 | break;
274 | case 'f':
275 | sb.append('\f');
276 | break;
277 | case 'r':
278 | sb.append('\r');
279 | break;
280 | case 'u':
281 | sb.append((char)Integer.parseInt(this.next(4), 16));
282 | break;
283 | case '"':
284 | case '\'':
285 | case '\\':
286 | case '/':
287 | sb.append(c);
288 | break;
289 | default:
290 | throw this.syntaxError("Illegal escape.");
291 | }
292 | break;
293 | default:
294 | if (c == quote) {
295 | return sb.toString();
296 | }
297 | sb.append(c);
298 | }
299 | }
300 | }
301 |
302 |
303 | /**
304 | * Get the text up but not including the specified character or the
305 | * end of line, whichever comes first.
306 | * @param delimiter A delimiter character.
307 | * @return A string.
308 | */
309 | public String nextTo(char delimiter) throws JSONException {
310 | StringBuilder sb = new StringBuilder();
311 | for (;;) {
312 | char c = this.next();
313 | if (c == delimiter || c == 0 || c == '\n' || c == '\r') {
314 | if (c != 0) {
315 | this.back();
316 | }
317 | return sb.toString().trim();
318 | }
319 | sb.append(c);
320 | }
321 | }
322 |
323 |
324 | /**
325 | * Get the text up but not including one of the specified delimiter
326 | * characters or the end of line, whichever comes first.
327 | * @param delimiters A set of delimiter characters.
328 | * @return A string, trimmed.
329 | */
330 | public String nextTo(String delimiters) throws JSONException {
331 | char c;
332 | StringBuilder sb = new StringBuilder();
333 | for (;;) {
334 | c = this.next();
335 | if (delimiters.indexOf(c) >= 0 || c == 0 ||
336 | c == '\n' || c == '\r') {
337 | if (c != 0) {
338 | this.back();
339 | }
340 | return sb.toString().trim();
341 | }
342 | sb.append(c);
343 | }
344 | }
345 |
346 |
347 | /**
348 | * Get the next value. The value can be a Boolean, Double, Integer,
349 | * JSONArray, JSONObject, Long, or String, or the JSONObject.NULL object.
350 | * @throws JSONException If syntax error.
351 | *
352 | * @return An object.
353 | */
354 | public Object nextValue() throws JSONException {
355 | char c = this.nextClean();
356 | String string;
357 |
358 | switch (c) {
359 | case '"':
360 | case '\'':
361 | return this.nextString(c);
362 | case '{':
363 | this.back();
364 | return new JSONObject(this);
365 | case '[':
366 | this.back();
367 | return new JSONArray(this);
368 | }
369 |
370 | /*
371 | * Handle unquoted text. This could be the values true, false, or
372 | * null, or it can be a number. An implementation (such as this one)
373 | * is allowed to also accept non-standard forms.
374 | *
375 | * Accumulate characters until we reach the end of the text or a
376 | * formatting character.
377 | */
378 |
379 | StringBuilder sb = new StringBuilder();
380 | while (c >= ' ' && ",:]}/\\\"[{;=#".indexOf(c) < 0) {
381 | sb.append(c);
382 | c = this.next();
383 | }
384 | this.back();
385 |
386 | string = sb.toString().trim();
387 | if ("".equals(string)) {
388 | throw this.syntaxError("Missing value");
389 | }
390 | return JSONObject.stringToValue(string);
391 | }
392 |
393 |
394 | /**
395 | * Skip characters until the next character is the requested character.
396 | * If the requested character is not found, no characters are skipped.
397 | * @param to A character to skip to.
398 | * @return The requested character, or zero if the requested character
399 | * is not found.
400 | */
401 | public char skipTo(char to) throws JSONException {
402 | char c;
403 | try {
404 | long startIndex = this.index;
405 | long startCharacter = this.character;
406 | long startLine = this.line;
407 | this.reader.mark(1000000);
408 | do {
409 | c = this.next();
410 | if (c == 0) {
411 | this.reader.reset();
412 | this.index = startIndex;
413 | this.character = startCharacter;
414 | this.line = startLine;
415 | return c;
416 | }
417 | } while (c != to);
418 | } catch (IOException exception) {
419 | throw new JSONException(exception);
420 | }
421 | this.back();
422 | return c;
423 | }
424 |
425 |
426 | /**
427 | * Make a JSONException to signal a syntax error.
428 | *
429 | * @param message The error message.
430 | * @return A JSONException object, suitable for throwing
431 | */
432 | public JSONException syntaxError(String message) {
433 | return new JSONException(message + this.toString());
434 | }
435 |
436 |
437 | /**
438 | * Make a printable string of this JSONTokener.
439 | *
440 | * @return " at {index} [character {character} line {line}]"
441 | */
442 | public String toString() {
443 | return " at " + this.index + " [character " + this.character + " line " +
444 | this.line + "]";
445 | }
446 | }
447 |
--------------------------------------------------------------------------------
/CrunchbaseWrapper/src/org/json/JSONWriter.java:
--------------------------------------------------------------------------------
1 | package org.json;
2 |
3 | import java.io.IOException;
4 | import java.io.Writer;
5 |
6 | /*
7 | Copyright (c) 2006 JSON.org
8 |
9 | Permission is hereby granted, free of charge, to any person obtaining a copy
10 | of this software and associated documentation files (the "Software"), to deal
11 | in the Software without restriction, including without limitation the rights
12 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
13 | copies of the Software, and to permit persons to whom the Software is
14 | furnished to do so, subject to the following conditions:
15 |
16 | The above copyright notice and this permission notice shall be included in all
17 | copies or substantial portions of the Software.
18 |
19 | The Software shall be used for Good, not Evil.
20 |
21 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
22 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
23 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
24 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
25 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
26 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
27 | SOFTWARE.
28 | */
29 |
30 | /**
31 | * JSONWriter provides a quick and convenient way of producing JSON text.
32 | * The texts produced strictly conform to JSON syntax rules. No whitespace is
33 | * added, so the results are ready for transmission or storage. Each instance of
34 | * JSONWriter can produce one JSON text.
35 | * value
method for appending
37 | * values to the
38 | * text, and a key
39 | * method for adding keys before values in objects. There are array
40 | * and endArray
methods that make and bound array values, and
41 | * object
and endObject
methods which make and bound
42 | * object values. All of these methods return the JSONWriter instance,
43 | * permitting a cascade style. For example,
44 | * new JSONWriter(myWriter)
45 | * .object()
46 | * .key("JSON")
47 | * .value("Hello, World!")
48 | * .endObject();
which writes
49 | * {"JSON":"Hello, World!"}
50 | * array
or object
.
52 | * There are no methods for adding commas or colons. JSONWriter adds them for
53 | * you. Objects and arrays can be nested up to 20 levels deep.
54 | * endArray
will be appended to this array. The
135 | * endArray
method must be called to mark the array's end.
136 | * @return this
137 | * @throws JSONException If the nesting is too deep, or if the object is
138 | * started in the wrong place (for example as a key or after the end of the
139 | * outermost array or object).
140 | */
141 | public JSONWriter array() throws JSONException {
142 | if (this.mode == 'i' || this.mode == 'o' || this.mode == 'a') {
143 | this.push(null);
144 | this.append("[");
145 | this.comma = false;
146 | return this;
147 | }
148 | throw new JSONException("Misplaced array.");
149 | }
150 |
151 | /**
152 | * End something.
153 | * @param mode Mode
154 | * @param c Closing character
155 | * @return this
156 | * @throws JSONException If unbalanced.
157 | */
158 | private JSONWriter end(char mode, char c) throws JSONException {
159 | if (this.mode != mode) {
160 | throw new JSONException(mode == 'a'
161 | ? "Misplaced endArray."
162 | : "Misplaced endObject.");
163 | }
164 | this.pop(mode);
165 | try {
166 | this.writer.write(c);
167 | } catch (IOException e) {
168 | throw new JSONException(e);
169 | }
170 | this.comma = true;
171 | return this;
172 | }
173 |
174 | /**
175 | * End an array. This method most be called to balance calls to
176 | * array
.
177 | * @return this
178 | * @throws JSONException If incorrectly nested.
179 | */
180 | public JSONWriter endArray() throws JSONException {
181 | return this.end('a', ']');
182 | }
183 |
184 | /**
185 | * End an object. This method most be called to balance calls to
186 | * object
.
187 | * @return this
188 | * @throws JSONException If incorrectly nested.
189 | */
190 | public JSONWriter endObject() throws JSONException {
191 | return this.end('k', '}');
192 | }
193 |
194 | /**
195 | * Append a key. The key will be associated with the next value. In an
196 | * object, every value must be preceded by a key.
197 | * @param string A key string.
198 | * @return this
199 | * @throws JSONException If the key is out of place. For example, keys
200 | * do not belong in arrays or if the key is null.
201 | */
202 | public JSONWriter key(String string) throws JSONException {
203 | if (string == null) {
204 | throw new JSONException("Null key.");
205 | }
206 | if (this.mode == 'k') {
207 | try {
208 | this.stack[this.top - 1].putOnce(string, Boolean.TRUE);
209 | if (this.comma) {
210 | this.writer.write(',');
211 | }
212 | this.writer.write(JSONObject.quote(string));
213 | this.writer.write(':');
214 | this.comma = false;
215 | this.mode = 'o';
216 | return this;
217 | } catch (IOException e) {
218 | throw new JSONException(e);
219 | }
220 | }
221 | throw new JSONException("Misplaced key.");
222 | }
223 |
224 |
225 | /**
226 | * Begin appending a new object. All keys and values until the balancing
227 | * endObject
will be appended to this object. The
228 | * endObject
method must be called to mark the object's end.
229 | * @return this
230 | * @throws JSONException If the nesting is too deep, or if the object is
231 | * started in the wrong place (for example as a key or after the end of the
232 | * outermost array or object).
233 | */
234 | public JSONWriter object() throws JSONException {
235 | if (this.mode == 'i') {
236 | this.mode = 'o';
237 | }
238 | if (this.mode == 'o' || this.mode == 'a') {
239 | this.append("{");
240 | this.push(new JSONObject());
241 | this.comma = false;
242 | return this;
243 | }
244 | throw new JSONException("Misplaced object.");
245 |
246 | }
247 |
248 |
249 | /**
250 | * Pop an array or object scope.
251 | * @param c The scope to close.
252 | * @throws JSONException If nesting is wrong.
253 | */
254 | private void pop(char c) throws JSONException {
255 | if (this.top <= 0) {
256 | throw new JSONException("Nesting error.");
257 | }
258 | char m = this.stack[this.top - 1] == null ? 'a' : 'k';
259 | if (m != c) {
260 | throw new JSONException("Nesting error.");
261 | }
262 | this.top -= 1;
263 | this.mode = this.top == 0
264 | ? 'd'
265 | : this.stack[this.top - 1] == null
266 | ? 'a'
267 | : 'k';
268 | }
269 |
270 | /**
271 | * Push an array or object scope.
272 | * @param jo The scope to open.
273 | * @throws JSONException If nesting is too deep.
274 | */
275 | private void push(JSONObject jo) throws JSONException {
276 | if (this.top >= maxdepth) {
277 | throw new JSONException("Nesting too deep.");
278 | }
279 | this.stack[this.top] = jo;
280 | this.mode = jo == null ? 'a' : 'k';
281 | this.top += 1;
282 | }
283 |
284 |
285 | /**
286 | * Append either the value true
or the value
287 | * false
.
288 | * @param b A boolean.
289 | * @return this
290 | * @throws JSONException
291 | */
292 | public JSONWriter value(boolean b) throws JSONException {
293 | return this.append(b ? "true" : "false");
294 | }
295 |
296 | /**
297 | * Append a double value.
298 | * @param d A double.
299 | * @return this
300 | * @throws JSONException If the number is not finite.
301 | */
302 | public JSONWriter value(double d) throws JSONException {
303 | return this.value(new Double(d));
304 | }
305 |
306 | /**
307 | * Append a long value.
308 | * @param l A long.
309 | * @return this
310 | * @throws JSONException
311 | */
312 | public JSONWriter value(long l) throws JSONException {
313 | return this.append(Long.toString(l));
314 | }
315 |
316 |
317 | /**
318 | * Append an object value.
319 | * @param object The object to append. It can be null, or a Boolean, Number,
320 | * String, JSONObject, or JSONArray, or an object that implements JSONString.
321 | * @return this
322 | * @throws JSONException If the value is out of sequence.
323 | */
324 | public JSONWriter value(Object object) throws JSONException {
325 | return this.append(JSONObject.valueToString(object));
326 | }
327 | }
328 |
--------------------------------------------------------------------------------
/CrunchbaseWrapper/src/org/json/Property.java:
--------------------------------------------------------------------------------
1 | package org.json;
2 |
3 | /*
4 | Copyright (c) 2002 JSON.org
5 |
6 | Permission is hereby granted, free of charge, to any person obtaining a copy
7 | of this software and associated documentation files (the "Software"), to deal
8 | in the Software without restriction, including without limitation the rights
9 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 | copies of the Software, and to permit persons to whom the Software is
11 | furnished to do so, subject to the following conditions:
12 |
13 | The above copyright notice and this permission notice shall be included in all
14 | copies or substantial portions of the Software.
15 |
16 | The Software shall be used for Good, not Evil.
17 |
18 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
21 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
23 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
24 | SOFTWARE.
25 | */
26 |
27 | import java.util.Enumeration;
28 | import java.util.Iterator;
29 | import java.util.Properties;
30 |
31 | /**
32 | * Converts a Property file data into JSONObject and back.
33 | * @author JSON.org
34 | * @version 2015-05-05
35 | */
36 | public class Property {
37 | /**
38 | * Converts a property file object into a JSONObject. The property file object is a table of name value pairs.
39 | * @param properties java.util.Properties
40 | * @return JSONObject
41 | * @throws JSONException
42 | */
43 | public static JSONObject toJSONObject(java.util.Properties properties) throws JSONException {
44 | JSONObject jo = new JSONObject();
45 | if (properties != null && !properties.isEmpty()) {
46 | Enumeration> enumProperties = properties.propertyNames();
47 | while(enumProperties.hasMoreElements()) {
48 | String name = (String)enumProperties.nextElement();
49 | jo.put(name, properties.getProperty(name));
50 | }
51 | }
52 | return jo;
53 | }
54 |
55 | /**
56 | * Converts the JSONObject into a property file object.
57 | * @param jo JSONObject
58 | * @return java.util.Properties
59 | * @throws JSONException
60 | */
61 | public static Properties toProperties(JSONObject jo) throws JSONException {
62 | Properties properties = new Properties();
63 | if (jo != null) {
64 | Iterator
67 | * & (ampersand) is replaced by &
68 | * < (less than) is replaced by <
69 | * > (greater than) is replaced by >
70 | * " (double quote) is replaced by "
71 | *
72 | * @param string The string to be escaped.
73 | * @return The escaped string.
74 | */
75 | public static String escape(String string) {
76 | StringBuilder sb = new StringBuilder(string.length());
77 | for (int i = 0, length = string.length(); i < length; i++) {
78 | char c = string.charAt(i);
79 | switch (c) {
80 | case '&':
81 | sb.append("&");
82 | break;
83 | case '<':
84 | sb.append("<");
85 | break;
86 | case '>':
87 | sb.append(">");
88 | break;
89 | case '"':
90 | sb.append(""");
91 | break;
92 | case '\'':
93 | sb.append("'");
94 | break;
95 | default:
96 | sb.append(c);
97 | }
98 | }
99 | return sb.toString();
100 | }
101 |
102 | /**
103 | * Throw an exception if the string contains whitespace.
104 | * Whitespace is not allowed in tagNames and attributes.
105 | * @param string A string.
106 | * @throws JSONException
107 | */
108 | public static void noSpace(String string) throws JSONException {
109 | int i, length = string.length();
110 | if (length == 0) {
111 | throw new JSONException("Empty string.");
112 | }
113 | for (i = 0; i < length; i += 1) {
114 | if (Character.isWhitespace(string.charAt(i))) {
115 | throw new JSONException("'" + string +
116 | "' contains a space character.");
117 | }
118 | }
119 | }
120 |
121 | /**
122 | * Scan the content following the named tag, attaching it to the context.
123 | * @param x The XMLTokener containing the source string.
124 | * @param context The JSONObject that will include the new material.
125 | * @param name The tag name.
126 | * @return true if the close tag is processed.
127 | * @throws JSONException
128 | */
129 | private static boolean parse(XMLTokener x, JSONObject context,
130 | String name) throws JSONException {
131 | char c;
132 | int i;
133 | JSONObject jsonobject = null;
134 | String string;
135 | String tagName;
136 | Object token;
137 |
138 | // Test for and skip past these forms:
139 | //
140 | //
141 | //
142 | // ... ?>
143 | // Report errors for these forms:
144 | // <>
145 | // <=
146 | // <<
147 |
148 | token = x.nextToken();
149 |
150 | // ");
157 | return false;
158 | }
159 | x.back();
160 | } else if (c == '[') {
161 | token = x.nextToken();
162 | if ("CDATA".equals(token)) {
163 | if (x.next() == '[') {
164 | string = x.nextCDATA();
165 | if (string.length() > 0) {
166 | context.accumulate("content", string);
167 | }
168 | return false;
169 | }
170 | }
171 | throw x.syntaxError("Expected 'CDATA['");
172 | }
173 | i = 1;
174 | do {
175 | token = x.nextMeta();
176 | if (token == null) {
177 | throw x.syntaxError("Missing '>' after ' 0);
184 | return false;
185 | } else if (token == QUEST) {
186 |
187 | //
188 |
189 | x.skipPast("?>");
190 | return false;
191 | } else if (token == SLASH) {
192 |
193 | // Close tag
194 |
195 | token = x.nextToken();
196 | if (name == null) {
197 | throw x.syntaxError("Mismatched close tag " + token);
198 | }
199 | if (!token.equals(name)) {
200 | throw x.syntaxError("Mismatched " + name + " and " + token);
201 | }
202 | if (x.nextToken() != GT) {
203 | throw x.syntaxError("Misshaped close tag");
204 | }
205 | return true;
206 |
207 | } else if (token instanceof Character) {
208 | throw x.syntaxError("Misshaped tag");
209 |
210 | // Open tag <
211 |
212 | } else {
213 | tagName = (String)token;
214 | token = null;
215 | jsonobject = new JSONObject();
216 | for (;;) {
217 | if (token == null) {
218 | token = x.nextToken();
219 | }
220 |
221 | // attribute = value
222 |
223 | if (token instanceof String) {
224 | string = (String)token;
225 | token = x.nextToken();
226 | if (token == EQ) {
227 | token = x.nextToken();
228 | if (!(token instanceof String)) {
229 | throw x.syntaxError("Missing value");
230 | }
231 | jsonobject.accumulate(string,
232 | XML.stringToValue((String)token));
233 | token = null;
234 | } else {
235 | jsonobject.accumulate(string, "");
236 | }
237 |
238 | // Empty tag <.../>
239 |
240 | } else if (token == SLASH) {
241 | if (x.nextToken() != GT) {
242 | throw x.syntaxError("Misshaped tag");
243 | }
244 | if (jsonobject.length() > 0) {
245 | context.accumulate(tagName, jsonobject);
246 | } else {
247 | context.accumulate(tagName, "");
248 | }
249 | return false;
250 |
251 | // Content, between <...> and
252 |
253 | } else if (token == GT) {
254 | for (;;) {
255 | token = x.nextContent();
256 | if (token == null) {
257 | if (tagName != null) {
258 | throw x.syntaxError("Unclosed tag " + tagName);
259 | }
260 | return false;
261 | } else if (token instanceof String) {
262 | string = (String)token;
263 | if (string.length() > 0) {
264 | jsonobject.accumulate("content",
265 | XML.stringToValue(string));
266 | }
267 |
268 | // Nested element
269 |
270 | } else if (token == LT) {
271 | if (parse(x, jsonobject, tagName)) {
272 | if (jsonobject.length() == 0) {
273 | context.accumulate(tagName, "");
274 | } else if (jsonobject.length() == 1 &&
275 | jsonobject.opt("content") != null) {
276 | context.accumulate(tagName,
277 | jsonobject.opt("content"));
278 | } else {
279 | context.accumulate(tagName, jsonobject);
280 | }
281 | return false;
282 | }
283 | }
284 | }
285 | } else {
286 | throw x.syntaxError("Misshaped tag");
287 | }
288 | }
289 | }
290 | }
291 |
292 |
293 | /**
294 | * Try to convert a string into a number, boolean, or null. If the string
295 | * can't be converted, return the string. This is much less ambitious than
296 | * JSONObject.stringToValue, especially because it does not attempt to
297 | * convert plus forms, octal forms, hex forms, or E forms lacking decimal
298 | * points.
299 | * @param string A String.
300 | * @return A simple JSON value.
301 | */
302 | public static Object stringToValue(String string) {
303 | if ("true".equalsIgnoreCase(string)) {
304 | return Boolean.TRUE;
305 | }
306 | if ("false".equalsIgnoreCase(string)) {
307 | return Boolean.FALSE;
308 | }
309 | if ("null".equalsIgnoreCase(string)) {
310 | return JSONObject.NULL;
311 | }
312 |
313 | // If it might be a number, try converting it, first as a Long, and then as a
314 | // Double. If that doesn't work, return the string.
315 |
316 | try {
317 | char initial = string.charAt(0);
318 | if (initial == '-' || (initial >= '0' && initial <= '9')) {
319 | Long value = new Long(string);
320 | if (value.toString().equals(string)) {
321 | return value;
322 | }
323 | }
324 | } catch (Exception ignore) {
325 | try {
326 | Double value = new Double(string);
327 | if (value.toString().equals(string)) {
328 | return value;
329 | }
330 | } catch (Exception ignoreAlso) {
331 | }
332 | }
333 | return string;
334 | }
335 |
336 |
337 | /**
338 | * Convert a well-formed (but not necessarily valid) XML string into a
339 | * JSONObject. Some information may be lost in this transformation
340 | * because JSON is a data format and XML is a document format. XML uses
341 | * elements, attributes, and content text, while JSON uses unordered
342 | * collections of name/value pairs and arrays of values. JSON does not
343 | * does not like to distinguish between elements and attributes.
344 | * Sequences of similar elements are represented as JSONArrays. Content
345 | * text may be placed in a "content" member. Comments, prologs, DTDs, and
346 | * <[ [ ]]>
are ignored.
347 | * @param string The source string.
348 | * @return A JSONObject containing the structured data from the XML string.
349 | * @throws JSONException
350 | */
351 | public static JSONObject toJSONObject(String string) throws JSONException {
352 | JSONObject jo = new JSONObject();
353 | XMLTokener x = new XMLTokener(string);
354 | while (x.more() && x.skipPast("<")) {
355 | parse(x, jo, null);
356 | }
357 | return jo;
358 | }
359 |
360 |
361 | /**
362 | * Convert a JSONObject into a well-formed, element-normal XML string.
363 | * @param object A JSONObject.
364 | * @return A string.
365 | * @throws JSONException
366 | */
367 | public static String toString(Object object) throws JSONException {
368 | return toString(object, null);
369 | }
370 |
371 |
372 | /**
373 | * Convert a JSONObject into a well-formed, element-normal XML string.
374 | * @param object A JSONObject.
375 | * @param tagName The optional name of the enclosing tag.
376 | * @return A string.
377 | * @throws JSONException
378 | */
379 | public static String toString(Object object, String tagName)
380 | throws JSONException {
381 | StringBuilder sb = new StringBuilder();
382 | int i;
383 | JSONArray ja;
384 | JSONObject jo;
385 | String key;
386 | Iterator]]>
.
61 | * @throws JSONException If the ]]>
is not found.
62 | */
63 | public String nextCDATA() throws JSONException {
64 | char c;
65 | int i;
66 | StringBuilder sb = new StringBuilder();
67 | for (;;) {
68 | c = next();
69 | if (end()) {
70 | throw syntaxError("Unclosed CDATA");
71 | }
72 | sb.append(c);
73 | i = sb.length() - 3;
74 | if (i >= 0 && sb.charAt(i) == ']' &&
75 | sb.charAt(i + 1) == ']' && sb.charAt(i + 2) == '>') {
76 | sb.setLength(i);
77 | return sb.toString();
78 | }
79 | }
80 | }
81 |
82 |
83 | /**
84 | * Get the next XML outer token, trimming whitespace. There are two kinds
85 | * of tokens: the '<' character which begins a markup tag, and the content
86 | * text between markup tags.
87 | *
88 | * @return A string, or a '<' Character, or null if there is no more
89 | * source text.
90 | * @throws JSONException
91 | */
92 | public Object nextContent() throws JSONException {
93 | char c;
94 | StringBuilder sb;
95 | do {
96 | c = next();
97 | } while (Character.isWhitespace(c));
98 | if (c == 0) {
99 | return null;
100 | }
101 | if (c == '<') {
102 | return XML.LT;
103 | }
104 | sb = new StringBuilder();
105 | for (;;) {
106 | if (c == '<' || c == 0) {
107 | back();
108 | return sb.toString().trim();
109 | }
110 | if (c == '&') {
111 | sb.append(nextEntity(c));
112 | } else {
113 | sb.append(c);
114 | }
115 | c = next();
116 | }
117 | }
118 |
119 |
120 | /**
121 | * Return the next entity. These entities are translated to Characters:
122 | * & ' > < "
.
123 | * @param ampersand An ampersand character.
124 | * @return A Character or an entity String if the entity is not recognized.
125 | * @throws JSONException If missing ';' in XML entity.
126 | */
127 | public Object nextEntity(char ampersand) throws JSONException {
128 | StringBuilder sb = new StringBuilder();
129 | for (;;) {
130 | char c = next();
131 | if (Character.isLetterOrDigit(c) || c == '#') {
132 | sb.append(Character.toLowerCase(c));
133 | } else if (c == ';') {
134 | break;
135 | } else {
136 | throw syntaxError("Missing ';' in XML entity: &" + sb);
137 | }
138 | }
139 | String string = sb.toString();
140 | Object object = entity.get(string);
141 | return object != null ? object : ampersand + string + ";";
142 | }
143 |
144 |
145 | /**
146 | * Returns the next XML meta token. This is used for skipping over
147 | * and ...?> structures.
148 | * @return Syntax characters (< > / = ! ?
) are returned as
149 | * Character, and strings and names are returned as Boolean. We don't care
150 | * what the values actually are.
151 | * @throws JSONException If a string is not properly closed or if the XML
152 | * is badly structured.
153 | */
154 | public Object nextMeta() throws JSONException {
155 | char c;
156 | char q;
157 | do {
158 | c = next();
159 | } while (Character.isWhitespace(c));
160 | switch (c) {
161 | case 0:
162 | throw syntaxError("Misshaped meta tag");
163 | case '<':
164 | return XML.LT;
165 | case '>':
166 | return XML.GT;
167 | case '/':
168 | return XML.SLASH;
169 | case '=':
170 | return XML.EQ;
171 | case '!':
172 | return XML.BANG;
173 | case '?':
174 | return XML.QUEST;
175 | case '"':
176 | case '\'':
177 | q = c;
178 | for (;;) {
179 | c = next();
180 | if (c == 0) {
181 | throw syntaxError("Unterminated string");
182 | }
183 | if (c == q) {
184 | return Boolean.TRUE;
185 | }
186 | }
187 | default:
188 | for (;;) {
189 | c = next();
190 | if (Character.isWhitespace(c)) {
191 | return Boolean.TRUE;
192 | }
193 | switch (c) {
194 | case 0:
195 | case '<':
196 | case '>':
197 | case '/':
198 | case '=':
199 | case '!':
200 | case '?':
201 | case '"':
202 | case '\'':
203 | back();
204 | return Boolean.TRUE;
205 | }
206 | }
207 | }
208 | }
209 |
210 |
211 | /**
212 | * Get the next XML Token. These tokens are found inside of angle
213 | * brackets. It may be one of these characters: / > = ! ?
or it
214 | * may be a string wrapped in single quotes or double quotes, or it may be a
215 | * name.
216 | * @return a String or a Character.
217 | * @throws JSONException If the XML is not well formed.
218 | */
219 | public Object nextToken() throws JSONException {
220 | char c;
221 | char q;
222 | StringBuilder sb;
223 | do {
224 | c = next();
225 | } while (Character.isWhitespace(c));
226 | switch (c) {
227 | case 0:
228 | throw syntaxError("Misshaped element");
229 | case '<':
230 | throw syntaxError("Misplaced '<'");
231 | case '>':
232 | return XML.GT;
233 | case '/':
234 | return XML.SLASH;
235 | case '=':
236 | return XML.EQ;
237 | case '!':
238 | return XML.BANG;
239 | case '?':
240 | return XML.QUEST;
241 |
242 | // Quoted string
243 |
244 | case '"':
245 | case '\'':
246 | q = c;
247 | sb = new StringBuilder();
248 | for (;;) {
249 | c = next();
250 | if (c == 0) {
251 | throw syntaxError("Unterminated string");
252 | }
253 | if (c == q) {
254 | return sb.toString();
255 | }
256 | if (c == '&') {
257 | sb.append(nextEntity(c));
258 | } else {
259 | sb.append(c);
260 | }
261 | }
262 | default:
263 |
264 | // Name
265 |
266 | sb = new StringBuilder();
267 | for (;;) {
268 | sb.append(c);
269 | c = next();
270 | if (Character.isWhitespace(c)) {
271 | return sb.toString();
272 | }
273 | switch (c) {
274 | case 0:
275 | return sb.toString();
276 | case '>':
277 | case '/':
278 | case '=':
279 | case '!':
280 | case '?':
281 | case '[':
282 | case ']':
283 | back();
284 | return sb.toString();
285 | case '<':
286 | case '"':
287 | case '\'':
288 | throw syntaxError("Bad character in a name");
289 | }
290 | }
291 | }
292 | }
293 |
294 |
295 | /**
296 | * Skip characters until past the requested string.
297 | * If it is not found, we are left at the end of the source with a result of false.
298 | * @param to A string to skip past.
299 | * @throws JSONException
300 | */
301 | public boolean skipPast(String to) throws JSONException {
302 | boolean b;
303 | char c;
304 | int i;
305 | int j;
306 | int offset = 0;
307 | int length = to.length();
308 | char[] circle = new char[length];
309 |
310 | /*
311 | * First fill the circle buffer with as many characters as are in the
312 | * to string. If we reach an early end, bail.
313 | */
314 |
315 | for (i = 0; i < length; i += 1) {
316 | c = next();
317 | if (c == 0) {
318 | return false;
319 | }
320 | circle[i] = c;
321 | }
322 |
323 | /* We will loop, possibly for all of the remaining characters. */
324 |
325 | for (;;) {
326 | j = offset;
327 | b = true;
328 |
329 | /* Compare the circle buffer with the to string. */
330 |
331 | for (i = 0; i < length; i += 1) {
332 | if (circle[j] != to.charAt(i)) {
333 | b = false;
334 | break;
335 | }
336 | j += 1;
337 | if (j >= length) {
338 | j -= length;
339 | }
340 | }
341 |
342 | /* If we exit the loop with b intact, then victory is ours. */
343 |
344 | if (b) {
345 | return true;
346 | }
347 |
348 | /* Get the next character. If there isn't one, then defeat is ours. */
349 |
350 | c = next();
351 | if (c == 0) {
352 | return false;
353 | }
354 | /*
355 | * Shove the character in the circle buffer and advance the
356 | * circle offset. The offset is mod n.
357 | */
358 | circle[offset] = c;
359 | offset += 1;
360 | if (offset >= length) {
361 | offset -= length;
362 | }
363 | }
364 | }
365 | }
366 |
--------------------------------------------------------------------------------
/CrunchbaseWrapper/src/servlets/Authenticate.java:
--------------------------------------------------------------------------------
1 | package servlets;
2 |
3 | import java.io.IOException;
4 |
5 | import javax.servlet.ServletException;
6 | import javax.servlet.annotation.WebServlet;
7 | import javax.servlet.http.HttpServlet;
8 | import javax.servlet.http.HttpServletRequest;
9 | import javax.servlet.http.HttpServletResponse;
10 |
11 | import utilities.Authentication;
12 |
13 | /**
14 | * Servlet implementation class Authenticate
15 | */
16 | @WebServlet("/auth")
17 | public class Authenticate extends HttpServlet {
18 | private static final long serialVersionUID = 1L;
19 |
20 | /**
21 | * @see HttpServlet#HttpServlet()
22 | */
23 | public Authenticate() {
24 | super();
25 | }
26 |
27 | /**
28 | * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
29 | * response)
30 | */
31 | protected void doGet(HttpServletRequest request,
32 | HttpServletResponse response) throws ServletException, IOException {
33 | doPost(request, response);
34 | }
35 |
36 | /**
37 | * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
38 | * response)
39 | */
40 | protected void doPost(HttpServletRequest request,
41 | HttpServletResponse response) throws ServletException, IOException {
42 | String apikey = Authentication.getAPIKey(request);
43 | boolean isValid = Authentication.isAPIKeyValid(apikey);
44 |
45 | if (apikey == null || !isValid) {
46 | Authentication.requireAuthentication(request, response);
47 | } else {
48 | response.getWriter().println("Authorization was successfull!");
49 | }
50 |
51 |
52 | }
53 |
54 | }
55 |
--------------------------------------------------------------------------------
/CrunchbaseWrapper/src/servlets/CrunchbaseWrapper.java:
--------------------------------------------------------------------------------
1 | package servlets;
2 |
3 | import java.io.IOException;
4 | import java.io.StringWriter;
5 | import java.util.concurrent.TimeUnit;
6 |
7 | import javax.servlet.ServletException;
8 | import javax.servlet.annotation.WebServlet;
9 | import javax.servlet.http.HttpServlet;
10 | import javax.servlet.http.HttpServletRequest;
11 | import javax.servlet.http.HttpServletResponse;
12 |
13 | import com.hp.hpl.jena.rdf.model.Model;
14 | import com.hp.hpl.jena.rdf.model.ModelFactory;
15 | import com.hp.hpl.jena.rdf.model.Resource;
16 | import com.squareup.okhttp.HttpUrl;
17 | import com.squareup.okhttp.OkHttpClient;
18 | import com.squareup.okhttp.Request;
19 | import com.squareup.okhttp.Response;
20 |
21 | import utilities.Authentication;
22 | import utilities.JSONLDHelper;
23 | import utilities.MappingUtility;
24 | import utilities.SPARQLLoader;
25 |
26 | /**
27 | * Servlet implementation class CrunchbaseWrapper
28 | */
29 | @WebServlet("/api/*")
30 | public class CrunchbaseWrapper extends HttpServlet {
31 | private static final long serialVersionUID = 1L;
32 | private static final boolean SPARQLendpoint = false; // introduced 2018
33 | private static final String CB_API_BASE_URI = "https://api.crunchbase.com/v3.1";
34 |
35 | // local testing
36 | //private static final String PUBLIC_URL = "http://localhost:8081/CrunchbaseWrapper/api/";
37 | //private static final String PUBLIC_CONTEXT = "http://localhost:8081/CrunchbaseWrapper/context.jsonld";
38 | // productive use
39 | // private static final String PUBLIC_URL = "http://corse.informatik.uni-freiburg.de:8080/CrunchbaseWrapper/api/";
40 | // private static final String PUBLIC_CONTEXT = "http://corse.informatik.uni-freiburg.de:8080/CrunchbaseWrapper/context.jsonld";
41 | private static final String PUBLIC_URL = "http://linked-crunchbase.org/api/";
42 | private static final String PUBLIC_CONTEXT = "http://linked-crunchbase.org/context.jsonld";
43 |
44 | private OkHttpClient client;
45 | private JSONLDHelper jsonldHelper;
46 |
47 | /**
48 | * @see HttpServlet#HttpServlet()
49 | */
50 | public CrunchbaseWrapper() {
51 | super();
52 | }
53 |
54 | /**
55 | * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
56 | * response)
57 | */
58 | protected void doGet(HttpServletRequest request, HttpServletResponse response)
59 | throws ServletException, IOException {
60 | doPost(request, response);
61 | }
62 |
63 | /**
64 | * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
65 | * response)
66 | */
67 | protected void doPost(HttpServletRequest request, HttpServletResponse response)
68 | throws ServletException, IOException {
69 | String endpoint = request.getRequestURI().replaceFirst(request.getContextPath(), ""); // extract api endpoint
70 | // from
71 | // query
72 | endpoint = endpoint.substring(4, endpoint.length()); // remove "/api"
73 |
74 | // determine accept header
75 | String requestAccept = request.getHeader("Accept");
76 | if (requestAccept == null) {
77 | // set default here
78 | requestAccept = "application/ld+json";
79 | }
80 |
81 | MappingUtility mu = (MappingUtility) getServletContext().getAttribute(Listener.MAPPING);
82 |
83 | if (request.getHeader("Authorization") == null) {
84 | if (SPARQLendpoint) {
85 | // load sparql stuff
86 | if (requestAccept.contains("json")) {
87 | response.getWriter().println(SPARQLLoader.loadTriple(endpoint, mu, "JSON-LD"));
88 | response.setCharacterEncoding("UTF-8");
89 | response.setContentType("application/ld+json");
90 | } else {
91 | response.getWriter().println(SPARQLLoader.loadTriple(endpoint, mu, "N-TRIPLES"));
92 | response.setCharacterEncoding("UTF-8");
93 | response.setContentType("text/turtle");
94 | }
95 | } else {
96 | /** use no SPARQL endpoint: **/
97 | if (requestAccept.contains("json")) {
98 | // response.getWriter().println(SPARQLLoader.loadTriple(endpoint, mu, "JSON-LD"));
99 | response.setCharacterEncoding("UTF-8");
100 | response.setContentType("application/ld+json");
101 | response.getWriter().println(addSameAsMappingPredicate(endpoint, mu, "JSON-LD"));
102 | } else {
103 | // response.getWriter().println(SPARQLLoader.loadTriple(endpoint, mu, "N-TRIPLES"));
104 | response.setCharacterEncoding("UTF-8");
105 | response.setContentType("text/turtle");
106 | response.getWriter().println(addSameAsMappingPredicate(endpoint, mu, "TTL"));
107 | }
108 | }
109 | } else {
110 | String apikey = Authentication.getAPIKey(request);
111 |
112 | jsonldHelper = new JSONLDHelper(PUBLIC_CONTEXT, CB_API_BASE_URI, PUBLIC_URL, mu);
113 | client = new OkHttpClient();
114 | client.setConnectTimeout(30, TimeUnit.SECONDS); // maybe increase,
115 | // crunchbase isnt
116 | // always fast
117 | String query = endpoint;
118 | if (request.getQueryString() != null) {
119 | query += "?" + request.getQueryString();
120 | }
121 |
122 | HttpUrl url = HttpUrl.parse(CB_API_BASE_URI + query);
123 |
124 | url = url.newBuilder().addQueryParameter("user_key", apikey).build();
125 | // finally build api request for crunchbase
126 | Request apiRequest = new Request.Builder().url(url).build();
127 | // get api response
128 | Response apiResponse = client.newCall(apiRequest).execute();
129 |
130 | // set response header of this servlet
131 | response.setHeader("Cache-Control", "private, no-store, no-cache, must-revalidate");
132 | response.setStatus(apiResponse.code());
133 | response.setCharacterEncoding("UTF-8");
134 |
135 | String result = apiResponse.body().string();
136 | // System.out.println(result);
137 |
138 | if (apiResponse.code() == 200) { // errorhandling
139 | // content negotiation
140 | if (requestAccept.contains("text/turtle") || requestAccept.contains("application/x-turtle")) {
141 | // do rdf
142 | response.setContentType("text/turtle");
143 | response.getWriter().write(jsonldHelper.json2rdf(result, endpoint));
144 | // System.out.println("DidRDF");
145 | } else if (requestAccept.contains("application/ld+json") || requestAccept.contains("*/*")) {
146 | // do jsonld
147 | response.setContentType("application/ld+json");
148 | response.getWriter().write(jsonldHelper.json2jsonld(result, endpoint));
149 | System.out.println("DidJSONLD");
150 | } else {
151 | // just display the json from crunchbase
152 | response.setContentType("application/json");
153 | response.getWriter().write(result);
154 | }
155 | } else if (apiResponse.code() == 401) {
156 | Authentication.requireAuthentication(request, response);
157 | return;
158 | } else {
159 | response.getWriter().write(result);
160 | }
161 | }
162 | }
163 |
164 | /**
165 | * this function generates the baseURI for the RDF transformation from the given
166 | * endpoint and public URL
167 | *
168 | * @param endpoint
169 | * @return
170 | */
171 | private static String getBaseURI(String endpoint) {
172 | if (endpoint.endsWith("/")) {
173 | endpoint = endpoint.substring(0, endpoint.lastIndexOf("/"));
174 | }
175 | return PUBLIC_URL + "api" + endpoint.substring(0, endpoint.lastIndexOf("/") + 1);
176 | }
177 |
178 | /**
179 | * Takes the given permalink, processes it a bit, checks whether it's an
180 | * organization or a person, then grabs the appropriate mapping for it and
181 | * outputs it with a SAMEAS predicate into a model which is transformed into the
182 | * wanted form of type and returned as such in string representation
183 | *
184 | * @param permalink link to be processed
185 | * @param mu MappingUtility object used for the organization/people
186 | * mapping
187 | * @param type what kind of output type is chosen (e.g. "RDF/XML",
188 | * "RDF/XML-ABBREV", "N-TRIPLE", "TURTLE", (and "TTL") or "N3")
189 | * @return String representation of