I am working on code (java) that will open up a selenium headless browser with HTML Unit webdriver and then take a screenshot. Unfortunately, HTML Unit does not support screenshots on its own, so I had to download an extended version:
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.URL;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.openqa.selenium.Capabilities;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriverException;
import org.openqa.selenium.htmlunit.HtmlUnitDriver;
import org.openqa.selenium.internal.Base64Encoder;
import org.openqa.selenium.remote.CapabilityType;
import org.openqa.selenium.remote.DesiredCapabilities;
import com.gargoylesoftware.htmlunit.BrowserVersion;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.WebRequest;
import com.gargoylesoftware.htmlunit.WebWindow;
import com.gargoylesoftware.htmlunit.html.HtmlElement;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
public class ScreenCaptureHtmlUnitDriver extends HtmlUnitDriver implements TakesScreenshot {
private static Map<String, byte[]> imagesCache = Collections.synchronizedMap(new HashMap<String, byte[]>());
private static Map<String, String> cssjsCache = Collections.synchronizedMap(new HashMap<String, String>());
// http://stackoverflow.com/questions/4652777/java-regex-to-get-the-urls-from-css
private final static Pattern cssUrlPattern = Pattern.compile("background(-image)?[\\s]*:[^url]*url[\\s]*\\([\\s]*([^\\)]*)[\\s]*\\)[\\s]*");// ?<url>
public ScreenCaptureHtmlUnitDriver() {
super();
}
public ScreenCaptureHtmlUnitDriver(boolean enableJavascript) {
super(enableJavascript);
}
public ScreenCaptureHtmlUnitDriver(Capabilities capabilities) {
super(capabilities);
}
public ScreenCaptureHtmlUnitDriver(BrowserVersion version) {
super(version);
DesiredCapabilities var = ((DesiredCapabilities) getCapabilities());
var.setCapability(CapabilityType.TAKES_SCREENSHOT, true);
}
//#Override
#SuppressWarnings("unchecked")
public <X> X getScreenshotAs(OutputType<X> target) throws WebDriverException {
byte[] archive = new byte[0];
try {
archive = downloadCssAndImages(getWebClient(), (HtmlPage) getCurrentWindow().getEnclosedPage());
} catch (Exception e) {
}
if(target.equals(OutputType.BASE64)){
return target.convertFromBase64Png(new Base64Encoder().encode(archive));
}
if(target.equals(OutputType.BYTES)){
return (X) archive;
}
return (X) archive;
}
// http://stackoverflow.com/questions/2244272/how-can-i-tell-htmlunits-webclient-to-download-images-and-css
protected byte[] downloadCssAndImages(WebClient webClient, HtmlPage page) throws Exception {
WebWindow currentWindow = webClient.getCurrentWindow();
Map<String, String> urlMapping = new HashMap<String, String>();
Map<String, byte[]> files = new HashMap<String, byte[]>();
WebWindow window = null;
try {
window = webClient.getWebWindowByName(page.getUrl().toString()+"_screenshot");
webClient.getPage(window, new WebRequest(page.getUrl()));
} catch (Exception e) {
window = webClient.openWindow(page.getUrl(), page.getUrl().toString()+"_screenshot");
}
String xPathExpression = "//*[name() = 'img' or name() = 'link' and (#type = 'text/css' or #type = 'image/x-icon') or #type = 'text/javascript']";
List<?> resultList = page.getByXPath(xPathExpression);
Iterator<?> i = resultList.iterator();
while (i.hasNext()) {
try {
HtmlElement el = (HtmlElement) i.next();
String resourceSourcePath = el.getAttribute("src").equals("") ? el.getAttribute("href") : el
.getAttribute("src");
if (resourceSourcePath == null || resourceSourcePath.equals(""))
continue;
URL resourceRemoteLink = page.getFullyQualifiedUrl(resourceSourcePath);
String resourceLocalPath = mapLocalUrl(page, resourceRemoteLink, resourceSourcePath, urlMapping);
urlMapping.put(resourceSourcePath, resourceLocalPath);
if (!resourceRemoteLink.toString().endsWith(".css")) {
byte[] image = downloadImage(webClient, window, resourceRemoteLink);
files.put(resourceLocalPath, image);
} else {
String css = downloadCss(webClient, window, resourceRemoteLink);
for (String cssImagePath : getLinksFromCss(css)) {
URL cssImagelink = page.getFullyQualifiedUrl(cssImagePath.replace("\"", "").replace("\'", "")
.replace(" ", ""));
String cssImageLocalPath = mapLocalUrl(page, cssImagelink, cssImagePath, urlMapping);
files.put(cssImageLocalPath, downloadImage(webClient, window, cssImagelink));
}
files.put(resourceLocalPath, replaceRemoteUrlsWithLocal(css, urlMapping)
.replace("resources/", "./").getBytes());
}
} catch (Exception e) {
}
}
String pagesrc = replaceRemoteUrlsWithLocal(page.getWebResponse().getContentAsString(), urlMapping);
files.put("page.html", pagesrc.getBytes());
webClient.setCurrentWindow(currentWindow);
return createZip(files);
}
String downloadCss(WebClient webClient, WebWindow window, URL resourceUrl) throws Exception {
if (cssjsCache.get(resourceUrl.toString()) == null) {
cssjsCache.put(resourceUrl.toString(), webClient.getPage(window, new WebRequest(resourceUrl))
.getWebResponse().getContentAsString());
}
return cssjsCache.get(resourceUrl.toString());
}
byte[] downloadImage(WebClient webClient, WebWindow window, URL resourceUrl) throws Exception {
if (imagesCache.get(resourceUrl.toString()) == null) {
imagesCache.put(
resourceUrl.toString(),
IOUtils.toByteArray(webClient.getPage(window, new WebRequest(resourceUrl)).getWebResponse()
.getContentAsStream()));
}
return imagesCache.get(resourceUrl.toString());
}
public static byte[] createZip(Map<String, byte[]> files) throws IOException {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ZipOutputStream zipfile = new ZipOutputStream(bos);
Iterator<String> i = files.keySet().iterator();
String fileName = null;
ZipEntry zipentry = null;
while (i.hasNext()) {
fileName = i.next();
zipentry = new ZipEntry(fileName);
zipfile.putNextEntry(zipentry);
zipfile.write(files.get(fileName));
}
zipfile.close();
return bos.toByteArray();
}
List<String> getLinksFromCss(String css) {
List<String> result = new LinkedList<String>();
Matcher m = cssUrlPattern.matcher(css);
while (m.find()) { // find next match
result.add( m.group(2));
}
return result;
}
String replaceRemoteUrlsWithLocal(String source, Map<String, String> replacement) {
for (String object : replacement.keySet()) {
// background:url(http://org.com/images/image.gif)
source = source.replace(object, replacement.get(object));
}
return source;
}
String mapLocalUrl(HtmlPage page, URL link, String path, Map<String, String> replacementToAdd) throws Exception {
String resultingFileName = "resources/" + FilenameUtils.getName(link.getFile());
replacementToAdd.put(path, resultingFileName);
return resultingFileName;
}
}
Anyway, I found this code, but I am unsure how to use this code to actually take a screenshot.
I would like the screenshot to be a .jpg and to be able to be stored in a certain folder.
In the long haul, I am also going to need to run the screenshot code repeatedly.
Any help would be appreciated.
Related
I would like to group specific files based on their file names from multiple paths. I have followed this stackoverflow link. I have not been able to loop through each file after I start streaming the path to find that specific file name.
Here are the paths with files contents:
/var/tmp/data_sample1/data2_first_example.set.csv
/var/tmp/data_sample1/data3_first_example.set.csv
/var/tmp/data_sample1/data1_first_example.set.csv
/var/tmp/data_sample2/data2_second_example.set.csv
/var/tmp/data_sample2/data1_second_example.set.csv
/var/tmp/data_sample2/data3_second_example.set.csv
/tmp/csv_files/data_sample3/data2_third_example.set.csv
/tmp/csv_files/data_sample3/data1_third_example.set.csv
/tmp/csv_files/data_sample3/data3_third_example.set.csv
Enum Class:
enum PersonType {
A,
B
}
FileName.java
import java.util.Arrays;
import java.util.List;
public class FileName {
private final String first = "_first_sample";
private final String second = "_second_sample";
private final String third = "_third_sample";
private final List<String> filenames = Arrays.asList(first, second, third);
public List<String> getFilenames() {
return filenames;
}
}
CSVFiles.java
import java.io.File;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;
import java.util.stream.Collectors;
public class CSVFiles {
private PersonType personType;
private List<String> fileNames = new ArrayList<>();
private List<File> firstSample = new ArrayList<>();
private List<File> secondSample = new ArrayList<>();
private List<File> thirdSample = new ArrayList<>();
public CSVFiles(PersonType personType, List<String> paths) {
if (personType == PersonType.A) {
this.personType = personType;
FileName fileName = new FileName();
this.fileNames = fileName.getFilenames();
setCSVFiles(paths);
}
}
public List<File> setCSVFiles(List<String> paths) {
List<Path> collect = paths.stream()
.flatMap(path -> {
try {
return Files.find(Paths.get(path), Integer.MAX_VALUE,
(p, attrs) -> attrs.isRegularFile()
&& p.toString().contains(".set")
&& p.toString().endsWith(".csv")
);
} catch (IOException ex) {
throw new UncheckedIOException(ex);
}
}).collect(Collectors.toList());
return collect.stream()
.map(Path::toFile)
.filter(file -> {
if (file.getName().contains("_first_sample")) {
firstSample.add(file);
return true;
} else if (file.getName().contains("_second_sample")) {
secondSample.add(file);
return true;
} else if (file.getName().contains("_third_sample")) {
thirdSample.add(file);
return true;
}
return false;
})
.collect(Collectors.toList());
}
}
CSVFilesTest.java
import org.junit.Test;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.*;
public class CSVFilesTest {
#Test
public void test() {
String data_sample1 = "/var/tmp/data_sample1";
String data_sample2 = "/var/tmp/data_sample2";
String data_sample3 = "/tmp/csv_files/data_sample3";
List<String> paths = Arrays.asList(data_sample1, data_sample2, data_sample3);
System.out.println(paths);
CSVFiles csvFiles = new CSVFiles(PersonType.A, paths);
}
}
Desired Output:
firstSample: [data1_first_example.set.csv, data2_first_example.set.csv, data3_first_example.set.csv]
secondSample: [data1_second_example.set.csv, data2_second_example.set.csv, data3_second_example.set.csv]
thirdSample: [data1_third_example.set.csv, data2_third_example.set.csv, data3_third_example.set.csv]
Any feedback is appreciated!
Solution thanks to "sync it" comments:
public Map<String, List<String>> setCSVFiles(List<String> paths) {
List<Path> collect = paths.stream()
.flatMap(path -> {
try {
return Files.find(Paths.get(path), Integer.MAX_VALUE,
(p, attrs) -> attrs.isRegularFile()
&& p.toString().contains(".set")
&& p.toString().endsWith(".csv")
);
} catch (IOException ex) {
throw new UncheckedIOException(ex);
}
}).collect(Collectors.toList());
return collect.stream()
.map(Path::toString)
.collect(Collectors.groupingBy(path ->
path.substring(path.lastIndexOf("/")+1)
));
}
Hi i have created a handler in java for getting the events from dynamo DB
Here is my code
package com.Lambda.dynamodb;
import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.LambdaLogger;
import com.amazonaws.services.lambda.runtime.RequestHandler;
import com.amazonaws.services.lambda.runtime.events.DynamodbEvent;
import com.amazonaws.services.lambda.runtime.events.DynamodbEvent.DynamodbStreamRecord;
public class DDBEventProcessor implements
RequestHandler<DynamodbEvent, String> {
public String handleRequest(DynamodbEvent ddbEvent, Context context) {
for (DynamodbStreamRecord record : ddbEvent.getRecords()){
System.out.println(record.getEventID());
System.out.println(record.getEventName());
System.out.println(record.getDynamodb().toString());
}
return "Successfully processed " + ddbEvent.getRecords().size() + " records.";
}
}
Lambda function able to write the events in cloudwatch but the challenge is i have to index all the streamed records to the AWS elasticsearch service endpoint and index it.
while search through blogs i got few code samples in python and node.js but my requirement is i have to build this lambda function in java
Could anyone please suggest how to achieve this in java lambda function?
Hi i have included the code below may helpful to some one. Dynamo DB streams to index the document in elasticsearch both inside AWS and outside AWS
package com.Firstlambda;
import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.RequestHandler;
import com.amazonaws.auth.AWS4Signer;
import com.amazonaws.auth.AWSCredentialsProvider;
import com.amazonaws.auth.DefaultAWSCredentialsProviderChain;
import com.amazonaws.services.dynamodbv2.document.Item;
import com.amazonaws.services.dynamodbv2.document.ItemUtils;
import com.amazonaws.services.dynamodbv2.model.AttributeValue;
import com.amazonaws.services.lambda.runtime.events.DynamodbEvent;
import com.amazonaws.services.lambda.runtime.events.DynamodbEvent.DynamodbStreamRecord;
import org.apache.http.HttpHost;
import org.apache.http.HttpRequestInterceptor;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.json.JSONObject;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class HelloWorld implements RequestHandler<DynamodbEvent, String> {
private static String serviceName = "es";
private static String region = "us-east-1";
private static String aesEndpoint = ""
private static String index = "";
private static String type = "_doc";
static final AWSCredentialsProvider credentialsProvider = new DefaultAWSCredentialsProviderChain();
public String handleRequest(DynamodbEvent ddbEvent, Context context) {
for (DynamodbStreamRecord record : ddbEvent.getRecords()) {
System.out.println("EventName : " + record.getEventName());
System.out.println("EventName : " + record.getDynamodb());
//AWS outside
RestHighLevelClient esClient = esClient();
//AWS outside
//AWS Inside
//RestHighLevelClient esClient = esClient(serviceName, region);
//AWS Inside
if (record.getEventName().toLowerCase().equals("insert")) {
String JsonString = getJsonstring(record.getDynamodb().getNewImage());
String JsonUniqueId = GetIdfromJsonString(JsonString);
IndexRequest indexRequest = new IndexRequest(index, type, JsonUniqueId);
indexRequest.source(JsonString, XContentType.JSON);
try {
IndexResponse indexResponse = esClient.index(indexRequest, RequestOptions.DEFAULT);
System.out.println(indexResponse.toString());
return "Successfully processed " + ddbEvent.getRecords().size() + " records.";
} catch (IOException e) {
System.out.println(e.getMessage());
}
} else if (record.getEventName().toLowerCase().equals("modify")) {
String JsonString = getJsonstring(record.getDynamodb().getNewImage());
String JsonUniqueId = GetIdfromJsonString(JsonString);
UpdateRequest request = new UpdateRequest(index, type, JsonUniqueId);
String jsonString = JsonString;
request.doc(jsonString, XContentType.JSON);
try {
UpdateResponse updateResponse = esClient.update(
request, RequestOptions.DEFAULT);
System.out.println(updateResponse.toString());
return "Successfully processed " + ddbEvent.getRecords().size() + " records.";
} catch (IOException e) {
System.out.println(e.getMessage());
}
} else {
System.out.println("remove");
System.out.println("KEYID : " + record.getDynamodb().getKeys().get("ID").getN());
String deletedId = record.getDynamodb().getKeys().get("ID").getN();
DeleteRequest request = new DeleteRequest(index, type, deletedId);
try {
DeleteResponse deleteResponse = esClient.delete(
request, RequestOptions.DEFAULT);
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
}
return "Successfullyprocessed";
}
public String getJsonstring(Map<String, AttributeValue> newIma) {
String json = null;
Map<String, AttributeValue> newImage = newIma;
List<Map<String, AttributeValue>> listOfMaps = new ArrayList<Map<String, AttributeValue>>();
listOfMaps.add(newImage);
List<Item> itemList = ItemUtils.toItemList(listOfMaps);
for (Item item : itemList) {
json = item.toJSON();
}
return json;
}
public String GetIdfromJsonString(String Json) {
JSONObject jsonObj = new JSONObject(Json);
return String.valueOf(jsonObj.getInt("ID"));
}
// Adds the interceptor to the ES REST client
// public static RestHighLevelClient esClient(String serviceName, String region) {
// AWS4Signer signer = new AWS4Signer();
// signer.setServiceName(serviceName);
// signer.setRegionName(region);
// HttpRequestInterceptor interceptor = new AWSRequestSigningApacheInterceptor(serviceName, signer, credentialsProvider);
// return new RestHighLevelClient(RestClient.builder(HttpHost.create(aesEndpoint)).setHttpClientConfigCallback(hacb -> hacb.addInterceptorLast(interceptor)));
// }
public static RestHighLevelClient esClient() {
String host = "d9bc7cbca5ec49ea96a6ea683f70caca.eastus2.azure.elastic-cloud.com";
int port = 9200;
String userName = "elastic";
String password = "L4Nfnle3wxLmV95lffwsf$Ub46hp";
String protocol = "https";
final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(AuthScope.ANY,
new UsernamePasswordCredentials(userName, password));
RestClientBuilder builder = RestClient.builder(new HttpHost(host, port, protocol))
.setHttpClientConfigCallback(httpClientBuilder -> httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider));
RestHighLevelClient client = new RestHighLevelClient(builder);
return client;
}
}
This is just a sample code has to be modified based on our requirements
I had/have a java application which is loading a game, and i tried to make it into an applet and loading into a html webpage, but when i try and load it i get and error and it doesn't load, could someone please help me and tell me what i am doing wrong?
Java application code:
import java.applet.*;
import java.awt.Dimension;
import java.io.*;
import java.net.*;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.*;
public class OSRSLoader
implements AppletStub
{
static JMenuBar menubar;
static JFrame i;
public static void main(String args[])
throws Exception
{
new OSRSLoader();
}
public OSRSLoader()
throws Exception, FileNotFoundException
{
JFrame i = new JFrame("RS Oldschool Client Beta V1:00");
i.setSize(new Dimension(763, 514));
i.setPreferredSize(new Dimension(763, 514));
JLabel label = new JLabel();
ImageIcon icon = new ImageIcon(new URL("http://www.runescape.com/image/rsp777/oldschool_ani.gif"));
icon.setImageObserver(null);
label.setIcon(icon);
i.add(label);
i.pack();
i.setVisible(true);
String str = getPageSource(new URL("http://oldschool38.runescape.com"));
Pattern pattern = Pattern.compile("gamep\\w+");
Matcher match = pattern.matcher(str);
if(match.find())
{
OSRSLoader stub = new OSRSLoader(Pattern.compile("<param name=\"([^\\s]+)\"\\s+value=\"([^>]*)\">"), str);
Download("http://oldschool38.runescape.com/", (new StringBuilder(String.valueOf(match.group(0)))).append(".jar").toString());
stub.setCodeBase(new URL((new StringBuilder("http://oldschool38.runescape.com/")).append(match.group(0)).append(".jar").toString()));
stub.setDocumentBase(new URL((new StringBuilder("http://oldschool38.runescape.com/")).append(match.group(0)).append(".jar").toString()));
stub.getParameter((String)parameters.get("java_arguments"));
URLClassLoader classLoader = new URLClassLoader(new URL[] {
new URL("file:gamepack.jar")
});
Applet applet = (Applet)classLoader.loadClass("client").newInstance();
applet.setStub(stub);
applet.setSize(new Dimension(763, 514));
applet.init();
applet.start();
i.add(applet);
i.pack();
i.setDefaultCloseOperation(3);
label.setVisible(false);
}
}
public OSRSLoader(Pattern parameterPattern, String frameSource)
{
String key;
String value;
for(Matcher param = parameterPattern.matcher(frameSource); param.find(); System.out.println((new StringBuilder("Parameter Loaded. Key = ")).append(key).append(", value =").append(value).toString()))
{
key = param.group(1);
value = param.group(2);
parameters.put(key, value);
}
}
private String getPageSource(URL url)
throws IOException, InterruptedException
{
URLConnection cn = url.openConnection();
cn.addRequestProperty("Accept", "text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5");
cn.addRequestProperty("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.7");
cn.addRequestProperty("Accept-Encoding", "gzip,deflate");
cn.addRequestProperty("Accept-Language", "en-gb,en;q=0.5");
cn.addRequestProperty("Connection", "keep-alive");
cn.addRequestProperty("Host", "www.runescape.com");
cn.addRequestProperty("Keep-Alive", "300");
cn.addRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; rv:9.0.1) Gecko/20100101 Firefox/9.01");
DataInputStream di = new DataInputStream(cn.getInputStream());
byte tmp[] = new byte[cn.getContentLength()];
di.readFully(tmp);
di.close();
Thread.sleep(250 + (int)Math.random() * 500);
return new String(tmp);
}
public void appletResize(int i, int j)
{
}
public void setCodeBase(URL codeBase)
{
this.codeBase = codeBase;
}
public void setDocumentBase(URL documentBase)
{
this.documentBase = documentBase;
}
public AppletContext getAppletContext()
{
return null;
}
public URL getCodeBase()
{
return codeBase;
}
public URL getDocumentBase()
{
return documentBase;
}
public String getParameter(String name)
{
return (String)parameters.get(name);
}
public boolean isActive()
{
return false;
}
public static void Download(String world, String archive)
throws Exception
{
URLConnection jarConnection = (new URL((new StringBuilder(String.valueOf(world))).append(archive).toString())).openConnection();
FileOutputStream out = new FileOutputStream("./gamepack.jar");
InputStream input = jarConnection.getInputStream();
byte info[] = new byte[1024];
int ln;
while((ln = input.read(info)) != -1)
out.write(info, 0, ln);
}
private static Map parameters = new HashMap();
private URL codeBase;
private URL documentBase;
}
Java applet code:
import java.applet.*;
import java.awt.*;
import java.io.DataInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLClassLoader;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class Main extends Applet implements AppletStub {
public void init() {
}
public void run() throws FileNotFoundException, Exception {
new Main();
}
public Main() throws Exception, FileNotFoundException {
String str = getPageSource(new URL("http://oldschool38.runescape.com"));
Pattern pattern = Pattern.compile("gamep\\w+");
Matcher match = pattern.matcher(str);
if(match.find())
{
Main stub = new Main(Pattern.compile("<param name=\"([^\\s]+)\"\\s+value=\"([^>]*)\">"), str);
Download("http://oldschool38.runescape.com/", (new StringBuilder(String.valueOf(match.group(0)))).append(".jar").toString());
stub.setCodeBase(new URL((new StringBuilder("http://oldschool38.runescape.com/")).append(match.group(0)).append(".jar").toString()));
stub.setDocumentBase(new URL((new StringBuilder("http://oldschool38.runescape.com/")).append(match.group(0)).append(".jar").toString()));
stub.getParameter((String)parameters.get("java_arguments"));
URLClassLoader classLoader = new URLClassLoader(new URL[] {
new URL("file:gamepack.jar")
});
Applet applet = (Applet)classLoader.loadClass("client").newInstance();
applet.setStub(stub);
applet.setPreferredSize(new Dimension(765, 503));
applet.setSize(new Dimension(765, 503));
applet.init();
applet.start();
}
}
public Main(Pattern parameterPattern, String frameSource)
{
String key;
String value;
for(Matcher param = parameterPattern.matcher(frameSource); param.find(); System.out.println((new StringBuilder("Parameter Loaded. Key = ")).append(key).append(", value =").append(value).toString()))
{
key = param.group(1);
value = param.group(2);
parameters.put(key, value);
}
}
private String getPageSource(URL url)
throws IOException, InterruptedException
{
URLConnection cn = url.openConnection();
cn.addRequestProperty("Accept", "text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5");
cn.addRequestProperty("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.7");
cn.addRequestProperty("Accept-Encoding", "gzip,deflate");
cn.addRequestProperty("Accept-Language", "en-gb,en;q=0.5");
cn.addRequestProperty("Connection", "keep-alive");
cn.addRequestProperty("Host", "www.runescape.com");
cn.addRequestProperty("Keep-Alive", "300");
cn.addRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; rv:9.0.1) Gecko/20100101 Firefox/9.01");
DataInputStream di = new DataInputStream(cn.getInputStream());
byte tmp[] = new byte[cn.getContentLength()];
di.readFully(tmp);
di.close();
Thread.sleep(250 + (int)Math.random() * 500);
return new String(tmp);
}
public void appletResize(int i, int j)
{
}
public void setCodeBase(URL codeBase)
{
this.codeBase = codeBase;
}
public void setDocumentBase(URL documentBase)
{
this.documentBase = documentBase;
}
public AppletContext getAppletContext()
{
return null;
}
public URL getCodeBase()
{
return codeBase;
}
public URL getDocumentBase()
{
return documentBase;
}
public String getParameter(String name)
{
return (String)parameters.get(name);
}
public boolean isActive()
{
return false;
}
public static void Download(String world, String archive)
throws Exception
{
URLConnection jarConnection = (new URL((new StringBuilder(String.valueOf(world))).append(archive).toString())).openConnection();
FileOutputStream out = new FileOutputStream("./gamepack.jar");
InputStream input = jarConnection.getInputStream();
byte info[] = new byte[1024];
int ln;
while((ln = input.read(info)) != -1)
out.write(info, 0, ln);
}
private static Map parameters = new HashMap();
private URL codeBase;
private URL documentBase;
}
The error when i try and load it in html is: java.lang.reflect.invocationtargetexception
i click details and it sais:
Java Plug-in 10.25.2.17
Using JRE version 1.7.0_25-b17 Java HotSpot(TM) Client VM
User home directory = C:\Users\Will
----------------------------------------------------
c: clear console window
f: finalize objects on finalization queue
g: garbage collect
h: display this help message
l: dump classloader list
m: print memory usage
o: trigger logging
q: hide console
r: reload policy configuration
s: dump system and deployment properties
t: dump thread list
v: dump thread stack
x: clear classloader cache
0-5: set trace level to <n>
----------------------------------------------------
I'm writing code to upload a file in FileNet.
A standalone java program to take the some inputs, and upload it in FileNet. I'm new to FileNet. Can you help me out, How to do it?
You can use Document.java provided by IBM for your activities and many other Java classes
package fbis.apitocasemanager;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import com.user.DocumentUtil;
public class Addfilescasemanager {
/**
* #param args
*/
public static void addfiles_toicm(String directory, String lFolderPath)
{
try {
DocumentUtil.initialize();
String path = directory;
System.out.println("This is the path:..............................."
+ path);
String file_name;
File folder = new File(directory);
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++)
{
if (listOfFiles[i].isFile())
{
file_name = listOfFiles[i].getName();
System.out.println(file_name);
String filePaths = directory + file_name;
// File file = new File("C:\\FNB\\att.jpg");
File file = new File(filePaths);
InputStream attStream = null;
attStream = new FileInputStream(file);
DocumentUtil.addDocumentWithStream(lFolderPath, attStream,
"image/jpeg", file_name, "Document");
}
}
} catch (FileNotFoundException e)
{
e.printStackTrace();
}
}//end of method
public static void addfile_toicm(File file_name, String lFolderPath)
{
try {
DocumentUtil.initialize();
InputStream attStream = null;
attStream = new FileInputStream(file_name);
DocumentUtil.addDocumentWithStream(lFolderPath, attStream,
"image/jpeg", file_name.getName(), "Document");
System.out.println("File added successfully");
} catch (Exception e)
{
System.out.println(e.getMessage());
}
}//end of method
public static void main(String nag[])
{
addfiles_toicm("E:\\FSPATH1\\BLR_14122012_001F1A\\","/IBM Case Manager/Solution Deployments/Surakshate Solution for form 2/Case Types/FISB_FactoriesRegistration/Cases/2012/12/06/16/000000100103");
}
}
and my DocumentUtil class is
package com.user;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import javax.security.auth.Subject;
import com.filenet.api.collection.ContentElementList;
import com.filenet.api.constants.AutoClassify;
import com.filenet.api.constants.AutoUniqueName;
import com.filenet.api.constants.CheckinType;
import com.filenet.api.constants.DefineSecurityParentage;
import com.filenet.api.constants.RefreshMode;
import com.filenet.api.core.Connection;
import com.filenet.api.core.ContentTransfer;
import com.filenet.api.core.Document;
import com.filenet.api.core.Domain;
import com.filenet.api.core.Factory;
import com.filenet.api.core.Folder;
import com.filenet.api.core.ObjectStore;
import com.filenet.api.core.ReferentialContainmentRelationship;
import com.filenet.api.util.UserContext;
public class DocumentUtil {
public static ObjectStore objectStore = null;
public static Domain domain = null;
public static Connection connection = null;
public static void main(String[] args)
{
initialize();
/*
addDocumentWithPath("/FNB", "C:\\Users\\Administrator\\Desktop\\Sample.txt.txt",
"text/plain", "NNN", "Document");
*/
File file = new File("E:\\Users\\Administrator\\Desktop\\TT.txt");
FileInputStream fis = null;
try {
fis = new FileInputStream(file);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
addDocumentWithStream("/FNB", fis, "text/plain", "My New Doc", "Document");
}
public static void initialize()
{
System.setProperty("WASP.LOCATION", "C:\\Progra~1\\IBM\\WebSphere\\AppServer\\profiles\\AppSrv01\\installedApps\\P8Node01Cell\\FileNetEngine.ear \\cews.war\\WEB-INF\\classes\\com\\filenet\\engine\\wsi");
System.setProperty("SECURITY.AUTH.LOGIN.CONFIG",
"C:\\Progra~1\\IBM\\WebSphere\\AppServer\\profiles\\AppSrv01\\installedApps\\P8Node01Cell\\FileNetEngine.ear\\client-download.war\\FileNet\\Download\\dap501.153\\jaas.conf.wsi");
System.setProperty(":SECURITY.AUTH.LOGIN.CONFIG",
"C:\\Progra~1\\IBM\\WebSphere\\AppServer\\profiles\\AppSrv01\\installedApps\\P8Node01Cell\\FileNetEngine.ear\\client-download.war\\FileNet\\Download\\dap501.153\\jaas.conf.wsi");
System.setProperty("java.security.auth.login.config","C:\\Progra~1\\IBM\\WebSphere\\AppServer\\java\\jre");
connection = Factory.Connection.getConnection(CEConnection.uri);
Subject sub = UserContext.createSubject(connection,
com.user.CEConnection.username, CEConnection.password,
CEConnection.stanza);
UserContext.get().pushSubject(sub);
domain = Factory.Domain.getInstance(connection, null);
objectStore = Factory.ObjectStore.fetchInstance(domain, "TARGET", null);
System.out.println("\n\n objectStore--> " + objectStore.get_DisplayName());
}
public static void addDocumentWithPath(String folderPath, String filePath,
String mimeType, String docName, String docClass) {
Folder folder = Factory.Folder.fetchInstance(objectStore,
folderPath, null);
System.out.println("\n\n Folder ID: " + folder.get_Id());
// Document doc = Factory.Document.createInstance(os, classId);
Document doc = CEUtil.createDocWithContent(new File(filePath), mimeType,
objectStore, docName, docClass);
doc.save(RefreshMode.REFRESH);
doc = CEUtil.createDocNoContent(mimeType, objectStore, docName, docClass);
doc.save(RefreshMode.REFRESH);
CEUtil.checkinDoc(doc);
ReferentialContainmentRelationship rcr = CEUtil.fileObject(objectStore, doc, folderPath);
rcr.save(RefreshMode.REFRESH);
}
public static void addDocumentWithStream(String folderPath,
InputStream inputStream, String mimeType,
String docName, String docClass) {
Folder folder = Factory.Folder.fetchInstance(objectStore,
folderPath, null);
System.out.println("\n\n Folder ID: " + folder.get_Id());
// Document doc = Factory.Document.createInstance(os, classId);
Document doc = Factory.Document.createInstance(objectStore, null);
ContentElementList contEleList = Factory.ContentElement.createList();
ContentTransfer ct = Factory.ContentTransfer.createInstance();
ct.setCaptureSource(inputStream);
ct.set_ContentType(mimeType);
ct.set_RetrievalName(docName);
contEleList.add(ct);
doc.set_ContentElements(contEleList);
doc.getProperties().putValue("DocumentTitle", docName);
doc.set_MimeType(mimeType);
doc.checkin(AutoClassify.AUTO_CLASSIFY, CheckinType.MAJOR_VERSION);
doc.save(RefreshMode.REFRESH);
ReferentialContainmentRelationship rcr = folder.file(doc,
AutoUniqueName.AUTO_UNIQUE, docName,
DefineSecurityParentage.DO_NOT_DEFINE_SECURITY_PARENTAGE);
rcr.save(RefreshMode.REFRESH);
/*
doc.save(RefreshMode.REFRESH);
doc = CEUtil.createDocNoContent(mimeType, objectStore, docName, docClass);
CEUtil.checkinDoc(doc);
ReferentialContainmentRelationship rcr = CEUtil.fileObject(objectStore, doc, folderPath);
rcr.save(RefreshMode.REFRESH);
*/
}
public static ObjectStore getObjecctStore()
{
if (objectStore != null) {
return objectStore;
}
// Make connection.
com.filenet.api.core.Connection conn = Factory.Connection
.getConnection(CEConnection.uri);
Subject subject = UserContext.createSubject(conn,
CEConnection.username, CEConnection.password, null);
UserContext.get().pushSubject(subject);
try {
// Get default domain.
Domain domain = Factory.Domain.getInstance(conn, null);
// Get object stores for domain.
objectStore = Factory.ObjectStore.fetchInstance(domain, "TARGET",
null);
System.out.println("\n\n Connection to Content Engine successful !!");
} finally {
UserContext.get().popSubject();
}
return objectStore;
}
}
The above answer is extremely good. Just wanted to save people some time but I don't have the points to comment so am adding this as an answer.
Eclipse wasted a lot of my time getting the above to work because it suggested the wrong classes to import. Here's the list of correct ones:
import com.filenet.api.collection.ContentElementList;
import com.filenet.api.constants.AutoClassify;
import com.filenet.api.constants.AutoUniqueName;
import com.filenet.api.constants.CheckinType;
import com.filenet.api.constants.DefineSecurityParentage;
import com.filenet.api.constants.RefreshMode;
import com.filenet.api.core.Document;
import com.filenet.api.core.ObjectStore;
import com.filenet.api.core.ContentTransfer;
import com.filenet.api.core.Folder;
import com.filenet.api.core.Factory;
import com.filenet.api.core.ReferentialContainmentRelationship;
this is my nodefinder.java file
package com.acme.web.action.executer;
import java.sql.ResultSet;
import java.util.Map;
import org.alfresco.web.bean.repository.Node;
import org.alfresco.web.bean.repository.Repository;
import org.alfresco.web.ui.common.component.UIActionLink;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import org.alfresco.service.cmr.model.FileFolderService;
import org.alfresco.service.cmr.repository.NodeRef;
import org.alfresco.service.cmr.repository.NodeService;
import org.alfresco.service.cmr.repository.StoreRef;
import org.alfresco.service.cmr.search.SearchParameters;
import org.alfresco.service.cmr.search.SearchService;
public class NodeFinder {
// private static final String = null;
SearchParameters sp = new SearchParameters();
private NodeService nodeService;
private FileFolderService fileFolderService;
//geting the filefolder service
public FileFolderService getFileFolderService() {
return fileFolderService;
}
// setting the file folder service
public void setFileFolderService(FileFolderService fileFolderService) {
this.fileFolderService = fileFolderService;
}
// getting the node servise
public NodeService getNodeService() {
return nodeService;
}
// setting the node server
public void setNodeService(NodeService nodeService) {
this.nodeService = nodeService;
}
public void execute(ActionEvent event) {
ResultSet resultSet_s = null;
UIActionLink comp = (UIActionLink) event.getComponent();
Map<String, String> params = comp.getParameterMap();
String id = params.get("id1");
System.out.println("1");
NodeRef actionedUponNodeRef = new NodeRef(Repository.getStoreRef(), id);
String qry_s = "#cm\\:name:train";
System.out.println("2");
SearchParameters sp_s = new SearchParameters();
System.out.println("3");
sp_s.addStore(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE);
sp_s.setLanguage(SearchService.LANGUAGE_LUCENE);
sp_s.setQuery(qry_s);
System.out.println( "4" );
Node node = new Node(actionedUponNodeRef);
System.out.println("5");
resultSet_s = (ResultSet) Repository.getServiceRegistry(
FacesContext.getCurrentInstance()).getSearchService().query(
sp_s);
System.out.println("5.1");
if (resultSet_s != null) {
System.out.println("6");
System.out.println("Node value is::::" + node.getName());
}
}
}
Because you imported java.sql.ResultSet instead of an alfresco class/interface compatible to org.alfresco.repo.search.impl.lucene.PagingLuceneResultSet
Look at that line ...(ResultSet) Repository.getServiceRegistry(..., then look at your exception and finally at your imports. There you will see that ResultSet is actually java.sql.ResultSet (which is indicated by your ClassCastException's message).
If you then look at the super classes or interfaces of org.alfresco.repo.search.impl.lucene.PagingLuceneResultSet I'd say you won't find any java.sql.ResultSet. That's why you get that exception.