Skip to content

Commit

Permalink
Resolve #240: merge branch 'philboeselager-lobid-organisations/#issue49'
Browse files Browse the repository at this point in the history
Pull request with commits:
 - Enable RestMap and deliver test
 - RestMap: catch all exceptions by returning null
  • Loading branch information
cboehme committed Oct 28, 2016
2 parents 9c7e543 + a72b80c commit 2ea12b6
Showing 1 changed file with 42 additions and 15 deletions.
57 changes: 42 additions & 15 deletions src/main/java/org/culturegraph/mf/morph/maps/RestMap.java
Original file line number Diff line number Diff line change
Expand Up @@ -15,42 +15,69 @@
*/
package org.culturegraph.mf.morph.maps;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.Charset;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.culturegraph.mf.exceptions.MetafactureException;

/**
* NOT WORKING YET
*
* @author "Markus Michael Geipel"
* @author "Markus Michael Geipel", "Philipp v. Böselager"
*
*/
public final class RestMap extends AbstractReadOnlyMap<String, String> {

private static final Pattern VAR_PATTERN = Pattern.compile("${key}",
Pattern.LITERAL);
private static final Pattern VAR_PATTERN = Pattern.compile("${key}", Pattern.LITERAL);
private String charsetName = "UTF-8";
private String url;

public void setUrl(final String url) {
public RestMap() {
}

public RestMap(String url) {
this.url = url;
}

@Override
public String get(final Object key) {
final Matcher matcher = VAR_PATTERN.matcher(url);
try {
final URL url = new URL(matcher.replaceAll(key.toString()));
final URLConnection con = url.openConnection();
// TODO correctly read from connection!
return (String) con.getContent();
String urlString = matcher.replaceAll(key.toString());
return readFromUrl(urlString);
} catch (IOException | URISyntaxException e) {
// There was no data result for the given URL
return null;
}
}

} catch (final IOException e) {
throw new MetafactureException(e);
private String readFromUrl(final String url) throws IOException, URISyntaxException {
InputStream inputStream = new URL(new URI(url.replace(" ", "%20")).toASCIIString()).openConnection()
.getInputStream();
try {
BufferedReader reader = new BufferedReader(
new InputStreamReader(inputStream, Charset.forName(charsetName)));
StringBuilder stringBuffer = new StringBuilder();
int value;
while ((value = reader.read()) != -1) {
stringBuffer.append((char) value);
}
return stringBuffer.toString();
} finally {
inputStream.close();
}
}

public void setUrl(final String url) {
this.url = url;
}

public void setCharsetName(String name) {
charsetName = name;
}

}

0 comments on commit 2ea12b6

Please sign in to comment.