diff
stringlengths 262
553k
| is_single_chunk
bool 2
classes | is_single_function
bool 1
class | buggy_function
stringlengths 20
391k
| fixed_function
stringlengths 0
392k
|
---|---|---|---|---|
diff --git a/webservice/src/main/java/org/daisy/pipeline/webservice/JobsResource.java b/webservice/src/main/java/org/daisy/pipeline/webservice/JobsResource.java
index 9a0b6e6b..db75babc 100644
--- a/webservice/src/main/java/org/daisy/pipeline/webservice/JobsResource.java
+++ b/webservice/src/main/java/org/daisy/pipeline/webservice/JobsResource.java
@@ -1,506 +1,506 @@
package org.daisy.pipeline.webservice;
import java.io.File;
import java.io.IOException;
import java.io.StringReader;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Iterator;
import java.util.List;
import java.util.zip.ZipFile;
import javax.xml.namespace.QName;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Source;
import javax.xml.transform.sax.SAXSource;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.daisy.common.base.Provider;
import org.daisy.common.transform.LazySaxSourceProvider;
import org.daisy.common.xproc.XProcInput;
import org.daisy.common.xproc.XProcOptionInfo;
import org.daisy.common.xproc.XProcPortInfo;
import org.daisy.pipeline.job.Job;
import org.daisy.pipeline.job.JobManager;
import org.daisy.pipeline.job.ResourceCollection;
import org.daisy.pipeline.job.ZipResourceContext;
import org.daisy.pipeline.script.ScriptRegistry;
import org.daisy.pipeline.script.XProcOptionMetadata;
import org.daisy.pipeline.script.XProcScript;
import org.daisy.pipeline.script.XProcScriptService;
import org.daisy.pipeline.webserviceutils.callback.Callback;
import org.daisy.pipeline.webserviceutils.callback.Callback.CallbackType;
import org.daisy.pipeline.webserviceutils.clients.Client;
import org.daisy.pipeline.webserviceutils.xml.JobXmlWriter;
import org.daisy.pipeline.webserviceutils.xml.JobsXmlWriter;
import org.daisy.pipeline.webserviceutils.xml.XmlUtils;
import org.daisy.pipeline.webserviceutils.xml.XmlWriterFactory;
import org.restlet.Request;
import org.restlet.data.MediaType;
import org.restlet.data.Status;
import org.restlet.ext.fileupload.RestletFileUpload;
import org.restlet.ext.xml.DomRepresentation;
import org.restlet.representation.Representation;
import org.restlet.resource.Get;
import org.restlet.resource.Post;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
// TODO: Auto-generated Javadoc
/**
* The Class JobsResource.
*/
public class JobsResource extends AuthenticatedResource {
/** The tempfile prefix. */
private final String tempfilePrefix = "p2ws";
private final String tempfileSuffix = ".zip";
private final String JOB_DATA_FIELD = "job-data";
private final String JOB_REQUEST_FIELD = "job-request";
/** The logger. */
private static Logger logger = LoggerFactory.getLogger(JobsResource.class.getName());
/**
* Gets the resource.
*
* @return the resource
*/
@Get("xml")
public Representation getResource() {
if (!isAuthenticated()) {
setStatus(Status.CLIENT_ERROR_UNAUTHORIZED);
return null;
}
JobManager jobMan = webservice().getJobManager();
JobsXmlWriter writer = XmlWriterFactory.createXmlWriter(jobMan.getJobs());
Document doc = writer.getXmlDocument();
DomRepresentation dom = new DomRepresentation(MediaType.APPLICATION_XML, doc);
setStatus(Status.SUCCESS_OK);
return dom;
}
/**
* Creates the resource.
*
* @param representation the representation
* @return the representation
* @throws Exception the exception
*/
@Post
public Representation createResource(Representation representation) {
if (!isAuthenticated()) {
setStatus(Status.CLIENT_ERROR_UNAUTHORIZED);
return null;
}
Client client = null;
if (webservice().getConfiguration().isAuthenticationEnabled()) {
String clientId = getQuery().getFirstValue("authid");
client = webservice().getClientStore().get(clientId);
}
if (representation == null) {
// POST request with no entity.
setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
return this.getErrorRepresentation("POST request with no entity");
}
Document doc = null;
ZipFile zipfile = null;
if (MediaType.MULTIPART_FORM_DATA.equals(representation.getMediaType(), true)) {
Request request = getRequest();
// sort through the multipart request
MultipartRequestData data = processMultipart(request);
if (data == null) {
setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
return this.getErrorRepresentation("Multipart data is empty");
}
doc = data.getXml();
zipfile = data.getZipFile();
}
// else it's not multipart; all data should be inline.
else {
String s;
try {
s = representation.getText();
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
DocumentBuilder builder = factory.newDocumentBuilder();
InputSource is = new InputSource(new StringReader(s));
doc = builder.parse(is);
} catch (IOException e) {
logger.error(e.getMessage());
setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
- this.getErrorRepresentation(e);
+ return this.getErrorRepresentation(e);
} catch (ParserConfigurationException e) {
logger.error(e.getMessage());
setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
- this.getErrorRepresentation(e);
+ return this.getErrorRepresentation(e);
} catch (SAXException e) {
logger.error(e.getMessage());
setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
- this.getErrorRepresentation(e);
+ return this.getErrorRepresentation(e);
}
}
boolean isValid = Validator.validateJobRequest(doc, webservice());
if (!isValid) {
setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
return this.getErrorRepresentation("Response XML is not valid");
}
Job job = createJob(doc, zipfile, client);
if (job == null) {
setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
return this.getErrorRepresentation("Could not create job (job was null)");
}
JobXmlWriter writer = XmlWriterFactory.createXmlWriter(job);
Document jobXml = writer.withAllMessages().withScriptDetails().getXmlDocument();
DomRepresentation dom = new DomRepresentation(MediaType.APPLICATION_XML, jobXml);
setStatus(Status.SUCCESS_CREATED);
return dom;
}
/*
* taken from an example at:
* http://wiki.restlet.org/docs_2.0/13-restlet/28-restlet/64-restlet.html
*/
/**
* Process multipart.
*
* @param request the request
* @return the multipart request data
*/
private MultipartRequestData processMultipart(Request request) {
String tmpdir = webservice().getConfiguration().getTmpDir();
// 1/ Create a factory for disk-based file items
DiskFileItemFactory fileItemFactory = new DiskFileItemFactory();
fileItemFactory.setSizeThreshold(1000240);
// 2/ Create a new file upload handler based on the Restlet
// FileUpload extension that will parse Restlet requests and
// generates FileItems.
RestletFileUpload upload = new RestletFileUpload(fileItemFactory);
List<FileItem> items;
ZipFile zip = null;
String xml = "";
try {
items = upload.parseRequest(request);
Iterator<FileItem> it = items.iterator();
while (it.hasNext()) {
FileItem fi = it.next();
if (fi.getFieldName().equals(JOB_DATA_FIELD)) {
File file = File.createTempFile(tempfilePrefix, tempfileSuffix, new File(tmpdir));
fi.write(file);
// re-opening the file after writing to it
File file2 = new File(file.getAbsolutePath());
zip = new ZipFile(file2);
}
else if (fi.getFieldName().equals(JOB_REQUEST_FIELD)) {
xml = fi.getString("utf-8");
logger.debug("XML multi:"+xml);
}
}
if (zip == null || xml.length() == 0) {
setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
return null;
}
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
docFactory.setNamespaceAware(true);
DocumentBuilder builder = docFactory.newDocumentBuilder();
InputSource is = new InputSource(new StringReader(xml));
Document doc = builder.parse(is);
MultipartRequestData data = new MultipartRequestData(zip, doc);
return data;
} catch (FileUploadException e) {
logger.error(e.getMessage());
return null;
} catch (Exception e) {
logger.error(e.getMessage());
return null;
}
}
// just a convenience class for representing the parts of a multipart request
/**
* The Class MultipartRequestData.
*/
private class MultipartRequestData {
/**
* Process multipart.
*
* @param request the request
* @return the multipart request data
*/
/** The zip. */
private final ZipFile zip;
/** The xml. */
private final Document xml;
/**
* Instantiates a new multipart request data.
*
* @param zip the zip
* @param xml the xml
*/
MultipartRequestData(ZipFile zip, Document xml) {
this.zip = zip;
this.xml = xml;
}
/**
* Gets the zip file.
*
* @return the zip file
*/
ZipFile getZipFile() {
return zip;
}
/**
* Gets the xml.
*
* @return the xml
*/
Document getXml() {
return xml;
}
}
/**
* Creates the job.
*
* @param doc the doc
* @param zip the zip
* @return the job
*/
private Job createJob(Document doc, ZipFile zip, Client client) {
Element scriptElm = (Element) doc.getElementsByTagName("script").item(0);
// TODO eventually we might want to have an href-script ID lookup table
// but for now, we'll get the script ID from the last part of the URL
String scriptId = scriptElm.getAttribute("href");
if (scriptId.endsWith("/")) {
scriptId = scriptId.substring(0, scriptId.length() - 1);
}
int idx = scriptId.lastIndexOf('/');
scriptId = scriptId.substring(idx+1);
// get the script from the ID
ScriptRegistry scriptRegistry = webservice().getScriptRegistry();
XProcScriptService unfilteredScript = scriptRegistry.getScript(scriptId);
if (unfilteredScript == null) {
logger.error("Script not found");
return null;
}
XProcScript script = unfilteredScript.load();
XProcInput.Builder builder = new XProcInput.Builder(script.getXProcPipelineInfo());
addInputsToJob(doc.getElementsByTagName("input"), script.getXProcPipelineInfo().getInputPorts(), builder);
/*Iterable<XProcOptionInfo> filteredOptions = null;
if (!((PipelineWebService) getApplication()).isLocal()) {
filteredOptions = XProcScriptFilter.INSTANCE.filter(script).getXProcPipelineInfo().getOptions();
}*/
addOptionsToJob(doc.getElementsByTagName("option"), script, builder);// script.getXProcPipelineInfo().getOptions(), builder, filteredOptions);
XProcInput input = builder.build();
JobManager jobMan = webservice().getJobManager();
Job job = null;
if (zip != null){
ResourceCollection resourceCollection = new ZipResourceContext(zip);
job = jobMan.newJob(script, input, resourceCollection);
}
else {
job = jobMan.newJob(script, input);
}
NodeList callbacks = doc.getElementsByTagName("callback");
for (int i = 0; i<callbacks.getLength(); i++) {
Element elm = (Element)callbacks.item(i);
String href = elm.getAttribute("href");
CallbackType type = CallbackType.valueOf(elm.getAttribute("type").toUpperCase());
String frequency = elm.getAttribute("frequency");
Callback callback = null;
int freq = 0;
if (frequency.length() > 0) {
freq = Integer.parseInt(frequency);
}
try {
callback = new Callback(job.getId(), client, new URI(href), type, freq);
} catch (URISyntaxException e) {
logger.warn("Cannot create callback: " + e.getMessage());
}
if (callback != null) {
webservice().getCallbackRegistry().addCallback(callback);
}
}
return job;
}
/**
* Adds the inputs to job.
*
* @param nodes the nodes
* @param inputPorts the input ports
* @param builder the builder
*/
private void addInputsToJob(NodeList nodes, Iterable<XProcPortInfo> inputPorts, XProcInput.Builder builder) {
Iterator<XProcPortInfo> it = inputPorts.iterator();
while (it.hasNext()) {
XProcPortInfo input = it.next();
String inputName = input.getName();
for (int i = 0; i < nodes.getLength(); i++) {
Element inputElm = (Element) nodes.item(i);
String name = inputElm.getAttribute("name");
if (name.equals(inputName)) {
NodeList fileNodes = inputElm.getElementsByTagName("item");
NodeList docwrapperNodes = inputElm.getElementsByTagName("docwrapper");
if (fileNodes.getLength() > 0) {
for (int j = 0; j < fileNodes.getLength(); j++) {
String src = ((Element)fileNodes.item(j)).getAttribute("value");
// Provider<Source> prov= new Provider<Source>(){
// @Override
// public Source provide(){
// SAXSource source = new SAXSource();
// source.setSystemId(new String(src.getBytes()));
// return source;
// }
// };
LazySaxSourceProvider prov= new LazySaxSourceProvider(src);
builder.withInput(name, prov);
}
}
else {
for (int j = 0; j< docwrapperNodes.getLength(); j++){
Element docwrapper = (Element)docwrapperNodes.item(j);
Node content = null;
// find the first element child
for (int q = 0; q < docwrapper.getChildNodes().getLength(); q++) {
if (docwrapper.getChildNodes().item(q).getNodeType() == Node.ELEMENT_NODE) {
content = docwrapper.getChildNodes().item(q);
break;
}
}
final SAXSource source = new SAXSource();
// TODO any way to get Source directly from a node?
String xml = XmlUtils.nodeToString(content);
InputSource is = new org.xml.sax.InputSource(new java.io.StringReader(xml));
source.setInputSource(is);
Provider<Source> prov= new Provider<Source>(){
@Override
public Source provide(){
return source;
}
};
builder.withInput(name, prov);
}
}
}
}
}
}
/**
* Adds the options to job.
*/
//private void addOptionsToJob(NodeList nodes, Iterable<XProcOptionInfo> allOptions, XProcInput.Builder builder, Iterable<XProcOptionInfo> filteredOptions) {
private void addOptionsToJob(NodeList nodes, XProcScript script, XProcInput.Builder builder) {
Iterable<XProcOptionInfo> allOptions = script.getXProcPipelineInfo().getOptions();
Iterable<XProcOptionInfo> filteredOptions = null;
if (!webservice().getConfiguration().isLocal()) {
filteredOptions = XProcScriptFilter.INSTANCE.filter(script).getXProcPipelineInfo().getOptions();
}
Iterator<XProcOptionInfo> it = allOptions.iterator();
while(it.hasNext()) {
XProcOptionInfo opt = it.next();
String optionName = opt.getName().toString();
// if we are filtering options, then check to ensure that this particular option exists in the filtered set
if (filteredOptions != null) {
Iterator<XProcOptionInfo> itFilter = filteredOptions.iterator();
boolean found = false;
while (itFilter.hasNext()) {
String filteredOptName = itFilter.next().getName().toString();
if (filteredOptName.equals(optionName)) {
found = true;
break;
}
}
// if the option did not exist in the filtered set of options
// then we are not allowed to set it
// however, it still requires a value, so set it to ""
if (!found) {
builder.withOption(new QName(optionName), "");
continue;
}
}
// this is an option we are allowed to set. so, look for the option in the job request doc.
for (int i = 0; i< nodes.getLength(); i++) {
Element optionElm = (Element) nodes.item(i);
String name = optionElm.getAttribute("name");
if (name.equals(optionName)) {
XProcOptionMetadata metadata = script.getOptionMetadata(new QName(name));
if (metadata.isSequence()) {
NodeList items = optionElm.getElementsByTagName("item");
// concat items
String val = ((Element)items.item(0)).getAttribute("value");
for (int j = 1; j<items.getLength(); j++) {
Element e = (Element)items.item(j);
val += metadata.getSeparator() + e.getAttribute("value");
}
builder.withOption(new QName(name), val);
}
else {
String val = optionElm.getTextContent();
builder.withOption(new QName(name), val);
break;
}
}
}
}
}
}
| false | true | public Representation createResource(Representation representation) {
if (!isAuthenticated()) {
setStatus(Status.CLIENT_ERROR_UNAUTHORIZED);
return null;
}
Client client = null;
if (webservice().getConfiguration().isAuthenticationEnabled()) {
String clientId = getQuery().getFirstValue("authid");
client = webservice().getClientStore().get(clientId);
}
if (representation == null) {
// POST request with no entity.
setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
return this.getErrorRepresentation("POST request with no entity");
}
Document doc = null;
ZipFile zipfile = null;
if (MediaType.MULTIPART_FORM_DATA.equals(representation.getMediaType(), true)) {
Request request = getRequest();
// sort through the multipart request
MultipartRequestData data = processMultipart(request);
if (data == null) {
setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
return this.getErrorRepresentation("Multipart data is empty");
}
doc = data.getXml();
zipfile = data.getZipFile();
}
// else it's not multipart; all data should be inline.
else {
String s;
try {
s = representation.getText();
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
DocumentBuilder builder = factory.newDocumentBuilder();
InputSource is = new InputSource(new StringReader(s));
doc = builder.parse(is);
} catch (IOException e) {
logger.error(e.getMessage());
setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
this.getErrorRepresentation(e);
} catch (ParserConfigurationException e) {
logger.error(e.getMessage());
setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
this.getErrorRepresentation(e);
} catch (SAXException e) {
logger.error(e.getMessage());
setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
this.getErrorRepresentation(e);
}
}
boolean isValid = Validator.validateJobRequest(doc, webservice());
if (!isValid) {
setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
return this.getErrorRepresentation("Response XML is not valid");
}
Job job = createJob(doc, zipfile, client);
if (job == null) {
setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
return this.getErrorRepresentation("Could not create job (job was null)");
}
JobXmlWriter writer = XmlWriterFactory.createXmlWriter(job);
Document jobXml = writer.withAllMessages().withScriptDetails().getXmlDocument();
DomRepresentation dom = new DomRepresentation(MediaType.APPLICATION_XML, jobXml);
setStatus(Status.SUCCESS_CREATED);
return dom;
}
| public Representation createResource(Representation representation) {
if (!isAuthenticated()) {
setStatus(Status.CLIENT_ERROR_UNAUTHORIZED);
return null;
}
Client client = null;
if (webservice().getConfiguration().isAuthenticationEnabled()) {
String clientId = getQuery().getFirstValue("authid");
client = webservice().getClientStore().get(clientId);
}
if (representation == null) {
// POST request with no entity.
setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
return this.getErrorRepresentation("POST request with no entity");
}
Document doc = null;
ZipFile zipfile = null;
if (MediaType.MULTIPART_FORM_DATA.equals(representation.getMediaType(), true)) {
Request request = getRequest();
// sort through the multipart request
MultipartRequestData data = processMultipart(request);
if (data == null) {
setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
return this.getErrorRepresentation("Multipart data is empty");
}
doc = data.getXml();
zipfile = data.getZipFile();
}
// else it's not multipart; all data should be inline.
else {
String s;
try {
s = representation.getText();
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
DocumentBuilder builder = factory.newDocumentBuilder();
InputSource is = new InputSource(new StringReader(s));
doc = builder.parse(is);
} catch (IOException e) {
logger.error(e.getMessage());
setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
return this.getErrorRepresentation(e);
} catch (ParserConfigurationException e) {
logger.error(e.getMessage());
setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
return this.getErrorRepresentation(e);
} catch (SAXException e) {
logger.error(e.getMessage());
setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
return this.getErrorRepresentation(e);
}
}
boolean isValid = Validator.validateJobRequest(doc, webservice());
if (!isValid) {
setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
return this.getErrorRepresentation("Response XML is not valid");
}
Job job = createJob(doc, zipfile, client);
if (job == null) {
setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
return this.getErrorRepresentation("Could not create job (job was null)");
}
JobXmlWriter writer = XmlWriterFactory.createXmlWriter(job);
Document jobXml = writer.withAllMessages().withScriptDetails().getXmlDocument();
DomRepresentation dom = new DomRepresentation(MediaType.APPLICATION_XML, jobXml);
setStatus(Status.SUCCESS_CREATED);
return dom;
}
|
diff --git a/rxjava-contrib/rxjava-debug/src/test/java/rx/debug/DebugHookTest.java b/rxjava-contrib/rxjava-debug/src/test/java/rx/debug/DebugHookTest.java
index 5a113ffc7..92c6cdd0d 100644
--- a/rxjava-contrib/rxjava-debug/src/test/java/rx/debug/DebugHookTest.java
+++ b/rxjava-contrib/rxjava-debug/src/test/java/rx/debug/DebugHookTest.java
@@ -1,130 +1,130 @@
package rx.debug;
import static org.mockito.Matchers.*;
import static org.mockito.Mockito.*;
import java.util.Arrays;
import org.hamcrest.BaseMatcher;
import org.hamcrest.Description;
import org.junit.After;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import rx.Notification;
import rx.Observable;
import rx.Observer;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.plugins.DebugHook;
import rx.plugins.DebugNotification;
import rx.plugins.PlugReset;
import rx.plugins.RxJavaPlugins;
public class DebugHookTest {
@Before
@After
public void reset() {
PlugReset.reset();
}
@Test
@Ignore
public void testSimple() {
Action1<DebugNotification> events = mock(Action1.class);
final DebugHook hook = new DebugHook(null, events);
RxJavaPlugins.getInstance().registerObservableExecutionHook(hook);
Observable.empty().subscribe();
verify(events, times(1)).call(subscribe());
verify(events, times(1)).call(onCompleted());
}
@Test
public void testOneOp() {
Action1<DebugNotification> events = mock(Action1.class);
final DebugHook hook = new DebugHook(null, events);
RxJavaPlugins.getInstance().registerObservableExecutionHook(hook);
Observable.from(Arrays.asList(1, 3)).flatMap(new Func1<Integer, Observable<Integer>>() {
@Override
public Observable<Integer> call(Integer it) {
return Observable.from(Arrays.asList(it, it + 1));
}
}).take(3).subscribe(new Observer<Integer>() {
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable e) {
}
@Override
public void onNext(Integer t) {
}
});
- verify(events, times(6)).call(subscribe());
+ verify(events, atLeast(3)).call(subscribe());
verify(events, times(4)).call(onNext(1));
// one less because it originates from the inner observable sent to merge
verify(events, times(3)).call(onNext(2));
verify(events, times(4)).call(onNext(3));
// because the take unsubscribes
verify(events, never()).call(onNext(4));
}
private static <T> DebugNotification<T> onNext(final T value) {
return argThat(new BaseMatcher<DebugNotification<T>>() {
@Override
public boolean matches(Object item) {
if (item instanceof DebugNotification) {
DebugNotification<T> dn = (DebugNotification<T>) item;
Notification<T> n = dn.getNotification();
return n != null && n.hasValue() && n.getValue().equals(value);
}
return false;
}
@Override
public void describeTo(Description description) {
description.appendText("OnNext " + value);
}
});
}
private static DebugNotification subscribe() {
return argThat(new BaseMatcher<DebugNotification>() {
@Override
public boolean matches(Object item) {
if (item instanceof DebugNotification) {
DebugNotification dn = (DebugNotification) item;
return dn.getKind() == DebugNotification.Kind.Subscribe;
}
return false;
}
@Override
public void describeTo(Description description) {
description.appendText("Subscribe");
}
});
}
private static DebugNotification onCompleted() {
return argThat(new BaseMatcher<DebugNotification>() {
@Override
public boolean matches(Object item) {
if (item instanceof DebugNotification) {
DebugNotification dn = (DebugNotification) item;
Notification n = dn.getNotification();
return n != null && n.isOnCompleted();
}
return false;
}
@Override
public void describeTo(Description description) {
description.appendText("onCompleted");
}
});
}
}
| true | true | public void testOneOp() {
Action1<DebugNotification> events = mock(Action1.class);
final DebugHook hook = new DebugHook(null, events);
RxJavaPlugins.getInstance().registerObservableExecutionHook(hook);
Observable.from(Arrays.asList(1, 3)).flatMap(new Func1<Integer, Observable<Integer>>() {
@Override
public Observable<Integer> call(Integer it) {
return Observable.from(Arrays.asList(it, it + 1));
}
}).take(3).subscribe(new Observer<Integer>() {
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable e) {
}
@Override
public void onNext(Integer t) {
}
});
verify(events, times(6)).call(subscribe());
verify(events, times(4)).call(onNext(1));
// one less because it originates from the inner observable sent to merge
verify(events, times(3)).call(onNext(2));
verify(events, times(4)).call(onNext(3));
// because the take unsubscribes
verify(events, never()).call(onNext(4));
}
| public void testOneOp() {
Action1<DebugNotification> events = mock(Action1.class);
final DebugHook hook = new DebugHook(null, events);
RxJavaPlugins.getInstance().registerObservableExecutionHook(hook);
Observable.from(Arrays.asList(1, 3)).flatMap(new Func1<Integer, Observable<Integer>>() {
@Override
public Observable<Integer> call(Integer it) {
return Observable.from(Arrays.asList(it, it + 1));
}
}).take(3).subscribe(new Observer<Integer>() {
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable e) {
}
@Override
public void onNext(Integer t) {
}
});
verify(events, atLeast(3)).call(subscribe());
verify(events, times(4)).call(onNext(1));
// one less because it originates from the inner observable sent to merge
verify(events, times(3)).call(onNext(2));
verify(events, times(4)).call(onNext(3));
// because the take unsubscribes
verify(events, never()).call(onNext(4));
}
|
diff --git a/src/de/_13ducks/cor/game/server/movement/Formation.java b/src/de/_13ducks/cor/game/server/movement/Formation.java
index 209c6a3..33193fe 100644
--- a/src/de/_13ducks/cor/game/server/movement/Formation.java
+++ b/src/de/_13ducks/cor/game/server/movement/Formation.java
@@ -1,133 +1,133 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package de._13ducks.cor.game.server.movement;
import de._13ducks.cor.game.FloatingPointPosition;
import de._13ducks.cor.game.server.Server;
/**
* Diese Klasse bietet Funktionen für Einheitenformationen
*
* @author michael
*/
public class Formation {
/**
* erstellt eine Quadratformation am Ziel, die in die Richtung des Vektors zeigt
* @param unitCount - die Zahl der Einheiten
* @param target - Die Mitte der Formation
* @param vector - Die Richtung in die die Formation zeigen soll
* @param distance - Der Abstand zwischen den Einheiten
*/
public static FloatingPointPosition[] createSquareFormation(int unitCount, FloatingPointPosition target, FloatingPointPosition vector, double distance) {
// Rückgabe-Array initialisieren:
FloatingPointPosition[] formation = new FloatingPointPosition[unitCount];
for (int i = 0; i < formation.length; i++) {
formation[i] = new FloatingPointPosition(0, 0);
}
// Die Position, die gerde bearbeitet wird
FloatingPointPosition checkPosition = new FloatingPointPosition(0, 0);
// Wieviele Positionen wurden schon gefudnden?
int foundPositions = 0;
// Richtung (1=E, 2=N, 3=W, 4=S)
int direction = 1;
// Wie viele sSchritte gecheckt werden
int steps = 1;
// wenn true wird steps erhöt
boolean increaseStepFlag = false;
// Die Position, auf die geklickt wurde:
if (Server.getInnerServer().netmap.getMoveMap().isPositionWalkable(new FloatingPointPosition(0, 0))) {
formation[foundPositions] = new FloatingPointPosition(0, 0);
foundPositions++;
if (foundPositions == unitCount) {
return formation;
}
}
// endlosschleife, wenn genug positionen gefunden wurden wird sie abgebrochen
while (true) {
// X- und Y-Veränderung
double dx = 0, dy = 0;
// in welche Richtung wird gerade gesucht?
switch (direction) {
case 1:
dx = distance;
dy = 0;
break;
case 2:
dx = 0;
dy = distance;
break;
case 3:
dx = -distance;
dy = 0;
break;
case 4:
dx = 0;
dy = -distance;
break;
}
// (steps) Schritte in die aktuelle Richtung gehen und bei jedem Schritt die Position überprüfen:
for (int i = 0; i < steps; i++) {
// CheckPosition verschieben:
checkPosition.setfX(checkPosition.getfX() + dx);
checkPosition.setfY(checkPosition.getfY() + dy);
// CheckPosition rotieren (und damit finalPos berechnen):
double lenght = Math.sqrt((vector.getX() * vector.getX()) + (vector.getY() * vector.getY()));
double skalar = vector.getY();
double cosrot = skalar / lenght;
- if(cosrot == Double.NaN){cosrot = 0.001;}
+ if(Double.isNaN(cosrot)){cosrot = 0.001;}
double rotation = Math.acos(cosrot);
double x = checkPosition.getfX();
double y = checkPosition.getfY();
double dist = Math.sqrt((x * x) + (y * y));
double newRot = rotation + Math.atan2(checkPosition.getfX(), checkPosition.getfY());
x = (Math.cos(newRot) * dist);
y = (Math.sin(newRot) * dist);
FloatingPointPosition finalPos = new FloatingPointPosition(x, y);
// Wenn finalPos gültig ist zur Liste hinzufügen:
// Wenn die Position gültig ist (also kein NaN oder infinite enthält), wird überprüft ob Einheiten dort stehen können:
if (finalPos.add(target).valid()) {
if (Server.getInnerServer().netmap.getMoveMap().isPositionWalkable(finalPos.add(target))) {
formation[foundPositions] = new FloatingPointPosition(finalPos.getfX(), finalPos.getfY());
foundPositions++;
if (foundPositions == unitCount) {
return formation;
}
}
}
}
// Richtung ändern:
direction++;
if (direction > 4) {
direction = 1;
}
// Wenn die Flag schon gesetzt ist inkrementieren, sonst flag setzten
//(dadurch wird steps bei jedem 2. Richtungswechsel inkrementiert, was in einer kreisbewegung resultiert)
if (increaseStepFlag == true) {
increaseStepFlag = false;
steps++;
} else {
increaseStepFlag = true;
}
}
}
}
| true | true | public static FloatingPointPosition[] createSquareFormation(int unitCount, FloatingPointPosition target, FloatingPointPosition vector, double distance) {
// Rückgabe-Array initialisieren:
FloatingPointPosition[] formation = new FloatingPointPosition[unitCount];
for (int i = 0; i < formation.length; i++) {
formation[i] = new FloatingPointPosition(0, 0);
}
// Die Position, die gerde bearbeitet wird
FloatingPointPosition checkPosition = new FloatingPointPosition(0, 0);
// Wieviele Positionen wurden schon gefudnden?
int foundPositions = 0;
// Richtung (1=E, 2=N, 3=W, 4=S)
int direction = 1;
// Wie viele sSchritte gecheckt werden
int steps = 1;
// wenn true wird steps erhöt
boolean increaseStepFlag = false;
// Die Position, auf die geklickt wurde:
if (Server.getInnerServer().netmap.getMoveMap().isPositionWalkable(new FloatingPointPosition(0, 0))) {
formation[foundPositions] = new FloatingPointPosition(0, 0);
foundPositions++;
if (foundPositions == unitCount) {
return formation;
}
}
// endlosschleife, wenn genug positionen gefunden wurden wird sie abgebrochen
while (true) {
// X- und Y-Veränderung
double dx = 0, dy = 0;
// in welche Richtung wird gerade gesucht?
switch (direction) {
case 1:
dx = distance;
dy = 0;
break;
case 2:
dx = 0;
dy = distance;
break;
case 3:
dx = -distance;
dy = 0;
break;
case 4:
dx = 0;
dy = -distance;
break;
}
// (steps) Schritte in die aktuelle Richtung gehen und bei jedem Schritt die Position überprüfen:
for (int i = 0; i < steps; i++) {
// CheckPosition verschieben:
checkPosition.setfX(checkPosition.getfX() + dx);
checkPosition.setfY(checkPosition.getfY() + dy);
// CheckPosition rotieren (und damit finalPos berechnen):
double lenght = Math.sqrt((vector.getX() * vector.getX()) + (vector.getY() * vector.getY()));
double skalar = vector.getY();
double cosrot = skalar / lenght;
if(cosrot == Double.NaN){cosrot = 0.001;}
double rotation = Math.acos(cosrot);
double x = checkPosition.getfX();
double y = checkPosition.getfY();
double dist = Math.sqrt((x * x) + (y * y));
double newRot = rotation + Math.atan2(checkPosition.getfX(), checkPosition.getfY());
x = (Math.cos(newRot) * dist);
y = (Math.sin(newRot) * dist);
FloatingPointPosition finalPos = new FloatingPointPosition(x, y);
// Wenn finalPos gültig ist zur Liste hinzufügen:
// Wenn die Position gültig ist (also kein NaN oder infinite enthält), wird überprüft ob Einheiten dort stehen können:
if (finalPos.add(target).valid()) {
if (Server.getInnerServer().netmap.getMoveMap().isPositionWalkable(finalPos.add(target))) {
formation[foundPositions] = new FloatingPointPosition(finalPos.getfX(), finalPos.getfY());
foundPositions++;
if (foundPositions == unitCount) {
return formation;
}
}
}
}
// Richtung ändern:
direction++;
if (direction > 4) {
direction = 1;
}
// Wenn die Flag schon gesetzt ist inkrementieren, sonst flag setzten
//(dadurch wird steps bei jedem 2. Richtungswechsel inkrementiert, was in einer kreisbewegung resultiert)
if (increaseStepFlag == true) {
increaseStepFlag = false;
steps++;
} else {
increaseStepFlag = true;
}
}
}
| public static FloatingPointPosition[] createSquareFormation(int unitCount, FloatingPointPosition target, FloatingPointPosition vector, double distance) {
// Rückgabe-Array initialisieren:
FloatingPointPosition[] formation = new FloatingPointPosition[unitCount];
for (int i = 0; i < formation.length; i++) {
formation[i] = new FloatingPointPosition(0, 0);
}
// Die Position, die gerde bearbeitet wird
FloatingPointPosition checkPosition = new FloatingPointPosition(0, 0);
// Wieviele Positionen wurden schon gefudnden?
int foundPositions = 0;
// Richtung (1=E, 2=N, 3=W, 4=S)
int direction = 1;
// Wie viele sSchritte gecheckt werden
int steps = 1;
// wenn true wird steps erhöt
boolean increaseStepFlag = false;
// Die Position, auf die geklickt wurde:
if (Server.getInnerServer().netmap.getMoveMap().isPositionWalkable(new FloatingPointPosition(0, 0))) {
formation[foundPositions] = new FloatingPointPosition(0, 0);
foundPositions++;
if (foundPositions == unitCount) {
return formation;
}
}
// endlosschleife, wenn genug positionen gefunden wurden wird sie abgebrochen
while (true) {
// X- und Y-Veränderung
double dx = 0, dy = 0;
// in welche Richtung wird gerade gesucht?
switch (direction) {
case 1:
dx = distance;
dy = 0;
break;
case 2:
dx = 0;
dy = distance;
break;
case 3:
dx = -distance;
dy = 0;
break;
case 4:
dx = 0;
dy = -distance;
break;
}
// (steps) Schritte in die aktuelle Richtung gehen und bei jedem Schritt die Position überprüfen:
for (int i = 0; i < steps; i++) {
// CheckPosition verschieben:
checkPosition.setfX(checkPosition.getfX() + dx);
checkPosition.setfY(checkPosition.getfY() + dy);
// CheckPosition rotieren (und damit finalPos berechnen):
double lenght = Math.sqrt((vector.getX() * vector.getX()) + (vector.getY() * vector.getY()));
double skalar = vector.getY();
double cosrot = skalar / lenght;
if(Double.isNaN(cosrot)){cosrot = 0.001;}
double rotation = Math.acos(cosrot);
double x = checkPosition.getfX();
double y = checkPosition.getfY();
double dist = Math.sqrt((x * x) + (y * y));
double newRot = rotation + Math.atan2(checkPosition.getfX(), checkPosition.getfY());
x = (Math.cos(newRot) * dist);
y = (Math.sin(newRot) * dist);
FloatingPointPosition finalPos = new FloatingPointPosition(x, y);
// Wenn finalPos gültig ist zur Liste hinzufügen:
// Wenn die Position gültig ist (also kein NaN oder infinite enthält), wird überprüft ob Einheiten dort stehen können:
if (finalPos.add(target).valid()) {
if (Server.getInnerServer().netmap.getMoveMap().isPositionWalkable(finalPos.add(target))) {
formation[foundPositions] = new FloatingPointPosition(finalPos.getfX(), finalPos.getfY());
foundPositions++;
if (foundPositions == unitCount) {
return formation;
}
}
}
}
// Richtung ändern:
direction++;
if (direction > 4) {
direction = 1;
}
// Wenn die Flag schon gesetzt ist inkrementieren, sonst flag setzten
//(dadurch wird steps bei jedem 2. Richtungswechsel inkrementiert, was in einer kreisbewegung resultiert)
if (increaseStepFlag == true) {
increaseStepFlag = false;
steps++;
} else {
increaseStepFlag = true;
}
}
}
|
diff --git a/src-pos/com/openbravo/pos/printer/escpos/PrinterWritterRXTX.java b/src-pos/com/openbravo/pos/printer/escpos/PrinterWritterRXTX.java
index 9fd18c5..4946cb3 100644
--- a/src-pos/com/openbravo/pos/printer/escpos/PrinterWritterRXTX.java
+++ b/src-pos/com/openbravo/pos/printer/escpos/PrinterWritterRXTX.java
@@ -1,92 +1,93 @@
// Openbravo POS is a point of sales application designed for touch screens.
// Copyright (C) 2007-2009 Openbravo, S.L.
// http://www.openbravo.com/product/pos
//
// This file is part of Openbravo POS.
//
// Openbravo POS is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Openbravo POS is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Openbravo POS. If not, see <http://www.gnu.org/licenses/>.
package com.openbravo.pos.printer.escpos;
// import javax.comm.*; // Java comm library
import gnu.io.*; // RXTX comm library
import java.io.*;
import com.openbravo.pos.printer.*;
public class PrinterWritterRXTX extends PrinterWritter /* implements SerialPortEventListener */ {
private CommPortIdentifier m_PortIdPrinter;
private CommPort m_CommPortPrinter;
private String m_sPortPrinter;
private OutputStream m_out;
/** Creates a new instance of PrinterWritterComm */
public PrinterWritterRXTX(String sPortPrinter) throws TicketPrinterException {
m_sPortPrinter = sPortPrinter;
m_out = null;
}
protected void internalWrite(byte[] data) {
try {
if (m_out == null) {
m_PortIdPrinter = CommPortIdentifier.getPortIdentifier(m_sPortPrinter); // Tomamos el puerto
m_CommPortPrinter = m_PortIdPrinter.open("PORTID", 2000); // Abrimos el puerto
m_out = m_CommPortPrinter.getOutputStream(); // Tomamos el chorro de escritura
if (m_PortIdPrinter.getPortType() == CommPortIdentifier.PORT_SERIAL) {
((SerialPort)m_CommPortPrinter).setSerialPortParams(9600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE); // Configuramos el puerto
+ ((SerialPort)m_CommPortPrinter).setFlowControlMode(SerialPort.FLOWCONTROL_RTSCTS_IN); // this line prevents the printer tmu220 to stop printing after +-18 lines printed
// Not needed to set parallel properties
// } else if (m_PortIdPrinter.getPortType() == CommPortIdentifier.PORT_PARALLEL) {
// ((ParallelPort)m_CommPortPrinter).setMode(1);
}
}
m_out.write(data);
} catch (NoSuchPortException e) {
System.err.println(e);
} catch (PortInUseException e) {
System.err.println(e);
} catch (UnsupportedCommOperationException e) {
System.err.println(e);
} catch (IOException e) {
System.err.println(e);
}
}
protected void internalFlush() {
try {
if (m_out != null) {
m_out.flush();
}
} catch (IOException e) {
System.err.println(e);
}
}
protected void internalClose() {
try {
if (m_out != null) {
m_out.flush();
m_out.close();
m_out = null;
m_CommPortPrinter = null;
m_PortIdPrinter = null;
}
} catch (IOException e) {
System.err.println(e);
}
}
}
| true | true | protected void internalWrite(byte[] data) {
try {
if (m_out == null) {
m_PortIdPrinter = CommPortIdentifier.getPortIdentifier(m_sPortPrinter); // Tomamos el puerto
m_CommPortPrinter = m_PortIdPrinter.open("PORTID", 2000); // Abrimos el puerto
m_out = m_CommPortPrinter.getOutputStream(); // Tomamos el chorro de escritura
if (m_PortIdPrinter.getPortType() == CommPortIdentifier.PORT_SERIAL) {
((SerialPort)m_CommPortPrinter).setSerialPortParams(9600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE); // Configuramos el puerto
// Not needed to set parallel properties
// } else if (m_PortIdPrinter.getPortType() == CommPortIdentifier.PORT_PARALLEL) {
// ((ParallelPort)m_CommPortPrinter).setMode(1);
}
}
m_out.write(data);
} catch (NoSuchPortException e) {
System.err.println(e);
} catch (PortInUseException e) {
System.err.println(e);
} catch (UnsupportedCommOperationException e) {
System.err.println(e);
} catch (IOException e) {
System.err.println(e);
}
}
| protected void internalWrite(byte[] data) {
try {
if (m_out == null) {
m_PortIdPrinter = CommPortIdentifier.getPortIdentifier(m_sPortPrinter); // Tomamos el puerto
m_CommPortPrinter = m_PortIdPrinter.open("PORTID", 2000); // Abrimos el puerto
m_out = m_CommPortPrinter.getOutputStream(); // Tomamos el chorro de escritura
if (m_PortIdPrinter.getPortType() == CommPortIdentifier.PORT_SERIAL) {
((SerialPort)m_CommPortPrinter).setSerialPortParams(9600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE); // Configuramos el puerto
((SerialPort)m_CommPortPrinter).setFlowControlMode(SerialPort.FLOWCONTROL_RTSCTS_IN); // this line prevents the printer tmu220 to stop printing after +-18 lines printed
// Not needed to set parallel properties
// } else if (m_PortIdPrinter.getPortType() == CommPortIdentifier.PORT_PARALLEL) {
// ((ParallelPort)m_CommPortPrinter).setMode(1);
}
}
m_out.write(data);
} catch (NoSuchPortException e) {
System.err.println(e);
} catch (PortInUseException e) {
System.err.println(e);
} catch (UnsupportedCommOperationException e) {
System.err.println(e);
} catch (IOException e) {
System.err.println(e);
}
}
|
diff --git a/src/com/app/wordservant/TodaysMemoryVerses.java b/src/com/app/wordservant/TodaysMemoryVerses.java
index 7345ed2..fa80101 100644
--- a/src/com/app/wordservant/TodaysMemoryVerses.java
+++ b/src/com/app/wordservant/TodaysMemoryVerses.java
@@ -1,186 +1,186 @@
package com.app.wordservant;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.os.Bundle;
import android.text.format.DateFormat;
import android.view.HapticFeedbackConstants;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class TodaysMemoryVerses extends Activity{
private SQLiteDatabase mDatabaseConnection;
private Cursor mScriptureQuery;
private java.text.DateFormat dbDateFormat;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_todays_memory_verses);
mDatabaseConnection = new WordServantDbHelper(this, WordServantContract.DB_NAME, null, WordServantDbHelper.DATABASE_VERSION).getWritableDatabase();
}
public void onStart(){
super.onStart();
LinearLayout allSections = (LinearLayout) findViewById(R.id.test);
allSections.removeAllViews();
//Query for all scriptures that are due today.
String [] queryColumns = {
WordServantContract.ScriptureEntry.COLUMN_NAME_REFERENCE,
WordServantContract.ScriptureEntry._ID,
WordServantContract.ScriptureEntry.COLUMN_NAME_NEXT_REVIEW_DATE,
WordServantContract.ScriptureEntry.COLUMN_NAME_LAST_REVIEWED_DATE};
dbDateFormat = new SimpleDateFormat(getResources().getString(R.string.date_format), Locale.US);
for(int i=0;i<4;i++){
String whereClause = WordServantContract.ScriptureEntry.COLUMN_NAME_NEXT_REVIEW_DATE+" <= date('now','localtime','-"+i+" day')";
whereClause += i==0?" OR "+WordServantContract.ScriptureEntry.COLUMN_NAME_LAST_REVIEWED_DATE+" = date('now','localtime')":"";
mScriptureQuery = mDatabaseConnection.query(false, getResources().getString(R.string.scripture_table_name), queryColumns, whereClause, null, null, null, null, null);
if (mScriptureQuery.getCount()==0 && i>0){
continue;
}
//Make a new scripture section.
LinearLayout scriptureSection = (LinearLayout) this.getLayoutInflater().inflate(R.layout.review_scripture_layout, null);
//Set the date for the section.
TextView currentDateDisplayer = (TextView) scriptureSection.getChildAt(0);
Calendar currentCalendar = Calendar.getInstance();
currentCalendar.add(Calendar.DATE, i*-1);
currentDateDisplayer.setText(DateFormat.format("EEEE, MMMM dd, yyyy", currentCalendar));
//Add the section to all the sections.
allSections.addView(scriptureSection);
//Display the scripture list.
displayScriptureList((ListView) scriptureSection.getChildAt(1), mScriptureQuery, i==0?true:false);
}
}
/**
* @author Lewis Gordon
* Queries the database for any memory verses that are due when the screen is accessed.
*/
private void displayScriptureList(ListView view, Cursor scriptureQuery, final Boolean enabled) {
// Set up the adapter that is going to be displayed in the list view.
Context context = this.getApplicationContext();
final Bundle bundledScriptureList = new Bundle();
ArrayAdapter<LinearLayout> scriptureAdapter = new ArrayAdapter<LinearLayout>(context, android.R.layout.simple_list_item_1){
public View getView (int position, View convertView, ViewGroup parent){
return (View) this.getItem(position);
}
};
view.setAdapter(scriptureAdapter);
//Queries the database for any verses that have the same review date as the date when the screen was accessed.
try{
for(int positionOnScreen=0;positionOnScreen<scriptureQuery.getCount();positionOnScreen++){
scriptureQuery.moveToNext();
//Get the layout from the XML file for checkbox lists.
LinearLayout newLayout = (LinearLayout) this.getLayoutInflater().inflate(R.layout.checkbox_list_layout, null);
newLayout.setOrientation(LinearLayout.HORIZONTAL);
TextView newLabel = (TextView) newLayout.getChildAt(1);
newLabel.setText(scriptureQuery.getString(0));
final int position = positionOnScreen;
bundledScriptureList.putInt(String.valueOf(positionOnScreen), scriptureQuery.getInt(1));
//Display a checkbox.
CheckBox newCheckBox = (CheckBox) newLayout.getChildAt(0);
newCheckBox.setEnabled(enabled);
- if(dbDateFormat.parse(scriptureQuery.getString(2)).getTime()>Calendar.getInstance().getTimeInMillis()){
+ if(dbDateFormat.parse(scriptureQuery.getString(2)).getTime()>Calendar.getInstance(Locale.getDefault()).getTimeInMillis()){
newCheckBox.setChecked(true);
}
newCheckBox.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
// Reset the NEXT_REVIEW_DATE if we are unchecking, otherwise mark the scripture as reviewed.
if(!((CheckBox) v).isChecked()){
FlashcardScriptureReviewFragment.updateReviewedScripture(TodaysMemoryVerses.this, bundledScriptureList.getInt(String.valueOf(position)), false);
}else{
FlashcardScriptureReviewFragment.updateReviewedScripture(TodaysMemoryVerses.this, bundledScriptureList.getInt(String.valueOf(position)), true);
}
}
});
scriptureAdapter.add(newLayout);
}
} catch(SQLiteException e){
System.err.println("Database issue...");
e.printStackTrace();
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// When any of the entries are pressed they can then be edited.
view.setOnItemClickListener(new OnItemClickListener(){
public void onItemClick(AdapterView<?> parent, View dueTodayView, int position,long id) {
// Sends the query row that holds the values we would like to edit.
if(enabled){
LinearLayout view = (LinearLayout) dueTodayView;
CheckBox checkBox = (CheckBox) view.getChildAt(0);
if(!checkBox.isPressed()){
Intent intent = new Intent(TodaysMemoryVerses.this,ScriptureReviewFragmentActivity.class);
intent.putExtra("bundledScriptureList",bundledScriptureList);
intent.putExtra("positionOnScreen", position);
startActivity(intent);
}
}else{
dueTodayView.performHapticFeedback(HapticFeedbackConstants.KEYBOARD_TAP);
Toast.makeText(getApplicationContext(), "Scripture is disabled.", Toast.LENGTH_SHORT).show();
}
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_todays_memory_verses, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.menu_settings:
Intent intent = new Intent(this, Settings.class);
startActivity(intent);
default:
return super.onOptionsItemSelected(item);
}
}
protected void onDestroy(){
super.onDestroy();
mDatabaseConnection.close();
mScriptureQuery.close();
}
}
| true | true | private void displayScriptureList(ListView view, Cursor scriptureQuery, final Boolean enabled) {
// Set up the adapter that is going to be displayed in the list view.
Context context = this.getApplicationContext();
final Bundle bundledScriptureList = new Bundle();
ArrayAdapter<LinearLayout> scriptureAdapter = new ArrayAdapter<LinearLayout>(context, android.R.layout.simple_list_item_1){
public View getView (int position, View convertView, ViewGroup parent){
return (View) this.getItem(position);
}
};
view.setAdapter(scriptureAdapter);
//Queries the database for any verses that have the same review date as the date when the screen was accessed.
try{
for(int positionOnScreen=0;positionOnScreen<scriptureQuery.getCount();positionOnScreen++){
scriptureQuery.moveToNext();
//Get the layout from the XML file for checkbox lists.
LinearLayout newLayout = (LinearLayout) this.getLayoutInflater().inflate(R.layout.checkbox_list_layout, null);
newLayout.setOrientation(LinearLayout.HORIZONTAL);
TextView newLabel = (TextView) newLayout.getChildAt(1);
newLabel.setText(scriptureQuery.getString(0));
final int position = positionOnScreen;
bundledScriptureList.putInt(String.valueOf(positionOnScreen), scriptureQuery.getInt(1));
//Display a checkbox.
CheckBox newCheckBox = (CheckBox) newLayout.getChildAt(0);
newCheckBox.setEnabled(enabled);
if(dbDateFormat.parse(scriptureQuery.getString(2)).getTime()>Calendar.getInstance().getTimeInMillis()){
newCheckBox.setChecked(true);
}
newCheckBox.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
// Reset the NEXT_REVIEW_DATE if we are unchecking, otherwise mark the scripture as reviewed.
if(!((CheckBox) v).isChecked()){
FlashcardScriptureReviewFragment.updateReviewedScripture(TodaysMemoryVerses.this, bundledScriptureList.getInt(String.valueOf(position)), false);
}else{
FlashcardScriptureReviewFragment.updateReviewedScripture(TodaysMemoryVerses.this, bundledScriptureList.getInt(String.valueOf(position)), true);
}
}
});
scriptureAdapter.add(newLayout);
}
} catch(SQLiteException e){
System.err.println("Database issue...");
e.printStackTrace();
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// When any of the entries are pressed they can then be edited.
view.setOnItemClickListener(new OnItemClickListener(){
public void onItemClick(AdapterView<?> parent, View dueTodayView, int position,long id) {
// Sends the query row that holds the values we would like to edit.
if(enabled){
LinearLayout view = (LinearLayout) dueTodayView;
CheckBox checkBox = (CheckBox) view.getChildAt(0);
if(!checkBox.isPressed()){
Intent intent = new Intent(TodaysMemoryVerses.this,ScriptureReviewFragmentActivity.class);
intent.putExtra("bundledScriptureList",bundledScriptureList);
intent.putExtra("positionOnScreen", position);
startActivity(intent);
}
}else{
dueTodayView.performHapticFeedback(HapticFeedbackConstants.KEYBOARD_TAP);
Toast.makeText(getApplicationContext(), "Scripture is disabled.", Toast.LENGTH_SHORT).show();
}
}
});
}
| private void displayScriptureList(ListView view, Cursor scriptureQuery, final Boolean enabled) {
// Set up the adapter that is going to be displayed in the list view.
Context context = this.getApplicationContext();
final Bundle bundledScriptureList = new Bundle();
ArrayAdapter<LinearLayout> scriptureAdapter = new ArrayAdapter<LinearLayout>(context, android.R.layout.simple_list_item_1){
public View getView (int position, View convertView, ViewGroup parent){
return (View) this.getItem(position);
}
};
view.setAdapter(scriptureAdapter);
//Queries the database for any verses that have the same review date as the date when the screen was accessed.
try{
for(int positionOnScreen=0;positionOnScreen<scriptureQuery.getCount();positionOnScreen++){
scriptureQuery.moveToNext();
//Get the layout from the XML file for checkbox lists.
LinearLayout newLayout = (LinearLayout) this.getLayoutInflater().inflate(R.layout.checkbox_list_layout, null);
newLayout.setOrientation(LinearLayout.HORIZONTAL);
TextView newLabel = (TextView) newLayout.getChildAt(1);
newLabel.setText(scriptureQuery.getString(0));
final int position = positionOnScreen;
bundledScriptureList.putInt(String.valueOf(positionOnScreen), scriptureQuery.getInt(1));
//Display a checkbox.
CheckBox newCheckBox = (CheckBox) newLayout.getChildAt(0);
newCheckBox.setEnabled(enabled);
if(dbDateFormat.parse(scriptureQuery.getString(2)).getTime()>Calendar.getInstance(Locale.getDefault()).getTimeInMillis()){
newCheckBox.setChecked(true);
}
newCheckBox.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
// Reset the NEXT_REVIEW_DATE if we are unchecking, otherwise mark the scripture as reviewed.
if(!((CheckBox) v).isChecked()){
FlashcardScriptureReviewFragment.updateReviewedScripture(TodaysMemoryVerses.this, bundledScriptureList.getInt(String.valueOf(position)), false);
}else{
FlashcardScriptureReviewFragment.updateReviewedScripture(TodaysMemoryVerses.this, bundledScriptureList.getInt(String.valueOf(position)), true);
}
}
});
scriptureAdapter.add(newLayout);
}
} catch(SQLiteException e){
System.err.println("Database issue...");
e.printStackTrace();
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// When any of the entries are pressed they can then be edited.
view.setOnItemClickListener(new OnItemClickListener(){
public void onItemClick(AdapterView<?> parent, View dueTodayView, int position,long id) {
// Sends the query row that holds the values we would like to edit.
if(enabled){
LinearLayout view = (LinearLayout) dueTodayView;
CheckBox checkBox = (CheckBox) view.getChildAt(0);
if(!checkBox.isPressed()){
Intent intent = new Intent(TodaysMemoryVerses.this,ScriptureReviewFragmentActivity.class);
intent.putExtra("bundledScriptureList",bundledScriptureList);
intent.putExtra("positionOnScreen", position);
startActivity(intent);
}
}else{
dueTodayView.performHapticFeedback(HapticFeedbackConstants.KEYBOARD_TAP);
Toast.makeText(getApplicationContext(), "Scripture is disabled.", Toast.LENGTH_SHORT).show();
}
}
});
}
|
diff --git a/src/test/integration/nl/surfnet/bod/mtosi/MtosiLiveClientTestIntegration.java b/src/test/integration/nl/surfnet/bod/mtosi/MtosiLiveClientTestIntegration.java
index 2cf46ce2a..055bbd779 100644
--- a/src/test/integration/nl/surfnet/bod/mtosi/MtosiLiveClientTestIntegration.java
+++ b/src/test/integration/nl/surfnet/bod/mtosi/MtosiLiveClientTestIntegration.java
@@ -1,75 +1,75 @@
/**
* The owner of the original code is SURFnet BV.
*
* Portions created by the original owner are Copyright (C) 2011-2012 the
* original owner. All Rights Reserved.
*
* Portions created by other contributors are Copyright (C) the contributor.
* All Rights Reserved.
*
* Contributor(s):
* (Contributors insert name & email here)
*
* This file is part of the SURFnet7 Bandwidth on Demand software.
*
* The SURFnet7 Bandwidth on Demand software is free software: you can
* redistribute it and/or modify it under the terms of the BSD license
* included with this distribution.
*
* If the BSD license cannot be found with this distribution, it is available
* at the following location <http://www.opensource.org/licenses/BSD-3-Clause>
*/
package nl.surfnet.bod.mtosi;
import static org.hamcrest.MatcherAssert.*;
import static org.hamcrest.Matchers.*;
import java.io.IOException;
import java.util.List;
import javax.annotation.Resource;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractTransactionalJUnit4SpringContextTests;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.transaction.TransactionConfiguration;
import nl.surfnet.bod.domain.PhysicalPort;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "/spring/appCtx.xml", "/spring/appCtx-jpa-integration.xml",
"/spring/appCtx-nbi-client.xml", "/spring/appCtx-idd-client.xml" })
@TransactionConfiguration(defaultRollback = true, transactionManager = "transactionManager")
public class MtosiLiveClientTestIntegration extends AbstractTransactionalJUnit4SpringContextTests {
@Resource(name = "mtosiLiveClient")
private MtosiLiveClient mtosiLiveClient;
@Before
public void setup() throws IOException {
}
@Test
public void getUnallocatedPorts() {
final List<PhysicalPort> unallocatedPorts = mtosiLiveClient.getUnallocatedPorts();
assertThat(unallocatedPorts, hasSize(greaterThan(0)));
final PhysicalPort firstPhysicalPort = unallocatedPorts.get(0);
// It's always /rack=1/shelf=1 for every NE so we can use 1-1 safely
assertThat(firstPhysicalPort.getBodPortId(), containsString("1-1"));
- assertThat(firstPhysicalPort.getBodPortId(), containsString("1-1"));
+ assertThat(firstPhysicalPort.getBodPortId(), containsString("_"));
assertThat(firstPhysicalPort.getNmsPortId(), containsString("1-1"));
assertThat(firstPhysicalPort.getNmsPortSpeed(), notNullValue());
assertThat(firstPhysicalPort.getNmsSapName(), startsWith("SAP-"));
assertThat(firstPhysicalPort.isAlignedWithNMS(), is(true));
}
@Test
public void getUnallocatedPortsCount() {
assertThat(mtosiLiveClient.getUnallocatedMtosiPortCount(), greaterThan(0));
}
}
| true | true | public void getUnallocatedPorts() {
final List<PhysicalPort> unallocatedPorts = mtosiLiveClient.getUnallocatedPorts();
assertThat(unallocatedPorts, hasSize(greaterThan(0)));
final PhysicalPort firstPhysicalPort = unallocatedPorts.get(0);
// It's always /rack=1/shelf=1 for every NE so we can use 1-1 safely
assertThat(firstPhysicalPort.getBodPortId(), containsString("1-1"));
assertThat(firstPhysicalPort.getBodPortId(), containsString("1-1"));
assertThat(firstPhysicalPort.getNmsPortId(), containsString("1-1"));
assertThat(firstPhysicalPort.getNmsPortSpeed(), notNullValue());
assertThat(firstPhysicalPort.getNmsSapName(), startsWith("SAP-"));
assertThat(firstPhysicalPort.isAlignedWithNMS(), is(true));
}
| public void getUnallocatedPorts() {
final List<PhysicalPort> unallocatedPorts = mtosiLiveClient.getUnallocatedPorts();
assertThat(unallocatedPorts, hasSize(greaterThan(0)));
final PhysicalPort firstPhysicalPort = unallocatedPorts.get(0);
// It's always /rack=1/shelf=1 for every NE so we can use 1-1 safely
assertThat(firstPhysicalPort.getBodPortId(), containsString("1-1"));
assertThat(firstPhysicalPort.getBodPortId(), containsString("_"));
assertThat(firstPhysicalPort.getNmsPortId(), containsString("1-1"));
assertThat(firstPhysicalPort.getNmsPortSpeed(), notNullValue());
assertThat(firstPhysicalPort.getNmsSapName(), startsWith("SAP-"));
assertThat(firstPhysicalPort.isAlignedWithNMS(), is(true));
}
|
diff --git a/luni/src/test/java/libcore/java/util/FormatterTest.java b/luni/src/test/java/libcore/java/util/FormatterTest.java
index ce33c271a..00d0ab74c 100644
--- a/luni/src/test/java/libcore/java/util/FormatterTest.java
+++ b/luni/src/test/java/libcore/java/util/FormatterTest.java
@@ -1,129 +1,129 @@
/*
* Copyright (C) 2009 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package libcore.java.util;
import java.math.BigDecimal;
import java.util.Calendar;
import java.util.Locale;
import java.util.TimeZone;
public class FormatterTest extends junit.framework.TestCase {
public void test_numberLocalization() throws Exception {
Locale arabic = new Locale("ar");
// Check the fast path for %d:
assertEquals("12 \u0661\u0662\u0663\u0664\u0665\u0666\u0667\u0668\u0669\u0660 34",
String.format(arabic, "12 %d 34", 1234567890));
// And the slow path too:
assertEquals("12 \u0661\u066c\u0662\u0663\u0664\u066c\u0665\u0666\u0667\u066c\u0668\u0669\u0660 34",
String.format(arabic, "12 %,d 34", 1234567890));
// And three localized floating point formats:
- assertEquals("12 \u0661\u066b\u0662\u0663\u0660e+\u0660\u0660 34",
+ assertEquals("12 \u0661\u066b\u0662\u0663\u0660\u0627\u0633+\u0660\u0660 34",
String.format(arabic, "12 %.3e 34", 1.23));
assertEquals("12 \u0661\u066b\u0662\u0663\u0660 34",
String.format(arabic, "12 %.3f 34", 1.23));
assertEquals("12 \u0661\u066b\u0662\u0663 34",
String.format(arabic, "12 %.3g 34", 1.23));
// And date/time formatting (we assume that all time/date number formatting is done by the
// same code, so this is representative):
Calendar c = Calendar.getInstance(TimeZone.getTimeZone("GMT-08:00"));
c.setTimeInMillis(0);
assertEquals("12 \u0661\u0666:\u0660\u0660:\u0660\u0660 34",
String.format(arabic, "12 %tT 34", c));
// These shouldn't get localized:
assertEquals("1234", String.format(arabic, "1234"));
assertEquals("1234", String.format(arabic, "%s", "1234"));
assertEquals("1234", String.format(arabic, "%s", 1234));
assertEquals("2322", String.format(arabic, "%o", 1234));
assertEquals("4d2", String.format(arabic, "%x", 1234));
assertEquals("0x1.0p0", String.format(arabic, "%a", 1.0));
}
// http://b/2301938
public void test_uppercaseConversions() throws Exception {
// In most locales, the upper-case equivalent of "i" is "I".
assertEquals("JAKOB ARJOUNI", String.format(Locale.US, "%S", "jakob arjouni"));
// In Turkish-language locales, there's a dotted capital "i".
assertEquals("JAKOB ARJOUN\u0130", String.format(new Locale("tr", "TR"), "%S", "jakob arjouni"));
}
// Creating a NumberFormat is expensive, so we like to reuse them, but we need to be careful
// because they're mutable.
public void test_NumberFormat_reuse() throws Exception {
assertEquals("7.000000 7", String.format("%.6f %d", 7.0, 7));
}
public void test_grouping() throws Exception {
// The interesting case is -123, where you might naively output "-,123" if you're just
// inserting a separator every three characters. The cases where there are three digits
// before the first separator may also be interesting.
assertEquals("-1", String.format("%,d", -1));
assertEquals("-12", String.format("%,d", -12));
assertEquals("-123", String.format("%,d", -123));
assertEquals("-1,234", String.format("%,d", -1234));
assertEquals("-12,345", String.format("%,d", -12345));
assertEquals("-123,456", String.format("%,d", -123456));
assertEquals("-1,234,567", String.format("%,d", -1234567));
assertEquals("-12,345,678", String.format("%,d", -12345678));
assertEquals("-123,456,789", String.format("%,d", -123456789));
assertEquals("1", String.format("%,d", 1));
assertEquals("12", String.format("%,d", 12));
assertEquals("123", String.format("%,d", 123));
assertEquals("1,234", String.format("%,d", 1234));
assertEquals("12,345", String.format("%,d", 12345));
assertEquals("123,456", String.format("%,d", 123456));
assertEquals("1,234,567", String.format("%,d", 1234567));
assertEquals("12,345,678", String.format("%,d", 12345678));
assertEquals("123,456,789", String.format("%,d", 123456789));
}
public void test_formatNull() throws Exception {
// We fast-path %s and %d (with no configuration) but need to make sure we handle the
// special case of the null argument...
assertEquals("null", String.format(Locale.US, "%s", (String) null));
assertEquals("null", String.format(Locale.US, "%d", (Integer) null));
// ...without screwing up conversions that don't take an argument.
assertEquals("%", String.format(Locale.US, "%%"));
}
// Alleged regression tests for historical bugs. (It's unclear whether the bugs were in
// BigDecimal or Formatter.)
public void test_BigDecimalFormatting() throws Exception {
BigDecimal[] input = new BigDecimal[] {
new BigDecimal("20.00000"),
new BigDecimal("20.000000"),
new BigDecimal(".2"),
new BigDecimal("2"),
new BigDecimal("-2"),
new BigDecimal("200000000000000000000000"),
new BigDecimal("20000000000000000000000000000000000000000000000000")
};
String[] output = new String[] {
"20.00",
"20.00",
"0.20",
"2.00",
"-2.00",
"200000000000000000000000.00",
"20000000000000000000000000000000000000000000000000.00"
};
for (int i = 0; i < input.length; ++i) {
String result = String.format("%.2f", input[i]);
assertEquals("input=\"" + input[i] + "\", " + ",expected=" + output[i] + ",actual=" + result,
output[i], result);
}
}
}
| true | true | public void test_numberLocalization() throws Exception {
Locale arabic = new Locale("ar");
// Check the fast path for %d:
assertEquals("12 \u0661\u0662\u0663\u0664\u0665\u0666\u0667\u0668\u0669\u0660 34",
String.format(arabic, "12 %d 34", 1234567890));
// And the slow path too:
assertEquals("12 \u0661\u066c\u0662\u0663\u0664\u066c\u0665\u0666\u0667\u066c\u0668\u0669\u0660 34",
String.format(arabic, "12 %,d 34", 1234567890));
// And three localized floating point formats:
assertEquals("12 \u0661\u066b\u0662\u0663\u0660e+\u0660\u0660 34",
String.format(arabic, "12 %.3e 34", 1.23));
assertEquals("12 \u0661\u066b\u0662\u0663\u0660 34",
String.format(arabic, "12 %.3f 34", 1.23));
assertEquals("12 \u0661\u066b\u0662\u0663 34",
String.format(arabic, "12 %.3g 34", 1.23));
// And date/time formatting (we assume that all time/date number formatting is done by the
// same code, so this is representative):
Calendar c = Calendar.getInstance(TimeZone.getTimeZone("GMT-08:00"));
c.setTimeInMillis(0);
assertEquals("12 \u0661\u0666:\u0660\u0660:\u0660\u0660 34",
String.format(arabic, "12 %tT 34", c));
// These shouldn't get localized:
assertEquals("1234", String.format(arabic, "1234"));
assertEquals("1234", String.format(arabic, "%s", "1234"));
assertEquals("1234", String.format(arabic, "%s", 1234));
assertEquals("2322", String.format(arabic, "%o", 1234));
assertEquals("4d2", String.format(arabic, "%x", 1234));
assertEquals("0x1.0p0", String.format(arabic, "%a", 1.0));
}
| public void test_numberLocalization() throws Exception {
Locale arabic = new Locale("ar");
// Check the fast path for %d:
assertEquals("12 \u0661\u0662\u0663\u0664\u0665\u0666\u0667\u0668\u0669\u0660 34",
String.format(arabic, "12 %d 34", 1234567890));
// And the slow path too:
assertEquals("12 \u0661\u066c\u0662\u0663\u0664\u066c\u0665\u0666\u0667\u066c\u0668\u0669\u0660 34",
String.format(arabic, "12 %,d 34", 1234567890));
// And three localized floating point formats:
assertEquals("12 \u0661\u066b\u0662\u0663\u0660\u0627\u0633+\u0660\u0660 34",
String.format(arabic, "12 %.3e 34", 1.23));
assertEquals("12 \u0661\u066b\u0662\u0663\u0660 34",
String.format(arabic, "12 %.3f 34", 1.23));
assertEquals("12 \u0661\u066b\u0662\u0663 34",
String.format(arabic, "12 %.3g 34", 1.23));
// And date/time formatting (we assume that all time/date number formatting is done by the
// same code, so this is representative):
Calendar c = Calendar.getInstance(TimeZone.getTimeZone("GMT-08:00"));
c.setTimeInMillis(0);
assertEquals("12 \u0661\u0666:\u0660\u0660:\u0660\u0660 34",
String.format(arabic, "12 %tT 34", c));
// These shouldn't get localized:
assertEquals("1234", String.format(arabic, "1234"));
assertEquals("1234", String.format(arabic, "%s", "1234"));
assertEquals("1234", String.format(arabic, "%s", 1234));
assertEquals("2322", String.format(arabic, "%o", 1234));
assertEquals("4d2", String.format(arabic, "%x", 1234));
assertEquals("0x1.0p0", String.format(arabic, "%a", 1.0));
}
|
diff --git a/src/com/blastedstudios/gdxworld/plugin/mode/quest/QuestWindow.java b/src/com/blastedstudios/gdxworld/plugin/mode/quest/QuestWindow.java
index 4a09d18..f196b78 100644
--- a/src/com/blastedstudios/gdxworld/plugin/mode/quest/QuestWindow.java
+++ b/src/com/blastedstudios/gdxworld/plugin/mode/quest/QuestWindow.java
@@ -1,93 +1,94 @@
package com.blastedstudios.gdxworld.plugin.mode.quest;
import java.util.List;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.scenes.scene2d.InputEvent;
import com.badlogic.gdx.scenes.scene2d.ui.Button;
import com.badlogic.gdx.scenes.scene2d.ui.ScrollPane;
import com.badlogic.gdx.scenes.scene2d.ui.Skin;
import com.badlogic.gdx.scenes.scene2d.ui.Table;
import com.badlogic.gdx.scenes.scene2d.ui.TextButton;
import com.badlogic.gdx.scenes.scene2d.utils.ClickListener;
import com.blastedstudios.gdxworld.ui.AbstractWindow;
import com.blastedstudios.gdxworld.ui.leveleditor.LevelEditorScreen;
import com.blastedstudios.gdxworld.plugin.mode.quest.QuestMode;
import com.blastedstudios.gdxworld.world.quest.GDXQuest;
class QuestWindow extends AbstractWindow {
private final Skin skin;
private final Table questTable;
private final List<GDXQuest> quests;
private final LevelEditorScreen screen;
private QuestEditor editor;
public QuestWindow(final Skin skin, final List<GDXQuest> quests,
final QuestMode mode, LevelEditorScreen screen) {
super("Quest Window", skin);
this.skin = skin;
this.quests = quests;
this.screen = screen;
questTable = new Table(skin);
ScrollPane scrollPane = new ScrollPane(questTable);
Button clearButton = new TextButton("Clear", skin);
Button addButton = new TextButton("Add", skin);
for(GDXQuest quest : quests){
questTable.add(createQuestTable(quest));
questTable.row();
}
clearButton.addListener(new ClickListener() {
@Override public void clicked(InputEvent event, float x, float y) {
quests.clear();
questTable.clear();
- editor.remove();
+ if(editor != null)
+ editor.remove();
}
});
addButton.addListener(new ClickListener() {
@Override public void clicked(InputEvent event, float x, float y) {
GDXQuest quest = new GDXQuest();
quests.add(quest);
questTable.add(createQuestTable(quest));
}
});
add(scrollPane).colspan(3);
row();
add(addButton);
add(clearButton);
setMovable(false);
setHeight(400);
setWidth(400);
}
private QuestTable createQuestTable(GDXQuest quest){
return new QuestTable(skin, quest, this);
}
public void removeQuest(GDXQuest quest) {
quests.remove(quest);
questTable.clear();
for(GDXQuest addQuest : quests){
questTable.add(createQuestTable(addQuest));
questTable.row();
}
}
public void editQuest(GDXQuest quest, QuestTable table) {
if(editor != null)
editor.remove();
screen.getStage().addActor(editor = new QuestEditor(quest, skin, table));
}
@Override public boolean remove(){
return super.remove() && (editor == null || editor.remove());
}
@Override public boolean contains(float x, float y){
return super.contains(x, y) || (editor != null && editor.contains(x, y));
}
public void touched(Vector2 coordinates) {
if(editor != null)
editor.touched(coordinates);
}
}
| true | true | public QuestWindow(final Skin skin, final List<GDXQuest> quests,
final QuestMode mode, LevelEditorScreen screen) {
super("Quest Window", skin);
this.skin = skin;
this.quests = quests;
this.screen = screen;
questTable = new Table(skin);
ScrollPane scrollPane = new ScrollPane(questTable);
Button clearButton = new TextButton("Clear", skin);
Button addButton = new TextButton("Add", skin);
for(GDXQuest quest : quests){
questTable.add(createQuestTable(quest));
questTable.row();
}
clearButton.addListener(new ClickListener() {
@Override public void clicked(InputEvent event, float x, float y) {
quests.clear();
questTable.clear();
editor.remove();
}
});
addButton.addListener(new ClickListener() {
@Override public void clicked(InputEvent event, float x, float y) {
GDXQuest quest = new GDXQuest();
quests.add(quest);
questTable.add(createQuestTable(quest));
}
});
add(scrollPane).colspan(3);
row();
add(addButton);
add(clearButton);
setMovable(false);
setHeight(400);
setWidth(400);
}
| public QuestWindow(final Skin skin, final List<GDXQuest> quests,
final QuestMode mode, LevelEditorScreen screen) {
super("Quest Window", skin);
this.skin = skin;
this.quests = quests;
this.screen = screen;
questTable = new Table(skin);
ScrollPane scrollPane = new ScrollPane(questTable);
Button clearButton = new TextButton("Clear", skin);
Button addButton = new TextButton("Add", skin);
for(GDXQuest quest : quests){
questTable.add(createQuestTable(quest));
questTable.row();
}
clearButton.addListener(new ClickListener() {
@Override public void clicked(InputEvent event, float x, float y) {
quests.clear();
questTable.clear();
if(editor != null)
editor.remove();
}
});
addButton.addListener(new ClickListener() {
@Override public void clicked(InputEvent event, float x, float y) {
GDXQuest quest = new GDXQuest();
quests.add(quest);
questTable.add(createQuestTable(quest));
}
});
add(scrollPane).colspan(3);
row();
add(addButton);
add(clearButton);
setMovable(false);
setHeight(400);
setWidth(400);
}
|
diff --git a/Arena/src/game/View.java b/Arena/src/game/View.java
index baa76fb..ac05736 100644
--- a/Arena/src/game/View.java
+++ b/Arena/src/game/View.java
@@ -1,53 +1,54 @@
package game;
import java.awt.Graphics;
import java.awt.Image;
import javax.swing.JFrame;
import javax.swing.JPanel;
/**
* Class for the GUI
*
* @author Jacob Charles, Dean Hamlin
*
*/
public class View extends JFrame {
//for double buffering
Image backBuffer;
/**
* test constructor
*/
public View() {
super();
setSize(640, 480);
backBuffer = this.createImage(this.getWidth(), this.getHeight());
+ //TODO: make backBuffer able to return a non-null Graphics object
setVisible(true);
}
/**
* Connects a controller to the screen
*
* @param c
* the controller object to be connected
*/
public void attachController(Controller c) {
this.addKeyListener(new ControlListener(c));
}
/**
* Draw a game state
*
* @param state
* game state to draw
*/
public void reDraw(ClientGameState state){
//state.draw(this.getContentPane().getGraphics());
state.draw(backBuffer.getGraphics());
this.getContentPane().getGraphics().drawImage(backBuffer, 0, 0, null);
}
}
| true | true | public View() {
super();
setSize(640, 480);
backBuffer = this.createImage(this.getWidth(), this.getHeight());
setVisible(true);
}
| public View() {
super();
setSize(640, 480);
backBuffer = this.createImage(this.getWidth(), this.getHeight());
//TODO: make backBuffer able to return a non-null Graphics object
setVisible(true);
}
|
diff --git a/remoting/fr.opensagres.xdocreport.remoting.resources/src/main/java/fr/opensagres/xdocreport/remoting/resources/services/rest/client/JAXRSResourcesServiceClient.java b/remoting/fr.opensagres.xdocreport.remoting.resources/src/main/java/fr/opensagres/xdocreport/remoting/resources/services/rest/client/JAXRSResourcesServiceClient.java
index b2bb0572..7333b182 100644
--- a/remoting/fr.opensagres.xdocreport.remoting.resources/src/main/java/fr/opensagres/xdocreport/remoting/resources/services/rest/client/JAXRSResourcesServiceClient.java
+++ b/remoting/fr.opensagres.xdocreport.remoting.resources/src/main/java/fr/opensagres/xdocreport/remoting/resources/services/rest/client/JAXRSResourcesServiceClient.java
@@ -1,66 +1,66 @@
package fr.opensagres.xdocreport.remoting.resources.services.rest.client;
import java.util.List;
import javax.ws.rs.core.MediaType;
import org.apache.cxf.jaxrs.client.WebClient;
import fr.opensagres.xdocreport.remoting.resources.domain.Filter;
import fr.opensagres.xdocreport.remoting.resources.domain.Resource;
import fr.opensagres.xdocreport.remoting.resources.services.ResourcesService;
import fr.opensagres.xdocreport.remoting.resources.services.ResourcesServiceName;
public class JAXRSResourcesServiceClient
implements ResourcesService
{
private final WebClient client;
public JAXRSResourcesServiceClient( String baseAddress, String username, String password )
{
- if (username!=null && !username.isEmpty()) {
+ if (username!=null && !"".equals(username)) {
this.client = WebClient.create( baseAddress , username, password, null);
} else {
this.client = WebClient.create( baseAddress );
}
}
public String getName()
{
return client.path( ResourcesServiceName.name ).accept( MediaType.TEXT_PLAIN ).get( String.class );
}
public Resource getRoot()
{
return client.path( ResourcesServiceName.root ).accept( MediaType.APPLICATION_JSON ).get( Resource.class );
}
public Resource getRoot( Filter filter )
{
// TODO Auto-generated method stub
return null;
}
public List<byte[]> download( List<String> resourcePaths )
{
// TODO Auto-generated method stub
return null;
}
public byte[] download( String resourcePath )
{
StringBuilder path = new StringBuilder( ResourcesServiceName.download.name() );
path.append( "/" );
path.append( resourcePath );
return client.path( path.toString() ).accept( MediaType.APPLICATION_JSON_TYPE ).get( byte[].class );
}
public void upload( String resourcePath, byte[] content )
{
// TODO Auto-generated method stub
}
}
| true | true | public JAXRSResourcesServiceClient( String baseAddress, String username, String password )
{
if (username!=null && !username.isEmpty()) {
this.client = WebClient.create( baseAddress , username, password, null);
} else {
this.client = WebClient.create( baseAddress );
}
}
| public JAXRSResourcesServiceClient( String baseAddress, String username, String password )
{
if (username!=null && !"".equals(username)) {
this.client = WebClient.create( baseAddress , username, password, null);
} else {
this.client = WebClient.create( baseAddress );
}
}
|
diff --git a/openregistry-service-impl/src/main/java/org/openregistry/core/service/identifier/TestIdentifierAssigner.java b/openregistry-service-impl/src/main/java/org/openregistry/core/service/identifier/TestIdentifierAssigner.java
index ad52aa93..4bdc209d 100644
--- a/openregistry-service-impl/src/main/java/org/openregistry/core/service/identifier/TestIdentifierAssigner.java
+++ b/openregistry-service-impl/src/main/java/org/openregistry/core/service/identifier/TestIdentifierAssigner.java
@@ -1,100 +1,100 @@
/**
* Licensed to Jasig under one or more contributor license
* agreements. See the NOTICE file distributed with this work
* for additional information regarding copyright ownership.
* Jasig licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a
* copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.openregistry.core.service.identifier;
import org.openregistry.core.domain.sor.SorPerson;
import org.openregistry.core.domain.Person;
import org.openregistry.core.domain.Name;
import org.openregistry.core.domain.Identifier;
import org.openregistry.core.repository.ReferenceRepository;
import org.springframework.util.StringUtils;
import javax.inject.Inject;
import java.security.SecureRandom;
/**
* Test identifier assigner that generates identifiers purely randomly. Its PERFECT for demonstrations, but not
* for any form of actual testing or production usage.
*
* @version $Revision$ $Date$
* @since 0.1
*/
public class TestIdentifierAssigner extends AbstractIdentifierAssigner {
/** The array of printable characters to be used in our random string. */
private static final char[] PRINTABLE_CHARACTERS = "0123456789".toCharArray();
private static final SecureRandom secureRandom = new SecureRandom();
private final ReferenceRepository referenceRepository;
@Inject
public TestIdentifierAssigner(final ReferenceRepository referenceRepository) {
this.referenceRepository = referenceRepository;
}
public void addIdentifierTo(final SorPerson sorPerson, final Person person) {
final Identifier primaryNetid = findPrimaryIdentifier(person, this.getIdentifierType());
- if (primaryNetid != null) { // don't set if already there
+ if (primaryNetid == null) { // don't set if already there
final Name name = person.getOfficialName();
final StringBuilder builder = new StringBuilder();
if (StringUtils.hasText(name.getGiven())) {
builder.append(name.getGiven().substring(0,1));
}
if (StringUtils.hasText(name.getMiddle())) {
builder.append(name.getMiddle().substring(0,1));
}
if (StringUtils.hasText(name.getFamily())) {
builder.append(name.getFamily().substring(0,1));
}
builder.append(constructNewValue());
final Identifier identifier = person.addIdentifier(referenceRepository.findIdentifierType(getIdentifierType()), builder.toString());
identifier.setDeleted(false);
identifier.setPrimary(true);
}
}
public String getIdentifierType() {
return "NETID";
}
private String constructNewValue() {
final int ID_LENGTH = secureRandom.nextInt(7) + 3;
final byte[] random = new byte[ID_LENGTH];
secureRandom.nextBytes(random);
return convertBytesToString(random);
}
private String convertBytesToString(final byte[] random) {
final char[] output = new char[random.length];
for (int i = 0; i < random.length; i++) {
final int index = Math.abs(random[i] % PRINTABLE_CHARACTERS.length);
output[i] = PRINTABLE_CHARACTERS[index];
}
return new String(output);
}
}
| true | true | public void addIdentifierTo(final SorPerson sorPerson, final Person person) {
final Identifier primaryNetid = findPrimaryIdentifier(person, this.getIdentifierType());
if (primaryNetid != null) { // don't set if already there
final Name name = person.getOfficialName();
final StringBuilder builder = new StringBuilder();
if (StringUtils.hasText(name.getGiven())) {
builder.append(name.getGiven().substring(0,1));
}
if (StringUtils.hasText(name.getMiddle())) {
builder.append(name.getMiddle().substring(0,1));
}
if (StringUtils.hasText(name.getFamily())) {
builder.append(name.getFamily().substring(0,1));
}
builder.append(constructNewValue());
final Identifier identifier = person.addIdentifier(referenceRepository.findIdentifierType(getIdentifierType()), builder.toString());
identifier.setDeleted(false);
identifier.setPrimary(true);
}
}
| public void addIdentifierTo(final SorPerson sorPerson, final Person person) {
final Identifier primaryNetid = findPrimaryIdentifier(person, this.getIdentifierType());
if (primaryNetid == null) { // don't set if already there
final Name name = person.getOfficialName();
final StringBuilder builder = new StringBuilder();
if (StringUtils.hasText(name.getGiven())) {
builder.append(name.getGiven().substring(0,1));
}
if (StringUtils.hasText(name.getMiddle())) {
builder.append(name.getMiddle().substring(0,1));
}
if (StringUtils.hasText(name.getFamily())) {
builder.append(name.getFamily().substring(0,1));
}
builder.append(constructNewValue());
final Identifier identifier = person.addIdentifier(referenceRepository.findIdentifierType(getIdentifierType()), builder.toString());
identifier.setDeleted(false);
identifier.setPrimary(true);
}
}
|
diff --git a/htmlunit/src/test/java/com/gargoylesoftware/htmlunit/javascript/host/css/SelectorSpecificityTest.java b/htmlunit/src/test/java/com/gargoylesoftware/htmlunit/javascript/host/css/SelectorSpecificityTest.java
index b0bf0efca..a896b792b 100644
--- a/htmlunit/src/test/java/com/gargoylesoftware/htmlunit/javascript/host/css/SelectorSpecificityTest.java
+++ b/htmlunit/src/test/java/com/gargoylesoftware/htmlunit/javascript/host/css/SelectorSpecificityTest.java
@@ -1,100 +1,101 @@
/*
* Copyright (c) 2002-2011 Gargoyle Software Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.gargoylesoftware.htmlunit.javascript.host.css;
import java.io.StringReader;
import org.junit.Assert;
import org.junit.Test;
import org.w3c.css.sac.InputSource;
import org.w3c.css.sac.Selector;
import com.gargoylesoftware.htmlunit.WebTestCase;
import com.gargoylesoftware.htmlunit.BrowserRunner.Browser;
import com.gargoylesoftware.htmlunit.BrowserRunner.Browsers;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.gargoylesoftware.htmlunit.html.HtmlStyle;
import com.gargoylesoftware.htmlunit.javascript.host.html.HTMLStyleElement;
/**
* Tests for {@link SelectorSpecificity}.
*
* @version $Revision$
* @author Marc Guillemot
*/
public class SelectorSpecificityTest extends WebTestCase {
/**
* @throws Exception if the test fails
*/
@Test
@Browsers(Browser.NONE)
public void selectorSpecifity() throws Exception {
final SelectorSpecificity specificy0 = selectorSpecifity("*", "0,0,0,0");
final SelectorSpecificity specificy1 = selectorSpecifity("li", "0,0,0,1");
final SelectorSpecificity specificy2a = selectorSpecifity("li:first-line", "0,0,0,2");
final SelectorSpecificity specificy2b = selectorSpecifity("ul li", "0,0,0,2");
+ final SelectorSpecificity specificy2c = selectorSpecifity("body > p", "0,0,0,2");
final SelectorSpecificity specificy3 = selectorSpecifity("ul ol+li", "0,0,0,3");
- selectorSpecifity("body > p", "0,0,1,1");
final SelectorSpecificity specificy11 = selectorSpecifity("h1 + *[rel=up]", "0,0,1,1");
final SelectorSpecificity specificy13 = selectorSpecifity("ul ol li.red", "0,0,1,3");
final SelectorSpecificity specificy21 = selectorSpecifity("li.red.level", "0,0,2,1");
final SelectorSpecificity specificy100 = selectorSpecifity("#x34y", "0,1,0,0");
Assert.assertEquals(0, specificy0.compareTo(specificy0));
Assert.assertTrue(specificy0.compareTo(specificy1) < 0);
Assert.assertTrue(specificy0.compareTo(specificy2a) < 0);
Assert.assertTrue(specificy0.compareTo(specificy13) < 0);
Assert.assertEquals(0, specificy1.compareTo(specificy1));
Assert.assertTrue(specificy1.compareTo(specificy0) > 0);
Assert.assertTrue(specificy1.compareTo(specificy2a) < 0);
Assert.assertTrue(specificy1.compareTo(specificy13) < 0);
Assert.assertEquals(0, specificy2a.compareTo(specificy2b));
+ Assert.assertEquals(0, specificy2a.compareTo(specificy2c));
Assert.assertTrue(specificy2a.compareTo(specificy0) > 0);
Assert.assertTrue(specificy2a.compareTo(specificy3) < 0);
Assert.assertTrue(specificy2a.compareTo(specificy11) < 0);
Assert.assertTrue(specificy2a.compareTo(specificy13) < 0);
Assert.assertTrue(specificy2a.compareTo(specificy100) < 0);
Assert.assertEquals(0, specificy11.compareTo(specificy11));
Assert.assertTrue(specificy11.compareTo(specificy0) > 0);
Assert.assertTrue(specificy11.compareTo(specificy13) < 0);
Assert.assertTrue(specificy11.compareTo(specificy21) < 0);
Assert.assertTrue(specificy11.compareTo(specificy100) < 0);
}
private SelectorSpecificity selectorSpecifity(final String selector, final String expectedSpecificity)
throws Exception {
final String html =
"<html><body id='b'><style></style>\n"
+ "<div id='d' class='foo bar'><span>x</span><span id='s'>a</span>b</div>\n"
+ "</body></html>";
final HtmlPage page = loadPage(html);
final HtmlStyle node = (HtmlStyle) page.getElementsByTagName("style").item(0);
final HTMLStyleElement host = (HTMLStyleElement) node.getScriptObject();
final CSSStyleSheet sheet = host.jsxGet_sheet();
final Selector selectorObject = parseSelector(sheet, selector);
final SelectorSpecificity specificity = new SelectorSpecificity(selectorObject);
assertEquals(expectedSpecificity, specificity.toString());
return specificity;
}
private Selector parseSelector(final CSSStyleSheet sheet, final String rule) {
return sheet.parseSelectors(new InputSource(new StringReader(rule))).item(0);
}
}
| false | true | public void selectorSpecifity() throws Exception {
final SelectorSpecificity specificy0 = selectorSpecifity("*", "0,0,0,0");
final SelectorSpecificity specificy1 = selectorSpecifity("li", "0,0,0,1");
final SelectorSpecificity specificy2a = selectorSpecifity("li:first-line", "0,0,0,2");
final SelectorSpecificity specificy2b = selectorSpecifity("ul li", "0,0,0,2");
final SelectorSpecificity specificy3 = selectorSpecifity("ul ol+li", "0,0,0,3");
selectorSpecifity("body > p", "0,0,1,1");
final SelectorSpecificity specificy11 = selectorSpecifity("h1 + *[rel=up]", "0,0,1,1");
final SelectorSpecificity specificy13 = selectorSpecifity("ul ol li.red", "0,0,1,3");
final SelectorSpecificity specificy21 = selectorSpecifity("li.red.level", "0,0,2,1");
final SelectorSpecificity specificy100 = selectorSpecifity("#x34y", "0,1,0,0");
Assert.assertEquals(0, specificy0.compareTo(specificy0));
Assert.assertTrue(specificy0.compareTo(specificy1) < 0);
Assert.assertTrue(specificy0.compareTo(specificy2a) < 0);
Assert.assertTrue(specificy0.compareTo(specificy13) < 0);
Assert.assertEquals(0, specificy1.compareTo(specificy1));
Assert.assertTrue(specificy1.compareTo(specificy0) > 0);
Assert.assertTrue(specificy1.compareTo(specificy2a) < 0);
Assert.assertTrue(specificy1.compareTo(specificy13) < 0);
Assert.assertEquals(0, specificy2a.compareTo(specificy2b));
Assert.assertTrue(specificy2a.compareTo(specificy0) > 0);
Assert.assertTrue(specificy2a.compareTo(specificy3) < 0);
Assert.assertTrue(specificy2a.compareTo(specificy11) < 0);
Assert.assertTrue(specificy2a.compareTo(specificy13) < 0);
Assert.assertTrue(specificy2a.compareTo(specificy100) < 0);
Assert.assertEquals(0, specificy11.compareTo(specificy11));
Assert.assertTrue(specificy11.compareTo(specificy0) > 0);
Assert.assertTrue(specificy11.compareTo(specificy13) < 0);
Assert.assertTrue(specificy11.compareTo(specificy21) < 0);
Assert.assertTrue(specificy11.compareTo(specificy100) < 0);
}
| public void selectorSpecifity() throws Exception {
final SelectorSpecificity specificy0 = selectorSpecifity("*", "0,0,0,0");
final SelectorSpecificity specificy1 = selectorSpecifity("li", "0,0,0,1");
final SelectorSpecificity specificy2a = selectorSpecifity("li:first-line", "0,0,0,2");
final SelectorSpecificity specificy2b = selectorSpecifity("ul li", "0,0,0,2");
final SelectorSpecificity specificy2c = selectorSpecifity("body > p", "0,0,0,2");
final SelectorSpecificity specificy3 = selectorSpecifity("ul ol+li", "0,0,0,3");
final SelectorSpecificity specificy11 = selectorSpecifity("h1 + *[rel=up]", "0,0,1,1");
final SelectorSpecificity specificy13 = selectorSpecifity("ul ol li.red", "0,0,1,3");
final SelectorSpecificity specificy21 = selectorSpecifity("li.red.level", "0,0,2,1");
final SelectorSpecificity specificy100 = selectorSpecifity("#x34y", "0,1,0,0");
Assert.assertEquals(0, specificy0.compareTo(specificy0));
Assert.assertTrue(specificy0.compareTo(specificy1) < 0);
Assert.assertTrue(specificy0.compareTo(specificy2a) < 0);
Assert.assertTrue(specificy0.compareTo(specificy13) < 0);
Assert.assertEquals(0, specificy1.compareTo(specificy1));
Assert.assertTrue(specificy1.compareTo(specificy0) > 0);
Assert.assertTrue(specificy1.compareTo(specificy2a) < 0);
Assert.assertTrue(specificy1.compareTo(specificy13) < 0);
Assert.assertEquals(0, specificy2a.compareTo(specificy2b));
Assert.assertEquals(0, specificy2a.compareTo(specificy2c));
Assert.assertTrue(specificy2a.compareTo(specificy0) > 0);
Assert.assertTrue(specificy2a.compareTo(specificy3) < 0);
Assert.assertTrue(specificy2a.compareTo(specificy11) < 0);
Assert.assertTrue(specificy2a.compareTo(specificy13) < 0);
Assert.assertTrue(specificy2a.compareTo(specificy100) < 0);
Assert.assertEquals(0, specificy11.compareTo(specificy11));
Assert.assertTrue(specificy11.compareTo(specificy0) > 0);
Assert.assertTrue(specificy11.compareTo(specificy13) < 0);
Assert.assertTrue(specificy11.compareTo(specificy21) < 0);
Assert.assertTrue(specificy11.compareTo(specificy100) < 0);
}
|
diff --git a/src/shoddybattleclient/LobbyWindow.java b/src/shoddybattleclient/LobbyWindow.java
index ece3eab..7d99c91 100644
--- a/src/shoddybattleclient/LobbyWindow.java
+++ b/src/shoddybattleclient/LobbyWindow.java
@@ -1,464 +1,464 @@
/*
* LobbyWindow.java
*
* Created on Apr 5, 2009, 12:47:25 PM
*
* This file is a part of Shoddy Battle.
* Copyright (C) 2009 Catherine Fitzpatrick and Benjamin Gwin
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License
* as published by the Free Software Foundation; either version 3
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program; if not, visit the Free Software Foundation, Inc.
* online at http://gnu.org.
*/
package shoddybattleclient;
import java.awt.Component;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.net.URL;
import javax.swing.*;
import java.util.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import shoddybattleclient.network.ServerLink;
import shoddybattleclient.network.ServerLink.ChallengeMediator;
import shoddybattleclient.utils.UserListModel;
/**
*
* @author ben
*/
public class LobbyWindow extends javax.swing.JFrame {
public static class Channel {
public static final int OWNER = 1; // +q
public static final int PROTECTED = 2; // +a
public static final int OP = 4; // +o
public static final int HALF_OP = 8; // +h
public static final int VOICE = 16; // +v
public static final int IDLE = 32; // inactive
public static final int BUSY = 64; // ("ignoring challenges")
public static final int TYPE_ORDINARY = 0;
public static final int TYPE_BATTLE = 1;
private int m_id;
private int m_type;
private String m_name;
private String m_topic;
private int m_flags;
private ChatPane m_chat;
private UserListModel m_users =
new UserListModel(new ArrayList<User>());
public void setChatPane(ChatPane c) {
m_chat = c;
}
public ChatPane getChatPane() {
return m_chat;
}
public UserListModel getModel() {
return m_users;
}
public static int getLevel(int flags) {
if ((flags & OWNER) != 0)
return 5;
if ((flags & PROTECTED) != 0)
return 4;
if ((flags & OP) != 0)
return 3;
if ((flags & HALF_OP) != 0)
return 2;
if ((flags & VOICE) != 0)
return 1;
return 0;
}
public Channel(int id, int type, String name, String topic, int flags) {
m_id = id;
m_type = type;
m_name = name;
m_topic = topic;
m_flags = flags;
}
public void addUser(String name, int flags) {
m_users.add(new User(name, flags));
}
public void removeUser(String name) {
m_users.remove(name);
}
public void updateUser(String name, int flags) {
m_users.setLevel(name, flags);
}
public void sort() {
m_users.sort();
}
public String getTopic() {
return m_topic;
}
public void setTopic(String topic) {
m_topic = topic;
}
public String getName() {
return m_name;
}
int getId() {
return m_id;
}
public User getUser(String name) {
return m_users.getUser(name);
}
public int getType() {
return m_type;
}
}
public static class User implements Comparable {
public final static int STATUS_PRESENT = 0;
public final static int STATUS_AWAY = 1;
private String m_name;
private int m_status = 0;
private int m_flags, m_level;
private List<Integer> m_battles = new ArrayList<Integer>();
public User(String name, int flags) {
m_name = name;
m_flags = flags;
m_level = Channel.getLevel(flags);
}
public void setLevel(int level) {
m_level = Channel.getLevel(level);
}
public void setStatus(int status) {
m_status = status;
}
public String getName() {
return m_name;
}
public int compareTo(Object o2) {
User u2 = ((User)o2);
if (m_level > u2.m_level)
return -1;
if (m_level < u2.m_level)
return 1;
if (m_status < u2.m_status)
return -1;
if (m_status > u2.m_status)
return 1;
String s2 = u2.m_name;
return m_name.compareToIgnoreCase(s2);
}
public String getPrefix() {
String[] prefixes = { "", "+", "%", "@", "&", "~" };
return prefixes[m_level];
}
public void addBattle(int id) {
m_battles.add(id);
}
public void removeBattle(int id) {
m_battles.remove(id);
}
@Override
public boolean equals(Object o2) {
return ((User)o2).m_name.equals(m_name);
}
@Override
public String toString() {
String colour = "rgb(0, 0, 0)"; // black for now
String style = (m_battles.size() > 0) ? "font-style: italic;" : "";
return "<html><font style='color: "
+ colour + style + "'>" + getPrefix()
+ m_name + "</font></html>";
}
}
//private ChatPane m_chat;
private ChallengeNotifier m_notifier;
private String m_name;
private ServerLink m_link;
private Map<Integer, Channel> m_channels = new HashMap<Integer, Channel>();
public Channel getChannel(String name) {
for (Channel i : m_channels.values()) {
if (name.equals(i.getName())) {
return i;
}
}
return null;
}
public void addChannel(Channel channel) {
m_channels.put(channel.m_id, channel);
ChatPane c = new ChatPane(channel, this, m_name);
c.getChat().addMouseListener(new MouseAdapter() {
@Override
public void mouseReleased(MouseEvent e) {
m_notifier.processClick(e);
}
});
channel.setChatPane(c);
if (channel.getType() == Channel.TYPE_BATTLE)
return;
String name = channel.getName();
c.addMessage(null, "<b>The topic for #"
+ name + " is: "
+ channel.getTopic()
+ "</b>", false);
tabChats.add("#" + name, c);
}
public Channel getChannel(int id) {
return m_channels.get(id);
}
public void handleJoinPart(int id, String user, boolean join) {
Channel channel = m_channels.get(id);
if (channel != null) {
if (join) {
channel.addUser(user, 0);
} else {
channel.removeUser(user);
}
}
if (channel.getChatPane() == tabChats.getSelectedComponent()) {
listUsers.setModel(new UserListModel(channel.getModel().getList()));
}
}
/** Creates new form LobbyWindow */
public LobbyWindow(ServerLink link, String userName) {
initComponents();
m_link = link;
m_link.setLobbyWindow(this);
m_name = userName;
m_notifier = new ChallengeNotifier(this);
setGlassPane(m_notifier);
tabChats.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
Component comp = tabChats.getSelectedComponent();
if (!(comp instanceof ChatPane)) return;
ChatPane c = (ChatPane)comp;
listUsers.setModel(c.getChannel().getModel());
}
});
setTitle("Shoddy Battle - " + userName);
}
public ServerLink getLink() {
return m_link;
}
/**
* Returns the bounds of the main chat pane
*/
public Rectangle getChatBounds() {
ChatPane chat = (ChatPane)tabChats.getComponentAt(0);
Point p = chat.getPane().getLocation();
Point p2 = chat.getLocation();
Point p3 = tabChats.getLocation();
JScrollPane pane = chat.getPane();
int w = pane.getWidth() - pane.getVerticalScrollBar().getWidth();
int h = pane.getHeight();
int x = p.x + p2.x + p3.x;
int y = p.y + p2.y + p3.y;
return new Rectangle(x, y, w, h);
}
public static void viewWebPage(URL page) {
try {
throw new Exception();
} catch (Exception e) {
System.out.println(page);
}
}
public void addChallenge(String name, boolean incoming, int gen, int n) {
m_notifier.addChallenge(name, incoming, gen, n);
}
public ChallengeMediator getChallengeMediator(String name) {
return m_notifier.getMediator(name);
}
public void cancelChallenge(String name) {
m_notifier.removeChallenge(name);
}
public void cancelChallenge(int id) {
m_notifier.removeChallenge(id);
}
public ChatPane getChat() {
return (ChatPane)tabChats.getSelectedComponent();
}
public String getUserName() {
return m_name;
}
public void handleUpdateStatus(int id, String user, int flags) {
Channel channel = m_channels.get(id);
if (channel != null) {
channel.updateUser(user, flags);
if (channel.getChatPane() == tabChats.getSelectedComponent()) {
updateUsers(channel);
}
}
}
private void updateUsers(Channel channel) {
UserListModel model = channel.getModel();
model.sort();
listUsers.setModel(new UserListModel(model.getList()));
}
public void showChannelMessage(Channel channel,
String user, String message, boolean encode) {
if (channel.getType() == Channel.TYPE_ORDINARY) {
channel.getChatPane().addMessage(user, message, encode);
} else {
// battle chat message
BattleWindow wnd = m_link.getBattle(channel.getId());
wnd.addMessage(user, message, encode);
}
}
public void handleChannelMessage(int id, String user, String message) {
Channel channel = m_channels.get(id);
if (channel != null) {
String prefix = channel.getUser(user).getPrefix();
showChannelMessage(channel, prefix + user, message, true);
}
}
public void closeTab(int index) {
tabChats.removeTabAt(index);
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
btnChallenge = new javax.swing.JButton();
jScrollPane1 = new javax.swing.JScrollPane();
listUsers = new javax.swing.JList();
tabChats = new javax.swing.JTabbedPane();
setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
setLocationByPlatform(true);
addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent evt) {
formWindowClosing(evt);
}
});
btnChallenge.setText("Challenge");
btnChallenge.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnChallengeActionPerformed(evt);
}
});
jScrollPane1.setViewportView(listUsers);
org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
.addContainerGap()
- .add(tabChats, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 476, Short.MAX_VALUE)
+ .add(tabChats, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 475, Short.MAX_VALUE)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
- .add(btnChallenge, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 107, Short.MAX_VALUE)
- .add(jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 107, Short.MAX_VALUE))
+ .add(jScrollPane1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 108, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
+ .add(btnChallenge, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 110, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
.addContainerGap()
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
.add(layout.createSequentialGroup()
.add(jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 343, Short.MAX_VALUE)
.add(9, 9, 9)
.add(btnChallenge))
- .add(org.jdesktop.layout.GroupLayout.LEADING, tabChats, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 375, Short.MAX_VALUE))
+ .add(org.jdesktop.layout.GroupLayout.LEADING, tabChats, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 381, Short.MAX_VALUE))
.addContainerGap())
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
int response = JOptionPane.showConfirmDialog(this, "Are you sure you " +
"want to leave this server?", "Disconnecting...", JOptionPane.YES_NO_OPTION);
if (response == JOptionPane.YES_OPTION) {
this.dispose();
m_link.close();
new WelcomeWindow().setVisible(true);
}
}//GEN-LAST:event_formWindowClosing
private void btnChallengeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnChallengeActionPerformed
User user = (User)listUsers.getSelectedValue();
if (user == null) return;
String opponent = user.getName();
if (opponent.equals(m_name) && false) {
// todo: internationalisation
JOptionPane.showMessageDialog(this, "You cannot challenge yourself.");
} else {
int index = tabChats.getTabCount();
UserPanel panel = new UserPanel(opponent, m_link, index);
tabChats.add(opponent, panel);
tabChats.setSelectedComponent(panel);
}
}//GEN-LAST:event_btnChallengeActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
LobbyWindow lw = new LobbyWindow(null, "Ben");
lw.setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton btnChallenge;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JList listUsers;
private javax.swing.JTabbedPane tabChats;
// End of variables declaration//GEN-END:variables
}
| false | true | private void initComponents() {
btnChallenge = new javax.swing.JButton();
jScrollPane1 = new javax.swing.JScrollPane();
listUsers = new javax.swing.JList();
tabChats = new javax.swing.JTabbedPane();
setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
setLocationByPlatform(true);
addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent evt) {
formWindowClosing(evt);
}
});
btnChallenge.setText("Challenge");
btnChallenge.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnChallengeActionPerformed(evt);
}
});
jScrollPane1.setViewportView(listUsers);
org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
.addContainerGap()
.add(tabChats, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 476, Short.MAX_VALUE)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(btnChallenge, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 107, Short.MAX_VALUE)
.add(jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 107, Short.MAX_VALUE))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
.addContainerGap()
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
.add(layout.createSequentialGroup()
.add(jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 343, Short.MAX_VALUE)
.add(9, 9, 9)
.add(btnChallenge))
.add(org.jdesktop.layout.GroupLayout.LEADING, tabChats, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 375, Short.MAX_VALUE))
.addContainerGap())
);
pack();
}// </editor-fold>//GEN-END:initComponents
| private void initComponents() {
btnChallenge = new javax.swing.JButton();
jScrollPane1 = new javax.swing.JScrollPane();
listUsers = new javax.swing.JList();
tabChats = new javax.swing.JTabbedPane();
setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
setLocationByPlatform(true);
addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent evt) {
formWindowClosing(evt);
}
});
btnChallenge.setText("Challenge");
btnChallenge.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnChallengeActionPerformed(evt);
}
});
jScrollPane1.setViewportView(listUsers);
org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
.addContainerGap()
.add(tabChats, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 475, Short.MAX_VALUE)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(jScrollPane1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 108, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.add(btnChallenge, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 110, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
.addContainerGap()
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
.add(layout.createSequentialGroup()
.add(jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 343, Short.MAX_VALUE)
.add(9, 9, 9)
.add(btnChallenge))
.add(org.jdesktop.layout.GroupLayout.LEADING, tabChats, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 381, Short.MAX_VALUE))
.addContainerGap())
);
pack();
}// </editor-fold>//GEN-END:initComponents
|
diff --git a/fathomcloud-compute/src/main/java/io/fathom/cloud/compute/scheduler/ShellCommand.java b/fathomcloud-compute/src/main/java/io/fathom/cloud/compute/scheduler/ShellCommand.java
index 920061a..fc1b271 100644
--- a/fathomcloud-compute/src/main/java/io/fathom/cloud/compute/scheduler/ShellCommand.java
+++ b/fathomcloud-compute/src/main/java/io/fathom/cloud/compute/scheduler/ShellCommand.java
@@ -1,74 +1,74 @@
package io.fathom.cloud.compute.scheduler;
import io.fathom.cloud.ssh.SshConfig;
import java.io.File;
import java.util.List;
import com.google.common.base.Joiner;
import com.google.common.collect.Lists;
public class ShellCommand {
final List<String> args = Lists.newArrayList();
ShellCommand(String[] args) {
for (String arg : args) {
this.args.add(arg);
}
}
public static ShellCommand create(String... args) {
return new ShellCommand(args);
}
public void arg(File file) {
argQuoted(file.getAbsolutePath());
}
public void literal(String literal) {
args.add(literal);
}
public void argQuoted(String s) {
StringBuilder escaped = new StringBuilder();
escaped.append('"');
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if ('a' <= c && c <= 'z') {
} else if ('A' <= c && c <= 'Z') {
- } else if ('0' <= c && c <= '0') {
+ } else if ('0' <= c && c <= '9') {
} else {
switch (c) {
case '-':
case '_':
case '/':
case ':':
case '.':
break;
default:
throw new IllegalArgumentException("Don't know how to escape character: " + c);
}
}
escaped.append(c);
}
escaped.append('"');
args.add(escaped.toString());
}
public void useSudo() {
args.add(0, "sudo");
}
public SshCommand withSsh(SshConfig sshConfig) {
String sshCommand = Joiner.on(' ').join(args);
return new SshCommand(sshConfig, sshCommand);
}
}
| true | true | public void argQuoted(String s) {
StringBuilder escaped = new StringBuilder();
escaped.append('"');
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if ('a' <= c && c <= 'z') {
} else if ('A' <= c && c <= 'Z') {
} else if ('0' <= c && c <= '0') {
} else {
switch (c) {
case '-':
case '_':
case '/':
case ':':
case '.':
break;
default:
throw new IllegalArgumentException("Don't know how to escape character: " + c);
}
}
escaped.append(c);
}
escaped.append('"');
args.add(escaped.toString());
}
| public void argQuoted(String s) {
StringBuilder escaped = new StringBuilder();
escaped.append('"');
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if ('a' <= c && c <= 'z') {
} else if ('A' <= c && c <= 'Z') {
} else if ('0' <= c && c <= '9') {
} else {
switch (c) {
case '-':
case '_':
case '/':
case ':':
case '.':
break;
default:
throw new IllegalArgumentException("Don't know how to escape character: " + c);
}
}
escaped.append(c);
}
escaped.append('"');
args.add(escaped.toString());
}
|
diff --git a/framework/core/src/main/java/fr/liglab/adele/cilia/model/impl/BindingImpl.java b/framework/core/src/main/java/fr/liglab/adele/cilia/model/impl/BindingImpl.java
index 332b9472..4dd45443 100644
--- a/framework/core/src/main/java/fr/liglab/adele/cilia/model/impl/BindingImpl.java
+++ b/framework/core/src/main/java/fr/liglab/adele/cilia/model/impl/BindingImpl.java
@@ -1,224 +1,227 @@
/*
* Copyright Adele Team LIG
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package fr.liglab.adele.cilia.model.impl;
import java.util.Dictionary;
import fr.liglab.adele.cilia.model.Binding;
import fr.liglab.adele.cilia.model.Chain;
import fr.liglab.adele.cilia.model.Component;
import fr.liglab.adele.cilia.model.MediatorComponent;
import fr.liglab.adele.cilia.model.Port;
/**
* This class represent the relation between two mediators in the Cilia Model.
*
* @author <a href="mailto:[email protected]">Cilia Project Team</a>
*
*/
public class BindingImpl extends ComponentImpl implements Binding{
/**
* Reference to the port of the source mediator where this bind is done.
*/
private Port targetPort = null;
/**
* Reference to the port of the target mediator where this bind is done.
*/
private Port sourcePort = null;
private volatile static long bindingIds = 0;
private volatile SenderImpl sender;
private volatile CollectorImpl collector;
private final Object lockObject = new Object();
/**
* Constructor.
*/
public BindingImpl() {
this(null, null);
}
/**
*
* @param id BindingImpl identificator.
* @param type BindingImpl type.
* @param classname //Not used.
* @param properties Properties that will be mapped to sender/collector properties.
*/
public BindingImpl(String type,
Dictionary properties) {
super(new Long(bindingIds++).toString(), type, null, properties);
}
/**
* Get the parent chain.
* @return the parent chain.
*/
public Chain getChain() {
return getSourceMediator().getChain();
}
/**
* Set the source mediator model.
* @param source the mediator model.
*/
public void setSourcePort(Port source) {
MediatorComponentImpl med;
synchronized (lockObject) {
this.sourcePort = source;
med = (MediatorComponentImpl)this.sourcePort.getMediator();
}
med.addOutBinding(this);
}
/**
* Get the source mediator port in this binding.
* @return the source mediator port.
*/
public Port getSourcePort() {
synchronized (lockObject) {
return this.sourcePort;
}
}
/**
* Set the target mediator model.
* @param target
*/
public void setTargetPort(Port target) {
MediatorComponentImpl med;
synchronized (lockObject) {
this.targetPort = target;
med = (MediatorComponentImpl)this.targetPort.getMediator();
}
med.addInBinding(this);
}
/**
* Get the target mediator port asociated to this binding.
* @return the target mediator port.
*/
public Port getTargetPort() {
synchronized (lockObject) {
return this.targetPort;
}
}
/**
* Get the source mediator model.
* @return the source mediator model.
*/
public MediatorComponent getSourceMediator() {
MediatorComponent med = null;
synchronized (lockObject) {
if (sourcePort != null) {
med = sourcePort.getMediator();
}
}
return med;
}
/**
* Get the target mediator model.
* @return the target mediator model.
*/
public MediatorComponent getTargetMediator() {
MediatorComponent med = null;
synchronized (lockObject) {
if (targetPort != null) {
med = targetPort.getMediator();
}
}
return med;
}
/**
* Add a sender to the current mediator representation model.
* @param sender Sender representation model to add to the current mediator.
* @return true if was successfully added, false if not.
*/
public boolean addSender(SenderImpl sender) {
boolean result = false;
try {
synchronized (lockObject) {
this.sender = sender;
result = true;
}
}catch (Exception ex){
result = false;
}
return result;
}
/**
* Get the sender added to tue current mediator wich contains the given identificator.
* @param senderId sender identificator.
* @return the sender which contains the identificator, null if there is any sender with the given identificator.
*/
public SenderImpl getSender() {
synchronized (lockObject) {
return sender;
}
}
/**
* Add a collector to the mediator representation model.
* @param collector Collector model to add.
* @return true if collector was successfully added, false if not.
*/
public boolean addCollector(CollectorImpl collector) {
boolean result = false;
try {
synchronized (lockObject) {
this.collector = collector;
result = true;
}
}catch (Exception ex){
result = false;
}
return result;
}
/**
* Get the collector representation model which has the given identificator.
* @param collectorId collector identificator.
* @return the reference collector, null if any collector correspond to that identificator.
*/
public CollectorImpl getCollector() {
synchronized (lockObject) {
return collector;
}
}
public String toString(){
- StringBuffer toShow = new StringBuffer();
+ StringBuffer toShow = new StringBuffer("{");
if (getSourcePort() != null) {
- toShow.append("FROM ");
+ toShow.append("\"from\":\"");
toShow.append(getSourceMediator().getId());
toShow.append(":");
toShow.append(getSourcePort().getName());
+ toShow.append("\", ");
}
- if (getSourcePort() != null) {
- toShow.append(" TO ");
+ if (getTargetPort() != null) {
+ toShow.append("\"to\":\"");
toShow.append(getTargetMediator().getId());
toShow.append(":");
toShow.append(getTargetPort().getName());
+ toShow.append("\"");
}
+ toShow.append("}");
return toShow.toString();
}
}
| false | true | public String toString(){
StringBuffer toShow = new StringBuffer();
if (getSourcePort() != null) {
toShow.append("FROM ");
toShow.append(getSourceMediator().getId());
toShow.append(":");
toShow.append(getSourcePort().getName());
}
if (getSourcePort() != null) {
toShow.append(" TO ");
toShow.append(getTargetMediator().getId());
toShow.append(":");
toShow.append(getTargetPort().getName());
}
return toShow.toString();
}
| public String toString(){
StringBuffer toShow = new StringBuffer("{");
if (getSourcePort() != null) {
toShow.append("\"from\":\"");
toShow.append(getSourceMediator().getId());
toShow.append(":");
toShow.append(getSourcePort().getName());
toShow.append("\", ");
}
if (getTargetPort() != null) {
toShow.append("\"to\":\"");
toShow.append(getTargetMediator().getId());
toShow.append(":");
toShow.append(getTargetPort().getName());
toShow.append("\"");
}
toShow.append("}");
return toShow.toString();
}
|
diff --git a/modules/extension/xsd/xsd-gml3/src/test/java/org/geotools/gml3/GML3EncodingTest.java b/modules/extension/xsd/xsd-gml3/src/test/java/org/geotools/gml3/GML3EncodingTest.java
index cf922e929..ce77a37e2 100644
--- a/modules/extension/xsd/xsd-gml3/src/test/java/org/geotools/gml3/GML3EncodingTest.java
+++ b/modules/extension/xsd/xsd-gml3/src/test/java/org/geotools/gml3/GML3EncodingTest.java
@@ -1,196 +1,196 @@
/*
* GeoTools - The Open Source Java GIS Toolkit
* http://geotools.org
*
* (C) 2002-2008, Open Source Geospatial Foundation (OSGeo)
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation;
* version 2.1 of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*/
package org.geotools.gml3;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import junit.framework.TestCase;
import org.apache.xerces.parsers.SAXParser;
import org.eclipse.xsd.XSDSchema;
import org.geotools.data.simple.SimpleFeatureCollection;
import org.geotools.gml3.bindings.GML3MockData;
import org.geotools.gml3.bindings.TEST;
import org.geotools.gml3.bindings.TestConfiguration;
import org.geotools.xml.Encoder;
import org.geotools.xml.Parser;
import org.opengis.feature.simple.SimpleFeature;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.xml.sax.helpers.DefaultHandler;
/**
*
*
* @source $URL$
*/
public class GML3EncodingTest extends TestCase {
boolean isOffline() throws Exception {
//this test will only run if network is available
URL url = new URL("http://schemas.opengis.net");
try {
URLConnection conn = url.openConnection();
conn.setConnectTimeout(2000);
conn.getInputStream().read();
} catch (Exception e) {
return true;
}
return false;
}
public void testWithConfiguration() throws Exception {
if (isOffline()) {
return;
}
TestConfiguration configuration = new TestConfiguration();
//first parse in test data
Parser parser = new Parser(configuration);
SimpleFeatureCollection fc = (SimpleFeatureCollection) parser.parse(TestConfiguration.class
.getResourceAsStream("test.xml"));
assertNotNull(fc);
XSDSchema schema = TEST.getInstance().getSchema();
assertNotNull(schema);
Encoder encoder = new Encoder(configuration, schema);
ByteArrayOutputStream output = new ByteArrayOutputStream();
encoder.write(fc, TEST.TestFeatureCollection, output);
SAXParser saxParser = new SAXParser();
saxParser.setFeature("http://xml.org/sax/features/validation", true);
saxParser.setFeature("http://apache.org/xml/features/validation/schema", true);
saxParser.setFeature("http://apache.org/xml/features/validation/schema-full-checking", true);
saxParser.setProperty("http://apache.org/xml/properties/schema/external-noNamespaceSchemaLocation",
TEST.NAMESPACE);
saxParser.setProperty("http://apache.org/xml/properties/schema/external-schemaLocation",
TEST.NAMESPACE + " " + configuration.getSchemaFileURL());
final ArrayList errors = new ArrayList();
DefaultHandler handler = new DefaultHandler() {
public void error(SAXParseException e)
throws SAXException {
System.out.println(e.getMessage());
errors.add(e);
}
public void fatalError(SAXParseException e)
throws SAXException {
System.out.println(e.getMessage());
errors.add(e);
}
};
saxParser.setErrorHandler(handler);
saxParser.parse(new InputSource(new ByteArrayInputStream(output.toByteArray())));
assertTrue(errors.isEmpty());
}
public void testWithApplicationSchemaConfiguration()
throws Exception {
if (isOffline()) {
return;
}
- String schemaLocation = new File(TestConfiguration.class.getResource("test.xsd").getFile())
- .getAbsolutePath();
+ // The schema location needs to be a well formed URI/URL, a file path is not sufficient.
+ String schemaLocation = TestConfiguration.class.getResource("test.xsd").toString();
ApplicationSchemaConfiguration configuration = new ApplicationSchemaConfiguration(TEST.NAMESPACE,
schemaLocation);
//first parse in test data
Parser parser = new Parser(configuration);
SimpleFeatureCollection fc = (SimpleFeatureCollection) parser.parse(TestConfiguration.class
.getResourceAsStream("test.xml"));
assertNotNull(fc);
XSDSchema schema = TEST.getInstance().getSchema();
assertNotNull(schema);
Encoder encoder = new Encoder(configuration, schema);
ByteArrayOutputStream output = new ByteArrayOutputStream();
encoder.write(fc, TEST.TestFeatureCollection, output);
SAXParser saxParser = new SAXParser();
saxParser.setFeature("http://xml.org/sax/features/validation", true);
saxParser.setFeature("http://apache.org/xml/features/validation/schema", true);
saxParser.setFeature("http://apache.org/xml/features/validation/schema-full-checking", true);
saxParser.setProperty("http://apache.org/xml/properties/schema/external-noNamespaceSchemaLocation",
TEST.NAMESPACE);
saxParser.setProperty("http://apache.org/xml/properties/schema/external-schemaLocation",
TEST.NAMESPACE + " " + configuration.getSchemaFileURL());
final ArrayList errors = new ArrayList();
DefaultHandler handler = new DefaultHandler() {
public void error(SAXParseException e)
throws SAXException {
System.out.println(e.getMessage());
errors.add(e);
}
public void fatalError(SAXParseException e)
throws SAXException {
System.out.println(e.getMessage());
errors.add(e);
}
};
saxParser.setErrorHandler(handler);
saxParser.parse(new InputSource(new ByteArrayInputStream(output.toByteArray())));
assertTrue(errors.isEmpty());
}
public void testEncodeFeatureWithBounds() throws Exception {
SimpleFeature feature = GML3MockData.feature();
TestConfiguration configuration = new TestConfiguration();
//configuration.getProperties().add( org.geotools.gml2.GMLConfiguration.NO_FEATURE_BOUNDS );
Encoder encoder = new Encoder( configuration );
Document dom = encoder.encodeAsDOM(feature, TEST.TestFeature );
assertEquals( 1, dom.getElementsByTagName("gml:boundedBy").getLength());
}
public void testEncodeFeatureWithNoBounds() throws Exception {
SimpleFeature feature = GML3MockData.feature();
TestConfiguration configuration = new TestConfiguration();
configuration.getProperties().add( org.geotools.gml2.GMLConfiguration.NO_FEATURE_BOUNDS );
Encoder encoder = new Encoder( configuration );
Document dom = encoder.encodeAsDOM(feature, TEST.TestFeature );
assertEquals( 0, dom.getElementsByTagName("gml:boundedBy").getLength());
}
}
| true | true | public void testWithApplicationSchemaConfiguration()
throws Exception {
if (isOffline()) {
return;
}
String schemaLocation = new File(TestConfiguration.class.getResource("test.xsd").getFile())
.getAbsolutePath();
ApplicationSchemaConfiguration configuration = new ApplicationSchemaConfiguration(TEST.NAMESPACE,
schemaLocation);
//first parse in test data
Parser parser = new Parser(configuration);
SimpleFeatureCollection fc = (SimpleFeatureCollection) parser.parse(TestConfiguration.class
.getResourceAsStream("test.xml"));
assertNotNull(fc);
XSDSchema schema = TEST.getInstance().getSchema();
assertNotNull(schema);
Encoder encoder = new Encoder(configuration, schema);
ByteArrayOutputStream output = new ByteArrayOutputStream();
encoder.write(fc, TEST.TestFeatureCollection, output);
SAXParser saxParser = new SAXParser();
saxParser.setFeature("http://xml.org/sax/features/validation", true);
saxParser.setFeature("http://apache.org/xml/features/validation/schema", true);
saxParser.setFeature("http://apache.org/xml/features/validation/schema-full-checking", true);
saxParser.setProperty("http://apache.org/xml/properties/schema/external-noNamespaceSchemaLocation",
TEST.NAMESPACE);
saxParser.setProperty("http://apache.org/xml/properties/schema/external-schemaLocation",
TEST.NAMESPACE + " " + configuration.getSchemaFileURL());
final ArrayList errors = new ArrayList();
DefaultHandler handler = new DefaultHandler() {
public void error(SAXParseException e)
throws SAXException {
System.out.println(e.getMessage());
errors.add(e);
}
public void fatalError(SAXParseException e)
throws SAXException {
System.out.println(e.getMessage());
errors.add(e);
}
};
saxParser.setErrorHandler(handler);
saxParser.parse(new InputSource(new ByteArrayInputStream(output.toByteArray())));
assertTrue(errors.isEmpty());
}
| public void testWithApplicationSchemaConfiguration()
throws Exception {
if (isOffline()) {
return;
}
// The schema location needs to be a well formed URI/URL, a file path is not sufficient.
String schemaLocation = TestConfiguration.class.getResource("test.xsd").toString();
ApplicationSchemaConfiguration configuration = new ApplicationSchemaConfiguration(TEST.NAMESPACE,
schemaLocation);
//first parse in test data
Parser parser = new Parser(configuration);
SimpleFeatureCollection fc = (SimpleFeatureCollection) parser.parse(TestConfiguration.class
.getResourceAsStream("test.xml"));
assertNotNull(fc);
XSDSchema schema = TEST.getInstance().getSchema();
assertNotNull(schema);
Encoder encoder = new Encoder(configuration, schema);
ByteArrayOutputStream output = new ByteArrayOutputStream();
encoder.write(fc, TEST.TestFeatureCollection, output);
SAXParser saxParser = new SAXParser();
saxParser.setFeature("http://xml.org/sax/features/validation", true);
saxParser.setFeature("http://apache.org/xml/features/validation/schema", true);
saxParser.setFeature("http://apache.org/xml/features/validation/schema-full-checking", true);
saxParser.setProperty("http://apache.org/xml/properties/schema/external-noNamespaceSchemaLocation",
TEST.NAMESPACE);
saxParser.setProperty("http://apache.org/xml/properties/schema/external-schemaLocation",
TEST.NAMESPACE + " " + configuration.getSchemaFileURL());
final ArrayList errors = new ArrayList();
DefaultHandler handler = new DefaultHandler() {
public void error(SAXParseException e)
throws SAXException {
System.out.println(e.getMessage());
errors.add(e);
}
public void fatalError(SAXParseException e)
throws SAXException {
System.out.println(e.getMessage());
errors.add(e);
}
};
saxParser.setErrorHandler(handler);
saxParser.parse(new InputSource(new ByteArrayInputStream(output.toByteArray())));
assertTrue(errors.isEmpty());
}
|
diff --git a/demo-wingset/src/java/wingset/XCalendarExample.java b/demo-wingset/src/java/wingset/XCalendarExample.java
index e7e8e32..e62c31a 100644
--- a/demo-wingset/src/java/wingset/XCalendarExample.java
+++ b/demo-wingset/src/java/wingset/XCalendarExample.java
@@ -1,128 +1,127 @@
package wingset;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import javax.swing.*;
import org.wings.*;
import org.wings.text.SDateFormatter;
import org.wingx.XCalendar;
public class XCalendarExample extends WingSetPane {
protected SComponent createControls() {
return null;
}
public SComponent createExample() {
SGridLayout layout = new SGridLayout(3);
layout.setHgap(15);
SPanel panel = new SPanel(layout);
//
// Regular nullable calendar
final DateFormat nullableDateFormat = new NullableDateFormatter();
panel.add(new SLabel("Calendar: ", SConstants.RIGHT_ALIGN));
final XCalendar nullablXCalendar = new XCalendar(new SDateFormatter(nullableDateFormat));
- nullablXCalendar.setPreferredSize(SDimension.FULLWIDTH);
nullablXCalendar.setNullable(true);
nullablXCalendar.setDate(null);
panel.add(nullablXCalendar);
final SLabel valueLabel1 = new SLabel("< press submit >");
panel.add(valueLabel1);
//
// Date spinner example
Calendar calendar = new GregorianCalendar();
Date initDate = calendar.getTime();
calendar.add(Calendar.YEAR, -50);
Date earliestDate = calendar.getTime();
calendar.add(Calendar.YEAR, 100);
Date latestDate = calendar.getTime();
final SSpinner spinner = new SSpinner(new SpinnerDateModel(initDate, earliestDate, latestDate, Calendar.MONTH));
final CalendarEditor calendarEditor = new CalendarEditor(spinner, new SDateFormatter(DateFormat.getDateInstance()));
spinner.setEditor(calendarEditor);
panel.add(new SLabel("Spinner: ", SConstants.RIGHT_ALIGN));
panel.add(spinner);
final SLabel valueLabel2 = new SLabel("< press submit >");
panel.add(valueLabel2);
// For debugging purposes. Maybe ommit those labels
final SButton button = new SButton("submit input");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
valueLabel1.setText(""+nullablXCalendar.getDate());
valueLabel2.setText(""+calendarEditor.getCalendar().getDate());
}
});
panel.add(new SLabel());
panel.add(button);
return panel;
}
public static class CalendarEditor extends SSpinner.DefaultEditor {
private XCalendar calendar = null;
public CalendarEditor(SSpinner spinner, SDateFormatter formatter) {
super(spinner);
removeAll();
calendar = new XCalendar(formatter);
calendar.getFormattedTextField().setColumns(15);
add(calendar);
}
public XCalendar getCalendar() {
return calendar;
}
public SFormattedTextField getTextField() {
return calendar.getFormattedTextField();
}
}
/**
* A simple date formatter that parses and allows empty strings as <code>null</code>.
*/
private static class NullableDateFormatter extends SimpleDateFormat {
public NullableDateFormatter() {
super("dd.MM.yyyy");
}
public Object parseObject(String source) throws ParseException {
if (source == null || source.trim().length() == 0) {
return null;
}
return super.parseObject(source);
}
public Date parse(String text, ParsePosition pos) {
if (text == null || text.trim().length() == 0) {
return null;
}
return super.parse(text, pos);
}
}
}
| true | true | public SComponent createExample() {
SGridLayout layout = new SGridLayout(3);
layout.setHgap(15);
SPanel panel = new SPanel(layout);
//
// Regular nullable calendar
final DateFormat nullableDateFormat = new NullableDateFormatter();
panel.add(new SLabel("Calendar: ", SConstants.RIGHT_ALIGN));
final XCalendar nullablXCalendar = new XCalendar(new SDateFormatter(nullableDateFormat));
nullablXCalendar.setPreferredSize(SDimension.FULLWIDTH);
nullablXCalendar.setNullable(true);
nullablXCalendar.setDate(null);
panel.add(nullablXCalendar);
final SLabel valueLabel1 = new SLabel("< press submit >");
panel.add(valueLabel1);
//
// Date spinner example
Calendar calendar = new GregorianCalendar();
Date initDate = calendar.getTime();
calendar.add(Calendar.YEAR, -50);
Date earliestDate = calendar.getTime();
calendar.add(Calendar.YEAR, 100);
Date latestDate = calendar.getTime();
final SSpinner spinner = new SSpinner(new SpinnerDateModel(initDate, earliestDate, latestDate, Calendar.MONTH));
final CalendarEditor calendarEditor = new CalendarEditor(spinner, new SDateFormatter(DateFormat.getDateInstance()));
spinner.setEditor(calendarEditor);
panel.add(new SLabel("Spinner: ", SConstants.RIGHT_ALIGN));
panel.add(spinner);
final SLabel valueLabel2 = new SLabel("< press submit >");
panel.add(valueLabel2);
// For debugging purposes. Maybe ommit those labels
final SButton button = new SButton("submit input");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
valueLabel1.setText(""+nullablXCalendar.getDate());
valueLabel2.setText(""+calendarEditor.getCalendar().getDate());
}
});
panel.add(new SLabel());
panel.add(button);
return panel;
}
| public SComponent createExample() {
SGridLayout layout = new SGridLayout(3);
layout.setHgap(15);
SPanel panel = new SPanel(layout);
//
// Regular nullable calendar
final DateFormat nullableDateFormat = new NullableDateFormatter();
panel.add(new SLabel("Calendar: ", SConstants.RIGHT_ALIGN));
final XCalendar nullablXCalendar = new XCalendar(new SDateFormatter(nullableDateFormat));
nullablXCalendar.setNullable(true);
nullablXCalendar.setDate(null);
panel.add(nullablXCalendar);
final SLabel valueLabel1 = new SLabel("< press submit >");
panel.add(valueLabel1);
//
// Date spinner example
Calendar calendar = new GregorianCalendar();
Date initDate = calendar.getTime();
calendar.add(Calendar.YEAR, -50);
Date earliestDate = calendar.getTime();
calendar.add(Calendar.YEAR, 100);
Date latestDate = calendar.getTime();
final SSpinner spinner = new SSpinner(new SpinnerDateModel(initDate, earliestDate, latestDate, Calendar.MONTH));
final CalendarEditor calendarEditor = new CalendarEditor(spinner, new SDateFormatter(DateFormat.getDateInstance()));
spinner.setEditor(calendarEditor);
panel.add(new SLabel("Spinner: ", SConstants.RIGHT_ALIGN));
panel.add(spinner);
final SLabel valueLabel2 = new SLabel("< press submit >");
panel.add(valueLabel2);
// For debugging purposes. Maybe ommit those labels
final SButton button = new SButton("submit input");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
valueLabel1.setText(""+nullablXCalendar.getDate());
valueLabel2.setText(""+calendarEditor.getCalendar().getDate());
}
});
panel.add(new SLabel());
panel.add(button);
return panel;
}
|
diff --git a/HotelDatabase/src/DBConn.java b/HotelDatabase/src/DBConn.java
index 5a7e5e6..03bf33c 100644
--- a/HotelDatabase/src/DBConn.java
+++ b/HotelDatabase/src/DBConn.java
@@ -1,17 +1,17 @@
import java.sql.*;
public class DBConn {
- public static Connection main(String args[]) throws Exception
+ public static Connection getConnection() throws Exception
{
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost/test";
String username = "root";
String pwd = "";
Connection conn = DriverManager.getConnection(url, username, pwd);
return conn;
}
}
| true | true | public static Connection main(String args[]) throws Exception
{
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost/test";
String username = "root";
String pwd = "";
Connection conn = DriverManager.getConnection(url, username, pwd);
return conn;
}
| public static Connection getConnection() throws Exception
{
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost/test";
String username = "root";
String pwd = "";
Connection conn = DriverManager.getConnection(url, username, pwd);
return conn;
}
|
diff --git a/src/de/raptor2101/GalDroid/WebGallery/GalleryImageView.java b/src/de/raptor2101/GalDroid/WebGallery/GalleryImageView.java
index 19f393b..6c48850 100644
--- a/src/de/raptor2101/GalDroid/WebGallery/GalleryImageView.java
+++ b/src/de/raptor2101/GalDroid/WebGallery/GalleryImageView.java
@@ -1,202 +1,203 @@
/*
* GalDroid - a webgallery frontend for android
* Copyright (C) 2011 Raptor 2101 [[email protected]]
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.raptor2101.GalDroid.WebGallery;
import java.lang.ref.WeakReference;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.graphics.Typeface;
import android.os.AsyncTask.Status;
import android.util.Log;
import android.view.Gravity;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import de.raptor2101.GalDroid.WebGallery.Interfaces.GalleryObject;
import de.raptor2101.GalDroid.WebGallery.Tasks.ImageLoaderTask;
import de.raptor2101.GalDroid.WebGallery.Tasks.ImageLoaderTaskListener;
public class GalleryImageView extends LinearLayout implements ImageLoaderTaskListener{
private static final String CLASS_TAG = "GalleryImageView";
private final ProgressBar mProgressBar;
private final ImageView mImageView;
private final TextView mTitleTextView;
private final boolean mShowTitle;
private GalleryObject mGalleryObject;
private Bitmap mBitmap;
private ImageLoaderTask mImageLoaderTask;
private WeakReference<ImageLoaderTaskListener> mListener;
public GalleryImageView(Context context, android.view.ViewGroup.LayoutParams layoutParams, boolean showTitle) {
super(context);
mShowTitle = showTitle;
mImageView = CreateImageView(context);
mProgressBar = new ProgressBar(context,null,android.R.attr.progressBarStyleLarge);
mProgressBar.setVisibility(GONE);
this.addView(mProgressBar);
this.setOrientation(VERTICAL);
this.setGravity(Gravity.CENTER_VERTICAL|Gravity.CENTER_HORIZONTAL);
this.setLayoutParams(layoutParams);
this.addView(mImageView);
if(mShowTitle){
mTitleTextView = new TextView(context);
mTitleTextView.setTextSize(16);
mTitleTextView.setGravity(Gravity.CENTER_HORIZONTAL);
mTitleTextView.setTypeface(Typeface.create("Tahoma", Typeface.BOLD));
this.addView(mTitleTextView);
}
else{
mTitleTextView = null;
}
mImageLoaderTask = null;
+ mListener = new WeakReference<ImageLoaderTaskListener>(null);
}
public void setGalleryObject(GalleryObject galleryObject)
{
mGalleryObject = galleryObject;
this.setTitle(galleryObject.getTitle());
}
public GalleryObject getGalleryObject(){
return mGalleryObject;
}
public void setTitle(String title)
{
if(mTitleTextView != null){
mTitleTextView.setText(title);
}
}
private ImageView CreateImageView(Context context) {
ImageView imageView = new ImageView(context);
imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
imageView.setPadding(5, 5, 5, 5);
imageView.setDrawingCacheEnabled(false);
return imageView;
}
public void recylceBitmap(){
if (mBitmap != null) {
Log.d(CLASS_TAG, String.format("Recycle %s",mGalleryObject.getObjectId()));
mImageView.setImageBitmap(null);
mBitmap.recycle();
mBitmap = null;
}
}
public Matrix getImageMatrix(){
return mImageView.getMatrix();
}
public void setImageMatrix(Matrix matrix) {
mImageView.setScaleType(ImageView.ScaleType.MATRIX);
mImageView.setImageMatrix(matrix);
}
public void cancelImageLoaderTask(){
if(mImageLoaderTask != null){
Log.d(CLASS_TAG, String.format("Cancel downloadTask %s",mGalleryObject.getObjectId()));
mImageLoaderTask.cancel(true);
mImageLoaderTask = null;
}
}
public void setImageLoaderTask(ImageLoaderTask downloadTask) {
Log.d(CLASS_TAG, String.format("Reference downloadTask %s",mGalleryObject.getObjectId()));
mImageLoaderTask = downloadTask;
}
public boolean isLoaded() {
return mBitmap != null;
}
public boolean isLoading() {
return mImageLoaderTask != null && mImageLoaderTask.getStatus() != Status.FINISHED;
}
public String getObjectId() {
return mGalleryObject.getObjectId();
}
public void onLoadingStarted(String uniqueId) {
mProgressBar.setVisibility(VISIBLE);
Log.d(CLASS_TAG, String.format("Loading started %s",uniqueId));
ImageLoaderTaskListener listener = mListener.get();
if(listener != null) {
listener.onLoadingStarted(uniqueId);
}
}
public void onLoadingProgress(String uniqueId, int currentValue, int maxValue) {
mProgressBar.setMax(maxValue);
mProgressBar.setProgress(currentValue);
ImageLoaderTaskListener listener = mListener.get();
if(listener != null) {
listener.onLoadingProgress(uniqueId, currentValue, maxValue);
}
}
public void onLoadingCompleted(String uniqueId, Bitmap bitmap) {
mProgressBar.setVisibility(GONE);
mImageView.setImageBitmap(bitmap);
mBitmap = bitmap;
mImageLoaderTask = null;
Log.d(CLASS_TAG, String.format("Loading done %s",uniqueId));
ImageLoaderTaskListener listener = mListener.get();
if(listener != null) {
listener.onLoadingCompleted(uniqueId, bitmap);
}
}
public void onLoadingCancelled(String uniqueId) {
Log.d(CLASS_TAG, String.format("DownloadTask was cancalled %s",uniqueId));
mImageLoaderTask = null;
mProgressBar.setVisibility(GONE);
mBitmap = null;
ImageLoaderTaskListener listener = mListener.get();
if(listener != null) {
listener.onLoadingCancelled(uniqueId);
}
}
public void setListener(ImageLoaderTaskListener listener) {
mListener = new WeakReference<ImageLoaderTaskListener>(listener);
}
}
| true | true | public GalleryImageView(Context context, android.view.ViewGroup.LayoutParams layoutParams, boolean showTitle) {
super(context);
mShowTitle = showTitle;
mImageView = CreateImageView(context);
mProgressBar = new ProgressBar(context,null,android.R.attr.progressBarStyleLarge);
mProgressBar.setVisibility(GONE);
this.addView(mProgressBar);
this.setOrientation(VERTICAL);
this.setGravity(Gravity.CENTER_VERTICAL|Gravity.CENTER_HORIZONTAL);
this.setLayoutParams(layoutParams);
this.addView(mImageView);
if(mShowTitle){
mTitleTextView = new TextView(context);
mTitleTextView.setTextSize(16);
mTitleTextView.setGravity(Gravity.CENTER_HORIZONTAL);
mTitleTextView.setTypeface(Typeface.create("Tahoma", Typeface.BOLD));
this.addView(mTitleTextView);
}
else{
mTitleTextView = null;
}
mImageLoaderTask = null;
}
| public GalleryImageView(Context context, android.view.ViewGroup.LayoutParams layoutParams, boolean showTitle) {
super(context);
mShowTitle = showTitle;
mImageView = CreateImageView(context);
mProgressBar = new ProgressBar(context,null,android.R.attr.progressBarStyleLarge);
mProgressBar.setVisibility(GONE);
this.addView(mProgressBar);
this.setOrientation(VERTICAL);
this.setGravity(Gravity.CENTER_VERTICAL|Gravity.CENTER_HORIZONTAL);
this.setLayoutParams(layoutParams);
this.addView(mImageView);
if(mShowTitle){
mTitleTextView = new TextView(context);
mTitleTextView.setTextSize(16);
mTitleTextView.setGravity(Gravity.CENTER_HORIZONTAL);
mTitleTextView.setTypeface(Typeface.create("Tahoma", Typeface.BOLD));
this.addView(mTitleTextView);
}
else{
mTitleTextView = null;
}
mImageLoaderTask = null;
mListener = new WeakReference<ImageLoaderTaskListener>(null);
}
|
diff --git a/itests/ofertie.ncl/src/test/java/org/opennaas/itests/ofertie/ncl/NCLProvisionerTest.java b/itests/ofertie.ncl/src/test/java/org/opennaas/itests/ofertie/ncl/NCLProvisionerTest.java
index d396a6bbb..ded136f12 100644
--- a/itests/ofertie.ncl/src/test/java/org/opennaas/itests/ofertie/ncl/NCLProvisionerTest.java
+++ b/itests/ofertie.ncl/src/test/java/org/opennaas/itests/ofertie/ncl/NCLProvisionerTest.java
@@ -1,357 +1,357 @@
package org.opennaas.itests.ofertie.ncl;
import static org.openengsb.labs.paxexam.karaf.options.KarafDistributionOption.keepRuntimeFolder;
import static org.opennaas.itests.helpers.OpennaasExamOptions.includeFeatures;
import static org.opennaas.itests.helpers.OpennaasExamOptions.noConsole;
import static org.opennaas.itests.helpers.OpennaasExamOptions.opennaasDistributionConfiguration;
import static org.ops4j.pax.exam.CoreOptions.options;
import static org.ops4j.pax.exam.CoreOptions.systemTimeout;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.inject.Inject;
import junit.framework.Assert;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.opennaas.core.resources.IResource;
import org.opennaas.core.resources.IResourceManager;
import org.opennaas.core.resources.ResourceException;
import org.opennaas.core.resources.descriptor.CapabilityDescriptor;
import org.opennaas.core.resources.descriptor.ResourceDescriptor;
import org.opennaas.core.resources.helpers.ResourceHelper;
import org.opennaas.core.resources.protocol.IProtocolManager;
import org.opennaas.core.resources.protocol.IProtocolSessionManager;
import org.opennaas.core.resources.protocol.ProtocolException;
import org.opennaas.core.resources.protocol.ProtocolSessionContext;
import org.opennaas.extensions.ofertie.ncl.provisioner.api.INCLProvisioner;
import org.opennaas.extensions.ofertie.ncl.provisioner.api.model.Circuit;
import org.opennaas.extensions.ofertie.ncl.provisioner.api.model.FlowRequest;
import org.opennaas.extensions.ofertie.ncl.provisioner.api.model.QoSRequirements;
import org.opennaas.extensions.ofnetwork.capability.ofprovision.IOFProvisioningNetworkCapability;
import org.opennaas.extensions.ofnetwork.capability.ofprovision.OFProvisioningNetworkCapability;
import org.opennaas.extensions.ofnetwork.model.NetOFFlow;
import org.opennaas.extensions.openflowswitch.capability.offorwarding.IOpenflowForwardingCapability;
import org.opennaas.extensions.openflowswitch.capability.offorwarding.OpenflowForwardingCapability;
import org.opennaas.extensions.openflowswitch.driver.floodlight.protocol.FloodlightProtocolSession;
import org.opennaas.extensions.openflowswitch.driver.floodlight.protocol.client.IFloodlightStaticFlowPusherClient;
import org.opennaas.extensions.openflowswitch.driver.floodlight.protocol.client.mockup.FloodlightMockClientFactory;
import org.opennaas.extensions.openflowswitch.model.FloodlightOFFlow;
import org.opennaas.itests.helpers.InitializerTestHelper;
import org.ops4j.pax.exam.Option;
import org.ops4j.pax.exam.junit.Configuration;
import org.ops4j.pax.exam.junit.ExamReactorStrategy;
import org.ops4j.pax.exam.junit.JUnit4TestRunner;
import org.ops4j.pax.exam.spi.reactors.EagerSingleStagedReactorFactory;
import org.ops4j.pax.exam.util.Filter;
import org.osgi.service.blueprint.container.BlueprintContainer;
/**
*
* @author Adrian Rosello (i2cat)
* @author Isart Canyameres Gimenez (i2cat)
*
*/
@RunWith(JUnit4TestRunner.class)
@ExamReactorStrategy(EagerSingleStagedReactorFactory.class)
public class NCLProvisionerTest {
private IResource switch3;
private IResource switch4;
private IResource switch5;
private IResource switch6;
private IResource switch7;
private IResource switch8;
private IResource sdnNetResource;
private FlowRequest flowRequest;
private Map<String, IResource> switches;
private static final String SWITCH_3_NAME = "s3";
private static final String SWITCH_4_NAME = "s4";
private static final String SWITCH_5_NAME = "s5";
private static final String SWITCH_6_NAME = "s6";
private static final String SWITCH_7_NAME = "s7";
private static final String SWITCH_8_NAME = "s8";
private static final String SWITCH_3_ID = "00:00:00:00:00:00:00:03";
private static final String SWITCH_4_ID = "00:00:00:00:00:00:00:04";
private static final String SWITCH_5_ID = "00:00:00:00:00:00:00:05";
private static final String SWITCH_6_ID = "00:00:00:00:00:00:00:06";
private static final String SWITCH_7_ID = "00:00:00:00:00:00:00:07";
private static final String SWITCH_8_ID = "00:00:00:00:00:00:00:08";
private static final String FLOODLIGHT_ACTIONSET_NAME = "floodlight";
private static final String FLOODLIGHT_ACTIONSET_VERSION = "0.90";
private static final String FLOODLIGHT_PROTOCOL = FloodlightProtocolSession.FLOODLIGHT_PROTOCOL_TYPE;
private static final String OFSWITCH_RESOURCE_TYPE = "openflowswitch";
private static final String SWITCH_ID_NAME = FloodlightProtocolSession.SWITCHID_CONTEXT_PARAM_NAME;
private static final String CAPABILITY_URI = "mock://user:[email protected]:2212/mocksubsystem";
private static final String RESOURCE_URI = "mock://user:[email protected]:2212/mocksubsystem";
private static final String PROTOCOL_URI = "http://dev.ofertie.i2cat.net:8080";
private static final String SDN_ACTIONSET_NAME = "internal";
private static final String SDN_ACTIONSET_VERSION = "1.0.0";
private static final String SDN_RESOURCE_NAME = "sdnNetwork";
private static final String OFNETWORK_RESOURCE_TYPE = "ofnetwork";
/* FLOW REQUEST PARAMS */
private static final String SRC_IP_ADDRESS = "192.168.2.10";
private static final String DST_IP_ADDRESS = "192.168.2.11";
private static final int SRC_PORT = 0;
private static final int DST_PORT = 1;
private static final int TOS = 0;
private static final int SRC_VLAN_ID = 22;
private static final int DST_VLAN_ID = 22;
private static final int QOS_MIN_DELAY = 5;
private static final int QOS_MAX_DELAY = 10;
private static final int QOS_MIN_JITTER = 2;
private static final int QOS_MAX_JITTER = 4;
private static final int QOS_MIN_BANDWIDTH = 100;
private static final int QOS_MAX_BANDWIDTH = 1000;
private static final int QOS_MIN_PACKET_LOSS = 0;
private static final int QOS_MAX_PACKET_LOSS = 1;
private static final String WS_URI = "http://localhost:8888/opennaas/ofertie/ncl";
private static final String WS_USERNAME = "admin";
private static final String WS_PASSWORD = "123456";
/**
* Make sure blueprint for specified bundle has finished its initialization
*/
@SuppressWarnings("unused")
@Inject
@Filter(value = "(osgi.blueprint.container.symbolicname=org.opennaas.extensions.openflowswitch)", timeout = 50000)
private BlueprintContainer switchBlueprintContainer;
@SuppressWarnings("unused")
@Inject
@Filter(value = "(osgi.blueprint.container.symbolicname=org.opennaas.extensions.openflowswitch.driver.floodlight)", timeout = 50000)
private BlueprintContainer floodlightDriverBundleContainer;
@SuppressWarnings("unused")
@Inject
@Filter(value = "(osgi.blueprint.container.symbolicname=org.opennaas.extensions.ofnetwork)", timeout = 50000)
private BlueprintContainer ofNetworkBlueprintContainer;
@SuppressWarnings("unused")
@Inject
@Filter(value = "(osgi.blueprint.container.symbolicname=org.opennaas.extensions.ofertie.ncl)", timeout = 50000)
private BlueprintContainer nclBlueprintContainer;
@Inject
private IProtocolManager protocolManager;
@Inject
private IResourceManager resourceManager;
@Inject
private INCLProvisioner provisioner;
@Configuration
public static Option[] configuration() {
return options(
opennaasDistributionConfiguration(),
includeFeatures("opennaas-openflowswitch", "opennaas-ofnetwork", "opennaas-openflowswitch-driver-floodlight",
"opennaas-ofertie-ncl", "itests-helpers"),
systemTimeout(1000 * 60 * 10),
noConsole(),
// OpennaasExamOptions.openDebugSocket(),
keepRuntimeFolder());
}
@Before
public void createResources() throws Exception {
createSwitches();
createSDNNetwork();
flowRequest = generateSampleFlowRequest();
}
@After
public void deleteResources() throws Exception {
resourceManager.destroyAllResources();
}
@Test
public void test() throws Exception {
testAllocateDeallocate(provisioner);
}
@Test
public void wsTest() throws Exception {
INCLProvisioner provisionerClient = InitializerTestHelper.createRestClient(WS_URI, INCLProvisioner.class, null, WS_USERNAME, WS_PASSWORD);
testAllocateDeallocate(provisionerClient);
}
public void testAllocateDeallocate(INCLProvisioner provisioner) throws Exception {
String circuitId = provisioner.allocateFlow(flowRequest);
Collection<Circuit> flows = provisioner.readAllocatedFlows();
Circuit allocatedFlow = null;
for (Circuit flow : flows) {
if (flow.getId().equals(circuitId)) {
allocatedFlow = flow;
break;
}
}
Assert.assertNotNull("readAllocatedFlows() must contain allocated flow", allocatedFlow);
List<NetOFFlow> netFlows = provisioner.getFlowImplementation(circuitId);
Assert.assertNotNull("implementation must not be null", netFlows);
Assert.assertFalse("implementation must not be empty", netFlows.isEmpty());
// Get flows in SDN network
IOFProvisioningNetworkCapability sdnCapab = (IOFProvisioningNetworkCapability) sdnNetResource
.getCapabilityByInterface(IOFProvisioningNetworkCapability.class);
Set<NetOFFlow> allocatedNetFlows = sdnCapab.getAllocatedFlows();
for (NetOFFlow expected : netFlows) {
Assert.assertTrue("expected flows are present in the network", allocatedNetFlows.contains(expected));
// Get flow in switches
IResource switchResource = getSwitchResourceFromName(expected.getResourceId());
IOpenflowForwardingCapability s3capab = (IOpenflowForwardingCapability) switchResource
.getCapabilityByInterface(IOpenflowForwardingCapability.class);
List<FloodlightOFFlow> switchFlows = s3capab.getOpenflowForwardingRules();
FloodlightOFFlow switchFlow = null;
for (FloodlightOFFlow flow : switchFlows) {
if (flow.getName().equals(expected.getName())) {
switchFlow = flow;
break;
}
}
Assert.assertNotNull("switch has flow with flowId equals to expected one", switchFlow);
}
provisioner.deallocateFlow(circuitId);
flows = provisioner.readAllocatedFlows();
Assert.assertTrue("There should no be allocated circuits.", flows.isEmpty());
// Get flows in SDN network
allocatedNetFlows = sdnCapab.getAllocatedFlows();
// Get allocated flow in SDN network
- Assert.assertEquals("There should be no allocated sdnFlow", 0, netFlows.size());
+ Assert.assertEquals("There should be no allocated sdnFlow", 0, allocatedNetFlows.size());
}
private IResource getSwitchResourceFromName(String deviceName) {
return switches.get(deviceName);
}
private FlowRequest generateSampleFlowRequest() {
FlowRequest myRequest = new FlowRequest();
QoSRequirements myQoSRequirements = new QoSRequirements();
myRequest.setRequestId(String.valueOf(TOS));
myRequest.setSourceIPAddress(SRC_IP_ADDRESS);
myRequest.setDestinationIPAddress(DST_IP_ADDRESS);
myRequest.setSourcePort(SRC_PORT);
myRequest.setDestinationPort(DST_PORT);
myRequest.setTos(TOS);
myRequest.setSourceVlanId(SRC_VLAN_ID);
myRequest.setDestinationVlanId(DST_VLAN_ID);
myQoSRequirements.setMinDelay(QOS_MIN_DELAY);
myQoSRequirements.setMaxDelay(QOS_MAX_DELAY);
myQoSRequirements.setMinJitter(QOS_MIN_JITTER);
myQoSRequirements.setMaxJitter(QOS_MAX_JITTER);
myQoSRequirements.setMinBandwidth(QOS_MIN_BANDWIDTH);
myQoSRequirements.setMaxBandwidth(QOS_MAX_BANDWIDTH);
myQoSRequirements.setMinPacketLoss(QOS_MIN_PACKET_LOSS);
myQoSRequirements.setMaxPacketLoss(QOS_MAX_PACKET_LOSS);
myRequest.setQoSRequirements(myQoSRequirements);
return myRequest;
}
private void createSwitches() throws ResourceException, ProtocolException {
switches = new HashMap<String, IResource>();
switches.put(SWITCH_3_NAME, createSwitch(switch3, SWITCH_3_ID, SWITCH_3_NAME));
switches.put(SWITCH_4_NAME, createSwitch(switch4, SWITCH_4_ID, SWITCH_4_NAME));
switches.put(SWITCH_5_NAME, createSwitch(switch5, SWITCH_5_ID, SWITCH_5_NAME));
switches.put(SWITCH_6_NAME, createSwitch(switch6, SWITCH_6_ID, SWITCH_6_NAME));
switches.put(SWITCH_7_NAME, createSwitch(switch7, SWITCH_7_ID, SWITCH_7_NAME));
switches.put(SWITCH_8_NAME, createSwitch(switch8, SWITCH_8_ID, SWITCH_8_NAME));
}
private void createSDNNetwork() throws ResourceException {
List<CapabilityDescriptor> lCapabilityDescriptors = new ArrayList<CapabilityDescriptor>();
CapabilityDescriptor provisionCapab = ResourceHelper.newCapabilityDescriptor(SDN_ACTIONSET_NAME,
SDN_ACTIONSET_VERSION, OFProvisioningNetworkCapability.CAPABILITY_TYPE, CAPABILITY_URI);
lCapabilityDescriptors.add(provisionCapab);
ResourceDescriptor resourceDescriptor = ResourceHelper.newResourceDescriptor(lCapabilityDescriptors, OFNETWORK_RESOURCE_TYPE,
RESOURCE_URI, SDN_RESOURCE_NAME);
sdnNetResource = resourceManager.createResource(resourceDescriptor);
resourceManager.startResource(sdnNetResource.getResourceIdentifier());
}
private IResource createSwitch(IResource switchResource, String switchId, String switchName) throws ResourceException, ProtocolException {
List<CapabilityDescriptor> lCapabilityDescriptors = new ArrayList<CapabilityDescriptor>();
CapabilityDescriptor ofForwardingDescriptor = ResourceHelper.newCapabilityDescriptor(FLOODLIGHT_ACTIONSET_NAME,
FLOODLIGHT_ACTIONSET_VERSION, OpenflowForwardingCapability.CAPABILITY_TYPE, CAPABILITY_URI);
lCapabilityDescriptors.add(ofForwardingDescriptor);
lCapabilityDescriptors.add(ofForwardingDescriptor);
// OFSwitch Resource Descriptor
ResourceDescriptor resourceDescriptor = ResourceHelper.newResourceDescriptor(lCapabilityDescriptors, OFSWITCH_RESOURCE_TYPE,
RESOURCE_URI, switchName);
switchResource = resourceManager.createResource(resourceDescriptor);
Map<String, Object> sessionParameters = new HashMap<String, Object>();
sessionParameters.put(SWITCH_ID_NAME, switchId);
sessionParameters.put(ProtocolSessionContext.AUTH_TYPE, "noauth");
// If not exists the protocol session manager, it's created and add the session context
InitializerTestHelper.addSessionContextWithSessionParams(protocolManager, switchResource.getResourceIdentifier().getId(), PROTOCOL_URI,
FLOODLIGHT_PROTOCOL, sessionParameters);
// Start resource
resourceManager.startResource(switchResource.getResourceIdentifier());
// COMMENT THIS LINE BELOW TO LAUNCH THE TEST IN THE REAL ENVIRONMENT
// BE SURE TO HAVE PROTOCOL_URI POINTING TO YOUR FLOODLIGHT CONTROLLER
prepareClientForSwitch(switchResource);
return switchResource;
}
/**
* Overrides IFloodlightStaticFlowPusherClient in floodlight protocol session, with a FloodlightMockClient.
*
* @param switchResource
* @throws ProtocolException
*/
private void prepareClientForSwitch(IResource switchResource) throws ProtocolException {
IProtocolSessionManager sessionManager = protocolManager.getProtocolSessionManager(switchResource.getResourceIdentifier().getId());
FloodlightProtocolSession session = (FloodlightProtocolSession) sessionManager.obtainSessionByProtocol(
FloodlightProtocolSession.FLOODLIGHT_PROTOCOL_TYPE, false);
session.setClientFactory(new FloodlightMockClientFactory());
IFloodlightStaticFlowPusherClient client = session.getClientFactory().createClient(session.getSessionContext());
session.setFloodlightClient(client);
}
}
| true | true | public void testAllocateDeallocate(INCLProvisioner provisioner) throws Exception {
String circuitId = provisioner.allocateFlow(flowRequest);
Collection<Circuit> flows = provisioner.readAllocatedFlows();
Circuit allocatedFlow = null;
for (Circuit flow : flows) {
if (flow.getId().equals(circuitId)) {
allocatedFlow = flow;
break;
}
}
Assert.assertNotNull("readAllocatedFlows() must contain allocated flow", allocatedFlow);
List<NetOFFlow> netFlows = provisioner.getFlowImplementation(circuitId);
Assert.assertNotNull("implementation must not be null", netFlows);
Assert.assertFalse("implementation must not be empty", netFlows.isEmpty());
// Get flows in SDN network
IOFProvisioningNetworkCapability sdnCapab = (IOFProvisioningNetworkCapability) sdnNetResource
.getCapabilityByInterface(IOFProvisioningNetworkCapability.class);
Set<NetOFFlow> allocatedNetFlows = sdnCapab.getAllocatedFlows();
for (NetOFFlow expected : netFlows) {
Assert.assertTrue("expected flows are present in the network", allocatedNetFlows.contains(expected));
// Get flow in switches
IResource switchResource = getSwitchResourceFromName(expected.getResourceId());
IOpenflowForwardingCapability s3capab = (IOpenflowForwardingCapability) switchResource
.getCapabilityByInterface(IOpenflowForwardingCapability.class);
List<FloodlightOFFlow> switchFlows = s3capab.getOpenflowForwardingRules();
FloodlightOFFlow switchFlow = null;
for (FloodlightOFFlow flow : switchFlows) {
if (flow.getName().equals(expected.getName())) {
switchFlow = flow;
break;
}
}
Assert.assertNotNull("switch has flow with flowId equals to expected one", switchFlow);
}
provisioner.deallocateFlow(circuitId);
flows = provisioner.readAllocatedFlows();
Assert.assertTrue("There should no be allocated circuits.", flows.isEmpty());
// Get flows in SDN network
allocatedNetFlows = sdnCapab.getAllocatedFlows();
// Get allocated flow in SDN network
Assert.assertEquals("There should be no allocated sdnFlow", 0, netFlows.size());
}
| public void testAllocateDeallocate(INCLProvisioner provisioner) throws Exception {
String circuitId = provisioner.allocateFlow(flowRequest);
Collection<Circuit> flows = provisioner.readAllocatedFlows();
Circuit allocatedFlow = null;
for (Circuit flow : flows) {
if (flow.getId().equals(circuitId)) {
allocatedFlow = flow;
break;
}
}
Assert.assertNotNull("readAllocatedFlows() must contain allocated flow", allocatedFlow);
List<NetOFFlow> netFlows = provisioner.getFlowImplementation(circuitId);
Assert.assertNotNull("implementation must not be null", netFlows);
Assert.assertFalse("implementation must not be empty", netFlows.isEmpty());
// Get flows in SDN network
IOFProvisioningNetworkCapability sdnCapab = (IOFProvisioningNetworkCapability) sdnNetResource
.getCapabilityByInterface(IOFProvisioningNetworkCapability.class);
Set<NetOFFlow> allocatedNetFlows = sdnCapab.getAllocatedFlows();
for (NetOFFlow expected : netFlows) {
Assert.assertTrue("expected flows are present in the network", allocatedNetFlows.contains(expected));
// Get flow in switches
IResource switchResource = getSwitchResourceFromName(expected.getResourceId());
IOpenflowForwardingCapability s3capab = (IOpenflowForwardingCapability) switchResource
.getCapabilityByInterface(IOpenflowForwardingCapability.class);
List<FloodlightOFFlow> switchFlows = s3capab.getOpenflowForwardingRules();
FloodlightOFFlow switchFlow = null;
for (FloodlightOFFlow flow : switchFlows) {
if (flow.getName().equals(expected.getName())) {
switchFlow = flow;
break;
}
}
Assert.assertNotNull("switch has flow with flowId equals to expected one", switchFlow);
}
provisioner.deallocateFlow(circuitId);
flows = provisioner.readAllocatedFlows();
Assert.assertTrue("There should no be allocated circuits.", flows.isEmpty());
// Get flows in SDN network
allocatedNetFlows = sdnCapab.getAllocatedFlows();
// Get allocated flow in SDN network
Assert.assertEquals("There should be no allocated sdnFlow", 0, allocatedNetFlows.size());
}
|
diff --git a/src/main/java/be/Balor/Manager/Commands/Player/Experience.java b/src/main/java/be/Balor/Manager/Commands/Player/Experience.java
index 144c02df..809a5faa 100644
--- a/src/main/java/be/Balor/Manager/Commands/Player/Experience.java
+++ b/src/main/java/be/Balor/Manager/Commands/Player/Experience.java
@@ -1,179 +1,182 @@
/************************************************************************
* This file is part of AdminCmd.
*
* AdminCmd is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* AdminCmd is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with AdminCmd. If not, see <http://www.gnu.org/licenses/>.
************************************************************************/
package be.Balor.Manager.Commands.Player;
import java.util.HashMap;
import org.bukkit.Location;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.ExperienceOrb;
import org.bukkit.entity.Player;
import be.Balor.Manager.Commands.CommandArgs;
import be.Balor.Manager.Exceptions.PlayerNotFound;
import be.Balor.Manager.Permissions.ActionNotPermitedException;
import be.Balor.Tools.Utils;
import be.Balor.bukkit.AdminCmd.ACPluginManager;
/**
* @author Lathanael (aka Philippe Leipold)
*
*/
public class Experience extends PlayerCommand {
public Experience() {
permNode = "admincmd.player.experience";
cmdName = "bal_exp";
other = true;
}
/*
* (non-Javadoc)
*
* @see
* be.Balor.Manager.ACCommands#execute(org.bukkit.command.CommandSender,
* java.lang.String[])
*/
@Override
public void execute(final CommandSender sender, final CommandArgs args)
throws ActionNotPermitedException, PlayerNotFound {
float amount = 0;
Player target = null;
final HashMap<String, String> replace = new HashMap<String, String>();
boolean self = false;
if (args.hasFlag('p')) {
- target = Utils.getPlayer(args.getValueFlag('p'));
+ target = Utils.getPlayer(args.getValueFlag('p'));
} else {
+ if (!Utils.isPlayer(sender)) {
+ return;
+ }
target = (Player) sender;
self = true;
}
if (0 < args.length) {
if (!args.hasFlag('t')) {
try {
amount = args.getFloat(0);
} catch (final NumberFormatException e) {
replace.put("number", args.getString(0));
Utils.I18n("NaN", replace);
return;
}
}
} else {
if (Utils.isPlayer(sender, true)) {
if (args.hasFlag('t')) {
target = (Player) sender;
replace.put("exp",
String.valueOf(target.getTotalExperience()));
sender.sendMessage(Utils.I18n("expTotal", replace));
return;
}
} else {
return;
}
}
if (target == null) {
return;
}
replace.put("amount", String.valueOf(amount));
final Player taskTarget = target;
final float amountXp = amount;
if (args.hasFlag('d')) {
final Location loc = target.getLocation();
loc.setX(loc.getX() + 2);
ACPluginManager.scheduleSyncTask(new Runnable() {
@Override
public void run() {
taskTarget.getLocation().getWorld()
.spawn(loc, ExperienceOrb.class)
.setExperience((int) amountXp);
}
});
if (self) {
target.sendMessage(Utils.I18n("expDropped", replace));
} else {
replace.put("target", Utils.getPlayerName(target));
target.sendMessage(Utils.I18n("expDropped", replace));
sender.sendMessage(Utils.I18n("expDroppedTarget", replace));
}
} else if (args.hasFlag('a')) {
ACPluginManager.scheduleSyncTask(new Runnable() {
@Override
public void run() {
taskTarget.giveExp((int) amountXp);
}
});
if (self) {
target.sendMessage(Utils.I18n("expAdded", replace));
} else {
replace.put("target", Utils.getPlayerName(target));
sender.sendMessage(Utils.I18n("expAddedTarget", replace));
target.sendMessage(Utils.I18n("expAdded", replace));
}
} else if (args.hasFlag('b')) {
final float exp = (amount > 1 ? 1 : amount);
ACPluginManager.scheduleSyncTask(new Runnable() {
@Override
public void run() {
taskTarget.setExp(exp);
}
});
replace.put("amount", String.valueOf(exp * 100.0F));
if (self) {
target.sendMessage(Utils.I18n("expProgressionSet", replace));
} else {
replace.put("target", Utils.getPlayerName(target));
target.sendMessage(Utils.I18n("expProgressionSet", replace));
sender.sendMessage(Utils.I18n("expProgressionSetTarget",
replace));
}
} else if (args.hasFlag('l')) {
ACPluginManager.scheduleSyncTask(new Runnable() {
@Override
public void run() {
taskTarget.setLevel((int) amountXp);
}
});
if (self) {
target.sendMessage(Utils.I18n("expLevelSet", replace));
} else {
replace.put("target", Utils.getPlayerName(target));
target.sendMessage(Utils.I18n("expLevelSet", replace));
sender.sendMessage(Utils.I18n("expLevelSetTarget", replace));
}
} else if (args.hasFlag('t')) {
replace.put("exp", String.valueOf(target.getTotalExperience()));
if (self) {
sender.sendMessage(Utils.I18n("expTotal", replace));
} else {
replace.put("target", Utils.getPlayerName(target));
sender.sendMessage(Utils.I18n("expTotalTarget", replace));
}
}
}
/*
* (non-Javadoc)
*
* @see be.Balor.Manager.ACCommands#argsCheck(java.lang.String[])
*/
@Override
public boolean argsCheck(final String... args) {
return args != null && args.length >= 1;
}
}
| false | true | public void execute(final CommandSender sender, final CommandArgs args)
throws ActionNotPermitedException, PlayerNotFound {
float amount = 0;
Player target = null;
final HashMap<String, String> replace = new HashMap<String, String>();
boolean self = false;
if (args.hasFlag('p')) {
target = Utils.getPlayer(args.getValueFlag('p'));
} else {
target = (Player) sender;
self = true;
}
if (0 < args.length) {
if (!args.hasFlag('t')) {
try {
amount = args.getFloat(0);
} catch (final NumberFormatException e) {
replace.put("number", args.getString(0));
Utils.I18n("NaN", replace);
return;
}
}
} else {
if (Utils.isPlayer(sender, true)) {
if (args.hasFlag('t')) {
target = (Player) sender;
replace.put("exp",
String.valueOf(target.getTotalExperience()));
sender.sendMessage(Utils.I18n("expTotal", replace));
return;
}
} else {
return;
}
}
if (target == null) {
return;
}
replace.put("amount", String.valueOf(amount));
final Player taskTarget = target;
final float amountXp = amount;
if (args.hasFlag('d')) {
final Location loc = target.getLocation();
loc.setX(loc.getX() + 2);
ACPluginManager.scheduleSyncTask(new Runnable() {
@Override
public void run() {
taskTarget.getLocation().getWorld()
.spawn(loc, ExperienceOrb.class)
.setExperience((int) amountXp);
}
});
if (self) {
target.sendMessage(Utils.I18n("expDropped", replace));
} else {
replace.put("target", Utils.getPlayerName(target));
target.sendMessage(Utils.I18n("expDropped", replace));
sender.sendMessage(Utils.I18n("expDroppedTarget", replace));
}
} else if (args.hasFlag('a')) {
ACPluginManager.scheduleSyncTask(new Runnable() {
@Override
public void run() {
taskTarget.giveExp((int) amountXp);
}
});
if (self) {
target.sendMessage(Utils.I18n("expAdded", replace));
} else {
replace.put("target", Utils.getPlayerName(target));
sender.sendMessage(Utils.I18n("expAddedTarget", replace));
target.sendMessage(Utils.I18n("expAdded", replace));
}
} else if (args.hasFlag('b')) {
final float exp = (amount > 1 ? 1 : amount);
ACPluginManager.scheduleSyncTask(new Runnable() {
@Override
public void run() {
taskTarget.setExp(exp);
}
});
replace.put("amount", String.valueOf(exp * 100.0F));
if (self) {
target.sendMessage(Utils.I18n("expProgressionSet", replace));
} else {
replace.put("target", Utils.getPlayerName(target));
target.sendMessage(Utils.I18n("expProgressionSet", replace));
sender.sendMessage(Utils.I18n("expProgressionSetTarget",
replace));
}
} else if (args.hasFlag('l')) {
ACPluginManager.scheduleSyncTask(new Runnable() {
@Override
public void run() {
taskTarget.setLevel((int) amountXp);
}
});
if (self) {
target.sendMessage(Utils.I18n("expLevelSet", replace));
} else {
replace.put("target", Utils.getPlayerName(target));
target.sendMessage(Utils.I18n("expLevelSet", replace));
sender.sendMessage(Utils.I18n("expLevelSetTarget", replace));
}
} else if (args.hasFlag('t')) {
replace.put("exp", String.valueOf(target.getTotalExperience()));
if (self) {
sender.sendMessage(Utils.I18n("expTotal", replace));
} else {
replace.put("target", Utils.getPlayerName(target));
sender.sendMessage(Utils.I18n("expTotalTarget", replace));
}
}
}
| public void execute(final CommandSender sender, final CommandArgs args)
throws ActionNotPermitedException, PlayerNotFound {
float amount = 0;
Player target = null;
final HashMap<String, String> replace = new HashMap<String, String>();
boolean self = false;
if (args.hasFlag('p')) {
target = Utils.getPlayer(args.getValueFlag('p'));
} else {
if (!Utils.isPlayer(sender)) {
return;
}
target = (Player) sender;
self = true;
}
if (0 < args.length) {
if (!args.hasFlag('t')) {
try {
amount = args.getFloat(0);
} catch (final NumberFormatException e) {
replace.put("number", args.getString(0));
Utils.I18n("NaN", replace);
return;
}
}
} else {
if (Utils.isPlayer(sender, true)) {
if (args.hasFlag('t')) {
target = (Player) sender;
replace.put("exp",
String.valueOf(target.getTotalExperience()));
sender.sendMessage(Utils.I18n("expTotal", replace));
return;
}
} else {
return;
}
}
if (target == null) {
return;
}
replace.put("amount", String.valueOf(amount));
final Player taskTarget = target;
final float amountXp = amount;
if (args.hasFlag('d')) {
final Location loc = target.getLocation();
loc.setX(loc.getX() + 2);
ACPluginManager.scheduleSyncTask(new Runnable() {
@Override
public void run() {
taskTarget.getLocation().getWorld()
.spawn(loc, ExperienceOrb.class)
.setExperience((int) amountXp);
}
});
if (self) {
target.sendMessage(Utils.I18n("expDropped", replace));
} else {
replace.put("target", Utils.getPlayerName(target));
target.sendMessage(Utils.I18n("expDropped", replace));
sender.sendMessage(Utils.I18n("expDroppedTarget", replace));
}
} else if (args.hasFlag('a')) {
ACPluginManager.scheduleSyncTask(new Runnable() {
@Override
public void run() {
taskTarget.giveExp((int) amountXp);
}
});
if (self) {
target.sendMessage(Utils.I18n("expAdded", replace));
} else {
replace.put("target", Utils.getPlayerName(target));
sender.sendMessage(Utils.I18n("expAddedTarget", replace));
target.sendMessage(Utils.I18n("expAdded", replace));
}
} else if (args.hasFlag('b')) {
final float exp = (amount > 1 ? 1 : amount);
ACPluginManager.scheduleSyncTask(new Runnable() {
@Override
public void run() {
taskTarget.setExp(exp);
}
});
replace.put("amount", String.valueOf(exp * 100.0F));
if (self) {
target.sendMessage(Utils.I18n("expProgressionSet", replace));
} else {
replace.put("target", Utils.getPlayerName(target));
target.sendMessage(Utils.I18n("expProgressionSet", replace));
sender.sendMessage(Utils.I18n("expProgressionSetTarget",
replace));
}
} else if (args.hasFlag('l')) {
ACPluginManager.scheduleSyncTask(new Runnable() {
@Override
public void run() {
taskTarget.setLevel((int) amountXp);
}
});
if (self) {
target.sendMessage(Utils.I18n("expLevelSet", replace));
} else {
replace.put("target", Utils.getPlayerName(target));
target.sendMessage(Utils.I18n("expLevelSet", replace));
sender.sendMessage(Utils.I18n("expLevelSetTarget", replace));
}
} else if (args.hasFlag('t')) {
replace.put("exp", String.valueOf(target.getTotalExperience()));
if (self) {
sender.sendMessage(Utils.I18n("expTotal", replace));
} else {
replace.put("target", Utils.getPlayerName(target));
sender.sendMessage(Utils.I18n("expTotalTarget", replace));
}
}
}
|
diff --git a/src/main/java/dridco/seleniumhtmltojava/Commands.java b/src/main/java/dridco/seleniumhtmltojava/Commands.java
index b59e229..f666e10 100644
--- a/src/main/java/dridco/seleniumhtmltojava/Commands.java
+++ b/src/main/java/dridco/seleniumhtmltojava/Commands.java
@@ -1,513 +1,513 @@
package dridco.seleniumhtmltojava;
import static dridco.seleniumhtmltojava.TestVariables.LOGGER;
import static dridco.seleniumhtmltojava.TestVariables.SELENIUM;
import static dridco.seleniumhtmltojava.TestVariables.STORAGE;
import static java.lang.String.format;
import static org.apache.commons.lang.StringUtils.EMPTY;
import static org.apache.commons.lang.StringUtils.isNotEmpty;
import static org.apache.commons.logging.LogFactory.getLog;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
enum Commands {
fireEvent {
@Override
public String doBuild(final String locator, final String eventName) {
return format("%s.fireEvent(\"%s\", \"%s\");", SELENIUM, locator,
eventName);
}
},
waitForVisible {
@Override
public String doBuild(String target, String value) {
warnIfUnusedValueIsNotEmpty(value);
return format("waitForVisible(\"%s\", \"%s\");", target, resolveTimeout(EMPTY));
}
},
open {
@Override
public String doBuild(final String target, final String value) {
warnIfUnusedValueIsNotEmpty(value);
return format("open(\"%s\");", target);
}
},
verifyNotChecked {
@Override
public String doBuild(String locator, String unused) {
warnIfUnusedValueIsNotEmpty(unused);
return format("assertFalse(\"%s\", %s.isChecked(\"%s\"));",
message(locator, unused), SELENIUM, locator);
}
},
waitForPageToLoad {
@Override
public String doBuild(final String target, final String value) {
warnIfUnusedValueIsNotEmpty(value);
return format("waitForPageToLoad(\"%s\");", target);
}
},
uncheck {
@Override
public String doBuild(String locator, String unused) {
warnIfUnusedValueIsNotEmpty(unused);
return format("%s.uncheck(\"%s\");", SELENIUM, locator);
}
},
verifyEditable {
@Override
public String doBuild(String locator, String unused) {
warnIfUnusedValueIsNotEmpty(unused);
return format("assertTrue(\"%s\", %s.isEditable(\"%s\"));", message(locator, unused), SELENIUM, locator);
}
},
verifyVisible {
@Override
public String doBuild(String locator, String unused) {
warnIfUnusedValueIsNotEmpty(unused);
return format("assertTrue(\"%s\", %s.isVisible(\"%s\"));", message(locator, unused), SELENIUM, locator);
}
},
verifyNotEditable {
@Override
public String doBuild(String locator, String unused) {
warnIfUnusedValueIsNotEmpty(unused);
return format("assertFalse(\"%s\", %s.isEditable(\"%s\"));", message(locator, unused), SELENIUM, locator);
}
},
verifyNotVisible {
@Override
public String doBuild(String locator, String unused) {
warnIfUnusedValueIsNotEmpty(unused);
return format("assertFalse(\"%s\", %s.isVisible(\"%s\"));", message(locator, unused), SELENIUM, locator);
}
},
verifyChecked {
@Override
public String doBuild(String locator, String unused) {
warnIfUnusedValueIsNotEmpty(unused);
return format("assertTrue(\"%s\", %s.isChecked(\"%s\"));",
message(locator, unused), SELENIUM, locator);
}
},
clickAndWait {
@Override
public String doBuild(final String target, final String value) {
return click.doBuild(target, value) + waitForPageToLoad.doBuild(String.valueOf(Globals.timeout()), value);
}
},
verifyText {
@Override
public String doBuild(final String target, final String value) {
final String exactMatchPrefix = "exact:";
final String regularExpressionPrefix = "regexp:";
String built;
if (value.startsWith(exactMatchPrefix)) {
built = format(
"assertEquals(\"%s\", \"%s\", %s.getText(\"%s\"));",
message(target, value),
escape(value.substring(exactMatchPrefix.length())),
SELENIUM, target);
} else if (value.startsWith(regularExpressionPrefix)) {
built = format(
"assertThat(\"%s\", %s.getText(\"%s\"), containsString(\"%s\"));",
message(target, value), SELENIUM, target,
value.substring(regularExpressionPrefix.length()));
} else {
built = format(
- "assertThat(\"%s\", %s.getText(\"%s\"), containsString(\"%s\"));",
+ "assertThat(\"%s\", %s.getText(\"%s\").toLowerCase(), containsString((\"%s\").toLowerCase()));",
message(target, value), SELENIUM, target, escape(value));
}
return built;
}
private String escape(final String s) {
return s.replaceAll("<br */?>", "\\\\n");
}
},
verifyValue {
@Override
public String doBuild(final String target, final String value) {
return format(
"assertThat(\"%s\", %s.getValue(\"%s\"), containsString(\"%s\"));",
message(target, value), SELENIUM, target, value);
}
},
verifyTitle {
@Override
public String doBuild(final String target, final String value) {
warnIfUnusedValueIsNotEmpty(value);
return format(
"assertThat(\"%s\", %s.getTitle(), containsString(\"%s\"));",
message(target, value), SELENIUM, target);
}
},
verifyExpression {
@Override
public String doBuild(final String target, final String value) {
return format(
"assertThat(\"%s\", %s.getExpression(\"%s\"), containsString(\"%s\"));",
message(target, value), SELENIUM, target, value);
}
},
verifyEval {
private static final String GLOB_PREFIX = "glob:";
@Override
public String doBuild(final String script, final String pattern) {
Transformations transformations;
if (pattern.startsWith(GLOB_PREFIX)) {
transformations = new GlobTransformations(pattern);
} else {
transformations = new QuoteTransformation(pattern);
}
return format(
"assertTrue(\"%s\", %s.getEval(\"%s\").matches(%s));",
message(script, pattern), SELENIUM, script,
transformations.javaCalls());
}
},
verifyElementNotPresent {
@Override
public String doBuild(final String target, final String value) {
warnIfUnusedValueIsNotEmpty(value);
return format("assertFalse(\"%s\", %s.isElementPresent(\"%s\"));",
message(target, value), SELENIUM, target);
}
},
verifySelectedLabel {
@Override
public String doBuild(String locator, String pattern) {
LOG.warn("VerifySelectedLabel supports only exact matching");
return format("assertEquals(\"%s\", %s.getSelectedLabel(\"%s\"));", pattern, SELENIUM, locator);
}
},
storeValue {
@Override
public String doBuild(final String target, final String value) {
return format(
"%s.put(\"%s\", escapeJavaScript(%s.getValue(\"%s\")));",
STORAGE, value, SELENIUM, target);
}
},
typeKeys {
@Override
public String doBuild(final String target, final String value) {
return format("%s.typeKeys(\"%s\", \"%s\");", SELENIUM, target,
value);
}
},
storeText {
@Override
public String doBuild(final String target, final String value) {
return format("%s.put(\"%s\", %s.getText(\"%s\"));", STORAGE,
value, SELENIUM, target);
}
},
storeLocation {
@Override
public String doBuild(final String target, final String value) {
warnIfUnusedValueIsNotEmpty(value);
return format("%s.put(\"%s\", %s.getLocation());", STORAGE, target,
SELENIUM);
}
},
store {
@Override
public String doBuild(final String target, final String value) {
return format("%s.put(\"%s\", \"%s\");", STORAGE, value, target);
}
},
setTimeout {
@Override
public String doBuild(final String target, final String value) {
warnIfUnusedValueIsNotEmpty(value);
return format("%s.setTimeout(\"%s\");", SELENIUM, target);
}
},
setSpeed {
@Override
public String doBuild(final String target, final String value) {
return format("%s.setSpeed(\"%s\");", SELENIUM, target);
}
},
selectWindow {
@Override
public String doBuild(final String target, final String value) {
return format("%s.selectWindow(\"%s\");", SELENIUM, target);
}
},
selectFrame {
@Override
public String doBuild(final String target, final String value) {
return format("%s.selectFrame(\"%s\");", SELENIUM, target);
}
},
removeSelection {
@Override
public String doBuild(final String target, final String value) {
return format("%s.removeSelection(\"%s\", \"%s\");", SELENIUM,
target, value);
}
},
assertTitle {
@Override
public String doBuild(final String target, final String value) {
return verifyTitle.doBuild(target, value);
}
},
assertTextPresent {
@Override
public String doBuild(final String target, final String value) {
return verifyTextPresent.doBuild(target, value);
}
},
assertText {
@Override
public String doBuild(final String target, final String value) {
return verifyText.doBuild(target, value);
}
},
assertElementPresent {
@Override
public String doBuild(final String target, final String value) {
return verifyElementPresent.doBuild(target, value);
}
},
assertConfirmation {
@Override
public String doBuild(final String target, final String value) {
warnIfUnusedValueIsNotEmpty(value);
return format(
"assertEquals(\"%s\", unescapeJava(\"%s\"), %s.getConfirmation());",
message(target, value), target, SELENIUM);
}
},
addSelection {
@Override
public String doBuild(final String target, final String value) {
return format("%s.addSelection(\"%s\", \"%s\");", SELENIUM, target,
value);
}
},
verifyTextNotPresent {
@Override
public String doBuild(final String target, final String value) {
warnIfUnusedValueIsNotEmpty(value);
return format("assertFalse(\"%s\", %s.isTextPresent(\"%s\"));",
message(target, value), SELENIUM, target);
}
},
verifyTextPresent {
@Override
public String doBuild(final String target, final String value) {
warnIfUnusedValueIsNotEmpty(value);
return format("assertTrue(\"%s\", %s.isTextPresent(\"%s\"));",
message(target, value), SELENIUM, target);
}
},
verifyElementPresent {
@Override
public String doBuild(final String target, final String value) {
warnIfUnusedValueIsNotEmpty(value);
return format("assertTrue(\"%s\", %s.isElementPresent(\"%s\"));",
message(target, value), SELENIUM, target);
}
},
deleteAllVisibleCookies {
@Override
public String doBuild(final String target, final String value) {
warnIfUnusedTargetIsNotEmpty(target);
warnIfUnusedValueIsNotEmpty(value);
return format("%s.deleteAllVisibleCookies();", SELENIUM);
}
},
type {
@Override
public String doBuild(final String target, final String value) {
return format("%s.type(\"%s\", \"%s\");", SELENIUM, target, value);
}
},
select {
@Override
public String doBuild(final String target, final String value) {
return format("%s.select(\"%s\", \"%s\");", SELENIUM, target, value);
}
},
click {
@Override
public String doBuild(final String target, final String value) {
warnIfUnusedValueIsNotEmpty(value);
return SELENIUM + ".click(\"" + target + "\");";
}
},
echo {
@Override
public String doBuild(final String target, final String value) {
warnIfUnusedValueIsNotEmpty(value);
return format("%s.info(\"%s\");", LOGGER, target);
}
},
storeAttribute {
@Override
public String doBuild(final String target, final String value) {
return format("%s.put(\"%s\", selenium.getValue(\"%s\"));",
STORAGE, value, target);
}
},
storeEval {
@Override
public String doBuild(final String target, final String value) {
return format("%s.put(\"%s\", selenium.getEval(\"%s\"));", STORAGE,
value, target);
}
},
pause {
@Override
public String doBuild(final String target, final String value) {
warnIfUnusedValueIsNotEmpty(value);
LOG.warn("The use of pause is discouraged.");
return format("pause(%d);", Integer.valueOf(target));
}
},
storeHtmlSource {
@Override
public String doBuild(final String target, final String value) {
warnIfUnusedValueIsNotEmpty(value);
return format(
"%s.put(\"%s\", escapeJavaScript(%s.getHtmlSource()));",
STORAGE, target, SELENIUM);
}
},
clickAt {
@Override
public String doBuild(final String target, final String value) {
return format("%s.clickAt(\"%s\", \"%s\");", SELENIUM, target,
value);
}
},
waitForElementPresent {
@Override
public String doBuild(final String target, final String timeout) {
return format("waitForElementPresent(\"%s\", \"%s\");", //
target, resolveTimeout(timeout));
}
},
refresh {
@Override
public String doBuild(String target, String value) {
warnIfUnusedTargetIsNotEmpty(target);
warnIfUnusedValueIsNotEmpty(value);
return format("%s.refresh();", SELENIUM);
}
},
refreshAndWait {
@Override
public String doBuild(final String target, final String value) {
return refresh.doBuild(target, value) + waitForPageToLoad.doBuild(String.valueOf(Globals.timeout()), value);
}
},
waitForEditable() {
@Override
public String doBuild(final String target, final String timeout) {
warnIfUnusedValueIsNotEmpty(timeout);
return format("waitForEditable(\"%s\", \"%s\");", //
target, resolveTimeout(timeout));
}
},
waitForTextPresent() {
@Override
public String doBuild(final String target, final String timeout) {
warnIfUnusedValueIsNotEmpty(timeout);
return format("waitForTextPresent(\"%s\", \"%s\");", //
target, resolveTimeout(timeout));
}
},
waitForNotValue() {
@Override
public String doBuild(final String target, final String value) {
return format("waitForNotValue(\"%s\", \"%s\");", target, value);
}
},
check() {
@Override
public String doBuild(String locator, String unused) {
warnIfUnusedValueIsNotEmpty(unused);
return format("%s.check(\"%s\");", SELENIUM, locator);
}
},
__unknown__ {
@Override
public String doBuild(final String target, final String value) {
return format("fail(\"unknown command %s\");",
message(target, value));
}
};
private static final Log LOG = getLog(Commands.class);
public final String build(final String target, final String value) {
if (LOG.isDebugEnabled()) {
LOG.debug(format("Invoking %s", message(target, value)));
}
return doBuild( //
new Argument(target).parse(), //
new Argument(value).parse());
}
/**
* Each implementation should be printing Java lines of code, considering
* the existence of all variables defined in
* {@link dridco.seleniumhtmltojava.TestVariables}, and every method in the
* {@link org.junit.Assert}, {@link org.apache.commons.lang.StringEscapeUtils}
* and {@link org.junit.matchers.JUnitMatchers} classes. There's also every
* function defined in the {@link dridco.seleniumhtmltojava.Functions}
* enumeration
*/
public abstract String doBuild(String target, String value);
protected final void warnIfUnusedTargetIsNotEmpty(final String value) {
warnIfUnusedIsNotEmpty(value, "target");
}
protected final void warnIfUnusedValueIsNotEmpty(final String value) {
warnIfUnusedIsNotEmpty(value, "value");
}
private void warnIfUnusedIsNotEmpty(final String value,
final String description) {
if (isNotEmpty(value)) {
LOG.warn(format(
"Ignoring declared value %s for unused field %s in %s command",
value, description, name()));
}
}
protected final String message(final String target, final String value) {
return format("%s(\\\"%s\\\", \\\"%s\\\")", name(), target, value);
}
protected String resolveTimeout(final String defined) {
String actualTimeout;
if (StringUtils.isEmpty(defined)) {
actualTimeout = Globals.timeout().toString();
} else {
actualTimeout = defined;
}
return actualTimeout;
}
}
| true | true | public String doBuild(final String target, final String value) {
final String exactMatchPrefix = "exact:";
final String regularExpressionPrefix = "regexp:";
String built;
if (value.startsWith(exactMatchPrefix)) {
built = format(
"assertEquals(\"%s\", \"%s\", %s.getText(\"%s\"));",
message(target, value),
escape(value.substring(exactMatchPrefix.length())),
SELENIUM, target);
} else if (value.startsWith(regularExpressionPrefix)) {
built = format(
"assertThat(\"%s\", %s.getText(\"%s\"), containsString(\"%s\"));",
message(target, value), SELENIUM, target,
value.substring(regularExpressionPrefix.length()));
} else {
built = format(
"assertThat(\"%s\", %s.getText(\"%s\"), containsString(\"%s\"));",
message(target, value), SELENIUM, target, escape(value));
}
return built;
}
| public String doBuild(final String target, final String value) {
final String exactMatchPrefix = "exact:";
final String regularExpressionPrefix = "regexp:";
String built;
if (value.startsWith(exactMatchPrefix)) {
built = format(
"assertEquals(\"%s\", \"%s\", %s.getText(\"%s\"));",
message(target, value),
escape(value.substring(exactMatchPrefix.length())),
SELENIUM, target);
} else if (value.startsWith(regularExpressionPrefix)) {
built = format(
"assertThat(\"%s\", %s.getText(\"%s\"), containsString(\"%s\"));",
message(target, value), SELENIUM, target,
value.substring(regularExpressionPrefix.length()));
} else {
built = format(
"assertThat(\"%s\", %s.getText(\"%s\").toLowerCase(), containsString((\"%s\").toLowerCase()));",
message(target, value), SELENIUM, target, escape(value));
}
return built;
}
|
diff --git a/src/edu/berkeley/gamesman/solver/LoopySolver.java b/src/edu/berkeley/gamesman/solver/LoopySolver.java
index 59cbca96..97f92513 100644
--- a/src/edu/berkeley/gamesman/solver/LoopySolver.java
+++ b/src/edu/berkeley/gamesman/solver/LoopySolver.java
@@ -1,132 +1,132 @@
package edu.berkeley.gamesman.solver;
import java.util.List;
import edu.berkeley.gamesman.core.Configuration;
import edu.berkeley.gamesman.core.Record;
import edu.berkeley.gamesman.core.Value;
import edu.berkeley.gamesman.core.WorkUnit;
import edu.berkeley.gamesman.database.DatabaseHandle;
import edu.berkeley.gamesman.game.LoopyMutaGame;
import edu.berkeley.gamesman.game.LoopyRecord;
import edu.berkeley.gamesman.util.qll.Pool;
import edu.berkeley.gamesman.util.qll.Factory;
public class LoopySolver extends Solver {
Pool<LoopyRecord> recordPool;
public LoopySolver(Configuration conf) {
super(conf);
}
@Override
public WorkUnit prepareSolve(final Configuration conf) {
final LoopyMutaGame game = (LoopyMutaGame) conf.getGame();
recordPool = new Pool<LoopyRecord>(new Factory<LoopyRecord>() {
public LoopyRecord newObject() {
return game.getRecord();
}
public void reset(LoopyRecord t) {
t.value = Value.UNDECIDED;
}
});
long hashSpace = game.numHashes();
Record defaultRecord = game.getRecord();
defaultRecord.value = Value.IMPOSSIBLE;
writeDb.fill(conf.getGame().recordToLong(null, defaultRecord), 0,
hashSpace);
return new WorkUnit() {
public void conquer() {
solve(conf);
}
public List<WorkUnit> divide(int num) {
throw new UnsupportedOperationException();
}
};
}
public void solve(Configuration conf) {
LoopyMutaGame game = (LoopyMutaGame) conf.getGame();
for (int startNum = 0; startNum < game.numStartingPositions(); startNum++) {
game.setStartingPosition(startNum);
solve(game, game.getRecord(), 0, readDb.getHandle(),
writeDb.getHandle());
}
/*
* Run through database:
* If (database value)<DRAW and remainingChildren>0:
* (database value)=DRAW
*/
}
private void solve(LoopyMutaGame game, Record value, int depth,
DatabaseHandle readDh, DatabaseHandle writeDh) {
/*
* value = {retrieve from database}
* case IMPOSSIBLE:
* value.value = primitiveValue()
* if primitive:
* value.remoteness = value.remainingChildren = 0
* {Store value in database}
* value = value.previousPosition()
* Run through parents:
* fix(..., false)
* else:
* value.remainingChildren = len(children)
* value.value = DRAW
* {Store value in database}
* bestValue = -infinity
* Run through children:
* solve(...)
* if value.value == UNDECIDED:
* bestValue = {retrieve from database}
* else:
- * if(value.remainingChildren==0):
+ * if(value.remainingChildren==0 OR value.value.nextPosition() > DRAW):
* value.remainingChildren = (database value).remainingChildren - 1
* else
* value.remainingChildren = (database value).remainingChildren
* if(value>bestValue)
* bestValue = value
* {store value in database}
* else
* {store value.remainingChildren in database}
* value = bestValue
* Run through parents:
* fix(..., false)
* value = UNDECIDED
* default:
* value = value.previousPosition()
*
*/
}
private void fix(LoopyMutaGame game, Record value, int depth,
DatabaseHandle readDh, DatabaseHandle writeDh, boolean update) {
/*
* (database value) = {retrieve from database}
* case IMPOSSIBLE:
* Do nothing
* default:
* If update:
* value.remainingChildren = (database value).remainingChildren
* else:
* value.remainingChildren = (database value).remainingChildren - 1
* if (database value).value is DRAW or value>(database value)
* {Store value in database}
* value = value.previousPosition()
* Run through parents:
* fix(..., not (database value changed from <=DRAW to >DRAW or
* (database value<DRAW and database value.remainingChildren changed from 1 to 0)))
* value = value.nextPosition()
* else
* {Store value.remainingChildren in database}
*/
}
}
| true | true | private void solve(LoopyMutaGame game, Record value, int depth,
DatabaseHandle readDh, DatabaseHandle writeDh) {
/*
* value = {retrieve from database}
* case IMPOSSIBLE:
* value.value = primitiveValue()
* if primitive:
* value.remoteness = value.remainingChildren = 0
* {Store value in database}
* value = value.previousPosition()
* Run through parents:
* fix(..., false)
* else:
* value.remainingChildren = len(children)
* value.value = DRAW
* {Store value in database}
* bestValue = -infinity
* Run through children:
* solve(...)
* if value.value == UNDECIDED:
* bestValue = {retrieve from database}
* else:
* if(value.remainingChildren==0):
* value.remainingChildren = (database value).remainingChildren - 1
* else
* value.remainingChildren = (database value).remainingChildren
* if(value>bestValue)
* bestValue = value
* {store value in database}
* else
* {store value.remainingChildren in database}
* value = bestValue
* Run through parents:
* fix(..., false)
* value = UNDECIDED
* default:
* value = value.previousPosition()
*
*/
}
| private void solve(LoopyMutaGame game, Record value, int depth,
DatabaseHandle readDh, DatabaseHandle writeDh) {
/*
* value = {retrieve from database}
* case IMPOSSIBLE:
* value.value = primitiveValue()
* if primitive:
* value.remoteness = value.remainingChildren = 0
* {Store value in database}
* value = value.previousPosition()
* Run through parents:
* fix(..., false)
* else:
* value.remainingChildren = len(children)
* value.value = DRAW
* {Store value in database}
* bestValue = -infinity
* Run through children:
* solve(...)
* if value.value == UNDECIDED:
* bestValue = {retrieve from database}
* else:
* if(value.remainingChildren==0 OR value.value.nextPosition() > DRAW):
* value.remainingChildren = (database value).remainingChildren - 1
* else
* value.remainingChildren = (database value).remainingChildren
* if(value>bestValue)
* bestValue = value
* {store value in database}
* else
* {store value.remainingChildren in database}
* value = bestValue
* Run through parents:
* fix(..., false)
* value = UNDECIDED
* default:
* value = value.previousPosition()
*
*/
}
|
diff --git a/podsalinan/src/podsalinan/Downloader.java b/podsalinan/src/podsalinan/Downloader.java
index de44c4f..44f58f5 100644
--- a/podsalinan/src/podsalinan/Downloader.java
+++ b/podsalinan/src/podsalinan/Downloader.java
@@ -1,372 +1,373 @@
/*******************************************************************************
* Copyright (c) 2011 Sam Bell.
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published
* by the Free Software Foundation, either version 3 of the License,
* or any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See
* the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Contributors:
* Sam Bell - initial API and implementation
******************************************************************************/
/**
*
*/
package podsalinan;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.UnknownHostException;
import java.text.DecimalFormat;
import java.util.List;
import java.util.Map;
public class Downloader extends NotifyingRunnable{
private URLDownload downloadItem;
private int percentage=0;
private static int result;
private boolean stopDownload=false;
private String fileSystemSlash;
public final static int CONNECTION_FAILED=-1;
public final static int DOWNLOAD_COMPLETE=1;
public final static int DOWNLOAD_INCOMPLETE=-2;
public Downloader(URLDownload download, String newFileSystemSlash){
downloadItem = download;
fileSystemSlash=newFileSystemSlash;
}
public Downloader(URL urlDownload, String outputFile, String size){
downloadItem = new URLDownload();
downloadItem.setURL(urlDownload);
downloadItem.setSize(size);
}
public Downloader(URL urlDownload, String outputFile) {
downloadItem = new URLDownload();
downloadItem.setURL(urlDownload);
try {
URLConnection conn = downloadItem.getURL().openConnection();
List<String> values = conn.getHeaderFields().get("content-Length");
if (values != null && !values.isEmpty())
downloadItem.setSize((String) values.get(0));
} catch (MalformedURLException e) {
} catch (IOException e) {
}
}
public Downloader(URL urlDownload, File outputFile){
downloadItem = new URLDownload();
downloadItem.setURL(urlDownload);
downloadItem.setDestination(outputFile);
}
/** code found at:
* http://stackoverflow.com/questions/1139547/detect-internet-connection-using-java
* This test will cover if a download can occur or not.
* @return if its connected to the internet
*/
public static boolean isInternetReachable()
{
try {
//System.out.println("Checking the internet");
//make a URL to a known source
URL url = new URL("http://www.google.com");
//open a connection to that source
HttpURLConnection urlConnect = (HttpURLConnection)url.openConnection();
//trying to retrieve data from the source. If there
//is no connection, this line will fail
Object objData = urlConnect.getContent();
} catch (UnknownHostException e) {
result=CONNECTION_FAILED;
return false;
}
catch (IOException e) {
result=CONNECTION_FAILED;
return false;
}
return true;
}
/** This is where the file gets downloaded from
*
*/
public int getFile(){
RandomAccessFile outStream;
boolean remoteFileExists=false;
int numTries=0;
URLConnection conn;
//System.out.print("Is internet Reachable? ");
if (isInternetReachable()){
//System.out.println("Yes it is.");
byte buf[]=new byte[1024];
int byteRead; // Number of bytes read from file being downloaded
long saved=0; // Number of bytes saved
String totalSizeModifier;
//System.out.println("Internet is reachable.");
while ((!remoteFileExists)&&(numTries<2)
&&(!stopDownload)){
//System.out.println("Inside first while");
try {
conn = downloadItem.getURL().openConnection();
/* The following line gets the file size of the Download. had to do it this
* way cos URLConnection.getContentLength was an int and couldn't handle over
* 2GB
*/
//String length=conn.getHeaderField("content-Length");
String length=null;
List<String> values = conn.getHeaderFields().get("content-Length");
// If the destination is currently set to a folder, we need to add the filename to it
if ((downloadItem.getDestinationFile().exists())&&(downloadItem.getDestinationFile().isDirectory())){
// First we test if the server is handing the program a filename to set, set it here.
List<String> disposition = conn.getHeaderFields().get("content-disposition");
if (disposition!=null){
// If the file is going to be renamed from the server, grab the new name here
int index = disposition.get(0).indexOf("filename=");
if (index > 0){
String newFilename=disposition.get(0).substring(index+10, disposition.get(0).length() - 1);
File newFile = new File(downloadItem.getDestination()+fileSystemSlash+newFilename);
// If it doesn't exists create it.
if (!newFile.exists())
newFile.createNewFile();
// If it has been created set it as the destination for the download.
if ((newFile.exists())&&(newFile.isFile()))
downloadItem.setDestination(newFile);
}
} else {
//
// The following if statement checks if the file exists, and then get's the size
String filePath=downloadItem.getDestination()+fileSystemSlash+getFilenameDownload();
File outputFile = new File(filePath);
+ downloadItem.setDestination(outputFile);
if (outputFile.exists()){
downloadItem.setDestination(outputFile);
saved=outputFile.length();
}
}
}
/*
Map<String, List<String>> map = conn.getHeaderFields();
for (Map.Entry<String, List<String>> entry: map.entrySet()){
System.out.println("Key : " + entry.getKey()+
" , Value : "+entry.getValue());
}
*/
if (values != null && !values.isEmpty()){
length = (String) values.get(0);
}
long tempfileSize=-1;
if (length!=null){
tempfileSize = Long.parseLong(length);
if (Long.parseLong(downloadItem.getSize())!=tempfileSize)
downloadItem.setSize(length);
}
remoteFileExists=true;
} catch (MalformedURLException e) {
e.printStackTrace();
result=CONNECTION_FAILED;
remoteFileExists=false;
} catch (IOException e) {
e.printStackTrace();
result=CONNECTION_FAILED;
remoteFileExists=false;
}
/* Just incase the link (whether it was manually added or via a podcast)
* is incorrect, we will try to switch it from http to ftp and vice versa.
*/
if (!remoteFileExists){
String protocol;
if (downloadItem.getURL().toString().substring(0, 3).equals("http")){
protocol = "ftp";
} else
protocol = "http";
try {
URL newDownload = downloadItem.getURL();
downloadItem.setURL(new URL(protocol,
newDownload.getHost(),
newDownload.getPort(),
newDownload.getFile()).toString());
} catch (MalformedURLException e) {
result=CONNECTION_FAILED;
remoteFileExists=false;
}
}
numTries++;
}
if (remoteFileExists){
double fileSizeModified = 0;
totalSizeModifier="";
if (downloadItem.getSize()==null)
downloadItem.setSize("-1");
if (Long.parseLong(downloadItem.getSize())>1073741824){
totalSizeModifier=" Gb";
fileSizeModified=Long.parseLong(downloadItem.getSize())/1073741824;
} else if (Long.parseLong(downloadItem.getSize())>1048576){
totalSizeModifier=" Mb";
fileSizeModified=Long.parseLong(downloadItem.getSize())/1048576;
} else if (Long.parseLong(downloadItem.getSize())>1024){
totalSizeModifier=" Kb";
fileSizeModified=Long.parseLong(downloadItem.getSize())/1024;
}
try {
//System.out.println("outside the if");
if ((saved<Long.parseLong(downloadItem.getSize()))||
(Long.parseLong(downloadItem.getSize())==-1)){
outStream = new RandomAccessFile(downloadItem.getDestinationFile(),"rw");
outStream.seek(saved);
conn = downloadItem.getURL().openConnection();
/* Skip incoming connection ahead before we connect a stream to it,
* otherwise it'll waste user bandwidth
*/
conn.setRequestProperty("Range", "bytes="+ saved + "-");
conn.connect();
InputStream inStream = conn.getInputStream();
long time=System.currentTimeMillis();
int chunkCount=0;
//System.out.println("before the download while");
while (((byteRead = inStream.read(buf)) > 0)
&&(!stopDownload)){
//System.out.println("Downloading....");
outStream.write(buf, 0, byteRead);
saved+=byteRead;
chunkCount++;
String outputString;
String savedModifier="";
double savedModified=0;
// Download window output
if (saved>1073741824){
savedModifier=" Gb";
savedModified = (double)saved/1073741824;
} else if (saved>1048576){
savedModifier=" Mb";
savedModified = (double)saved/1048576;
} else if (saved>1024){
savedModifier=" Kb";
savedModified = (double)saved/1024;
} else
savedModified=saved;
savedModified=new Double(new DecimalFormat("#.##").format(savedModified)).doubleValue();
if (Long.parseLong(downloadItem.getSize())>0)
outputString = savedModified + savedModifier + " of " + fileSizeModified + totalSizeModifier;
else
outputString = savedModified + savedModifier;
// Download speed limited to 300kb/sec
if (chunkCount>=300){
try {
if ((System.currentTimeMillis()-time)<1000){
Thread.sleep(1000-(System.currentTimeMillis()-time));
}
} catch (InterruptedException e) {
// sleep interrupted
}
}
}
inStream.close();
outStream.close();
}
if (saved==Long.parseLong(downloadItem.getSize())){
percentage=100;
downloadItem.setStatus(Details.FINISHED);
} else if (saved<Long.parseLong(downloadItem.getSize())){
downloadItem.setStatus(Details.INCOMPLETE_DOWNLOAD);
}
} catch (UnknownHostException e){
downloadItem.setStatus(Details.INCOMPLETE_DOWNLOAD);
e.printStackTrace();
return CONNECTION_FAILED;
} catch (IOException e) {
downloadItem.setStatus(Details.INCOMPLETE_DOWNLOAD);
e.printStackTrace();
return CONNECTION_FAILED;
}
}
} else {
// No internet connection.
return CONNECTION_FAILED;
}
return DOWNLOAD_COMPLETE;
}
public int downloadCompleted(){
return percentage;
}
/**
* doRun is just a reconfiguration because4 of the NotifyingRunnable, it is called by the run method in the
* interface Downloader inherits
*/
public void doRun() {
//System.out.println("Downloader.doRun()");
// All it needs to do is start downloading and grab the result.
result = getFile();
}
public String getFilenameDownload(){
return downloadItem.getURL().toString().split("/")[downloadItem.getURL().toString().split("/").length-1];
}
/**
* @return the result
*/
public int getResult() {
return result;
}
/**
* @param result the result to set
*/
public void setResult(int result) {
Downloader.result = result;
}
/**
* @return the stopDownload
*/
public boolean isStopDownload() {
return stopDownload;
}
/**
* @param stopDownload the stopDownload to set
*/
public void setStopDownload(boolean stopDownload) {
this.stopDownload = stopDownload;
}
}
| true | true | public int getFile(){
RandomAccessFile outStream;
boolean remoteFileExists=false;
int numTries=0;
URLConnection conn;
//System.out.print("Is internet Reachable? ");
if (isInternetReachable()){
//System.out.println("Yes it is.");
byte buf[]=new byte[1024];
int byteRead; // Number of bytes read from file being downloaded
long saved=0; // Number of bytes saved
String totalSizeModifier;
//System.out.println("Internet is reachable.");
while ((!remoteFileExists)&&(numTries<2)
&&(!stopDownload)){
//System.out.println("Inside first while");
try {
conn = downloadItem.getURL().openConnection();
/* The following line gets the file size of the Download. had to do it this
* way cos URLConnection.getContentLength was an int and couldn't handle over
* 2GB
*/
//String length=conn.getHeaderField("content-Length");
String length=null;
List<String> values = conn.getHeaderFields().get("content-Length");
// If the destination is currently set to a folder, we need to add the filename to it
if ((downloadItem.getDestinationFile().exists())&&(downloadItem.getDestinationFile().isDirectory())){
// First we test if the server is handing the program a filename to set, set it here.
List<String> disposition = conn.getHeaderFields().get("content-disposition");
if (disposition!=null){
// If the file is going to be renamed from the server, grab the new name here
int index = disposition.get(0).indexOf("filename=");
if (index > 0){
String newFilename=disposition.get(0).substring(index+10, disposition.get(0).length() - 1);
File newFile = new File(downloadItem.getDestination()+fileSystemSlash+newFilename);
// If it doesn't exists create it.
if (!newFile.exists())
newFile.createNewFile();
// If it has been created set it as the destination for the download.
if ((newFile.exists())&&(newFile.isFile()))
downloadItem.setDestination(newFile);
}
} else {
//
// The following if statement checks if the file exists, and then get's the size
String filePath=downloadItem.getDestination()+fileSystemSlash+getFilenameDownload();
File outputFile = new File(filePath);
if (outputFile.exists()){
downloadItem.setDestination(outputFile);
saved=outputFile.length();
}
}
}
/*
Map<String, List<String>> map = conn.getHeaderFields();
for (Map.Entry<String, List<String>> entry: map.entrySet()){
System.out.println("Key : " + entry.getKey()+
" , Value : "+entry.getValue());
}
*/
if (values != null && !values.isEmpty()){
length = (String) values.get(0);
}
long tempfileSize=-1;
if (length!=null){
tempfileSize = Long.parseLong(length);
if (Long.parseLong(downloadItem.getSize())!=tempfileSize)
downloadItem.setSize(length);
}
remoteFileExists=true;
} catch (MalformedURLException e) {
e.printStackTrace();
result=CONNECTION_FAILED;
remoteFileExists=false;
} catch (IOException e) {
e.printStackTrace();
result=CONNECTION_FAILED;
remoteFileExists=false;
}
/* Just incase the link (whether it was manually added or via a podcast)
* is incorrect, we will try to switch it from http to ftp and vice versa.
*/
if (!remoteFileExists){
String protocol;
if (downloadItem.getURL().toString().substring(0, 3).equals("http")){
protocol = "ftp";
} else
protocol = "http";
try {
URL newDownload = downloadItem.getURL();
downloadItem.setURL(new URL(protocol,
newDownload.getHost(),
newDownload.getPort(),
newDownload.getFile()).toString());
} catch (MalformedURLException e) {
result=CONNECTION_FAILED;
remoteFileExists=false;
}
}
numTries++;
}
if (remoteFileExists){
double fileSizeModified = 0;
totalSizeModifier="";
if (downloadItem.getSize()==null)
downloadItem.setSize("-1");
if (Long.parseLong(downloadItem.getSize())>1073741824){
totalSizeModifier=" Gb";
fileSizeModified=Long.parseLong(downloadItem.getSize())/1073741824;
} else if (Long.parseLong(downloadItem.getSize())>1048576){
totalSizeModifier=" Mb";
fileSizeModified=Long.parseLong(downloadItem.getSize())/1048576;
} else if (Long.parseLong(downloadItem.getSize())>1024){
totalSizeModifier=" Kb";
fileSizeModified=Long.parseLong(downloadItem.getSize())/1024;
}
try {
//System.out.println("outside the if");
if ((saved<Long.parseLong(downloadItem.getSize()))||
(Long.parseLong(downloadItem.getSize())==-1)){
outStream = new RandomAccessFile(downloadItem.getDestinationFile(),"rw");
outStream.seek(saved);
conn = downloadItem.getURL().openConnection();
/* Skip incoming connection ahead before we connect a stream to it,
* otherwise it'll waste user bandwidth
*/
conn.setRequestProperty("Range", "bytes="+ saved + "-");
conn.connect();
InputStream inStream = conn.getInputStream();
long time=System.currentTimeMillis();
int chunkCount=0;
//System.out.println("before the download while");
while (((byteRead = inStream.read(buf)) > 0)
&&(!stopDownload)){
//System.out.println("Downloading....");
outStream.write(buf, 0, byteRead);
saved+=byteRead;
chunkCount++;
String outputString;
String savedModifier="";
double savedModified=0;
// Download window output
if (saved>1073741824){
savedModifier=" Gb";
savedModified = (double)saved/1073741824;
} else if (saved>1048576){
savedModifier=" Mb";
savedModified = (double)saved/1048576;
} else if (saved>1024){
savedModifier=" Kb";
savedModified = (double)saved/1024;
} else
savedModified=saved;
savedModified=new Double(new DecimalFormat("#.##").format(savedModified)).doubleValue();
if (Long.parseLong(downloadItem.getSize())>0)
outputString = savedModified + savedModifier + " of " + fileSizeModified + totalSizeModifier;
else
outputString = savedModified + savedModifier;
// Download speed limited to 300kb/sec
if (chunkCount>=300){
try {
if ((System.currentTimeMillis()-time)<1000){
Thread.sleep(1000-(System.currentTimeMillis()-time));
}
} catch (InterruptedException e) {
// sleep interrupted
}
}
}
inStream.close();
outStream.close();
}
if (saved==Long.parseLong(downloadItem.getSize())){
percentage=100;
downloadItem.setStatus(Details.FINISHED);
} else if (saved<Long.parseLong(downloadItem.getSize())){
downloadItem.setStatus(Details.INCOMPLETE_DOWNLOAD);
}
} catch (UnknownHostException e){
downloadItem.setStatus(Details.INCOMPLETE_DOWNLOAD);
e.printStackTrace();
return CONNECTION_FAILED;
} catch (IOException e) {
downloadItem.setStatus(Details.INCOMPLETE_DOWNLOAD);
e.printStackTrace();
return CONNECTION_FAILED;
}
}
} else {
// No internet connection.
return CONNECTION_FAILED;
}
return DOWNLOAD_COMPLETE;
}
| public int getFile(){
RandomAccessFile outStream;
boolean remoteFileExists=false;
int numTries=0;
URLConnection conn;
//System.out.print("Is internet Reachable? ");
if (isInternetReachable()){
//System.out.println("Yes it is.");
byte buf[]=new byte[1024];
int byteRead; // Number of bytes read from file being downloaded
long saved=0; // Number of bytes saved
String totalSizeModifier;
//System.out.println("Internet is reachable.");
while ((!remoteFileExists)&&(numTries<2)
&&(!stopDownload)){
//System.out.println("Inside first while");
try {
conn = downloadItem.getURL().openConnection();
/* The following line gets the file size of the Download. had to do it this
* way cos URLConnection.getContentLength was an int and couldn't handle over
* 2GB
*/
//String length=conn.getHeaderField("content-Length");
String length=null;
List<String> values = conn.getHeaderFields().get("content-Length");
// If the destination is currently set to a folder, we need to add the filename to it
if ((downloadItem.getDestinationFile().exists())&&(downloadItem.getDestinationFile().isDirectory())){
// First we test if the server is handing the program a filename to set, set it here.
List<String> disposition = conn.getHeaderFields().get("content-disposition");
if (disposition!=null){
// If the file is going to be renamed from the server, grab the new name here
int index = disposition.get(0).indexOf("filename=");
if (index > 0){
String newFilename=disposition.get(0).substring(index+10, disposition.get(0).length() - 1);
File newFile = new File(downloadItem.getDestination()+fileSystemSlash+newFilename);
// If it doesn't exists create it.
if (!newFile.exists())
newFile.createNewFile();
// If it has been created set it as the destination for the download.
if ((newFile.exists())&&(newFile.isFile()))
downloadItem.setDestination(newFile);
}
} else {
//
// The following if statement checks if the file exists, and then get's the size
String filePath=downloadItem.getDestination()+fileSystemSlash+getFilenameDownload();
File outputFile = new File(filePath);
downloadItem.setDestination(outputFile);
if (outputFile.exists()){
downloadItem.setDestination(outputFile);
saved=outputFile.length();
}
}
}
/*
Map<String, List<String>> map = conn.getHeaderFields();
for (Map.Entry<String, List<String>> entry: map.entrySet()){
System.out.println("Key : " + entry.getKey()+
" , Value : "+entry.getValue());
}
*/
if (values != null && !values.isEmpty()){
length = (String) values.get(0);
}
long tempfileSize=-1;
if (length!=null){
tempfileSize = Long.parseLong(length);
if (Long.parseLong(downloadItem.getSize())!=tempfileSize)
downloadItem.setSize(length);
}
remoteFileExists=true;
} catch (MalformedURLException e) {
e.printStackTrace();
result=CONNECTION_FAILED;
remoteFileExists=false;
} catch (IOException e) {
e.printStackTrace();
result=CONNECTION_FAILED;
remoteFileExists=false;
}
/* Just incase the link (whether it was manually added or via a podcast)
* is incorrect, we will try to switch it from http to ftp and vice versa.
*/
if (!remoteFileExists){
String protocol;
if (downloadItem.getURL().toString().substring(0, 3).equals("http")){
protocol = "ftp";
} else
protocol = "http";
try {
URL newDownload = downloadItem.getURL();
downloadItem.setURL(new URL(protocol,
newDownload.getHost(),
newDownload.getPort(),
newDownload.getFile()).toString());
} catch (MalformedURLException e) {
result=CONNECTION_FAILED;
remoteFileExists=false;
}
}
numTries++;
}
if (remoteFileExists){
double fileSizeModified = 0;
totalSizeModifier="";
if (downloadItem.getSize()==null)
downloadItem.setSize("-1");
if (Long.parseLong(downloadItem.getSize())>1073741824){
totalSizeModifier=" Gb";
fileSizeModified=Long.parseLong(downloadItem.getSize())/1073741824;
} else if (Long.parseLong(downloadItem.getSize())>1048576){
totalSizeModifier=" Mb";
fileSizeModified=Long.parseLong(downloadItem.getSize())/1048576;
} else if (Long.parseLong(downloadItem.getSize())>1024){
totalSizeModifier=" Kb";
fileSizeModified=Long.parseLong(downloadItem.getSize())/1024;
}
try {
//System.out.println("outside the if");
if ((saved<Long.parseLong(downloadItem.getSize()))||
(Long.parseLong(downloadItem.getSize())==-1)){
outStream = new RandomAccessFile(downloadItem.getDestinationFile(),"rw");
outStream.seek(saved);
conn = downloadItem.getURL().openConnection();
/* Skip incoming connection ahead before we connect a stream to it,
* otherwise it'll waste user bandwidth
*/
conn.setRequestProperty("Range", "bytes="+ saved + "-");
conn.connect();
InputStream inStream = conn.getInputStream();
long time=System.currentTimeMillis();
int chunkCount=0;
//System.out.println("before the download while");
while (((byteRead = inStream.read(buf)) > 0)
&&(!stopDownload)){
//System.out.println("Downloading....");
outStream.write(buf, 0, byteRead);
saved+=byteRead;
chunkCount++;
String outputString;
String savedModifier="";
double savedModified=0;
// Download window output
if (saved>1073741824){
savedModifier=" Gb";
savedModified = (double)saved/1073741824;
} else if (saved>1048576){
savedModifier=" Mb";
savedModified = (double)saved/1048576;
} else if (saved>1024){
savedModifier=" Kb";
savedModified = (double)saved/1024;
} else
savedModified=saved;
savedModified=new Double(new DecimalFormat("#.##").format(savedModified)).doubleValue();
if (Long.parseLong(downloadItem.getSize())>0)
outputString = savedModified + savedModifier + " of " + fileSizeModified + totalSizeModifier;
else
outputString = savedModified + savedModifier;
// Download speed limited to 300kb/sec
if (chunkCount>=300){
try {
if ((System.currentTimeMillis()-time)<1000){
Thread.sleep(1000-(System.currentTimeMillis()-time));
}
} catch (InterruptedException e) {
// sleep interrupted
}
}
}
inStream.close();
outStream.close();
}
if (saved==Long.parseLong(downloadItem.getSize())){
percentage=100;
downloadItem.setStatus(Details.FINISHED);
} else if (saved<Long.parseLong(downloadItem.getSize())){
downloadItem.setStatus(Details.INCOMPLETE_DOWNLOAD);
}
} catch (UnknownHostException e){
downloadItem.setStatus(Details.INCOMPLETE_DOWNLOAD);
e.printStackTrace();
return CONNECTION_FAILED;
} catch (IOException e) {
downloadItem.setStatus(Details.INCOMPLETE_DOWNLOAD);
e.printStackTrace();
return CONNECTION_FAILED;
}
}
} else {
// No internet connection.
return CONNECTION_FAILED;
}
return DOWNLOAD_COMPLETE;
}
|
diff --git a/mes-plugins/mes-plugins-operation-time-calculations/src/main/java/com/qcadoo/mes/operationTimeCalculations/OrderRealizationTimeServiceImpl.java b/mes-plugins/mes-plugins-operation-time-calculations/src/main/java/com/qcadoo/mes/operationTimeCalculations/OrderRealizationTimeServiceImpl.java
index ef6a816a05..8bede9c127 100644
--- a/mes-plugins/mes-plugins-operation-time-calculations/src/main/java/com/qcadoo/mes/operationTimeCalculations/OrderRealizationTimeServiceImpl.java
+++ b/mes-plugins/mes-plugins-operation-time-calculations/src/main/java/com/qcadoo/mes/operationTimeCalculations/OrderRealizationTimeServiceImpl.java
@@ -1,370 +1,370 @@
/**
* ***************************************************************************
* Copyright (c) 2010 Qcadoo Limited
* Project: Qcadoo MES
* Version: 1.2.0-SNAPSHOT
*
* This file is part of Qcadoo.
*
* Qcadoo is free software; you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation; either version 3 of the License,
* or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty
* of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
* ***************************************************************************
*/
package com.qcadoo.mes.operationTimeCalculations;
import static com.qcadoo.mes.technologies.constants.TechnologyOperationComponentFields.TECHNOLOGY;
import java.math.BigDecimal;
import java.math.MathContext;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.qcadoo.localization.api.utils.DateUtils;
import com.qcadoo.mes.productionLines.ProductionLinesService;
import com.qcadoo.mes.technologies.ProductQuantitiesService;
import com.qcadoo.mes.technologies.constants.TechnologiesConstants;
import com.qcadoo.model.api.DataDefinitionService;
import com.qcadoo.model.api.Entity;
import com.qcadoo.model.api.EntityTreeNode;
import com.qcadoo.model.api.NumberService;
@Service
public class OrderRealizationTimeServiceImpl implements OrderRealizationTimeService {
private static final String L_TECHNOLOGY_INSTANCE_OPERATION_COMPONENT = "technologyInstanceOperationComponent";
private static final String L_ORDER = "order";
private static final String L_TECHNOLOGY_OPERATION_COMPONENT = "technologyOperationComponent";
private static final String L_OPERATION = "operation";
private static final String L_REFERENCE_TECHNOLOGY = "referenceTechnology";
private final Map<Entity, BigDecimal> operationRunsField = new HashMap<Entity, BigDecimal>();
@Autowired
private ProductQuantitiesService productQuantitiesService;
@Autowired
private NumberService numberService;
@Autowired
private DataDefinitionService dataDefinitionService;
@Autowired
private ProductionLinesService productionLinesService;
@Override
public Object setDateToField(final Date date) {
return new SimpleDateFormat(DateUtils.L_DATE_TIME_FORMAT, Locale.getDefault()).format(date);
}
@Override
@Transactional
public int estimateOperationTimeConsumption(final EntityTreeNode operationComponent, final BigDecimal plannedQuantity,
final Entity productionLine) {
return estimateOperationTimeConsumption(operationComponent, plannedQuantity, true, true, productionLine);
}
@Override
@Transactional
public int estimateOperationTimeConsumption(final EntityTreeNode operationComponent, final BigDecimal plannedQuantity,
final boolean includeTpz, final boolean includeAdditionalTime, final Entity productionLine) {
Entity technology = operationComponent.getBelongsToField(TECHNOLOGY);
Map<Entity, BigDecimal> productComponentQuantities = productQuantitiesService.getProductComponentQuantities(technology,
plannedQuantity, operationRunsField);
return evaluateOperationTime(operationComponent, includeTpz, includeAdditionalTime, operationRunsField, productionLine,
false, productComponentQuantities);
}
@Override
@Transactional
public int estimateMaxOperationTimeConsumptionForWorkstation(final EntityTreeNode operationComponent,
final BigDecimal plannedQuantity, final boolean includeTpz, final boolean includeAdditionalTime,
final Entity productionLine) {
Entity technology = operationComponent.getBelongsToField(TECHNOLOGY);
Map<Entity, BigDecimal> productComponentQuantities = productQuantitiesService.getProductComponentQuantities(technology,
plannedQuantity, operationRunsField);
return evaluateOperationTime(operationComponent, includeTpz, includeAdditionalTime, operationRunsField, productionLine,
true, productComponentQuantities);
}
@Override
public Map<Entity, Integer> estimateOperationTimeConsumptions(final Entity entity, final BigDecimal plannedQuantity,
final boolean includeTpz, final boolean includeAdditionalTime, final Entity productionLine) {
return estimateOperationTimeConsumptions(entity, plannedQuantity, includeTpz, includeAdditionalTime, productionLine,
false);
}
@Override
public Map<Entity, Integer> estimateMaxOperationTimeConsumptionsForWorkstations(final Entity entity,
final BigDecimal plannedQuantity, final boolean includeTpz, final boolean includeAdditionalTime,
final Entity productionLine) {
return estimateOperationTimeConsumptions(entity, plannedQuantity, includeTpz, includeAdditionalTime, productionLine, true);
}
private Map<Entity, Integer> estimateOperationTimeConsumptions(final Entity entity, final BigDecimal plannedQuantity,
final boolean includeTpz, final boolean includeAdditionalTime, final Entity productionLine,
final boolean maxForWorkstation) {
Map<Entity, Integer> operationDurations = new HashMap<Entity, Integer>();
String entityType = entity.getDataDefinition().getName();
Entity technology;
List<Entity> operationComponents;
if (TECHNOLOGY.equals(entityType)) {
technology = entity;
operationComponents = technology.getTreeField("operationComponents");
} else if (L_ORDER.equals(entityType)) {
technology = entity.getBelongsToField(TECHNOLOGY);
operationComponents = entity.getTreeField("technologyInstanceOperationComponents");
} else {
throw new IllegalStateException("Entity has to be either order or technology");
}
productQuantitiesService.getProductComponentQuantities(technology, plannedQuantity, operationRunsField);
for (Entity operationComponent : operationComponents) {
evaluateTimesConsideringOperationCanBeReferencedTechnology(operationDurations, operationComponent, includeTpz,
includeAdditionalTime, operationRunsField, productionLine, maxForWorkstation);
}
return operationDurations;
}
private void evaluateTimesConsideringOperationCanBeReferencedTechnology(final Map<Entity, Integer> operationDurations,
final Entity operationComponent, final boolean includeTpz, final boolean includeAdditionalTime,
final Map<Entity, BigDecimal> operationRuns, final Entity productionLine, final boolean maxForWorkstation) {
if (L_REFERENCE_TECHNOLOGY.equals(operationComponent.getStringField("entityType"))) {
for (Entity operComp : operationComponent.getBelongsToField("referenceTechnology")
.getTreeField("operationComponents")) {
evaluateTimesConsideringOperationCanBeReferencedTechnology(operationDurations, operComp, includeTpz,
includeAdditionalTime, operationRuns, productionLine, maxForWorkstation);
}
} else {
int duration = evaluateSingleOperationTime(operationComponent, includeTpz, includeAdditionalTime, operationRunsField,
productionLine, maxForWorkstation);
if (L_TECHNOLOGY_INSTANCE_OPERATION_COMPONENT.equals(operationComponent.getDataDefinition().getName())) {
operationDurations.put(operationComponent.getBelongsToField(L_TECHNOLOGY_OPERATION_COMPONENT), duration);
} else {
operationDurations.put(operationComponent, duration);
}
}
}
private int evaluateOperationTime(final Entity operationComponent, final boolean includeTpz,
final boolean includeAdditionalTime, final Map<Entity, BigDecimal> operationRuns, final Entity productionLine,
final boolean maxForWorkstation, final Map<Entity, BigDecimal> productComponentQuantities) {
String entityType = operationComponent.getStringField("entityType");
if (L_REFERENCE_TECHNOLOGY.equals(entityType)) {
EntityTreeNode actualOperationComponent = operationComponent.getBelongsToField("referenceTechnology")
.getTreeField("operationComponents").getRoot();
return evaluateOperationTime(actualOperationComponent, includeTpz, includeAdditionalTime, operationRuns,
productionLine, maxForWorkstation, productComponentQuantities);
} else if (L_OPERATION.equals(entityType)) {
- int operationTime = evaluateSingleOperationTime(operationComponent, includeTpz, includeAdditionalTime, operationRuns,
- productionLine, maxForWorkstation);
+ int operationTime = evaluateSingleOperationTime(operationComponent, includeTpz, false, operationRuns, productionLine,
+ maxForWorkstation);
int offset = 0;
for (Entity child : operationComponent.getHasManyField("children")) {
int childTime = evaluateOperationTime(child, includeTpz, includeAdditionalTime, operationRuns, productionLine,
maxForWorkstation, productComponentQuantities);
if ("02specified".equals(child.getStringField("nextOperationAfterProducedType"))) {
int childTimeTotal = evaluateSingleOperationTime(child, includeTpz, false, operationRuns, productionLine,
true);
int childTimeForQuantity = evaluateSingleOperationTimeIncludedNextOperationAfterProducedQuantity(child,
includeTpz, false, operationRuns, productionLine, true, productComponentQuantities);
int difference = childTimeTotal - childTimeForQuantity;
childTime -= difference;
}
if (childTime > offset) {
offset = childTime;
}
}
if (L_TECHNOLOGY_INSTANCE_OPERATION_COMPONENT.equals(operationComponent.getDataDefinition().getName())) {
operationComponent.setField("effectiveOperationRealizationTime", operationTime);
operationComponent.setField("operationOffSet", offset);
operationComponent.getDataDefinition().save(operationComponent);
}
return offset + operationTime;
}
throw new IllegalStateException("entityType has to be either operation or referenceTechnology");
}
private Integer retrieveWorkstationTypesCount(final Entity operationComponent, final Entity productionLine) {
String modelName = operationComponent.getDataDefinition().getName();
if (L_TECHNOLOGY_INSTANCE_OPERATION_COMPONENT.equals(modelName)) {
return getIntegerValue(operationComponent.getField("quantityOfWorkstationTypes"));
} else if (L_TECHNOLOGY_OPERATION_COMPONENT.equals(modelName)) {
return productionLinesService.getWorkstationTypesCount(operationComponent, productionLine);
}
throw new IllegalStateException(
"operationComponent is neither technologyInstanceOperationComponent nor technologyOperationComponent");
}
private int evaluateSingleOperationTime(Entity operationComponent, final boolean includeTpz,
final boolean includeAdditionalTime, final Map<Entity, BigDecimal> operationRuns, final Entity productionLine,
final boolean maxForWorkstation) {
operationComponent = operationComponent.getDataDefinition().get(operationComponent.getId());
Entity technologyOperationComponent = operationComponent;
if (L_TECHNOLOGY_INSTANCE_OPERATION_COMPONENT.equals(operationComponent.getDataDefinition().getName())) {
technologyOperationComponent = dataDefinitionService.get(TechnologiesConstants.PLUGIN_IDENTIFIER,
TechnologiesConstants.MODEL_TECHNOLOGY_OPERATION_COMPONENT).get(
operationComponent.getBelongsToField(L_TECHNOLOGY_OPERATION_COMPONENT).getId());
}
BigDecimal cycles = operationRuns.get(technologyOperationComponent);
return evaluateOperationDurationOutOfCycles(cycles, operationComponent, productionLine, maxForWorkstation, includeTpz,
includeAdditionalTime);
}
private int evaluateSingleOperationTimeIncludedNextOperationAfterProducedQuantity(Entity operationComponent,
final boolean includeTpz, final boolean includeAdditionalTime, final Map<Entity, BigDecimal> operationRuns,
final Entity productionLine, final boolean maxForWorkstation, final Map<Entity, BigDecimal> productComponentQuantities) {
operationComponent = operationComponent.getDataDefinition().get(operationComponent.getId());
BigDecimal cycles = BigDecimal.ONE;
BigDecimal nextOperationAfterProducedQuantity = convertNullToZero(operationComponent
.getDecimalField("nextOperationAfterProducedQuantity"));
BigDecimal productComponentQuantity = productComponentQuantities.get(getOutputProduct(operationComponent));
Entity technologyOperationComponent = getTechnologyOperationComponent(operationComponent);
if (nextOperationAfterProducedQuantity.compareTo(productComponentQuantity) != 1) {
cycles = getQuantityCyclesNeededToProducedNextOperationAfterProducedQuantity(technologyOperationComponent,
nextOperationAfterProducedQuantity);
} else {
cycles = operationRuns.get(technologyOperationComponent);
}
return evaluateOperationDurationOutOfCycles(cycles, operationComponent, productionLine, maxForWorkstation, includeTpz,
includeAdditionalTime);
}
private Entity getTechnologyOperationComponent(final Entity operationComponent) {
if (L_TECHNOLOGY_INSTANCE_OPERATION_COMPONENT.equals(operationComponent.getDataDefinition().getName())) {
return dataDefinitionService.get(TechnologiesConstants.PLUGIN_IDENTIFIER,
TechnologiesConstants.MODEL_TECHNOLOGY_OPERATION_COMPONENT).get(
operationComponent.getBelongsToField(L_TECHNOLOGY_OPERATION_COMPONENT).getId());
} else {
return operationComponent;
}
}
private Entity getOutputProduct(final Entity operationComponent) {
if (L_TECHNOLOGY_INSTANCE_OPERATION_COMPONENT.equals(operationComponent.getDataDefinition().getName())) {
Entity technologyOperComp = operationComponent.getBelongsToField("technologyOperationComponent");
return productQuantitiesService.getOutputProductsFromOperataionComponent(technologyOperComp);
} else {
return productQuantitiesService.getOutputProductsFromOperataionComponent(operationComponent);
}
}
private BigDecimal getQuantityCyclesNeededToProducedNextOperationAfterProducedQuantity(final Entity operationComponent,
final BigDecimal nextOperationAfterProducedQuantity) {
MathContext mc = numberService.getMathContext();
Entity technology = operationComponent.getBelongsToField("technology");
Map<Entity, BigDecimal> operationsRunsForOrderForOneProduct = new HashMap<Entity, BigDecimal>();
Map<Entity, BigDecimal> productQuantities = productQuantitiesService.getProductComponentQuantities(technology,
BigDecimal.ONE, operationsRunsForOrderForOneProduct);
BigDecimal operationsRunsForOneMainProduct = operationsRunsForOrderForOneProduct.get(operationComponent);
BigDecimal quantityOutputProductProduced = productQuantities.get(getOutputProduct(operationComponent));
BigDecimal cycles = operationsRunsForOneMainProduct.multiply(nextOperationAfterProducedQuantity, mc).divide(
quantityOutputProductProduced, mc);
return numberService.setScale(cycles);
}
private int evaluateOperationDurationOutOfCycles(final BigDecimal cycles, final Entity operationComponent,
final Entity productionLine, final boolean maxForWorkstation, final boolean includeTpz,
final boolean includeAdditionalTime) {
boolean isTjDivisable = operationComponent.getBooleanField("isTjDivisible");
Integer workstationsCount = retrieveWorkstationTypesCount(operationComponent, productionLine);
BigDecimal cyclesPerOperation = cycles;
if (maxForWorkstation) {
cyclesPerOperation = cycles.divide(BigDecimal.valueOf(workstationsCount), numberService.getMathContext());
if (!isTjDivisable) {
cyclesPerOperation = cyclesPerOperation.setScale(0, RoundingMode.CEILING);
}
}
int tj = getIntegerValue(operationComponent.getField("tj"));
int operationTime = cyclesPerOperation.multiply(BigDecimal.valueOf(tj), numberService.getMathContext()).intValue();
if (includeTpz) {
int tpz = getIntegerValue(operationComponent.getField("tpz"));
operationTime += (maxForWorkstation ? tpz : (tpz * workstationsCount));
}
if (includeAdditionalTime) {
int additionalTime = getIntegerValue(operationComponent.getField("timeNextOperation"));
operationTime += (maxForWorkstation ? additionalTime : (additionalTime * workstationsCount));
}
return operationTime;
}
@Override
public BigDecimal getBigDecimalFromField(final Object value, final Locale locale) {
try {
DecimalFormat format = (DecimalFormat) DecimalFormat.getInstance(locale);
format.setParseBigDecimal(true);
return new BigDecimal(format.parse(value.toString()).doubleValue());
} catch (ParseException e) {
throw new IllegalStateException(e.getMessage(), e);
}
}
private Integer getIntegerValue(final Object value) {
return value == null ? Integer.valueOf(0) : (Integer) value;
}
private BigDecimal convertNullToZero(final BigDecimal value) {
if (value == null) {
return BigDecimal.ZERO;
}
return value;
}
}
| true | true | private int evaluateOperationTime(final Entity operationComponent, final boolean includeTpz,
final boolean includeAdditionalTime, final Map<Entity, BigDecimal> operationRuns, final Entity productionLine,
final boolean maxForWorkstation, final Map<Entity, BigDecimal> productComponentQuantities) {
String entityType = operationComponent.getStringField("entityType");
if (L_REFERENCE_TECHNOLOGY.equals(entityType)) {
EntityTreeNode actualOperationComponent = operationComponent.getBelongsToField("referenceTechnology")
.getTreeField("operationComponents").getRoot();
return evaluateOperationTime(actualOperationComponent, includeTpz, includeAdditionalTime, operationRuns,
productionLine, maxForWorkstation, productComponentQuantities);
} else if (L_OPERATION.equals(entityType)) {
int operationTime = evaluateSingleOperationTime(operationComponent, includeTpz, includeAdditionalTime, operationRuns,
productionLine, maxForWorkstation);
int offset = 0;
for (Entity child : operationComponent.getHasManyField("children")) {
int childTime = evaluateOperationTime(child, includeTpz, includeAdditionalTime, operationRuns, productionLine,
maxForWorkstation, productComponentQuantities);
if ("02specified".equals(child.getStringField("nextOperationAfterProducedType"))) {
int childTimeTotal = evaluateSingleOperationTime(child, includeTpz, false, operationRuns, productionLine,
true);
int childTimeForQuantity = evaluateSingleOperationTimeIncludedNextOperationAfterProducedQuantity(child,
includeTpz, false, operationRuns, productionLine, true, productComponentQuantities);
int difference = childTimeTotal - childTimeForQuantity;
childTime -= difference;
}
if (childTime > offset) {
offset = childTime;
}
}
if (L_TECHNOLOGY_INSTANCE_OPERATION_COMPONENT.equals(operationComponent.getDataDefinition().getName())) {
operationComponent.setField("effectiveOperationRealizationTime", operationTime);
operationComponent.setField("operationOffSet", offset);
operationComponent.getDataDefinition().save(operationComponent);
}
return offset + operationTime;
}
throw new IllegalStateException("entityType has to be either operation or referenceTechnology");
}
| private int evaluateOperationTime(final Entity operationComponent, final boolean includeTpz,
final boolean includeAdditionalTime, final Map<Entity, BigDecimal> operationRuns, final Entity productionLine,
final boolean maxForWorkstation, final Map<Entity, BigDecimal> productComponentQuantities) {
String entityType = operationComponent.getStringField("entityType");
if (L_REFERENCE_TECHNOLOGY.equals(entityType)) {
EntityTreeNode actualOperationComponent = operationComponent.getBelongsToField("referenceTechnology")
.getTreeField("operationComponents").getRoot();
return evaluateOperationTime(actualOperationComponent, includeTpz, includeAdditionalTime, operationRuns,
productionLine, maxForWorkstation, productComponentQuantities);
} else if (L_OPERATION.equals(entityType)) {
int operationTime = evaluateSingleOperationTime(operationComponent, includeTpz, false, operationRuns, productionLine,
maxForWorkstation);
int offset = 0;
for (Entity child : operationComponent.getHasManyField("children")) {
int childTime = evaluateOperationTime(child, includeTpz, includeAdditionalTime, operationRuns, productionLine,
maxForWorkstation, productComponentQuantities);
if ("02specified".equals(child.getStringField("nextOperationAfterProducedType"))) {
int childTimeTotal = evaluateSingleOperationTime(child, includeTpz, false, operationRuns, productionLine,
true);
int childTimeForQuantity = evaluateSingleOperationTimeIncludedNextOperationAfterProducedQuantity(child,
includeTpz, false, operationRuns, productionLine, true, productComponentQuantities);
int difference = childTimeTotal - childTimeForQuantity;
childTime -= difference;
}
if (childTime > offset) {
offset = childTime;
}
}
if (L_TECHNOLOGY_INSTANCE_OPERATION_COMPONENT.equals(operationComponent.getDataDefinition().getName())) {
operationComponent.setField("effectiveOperationRealizationTime", operationTime);
operationComponent.setField("operationOffSet", offset);
operationComponent.getDataDefinition().save(operationComponent);
}
return offset + operationTime;
}
throw new IllegalStateException("entityType has to be either operation or referenceTechnology");
}
|
diff --git a/src/me/ellbristow/simplespawnliteback/SimpleSpawnLiteBack.java b/src/me/ellbristow/simplespawnliteback/SimpleSpawnLiteBack.java
index c8d1b08..b5f5076 100644
--- a/src/me/ellbristow/simplespawnliteback/SimpleSpawnLiteBack.java
+++ b/src/me/ellbristow/simplespawnliteback/SimpleSpawnLiteBack.java
@@ -1,104 +1,104 @@
package me.ellbristow.simplespawnliteback;
import java.util.HashMap;
import me.ellbristow.simplespawnliteback.listeners.PlayerListener;
import me.ellbristow.simplespawnlitecore.LocationType;
import me.ellbristow.simplespawnlitecore.SimpleSpawnLiteCore;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.plugin.java.JavaPlugin;
public class SimpleSpawnLiteBack extends JavaPlugin {
private SimpleSpawnLiteBack plugin = this;
private boolean setHomeWithBeds = false;
private FileConfiguration config;
private SimpleSpawnLiteCore ss;
private String[] backColumns = {"player", "world", "x", "y", "z", "yaw", "pitch"};
private String[] backDims = {"TEXT NOT NULL PRIMARY KEY", "TEXT NOT NULL", "DOUBLE NOT NULL DEFAULT 0", "DOUBLE NOT NULL DEFAULT 0", "DOUBLE NOT NULL DEFAULT 0", "FLOAT NOT NULL DEFAULT 0", "FLOAT NOT NULL DEFAULT 0"};
@Override
public boolean onCommand(CommandSender sender, Command command, String commandLabel, String[] args) {
if (!(sender instanceof Player)) {
sender.sendMessage("Sorry! Command " + commandLabel + " cannot be run from the console!");
return false;
}
Player player = (Player)sender;
- if (commandLabel.equalsIgnoreCase("back")) {
+ if (commandLabel.equalsIgnoreCase("back") || commandLabel.equalsIgnoreCase("sback")) {
if (!player.hasPermission("simplespawn.back")) {
player.sendMessage(ChatColor.RED + "You do not have permission to use that command!");
return false;
}
Location backLoc = getBackLoc(player.getName());
ss.simpleTeleport(player, backLoc, LocationType.OTHER);
return true;
}
return true;
}
public void setBackLoc(String playerName, Location loc) {
String world = loc.getWorld().getName();
double x = loc.getX();
double y = loc.getY();
double z = loc.getZ();
float yaw = loc.getYaw();
float pitch = loc.getPitch();
ss.sql.query("INSERT OR REPLACE INTO BackSpawns (player, world, x, y, z, yaw, pitch) VALUES ('" + playerName + "', '" + world + "', " + x + ", " + y + ", " + z + ", " + yaw + ", " + pitch + ")");
}
public Location getBackLoc(String playerName) {
HashMap<Integer, HashMap<String, Object>> result = ss.sql.select("world, x, y, z, yaw, pitch", "BackSpawns", "player = '" + playerName + "'", null, null);
Location location;
if (result == null || result.isEmpty()) {
// if you haven't used /sethome - first home is your bed
location = getServer().getOfflinePlayer(playerName).getBedSpawnLocation();
} else {
String world = (String) result.get(0).get("world");
double x = (Double) result.get(0).get("x");
double y = (Double) result.get(0).get("y");
double z = (Double) result.get(0).get("z");
float yaw = Float.parseFloat(result.get(0).get("yaw").toString());
float pitch = Float.parseFloat(result.get(0).get("pitch").toString());
location = new Location(getServer().getWorld(world), x, y, z, yaw, pitch);
}
return location;
}
public boolean getSetting(String setting) {
if (setting.equalsIgnoreCase("SetHomeWithBeds")) return setHomeWithBeds;
return false;
}
@Override
public void saveConfig() {
ss.saveConfig();
}
@Override
public void onDisable() {
ss.sql.close();
}
@Override
public void onEnable() {
ss = SimpleSpawnLiteCore.getPluginLink();
getServer().getPluginManager().registerEvents(new PlayerListener(plugin), plugin);
if (!ss.sql.checkTable("PlayerBacks")) {
ss.sql.createTable("PlayerBacks", backColumns, backDims);
}
}
}
| true | true | public boolean onCommand(CommandSender sender, Command command, String commandLabel, String[] args) {
if (!(sender instanceof Player)) {
sender.sendMessage("Sorry! Command " + commandLabel + " cannot be run from the console!");
return false;
}
Player player = (Player)sender;
if (commandLabel.equalsIgnoreCase("back")) {
if (!player.hasPermission("simplespawn.back")) {
player.sendMessage(ChatColor.RED + "You do not have permission to use that command!");
return false;
}
Location backLoc = getBackLoc(player.getName());
ss.simpleTeleport(player, backLoc, LocationType.OTHER);
return true;
}
return true;
}
| public boolean onCommand(CommandSender sender, Command command, String commandLabel, String[] args) {
if (!(sender instanceof Player)) {
sender.sendMessage("Sorry! Command " + commandLabel + " cannot be run from the console!");
return false;
}
Player player = (Player)sender;
if (commandLabel.equalsIgnoreCase("back") || commandLabel.equalsIgnoreCase("sback")) {
if (!player.hasPermission("simplespawn.back")) {
player.sendMessage(ChatColor.RED + "You do not have permission to use that command!");
return false;
}
Location backLoc = getBackLoc(player.getName());
ss.simpleTeleport(player, backLoc, LocationType.OTHER);
return true;
}
return true;
}
|
diff --git a/bundles/plugins/org.bonitasoft.studio.expression.editor/src/org/bonitasoft/studio/expression/editor/provider/ExpressionComparator.java b/bundles/plugins/org.bonitasoft.studio.expression.editor/src/org/bonitasoft/studio/expression/editor/provider/ExpressionComparator.java
index 37907fc086..3c47d3cfea 100644
--- a/bundles/plugins/org.bonitasoft.studio.expression.editor/src/org/bonitasoft/studio/expression/editor/provider/ExpressionComparator.java
+++ b/bundles/plugins/org.bonitasoft.studio.expression.editor/src/org/bonitasoft/studio/expression/editor/provider/ExpressionComparator.java
@@ -1,38 +1,38 @@
/**
* Copyright (C) 2012 BonitaSoft S.A.
* BonitaSoft, 31 rue Gustave Eiffel - 38000 Grenoble
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2.0 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.bonitasoft.studio.expression.editor.provider;
import java.util.Comparator;
import org.bonitasoft.studio.model.expression.Expression;
/**
* @author Romain Bioteau
*
*/
public class ExpressionComparator implements Comparator<Expression> {
@Override
public int compare(Expression exp0, Expression exp1) {
- if(exp0.getType().equals(exp1.getType())){
+ if(exp0.getType().equals(exp1.getType()) && exp0.getName() != null){
return exp0.getName().compareTo(exp1.getName()) ;
}
return exp0.getType().compareTo(exp1.getType());
}
}
| true | true | public int compare(Expression exp0, Expression exp1) {
if(exp0.getType().equals(exp1.getType())){
return exp0.getName().compareTo(exp1.getName()) ;
}
return exp0.getType().compareTo(exp1.getType());
}
| public int compare(Expression exp0, Expression exp1) {
if(exp0.getType().equals(exp1.getType()) && exp0.getName() != null){
return exp0.getName().compareTo(exp1.getName()) ;
}
return exp0.getType().compareTo(exp1.getType());
}
|
diff --git a/src/main/java/org/got5/tapestry5/jquery/services/javascript/AjaxUploadStack.java b/src/main/java/org/got5/tapestry5/jquery/services/javascript/AjaxUploadStack.java
index f57d51e2..a130fd7d 100644
--- a/src/main/java/org/got5/tapestry5/jquery/services/javascript/AjaxUploadStack.java
+++ b/src/main/java/org/got5/tapestry5/jquery/services/javascript/AjaxUploadStack.java
@@ -1,74 +1,74 @@
package org.got5.tapestry5.jquery.services.javascript;
import java.util.Collections;
import java.util.List;
import org.apache.tapestry5.Asset;
import org.apache.tapestry5.SymbolConstants;
import org.apache.tapestry5.func.F;
import org.apache.tapestry5.func.Mapper;
import org.apache.tapestry5.ioc.annotations.Symbol;
import org.apache.tapestry5.services.AssetSource;
import org.apache.tapestry5.services.javascript.JavaScriptStack;
import org.apache.tapestry5.services.javascript.StylesheetLink;
import org.got5.tapestry5.jquery.components.AjaxUpload;
import org.got5.tapestry5.jquery.utils.JQueryUtils;
/**
* Resource stack for {@link AjaxUpload}.
*
* @author criedel
*/
public class AjaxUploadStack implements JavaScriptStack
{
public static final String STACK_ID = "AjaxUploadStack";
private final List<Asset> javaScriptStack;
private final List<StylesheetLink> cssStack;
public AjaxUploadStack(
@Symbol(SymbolConstants.PRODUCTION_MODE)
final boolean productionMode,
final AssetSource assetSource)
{
final Mapper<String, Asset> pathToAsset = new Mapper<String, Asset>()
{
public Asset map(String path)
{
return assetSource.getExpandedAsset(path);
}
};
final String path = String.format("${assets.path}/components/upload/jquery.fileuploader%s.js", productionMode ? ".min" : "");
- javaScriptStack = F.flow(path).map(pathToAsset).toList();
+ javaScriptStack = F.flow(path, "${assets.path}/components/upload/upload.js").map(pathToAsset).toList();
final Mapper<String, StylesheetLink> pathToStylesheetLink = F.combine(pathToAsset, JQueryUtils.assetToStylesheetLink);
cssStack = F.flow("${assets.path}/components/upload/fileuploader.css").map(pathToStylesheetLink).toList();
}
public String getInitialization()
{
return null;
}
public List<Asset> getJavaScriptLibraries()
{
return javaScriptStack;
}
public List<StylesheetLink> getStylesheets()
{
return cssStack;
}
public List<String> getStacks()
{
return Collections.emptyList();
}
}
| true | true | public AjaxUploadStack(
@Symbol(SymbolConstants.PRODUCTION_MODE)
final boolean productionMode,
final AssetSource assetSource)
{
final Mapper<String, Asset> pathToAsset = new Mapper<String, Asset>()
{
public Asset map(String path)
{
return assetSource.getExpandedAsset(path);
}
};
final String path = String.format("${assets.path}/components/upload/jquery.fileuploader%s.js", productionMode ? ".min" : "");
javaScriptStack = F.flow(path).map(pathToAsset).toList();
final Mapper<String, StylesheetLink> pathToStylesheetLink = F.combine(pathToAsset, JQueryUtils.assetToStylesheetLink);
cssStack = F.flow("${assets.path}/components/upload/fileuploader.css").map(pathToStylesheetLink).toList();
}
| public AjaxUploadStack(
@Symbol(SymbolConstants.PRODUCTION_MODE)
final boolean productionMode,
final AssetSource assetSource)
{
final Mapper<String, Asset> pathToAsset = new Mapper<String, Asset>()
{
public Asset map(String path)
{
return assetSource.getExpandedAsset(path);
}
};
final String path = String.format("${assets.path}/components/upload/jquery.fileuploader%s.js", productionMode ? ".min" : "");
javaScriptStack = F.flow(path, "${assets.path}/components/upload/upload.js").map(pathToAsset).toList();
final Mapper<String, StylesheetLink> pathToStylesheetLink = F.combine(pathToAsset, JQueryUtils.assetToStylesheetLink);
cssStack = F.flow("${assets.path}/components/upload/fileuploader.css").map(pathToStylesheetLink).toList();
}
|
diff --git a/whois-commons/src/main/java/net/ripe/db/whois/common/dao/DatabaseMaintenanceJmx.java b/whois-commons/src/main/java/net/ripe/db/whois/common/dao/DatabaseMaintenanceJmx.java
index 1d6858d4a..c2cd54fbd 100644
--- a/whois-commons/src/main/java/net/ripe/db/whois/common/dao/DatabaseMaintenanceJmx.java
+++ b/whois-commons/src/main/java/net/ripe/db/whois/common/dao/DatabaseMaintenanceJmx.java
@@ -1,79 +1,79 @@
package net.ripe.db.whois.common.dao;
import net.ripe.db.whois.common.dao.jdbc.IndexDao;
import net.ripe.db.whois.common.jmx.JmxBase;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jmx.export.annotation.ManagedOperation;
import org.springframework.jmx.export.annotation.ManagedOperationParameter;
import org.springframework.jmx.export.annotation.ManagedOperationParameters;
import org.springframework.jmx.export.annotation.ManagedResource;
import org.springframework.stereotype.Component;
import java.util.concurrent.Callable;
@Component
@ManagedResource(objectName = JmxBase.OBJECT_NAME_BASE + "DatabaseMaintenance", description = "Whois database maintenance operations")
public class DatabaseMaintenanceJmx extends JmxBase {
private static final Logger LOGGER = LoggerFactory.getLogger(DatabaseMaintenanceJmx.class);
private final RpslObjectUpdateDao updateDao;
private final IndexDao indexDao;
@Autowired
public DatabaseMaintenanceJmx(final RpslObjectUpdateDao updateDao, final IndexDao indexDao) {
super(LOGGER);
this.updateDao = updateDao;
this.indexDao = indexDao;
}
@ManagedOperation(description = "Recovers a deleted object")
@ManagedOperationParameters({
@ManagedOperationParameter(name = "objectId", description = "Id of the object to recover"),
@ManagedOperationParameter(name = "comment", description = "Optional comment for invoking the operation")
})
public String undeleteObject(final int objectId, final String comment) {
- return invokeOperation("Unref cleanup", comment, new Callable<String>() {
+ return invokeOperation("Undelete Object", comment, new Callable<String>() {
@Override
public String call() {
try {
final RpslObjectUpdateInfo updateInfo = updateDao.undeleteObject(objectId);
return String.format("Recovered object: %s", updateInfo);
} catch (RuntimeException e) {
LOGGER.error("Unable to recover object with id: {}", objectId, e);
return String.format("Unable to recover: %s", e.getMessage());
}
}
});
}
@ManagedOperation(description = "Rebuild all indexes based on objects in last")
@ManagedOperationParameters({
@ManagedOperationParameter(name = "comment", description = "Optional comment for invoking the operation")
})
public String rebuildIndexes(final String comment) {
return invokeOperation("Rebuild indexes", comment, new Callable<String>() {
@Override
public String call() throws Exception {
indexDao.rebuild();
return "Rebuilt indexes";
}
});
}
@ManagedOperation(description = "Rebuild indexes for specified object")
@ManagedOperationParameters({
@ManagedOperationParameter(name = "objectId", description = "Id of the object to rebuild"),
@ManagedOperationParameter(name = "comment", description = "Optional comment for invoking the operation")
})
public String rebuildIndexesForObject(final int objectId, final String comment) {
return invokeOperation("Rebuild indexes for object: " + objectId, comment, new Callable<String>() {
@Override
public String call() throws Exception {
indexDao.rebuildForObject(objectId);
return "Rebuilt indexes for object: " + objectId;
}
});
}
}
| true | true | public String undeleteObject(final int objectId, final String comment) {
return invokeOperation("Unref cleanup", comment, new Callable<String>() {
@Override
public String call() {
try {
final RpslObjectUpdateInfo updateInfo = updateDao.undeleteObject(objectId);
return String.format("Recovered object: %s", updateInfo);
} catch (RuntimeException e) {
LOGGER.error("Unable to recover object with id: {}", objectId, e);
return String.format("Unable to recover: %s", e.getMessage());
}
}
});
}
| public String undeleteObject(final int objectId, final String comment) {
return invokeOperation("Undelete Object", comment, new Callable<String>() {
@Override
public String call() {
try {
final RpslObjectUpdateInfo updateInfo = updateDao.undeleteObject(objectId);
return String.format("Recovered object: %s", updateInfo);
} catch (RuntimeException e) {
LOGGER.error("Unable to recover object with id: {}", objectId, e);
return String.format("Unable to recover: %s", e.getMessage());
}
}
});
}
|
diff --git a/HyPeerWeb/test/hypeerweb/HyPeerWebTest.java b/HyPeerWeb/test/hypeerweb/HyPeerWebTest.java
index fc9f55d..4eef63a 100644
--- a/HyPeerWeb/test/hypeerweb/HyPeerWebTest.java
+++ b/HyPeerWeb/test/hypeerweb/HyPeerWebTest.java
@@ -1,115 +1,115 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package hypeerweb;
import org.junit.Test;
import static org.junit.Assert.*;
import validator.Validator;
/**
* HyPeerWeb testing
*/
public class HyPeerWebTest {
//Validation variables
private final int MAX_TESTS = 114;//use <=100 if testing database
private final int TEST_EVERY = 1;
private final int GRAPH_LEVELS = 3;
private final boolean TEST_DATABASE = false;
private final boolean USE_TRACE_LOG = false;
private final boolean DRAW_GRAPH = false;
private HyPeerWeb web;
private DrawingThread draw;
public HyPeerWebTest() throws Exception{
web = HyPeerWeb.getInstance();
if (!TEST_DATABASE)
web.disableDatabase();
if (USE_TRACE_LOG){
//*
if (!web.loadTrace()){
System.out.println("Could not load insertion trace from log file!!!");
System.out.println("Try again or disable USE_TRACE_LOG");
fail();
}
//*/
}
else web.startTrace();
//Drawing a HyPeerWeb Graph
if(DRAW_GRAPH)
draw = new DrawingThread(this);
}
/**
* Test of addNode method, of class HyPeerWeb.
*/
@Test
public void testAddNode() throws Exception {
int t = 0, i = 1;
try{
if (TEST_DATABASE){
//I put the testHyPeerWeb code here because it was always running after testAddNode and so wasn't testing anything.
System.out.println("Testing restore");
assertTrue((new Validator(web)).validate());//comment out this line to get new HyPeerWeb
System.out.println("Done testing restore");
}
//Add a bunch of nodes; if it validates afterwards, addNode should be working
//We cannot do simulated tests, since addNode inserts at arbitrary places
web.removeAllNodes();
boolean valid;
int old_size = 0;
Node temp;
for (; t<2; t++){
System.out.println("BEGIN "+(t == 0 ? "ADDING" : "DELETING")+" NODES");
for (i=1; i<=MAX_TESTS; i++){
//Add nodes first time around
if (t == 0){
if ((temp = web.addNode()) == null)
throw new Exception("Added node should not be null!");
if (web.getSize() != ++old_size)
throw new Exception("HyPeerWeb is not the correct size");
if (temp.getWebId() == 254)
drawGraph(temp);
System.out.println("ADDED = "+temp.getWebId());
}
//Then delete all nodes
else{
if ((temp = web.removeNode(web.getFirstNode())) == null)
throw new Exception("Removed node should not be null!");
if (web.getSize() != --old_size)
throw new Exception("HyPeerWeb is not the correct size");
}
if (i % TEST_EVERY == 0){
valid = (new Validator(web)).validate();
assertTrue(valid);
}
}
//After insertion graph
System.out.println("DONE "+(t == 0 ? "ADDING" : "DELETING")+" NODES");
if(DRAW_GRAPH)
- drawGraph(web.getFirstNode(), 5);
+ drawGraph(web.getFirstNode());
}
} catch (Exception e){
System.out.println("Fatal Error from HyPeerWeb:");
System.out.println(e);
System.out.println(e.getMessage());
e.printStackTrace();
fail();
} finally{
if (!web.endTrace())
System.out.println("WARNING!!! Could not save the insertion trace to log file");
System.out.println("ADDED "+(t > 0 ? MAX_TESTS : i)+" NODES");
System.out.println("DELETED "+(t == 1 ? i : t == 2 ? MAX_TESTS : 0)+" NODES");
}
}
public void drawGraph(Node n) throws Exception{
if (n == null) return;
draw.start(n, GRAPH_LEVELS);
synchronized (this){
this.wait();
}
}
}
| true | true | public void testAddNode() throws Exception {
int t = 0, i = 1;
try{
if (TEST_DATABASE){
//I put the testHyPeerWeb code here because it was always running after testAddNode and so wasn't testing anything.
System.out.println("Testing restore");
assertTrue((new Validator(web)).validate());//comment out this line to get new HyPeerWeb
System.out.println("Done testing restore");
}
//Add a bunch of nodes; if it validates afterwards, addNode should be working
//We cannot do simulated tests, since addNode inserts at arbitrary places
web.removeAllNodes();
boolean valid;
int old_size = 0;
Node temp;
for (; t<2; t++){
System.out.println("BEGIN "+(t == 0 ? "ADDING" : "DELETING")+" NODES");
for (i=1; i<=MAX_TESTS; i++){
//Add nodes first time around
if (t == 0){
if ((temp = web.addNode()) == null)
throw new Exception("Added node should not be null!");
if (web.getSize() != ++old_size)
throw new Exception("HyPeerWeb is not the correct size");
if (temp.getWebId() == 254)
drawGraph(temp);
System.out.println("ADDED = "+temp.getWebId());
}
//Then delete all nodes
else{
if ((temp = web.removeNode(web.getFirstNode())) == null)
throw new Exception("Removed node should not be null!");
if (web.getSize() != --old_size)
throw new Exception("HyPeerWeb is not the correct size");
}
if (i % TEST_EVERY == 0){
valid = (new Validator(web)).validate();
assertTrue(valid);
}
}
//After insertion graph
System.out.println("DONE "+(t == 0 ? "ADDING" : "DELETING")+" NODES");
if(DRAW_GRAPH)
drawGraph(web.getFirstNode(), 5);
}
} catch (Exception e){
System.out.println("Fatal Error from HyPeerWeb:");
System.out.println(e);
System.out.println(e.getMessage());
e.printStackTrace();
fail();
} finally{
if (!web.endTrace())
System.out.println("WARNING!!! Could not save the insertion trace to log file");
System.out.println("ADDED "+(t > 0 ? MAX_TESTS : i)+" NODES");
System.out.println("DELETED "+(t == 1 ? i : t == 2 ? MAX_TESTS : 0)+" NODES");
}
}
| public void testAddNode() throws Exception {
int t = 0, i = 1;
try{
if (TEST_DATABASE){
//I put the testHyPeerWeb code here because it was always running after testAddNode and so wasn't testing anything.
System.out.println("Testing restore");
assertTrue((new Validator(web)).validate());//comment out this line to get new HyPeerWeb
System.out.println("Done testing restore");
}
//Add a bunch of nodes; if it validates afterwards, addNode should be working
//We cannot do simulated tests, since addNode inserts at arbitrary places
web.removeAllNodes();
boolean valid;
int old_size = 0;
Node temp;
for (; t<2; t++){
System.out.println("BEGIN "+(t == 0 ? "ADDING" : "DELETING")+" NODES");
for (i=1; i<=MAX_TESTS; i++){
//Add nodes first time around
if (t == 0){
if ((temp = web.addNode()) == null)
throw new Exception("Added node should not be null!");
if (web.getSize() != ++old_size)
throw new Exception("HyPeerWeb is not the correct size");
if (temp.getWebId() == 254)
drawGraph(temp);
System.out.println("ADDED = "+temp.getWebId());
}
//Then delete all nodes
else{
if ((temp = web.removeNode(web.getFirstNode())) == null)
throw new Exception("Removed node should not be null!");
if (web.getSize() != --old_size)
throw new Exception("HyPeerWeb is not the correct size");
}
if (i % TEST_EVERY == 0){
valid = (new Validator(web)).validate();
assertTrue(valid);
}
}
//After insertion graph
System.out.println("DONE "+(t == 0 ? "ADDING" : "DELETING")+" NODES");
if(DRAW_GRAPH)
drawGraph(web.getFirstNode());
}
} catch (Exception e){
System.out.println("Fatal Error from HyPeerWeb:");
System.out.println(e);
System.out.println(e.getMessage());
e.printStackTrace();
fail();
} finally{
if (!web.endTrace())
System.out.println("WARNING!!! Could not save the insertion trace to log file");
System.out.println("ADDED "+(t > 0 ? MAX_TESTS : i)+" NODES");
System.out.println("DELETED "+(t == 1 ? i : t == 2 ? MAX_TESTS : 0)+" NODES");
}
}
|
diff --git a/java/testing/org/apache/derbyTesting/functionTests/tests/jdbcapi/checkDataSource.java b/java/testing/org/apache/derbyTesting/functionTests/tests/jdbcapi/checkDataSource.java
index 7f9084cc0..c026fb8f7 100644
--- a/java/testing/org/apache/derbyTesting/functionTests/tests/jdbcapi/checkDataSource.java
+++ b/java/testing/org/apache/derbyTesting/functionTests/tests/jdbcapi/checkDataSource.java
@@ -1,1802 +1,1807 @@
/*
Derby - Class org.apache.derbyTesting.functionTests.tests.jdbcapi.checkDataSource
Copyright 2002, 2005 The Apache Software Foundation or its licensors, as applicable.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.apache.derbyTesting.functionTests.tests.jdbcapi;
import java.io.Serializable;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Properties;
import javax.sql.ConnectionEvent;
import javax.sql.ConnectionEventListener;
import javax.sql.ConnectionPoolDataSource;
import javax.sql.DataSource;
import javax.sql.PooledConnection;
import javax.sql.XAConnection;
import javax.sql.XADataSource;
import javax.transaction.xa.XAException;
import javax.transaction.xa.XAResource;
import javax.transaction.xa.Xid;
import org.apache.derby.jdbc.EmbeddedConnectionPoolDataSource;
import org.apache.derby.jdbc.EmbeddedDataSource;
import org.apache.derby.jdbc.EmbeddedXADataSource;
import org.apache.derby.tools.JDBCDisplayUtil;
import org.apache.derby.tools.ij;
import org.apache.derbyTesting.functionTests.util.SecurityCheck;
import org.apache.derbyTesting.functionTests.util.TestUtil;
import org.apache.oro.text.perl.Perl5Util;
/**
* Test the various embedded DataSource implementations of Derby.
*
* Performs SecurityCheck analysis on the JDBC objects returned.
* This is because this test returns to the client a number of
* different implementations of Connection, Statement etc.
*
* @see org.apache.derbyTesting.functionTests.util.SecurityCheck
*
*/
public class checkDataSource
{
// Only test connection toString values for embedded.
// Client connection toString values are not correlated at this time and just
// use default toString
// These tests are exempted from other frameworks
private boolean testConnectionToString = TestUtil.isEmbeddedFramework();
// Only embedded supports SimpleDataSource (JSR169).
// These tests are exempted from other frameworks
private boolean testSimpleDataSource = TestUtil.isEmbeddedFramework();
// for a PooledConnection.getConnection() the connection gets closed.
// Embedded automatically rolls back any activity on the connection.
// Client requires the user to rollback and gives an SQLException
// java.sql.Connection.close() requested while a transaction is in progress
// This has been filed as DERBY-1004
private boolean needRollbackBeforePCGetConnection =
TestUtil.isDerbyNetClientFramework();
// DERBY-1035 With client, Connection.getTransactionIsolation() return value is
// wrong after changing the isolation level with an SQL statement such as
// "set current isolation = RS"
// Tests for setting isolation level this way only run in embedded for now.
private boolean canSetIsolationWithStatement = TestUtil.isEmbeddedFramework();
// DERBY-1148 - Client Connection state does not
// get set properly when joining a global transaction.
private static boolean isolationSetProperlyOnJoin = TestUtil.isEmbeddedFramework();
// DERBY-1183 getCursorName not correct after first statement execution
private static boolean hasGetCursorNameBug = TestUtil.isDerbyNetClientFramework();
/**
* A hashtable of opened connections. This is used when checking to
* make sure connection strings are unique; we need to make sure all
* the connections are closed when we are done, so they are stored
* in this hashtable
*/
protected static Hashtable conns = new Hashtable();
/**
* This is a utility that knows how to do pattern matching. Used
* in checking the format of a connection string
*/
protected static Perl5Util p5u = new Perl5Util();
/** The expected format of a connection string. In English:
* "<classname>@<hashcode> (XID=<xid>), (SESSION = <sessionid>),
* (DATABASE=<dbname>), (DRDAID = <drdaid>)"
*/
private static final String CONNSTRING_FORMAT = "\\S+@[0-9]+ " +
"\\(XID = .*\\), \\(SESSIONID = [0-9]+\\), " +
"\\(DATABASE = [A-Za-z]+\\), \\(DRDAID = .+\\)";
/**
* Hang onto the SecurityCheck class while running the
* tests so that it is not garbage collected during the
* test and lose the information it has collected.
*/
private final Object nogc = SecurityCheck.class;
public static void main(String[] args) throws Exception {
try
{
new checkDataSource().runTest(args);
// Print a report on System.out of the issues
// found with the security checks.
SecurityCheck.report();
}
catch ( Exception e )
{
e.printStackTrace();
throw e;
}
System.out.println("Completed checkDataSource");
}
public checkDataSource() {
}
protected void runTest(String[] args) throws Exception {
// Check the returned type of the JDBC Connections.
ij.getPropertyArg(args);
Connection dmc = ij.startJBMS();
dmc.createStatement().executeUpdate("create table y(i int)");
dmc.createStatement().executeUpdate(
"create procedure checkConn2(in dsname varchar(20)) " +
"parameter style java language java modifies SQL DATA " +
"external name 'org.apache.derbyTesting.functionTests.tests.jdbcapi." +
this.getNestedMethodName() +
"'");
CallableStatement cs = dmc.prepareCall("call checkConn2(?)");
cs.setString(1,"Nested");
cs.execute();
checkConnection("DriverManager ", dmc);
if (testConnectionToString)
checkJBMSToString();
Properties attrs = new Properties();
attrs.setProperty("databaseName", "wombat");
DataSource dscs = TestUtil.getDataSource(attrs);
if (testConnectionToString)
checkToString(dscs);
DataSource ds = dscs;
checkConnection("DataSource", ds.getConnection());
DataSource dssimple = null;
if (testSimpleDataSource)
{
dssimple = TestUtil.getSimpleDataSource(attrs);
ds = dssimple;
checkConnection("SimpleDataSource", ds.getConnection());
}
ConnectionPoolDataSource dsp = TestUtil.getConnectionPoolDataSource(attrs);
if (testConnectionToString)
checkToString(dsp);
PooledConnection pc = dsp.getPooledConnection();
SecurityCheck.inspect(pc, "javax.sql.PooledConnection");
pc.addConnectionEventListener(new EventCatcher(1));
checkConnection("ConnectionPoolDataSource", pc.getConnection());
checkConnection("ConnectionPoolDataSource", pc.getConnection());
// BUG 4471 - check outstanding updates are rolled back.
Connection c1 = pc.getConnection();
Statement s = c1.createStatement();
s.executeUpdate("create table t (i int)");
s.executeUpdate("insert into t values(1)");
c1.setAutoCommit(false);
// this update should be rolled back
s.executeUpdate("insert into t values(2)");
if (needRollbackBeforePCGetConnection)
c1.rollback();
c1 = pc.getConnection();
ResultSet rs = c1.createStatement().executeQuery("select count(*) from t");
rs.next();
int count = rs.getInt(1);
System.out.println(count == 1 ? "Changes rolled back OK in auto closed pooled connection" :
("FAIL changes committed in in auto closed pooled connection - " + count));
c1.close();
// check connection objects are closed once connection is closed
try {
rs.next();
System.out.println("FAIL - ResultSet is open for a closed connection obtained from PooledConnection");
} catch (SQLException sqle) {
System.out.println("expected " + sqle.toString());
}
try {
s.executeUpdate("update t set i = 1");
System.out.println("FAIL - Statement is open for a closed connection obtained from PooledConnection");
} catch (SQLException sqle) {
System.out.println("expected " + sqle.toString());
}
pc.close();
pc = null;
testPoolReset("ConnectionPoolDataSource", dsp.getPooledConnection());
XADataSource dsx = TestUtil.getXADataSource(attrs);
if (testConnectionToString)
checkToString(dsx);
XAConnection xac = dsx.getXAConnection();
SecurityCheck.inspect(xac, "javax.sql.XAConnection");
xac.addConnectionEventListener(new EventCatcher(3));
checkConnection("XADataSource", xac.getConnection());
// BUG 4471 - check outstanding updates are rolled back wi XAConnection.
c1 = xac.getConnection();
s = c1.createStatement();
s.executeUpdate("insert into t values(1)");
c1.setAutoCommit(false);
// this update should be rolled back
s.executeUpdate("insert into t values(2)");
if (needRollbackBeforePCGetConnection)
c1.rollback();
c1 = xac.getConnection();
rs = c1.createStatement().executeQuery("select count(*) from t");
rs.next();
count = rs.getInt(1);
rs.close();
System.out.println(count == 2 ? "Changes rolled back OK in auto closed local XAConnection" :
("FAIL changes committed in in auto closed pooled connection - " + count));
c1.close();
xac.close();
xac = null;
testPoolReset("XADataSource", dsx.getXAConnection());
try {
TestUtil.getConnection("","shutdown=true");
} catch (SQLException sqle) {
JDBCDisplayUtil.ShowSQLException(System.out, sqle);
}
dmc = ij.startJBMS();
cs = dmc.prepareCall("call checkConn2(?)");
SecurityCheck.inspect(cs, "java.sql.CallableStatement");
cs.setString(1,"Nested");
cs.execute();
checkConnection("DriverManager ", dmc);
// reset ds back to the Regular DataSource
ds = dscs;
checkConnection("DataSource", ds.getConnection());
// and back to EmbeddedSimpleDataSource
if(TestUtil.isEmbeddedFramework())
{
// JSR169 (SimpleDataSource) is only available on embedded.
ds = dssimple;
checkConnection("EmbeddedSimpleDataSource", dssimple.getConnection());
}
pc = dsp.getPooledConnection();
pc.addConnectionEventListener(new EventCatcher(2));
checkConnection("ConnectionPoolDataSource", pc.getConnection());
checkConnection("ConnectionPoolDataSource", pc.getConnection());
// test "local" XAConnections
xac = dsx.getXAConnection();
xac.addConnectionEventListener(new EventCatcher(4));
checkConnection("XADataSource", xac.getConnection());
checkConnection("XADataSource", xac.getConnection());
xac.close();
// test "global" XAConnections
xac = dsx.getXAConnection();
xac.addConnectionEventListener(new EventCatcher(5));
XAResource xar = xac.getXAResource();
SecurityCheck.inspect(xar, "javax.transaction.xa.XAResource");
Xid xid = new cdsXid(1, (byte) 35, (byte) 47);
xar.start(xid, XAResource.TMNOFLAGS);
Connection xacc = xac.getConnection();
xacc.close();
checkConnection("Global XADataSource", xac.getConnection());
checkConnection("Global XADataSource", xac.getConnection());
xar.end(xid, XAResource.TMSUCCESS);
checkConnection("Switch to local XADataSource", xac.getConnection());
checkConnection("Switch to local XADataSource", xac.getConnection());
Connection backtoGlobal = xac.getConnection();
xar.start(xid, XAResource.TMJOIN);
checkConnection("Switch to global XADataSource", backtoGlobal);
checkConnection("Switch to global XADataSource", xac.getConnection());
xar.end(xid, XAResource.TMSUCCESS);
xar.commit(xid, true);
xac.close();
// now some explicit tests for how connection state behaves
// when switching between global transactions and local
// and setting connection state.
// some of this is already tested in simpleDataSource and checkDataSource
// but I want to make sure I cover all situations. (djd)
xac = dsx.getXAConnection();
xac.addConnectionEventListener(new EventCatcher(6));
xar = xac.getXAResource();
xid = new cdsXid(1, (byte) 93, (byte) 103);
// series 1 - Single connection object
Connection cs1 = xac.getConnection();
printState("initial local", cs1);
xar.start(xid, XAResource.TMNOFLAGS);
printState("initial X1", cs1);
cs1.setTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED);
cs1.setReadOnly(true);
setHoldability(cs1, false);
printState("modified X1", cs1);
xar.end(xid, XAResource.TMSUCCESS);
// the underlying local transaction/connection must pick up the
// state of the Connection handle cs1
printState("modified local", cs1);
cs1.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
cs1.setReadOnly(false);
setHoldability(cs1, false);
printState("reset local", cs1);
// now re-join the transaction, should pick up the read-only
// and isolation level from the transaction,
// holdability remains that of this handle.
xar.start(xid, XAResource.TMJOIN);
// DERBY-1148
if (isolationSetProperlyOnJoin)
printState("re-join X1", cs1);
xar.end(xid, XAResource.TMSUCCESS);
// should be the same as the reset local
printState("back to local (same as reset)", cs1);
cs1.setTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED);
cs1.setReadOnly(true);
setHoldability(cs1, true);
cs1.close();
cs1 = xac.getConnection();
printState("new handle - local ", cs1);
cs1.close();
xar.start(xid, XAResource.TMJOIN);
cs1 = xac.getConnection();
// DERBY-1148
if (isolationSetProperlyOnJoin)
printState("re-join with new handle X1", cs1);
cs1.close();
xar.end(xid, XAResource.TMSUCCESS);
// now get a connection (attached to a local)
// attach to the global and commit it.
// state should be that of the local after the commit.
cs1 = xac.getConnection();
cs1.setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ);
printState("pre-X1 commit - local", cs1);
xar.start(xid, XAResource.TMJOIN);
// DERBY-1148
if (isolationSetProperlyOnJoin)
printState("pre-X1 commit - X1", cs1);
xar.end(xid, XAResource.TMSUCCESS);
printState("post-X1 end - local", cs1);
xar.commit(xid, true);
printState("post-X1 commit - local", cs1);
cs1.close();
//Derby-421 Setting isolation level with SQL was not getting handled correctly
System.out.println("Some more isolation testing using SQL and JDBC api");
cs1 = xac.getConnection();
s = cs1.createStatement();
printState("initial local", cs1);
System.out.println("Issue setTransactionIsolation in local transaction");
cs1.setTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED);
printState("setTransactionIsolation in local", cs1);
if (canSetIsolationWithStatement)
testSetIsolationWithStatement(s, xar, cs1);
// now check re-use of *Statement objects across local/global connections.
System.out.println("TESTING RE_USE OF STATEMENT OBJECTS");
cs1 = xac.getConnection();
// ensure read locks stay around until end-of transaction
cs1.setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ);
cs1.setAutoCommit(false);
checkLocks(cs1);
Statement sru1 = cs1.createStatement();
sru1.setCursorName("SN1");
sru1.executeUpdate("create table ru(i int)");
sru1.executeUpdate("insert into ru values 1,2,3");
Statement sruBatch = cs1.createStatement();
Statement sruState = createFloatStatementForStateChecking(cs1);
PreparedStatement psruState = createFloatStatementForStateChecking(cs1, "select i from ru where i = ?");
CallableStatement csruState = createFloatCallForStateChecking(cs1, "CALL SYSCS_UTIL.SYSCS_SET_DATABASE_PROPERTY(?,?)");
PreparedStatement psParams = cs1.prepareStatement("select * from ru where i > ?");
psParams.setCursorName("params");
psParams.setInt(1, 2);
resultSetQuery("Params-local-1", psParams.executeQuery());
sruBatch.addBatch("insert into ru values 4");
queryOnStatement("sru1-local-1", cs1, sru1);
cs1.commit(); // need to commit to switch to an global connection;
xid = new cdsXid(1, (byte) 103, (byte) 119);
xar.start(xid, XAResource.TMNOFLAGS); // simple case - underlying connection is re-used for global.
System.out.println("Expecting downgrade because global transaction sru1-global-2 is using a statement with holdability true");
queryOnStatement("sru1-global-2", cs1, sru1);
sruBatch.addBatch("insert into ru values 5");
Statement sru2 = cs1.createStatement();
sru2.setCursorName("OAK2");
queryOnStatement("sru2-global-3", cs1, sru2);
System.out.println("Expecting downgrade because global transaction sru1-global-4 is using a statement with holdability true");
queryOnStatement("sru1-global-4", cs1, sru1);
showStatementState("GLOBAL ", sruState);
showStatementState("PS GLOBAL ", psruState);
showStatementState("CS GLOBAL ", csruState);
resultSetQuery("Params-global-1", psParams.executeQuery());
xar.end(xid, XAResource.TMSUCCESS);
// now a new underlying connection is created
queryOnStatement("sru1-local-5", cs1, sru1);
queryOnStatement("sru2-local-6", cs1, sru2);
sruBatch.addBatch("insert into ru values 6,7");
Statement sru3 = cs1.createStatement();
sru3.setCursorName("SF3");
queryOnStatement("sru3-local-7", cs1, sru3);
// Two transactions should hold locks (global and the current XA);
showStatementState("LOCAL ", sruState);
showStatementState("PS LOCAL ", psruState);
showStatementState("CS LOCAL ", csruState);
resultSetQuery("Params-local-2", psParams.executeQuery());
checkLocks(cs1);
cs1.commit();
// attach the XA transaction to another connection and see what happens
XAConnection xac2 = dsx.getXAConnection();
xac2.addConnectionEventListener(new EventCatcher(5));
XAResource xar2 = xac2.getXAResource();
xar2.start(xid, XAResource.TMJOIN);
Connection cs2 = xac2.getConnection();
// these statements were generated by cs1 and thus are still
// in a local connection.
queryOnStatement("sru1-local-8", cs1, sru1);
queryOnStatement("sru2-local-9", cs1, sru2);
queryOnStatement("sru3-local-10", cs1, sru3);
sruBatch.addBatch("insert into ru values 8");
showStatementState("LOCAL 2 ", sruState);
showStatementState("PS LOCAL 2 ", psruState);
showStatementState("CS LOCAL 2", csruState);
checkLocks(cs1);
int[] updateCounts = sruBatch.executeBatch();
System.out.print("sruBatch update counts :");
for (int i = 0; i < updateCounts.length; i++) {
System.out.print(" " + updateCounts[i] + " ");
}
System.out.println(":");
queryOnStatement("sruBatch", cs1, sruBatch);
xar2.end(xid, XAResource.TMSUCCESS);
xac2.close();
// allow close on already closed XAConnection
xac2.close();
xac2.addConnectionEventListener(null);
xac2.removeConnectionEventListener(null);
// test methods against a closed XAConnection and its resource
try {
xac2.getXAResource();
} catch (SQLException sqle) {
System.out.println("XAConnection.getXAResource : " + sqle.getMessage());
}
try {
xac2.getConnection();
} catch (SQLException sqle) {
System.out.println("XAConnection.getConnection : " + sqle.getMessage());
}
try {
xar2.start(xid, XAResource.TMJOIN);
} catch (XAException xae) {
showXAException("XAResource.start", xae);
}
try {
xar2.end(xid, XAResource.TMJOIN);
} catch (XAException xae) {
showXAException("XAResource.end", xae);
}
try {
xar2.commit(xid, true);
} catch (XAException xae) {
showXAException("XAResource.commit", xae);
}
try {
xar2.prepare(xid);
} catch (XAException xae) {
showXAException("XAResource.prepare", xae);
}
try {
xar2.recover(0);
} catch (XAException xae) {
showXAException("XAResource.recover", xae);
}
try {
xar2.prepare(xid);
} catch (XAException xae) {
showXAException("XAResource.prepare", xae);
}
try {
xar2.isSameRM(xar2);
} catch (XAException xae) {
showXAException("XAResource.isSameRM", xae);
}
// Patricio (on the forum) one was having an issue with set schema not working in an XA connection.
dmc = ij.startJBMS();
dmc.createStatement().executeUpdate("create schema SCHEMA_Patricio");
dmc.createStatement().executeUpdate("create table SCHEMA_Patricio.Patricio (id VARCHAR(255), value INTEGER)");
dmc.commit();
dmc.close();
XAConnection xac3 = dsx.getXAConnection();
Connection conn3 = xac3.getConnection();
Statement st3 = conn3.createStatement();
st3.execute("SET SCHEMA SCHEMA_Patricio");
st3.close();
PreparedStatement ps3 = conn3.prepareStatement("INSERT INTO Patricio VALUES (? , ?)");
ps3.setString(1, "Patricio");
ps3.setInt(2, 3);
ps3.executeUpdate();
System.out.println("Patricio update count " + ps3.getUpdateCount());
ps3.close();
conn3.close();
xac3.close();
// test that an xastart in auto commit mode commits the existing work.(beetle 5178)
XAConnection xac4 = dsx.getXAConnection();
Xid xid4a = new cdsXid(4, (byte) 23, (byte) 76);
Connection conn4 = xac4.getConnection();
System.out.println("conn4 autcommit " + conn4.getAutoCommit());
Statement s4 = conn4.createStatement();
s4.executeUpdate("create table autocommitxastart(i int)");
s4.executeUpdate("insert into autocommitxastart values 1,2,3,4,5");
ResultSet rs4 = s4.executeQuery("select i from autocommitxastart");
rs4.next(); System.out.println("acxs " + rs4.getInt(1));
rs4.next(); System.out.println("acxs " + rs4.getInt(1));
xac4.getXAResource().start(xid4a, XAResource.TMNOFLAGS);
xac4.getXAResource().end(xid4a, XAResource.TMSUCCESS);
try {
rs4.next(); System.out.println("acxs " + rs.getInt(1));
} catch (SQLException sqle) {
System.out.println("autocommitxastart expected " + sqle.getMessage());
}
conn4.setAutoCommit(false);
rs4 = s4.executeQuery("select i from autocommitxastart");
rs4.next(); System.out.println("acxs " + rs4.getInt(1));
rs4.next(); System.out.println("acxs " + rs4.getInt(1));
+ // Get a new xid to begin another transaction.
+ // This should give XAER_OUTSIDE exception because
+ // the resource manager is busy in the local transaction
+ xid4a = new cdsXid(4, (byte) 93, (byte) 103);
try {
xac4.getXAResource().start(xid4a, XAResource.TMNOFLAGS);
} catch (XAException xae) {
showXAException("autocommitxastart expected ", xae);
+ System.out.println("Expected XA error code: " + xae.errorCode);
}
rs4.next(); System.out.println("acxs " + rs4.getInt(1));
rs4.close();
conn4.rollback();
conn4.close();
xac4.close();
// test jira-derby 95 - a NullPointerException was returned when passing
// an incorrect database name (a url in this case) - should now give error XCY00
Connection dmc95 = ij.startJBMS();
String sqls;
try {
testJira95ds( dmc95, "jdbc:derby:mydb" );
} catch (SQLException sqle) {
sqls = sqle.getSQLState();
if (sqls.equals("XCY00"))
System.out.println("; ok - expected exception: " + sqls);
else
System.out.println("; wrong, unexpected exception: " + sqls + " - " + sqle.toString());
} catch (Exception e) {
System.out.println("; wrong, unexpected exception: " + e.toString());
}
try {
testJira95xads( dmc95, "jdbc:derby:wombat" );
} catch (SQLException sqle) {
sqls = sqle.getSQLState();
if (sqls.equals("XCY00"))
System.out.println("; ok - expected exception: " + sqls + "\n");
else
System.out.println("; wrong - unexpected exception: " + sqls + " - " + sqle.toString());
} catch (Exception e) {
System.out.println("; wrong, unexpected exception: " + e.toString());
}
// skip testDSRequestAuthentication for client because of these
// two issues:
// DERBY-1130 : Client should not allow databaseName to be set with
// setConnectionAttributes
// DERBY-1131 : Deprecate Derby DataSource property attributesAsPassword
if (TestUtil.isDerbyNetClientFramework())
return;
testDSRequestAuthentication();
}
/**
* @param s
* @param xar
* @param conn
* @throws SQLException
* @throws XAException
*/
private void testSetIsolationWithStatement(Statement s, XAResource xar, Connection conn) throws SQLException, XAException {
Xid xid;
System.out.println("Issue SQL to change isolation in local transaction");
s.executeUpdate("set current isolation = RR");
printState("SQL to change isolation in local", conn);
xid = new cdsXid(1, (byte) 35, (byte) 47);
xar.start(xid, XAResource.TMNOFLAGS);
printState("1st global(new)", conn);
xar.end(xid, XAResource.TMSUCCESS);
printState("local", conn);
System.out.println("Issue SQL to change isolation in local transaction");
s.executeUpdate("set current isolation = RS");
printState("SQL to change isolation in local", conn);
Xid xid2 = new cdsXid(1, (byte) 93, (byte) 103);
xar.start(xid2, XAResource.TMNOFLAGS);
printState("2nd global(new)", conn);
xar.end(xid2, XAResource.TMSUCCESS);
xar.start(xid, XAResource.TMJOIN);
printState("1st global(existing)", conn);
xar.end(xid, XAResource.TMSUCCESS);
printState("local", conn);
xar.start(xid, XAResource.TMJOIN);
printState("1st global(existing)", conn);
System.out.println("Issue SQL to change isolation in 1st global transaction");
s.executeUpdate("set current isolation = UR");
printState("change isolation of existing 1st global transaction", conn);
xar.end(xid, XAResource.TMSUCCESS);
printState("local", conn);
xar.start(xid2, XAResource.TMJOIN);
printState("2nd global(existing)", conn);
xar.end(xid2, XAResource.TMSUCCESS);
xar.rollback(xid2);
printState("(After 2nd global rollback) local", conn);
xar.rollback(xid);
printState("(After 1st global rollback) local", conn);
}
protected void showXAException(String tag, XAException xae) {
System.out.println(tag + " : XAException - " + xae.getMessage());
}
/**
Create a statement with modified State.
*/
protected Statement createFloatStatementForStateChecking(Connection conn) throws SQLException {
Statement s = internalCreateFloatStatementForStateChecking(conn);
s.setCursorName("StokeNewington");
s.setFetchDirection(ResultSet.FETCH_REVERSE);
s.setFetchSize(444);
s.setMaxFieldSize(713);
s.setMaxRows(19);
showStatementState("Create ", s);
return s;
}
protected Statement internalCreateFloatStatementForStateChecking(Connection conn) throws SQLException {
return conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
}
protected void showStatementState(String when, Statement s) throws SQLException {
System.out.println("Statement State @ " + when);
System.out.println(" getResultSetType() " + rsType(s.getResultSetType()));
System.out.println(" getResultSetConcurrency() " + rsConcurrency(s.getResultSetConcurrency()));
System.out.println(" getFetchDirection() " + rsFetchDirection(s.getFetchDirection()));
System.out.println(" getFetchSize() " + s.getFetchSize());
System.out.println(" getMaxFieldSize() " + s.getMaxFieldSize());
System.out.println(" getMaxRows() " + s.getMaxRows());
}
protected PreparedStatement createFloatStatementForStateChecking(Connection conn, String sql) throws SQLException {
PreparedStatement s = internalCreateFloatStatementForStateChecking(conn, sql);
// Need to make a different cursor name here because of DERBY-1036
// client won't allow duplicate name.
//s.setCursorName("StokeNewington");
s.setCursorName("LondonNW17");
s.setFetchDirection(ResultSet.FETCH_REVERSE);
s.setFetchSize(888);
s.setMaxFieldSize(317);
s.setMaxRows(91);
showStatementState("PS Create ", s);
return s;
}
protected CallableStatement createFloatCallForStateChecking(Connection conn, String sql) throws SQLException {
CallableStatement s = internalCreateFloatCallForStateChecking(conn, sql);
//DERBY-1036 - need a new name
//s.setCursorName("StokeNewington");
s.setCursorName("districtInLondon");
s.setFetchDirection(ResultSet.FETCH_REVERSE);
s.setFetchSize(999);
s.setMaxFieldSize(137);
s.setMaxRows(85);
showStatementState("CS Create ", s);
return s;
}
protected PreparedStatement internalCreateFloatStatementForStateChecking(Connection conn, String sql) throws SQLException {
return conn.prepareStatement(sql, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
}
protected CallableStatement internalCreateFloatCallForStateChecking(Connection conn, String sql) throws SQLException {
return conn.prepareCall(sql, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
}
/**
* Return the Java class and method for the procedure
* for the nested connection test.
* checkDataSource 30 will override.
*/
protected String getNestedMethodName()
{
return "checkDataSource.checkNesConn";
}
static String rsType(int type) {
switch (type) {
case ResultSet.TYPE_FORWARD_ONLY:
return "FORWARD_ONLY";
case ResultSet.TYPE_SCROLL_SENSITIVE:
return "SCROLL_SENSITIVE";
case ResultSet.TYPE_SCROLL_INSENSITIVE:
return "SCROLL_INSENSITIVE";
default:
return "?? TYPE UNKNOWN ??";
}
}
static String rsConcurrency(int type) {
switch (type) {
case ResultSet.CONCUR_READ_ONLY:
return "READ_ONLY";
case ResultSet.CONCUR_UPDATABLE:
return "UPDATEABLE";
default:
return "?? CONCURRENCY UNKNOWN ??";
}
}
static String rsFetchDirection(int type) {
switch (type) {
case ResultSet.FETCH_FORWARD:
return "FORWARD";
case ResultSet.FETCH_REVERSE:
return "REVERSE";
case ResultSet.FETCH_UNKNOWN:
return "UNKNOWN";
default:
return "?? FETCH DIRECTION REALLY UNKNOWN ??";
}
}
private static void checkLocks(Connection conn) throws SQLException {
Statement s = conn.createStatement();
ResultSet rs = s.executeQuery("SELECT XID, sum(cast (LOCKCOUNT AS INT)) FROM SYSCS_DIAG.LOCK_TABLE AS L GROUP BY XID");
System.out.println("LOCK TABLE");
// Don't output actual XID's as they tend for every catalog change
// to the system.
int xact_index = 0;
while (rs.next()) {
// System.out.println(" xid " + rs.getString(1) + " lock count " + rs.getInt(2));
System.out.println(" xid row " + xact_index + " lock count " + rs.getInt(2));
xact_index++;
}
s.close();
System.out.println("END LOCK TABLE");
}
private static void queryOnStatement(String tag, Connection conn, Statement s) throws SQLException {
try {
if (s.getConnection() != conn)
System.out.println(tag + ": mismatched Statement connection");
resultSetQuery(tag, s.executeQuery("select * from ru"));
} catch (SQLException sqle) {
System.out.println(tag + ": " + sqle.toString());
}
}
private static void resultSetQuery(String tag, ResultSet rs) throws SQLException {
String cursorName = rs.getCursorName();
// DERBY-1183 client cursor name is not correct.
// need to truncate the cursor number of the generated name as it might
// not be consistent.
if (hasGetCursorNameBug && cursorName.startsWith("SQL_CUR"))
{
cursorName = cursorName.substring(0,13);
}
System.out.print(tag + ": ru(" + cursorName + ") contents");
SecurityCheck.inspect(rs, "java.sql.ResultSet");
while (rs.next()) {
System.out.print(" {" + rs.getInt(1) + "}");
}
System.out.println("");
rs.close();
}
private void printState(String header, Connection conn) throws SQLException {
System.out.println(header);
getHoldability(conn);
System.out.println(" isolation level " + translateIso(conn.getTransactionIsolation()));
System.out.println(" auto commit " + conn.getAutoCommit());
System.out.println(" read only " + conn.isReadOnly());
}
protected void setHoldability(Connection conn, boolean hold) throws SQLException {
}
protected void getHoldability(Connection conn) throws SQLException {
}
//calling checkConnection - for use in a procedure to get a nested connection.
public static void checkNesConn (String dsName) throws SQLException {
Connection conn = DriverManager.getConnection("jdbc:default:connection");
new checkDataSource().checkConnection(dsName, conn);
}
public void checkConnection(String dsName, Connection conn) throws SQLException {
System.out.println("Running connection checks on " + dsName);
SecurityCheck.inspect(conn, "java.sql.Connection");
SecurityCheck.inspect(conn.getMetaData(), "java.sql.DatabaseMetaData");
//System.out.println(" url " + conn.getMetaData().getURL());
System.out.println(" isolation level " + conn.getTransactionIsolation());
System.out.println(" auto commit " + conn.getAutoCommit());
System.out.println(" read only " + conn.isReadOnly());
// when 4729 is fixed, remove the startsWith() clause
if (dsName.endsWith("DataSource") && !dsName.startsWith("Global"))
System.out.println(" has warnings " + (conn.getWarnings() != null));
Statement s1 = conn.createStatement();
checkStatement(dsName, conn, s1);
checkStatement(dsName, conn, conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY));
Connection c1 = conn.getMetaData().getConnection();
if (c1 != conn)
System.out.println("FAIL incorrect connection object returned for DatabaseMetaData.getConnection()");
// Derby-33 - setTypeMap on connection
try {
conn.setTypeMap(java.util.Collections.EMPTY_MAP);
System.out.println("setTypeMap(EMPTY_MAP) - ok");
} catch (SQLException sqle) {
System.out.println("setTypeMap(EMPTY_MAP) - FAIL " + sqle.getSQLState() + " - " + sqle.getMessage());
}
try {
conn.setTypeMap(null);
System.out.println("setTypeMap(null) - FAIL - should throw exception");
} catch (SQLException sqle) {
System.out.println("setTypeMap(null) - ok " + sqle.getSQLState() + " - " + sqle.getMessage());
}
try {
// a populated map, not implemented
java.util.Map map = new java.util.HashMap();
map.put("name", "class");
conn.setTypeMap(map);
System.out.println("setTypeMap(map) - FAIL - should throw exception");
} catch (SQLException sqle) {
System.out.println("setTypeMap(map) - ok " + sqle.getSQLState() + " - " + sqle.getMessage());
}
checkConnectionPreClose(dsName, conn);
conn.close();
System.out.println("method calls on a closed connection");
try {
conn.close();
System.out.println(dsName + " <closedconn>.close() no error");
} catch (SQLException sqle) {
System.out.println(dsName + " <closedconn>.close() " + sqle.getSQLState() + " - " + sqle.getMessage());
}
try {
conn.createStatement();
System.out.println(dsName + " <closedconn>.createStatement() no error");
} catch (SQLException sqle) {
System.out.println(dsName + " <closedconn>.createStatement() " + sqle.getSQLState() + " - " + sqle.getMessage());
}
try {
s1.execute("values 1");
System.out.println(dsName + " <closedstmt>.execute() no error");
} catch (SQLException sqle) {
System.out.println(dsName + " <closedstmt>.execute() " + sqle.getSQLState() + " - " + sqle.getMessage());
}
}
/**
* Make sure this connection's string is unique (DERBY-243)
*/
protected static void checkToString(Connection conn) throws Exception
{
checkStringFormat(conn);
String str = conn.toString();
if ( conns.containsKey(str))
{
throw new Exception("ERROR: Connection toString() is not unique: "
+ str);
}
conns.put(str, conn);
}
/**
* Check the format of a pooled connection
**/
protected static void checkStringFormat(PooledConnection pc) throws Exception
{
String prefix = checkStringPrefix(pc);
String connstr = pc.toString();
String format = "/" + prefix +
" \\(ID = [0-9]+\\), Physical Connection = " +
"<none>|" + CONNSTRING_FORMAT + "/";
if ( ! p5u.match(format, connstr) )
{
throw new Exception( "Connection.toString() (" + connstr + ") " +
"does not match expected format (" + format + ")");
}
}
/**
* Check the format of the connection string. This is the default test
* to run if this is not a BrokeredConnection class
*/
protected static void checkStringFormat(Connection conn) throws Exception
{
String prefix = checkStringPrefix(conn);
String str = conn.toString();
// See if the connection string matches the format pattern
if ( ! p5u.match("/" + CONNSTRING_FORMAT + "/", str) )
{
throw new Exception( "Connection.toString() (" + str + ") " +
"does not match expected format (" + CONNSTRING_FORMAT + ")");
}
}
/**
* Make sure the connection string starts with the right prefix, which
* is the classname@hashcode.
*
* @return the expected prefix string, this is used in further string
* format checking
*/
protected static String checkStringPrefix(Object conn) throws Exception
{
String connstr = conn.toString();
String prefix = conn.getClass().getName() + "@" + conn.hashCode();
if ( ! connstr.startsWith(prefix) )
{
throw new Exception("Connection class and hash code for " +
"connection string (" + connstr + ") does not match expected " +
"(" + prefix + ")");
}
return prefix;
}
/**
* Clear out and close connections in the connections
* hashtable.
*/
protected static void clearConnections() throws SQLException
{
java.util.Iterator it = conns.values().iterator();
while ( it.hasNext() )
{
Connection conn = (Connection)it.next();
conn.close();
}
conns.clear();
}
/**
* Get connections using ij.startJBMS() and make sure
* they're unique
*/
protected static void checkJBMSToString() throws Exception
{
clearConnections();
// Open ten connections rather than just two to
// try and catch any odd uniqueness bugs. Still
// no guarantee but is better than just two.
int numConnections = 10;
for ( int i = 0 ; i < numConnections ; i++ )
{
Connection conn = ij.startJBMS();
checkToString(conn);
}
// Now close the connections
clearConnections();
}
/**
* Check uniqueness of connection strings coming from a
* DataSouce
*/
protected static void checkToString(DataSource ds) throws Exception
{
clearConnections();
int numConnections = 10;
for ( int i = 0 ; i < numConnections ; i++ )
{
Connection conn = ds.getConnection();
checkToString(conn);
}
clearConnections();
}
/**
* Check uniqueness of strings with a pooled data source.
* We want to check the PooledConnection as well as the
* underlying physical connection.
*/
protected static void checkToString(ConnectionPoolDataSource pds)
throws Exception
{
int numConnections = 10;
// First get a bunch of pooled connections
// and make sure they're all unique
Hashtable pooledConns = new Hashtable();
for ( int i = 0 ; i < numConnections ; i++ )
{
PooledConnection pc = pds.getPooledConnection();
checkStringFormat(pc);
String str = pc.toString();
if ( pooledConns.get(str) != null )
{
throw new Exception("Pooled connection toString " +
"value " + str + " is not unique");
}
pooledConns.put(str, pc);
}
// Now check that connections from each of these
// pooled connections have different string values
Iterator it = pooledConns.values().iterator();
clearConnections();
while ( it.hasNext() )
{
PooledConnection pc = (PooledConnection)it.next();
Connection conn = pc.getConnection();
checkToString(conn);
}
clearConnections();
// Now clear out the pooled connections
it = pooledConns.values().iterator();
while ( it.hasNext() )
{
PooledConnection pc = (PooledConnection)it.next();
pc.close();
}
pooledConns.clear();
}
/**
* Check uniqueness of strings for an XA data source
*/
protected static void checkToString(XADataSource xds) throws Exception
{
int numConnections = 10;
// First get a bunch of pooled connections
// and make sure they're all unique
Hashtable xaConns = new Hashtable();
for ( int i = 0 ; i < numConnections ; i++ )
{
XAConnection xc = xds.getXAConnection();
checkStringFormat(xc);
String str = xc.toString();
if ( xaConns.get(str) != null )
{
throw new Exception("XA connection toString " +
"value " + str + " is not unique");
}
xaConns.put(str, xc);
}
// Now check that connections from each of these
// pooled connections have different string values
Iterator it = xaConns.values().iterator();
clearConnections();
while ( it.hasNext() )
{
XAConnection xc = (XAConnection)it.next();
Connection conn = xc.getConnection();
checkToString(conn);
}
clearConnections();
// Now clear out the pooled connections
it = xaConns.values().iterator();
while ( it.hasNext() )
{
XAConnection xc = (XAConnection)it.next();
xc.close();
}
xaConns.clear();
}
protected void checkConnectionPreClose(String dsName, Connection conn) throws SQLException {
if (dsName.endsWith("DataSource")) {
// see if setting the state is carried over to any future connection from the
// data source object.
try {
conn.setReadOnly(true);
} catch (SQLException sqle) {
// cannot set read-only in an active transaction, & sometimes
// connections are active at this point.
}
}
}
protected void checkStatement(String dsName, Connection conn, Statement s) throws SQLException {
SecurityCheck.inspect(s, "java.sql.Statement");
Connection c1 = s.getConnection();
if (c1 != conn)
System.out.println("FAIL incorrect connection object returned for Statement.getConnection()");
s.addBatch("insert into y values 1");
s.addBatch("insert into y values 2,3");
int[] states = s.executeBatch();
if (states[0] != 1)
System.out.println("FAIL invalid update count for first batch statement");
if (states[1] != 2)
System.out.println("FAIL invalid update count for second batch statement");
ResultSet rs = s.executeQuery("VALUES 1");
if (rs.getStatement() != s)
System.out.println(dsName + " FAIL incorrect Statement object returned for ResultSet.getStatement");
rs.close();
s.close();
}
private static void testDSRequestAuthentication() throws SQLException {
EmbeddedDataSource ds = new EmbeddedDataSource();
System.out.println("DataSource - EMPTY");
dsConnectionRequests(ds);
System.out.println("DataSource - connectionAttributes=databaseName=wombat");
ds.setConnectionAttributes("databaseName=wombat");
dsConnectionRequests(ds);
ds.setConnectionAttributes(null);
System.out.println("DataSource - attributesAsPassword=true");
ds.setAttributesAsPassword(true);
dsConnectionRequests(ds);
ds.setAttributesAsPassword(false);
System.out.println("DataSource - attributesAsPassword=true, connectionAttributes=databaseName=kangaroo");
ds.setAttributesAsPassword(true);
ds.setConnectionAttributes("databaseName=kangaroo");
dsConnectionRequests(ds);
ds.setAttributesAsPassword(false);
ds.setConnectionAttributes(null);
System.out.println("Enable Authentication");
ds.setDatabaseName("wombat");
Connection cadmin = ds.getConnection();
CallableStatement cs = cadmin.prepareCall("CALL SYSCS_UTIL.SYSCS_SET_DATABASE_PROPERTY(?, ?)");
cs.setString(1, "derby.user.fred");
cs.setString(2, "wilma");
cs.execute();
cs.setString(1, "derby.authentication.provider");
cs.setString(2, "BUILTIN");
cs.execute();
cs.setString(1, "derby.connection.requireAuthentication");
cs.setString(2, "true");
cs.execute();
cs.close();
cadmin.close();
ds.setShutdownDatabase("shutdown");
try {
ds.getConnection();
} catch (SQLException sqle) {
System.out.println(sqle.getSQLState() + ":" + sqle.getMessage() );
}
ds.setDatabaseName(null);
ds.setShutdownDatabase(null);
System.out.println("AUTHENTICATION NOW ENABLED");
System.out.println("DataSource - attributesAsPassword=true");
ds.setAttributesAsPassword(true);
dsConnectionRequests(ds);
ds.setAttributesAsPassword(false);
// ensure the DS property password is not treated as a set of attributes.
System.out.println("DataSource - attributesAsPassword=true, user=fred, password=databaseName=wombat;password=wilma");
ds.setAttributesAsPassword(true);
ds.setUser("fred");
ds.setPassword("databaseName=wombat;password=wilma");
dsConnectionRequests(ds);
ds.setAttributesAsPassword(false);
ds.setUser(null);
ds.setPassword(null);
ds = null;
// now with ConnectionPoolDataSource
EmbeddedConnectionPoolDataSource cpds = new EmbeddedConnectionPoolDataSource();
System.out.println("ConnectionPoolDataSource - EMPTY");
dsConnectionRequests((ConnectionPoolDataSource)cpds);
System.out.println("ConnectionPoolDataSource - connectionAttributes=databaseName=wombat");
cpds.setConnectionAttributes("databaseName=wombat");
dsConnectionRequests((ConnectionPoolDataSource)cpds);
cpds.setConnectionAttributes(null);
System.out.println("ConnectionPoolDataSource - attributesAsPassword=true");
cpds.setAttributesAsPassword(true);
dsConnectionRequests((ConnectionPoolDataSource)cpds);
cpds.setAttributesAsPassword(false);
// ensure the DS property password is not treated as a set of attributes.
System.out.println("ConnectionPoolDataSource - attributesAsPassword=true, user=fred, password=databaseName=wombat;password=wilma");
cpds.setAttributesAsPassword(true);
cpds.setUser("fred");
cpds.setPassword("databaseName=wombat;password=wilma");
dsConnectionRequests((ConnectionPoolDataSource)cpds);
cpds.setAttributesAsPassword(false);
cpds.setUser(null);
cpds.setPassword(null);
cpds = null;
// now with XADataSource
EmbeddedXADataSource xads = new EmbeddedXADataSource();
System.out.println("XADataSource - EMPTY");
dsConnectionRequests((XADataSource) xads);
System.out.println("XADataSource - databaseName=wombat");
xads.setDatabaseName("wombat");
dsConnectionRequests((XADataSource) xads);
xads.setDatabaseName(null);
System.out.println("XADataSource - connectionAttributes=databaseName=wombat");
xads.setConnectionAttributes("databaseName=wombat");
dsConnectionRequests((XADataSource) xads);
xads.setConnectionAttributes(null);
System.out.println("XADataSource - attributesAsPassword=true");
xads.setAttributesAsPassword(true);
dsConnectionRequests((XADataSource) xads);
xads.setAttributesAsPassword(false);
System.out.println("XADataSource - databaseName=wombat, attributesAsPassword=true");
xads.setDatabaseName("wombat");
xads.setAttributesAsPassword(true);
dsConnectionRequests((XADataSource) xads);
xads.setAttributesAsPassword(false);
xads.setDatabaseName(null);
}
private static void dsConnectionRequests(DataSource ds) {
SecurityCheck.inspect(ds, "javax.sql.DataSource");
try {
Connection c1 = ds.getConnection();
System.out.println(" getConnection() - OK");
c1.close();
} catch (SQLException sqle) {
System.out.println(" getConnection() - " + sqle.getSQLState() + ":" + sqle.getMessage() );
}
try {
Connection c1 = ds.getConnection(null, null);
System.out.println(" getConnection(null, null) - OK");
c1.close();
} catch (SQLException sqle) {
System.out.println(" getConnection(null, null) - " + sqle.getSQLState() + ":" + sqle.getMessage() );
}
try {
Connection c1 = ds.getConnection("fred", null);
System.out.println(" getConnection(fred, null) - OK");
c1.close();
} catch (SQLException sqle) {
System.out.println(" getConnection(fred, null) - " + sqle.getSQLState() + ":" + sqle.getMessage() );
}
try {
Connection c1 = ds.getConnection("fred", "wilma");
System.out.println(" getConnection(fred, wilma) - OK");
c1.close();
} catch (SQLException sqle) {
System.out.println(" getConnection(fred, wilma) - " + sqle.getSQLState() + ":" + sqle.getMessage() );
}
try {
Connection c1 = ds.getConnection(null, "wilma");
System.out.println(" getConnection(null, wilma) - OK");
c1.close();
} catch (SQLException sqle) {
System.out.println(" getConnection(null, wilma) - " + sqle.getSQLState() + ":" + sqle.getMessage() );
}
try {
Connection c1 = ds.getConnection(null, "databaseName=wombat");
System.out.println(" getConnection(null, databaseName=wombat) - OK");
c1.close();
} catch (SQLException sqle) {
System.out.println(" getConnection(null, databaseName=wombat) - " + sqle.getSQLState() + ":" + sqle.getMessage() );
}
try {
Connection c1 = ds.getConnection("fred", "databaseName=wombat");
System.out.println(" getConnection(fred, databaseName=wombat) - OK");
c1.close();
} catch (SQLException sqle) {
System.out.println(" getConnection(fred, databaseName=wombat) - " + sqle.getSQLState() + ":" + sqle.getMessage() );
}
try {
Connection c1 = ds.getConnection("fred", "databaseName=wombat;password=wilma");
System.out.println(" getConnection(fred, databaseName=wombat;password=wilma) - OK");
c1.close();
} catch (SQLException sqle) {
System.out.println(" getConnection(fred, databaseName=wombat;password=wilma) - " + sqle.getSQLState() + ":" + sqle.getMessage() );
}
try {
Connection c1 = ds.getConnection("fred", "databaseName=wombat;password=betty");
System.out.println(" getConnection(fred, databaseName=wombat;password=betty) - OK");
c1.close();
} catch (SQLException sqle) {
System.out.println(" getConnection(fred, databaseName=wombat;password=betty) - " + sqle.getSQLState() + ":" + sqle.getMessage() );
}
}
private static void dsConnectionRequests(ConnectionPoolDataSource ds) {
try {
PooledConnection pc = ds.getPooledConnection();
System.out.println(" getPooledConnection() - OK");
Connection c1 = pc.getConnection();
c1.close();
pc.close();
} catch (SQLException sqle) {
System.out.println(" getPooledConnection() - " + sqle.getSQLState() + ":" + sqle.getMessage() );
}
try {
PooledConnection pc = ds.getPooledConnection(null, null);
System.out.println(" getPooledConnection(null, null) - OK");
Connection c1 = pc.getConnection();
c1.close();
} catch (SQLException sqle) {
System.out.println(" getPooledConnection(null, null) - " + sqle.getSQLState() + ":" + sqle.getMessage() );
}
try {
PooledConnection pc = ds.getPooledConnection("fred", null);
System.out.println(" getPooledConnection(fred, null) - OK");
Connection c1 = pc.getConnection();
c1.close();
pc.close();
} catch (SQLException sqle) {
System.out.println(" getPooledConnection(fred, null) - " + sqle.getSQLState() + ":" + sqle.getMessage() );
}
try {
PooledConnection pc = ds.getPooledConnection("fred", "wilma");
System.out.println(" getPooledConnection(fred, wilma) - OK");
Connection c1 = pc.getConnection();
c1.close();
pc.close();
} catch (SQLException sqle) {
System.out.println(" getPooledConnection(fred, wilma) - " + sqle.getSQLState() + ":" + sqle.getMessage() );
}
try {
PooledConnection pc = ds.getPooledConnection(null, "wilma");
System.out.println(" getPooledConnection(null, wilma) - OK");
Connection c1 = pc.getConnection();
c1.close();
pc.close();
} catch (SQLException sqle) {
System.out.println(" getPooledConnection(null, wilma) - " + sqle.getSQLState() + ":" + sqle.getMessage() );
}
try {
PooledConnection pc = ds.getPooledConnection(null, "databaseName=wombat");
System.out.println(" getPooledConnection(null, databaseName=wombat) - OK");
Connection c1 = pc.getConnection();
c1.close();
pc.close();
} catch (SQLException sqle) {
System.out.println(" getPooledConnection(null, databaseName=wombat) - " + sqle.getSQLState() + ":" + sqle.getMessage() );
}
try {
PooledConnection pc = ds.getPooledConnection("fred", "databaseName=wombat");
System.out.println(" getPooledConnection(fred, databaseName=wombat) - OK");
Connection c1 = pc.getConnection();
c1.close();
pc.close();
} catch (SQLException sqle) {
System.out.println(" getPooledConnection(fred, databaseName=wombat) - " + sqle.getSQLState() + ":" + sqle.getMessage() );
}
try {
PooledConnection pc = ds.getPooledConnection("fred", "databaseName=wombat;password=wilma");
System.out.println(" getPooledConnection(fred, databaseName=wombat;password=wilma) - OK");
Connection c1 = pc.getConnection();
c1.close();
pc.close();
} catch (SQLException sqle) {
System.out.println(" getPooledConnection(fred, databaseName=wombat;password=wilma) - " + sqle.getSQLState() + ":" + sqle.getMessage() );
}
try {
PooledConnection pc = ds.getPooledConnection("fred", "databaseName=wombat;password=betty");
System.out.println(" getPooledConnection(fred, databaseName=wombat;password=betty) - OK");
Connection c1 = pc.getConnection();
c1.close();
pc.close();
} catch (SQLException sqle) {
System.out.println(" getPooledConnection(fred, databaseName=wombat;password=betty) - " + sqle.getSQLState() + ":" + sqle.getMessage() );
}
}
private static void dsConnectionRequests(XADataSource ds) {
try {
XAConnection xc = ds.getXAConnection();
System.out.println(" getXAConnection() - OK");
Connection c1 = xc.getConnection();
c1.close();
xc.close();
} catch (SQLException sqle) {
System.out.println(" getXAConnection() - " + sqle.getSQLState() + ":" + sqle.getMessage() );
}
try {
XAConnection xc = ds.getXAConnection(null, null);
System.out.println(" getXAConnection(null, null) - OK");
Connection c1 = xc.getConnection();
c1.close();
} catch (SQLException sqle) {
System.out.println(" getXAConnection(null, null) - " + sqle.getSQLState() + ":" + sqle.getMessage() );
}
try {
XAConnection xc = ds.getXAConnection("fred", null);
System.out.println(" getXAConnection(fred, null) - OK");
Connection c1 = xc.getConnection();
c1.close();
xc.close();
} catch (SQLException sqle) {
System.out.println(" getXAConnection(fred, null) - " + sqle.getSQLState() + ":" + sqle.getMessage() );
}
try {
XAConnection xc = ds.getXAConnection("fred", "wilma");
System.out.println(" getXAConnection(fred, wilma) - OK");
Connection c1 = xc.getConnection();
c1.close();
xc.close();
} catch (SQLException sqle) {
System.out.println(" getXAConnection(fred, wilma) - " + sqle.getSQLState() + ":" + sqle.getMessage() );
}
try {
XAConnection xc = ds.getXAConnection(null, "wilma");
System.out.println(" getXAConnection(null, wilma) - OK");
Connection c1 = xc.getConnection();
c1.close();
xc.close();
} catch (SQLException sqle) {
System.out.println(" getXAConnection(null, wilma) - " + sqle.getSQLState() + ":" + sqle.getMessage() );
}
try {
XAConnection xc = ds.getXAConnection(null, "databaseName=wombat");
System.out.println(" getXAConnection(null, databaseName=wombat) - OK");
Connection c1 = xc.getConnection();
c1.close();
xc.close();
} catch (SQLException sqle) {
System.out.println(" getXAConnection(null, databaseName=wombat) - " + sqle.getSQLState() + ":" + sqle.getMessage() );
}
try {
XAConnection xc = ds.getXAConnection("fred", "databaseName=wombat");
System.out.println(" getXAConnection(fred, databaseName=wombat) - OK");
Connection c1 = xc.getConnection();
c1.close();
xc.close();
} catch (SQLException sqle) {
System.out.println(" getXAConnection(fred, databaseName=wombat) - " + sqle.getSQLState() + ":" + sqle.getMessage() );
}
try {
XAConnection xc = ds.getXAConnection("fred", "databaseName=wombat;password=wilma");
System.out.println(" getXAConnection(fred, databaseName=wombat;password=wilma) - OK");
Connection c1 = xc.getConnection();
c1.close();
xc.close();
} catch (SQLException sqle) {
System.out.println(" getXAConnection(fred, databaseName=wombat;password=wilma) - " + sqle.getSQLState() + ":" + sqle.getMessage() );
}
try {
XAConnection xc = ds.getXAConnection("fred", "databaseName=wombat;password=betty");
System.out.println(" getXAConnection(fred, databaseName=wombat;password=betty) - OK");
Connection c1 = xc.getConnection();
c1.close();
xc.close();
} catch (SQLException sqle) {
System.out.println(" getXAConnection(fred, databaseName=wombat;password=betty) - " + sqle.getSQLState() + ":" + sqle.getMessage() );
}
}
protected Xid getXid(int xid, byte b1, byte b2) {
return new cdsXid(xid, b1, b2);
}
public static String translateIso(int iso)
{
switch(iso)
{
case Connection.TRANSACTION_READ_COMMITTED: return "READ_COMMITTED";
case Connection.TRANSACTION_SERIALIZABLE: return "SERIALIZABLE";
case Connection.TRANSACTION_REPEATABLE_READ: return "REPEATABLE_READ";
case Connection.TRANSACTION_READ_UNCOMMITTED: return "READ_UNCOMMITTED";
}
return "unknown";
}
/**
When a connection is being pooled, the underlying JDBC embedded
connection object is re-used. As each application gets a new
Connection object, that is really a wrapper around the old connection
it should reset any connection spoecific state on the embedded connection
object.
*/
private static void testPoolReset(String type, PooledConnection pc) throws SQLException
{
System.out.println("Start testPoolReset " + type);
testPoolResetWork("C", pc.getConnection());
testPoolResetWork("", pc.getConnection());
testPoolResetWork("D", pc.getConnection());
pc.close();
System.out.println("End testPoolReset " + type);
}
private static void testPoolResetWork(String tableAction, Connection conn) throws SQLException
{
Statement s = conn.createStatement();
if (tableAction.equals("C"))
{
s.execute("CREATE TABLE testPoolResetWork (id int generated always as identity, name varchar(25))");
}
ResultSet rs = s.executeQuery("VALUES IDENTITY_VAL_LOCAL()");
rs.next();
String val = rs.getString(1);
if (!rs.wasNull() || (val != null))
System.out.println("FAIL - initial call to IDENTITY_VAL_LOCAL is not NULL!" + val);
rs.close();
s.executeUpdate("INSERT INTO testPoolResetWork(name) values ('derby-222')");
rs = s.executeQuery("VALUES IDENTITY_VAL_LOCAL()");
rs.next();
val = rs.getString(1);
System.out.println("IDENTITY_VAL_LOCAL=" + val);
rs.close();
if (tableAction.equals("D"))
{
s.execute("DROP TABLE testPoolResetWork");
}
s.close();
conn.close();
}
public void testJira95ds(Connection conn, String dbName) throws SQLException
{
System.out.print("\ntesting jira 95 for DataSource");
EmbeddedDataSource ds = new EmbeddedDataSource();
ds.setDatabaseName( dbName);
Connection conn1 = ds.getConnection();
conn1.close();
}
public void testJira95xads(Connection conn, String dbName) throws SQLException
{
System.out.print("testing jira 95 for XADataSource");
EmbeddedXADataSource dxs = new EmbeddedXADataSource();
dxs.setDatabaseName(dbName);
Connection conn2 = dxs.getXAConnection().getConnection();
conn2.close();
}
}
class cdsXid implements Xid, Serializable
{
private static final long serialVersionUID = 64467338100036L;
private final int format_id;
private byte[] global_id;
private byte[] branch_id;
cdsXid(int xid, byte b1, byte b2)
{
format_id = xid;
global_id = new byte[Xid.MAXGTRIDSIZE];
branch_id = new byte[Xid.MAXBQUALSIZE];
for (int i = 0; i < global_id.length; i++) {
global_id[i] = b1;
}
for (int i = 0; i < branch_id.length; i++) {
branch_id[i] = b2;
}
}
/**
* Obtain the format id part of the Xid.
* <p>
*
* @return Format identifier. O means the OSI CCR format.
**/
public int getFormatId()
{
return(format_id);
}
/**
* Obtain the global transaction identifier part of XID as an array of
* bytes.
* <p>
*
* @return A byte array containing the global transaction identifier.
**/
public byte[] getGlobalTransactionId()
{
return(global_id);
}
/**
* Obtain the transaction branch qualifier part of the Xid in a byte array.
* <p>
*
* @return A byte array containing the branch qualifier of the transaction.
**/
public byte[] getBranchQualifier()
{
return(branch_id);
}
}
class EventCatcher implements ConnectionEventListener
{
private final int catcher;
EventCatcher(int which) {
catcher=which;
}
// ConnectionEventListener methods
public void connectionClosed(ConnectionEvent event)
{
System.out.print("EVENT("+catcher+"):connectionClosed");
SQLException sqle = event.getSQLException();
if (sqle != null)
System.out.print(" SQLSTATE=" + sqle.getSQLState());
System.out.println("");
}
public void connectionErrorOccurred(ConnectionEvent event)
{
System.out.print("EVENT("+catcher+"):connectionErrorOccurred");
SQLException sqle = event.getSQLException();
if (sqle != null)
System.out.print(" SQLSTATE=" + sqle.getSQLState());
System.out.println("");
}
}
| false | true | protected void runTest(String[] args) throws Exception {
// Check the returned type of the JDBC Connections.
ij.getPropertyArg(args);
Connection dmc = ij.startJBMS();
dmc.createStatement().executeUpdate("create table y(i int)");
dmc.createStatement().executeUpdate(
"create procedure checkConn2(in dsname varchar(20)) " +
"parameter style java language java modifies SQL DATA " +
"external name 'org.apache.derbyTesting.functionTests.tests.jdbcapi." +
this.getNestedMethodName() +
"'");
CallableStatement cs = dmc.prepareCall("call checkConn2(?)");
cs.setString(1,"Nested");
cs.execute();
checkConnection("DriverManager ", dmc);
if (testConnectionToString)
checkJBMSToString();
Properties attrs = new Properties();
attrs.setProperty("databaseName", "wombat");
DataSource dscs = TestUtil.getDataSource(attrs);
if (testConnectionToString)
checkToString(dscs);
DataSource ds = dscs;
checkConnection("DataSource", ds.getConnection());
DataSource dssimple = null;
if (testSimpleDataSource)
{
dssimple = TestUtil.getSimpleDataSource(attrs);
ds = dssimple;
checkConnection("SimpleDataSource", ds.getConnection());
}
ConnectionPoolDataSource dsp = TestUtil.getConnectionPoolDataSource(attrs);
if (testConnectionToString)
checkToString(dsp);
PooledConnection pc = dsp.getPooledConnection();
SecurityCheck.inspect(pc, "javax.sql.PooledConnection");
pc.addConnectionEventListener(new EventCatcher(1));
checkConnection("ConnectionPoolDataSource", pc.getConnection());
checkConnection("ConnectionPoolDataSource", pc.getConnection());
// BUG 4471 - check outstanding updates are rolled back.
Connection c1 = pc.getConnection();
Statement s = c1.createStatement();
s.executeUpdate("create table t (i int)");
s.executeUpdate("insert into t values(1)");
c1.setAutoCommit(false);
// this update should be rolled back
s.executeUpdate("insert into t values(2)");
if (needRollbackBeforePCGetConnection)
c1.rollback();
c1 = pc.getConnection();
ResultSet rs = c1.createStatement().executeQuery("select count(*) from t");
rs.next();
int count = rs.getInt(1);
System.out.println(count == 1 ? "Changes rolled back OK in auto closed pooled connection" :
("FAIL changes committed in in auto closed pooled connection - " + count));
c1.close();
// check connection objects are closed once connection is closed
try {
rs.next();
System.out.println("FAIL - ResultSet is open for a closed connection obtained from PooledConnection");
} catch (SQLException sqle) {
System.out.println("expected " + sqle.toString());
}
try {
s.executeUpdate("update t set i = 1");
System.out.println("FAIL - Statement is open for a closed connection obtained from PooledConnection");
} catch (SQLException sqle) {
System.out.println("expected " + sqle.toString());
}
pc.close();
pc = null;
testPoolReset("ConnectionPoolDataSource", dsp.getPooledConnection());
XADataSource dsx = TestUtil.getXADataSource(attrs);
if (testConnectionToString)
checkToString(dsx);
XAConnection xac = dsx.getXAConnection();
SecurityCheck.inspect(xac, "javax.sql.XAConnection");
xac.addConnectionEventListener(new EventCatcher(3));
checkConnection("XADataSource", xac.getConnection());
// BUG 4471 - check outstanding updates are rolled back wi XAConnection.
c1 = xac.getConnection();
s = c1.createStatement();
s.executeUpdate("insert into t values(1)");
c1.setAutoCommit(false);
// this update should be rolled back
s.executeUpdate("insert into t values(2)");
if (needRollbackBeforePCGetConnection)
c1.rollback();
c1 = xac.getConnection();
rs = c1.createStatement().executeQuery("select count(*) from t");
rs.next();
count = rs.getInt(1);
rs.close();
System.out.println(count == 2 ? "Changes rolled back OK in auto closed local XAConnection" :
("FAIL changes committed in in auto closed pooled connection - " + count));
c1.close();
xac.close();
xac = null;
testPoolReset("XADataSource", dsx.getXAConnection());
try {
TestUtil.getConnection("","shutdown=true");
} catch (SQLException sqle) {
JDBCDisplayUtil.ShowSQLException(System.out, sqle);
}
dmc = ij.startJBMS();
cs = dmc.prepareCall("call checkConn2(?)");
SecurityCheck.inspect(cs, "java.sql.CallableStatement");
cs.setString(1,"Nested");
cs.execute();
checkConnection("DriverManager ", dmc);
// reset ds back to the Regular DataSource
ds = dscs;
checkConnection("DataSource", ds.getConnection());
// and back to EmbeddedSimpleDataSource
if(TestUtil.isEmbeddedFramework())
{
// JSR169 (SimpleDataSource) is only available on embedded.
ds = dssimple;
checkConnection("EmbeddedSimpleDataSource", dssimple.getConnection());
}
pc = dsp.getPooledConnection();
pc.addConnectionEventListener(new EventCatcher(2));
checkConnection("ConnectionPoolDataSource", pc.getConnection());
checkConnection("ConnectionPoolDataSource", pc.getConnection());
// test "local" XAConnections
xac = dsx.getXAConnection();
xac.addConnectionEventListener(new EventCatcher(4));
checkConnection("XADataSource", xac.getConnection());
checkConnection("XADataSource", xac.getConnection());
xac.close();
// test "global" XAConnections
xac = dsx.getXAConnection();
xac.addConnectionEventListener(new EventCatcher(5));
XAResource xar = xac.getXAResource();
SecurityCheck.inspect(xar, "javax.transaction.xa.XAResource");
Xid xid = new cdsXid(1, (byte) 35, (byte) 47);
xar.start(xid, XAResource.TMNOFLAGS);
Connection xacc = xac.getConnection();
xacc.close();
checkConnection("Global XADataSource", xac.getConnection());
checkConnection("Global XADataSource", xac.getConnection());
xar.end(xid, XAResource.TMSUCCESS);
checkConnection("Switch to local XADataSource", xac.getConnection());
checkConnection("Switch to local XADataSource", xac.getConnection());
Connection backtoGlobal = xac.getConnection();
xar.start(xid, XAResource.TMJOIN);
checkConnection("Switch to global XADataSource", backtoGlobal);
checkConnection("Switch to global XADataSource", xac.getConnection());
xar.end(xid, XAResource.TMSUCCESS);
xar.commit(xid, true);
xac.close();
// now some explicit tests for how connection state behaves
// when switching between global transactions and local
// and setting connection state.
// some of this is already tested in simpleDataSource and checkDataSource
// but I want to make sure I cover all situations. (djd)
xac = dsx.getXAConnection();
xac.addConnectionEventListener(new EventCatcher(6));
xar = xac.getXAResource();
xid = new cdsXid(1, (byte) 93, (byte) 103);
// series 1 - Single connection object
Connection cs1 = xac.getConnection();
printState("initial local", cs1);
xar.start(xid, XAResource.TMNOFLAGS);
printState("initial X1", cs1);
cs1.setTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED);
cs1.setReadOnly(true);
setHoldability(cs1, false);
printState("modified X1", cs1);
xar.end(xid, XAResource.TMSUCCESS);
// the underlying local transaction/connection must pick up the
// state of the Connection handle cs1
printState("modified local", cs1);
cs1.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
cs1.setReadOnly(false);
setHoldability(cs1, false);
printState("reset local", cs1);
// now re-join the transaction, should pick up the read-only
// and isolation level from the transaction,
// holdability remains that of this handle.
xar.start(xid, XAResource.TMJOIN);
// DERBY-1148
if (isolationSetProperlyOnJoin)
printState("re-join X1", cs1);
xar.end(xid, XAResource.TMSUCCESS);
// should be the same as the reset local
printState("back to local (same as reset)", cs1);
cs1.setTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED);
cs1.setReadOnly(true);
setHoldability(cs1, true);
cs1.close();
cs1 = xac.getConnection();
printState("new handle - local ", cs1);
cs1.close();
xar.start(xid, XAResource.TMJOIN);
cs1 = xac.getConnection();
// DERBY-1148
if (isolationSetProperlyOnJoin)
printState("re-join with new handle X1", cs1);
cs1.close();
xar.end(xid, XAResource.TMSUCCESS);
// now get a connection (attached to a local)
// attach to the global and commit it.
// state should be that of the local after the commit.
cs1 = xac.getConnection();
cs1.setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ);
printState("pre-X1 commit - local", cs1);
xar.start(xid, XAResource.TMJOIN);
// DERBY-1148
if (isolationSetProperlyOnJoin)
printState("pre-X1 commit - X1", cs1);
xar.end(xid, XAResource.TMSUCCESS);
printState("post-X1 end - local", cs1);
xar.commit(xid, true);
printState("post-X1 commit - local", cs1);
cs1.close();
//Derby-421 Setting isolation level with SQL was not getting handled correctly
System.out.println("Some more isolation testing using SQL and JDBC api");
cs1 = xac.getConnection();
s = cs1.createStatement();
printState("initial local", cs1);
System.out.println("Issue setTransactionIsolation in local transaction");
cs1.setTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED);
printState("setTransactionIsolation in local", cs1);
if (canSetIsolationWithStatement)
testSetIsolationWithStatement(s, xar, cs1);
// now check re-use of *Statement objects across local/global connections.
System.out.println("TESTING RE_USE OF STATEMENT OBJECTS");
cs1 = xac.getConnection();
// ensure read locks stay around until end-of transaction
cs1.setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ);
cs1.setAutoCommit(false);
checkLocks(cs1);
Statement sru1 = cs1.createStatement();
sru1.setCursorName("SN1");
sru1.executeUpdate("create table ru(i int)");
sru1.executeUpdate("insert into ru values 1,2,3");
Statement sruBatch = cs1.createStatement();
Statement sruState = createFloatStatementForStateChecking(cs1);
PreparedStatement psruState = createFloatStatementForStateChecking(cs1, "select i from ru where i = ?");
CallableStatement csruState = createFloatCallForStateChecking(cs1, "CALL SYSCS_UTIL.SYSCS_SET_DATABASE_PROPERTY(?,?)");
PreparedStatement psParams = cs1.prepareStatement("select * from ru where i > ?");
psParams.setCursorName("params");
psParams.setInt(1, 2);
resultSetQuery("Params-local-1", psParams.executeQuery());
sruBatch.addBatch("insert into ru values 4");
queryOnStatement("sru1-local-1", cs1, sru1);
cs1.commit(); // need to commit to switch to an global connection;
xid = new cdsXid(1, (byte) 103, (byte) 119);
xar.start(xid, XAResource.TMNOFLAGS); // simple case - underlying connection is re-used for global.
System.out.println("Expecting downgrade because global transaction sru1-global-2 is using a statement with holdability true");
queryOnStatement("sru1-global-2", cs1, sru1);
sruBatch.addBatch("insert into ru values 5");
Statement sru2 = cs1.createStatement();
sru2.setCursorName("OAK2");
queryOnStatement("sru2-global-3", cs1, sru2);
System.out.println("Expecting downgrade because global transaction sru1-global-4 is using a statement with holdability true");
queryOnStatement("sru1-global-4", cs1, sru1);
showStatementState("GLOBAL ", sruState);
showStatementState("PS GLOBAL ", psruState);
showStatementState("CS GLOBAL ", csruState);
resultSetQuery("Params-global-1", psParams.executeQuery());
xar.end(xid, XAResource.TMSUCCESS);
// now a new underlying connection is created
queryOnStatement("sru1-local-5", cs1, sru1);
queryOnStatement("sru2-local-6", cs1, sru2);
sruBatch.addBatch("insert into ru values 6,7");
Statement sru3 = cs1.createStatement();
sru3.setCursorName("SF3");
queryOnStatement("sru3-local-7", cs1, sru3);
// Two transactions should hold locks (global and the current XA);
showStatementState("LOCAL ", sruState);
showStatementState("PS LOCAL ", psruState);
showStatementState("CS LOCAL ", csruState);
resultSetQuery("Params-local-2", psParams.executeQuery());
checkLocks(cs1);
cs1.commit();
// attach the XA transaction to another connection and see what happens
XAConnection xac2 = dsx.getXAConnection();
xac2.addConnectionEventListener(new EventCatcher(5));
XAResource xar2 = xac2.getXAResource();
xar2.start(xid, XAResource.TMJOIN);
Connection cs2 = xac2.getConnection();
// these statements were generated by cs1 and thus are still
// in a local connection.
queryOnStatement("sru1-local-8", cs1, sru1);
queryOnStatement("sru2-local-9", cs1, sru2);
queryOnStatement("sru3-local-10", cs1, sru3);
sruBatch.addBatch("insert into ru values 8");
showStatementState("LOCAL 2 ", sruState);
showStatementState("PS LOCAL 2 ", psruState);
showStatementState("CS LOCAL 2", csruState);
checkLocks(cs1);
int[] updateCounts = sruBatch.executeBatch();
System.out.print("sruBatch update counts :");
for (int i = 0; i < updateCounts.length; i++) {
System.out.print(" " + updateCounts[i] + " ");
}
System.out.println(":");
queryOnStatement("sruBatch", cs1, sruBatch);
xar2.end(xid, XAResource.TMSUCCESS);
xac2.close();
// allow close on already closed XAConnection
xac2.close();
xac2.addConnectionEventListener(null);
xac2.removeConnectionEventListener(null);
// test methods against a closed XAConnection and its resource
try {
xac2.getXAResource();
} catch (SQLException sqle) {
System.out.println("XAConnection.getXAResource : " + sqle.getMessage());
}
try {
xac2.getConnection();
} catch (SQLException sqle) {
System.out.println("XAConnection.getConnection : " + sqle.getMessage());
}
try {
xar2.start(xid, XAResource.TMJOIN);
} catch (XAException xae) {
showXAException("XAResource.start", xae);
}
try {
xar2.end(xid, XAResource.TMJOIN);
} catch (XAException xae) {
showXAException("XAResource.end", xae);
}
try {
xar2.commit(xid, true);
} catch (XAException xae) {
showXAException("XAResource.commit", xae);
}
try {
xar2.prepare(xid);
} catch (XAException xae) {
showXAException("XAResource.prepare", xae);
}
try {
xar2.recover(0);
} catch (XAException xae) {
showXAException("XAResource.recover", xae);
}
try {
xar2.prepare(xid);
} catch (XAException xae) {
showXAException("XAResource.prepare", xae);
}
try {
xar2.isSameRM(xar2);
} catch (XAException xae) {
showXAException("XAResource.isSameRM", xae);
}
// Patricio (on the forum) one was having an issue with set schema not working in an XA connection.
dmc = ij.startJBMS();
dmc.createStatement().executeUpdate("create schema SCHEMA_Patricio");
dmc.createStatement().executeUpdate("create table SCHEMA_Patricio.Patricio (id VARCHAR(255), value INTEGER)");
dmc.commit();
dmc.close();
XAConnection xac3 = dsx.getXAConnection();
Connection conn3 = xac3.getConnection();
Statement st3 = conn3.createStatement();
st3.execute("SET SCHEMA SCHEMA_Patricio");
st3.close();
PreparedStatement ps3 = conn3.prepareStatement("INSERT INTO Patricio VALUES (? , ?)");
ps3.setString(1, "Patricio");
ps3.setInt(2, 3);
ps3.executeUpdate();
System.out.println("Patricio update count " + ps3.getUpdateCount());
ps3.close();
conn3.close();
xac3.close();
// test that an xastart in auto commit mode commits the existing work.(beetle 5178)
XAConnection xac4 = dsx.getXAConnection();
Xid xid4a = new cdsXid(4, (byte) 23, (byte) 76);
Connection conn4 = xac4.getConnection();
System.out.println("conn4 autcommit " + conn4.getAutoCommit());
Statement s4 = conn4.createStatement();
s4.executeUpdate("create table autocommitxastart(i int)");
s4.executeUpdate("insert into autocommitxastart values 1,2,3,4,5");
ResultSet rs4 = s4.executeQuery("select i from autocommitxastart");
rs4.next(); System.out.println("acxs " + rs4.getInt(1));
rs4.next(); System.out.println("acxs " + rs4.getInt(1));
xac4.getXAResource().start(xid4a, XAResource.TMNOFLAGS);
xac4.getXAResource().end(xid4a, XAResource.TMSUCCESS);
try {
rs4.next(); System.out.println("acxs " + rs.getInt(1));
} catch (SQLException sqle) {
System.out.println("autocommitxastart expected " + sqle.getMessage());
}
conn4.setAutoCommit(false);
rs4 = s4.executeQuery("select i from autocommitxastart");
rs4.next(); System.out.println("acxs " + rs4.getInt(1));
rs4.next(); System.out.println("acxs " + rs4.getInt(1));
try {
xac4.getXAResource().start(xid4a, XAResource.TMNOFLAGS);
} catch (XAException xae) {
showXAException("autocommitxastart expected ", xae);
}
rs4.next(); System.out.println("acxs " + rs4.getInt(1));
rs4.close();
conn4.rollback();
conn4.close();
xac4.close();
// test jira-derby 95 - a NullPointerException was returned when passing
// an incorrect database name (a url in this case) - should now give error XCY00
Connection dmc95 = ij.startJBMS();
String sqls;
try {
testJira95ds( dmc95, "jdbc:derby:mydb" );
} catch (SQLException sqle) {
sqls = sqle.getSQLState();
if (sqls.equals("XCY00"))
System.out.println("; ok - expected exception: " + sqls);
else
System.out.println("; wrong, unexpected exception: " + sqls + " - " + sqle.toString());
} catch (Exception e) {
System.out.println("; wrong, unexpected exception: " + e.toString());
}
try {
testJira95xads( dmc95, "jdbc:derby:wombat" );
} catch (SQLException sqle) {
sqls = sqle.getSQLState();
if (sqls.equals("XCY00"))
System.out.println("; ok - expected exception: " + sqls + "\n");
else
System.out.println("; wrong - unexpected exception: " + sqls + " - " + sqle.toString());
} catch (Exception e) {
System.out.println("; wrong, unexpected exception: " + e.toString());
}
// skip testDSRequestAuthentication for client because of these
// two issues:
// DERBY-1130 : Client should not allow databaseName to be set with
// setConnectionAttributes
// DERBY-1131 : Deprecate Derby DataSource property attributesAsPassword
if (TestUtil.isDerbyNetClientFramework())
return;
testDSRequestAuthentication();
}
| protected void runTest(String[] args) throws Exception {
// Check the returned type of the JDBC Connections.
ij.getPropertyArg(args);
Connection dmc = ij.startJBMS();
dmc.createStatement().executeUpdate("create table y(i int)");
dmc.createStatement().executeUpdate(
"create procedure checkConn2(in dsname varchar(20)) " +
"parameter style java language java modifies SQL DATA " +
"external name 'org.apache.derbyTesting.functionTests.tests.jdbcapi." +
this.getNestedMethodName() +
"'");
CallableStatement cs = dmc.prepareCall("call checkConn2(?)");
cs.setString(1,"Nested");
cs.execute();
checkConnection("DriverManager ", dmc);
if (testConnectionToString)
checkJBMSToString();
Properties attrs = new Properties();
attrs.setProperty("databaseName", "wombat");
DataSource dscs = TestUtil.getDataSource(attrs);
if (testConnectionToString)
checkToString(dscs);
DataSource ds = dscs;
checkConnection("DataSource", ds.getConnection());
DataSource dssimple = null;
if (testSimpleDataSource)
{
dssimple = TestUtil.getSimpleDataSource(attrs);
ds = dssimple;
checkConnection("SimpleDataSource", ds.getConnection());
}
ConnectionPoolDataSource dsp = TestUtil.getConnectionPoolDataSource(attrs);
if (testConnectionToString)
checkToString(dsp);
PooledConnection pc = dsp.getPooledConnection();
SecurityCheck.inspect(pc, "javax.sql.PooledConnection");
pc.addConnectionEventListener(new EventCatcher(1));
checkConnection("ConnectionPoolDataSource", pc.getConnection());
checkConnection("ConnectionPoolDataSource", pc.getConnection());
// BUG 4471 - check outstanding updates are rolled back.
Connection c1 = pc.getConnection();
Statement s = c1.createStatement();
s.executeUpdate("create table t (i int)");
s.executeUpdate("insert into t values(1)");
c1.setAutoCommit(false);
// this update should be rolled back
s.executeUpdate("insert into t values(2)");
if (needRollbackBeforePCGetConnection)
c1.rollback();
c1 = pc.getConnection();
ResultSet rs = c1.createStatement().executeQuery("select count(*) from t");
rs.next();
int count = rs.getInt(1);
System.out.println(count == 1 ? "Changes rolled back OK in auto closed pooled connection" :
("FAIL changes committed in in auto closed pooled connection - " + count));
c1.close();
// check connection objects are closed once connection is closed
try {
rs.next();
System.out.println("FAIL - ResultSet is open for a closed connection obtained from PooledConnection");
} catch (SQLException sqle) {
System.out.println("expected " + sqle.toString());
}
try {
s.executeUpdate("update t set i = 1");
System.out.println("FAIL - Statement is open for a closed connection obtained from PooledConnection");
} catch (SQLException sqle) {
System.out.println("expected " + sqle.toString());
}
pc.close();
pc = null;
testPoolReset("ConnectionPoolDataSource", dsp.getPooledConnection());
XADataSource dsx = TestUtil.getXADataSource(attrs);
if (testConnectionToString)
checkToString(dsx);
XAConnection xac = dsx.getXAConnection();
SecurityCheck.inspect(xac, "javax.sql.XAConnection");
xac.addConnectionEventListener(new EventCatcher(3));
checkConnection("XADataSource", xac.getConnection());
// BUG 4471 - check outstanding updates are rolled back wi XAConnection.
c1 = xac.getConnection();
s = c1.createStatement();
s.executeUpdate("insert into t values(1)");
c1.setAutoCommit(false);
// this update should be rolled back
s.executeUpdate("insert into t values(2)");
if (needRollbackBeforePCGetConnection)
c1.rollback();
c1 = xac.getConnection();
rs = c1.createStatement().executeQuery("select count(*) from t");
rs.next();
count = rs.getInt(1);
rs.close();
System.out.println(count == 2 ? "Changes rolled back OK in auto closed local XAConnection" :
("FAIL changes committed in in auto closed pooled connection - " + count));
c1.close();
xac.close();
xac = null;
testPoolReset("XADataSource", dsx.getXAConnection());
try {
TestUtil.getConnection("","shutdown=true");
} catch (SQLException sqle) {
JDBCDisplayUtil.ShowSQLException(System.out, sqle);
}
dmc = ij.startJBMS();
cs = dmc.prepareCall("call checkConn2(?)");
SecurityCheck.inspect(cs, "java.sql.CallableStatement");
cs.setString(1,"Nested");
cs.execute();
checkConnection("DriverManager ", dmc);
// reset ds back to the Regular DataSource
ds = dscs;
checkConnection("DataSource", ds.getConnection());
// and back to EmbeddedSimpleDataSource
if(TestUtil.isEmbeddedFramework())
{
// JSR169 (SimpleDataSource) is only available on embedded.
ds = dssimple;
checkConnection("EmbeddedSimpleDataSource", dssimple.getConnection());
}
pc = dsp.getPooledConnection();
pc.addConnectionEventListener(new EventCatcher(2));
checkConnection("ConnectionPoolDataSource", pc.getConnection());
checkConnection("ConnectionPoolDataSource", pc.getConnection());
// test "local" XAConnections
xac = dsx.getXAConnection();
xac.addConnectionEventListener(new EventCatcher(4));
checkConnection("XADataSource", xac.getConnection());
checkConnection("XADataSource", xac.getConnection());
xac.close();
// test "global" XAConnections
xac = dsx.getXAConnection();
xac.addConnectionEventListener(new EventCatcher(5));
XAResource xar = xac.getXAResource();
SecurityCheck.inspect(xar, "javax.transaction.xa.XAResource");
Xid xid = new cdsXid(1, (byte) 35, (byte) 47);
xar.start(xid, XAResource.TMNOFLAGS);
Connection xacc = xac.getConnection();
xacc.close();
checkConnection("Global XADataSource", xac.getConnection());
checkConnection("Global XADataSource", xac.getConnection());
xar.end(xid, XAResource.TMSUCCESS);
checkConnection("Switch to local XADataSource", xac.getConnection());
checkConnection("Switch to local XADataSource", xac.getConnection());
Connection backtoGlobal = xac.getConnection();
xar.start(xid, XAResource.TMJOIN);
checkConnection("Switch to global XADataSource", backtoGlobal);
checkConnection("Switch to global XADataSource", xac.getConnection());
xar.end(xid, XAResource.TMSUCCESS);
xar.commit(xid, true);
xac.close();
// now some explicit tests for how connection state behaves
// when switching between global transactions and local
// and setting connection state.
// some of this is already tested in simpleDataSource and checkDataSource
// but I want to make sure I cover all situations. (djd)
xac = dsx.getXAConnection();
xac.addConnectionEventListener(new EventCatcher(6));
xar = xac.getXAResource();
xid = new cdsXid(1, (byte) 93, (byte) 103);
// series 1 - Single connection object
Connection cs1 = xac.getConnection();
printState("initial local", cs1);
xar.start(xid, XAResource.TMNOFLAGS);
printState("initial X1", cs1);
cs1.setTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED);
cs1.setReadOnly(true);
setHoldability(cs1, false);
printState("modified X1", cs1);
xar.end(xid, XAResource.TMSUCCESS);
// the underlying local transaction/connection must pick up the
// state of the Connection handle cs1
printState("modified local", cs1);
cs1.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
cs1.setReadOnly(false);
setHoldability(cs1, false);
printState("reset local", cs1);
// now re-join the transaction, should pick up the read-only
// and isolation level from the transaction,
// holdability remains that of this handle.
xar.start(xid, XAResource.TMJOIN);
// DERBY-1148
if (isolationSetProperlyOnJoin)
printState("re-join X1", cs1);
xar.end(xid, XAResource.TMSUCCESS);
// should be the same as the reset local
printState("back to local (same as reset)", cs1);
cs1.setTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED);
cs1.setReadOnly(true);
setHoldability(cs1, true);
cs1.close();
cs1 = xac.getConnection();
printState("new handle - local ", cs1);
cs1.close();
xar.start(xid, XAResource.TMJOIN);
cs1 = xac.getConnection();
// DERBY-1148
if (isolationSetProperlyOnJoin)
printState("re-join with new handle X1", cs1);
cs1.close();
xar.end(xid, XAResource.TMSUCCESS);
// now get a connection (attached to a local)
// attach to the global and commit it.
// state should be that of the local after the commit.
cs1 = xac.getConnection();
cs1.setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ);
printState("pre-X1 commit - local", cs1);
xar.start(xid, XAResource.TMJOIN);
// DERBY-1148
if (isolationSetProperlyOnJoin)
printState("pre-X1 commit - X1", cs1);
xar.end(xid, XAResource.TMSUCCESS);
printState("post-X1 end - local", cs1);
xar.commit(xid, true);
printState("post-X1 commit - local", cs1);
cs1.close();
//Derby-421 Setting isolation level with SQL was not getting handled correctly
System.out.println("Some more isolation testing using SQL and JDBC api");
cs1 = xac.getConnection();
s = cs1.createStatement();
printState("initial local", cs1);
System.out.println("Issue setTransactionIsolation in local transaction");
cs1.setTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED);
printState("setTransactionIsolation in local", cs1);
if (canSetIsolationWithStatement)
testSetIsolationWithStatement(s, xar, cs1);
// now check re-use of *Statement objects across local/global connections.
System.out.println("TESTING RE_USE OF STATEMENT OBJECTS");
cs1 = xac.getConnection();
// ensure read locks stay around until end-of transaction
cs1.setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ);
cs1.setAutoCommit(false);
checkLocks(cs1);
Statement sru1 = cs1.createStatement();
sru1.setCursorName("SN1");
sru1.executeUpdate("create table ru(i int)");
sru1.executeUpdate("insert into ru values 1,2,3");
Statement sruBatch = cs1.createStatement();
Statement sruState = createFloatStatementForStateChecking(cs1);
PreparedStatement psruState = createFloatStatementForStateChecking(cs1, "select i from ru where i = ?");
CallableStatement csruState = createFloatCallForStateChecking(cs1, "CALL SYSCS_UTIL.SYSCS_SET_DATABASE_PROPERTY(?,?)");
PreparedStatement psParams = cs1.prepareStatement("select * from ru where i > ?");
psParams.setCursorName("params");
psParams.setInt(1, 2);
resultSetQuery("Params-local-1", psParams.executeQuery());
sruBatch.addBatch("insert into ru values 4");
queryOnStatement("sru1-local-1", cs1, sru1);
cs1.commit(); // need to commit to switch to an global connection;
xid = new cdsXid(1, (byte) 103, (byte) 119);
xar.start(xid, XAResource.TMNOFLAGS); // simple case - underlying connection is re-used for global.
System.out.println("Expecting downgrade because global transaction sru1-global-2 is using a statement with holdability true");
queryOnStatement("sru1-global-2", cs1, sru1);
sruBatch.addBatch("insert into ru values 5");
Statement sru2 = cs1.createStatement();
sru2.setCursorName("OAK2");
queryOnStatement("sru2-global-3", cs1, sru2);
System.out.println("Expecting downgrade because global transaction sru1-global-4 is using a statement with holdability true");
queryOnStatement("sru1-global-4", cs1, sru1);
showStatementState("GLOBAL ", sruState);
showStatementState("PS GLOBAL ", psruState);
showStatementState("CS GLOBAL ", csruState);
resultSetQuery("Params-global-1", psParams.executeQuery());
xar.end(xid, XAResource.TMSUCCESS);
// now a new underlying connection is created
queryOnStatement("sru1-local-5", cs1, sru1);
queryOnStatement("sru2-local-6", cs1, sru2);
sruBatch.addBatch("insert into ru values 6,7");
Statement sru3 = cs1.createStatement();
sru3.setCursorName("SF3");
queryOnStatement("sru3-local-7", cs1, sru3);
// Two transactions should hold locks (global and the current XA);
showStatementState("LOCAL ", sruState);
showStatementState("PS LOCAL ", psruState);
showStatementState("CS LOCAL ", csruState);
resultSetQuery("Params-local-2", psParams.executeQuery());
checkLocks(cs1);
cs1.commit();
// attach the XA transaction to another connection and see what happens
XAConnection xac2 = dsx.getXAConnection();
xac2.addConnectionEventListener(new EventCatcher(5));
XAResource xar2 = xac2.getXAResource();
xar2.start(xid, XAResource.TMJOIN);
Connection cs2 = xac2.getConnection();
// these statements were generated by cs1 and thus are still
// in a local connection.
queryOnStatement("sru1-local-8", cs1, sru1);
queryOnStatement("sru2-local-9", cs1, sru2);
queryOnStatement("sru3-local-10", cs1, sru3);
sruBatch.addBatch("insert into ru values 8");
showStatementState("LOCAL 2 ", sruState);
showStatementState("PS LOCAL 2 ", psruState);
showStatementState("CS LOCAL 2", csruState);
checkLocks(cs1);
int[] updateCounts = sruBatch.executeBatch();
System.out.print("sruBatch update counts :");
for (int i = 0; i < updateCounts.length; i++) {
System.out.print(" " + updateCounts[i] + " ");
}
System.out.println(":");
queryOnStatement("sruBatch", cs1, sruBatch);
xar2.end(xid, XAResource.TMSUCCESS);
xac2.close();
// allow close on already closed XAConnection
xac2.close();
xac2.addConnectionEventListener(null);
xac2.removeConnectionEventListener(null);
// test methods against a closed XAConnection and its resource
try {
xac2.getXAResource();
} catch (SQLException sqle) {
System.out.println("XAConnection.getXAResource : " + sqle.getMessage());
}
try {
xac2.getConnection();
} catch (SQLException sqle) {
System.out.println("XAConnection.getConnection : " + sqle.getMessage());
}
try {
xar2.start(xid, XAResource.TMJOIN);
} catch (XAException xae) {
showXAException("XAResource.start", xae);
}
try {
xar2.end(xid, XAResource.TMJOIN);
} catch (XAException xae) {
showXAException("XAResource.end", xae);
}
try {
xar2.commit(xid, true);
} catch (XAException xae) {
showXAException("XAResource.commit", xae);
}
try {
xar2.prepare(xid);
} catch (XAException xae) {
showXAException("XAResource.prepare", xae);
}
try {
xar2.recover(0);
} catch (XAException xae) {
showXAException("XAResource.recover", xae);
}
try {
xar2.prepare(xid);
} catch (XAException xae) {
showXAException("XAResource.prepare", xae);
}
try {
xar2.isSameRM(xar2);
} catch (XAException xae) {
showXAException("XAResource.isSameRM", xae);
}
// Patricio (on the forum) one was having an issue with set schema not working in an XA connection.
dmc = ij.startJBMS();
dmc.createStatement().executeUpdate("create schema SCHEMA_Patricio");
dmc.createStatement().executeUpdate("create table SCHEMA_Patricio.Patricio (id VARCHAR(255), value INTEGER)");
dmc.commit();
dmc.close();
XAConnection xac3 = dsx.getXAConnection();
Connection conn3 = xac3.getConnection();
Statement st3 = conn3.createStatement();
st3.execute("SET SCHEMA SCHEMA_Patricio");
st3.close();
PreparedStatement ps3 = conn3.prepareStatement("INSERT INTO Patricio VALUES (? , ?)");
ps3.setString(1, "Patricio");
ps3.setInt(2, 3);
ps3.executeUpdate();
System.out.println("Patricio update count " + ps3.getUpdateCount());
ps3.close();
conn3.close();
xac3.close();
// test that an xastart in auto commit mode commits the existing work.(beetle 5178)
XAConnection xac4 = dsx.getXAConnection();
Xid xid4a = new cdsXid(4, (byte) 23, (byte) 76);
Connection conn4 = xac4.getConnection();
System.out.println("conn4 autcommit " + conn4.getAutoCommit());
Statement s4 = conn4.createStatement();
s4.executeUpdate("create table autocommitxastart(i int)");
s4.executeUpdate("insert into autocommitxastart values 1,2,3,4,5");
ResultSet rs4 = s4.executeQuery("select i from autocommitxastart");
rs4.next(); System.out.println("acxs " + rs4.getInt(1));
rs4.next(); System.out.println("acxs " + rs4.getInt(1));
xac4.getXAResource().start(xid4a, XAResource.TMNOFLAGS);
xac4.getXAResource().end(xid4a, XAResource.TMSUCCESS);
try {
rs4.next(); System.out.println("acxs " + rs.getInt(1));
} catch (SQLException sqle) {
System.out.println("autocommitxastart expected " + sqle.getMessage());
}
conn4.setAutoCommit(false);
rs4 = s4.executeQuery("select i from autocommitxastart");
rs4.next(); System.out.println("acxs " + rs4.getInt(1));
rs4.next(); System.out.println("acxs " + rs4.getInt(1));
// Get a new xid to begin another transaction.
// This should give XAER_OUTSIDE exception because
// the resource manager is busy in the local transaction
xid4a = new cdsXid(4, (byte) 93, (byte) 103);
try {
xac4.getXAResource().start(xid4a, XAResource.TMNOFLAGS);
} catch (XAException xae) {
showXAException("autocommitxastart expected ", xae);
System.out.println("Expected XA error code: " + xae.errorCode);
}
rs4.next(); System.out.println("acxs " + rs4.getInt(1));
rs4.close();
conn4.rollback();
conn4.close();
xac4.close();
// test jira-derby 95 - a NullPointerException was returned when passing
// an incorrect database name (a url in this case) - should now give error XCY00
Connection dmc95 = ij.startJBMS();
String sqls;
try {
testJira95ds( dmc95, "jdbc:derby:mydb" );
} catch (SQLException sqle) {
sqls = sqle.getSQLState();
if (sqls.equals("XCY00"))
System.out.println("; ok - expected exception: " + sqls);
else
System.out.println("; wrong, unexpected exception: " + sqls + " - " + sqle.toString());
} catch (Exception e) {
System.out.println("; wrong, unexpected exception: " + e.toString());
}
try {
testJira95xads( dmc95, "jdbc:derby:wombat" );
} catch (SQLException sqle) {
sqls = sqle.getSQLState();
if (sqls.equals("XCY00"))
System.out.println("; ok - expected exception: " + sqls + "\n");
else
System.out.println("; wrong - unexpected exception: " + sqls + " - " + sqle.toString());
} catch (Exception e) {
System.out.println("; wrong, unexpected exception: " + e.toString());
}
// skip testDSRequestAuthentication for client because of these
// two issues:
// DERBY-1130 : Client should not allow databaseName to be set with
// setConnectionAttributes
// DERBY-1131 : Deprecate Derby DataSource property attributesAsPassword
if (TestUtil.isDerbyNetClientFramework())
return;
testDSRequestAuthentication();
}
|
diff --git a/src/org/meta_environment/rascal/interpreter/RascalShell.java b/src/org/meta_environment/rascal/interpreter/RascalShell.java
index dbb07a972a..43baa0de18 100644
--- a/src/org/meta_environment/rascal/interpreter/RascalShell.java
+++ b/src/org/meta_environment/rascal/interpreter/RascalShell.java
@@ -1,198 +1,199 @@
package org.meta_environment.rascal.interpreter;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.Writer;
import jline.ConsoleReader;
import org.eclipse.imp.pdb.facts.IConstructor;
import org.eclipse.imp.pdb.facts.IValue;
import org.eclipse.imp.pdb.facts.exceptions.FactTypeUseException;
import org.eclipse.imp.pdb.facts.type.Type;
import org.meta_environment.ValueFactoryFactory;
import org.meta_environment.errors.SubjectAdapter;
import org.meta_environment.errors.SummaryAdapter;
import org.meta_environment.rascal.ast.ASTFactory;
import org.meta_environment.rascal.ast.Command;
import org.meta_environment.rascal.interpreter.asserts.ImplementationError;
import org.meta_environment.rascal.interpreter.control_exceptions.QuitException;
import org.meta_environment.rascal.interpreter.control_exceptions.Throw;
import org.meta_environment.rascal.interpreter.env.GlobalEnvironment;
import org.meta_environment.rascal.interpreter.env.ModuleEnvironment;
import org.meta_environment.rascal.interpreter.result.Result;
import org.meta_environment.rascal.interpreter.staticErrors.StaticError;
import org.meta_environment.rascal.parser.ASTBuilder;
import org.meta_environment.uptr.Factory;
import org.meta_environment.uptr.TreeAdapter;
public class RascalShell {
private final static String PROMPT = "rascal>";
private final static String CONTINUE_PROMPT = ">>>>>>>";
private final static int MAX_CONSOLE_LINE = 100;
private static final String SHELL_MODULE = "***shell***";
private final ConsoleReader console;
private final CommandEvaluator evaluator;
// TODO: cleanup these constructors.
public RascalShell() throws IOException {
console = new ConsoleReader();
GlobalEnvironment heap = new GlobalEnvironment();
ModuleEnvironment root = heap.addModule(new ModuleEnvironment(SHELL_MODULE));
evaluator = new CommandEvaluator(ValueFactoryFactory.getValueFactory(),
new PrintWriter(System.err), root, heap);
}
public RascalShell(InputStream inputStream, Writer out) throws IOException {
console = new ConsoleReader(inputStream, out);
GlobalEnvironment heap = new GlobalEnvironment();
ModuleEnvironment root = heap.addModule(new ModuleEnvironment(SHELL_MODULE));
evaluator = new CommandEvaluator(ValueFactoryFactory.getValueFactory(), out, root, heap);
}
public void setInputStream(InputStream in) {
console.setInput(in);
}
public void run() throws IOException {
StringBuffer input = new StringBuffer();
String line;
next:while (true) {
try {
input.delete(0, input.length());
String prompt = PROMPT;
do {
line = console.readLine(prompt);
if (line == null) {
break next; // EOF
}
if (line.trim().length() == 0) {
console.printString("cancelled\n");
continue next;
}
input.append((input.length() > 0 ? "\n" : "") + line);
prompt = CONTINUE_PROMPT;
} while (!completeStatement(input));
String output = handleInput(evaluator, input);
if(output.length() > MAX_CONSOLE_LINE) {
output = output.substring(0, MAX_CONSOLE_LINE) + " ...";
}
console.printString(output);
console.printNewline();
}
catch (StaticError e) {
console.printString("Static Error: " + e.getMessage() + "\n");
+ printStacktrace(console, e);
}
catch (Throw e) {
console.printString("Uncaught Rascal Exception: " + e.getMessage() + "\n");
console.printString(e.getTrace());
}
catch (ImplementationError e) {
e.printStackTrace();
console.printString("ImplementationError: " + e.getMessage() + "\n");
printStacktrace(console, e);
}
catch (QuitException q) {
break next;
}
catch (Throwable e) {
console.printString("ImplementationError (generic Throwable): " + e.getMessage() + "\n");
printStacktrace(console, e);
}
}
}
private void printStacktrace(ConsoleReader console, Throwable e) throws IOException {
String message = e.getMessage();
console.printString("stacktrace: " + (message != null ? message : "" )+ "\n");
for (StackTraceElement elem : e.getStackTrace()) {
console.printString("\tat " + elem.getClassName() + "." + elem.getMethodName() + "(" + elem.getFileName() + ":" + elem.getLineNumber() + ")\n");
}
Throwable cause = e.getCause();
if (cause != null) {
console.printString("caused by:\n");
printStacktrace(console, cause);
}
}
private String handleInput(final CommandEvaluator command, StringBuffer statement) throws IOException {
StringBuilder result = new StringBuilder();
IConstructor tree = evaluator.parseCommand(statement.toString());
if (tree.getConstructorType() == Factory.ParseTree_Summary) {
SubjectAdapter s = new SummaryAdapter(tree).getInitialSubject();
for (int i = 0; i < s.getEndColumn(); i++) {
result.append(" ");
}
result.append("^\n");
result.append("parse error at" + (s.getEndLine() != 1 ? (" line" + s.getEndLine()) : "") + " column " + s.getEndColumn());
}
else {
Command stat = new ASTBuilder(new ASTFactory()).buildCommand(tree);
if (stat == null) {
throw new ImplementationError("Disambiguation failed: it removed all alternatives");
}
Result<IValue> value = command.eval(stat);
if (value.getValue() == null) {
return "ok";
}
IValue v = value.getValue();
Type type = value.getType();
if (type.isAbstractDataType() && type.isSubtypeOf(Factory.Tree)) {
return "[|" + new TreeAdapter((IConstructor) v).yield() + "|]\n" + type + ": " + v.toString();
}
return type + ": " + ((v != null) ? v.toString() : null);
}
return result.toString();
}
private boolean completeStatement(StringBuffer statement) throws FactTypeUseException, IOException {
String command = statement.toString();
IConstructor tree = evaluator.parseCommand(command);
if (tree.getConstructorType() == Factory.ParseTree_Summary) {
SubjectAdapter subject = new SummaryAdapter(tree).getInitialSubject();
String[] commandLines = command.split("\n");
int lastLine = commandLines.length;
int lastColumn = commandLines[lastLine - 1].length();
if (subject.getEndLine() == lastLine && lastColumn <= subject.getEndColumn()) {
return false;
}
return true;
}
return true;
}
public static void main(String[] args) {
if (args.length == 0) {
// interactive mode
try {
new RascalShell().run();
System.err.println("Que le Rascal soit avec vous!");
System.exit(0);
} catch (IOException e) {
System.err.println("unexpected error: " + e.getMessage());
System.exit(1);
}
}
}
}
| true | true | public void run() throws IOException {
StringBuffer input = new StringBuffer();
String line;
next:while (true) {
try {
input.delete(0, input.length());
String prompt = PROMPT;
do {
line = console.readLine(prompt);
if (line == null) {
break next; // EOF
}
if (line.trim().length() == 0) {
console.printString("cancelled\n");
continue next;
}
input.append((input.length() > 0 ? "\n" : "") + line);
prompt = CONTINUE_PROMPT;
} while (!completeStatement(input));
String output = handleInput(evaluator, input);
if(output.length() > MAX_CONSOLE_LINE) {
output = output.substring(0, MAX_CONSOLE_LINE) + " ...";
}
console.printString(output);
console.printNewline();
}
catch (StaticError e) {
console.printString("Static Error: " + e.getMessage() + "\n");
}
catch (Throw e) {
console.printString("Uncaught Rascal Exception: " + e.getMessage() + "\n");
console.printString(e.getTrace());
}
catch (ImplementationError e) {
e.printStackTrace();
console.printString("ImplementationError: " + e.getMessage() + "\n");
printStacktrace(console, e);
}
catch (QuitException q) {
break next;
}
catch (Throwable e) {
console.printString("ImplementationError (generic Throwable): " + e.getMessage() + "\n");
printStacktrace(console, e);
}
}
}
| public void run() throws IOException {
StringBuffer input = new StringBuffer();
String line;
next:while (true) {
try {
input.delete(0, input.length());
String prompt = PROMPT;
do {
line = console.readLine(prompt);
if (line == null) {
break next; // EOF
}
if (line.trim().length() == 0) {
console.printString("cancelled\n");
continue next;
}
input.append((input.length() > 0 ? "\n" : "") + line);
prompt = CONTINUE_PROMPT;
} while (!completeStatement(input));
String output = handleInput(evaluator, input);
if(output.length() > MAX_CONSOLE_LINE) {
output = output.substring(0, MAX_CONSOLE_LINE) + " ...";
}
console.printString(output);
console.printNewline();
}
catch (StaticError e) {
console.printString("Static Error: " + e.getMessage() + "\n");
printStacktrace(console, e);
}
catch (Throw e) {
console.printString("Uncaught Rascal Exception: " + e.getMessage() + "\n");
console.printString(e.getTrace());
}
catch (ImplementationError e) {
e.printStackTrace();
console.printString("ImplementationError: " + e.getMessage() + "\n");
printStacktrace(console, e);
}
catch (QuitException q) {
break next;
}
catch (Throwable e) {
console.printString("ImplementationError (generic Throwable): " + e.getMessage() + "\n");
printStacktrace(console, e);
}
}
}
|
diff --git a/tests-src/net/grinder/console/swingui/TestGraph.java b/tests-src/net/grinder/console/swingui/TestGraph.java
index d7744da9..d629747d 100755
--- a/tests-src/net/grinder/console/swingui/TestGraph.java
+++ b/tests-src/net/grinder/console/swingui/TestGraph.java
@@ -1,181 +1,181 @@
// The Grinder
// Copyright (C) 2000, 2001 Paco Gomez
// Copyright (C) 2000, 2001 Philip Aston
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
package net.grinder.console.swingui;
import junit.framework.TestCase;
import junit.swingui.TestRunner;
//import junit.textui.TestRunner;
import java.awt.BorderLayout;
import java.text.DecimalFormat;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Random;
import javax.swing.JComponent;
import javax.swing.JFrame;
import net.grinder.statistics.PeakStatisticExpression;
import net.grinder.statistics.StatisticExpression;
import net.grinder.statistics.StatisticExpressionFactory;
import net.grinder.statistics.StatisticsIndexMap;
import net.grinder.statistics.TestStatistics;
import net.grinder.statistics.TestStatisticsFactory;
/**
* @author Philip Aston
* @version $Revision$
*/
public class TestGraph extends TestCase
{
public static void main(String[] args)
{
TestRunner.run(TestGraph.class);
}
public TestGraph(String name)
{
super(name);
}
private int m_pauseTime = 1;
private Random s_random = new Random();
private JFrame m_frame;
protected void setUp() throws Exception
{
m_frame = new JFrame("Test Graph");
}
protected void tearDown() throws Exception
{
m_frame.dispose();
}
private void createUI(JComponent component) throws Exception
{
m_frame.getContentPane().add(component, BorderLayout.CENTER);
m_frame.pack();
m_frame.setVisible(true);
}
public void testRamp() throws Exception
{
final Graph graph = new Graph(25);
createUI(graph);
graph.setMaximum(150);
for (int i=0; i<150; i++) {
graph.add(i);
pause();
}
}
public void testRandom() throws Exception
{
final Graph graph = new Graph(100);
createUI(graph);
graph.setMaximum(1);
for (int i=0; i<200; i++) {
graph.add(s_random.nextDouble());
pause();
}
}
public void testLabelledGraph() throws Exception
{
final TestStatisticsFactory testStatisticsFactory
= TestStatisticsFactory.getInstance();
final StatisticsIndexMap indexMap =
StatisticsIndexMap.getProcessInstance();
final StatisticsIndexMap.LongIndex periodIndex =
indexMap.getIndexForLong("period");
final StatisticExpressionFactory statisticExpressionFactory =
StatisticExpressionFactory.getInstance();
final StatisticExpression tpsExpression =
statisticExpressionFactory.createExpression(
"(* 1000 (/(+ untimedTransactions timedTransactions) period))"
);
final PeakStatisticExpression peakTPSExpression =
statisticExpressionFactory.createPeak(
indexMap.getIndexForDouble("peakTPS"), tpsExpression);
final LabelledGraph labelledGraph =
new LabelledGraph("Test", new Resources(), tpsExpression,
peakTPSExpression);
createUI(labelledGraph);
double peak = 0d;
final TestStatistics cumulativeStatistics =
testStatisticsFactory.create();
final DecimalFormat format = new DecimalFormat();
final int period = 1000;
for (int i=0; i<200; i++) {
final TestStatistics intervalStatistics =
testStatisticsFactory.create();
intervalStatistics.setValue(periodIndex, period);
while (s_random.nextInt() > 0) {
intervalStatistics.addTransaction();
}
long time;
while ((time = s_random.nextInt()) > 0) {
intervalStatistics.addTransaction(time % 10000);
}
while (s_random.nextFloat() > 0.95) {
intervalStatistics.addError();
}
cumulativeStatistics.add(intervalStatistics);
cumulativeStatistics.setValue(periodIndex, (1+i)*period);
- peakTPSExpression.update(cumulativeStatistics);
+ peakTPSExpression.update(intervalStatistics, cumulativeStatistics);
labelledGraph.add(intervalStatistics, cumulativeStatistics,
format);
pause();
}
}
private void pause() throws Exception
{
if (m_pauseTime > 0) {
Thread.sleep(m_pauseTime);
}
}
}
| true | true | public void testLabelledGraph() throws Exception
{
final TestStatisticsFactory testStatisticsFactory
= TestStatisticsFactory.getInstance();
final StatisticsIndexMap indexMap =
StatisticsIndexMap.getProcessInstance();
final StatisticsIndexMap.LongIndex periodIndex =
indexMap.getIndexForLong("period");
final StatisticExpressionFactory statisticExpressionFactory =
StatisticExpressionFactory.getInstance();
final StatisticExpression tpsExpression =
statisticExpressionFactory.createExpression(
"(* 1000 (/(+ untimedTransactions timedTransactions) period))"
);
final PeakStatisticExpression peakTPSExpression =
statisticExpressionFactory.createPeak(
indexMap.getIndexForDouble("peakTPS"), tpsExpression);
final LabelledGraph labelledGraph =
new LabelledGraph("Test", new Resources(), tpsExpression,
peakTPSExpression);
createUI(labelledGraph);
double peak = 0d;
final TestStatistics cumulativeStatistics =
testStatisticsFactory.create();
final DecimalFormat format = new DecimalFormat();
final int period = 1000;
for (int i=0; i<200; i++) {
final TestStatistics intervalStatistics =
testStatisticsFactory.create();
intervalStatistics.setValue(periodIndex, period);
while (s_random.nextInt() > 0) {
intervalStatistics.addTransaction();
}
long time;
while ((time = s_random.nextInt()) > 0) {
intervalStatistics.addTransaction(time % 10000);
}
while (s_random.nextFloat() > 0.95) {
intervalStatistics.addError();
}
cumulativeStatistics.add(intervalStatistics);
cumulativeStatistics.setValue(periodIndex, (1+i)*period);
peakTPSExpression.update(cumulativeStatistics);
labelledGraph.add(intervalStatistics, cumulativeStatistics,
format);
pause();
}
}
| public void testLabelledGraph() throws Exception
{
final TestStatisticsFactory testStatisticsFactory
= TestStatisticsFactory.getInstance();
final StatisticsIndexMap indexMap =
StatisticsIndexMap.getProcessInstance();
final StatisticsIndexMap.LongIndex periodIndex =
indexMap.getIndexForLong("period");
final StatisticExpressionFactory statisticExpressionFactory =
StatisticExpressionFactory.getInstance();
final StatisticExpression tpsExpression =
statisticExpressionFactory.createExpression(
"(* 1000 (/(+ untimedTransactions timedTransactions) period))"
);
final PeakStatisticExpression peakTPSExpression =
statisticExpressionFactory.createPeak(
indexMap.getIndexForDouble("peakTPS"), tpsExpression);
final LabelledGraph labelledGraph =
new LabelledGraph("Test", new Resources(), tpsExpression,
peakTPSExpression);
createUI(labelledGraph);
double peak = 0d;
final TestStatistics cumulativeStatistics =
testStatisticsFactory.create();
final DecimalFormat format = new DecimalFormat();
final int period = 1000;
for (int i=0; i<200; i++) {
final TestStatistics intervalStatistics =
testStatisticsFactory.create();
intervalStatistics.setValue(periodIndex, period);
while (s_random.nextInt() > 0) {
intervalStatistics.addTransaction();
}
long time;
while ((time = s_random.nextInt()) > 0) {
intervalStatistics.addTransaction(time % 10000);
}
while (s_random.nextFloat() > 0.95) {
intervalStatistics.addError();
}
cumulativeStatistics.add(intervalStatistics);
cumulativeStatistics.setValue(periodIndex, (1+i)*period);
peakTPSExpression.update(intervalStatistics, cumulativeStatistics);
labelledGraph.add(intervalStatistics, cumulativeStatistics,
format);
pause();
}
}
|
diff --git a/src/admin/panel/person/contestant/ContestantPanel.java b/src/admin/panel/person/contestant/ContestantPanel.java
index b83702e..e6405ef 100644
--- a/src/admin/panel/person/contestant/ContestantPanel.java
+++ b/src/admin/panel/person/contestant/ContestantPanel.java
@@ -1,535 +1,541 @@
package admin.panel.person.contestant;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.Arrays;
import java.util.List;
import java.util.Observable;
import java.util.Observer;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.UIManager;
import javax.swing.table.TableCellRenderer;
import admin.FileDrop;
import admin.MainFrame;
import admin.Utils;
import admin.panel.person.PersonPanel;
import data.Contestant;
import data.GameData;
import data.InvalidFieldException;
public class ContestantPanel extends PersonPanel<Contestant> implements MouseListener, Observer {
private static final long serialVersionUID = 1L;
// container for top stuff
private JButton btnCastOff;
private JButton imgDisplay;
private JLabel labelName;
// TODO: Refactor to something more obvious?
private JLabel labelCastOff;
private JLabel labelCastStatus;
private JLabel labelTribe;
private JTextField tfFirstName;
private JTextField tfLastName;
private JComboBox<String> cbTribe;
private JTextField tfContID;
private JLabel labelID;
// static constants:
private static final String CAST_OFF_TEXT = "Cast Off";
private static final String UNDO_CAST_TEXT = "Undo Cast Off";
// tool tip texts:
protected static final String TOOL_NAME = "First and Last name must be alphabetic";
protected static final String TOOL_ID = "ID must be two characters long and " +
"alpha-numeric";
protected static final String TOOL_TRIBE = "Select a tribe";
protected static final String TOOL_CASTOFF = "Click to cast off contestant.";
protected static final String TOOL_SAVE = "Click to save contestant data";
protected static final String TOOL_IMAGE = "Click to select image";
protected static final String TOOL_ADDNEW = "Click to add new contestant";
protected static final String TOOL_DELETE = "Click to remove currently selected " +
"Contestant";
protected static final String TOOL_WINNER = "Click to choose winner";
public ContestantPanel() {
super(new Contestant());
// ////////////////////////////
// Top Panel:
// ////////////////////////////
// TODO: Better Test picture
imgDisplay = new JButton();
// Edit fields:
labelName = new JLabel("Name:");
tfFirstName = new JTextField(20);
tfLastName = new JTextField(20);
labelCastOff = new JLabel("Cast off:");
// TODO: FIx the init of this.. :>
labelCastStatus = new JLabel("-");
labelTribe = new JLabel("Tribe:");
cbTribe = new JComboBox<String>(GameData.getCurrentGame()
.getTribeNames());
labelID = new JLabel("ID:");
tfContID = new JTextField(2);
// holds all the fields
personFields = new ContestantFieldsPanel(imgDisplay, labelName,
tfFirstName, tfLastName, labelID, tfContID, labelCastOff,
labelCastStatus, labelTribe, cbTribe);
// add the mouse listener to all components.
for (Component c : ((JPanel)personFields).getComponents()) {
if (c instanceof JPanel) {
for (Component d: ((JPanel)c).getComponents())
d.addMouseListener(this);
}
c.addMouseListener(this);
}
// buttons:
btnCastOff = new JButton("Cast Off");
/* check to stop casting off before start */
if (!GameData.getCurrentGame().isSeasonStarted()) {
btnCastOff.setEnabled(false);
}
//////////////////////////////
// Mid (table!)
//////////////////////////////
// handled by super call
// ////////////////////////////
// Bottom
//////////////////////////////
// build the two panes
// setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));
assembleAll();
}
/**
* Builds the top panel including all the editable information
*/
@Override
protected void buildTopPanel() {
JPanel panel = new JPanel();
panel.setLayout(new BorderLayout(10, 10));
// this does not need to be referenced else where, only for layout
JPanel paneButtons = new JPanel();
GridLayout bl = new GridLayout(2, 1);
paneButtons.setLayout(bl);
paneButtons.add(btnCastOff);
paneButtons.add(btnSave);
// add all components on top:
panel.add((JPanel)personFields, BorderLayout.CENTER);
panel.add(paneButtons, BorderLayout.LINE_END);
add(panel, BorderLayout.PAGE_START);
// add the mouse listener to all components.
for (Component c : panel.getComponents()) {
c.addMouseListener(this);
}
for (Component c : paneButtons.getComponents())
c.addMouseListener(this);
}
/**
* Builds the panel containing the JTable
*/
@Override
protected void buildTablePanel() {
JPanel panel = new JPanel();
// settings:
header.setReorderingAllowed(false); // no moving.
table.setColumnSelectionAllowed(true);
table.setRowSelectionAllowed(true);
table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
//header.addMouseListener(tableModel.new SortColumnAdapter());
TableCellRenderer renderer = new TableCellRenderer() {
JLabel label = new JLabel();
@Override
public JComponent getTableCellRendererComponent(JTable table,
Object value, boolean isSelected, boolean hasFocus,
int row, int column) {
if (table.isRowSelected(row)) {
label.setBackground(Utils.getThemeTableHighlight());
label.setForeground(Utils.getThemeBG());
} else {
label.setBackground(UIManager.getColor("Table.background"));
label.setForeground(UIManager.getColor("Table.foreground"));
}
label.setOpaque(true);
label.setText("" + value);
return label;
}
};
table.setDefaultRenderer(Object.class, renderer);
JScrollPane scroll = new JScrollPane(table);
panel.setLayout(new BorderLayout(5, 5));
panel.add(scroll, BorderLayout.CENTER);
add(panel, BorderLayout.CENTER);
// add the mouse listener to all components.
for (Component c : scroll.getComponents()) {
c.addMouseListener(this);
}
}
/**
* Helper method to build the bottom panel of the container
*/
@Override
protected void buildBottomPanel() {
JPanel panel = new JPanel();
panel.setLayout(new FlowLayout(FlowLayout.RIGHT));
panel.add(btnAddNew);
panel.add(btnDelete);
add(panel, BorderLayout.PAGE_END);
// add the mouse listener to all components.
for (Component c : panel.getComponents()) {
c.addMouseListener(this);
}
}
/**
* Sets the tool tips for all the components.
*/
@Override
protected void setToolTips() {
labelName.setToolTipText(ContestantPanel.TOOL_NAME);
tfFirstName.setToolTipText(ContestantPanel.TOOL_NAME);
tfLastName.setToolTipText(ContestantPanel.TOOL_NAME);
labelID.setToolTipText(ContestantPanel.TOOL_ID);
tfContID.setToolTipText(ContestantPanel.TOOL_ID);
labelTribe.setToolTipText(ContestantPanel.TOOL_TRIBE);
cbTribe.setToolTipText(ContestantPanel.TOOL_TRIBE);
if (GameData.getCurrentGame().isFinalWeek()){
btnCastOff.setToolTipText(TOOL_WINNER);
} else {
btnCastOff.setToolTipText(TOOL_CASTOFF);
}
btnSave.setToolTipText(TOOL_SAVE);
imgDisplay.setToolTipText(TOOL_IMAGE);
btnAddNew.setToolTipText(TOOL_ADDNEW);
btnDelete.setToolTipText(TOOL_DELETE);
}
/**
* Wrapper that allows the super class to do most of the work. Small
* adjustments for contestants vs. players.
*
* @param c
* @param newContestant
*/
@Override
protected void setPanelPerson(Contestant c, boolean newContestant) {
super.setPanelPerson(c, newContestant);
btnCastOff.setEnabled(GameData.getCurrentGame().isSeasonStarted());
if (newContestant || c == null) {
// we don't want any rows selected
ListSelectionModel m = table.getSelectionModel();
m.clearSelection();
return;
}
tableModel.setRowSelect(c);
}
/**
* Sets the error infromation based on an exception!
*
* @param e
* Exception with the information necessary
*/
@Override
protected void setExceptionError(InvalidFieldException e) {
if (e.isHandled())
return;
MainFrame mf = MainFrame.getRunningFrame();
switch (e.getField()) {
case CONT_ID:
mf.setStatusErrorMsg("Invalid ID (must be 2 alphanumeric "
+ "characters long)", tfContID);
break;
case CONT_ID_DUP:
mf.setStatusErrorMsg("Invalid ID (in use)", tfContID);
break;
case CONT_FIRST:
mf.setStatusErrorMsg("Invalid First Name (must be alphabetic"
+ ", 1-20 characters)", tfFirstName);
break;
case CONT_LAST:
mf.setStatusErrorMsg("Invalid Last Name (must be alphabetic"
+ ", 1-20 characters)", tfLastName);
break;
case CONT_TRIBE: // how you did this is beyond me..
mf.setStatusErrorMsg("Invalid Tribe selection", cbTribe);
break;
default:
mf.setStatusErrorMsg("Unknown problem with fields");
}
e.handle();
}
/**
* Used to store the listener event so we can remove it later.
*/
private ActionListener imgButtonListener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JFileChooser fc = new JFileChooser();
int ret = fc.showOpenDialog(null);
if (ret == JFileChooser.APPROVE_OPTION) {
// File f = fc.getSelectedFile();
updateContPicture(fc.getSelectedFile().getAbsolutePath());
}
}
};
/**
*
*/
@Override
protected void buildActions() {
super.buildActions();
btnAddNew.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
GameData g = GameData.getCurrentGame();
// check if too many contestants
if (g.getAllContestants().size() == g.getInitialContestants()) {
JOptionPane.showMessageDialog(
null,
"There are already the maximum "
+ "number of contestants in the " +
"game. To add another you must " +
"delete an existing contestant.");
return;
}
if (getFieldsChanged()) {
try {
savePerson();
} catch (InvalidFieldException ex) {
setExceptionError(ex);
return;
}
}
setPanelPerson(null, true);
}
});
btnCastOff.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String s = ((JButton) e.getSource()).getText();
Contestant c = null;
try {
c = getPerson();
} catch (InvalidFieldException ie) {
// FIXME: Intelligently respond on the exception.
// In theory, it shouldn't happen, but we shouldn't cast
// someone who isn't fully in the game.. :/
return;
}
- if (s.equals("Cast Off")) {
+ if (s.equals("Cast Off") || s.equals("Select Winner")) {
// check if someone is already cast off
if (GameData.getCurrentGame().doesElimExist() == true) {
JOptionPane.showMessageDialog(
null,
"You can't cast off more than one " +
"person per week. If you accidently" +
" casted the wrong person, you can " +
"undo the incorrect cast first, and " +
"then cast off the correct one.");
return;
}
// can't cast off someone already off.
if (c.isCastOff()) {
JOptionPane.showMessageDialog(null,
"This person is already out of the game.");
return;
}
c.toCastOff();
- labelCastStatus.setText("Week " + c.getCastDate());
+ if (GameData.getCurrentGame().isFinalWeek())
+ labelCastStatus.setText("Winner");
+ else
+ labelCastStatus.setText("Week " + c.getCastDate());
} else {
c.undoCast();
labelCastStatus.setText("Active");
- btnCastOff.setText("Cast Off");
+ if (GameData.getCurrentGame().isFinalWeek())
+ btnCastOff.setText("Select Winner");
+ else
+ btnCastOff.setText("Cast Off");
}
update(GameData.getCurrentGame(), null);
}
});
imgDisplay.addActionListener(imgButtonListener);
new FileDrop( this, new FileDrop.Listener(){
public void filesDropped( java.io.File[] files ){
updateContPicture(files[0].getAbsolutePath());
}
});
List<JTextField> tfArr = Arrays.asList(tfContID, tfFirstName,
tfLastName);
for (JTextField tf : tfArr) {
tf.addFocusListener(editAdapt);
}
}
/**
* Convienience wrapper.
* @param absolutePath
*/
protected void updateContPicture(String absolutePath) {
((ContestantFieldsPanel)personFields).updateContPicture(absolutePath);
}
@Override
public void mouseClicked(MouseEvent e) {
return;
}
@Override
public void mouseEntered(MouseEvent e) {
JComponent c = (JComponent)e.getComponent();
MainFrame mf = MainFrame.getRunningFrame();
String txt = c.getToolTipText();
if (txt != null)
mf.setStatusMsg(txt);
}
@Override
public void mouseExited(MouseEvent e) {
mouseEntered(e);
}
// unused
@Override
public void mousePressed(MouseEvent e) {
Component c = e.getComponent();
if (c == tfContID || c == tfFirstName || c == tfLastName
|| c == cbTribe || c == table || c == btnCastOff) {
setFieldsChanged(true);
}
}
// unused
@Override
public void mouseReleased(MouseEvent e) {
return;
}
/**
* Refreshes all values associated with GameData reference. <br>
* Currently: - Tribe combobox - Table - Sets buttons enabled/disabled as
* appropriate.
*
* @see GameDataDependant.refreshGameFields
*/
@Override
public void update(Observable obj, Object arg) {
GameData g = (GameData) obj;
// tribe combobox
String[] newTribes = g.getTribeNames();
cbTribe.removeAllItems();
for (String s : newTribes) {
cbTribe.addItem(s);
}
// updates the data in the table
tableModel.fireTableDataChanged();
// depends on season started:
boolean sStart = g.isSeasonStarted();
// change text to "select winner" once its the final week
if (g.isFinalWeek())
btnCastOff.setText("Select Winner");
btnAddNew.setEnabled(!sStart);
btnCastOff.setEnabled(sStart);
btnDelete.setEnabled(!sStart);
tfLastName.setEnabled(!sStart);
tfFirstName.setEnabled(!sStart);
tfContID.setEnabled(!sStart);
List<ActionListener> acts = Arrays.asList(imgDisplay
.getActionListeners());
boolean actPresent = acts.contains(imgButtonListener);
if (actPresent && sStart) {
imgDisplay.removeActionListener(imgButtonListener);
} else if (!actPresent && !sStart) {
imgDisplay.addActionListener(imgButtonListener);
}
}
}
| false | true | protected void buildActions() {
super.buildActions();
btnAddNew.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
GameData g = GameData.getCurrentGame();
// check if too many contestants
if (g.getAllContestants().size() == g.getInitialContestants()) {
JOptionPane.showMessageDialog(
null,
"There are already the maximum "
+ "number of contestants in the " +
"game. To add another you must " +
"delete an existing contestant.");
return;
}
if (getFieldsChanged()) {
try {
savePerson();
} catch (InvalidFieldException ex) {
setExceptionError(ex);
return;
}
}
setPanelPerson(null, true);
}
});
btnCastOff.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String s = ((JButton) e.getSource()).getText();
Contestant c = null;
try {
c = getPerson();
} catch (InvalidFieldException ie) {
// FIXME: Intelligently respond on the exception.
// In theory, it shouldn't happen, but we shouldn't cast
// someone who isn't fully in the game.. :/
return;
}
if (s.equals("Cast Off")) {
// check if someone is already cast off
if (GameData.getCurrentGame().doesElimExist() == true) {
JOptionPane.showMessageDialog(
null,
"You can't cast off more than one " +
"person per week. If you accidently" +
" casted the wrong person, you can " +
"undo the incorrect cast first, and " +
"then cast off the correct one.");
return;
}
// can't cast off someone already off.
if (c.isCastOff()) {
JOptionPane.showMessageDialog(null,
"This person is already out of the game.");
return;
}
c.toCastOff();
labelCastStatus.setText("Week " + c.getCastDate());
} else {
c.undoCast();
labelCastStatus.setText("Active");
btnCastOff.setText("Cast Off");
}
update(GameData.getCurrentGame(), null);
}
});
imgDisplay.addActionListener(imgButtonListener);
new FileDrop( this, new FileDrop.Listener(){
public void filesDropped( java.io.File[] files ){
updateContPicture(files[0].getAbsolutePath());
}
});
List<JTextField> tfArr = Arrays.asList(tfContID, tfFirstName,
tfLastName);
for (JTextField tf : tfArr) {
tf.addFocusListener(editAdapt);
}
}
| protected void buildActions() {
super.buildActions();
btnAddNew.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
GameData g = GameData.getCurrentGame();
// check if too many contestants
if (g.getAllContestants().size() == g.getInitialContestants()) {
JOptionPane.showMessageDialog(
null,
"There are already the maximum "
+ "number of contestants in the " +
"game. To add another you must " +
"delete an existing contestant.");
return;
}
if (getFieldsChanged()) {
try {
savePerson();
} catch (InvalidFieldException ex) {
setExceptionError(ex);
return;
}
}
setPanelPerson(null, true);
}
});
btnCastOff.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String s = ((JButton) e.getSource()).getText();
Contestant c = null;
try {
c = getPerson();
} catch (InvalidFieldException ie) {
// FIXME: Intelligently respond on the exception.
// In theory, it shouldn't happen, but we shouldn't cast
// someone who isn't fully in the game.. :/
return;
}
if (s.equals("Cast Off") || s.equals("Select Winner")) {
// check if someone is already cast off
if (GameData.getCurrentGame().doesElimExist() == true) {
JOptionPane.showMessageDialog(
null,
"You can't cast off more than one " +
"person per week. If you accidently" +
" casted the wrong person, you can " +
"undo the incorrect cast first, and " +
"then cast off the correct one.");
return;
}
// can't cast off someone already off.
if (c.isCastOff()) {
JOptionPane.showMessageDialog(null,
"This person is already out of the game.");
return;
}
c.toCastOff();
if (GameData.getCurrentGame().isFinalWeek())
labelCastStatus.setText("Winner");
else
labelCastStatus.setText("Week " + c.getCastDate());
} else {
c.undoCast();
labelCastStatus.setText("Active");
if (GameData.getCurrentGame().isFinalWeek())
btnCastOff.setText("Select Winner");
else
btnCastOff.setText("Cast Off");
}
update(GameData.getCurrentGame(), null);
}
});
imgDisplay.addActionListener(imgButtonListener);
new FileDrop( this, new FileDrop.Listener(){
public void filesDropped( java.io.File[] files ){
updateContPicture(files[0].getAbsolutePath());
}
});
List<JTextField> tfArr = Arrays.asList(tfContID, tfFirstName,
tfLastName);
for (JTextField tf : tfArr) {
tf.addFocusListener(editAdapt);
}
}
|
diff --git a/src/edgruberman/bukkit/guillotine/commands/Reload.java b/src/edgruberman/bukkit/guillotine/commands/Reload.java
index c5b7a61..d7f6a86 100644
--- a/src/edgruberman/bukkit/guillotine/commands/Reload.java
+++ b/src/edgruberman/bukkit/guillotine/commands/Reload.java
@@ -1,26 +1,26 @@
package edgruberman.bukkit.guillotine.commands;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.plugin.Plugin;
import edgruberman.bukkit.guillotine.Main;
public final class Reload implements CommandExecutor {
private final Plugin plugin;
public Reload(final Plugin plugin) {
this.plugin = plugin;
}
@Override
public boolean onCommand(final CommandSender sender, final Command command, final String label, final String[] args) {
this.plugin.onDisable();
this.plugin.onEnable();
- Main.courier.send(sender, "messages.reload", this.plugin.getName());
+ Main.courier.send(sender, "reload", this.plugin.getName());
return true;
}
}
| true | true | public boolean onCommand(final CommandSender sender, final Command command, final String label, final String[] args) {
this.plugin.onDisable();
this.plugin.onEnable();
Main.courier.send(sender, "messages.reload", this.plugin.getName());
return true;
}
| public boolean onCommand(final CommandSender sender, final Command command, final String label, final String[] args) {
this.plugin.onDisable();
this.plugin.onEnable();
Main.courier.send(sender, "reload", this.plugin.getName());
return true;
}
|
diff --git a/org.smartsnip/src/org/smartsnip/client/Meta.java b/org.smartsnip/src/org/smartsnip/client/Meta.java
index ca55189..7a6a875 100644
--- a/org.smartsnip/src/org/smartsnip/client/Meta.java
+++ b/org.smartsnip/src/org/smartsnip/client/Meta.java
@@ -1,234 +1,234 @@
package org.smartsnip.client;
import org.smartsnip.shared.IModerator;
import org.smartsnip.shared.ISession;
import org.smartsnip.shared.IUser;
import org.smartsnip.shared.XUser;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Anchor;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HasVerticalAlignment;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.VerticalPanel;
/**
*
*
*
* @author Paul
* @author Felix Niederwanger
*
*
* A composed Widget to display the meta navigation menu
*
*/
public class Meta extends Composite {
private final VerticalPanel pnlUser;
private final HorizontalPanel metaPanel;
private final Anchor user;
private final Anchor login;
private final Anchor register;
private final Anchor logout;
private final Anchor mod;
private final Image icon;
private final Control control;
private final NotificationIcon notificationIcon;
/**
* Initializes the menu
*/
public Meta() {
control = Control.getInstance();
pnlUser = new VerticalPanel();
metaPanel = new HorizontalPanel();
mod = new Anchor("Moderator");
login = new Anchor(" > Login");
user = new Anchor("Guest");
register = new Anchor(" > Register");
logout = new Anchor(" > Logout");
notificationIcon = new NotificationIcon();
- icon = new Image(Control.baseURL + "/images/user1.png");
+ icon = new Image(Control.baseURL + "/images/guest.png");
icon.setSize("35px", "35px");
user.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
control.changeSite('p');
}
});
mod.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
control.changeSite('m');
}
});
login.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
control.changeSite('l');
}
});
register.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
control.changeSite('r');
}
});
logout.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
control.logout();
}
});
metaPanel.setVerticalAlignment(HasVerticalAlignment.ALIGN_MIDDLE);
metaPanel.add(icon);
metaPanel.add(user);
metaPanel.add(login);
metaPanel.add(register);
metaPanel.add(mod);
metaPanel.add(notificationIcon);
metaPanel.add(logout);
// Default visibility
changeToolbarVisibility(false);
initWidget(metaPanel);
applyStyles();
}
private void applyStyles() {
mod.setStyleName("mod");
user.setStyleName("user");
// Give the overall composite a style name.
setStyleName("meta");
}
/** Update */
public void update() {
ISession.Util.getInstance().isLoggedIn(new AsyncCallback<Boolean>() {
@Override
public void onSuccess(Boolean result) {
if (result == null) {
onFailure(new IllegalArgumentException("NUll returned"));
return;
}
update(result);
}
@Override
public void onFailure(Throwable caught) {
// TODO Possible error handling!
}
});
}
/**
* Second step for the update cycle. Called after the callback for isLogged
* in has been received
*
* @param isLoggedin
* indicating if the current session is logged in or not
*/
private void update(final boolean isLoggedin) {
changeToolbarVisibility(isLoggedin);
if (isLoggedin) {
user.setText("Fetching user data ... ");
IUser.Util.getInstance().getMe(new AsyncCallback<XUser>() {
@Override
public void onSuccess(XUser result) {
if (result == null)
return;
user.setText(result.realname + " | " + result.email);
}
@Override
public void onFailure(Throwable caught) {
user.setText("<< Error fetching Userdata >>");
}
});
IModerator.Util.getInstance().isModerator(new AsyncCallback<Boolean>() {
@Override
public void onSuccess(Boolean result) {
if (result == null)
return;
boolean isModerator = result;
mod.setVisible(isModerator);
if (isModerator)
icon.setUrl(Control.baseURL + "/images/moderator.png");
else
icon.setUrl(Control.baseURL + "/images/user.png");
}
@Override
public void onFailure(Throwable caught) {
}
});
} else {
// If not logged in
user.setText("Guest");
icon.setUrl(Control.baseURL + "/images/guest.png");
}
}
/**
* Changes the visibility state of the toolbar elements based on the login
* status
*
* @param loggedIn
* login status
*/
private void changeToolbarVisibility(final boolean loggedIn) {
// With the visibility this frak is not working
// FRAKKING GWT!!!
// XXX Ugly hack to get rid of the visibility problem
metaPanel.clear();
metaPanel.add(icon);
metaPanel.add(user);
if (!loggedIn) {
metaPanel.add(login);
metaPanel.add(register);
} else {
metaPanel.add(mod);
metaPanel.add(notificationIcon);
metaPanel.add(logout);
}
// login.setVisible(!loggedIn);
// register.setVisible(!loggedIn);
// logout.setVisible(loggedIn);
// notificationIcon.setVisible(loggedIn);
// if (!loggedIn)
// mod.setVisible(false);
}
}
| true | true | public Meta() {
control = Control.getInstance();
pnlUser = new VerticalPanel();
metaPanel = new HorizontalPanel();
mod = new Anchor("Moderator");
login = new Anchor(" > Login");
user = new Anchor("Guest");
register = new Anchor(" > Register");
logout = new Anchor(" > Logout");
notificationIcon = new NotificationIcon();
icon = new Image(Control.baseURL + "/images/user1.png");
icon.setSize("35px", "35px");
user.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
control.changeSite('p');
}
});
mod.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
control.changeSite('m');
}
});
login.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
control.changeSite('l');
}
});
register.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
control.changeSite('r');
}
});
logout.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
control.logout();
}
});
metaPanel.setVerticalAlignment(HasVerticalAlignment.ALIGN_MIDDLE);
metaPanel.add(icon);
metaPanel.add(user);
metaPanel.add(login);
metaPanel.add(register);
metaPanel.add(mod);
metaPanel.add(notificationIcon);
metaPanel.add(logout);
// Default visibility
changeToolbarVisibility(false);
initWidget(metaPanel);
applyStyles();
}
| public Meta() {
control = Control.getInstance();
pnlUser = new VerticalPanel();
metaPanel = new HorizontalPanel();
mod = new Anchor("Moderator");
login = new Anchor(" > Login");
user = new Anchor("Guest");
register = new Anchor(" > Register");
logout = new Anchor(" > Logout");
notificationIcon = new NotificationIcon();
icon = new Image(Control.baseURL + "/images/guest.png");
icon.setSize("35px", "35px");
user.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
control.changeSite('p');
}
});
mod.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
control.changeSite('m');
}
});
login.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
control.changeSite('l');
}
});
register.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
control.changeSite('r');
}
});
logout.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
control.logout();
}
});
metaPanel.setVerticalAlignment(HasVerticalAlignment.ALIGN_MIDDLE);
metaPanel.add(icon);
metaPanel.add(user);
metaPanel.add(login);
metaPanel.add(register);
metaPanel.add(mod);
metaPanel.add(notificationIcon);
metaPanel.add(logout);
// Default visibility
changeToolbarVisibility(false);
initWidget(metaPanel);
applyStyles();
}
|
diff --git a/trunk/src/java/org/apache/commons/dbcp2/datasources/InstanceKeyDataSource.java b/trunk/src/java/org/apache/commons/dbcp2/datasources/InstanceKeyDataSource.java
index 5fca94a..20f0aab 100644
--- a/trunk/src/java/org/apache/commons/dbcp2/datasources/InstanceKeyDataSource.java
+++ b/trunk/src/java/org/apache/commons/dbcp2/datasources/InstanceKeyDataSource.java
@@ -1,945 +1,945 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.dbcp2.datasources;
import java.io.OutputStreamWriter;
import java.io.Serializable;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import java.util.NoSuchElementException;
import java.util.Properties;
import java.util.logging.Logger;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.naming.Reference;
import javax.naming.StringRefAddr;
import javax.naming.Referenceable;
import javax.sql.ConnectionPoolDataSource;
import javax.sql.DataSource;
import javax.sql.PooledConnection;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
/**
* <p>The base class for <code>SharedPoolDataSource</code> and
* <code>PerUserPoolDataSource</code>. Many of the configuration properties
* are shared and defined here. This class is declared public in order
* to allow particular usage with commons-beanutils; do not make direct
* use of it outside of commons-dbcp.
* </p>
*
* <p>
* A J2EE container will normally provide some method of initializing the
* <code>DataSource</code> whose attributes are presented
* as bean getters/setters and then deploying it via JNDI. It is then
* available to an application as a source of pooled logical connections to
* the database. The pool needs a source of physical connections. This
* source is in the form of a <code>ConnectionPoolDataSource</code> that
* can be specified via the {@link #setDataSourceName(String)} used to
* lookup the source via JNDI.
* </p>
*
* <p>
* Although normally used within a JNDI environment, A DataSource
* can be instantiated and initialized as any bean. In this case the
* <code>ConnectionPoolDataSource</code> will likely be instantiated in
* a similar manner. This class allows the physical source of connections
* to be attached directly to this pool using the
* {@link #setConnectionPoolDataSource(ConnectionPoolDataSource)} method.
* </p>
*
* <p>
* The dbcp package contains an adapter,
* {@link org.apache.commons.dbcp2.cpdsadapter.DriverAdapterCPDS},
* that can be used to allow the use of <code>DataSource</code>'s based on this
* class with jdbc driver implementations that do not supply a
* <code>ConnectionPoolDataSource</code>, but still
* provide a {@link java.sql.Driver} implementation.
* </p>
*
* <p>
* The <a href="package-summary.html">package documentation</a> contains an
* example using Apache Tomcat and JNDI and it also contains a non-JNDI example.
* </p>
*
* @author John D. McNally
* @version $Revision$ $Date$
*/
public abstract class InstanceKeyDataSource
implements DataSource, Referenceable, Serializable {
private static final long serialVersionUID = -4243533936955098795L;
private static final String GET_CONNECTION_CALLED
= "A Connection was already requested from this source, "
+ "further initialization is not allowed.";
private static final String BAD_TRANSACTION_ISOLATION
= "The requested TransactionIsolation level is invalid.";
/**
* Internal constant to indicate the level is not set.
*/
protected static final int UNKNOWN_TRANSACTIONISOLATION = -1;
/** Guards property setters - once true, setters throw IllegalStateException */
private volatile boolean getConnectionCalled = false;
/** Underlying source of PooledConnections */
private ConnectionPoolDataSource dataSource = null;
/** DataSource Name used to find the ConnectionPoolDataSource */
private String dataSourceName = null;
// Default connection properties
private boolean defaultAutoCommit = false;
private int defaultTransactionIsolation = UNKNOWN_TRANSACTIONISOLATION;
private boolean defaultReadOnly = false;
/** Description */
private String description = null;
/** Environment that may be used to set up a jndi initial context. */
private Properties jndiEnvironment = null;
/** Login TimeOut in seconds */
private int loginTimeout = 0;
/** Log stream */
private PrintWriter logWriter = null;
// Pool properties
private boolean _testOnBorrow =
GenericObjectPoolConfig.DEFAULT_TEST_ON_BORROW;
private boolean _testOnReturn =
GenericObjectPoolConfig.DEFAULT_TEST_ON_RETURN;
private int _timeBetweenEvictionRunsMillis = (int)
Math.min(Integer.MAX_VALUE,
GenericObjectPoolConfig.DEFAULT_TIME_BETWEEN_EVICTION_RUNS_MILLIS);
private int _numTestsPerEvictionRun =
GenericObjectPoolConfig.DEFAULT_NUM_TESTS_PER_EVICTION_RUN;
private int _minEvictableIdleTimeMillis = (int)
Math.min(Integer.MAX_VALUE,
GenericObjectPoolConfig.DEFAULT_MIN_EVICTABLE_IDLE_TIME_MILLIS);
private boolean _testWhileIdle =
GenericObjectPoolConfig.DEFAULT_TEST_WHILE_IDLE;
private String validationQuery = null;
private boolean rollbackAfterValidation = false;
private long maxConnLifetimeMillis = -1;
/** true iff one of the setters for testOnBorrow, testOnReturn, testWhileIdle has been called. */
private boolean testPositionSet = false;
/** Instance key */
private String instanceKey = null; // TODO make packge protected?
/**
* Default no-arg constructor for Serialization
*/
public InstanceKeyDataSource() {
defaultAutoCommit = true;
}
/**
* Throws an IllegalStateException, if a PooledConnection has already
* been requested.
*/
protected void assertInitializationAllowed()
throws IllegalStateException {
if (getConnectionCalled) {
throw new IllegalStateException(GET_CONNECTION_CALLED);
}
}
/**
* Close the connection pool being maintained by this datasource.
*/
public abstract void close() throws Exception;
protected abstract PooledConnectionManager getConnectionManager(UserPassKey upkey);
/* JDBC_4_ANT_KEY_BEGIN */
@Override
public boolean isWrapperFor(Class<?> iface) throws SQLException {
return false;
}
@Override
public <T> T unwrap(Class<T> iface) throws SQLException {
throw new SQLException("InstanceKeyDataSource is not a wrapper.");
}
/* JDBC_4_ANT_KEY_END */
@Override
public Logger getParentLogger() throws SQLFeatureNotSupportedException {
throw new SQLFeatureNotSupportedException();
}
// -------------------------------------------------------------------
// Properties
/**
* Get the value of connectionPoolDataSource. This method will return
* null, if the backing datasource is being accessed via jndi.
*
* @return value of connectionPoolDataSource.
*/
public ConnectionPoolDataSource getConnectionPoolDataSource() {
return dataSource;
}
/**
* Set the backend ConnectionPoolDataSource. This property should not be
* set if using jndi to access the datasource.
*
* @param v Value to assign to connectionPoolDataSource.
*/
public void setConnectionPoolDataSource(ConnectionPoolDataSource v) {
assertInitializationAllowed();
if (dataSourceName != null) {
throw new IllegalStateException(
"Cannot set the DataSource, if JNDI is used.");
}
if (dataSource != null)
{
throw new IllegalStateException(
"The CPDS has already been set. It cannot be altered.");
}
dataSource = v;
instanceKey = InstanceKeyObjectFactory.registerNewInstance(this);
}
/**
* Get the name of the ConnectionPoolDataSource which backs this pool.
* This name is used to look up the datasource from a jndi service
* provider.
*
* @return value of dataSourceName.
*/
public String getDataSourceName() {
return dataSourceName;
}
/**
* Set the name of the ConnectionPoolDataSource which backs this pool.
* This name is used to look up the datasource from a jndi service
* provider.
*
* @param v Value to assign to dataSourceName.
*/
public void setDataSourceName(String v) {
assertInitializationAllowed();
if (dataSource != null) {
throw new IllegalStateException(
"Cannot set the JNDI name for the DataSource, if already " +
"set using setConnectionPoolDataSource.");
}
if (dataSourceName != null)
{
throw new IllegalStateException(
"The DataSourceName has already been set. " +
"It cannot be altered.");
}
this.dataSourceName = v;
instanceKey = InstanceKeyObjectFactory.registerNewInstance(this);
}
/**
* Get the value of defaultAutoCommit, which defines the state of
* connections handed out from this pool. The value can be changed
* on the Connection using Connection.setAutoCommit(boolean).
* The default is true.
*
* @return value of defaultAutoCommit.
*/
public boolean isDefaultAutoCommit() {
return defaultAutoCommit;
}
/**
* Set the value of defaultAutoCommit, which defines the state of
* connections handed out from this pool. The value can be changed
* on the Connection using Connection.setAutoCommit(boolean).
* The default is true.
*
* @param v Value to assign to defaultAutoCommit.
*/
public void setDefaultAutoCommit(boolean v) {
assertInitializationAllowed();
this.defaultAutoCommit = v;
}
/**
* Get the value of defaultReadOnly, which defines the state of
* connections handed out from this pool. The value can be changed
* on the Connection using Connection.setReadOnly(boolean).
* The default is false.
*
* @return value of defaultReadOnly.
*/
public boolean isDefaultReadOnly() {
return defaultReadOnly;
}
/**
* Set the value of defaultReadOnly, which defines the state of
* connections handed out from this pool. The value can be changed
* on the Connection using Connection.setReadOnly(boolean).
* The default is false.
*
* @param v Value to assign to defaultReadOnly.
*/
public void setDefaultReadOnly(boolean v) {
assertInitializationAllowed();
this.defaultReadOnly = v;
}
/**
* Get the value of defaultTransactionIsolation, which defines the state of
* connections handed out from this pool. The value can be changed
* on the Connection using Connection.setTransactionIsolation(int).
* If this method returns -1, the default is JDBC driver dependent.
*
* @return value of defaultTransactionIsolation.
*/
public int getDefaultTransactionIsolation() {
return defaultTransactionIsolation;
}
/**
* Set the value of defaultTransactionIsolation, which defines the state of
* connections handed out from this pool. The value can be changed
* on the Connection using Connection.setTransactionIsolation(int).
* The default is JDBC driver dependent.
*
* @param v Value to assign to defaultTransactionIsolation
*/
public void setDefaultTransactionIsolation(int v) {
assertInitializationAllowed();
switch (v) {
case Connection.TRANSACTION_NONE:
case Connection.TRANSACTION_READ_COMMITTED:
case Connection.TRANSACTION_READ_UNCOMMITTED:
case Connection.TRANSACTION_REPEATABLE_READ:
case Connection.TRANSACTION_SERIALIZABLE:
break;
default:
throw new IllegalArgumentException(BAD_TRANSACTION_ISOLATION);
}
this.defaultTransactionIsolation = v;
}
/**
* Get the description. This property is defined by jdbc as for use with
* GUI (or other) tools that might deploy the datasource. It serves no
* internal purpose.
*
* @return value of description.
*/
public String getDescription() {
return description;
}
/**
* Set the description. This property is defined by jdbc as for use with
* GUI (or other) tools that might deploy the datasource. It serves no
* internal purpose.
*
* @param v Value to assign to description.
*/
public void setDescription(String v) {
this.description = v;
}
protected String getInstanceKey() {
return instanceKey;
}
/**
* Get the value of jndiEnvironment which is used when instantiating
* a jndi InitialContext. This InitialContext is used to locate the
* backend ConnectionPoolDataSource.
*
* @return value of jndiEnvironment.
*/
public String getJndiEnvironment(String key) {
String value = null;
if (jndiEnvironment != null) {
value = jndiEnvironment.getProperty(key);
}
return value;
}
/**
* Sets the value of the given JNDI environment property to be used when
* instantiating a JNDI InitialContext. This InitialContext is used to
* locate the backend ConnectionPoolDataSource.
*
* @param key the JNDI environment property to set.
* @param value the value assigned to specified JNDI environment property.
*/
public void setJndiEnvironment(String key, String value) {
if (jndiEnvironment == null) {
jndiEnvironment = new Properties();
}
jndiEnvironment.setProperty(key, value);
}
/**
* Sets the JNDI environment to be used when instantiating a JNDI
* InitialContext. This InitialContext is used to locate the backend
* ConnectionPoolDataSource.
*
* @param properties the JNDI environment property to set which will
* overwrite any current settings
*/
void setJndiEnvironment(Properties properties) {
if (jndiEnvironment == null) {
jndiEnvironment = new Properties();
} else {
jndiEnvironment.clear();
}
jndiEnvironment.putAll(properties);
}
/**
* Get the value of loginTimeout.
* @return value of loginTimeout.
*/
@Override
public int getLoginTimeout() {
return loginTimeout;
}
/**
* Set the value of loginTimeout.
* @param v Value to assign to loginTimeout.
*/
@Override
public void setLoginTimeout(int v) {
this.loginTimeout = v;
}
/**
* Get the value of logWriter.
* @return value of logWriter.
*/
@Override
public PrintWriter getLogWriter() {
if (logWriter == null) {
logWriter = new PrintWriter(
new OutputStreamWriter(System.out, StandardCharsets.UTF_8));
}
return logWriter;
}
/**
* Set the value of logWriter.
* @param v Value to assign to logWriter.
*/
@Override
public void setLogWriter(PrintWriter v) {
this.logWriter = v;
}
/**
* @see #getTestOnBorrow
*/
public final boolean isTestOnBorrow() {
return getTestOnBorrow();
}
/**
* When <tt>true</tt>, objects will be
* {*link PoolableObjectFactory#validateObject validated}
* before being returned by the {*link #borrowObject}
* method. If the object fails to validate,
* it will be dropped from the pool, and we will attempt
* to borrow another.
*
* @see #setTestOnBorrow
*/
public boolean getTestOnBorrow() {
return _testOnBorrow;
}
/**
* When <tt>true</tt>, objects will be
* {*link PoolableObjectFactory#validateObject validated}
* before being returned by the {*link #borrowObject}
* method. If the object fails to validate,
* it will be dropped from the pool, and we will attempt
* to borrow another. For a <code>true</code> value to have any effect,
* the <code>validationQuery</code> property must be set to a non-null
* string.
*
* @see #getTestOnBorrow
*/
public void setTestOnBorrow(boolean testOnBorrow) {
assertInitializationAllowed();
_testOnBorrow = testOnBorrow;
testPositionSet = true;
}
/**
* @see #getTestOnReturn
*/
public final boolean isTestOnReturn() {
return getTestOnReturn();
}
/**
* When <tt>true</tt>, objects will be
* {*link PoolableObjectFactory#validateObject validated}
* before being returned to the pool within the
* {*link #returnObject}.
*
* @see #setTestOnReturn
*/
public boolean getTestOnReturn() {
return _testOnReturn;
}
/**
* When <tt>true</tt>, objects will be
* {*link PoolableObjectFactory#validateObject validated}
* before being returned to the pool within the
* {*link #returnObject}. For a <code>true</code> value to have any effect,
* the <code>validationQuery</code> property must be set to a non-null
* string.
*
* @see #getTestOnReturn
*/
public void setTestOnReturn(boolean testOnReturn) {
assertInitializationAllowed();
_testOnReturn = testOnReturn;
testPositionSet = true;
}
/**
* Returns the number of milliseconds to sleep between runs of the
* idle object evictor thread.
* When non-positive, no idle object evictor thread will be
* run.
*
* @see #setTimeBetweenEvictionRunsMillis
*/
public int getTimeBetweenEvictionRunsMillis() {
return _timeBetweenEvictionRunsMillis;
}
/**
* Sets the number of milliseconds to sleep between runs of the
* idle object evictor thread.
* When non-positive, no idle object evictor thread will be
* run.
*
* @see #getTimeBetweenEvictionRunsMillis
*/
public void
setTimeBetweenEvictionRunsMillis(int timeBetweenEvictionRunsMillis) {
assertInitializationAllowed();
_timeBetweenEvictionRunsMillis = timeBetweenEvictionRunsMillis;
}
/**
* Returns the number of objects to examine during each run of the
* idle object evictor thread (if any).
*
* @see #setNumTestsPerEvictionRun
* @see #setTimeBetweenEvictionRunsMillis
*/
public int getNumTestsPerEvictionRun() {
return _numTestsPerEvictionRun;
}
/**
* Sets the number of objects to examine during each run of the
* idle object evictor thread (if any).
* <p>
* When a negative value is supplied, <tt>ceil({*link #numIdle})/abs({*link #getNumTestsPerEvictionRun})</tt>
* tests will be run. I.e., when the value is <i>-n</i>, roughly one <i>n</i>th of the
* idle objects will be tested per run.
*
* @see #getNumTestsPerEvictionRun
* @see #setTimeBetweenEvictionRunsMillis
*/
public void setNumTestsPerEvictionRun(int numTestsPerEvictionRun) {
assertInitializationAllowed();
_numTestsPerEvictionRun = numTestsPerEvictionRun;
}
/**
* Returns the minimum amount of time an object may sit idle in the pool
* before it is eligable for eviction by the idle object evictor
* (if any).
*
* @see #setMinEvictableIdleTimeMillis
* @see #setTimeBetweenEvictionRunsMillis
*/
public int getMinEvictableIdleTimeMillis() {
return _minEvictableIdleTimeMillis;
}
/**
* Sets the minimum amount of time an object may sit idle in the pool
* before it is eligable for eviction by the idle object evictor
* (if any).
* When non-positive, no objects will be evicted from the pool
* due to idle time alone.
*
* @see #getMinEvictableIdleTimeMillis
* @see #setTimeBetweenEvictionRunsMillis
*/
public void setMinEvictableIdleTimeMillis(int minEvictableIdleTimeMillis) {
assertInitializationAllowed();
_minEvictableIdleTimeMillis = minEvictableIdleTimeMillis;
}
/**
* @see #getTestWhileIdle
*/
public final boolean isTestWhileIdle() {
return getTestWhileIdle();
}
/**
* When <tt>true</tt>, objects will be
* {*link PoolableObjectFactory#validateObject validated}
* by the idle object evictor (if any). If an object
* fails to validate, it will be dropped from the pool.
*
* @see #setTestWhileIdle
* @see #setTimeBetweenEvictionRunsMillis
*/
public boolean getTestWhileIdle() {
return _testWhileIdle;
}
/**
* When <tt>true</tt>, objects will be
* {*link PoolableObjectFactory#validateObject validated}
* by the idle object evictor (if any). If an object
* fails to validate, it will be dropped from the pool. For a
* <code>true</code> value to have any effect,
* the <code>validationQuery</code> property must be set to a non-null
* string.
*
* @see #getTestWhileIdle
* @see #setTimeBetweenEvictionRunsMillis
*/
public void setTestWhileIdle(boolean testWhileIdle) {
assertInitializationAllowed();
_testWhileIdle = testWhileIdle;
testPositionSet = true;
}
/**
* The SQL query that will be used to validate connections from this pool
* before returning them to the caller. If specified, this query
* <strong>MUST</strong> be an SQL SELECT statement that returns at least
* one row.
*/
public String getValidationQuery() {
return (this.validationQuery);
}
/**
* The SQL query that will be used to validate connections from this pool
* before returning them to the caller. If specified, this query
* <strong>MUST</strong> be an SQL SELECT statement that returns at least
* one row. If none of the properties, testOnBorow, testOnReturn, testWhileIdle
* have been previously set, calling this method sets testOnBorrow to true.
*/
public void setValidationQuery(String validationQuery) {
assertInitializationAllowed();
this.validationQuery = validationQuery;
if (!testPositionSet) {
setTestOnBorrow(true);
}
}
/**
* Whether a rollback will be issued after executing the SQL query
* that will be used to validate connections from this pool
* before returning them to the caller.
*
* @return true if a rollback will be issued after executing the
* validation query
* @since 1.2.2
*/
public boolean isRollbackAfterValidation() {
return (this.rollbackAfterValidation);
}
/**
* Whether a rollback will be issued after executing the SQL query
* that will be used to validate connections from this pool
* before returning them to the caller. Default behavior is NOT
* to issue a rollback. The setting will only have an effect
* if a validation query is set
*
* @param rollbackAfterValidation new property value
* @since 1.2.2
*/
public void setRollbackAfterValidation(boolean rollbackAfterValidation) {
assertInitializationAllowed();
this.rollbackAfterValidation = rollbackAfterValidation;
}
/**
* Returns the maximum permitted lifetime of a connection in milliseconds. A
* value of zero or less indicates an infinite lifetime.
*/
public long getMaxConnLifetimeMillis() {
return maxConnLifetimeMillis;
}
/**
* <p>Sets the maximum permitted lifetime of a connection in
* milliseconds. A value of zero or less indicates an infinite lifetime.</p>
* <p>
* Note: this method currently has no effect once the pool has been
* initialized. The pool is initialized the first time one of the
* following methods is invoked: <code>getConnection, setLogwriter,
* setLoginTimeout, getLoginTimeout, getLogWriter.</code></p>
*/
public void setMaxConnLifetimeMillis(long maxConnLifetimeMillis) {
this.maxConnLifetimeMillis = maxConnLifetimeMillis;
}
// ----------------------------------------------------------------------
// Instrumentation Methods
// ----------------------------------------------------------------------
// DataSource implementation
/**
* Attempt to establish a database connection.
*/
@Override
public Connection getConnection() throws SQLException {
return getConnection(null, null);
}
/**
* Attempt to retrieve a database connection using {@link #getPooledConnectionAndInfo(String, String)}
* with the provided username and password. The password on the {@link PooledConnectionAndInfo}
* instance returned by <code>getPooledConnectionAndInfo</code> is compared to the <code>password</code>
* parameter. If the comparison fails, a database connection using the supplied username and password
* is attempted. If the connection attempt fails, an SQLException is thrown, indicating that the given password
* did not match the password used to create the pooled connection. If the connection attempt succeeds, this
* means that the database password has been changed. In this case, the <code>PooledConnectionAndInfo</code>
* instance retrieved with the old password is destroyed and the <code>getPooledConnectionAndInfo</code> is
* repeatedly invoked until a <code>PooledConnectionAndInfo</code> instance with the new password is returned.
*
*/
@Override
public Connection getConnection(String username, String password)
throws SQLException {
if (instanceKey == null) {
throw new SQLException("Must set the ConnectionPoolDataSource "
+ "through setDataSourceName or setConnectionPoolDataSource"
+ " before calling getConnection.");
}
getConnectionCalled = true;
PooledConnectionAndInfo info = null;
try {
info = getPooledConnectionAndInfo(username, password);
} catch (NoSuchElementException e) {
closeDueToException(info);
throw new SQLException("Cannot borrow connection from pool", e);
} catch (RuntimeException e) {
closeDueToException(info);
throw e;
} catch (SQLException e) {
closeDueToException(info);
throw e;
} catch (Exception e) {
closeDueToException(info);
throw new SQLException("Cannot borrow connection from pool", e);
}
if (!(null == password ? null == info.getPassword()
: password.equals(info.getPassword()))) { // Password on PooledConnectionAndInfo does not match
try { // See if password has changed by attempting connection
testCPDS(username, password);
} catch (SQLException ex) {
// Password has not changed, so refuse client, but return connection to the pool
closeDueToException(info);
throw new SQLException("Given password did not match password used"
+ " to create the PooledConnection.");
} catch (javax.naming.NamingException ne) {
throw (SQLException) new SQLException(
"NamingException encountered connecting to database").initCause(ne);
}
/*
* Password must have changed -> destroy connection and keep retrying until we get a new, good one,
* destroying any idle connections with the old passowrd as we pull them from the pool.
*/
final UserPassKey upkey = info.getUserPassKey();
final PooledConnectionManager manager = getConnectionManager(upkey);
manager.invalidate(info.getPooledConnection()); // Destroy and remove from pool
manager.setPassword(upkey.getPassword()); // Reset the password on the factory if using CPDSConnectionFactory
info = null;
for (int i = 0; i < 10; i++) { // Bound the number of retries - only needed if bad instances return
try {
info = getPooledConnectionAndInfo(username, password);
} catch (NoSuchElementException e) {
closeDueToException(info);
throw new SQLException("Cannot borrow connection from pool", e);
} catch (RuntimeException e) {
closeDueToException(info);
throw e;
} catch (SQLException e) {
closeDueToException(info);
throw e;
} catch (Exception e) {
closeDueToException(info);
throw new SQLException("Cannot borrow connection from pool", e);
}
- if (info != null && password.equals(info.getPassword())) {
+ if (info != null && password != null && password.equals(info.getPassword())) {
break;
} else {
if (info != null) {
manager.invalidate(info.getPooledConnection());
}
info = null;
}
}
if (info == null) {
throw new SQLException("Cannot borrow connection from pool - password change failure.");
}
}
Connection con = info.getPooledConnection().getConnection();
try {
setupDefaults(con, username);
con.clearWarnings();
return con;
} catch (SQLException ex) {
try {
con.close();
} catch (Exception exc) {
getLogWriter().println(
"ignoring exception during close: " + exc);
}
throw ex;
}
}
protected abstract PooledConnectionAndInfo
getPooledConnectionAndInfo(String username, String password)
throws SQLException;
protected abstract void setupDefaults(Connection con, String username)
throws SQLException;
private void closeDueToException(PooledConnectionAndInfo info) {
if (info != null) {
try {
info.getPooledConnection().getConnection().close();
} catch (Exception e) {
// do not throw this exception because we are in the middle
// of handling another exception. But record it because
// it potentially leaks connections from the pool.
getLogWriter().println("[ERROR] Could not return connection to "
+ "pool during exception handling. " + e.getMessage());
}
}
}
protected ConnectionPoolDataSource
testCPDS(String username, String password)
throws javax.naming.NamingException, SQLException {
// The source of physical db connections
ConnectionPoolDataSource cpds = this.dataSource;
if (cpds == null) {
Context ctx = null;
if (jndiEnvironment == null) {
ctx = new InitialContext();
} else {
ctx = new InitialContext(jndiEnvironment);
}
Object ds = ctx.lookup(dataSourceName);
if (ds instanceof ConnectionPoolDataSource) {
cpds = (ConnectionPoolDataSource) ds;
} else {
throw new SQLException("Illegal configuration: "
+ "DataSource " + dataSourceName
+ " (" + ds.getClass().getName() + ")"
+ " doesn't implement javax.sql.ConnectionPoolDataSource");
}
}
// try to get a connection with the supplied username/password
PooledConnection conn = null;
try {
if (username != null) {
conn = cpds.getPooledConnection(username, password);
}
else {
conn = cpds.getPooledConnection();
}
if (conn == null) {
throw new SQLException(
"Cannot connect using the supplied username/password");
}
}
finally {
if (conn != null) {
try {
conn.close();
}
catch (SQLException e) {
// at least we could connect
}
}
}
return cpds;
}
// ----------------------------------------------------------------------
// Referenceable implementation
/**
* Retrieves the Reference of this object.
* <strong>Note:</strong> <code>InstanceKeyDataSource</code> subclasses
* should override this method. The implementaion included below
* is not robust and will be removed at the next major version DBCP
* release.
*
* @return The non-null Reference of this object.
* @exception NamingException If a naming exception was encountered
* while retrieving the reference.
*/
// TODO: Remove the implementation of this method at next major
// version release.
@Override
public Reference getReference() throws NamingException {
final String className = getClass().getName();
final String factoryName = className + "Factory"; // XXX: not robust
Reference ref = new Reference(className, factoryName, null);
ref.add(new StringRefAddr("instanceKey", instanceKey));
return ref;
}
}
| true | true | public Connection getConnection(String username, String password)
throws SQLException {
if (instanceKey == null) {
throw new SQLException("Must set the ConnectionPoolDataSource "
+ "through setDataSourceName or setConnectionPoolDataSource"
+ " before calling getConnection.");
}
getConnectionCalled = true;
PooledConnectionAndInfo info = null;
try {
info = getPooledConnectionAndInfo(username, password);
} catch (NoSuchElementException e) {
closeDueToException(info);
throw new SQLException("Cannot borrow connection from pool", e);
} catch (RuntimeException e) {
closeDueToException(info);
throw e;
} catch (SQLException e) {
closeDueToException(info);
throw e;
} catch (Exception e) {
closeDueToException(info);
throw new SQLException("Cannot borrow connection from pool", e);
}
if (!(null == password ? null == info.getPassword()
: password.equals(info.getPassword()))) { // Password on PooledConnectionAndInfo does not match
try { // See if password has changed by attempting connection
testCPDS(username, password);
} catch (SQLException ex) {
// Password has not changed, so refuse client, but return connection to the pool
closeDueToException(info);
throw new SQLException("Given password did not match password used"
+ " to create the PooledConnection.");
} catch (javax.naming.NamingException ne) {
throw (SQLException) new SQLException(
"NamingException encountered connecting to database").initCause(ne);
}
/*
* Password must have changed -> destroy connection and keep retrying until we get a new, good one,
* destroying any idle connections with the old passowrd as we pull them from the pool.
*/
final UserPassKey upkey = info.getUserPassKey();
final PooledConnectionManager manager = getConnectionManager(upkey);
manager.invalidate(info.getPooledConnection()); // Destroy and remove from pool
manager.setPassword(upkey.getPassword()); // Reset the password on the factory if using CPDSConnectionFactory
info = null;
for (int i = 0; i < 10; i++) { // Bound the number of retries - only needed if bad instances return
try {
info = getPooledConnectionAndInfo(username, password);
} catch (NoSuchElementException e) {
closeDueToException(info);
throw new SQLException("Cannot borrow connection from pool", e);
} catch (RuntimeException e) {
closeDueToException(info);
throw e;
} catch (SQLException e) {
closeDueToException(info);
throw e;
} catch (Exception e) {
closeDueToException(info);
throw new SQLException("Cannot borrow connection from pool", e);
}
if (info != null && password.equals(info.getPassword())) {
break;
} else {
if (info != null) {
manager.invalidate(info.getPooledConnection());
}
info = null;
}
}
if (info == null) {
throw new SQLException("Cannot borrow connection from pool - password change failure.");
}
}
Connection con = info.getPooledConnection().getConnection();
try {
setupDefaults(con, username);
con.clearWarnings();
return con;
} catch (SQLException ex) {
try {
con.close();
} catch (Exception exc) {
getLogWriter().println(
"ignoring exception during close: " + exc);
}
throw ex;
}
}
| public Connection getConnection(String username, String password)
throws SQLException {
if (instanceKey == null) {
throw new SQLException("Must set the ConnectionPoolDataSource "
+ "through setDataSourceName or setConnectionPoolDataSource"
+ " before calling getConnection.");
}
getConnectionCalled = true;
PooledConnectionAndInfo info = null;
try {
info = getPooledConnectionAndInfo(username, password);
} catch (NoSuchElementException e) {
closeDueToException(info);
throw new SQLException("Cannot borrow connection from pool", e);
} catch (RuntimeException e) {
closeDueToException(info);
throw e;
} catch (SQLException e) {
closeDueToException(info);
throw e;
} catch (Exception e) {
closeDueToException(info);
throw new SQLException("Cannot borrow connection from pool", e);
}
if (!(null == password ? null == info.getPassword()
: password.equals(info.getPassword()))) { // Password on PooledConnectionAndInfo does not match
try { // See if password has changed by attempting connection
testCPDS(username, password);
} catch (SQLException ex) {
// Password has not changed, so refuse client, but return connection to the pool
closeDueToException(info);
throw new SQLException("Given password did not match password used"
+ " to create the PooledConnection.");
} catch (javax.naming.NamingException ne) {
throw (SQLException) new SQLException(
"NamingException encountered connecting to database").initCause(ne);
}
/*
* Password must have changed -> destroy connection and keep retrying until we get a new, good one,
* destroying any idle connections with the old passowrd as we pull them from the pool.
*/
final UserPassKey upkey = info.getUserPassKey();
final PooledConnectionManager manager = getConnectionManager(upkey);
manager.invalidate(info.getPooledConnection()); // Destroy and remove from pool
manager.setPassword(upkey.getPassword()); // Reset the password on the factory if using CPDSConnectionFactory
info = null;
for (int i = 0; i < 10; i++) { // Bound the number of retries - only needed if bad instances return
try {
info = getPooledConnectionAndInfo(username, password);
} catch (NoSuchElementException e) {
closeDueToException(info);
throw new SQLException("Cannot borrow connection from pool", e);
} catch (RuntimeException e) {
closeDueToException(info);
throw e;
} catch (SQLException e) {
closeDueToException(info);
throw e;
} catch (Exception e) {
closeDueToException(info);
throw new SQLException("Cannot borrow connection from pool", e);
}
if (info != null && password != null && password.equals(info.getPassword())) {
break;
} else {
if (info != null) {
manager.invalidate(info.getPooledConnection());
}
info = null;
}
}
if (info == null) {
throw new SQLException("Cannot borrow connection from pool - password change failure.");
}
}
Connection con = info.getPooledConnection().getConnection();
try {
setupDefaults(con, username);
con.clearWarnings();
return con;
} catch (SQLException ex) {
try {
con.close();
} catch (Exception exc) {
getLogWriter().println(
"ignoring exception during close: " + exc);
}
throw ex;
}
}
|
diff --git a/ngrinder-controller/src/main/java/org/ngrinder/perftest/controller/PerfTestController.java b/ngrinder-controller/src/main/java/org/ngrinder/perftest/controller/PerfTestController.java
index 9381238f..430e5560 100644
--- a/ngrinder-controller/src/main/java/org/ngrinder/perftest/controller/PerfTestController.java
+++ b/ngrinder-controller/src/main/java/org/ngrinder/perftest/controller/PerfTestController.java
@@ -1,951 +1,951 @@
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.ngrinder.perftest.controller;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import net.grinder.util.LogCompressUtils;
import net.grinder.util.Pair;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.Predicate;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.apache.commons.lang.mutable.MutableInt;
import org.ngrinder.agent.service.AgentManagerService;
import org.ngrinder.common.controller.BaseController;
import org.ngrinder.common.controller.RestAPI;
import org.ngrinder.common.util.DateUtils;
import org.ngrinder.common.util.FileDownloadUtils;
import org.ngrinder.infra.config.Config;
import org.ngrinder.infra.logger.CoreLogger;
import org.ngrinder.infra.spring.RemainedPath;
import org.ngrinder.model.PerfTest;
import org.ngrinder.model.Role;
import org.ngrinder.model.Status;
import org.ngrinder.model.User;
import org.ngrinder.perftest.service.AgentManager;
import org.ngrinder.perftest.service.PerfTestService;
import org.ngrinder.perftest.service.TagService;
import org.ngrinder.script.handler.ScriptHandlerFactory;
import org.ngrinder.script.model.FileCategory;
import org.ngrinder.script.model.FileEntry;
import org.ngrinder.script.service.FileEntryService;
import org.ngrinder.user.service.UserService;
import org.python.google.common.collect.Lists;
import org.python.google.common.collect.Maps;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.web.PageableDefaults;
import org.springframework.http.HttpEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import javax.annotation.PostConstruct;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.net.URL;
import java.util.*;
import static org.apache.commons.lang.StringUtils.trimToEmpty;
import static org.ngrinder.common.util.CollectionUtils.*;
import static org.ngrinder.common.util.ExceptionUtils.processException;
import static org.ngrinder.common.util.ObjectUtils.defaultIfNull;
import static org.ngrinder.common.util.Preconditions.*;
/**
* Performance Test Controller.
*
* @author Mavlarn
* @author JunHo Yoon
*/
@Controller
@RequestMapping("/perftest")
public class PerfTestController extends BaseController {
@Autowired
private PerfTestService perfTestService;
@Autowired
private FileEntryService fileEntryService;
@Autowired
private AgentManager agentManager;
@Autowired
private AgentManagerService agentManagerService;
@Autowired
private TagService tagService;
@Autowired
private ScriptHandlerFactory scriptHandlerFactory;
@Autowired
private UserService userService;
private Gson fileEntryGson;
/**
* Initialize.
*/
@PostConstruct
public void init() {
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(FileEntry.class, new FileEntry.FileEntrySerializer());
fileEntryGson = gsonBuilder.create();
}
/**
* Get the perf test lists.
*
* @param user user
* @param query query string to search the perf test
* @param model modelMap
* @param tag tag
* @param queryFilter "F" means get only finished, "S" means get only scheduled tests.
* @param pageable page
* @return perftest/list
*/
@RequestMapping({"/list", "/", ""})
public String getAll(User user, @RequestParam(required = false) String query,
@RequestParam(required = false) String tag, @RequestParam(required = false) String queryFilter,
@PageableDefaults Pageable pageable, ModelMap model) {
pageable = new PageRequest(pageable.getPageNumber(), pageable.getPageSize(),
defaultIfNull(pageable.getSort(),
new Sort(Direction.DESC, "lastModifiedDate")));
Page<PerfTest> tests = perfTestService.getPagedAll(user, query, tag, queryFilter, pageable);
annotateDateMarker(tests);
model.addAttribute("tag", tag);
model.addAttribute("availTags", tagService.getAllTagStrings(user, StringUtils.EMPTY));
model.addAttribute("testListPage", tests);
model.addAttribute("queryFilter", queryFilter);
model.addAttribute("query", query);
putPageIntoModelMap(model, pageable);
return "perftest/list";
}
private void annotateDateMarker(Page<PerfTest> tests) {
TimeZone userTZ = TimeZone.getTimeZone(getCurrentUser().getTimeZone());
Calendar userToday = Calendar.getInstance(userTZ);
Calendar userYesterday = Calendar.getInstance(userTZ);
userYesterday.add(Calendar.DATE, -1);
for (PerfTest test : tests) {
Calendar localedModified = Calendar.getInstance(userTZ);
localedModified.setTime(DateUtils.convertToUserDate(getCurrentUser().getTimeZone(),
test.getLastModifiedDate()));
if (org.apache.commons.lang.time.DateUtils.isSameDay(userToday, localedModified)) {
test.setDateString("today");
} else if (org.apache.commons.lang.time.DateUtils.isSameDay(userYesterday, localedModified)) {
test.setDateString("yesterday");
} else {
test.setDateString("earlier");
}
}
}
/**
* Open the new perf test creation form.
*
* @param user user
* @param model model
* @return "perftest/detail"
*/
@RequestMapping("/new")
public String openForm(User user, ModelMap model) {
return getOne(user, null, model);
}
/**
* Get the perf test detail on the given perf test id.
*
* @param user user
* @param model model
* @param id perf test id
* @return perftest/detail
*/
@RequestMapping("/{id}")
public String getOne(User user, @PathVariable("id") Long id, ModelMap model) {
PerfTest test;
if (id != null) {
test = getOneWithPermissionCheck(user, id, true);
} else {
test = new PerfTest(user);
test.init();
}
model.addAttribute(PARAM_TEST, test);
// Retrieve the agent count map based on create user, if the test is
// created by the others.
user = test.getCreatedUser() != null ? test.getCreatedUser() : user;
Map<String, MutableInt> agentCountMap = agentManagerService.getUserAvailableAgentCountMap(user);
model.addAttribute(PARAM_REGION_AGENT_COUNT_MAP, agentCountMap);
model.addAttribute(PARAM_REGION_LIST, getRegions(agentCountMap));
model.addAttribute(PARAM_PROCESSTHREAD_POLICY_SCRIPT, perfTestService.getProcessAndThreadPolicyScript());
addDefaultAttributeOnModel(model);
return "perftest/detail";
}
private ArrayList<String> getRegions(Map<String, MutableInt> agentCountMap) {
ArrayList<String> regions = new ArrayList<String>(agentCountMap.keySet());
Collections.sort(regions);
return regions;
}
/**
* Search tags based on the given query.
*
* @param user user to search
* @param query query string
* @return found tag list in json
*/
@RequestMapping("/search_tag")
public HttpEntity<String> searchTag(User user, @RequestParam(required = false) String query) {
List<String> allStrings = tagService.getAllTagStrings(user, query);
if (StringUtils.isNotBlank(query)) {
allStrings.add(query);
}
return toJsonHttpEntity(allStrings);
}
/**
* Add the various default configuration values on the model.
*
* @param model model to which put the default values
*/
public void addDefaultAttributeOnModel(ModelMap model) {
model.addAttribute(PARAM_MAX_VUSER_PER_AGENT, agentManager.getMaxVuserPerAgent());
model.addAttribute(PARAM_MAX_RUN_COUNT, agentManager.getMaxRunCount());
model.addAttribute(PARAM_SECURITY_MODE, getConfig().isSecurityEnabled());
model.addAttribute(PARAM_MAX_RUN_HOUR, agentManager.getMaxRunHour());
model.addAttribute(PARAM_SAFE_FILE_DISTRIBUTION,
getConfig().getSystemProperties().getPropertyBoolean(NGRINDER_PROP_DIST_SAFE, false));
String timeZone = getCurrentUser().getTimeZone();
int offset;
if (StringUtils.isNotBlank(timeZone)) {
offset = TimeZone.getTimeZone(timeZone).getOffset(System.currentTimeMillis());
} else {
offset = TimeZone.getDefault().getOffset(System.currentTimeMillis());
}
model.addAttribute(PARAM_TIMEZONE_OFFSET, offset);
}
/**
* Get the perf test creation form for quickStart.
*
* @param user user
* @param urlString URL string to be tested.
* @param scriptType scriptType
* @param model model
* @return perftest/detail
*/
@RequestMapping("/quickstart")
public String getQuickStart(User user,
@RequestParam(value = "url", required = true) String urlString,
@RequestParam(value = "scriptType", required = true) String scriptType,
ModelMap model) {
URL url = checkValidURL(urlString);
FileEntry newEntry = fileEntryService.prepareNewEntryForQuickTest(user, urlString,
scriptHandlerFactory.getHandler(scriptType));
model.addAttribute(PARAM_QUICK_SCRIPT, newEntry.getPath());
model.addAttribute(PARAM_QUICK_SCRIPT_REVISION, newEntry.getRevision());
model.addAttribute(PARAM_TEST, createPerfTestFromQuickStart(user, "Test for " + url.getHost(), url.getHost()));
Map<String, MutableInt> agentCountMap = agentManagerService.getUserAvailableAgentCountMap(user);
model.addAttribute(PARAM_REGION_AGENT_COUNT_MAP, agentCountMap);
model.addAttribute(PARAM_REGION_LIST, getRegions(agentCountMap));
addDefaultAttributeOnModel(model);
model.addAttribute(PARAM_PROCESSTHREAD_POLICY_SCRIPT, perfTestService.getProcessAndThreadPolicyScript());
return "perftest/detail";
}
/**
* Create a new test from quick start mode.
*
* @param user user
* @param testName test name
* @param targetHost target host
* @return PerfTest
*/
private PerfTest createPerfTestFromQuickStart(User user, String testName, String targetHost) {
PerfTest test = new PerfTest(user);
test.init();
test.setTestName(testName);
test.setTargetHosts(targetHost);
return test;
}
/**
* Create a new test or cloneTo a current test.
*
* @param user user
* @param model model
* @param test {@link PerfTest}
* @param isClone true if cloneTo
* @return redirect:/perftest/list
*/
@RequestMapping(value = "/new", method = RequestMethod.POST)
public String saveOne(User user, ModelMap model, PerfTest test,
@RequestParam(value = "isClone", required = false, defaultValue = "false") boolean isClone) {
test.setTestName(StringUtils.trimToEmpty(test.getTestName()));
checkNotEmpty(test.getTestName(), "test name should be provided");
checkArgument(test.getStatus().equals(Status.READY) || test.getStatus().equals(Status.SAVED),
"save test only support for SAVE or READY status");
checkArgument(test.getRunCount() == null || test.getRunCount() <= agentManager.getMaxRunCount(),
"test run count should be equal to or less than %s", agentManager.getMaxRunCount());
checkArgument(test.getDuration() == null
|| test.getDuration() <= (((long) agentManager.getMaxRunHour()) * 3600000L),
"test run duration should be equal to or less than %s", agentManager.getMaxRunHour());
Map<String, MutableInt> agentCountMap = agentManagerService.getUserAvailableAgentCountMap(user);
MutableInt agentCountObj = agentCountMap.get(isClustered() ? test.getRegion() : Config.NONE_REGION);
checkNotNull(agentCountObj, "test region should be within current region list");
int agentMaxCount = agentCountObj.intValue();
checkArgument(test.getAgentCount() <= agentMaxCount, "test agent should be equal to or less than %s",
agentMaxCount);
checkArgument(test.getVuserPerAgent() == null || test.getVuserPerAgent() <= agentManager.getMaxVuserPerAgent(),
- "test vuser should be equal to or less than %s", agentManager.getMaxVuserPerAgent());
+ "Test vuser should be equal to or less than %s", agentManager.getMaxVuserPerAgent());
if (getConfig().isSecurityEnabled()) {
checkArgument(StringUtils.isNotEmpty(test.getTargetHosts()),
- "test target hosts should be provided when security mode is enabled");
+ "Test target hosts should be provided when security mode is enabled");
}
checkArgument(test.getProcesses() != null && 0 != test.getProcesses(), "test process should not be 0");
checkArgument(test.getThreads() != null && 0 != test.getThreads(), "test thread should not be 0");
// Point to the head revision
test.setScriptRevision(-1L);
test.prepare(isClone);
test = perfTestService.save(user, test);
model.clear();
if (test.getStatus() == Status.SAVED || test.getScheduledTime() != null) {
return "redirect:/perftest/list";
} else {
return "redirect:/perftest/" + test.getId();
}
}
/**
* Leave the comment on the perf test.
*
* @param id testId
* @param user user
* @param testComment test comment
* @param tagString tagString
* @return JSON
*/
@RequestMapping(value = "/{id}/leave_comment", method = RequestMethod.POST)
@ResponseBody
public String leaveComment(User user, @PathVariable("id") Long id, @RequestParam("testComment") String testComment,
@RequestParam(value = "tagString", required = false) String tagString) {
perfTestService.addCommentOn(user, id, testComment, tagString);
return returnSuccess();
}
private Long[] convertString2Long(String ids) {
String[] numbers = StringUtils.split(ids, ",");
Long[] id = new Long[numbers.length];
int i = 0;
for (String each : numbers) {
id[i++] = NumberUtils.toLong(each, 0);
}
return id;
}
private List<Map<String, Object>> getStatus(List<PerfTest> perfTests) {
List<Map<String, Object>> statuses = newArrayList();
for (PerfTest each : perfTests) {
Map<String, Object> result = newHashMap();
result.put(PARAM_STATUS_UPDATE_ID, each.getId());
result.put(PARAM_STATUS_UPDATE_STATUS_ID, each.getStatus());
result.put(PARAM_STATUS_UPDATE_STATUS_TYPE, each.getStatus());
String errorMessages = getMessages(each.getStatus().getSpringMessageKey());
result.put(PARAM_STATUS_UPDATE_STATUS_NAME, errorMessages);
result.put(PARAM_STATUS_UPDATE_STATUS_ICON, each.getStatus().getIconName());
result.put(
PARAM_STATUS_UPDATE_STATUS_MESSAGE,
StringUtils.replace(each.getProgressMessage() + "\n<b>" + each.getLastProgressMessage() + "</b>\n"
+ each.getLastModifiedDateToStr(), "\n", "<br/>"));
result.put(PARAM_STATUS_UPDATE_DELETABLE, each.getStatus().isDeletable());
result.put(PARAM_STATUS_UPDATE_STOPPABLE, each.getStatus().isStoppable());
statuses.add(result);
}
return statuses;
}
/**
* Delete the perf tests having given IDs.
*
* @param user user
* @param ids comma operated IDs
* @return success json messages if succeeded.
*/
@RestAPI
@RequestMapping(value = "/api/delete", method = RequestMethod.POST)
public HttpEntity<String> delete(User user, @RequestParam(defaultValue = "") String ids) {
for (String idStr : StringUtils.split(ids, ",")) {
perfTestService.delete(user, NumberUtils.toLong(idStr, 0));
}
return successJsonHttpEntity();
}
/**
* Stop the perf tests having given IDs.
*
* @param user user
* @param ids comma separated perf test IDs
* @return success json if succeeded.
*/
@RestAPI
@RequestMapping(value = "/api/stop", method = RequestMethod.POST)
public HttpEntity<String> stop(User user, @RequestParam(value = "ids", defaultValue = "") String ids) {
for (String idStr : StringUtils.split(ids, ",")) {
perfTestService.stop(user, NumberUtils.toLong(idStr, 0));
}
return successJsonHttpEntity();
}
/**
* Filter out please_modify_this.com from hosts string.
*
* @param originalString original string
* @return filtered string
*/
private String filterHostString(String originalString) {
List<String> hosts = Lists.newArrayList();
for (String each : StringUtils.split(StringUtils.trimToEmpty(originalString), ",")) {
if (!each.contains("please_modify_this.com")) {
hosts.add(each);
}
}
return StringUtils.join(hosts, ",");
}
private Map<String, Object> getPerfGraphData(Long id, String[] dataTypes, int imgWidth) {
final PerfTest test = perfTestService.getOne(id);
int interval = perfTestService.getReportDataInterval(id, dataTypes[0], imgWidth);
Map<String, Object> resultMap = Maps.newHashMap();
for (String each : dataTypes) {
Pair<ArrayList<String>, ArrayList<String>> tpsResult = perfTestService.getReportData(id, each, interval);
Map<String, Object> dataMap = Maps.newHashMap();
dataMap.put("lables", tpsResult.getFirst());
dataMap.put("data", tpsResult.getSecond());
resultMap.put(StringUtils.replaceChars(each, "()", ""), dataMap);
}
resultMap.put(PARAM_TEST_CHART_INTERVAL, interval * test.getSamplingInterval());
return resultMap;
}
/**
* Get the running division in perftest configuration page.
*
* @param user user
* @param model model
* @param id test id
* @param imgWidth image width
* @return perftest/basic_report
*/
@RequestMapping(value = "{id}/running_div")
public String getReportSection(User user, ModelMap model, @PathVariable long id) {
PerfTest test = getOneWithPermissionCheck(user, id, false);
model.addAttribute(PARAM_TEST, test);
return "perftest/running";
}
/**
* Get the basic report content in perftest configuration page.
*
* This method returns the appropriate points based on the given imgWidth.
*
* @param user user
* @param model model
* @param id test id
* @param imgWidth image width
* @return perftest/basic_report
*/
@RequestMapping(value = "{id}/basic_report")
public String getReportSection(User user, ModelMap model, @PathVariable long id, @RequestParam int imgWidth) {
PerfTest test = getOneWithPermissionCheck(user, id, false);
int interval = perfTestService.getReportDataInterval(id, "TPS", imgWidth);
model.addAttribute(PARAM_LOG_LIST, perfTestService.getLogFiles(id));
model.addAttribute(PARAM_TEST_CHART_INTERVAL, interval * test.getSamplingInterval());
model.addAttribute(PARAM_TEST, test);
model.addAttribute(PARAM_TPS, perfTestService.getSingleReportDataAsJson(id, "TPS", interval));
return "perftest/basic_report";
}
/**
* Download the CSV report for the given perf test id.
*
* @param user user
* @param response response
* @param id test id
*/
@RequestMapping(value = "/{id}/download_csv")
public void downloadCSV(User user, @PathVariable("id") long id, HttpServletResponse response) {
PerfTest test = getOneWithPermissionCheck(user, id, false);
File targetFile = perfTestService.getReportFile(test);
checkState(targetFile.exists(), "File %s doesn't exist!", targetFile.getName());
FileDownloadUtils.downloadFile(response, targetFile);
}
/**
* Download logs for the perf test having the given id.
*
* @param user user
* @param path path in the log folder
* @param id test id
* @param response response
*/
@RequestMapping(value = "/{id}/download_log/**")
public void downloadLog(User user, @PathVariable("id") long id, @RemainedPath String path,
HttpServletResponse response) {
getOneWithPermissionCheck(user, id, false);
File targetFile = perfTestService.getLogFile(id, path);
FileDownloadUtils.downloadFile(response, targetFile);
}
/**
* Show the given log for the perf test having the given id.
*
* @param user user
* @param id test id
* @param path path in the log folder
* @param response response
*/
@RequestMapping(value = "/{id}/show_log/**")
public void showLog(User user, @PathVariable("id") long id, @RemainedPath String path, HttpServletResponse response) {
getOneWithPermissionCheck(user, id, false);
File targetFile = perfTestService.getLogFile(id, path);
response.reset();
response.setContentType("text/plain");
FileInputStream fileInputStream = null;
try {
fileInputStream = new FileInputStream(targetFile);
ServletOutputStream outputStream = response.getOutputStream();
if (FilenameUtils.isExtension(targetFile.getName(), "zip")) {
// Limit log view to 1MB
outputStream.println(" Only the last 1MB of a log shows.\n");
outputStream.println("==========================================================================\n\n");
LogCompressUtils.decompress(fileInputStream, outputStream, 1 * 1024 * 1204);
} else {
IOUtils.copy(fileInputStream, outputStream);
}
} catch (Exception e) {
CoreLogger.LOGGER.error("Error while processing log. {}", targetFile, e);
} finally {
IOUtils.closeQuietly(fileInputStream);
}
}
/**
* Get the running perf test info having the given id.
*
* @param user user
* @param id test id
* @return "perftest/sample"
*/
@RequestMapping(value = "/{id}/api/sample")
@RestAPI
public HttpEntity<String> refreshTestRunning(User user, @PathVariable("id") long id) {
PerfTest test = checkNotNull(getOneWithPermissionCheck(user, id, false), "given test should be exist : " + id);
Map<String, Object> map = newHashMap();
map.put("status", test.getStatus());
map.put("perf", perfTestService.getStatistics(test));
map.put("agent", perfTestService.getAgentStat(test));
map.put("monitor", perfTestService.getMonitorStat(test));
return toJsonHttpEntity(map);
}
/**
* Get the detailed perf test report.
*
* @param model model
* @param id test id
* @return perftest/detail_report
*/
@RequestMapping(value = {"/{id}/detail_report", /** for backward compatibility */"/{id}/report"})
public String getReport(ModelMap model, @PathVariable("id") long id) {
model.addAttribute("test", perfTestService.getOne(id));
model.addAttribute("plugins", perfTestService.getAvailableReportPlugins(id));
return "perftest/detail_report";
}
/**
* Get the detailed perf test report.
*
* @param id test id
* @return perftest/detail_report
*/
@RequestMapping("/{id}/detail_report/perf")
public String getDetailPerfReport(@PathVariable("id") long id) {
return "perftest/detail_report/perf";
}
/**
* Get the detailed perf test monitor report.
*
* @param id test id
* @return perftest/detail_report/monitor
*/
@RequestMapping("/{id}/detail_report/monitor")
public String getDetailMonitorReport(@PathVariable("id") long id, @RequestParam("targetIP") String targetIP,
ModelMap modelMap) {
modelMap.addAttribute("targetIP", targetIP);
return "perftest/detail_report/monitor";
}
/**
* Get the detailed perf test report.
*
* @param model model
* @param id test id
* @param reportCategory test report plugin category
* @return perftest/detail_report/target
*/
@RequestMapping("/{id}/detail_report/plugin/{plugin}")
public String getDetailPluginReport(ModelMap model, @PathVariable("id") long id,
@PathVariable("plugin") String plugin, @RequestParam("kind") String kind, ModelMap modelMap) {
modelMap.addAttribute("plugin", plugin);
modelMap.addAttribute("kind", kind);
return "perftest/detail_report/plugin";
}
private PerfTest getOneWithPermissionCheck(User user, Long id, boolean withTag) {
PerfTest perfTest = withTag ? perfTestService.getOneWithTag(id) : perfTestService.getOne(id);
if (user.getRole().equals(Role.ADMIN) || user.getRole().equals(Role.SUPER_USER)) {
return perfTest;
}
if (perfTest != null && !user.equals(perfTest.getCreatedUser())) {
throw processException("User " + user.getUserId() + " has no right on PerfTest ");
}
return perfTest;
}
private Map<String, String> getMonitorGraphData(long id, String targetIP, int imgWidth) {
int interval = perfTestService.getMonitorGraphInterval(id, targetIP, imgWidth);
Map<String, String> sysMonitorMap = perfTestService.getMonitorGraph(id, targetIP, interval);
PerfTest perfTest = perfTestService.getOne(id);
sysMonitorMap.put("interval", String.valueOf(interval * (perfTest != null ? perfTest
.getSamplingInterval() : SAMPLING_INTERVAL_DEFAULT_VALUE)));
return sysMonitorMap;
}
/**
* Get the count of currently running perf test and the detailed progress info for the given perf test IDs.
*
* @param user user
* @param ids comma separated perf test list
* @return JSON message containing perf test status
*/
@RestAPI
@RequestMapping("/api/status")
public HttpEntity<String> getStatuses(User user, @RequestParam(value = "ids", defaultValue = "") String ids) {
List<PerfTest> perfTests = perfTestService.getAll(user, convertString2Long(ids));
return toJsonHttpEntity(buildMap("perfTestInfo", perfTestService.getCurrentPerfTestStatistics(), "status",
getStatus(perfTests)));
}
/**
* Get all available scripts in JSON format for the current factual user.
*
* @param user user
* @param ownerId owner id
* @return JSON containing script's list.
*/
@RestAPI
@RequestMapping("/api/script")
public HttpEntity<String> getScripts(User user, @RequestParam(value = "ownerId", required = false) String ownerId) {
if (StringUtils.isNotEmpty(ownerId)) {
user = userService.getOne(ownerId);
}
List<FileEntry> allFileEntries = fileEntryService.getAll(user);
CollectionUtils.filter(allFileEntries, new Predicate() {
@Override
public boolean evaluate(Object object) {
return ((FileEntry) object).getFileType().getFileCategory() == FileCategory.SCRIPT;
}
});
return toJsonHttpEntity(allFileEntries, fileEntryGson);
}
/**
* Get resources and lib file list from the same folder with the given script path.
*
* @param user user
* @param scriptPath script path
* @param ownerId ownerId
* @return json string representing resources and libs.
*/
@RequestMapping("/api/resource")
public HttpEntity<String> getResources(User user, @RequestParam String scriptPath,
@RequestParam(required = false) String ownerId) {
if (user.getRole() == Role.ADMIN && StringUtils.isNotBlank(ownerId)) {
user = userService.getOne(ownerId);
}
FileEntry fileEntry = fileEntryService.getOne(user, scriptPath);
String targetHosts = "";
List<String> fileStringList = newArrayList();
if (fileEntry != null) {
List<FileEntry> fileList = fileEntryService.getScriptHandler(fileEntry).getLibAndResourceEntries(user, fileEntry, -1L);
for (FileEntry each : fileList) {
fileStringList.add(each.getPath());
}
targetHosts = filterHostString(fileEntry.getProperties().get("targetHosts"));
}
return toJsonHttpEntity(buildMap("targetHosts", trimToEmpty(targetHosts), "resources", fileStringList));
}
/**
* Get the status of the given perf test.
*
* @param user user
* @param id perftest id
* @return JSON message containing perf test status
*/
@RestAPI
@RequestMapping("/api/{id}/status")
public HttpEntity<String> getStatus(User user, @PathVariable("id") Long id) {
List<PerfTest> perfTests = perfTestService.getAll(user, new Long[]{id});
return toJsonHttpEntity(buildMap("status", getStatus(perfTests)));
}
/**
* Get the detailed report graph data for the given perf test id.
*
* This method returns the appropriate points based on the given imgWidth.
*
* @param id test id
* @param dataType which data
* @param imgWidth imageWidth
* @return json string.
*/
@RestAPI
@RequestMapping({"/api/{id}/perf", "/api/{id}/graph"})
public HttpEntity<String> getPerfGraph(@PathVariable("id") long id,
@RequestParam(required = true, defaultValue = "") String dataType, @RequestParam int imgWidth) {
String[] dataTypes = checkNotEmpty(StringUtils.split(dataType, ","), "dataType argument should be provided");
return toJsonHttpEntity(getPerfGraphData(id, dataTypes, imgWidth));
}
/**
* Get the monitor data of the target having the given IP.
*
* @param id test Id
* @param targetIP targetIP
* @param imgWidth image width
* @return json message
*/
@RestAPI
@RequestMapping("/api/{id}/monitor")
public HttpEntity<String> getMonitorGraph(@PathVariable("id") long id,
@RequestParam("targetIP") String targetIP, @RequestParam int imgWidth) {
return toJsonHttpEntity(getMonitorGraphData(id, targetIP, imgWidth));
}
/**
* Get the plugin monitor data of the target.
*
* @param id test Id
* @param reportCategory monitor plugin category
* @param targetIP monitor target IP
* @param imgWidth image width
* @return json message
*/
@RestAPI
@RequestMapping("/api/{id}/plugin/{plugin}")
public HttpEntity<String> getPluginGraph(@PathVariable("id") long id,
@PathVariable("plugin") String plugin,
@RequestParam("kind") String kind, @RequestParam int imgWidth) {
return toJsonHttpEntity(getReportPluginGraphData(id, plugin, kind, imgWidth));
}
private Map<String, String> getReportPluginGraphData(long id, String plugin, String kind, int imgWidth) {
int interval = perfTestService.getReportPluginGraphInterval(id, plugin, kind, imgWidth);
Map<String, String> pluginMonitorData = perfTestService.getReportPluginGraph(id, plugin, kind, interval);
pluginMonitorData.put("interval",
String.valueOf(interval * perfTestService.getReportPluginGraphSamplingInterval(id, plugin)));
return pluginMonitorData;
}
/**
* Get the last perf test details in the form of json.
*
* @param user user
* @param size size of retrieved perf test
* @return json string
*/
@RestAPI
@RequestMapping(value = {"/api/last", "/api", "/api/"}, method = RequestMethod.GET)
public HttpEntity<String> getAll(User user, @RequestParam(value = "page", defaultValue = "0") int page,
@RequestParam(value = "size", defaultValue = "1") int size) {
PageRequest pageRequest = new PageRequest(page, size, new Sort(Direction.DESC, "id"));
Page<PerfTest> testList = perfTestService.getPagedAll(user, null, null, null, pageRequest);
return toJsonHttpEntity(testList.getContent());
}
/**
* Get the perf test detail in the form of json.
*
* @param user user
* @param id perftest id
* @return json success message if succeeded
*/
@RestAPI
@RequestMapping(value = "/api/{id}", method = RequestMethod.GET)
public HttpEntity<String> getOne(User user, @PathVariable("id") Long id) {
PerfTest test = checkNotNull(getOneWithPermissionCheck(user, id, false), "PerfTest %s does not exists", id);
return toJsonHttpEntity(test);
}
/**
* Create the given perf test.
*
* @param user user
* @param perftest perf test
* @return json success message if succeeded
*/
@RestAPI
@RequestMapping(value = {"/api/", "/api"}, method = RequestMethod.POST)
public HttpEntity<String> create(User user, PerfTest perftest) {
checkNull(perftest.getId(), "id should be null");
PerfTest savePerfTest = perfTestService.save(user, perftest);
return toJsonHttpEntity(savePerfTest);
}
/**
* Delete the given perf test.
*
* @param user user
* @param id perf test id
* @return json success message if succeeded
*/
@RestAPI
@RequestMapping(value = "/api/{id}", method = RequestMethod.DELETE)
public HttpEntity<String> delete(User user, @PathVariable("id") Long id) {
PerfTest perfTest = getOneWithPermissionCheck(user, id, false);
checkNotNull(perfTest, "no perftest for %s exits", id);
perfTestService.delete(user, id);
return successJsonHttpEntity();
}
/**
* Update the given perf test.
*
* @param user user
* @param id perf test id
* @param perfTest perf test configuration changes
* @return json success message if succeeded
*/
@RestAPI
@RequestMapping(value = "/api/{id}", method = RequestMethod.PUT)
public HttpEntity<String> update(User user, @PathVariable("id") Long id, PerfTest perfTest) {
perfTest.setId(id);
return toJsonHttpEntity(perfTestService.save(user, perfTest));
}
/**
* Stop the given perf test.
*
* @param user user
* @param id perf test id
* @return json success message if succeeded
*/
@RestAPI
@RequestMapping(value = "/api/{id}", params = "action=stop", method = RequestMethod.PUT)
public HttpEntity<String> stop(User user, @PathVariable("id") Long id) {
perfTestService.stop(user, id);
return successJsonHttpEntity();
}
/**
* Update the given perf test's status.
*
* @param user user
* @param id perf test id
* @param status Status to be moved to
* @return json success message if succeeded
*/
@RestAPI
@RequestMapping(value = "/api/{id}", params = "action=status", method = RequestMethod.PUT)
public HttpEntity<String> updateStatus(User user, @PathVariable("id") Long id, Status status) {
PerfTest perfTest = getOneWithPermissionCheck(user, id, false);
checkNotNull(perfTest, "no perftest for %s exits", id).setStatus(status);
return toJsonHttpEntity(perfTestService.save(user, perfTest));
}
/**
* Clone and start the given perf test.
*
* @param user user
* @param id perf test id to be cloned
* @param perftest option to override while cloning.
* @return json string
*/
@RestAPI
@RequestMapping(value = {"/api/{id}/clone_and_start", /* for backward compatibility */ "/api/{id}/cloneAndStart"})
public HttpEntity<String> cloneAndStart(User user, @PathVariable("id") Long id, PerfTest perftest) {
PerfTest test = getOneWithPermissionCheck(user, id, false);
checkNotNull(test, "no perftest for %s exits", id);
PerfTest newOne = test.cloneTo(new PerfTest());
newOne.setStatus(Status.READY);
if (perftest != null) {
if (perftest.getScheduledTime() != null) {
newOne.setScheduledTime(perftest.getScheduledTime());
}
if (perftest.getScriptRevision() != null) {
newOne.setScriptRevision(perftest.getScriptRevision());
}
if (perftest.getAgentCount() != null) {
newOne.setAgentCount(perftest.getAgentCount());
}
}
if (newOne.getAgentCount() == null) {
newOne.setAgentCount(0);
}
Map<String, MutableInt> agentCountMap = agentManagerService.getUserAvailableAgentCountMap(user);
MutableInt agentCountObj = agentCountMap.get(isClustered() ? test.getRegion() : Config.NONE_REGION);
checkNotNull(agentCountObj, "test region should be within current region list");
int agentMaxCount = agentCountObj.intValue();
checkArgument(newOne.getAgentCount() != 0, "test agent should not be %s", agentMaxCount);
checkArgument(newOne.getAgentCount() <= agentMaxCount, "test agent should be equal to or less than %s",
agentMaxCount);
PerfTest savePerfTest = perfTestService.save(user, newOne);
CoreLogger.LOGGER.info("test {} is created through web api by {}", savePerfTest.getId(), user.getUserId());
return toJsonHttpEntity(savePerfTest);
}
}
| false | true | public String saveOne(User user, ModelMap model, PerfTest test,
@RequestParam(value = "isClone", required = false, defaultValue = "false") boolean isClone) {
test.setTestName(StringUtils.trimToEmpty(test.getTestName()));
checkNotEmpty(test.getTestName(), "test name should be provided");
checkArgument(test.getStatus().equals(Status.READY) || test.getStatus().equals(Status.SAVED),
"save test only support for SAVE or READY status");
checkArgument(test.getRunCount() == null || test.getRunCount() <= agentManager.getMaxRunCount(),
"test run count should be equal to or less than %s", agentManager.getMaxRunCount());
checkArgument(test.getDuration() == null
|| test.getDuration() <= (((long) agentManager.getMaxRunHour()) * 3600000L),
"test run duration should be equal to or less than %s", agentManager.getMaxRunHour());
Map<String, MutableInt> agentCountMap = agentManagerService.getUserAvailableAgentCountMap(user);
MutableInt agentCountObj = agentCountMap.get(isClustered() ? test.getRegion() : Config.NONE_REGION);
checkNotNull(agentCountObj, "test region should be within current region list");
int agentMaxCount = agentCountObj.intValue();
checkArgument(test.getAgentCount() <= agentMaxCount, "test agent should be equal to or less than %s",
agentMaxCount);
checkArgument(test.getVuserPerAgent() == null || test.getVuserPerAgent() <= agentManager.getMaxVuserPerAgent(),
"test vuser should be equal to or less than %s", agentManager.getMaxVuserPerAgent());
if (getConfig().isSecurityEnabled()) {
checkArgument(StringUtils.isNotEmpty(test.getTargetHosts()),
"test target hosts should be provided when security mode is enabled");
}
checkArgument(test.getProcesses() != null && 0 != test.getProcesses(), "test process should not be 0");
checkArgument(test.getThreads() != null && 0 != test.getThreads(), "test thread should not be 0");
// Point to the head revision
test.setScriptRevision(-1L);
test.prepare(isClone);
test = perfTestService.save(user, test);
model.clear();
if (test.getStatus() == Status.SAVED || test.getScheduledTime() != null) {
return "redirect:/perftest/list";
} else {
return "redirect:/perftest/" + test.getId();
}
}
| public String saveOne(User user, ModelMap model, PerfTest test,
@RequestParam(value = "isClone", required = false, defaultValue = "false") boolean isClone) {
test.setTestName(StringUtils.trimToEmpty(test.getTestName()));
checkNotEmpty(test.getTestName(), "test name should be provided");
checkArgument(test.getStatus().equals(Status.READY) || test.getStatus().equals(Status.SAVED),
"save test only support for SAVE or READY status");
checkArgument(test.getRunCount() == null || test.getRunCount() <= agentManager.getMaxRunCount(),
"test run count should be equal to or less than %s", agentManager.getMaxRunCount());
checkArgument(test.getDuration() == null
|| test.getDuration() <= (((long) agentManager.getMaxRunHour()) * 3600000L),
"test run duration should be equal to or less than %s", agentManager.getMaxRunHour());
Map<String, MutableInt> agentCountMap = agentManagerService.getUserAvailableAgentCountMap(user);
MutableInt agentCountObj = agentCountMap.get(isClustered() ? test.getRegion() : Config.NONE_REGION);
checkNotNull(agentCountObj, "test region should be within current region list");
int agentMaxCount = agentCountObj.intValue();
checkArgument(test.getAgentCount() <= agentMaxCount, "test agent should be equal to or less than %s",
agentMaxCount);
checkArgument(test.getVuserPerAgent() == null || test.getVuserPerAgent() <= agentManager.getMaxVuserPerAgent(),
"Test vuser should be equal to or less than %s", agentManager.getMaxVuserPerAgent());
if (getConfig().isSecurityEnabled()) {
checkArgument(StringUtils.isNotEmpty(test.getTargetHosts()),
"Test target hosts should be provided when security mode is enabled");
}
checkArgument(test.getProcesses() != null && 0 != test.getProcesses(), "test process should not be 0");
checkArgument(test.getThreads() != null && 0 != test.getThreads(), "test thread should not be 0");
// Point to the head revision
test.setScriptRevision(-1L);
test.prepare(isClone);
test = perfTestService.save(user, test);
model.clear();
if (test.getStatus() == Status.SAVED || test.getScheduledTime() != null) {
return "redirect:/perftest/list";
} else {
return "redirect:/perftest/" + test.getId();
}
}
|
diff --git a/src/main/java/tconstruct/smeltery/TinkerSmeltery.java b/src/main/java/tconstruct/smeltery/TinkerSmeltery.java
index ae32dd2ef..6c511a827 100644
--- a/src/main/java/tconstruct/smeltery/TinkerSmeltery.java
+++ b/src/main/java/tconstruct/smeltery/TinkerSmeltery.java
@@ -1,1144 +1,1144 @@
package tconstruct.smeltery;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import mantle.blocks.BlockUtils;
import mantle.blocks.abstracts.MultiServantLogic;
import mantle.pulsar.pulse.Handler;
import mantle.pulsar.pulse.Pulse;
import mantle.pulsar.pulse.PulseProxy;
import net.minecraft.block.Block;
import net.minecraft.block.material.MapColor;
import net.minecraft.block.material.Material;
import net.minecraft.block.material.MaterialLiquid;
import net.minecraft.init.Blocks;
import net.minecraft.init.Items;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.item.crafting.FurnaceRecipes;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.fluids.Fluid;
import net.minecraftforge.fluids.FluidContainerRegistry;
import net.minecraftforge.fluids.FluidContainerRegistry.FluidContainerData;
import net.minecraftforge.fluids.FluidRegistry;
import net.minecraftforge.fluids.FluidStack;
import net.minecraftforge.oredict.OreDictionary;
import net.minecraftforge.oredict.ShapedOreRecipe;
import net.minecraftforge.oredict.ShapelessOreRecipe;
import tconstruct.TConstruct;
import tconstruct.library.TConstructRegistry;
import tconstruct.library.crafting.FluidType;
import tconstruct.library.crafting.LiquidCasting;
import tconstruct.library.crafting.Smeltery;
import tconstruct.library.util.IPattern;
import tconstruct.smeltery.blocks.BloodBlock;
import tconstruct.smeltery.blocks.CastingChannelBlock;
import tconstruct.smeltery.blocks.GlassBlockConnected;
import tconstruct.smeltery.blocks.GlassBlockConnectedMeta;
import tconstruct.smeltery.blocks.GlassPaneConnected;
import tconstruct.smeltery.blocks.GlassPaneStained;
import tconstruct.smeltery.blocks.GlueBlock;
import tconstruct.smeltery.blocks.GlueFluid;
import tconstruct.smeltery.blocks.LavaTankBlock;
import tconstruct.smeltery.blocks.SearedBlock;
import tconstruct.smeltery.blocks.SearedSlab;
import tconstruct.smeltery.blocks.SmelteryBlock;
import tconstruct.smeltery.blocks.SpeedBlock;
import tconstruct.smeltery.blocks.SpeedSlab;
import tconstruct.smeltery.blocks.TConstructFluid;
import tconstruct.smeltery.blocks.TankAirBlock;
import tconstruct.smeltery.itemblocks.CastingChannelItem;
import tconstruct.smeltery.itemblocks.GlassBlockItem;
import tconstruct.smeltery.itemblocks.GlassPaneItem;
import tconstruct.smeltery.itemblocks.LavaTankItemBlock;
import tconstruct.smeltery.itemblocks.SearedSlabItem;
import tconstruct.smeltery.itemblocks.SearedTableItemBlock;
import tconstruct.smeltery.itemblocks.SmelteryItemBlock;
import tconstruct.smeltery.itemblocks.SpeedBlockItem;
import tconstruct.smeltery.itemblocks.SpeedSlabItem;
import tconstruct.smeltery.itemblocks.StainedGlassClearItem;
import tconstruct.smeltery.itemblocks.StainedGlassClearPaneItem;
import tconstruct.smeltery.items.FilledBucket;
import tconstruct.smeltery.items.MetalPattern;
import tconstruct.smeltery.logic.AdaptiveDrainLogic;
import tconstruct.smeltery.logic.AdaptiveSmelteryLogic;
import tconstruct.smeltery.logic.CastingBasinLogic;
import tconstruct.smeltery.logic.CastingChannelLogic;
import tconstruct.smeltery.logic.CastingTableLogic;
import tconstruct.smeltery.logic.FaucetLogic;
import tconstruct.smeltery.logic.LavaTankLogic;
import tconstruct.smeltery.logic.SmelteryDrainLogic;
import tconstruct.smeltery.logic.SmelteryLogic;
import tconstruct.smeltery.logic.TankAirLogic;
import tconstruct.tools.TinkerTools;
import tconstruct.util.config.PHConstruct;
import tconstruct.world.TinkerWorld;
import cpw.mods.fml.common.event.FMLInitializationEvent;
import cpw.mods.fml.common.event.FMLPostInitializationEvent;
import cpw.mods.fml.common.event.FMLPreInitializationEvent;
import cpw.mods.fml.common.registry.GameRegistry;
import cpw.mods.fml.common.registry.GameRegistry.ObjectHolder;
@ObjectHolder(TConstruct.modID)
@Pulse(id = "Tinkers' Smeltery", description = "Liquid metals, casting, and the multiblock structure.")
public class TinkerSmeltery
{
@PulseProxy(clientSide = "tconstruct.smeltery.SmelteryProxyClient", serverSide = "tconstruct.smeltery.SmelteryProxyCommon")
public static SmelteryProxyCommon proxy;
public static Item metalPattern;
// public static Item armorPattern;
public static Item buckets;
public static Block smeltery;
public static Block lavaTank;
public static Block searedBlock;
public static Block castingChannel;
public static Block tankAir;
public static Block smelteryNether;
public static Block lavaTankNether;
public static Block searedBlockNether;
public static Block searedSlab;
public static Block glueBlock;
public static Block clearGlass;
// public static Block stainedGlass;
public static Block stainedGlassClear;
public static Block glassPane;
// public static Block stainedGlassPane;
public static Block stainedGlassClearPane;
public static Block glassMagicSlab;
public static Block stainedGlassMagicSlab;
public static Block stainedGlassClearMagicSlab;
// Liquids
public static Material liquidMetal;
public static Fluid moltenIronFluid;
public static Fluid moltenGoldFluid;
public static Fluid moltenCopperFluid;
public static Fluid moltenTinFluid;
public static Fluid moltenAluminumFluid;
public static Fluid moltenCobaltFluid;
public static Fluid moltenArditeFluid;
public static Fluid moltenBronzeFluid;
public static Fluid moltenAlubrassFluid;
public static Fluid moltenManyullynFluid;
public static Fluid moltenAlumiteFluid;
public static Fluid moltenObsidianFluid;
public static Fluid moltenSteelFluid;
public static Fluid moltenGlassFluid;
public static Fluid moltenStoneFluid;
public static Fluid moltenEmeraldFluid;
public static Fluid moltenNickelFluid;
public static Fluid moltenLeadFluid;
public static Fluid moltenSilverFluid;
public static Fluid moltenShinyFluid;
public static Fluid moltenInvarFluid;
public static Fluid moltenElectrumFluid;
public static Fluid moltenEnderFluid;
public static Fluid pigIronFluid;
public static Block moltenIron;
public static Block moltenGold;
public static Block moltenCopper;
public static Block moltenTin;
public static Block moltenAluminum;
public static Block moltenCobalt;
public static Block moltenArdite;
public static Block moltenBronze;
public static Block moltenAlubrass;
public static Block moltenManyullyn;
public static Block moltenAlumite;
public static Block moltenObsidian;
public static Block moltenSteel;
public static Block moltenGlass;
public static Block moltenStone;
public static Block moltenEmerald;
public static Block moltenNickel;
public static Block moltenLead;
public static Block moltenSilver;
public static Block moltenShiny;
public static Block moltenInvar;
public static Block moltenElectrum;
public static Block moltenEnder;
// Glue
public static Fluid glueFluid;
public static Block glueFluidBlock;
public static Fluid[] fluids = new Fluid[26];
public static Block[] fluidBlocks = new Block[25];
public static FluidStack[] liquids;
public static Block speedSlab;
// InfiBlocks
public static Block speedBlock;
public static Fluid bloodFluid;
public static Block blood;
@Handler
public void preInit (FMLPreInitializationEvent event)
{
MinecraftForge.EVENT_BUS.register(new TinkerSmelteryEvents());
TinkerSmeltery.buckets = new FilledBucket(BlockUtils.getBlockFromItem(TinkerSmeltery.buckets));
GameRegistry.registerItem(TinkerSmeltery.buckets, "buckets");
TinkerSmeltery.searedSlab = new SearedSlab().setBlockName("SearedSlab");
TinkerSmeltery.searedSlab.stepSound = Block.soundTypeStone;
TinkerSmeltery.speedSlab = new SpeedSlab().setBlockName("SpeedSlab");
TinkerSmeltery.speedSlab.stepSound = Block.soundTypeStone;
TinkerSmeltery.glueBlock = new GlueBlock().setBlockName("GlueBlock").setCreativeTab(TConstructRegistry.blockTab);
// Smeltery
TinkerSmeltery.smeltery = new SmelteryBlock().setBlockName("Smeltery");
TinkerSmeltery.smelteryNether = new SmelteryBlock("nether").setBlockName("Smeltery");
TinkerSmeltery.lavaTank = new LavaTankBlock().setBlockName("LavaTank");
TinkerSmeltery.lavaTank.setStepSound(Block.soundTypeGlass);
TinkerSmeltery.lavaTankNether = new LavaTankBlock("nether").setStepSound(Block.soundTypeGlass).setBlockName("LavaTank");
TinkerSmeltery.searedBlock = new SearedBlock().setBlockName("SearedBlock");
TinkerSmeltery.searedBlockNether = new SearedBlock("nether").setBlockName("SearedBlock");
TinkerSmeltery.castingChannel = (new CastingChannelBlock()).setBlockName("CastingChannel");
TinkerSmeltery.tankAir = new TankAirBlock(Material.leaves).setBlockUnbreakable().setBlockName("tconstruct.tank.air");
// Liquids
TinkerSmeltery.liquidMetal = new MaterialLiquid(MapColor.tntColor);
TinkerSmeltery.moltenIronFluid = new Fluid("iron.molten");
if (!FluidRegistry.registerFluid(TinkerSmeltery.moltenIronFluid))
TinkerSmeltery.moltenIronFluid = FluidRegistry.getFluid("iron.molten");
TinkerSmeltery.moltenIron = new TConstructFluid(TinkerSmeltery.moltenIronFluid, Material.lava, "liquid_iron").setBlockName("fluid.molten.iron");
GameRegistry.registerBlock(TinkerSmeltery.moltenIron, "fluid.molten.iron");
TinkerSmeltery.moltenIronFluid.setBlock(TinkerSmeltery.moltenIron).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(TinkerSmeltery.moltenIronFluid, 1000), new ItemStack(TinkerSmeltery.buckets, 1, 0), new ItemStack(
Items.bucket)));
TinkerSmeltery.moltenGoldFluid = new Fluid("gold.molten");
if (!FluidRegistry.registerFluid(TinkerSmeltery.moltenGoldFluid))
TinkerSmeltery.moltenGoldFluid = FluidRegistry.getFluid("gold.molten");
TinkerSmeltery.moltenGold = new TConstructFluid(TinkerSmeltery.moltenGoldFluid, Material.lava, "liquid_gold").setBlockName("fluid.molten.gold");
GameRegistry.registerBlock(TinkerSmeltery.moltenGold, "fluid.molten.gold");
TinkerSmeltery.moltenGoldFluid.setBlock(TinkerSmeltery.moltenGold).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(TinkerSmeltery.moltenGoldFluid, 1000), new ItemStack(TinkerSmeltery.buckets, 1, 1), new ItemStack(
Items.bucket)));
TinkerSmeltery.moltenCopperFluid = new Fluid("copper.molten");
if (!FluidRegistry.registerFluid(TinkerSmeltery.moltenCopperFluid))
TinkerSmeltery.moltenCopperFluid = FluidRegistry.getFluid("copper.molten");
TinkerSmeltery.moltenCopper = new TConstructFluid(TinkerSmeltery.moltenCopperFluid, Material.lava, "liquid_copper").setBlockName("fluid.molten.copper");
GameRegistry.registerBlock(TinkerSmeltery.moltenCopper, "fluid.molten.copper");
TinkerSmeltery.moltenCopperFluid.setBlock(TinkerSmeltery.moltenCopper).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(TinkerSmeltery.moltenCopperFluid, 1000), new ItemStack(TinkerSmeltery.buckets, 1, 2), new ItemStack(
Items.bucket)));
TinkerSmeltery.moltenTinFluid = new Fluid("tin.molten");
if (!FluidRegistry.registerFluid(TinkerSmeltery.moltenTinFluid))
TinkerSmeltery.moltenTinFluid = FluidRegistry.getFluid("tin.molten");
TinkerSmeltery.moltenTin = new TConstructFluid(TinkerSmeltery.moltenTinFluid, Material.lava, "liquid_tin").setBlockName("fluid.molten.tin");
GameRegistry.registerBlock(TinkerSmeltery.moltenTin, "fluid.molten.tin");
TinkerSmeltery.moltenTinFluid.setBlock(TinkerSmeltery.moltenTin).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(TinkerSmeltery.moltenTinFluid, 1000), new ItemStack(TinkerSmeltery.buckets, 1, 3), new ItemStack(
Items.bucket)));
TinkerSmeltery.moltenAluminumFluid = new Fluid("aluminum.molten");
if (!FluidRegistry.registerFluid(TinkerSmeltery.moltenAluminumFluid))
TinkerSmeltery.moltenAluminumFluid = FluidRegistry.getFluid("aluminum.molten");
TinkerSmeltery.moltenAluminum = new TConstructFluid(TinkerSmeltery.moltenAluminumFluid, Material.lava, "liquid_aluminum").setBlockName("fluid.molten.aluminum");
GameRegistry.registerBlock(TinkerSmeltery.moltenAluminum, "fluid.molten.aluminum");
TinkerSmeltery.moltenAluminumFluid.setBlock(TinkerSmeltery.moltenAluminum).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(TinkerSmeltery.moltenAluminumFluid, 1000), new ItemStack(TinkerSmeltery.buckets, 1, 4), new ItemStack(
Items.bucket)));
TinkerSmeltery.moltenCobaltFluid = new Fluid("cobalt.molten");
if (!FluidRegistry.registerFluid(TinkerSmeltery.moltenCobaltFluid))
TinkerSmeltery.moltenCobaltFluid = FluidRegistry.getFluid("cobalt.molten");
TinkerSmeltery.moltenCobalt = new TConstructFluid(TinkerSmeltery.moltenCobaltFluid, Material.lava, "liquid_cobalt").setBlockName("fluid.molten.cobalt");
GameRegistry.registerBlock(TinkerSmeltery.moltenCobalt, "fluid.molten.cobalt");
TinkerSmeltery.moltenCobaltFluid.setBlock(TinkerSmeltery.moltenCobalt).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(TinkerSmeltery.moltenCobaltFluid, 1000), new ItemStack(TinkerSmeltery.buckets, 1, 5), new ItemStack(
Items.bucket)));
TinkerSmeltery.moltenArditeFluid = new Fluid("ardite.molten");
if (!FluidRegistry.registerFluid(TinkerSmeltery.moltenArditeFluid))
TinkerSmeltery.moltenArditeFluid = FluidRegistry.getFluid("ardite.molten");
TinkerSmeltery.moltenArdite = new TConstructFluid(TinkerSmeltery.moltenArditeFluid, Material.lava, "liquid_ardite").setBlockName("fluid.molten.ardite");
GameRegistry.registerBlock(TinkerSmeltery.moltenArdite, "fluid.molten.ardite");
TinkerSmeltery.moltenArditeFluid.setBlock(TinkerSmeltery.moltenArdite).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(TinkerSmeltery.moltenArditeFluid, 1000), new ItemStack(TinkerSmeltery.buckets, 1, 6), new ItemStack(
Items.bucket)));
TinkerSmeltery.moltenBronzeFluid = new Fluid("bronze.molten");
if (!FluidRegistry.registerFluid(TinkerSmeltery.moltenBronzeFluid))
TinkerSmeltery.moltenBronzeFluid = FluidRegistry.getFluid("bronze.molten");
TinkerSmeltery.moltenBronze = new TConstructFluid(TinkerSmeltery.moltenBronzeFluid, Material.lava, "liquid_bronze").setBlockName("fluid.molten.bronze");
GameRegistry.registerBlock(TinkerSmeltery.moltenBronze, "fluid.molten.bronze");
TinkerSmeltery.moltenBronzeFluid.setBlock(TinkerSmeltery.moltenBronze).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(TinkerSmeltery.moltenBronzeFluid, 1000), new ItemStack(TinkerSmeltery.buckets, 1, 7), new ItemStack(
Items.bucket)));
TinkerSmeltery.moltenAlubrassFluid = new Fluid("aluminumbrass.molten");
if (!FluidRegistry.registerFluid(TinkerSmeltery.moltenAlubrassFluid))
TinkerSmeltery.moltenAlubrassFluid = FluidRegistry.getFluid("aluminumbrass.molten");
TinkerSmeltery.moltenAlubrass = new TConstructFluid(TinkerSmeltery.moltenAlubrassFluid, Material.lava, "liquid_alubrass").setBlockName("fluid.molten.alubrass");
GameRegistry.registerBlock(TinkerSmeltery.moltenAlubrass, "fluid.molten.alubrass");
TinkerSmeltery.moltenAlubrassFluid.setBlock(TinkerSmeltery.moltenAlubrass).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(TinkerSmeltery.moltenAlubrassFluid, 1000), new ItemStack(TinkerSmeltery.buckets, 1, 8), new ItemStack(
Items.bucket)));
TinkerSmeltery.moltenManyullynFluid = new Fluid("manyullyn.molten");
if (!FluidRegistry.registerFluid(TinkerSmeltery.moltenManyullynFluid))
TinkerSmeltery.moltenManyullynFluid = FluidRegistry.getFluid("manyullyn.molten");
TinkerSmeltery.moltenManyullyn = new TConstructFluid(TinkerSmeltery.moltenManyullynFluid, Material.lava, "liquid_manyullyn").setBlockName("fluid.molten.manyullyn");
GameRegistry.registerBlock(TinkerSmeltery.moltenManyullyn, "fluid.molten.manyullyn");
TinkerSmeltery.moltenManyullynFluid.setBlock(TinkerSmeltery.moltenManyullyn).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(TinkerSmeltery.moltenManyullynFluid, 1000), new ItemStack(TinkerSmeltery.buckets, 1, 9), new ItemStack(
Items.bucket)));
TinkerSmeltery.moltenAlumiteFluid = new Fluid("alumite.molten");
if (!FluidRegistry.registerFluid(TinkerSmeltery.moltenAlumiteFluid))
TinkerSmeltery.moltenAlumiteFluid = FluidRegistry.getFluid("alumite.molten");
TinkerSmeltery.moltenAlumite = new TConstructFluid(TinkerSmeltery.moltenAlumiteFluid, Material.lava, "liquid_alumite").setBlockName("fluid.molten.alumite");
GameRegistry.registerBlock(TinkerSmeltery.moltenAlumite, "fluid.molten.alumite");
TinkerSmeltery.moltenAlumiteFluid.setBlock(TinkerSmeltery.moltenAlumite).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(TinkerSmeltery.moltenAlumiteFluid, 1000), new ItemStack(TinkerSmeltery.buckets, 1, 10), new ItemStack(
Items.bucket)));
TinkerSmeltery.moltenObsidianFluid = new Fluid("obsidian.molten");
if (!FluidRegistry.registerFluid(TinkerSmeltery.moltenObsidianFluid))
TinkerSmeltery.moltenObsidianFluid = FluidRegistry.getFluid("obsidian.molten");
TinkerSmeltery.moltenObsidian = new TConstructFluid(TinkerSmeltery.moltenObsidianFluid, Material.lava, "liquid_obsidian").setBlockName("fluid.molten.obsidian");
GameRegistry.registerBlock(TinkerSmeltery.moltenObsidian, "fluid.molten.obsidian");
TinkerSmeltery.moltenObsidianFluid.setBlock(TinkerSmeltery.moltenObsidian).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(TinkerSmeltery.moltenObsidianFluid, 1000), new ItemStack(TinkerSmeltery.buckets, 1, 11), new ItemStack(
Items.bucket)));
TinkerSmeltery.moltenSteelFluid = new Fluid("steel.molten");
if (!FluidRegistry.registerFluid(TinkerSmeltery.moltenSteelFluid))
TinkerSmeltery.moltenSteelFluid = FluidRegistry.getFluid("steel.molten");
TinkerSmeltery.moltenSteel = new TConstructFluid(TinkerSmeltery.moltenSteelFluid, Material.lava, "liquid_steel").setBlockName("fluid.molten.steel");
GameRegistry.registerBlock(TinkerSmeltery.moltenSteel, "fluid.molten.steel");
TinkerSmeltery.moltenSteelFluid.setBlock(TinkerSmeltery.moltenSteel).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(TinkerSmeltery.moltenSteelFluid, 1000), new ItemStack(TinkerSmeltery.buckets, 1, 12), new ItemStack(
Items.bucket)));
TinkerSmeltery.moltenGlassFluid = new Fluid("glass.molten");
if (!FluidRegistry.registerFluid(TinkerSmeltery.moltenGlassFluid))
TinkerSmeltery.moltenGlassFluid = FluidRegistry.getFluid("glass.molten");
TinkerSmeltery.moltenGlass = new TConstructFluid(TinkerSmeltery.moltenGlassFluid, Material.lava, "liquid_glass", true).setBlockName("fluid.molten.glass");
GameRegistry.registerBlock(TinkerSmeltery.moltenGlass, "fluid.molten.glass");
TinkerSmeltery.moltenGlassFluid.setBlock(TinkerSmeltery.moltenGlass).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(TinkerSmeltery.moltenGlassFluid, 1000), new ItemStack(TinkerSmeltery.buckets, 1, 13), new ItemStack(
Items.bucket)));
TinkerSmeltery.moltenStoneFluid = new Fluid("stone.seared");
if (!FluidRegistry.registerFluid(TinkerSmeltery.moltenStoneFluid))
TinkerSmeltery.moltenStoneFluid = FluidRegistry.getFluid("stone.seared");
TinkerSmeltery.moltenStone = new TConstructFluid(TinkerSmeltery.moltenStoneFluid, Material.lava, "liquid_stone").setBlockName("molten.stone");
GameRegistry.registerBlock(TinkerSmeltery.moltenStone, "molten.stone");
TinkerSmeltery.moltenStoneFluid.setBlock(TinkerSmeltery.moltenStone).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(TinkerSmeltery.moltenStoneFluid, 1000), new ItemStack(TinkerSmeltery.buckets, 1, 14), new ItemStack(
Items.bucket)));
TinkerSmeltery.moltenEmeraldFluid = new Fluid("emerald.liquid");
if (!FluidRegistry.registerFluid(TinkerSmeltery.moltenEmeraldFluid))
TinkerSmeltery.moltenEmeraldFluid = FluidRegistry.getFluid("emerald.liquid");
- TinkerSmeltery.moltenEmerald = new TConstructFluid(TinkerSmeltery.moltenEmeraldFluid, Material.water, "liquid_villager").setBlockName("molten.emerald");
+ TinkerSmeltery.moltenEmerald = new TConstructFluid(TinkerSmeltery.moltenEmeraldFluid, Material.lava, "liquid_villager").setBlockName("molten.emerald");
GameRegistry.registerBlock(TinkerSmeltery.moltenEmerald, "molten.emerald");
- TinkerSmeltery.moltenEmeraldFluid.setBlock(TinkerSmeltery.moltenEmerald).setDensity(3000).setViscosity(6000).setTemperature(1300);
+ TinkerSmeltery.moltenEmeraldFluid.setBlock(TinkerSmeltery.moltenEmerald).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(TinkerSmeltery.moltenEmeraldFluid, 1000), new ItemStack(TinkerSmeltery.buckets, 1, 15), new ItemStack(
Items.bucket)));
TinkerSmeltery.bloodFluid = new Fluid("blood");
if (!FluidRegistry.registerFluid(TinkerSmeltery.bloodFluid))
TinkerSmeltery.bloodFluid = FluidRegistry.getFluid("blood");
TinkerSmeltery.blood = new BloodBlock(TinkerSmeltery.bloodFluid, Material.water, "liquid_cow").setBlockName("liquid.blood");
GameRegistry.registerBlock(TinkerSmeltery.blood, "liquid.blood");
TinkerSmeltery.bloodFluid.setBlock(TinkerSmeltery.blood).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry
.registerFluidContainer(new FluidContainerData(new FluidStack(TinkerSmeltery.bloodFluid, 1000), new ItemStack(TinkerSmeltery.buckets, 1, 16), new ItemStack(Items.bucket)));
TinkerSmeltery.moltenNickelFluid = new Fluid("nickel.molten");
if (!FluidRegistry.registerFluid(TinkerSmeltery.moltenNickelFluid))
TinkerSmeltery.moltenNickelFluid = FluidRegistry.getFluid("nickel.molten");
TinkerSmeltery.moltenNickel = new TConstructFluid(TinkerSmeltery.moltenNickelFluid, Material.lava, "liquid_ferrous").setBlockName("fluid.molten.nickel");
GameRegistry.registerBlock(TinkerSmeltery.moltenNickel, "fluid.molten.nickel");
TinkerSmeltery.moltenNickelFluid.setBlock(TinkerSmeltery.moltenNickel).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(TinkerSmeltery.moltenNickelFluid, 1000), new ItemStack(TinkerSmeltery.buckets, 1, 17), new ItemStack(
Items.bucket)));
TinkerSmeltery.moltenLeadFluid = new Fluid("lead.molten");
if (!FluidRegistry.registerFluid(TinkerSmeltery.moltenLeadFluid))
TinkerSmeltery.moltenLeadFluid = FluidRegistry.getFluid("lead.molten");
TinkerSmeltery.moltenLead = new TConstructFluid(TinkerSmeltery.moltenLeadFluid, Material.lava, "liquid_lead").setBlockName("fluid.molten.lead");
GameRegistry.registerBlock(TinkerSmeltery.moltenLead, "fluid.molten.lead");
TinkerSmeltery.moltenLeadFluid.setBlock(TinkerSmeltery.moltenLead).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(TinkerSmeltery.moltenLeadFluid, 1000), new ItemStack(TinkerSmeltery.buckets, 1, 18), new ItemStack(
Items.bucket)));
TinkerSmeltery.moltenSilverFluid = new Fluid("silver.molten");
if (!FluidRegistry.registerFluid(TinkerSmeltery.moltenSilverFluid))
TinkerSmeltery.moltenSilverFluid = FluidRegistry.getFluid("silver.molten");
TinkerSmeltery.moltenSilver = new TConstructFluid(TinkerSmeltery.moltenSilverFluid, Material.lava, "liquid_silver").setBlockName("fluid.molten.silver");
GameRegistry.registerBlock(TinkerSmeltery.moltenSilver, "fluid.molten.silver");
TinkerSmeltery.moltenSilverFluid.setBlock(TinkerSmeltery.moltenSilver).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(TinkerSmeltery.moltenSilverFluid, 1000), new ItemStack(TinkerSmeltery.buckets, 1, 19), new ItemStack(
Items.bucket)));
TinkerSmeltery.moltenShinyFluid = new Fluid("platinum.molten");
if (!FluidRegistry.registerFluid(TinkerSmeltery.moltenShinyFluid))
TinkerSmeltery.moltenShinyFluid = FluidRegistry.getFluid("platinum.molten");
TinkerSmeltery.moltenShiny = new TConstructFluid(TinkerSmeltery.moltenShinyFluid, Material.lava, "liquid_shiny").setBlockName("fluid.molten.shiny");
GameRegistry.registerBlock(TinkerSmeltery.moltenShiny, "fluid.molten.shiny");
TinkerSmeltery.moltenShinyFluid.setBlock(TinkerSmeltery.moltenShiny).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(TinkerSmeltery.moltenShinyFluid, 1000), new ItemStack(TinkerSmeltery.buckets, 1, 20), new ItemStack(
Items.bucket)));
TinkerSmeltery.moltenInvarFluid = new Fluid("invar.molten");
if (!FluidRegistry.registerFluid(TinkerSmeltery.moltenInvarFluid))
TinkerSmeltery.moltenInvarFluid = FluidRegistry.getFluid("invar.molten");
TinkerSmeltery.moltenInvar = new TConstructFluid(TinkerSmeltery.moltenInvarFluid, Material.lava, "liquid_invar").setBlockName("fluid.molten.invar");
GameRegistry.registerBlock(TinkerSmeltery.moltenInvar, "fluid.molten.invar");
TinkerSmeltery.moltenInvarFluid.setBlock(TinkerSmeltery.moltenInvar).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(TinkerSmeltery.moltenInvarFluid, 1000), new ItemStack(TinkerSmeltery.buckets, 1, 21), new ItemStack(
Items.bucket)));
TinkerSmeltery.moltenElectrumFluid = new Fluid("electrum.molten");
if (!FluidRegistry.registerFluid(TinkerSmeltery.moltenElectrumFluid))
TinkerSmeltery.moltenElectrumFluid = FluidRegistry.getFluid("electrum.molten");
TinkerSmeltery.moltenElectrum = new TConstructFluid(TinkerSmeltery.moltenElectrumFluid, Material.lava, "liquid_electrum").setBlockName("fluid.molten.electrum");
GameRegistry.registerBlock(TinkerSmeltery.moltenElectrum, "fluid.molten.electrum");
TinkerSmeltery.moltenElectrumFluid.setBlock(TinkerSmeltery.moltenElectrum).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(TinkerSmeltery.moltenElectrumFluid, 1000), new ItemStack(TinkerSmeltery.buckets, 1, 22), new ItemStack(
Items.bucket)));
TinkerSmeltery.moltenEnderFluid = new Fluid("ender");
if (!FluidRegistry.registerFluid(TinkerSmeltery.moltenEnderFluid))
{
TinkerSmeltery.moltenEnderFluid = FluidRegistry.getFluid("ender");
TinkerSmeltery.moltenEnder = TinkerSmeltery.moltenEnderFluid.getBlock();
if (TinkerSmeltery.moltenEnder == null)
TConstruct.logger.info("Molten ender block missing!");
}
else
{
TinkerSmeltery.moltenEnder = new TConstructFluid(TinkerSmeltery.moltenEnderFluid, Material.water, "liquid_ender").setBlockName("fluid.ender");
GameRegistry.registerBlock(TinkerSmeltery.moltenEnder, "fluid.ender");
TinkerSmeltery.moltenEnderFluid.setBlock(TinkerSmeltery.moltenEnder).setDensity(3000).setViscosity(6000);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(TinkerSmeltery.moltenEnderFluid, 1000), new ItemStack(TinkerSmeltery.buckets, 1, 23), new ItemStack(
Items.bucket)));
}
// Glue
TinkerSmeltery.glueFluid = new Fluid("glue").setDensity(6000).setViscosity(6000).setTemperature(200);
if (!FluidRegistry.registerFluid(TinkerSmeltery.glueFluid))
TinkerSmeltery.glueFluid = FluidRegistry.getFluid("glue");
TinkerSmeltery.glueFluidBlock = new GlueFluid(TinkerSmeltery.glueFluid, Material.water).setCreativeTab(TConstructRegistry.blockTab).setStepSound(TinkerWorld.slimeStep)
.setBlockName("liquid.glue");
GameRegistry.registerBlock(TinkerSmeltery.glueFluidBlock, "liquid.glue");
TinkerSmeltery.glueFluid.setBlock(TinkerSmeltery.glueFluidBlock);
FluidContainerRegistry
.registerFluidContainer(new FluidContainerData(new FluidStack(TinkerSmeltery.glueFluid, 1000), new ItemStack(TinkerSmeltery.buckets, 1, 25), new ItemStack(Items.bucket)));
TinkerSmeltery.pigIronFluid = new Fluid("pigiron.molten");
if (!FluidRegistry.registerFluid(TinkerSmeltery.pigIronFluid))
TinkerSmeltery.pigIronFluid = FluidRegistry.getFluid("pigiron.molten");
else
TinkerSmeltery.pigIronFluid.setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(TinkerSmeltery.pigIronFluid, 1000), new ItemStack(TinkerSmeltery.buckets, 1, 26), new ItemStack(
Items.bucket)));
TinkerSmeltery.fluids = new Fluid[] { TinkerSmeltery.moltenIronFluid, TinkerSmeltery.moltenGoldFluid, TinkerSmeltery.moltenCopperFluid, TinkerSmeltery.moltenTinFluid,
TinkerSmeltery.moltenAluminumFluid, TinkerSmeltery.moltenCobaltFluid, TinkerSmeltery.moltenArditeFluid, TinkerSmeltery.moltenBronzeFluid, TinkerSmeltery.moltenAlubrassFluid,
TinkerSmeltery.moltenManyullynFluid, TinkerSmeltery.moltenAlumiteFluid, TinkerSmeltery.moltenObsidianFluid, TinkerSmeltery.moltenSteelFluid, TinkerSmeltery.moltenGlassFluid,
TinkerSmeltery.moltenStoneFluid, TinkerSmeltery.moltenEmeraldFluid, TinkerSmeltery.bloodFluid, TinkerSmeltery.moltenNickelFluid, TinkerSmeltery.moltenLeadFluid,
TinkerSmeltery.moltenSilverFluid, TinkerSmeltery.moltenShinyFluid, TinkerSmeltery.moltenInvarFluid, TinkerSmeltery.moltenElectrumFluid, TinkerSmeltery.moltenEnderFluid,
TinkerSmeltery.glueFluid, TinkerSmeltery.pigIronFluid };
TinkerSmeltery.fluidBlocks = new Block[] { TinkerSmeltery.moltenIron, TinkerSmeltery.moltenGold, TinkerSmeltery.moltenCopper, TinkerSmeltery.moltenTin, TinkerSmeltery.moltenAluminum,
TinkerSmeltery.moltenCobalt, TinkerSmeltery.moltenArdite, TinkerSmeltery.moltenBronze, TinkerSmeltery.moltenAlubrass, TinkerSmeltery.moltenManyullyn, TinkerSmeltery.moltenAlumite,
TinkerSmeltery.moltenObsidian, TinkerSmeltery.moltenSteel, TinkerSmeltery.moltenGlass, TinkerSmeltery.moltenStone, TinkerSmeltery.moltenEmerald, TinkerSmeltery.blood,
TinkerSmeltery.moltenNickel, TinkerSmeltery.moltenLead, TinkerSmeltery.moltenSilver, TinkerSmeltery.moltenShiny, TinkerSmeltery.moltenInvar, TinkerSmeltery.moltenElectrum,
TinkerSmeltery.moltenEnder, TinkerSmeltery.glueFluidBlock };
FluidType.registerFluidType("Water", Blocks.snow, 0, 20, FluidRegistry.getFluid("water"), false);
FluidType.registerFluidType("Iron", Blocks.iron_block, 0, 600, TinkerSmeltery.moltenIronFluid, true);
FluidType.registerFluidType("Gold", Blocks.gold_block, 0, 400, TinkerSmeltery.moltenGoldFluid, false);
FluidType.registerFluidType("Tin", TinkerWorld.metalBlock, 5, 400, TinkerSmeltery.moltenTinFluid, false);
FluidType.registerFluidType("Copper", TinkerWorld.metalBlock, 3, 550, TinkerSmeltery.moltenCopperFluid, true);
FluidType.registerFluidType("Aluminum", TinkerWorld.metalBlock, 6, 350, TinkerSmeltery.moltenAluminumFluid, false);
FluidType.registerFluidType("NaturalAluminum", TinkerWorld.oreSlag, 6, 350, TinkerSmeltery.moltenAluminumFluid, false);
FluidType.registerFluidType("Cobalt", TinkerWorld.metalBlock, 0, 650, TinkerSmeltery.moltenCobaltFluid, true);
FluidType.registerFluidType("Ardite", TinkerWorld.metalBlock, 1, 650, TinkerSmeltery.moltenArditeFluid, true);
FluidType.registerFluidType("AluminumBrass", TinkerWorld.metalBlock, 7, 350, TinkerSmeltery.moltenAlubrassFluid, false);
FluidType.registerFluidType("Alumite", TinkerWorld.metalBlock, 8, 800, TinkerSmeltery.moltenAlumiteFluid, true);
FluidType.registerFluidType("Manyullyn", TinkerWorld.metalBlock, 2, 750, TinkerSmeltery.moltenManyullynFluid, true);
FluidType.registerFluidType("Bronze", TinkerWorld.metalBlock, 4, 500, TinkerSmeltery.moltenBronzeFluid, true);
FluidType.registerFluidType("Steel", TinkerWorld.metalBlock, 9, 700, TinkerSmeltery.moltenSteelFluid, true);
FluidType.registerFluidType("Nickel", TinkerWorld.metalBlock, 0, 400, TinkerSmeltery.moltenNickelFluid, false);
FluidType.registerFluidType("Lead", TinkerWorld.metalBlock, 0, 400, TinkerSmeltery.moltenLeadFluid, false);
FluidType.registerFluidType("Silver", TinkerWorld.metalBlock, 0, 400, TinkerSmeltery.moltenSilverFluid, false);
FluidType.registerFluidType("Platinum", TinkerWorld.metalBlock, 0, 400, TinkerSmeltery.moltenShinyFluid, false);
FluidType.registerFluidType("Invar", TinkerWorld.metalBlock, 0, 400, TinkerSmeltery.moltenInvarFluid, false);
FluidType.registerFluidType("Electrum", TinkerWorld.metalBlock, 0, 400, TinkerSmeltery.moltenElectrumFluid, false);
FluidType.registerFluidType("Obsidian", Blocks.obsidian, 0, 750, TinkerSmeltery.moltenObsidianFluid, true);
FluidType.registerFluidType("Ender", TinkerWorld.metalBlock, 10, 500, TinkerSmeltery.moltenEnderFluid, false);
FluidType.registerFluidType("Glass", Blocks.sand, 0, 625, TinkerSmeltery.moltenGlassFluid, false);
FluidType.registerFluidType("Stone", Blocks.stone, 0, 800, TinkerSmeltery.moltenStoneFluid, true);
FluidType.registerFluidType("Emerald", Blocks.emerald_block, 0, 575, TinkerSmeltery.moltenEmeraldFluid, false);
FluidType.registerFluidType("PigIron", TinkerWorld.meatBlock, 0, 610, TinkerSmeltery.pigIronFluid, true);
FluidType.registerFluidType("Glue", TinkerSmeltery.glueBlock, 0, 125, TinkerSmeltery.glueFluid, false);
TinkerSmeltery.speedBlock = new SpeedBlock().setBlockName("SpeedBlock");
// Glass
TinkerSmeltery.clearGlass = new GlassBlockConnected("clear", false).setBlockName("GlassBlock");
TinkerSmeltery.clearGlass.stepSound = Block.soundTypeGlass;
TinkerSmeltery.glassPane = new GlassPaneConnected("clear", false);
TinkerSmeltery.stainedGlassClear = new GlassBlockConnectedMeta("stained", true, "white", "orange", "magenta", "light_blue", "yellow", "lime", "pink", "gray", "light_gray", "cyan", "purple",
"blue", "brown", "green", "red", "black").setBlockName("GlassBlock.StainedClear");
TinkerSmeltery.stainedGlassClear.stepSound = Block.soundTypeGlass;
TinkerSmeltery.stainedGlassClearPane = new GlassPaneStained();
GameRegistry.registerBlock(TinkerSmeltery.searedSlab, SearedSlabItem.class, "SearedSlab");
GameRegistry.registerBlock(TinkerSmeltery.speedSlab, SpeedSlabItem.class, "SpeedSlab");
GameRegistry.registerBlock(TinkerSmeltery.glueBlock, "GlueBlock");
OreDictionary.registerOre("blockRubber", new ItemStack(TinkerSmeltery.glueBlock));
// Smeltery stuff
GameRegistry.registerBlock(TinkerSmeltery.smeltery, SmelteryItemBlock.class, "Smeltery");
GameRegistry.registerBlock(TinkerSmeltery.smelteryNether, SmelteryItemBlock.class, "SmelteryNether");
if (PHConstruct.newSmeltery)
{
GameRegistry.registerTileEntity(AdaptiveSmelteryLogic.class, "TConstruct.Smeltery");
GameRegistry.registerTileEntity(AdaptiveDrainLogic.class, "TConstruct.SmelteryDrain");
}
else
{
GameRegistry.registerTileEntity(SmelteryLogic.class, "TConstruct.Smeltery");
GameRegistry.registerTileEntity(SmelteryDrainLogic.class, "TConstruct.SmelteryDrain");
}
GameRegistry.registerTileEntity(MultiServantLogic.class, "TConstruct.Servants");
GameRegistry.registerBlock(TinkerSmeltery.lavaTank, LavaTankItemBlock.class, "LavaTank");
GameRegistry.registerBlock(TinkerSmeltery.lavaTankNether, LavaTankItemBlock.class, "LavaTankNether");
GameRegistry.registerTileEntity(LavaTankLogic.class, "TConstruct.LavaTank");
GameRegistry.registerBlock(TinkerSmeltery.searedBlock, SearedTableItemBlock.class, "SearedBlock");
GameRegistry.registerBlock(TinkerSmeltery.searedBlockNether, SearedTableItemBlock.class, "SearedBlockNether");
GameRegistry.registerTileEntity(CastingTableLogic.class, "CastingTable");
GameRegistry.registerTileEntity(FaucetLogic.class, "Faucet");
GameRegistry.registerTileEntity(CastingBasinLogic.class, "CastingBasin");
GameRegistry.registerBlock(TinkerSmeltery.castingChannel, CastingChannelItem.class, "CastingChannel");
GameRegistry.registerTileEntity(CastingChannelLogic.class, "CastingChannel");
GameRegistry.registerBlock(TinkerSmeltery.tankAir, "TankAir");
GameRegistry.registerTileEntity(TankAirLogic.class, "tconstruct.tank.air");
GameRegistry.registerBlock(TinkerSmeltery.speedBlock, SpeedBlockItem.class, "SpeedBlock");
// Glass
GameRegistry.registerBlock(TinkerSmeltery.clearGlass, GlassBlockItem.class, "GlassBlock");
GameRegistry.registerBlock(TinkerSmeltery.glassPane, GlassPaneItem.class, "GlassPane");
GameRegistry.registerBlock(TinkerSmeltery.stainedGlassClear, StainedGlassClearItem.class, "GlassBlock.StainedClear");
GameRegistry.registerBlock(TinkerSmeltery.stainedGlassClearPane, StainedGlassClearPaneItem.class, "GlassPaneClearStained");
//Items
TinkerSmeltery.metalPattern = new MetalPattern("cast_", "materials/").setUnlocalizedName("tconstruct.MetalPattern");
GameRegistry.registerItem(TinkerSmeltery.metalPattern, "metalPattern");
TConstructRegistry.addItemToDirectory("metalPattern", TinkerSmeltery.metalPattern);
String[] patternTypes = { "ingot", "toolRod", "pickaxeHead", "shovelHead", "hatchetHead", "swordBlade", "wideGuard", "handGuard", "crossbar", "binding", "frypanHead", "signHead",
"knifeBlade", "chiselHead", "toughRod", "toughBinding", "largePlate", "broadAxeHead", "scytheHead", "excavatorHead", "largeBlade", "hammerHead", "fullGuard" };
for (int i = 0; i < patternTypes.length; i++)
{
TConstructRegistry.addItemStackToDirectory(patternTypes[i] + "Cast", new ItemStack(TinkerSmeltery.metalPattern, 1, i));
}
}
@Handler
public void init (FMLInitializationEvent event)
{
proxy.initialize();
craftingTableRecipes();
addRecipesForSmeltery();
addOreDictionarySmelteryRecipes();
addRecipesForTableCasting();
addRecipesForBasinCasting();
}
@Handler
public void postInit (FMLPostInitializationEvent evt)
{
modIntegration();
}
private void craftingTableRecipes ()
{
String[] patSurround = { "###", "#m#", "###" };
// stained Glass Recipes
String[] dyeTypes = { "dyeBlack", "dyeRed", "dyeGreen", "dyeBrown", "dyeBlue", "dyePurple", "dyeCyan", "dyeLightGray", "dyeGray", "dyePink", "dyeLime", "dyeYellow", "dyeLightBlue",
"dyeMagenta", "dyeOrange", "dyeWhite" };
String color = "";
for (int i = 0; i < 16; i++)
{
color = dyeTypes[15 - i];
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(TinkerSmeltery.stainedGlassClear, 8, i), patSurround, 'm', color, '#', TinkerSmeltery.clearGlass));
GameRegistry.addRecipe(new ShapelessOreRecipe(new ItemStack(TinkerSmeltery.stainedGlassClear, 1, i), color, TinkerSmeltery.clearGlass));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(TinkerSmeltery.stainedGlassClear, 8, i), patSurround, 'm', color, '#', new ItemStack(TinkerSmeltery.stainedGlassClear, 1,
Short.MAX_VALUE)));
GameRegistry.addRecipe(new ShapelessOreRecipe(new ItemStack(TinkerSmeltery.stainedGlassClear, 1, i), color, new ItemStack(TinkerSmeltery.stainedGlassClear, 1, Short.MAX_VALUE)));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(TinkerSmeltery.stainedGlassClearPane, 8, i), patSurround, 'm', color, '#', TinkerSmeltery.glassPane));
GameRegistry.addRecipe(new ShapelessOreRecipe(new ItemStack(TinkerSmeltery.stainedGlassClearPane, 1, i), color, TinkerSmeltery.glassPane));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(TinkerSmeltery.stainedGlassClearPane, 8, i), patSurround, 'm', color, '#', new ItemStack(TinkerSmeltery.stainedGlassClearPane, 1,
Short.MAX_VALUE)));
GameRegistry.addRecipe(new ShapelessOreRecipe(new ItemStack(TinkerSmeltery.stainedGlassClearPane, 1, i), color, new ItemStack(TinkerSmeltery.stainedGlassClearPane, 1, Short.MAX_VALUE)));
}
// Glass Recipes
GameRegistry.addRecipe(new ItemStack(Items.glass_bottle, 3), new Object[] { "# #", " # ", '#', TinkerSmeltery.clearGlass });
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(Blocks.daylight_detector), new Object[] { "GGG", "QQQ", "WWW", 'G', "blockGlass", 'Q', Items.quartz, 'W', "slabWood" }));
GameRegistry.addRecipe(new ItemStack(Blocks.beacon, 1), new Object[] { "GGG", "GSG", "OOO", 'G', TinkerSmeltery.clearGlass, 'S', Items.nether_star, 'O', Blocks.obsidian });
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(TinkerSmeltery.glassPane, 16, 0), "GGG", "GGG", 'G', TinkerSmeltery.clearGlass));
// Smeltery Components Recipes
ItemStack searedBrick = new ItemStack(TinkerTools.materials, 1, 2);
GameRegistry.addRecipe(new ItemStack(TinkerSmeltery.smeltery, 1, 0), "bbb", "b b", "bbb", 'b', searedBrick); // Controller
GameRegistry.addRecipe(new ItemStack(TinkerSmeltery.smeltery, 1, 1), "b b", "b b", "b b", 'b', searedBrick); // Drain
GameRegistry.addRecipe(new ItemStack(TinkerSmeltery.smeltery, 1, 2), "bb", "bb", 'b', searedBrick); // Bricks
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(TinkerSmeltery.lavaTank, 1, 0), patSurround, '#', searedBrick, 'm', "blockGlass")); // Tank
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(TinkerSmeltery.lavaTank, 1, 1), "bgb", "ggg", "bgb", 'b', searedBrick, 'g', "blockGlass")); // Glass
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(TinkerSmeltery.lavaTank, 1, 2), "bgb", "bgb", "bgb", 'b', searedBrick, 'g', "blockGlass")); // Window
GameRegistry.addRecipe(new ItemStack(TinkerSmeltery.searedBlock, 1, 0), "bbb", "b b", "b b", 'b', searedBrick); // Table
GameRegistry.addRecipe(new ItemStack(TinkerSmeltery.searedBlock, 1, 1), "b b", " b ", 'b', searedBrick); // Faucet
GameRegistry.addRecipe(new ItemStack(TinkerSmeltery.searedBlock, 1, 2), "b b", "b b", "bbb", 'b', searedBrick); // Basin
GameRegistry.addRecipe(new ItemStack(TinkerSmeltery.castingChannel, 4, 0), "b b", "bbb", 'b', searedBrick); // Channel
searedBrick = new ItemStack(TinkerTools.materials, 1, 37);
GameRegistry.addRecipe(new ItemStack(TinkerSmeltery.smelteryNether, 1, 0), "bbb", "b b", "bbb", 'b', searedBrick); // Controller
GameRegistry.addRecipe(new ItemStack(TinkerSmeltery.smelteryNether, 1, 1), "b b", "b b", "b b", 'b', searedBrick); // Drain
GameRegistry.addRecipe(new ItemStack(TinkerSmeltery.smelteryNether, 1, 2), "bb", "bb", 'b', searedBrick); // Bricks
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(TinkerSmeltery.lavaTankNether, 1, 0), patSurround, '#', searedBrick, 'm', "blockGlass")); // Tank
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(TinkerSmeltery.lavaTankNether, 1, 1), "bgb", "ggg", "bgb", 'b', searedBrick, 'g', "blockGlass")); // Glass
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(TinkerSmeltery.lavaTankNether, 1, 2), "bgb", "bgb", "bgb", 'b', searedBrick, 'g', "blockGlass")); // Window
GameRegistry.addRecipe(new ItemStack(TinkerSmeltery.searedBlockNether, 1, 0), "bbb", "b b", "b b", 'b', searedBrick); // Table
GameRegistry.addRecipe(new ItemStack(TinkerSmeltery.searedBlockNether, 1, 1), "b b", " b ", 'b', searedBrick); // Faucet
GameRegistry.addRecipe(new ItemStack(TinkerSmeltery.searedBlockNether, 1, 2), "b b", "b b", "bbb", 'b', searedBrick); // Basin
GameRegistry.addRecipe(new ItemStack(TinkerSmeltery.castingChannel, 4, 0), "b b", "bbb", 'b', searedBrick); // Channel
// Slab Smeltery Components Recipes
for (int i = 0; i < 7; i++)
{
GameRegistry.addRecipe(new ItemStack(TinkerSmeltery.speedSlab, 6, i), "bbb", 'b', new ItemStack(TinkerSmeltery.speedBlock, 1, i));
}
GameRegistry.addRecipe(new ItemStack(TinkerSmeltery.searedSlab, 6, 0), "bbb", 'b', new ItemStack(TinkerSmeltery.smeltery, 1, 2));
GameRegistry.addRecipe(new ItemStack(TinkerSmeltery.searedSlab, 6, 1), "bbb", 'b', new ItemStack(TinkerSmeltery.smeltery, 1, 4));
GameRegistry.addRecipe(new ItemStack(TinkerSmeltery.searedSlab, 6, 2), "bbb", 'b', new ItemStack(TinkerSmeltery.smeltery, 1, 5));
GameRegistry.addRecipe(new ItemStack(TinkerSmeltery.searedSlab, 6, 3), "bbb", 'b', new ItemStack(TinkerSmeltery.smeltery, 1, 6));
GameRegistry.addRecipe(new ItemStack(TinkerSmeltery.searedSlab, 6, 4), "bbb", 'b', new ItemStack(TinkerSmeltery.smeltery, 1, 8));
GameRegistry.addRecipe(new ItemStack(TinkerSmeltery.searedSlab, 6, 5), "bbb", 'b', new ItemStack(TinkerSmeltery.smeltery, 1, 9));
GameRegistry.addRecipe(new ItemStack(TinkerSmeltery.searedSlab, 6, 6), "bbb", 'b', new ItemStack(TinkerSmeltery.smeltery, 1, 10));
GameRegistry.addRecipe(new ItemStack(TinkerSmeltery.searedSlab, 6, 7), "bbb", 'b', new ItemStack(TinkerSmeltery.smeltery, 1, 11));
}
public void addOreDictionarySmelteryRecipes ()
{
List<FluidType> exceptions = Arrays.asList(new FluidType[] { FluidType.getFluidType("Water"), FluidType.getFluidType("Stone"), FluidType.getFluidType("Ender"),
FluidType.getFluidType("Glass"), FluidType.getFluidType("Slime"), FluidType.getFluidType("Obsidian") });
Iterator iter = FluidType.fluidTypes.entrySet().iterator();
while (iter.hasNext())
{
Map.Entry pairs = (Map.Entry) iter.next();
FluidType ft = (FluidType) pairs.getValue();
if (exceptions.contains(ft))
continue;
String fluidTypeName = (String) pairs.getKey();
// Nuggets
Smeltery.addDictionaryMelting("nugget" + fluidTypeName, ft, -100, TConstruct.nuggetLiquidValue);
// Ingots, Dust
registerIngotCasting(ft, "ingot" + fluidTypeName);
Smeltery.addDictionaryMelting("ingot" + fluidTypeName, ft, -50, TConstruct.ingotLiquidValue);
Smeltery.addDictionaryMelting("dust" + fluidTypeName, ft, -75, TConstruct.ingotLiquidValue);
// Factorization support
Smeltery.addDictionaryMelting("crystalline" + fluidTypeName, ft, -50, TConstruct.ingotLiquidValue);
// Ores
Smeltery.addDictionaryMelting("ore" + fluidTypeName, ft, 0, (int) (TConstruct.ingotLiquidValue * PHConstruct.ingotsPerOre));
// NetherOres support
Smeltery.addDictionaryMelting("oreNether" + fluidTypeName, ft, 75, (int) (TConstruct.ingotLiquidValue * PHConstruct.ingotsPerOre * 2));
// Blocks
Smeltery.addDictionaryMelting("block" + fluidTypeName, ft, 100, TConstruct.blockLiquidValue);
if (ft.isToolpart)
{
TinkerTools.registerPatternMaterial("ingot" + fluidTypeName, 2, fluidTypeName);
TinkerTools.registerPatternMaterial("block" + fluidTypeName, 18, fluidTypeName);
}
}
// Obsidian, different dust amount
{
FluidType ft = FluidType.getFluidType("Obsidian");
String fluidTypeName = "Obsidian";
Smeltery.addDictionaryMelting("nugget" + fluidTypeName, ft, -100, TConstruct.nuggetLiquidValue);
// Ingots, Dust
registerIngotCasting(ft, fluidTypeName);
Smeltery.addDictionaryMelting("ingot" + fluidTypeName, ft, -50, TConstruct.ingotLiquidValue);
Smeltery.addDictionaryMelting("dust" + fluidTypeName, ft, -75, TConstruct.ingotLiquidValue / 4);
// Factorization support
Smeltery.addDictionaryMelting("crystalline" + fluidTypeName, ft, -50, TConstruct.ingotLiquidValue);
// Ores
Smeltery.addDictionaryMelting("ore" + fluidTypeName, ft, 0, ((int) TConstruct.ingotLiquidValue * (int) PHConstruct.ingotsPerOre));
// Poor ores
Smeltery.addDictionaryMelting("orePoor" + fluidTypeName, ft, 0, (int) (TConstruct.nuggetLiquidValue * PHConstruct.ingotsPerOre * 1.5f));
// NetherOres support
Smeltery.addDictionaryMelting("oreNether" + fluidTypeName, ft, 75, ((int) TConstruct.ingotLiquidValue * (int) PHConstruct.ingotsPerOre * 2));
// Blocks
Smeltery.addDictionaryMelting("block" + fluidTypeName, ft, 100, TConstruct.blockLiquidValue);
if (ft.isToolpart)
{
TinkerTools.registerPatternMaterial("ingot" + fluidTypeName, 2, fluidTypeName);
TinkerTools.registerPatternMaterial("block" + fluidTypeName, 18, fluidTypeName);
}
}
// Compressed materials
for (int i = 1; i <= 8; i++)
{
Smeltery.addDictionaryMelting("compressedCobblestone" + i + "x", FluidType.getFluidType("Stone"), 0, TConstruct.ingotLiquidValue / 18 * (9 ^ i));
}
Smeltery.addDictionaryMelting("compressedSand1x", FluidType.getFluidType("Glass"), 175, FluidContainerRegistry.BUCKET_VOLUME * 9);
}
private void addRecipesForTableCasting ()
{
/* Smeltery */
ItemStack ingotcast = new ItemStack(TinkerSmeltery.metalPattern, 1, 0);
ItemStack gemcast = new ItemStack(TinkerSmeltery.metalPattern, 1, 26);
LiquidCasting tableCasting = TConstructRegistry.instance.getTableCasting();
// Blank
tableCasting.addCastingRecipe(new ItemStack(TinkerTools.blankPattern, 1, 1), new FluidStack(TinkerSmeltery.moltenAlubrassFluid, TConstruct.ingotLiquidValue), 80);
tableCasting.addCastingRecipe(new ItemStack(TinkerTools.blankPattern, 1, 2), new FluidStack(TinkerSmeltery.moltenGoldFluid, TConstruct.ingotLiquidValue * 2), 80);
tableCasting.addCastingRecipe(gemcast, new FluidStack(TinkerSmeltery.moltenAlubrassFluid, TConstruct.ingotLiquidValue), new ItemStack(Items.emerald), 80);
tableCasting.addCastingRecipe(gemcast, new FluidStack(TinkerSmeltery.moltenGoldFluid, TConstruct.ingotLiquidValue * 2), new ItemStack(Items.emerald), 80);
// Ingots
tableCasting.addCastingRecipe(new ItemStack(TinkerTools.materials, 1, 2), new FluidStack(TinkerSmeltery.moltenStoneFluid, TConstruct.ingotLiquidValue / 4), ingotcast, 80); // stone
// Misc
tableCasting.addCastingRecipe(new ItemStack(Items.emerald), new FluidStack(TinkerSmeltery.moltenEmeraldFluid, 640), gemcast, 80);
tableCasting.addCastingRecipe(new ItemStack(TinkerTools.materials, 1, 36), new FluidStack(TinkerSmeltery.glueFluid, TConstruct.ingotLiquidValue), null, 50);
tableCasting.addCastingRecipe(new ItemStack(TinkerWorld.strangeFood, 1, 1), new FluidStack(TinkerSmeltery.bloodFluid, 160), null, 50);
// Buckets
ItemStack bucket = new ItemStack(Items.bucket);
for (int sc = 0; sc < 23; sc++)
{
tableCasting.addCastingRecipe(new ItemStack(TinkerSmeltery.buckets, 1, sc), new FluidStack(TinkerSmeltery.fluids[sc], FluidContainerRegistry.BUCKET_VOLUME), bucket, true, 10);
}
tableCasting.addCastingRecipe(new ItemStack(TinkerSmeltery.buckets, 1, 25), new FluidStack(TinkerSmeltery.fluids[25], FluidContainerRegistry.BUCKET_VOLUME), bucket, true, 10);
// Clear glass pane casting
tableCasting.addCastingRecipe(new ItemStack(TinkerSmeltery.glassPane), new FluidStack(TinkerSmeltery.moltenGlassFluid, 250), null, 80);
// Metal toolpart casting
TinkerSmeltery.liquids = new FluidStack[] { new FluidStack(TinkerSmeltery.moltenIronFluid, 1), new FluidStack(TinkerSmeltery.moltenCopperFluid, 1),
new FluidStack(TinkerSmeltery.moltenCobaltFluid, 1), new FluidStack(TinkerSmeltery.moltenArditeFluid, 1), new FluidStack(TinkerSmeltery.moltenManyullynFluid, 1),
new FluidStack(TinkerSmeltery.moltenBronzeFluid, 1), new FluidStack(TinkerSmeltery.moltenAlumiteFluid, 1), new FluidStack(TinkerSmeltery.moltenObsidianFluid, 1),
new FluidStack(TinkerSmeltery.moltenSteelFluid, 1), new FluidStack(TinkerSmeltery.pigIronFluid, 1) };
int[] liquidDamage = new int[] { 2, 13, 10, 11, 12, 14, 15, 6, 16, 18 }; // ItemStack
// damage
// value
int fluidAmount = 0;
Fluid fs = null;
for (int iter = 0; iter < TinkerTools.patternOutputs.length; iter++)
{
if (TinkerTools.patternOutputs[iter] != null)
{
ItemStack cast = new ItemStack(TinkerSmeltery.metalPattern, 1, iter + 1);
tableCasting.addCastingRecipe(cast, new FluidStack(TinkerSmeltery.moltenAlubrassFluid, TConstruct.ingotLiquidValue),
new ItemStack(TinkerTools.patternOutputs[iter], 1, Short.MAX_VALUE), false, 50);
tableCasting.addCastingRecipe(cast, new FluidStack(TinkerSmeltery.moltenGoldFluid, TConstruct.ingotLiquidValue * 2),
new ItemStack(TinkerTools.patternOutputs[iter], 1, Short.MAX_VALUE), false, 50);
for (int iterTwo = 0; iterTwo < TinkerSmeltery.liquids.length; iterTwo++)
{
fs = TinkerSmeltery.liquids[iterTwo].getFluid();
fluidAmount = ((IPattern) TinkerSmeltery.metalPattern).getPatternCost(cast) * TConstruct.ingotLiquidValue / 2;
ItemStack metalCast = new ItemStack(TinkerTools.patternOutputs[iter], 1, liquidDamage[iterTwo]);
tableCasting.addCastingRecipe(metalCast, new FluidStack(fs, fluidAmount), cast, 50);
Smeltery.addMelting(FluidType.getFluidType(fs), metalCast, 0, fluidAmount);
}
}
}
tableCasting.addCastingRecipe(new ItemStack(Items.ender_pearl), new FluidStack(TinkerSmeltery.moltenEnderFluid, 250), new ItemStack(TinkerSmeltery.metalPattern, 1, 10), 50);
tableCasting.addCastingRecipe(new ItemStack(Items.ender_pearl), new FluidStack(TinkerSmeltery.moltenEnderFluid, 250), new ItemStack(TinkerSmeltery.metalPattern, 1, 26), 50);
ItemStack[] ingotShapes = { new ItemStack(Items.brick), new ItemStack(Items.netherbrick), new ItemStack(TinkerTools.materials, 1, 2), new ItemStack(TinkerTools.materials, 1, 37) };
for (int i = 0; i < ingotShapes.length; i++)
{
tableCasting.addCastingRecipe(ingotcast, new FluidStack(TinkerSmeltery.moltenAlubrassFluid, TConstruct.ingotLiquidValue), ingotShapes[i], false, 50);
tableCasting.addCastingRecipe(ingotcast, new FluidStack(TinkerSmeltery.moltenGoldFluid, TConstruct.ingotLiquidValue * 2), ingotShapes[i], false, 50);
}
ItemStack fullguardCast = new ItemStack(TinkerSmeltery.metalPattern, 1, 22);
tableCasting.addCastingRecipe(fullguardCast, new FluidStack(TinkerSmeltery.moltenAlubrassFluid, TConstruct.ingotLiquidValue), new ItemStack(TinkerTools.fullGuard, 1, Short.MAX_VALUE), false,
50);
tableCasting.addCastingRecipe(fullguardCast, new FluidStack(TinkerSmeltery.moltenGoldFluid, TConstruct.ingotLiquidValue * 2), new ItemStack(TinkerTools.fullGuard, 1, Short.MAX_VALUE), false,
50);
// Golden Food Stuff
FluidStack goldAmount = null;
if (PHConstruct.goldAppleRecipe)
{
goldAmount = new FluidStack(TinkerSmeltery.moltenGoldFluid, TConstruct.ingotLiquidValue * 8);
}
else
{
goldAmount = new FluidStack(TinkerSmeltery.moltenGoldFluid, TConstruct.nuggetLiquidValue * 8);
}
tableCasting.addCastingRecipe(new ItemStack(Items.golden_apple, 1), goldAmount, new ItemStack(Items.apple), true, 50);
tableCasting.addCastingRecipe(new ItemStack(Items.golden_carrot, 1), goldAmount, new ItemStack(Items.carrot), true, 50);
tableCasting.addCastingRecipe(new ItemStack(Items.speckled_melon, 1), goldAmount, new ItemStack(Items.melon), true, 50);
tableCasting.addCastingRecipe(new ItemStack(TinkerTools.goldHead), goldAmount, new ItemStack(Items.skull, 1, 3), true, 50);
}
protected static void addRecipesForBasinCasting ()
{
LiquidCasting basinCasting = TConstructRegistry.getBasinCasting();
// Block Casting
basinCasting.addCastingRecipe(new ItemStack(Blocks.iron_block), new FluidStack(TinkerSmeltery.moltenIronFluid, TConstruct.blockLiquidValue), null, true, 100); // Iron
basinCasting.addCastingRecipe(new ItemStack(Blocks.gold_block), new FluidStack(TinkerSmeltery.moltenGoldFluid, TConstruct.blockLiquidValue), null, true, 100); // gold
basinCasting.addCastingRecipe(new ItemStack(TinkerWorld.metalBlock, 1, 3), new FluidStack(TinkerSmeltery.moltenCopperFluid, TConstruct.blockLiquidValue), null, true, 100); // copper
basinCasting.addCastingRecipe(new ItemStack(TinkerWorld.metalBlock, 1, 5), new FluidStack(TinkerSmeltery.moltenTinFluid, TConstruct.blockLiquidValue), null, true, 100); // tin
basinCasting.addCastingRecipe(new ItemStack(TinkerWorld.metalBlock, 1, 6), new FluidStack(TinkerSmeltery.moltenAluminumFluid, TConstruct.blockLiquidValue), null, true, 100); // aluminum
basinCasting.addCastingRecipe(new ItemStack(TinkerWorld.metalBlock, 1, 0), new FluidStack(TinkerSmeltery.moltenCobaltFluid, TConstruct.blockLiquidValue), null, true, 100); // cobalt
basinCasting.addCastingRecipe(new ItemStack(TinkerWorld.metalBlock, 1, 1), new FluidStack(TinkerSmeltery.moltenArditeFluid, TConstruct.blockLiquidValue), null, true, 100); // ardite
basinCasting.addCastingRecipe(new ItemStack(TinkerWorld.metalBlock, 1, 4), new FluidStack(TinkerSmeltery.moltenBronzeFluid, TConstruct.blockLiquidValue), null, true, 100); // bronze
basinCasting.addCastingRecipe(new ItemStack(TinkerWorld.metalBlock, 1, 7), new FluidStack(TinkerSmeltery.moltenAlubrassFluid, TConstruct.blockLiquidValue), null, true, 100); // albrass
basinCasting.addCastingRecipe(new ItemStack(TinkerWorld.metalBlock, 1, 2), new FluidStack(TinkerSmeltery.moltenManyullynFluid, TConstruct.blockLiquidValue), null, true, 100); // manyullyn
basinCasting.addCastingRecipe(new ItemStack(TinkerWorld.metalBlock, 1, 8), new FluidStack(TinkerSmeltery.moltenAlumiteFluid, TConstruct.blockLiquidValue), null, true, 100); // alumite
basinCasting.addCastingRecipe(new ItemStack(Blocks.obsidian), new FluidStack(TinkerSmeltery.moltenObsidianFluid, TConstruct.oreLiquidValue), null, true, 100);// obsidian
basinCasting.addCastingRecipe(new ItemStack(TinkerWorld.metalBlock, 1, 9), new FluidStack(TinkerSmeltery.moltenSteelFluid, TConstruct.blockLiquidValue), null, true, 100); // steel
basinCasting.addCastingRecipe(new ItemStack(TinkerSmeltery.clearGlass, 1, 0), new FluidStack(TinkerSmeltery.moltenGlassFluid, FluidContainerRegistry.BUCKET_VOLUME), null, true, 100); // glass
basinCasting.addCastingRecipe(new ItemStack(TinkerSmeltery.smeltery, 1, 4), new FluidStack(TinkerSmeltery.moltenStoneFluid, TConstruct.ingotLiquidValue), null, true, 100); // seared
// stone
basinCasting.addCastingRecipe(new ItemStack(TinkerSmeltery.smeltery, 1, 5), new FluidStack(TinkerSmeltery.moltenStoneFluid, TConstruct.chunkLiquidValue), new ItemStack(Blocks.cobblestone),
true, 100);
basinCasting.addCastingRecipe(new ItemStack(Blocks.emerald_block), new FluidStack(TinkerSmeltery.moltenEmeraldFluid, 640 * 9), null, true, 100); // emerald
basinCasting.addCastingRecipe(new ItemStack(TinkerSmeltery.speedBlock, 1, 0), new FluidStack(TinkerSmeltery.moltenTinFluid, TConstruct.nuggetLiquidValue), new ItemStack(Blocks.gravel), true,
100); // brownstone
if (PHConstruct.craftEndstone)
{
basinCasting.addCastingRecipe(new ItemStack(Blocks.end_stone), new FluidStack(TinkerSmeltery.moltenEnderFluid, 50), new ItemStack(Blocks.obsidian), true, 100);
basinCasting.addCastingRecipe(new ItemStack(Blocks.end_stone), new FluidStack(TinkerSmeltery.moltenEnderFluid, 250), new ItemStack(Blocks.sandstone), true, 100);
}
basinCasting.addCastingRecipe(new ItemStack(TinkerWorld.metalBlock, 1, 10), new FluidStack(TinkerSmeltery.moltenEnderFluid, 1000), null, true, 100); // ender
basinCasting.addCastingRecipe(new ItemStack(TinkerSmeltery.glueBlock), new FluidStack(TinkerSmeltery.glueFluid, TConstruct.blockLiquidValue), null, true, 100); // glue
// basinCasting.addCastingRecipe(new ItemStack(slimeGel, 1, 0), new
// FluidStack(blueSlimeFluid, FluidContainerRegistry.BUCKET_VOLUME),
// null, true, 100);
// Armor casts
/*
* FluidRenderProperties frp = new
* FluidRenderProperties(Applications.BASIN.minHeight, 0.65F,
* Applications.BASIN); FluidStack aluFlu = new
* FluidStack(TRepo.moltenAlubrassFluid, TConstruct.ingotLiquidValue *
* 10); FluidStack gloFlu = new FluidStack(TRepo.moltenGoldFluid,
* TConstruct.ingotLiquidValue * 10); ItemStack[] armor = { new
* ItemStack(helmetWood), new ItemStack(chestplateWood), new
* ItemStack(leggingsWood), new ItemStack(bootsWood) }; for (int sc = 0;
* sc < armor.length; sc++) { basinCasting.addCastingRecipe(new
* ItemStack(armorPattern, 1, sc), aluFlu, armor[sc], 50, frp);
* basinCasting.addCastingRecipe(new ItemStack(armorPattern, 1, sc),
* gloFlu, armor[sc], 50, frp); }
*/
}
protected static void addRecipesForSmeltery ()
{
// Alloy Smelting
Smeltery.addAlloyMixing(new FluidStack(TinkerSmeltery.moltenBronzeFluid, (int) (TConstruct.nuggetLiquidValue * PHConstruct.ingotsBronzeAlloy)), new FluidStack(
TinkerSmeltery.moltenCopperFluid, TConstruct.nuggetLiquidValue * 3), new FluidStack(TinkerSmeltery.moltenTinFluid, TConstruct.nuggetLiquidValue)); // Bronze
Smeltery.addAlloyMixing(new FluidStack(TinkerSmeltery.moltenAlubrassFluid, (int) (TConstruct.nuggetLiquidValue * PHConstruct.ingotsAluminumBrassAlloy)), new FluidStack(
TinkerSmeltery.moltenAluminumFluid, TConstruct.nuggetLiquidValue * 3), new FluidStack(TinkerSmeltery.moltenCopperFluid, TConstruct.nuggetLiquidValue * 1)); // Aluminum Brass
Smeltery.addAlloyMixing(new FluidStack(TinkerSmeltery.moltenAlumiteFluid, (int) (TConstruct.nuggetLiquidValue * PHConstruct.ingotsAlumiteAlloy)), new FluidStack(
TinkerSmeltery.moltenAluminumFluid, TConstruct.nuggetLiquidValue * 5), new FluidStack(TinkerSmeltery.moltenIronFluid, TConstruct.nuggetLiquidValue * 2), new FluidStack(
TinkerSmeltery.moltenObsidianFluid, TConstruct.nuggetLiquidValue * 2)); // Alumite
Smeltery.addAlloyMixing(new FluidStack(TinkerSmeltery.moltenManyullynFluid, (int) (TConstruct.nuggetLiquidValue * PHConstruct.ingotsManyullynAlloy)), new FluidStack(
TinkerSmeltery.moltenCobaltFluid, TConstruct.nuggetLiquidValue), new FluidStack(TinkerSmeltery.moltenArditeFluid, TConstruct.nuggetLiquidValue)); // Manyullyn
Smeltery.addAlloyMixing(new FluidStack(TinkerSmeltery.pigIronFluid, (int) (TConstruct.nuggetLiquidValue * PHConstruct.ingotsPigironAlloy)), new FluidStack(TinkerSmeltery.moltenIronFluid,
TConstruct.nuggetLiquidValue), new FluidStack(TinkerSmeltery.moltenEmeraldFluid, 640), new FluidStack(TinkerSmeltery.bloodFluid, 80)); // Pigiron
Smeltery.addAlloyMixing(new FluidStack(TinkerSmeltery.moltenObsidianFluid, TConstruct.oreLiquidValue), new FluidStack(FluidRegistry.LAVA, 1000), new FluidStack(FluidRegistry.WATER, 1000)); //Obsidian
// Stone parts
FluidType stone = FluidType.getFluidType("Stone");
for (int sc = 0; sc < TinkerTools.patternOutputs.length; sc++)
{
if (TinkerTools.patternOutputs[sc] != null)
{
Smeltery.addMelting(stone, new ItemStack(TinkerTools.patternOutputs[sc], 1, 1), 1,
(8 * ((IPattern) TinkerTools.woodPattern).getPatternCost(new ItemStack(TinkerTools.woodPattern, 1, sc + 1))) / 2);
}
}
FluidType iron = FluidType.getFluidType("Iron");
FluidType gold = FluidType.getFluidType("Gold");
FluidType steel = FluidType.getFluidType("Steel");
// Chunks
Smeltery.addMelting(FluidType.getFluidType("Stone"), new ItemStack(TinkerTools.toolShard, 1, 1), 0, 4);
Smeltery.addMelting(iron, new ItemStack(TinkerTools.toolShard, 1, 2), 0, TConstruct.chunkLiquidValue);
Smeltery.addMelting(FluidType.getFluidType("Obsidian"), new ItemStack(TinkerTools.toolShard, 1, 6), 0, TConstruct.chunkLiquidValue);
Smeltery.addMelting(FluidType.getFluidType("Cobalt"), new ItemStack(TinkerTools.toolShard, 1, 10), 0, TConstruct.chunkLiquidValue);
Smeltery.addMelting(FluidType.getFluidType("Ardite"), new ItemStack(TinkerTools.toolShard, 1, 11), 0, TConstruct.chunkLiquidValue);
Smeltery.addMelting(FluidType.getFluidType("Manyullyn"), new ItemStack(TinkerTools.toolShard, 1, 12), 0, TConstruct.chunkLiquidValue);
Smeltery.addMelting(FluidType.getFluidType("Copper"), new ItemStack(TinkerTools.toolShard, 1, 13), 0, TConstruct.chunkLiquidValue);
Smeltery.addMelting(FluidType.getFluidType("Bronze"), new ItemStack(TinkerTools.toolShard, 1, 14), 0, TConstruct.chunkLiquidValue);
Smeltery.addMelting(FluidType.getFluidType("Alumite"), new ItemStack(TinkerTools.toolShard, 1, 15), 0, TConstruct.chunkLiquidValue);
Smeltery.addMelting(steel, new ItemStack(TinkerTools.toolShard, 1, 16), 0, TConstruct.chunkLiquidValue);
// Items
Smeltery.addMelting(FluidType.getFluidType("AluminumBrass"), new ItemStack(TinkerTools.blankPattern, 4, 1), -50, TConstruct.ingotLiquidValue);
Smeltery.addMelting(gold, new ItemStack(TinkerTools.blankPattern, 4, 2), -50, TConstruct.ingotLiquidValue * 2);
Smeltery.addMelting(FluidType.getFluidType("Glue"), new ItemStack(TinkerTools.materials, 1, 36), 0, TConstruct.ingotLiquidValue);
Smeltery.addMelting(FluidType.getFluidType("Ender"), new ItemStack(Items.ender_pearl, 4), 0, 250);
Smeltery.addMelting(TinkerWorld.metalBlock, 10, 50, new FluidStack(moltenEnderFluid, 1000));
Smeltery.addMelting(FluidType.getFluidType("Water"), new ItemStack(Items.snowball, 1, 0), 0, 125);
Smeltery.addMelting(iron, new ItemStack(Items.flint_and_steel, 1, 0), 0, TConstruct.ingotLiquidValue);
Smeltery.addMelting(iron, new ItemStack(Items.compass, 1, 0), 0, TConstruct.ingotLiquidValue * 4);
Smeltery.addMelting(iron, new ItemStack(Items.bucket), 0, TConstruct.ingotLiquidValue * 3);
Smeltery.addMelting(iron, new ItemStack(Items.minecart), 0, TConstruct.ingotLiquidValue * 5);
Smeltery.addMelting(iron, new ItemStack(Items.chest_minecart), 0, TConstruct.ingotLiquidValue * 5);
Smeltery.addMelting(iron, new ItemStack(Items.furnace_minecart), 0, TConstruct.ingotLiquidValue * 5);
Smeltery.addMelting(iron, new ItemStack(Items.hopper_minecart), 50, TConstruct.ingotLiquidValue * 10);
Smeltery.addMelting(iron, new ItemStack(Items.iron_door), 0, TConstruct.ingotLiquidValue * 6);
Smeltery.addMelting(iron, new ItemStack(Items.cauldron), 0, TConstruct.ingotLiquidValue * 7);
Smeltery.addMelting(iron, new ItemStack(Items.shears), 0, TConstruct.ingotLiquidValue * 2);
Smeltery.addMelting(FluidType.getFluidType("Emerald"), new ItemStack(Items.emerald), -50, 640);
Smeltery.addMelting(FluidType.getFluidType("Ardite"), new ItemStack(TinkerTools.materials, 1, 38), 0, TConstruct.ingotLiquidValue);
Smeltery.addMelting(FluidType.getFluidType("Cobalt"), new ItemStack(TinkerTools.materials, 1, 39), 0, TConstruct.ingotLiquidValue);
Smeltery.addMelting(FluidType.getFluidType("Aluminum"), new ItemStack(TinkerTools.materials, 1, 40), 0, TConstruct.ingotLiquidValue);
Smeltery.addMelting(FluidType.getFluidType("Manyullyn"), new ItemStack(TinkerTools.materials, 1, 41), 0, TConstruct.ingotLiquidValue);
Smeltery.addMelting(FluidType.getFluidType("AluminumBrass"), new ItemStack(TinkerTools.materials, 1, 42), 0, TConstruct.ingotLiquidValue);
// Blocks melt as themselves!
// Ore
Smeltery.addMelting(Blocks.iron_ore, 0, 600, new FluidStack(TinkerSmeltery.moltenIronFluid, TConstruct.ingotLiquidValue * 2));
Smeltery.addMelting(Blocks.gold_ore, 0, 400, new FluidStack(TinkerSmeltery.moltenGoldFluid, TConstruct.ingotLiquidValue * 2));
Smeltery.addMelting(TinkerWorld.oreGravel, 0, 600, new FluidStack(TinkerSmeltery.moltenIronFluid, TConstruct.ingotLiquidValue * 2));
Smeltery.addMelting(TinkerWorld.oreGravel, 1, 400, new FluidStack(TinkerSmeltery.moltenGoldFluid, TConstruct.ingotLiquidValue * 2));
// Blocks
Smeltery.addMelting(Blocks.iron_block, 0, 600, new FluidStack(TinkerSmeltery.moltenIronFluid, TConstruct.ingotLiquidValue * 9));
Smeltery.addMelting(Blocks.gold_block, 0, 400, new FluidStack(TinkerSmeltery.moltenGoldFluid, TConstruct.ingotLiquidValue * 9));
Smeltery.addMelting(Blocks.obsidian, 0, 800, new FluidStack(TinkerSmeltery.moltenObsidianFluid, TConstruct.ingotLiquidValue * 2));
Smeltery.addMelting(Blocks.ice, 0, 75, new FluidStack(FluidRegistry.getFluid("water"), 1000));
Smeltery.addMelting(Blocks.snow, 0, 75, new FluidStack(FluidRegistry.getFluid("water"), 500));
Smeltery.addMelting(Blocks.snow_layer, 0, 75, new FluidStack(FluidRegistry.getFluid("water"), 250));
Smeltery.addMelting(Blocks.sand, 0, 625, new FluidStack(TinkerSmeltery.moltenGlassFluid, FluidContainerRegistry.BUCKET_VOLUME));
Smeltery.addMelting(Blocks.glass, 0, 625, new FluidStack(TinkerSmeltery.moltenGlassFluid, FluidContainerRegistry.BUCKET_VOLUME));
Smeltery.addMelting(Blocks.glass_pane, 0, 625, new FluidStack(TinkerSmeltery.moltenGlassFluid, 250));
Smeltery.addMelting(Blocks.stone, 0, 800, new FluidStack(TinkerSmeltery.moltenStoneFluid, TConstruct.ingotLiquidValue / 18));
Smeltery.addMelting(Blocks.cobblestone, 0, 800, new FluidStack(TinkerSmeltery.moltenStoneFluid, TConstruct.ingotLiquidValue / 18));
Smeltery.addMelting(Blocks.emerald_block, 0, 800, new FluidStack(TinkerSmeltery.moltenEmeraldFluid, 640 * 9));
Smeltery.addMelting(TinkerSmeltery.glueBlock, 0, 250, new FluidStack(TinkerSmeltery.glueFluid, TConstruct.blockLiquidValue));
Smeltery.addMelting(TinkerTools.craftedSoil, 1, 600, new FluidStack(TinkerSmeltery.moltenStoneFluid, TConstruct.ingotLiquidValue / 4));
Smeltery.addMelting(TinkerSmeltery.clearGlass, 0, 500, new FluidStack(TinkerSmeltery.moltenGlassFluid, 1000));
Smeltery.addMelting(TinkerSmeltery.glassPane, 0, 350, new FluidStack(TinkerSmeltery.moltenGlassFluid, 250));
for (int i = 0; i < 16; i++)
{
Smeltery.addMelting(TinkerSmeltery.stainedGlassClear, i, 500, new FluidStack(TinkerSmeltery.moltenGlassFluid, 1000));
Smeltery.addMelting(TinkerSmeltery.stainedGlassClearPane, i, 350, new FluidStack(TinkerSmeltery.moltenGlassFluid, 250));
}
// Bricks
Smeltery.addMelting(TinkerTools.multiBrick, 4, 600, new FluidStack(TinkerSmeltery.moltenIronFluid, TConstruct.ingotLiquidValue));
Smeltery.addMelting(TinkerTools.multiBrickFancy, 4, 600, new FluidStack(TinkerSmeltery.moltenIronFluid, TConstruct.ingotLiquidValue));
Smeltery.addMelting(TinkerTools.multiBrick, 5, 400, new FluidStack(TinkerSmeltery.moltenGoldFluid, TConstruct.ingotLiquidValue));
Smeltery.addMelting(TinkerTools.multiBrickFancy, 5, 400, new FluidStack(TinkerSmeltery.moltenGoldFluid, TConstruct.ingotLiquidValue));
Smeltery.addMelting(TinkerTools.multiBrick, 0, 800, new FluidStack(TinkerSmeltery.moltenObsidianFluid, TConstruct.ingotLiquidValue * 2));
Smeltery.addMelting(TinkerTools.multiBrickFancy, 0, 800, new FluidStack(TinkerSmeltery.moltenObsidianFluid, TConstruct.ingotLiquidValue * 2));
// Vanilla blocks
Smeltery.addMelting(iron, new ItemStack(Blocks.iron_bars), 0, TConstruct.ingotLiquidValue * 6 / 16);
Smeltery.addMelting(iron, new ItemStack(Blocks.heavy_weighted_pressure_plate), 0, TConstruct.oreLiquidValue);
Smeltery.addMelting(gold, new ItemStack(Blocks.light_weighted_pressure_plate, 4), 0, TConstruct.oreLiquidValue);
Smeltery.addMelting(iron, new ItemStack(Blocks.rail), 0, TConstruct.ingotLiquidValue * 6 / 16);
Smeltery.addMelting(gold, new ItemStack(Blocks.golden_rail), 0, TConstruct.ingotLiquidValue);
Smeltery.addMelting(iron, new ItemStack(Blocks.detector_rail), 0, TConstruct.ingotLiquidValue);
Smeltery.addMelting(iron, new ItemStack(Blocks.activator_rail), 0, TConstruct.ingotLiquidValue);
Smeltery.addMelting(FluidType.getFluidType("Obsidian"), new ItemStack(Blocks.enchanting_table), 0, TConstruct.ingotLiquidValue * 4);
// Smeltery.addMelting(iron, new ItemStack(Blocks.cauldron),
// 0, TConstruct.ingotLiquidValue * 7);
Smeltery.addMelting(iron, new ItemStack(Blocks.anvil, 1, 0), 200, TConstruct.ingotLiquidValue * 31);
Smeltery.addMelting(iron, new ItemStack(Blocks.anvil, 1, 1), 200, TConstruct.ingotLiquidValue * 31);
Smeltery.addMelting(iron, new ItemStack(Blocks.anvil, 1, 2), 200, TConstruct.ingotLiquidValue * 31);
Smeltery.addMelting(iron, new ItemStack(Blocks.hopper), 0, TConstruct.ingotLiquidValue * 5);
// Vanilla Armor
Smeltery.addMelting(iron, new ItemStack(Items.iron_helmet, 1, 0), 50, TConstruct.ingotLiquidValue * 5);
Smeltery.addMelting(iron, new ItemStack(Items.iron_chestplate, 1, 0), 50, TConstruct.ingotLiquidValue * 8);
Smeltery.addMelting(iron, new ItemStack(Items.iron_leggings, 1, 0), 50, TConstruct.ingotLiquidValue * 7);
Smeltery.addMelting(iron, new ItemStack(Items.iron_boots, 1, 0), 50, TConstruct.ingotLiquidValue * 4);
Smeltery.addMelting(gold, new ItemStack(Items.golden_helmet, 1, 0), 50, TConstruct.ingotLiquidValue * 5);
Smeltery.addMelting(gold, new ItemStack(Items.golden_chestplate, 1, 0), 50, TConstruct.ingotLiquidValue * 8);
Smeltery.addMelting(gold, new ItemStack(Items.golden_leggings, 1, 0), 50, TConstruct.ingotLiquidValue * 7);
Smeltery.addMelting(gold, new ItemStack(Items.golden_boots, 1, 0), 50, TConstruct.ingotLiquidValue * 4);
Smeltery.addMelting(steel, new ItemStack(Items.chainmail_helmet, 1, 0), 25, TConstruct.ingotLiquidValue);
Smeltery.addMelting(steel, new ItemStack(Items.chainmail_chestplate, 1, 0), 50, TConstruct.oreLiquidValue);
Smeltery.addMelting(steel, new ItemStack(Items.chainmail_leggings, 1, 0), 50, TConstruct.oreLiquidValue);
Smeltery.addMelting(steel, new ItemStack(Items.chainmail_boots, 1, 0), 25, TConstruct.ingotLiquidValue);
Smeltery.addMelting(iron, new ItemStack(Items.iron_horse_armor, 1), 100, TConstruct.ingotLiquidValue * 8);
Smeltery.addMelting(gold, new ItemStack(Items.golden_horse_armor, 1), 100, TConstruct.ingotLiquidValue * 8);
// Vanilla tools
Smeltery.addMelting(iron, new ItemStack(Items.iron_hoe, 1, 0), 0, TConstruct.oreLiquidValue);
Smeltery.addMelting(iron, new ItemStack(Items.iron_sword, 1, 0), 0, TConstruct.oreLiquidValue);
Smeltery.addMelting(iron, new ItemStack(Items.iron_shovel, 1, 0), 0, TConstruct.ingotLiquidValue);
Smeltery.addMelting(iron, new ItemStack(Items.iron_pickaxe, 1, 0), 0, TConstruct.ingotLiquidValue * 3);
Smeltery.addMelting(iron, new ItemStack(Items.iron_axe, 1, 0), 0, TConstruct.ingotLiquidValue * 3);
Smeltery.addMelting(gold, new ItemStack(Items.golden_hoe, 1, 0), 0, TConstruct.oreLiquidValue);
Smeltery.addMelting(gold, new ItemStack(Items.golden_sword, 1, 0), 0, TConstruct.oreLiquidValue);
Smeltery.addMelting(gold, new ItemStack(Items.golden_shovel, 1, 0), 0, TConstruct.ingotLiquidValue);
Smeltery.addMelting(gold, new ItemStack(Items.golden_pickaxe, 1, 0), 0, TConstruct.ingotLiquidValue * 3);
Smeltery.addMelting(gold, new ItemStack(Items.golden_axe, 1, 0), 0, TConstruct.ingotLiquidValue * 3);
}
private void registerIngotCasting (FluidType ft, String name)
{
ItemStack pattern = new ItemStack(TinkerSmeltery.metalPattern, 1, 0);
LiquidCasting tableCasting = TConstructRegistry.instance.getTableCasting();
for (ItemStack ore : OreDictionary.getOres(name))
{
tableCasting.addCastingRecipe(pattern, new FluidStack(TinkerSmeltery.moltenAlubrassFluid, TConstruct.ingotLiquidValue), new ItemStack(ore.getItem(), 1, ore.getItemDamage()), false, 50);
tableCasting.addCastingRecipe(pattern, new FluidStack(TinkerSmeltery.moltenGoldFluid, TConstruct.ingotLiquidValue * 2), new ItemStack(ore.getItem(), 1, ore.getItemDamage()), false, 50);
tableCasting.addCastingRecipe(new ItemStack(ore.getItem(), 1, ore.getItemDamage()), new FluidStack(ft.fluid, TConstruct.ingotLiquidValue), pattern, 80);
}
}
public void modIntegration ()
{
/* Natura */
Block taintedSoil = GameRegistry.findBlock("Natura", "soil.tainted");
Block heatSand = GameRegistry.findBlock("Natura", "heatsand");
if (taintedSoil != null && heatSand != null)
GameRegistry.addShapelessRecipe(new ItemStack(TinkerTools.craftedSoil, 2, 6), Items.nether_wart, taintedSoil, heatSand);
ItemStack ingotcast = new ItemStack(TinkerSmeltery.metalPattern, 1, 0);
LiquidCasting tableCasting = TConstructRegistry.instance.getTableCasting();
LiquidCasting basinCasting = TConstructRegistry.instance.getBasinCasting();
/* Thermal Expansion 3 Metals */
ArrayList<ItemStack> ores = OreDictionary.getOres("ingotNickel");
if (ores.size() > 0)
{
tableCasting.addCastingRecipe(ores.get(0), new FluidStack(TinkerSmeltery.moltenNickelFluid, TConstruct.ingotLiquidValue), ingotcast, 80);
}
ores = OreDictionary.getOres("ingotLead");
if (ores.size() > 0)
{
tableCasting.addCastingRecipe(ores.get(0), new FluidStack(TinkerSmeltery.moltenLeadFluid, TConstruct.ingotLiquidValue), ingotcast, 80);
}
ores = OreDictionary.getOres("ingotSilver");
if (ores.size() > 0)
{
tableCasting.addCastingRecipe(ores.get(0), new FluidStack(TinkerSmeltery.moltenSilverFluid, TConstruct.ingotLiquidValue), ingotcast, 80);
}
ores = OreDictionary.getOres("ingotPlatinum");
if (ores.size() > 0)
{
tableCasting.addCastingRecipe(ores.get(0), new FluidStack(TinkerSmeltery.moltenShinyFluid, TConstruct.ingotLiquidValue), ingotcast, 80);
}
ores = OreDictionary.getOres("ingotInvar");
if (ores.size() > 0)
{
tableCasting.addCastingRecipe(ores.get(0), new FluidStack(TinkerSmeltery.moltenInvarFluid, TConstruct.ingotLiquidValue), ingotcast, 80);
Smeltery.addAlloyMixing(new FluidStack(TinkerSmeltery.moltenInvarFluid, TConstruct.ingotLiquidValue * 3), new FluidStack(TinkerSmeltery.moltenIronFluid, TConstruct.ingotLiquidValue * 2),
new FluidStack(TinkerSmeltery.moltenNickelFluid, TConstruct.ingotLiquidValue * 1)); // Invar
}
ores = OreDictionary.getOres("ingotElectrum");
if (ores.size() > 0)
{
tableCasting.addCastingRecipe(ores.get(0), new FluidStack(TinkerSmeltery.moltenElectrumFluid, TConstruct.ingotLiquidValue), ingotcast, 80);
Smeltery.addAlloyMixing(new FluidStack(TinkerSmeltery.moltenElectrumFluid, TConstruct.ingotLiquidValue * 2), new FluidStack(TinkerSmeltery.moltenGoldFluid, TConstruct.ingotLiquidValue),
new FluidStack(TinkerSmeltery.moltenSilverFluid, TConstruct.ingotLiquidValue)); // Electrum
}
ores = OreDictionary.getOres("blockNickel");
if (ores.size() > 0)
{
basinCasting.addCastingRecipe(ores.get(0), new FluidStack(TinkerSmeltery.moltenNickelFluid, TConstruct.blockLiquidValue), null, 100);
}
ores = OreDictionary.getOres("blockLead");
if (ores.size() > 0)
{
basinCasting.addCastingRecipe(ores.get(0), new FluidStack(TinkerSmeltery.moltenLeadFluid, TConstruct.blockLiquidValue), null, 100);
}
ores = OreDictionary.getOres("blockSilver");
if (ores.size() > 0)
{
basinCasting.addCastingRecipe(ores.get(0), new FluidStack(TinkerSmeltery.moltenSilverFluid, TConstruct.blockLiquidValue), null, 100);
}
ores = OreDictionary.getOres("blockPlatinum");
if (ores.size() > 0)
{
basinCasting.addCastingRecipe(ores.get(0), new FluidStack(TinkerSmeltery.moltenShinyFluid, TConstruct.blockLiquidValue), null, 100);
}
ores = OreDictionary.getOres("blockInvar");
if (ores.size() > 0)
{
basinCasting.addCastingRecipe(ores.get(0), new FluidStack(TinkerSmeltery.moltenInvarFluid, TConstruct.blockLiquidValue), null, 100);
}
ores = OreDictionary.getOres("blockElectrum");
if (ores.size() > 0)
{
basinCasting.addCastingRecipe(ores.get(0), new FluidStack(TinkerSmeltery.moltenElectrumFluid, TConstruct.blockLiquidValue), null, 100);
}
/* Extra Utilities */
ores = OreDictionary.getOres("compressedGravel1x");
if (ores.size() > 0)
{
basinCasting.addCastingRecipe(new ItemStack(TinkerSmeltery.speedBlock, 9), new FluidStack(TinkerSmeltery.moltenElectrumFluid, TConstruct.blockLiquidValue), ores.get(0), 100);
}
ores = OreDictionary.getOres("compressedGravel2x"); // Higher won't save
// properly
if (ores.size() > 0)
{
basinCasting.addCastingRecipe(new ItemStack(TinkerSmeltery.speedBlock, 81), new FluidStack(TinkerSmeltery.moltenElectrumFluid, TConstruct.blockLiquidValue * 9), ores.get(0), 100);
}
/* Rubber */
ores = OreDictionary.getOres("itemRubber");
if (ores.size() > 0)
{
FurnaceRecipes.smelting().func_151394_a(new ItemStack(TinkerTools.materials, 1, 36), ores.get(0), 0.2f);
}
}
}
| false | true | public void preInit (FMLPreInitializationEvent event)
{
MinecraftForge.EVENT_BUS.register(new TinkerSmelteryEvents());
TinkerSmeltery.buckets = new FilledBucket(BlockUtils.getBlockFromItem(TinkerSmeltery.buckets));
GameRegistry.registerItem(TinkerSmeltery.buckets, "buckets");
TinkerSmeltery.searedSlab = new SearedSlab().setBlockName("SearedSlab");
TinkerSmeltery.searedSlab.stepSound = Block.soundTypeStone;
TinkerSmeltery.speedSlab = new SpeedSlab().setBlockName("SpeedSlab");
TinkerSmeltery.speedSlab.stepSound = Block.soundTypeStone;
TinkerSmeltery.glueBlock = new GlueBlock().setBlockName("GlueBlock").setCreativeTab(TConstructRegistry.blockTab);
// Smeltery
TinkerSmeltery.smeltery = new SmelteryBlock().setBlockName("Smeltery");
TinkerSmeltery.smelteryNether = new SmelteryBlock("nether").setBlockName("Smeltery");
TinkerSmeltery.lavaTank = new LavaTankBlock().setBlockName("LavaTank");
TinkerSmeltery.lavaTank.setStepSound(Block.soundTypeGlass);
TinkerSmeltery.lavaTankNether = new LavaTankBlock("nether").setStepSound(Block.soundTypeGlass).setBlockName("LavaTank");
TinkerSmeltery.searedBlock = new SearedBlock().setBlockName("SearedBlock");
TinkerSmeltery.searedBlockNether = new SearedBlock("nether").setBlockName("SearedBlock");
TinkerSmeltery.castingChannel = (new CastingChannelBlock()).setBlockName("CastingChannel");
TinkerSmeltery.tankAir = new TankAirBlock(Material.leaves).setBlockUnbreakable().setBlockName("tconstruct.tank.air");
// Liquids
TinkerSmeltery.liquidMetal = new MaterialLiquid(MapColor.tntColor);
TinkerSmeltery.moltenIronFluid = new Fluid("iron.molten");
if (!FluidRegistry.registerFluid(TinkerSmeltery.moltenIronFluid))
TinkerSmeltery.moltenIronFluid = FluidRegistry.getFluid("iron.molten");
TinkerSmeltery.moltenIron = new TConstructFluid(TinkerSmeltery.moltenIronFluid, Material.lava, "liquid_iron").setBlockName("fluid.molten.iron");
GameRegistry.registerBlock(TinkerSmeltery.moltenIron, "fluid.molten.iron");
TinkerSmeltery.moltenIronFluid.setBlock(TinkerSmeltery.moltenIron).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(TinkerSmeltery.moltenIronFluid, 1000), new ItemStack(TinkerSmeltery.buckets, 1, 0), new ItemStack(
Items.bucket)));
TinkerSmeltery.moltenGoldFluid = new Fluid("gold.molten");
if (!FluidRegistry.registerFluid(TinkerSmeltery.moltenGoldFluid))
TinkerSmeltery.moltenGoldFluid = FluidRegistry.getFluid("gold.molten");
TinkerSmeltery.moltenGold = new TConstructFluid(TinkerSmeltery.moltenGoldFluid, Material.lava, "liquid_gold").setBlockName("fluid.molten.gold");
GameRegistry.registerBlock(TinkerSmeltery.moltenGold, "fluid.molten.gold");
TinkerSmeltery.moltenGoldFluid.setBlock(TinkerSmeltery.moltenGold).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(TinkerSmeltery.moltenGoldFluid, 1000), new ItemStack(TinkerSmeltery.buckets, 1, 1), new ItemStack(
Items.bucket)));
TinkerSmeltery.moltenCopperFluid = new Fluid("copper.molten");
if (!FluidRegistry.registerFluid(TinkerSmeltery.moltenCopperFluid))
TinkerSmeltery.moltenCopperFluid = FluidRegistry.getFluid("copper.molten");
TinkerSmeltery.moltenCopper = new TConstructFluid(TinkerSmeltery.moltenCopperFluid, Material.lava, "liquid_copper").setBlockName("fluid.molten.copper");
GameRegistry.registerBlock(TinkerSmeltery.moltenCopper, "fluid.molten.copper");
TinkerSmeltery.moltenCopperFluid.setBlock(TinkerSmeltery.moltenCopper).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(TinkerSmeltery.moltenCopperFluid, 1000), new ItemStack(TinkerSmeltery.buckets, 1, 2), new ItemStack(
Items.bucket)));
TinkerSmeltery.moltenTinFluid = new Fluid("tin.molten");
if (!FluidRegistry.registerFluid(TinkerSmeltery.moltenTinFluid))
TinkerSmeltery.moltenTinFluid = FluidRegistry.getFluid("tin.molten");
TinkerSmeltery.moltenTin = new TConstructFluid(TinkerSmeltery.moltenTinFluid, Material.lava, "liquid_tin").setBlockName("fluid.molten.tin");
GameRegistry.registerBlock(TinkerSmeltery.moltenTin, "fluid.molten.tin");
TinkerSmeltery.moltenTinFluid.setBlock(TinkerSmeltery.moltenTin).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(TinkerSmeltery.moltenTinFluid, 1000), new ItemStack(TinkerSmeltery.buckets, 1, 3), new ItemStack(
Items.bucket)));
TinkerSmeltery.moltenAluminumFluid = new Fluid("aluminum.molten");
if (!FluidRegistry.registerFluid(TinkerSmeltery.moltenAluminumFluid))
TinkerSmeltery.moltenAluminumFluid = FluidRegistry.getFluid("aluminum.molten");
TinkerSmeltery.moltenAluminum = new TConstructFluid(TinkerSmeltery.moltenAluminumFluid, Material.lava, "liquid_aluminum").setBlockName("fluid.molten.aluminum");
GameRegistry.registerBlock(TinkerSmeltery.moltenAluminum, "fluid.molten.aluminum");
TinkerSmeltery.moltenAluminumFluid.setBlock(TinkerSmeltery.moltenAluminum).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(TinkerSmeltery.moltenAluminumFluid, 1000), new ItemStack(TinkerSmeltery.buckets, 1, 4), new ItemStack(
Items.bucket)));
TinkerSmeltery.moltenCobaltFluid = new Fluid("cobalt.molten");
if (!FluidRegistry.registerFluid(TinkerSmeltery.moltenCobaltFluid))
TinkerSmeltery.moltenCobaltFluid = FluidRegistry.getFluid("cobalt.molten");
TinkerSmeltery.moltenCobalt = new TConstructFluid(TinkerSmeltery.moltenCobaltFluid, Material.lava, "liquid_cobalt").setBlockName("fluid.molten.cobalt");
GameRegistry.registerBlock(TinkerSmeltery.moltenCobalt, "fluid.molten.cobalt");
TinkerSmeltery.moltenCobaltFluid.setBlock(TinkerSmeltery.moltenCobalt).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(TinkerSmeltery.moltenCobaltFluid, 1000), new ItemStack(TinkerSmeltery.buckets, 1, 5), new ItemStack(
Items.bucket)));
TinkerSmeltery.moltenArditeFluid = new Fluid("ardite.molten");
if (!FluidRegistry.registerFluid(TinkerSmeltery.moltenArditeFluid))
TinkerSmeltery.moltenArditeFluid = FluidRegistry.getFluid("ardite.molten");
TinkerSmeltery.moltenArdite = new TConstructFluid(TinkerSmeltery.moltenArditeFluid, Material.lava, "liquid_ardite").setBlockName("fluid.molten.ardite");
GameRegistry.registerBlock(TinkerSmeltery.moltenArdite, "fluid.molten.ardite");
TinkerSmeltery.moltenArditeFluid.setBlock(TinkerSmeltery.moltenArdite).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(TinkerSmeltery.moltenArditeFluid, 1000), new ItemStack(TinkerSmeltery.buckets, 1, 6), new ItemStack(
Items.bucket)));
TinkerSmeltery.moltenBronzeFluid = new Fluid("bronze.molten");
if (!FluidRegistry.registerFluid(TinkerSmeltery.moltenBronzeFluid))
TinkerSmeltery.moltenBronzeFluid = FluidRegistry.getFluid("bronze.molten");
TinkerSmeltery.moltenBronze = new TConstructFluid(TinkerSmeltery.moltenBronzeFluid, Material.lava, "liquid_bronze").setBlockName("fluid.molten.bronze");
GameRegistry.registerBlock(TinkerSmeltery.moltenBronze, "fluid.molten.bronze");
TinkerSmeltery.moltenBronzeFluid.setBlock(TinkerSmeltery.moltenBronze).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(TinkerSmeltery.moltenBronzeFluid, 1000), new ItemStack(TinkerSmeltery.buckets, 1, 7), new ItemStack(
Items.bucket)));
TinkerSmeltery.moltenAlubrassFluid = new Fluid("aluminumbrass.molten");
if (!FluidRegistry.registerFluid(TinkerSmeltery.moltenAlubrassFluid))
TinkerSmeltery.moltenAlubrassFluid = FluidRegistry.getFluid("aluminumbrass.molten");
TinkerSmeltery.moltenAlubrass = new TConstructFluid(TinkerSmeltery.moltenAlubrassFluid, Material.lava, "liquid_alubrass").setBlockName("fluid.molten.alubrass");
GameRegistry.registerBlock(TinkerSmeltery.moltenAlubrass, "fluid.molten.alubrass");
TinkerSmeltery.moltenAlubrassFluid.setBlock(TinkerSmeltery.moltenAlubrass).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(TinkerSmeltery.moltenAlubrassFluid, 1000), new ItemStack(TinkerSmeltery.buckets, 1, 8), new ItemStack(
Items.bucket)));
TinkerSmeltery.moltenManyullynFluid = new Fluid("manyullyn.molten");
if (!FluidRegistry.registerFluid(TinkerSmeltery.moltenManyullynFluid))
TinkerSmeltery.moltenManyullynFluid = FluidRegistry.getFluid("manyullyn.molten");
TinkerSmeltery.moltenManyullyn = new TConstructFluid(TinkerSmeltery.moltenManyullynFluid, Material.lava, "liquid_manyullyn").setBlockName("fluid.molten.manyullyn");
GameRegistry.registerBlock(TinkerSmeltery.moltenManyullyn, "fluid.molten.manyullyn");
TinkerSmeltery.moltenManyullynFluid.setBlock(TinkerSmeltery.moltenManyullyn).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(TinkerSmeltery.moltenManyullynFluid, 1000), new ItemStack(TinkerSmeltery.buckets, 1, 9), new ItemStack(
Items.bucket)));
TinkerSmeltery.moltenAlumiteFluid = new Fluid("alumite.molten");
if (!FluidRegistry.registerFluid(TinkerSmeltery.moltenAlumiteFluid))
TinkerSmeltery.moltenAlumiteFluid = FluidRegistry.getFluid("alumite.molten");
TinkerSmeltery.moltenAlumite = new TConstructFluid(TinkerSmeltery.moltenAlumiteFluid, Material.lava, "liquid_alumite").setBlockName("fluid.molten.alumite");
GameRegistry.registerBlock(TinkerSmeltery.moltenAlumite, "fluid.molten.alumite");
TinkerSmeltery.moltenAlumiteFluid.setBlock(TinkerSmeltery.moltenAlumite).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(TinkerSmeltery.moltenAlumiteFluid, 1000), new ItemStack(TinkerSmeltery.buckets, 1, 10), new ItemStack(
Items.bucket)));
TinkerSmeltery.moltenObsidianFluid = new Fluid("obsidian.molten");
if (!FluidRegistry.registerFluid(TinkerSmeltery.moltenObsidianFluid))
TinkerSmeltery.moltenObsidianFluid = FluidRegistry.getFluid("obsidian.molten");
TinkerSmeltery.moltenObsidian = new TConstructFluid(TinkerSmeltery.moltenObsidianFluid, Material.lava, "liquid_obsidian").setBlockName("fluid.molten.obsidian");
GameRegistry.registerBlock(TinkerSmeltery.moltenObsidian, "fluid.molten.obsidian");
TinkerSmeltery.moltenObsidianFluid.setBlock(TinkerSmeltery.moltenObsidian).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(TinkerSmeltery.moltenObsidianFluid, 1000), new ItemStack(TinkerSmeltery.buckets, 1, 11), new ItemStack(
Items.bucket)));
TinkerSmeltery.moltenSteelFluid = new Fluid("steel.molten");
if (!FluidRegistry.registerFluid(TinkerSmeltery.moltenSteelFluid))
TinkerSmeltery.moltenSteelFluid = FluidRegistry.getFluid("steel.molten");
TinkerSmeltery.moltenSteel = new TConstructFluid(TinkerSmeltery.moltenSteelFluid, Material.lava, "liquid_steel").setBlockName("fluid.molten.steel");
GameRegistry.registerBlock(TinkerSmeltery.moltenSteel, "fluid.molten.steel");
TinkerSmeltery.moltenSteelFluid.setBlock(TinkerSmeltery.moltenSteel).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(TinkerSmeltery.moltenSteelFluid, 1000), new ItemStack(TinkerSmeltery.buckets, 1, 12), new ItemStack(
Items.bucket)));
TinkerSmeltery.moltenGlassFluid = new Fluid("glass.molten");
if (!FluidRegistry.registerFluid(TinkerSmeltery.moltenGlassFluid))
TinkerSmeltery.moltenGlassFluid = FluidRegistry.getFluid("glass.molten");
TinkerSmeltery.moltenGlass = new TConstructFluid(TinkerSmeltery.moltenGlassFluid, Material.lava, "liquid_glass", true).setBlockName("fluid.molten.glass");
GameRegistry.registerBlock(TinkerSmeltery.moltenGlass, "fluid.molten.glass");
TinkerSmeltery.moltenGlassFluid.setBlock(TinkerSmeltery.moltenGlass).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(TinkerSmeltery.moltenGlassFluid, 1000), new ItemStack(TinkerSmeltery.buckets, 1, 13), new ItemStack(
Items.bucket)));
TinkerSmeltery.moltenStoneFluid = new Fluid("stone.seared");
if (!FluidRegistry.registerFluid(TinkerSmeltery.moltenStoneFluid))
TinkerSmeltery.moltenStoneFluid = FluidRegistry.getFluid("stone.seared");
TinkerSmeltery.moltenStone = new TConstructFluid(TinkerSmeltery.moltenStoneFluid, Material.lava, "liquid_stone").setBlockName("molten.stone");
GameRegistry.registerBlock(TinkerSmeltery.moltenStone, "molten.stone");
TinkerSmeltery.moltenStoneFluid.setBlock(TinkerSmeltery.moltenStone).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(TinkerSmeltery.moltenStoneFluid, 1000), new ItemStack(TinkerSmeltery.buckets, 1, 14), new ItemStack(
Items.bucket)));
TinkerSmeltery.moltenEmeraldFluid = new Fluid("emerald.liquid");
if (!FluidRegistry.registerFluid(TinkerSmeltery.moltenEmeraldFluid))
TinkerSmeltery.moltenEmeraldFluid = FluidRegistry.getFluid("emerald.liquid");
TinkerSmeltery.moltenEmerald = new TConstructFluid(TinkerSmeltery.moltenEmeraldFluid, Material.water, "liquid_villager").setBlockName("molten.emerald");
GameRegistry.registerBlock(TinkerSmeltery.moltenEmerald, "molten.emerald");
TinkerSmeltery.moltenEmeraldFluid.setBlock(TinkerSmeltery.moltenEmerald).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(TinkerSmeltery.moltenEmeraldFluid, 1000), new ItemStack(TinkerSmeltery.buckets, 1, 15), new ItemStack(
Items.bucket)));
TinkerSmeltery.bloodFluid = new Fluid("blood");
if (!FluidRegistry.registerFluid(TinkerSmeltery.bloodFluid))
TinkerSmeltery.bloodFluid = FluidRegistry.getFluid("blood");
TinkerSmeltery.blood = new BloodBlock(TinkerSmeltery.bloodFluid, Material.water, "liquid_cow").setBlockName("liquid.blood");
GameRegistry.registerBlock(TinkerSmeltery.blood, "liquid.blood");
TinkerSmeltery.bloodFluid.setBlock(TinkerSmeltery.blood).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry
.registerFluidContainer(new FluidContainerData(new FluidStack(TinkerSmeltery.bloodFluid, 1000), new ItemStack(TinkerSmeltery.buckets, 1, 16), new ItemStack(Items.bucket)));
TinkerSmeltery.moltenNickelFluid = new Fluid("nickel.molten");
if (!FluidRegistry.registerFluid(TinkerSmeltery.moltenNickelFluid))
TinkerSmeltery.moltenNickelFluid = FluidRegistry.getFluid("nickel.molten");
TinkerSmeltery.moltenNickel = new TConstructFluid(TinkerSmeltery.moltenNickelFluid, Material.lava, "liquid_ferrous").setBlockName("fluid.molten.nickel");
GameRegistry.registerBlock(TinkerSmeltery.moltenNickel, "fluid.molten.nickel");
TinkerSmeltery.moltenNickelFluid.setBlock(TinkerSmeltery.moltenNickel).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(TinkerSmeltery.moltenNickelFluid, 1000), new ItemStack(TinkerSmeltery.buckets, 1, 17), new ItemStack(
Items.bucket)));
TinkerSmeltery.moltenLeadFluid = new Fluid("lead.molten");
if (!FluidRegistry.registerFluid(TinkerSmeltery.moltenLeadFluid))
TinkerSmeltery.moltenLeadFluid = FluidRegistry.getFluid("lead.molten");
TinkerSmeltery.moltenLead = new TConstructFluid(TinkerSmeltery.moltenLeadFluid, Material.lava, "liquid_lead").setBlockName("fluid.molten.lead");
GameRegistry.registerBlock(TinkerSmeltery.moltenLead, "fluid.molten.lead");
TinkerSmeltery.moltenLeadFluid.setBlock(TinkerSmeltery.moltenLead).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(TinkerSmeltery.moltenLeadFluid, 1000), new ItemStack(TinkerSmeltery.buckets, 1, 18), new ItemStack(
Items.bucket)));
TinkerSmeltery.moltenSilverFluid = new Fluid("silver.molten");
if (!FluidRegistry.registerFluid(TinkerSmeltery.moltenSilverFluid))
TinkerSmeltery.moltenSilverFluid = FluidRegistry.getFluid("silver.molten");
TinkerSmeltery.moltenSilver = new TConstructFluid(TinkerSmeltery.moltenSilverFluid, Material.lava, "liquid_silver").setBlockName("fluid.molten.silver");
GameRegistry.registerBlock(TinkerSmeltery.moltenSilver, "fluid.molten.silver");
TinkerSmeltery.moltenSilverFluid.setBlock(TinkerSmeltery.moltenSilver).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(TinkerSmeltery.moltenSilverFluid, 1000), new ItemStack(TinkerSmeltery.buckets, 1, 19), new ItemStack(
Items.bucket)));
TinkerSmeltery.moltenShinyFluid = new Fluid("platinum.molten");
if (!FluidRegistry.registerFluid(TinkerSmeltery.moltenShinyFluid))
TinkerSmeltery.moltenShinyFluid = FluidRegistry.getFluid("platinum.molten");
TinkerSmeltery.moltenShiny = new TConstructFluid(TinkerSmeltery.moltenShinyFluid, Material.lava, "liquid_shiny").setBlockName("fluid.molten.shiny");
GameRegistry.registerBlock(TinkerSmeltery.moltenShiny, "fluid.molten.shiny");
TinkerSmeltery.moltenShinyFluid.setBlock(TinkerSmeltery.moltenShiny).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(TinkerSmeltery.moltenShinyFluid, 1000), new ItemStack(TinkerSmeltery.buckets, 1, 20), new ItemStack(
Items.bucket)));
TinkerSmeltery.moltenInvarFluid = new Fluid("invar.molten");
if (!FluidRegistry.registerFluid(TinkerSmeltery.moltenInvarFluid))
TinkerSmeltery.moltenInvarFluid = FluidRegistry.getFluid("invar.molten");
TinkerSmeltery.moltenInvar = new TConstructFluid(TinkerSmeltery.moltenInvarFluid, Material.lava, "liquid_invar").setBlockName("fluid.molten.invar");
GameRegistry.registerBlock(TinkerSmeltery.moltenInvar, "fluid.molten.invar");
TinkerSmeltery.moltenInvarFluid.setBlock(TinkerSmeltery.moltenInvar).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(TinkerSmeltery.moltenInvarFluid, 1000), new ItemStack(TinkerSmeltery.buckets, 1, 21), new ItemStack(
Items.bucket)));
TinkerSmeltery.moltenElectrumFluid = new Fluid("electrum.molten");
if (!FluidRegistry.registerFluid(TinkerSmeltery.moltenElectrumFluid))
TinkerSmeltery.moltenElectrumFluid = FluidRegistry.getFluid("electrum.molten");
TinkerSmeltery.moltenElectrum = new TConstructFluid(TinkerSmeltery.moltenElectrumFluid, Material.lava, "liquid_electrum").setBlockName("fluid.molten.electrum");
GameRegistry.registerBlock(TinkerSmeltery.moltenElectrum, "fluid.molten.electrum");
TinkerSmeltery.moltenElectrumFluid.setBlock(TinkerSmeltery.moltenElectrum).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(TinkerSmeltery.moltenElectrumFluid, 1000), new ItemStack(TinkerSmeltery.buckets, 1, 22), new ItemStack(
Items.bucket)));
TinkerSmeltery.moltenEnderFluid = new Fluid("ender");
if (!FluidRegistry.registerFluid(TinkerSmeltery.moltenEnderFluid))
{
TinkerSmeltery.moltenEnderFluid = FluidRegistry.getFluid("ender");
TinkerSmeltery.moltenEnder = TinkerSmeltery.moltenEnderFluid.getBlock();
if (TinkerSmeltery.moltenEnder == null)
TConstruct.logger.info("Molten ender block missing!");
}
else
{
TinkerSmeltery.moltenEnder = new TConstructFluid(TinkerSmeltery.moltenEnderFluid, Material.water, "liquid_ender").setBlockName("fluid.ender");
GameRegistry.registerBlock(TinkerSmeltery.moltenEnder, "fluid.ender");
TinkerSmeltery.moltenEnderFluid.setBlock(TinkerSmeltery.moltenEnder).setDensity(3000).setViscosity(6000);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(TinkerSmeltery.moltenEnderFluid, 1000), new ItemStack(TinkerSmeltery.buckets, 1, 23), new ItemStack(
Items.bucket)));
}
// Glue
TinkerSmeltery.glueFluid = new Fluid("glue").setDensity(6000).setViscosity(6000).setTemperature(200);
if (!FluidRegistry.registerFluid(TinkerSmeltery.glueFluid))
TinkerSmeltery.glueFluid = FluidRegistry.getFluid("glue");
TinkerSmeltery.glueFluidBlock = new GlueFluid(TinkerSmeltery.glueFluid, Material.water).setCreativeTab(TConstructRegistry.blockTab).setStepSound(TinkerWorld.slimeStep)
.setBlockName("liquid.glue");
GameRegistry.registerBlock(TinkerSmeltery.glueFluidBlock, "liquid.glue");
TinkerSmeltery.glueFluid.setBlock(TinkerSmeltery.glueFluidBlock);
FluidContainerRegistry
.registerFluidContainer(new FluidContainerData(new FluidStack(TinkerSmeltery.glueFluid, 1000), new ItemStack(TinkerSmeltery.buckets, 1, 25), new ItemStack(Items.bucket)));
TinkerSmeltery.pigIronFluid = new Fluid("pigiron.molten");
if (!FluidRegistry.registerFluid(TinkerSmeltery.pigIronFluid))
TinkerSmeltery.pigIronFluid = FluidRegistry.getFluid("pigiron.molten");
else
TinkerSmeltery.pigIronFluid.setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(TinkerSmeltery.pigIronFluid, 1000), new ItemStack(TinkerSmeltery.buckets, 1, 26), new ItemStack(
Items.bucket)));
TinkerSmeltery.fluids = new Fluid[] { TinkerSmeltery.moltenIronFluid, TinkerSmeltery.moltenGoldFluid, TinkerSmeltery.moltenCopperFluid, TinkerSmeltery.moltenTinFluid,
TinkerSmeltery.moltenAluminumFluid, TinkerSmeltery.moltenCobaltFluid, TinkerSmeltery.moltenArditeFluid, TinkerSmeltery.moltenBronzeFluid, TinkerSmeltery.moltenAlubrassFluid,
TinkerSmeltery.moltenManyullynFluid, TinkerSmeltery.moltenAlumiteFluid, TinkerSmeltery.moltenObsidianFluid, TinkerSmeltery.moltenSteelFluid, TinkerSmeltery.moltenGlassFluid,
TinkerSmeltery.moltenStoneFluid, TinkerSmeltery.moltenEmeraldFluid, TinkerSmeltery.bloodFluid, TinkerSmeltery.moltenNickelFluid, TinkerSmeltery.moltenLeadFluid,
TinkerSmeltery.moltenSilverFluid, TinkerSmeltery.moltenShinyFluid, TinkerSmeltery.moltenInvarFluid, TinkerSmeltery.moltenElectrumFluid, TinkerSmeltery.moltenEnderFluid,
TinkerSmeltery.glueFluid, TinkerSmeltery.pigIronFluid };
TinkerSmeltery.fluidBlocks = new Block[] { TinkerSmeltery.moltenIron, TinkerSmeltery.moltenGold, TinkerSmeltery.moltenCopper, TinkerSmeltery.moltenTin, TinkerSmeltery.moltenAluminum,
TinkerSmeltery.moltenCobalt, TinkerSmeltery.moltenArdite, TinkerSmeltery.moltenBronze, TinkerSmeltery.moltenAlubrass, TinkerSmeltery.moltenManyullyn, TinkerSmeltery.moltenAlumite,
TinkerSmeltery.moltenObsidian, TinkerSmeltery.moltenSteel, TinkerSmeltery.moltenGlass, TinkerSmeltery.moltenStone, TinkerSmeltery.moltenEmerald, TinkerSmeltery.blood,
TinkerSmeltery.moltenNickel, TinkerSmeltery.moltenLead, TinkerSmeltery.moltenSilver, TinkerSmeltery.moltenShiny, TinkerSmeltery.moltenInvar, TinkerSmeltery.moltenElectrum,
TinkerSmeltery.moltenEnder, TinkerSmeltery.glueFluidBlock };
FluidType.registerFluidType("Water", Blocks.snow, 0, 20, FluidRegistry.getFluid("water"), false);
FluidType.registerFluidType("Iron", Blocks.iron_block, 0, 600, TinkerSmeltery.moltenIronFluid, true);
FluidType.registerFluidType("Gold", Blocks.gold_block, 0, 400, TinkerSmeltery.moltenGoldFluid, false);
FluidType.registerFluidType("Tin", TinkerWorld.metalBlock, 5, 400, TinkerSmeltery.moltenTinFluid, false);
FluidType.registerFluidType("Copper", TinkerWorld.metalBlock, 3, 550, TinkerSmeltery.moltenCopperFluid, true);
FluidType.registerFluidType("Aluminum", TinkerWorld.metalBlock, 6, 350, TinkerSmeltery.moltenAluminumFluid, false);
FluidType.registerFluidType("NaturalAluminum", TinkerWorld.oreSlag, 6, 350, TinkerSmeltery.moltenAluminumFluid, false);
FluidType.registerFluidType("Cobalt", TinkerWorld.metalBlock, 0, 650, TinkerSmeltery.moltenCobaltFluid, true);
FluidType.registerFluidType("Ardite", TinkerWorld.metalBlock, 1, 650, TinkerSmeltery.moltenArditeFluid, true);
FluidType.registerFluidType("AluminumBrass", TinkerWorld.metalBlock, 7, 350, TinkerSmeltery.moltenAlubrassFluid, false);
FluidType.registerFluidType("Alumite", TinkerWorld.metalBlock, 8, 800, TinkerSmeltery.moltenAlumiteFluid, true);
FluidType.registerFluidType("Manyullyn", TinkerWorld.metalBlock, 2, 750, TinkerSmeltery.moltenManyullynFluid, true);
FluidType.registerFluidType("Bronze", TinkerWorld.metalBlock, 4, 500, TinkerSmeltery.moltenBronzeFluid, true);
FluidType.registerFluidType("Steel", TinkerWorld.metalBlock, 9, 700, TinkerSmeltery.moltenSteelFluid, true);
FluidType.registerFluidType("Nickel", TinkerWorld.metalBlock, 0, 400, TinkerSmeltery.moltenNickelFluid, false);
FluidType.registerFluidType("Lead", TinkerWorld.metalBlock, 0, 400, TinkerSmeltery.moltenLeadFluid, false);
FluidType.registerFluidType("Silver", TinkerWorld.metalBlock, 0, 400, TinkerSmeltery.moltenSilverFluid, false);
FluidType.registerFluidType("Platinum", TinkerWorld.metalBlock, 0, 400, TinkerSmeltery.moltenShinyFluid, false);
FluidType.registerFluidType("Invar", TinkerWorld.metalBlock, 0, 400, TinkerSmeltery.moltenInvarFluid, false);
FluidType.registerFluidType("Electrum", TinkerWorld.metalBlock, 0, 400, TinkerSmeltery.moltenElectrumFluid, false);
FluidType.registerFluidType("Obsidian", Blocks.obsidian, 0, 750, TinkerSmeltery.moltenObsidianFluid, true);
FluidType.registerFluidType("Ender", TinkerWorld.metalBlock, 10, 500, TinkerSmeltery.moltenEnderFluid, false);
FluidType.registerFluidType("Glass", Blocks.sand, 0, 625, TinkerSmeltery.moltenGlassFluid, false);
FluidType.registerFluidType("Stone", Blocks.stone, 0, 800, TinkerSmeltery.moltenStoneFluid, true);
FluidType.registerFluidType("Emerald", Blocks.emerald_block, 0, 575, TinkerSmeltery.moltenEmeraldFluid, false);
FluidType.registerFluidType("PigIron", TinkerWorld.meatBlock, 0, 610, TinkerSmeltery.pigIronFluid, true);
FluidType.registerFluidType("Glue", TinkerSmeltery.glueBlock, 0, 125, TinkerSmeltery.glueFluid, false);
TinkerSmeltery.speedBlock = new SpeedBlock().setBlockName("SpeedBlock");
// Glass
TinkerSmeltery.clearGlass = new GlassBlockConnected("clear", false).setBlockName("GlassBlock");
TinkerSmeltery.clearGlass.stepSound = Block.soundTypeGlass;
TinkerSmeltery.glassPane = new GlassPaneConnected("clear", false);
TinkerSmeltery.stainedGlassClear = new GlassBlockConnectedMeta("stained", true, "white", "orange", "magenta", "light_blue", "yellow", "lime", "pink", "gray", "light_gray", "cyan", "purple",
"blue", "brown", "green", "red", "black").setBlockName("GlassBlock.StainedClear");
TinkerSmeltery.stainedGlassClear.stepSound = Block.soundTypeGlass;
TinkerSmeltery.stainedGlassClearPane = new GlassPaneStained();
GameRegistry.registerBlock(TinkerSmeltery.searedSlab, SearedSlabItem.class, "SearedSlab");
GameRegistry.registerBlock(TinkerSmeltery.speedSlab, SpeedSlabItem.class, "SpeedSlab");
GameRegistry.registerBlock(TinkerSmeltery.glueBlock, "GlueBlock");
OreDictionary.registerOre("blockRubber", new ItemStack(TinkerSmeltery.glueBlock));
// Smeltery stuff
GameRegistry.registerBlock(TinkerSmeltery.smeltery, SmelteryItemBlock.class, "Smeltery");
GameRegistry.registerBlock(TinkerSmeltery.smelteryNether, SmelteryItemBlock.class, "SmelteryNether");
if (PHConstruct.newSmeltery)
{
GameRegistry.registerTileEntity(AdaptiveSmelteryLogic.class, "TConstruct.Smeltery");
GameRegistry.registerTileEntity(AdaptiveDrainLogic.class, "TConstruct.SmelteryDrain");
}
else
{
GameRegistry.registerTileEntity(SmelteryLogic.class, "TConstruct.Smeltery");
GameRegistry.registerTileEntity(SmelteryDrainLogic.class, "TConstruct.SmelteryDrain");
}
GameRegistry.registerTileEntity(MultiServantLogic.class, "TConstruct.Servants");
GameRegistry.registerBlock(TinkerSmeltery.lavaTank, LavaTankItemBlock.class, "LavaTank");
GameRegistry.registerBlock(TinkerSmeltery.lavaTankNether, LavaTankItemBlock.class, "LavaTankNether");
GameRegistry.registerTileEntity(LavaTankLogic.class, "TConstruct.LavaTank");
GameRegistry.registerBlock(TinkerSmeltery.searedBlock, SearedTableItemBlock.class, "SearedBlock");
GameRegistry.registerBlock(TinkerSmeltery.searedBlockNether, SearedTableItemBlock.class, "SearedBlockNether");
GameRegistry.registerTileEntity(CastingTableLogic.class, "CastingTable");
GameRegistry.registerTileEntity(FaucetLogic.class, "Faucet");
GameRegistry.registerTileEntity(CastingBasinLogic.class, "CastingBasin");
GameRegistry.registerBlock(TinkerSmeltery.castingChannel, CastingChannelItem.class, "CastingChannel");
GameRegistry.registerTileEntity(CastingChannelLogic.class, "CastingChannel");
GameRegistry.registerBlock(TinkerSmeltery.tankAir, "TankAir");
GameRegistry.registerTileEntity(TankAirLogic.class, "tconstruct.tank.air");
GameRegistry.registerBlock(TinkerSmeltery.speedBlock, SpeedBlockItem.class, "SpeedBlock");
// Glass
GameRegistry.registerBlock(TinkerSmeltery.clearGlass, GlassBlockItem.class, "GlassBlock");
GameRegistry.registerBlock(TinkerSmeltery.glassPane, GlassPaneItem.class, "GlassPane");
GameRegistry.registerBlock(TinkerSmeltery.stainedGlassClear, StainedGlassClearItem.class, "GlassBlock.StainedClear");
GameRegistry.registerBlock(TinkerSmeltery.stainedGlassClearPane, StainedGlassClearPaneItem.class, "GlassPaneClearStained");
//Items
TinkerSmeltery.metalPattern = new MetalPattern("cast_", "materials/").setUnlocalizedName("tconstruct.MetalPattern");
GameRegistry.registerItem(TinkerSmeltery.metalPattern, "metalPattern");
TConstructRegistry.addItemToDirectory("metalPattern", TinkerSmeltery.metalPattern);
String[] patternTypes = { "ingot", "toolRod", "pickaxeHead", "shovelHead", "hatchetHead", "swordBlade", "wideGuard", "handGuard", "crossbar", "binding", "frypanHead", "signHead",
"knifeBlade", "chiselHead", "toughRod", "toughBinding", "largePlate", "broadAxeHead", "scytheHead", "excavatorHead", "largeBlade", "hammerHead", "fullGuard" };
for (int i = 0; i < patternTypes.length; i++)
{
TConstructRegistry.addItemStackToDirectory(patternTypes[i] + "Cast", new ItemStack(TinkerSmeltery.metalPattern, 1, i));
}
}
| public void preInit (FMLPreInitializationEvent event)
{
MinecraftForge.EVENT_BUS.register(new TinkerSmelteryEvents());
TinkerSmeltery.buckets = new FilledBucket(BlockUtils.getBlockFromItem(TinkerSmeltery.buckets));
GameRegistry.registerItem(TinkerSmeltery.buckets, "buckets");
TinkerSmeltery.searedSlab = new SearedSlab().setBlockName("SearedSlab");
TinkerSmeltery.searedSlab.stepSound = Block.soundTypeStone;
TinkerSmeltery.speedSlab = new SpeedSlab().setBlockName("SpeedSlab");
TinkerSmeltery.speedSlab.stepSound = Block.soundTypeStone;
TinkerSmeltery.glueBlock = new GlueBlock().setBlockName("GlueBlock").setCreativeTab(TConstructRegistry.blockTab);
// Smeltery
TinkerSmeltery.smeltery = new SmelteryBlock().setBlockName("Smeltery");
TinkerSmeltery.smelteryNether = new SmelteryBlock("nether").setBlockName("Smeltery");
TinkerSmeltery.lavaTank = new LavaTankBlock().setBlockName("LavaTank");
TinkerSmeltery.lavaTank.setStepSound(Block.soundTypeGlass);
TinkerSmeltery.lavaTankNether = new LavaTankBlock("nether").setStepSound(Block.soundTypeGlass).setBlockName("LavaTank");
TinkerSmeltery.searedBlock = new SearedBlock().setBlockName("SearedBlock");
TinkerSmeltery.searedBlockNether = new SearedBlock("nether").setBlockName("SearedBlock");
TinkerSmeltery.castingChannel = (new CastingChannelBlock()).setBlockName("CastingChannel");
TinkerSmeltery.tankAir = new TankAirBlock(Material.leaves).setBlockUnbreakable().setBlockName("tconstruct.tank.air");
// Liquids
TinkerSmeltery.liquidMetal = new MaterialLiquid(MapColor.tntColor);
TinkerSmeltery.moltenIronFluid = new Fluid("iron.molten");
if (!FluidRegistry.registerFluid(TinkerSmeltery.moltenIronFluid))
TinkerSmeltery.moltenIronFluid = FluidRegistry.getFluid("iron.molten");
TinkerSmeltery.moltenIron = new TConstructFluid(TinkerSmeltery.moltenIronFluid, Material.lava, "liquid_iron").setBlockName("fluid.molten.iron");
GameRegistry.registerBlock(TinkerSmeltery.moltenIron, "fluid.molten.iron");
TinkerSmeltery.moltenIronFluid.setBlock(TinkerSmeltery.moltenIron).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(TinkerSmeltery.moltenIronFluid, 1000), new ItemStack(TinkerSmeltery.buckets, 1, 0), new ItemStack(
Items.bucket)));
TinkerSmeltery.moltenGoldFluid = new Fluid("gold.molten");
if (!FluidRegistry.registerFluid(TinkerSmeltery.moltenGoldFluid))
TinkerSmeltery.moltenGoldFluid = FluidRegistry.getFluid("gold.molten");
TinkerSmeltery.moltenGold = new TConstructFluid(TinkerSmeltery.moltenGoldFluid, Material.lava, "liquid_gold").setBlockName("fluid.molten.gold");
GameRegistry.registerBlock(TinkerSmeltery.moltenGold, "fluid.molten.gold");
TinkerSmeltery.moltenGoldFluid.setBlock(TinkerSmeltery.moltenGold).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(TinkerSmeltery.moltenGoldFluid, 1000), new ItemStack(TinkerSmeltery.buckets, 1, 1), new ItemStack(
Items.bucket)));
TinkerSmeltery.moltenCopperFluid = new Fluid("copper.molten");
if (!FluidRegistry.registerFluid(TinkerSmeltery.moltenCopperFluid))
TinkerSmeltery.moltenCopperFluid = FluidRegistry.getFluid("copper.molten");
TinkerSmeltery.moltenCopper = new TConstructFluid(TinkerSmeltery.moltenCopperFluid, Material.lava, "liquid_copper").setBlockName("fluid.molten.copper");
GameRegistry.registerBlock(TinkerSmeltery.moltenCopper, "fluid.molten.copper");
TinkerSmeltery.moltenCopperFluid.setBlock(TinkerSmeltery.moltenCopper).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(TinkerSmeltery.moltenCopperFluid, 1000), new ItemStack(TinkerSmeltery.buckets, 1, 2), new ItemStack(
Items.bucket)));
TinkerSmeltery.moltenTinFluid = new Fluid("tin.molten");
if (!FluidRegistry.registerFluid(TinkerSmeltery.moltenTinFluid))
TinkerSmeltery.moltenTinFluid = FluidRegistry.getFluid("tin.molten");
TinkerSmeltery.moltenTin = new TConstructFluid(TinkerSmeltery.moltenTinFluid, Material.lava, "liquid_tin").setBlockName("fluid.molten.tin");
GameRegistry.registerBlock(TinkerSmeltery.moltenTin, "fluid.molten.tin");
TinkerSmeltery.moltenTinFluid.setBlock(TinkerSmeltery.moltenTin).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(TinkerSmeltery.moltenTinFluid, 1000), new ItemStack(TinkerSmeltery.buckets, 1, 3), new ItemStack(
Items.bucket)));
TinkerSmeltery.moltenAluminumFluid = new Fluid("aluminum.molten");
if (!FluidRegistry.registerFluid(TinkerSmeltery.moltenAluminumFluid))
TinkerSmeltery.moltenAluminumFluid = FluidRegistry.getFluid("aluminum.molten");
TinkerSmeltery.moltenAluminum = new TConstructFluid(TinkerSmeltery.moltenAluminumFluid, Material.lava, "liquid_aluminum").setBlockName("fluid.molten.aluminum");
GameRegistry.registerBlock(TinkerSmeltery.moltenAluminum, "fluid.molten.aluminum");
TinkerSmeltery.moltenAluminumFluid.setBlock(TinkerSmeltery.moltenAluminum).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(TinkerSmeltery.moltenAluminumFluid, 1000), new ItemStack(TinkerSmeltery.buckets, 1, 4), new ItemStack(
Items.bucket)));
TinkerSmeltery.moltenCobaltFluid = new Fluid("cobalt.molten");
if (!FluidRegistry.registerFluid(TinkerSmeltery.moltenCobaltFluid))
TinkerSmeltery.moltenCobaltFluid = FluidRegistry.getFluid("cobalt.molten");
TinkerSmeltery.moltenCobalt = new TConstructFluid(TinkerSmeltery.moltenCobaltFluid, Material.lava, "liquid_cobalt").setBlockName("fluid.molten.cobalt");
GameRegistry.registerBlock(TinkerSmeltery.moltenCobalt, "fluid.molten.cobalt");
TinkerSmeltery.moltenCobaltFluid.setBlock(TinkerSmeltery.moltenCobalt).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(TinkerSmeltery.moltenCobaltFluid, 1000), new ItemStack(TinkerSmeltery.buckets, 1, 5), new ItemStack(
Items.bucket)));
TinkerSmeltery.moltenArditeFluid = new Fluid("ardite.molten");
if (!FluidRegistry.registerFluid(TinkerSmeltery.moltenArditeFluid))
TinkerSmeltery.moltenArditeFluid = FluidRegistry.getFluid("ardite.molten");
TinkerSmeltery.moltenArdite = new TConstructFluid(TinkerSmeltery.moltenArditeFluid, Material.lava, "liquid_ardite").setBlockName("fluid.molten.ardite");
GameRegistry.registerBlock(TinkerSmeltery.moltenArdite, "fluid.molten.ardite");
TinkerSmeltery.moltenArditeFluid.setBlock(TinkerSmeltery.moltenArdite).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(TinkerSmeltery.moltenArditeFluid, 1000), new ItemStack(TinkerSmeltery.buckets, 1, 6), new ItemStack(
Items.bucket)));
TinkerSmeltery.moltenBronzeFluid = new Fluid("bronze.molten");
if (!FluidRegistry.registerFluid(TinkerSmeltery.moltenBronzeFluid))
TinkerSmeltery.moltenBronzeFluid = FluidRegistry.getFluid("bronze.molten");
TinkerSmeltery.moltenBronze = new TConstructFluid(TinkerSmeltery.moltenBronzeFluid, Material.lava, "liquid_bronze").setBlockName("fluid.molten.bronze");
GameRegistry.registerBlock(TinkerSmeltery.moltenBronze, "fluid.molten.bronze");
TinkerSmeltery.moltenBronzeFluid.setBlock(TinkerSmeltery.moltenBronze).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(TinkerSmeltery.moltenBronzeFluid, 1000), new ItemStack(TinkerSmeltery.buckets, 1, 7), new ItemStack(
Items.bucket)));
TinkerSmeltery.moltenAlubrassFluid = new Fluid("aluminumbrass.molten");
if (!FluidRegistry.registerFluid(TinkerSmeltery.moltenAlubrassFluid))
TinkerSmeltery.moltenAlubrassFluid = FluidRegistry.getFluid("aluminumbrass.molten");
TinkerSmeltery.moltenAlubrass = new TConstructFluid(TinkerSmeltery.moltenAlubrassFluid, Material.lava, "liquid_alubrass").setBlockName("fluid.molten.alubrass");
GameRegistry.registerBlock(TinkerSmeltery.moltenAlubrass, "fluid.molten.alubrass");
TinkerSmeltery.moltenAlubrassFluid.setBlock(TinkerSmeltery.moltenAlubrass).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(TinkerSmeltery.moltenAlubrassFluid, 1000), new ItemStack(TinkerSmeltery.buckets, 1, 8), new ItemStack(
Items.bucket)));
TinkerSmeltery.moltenManyullynFluid = new Fluid("manyullyn.molten");
if (!FluidRegistry.registerFluid(TinkerSmeltery.moltenManyullynFluid))
TinkerSmeltery.moltenManyullynFluid = FluidRegistry.getFluid("manyullyn.molten");
TinkerSmeltery.moltenManyullyn = new TConstructFluid(TinkerSmeltery.moltenManyullynFluid, Material.lava, "liquid_manyullyn").setBlockName("fluid.molten.manyullyn");
GameRegistry.registerBlock(TinkerSmeltery.moltenManyullyn, "fluid.molten.manyullyn");
TinkerSmeltery.moltenManyullynFluid.setBlock(TinkerSmeltery.moltenManyullyn).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(TinkerSmeltery.moltenManyullynFluid, 1000), new ItemStack(TinkerSmeltery.buckets, 1, 9), new ItemStack(
Items.bucket)));
TinkerSmeltery.moltenAlumiteFluid = new Fluid("alumite.molten");
if (!FluidRegistry.registerFluid(TinkerSmeltery.moltenAlumiteFluid))
TinkerSmeltery.moltenAlumiteFluid = FluidRegistry.getFluid("alumite.molten");
TinkerSmeltery.moltenAlumite = new TConstructFluid(TinkerSmeltery.moltenAlumiteFluid, Material.lava, "liquid_alumite").setBlockName("fluid.molten.alumite");
GameRegistry.registerBlock(TinkerSmeltery.moltenAlumite, "fluid.molten.alumite");
TinkerSmeltery.moltenAlumiteFluid.setBlock(TinkerSmeltery.moltenAlumite).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(TinkerSmeltery.moltenAlumiteFluid, 1000), new ItemStack(TinkerSmeltery.buckets, 1, 10), new ItemStack(
Items.bucket)));
TinkerSmeltery.moltenObsidianFluid = new Fluid("obsidian.molten");
if (!FluidRegistry.registerFluid(TinkerSmeltery.moltenObsidianFluid))
TinkerSmeltery.moltenObsidianFluid = FluidRegistry.getFluid("obsidian.molten");
TinkerSmeltery.moltenObsidian = new TConstructFluid(TinkerSmeltery.moltenObsidianFluid, Material.lava, "liquid_obsidian").setBlockName("fluid.molten.obsidian");
GameRegistry.registerBlock(TinkerSmeltery.moltenObsidian, "fluid.molten.obsidian");
TinkerSmeltery.moltenObsidianFluid.setBlock(TinkerSmeltery.moltenObsidian).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(TinkerSmeltery.moltenObsidianFluid, 1000), new ItemStack(TinkerSmeltery.buckets, 1, 11), new ItemStack(
Items.bucket)));
TinkerSmeltery.moltenSteelFluid = new Fluid("steel.molten");
if (!FluidRegistry.registerFluid(TinkerSmeltery.moltenSteelFluid))
TinkerSmeltery.moltenSteelFluid = FluidRegistry.getFluid("steel.molten");
TinkerSmeltery.moltenSteel = new TConstructFluid(TinkerSmeltery.moltenSteelFluid, Material.lava, "liquid_steel").setBlockName("fluid.molten.steel");
GameRegistry.registerBlock(TinkerSmeltery.moltenSteel, "fluid.molten.steel");
TinkerSmeltery.moltenSteelFluid.setBlock(TinkerSmeltery.moltenSteel).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(TinkerSmeltery.moltenSteelFluid, 1000), new ItemStack(TinkerSmeltery.buckets, 1, 12), new ItemStack(
Items.bucket)));
TinkerSmeltery.moltenGlassFluid = new Fluid("glass.molten");
if (!FluidRegistry.registerFluid(TinkerSmeltery.moltenGlassFluid))
TinkerSmeltery.moltenGlassFluid = FluidRegistry.getFluid("glass.molten");
TinkerSmeltery.moltenGlass = new TConstructFluid(TinkerSmeltery.moltenGlassFluid, Material.lava, "liquid_glass", true).setBlockName("fluid.molten.glass");
GameRegistry.registerBlock(TinkerSmeltery.moltenGlass, "fluid.molten.glass");
TinkerSmeltery.moltenGlassFluid.setBlock(TinkerSmeltery.moltenGlass).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(TinkerSmeltery.moltenGlassFluid, 1000), new ItemStack(TinkerSmeltery.buckets, 1, 13), new ItemStack(
Items.bucket)));
TinkerSmeltery.moltenStoneFluid = new Fluid("stone.seared");
if (!FluidRegistry.registerFluid(TinkerSmeltery.moltenStoneFluid))
TinkerSmeltery.moltenStoneFluid = FluidRegistry.getFluid("stone.seared");
TinkerSmeltery.moltenStone = new TConstructFluid(TinkerSmeltery.moltenStoneFluid, Material.lava, "liquid_stone").setBlockName("molten.stone");
GameRegistry.registerBlock(TinkerSmeltery.moltenStone, "molten.stone");
TinkerSmeltery.moltenStoneFluid.setBlock(TinkerSmeltery.moltenStone).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(TinkerSmeltery.moltenStoneFluid, 1000), new ItemStack(TinkerSmeltery.buckets, 1, 14), new ItemStack(
Items.bucket)));
TinkerSmeltery.moltenEmeraldFluid = new Fluid("emerald.liquid");
if (!FluidRegistry.registerFluid(TinkerSmeltery.moltenEmeraldFluid))
TinkerSmeltery.moltenEmeraldFluid = FluidRegistry.getFluid("emerald.liquid");
TinkerSmeltery.moltenEmerald = new TConstructFluid(TinkerSmeltery.moltenEmeraldFluid, Material.lava, "liquid_villager").setBlockName("molten.emerald");
GameRegistry.registerBlock(TinkerSmeltery.moltenEmerald, "molten.emerald");
TinkerSmeltery.moltenEmeraldFluid.setBlock(TinkerSmeltery.moltenEmerald).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(TinkerSmeltery.moltenEmeraldFluid, 1000), new ItemStack(TinkerSmeltery.buckets, 1, 15), new ItemStack(
Items.bucket)));
TinkerSmeltery.bloodFluid = new Fluid("blood");
if (!FluidRegistry.registerFluid(TinkerSmeltery.bloodFluid))
TinkerSmeltery.bloodFluid = FluidRegistry.getFluid("blood");
TinkerSmeltery.blood = new BloodBlock(TinkerSmeltery.bloodFluid, Material.water, "liquid_cow").setBlockName("liquid.blood");
GameRegistry.registerBlock(TinkerSmeltery.blood, "liquid.blood");
TinkerSmeltery.bloodFluid.setBlock(TinkerSmeltery.blood).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry
.registerFluidContainer(new FluidContainerData(new FluidStack(TinkerSmeltery.bloodFluid, 1000), new ItemStack(TinkerSmeltery.buckets, 1, 16), new ItemStack(Items.bucket)));
TinkerSmeltery.moltenNickelFluid = new Fluid("nickel.molten");
if (!FluidRegistry.registerFluid(TinkerSmeltery.moltenNickelFluid))
TinkerSmeltery.moltenNickelFluid = FluidRegistry.getFluid("nickel.molten");
TinkerSmeltery.moltenNickel = new TConstructFluid(TinkerSmeltery.moltenNickelFluid, Material.lava, "liquid_ferrous").setBlockName("fluid.molten.nickel");
GameRegistry.registerBlock(TinkerSmeltery.moltenNickel, "fluid.molten.nickel");
TinkerSmeltery.moltenNickelFluid.setBlock(TinkerSmeltery.moltenNickel).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(TinkerSmeltery.moltenNickelFluid, 1000), new ItemStack(TinkerSmeltery.buckets, 1, 17), new ItemStack(
Items.bucket)));
TinkerSmeltery.moltenLeadFluid = new Fluid("lead.molten");
if (!FluidRegistry.registerFluid(TinkerSmeltery.moltenLeadFluid))
TinkerSmeltery.moltenLeadFluid = FluidRegistry.getFluid("lead.molten");
TinkerSmeltery.moltenLead = new TConstructFluid(TinkerSmeltery.moltenLeadFluid, Material.lava, "liquid_lead").setBlockName("fluid.molten.lead");
GameRegistry.registerBlock(TinkerSmeltery.moltenLead, "fluid.molten.lead");
TinkerSmeltery.moltenLeadFluid.setBlock(TinkerSmeltery.moltenLead).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(TinkerSmeltery.moltenLeadFluid, 1000), new ItemStack(TinkerSmeltery.buckets, 1, 18), new ItemStack(
Items.bucket)));
TinkerSmeltery.moltenSilverFluid = new Fluid("silver.molten");
if (!FluidRegistry.registerFluid(TinkerSmeltery.moltenSilverFluid))
TinkerSmeltery.moltenSilverFluid = FluidRegistry.getFluid("silver.molten");
TinkerSmeltery.moltenSilver = new TConstructFluid(TinkerSmeltery.moltenSilverFluid, Material.lava, "liquid_silver").setBlockName("fluid.molten.silver");
GameRegistry.registerBlock(TinkerSmeltery.moltenSilver, "fluid.molten.silver");
TinkerSmeltery.moltenSilverFluid.setBlock(TinkerSmeltery.moltenSilver).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(TinkerSmeltery.moltenSilverFluid, 1000), new ItemStack(TinkerSmeltery.buckets, 1, 19), new ItemStack(
Items.bucket)));
TinkerSmeltery.moltenShinyFluid = new Fluid("platinum.molten");
if (!FluidRegistry.registerFluid(TinkerSmeltery.moltenShinyFluid))
TinkerSmeltery.moltenShinyFluid = FluidRegistry.getFluid("platinum.molten");
TinkerSmeltery.moltenShiny = new TConstructFluid(TinkerSmeltery.moltenShinyFluid, Material.lava, "liquid_shiny").setBlockName("fluid.molten.shiny");
GameRegistry.registerBlock(TinkerSmeltery.moltenShiny, "fluid.molten.shiny");
TinkerSmeltery.moltenShinyFluid.setBlock(TinkerSmeltery.moltenShiny).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(TinkerSmeltery.moltenShinyFluid, 1000), new ItemStack(TinkerSmeltery.buckets, 1, 20), new ItemStack(
Items.bucket)));
TinkerSmeltery.moltenInvarFluid = new Fluid("invar.molten");
if (!FluidRegistry.registerFluid(TinkerSmeltery.moltenInvarFluid))
TinkerSmeltery.moltenInvarFluid = FluidRegistry.getFluid("invar.molten");
TinkerSmeltery.moltenInvar = new TConstructFluid(TinkerSmeltery.moltenInvarFluid, Material.lava, "liquid_invar").setBlockName("fluid.molten.invar");
GameRegistry.registerBlock(TinkerSmeltery.moltenInvar, "fluid.molten.invar");
TinkerSmeltery.moltenInvarFluid.setBlock(TinkerSmeltery.moltenInvar).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(TinkerSmeltery.moltenInvarFluid, 1000), new ItemStack(TinkerSmeltery.buckets, 1, 21), new ItemStack(
Items.bucket)));
TinkerSmeltery.moltenElectrumFluid = new Fluid("electrum.molten");
if (!FluidRegistry.registerFluid(TinkerSmeltery.moltenElectrumFluid))
TinkerSmeltery.moltenElectrumFluid = FluidRegistry.getFluid("electrum.molten");
TinkerSmeltery.moltenElectrum = new TConstructFluid(TinkerSmeltery.moltenElectrumFluid, Material.lava, "liquid_electrum").setBlockName("fluid.molten.electrum");
GameRegistry.registerBlock(TinkerSmeltery.moltenElectrum, "fluid.molten.electrum");
TinkerSmeltery.moltenElectrumFluid.setBlock(TinkerSmeltery.moltenElectrum).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(TinkerSmeltery.moltenElectrumFluid, 1000), new ItemStack(TinkerSmeltery.buckets, 1, 22), new ItemStack(
Items.bucket)));
TinkerSmeltery.moltenEnderFluid = new Fluid("ender");
if (!FluidRegistry.registerFluid(TinkerSmeltery.moltenEnderFluid))
{
TinkerSmeltery.moltenEnderFluid = FluidRegistry.getFluid("ender");
TinkerSmeltery.moltenEnder = TinkerSmeltery.moltenEnderFluid.getBlock();
if (TinkerSmeltery.moltenEnder == null)
TConstruct.logger.info("Molten ender block missing!");
}
else
{
TinkerSmeltery.moltenEnder = new TConstructFluid(TinkerSmeltery.moltenEnderFluid, Material.water, "liquid_ender").setBlockName("fluid.ender");
GameRegistry.registerBlock(TinkerSmeltery.moltenEnder, "fluid.ender");
TinkerSmeltery.moltenEnderFluid.setBlock(TinkerSmeltery.moltenEnder).setDensity(3000).setViscosity(6000);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(TinkerSmeltery.moltenEnderFluid, 1000), new ItemStack(TinkerSmeltery.buckets, 1, 23), new ItemStack(
Items.bucket)));
}
// Glue
TinkerSmeltery.glueFluid = new Fluid("glue").setDensity(6000).setViscosity(6000).setTemperature(200);
if (!FluidRegistry.registerFluid(TinkerSmeltery.glueFluid))
TinkerSmeltery.glueFluid = FluidRegistry.getFluid("glue");
TinkerSmeltery.glueFluidBlock = new GlueFluid(TinkerSmeltery.glueFluid, Material.water).setCreativeTab(TConstructRegistry.blockTab).setStepSound(TinkerWorld.slimeStep)
.setBlockName("liquid.glue");
GameRegistry.registerBlock(TinkerSmeltery.glueFluidBlock, "liquid.glue");
TinkerSmeltery.glueFluid.setBlock(TinkerSmeltery.glueFluidBlock);
FluidContainerRegistry
.registerFluidContainer(new FluidContainerData(new FluidStack(TinkerSmeltery.glueFluid, 1000), new ItemStack(TinkerSmeltery.buckets, 1, 25), new ItemStack(Items.bucket)));
TinkerSmeltery.pigIronFluid = new Fluid("pigiron.molten");
if (!FluidRegistry.registerFluid(TinkerSmeltery.pigIronFluid))
TinkerSmeltery.pigIronFluid = FluidRegistry.getFluid("pigiron.molten");
else
TinkerSmeltery.pigIronFluid.setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(TinkerSmeltery.pigIronFluid, 1000), new ItemStack(TinkerSmeltery.buckets, 1, 26), new ItemStack(
Items.bucket)));
TinkerSmeltery.fluids = new Fluid[] { TinkerSmeltery.moltenIronFluid, TinkerSmeltery.moltenGoldFluid, TinkerSmeltery.moltenCopperFluid, TinkerSmeltery.moltenTinFluid,
TinkerSmeltery.moltenAluminumFluid, TinkerSmeltery.moltenCobaltFluid, TinkerSmeltery.moltenArditeFluid, TinkerSmeltery.moltenBronzeFluid, TinkerSmeltery.moltenAlubrassFluid,
TinkerSmeltery.moltenManyullynFluid, TinkerSmeltery.moltenAlumiteFluid, TinkerSmeltery.moltenObsidianFluid, TinkerSmeltery.moltenSteelFluid, TinkerSmeltery.moltenGlassFluid,
TinkerSmeltery.moltenStoneFluid, TinkerSmeltery.moltenEmeraldFluid, TinkerSmeltery.bloodFluid, TinkerSmeltery.moltenNickelFluid, TinkerSmeltery.moltenLeadFluid,
TinkerSmeltery.moltenSilverFluid, TinkerSmeltery.moltenShinyFluid, TinkerSmeltery.moltenInvarFluid, TinkerSmeltery.moltenElectrumFluid, TinkerSmeltery.moltenEnderFluid,
TinkerSmeltery.glueFluid, TinkerSmeltery.pigIronFluid };
TinkerSmeltery.fluidBlocks = new Block[] { TinkerSmeltery.moltenIron, TinkerSmeltery.moltenGold, TinkerSmeltery.moltenCopper, TinkerSmeltery.moltenTin, TinkerSmeltery.moltenAluminum,
TinkerSmeltery.moltenCobalt, TinkerSmeltery.moltenArdite, TinkerSmeltery.moltenBronze, TinkerSmeltery.moltenAlubrass, TinkerSmeltery.moltenManyullyn, TinkerSmeltery.moltenAlumite,
TinkerSmeltery.moltenObsidian, TinkerSmeltery.moltenSteel, TinkerSmeltery.moltenGlass, TinkerSmeltery.moltenStone, TinkerSmeltery.moltenEmerald, TinkerSmeltery.blood,
TinkerSmeltery.moltenNickel, TinkerSmeltery.moltenLead, TinkerSmeltery.moltenSilver, TinkerSmeltery.moltenShiny, TinkerSmeltery.moltenInvar, TinkerSmeltery.moltenElectrum,
TinkerSmeltery.moltenEnder, TinkerSmeltery.glueFluidBlock };
FluidType.registerFluidType("Water", Blocks.snow, 0, 20, FluidRegistry.getFluid("water"), false);
FluidType.registerFluidType("Iron", Blocks.iron_block, 0, 600, TinkerSmeltery.moltenIronFluid, true);
FluidType.registerFluidType("Gold", Blocks.gold_block, 0, 400, TinkerSmeltery.moltenGoldFluid, false);
FluidType.registerFluidType("Tin", TinkerWorld.metalBlock, 5, 400, TinkerSmeltery.moltenTinFluid, false);
FluidType.registerFluidType("Copper", TinkerWorld.metalBlock, 3, 550, TinkerSmeltery.moltenCopperFluid, true);
FluidType.registerFluidType("Aluminum", TinkerWorld.metalBlock, 6, 350, TinkerSmeltery.moltenAluminumFluid, false);
FluidType.registerFluidType("NaturalAluminum", TinkerWorld.oreSlag, 6, 350, TinkerSmeltery.moltenAluminumFluid, false);
FluidType.registerFluidType("Cobalt", TinkerWorld.metalBlock, 0, 650, TinkerSmeltery.moltenCobaltFluid, true);
FluidType.registerFluidType("Ardite", TinkerWorld.metalBlock, 1, 650, TinkerSmeltery.moltenArditeFluid, true);
FluidType.registerFluidType("AluminumBrass", TinkerWorld.metalBlock, 7, 350, TinkerSmeltery.moltenAlubrassFluid, false);
FluidType.registerFluidType("Alumite", TinkerWorld.metalBlock, 8, 800, TinkerSmeltery.moltenAlumiteFluid, true);
FluidType.registerFluidType("Manyullyn", TinkerWorld.metalBlock, 2, 750, TinkerSmeltery.moltenManyullynFluid, true);
FluidType.registerFluidType("Bronze", TinkerWorld.metalBlock, 4, 500, TinkerSmeltery.moltenBronzeFluid, true);
FluidType.registerFluidType("Steel", TinkerWorld.metalBlock, 9, 700, TinkerSmeltery.moltenSteelFluid, true);
FluidType.registerFluidType("Nickel", TinkerWorld.metalBlock, 0, 400, TinkerSmeltery.moltenNickelFluid, false);
FluidType.registerFluidType("Lead", TinkerWorld.metalBlock, 0, 400, TinkerSmeltery.moltenLeadFluid, false);
FluidType.registerFluidType("Silver", TinkerWorld.metalBlock, 0, 400, TinkerSmeltery.moltenSilverFluid, false);
FluidType.registerFluidType("Platinum", TinkerWorld.metalBlock, 0, 400, TinkerSmeltery.moltenShinyFluid, false);
FluidType.registerFluidType("Invar", TinkerWorld.metalBlock, 0, 400, TinkerSmeltery.moltenInvarFluid, false);
FluidType.registerFluidType("Electrum", TinkerWorld.metalBlock, 0, 400, TinkerSmeltery.moltenElectrumFluid, false);
FluidType.registerFluidType("Obsidian", Blocks.obsidian, 0, 750, TinkerSmeltery.moltenObsidianFluid, true);
FluidType.registerFluidType("Ender", TinkerWorld.metalBlock, 10, 500, TinkerSmeltery.moltenEnderFluid, false);
FluidType.registerFluidType("Glass", Blocks.sand, 0, 625, TinkerSmeltery.moltenGlassFluid, false);
FluidType.registerFluidType("Stone", Blocks.stone, 0, 800, TinkerSmeltery.moltenStoneFluid, true);
FluidType.registerFluidType("Emerald", Blocks.emerald_block, 0, 575, TinkerSmeltery.moltenEmeraldFluid, false);
FluidType.registerFluidType("PigIron", TinkerWorld.meatBlock, 0, 610, TinkerSmeltery.pigIronFluid, true);
FluidType.registerFluidType("Glue", TinkerSmeltery.glueBlock, 0, 125, TinkerSmeltery.glueFluid, false);
TinkerSmeltery.speedBlock = new SpeedBlock().setBlockName("SpeedBlock");
// Glass
TinkerSmeltery.clearGlass = new GlassBlockConnected("clear", false).setBlockName("GlassBlock");
TinkerSmeltery.clearGlass.stepSound = Block.soundTypeGlass;
TinkerSmeltery.glassPane = new GlassPaneConnected("clear", false);
TinkerSmeltery.stainedGlassClear = new GlassBlockConnectedMeta("stained", true, "white", "orange", "magenta", "light_blue", "yellow", "lime", "pink", "gray", "light_gray", "cyan", "purple",
"blue", "brown", "green", "red", "black").setBlockName("GlassBlock.StainedClear");
TinkerSmeltery.stainedGlassClear.stepSound = Block.soundTypeGlass;
TinkerSmeltery.stainedGlassClearPane = new GlassPaneStained();
GameRegistry.registerBlock(TinkerSmeltery.searedSlab, SearedSlabItem.class, "SearedSlab");
GameRegistry.registerBlock(TinkerSmeltery.speedSlab, SpeedSlabItem.class, "SpeedSlab");
GameRegistry.registerBlock(TinkerSmeltery.glueBlock, "GlueBlock");
OreDictionary.registerOre("blockRubber", new ItemStack(TinkerSmeltery.glueBlock));
// Smeltery stuff
GameRegistry.registerBlock(TinkerSmeltery.smeltery, SmelteryItemBlock.class, "Smeltery");
GameRegistry.registerBlock(TinkerSmeltery.smelteryNether, SmelteryItemBlock.class, "SmelteryNether");
if (PHConstruct.newSmeltery)
{
GameRegistry.registerTileEntity(AdaptiveSmelteryLogic.class, "TConstruct.Smeltery");
GameRegistry.registerTileEntity(AdaptiveDrainLogic.class, "TConstruct.SmelteryDrain");
}
else
{
GameRegistry.registerTileEntity(SmelteryLogic.class, "TConstruct.Smeltery");
GameRegistry.registerTileEntity(SmelteryDrainLogic.class, "TConstruct.SmelteryDrain");
}
GameRegistry.registerTileEntity(MultiServantLogic.class, "TConstruct.Servants");
GameRegistry.registerBlock(TinkerSmeltery.lavaTank, LavaTankItemBlock.class, "LavaTank");
GameRegistry.registerBlock(TinkerSmeltery.lavaTankNether, LavaTankItemBlock.class, "LavaTankNether");
GameRegistry.registerTileEntity(LavaTankLogic.class, "TConstruct.LavaTank");
GameRegistry.registerBlock(TinkerSmeltery.searedBlock, SearedTableItemBlock.class, "SearedBlock");
GameRegistry.registerBlock(TinkerSmeltery.searedBlockNether, SearedTableItemBlock.class, "SearedBlockNether");
GameRegistry.registerTileEntity(CastingTableLogic.class, "CastingTable");
GameRegistry.registerTileEntity(FaucetLogic.class, "Faucet");
GameRegistry.registerTileEntity(CastingBasinLogic.class, "CastingBasin");
GameRegistry.registerBlock(TinkerSmeltery.castingChannel, CastingChannelItem.class, "CastingChannel");
GameRegistry.registerTileEntity(CastingChannelLogic.class, "CastingChannel");
GameRegistry.registerBlock(TinkerSmeltery.tankAir, "TankAir");
GameRegistry.registerTileEntity(TankAirLogic.class, "tconstruct.tank.air");
GameRegistry.registerBlock(TinkerSmeltery.speedBlock, SpeedBlockItem.class, "SpeedBlock");
// Glass
GameRegistry.registerBlock(TinkerSmeltery.clearGlass, GlassBlockItem.class, "GlassBlock");
GameRegistry.registerBlock(TinkerSmeltery.glassPane, GlassPaneItem.class, "GlassPane");
GameRegistry.registerBlock(TinkerSmeltery.stainedGlassClear, StainedGlassClearItem.class, "GlassBlock.StainedClear");
GameRegistry.registerBlock(TinkerSmeltery.stainedGlassClearPane, StainedGlassClearPaneItem.class, "GlassPaneClearStained");
//Items
TinkerSmeltery.metalPattern = new MetalPattern("cast_", "materials/").setUnlocalizedName("tconstruct.MetalPattern");
GameRegistry.registerItem(TinkerSmeltery.metalPattern, "metalPattern");
TConstructRegistry.addItemToDirectory("metalPattern", TinkerSmeltery.metalPattern);
String[] patternTypes = { "ingot", "toolRod", "pickaxeHead", "shovelHead", "hatchetHead", "swordBlade", "wideGuard", "handGuard", "crossbar", "binding", "frypanHead", "signHead",
"knifeBlade", "chiselHead", "toughRod", "toughBinding", "largePlate", "broadAxeHead", "scytheHead", "excavatorHead", "largeBlade", "hammerHead", "fullGuard" };
for (int i = 0; i < patternTypes.length; i++)
{
TConstructRegistry.addItemStackToDirectory(patternTypes[i] + "Cast", new ItemStack(TinkerSmeltery.metalPattern, 1, i));
}
}
|
diff --git a/n3phele/src/n3phele/service/rest/impl/CloudProcessResource.java b/n3phele/src/n3phele/service/rest/impl/CloudProcessResource.java
index 0c5ca25..c6d0fce 100644
--- a/n3phele/src/n3phele/service/rest/impl/CloudProcessResource.java
+++ b/n3phele/src/n3phele/service/rest/impl/CloudProcessResource.java
@@ -1,711 +1,712 @@
package n3phele.service.rest.impl;
/**
* (C) Copyright 2010-2013. Nigel Cook. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Licensed under the terms described in LICENSE file that accompanied this code, (the "License"); you may not use this file
* except in compliance with the License.
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
import static com.googlecode.objectify.ObjectifyService.ofy;
import java.io.FileNotFoundException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import javax.annotation.security.RolesAllowed;
import javax.ws.rs.DELETE;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import javax.ws.rs.core.SecurityContext;
import javax.ws.rs.core.UriBuilder;
import javax.ws.rs.core.UriInfo;
import n3phele.service.actions.NShellAction;
import n3phele.service.actions.StackServiceAction;
import n3phele.service.core.NotFoundException;
import n3phele.service.core.Resource;
import n3phele.service.core.ResourceFile;
import n3phele.service.core.ResourceFileFactory;
import n3phele.service.lifecycle.ProcessLifecycle;
import n3phele.service.model.Action;
import n3phele.service.model.ActionState;
import n3phele.service.model.CachingAbstractManager;
import n3phele.service.model.CloudProcess;
import n3phele.service.model.CloudProcessCollection;
import n3phele.service.model.Relationship;
import n3phele.service.model.ServiceModelDao;
import n3phele.service.model.SignalKind;
import n3phele.service.model.Stack;
import n3phele.service.model.Variable;
import n3phele.service.model.core.Collection;
import n3phele.service.model.core.GenericModelDao;
import n3phele.service.model.core.Helpers;
import n3phele.service.model.core.User;
import n3phele.service.rest.impl.ActionResource.ActionManager;
import com.googlecode.objectify.Key;
@Path("/process")
public class CloudProcessResource {
final private static java.util.logging.Logger log = java.util.logging.Logger.getLogger(CloudProcessResource.class.getName());
final private static ResourceFileFactory resourceFileFactory = new ResourceFileFactory();
public CloudProcessResource() {
}
protected @Context
UriInfo uriInfo;
protected @Context
SecurityContext securityContext;
@GET
@Produces("application/json")
@RolesAllowed("authenticated")
public CloudProcessCollection list(@DefaultValue("false") @QueryParam("summary") Boolean summary, @DefaultValue("0") @QueryParam("start") int start, @DefaultValue("-1") @QueryParam("end") int end, @DefaultValue("false") @QueryParam("count") Boolean count) throws NotFoundException {
log.info("list entered with summary " + summary + " from start=" + start + " to end=" + end);
if (start < 0)
start = 0;
Collection<CloudProcess> result = dao.getCollection(start, end, UserResource.toUser(securityContext), count);// .collection(summary);
return new CloudProcessCollection(result);
}
// Ancestor query
// @GET
// @Produces("application/json")
// @RolesAllowed("authenticated")
// @Path("{id:[0-9]+}/childrencosts")
// public CloudProcessCollection listChildrenWithCosts(@PathParam("id") Long
// id){
// Collection<CloudProcess> result = dao.getChildrenWithCostsCollection(id);
// return new CloudProcessCollection(result);
// }
@GET
@Produces("application/json")
@RolesAllowed("authenticated")
@Path("{group:[0-9]+_}{id:[0-9]+}/children")
public CloudProcess[] listChildren(@PathParam("group") String group, @PathParam("id") Long id) {
CloudProcess parent;
try {
Key<CloudProcess> root = null;
if (group != null) {
root = Key.create(CloudProcess.class, Long.valueOf(group.substring(0, group.length() - 1)));
}
parent = dao.load(root, id, UserResource.toUser(securityContext));
} catch (NotFoundException e) {
throw e;
}
java.util.Collection<CloudProcess> result = dao.getChildren(parent.getUri());
return result.toArray(new CloudProcess[result.size()]);
}
@GET
@Produces("application/json")
@RolesAllowed("authenticated")
@Path("/{group:[0-9]+_}{id:[0-9]+}/toplevel")
public CloudProcess getTopLevel(@PathParam("group") String group, @PathParam("id") Long id) throws NotFoundException {
if (group != null)
return dao.load(null, Long.valueOf(group.substring(0, group.length() - 1)));
return dao.load(null, id, UserResource.toUser(securityContext));
}
@GET
@Produces("application/json")
@RolesAllowed("authenticated")
@Path("/toplevel{id:[0-9]+}")
public CloudProcess getTopLevel(@PathParam("id") Long id) throws NotFoundException {
return get(null, id);
}
@GET
@Produces("application/json")
@RolesAllowed("authenticated")
@Path("{id:[0-9]+}/children")
public CloudProcess[] listChildren(@PathParam("id") Long id) {
return listChildren(null, id);
}
@GET
@Produces("application/json")
@RolesAllowed("authenticated")
@Path("{group:[0-9]+_}{id:[0-9]+}")
public CloudProcess get(@PathParam("group") String group, @PathParam("id") Long id) throws NotFoundException {
Key<CloudProcess> root = null;
if (group != null) {
root = Key.create(CloudProcess.class, Long.valueOf(group.substring(0, group.length() - 1)));
}
CloudProcess item = dao.load(root, id, UserResource.toUser(securityContext));
return item;
}
@GET
@Produces("application/json")
@RolesAllowed("authenticated")
@Path("{id:[0-9]+}")
public CloudProcess get(@PathParam("id") Long id) throws NotFoundException {
return get(null, id);
}
@DELETE
@Produces("application/json")
@RolesAllowed("authenticated")
@Path("{group:[0-9]+_}{id:[0-9]+}")
public Response killProcess(@PathParam("group") String group, @PathParam("id") Long id) throws NotFoundException {
CloudProcess process = null;
Key<CloudProcess> root = null;
if (group != null) {
root = Key.create(CloudProcess.class, Long.valueOf(group.substring(0, group.length() - 1)));
}
try {
process = dao.load(root, id, UserResource.toUser(securityContext));
} catch (NotFoundException e) {
return Response.status(Status.GONE).build();
}
ProcessLifecycle.mgr().cancel(process);
return Response.status(Status.NO_CONTENT).build();
}
@DELETE
@Produces("application/json")
@RolesAllowed("authenticated")
@Path("{id:[0-9]+}")
public Response killProcess(@PathParam("id") Long id) throws NotFoundException {
return killProcess(null, id);
}
/*
* This is an eventing endpoint that can be invoked by an http request with
* no authentication.
*/
@GET
@Produces("text/plain")
@Path("{group:.*_}{id}/event")
public Response event(@PathParam("group") String group, @PathParam("id") Long id) {
log.info(String.format("Event %s", uriInfo.getRequestUri().toString()));
CloudProcess a = null;
Key<CloudProcess> root = null;
if (group != null) {
root = Key.create(CloudProcess.class, Long.valueOf(group.substring(0, group.length() - 1)));
}
try {
a = dao.load(root, id);
} catch (NotFoundException e) {
return Response.status(Status.GONE).build();
}
ProcessLifecycle.mgr().signal(a, SignalKind.Event, uriInfo.getRequestUri().toString());
return Response.ok().build();
}
/*
* This is an eventing endpoint that can be invoked by an http request with
* no authentication.
*/
@GET
@Produces("text/plain")
@Path("{id:[0-9]+}")
public Response event(@PathParam("id") Long id) {
return this.event(null, id);
}
@POST
@Produces("application/json")
@RolesAllowed("authenticated")
@Path("exec")
public Response exec(@DefaultValue("Log") @QueryParam("action") String action, @QueryParam("name") String name,
@DefaultValue("hello world!") @QueryParam("arg") String arg, @QueryParam("parent") String parent, List<Variable> context) throws ClassNotFoundException, URISyntaxException {
n3phele.service.model.Context env = new n3phele.service.model.Context();
env.putValue("arg", arg);
Class<? extends Action> clazz = Class.forName("n3phele.service.actions." + action + "Action").asSubclass(Action.class);
//check parent here
if(parent != null && parent.trim().length() > 0){
URI parentURI = new URI(parent);
CloudProcess processParent = CloudProcessResource.dao.load(parentURI);
URI actionURI = processParent.getAction();
Action parentAction = ActionResource.dao.load(actionURI);
if(processParent.getState() != ActionState.RUNABLE) return Response.serverError().build();
if(parentAction instanceof StackServiceAction){
StackServiceAction serviceAction = (StackServiceAction)parentAction;
env.putAll(serviceAction.getContext());
env.remove("name");
for (Variable v : Helpers.safeIterator(context)) {
env.put(v.getName(), v);
}
+ env.putValue("arg", arg);
if(env.getValue("service_name") != null)
name = env.getValue("service_name");
String description = env.getValue("description");
String[] argv;
String command = arg;
if(Helpers.isBlankOrNull(arg)) {
argv = new String[0];
command = "";
} else {
argv = arg.split("[\\s]+"); // FIXME - find a better regex for shell split
if(argv.length > 1)
command = argv[1];
else
command = argv[0];
}
Stack stack = new Stack(name, description);
stack.setCommandUri(command);
stack.setId(serviceAction.getNextStackNumber());
env.putValue("stackId", stack.getId());
CloudProcess p = ProcessLifecycle.mgr().createProcess(UserResource.toUser(securityContext), name, env, null, processParent, true, clazz);
ProcessLifecycle.mgr().init(p);
stack.setDeployProcess(p.getUri().toString());
serviceAction.addStack(stack);
ActionResource.dao.update(serviceAction);
return Response.created(p.getUri()).build();
}
}
for (Variable v : Helpers.safeIterator(context)) {
env.put(v.getName(), v);
}
if (clazz != null) {
CloudProcess p = ProcessLifecycle.mgr().createProcess(UserResource.toUser(securityContext), name, env, null, null, true, clazz);
ProcessLifecycle.mgr().init(p);
return Response.created(p.getUri()).build();
} else {
return Response.noContent().build();
}
}
@POST
@Produces("application/json")
@RolesAllowed("authenticated")
@Path("stackExpose/{id:[0-9]+}")
public Response stackExpose(@PathParam("id") long id,List<Variable> context) throws ClassNotFoundException {
StackServiceAction sAction = (StackServiceAction) ActionResource.dao.load(id);
if (CloudProcessResource.dao.load(URI.create(sAction.getProcess().toString())).getState() != ActionState.RUNABLE)
return Response.serverError().build();
n3phele.service.model.Context env = new n3phele.service.model.Context();
env.putValue("arg",getJujuExposeStackCommandURI() );
for (Variable v : Helpers.safeIterator(context)) {
env.put(v.getName(), v);
}
Stack stack = null;
for (Stack s : sAction.getStacks()) {
if (s.getName().equalsIgnoreCase(env.getValue("charm_name"))) {
stack = s;
break;
}
}
if(stack == null)
return Response.status(Response.Status.NOT_FOUND).build();
Class<? extends Action> clazz = NShellAction.class;
CloudProcess parent = dao.load(sAction.getProcess());
CloudProcess p = ProcessLifecycle.mgr().createProcess(UserResource.toUser(securityContext), "Expose "+stack.getName(), env, null, parent, true, clazz);
ProcessLifecycle.mgr().init(p);
return Response.created(p.getUri()).build();
}
@POST
@Produces("application/json")
@RolesAllowed("authenticated")
@Path("addRelationStacks/{id:[0-9]+}")
public Response addRelationStacks(@PathParam("id") long id,List<Variable> context) throws ClassNotFoundException {
StackServiceAction sAction = (StackServiceAction) ActionResource.dao.load(id);
if (CloudProcessResource.dao.load(URI.create(sAction.getProcess().toString())).getState() != ActionState.RUNABLE)
return Response.serverError().build();
n3phele.service.model.Context env = new n3phele.service.model.Context();
for (Variable v : Helpers.safeIterator(context)) {
env.put(v.getName(), v);
}
Stack stack1 = null;
Stack stack2 = null;
env.putValue("arg", getJujuAddRelationCommandURI());
for (Stack s : sAction.getStacks()) {
if (s.getName().equalsIgnoreCase(env.getValue("charm_name01"))) {
stack1 = s;
}
if (s.getName().equalsIgnoreCase(env.getValue("charm_name02"))) {
stack2 = s;
}
}
if(stack1 == null || stack2 == null)
return Response.status(Response.Status.NOT_FOUND).build();
Relationship relation = new Relationship(stack1.getId(), stack2.getId(), null, null);
Class<? extends Action> clazz = NShellAction.class;
CloudProcess parent = dao.load(sAction.getProcess());
CloudProcess p = ProcessLifecycle.mgr().createProcess(UserResource.toUser(securityContext), "Relation: "+ stack1.getName() + "_" + stack2.getName(), env, null, parent, true, clazz);
ProcessLifecycle.mgr().init(p);
relation.setName(stack1.getName()+"_"+stack2.getName());
sAction.addRelationhip(relation);
ActionResource.dao.update(sAction);
return Response.created(p.getUri()).build();
}
@POST
@Produces("application/json")
@RolesAllowed("authenticated")
@Path("deleteStackService")
public Response deleteStackService(@QueryParam("id") long id, List<Variable> context)
{
StackServiceAction sAction = (StackServiceAction) ActionResource.dao.load(id);
if(sAction == null)
return Response.status(Response.Status.NOT_FOUND).build();
n3phele.service.model.Context env = new n3phele.service.model.Context();
env.putValue("arg", getJujuDeleteCommandURI());
for (Variable v : Helpers.safeIterator(context)) {
env.put(v.getName(), v);
}
boolean deleted = deleteServiceStackFromAction(sAction, env.getValue("service_name"));
if(!deleted)
return Response.notModified().build();
Class<? extends Action> clazz = NShellAction.class;
CloudProcess parent = dao.load(sAction.getProcess());
CloudProcess p = ProcessLifecycle.mgr().createProcess(UserResource.toUser(securityContext), "DeleteService: "+ id, env, null, parent, true, clazz);
ProcessLifecycle.mgr().init(p);
return Response.ok().build();
}
public boolean deleteServiceStackFromAction(StackServiceAction sAction, String serviceName)
{
List<Stack> stackList = sAction.getStacks();
for(Stack stack : stackList)
{
if( stack.getName().equalsIgnoreCase(serviceName) )
{
stackList.remove(stack);
ActionResource.dao.update(sAction);
return true;
}
}
return false;
}
public String getJujuDeleteCommandURI()
{
try
{
ResourceFile fileConfig = CloudProcessResource.resourceFileFactory.create("n3phele.resource.service_commands");
String deleteCommandURI = fileConfig.get("deleteJujuCommand", "");
URI.create(deleteCommandURI); // Just to throw error if URI is invalid.
return deleteCommandURI;
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
}
public String getJujuAddRelationCommandURI()
{
try
{
ResourceFile fileConfig = CloudProcessResource.resourceFileFactory.create("n3phele.resource.service_commands");
String relationCommandURI = fileConfig.get("addRelationshipCommand", "");
URI.create(relationCommandURI); // Just to throw error if URI is invalid.
return relationCommandURI;
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
}
public String getJujuExposeStackCommandURI()
{
try
{
ResourceFile fileConfig = CloudProcessResource.resourceFileFactory.create("n3phele.resource.service_commands");
String exposeCommandURI = fileConfig.get("stackExpose", "");
URI.create(exposeCommandURI); // Just to throw error if URI is invalid.
return exposeCommandURI;
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
}
@GET
@Produces("application/json")
@RolesAllowed("authenticated")
@Path("exec")
public Response exec(@DefaultValue("Log") @QueryParam("action") String action, @QueryParam("name") String name, @DefaultValue("hello world!") @QueryParam("arg") String arg) throws ClassNotFoundException {
n3phele.service.model.Context env = new n3phele.service.model.Context();
env.putValue("arg", arg);
Class<? extends Action> clazz = Class.forName("n3phele.service.actions." + action + "Action").asSubclass(Action.class);
if (clazz != null) {
//env = new n3phele.service.model.Context();
CloudProcess p = ProcessLifecycle.mgr().createProcess(UserResource.toUser(securityContext), name, env, null, null, true, clazz);
ProcessLifecycle.mgr().init(p);
return Response.created(p.getUri()).build();
} else {
return Response.noContent().build();
}
}
@GET
@Produces("application/json")
@RolesAllowed("admin")
@Path("refresh")
public Response refresh() {
Date begin = new Date();
Map<String, Long> result = ProcessLifecycle.mgr().periodicScheduler();
log.info("Refresh " + (new Date().getTime() - begin.getTime()) + "ms");
return Response.ok(result.toString().replaceAll("([0-9a-zA-Z_]+)=", "\"$1\": "), MediaType.APPLICATION_JSON).build();
}
@GET
@Produces("application/json")
@RolesAllowed("authenticated")
@Path("/activeServiceActions")
public CloudProcessCollection getStackServiceActionProcessesRunning() throws NotFoundException {
User currentUser = UserResource.toUser(securityContext);
Collection<CloudProcess> result = dao.getServiceStackCollectionNonFinalized(currentUser.getUri().toString());
return new CloudProcessCollection(result);
}
/*
* Data Access
*/
public static class CloudProcessManager extends CachingAbstractManager<CloudProcess> {
public CloudProcessManager() {
}
@Override
protected URI myPath() {
return UriBuilder.fromUri(Resource.get("baseURI", "http://127.0.0.1:8888/resources")).path(CloudProcessResource.class).build();
}
@Override
public GenericModelDao<CloudProcess> itemDaoFactory() {
return new ServiceModelDao<CloudProcess>(CloudProcess.class);
}
public void clear() {
super.itemDao.clear();
}
public CloudProcess load(Key<CloudProcess> group, Long id, User requestor) throws NotFoundException {
return super.get(group, id, requestor);
}
/**
* Locate a item from the persistent store based on the item URI.
*
* @param uri
* @param requestor
* requesting user
* @return the item
* @throws NotFoundException
* is the object does not exist
*/
public CloudProcess load(URI uri, User requestor) throws NotFoundException {
return super.get(uri, requestor);
}
/**
* Locate a item from the persistent store based on the item URI.
*
* @param uri
* @param requestor
* requesting user
* @return the item
* @throws NotFoundException
* is the object does not exist
*/
public CloudProcess load(URI uri) throws NotFoundException {
log.info("Loading cloudProcess: " + uri);
return super.get(uri);
}
public CloudProcess load(Key<CloudProcess> group, Long id) throws NotFoundException {
return super.get(group, id);
}
public CloudProcess load(Key<CloudProcess> k) throws NotFoundException {
return super.itemDao.get(k);
}
public void update(CloudProcess cloudProcess) {
super.update(cloudProcess);
}
public java.util.Collection<CloudProcess> getNonfinalized() {
return super.itemDao.collectionByProperty("finalized", false);
}
public java.util.Collection<CloudProcess> getChildren(URI parent) {
return super.itemDao.collectionByProperty(parent, "parent", parent.toString());
}
public java.util.Collection<CloudProcess> getList(List<URI> ids) {
return super.itemDao.listByURI(ids);
}
public void add(CloudProcess process) {
super.add(process);
}
public void delete(CloudProcess process) {
super.delete(process);
}
public Collection<CloudProcess> getCollection2(User owner) {
return super.getCollection(owner);
}
/**
* Collection of resources of a particular class in the persistent
* store. The will be extended in the future to return the collection of
* resources accessible to a particular user.
*
* @return the collection
*/
public Collection<CloudProcess> getCollection(int start, int end, User owner, boolean count) {
return owner.isAdmin() ? getCollection(start, end, count) : getCollection(start, end, owner.getUri(), count);
}
public Collection<CloudProcess> getCollection(int start, int end) {
return getCollection(start, end, false);
}
/**
* Collection of resources of a particular class in the persistent
* store. The will be extended in the future to return the collection of
* resources accessible to a particular user.
*
* @return the collection
*/
public Collection<CloudProcess> getCollection(int start, int end, boolean count) {
log.info("admin query");
Collection<CloudProcess> result = null;
List<CloudProcess> items;
if (end > 0) {
int n = end - start;
if (n <= 0)
n = 0;
items = ofy().load().type(CloudProcess.class).filter("topLevel", true).order("-start").offset(start).limit(n).list();
} else {
items = ofy().load().type(CloudProcess.class).filter("topLevel", true).order("-start").offset(start).list();
}
result = new Collection<CloudProcess>(itemDao.clazz.getSimpleName(), super.path, items);
if (count) {
result.setTotal(ofy().load().type(CloudProcess.class).filter("topLevel", true).count());
}
log.info("admin query total (with sort) -is- " + result.getTotal());
return result;
}
public Collection<CloudProcess> getCollection(int start, int end, URI owner) {
return getCollection(start, end, owner, false);
}
/**
* Collection of resources of a particular class in the persistent
* store. The will be extended in the future to return the collection of
* resources accessible to a particular user.
*
* @return the collection
*/
public Collection<CloudProcess> getCollection(int start, int end, URI owner, boolean count) {
log.info("non-admin query");
Collection<CloudProcess> result = null;
List<CloudProcess> items;
if (end > 0) {
int n = end - start;
if (n <= 0)
n = 0;
items = ofy().load().type(CloudProcess.class).filter("owner", owner.toString()).filter("topLevel", true).order("-start").offset(start).limit(n).list();
} else {
items = ofy().load().type(CloudProcess.class).filter("owner", owner.toString()).filter("topLevel", true).order("-start").offset(start).list();
}
result = new Collection<CloudProcess>(itemDao.clazz.getSimpleName(), super.path, items);
if (count) {
result.setTotal(ofy().load().type(CloudProcess.class).filter("owner", owner.toString()).filter("topLevel", true).count());
}
return result;
}
public Collection<CloudProcess> getServiceStackCollectionNonFinalized(String owner) {
ActionManager actionManager = new ActionManager();
//Retrieve all stack service actions
Collection<StackServiceAction> stackServiceActions = actionManager.getStackServiceAction();
List<CloudProcess> elements;
if(stackServiceActions.getElements().size() > 0)
{
List<String> uris = new ArrayList<String>(stackServiceActions.getElements().size());
for(StackServiceAction action: stackServiceActions.getElements())
{
uris.add(action.getUri().toString());
}
java.util.Collection<CloudProcess> collection = ofy().load().type(CloudProcess.class).filter("owner", owner).filter("action in", uris).filter("finalized", false).list();
elements = new ArrayList<CloudProcess>(collection);
}
else
{
elements = new ArrayList<CloudProcess>(0);
}
Collection<CloudProcess> processes = new Collection<CloudProcess>(itemDao.clazz.getSimpleName(), super.path, elements);
return processes;
}
}
final public static CloudProcessManager dao = new CloudProcessManager();
}
| true | true | public Response exec(@DefaultValue("Log") @QueryParam("action") String action, @QueryParam("name") String name,
@DefaultValue("hello world!") @QueryParam("arg") String arg, @QueryParam("parent") String parent, List<Variable> context) throws ClassNotFoundException, URISyntaxException {
n3phele.service.model.Context env = new n3phele.service.model.Context();
env.putValue("arg", arg);
Class<? extends Action> clazz = Class.forName("n3phele.service.actions." + action + "Action").asSubclass(Action.class);
//check parent here
if(parent != null && parent.trim().length() > 0){
URI parentURI = new URI(parent);
CloudProcess processParent = CloudProcessResource.dao.load(parentURI);
URI actionURI = processParent.getAction();
Action parentAction = ActionResource.dao.load(actionURI);
if(processParent.getState() != ActionState.RUNABLE) return Response.serverError().build();
if(parentAction instanceof StackServiceAction){
StackServiceAction serviceAction = (StackServiceAction)parentAction;
env.putAll(serviceAction.getContext());
env.remove("name");
for (Variable v : Helpers.safeIterator(context)) {
env.put(v.getName(), v);
}
if(env.getValue("service_name") != null)
name = env.getValue("service_name");
String description = env.getValue("description");
String[] argv;
String command = arg;
if(Helpers.isBlankOrNull(arg)) {
argv = new String[0];
command = "";
} else {
argv = arg.split("[\\s]+"); // FIXME - find a better regex for shell split
if(argv.length > 1)
command = argv[1];
else
command = argv[0];
}
Stack stack = new Stack(name, description);
stack.setCommandUri(command);
stack.setId(serviceAction.getNextStackNumber());
env.putValue("stackId", stack.getId());
CloudProcess p = ProcessLifecycle.mgr().createProcess(UserResource.toUser(securityContext), name, env, null, processParent, true, clazz);
ProcessLifecycle.mgr().init(p);
stack.setDeployProcess(p.getUri().toString());
serviceAction.addStack(stack);
ActionResource.dao.update(serviceAction);
return Response.created(p.getUri()).build();
}
}
for (Variable v : Helpers.safeIterator(context)) {
env.put(v.getName(), v);
}
if (clazz != null) {
CloudProcess p = ProcessLifecycle.mgr().createProcess(UserResource.toUser(securityContext), name, env, null, null, true, clazz);
ProcessLifecycle.mgr().init(p);
return Response.created(p.getUri()).build();
} else {
return Response.noContent().build();
}
}
| public Response exec(@DefaultValue("Log") @QueryParam("action") String action, @QueryParam("name") String name,
@DefaultValue("hello world!") @QueryParam("arg") String arg, @QueryParam("parent") String parent, List<Variable> context) throws ClassNotFoundException, URISyntaxException {
n3phele.service.model.Context env = new n3phele.service.model.Context();
env.putValue("arg", arg);
Class<? extends Action> clazz = Class.forName("n3phele.service.actions." + action + "Action").asSubclass(Action.class);
//check parent here
if(parent != null && parent.trim().length() > 0){
URI parentURI = new URI(parent);
CloudProcess processParent = CloudProcessResource.dao.load(parentURI);
URI actionURI = processParent.getAction();
Action parentAction = ActionResource.dao.load(actionURI);
if(processParent.getState() != ActionState.RUNABLE) return Response.serverError().build();
if(parentAction instanceof StackServiceAction){
StackServiceAction serviceAction = (StackServiceAction)parentAction;
env.putAll(serviceAction.getContext());
env.remove("name");
for (Variable v : Helpers.safeIterator(context)) {
env.put(v.getName(), v);
}
env.putValue("arg", arg);
if(env.getValue("service_name") != null)
name = env.getValue("service_name");
String description = env.getValue("description");
String[] argv;
String command = arg;
if(Helpers.isBlankOrNull(arg)) {
argv = new String[0];
command = "";
} else {
argv = arg.split("[\\s]+"); // FIXME - find a better regex for shell split
if(argv.length > 1)
command = argv[1];
else
command = argv[0];
}
Stack stack = new Stack(name, description);
stack.setCommandUri(command);
stack.setId(serviceAction.getNextStackNumber());
env.putValue("stackId", stack.getId());
CloudProcess p = ProcessLifecycle.mgr().createProcess(UserResource.toUser(securityContext), name, env, null, processParent, true, clazz);
ProcessLifecycle.mgr().init(p);
stack.setDeployProcess(p.getUri().toString());
serviceAction.addStack(stack);
ActionResource.dao.update(serviceAction);
return Response.created(p.getUri()).build();
}
}
for (Variable v : Helpers.safeIterator(context)) {
env.put(v.getName(), v);
}
if (clazz != null) {
CloudProcess p = ProcessLifecycle.mgr().createProcess(UserResource.toUser(securityContext), name, env, null, null, true, clazz);
ProcessLifecycle.mgr().init(p);
return Response.created(p.getUri()).build();
} else {
return Response.noContent().build();
}
}
|
diff --git a/src/tkj/android/homecontrol/mythmote/LocationEditor.java b/src/tkj/android/homecontrol/mythmote/LocationEditor.java
index ca7f63b..b672b92 100644
--- a/src/tkj/android/homecontrol/mythmote/LocationEditor.java
+++ b/src/tkj/android/homecontrol/mythmote/LocationEditor.java
@@ -1,198 +1,193 @@
package tkj.android.homecontrol.mythmote;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.widget.Button;
import android.widget.EditText;
/*
* Edits a FrontendLocation object
* */
public class LocationEditor extends Activity {
private FrontendLocation _location;
public LocationEditor(){ }
public LocationEditor(FrontendLocation location)
{
_location = location;
}
/** Called when the activity is first created.*/
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(this.getLayoutInflater().inflate(R.layout.locationeditor, null));
this.setupSaveButtonEvent(R.id.ButtonLocationSave);
this.setupCancelButtonEvent(R.id.ButtonLocationCancel);
int id = this.getIntent().getIntExtra(FrontendLocation.STR_ID, -1);
if(id != -1)
{
this._location = new FrontendLocation();
this._location.ID = id;
this._location.Name = this.getIntent().getStringExtra(FrontendLocation.STR_NAME);
this._location.Address = this.getIntent().getStringExtra(FrontendLocation.STR_ADDRESS);
this._location.Port = this.getIntent().getIntExtra(FrontendLocation.STR_PORT, 6456);
SetUiFromLocation();
}
}
private void SetUiFromLocation()
{
this.SetName(this._location.Name);
this.SetAddress(this._location.Address);
this.SetPort(this._location.Port);
}
private boolean Save()
{
if(this._location == null)
this._location = new FrontendLocation();
this._location.Name = this.GetName();
this._location.Address = this.GetAddress();
this._location.Port = this.GetPort();
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(R.string.error_input_str);
builder.setNeutralButton(R.string.ok_str, new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}});
- if(this._location.Name == null)
+ if(this._location.Name.trim().equals(""))
{
builder.setMessage(R.string.error_invalid_name_str);
builder.show();
}
- else if(this._location.Address == null)
+ else if(this._location.Address.trim().equals(""))
{
builder.setMessage(R.string.error_invalid_address_str);
builder.show();
}
-// else if(this._location.Port < 0)
-// {
-// builder.setMessage(R.string.error_invalid_port_str);
-// builder.show();
-// }
else
{
//set default port if port was not set.
if(this._location.Port <= 0)
this._location.Port = MythCom.DEFAULT_MYTH_PORT;
LocationDbAdapter adapter = new LocationDbAdapter(this);
adapter.open();
if(this._location.ID == -1)
{
this._location.ID = (int) adapter.createFrontendLocation(this._location.Name, this._location.Address, this._location.Port);
}
else
{
return adapter.updateFrontendLocation(this._location.ID, this._location.Name, this._location.Address, this._location.Port);
}
adapter.close();
return true;
}
return false;
}
private void SaveAndExit()
{
//only exit if save is successful.
if(Save())
this.finish();
}
private final String GetName()
{
return this.GetTextBoxText(R.id.EditTextLocationName);
}
private final String GetAddress()
{
return this.GetTextBoxText(R.id.EditTextAddress);
}
private final int GetPort()
{
try
{
return Integer.parseInt(this.GetTextBoxText(R.id.EditTextPort));
}
catch(NumberFormatException e)
{
return -1;
}
}
private final void SetName(String name)
{
this.SetTextBoxText(R.id.EditTextLocationName, name);
}
private final void SetAddress(String address)
{
this.SetTextBoxText(R.id.EditTextAddress, address);
}
private final void SetPort(int port)
{
this.SetTextBoxText(R.id.EditTextPort, Integer.toString(port));
}
private final String GetTextBoxText(int textBoxViewId)
{
final EditText text = (EditText)this.findViewById(textBoxViewId);
return text.getText().toString();
}
private final void SetTextBoxText(int textBoxViewId, String text)
{
final EditText textBox = (EditText)this.findViewById(textBoxViewId);
textBox.setText(text);
}
private final void setupSaveButtonEvent(int buttonViewId)
{
final Button button = (Button) this.findViewById(buttonViewId);
button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
//save location and exit
SaveAndExit();
}
});
}
private final void setupCancelButtonEvent(int buttonViewId)
{
final Button button = (Button) this.findViewById(buttonViewId);
button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
//just exit
finish();
}
});
}
}
| false | true | private boolean Save()
{
if(this._location == null)
this._location = new FrontendLocation();
this._location.Name = this.GetName();
this._location.Address = this.GetAddress();
this._location.Port = this.GetPort();
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(R.string.error_input_str);
builder.setNeutralButton(R.string.ok_str, new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}});
if(this._location.Name == null)
{
builder.setMessage(R.string.error_invalid_name_str);
builder.show();
}
else if(this._location.Address == null)
{
builder.setMessage(R.string.error_invalid_address_str);
builder.show();
}
// else if(this._location.Port < 0)
// {
// builder.setMessage(R.string.error_invalid_port_str);
// builder.show();
// }
else
{
//set default port if port was not set.
if(this._location.Port <= 0)
this._location.Port = MythCom.DEFAULT_MYTH_PORT;
LocationDbAdapter adapter = new LocationDbAdapter(this);
adapter.open();
if(this._location.ID == -1)
{
this._location.ID = (int) adapter.createFrontendLocation(this._location.Name, this._location.Address, this._location.Port);
}
else
{
return adapter.updateFrontendLocation(this._location.ID, this._location.Name, this._location.Address, this._location.Port);
}
adapter.close();
return true;
}
return false;
}
| private boolean Save()
{
if(this._location == null)
this._location = new FrontendLocation();
this._location.Name = this.GetName();
this._location.Address = this.GetAddress();
this._location.Port = this.GetPort();
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(R.string.error_input_str);
builder.setNeutralButton(R.string.ok_str, new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}});
if(this._location.Name.trim().equals(""))
{
builder.setMessage(R.string.error_invalid_name_str);
builder.show();
}
else if(this._location.Address.trim().equals(""))
{
builder.setMessage(R.string.error_invalid_address_str);
builder.show();
}
else
{
//set default port if port was not set.
if(this._location.Port <= 0)
this._location.Port = MythCom.DEFAULT_MYTH_PORT;
LocationDbAdapter adapter = new LocationDbAdapter(this);
adapter.open();
if(this._location.ID == -1)
{
this._location.ID = (int) adapter.createFrontendLocation(this._location.Name, this._location.Address, this._location.Port);
}
else
{
return adapter.updateFrontendLocation(this._location.ID, this._location.Name, this._location.Address, this._location.Port);
}
adapter.close();
return true;
}
return false;
}
|
diff --git a/spock-core/src/main/java/spock/util/concurrent/PollingConditions.java b/spock-core/src/main/java/spock/util/concurrent/PollingConditions.java
index f2d75bde..c867b231 100644
--- a/spock-core/src/main/java/spock/util/concurrent/PollingConditions.java
+++ b/spock-core/src/main/java/spock/util/concurrent/PollingConditions.java
@@ -1,191 +1,191 @@
/*
* Copyright 2012 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package spock.util.concurrent;
import groovy.lang.Closure;
import org.spockframework.lang.ConditionBlock;
import org.spockframework.runtime.GroovyRuntimeUtil;
import org.spockframework.runtime.SpockTimeoutError;
import org.spockframework.util.Beta;
/**
* Repeatedly evaluates one or more conditions until they are satisfied or a timeout has elapsed.
* The timeout and delays between evaluation attempts are configurable. All durations are in seconds.
*
* <p>Usage example:</p>
*
* <pre>
* def conditions = new PollingConditions(timeout: 10, initialDelay: 1.5, factor: 1.25)
* def machine = new Machine()
*
* when:
* machine.start()
*
* then:
* conditions.eventually {
* assert machine.temperature >= 100
* assert machine.efficiency >= 0.9
* }
* </pre>
*/
@Beta
public class PollingConditions {
private double timeout = 1;
private double initialDelay = 0;
private double delay = 0.1;
private double factor = 1.0;
/**
* Returns the timeout (in seconds) until which the conditions have to be satisfied.
* Defaults to one second.
*
* @return the timeout (in seconds) until which the conditions have to be satisfied
*/
public double getTimeout() {
return timeout;
}
/**
* Sets the timeout (in seconds) until which the conditions have to be satisfied.
* Defaults to one second.
*
* @param seconds the timeout (in seconds) until which the conditions have to be satisfied
*/
public void setTimeout(double seconds) {
timeout = seconds;
}
/**
* Returns the initial delay (in seconds) before first evaluating the conditions.
* Defaults to zero seconds.
*/
public double getInitialDelay() {
return initialDelay;
}
/**
* Sets the initial delay (in seconds) before first evaluating the conditions.
* Defaults to zero seconds.
*
* @param seconds the initial delay (in seconds) before first evaluating the conditions
*/
public void setInitialDelay(double seconds) {
initialDelay = seconds;
}
/**
* Returns the delay (in seconds) between successive evaluations of the conditions.
* Defaults to 0.1 seconds.
*/
public double getDelay() {
return delay;
}
/**
* Sets the delay (in seconds) between successive evaluations of the conditions.
* Defaults to 0.1 seconds.
*
* @param seconds the delay (in seconds) between successive evaluations of the conditions.
*/
public void setDelay(double seconds) {
this.delay = seconds;
}
/**
* Returns the factor by which the delay grows (or shrinks) after each evaluation of the conditions.
* Defaults to 1.
*/
public double getFactor() {
return factor;
}
/**
* Sets the factor by which the delay grows (or shrinks) after each evaluation of the conditions.
* Defaults to 1.
*
* @param factor the factor by which the delay grows (or shrinks) after each evaluation of the conditions
*/
public void setFactor(double factor) {
this.factor = factor;
}
/**
* Repeatedly evaluates the specified conditions until they are satisfied or the timeout has elapsed.
*
* @param conditions the conditions to evaluate
*
* @throws InterruptedException if evaluation is interrupted
*/
@ConditionBlock
public void eventually(Closure<?> conditions) throws InterruptedException {
within(timeout, conditions);
}
/**
* Repeatedly evaluates the specified conditions until they are satisfied or the specified timeout (in seconds) has elapsed.
*
* @param conditions the conditions to evaluate
*
* @throws InterruptedException if evaluation is interrupted
*/
@ConditionBlock
public void within(double seconds, Closure<?> conditions) throws InterruptedException {
long timeoutMillis = toMillis(seconds);
long start = System.currentTimeMillis();
long lastAttempt = 0;
Thread.sleep(toMillis(initialDelay));
long currDelay = toMillis(delay);
int attempts = 0;
while(true) {
try {
attempts++;
lastAttempt = System.currentTimeMillis();
GroovyRuntimeUtil.invokeClosure(conditions);
return;
} catch (AssertionError e) {
long elapsedTime = lastAttempt - start;
if (elapsedTime >= timeoutMillis) {
String msg = String.format("Condition not satisfied after %1.2f seconds and %d attempts", elapsedTime / 1000d, attempts);
- throw new SpockTimeoutError(seconds, msg);
+ throw new SpockTimeoutError(seconds, msg, e);
}
Thread.sleep(Math.min(currDelay, start + timeoutMillis - System.currentTimeMillis()));
currDelay *= factor;
}
}
}
/**
* Alias for {@link #eventually(groovy.lang.Closure)}.
*/
@ConditionBlock
public void call(Closure<?> conditions) throws InterruptedException {
eventually(conditions);
}
/**
* Alias for {@link #within(double, groovy.lang.Closure)}.
*/
@ConditionBlock
public void call(double seconds, Closure<?> conditions) throws InterruptedException {
within(seconds, conditions);
}
private long toMillis(double seconds) {
return (long) (seconds * 1000);
}
}
| true | true | public void within(double seconds, Closure<?> conditions) throws InterruptedException {
long timeoutMillis = toMillis(seconds);
long start = System.currentTimeMillis();
long lastAttempt = 0;
Thread.sleep(toMillis(initialDelay));
long currDelay = toMillis(delay);
int attempts = 0;
while(true) {
try {
attempts++;
lastAttempt = System.currentTimeMillis();
GroovyRuntimeUtil.invokeClosure(conditions);
return;
} catch (AssertionError e) {
long elapsedTime = lastAttempt - start;
if (elapsedTime >= timeoutMillis) {
String msg = String.format("Condition not satisfied after %1.2f seconds and %d attempts", elapsedTime / 1000d, attempts);
throw new SpockTimeoutError(seconds, msg);
}
Thread.sleep(Math.min(currDelay, start + timeoutMillis - System.currentTimeMillis()));
currDelay *= factor;
}
}
}
| public void within(double seconds, Closure<?> conditions) throws InterruptedException {
long timeoutMillis = toMillis(seconds);
long start = System.currentTimeMillis();
long lastAttempt = 0;
Thread.sleep(toMillis(initialDelay));
long currDelay = toMillis(delay);
int attempts = 0;
while(true) {
try {
attempts++;
lastAttempt = System.currentTimeMillis();
GroovyRuntimeUtil.invokeClosure(conditions);
return;
} catch (AssertionError e) {
long elapsedTime = lastAttempt - start;
if (elapsedTime >= timeoutMillis) {
String msg = String.format("Condition not satisfied after %1.2f seconds and %d attempts", elapsedTime / 1000d, attempts);
throw new SpockTimeoutError(seconds, msg, e);
}
Thread.sleep(Math.min(currDelay, start + timeoutMillis - System.currentTimeMillis()));
currDelay *= factor;
}
}
}
|
diff --git a/src/starparty/utilities/FontLoader.java b/src/starparty/utilities/FontLoader.java
index 35bc49c..ad30e43 100644
--- a/src/starparty/utilities/FontLoader.java
+++ b/src/starparty/utilities/FontLoader.java
@@ -1,50 +1,50 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package starparty.utilities;
import java.awt.Font;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
import org.newdawn.slick.UnicodeFont;
import org.newdawn.slick.font.effects.ColorEffect;
/**
*
* @author Tyler
*/
public class FontLoader {
private static Map<String, UnicodeFont> cache = new HashMap<String, UnicodeFont>();
public static UnicodeFont load(String name, int size, boolean bold) {
String id = name + "-" + size + "-" + bold;
UnicodeFont font = null;
- if (cache.containsKey(id)) {
- return cache.get(id);
+ if ((font = cache.get(id)) != null) {
+ return font;
}
try {
Font baseFont = Font.createFont(Font.TRUETYPE_FONT, new File("resources/font/" + name));
baseFont.deriveFont(java.awt.Font.PLAIN, 12);
int style = (bold ? java.awt.Font.BOLD : java.awt.Font.PLAIN);
font = new UnicodeFont(baseFont.deriveFont(style, size));
font.addAsciiGlyphs();
font.getEffects().add(new ColorEffect(java.awt.Color.WHITE));
font.loadGlyphs();
} catch (Exception e) {
System.out.println("Error loading font: " + name);
e.printStackTrace();
}
cache.put(id, font);
return font;
}
public static UnicodeFont load(String name, int size) {
return load(name, size, false);
}
}
| true | true | public static UnicodeFont load(String name, int size, boolean bold) {
String id = name + "-" + size + "-" + bold;
UnicodeFont font = null;
if (cache.containsKey(id)) {
return cache.get(id);
}
try {
Font baseFont = Font.createFont(Font.TRUETYPE_FONT, new File("resources/font/" + name));
baseFont.deriveFont(java.awt.Font.PLAIN, 12);
int style = (bold ? java.awt.Font.BOLD : java.awt.Font.PLAIN);
font = new UnicodeFont(baseFont.deriveFont(style, size));
font.addAsciiGlyphs();
font.getEffects().add(new ColorEffect(java.awt.Color.WHITE));
font.loadGlyphs();
} catch (Exception e) {
System.out.println("Error loading font: " + name);
e.printStackTrace();
}
cache.put(id, font);
return font;
}
| public static UnicodeFont load(String name, int size, boolean bold) {
String id = name + "-" + size + "-" + bold;
UnicodeFont font = null;
if ((font = cache.get(id)) != null) {
return font;
}
try {
Font baseFont = Font.createFont(Font.TRUETYPE_FONT, new File("resources/font/" + name));
baseFont.deriveFont(java.awt.Font.PLAIN, 12);
int style = (bold ? java.awt.Font.BOLD : java.awt.Font.PLAIN);
font = new UnicodeFont(baseFont.deriveFont(style, size));
font.addAsciiGlyphs();
font.getEffects().add(new ColorEffect(java.awt.Color.WHITE));
font.loadGlyphs();
} catch (Exception e) {
System.out.println("Error loading font: " + name);
e.printStackTrace();
}
cache.put(id, font);
return font;
}
|
diff --git a/org.eclipse.egit.ui/src/org/eclipse/egit/ui/internal/synchronize/model/GitModelCache.java b/org.eclipse.egit.ui/src/org/eclipse/egit/ui/internal/synchronize/model/GitModelCache.java
index fc22c5ec..b51d27b6 100644
--- a/org.eclipse.egit.ui/src/org/eclipse/egit/ui/internal/synchronize/model/GitModelCache.java
+++ b/org.eclipse.egit.ui/src/org/eclipse/egit/ui/internal/synchronize/model/GitModelCache.java
@@ -1,220 +1,220 @@
/*******************************************************************************
* Copyright (C) 2010, Dariusz Luksza <[email protected]>
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*******************************************************************************/
package org.eclipse.egit.ui.internal.synchronize.model;
import static org.eclipse.compare.structuremergeviewer.Differencer.RIGHT;
import static org.eclipse.jgit.lib.FileMode.MISSING;
import static org.eclipse.jgit.lib.FileMode.TREE;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.Path;
import org.eclipse.egit.ui.Activator;
import org.eclipse.egit.ui.UIText;
import org.eclipse.jgit.dircache.DirCache;
import org.eclipse.jgit.dircache.DirCacheEntry;
import org.eclipse.jgit.dircache.DirCacheIterator;
import org.eclipse.jgit.lib.Constants;
import org.eclipse.jgit.lib.ObjectId;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.revwalk.RevCommit;
import org.eclipse.jgit.revwalk.RevWalk;
import org.eclipse.jgit.treewalk.TreeWalk;
/**
* Git cache representation in EGit Change Set
*/
public class GitModelCache extends GitModelObjectContainer {
/**
* NTH of {@link DirCacheIterator}
*/
protected int dirCacheIteratorNth;
private final FileModelFactory fileFactory;
private final Map<IPath, GitModelCacheTree> cacheTreeMap;
private static final int BASE_NTH = 0;
private static final int REMOTE_NTH = 1;
/**
* This interface enables creating proper instance of {@link GitModelBlob}
* for cached and working files. In case of working files the left side
* content of Compare View is loaded from local hard drive.
*/
protected interface FileModelFactory {
/**
* Creates proper instance of {@link GitModelBlob} for cache and working
* tree model representation
*
* @param parent
* parent object
* @param commit
* last {@link RevCommit} in repository
* @param repoId
* {@link ObjectId} of blob in repository
* @param cacheId
* {@link ObjectId} of blob in cache
* @param location
* of blob
* @return instance of {@link GitModelBlob}
* @throws IOException
*/
GitModelBlob createFileModel(GitModelObjectContainer parent,
RevCommit commit, ObjectId repoId, ObjectId cacheId, IPath location)
throws IOException;
}
/**
* Constructs model node that represents current status of Git cache.
*
* @param parent
* parent object
* @param baseCommit
* last {@link RevCommit} in repository
* @throws IOException
*/
public GitModelCache(GitModelObject parent, RevCommit baseCommit)
throws IOException {
this(parent, baseCommit, new FileModelFactory() {
public GitModelBlob createFileModel(
GitModelObjectContainer modelParent, RevCommit commit,
ObjectId repoId, ObjectId cacheId, IPath location)
throws IOException {
return new GitModelCacheFile(modelParent, commit, repoId,
cacheId, location);
}
});
}
/**
* @param parent
* @param baseCommit
* @param fileFactory
* @throws IOException
*/
protected GitModelCache(GitModelObject parent, RevCommit baseCommit,
FileModelFactory fileFactory) throws IOException {
super(parent, baseCommit, RIGHT);
this.fileFactory = fileFactory;
cacheTreeMap = new HashMap<IPath, GitModelCacheTree>();
}
@Override
public String getName() {
return UIText.GitModelIndex_index;
}
protected GitModelObject[] getChildrenImpl() {
List<GitModelObject> result = new ArrayList<GitModelObject>();
try {
TreeWalk tw = createAndConfigureTreeWalk();
while (tw.next()) {
GitModelObject entry = extractFromCache(tw);
if (entry == null)
continue;
result.add(entry);
}
} catch (IOException e) {
Activator.logError(e.getMessage(), e);
}
return result.toArray(new GitModelObject[result.size()]);
}
/**
* Creates and configures {@link TreeWalk} instance for
* {@link GitModelCache#getChildrenImpl()} method. It is IMPORTANT to add
* tree that will be used as a base as first, remote tree should be added as
* second; {@link GitModelCache#dirCacheIteratorNth} should be set with
* value of NTH that corresponds with {@link DirCacheIterator}.
*
* @return configured instance of TreeW
* @throws IOException
*/
protected TreeWalk createAndConfigureTreeWalk() throws IOException {
TreeWalk tw = createTreeWalk();
tw.setRecursive(true);
Repository repo = getRepository();
DirCache index = repo.readDirCache();
ObjectId headId = repo.getRef(Constants.HEAD).getObjectId();
tw.addTree(new RevWalk(repo).parseTree(headId));
tw.addTree(new DirCacheIterator(index));
dirCacheIteratorNth = 1;
return tw;
}
private GitModelObject extractFromCache(TreeWalk tw) throws IOException {
DirCacheIterator cacheIterator = tw.getTree(dirCacheIteratorNth,
DirCacheIterator.class);
if (cacheIterator == null)
return null;
DirCacheEntry cacheEntry = cacheIterator.getDirCacheEntry();
if (cacheEntry == null)
return null;
if (shouldIncludeEntry(tw)) {
- IPath path = new Path(tw.getPathString());
+ IPath path = getLocation().append(tw.getPathString());
ObjectId repoId = tw.getObjectId(BASE_NTH);
ObjectId cacheId = tw.getObjectId(REMOTE_NTH);
if (path.getFileExtension() == null)
return handleCacheTree(repoId, cacheId, path);
return fileFactory.createFileModel(this, baseCommit, repoId,
cacheId, path);
}
return null;
}
private boolean shouldIncludeEntry(TreeWalk tw) {
final int mHead = tw.getRawMode(BASE_NTH);
final int mCache = tw.getRawMode(REMOTE_NTH);
return mHead == MISSING.getBits() // initial add to cache
|| mCache == MISSING.getBits() // removed from cache
|| (mHead != mCache || (mCache != TREE.getBits() && !tw
.idEqual(BASE_NTH, REMOTE_NTH))); // modified
}
private GitModelObject handleCacheTree(ObjectId repoId, ObjectId cacheId,
IPath path) throws IOException {
GitModelCacheTree cacheTree = cacheTreeMap.get(path);
if (cacheTree == null) {
cacheTree = new GitModelCacheTree(this, baseCommit, repoId,
cacheId, path, fileFactory);
cacheTreeMap.put(path, cacheTree);
}
cacheTree.addChild(repoId, cacheId, path);
return cacheTree;
}
@Override
public IPath getLocation() {
return new Path(getRepository().getWorkTree().toString());
}
}
| true | true | private GitModelObject extractFromCache(TreeWalk tw) throws IOException {
DirCacheIterator cacheIterator = tw.getTree(dirCacheIteratorNth,
DirCacheIterator.class);
if (cacheIterator == null)
return null;
DirCacheEntry cacheEntry = cacheIterator.getDirCacheEntry();
if (cacheEntry == null)
return null;
if (shouldIncludeEntry(tw)) {
IPath path = new Path(tw.getPathString());
ObjectId repoId = tw.getObjectId(BASE_NTH);
ObjectId cacheId = tw.getObjectId(REMOTE_NTH);
if (path.getFileExtension() == null)
return handleCacheTree(repoId, cacheId, path);
return fileFactory.createFileModel(this, baseCommit, repoId,
cacheId, path);
}
return null;
}
| private GitModelObject extractFromCache(TreeWalk tw) throws IOException {
DirCacheIterator cacheIterator = tw.getTree(dirCacheIteratorNth,
DirCacheIterator.class);
if (cacheIterator == null)
return null;
DirCacheEntry cacheEntry = cacheIterator.getDirCacheEntry();
if (cacheEntry == null)
return null;
if (shouldIncludeEntry(tw)) {
IPath path = getLocation().append(tw.getPathString());
ObjectId repoId = tw.getObjectId(BASE_NTH);
ObjectId cacheId = tw.getObjectId(REMOTE_NTH);
if (path.getFileExtension() == null)
return handleCacheTree(repoId, cacheId, path);
return fileFactory.createFileModel(this, baseCommit, repoId,
cacheId, path);
}
return null;
}
|
diff --git a/src/com/android/launcher2/InstallShortcutReceiver.java b/src/com/android/launcher2/InstallShortcutReceiver.java
index 19b1c69d..82fb3d15 100644
--- a/src/com/android/launcher2/InstallShortcutReceiver.java
+++ b/src/com/android/launcher2/InstallShortcutReceiver.java
@@ -1,188 +1,188 @@
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.launcher2;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.widget.Toast;
import com.android.launcher.R;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;
public class InstallShortcutReceiver extends BroadcastReceiver {
public static final String ACTION_INSTALL_SHORTCUT =
"com.android.launcher.action.INSTALL_SHORTCUT";
public static final String NEW_APPS_PAGE_KEY = "apps.new.page";
public static final String NEW_APPS_LIST_KEY = "apps.new.list";
public static final int NEW_SHORTCUT_BOUNCE_DURATION = 450;
public static final int NEW_SHORTCUT_STAGGER_DELAY = 75;
private static final int INSTALL_SHORTCUT_SUCCESSFUL = 0;
private static final int INSTALL_SHORTCUT_IS_DUPLICATE = -1;
private static final int INSTALL_SHORTCUT_NO_SPACE = -2;
// A mime-type representing shortcut data
public static final String SHORTCUT_MIMETYPE =
"com.android.launcher/shortcut";
private final int[] mCoordinates = new int[2];
public void onReceive(Context context, Intent data) {
if (!ACTION_INSTALL_SHORTCUT.equals(data.getAction())) {
return;
}
String spKey = LauncherApplication.getSharedPreferencesKey();
SharedPreferences sp = context.getSharedPreferences(spKey, Context.MODE_PRIVATE);
final Intent intent = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_INTENT);
if (intent == null) {
return;
}
// This name is only used for comparisons and notifications, so fall back to activity name
// if not supplied
String name = data.getStringExtra(Intent.EXTRA_SHORTCUT_NAME);
if (name == null) {
try {
PackageManager pm = context.getPackageManager();
ActivityInfo info = pm.getActivityInfo(intent.getComponent(), 0);
name = info.loadLabel(pm).toString();
} catch (PackageManager.NameNotFoundException nnfe) {
return;
}
}
// Lock on the app so that we don't try and get the items while apps are being added
LauncherApplication app = (LauncherApplication) context.getApplicationContext();
final int[] result = {INSTALL_SHORTCUT_SUCCESSFUL};
boolean found = false;
synchronized (app) {
final ArrayList<ItemInfo> items = LauncherModel.getItemsInLocalCoordinates(context);
final boolean exists = LauncherModel.shortcutExists(context, name, intent);
// Try adding to the workspace screens incrementally, starting at the default or center
// screen and alternating between +1, -1, +2, -2, etc. (using ~ ceil(i/2f)*(-1)^(i-1))
final int screen = Launcher.DEFAULT_SCREEN;
for (int i = 0; i < (2 * Launcher.SCREEN_COUNT) + 1 && !found; ++i) {
int si = screen + (int) ((i / 2f) + 0.5f) * ((i % 2 == 1) ? 1 : -1);
if (0 <= si && si < Launcher.SCREEN_COUNT) {
found = installShortcut(context, data, items, name, intent, si, exists, sp,
result);
}
}
}
// We only report error messages (duplicate shortcut or out of space) as the add-animation
// will provide feedback otherwise
if (!found) {
if (result[0] == INSTALL_SHORTCUT_NO_SPACE) {
- Toast.makeText(context, context.getString(R.string.out_of_space),
+ Toast.makeText(context, context.getString(R.string.completely_out_of_space),
Toast.LENGTH_SHORT).show();
} else if (result[0] == INSTALL_SHORTCUT_IS_DUPLICATE) {
Toast.makeText(context, context.getString(R.string.shortcut_duplicate, name),
Toast.LENGTH_SHORT).show();
}
}
}
private boolean installShortcut(Context context, Intent data, ArrayList<ItemInfo> items,
String name, Intent intent, final int screen, boolean shortcutExists,
final SharedPreferences sharedPrefs, int[] result) {
if (findEmptyCell(context, items, mCoordinates, screen)) {
if (intent != null) {
if (intent.getAction() == null) {
intent.setAction(Intent.ACTION_VIEW);
}
// By default, we allow for duplicate entries (located in
// different places)
boolean duplicate = data.getBooleanExtra(Launcher.EXTRA_SHORTCUT_DUPLICATE, true);
if (duplicate || !shortcutExists) {
// If the new app is going to fall into the same page as before, then just
// continue adding to the current page
int newAppsScreen = sharedPrefs.getInt(NEW_APPS_PAGE_KEY, screen);
Set<String> newApps = new HashSet<String>();
if (newAppsScreen == screen) {
newApps = sharedPrefs.getStringSet(NEW_APPS_LIST_KEY, newApps);
}
newApps.add(intent.toUri(0).toString());
final Set<String> savedNewApps = newApps;
new Thread("setNewAppsThread") {
public void run() {
sharedPrefs.edit()
.putInt(NEW_APPS_PAGE_KEY, screen)
.putStringSet(NEW_APPS_LIST_KEY, savedNewApps)
.commit();
}
}.start();
// Update the Launcher db
LauncherApplication app = (LauncherApplication) context.getApplicationContext();
ShortcutInfo info = app.getModel().addShortcut(context, data,
LauncherSettings.Favorites.CONTAINER_DESKTOP, screen,
mCoordinates[0], mCoordinates[1], true);
if (info == null) {
return false;
}
} else {
result[0] = INSTALL_SHORTCUT_IS_DUPLICATE;
}
return true;
}
} else {
result[0] = INSTALL_SHORTCUT_NO_SPACE;
}
return false;
}
private static boolean findEmptyCell(Context context, ArrayList<ItemInfo> items, int[] xy,
int screen) {
final int xCount = LauncherModel.getCellCountX();
final int yCount = LauncherModel.getCellCountY();
boolean[][] occupied = new boolean[xCount][yCount];
ItemInfo item = null;
int cellX, cellY, spanX, spanY;
for (int i = 0; i < items.size(); ++i) {
item = items.get(i);
if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP) {
if (item.screen == screen) {
cellX = item.cellX;
cellY = item.cellY;
spanX = item.spanX;
spanY = item.spanY;
for (int x = cellX; x < cellX + spanX && x < xCount; x++) {
for (int y = cellY; y < cellY + spanY && y < yCount; y++) {
occupied[x][y] = true;
}
}
}
}
}
return CellLayout.findVacantCell(xy, 1, 1, xCount, yCount, occupied);
}
}
| true | true | public void onReceive(Context context, Intent data) {
if (!ACTION_INSTALL_SHORTCUT.equals(data.getAction())) {
return;
}
String spKey = LauncherApplication.getSharedPreferencesKey();
SharedPreferences sp = context.getSharedPreferences(spKey, Context.MODE_PRIVATE);
final Intent intent = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_INTENT);
if (intent == null) {
return;
}
// This name is only used for comparisons and notifications, so fall back to activity name
// if not supplied
String name = data.getStringExtra(Intent.EXTRA_SHORTCUT_NAME);
if (name == null) {
try {
PackageManager pm = context.getPackageManager();
ActivityInfo info = pm.getActivityInfo(intent.getComponent(), 0);
name = info.loadLabel(pm).toString();
} catch (PackageManager.NameNotFoundException nnfe) {
return;
}
}
// Lock on the app so that we don't try and get the items while apps are being added
LauncherApplication app = (LauncherApplication) context.getApplicationContext();
final int[] result = {INSTALL_SHORTCUT_SUCCESSFUL};
boolean found = false;
synchronized (app) {
final ArrayList<ItemInfo> items = LauncherModel.getItemsInLocalCoordinates(context);
final boolean exists = LauncherModel.shortcutExists(context, name, intent);
// Try adding to the workspace screens incrementally, starting at the default or center
// screen and alternating between +1, -1, +2, -2, etc. (using ~ ceil(i/2f)*(-1)^(i-1))
final int screen = Launcher.DEFAULT_SCREEN;
for (int i = 0; i < (2 * Launcher.SCREEN_COUNT) + 1 && !found; ++i) {
int si = screen + (int) ((i / 2f) + 0.5f) * ((i % 2 == 1) ? 1 : -1);
if (0 <= si && si < Launcher.SCREEN_COUNT) {
found = installShortcut(context, data, items, name, intent, si, exists, sp,
result);
}
}
}
// We only report error messages (duplicate shortcut or out of space) as the add-animation
// will provide feedback otherwise
if (!found) {
if (result[0] == INSTALL_SHORTCUT_NO_SPACE) {
Toast.makeText(context, context.getString(R.string.out_of_space),
Toast.LENGTH_SHORT).show();
} else if (result[0] == INSTALL_SHORTCUT_IS_DUPLICATE) {
Toast.makeText(context, context.getString(R.string.shortcut_duplicate, name),
Toast.LENGTH_SHORT).show();
}
}
}
| public void onReceive(Context context, Intent data) {
if (!ACTION_INSTALL_SHORTCUT.equals(data.getAction())) {
return;
}
String spKey = LauncherApplication.getSharedPreferencesKey();
SharedPreferences sp = context.getSharedPreferences(spKey, Context.MODE_PRIVATE);
final Intent intent = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_INTENT);
if (intent == null) {
return;
}
// This name is only used for comparisons and notifications, so fall back to activity name
// if not supplied
String name = data.getStringExtra(Intent.EXTRA_SHORTCUT_NAME);
if (name == null) {
try {
PackageManager pm = context.getPackageManager();
ActivityInfo info = pm.getActivityInfo(intent.getComponent(), 0);
name = info.loadLabel(pm).toString();
} catch (PackageManager.NameNotFoundException nnfe) {
return;
}
}
// Lock on the app so that we don't try and get the items while apps are being added
LauncherApplication app = (LauncherApplication) context.getApplicationContext();
final int[] result = {INSTALL_SHORTCUT_SUCCESSFUL};
boolean found = false;
synchronized (app) {
final ArrayList<ItemInfo> items = LauncherModel.getItemsInLocalCoordinates(context);
final boolean exists = LauncherModel.shortcutExists(context, name, intent);
// Try adding to the workspace screens incrementally, starting at the default or center
// screen and alternating between +1, -1, +2, -2, etc. (using ~ ceil(i/2f)*(-1)^(i-1))
final int screen = Launcher.DEFAULT_SCREEN;
for (int i = 0; i < (2 * Launcher.SCREEN_COUNT) + 1 && !found; ++i) {
int si = screen + (int) ((i / 2f) + 0.5f) * ((i % 2 == 1) ? 1 : -1);
if (0 <= si && si < Launcher.SCREEN_COUNT) {
found = installShortcut(context, data, items, name, intent, si, exists, sp,
result);
}
}
}
// We only report error messages (duplicate shortcut or out of space) as the add-animation
// will provide feedback otherwise
if (!found) {
if (result[0] == INSTALL_SHORTCUT_NO_SPACE) {
Toast.makeText(context, context.getString(R.string.completely_out_of_space),
Toast.LENGTH_SHORT).show();
} else if (result[0] == INSTALL_SHORTCUT_IS_DUPLICATE) {
Toast.makeText(context, context.getString(R.string.shortcut_duplicate, name),
Toast.LENGTH_SHORT).show();
}
}
}
|
diff --git a/src/com/android/music/MediaPlaybackService.java b/src/com/android/music/MediaPlaybackService.java
index 6414eb4..2e30cb4 100644
--- a/src/com/android/music/MediaPlaybackService.java
+++ b/src/com/android/music/MediaPlaybackService.java
@@ -1,2192 +1,2194 @@
/*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.music;
import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.appwidget.AppWidgetManager;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.BroadcastReceiver;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.database.Cursor;
import android.database.sqlite.SQLiteException;
import android.graphics.Bitmap;
import android.media.audiofx.AudioEffect;
import android.media.AudioManager;
import android.media.AudioManager.OnAudioFocusChangeListener;
import android.media.MediaMetadataRetriever;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.RemoteControlClient;
import android.media.RemoteControlClient.MetadataEditor;
import android.net.Uri;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.PowerManager;
import android.os.SystemClock;
import android.os.PowerManager.WakeLock;
import android.provider.MediaStore;
import android.util.Log;
import android.widget.RemoteViews;
import android.widget.Toast;
import java.io.FileDescriptor;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.ref.WeakReference;
import java.util.Random;
import java.util.Vector;
/**
* Provides "background" audio playback capabilities, allowing the
* user to switch between activities without stopping playback.
*/
public class MediaPlaybackService extends Service {
/** used to specify whether enqueue() should start playing
* the new list of files right away, next or once all the currently
* queued files have been played
*/
public static final int NOW = 1;
public static final int NEXT = 2;
public static final int LAST = 3;
public static final int PLAYBACKSERVICE_STATUS = 1;
public static final int SHUFFLE_NONE = 0;
public static final int SHUFFLE_NORMAL = 1;
public static final int SHUFFLE_AUTO = 2;
public static final int REPEAT_NONE = 0;
public static final int REPEAT_CURRENT = 1;
public static final int REPEAT_ALL = 2;
public static final String PLAYSTATE_CHANGED = "com.android.music.playstatechanged";
public static final String META_CHANGED = "com.android.music.metachanged";
public static final String QUEUE_CHANGED = "com.android.music.queuechanged";
public static final String SERVICECMD = "com.android.music.musicservicecommand";
public static final String CMDNAME = "command";
public static final String CMDTOGGLEPAUSE = "togglepause";
public static final String CMDSTOP = "stop";
public static final String CMDPAUSE = "pause";
public static final String CMDPLAY = "play";
public static final String CMDPREVIOUS = "previous";
public static final String CMDNEXT = "next";
public static final String TOGGLEPAUSE_ACTION = "com.android.music.musicservicecommand.togglepause";
public static final String PAUSE_ACTION = "com.android.music.musicservicecommand.pause";
public static final String PREVIOUS_ACTION = "com.android.music.musicservicecommand.previous";
public static final String NEXT_ACTION = "com.android.music.musicservicecommand.next";
private static final int TRACK_ENDED = 1;
private static final int RELEASE_WAKELOCK = 2;
private static final int SERVER_DIED = 3;
private static final int FOCUSCHANGE = 4;
private static final int FADEDOWN = 5;
private static final int FADEUP = 6;
private static final int TRACK_WENT_TO_NEXT = 7;
private static final int MAX_HISTORY_SIZE = 100;
private MultiPlayer mPlayer;
private String mFileToPlay;
private int mShuffleMode = SHUFFLE_NONE;
private int mRepeatMode = REPEAT_NONE;
private int mMediaMountedCount = 0;
private long [] mAutoShuffleList = null;
private long [] mPlayList = null;
private int mPlayListLen = 0;
private Vector<Integer> mHistory = new Vector<Integer>(MAX_HISTORY_SIZE);
private Cursor mCursor;
private int mPlayPos = -1;
private int mNextPlayPos = -1;
private static final String LOGTAG = "MediaPlaybackService";
private final Shuffler mRand = new Shuffler();
private int mOpenFailedCounter = 0;
String[] mCursorCols = new String[] {
"audio._id AS _id", // index must match IDCOLIDX below
MediaStore.Audio.Media.ARTIST,
MediaStore.Audio.Media.ALBUM,
MediaStore.Audio.Media.TITLE,
MediaStore.Audio.Media.DATA,
MediaStore.Audio.Media.MIME_TYPE,
MediaStore.Audio.Media.ALBUM_ID,
MediaStore.Audio.Media.ARTIST_ID,
MediaStore.Audio.Media.IS_PODCAST, // index must match PODCASTCOLIDX below
MediaStore.Audio.Media.BOOKMARK // index must match BOOKMARKCOLIDX below
};
private final static int IDCOLIDX = 0;
private final static int PODCASTCOLIDX = 8;
private final static int BOOKMARKCOLIDX = 9;
private BroadcastReceiver mUnmountReceiver = null;
private WakeLock mWakeLock;
private int mServiceStartId = -1;
private boolean mServiceInUse = false;
private boolean mIsSupposedToBePlaying = false;
private boolean mQuietMode = false;
private AudioManager mAudioManager;
private boolean mQueueIsSaveable = true;
// used to track what type of audio focus loss caused the playback to pause
private boolean mPausedByTransientLossOfFocus = false;
private SharedPreferences mPreferences;
// We use this to distinguish between different cards when saving/restoring playlists.
// This will have to change if we want to support multiple simultaneous cards.
private int mCardId;
private MediaAppWidgetProvider mAppWidgetProvider = MediaAppWidgetProvider.getInstance();
// interval after which we stop the service when idle
private static final int IDLE_DELAY = 60000;
private RemoteControlClient mRemoteControlClient;
private Handler mMediaplayerHandler = new Handler() {
float mCurrentVolume = 1.0f;
@Override
public void handleMessage(Message msg) {
MusicUtils.debugLog("mMediaplayerHandler.handleMessage " + msg.what);
switch (msg.what) {
case FADEDOWN:
mCurrentVolume -= .05f;
if (mCurrentVolume > .2f) {
mMediaplayerHandler.sendEmptyMessageDelayed(FADEDOWN, 10);
} else {
mCurrentVolume = .2f;
}
mPlayer.setVolume(mCurrentVolume);
break;
case FADEUP:
mCurrentVolume += .01f;
if (mCurrentVolume < 1.0f) {
mMediaplayerHandler.sendEmptyMessageDelayed(FADEUP, 10);
} else {
mCurrentVolume = 1.0f;
}
mPlayer.setVolume(mCurrentVolume);
break;
case SERVER_DIED:
if (mIsSupposedToBePlaying) {
gotoNext(true);
} else {
// the server died when we were idle, so just
// reopen the same song (it will start again
// from the beginning though when the user
// restarts)
openCurrentAndNext();
}
break;
case TRACK_WENT_TO_NEXT:
mPlayPos = mNextPlayPos;
if (mCursor != null) {
mCursor.close();
mCursor = null;
}
mCursor = getCursorForId(mPlayList[mPlayPos]);
notifyChange(META_CHANGED);
updateNotification();
setNextTrack();
break;
case TRACK_ENDED:
if (mRepeatMode == REPEAT_CURRENT) {
seek(0);
play();
} else {
gotoNext(false);
}
break;
case RELEASE_WAKELOCK:
mWakeLock.release();
break;
case FOCUSCHANGE:
// This code is here so we can better synchronize it with the code that
// handles fade-in
switch (msg.arg1) {
case AudioManager.AUDIOFOCUS_LOSS:
Log.v(LOGTAG, "AudioFocus: received AUDIOFOCUS_LOSS");
if(isPlaying()) {
mPausedByTransientLossOfFocus = false;
}
pause();
break;
case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK:
mMediaplayerHandler.removeMessages(FADEUP);
mMediaplayerHandler.sendEmptyMessage(FADEDOWN);
break;
case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT:
Log.v(LOGTAG, "AudioFocus: received AUDIOFOCUS_LOSS_TRANSIENT");
if(isPlaying()) {
mPausedByTransientLossOfFocus = true;
}
pause();
break;
case AudioManager.AUDIOFOCUS_GAIN:
Log.v(LOGTAG, "AudioFocus: received AUDIOFOCUS_GAIN");
if(!isPlaying() && mPausedByTransientLossOfFocus) {
mPausedByTransientLossOfFocus = false;
mCurrentVolume = 0f;
mPlayer.setVolume(mCurrentVolume);
play(); // also queues a fade-in
} else {
mMediaplayerHandler.removeMessages(FADEDOWN);
mMediaplayerHandler.sendEmptyMessage(FADEUP);
}
break;
default:
Log.e(LOGTAG, "Unknown audio focus change code");
}
break;
default:
break;
}
}
};
private BroadcastReceiver mIntentReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
String cmd = intent.getStringExtra("command");
MusicUtils.debugLog("mIntentReceiver.onReceive " + action + " / " + cmd);
if (CMDNEXT.equals(cmd) || NEXT_ACTION.equals(action)) {
gotoNext(true);
} else if (CMDPREVIOUS.equals(cmd) || PREVIOUS_ACTION.equals(action)) {
prev();
} else if (CMDTOGGLEPAUSE.equals(cmd) || TOGGLEPAUSE_ACTION.equals(action)) {
if (isPlaying()) {
pause();
mPausedByTransientLossOfFocus = false;
} else {
play();
}
} else if (CMDPAUSE.equals(cmd) || PAUSE_ACTION.equals(action)) {
pause();
mPausedByTransientLossOfFocus = false;
} else if (CMDPLAY.equals(cmd)) {
play();
} else if (CMDSTOP.equals(cmd)) {
pause();
mPausedByTransientLossOfFocus = false;
seek(0);
} else if (MediaAppWidgetProvider.CMDAPPWIDGETUPDATE.equals(cmd)) {
// Someone asked us to refresh a set of specific widgets, probably
// because they were just added.
int[] appWidgetIds = intent.getIntArrayExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS);
mAppWidgetProvider.performUpdate(MediaPlaybackService.this, appWidgetIds);
}
}
};
private OnAudioFocusChangeListener mAudioFocusListener = new OnAudioFocusChangeListener() {
public void onAudioFocusChange(int focusChange) {
mMediaplayerHandler.obtainMessage(FOCUSCHANGE, focusChange, 0).sendToTarget();
}
};
public MediaPlaybackService() {
}
@Override
public void onCreate() {
super.onCreate();
mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
ComponentName rec = new ComponentName(getPackageName(),
MediaButtonIntentReceiver.class.getName());
mAudioManager.registerMediaButtonEventReceiver(rec);
// TODO update to new constructor
// mRemoteControlClient = new RemoteControlClient(rec);
// mAudioManager.registerRemoteControlClient(mRemoteControlClient);
//
// int flags = RemoteControlClient.FLAG_KEY_MEDIA_PREVIOUS
// | RemoteControlClient.FLAG_KEY_MEDIA_NEXT
// | RemoteControlClient.FLAG_KEY_MEDIA_PLAY
// | RemoteControlClient.FLAG_KEY_MEDIA_PAUSE
// | RemoteControlClient.FLAG_KEY_MEDIA_PLAY_PAUSE
// | RemoteControlClient.FLAG_KEY_MEDIA_STOP;
// mRemoteControlClient.setTransportControlFlags(flags);
mPreferences = getSharedPreferences("Music", MODE_WORLD_READABLE | MODE_WORLD_WRITEABLE);
mCardId = MusicUtils.getCardId(this);
registerExternalStorageListener();
// Needs to be done in this thread, since otherwise ApplicationContext.getPowerManager() crashes.
mPlayer = new MultiPlayer();
mPlayer.setHandler(mMediaplayerHandler);
reloadQueue();
notifyChange(QUEUE_CHANGED);
notifyChange(META_CHANGED);
IntentFilter commandFilter = new IntentFilter();
commandFilter.addAction(SERVICECMD);
commandFilter.addAction(TOGGLEPAUSE_ACTION);
commandFilter.addAction(PAUSE_ACTION);
commandFilter.addAction(NEXT_ACTION);
commandFilter.addAction(PREVIOUS_ACTION);
registerReceiver(mIntentReceiver, commandFilter);
PowerManager pm = (PowerManager)getSystemService(Context.POWER_SERVICE);
mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, this.getClass().getName());
mWakeLock.setReferenceCounted(false);
// If the service was idle, but got killed before it stopped itself, the
// system will relaunch it. Make sure it gets stopped again in that case.
Message msg = mDelayedStopHandler.obtainMessage();
mDelayedStopHandler.sendMessageDelayed(msg, IDLE_DELAY);
}
@Override
public void onDestroy() {
// Check that we're not being destroyed while something is still playing.
if (isPlaying()) {
Log.e(LOGTAG, "Service being destroyed while still playing.");
}
// release all MediaPlayer resources, including the native player and wakelocks
Intent i = new Intent(AudioEffect.ACTION_CLOSE_AUDIO_EFFECT_CONTROL_SESSION);
i.putExtra(AudioEffect.EXTRA_AUDIO_SESSION, getAudioSessionId());
i.putExtra(AudioEffect.EXTRA_PACKAGE_NAME, getPackageName());
sendBroadcast(i);
mPlayer.release();
mPlayer = null;
mAudioManager.abandonAudioFocus(mAudioFocusListener);
//mAudioManager.unregisterRemoteControlClient(mRemoteControlClient);
// make sure there aren't any other messages coming
mDelayedStopHandler.removeCallbacksAndMessages(null);
mMediaplayerHandler.removeCallbacksAndMessages(null);
if (mCursor != null) {
mCursor.close();
mCursor = null;
}
unregisterReceiver(mIntentReceiver);
if (mUnmountReceiver != null) {
unregisterReceiver(mUnmountReceiver);
mUnmountReceiver = null;
}
mWakeLock.release();
super.onDestroy();
}
private final char hexdigits [] = new char [] {
'0', '1', '2', '3',
'4', '5', '6', '7',
'8', '9', 'a', 'b',
'c', 'd', 'e', 'f'
};
private void saveQueue(boolean full) {
if (!mQueueIsSaveable) {
return;
}
Editor ed = mPreferences.edit();
//long start = System.currentTimeMillis();
if (full) {
StringBuilder q = new StringBuilder();
// The current playlist is saved as a list of "reverse hexadecimal"
// numbers, which we can generate faster than normal decimal or
// hexadecimal numbers, which in turn allows us to save the playlist
// more often without worrying too much about performance.
// (saving the full state takes about 40 ms under no-load conditions
// on the phone)
int len = mPlayListLen;
for (int i = 0; i < len; i++) {
long n = mPlayList[i];
if (n < 0) {
continue;
} else if (n == 0) {
q.append("0;");
} else {
while (n != 0) {
int digit = (int)(n & 0xf);
n >>>= 4;
q.append(hexdigits[digit]);
}
q.append(";");
}
}
//Log.i("@@@@ service", "created queue string in " + (System.currentTimeMillis() - start) + " ms");
ed.putString("queue", q.toString());
ed.putInt("cardid", mCardId);
if (mShuffleMode != SHUFFLE_NONE) {
// In shuffle mode we need to save the history too
len = mHistory.size();
q.setLength(0);
for (int i = 0; i < len; i++) {
int n = mHistory.get(i);
if (n == 0) {
q.append("0;");
} else {
while (n != 0) {
int digit = (n & 0xf);
n >>>= 4;
q.append(hexdigits[digit]);
}
q.append(";");
}
}
ed.putString("history", q.toString());
}
}
ed.putInt("curpos", mPlayPos);
if (mPlayer.isInitialized()) {
ed.putLong("seekpos", mPlayer.position());
}
ed.putInt("repeatmode", mRepeatMode);
ed.putInt("shufflemode", mShuffleMode);
SharedPreferencesCompat.apply(ed);
//Log.i("@@@@ service", "saved state in " + (System.currentTimeMillis() - start) + " ms");
}
private void reloadQueue() {
String q = null;
boolean newstyle = false;
int id = mCardId;
if (mPreferences.contains("cardid")) {
newstyle = true;
id = mPreferences.getInt("cardid", ~mCardId);
}
if (id == mCardId) {
// Only restore the saved playlist if the card is still
// the same one as when the playlist was saved
q = mPreferences.getString("queue", "");
}
int qlen = q != null ? q.length() : 0;
if (qlen > 1) {
//Log.i("@@@@ service", "loaded queue: " + q);
int plen = 0;
int n = 0;
int shift = 0;
for (int i = 0; i < qlen; i++) {
char c = q.charAt(i);
if (c == ';') {
ensurePlayListCapacity(plen + 1);
mPlayList[plen] = n;
plen++;
n = 0;
shift = 0;
} else {
if (c >= '0' && c <= '9') {
n += ((c - '0') << shift);
} else if (c >= 'a' && c <= 'f') {
n += ((10 + c - 'a') << shift);
} else {
// bogus playlist data
plen = 0;
break;
}
shift += 4;
}
}
mPlayListLen = plen;
int pos = mPreferences.getInt("curpos", 0);
if (pos < 0 || pos >= mPlayListLen) {
// The saved playlist is bogus, discard it
mPlayListLen = 0;
return;
}
mPlayPos = pos;
// When reloadQueue is called in response to a card-insertion,
// we might not be able to query the media provider right away.
// To deal with this, try querying for the current file, and if
// that fails, wait a while and try again. If that too fails,
// assume there is a problem and don't restore the state.
Cursor crsr = MusicUtils.query(this,
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
new String [] {"_id"}, "_id=" + mPlayList[mPlayPos] , null, null);
if (crsr == null || crsr.getCount() == 0) {
// wait a bit and try again
SystemClock.sleep(3000);
crsr = getContentResolver().query(
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
mCursorCols, "_id=" + mPlayList[mPlayPos] , null, null);
}
if (crsr != null) {
crsr.close();
}
// Make sure we don't auto-skip to the next song, since that
// also starts playback. What could happen in that case is:
// - music is paused
// - go to UMS and delete some files, including the currently playing one
// - come back from UMS
// (time passes)
// - music app is killed for some reason (out of memory)
// - music service is restarted, service restores state, doesn't find
// the "current" file, goes to the next and: playback starts on its
// own, potentially at some random inconvenient time.
mOpenFailedCounter = 20;
mQuietMode = true;
openCurrentAndNext();
mQuietMode = false;
if (!mPlayer.isInitialized()) {
// couldn't restore the saved state
mPlayListLen = 0;
return;
}
long seekpos = mPreferences.getLong("seekpos", 0);
seek(seekpos >= 0 && seekpos < duration() ? seekpos : 0);
Log.d(LOGTAG, "restored queue, currently at position "
+ position() + "/" + duration()
+ " (requested " + seekpos + ")");
int repmode = mPreferences.getInt("repeatmode", REPEAT_NONE);
if (repmode != REPEAT_ALL && repmode != REPEAT_CURRENT) {
repmode = REPEAT_NONE;
}
mRepeatMode = repmode;
int shufmode = mPreferences.getInt("shufflemode", SHUFFLE_NONE);
if (shufmode != SHUFFLE_AUTO && shufmode != SHUFFLE_NORMAL) {
shufmode = SHUFFLE_NONE;
}
if (shufmode != SHUFFLE_NONE) {
// in shuffle mode we need to restore the history too
q = mPreferences.getString("history", "");
qlen = q != null ? q.length() : 0;
if (qlen > 1) {
plen = 0;
n = 0;
shift = 0;
mHistory.clear();
for (int i = 0; i < qlen; i++) {
char c = q.charAt(i);
if (c == ';') {
if (n >= mPlayListLen) {
// bogus history data
mHistory.clear();
break;
}
mHistory.add(n);
n = 0;
shift = 0;
} else {
if (c >= '0' && c <= '9') {
n += ((c - '0') << shift);
} else if (c >= 'a' && c <= 'f') {
n += ((10 + c - 'a') << shift);
} else {
// bogus history data
mHistory.clear();
break;
}
shift += 4;
}
}
}
}
if (shufmode == SHUFFLE_AUTO) {
if (! makeAutoShuffleList()) {
shufmode = SHUFFLE_NONE;
}
}
mShuffleMode = shufmode;
}
}
@Override
public IBinder onBind(Intent intent) {
mDelayedStopHandler.removeCallbacksAndMessages(null);
mServiceInUse = true;
return mBinder;
}
@Override
public void onRebind(Intent intent) {
mDelayedStopHandler.removeCallbacksAndMessages(null);
mServiceInUse = true;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
mServiceStartId = startId;
mDelayedStopHandler.removeCallbacksAndMessages(null);
if (intent != null) {
String action = intent.getAction();
String cmd = intent.getStringExtra("command");
MusicUtils.debugLog("onStartCommand " + action + " / " + cmd);
if (CMDNEXT.equals(cmd) || NEXT_ACTION.equals(action)) {
gotoNext(true);
} else if (CMDPREVIOUS.equals(cmd) || PREVIOUS_ACTION.equals(action)) {
if (position() < 2000) {
prev();
} else {
seek(0);
play();
}
} else if (CMDTOGGLEPAUSE.equals(cmd) || TOGGLEPAUSE_ACTION.equals(action)) {
if (isPlaying()) {
pause();
mPausedByTransientLossOfFocus = false;
} else {
play();
}
} else if (CMDPAUSE.equals(cmd) || PAUSE_ACTION.equals(action)) {
pause();
mPausedByTransientLossOfFocus = false;
} else if (CMDPLAY.equals(cmd)) {
play();
} else if (CMDSTOP.equals(cmd)) {
pause();
mPausedByTransientLossOfFocus = false;
seek(0);
}
}
// make sure the service will shut down on its own if it was
// just started but not bound to and nothing is playing
mDelayedStopHandler.removeCallbacksAndMessages(null);
Message msg = mDelayedStopHandler.obtainMessage();
mDelayedStopHandler.sendMessageDelayed(msg, IDLE_DELAY);
return START_STICKY;
}
@Override
public boolean onUnbind(Intent intent) {
mServiceInUse = false;
// Take a snapshot of the current playlist
saveQueue(true);
if (isPlaying() || mPausedByTransientLossOfFocus) {
// something is currently playing, or will be playing once
// an in-progress action requesting audio focus ends, so don't stop the service now.
return true;
}
// If there is a playlist but playback is paused, then wait a while
// before stopping the service, so that pause/resume isn't slow.
// Also delay stopping the service if we're transitioning between tracks.
if (mPlayListLen > 0 || mMediaplayerHandler.hasMessages(TRACK_ENDED)) {
Message msg = mDelayedStopHandler.obtainMessage();
mDelayedStopHandler.sendMessageDelayed(msg, IDLE_DELAY);
return true;
}
// No active playlist, OK to stop the service right now
stopSelf(mServiceStartId);
return true;
}
private Handler mDelayedStopHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
// Check again to make sure nothing is playing right now
if (isPlaying() || mPausedByTransientLossOfFocus || mServiceInUse
|| mMediaplayerHandler.hasMessages(TRACK_ENDED)) {
return;
}
// save the queue again, because it might have changed
// since the user exited the music app (because of
// party-shuffle or because the play-position changed)
saveQueue(true);
stopSelf(mServiceStartId);
}
};
/**
* Called when we receive a ACTION_MEDIA_EJECT notification.
*
* @param storagePath path to mount point for the removed media
*/
public void closeExternalStorageFiles(String storagePath) {
// stop playback and clean up if the SD card is going to be unmounted.
stop(true);
notifyChange(QUEUE_CHANGED);
notifyChange(META_CHANGED);
}
/**
* Registers an intent to listen for ACTION_MEDIA_EJECT notifications.
* The intent will call closeExternalStorageFiles() if the external media
* is going to be ejected, so applications can clean up any files they have open.
*/
public void registerExternalStorageListener() {
if (mUnmountReceiver == null) {
mUnmountReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(Intent.ACTION_MEDIA_EJECT)) {
saveQueue(true);
mQueueIsSaveable = false;
closeExternalStorageFiles(intent.getData().getPath());
} else if (action.equals(Intent.ACTION_MEDIA_MOUNTED)) {
mMediaMountedCount++;
mCardId = MusicUtils.getCardId(MediaPlaybackService.this);
reloadQueue();
mQueueIsSaveable = true;
notifyChange(QUEUE_CHANGED);
notifyChange(META_CHANGED);
}
}
};
IntentFilter iFilter = new IntentFilter();
iFilter.addAction(Intent.ACTION_MEDIA_EJECT);
iFilter.addAction(Intent.ACTION_MEDIA_MOUNTED);
iFilter.addDataScheme("file");
registerReceiver(mUnmountReceiver, iFilter);
}
}
/**
* Notify the change-receivers that something has changed.
* The intent that is sent contains the following data
* for the currently playing track:
* "id" - Integer: the database row ID
* "artist" - String: the name of the artist
* "album" - String: the name of the album
* "track" - String: the name of the track
* The intent has an action that is one of
* "com.android.music.metachanged"
* "com.android.music.queuechanged",
* "com.android.music.playbackcomplete"
* "com.android.music.playstatechanged"
* respectively indicating that a new track has
* started playing, that the playback queue has
* changed, that playback has stopped because
* the last file in the list has been played,
* or that the play-state changed (paused/resumed).
*/
private void notifyChange(String what) {
Intent i = new Intent(what);
i.putExtra("id", Long.valueOf(getAudioId()));
i.putExtra("artist", getArtistName());
i.putExtra("album",getAlbumName());
i.putExtra("track", getTrackName());
i.putExtra("playing", isPlaying());
sendStickyBroadcast(i);
if (what.equals(PLAYSTATE_CHANGED)) {
// mRemoteControlClient.setPlaybackState(isPlaying() ?
// RemoteControlClient.PLAYSTATE_PLAYING : RemoteControlClient.PLAYSTATE_PAUSED);
} else if (what.equals(META_CHANGED)) {
// RemoteControlClient.MetadataEditor ed = mRemoteControlClient.editMetadata(true);
// ed.putString(MediaMetadataRetriever.METADATA_KEY_TITLE, getTrackName());
// ed.putString(MediaMetadataRetriever.METADATA_KEY_ALBUM, getAlbumName());
// ed.putString(MediaMetadataRetriever.METADATA_KEY_ARTIST, getArtistName());
// ed.putLong(MediaMetadataRetriever.METADATA_KEY_DURATION, duration());
// Bitmap b = MusicUtils.getArtwork(this, getAudioId(), getAlbumId(), false);
// if (b != null) {
// ed.putBitmap(MetadataEditor.BITMAP_KEY_ARTWORK, b);
// }
// ed.apply();
}
if (what.equals(QUEUE_CHANGED)) {
saveQueue(true);
} else {
saveQueue(false);
}
// Share this notification directly with our widgets
mAppWidgetProvider.notifyChange(this, what);
}
private void ensurePlayListCapacity(int size) {
if (mPlayList == null || size > mPlayList.length) {
// reallocate at 2x requested size so we don't
// need to grow and copy the array for every
// insert
long [] newlist = new long[size * 2];
int len = mPlayList != null ? mPlayList.length : mPlayListLen;
for (int i = 0; i < len; i++) {
newlist[i] = mPlayList[i];
}
mPlayList = newlist;
}
// FIXME: shrink the array when the needed size is much smaller
// than the allocated size
}
// insert the list of songs at the specified position in the playlist
private void addToPlayList(long [] list, int position) {
int addlen = list.length;
if (position < 0) { // overwrite
mPlayListLen = 0;
position = 0;
}
ensurePlayListCapacity(mPlayListLen + addlen);
if (position > mPlayListLen) {
position = mPlayListLen;
}
// move part of list after insertion point
int tailsize = mPlayListLen - position;
for (int i = tailsize ; i > 0 ; i--) {
mPlayList[position + i] = mPlayList[position + i - addlen];
}
// copy list into playlist
for (int i = 0; i < addlen; i++) {
mPlayList[position + i] = list[i];
}
mPlayListLen += addlen;
if (mPlayListLen == 0) {
mCursor.close();
mCursor = null;
notifyChange(META_CHANGED);
}
}
/**
* Appends a list of tracks to the current playlist.
* If nothing is playing currently, playback will be started at
* the first track.
* If the action is NOW, playback will switch to the first of
* the new tracks immediately.
* @param list The list of tracks to append.
* @param action NOW, NEXT or LAST
*/
public void enqueue(long [] list, int action) {
synchronized(this) {
if (action == NEXT && mPlayPos + 1 < mPlayListLen) {
addToPlayList(list, mPlayPos + 1);
notifyChange(QUEUE_CHANGED);
} else {
// action == LAST || action == NOW || mPlayPos + 1 == mPlayListLen
addToPlayList(list, Integer.MAX_VALUE);
notifyChange(QUEUE_CHANGED);
if (action == NOW) {
mPlayPos = mPlayListLen - list.length;
openCurrentAndNext();
play();
notifyChange(META_CHANGED);
return;
}
}
if (mPlayPos < 0) {
mPlayPos = 0;
openCurrentAndNext();
play();
notifyChange(META_CHANGED);
}
}
}
/**
* Replaces the current playlist with a new list,
* and prepares for starting playback at the specified
* position in the list, or a random position if the
* specified position is 0.
* @param list The new list of tracks.
*/
public void open(long [] list, int position) {
synchronized (this) {
if (mShuffleMode == SHUFFLE_AUTO) {
mShuffleMode = SHUFFLE_NORMAL;
}
long oldId = getAudioId();
int listlength = list.length;
boolean newlist = true;
if (mPlayListLen == listlength) {
// possible fast path: list might be the same
newlist = false;
for (int i = 0; i < listlength; i++) {
if (list[i] != mPlayList[i]) {
newlist = true;
break;
}
}
}
if (newlist) {
addToPlayList(list, -1);
notifyChange(QUEUE_CHANGED);
}
int oldpos = mPlayPos;
if (position >= 0) {
mPlayPos = position;
} else {
mPlayPos = mRand.nextInt(mPlayListLen);
}
mHistory.clear();
saveBookmarkIfNeeded();
openCurrentAndNext();
if (oldId != getAudioId()) {
notifyChange(META_CHANGED);
}
}
}
/**
* Moves the item at index1 to index2.
* @param index1
* @param index2
*/
public void moveQueueItem(int index1, int index2) {
synchronized (this) {
if (index1 >= mPlayListLen) {
index1 = mPlayListLen - 1;
}
if (index2 >= mPlayListLen) {
index2 = mPlayListLen - 1;
}
if (index1 < index2) {
long tmp = mPlayList[index1];
for (int i = index1; i < index2; i++) {
mPlayList[i] = mPlayList[i+1];
}
mPlayList[index2] = tmp;
if (mPlayPos == index1) {
mPlayPos = index2;
} else if (mPlayPos >= index1 && mPlayPos <= index2) {
mPlayPos--;
}
} else if (index2 < index1) {
long tmp = mPlayList[index1];
for (int i = index1; i > index2; i--) {
mPlayList[i] = mPlayList[i-1];
}
mPlayList[index2] = tmp;
if (mPlayPos == index1) {
mPlayPos = index2;
} else if (mPlayPos >= index2 && mPlayPos <= index1) {
mPlayPos++;
}
}
notifyChange(QUEUE_CHANGED);
}
}
/**
* Returns the current play list
* @return An array of integers containing the IDs of the tracks in the play list
*/
public long [] getQueue() {
synchronized (this) {
int len = mPlayListLen;
long [] list = new long[len];
for (int i = 0; i < len; i++) {
list[i] = mPlayList[i];
}
return list;
}
}
private Cursor getCursorForId(long lid) {
String id = String.valueOf(lid);
Cursor c = getContentResolver().query(
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
mCursorCols, "_id=" + id , null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
private void openCurrentAndNext() {
synchronized (this) {
if (mCursor != null) {
mCursor.close();
mCursor = null;
}
if (mPlayListLen == 0) {
return;
}
stop(false);
mCursor = getCursorForId(mPlayList[mPlayPos]);
while(true) {
if (mCursor != null && mCursor.getCount() != 0 &&
open(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI + "/" +
mCursor.getLong(IDCOLIDX))) {
break;
}
// if we get here then opening the file failed. We can close the cursor now, because
// we're either going to create a new one next, or stop trying
if (mCursor != null) {
mCursor.close();
mCursor = null;
}
if (mOpenFailedCounter++ < 10 && mPlayListLen > 1) {
int pos = getNextPosition(false);
if (pos < 0) {
gotoIdleState();
if (mIsSupposedToBePlaying) {
mIsSupposedToBePlaying = false;
notifyChange(PLAYSTATE_CHANGED);
}
return;
}
mPlayPos = pos;
stop(false);
mPlayPos = pos;
mCursor = getCursorForId(mPlayList[mPlayPos]);
} else {
mOpenFailedCounter = 0;
if (!mQuietMode) {
Toast.makeText(this, R.string.playback_failed, Toast.LENGTH_SHORT).show();
}
Log.d(LOGTAG, "Failed to open file for playback");
gotoIdleState();
if (mIsSupposedToBePlaying) {
mIsSupposedToBePlaying = false;
notifyChange(PLAYSTATE_CHANGED);
}
return;
}
}
// go to bookmark if needed
if (isPodcast()) {
long bookmark = getBookmark();
// Start playing a little bit before the bookmark,
// so it's easier to get back in to the narrative.
seek(bookmark - 5000);
}
setNextTrack();
}
}
private void setNextTrack() {
mNextPlayPos = getNextPosition(false);
if (mNextPlayPos >= 0) {
long id = mPlayList[mNextPlayPos];
mPlayer.setNextDataSource(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI + "/" + id);
+ } else {
+ mPlayer.setNextDataSource(null);
}
}
/**
* Opens the specified file and readies it for playback.
*
* @param path The full path of the file to be opened.
*/
public boolean open(String path) {
synchronized (this) {
if (path == null) {
return false;
}
// if mCursor is null, try to associate path with a database cursor
if (mCursor == null) {
ContentResolver resolver = getContentResolver();
Uri uri;
String where;
String selectionArgs[];
if (path.startsWith("content://media/")) {
uri = Uri.parse(path);
where = null;
selectionArgs = null;
} else {
uri = MediaStore.Audio.Media.getContentUriForPath(path);
where = MediaStore.Audio.Media.DATA + "=?";
selectionArgs = new String[] { path };
}
try {
mCursor = resolver.query(uri, mCursorCols, where, selectionArgs, null);
if (mCursor != null) {
if (mCursor.getCount() == 0) {
mCursor.close();
mCursor = null;
} else {
mCursor.moveToNext();
ensurePlayListCapacity(1);
mPlayListLen = 1;
mPlayList[0] = mCursor.getLong(IDCOLIDX);
mPlayPos = 0;
}
}
} catch (UnsupportedOperationException ex) {
}
}
mFileToPlay = path;
mPlayer.setDataSource(mFileToPlay);
if (mPlayer.isInitialized()) {
mOpenFailedCounter = 0;
return true;
}
stop(true);
return false;
}
}
/**
* Starts playback of a previously opened file.
*/
public void play() {
mAudioManager.requestAudioFocus(mAudioFocusListener, AudioManager.STREAM_MUSIC,
AudioManager.AUDIOFOCUS_GAIN);
mAudioManager.registerMediaButtonEventReceiver(new ComponentName(this.getPackageName(),
MediaButtonIntentReceiver.class.getName()));
if (mPlayer.isInitialized()) {
// if we are at the end of the song, go to the next song first
long duration = mPlayer.duration();
if (mRepeatMode != REPEAT_CURRENT && duration > 2000 &&
mPlayer.position() >= duration - 2000) {
gotoNext(true);
}
mPlayer.start();
// make sure we fade in, in case a previous fadein was stopped because
// of another focus loss
mMediaplayerHandler.removeMessages(FADEDOWN);
mMediaplayerHandler.sendEmptyMessage(FADEUP);
updateNotification();
if (!mIsSupposedToBePlaying) {
mIsSupposedToBePlaying = true;
notifyChange(PLAYSTATE_CHANGED);
}
} else if (mPlayListLen <= 0) {
// This is mostly so that if you press 'play' on a bluetooth headset
// without every having played anything before, it will still play
// something.
setShuffleMode(SHUFFLE_AUTO);
}
}
private void updateNotification() {
RemoteViews views = new RemoteViews(getPackageName(), R.layout.statusbar);
views.setImageViewResource(R.id.icon, R.drawable.stat_notify_musicplayer);
if (getAudioId() < 0) {
// streaming
views.setTextViewText(R.id.trackname, getPath());
views.setTextViewText(R.id.artistalbum, null);
} else {
String artist = getArtistName();
views.setTextViewText(R.id.trackname, getTrackName());
if (artist == null || artist.equals(MediaStore.UNKNOWN_STRING)) {
artist = getString(R.string.unknown_artist_name);
}
String album = getAlbumName();
if (album == null || album.equals(MediaStore.UNKNOWN_STRING)) {
album = getString(R.string.unknown_album_name);
}
views.setTextViewText(R.id.artistalbum,
getString(R.string.notification_artist_album, artist, album)
);
}
Notification status = new Notification();
status.contentView = views;
status.flags |= Notification.FLAG_ONGOING_EVENT;
status.icon = R.drawable.stat_notify_musicplayer;
status.contentIntent = PendingIntent.getActivity(this, 0,
new Intent("com.android.music.PLAYBACK_VIEWER")
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK), 0);
startForeground(PLAYBACKSERVICE_STATUS, status);
}
private void stop(boolean remove_status_icon) {
if (mPlayer.isInitialized()) {
mPlayer.stop();
}
mFileToPlay = null;
if (mCursor != null) {
mCursor.close();
mCursor = null;
}
if (remove_status_icon) {
gotoIdleState();
} else {
stopForeground(false);
}
if (remove_status_icon) {
mIsSupposedToBePlaying = false;
}
}
/**
* Stops playback.
*/
public void stop() {
stop(true);
}
/**
* Pauses playback (call play() to resume)
*/
public void pause() {
synchronized(this) {
mMediaplayerHandler.removeMessages(FADEUP);
if (isPlaying()) {
mPlayer.pause();
gotoIdleState();
mIsSupposedToBePlaying = false;
notifyChange(PLAYSTATE_CHANGED);
saveBookmarkIfNeeded();
}
}
}
/** Returns whether something is currently playing
*
* @return true if something is playing (or will be playing shortly, in case
* we're currently transitioning between tracks), false if not.
*/
public boolean isPlaying() {
return mIsSupposedToBePlaying;
}
/*
Desired behavior for prev/next/shuffle:
- NEXT will move to the next track in the list when not shuffling, and to
a track randomly picked from the not-yet-played tracks when shuffling.
If all tracks have already been played, pick from the full set, but
avoid picking the previously played track if possible.
- when shuffling, PREV will go to the previously played track. Hitting PREV
again will go to the track played before that, etc. When the start of the
history has been reached, PREV is a no-op.
When not shuffling, PREV will go to the sequentially previous track (the
difference with the shuffle-case is mainly that when not shuffling, the
user can back up to tracks that are not in the history).
Example:
When playing an album with 10 tracks from the start, and enabling shuffle
while playing track 5, the remaining tracks (6-10) will be shuffled, e.g.
the final play order might be 1-2-3-4-5-8-10-6-9-7.
When hitting 'prev' 8 times while playing track 7 in this example, the
user will go to tracks 9-6-10-8-5-4-3-2. If the user then hits 'next',
a random track will be picked again. If at any time user disables shuffling
the next/previous track will be picked in sequential order again.
*/
public void prev() {
synchronized (this) {
if (mShuffleMode == SHUFFLE_NORMAL) {
// go to previously-played track and remove it from the history
int histsize = mHistory.size();
if (histsize == 0) {
// prev is a no-op
return;
}
Integer pos = mHistory.remove(histsize - 1);
mPlayPos = pos.intValue();
} else {
if (mPlayPos > 0) {
mPlayPos--;
} else {
mPlayPos = mPlayListLen - 1;
}
}
saveBookmarkIfNeeded();
stop(false);
openCurrentAndNext();
play();
notifyChange(META_CHANGED);
}
}
/**
* Get the next position to play. Note that this may actually modify mPlayPos
* if playback is in SHUFFLE_AUTO mode and the shuffle list window needed to
* be adjusted. Either way, the return value is the next value that should be
* assigned to mPlayPos;
*/
private int getNextPosition(boolean force) {
if (mRepeatMode == REPEAT_CURRENT) {
if (mPlayPos < 0) return 0;
return mPlayPos;
} else if (mShuffleMode == SHUFFLE_NORMAL) {
// Pick random next track from the not-yet-played ones
// TODO: make it work right after adding/removing items in the queue.
// Store the current file in the history, but keep the history at a
// reasonable size
if (mPlayPos >= 0) {
mHistory.add(mPlayPos);
}
if (mHistory.size() > MAX_HISTORY_SIZE) {
mHistory.removeElementAt(0);
}
int numTracks = mPlayListLen;
int[] tracks = new int[numTracks];
for (int i=0;i < numTracks; i++) {
tracks[i] = i;
}
int numHistory = mHistory.size();
int numUnplayed = numTracks;
for (int i=0;i < numHistory; i++) {
int idx = mHistory.get(i).intValue();
if (idx < numTracks && tracks[idx] >= 0) {
numUnplayed--;
tracks[idx] = -1;
}
}
// 'numUnplayed' now indicates how many tracks have not yet
// been played, and 'tracks' contains the indices of those
// tracks.
if (numUnplayed <=0) {
// everything's already been played
if (mRepeatMode == REPEAT_ALL || force) {
//pick from full set
numUnplayed = numTracks;
for (int i=0;i < numTracks; i++) {
tracks[i] = i;
}
} else {
// all done
return -1;
}
}
int skip = mRand.nextInt(numUnplayed);
int cnt = -1;
while (true) {
while (tracks[++cnt] < 0)
;
skip--;
if (skip < 0) {
break;
}
}
return cnt;
} else if (mShuffleMode == SHUFFLE_AUTO) {
doAutoShuffleUpdate();
return mPlayPos + 1;
} else {
if (mPlayPos >= mPlayListLen - 1) {
// we're at the end of the list
if (mRepeatMode == REPEAT_NONE && !force) {
// all done
return -1;
} else if (mRepeatMode == REPEAT_ALL || force) {
return 0;
}
return -1;
} else {
return mPlayPos + 1;
}
}
}
public void gotoNext(boolean force) {
synchronized (this) {
if (mPlayListLen <= 0) {
Log.d(LOGTAG, "No play queue");
return;
}
int pos = getNextPosition(force);
if (pos < 0) {
gotoIdleState();
if (mIsSupposedToBePlaying) {
mIsSupposedToBePlaying = false;
notifyChange(PLAYSTATE_CHANGED);
}
return;
}
mPlayPos = pos;
saveBookmarkIfNeeded();
stop(false);
mPlayPos = pos;
openCurrentAndNext();
play();
notifyChange(META_CHANGED);
}
}
private void gotoIdleState() {
mDelayedStopHandler.removeCallbacksAndMessages(null);
Message msg = mDelayedStopHandler.obtainMessage();
mDelayedStopHandler.sendMessageDelayed(msg, IDLE_DELAY);
stopForeground(true);
}
private void saveBookmarkIfNeeded() {
try {
if (isPodcast()) {
long pos = position();
long bookmark = getBookmark();
long duration = duration();
if ((pos < bookmark && (pos + 10000) > bookmark) ||
(pos > bookmark && (pos - 10000) < bookmark)) {
// The existing bookmark is close to the current
// position, so don't update it.
return;
}
if (pos < 15000 || (pos + 10000) > duration) {
// if we're near the start or end, clear the bookmark
pos = 0;
}
// write 'pos' to the bookmark field
ContentValues values = new ContentValues();
values.put(MediaStore.Audio.Media.BOOKMARK, pos);
Uri uri = ContentUris.withAppendedId(
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, mCursor.getLong(IDCOLIDX));
getContentResolver().update(uri, values, null, null);
}
} catch (SQLiteException ex) {
}
}
// Make sure there are at least 5 items after the currently playing item
// and no more than 10 items before.
private void doAutoShuffleUpdate() {
boolean notify = false;
// remove old entries
if (mPlayPos > 10) {
removeTracks(0, mPlayPos - 9);
notify = true;
}
// add new entries if needed
int to_add = 7 - (mPlayListLen - (mPlayPos < 0 ? -1 : mPlayPos));
for (int i = 0; i < to_add; i++) {
// pick something at random from the list
int lookback = mHistory.size();
int idx = -1;
while(true) {
idx = mRand.nextInt(mAutoShuffleList.length);
if (!wasRecentlyUsed(idx, lookback)) {
break;
}
lookback /= 2;
}
mHistory.add(idx);
if (mHistory.size() > MAX_HISTORY_SIZE) {
mHistory.remove(0);
}
ensurePlayListCapacity(mPlayListLen + 1);
mPlayList[mPlayListLen++] = mAutoShuffleList[idx];
notify = true;
}
if (notify) {
notifyChange(QUEUE_CHANGED);
}
}
// check that the specified idx is not in the history (but only look at at
// most lookbacksize entries in the history)
private boolean wasRecentlyUsed(int idx, int lookbacksize) {
// early exit to prevent infinite loops in case idx == mPlayPos
if (lookbacksize == 0) {
return false;
}
int histsize = mHistory.size();
if (histsize < lookbacksize) {
Log.d(LOGTAG, "lookback too big");
lookbacksize = histsize;
}
int maxidx = histsize - 1;
for (int i = 0; i < lookbacksize; i++) {
long entry = mHistory.get(maxidx - i);
if (entry == idx) {
return true;
}
}
return false;
}
// A simple variation of Random that makes sure that the
// value it returns is not equal to the value it returned
// previously, unless the interval is 1.
private static class Shuffler {
private int mPrevious;
private Random mRandom = new Random();
public int nextInt(int interval) {
int ret;
do {
ret = mRandom.nextInt(interval);
} while (ret == mPrevious && interval > 1);
mPrevious = ret;
return ret;
}
};
private boolean makeAutoShuffleList() {
ContentResolver res = getContentResolver();
Cursor c = null;
try {
c = res.query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
new String[] {MediaStore.Audio.Media._ID}, MediaStore.Audio.Media.IS_MUSIC + "=1",
null, null);
if (c == null || c.getCount() == 0) {
return false;
}
int len = c.getCount();
long [] list = new long[len];
for (int i = 0; i < len; i++) {
c.moveToNext();
list[i] = c.getLong(0);
}
mAutoShuffleList = list;
return true;
} catch (RuntimeException ex) {
} finally {
if (c != null) {
c.close();
}
}
return false;
}
/**
* Removes the range of tracks specified from the play list. If a file within the range is
* the file currently being played, playback will move to the next file after the
* range.
* @param first The first file to be removed
* @param last The last file to be removed
* @return the number of tracks deleted
*/
public int removeTracks(int first, int last) {
int numremoved = removeTracksInternal(first, last);
if (numremoved > 0) {
notifyChange(QUEUE_CHANGED);
}
return numremoved;
}
private int removeTracksInternal(int first, int last) {
synchronized (this) {
if (last < first) return 0;
if (first < 0) first = 0;
if (last >= mPlayListLen) last = mPlayListLen - 1;
boolean gotonext = false;
if (first <= mPlayPos && mPlayPos <= last) {
mPlayPos = first;
gotonext = true;
} else if (mPlayPos > last) {
mPlayPos -= (last - first + 1);
}
int num = mPlayListLen - last - 1;
for (int i = 0; i < num; i++) {
mPlayList[first + i] = mPlayList[last + 1 + i];
}
mPlayListLen -= last - first + 1;
if (gotonext) {
if (mPlayListLen == 0) {
stop(true);
mPlayPos = -1;
if (mCursor != null) {
mCursor.close();
mCursor = null;
}
} else {
if (mPlayPos >= mPlayListLen) {
mPlayPos = 0;
}
boolean wasPlaying = isPlaying();
stop(false);
openCurrentAndNext();
if (wasPlaying) {
play();
}
}
notifyChange(META_CHANGED);
}
return last - first + 1;
}
}
/**
* Removes all instances of the track with the given id
* from the playlist.
* @param id The id to be removed
* @return how many instances of the track were removed
*/
public int removeTrack(long id) {
int numremoved = 0;
synchronized (this) {
for (int i = 0; i < mPlayListLen; i++) {
if (mPlayList[i] == id) {
numremoved += removeTracksInternal(i, i);
i--;
}
}
}
if (numremoved > 0) {
notifyChange(QUEUE_CHANGED);
}
return numremoved;
}
public void setShuffleMode(int shufflemode) {
synchronized(this) {
if (mShuffleMode == shufflemode && mPlayListLen > 0) {
return;
}
mShuffleMode = shufflemode;
if (mShuffleMode == SHUFFLE_AUTO) {
if (makeAutoShuffleList()) {
mPlayListLen = 0;
doAutoShuffleUpdate();
mPlayPos = 0;
openCurrentAndNext();
play();
notifyChange(META_CHANGED);
return;
} else {
// failed to build a list of files to shuffle
mShuffleMode = SHUFFLE_NONE;
}
}
saveQueue(false);
}
}
public int getShuffleMode() {
return mShuffleMode;
}
public void setRepeatMode(int repeatmode) {
synchronized(this) {
mRepeatMode = repeatmode;
setNextTrack();
saveQueue(false);
}
}
public int getRepeatMode() {
return mRepeatMode;
}
public int getMediaMountedCount() {
return mMediaMountedCount;
}
/**
* Returns the path of the currently playing file, or null if
* no file is currently playing.
*/
public String getPath() {
return mFileToPlay;
}
/**
* Returns the rowid of the currently playing file, or -1 if
* no file is currently playing.
*/
public long getAudioId() {
synchronized (this) {
if (mPlayPos >= 0 && mPlayer.isInitialized()) {
return mPlayList[mPlayPos];
}
}
return -1;
}
/**
* Returns the position in the queue
* @return the position in the queue
*/
public int getQueuePosition() {
synchronized(this) {
return mPlayPos;
}
}
/**
* Starts playing the track at the given position in the queue.
* @param pos The position in the queue of the track that will be played.
*/
public void setQueuePosition(int pos) {
synchronized(this) {
stop(false);
mPlayPos = pos;
openCurrentAndNext();
play();
notifyChange(META_CHANGED);
if (mShuffleMode == SHUFFLE_AUTO) {
doAutoShuffleUpdate();
}
}
}
public String getArtistName() {
synchronized(this) {
if (mCursor == null) {
return null;
}
return mCursor.getString(mCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ARTIST));
}
}
public long getArtistId() {
synchronized (this) {
if (mCursor == null) {
return -1;
}
return mCursor.getLong(mCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ARTIST_ID));
}
}
public String getAlbumName() {
synchronized (this) {
if (mCursor == null) {
return null;
}
return mCursor.getString(mCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM));
}
}
public long getAlbumId() {
synchronized (this) {
if (mCursor == null) {
return -1;
}
return mCursor.getLong(mCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM_ID));
}
}
public String getTrackName() {
synchronized (this) {
if (mCursor == null) {
return null;
}
return mCursor.getString(mCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.TITLE));
}
}
private boolean isPodcast() {
synchronized (this) {
if (mCursor == null) {
return false;
}
return (mCursor.getInt(PODCASTCOLIDX) > 0);
}
}
private long getBookmark() {
synchronized (this) {
if (mCursor == null) {
return 0;
}
return mCursor.getLong(BOOKMARKCOLIDX);
}
}
/**
* Returns the duration of the file in milliseconds.
* Currently this method returns -1 for the duration of MIDI files.
*/
public long duration() {
if (mPlayer.isInitialized()) {
return mPlayer.duration();
}
return -1;
}
/**
* Returns the current playback position in milliseconds
*/
public long position() {
if (mPlayer.isInitialized()) {
return mPlayer.position();
}
return -1;
}
/**
* Seeks to the position specified.
*
* @param pos The position to seek to, in milliseconds
*/
public long seek(long pos) {
if (mPlayer.isInitialized()) {
if (pos < 0) pos = 0;
if (pos > mPlayer.duration()) pos = mPlayer.duration();
return mPlayer.seek(pos);
}
return -1;
}
/**
* Sets the audio session ID.
*
* @param sessionId: the audio session ID.
*/
public void setAudioSessionId(int sessionId) {
synchronized (this) {
mPlayer.setAudioSessionId(sessionId);
}
}
/**
* Returns the audio session ID.
*/
public int getAudioSessionId() {
synchronized (this) {
return mPlayer.getAudioSessionId();
}
}
/**
* Provides a unified interface for dealing with midi files and
* other media files.
*/
private class MultiPlayer {
private CompatMediaPlayer mCurrentMediaPlayer = new CompatMediaPlayer();
private CompatMediaPlayer mNextMediaPlayer;
private Handler mHandler;
private boolean mIsInitialized = false;
public MultiPlayer() {
mCurrentMediaPlayer.setWakeMode(MediaPlaybackService.this, PowerManager.PARTIAL_WAKE_LOCK);
}
public void setDataSource(String path) {
mIsInitialized = setDataSourceImpl(mCurrentMediaPlayer, path);
if (mIsInitialized) {
setNextDataSource(null);
}
}
private boolean setDataSourceImpl(MediaPlayer player, String path) {
try {
player.reset();
player.setOnPreparedListener(null);
if (path.startsWith("content://")) {
player.setDataSource(MediaPlaybackService.this, Uri.parse(path));
} else {
player.setDataSource(path);
}
player.setAudioStreamType(AudioManager.STREAM_MUSIC);
player.prepare();
} catch (IOException ex) {
// TODO: notify the user why the file couldn't be opened
return false;
} catch (IllegalArgumentException ex) {
// TODO: notify the user why the file couldn't be opened
return false;
}
player.setOnCompletionListener(listener);
player.setOnErrorListener(errorListener);
Intent i = new Intent(AudioEffect.ACTION_OPEN_AUDIO_EFFECT_CONTROL_SESSION);
i.putExtra(AudioEffect.EXTRA_AUDIO_SESSION, getAudioSessionId());
i.putExtra(AudioEffect.EXTRA_PACKAGE_NAME, getPackageName());
sendBroadcast(i);
return true;
}
public void setNextDataSource(String path) {
mCurrentMediaPlayer.setNextMediaPlayer(null);
if (mNextMediaPlayer != null) {
mNextMediaPlayer.release();
mNextMediaPlayer = null;
}
if (path == null) {
return;
}
mNextMediaPlayer = new CompatMediaPlayer();
mNextMediaPlayer.setWakeMode(MediaPlaybackService.this, PowerManager.PARTIAL_WAKE_LOCK);
mNextMediaPlayer.setAudioSessionId(getAudioSessionId());
if (setDataSourceImpl(mNextMediaPlayer, path)) {
mCurrentMediaPlayer.setNextMediaPlayer(mNextMediaPlayer);
} else {
// failed to open next, we'll transition the old fashioned way,
// which will skip over the faulty file
mNextMediaPlayer.release();
mNextMediaPlayer = null;
}
}
public boolean isInitialized() {
return mIsInitialized;
}
public void start() {
MusicUtils.debugLog(new Exception("MultiPlayer.start called"));
mCurrentMediaPlayer.start();
}
public void stop() {
mCurrentMediaPlayer.reset();
mIsInitialized = false;
}
/**
* You CANNOT use this player anymore after calling release()
*/
public void release() {
stop();
mCurrentMediaPlayer.release();
}
public void pause() {
mCurrentMediaPlayer.pause();
}
public void setHandler(Handler handler) {
mHandler = handler;
}
MediaPlayer.OnCompletionListener listener = new MediaPlayer.OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
if (mp == mCurrentMediaPlayer && mNextMediaPlayer != null) {
mCurrentMediaPlayer.release();
mCurrentMediaPlayer = mNextMediaPlayer;
mNextMediaPlayer = null;
mHandler.sendEmptyMessage(TRACK_WENT_TO_NEXT);
} else {
// Acquire a temporary wakelock, since when we return from
// this callback the MediaPlayer will release its wakelock
// and allow the device to go to sleep.
// This temporary wakelock is released when the RELEASE_WAKELOCK
// message is processed, but just in case, put a timeout on it.
mWakeLock.acquire(30000);
mHandler.sendEmptyMessage(TRACK_ENDED);
mHandler.sendEmptyMessage(RELEASE_WAKELOCK);
}
}
};
MediaPlayer.OnErrorListener errorListener = new MediaPlayer.OnErrorListener() {
public boolean onError(MediaPlayer mp, int what, int extra) {
switch (what) {
case MediaPlayer.MEDIA_ERROR_SERVER_DIED:
mIsInitialized = false;
mCurrentMediaPlayer.release();
// Creating a new MediaPlayer and settings its wakemode does not
// require the media service, so it's OK to do this now, while the
// service is still being restarted
mCurrentMediaPlayer = new CompatMediaPlayer();
mCurrentMediaPlayer.setWakeMode(MediaPlaybackService.this, PowerManager.PARTIAL_WAKE_LOCK);
mHandler.sendMessageDelayed(mHandler.obtainMessage(SERVER_DIED), 2000);
return true;
default:
Log.d("MultiPlayer", "Error: " + what + "," + extra);
break;
}
return false;
}
};
public long duration() {
return mCurrentMediaPlayer.getDuration();
}
public long position() {
return mCurrentMediaPlayer.getCurrentPosition();
}
public long seek(long whereto) {
mCurrentMediaPlayer.seekTo((int) whereto);
return whereto;
}
public void setVolume(float vol) {
mCurrentMediaPlayer.setVolume(vol, vol);
}
public void setAudioSessionId(int sessionId) {
mCurrentMediaPlayer.setAudioSessionId(sessionId);
}
public int getAudioSessionId() {
return mCurrentMediaPlayer.getAudioSessionId();
}
}
static class CompatMediaPlayer extends MediaPlayer implements OnCompletionListener {
private boolean mCompatMode = true;
private MediaPlayer mNextPlayer;
private OnCompletionListener mCompletion;
public CompatMediaPlayer() {
try {
MediaPlayer.class.getMethod("setNextMediaPlayer", MediaPlayer.class);
mCompatMode = false;
} catch (NoSuchMethodException e) {
mCompatMode = true;
super.setOnCompletionListener(this);
}
}
public void setNextMediaPlayer(MediaPlayer next) {
if (mCompatMode) {
mNextPlayer = next;
} else {
super.setNextMediaPlayer(next);
}
}
@Override
public void setOnCompletionListener(OnCompletionListener listener) {
if (mCompatMode) {
mCompletion = listener;
} else {
super.setOnCompletionListener(listener);
}
}
@Override
public void onCompletion(MediaPlayer mp) {
if (mNextPlayer != null) {
// as it turns out, starting a new MediaPlayer on the completion
// of a previous player ends up slightly overlapping the two
// playbacks, so slightly delaying the start of the next player
// gives a better user experience
SystemClock.sleep(50);
mNextPlayer.start();
}
mCompletion.onCompletion(this);
}
}
/*
* By making this a static class with a WeakReference to the Service, we
* ensure that the Service can be GCd even when the system process still
* has a remote reference to the stub.
*/
static class ServiceStub extends IMediaPlaybackService.Stub {
WeakReference<MediaPlaybackService> mService;
ServiceStub(MediaPlaybackService service) {
mService = new WeakReference<MediaPlaybackService>(service);
}
public void openFile(String path)
{
mService.get().open(path);
}
public void open(long [] list, int position) {
mService.get().open(list, position);
}
public int getQueuePosition() {
return mService.get().getQueuePosition();
}
public void setQueuePosition(int index) {
mService.get().setQueuePosition(index);
}
public boolean isPlaying() {
return mService.get().isPlaying();
}
public void stop() {
mService.get().stop();
}
public void pause() {
mService.get().pause();
}
public void play() {
mService.get().play();
}
public void prev() {
mService.get().prev();
}
public void next() {
mService.get().gotoNext(true);
}
public String getTrackName() {
return mService.get().getTrackName();
}
public String getAlbumName() {
return mService.get().getAlbumName();
}
public long getAlbumId() {
return mService.get().getAlbumId();
}
public String getArtistName() {
return mService.get().getArtistName();
}
public long getArtistId() {
return mService.get().getArtistId();
}
public void enqueue(long [] list , int action) {
mService.get().enqueue(list, action);
}
public long [] getQueue() {
return mService.get().getQueue();
}
public void moveQueueItem(int from, int to) {
mService.get().moveQueueItem(from, to);
}
public String getPath() {
return mService.get().getPath();
}
public long getAudioId() {
return mService.get().getAudioId();
}
public long position() {
return mService.get().position();
}
public long duration() {
return mService.get().duration();
}
public long seek(long pos) {
return mService.get().seek(pos);
}
public void setShuffleMode(int shufflemode) {
mService.get().setShuffleMode(shufflemode);
}
public int getShuffleMode() {
return mService.get().getShuffleMode();
}
public int removeTracks(int first, int last) {
return mService.get().removeTracks(first, last);
}
public int removeTrack(long id) {
return mService.get().removeTrack(id);
}
public void setRepeatMode(int repeatmode) {
mService.get().setRepeatMode(repeatmode);
}
public int getRepeatMode() {
return mService.get().getRepeatMode();
}
public int getMediaMountedCount() {
return mService.get().getMediaMountedCount();
}
public int getAudioSessionId() {
return mService.get().getAudioSessionId();
}
}
@Override
protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
writer.println("" + mPlayListLen + " items in queue, currently at index " + mPlayPos);
writer.println("Currently loaded:");
writer.println(getArtistName());
writer.println(getAlbumName());
writer.println(getTrackName());
writer.println(getPath());
writer.println("playing: " + mIsSupposedToBePlaying);
writer.println("actual: " + mPlayer.mCurrentMediaPlayer.isPlaying());
writer.println("shuffle mode: " + mShuffleMode);
MusicUtils.debugDump(writer);
}
private final IBinder mBinder = new ServiceStub(this);
}
| true | true | private void reloadQueue() {
String q = null;
boolean newstyle = false;
int id = mCardId;
if (mPreferences.contains("cardid")) {
newstyle = true;
id = mPreferences.getInt("cardid", ~mCardId);
}
if (id == mCardId) {
// Only restore the saved playlist if the card is still
// the same one as when the playlist was saved
q = mPreferences.getString("queue", "");
}
int qlen = q != null ? q.length() : 0;
if (qlen > 1) {
//Log.i("@@@@ service", "loaded queue: " + q);
int plen = 0;
int n = 0;
int shift = 0;
for (int i = 0; i < qlen; i++) {
char c = q.charAt(i);
if (c == ';') {
ensurePlayListCapacity(plen + 1);
mPlayList[plen] = n;
plen++;
n = 0;
shift = 0;
} else {
if (c >= '0' && c <= '9') {
n += ((c - '0') << shift);
} else if (c >= 'a' && c <= 'f') {
n += ((10 + c - 'a') << shift);
} else {
// bogus playlist data
plen = 0;
break;
}
shift += 4;
}
}
mPlayListLen = plen;
int pos = mPreferences.getInt("curpos", 0);
if (pos < 0 || pos >= mPlayListLen) {
// The saved playlist is bogus, discard it
mPlayListLen = 0;
return;
}
mPlayPos = pos;
// When reloadQueue is called in response to a card-insertion,
// we might not be able to query the media provider right away.
// To deal with this, try querying for the current file, and if
// that fails, wait a while and try again. If that too fails,
// assume there is a problem and don't restore the state.
Cursor crsr = MusicUtils.query(this,
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
new String [] {"_id"}, "_id=" + mPlayList[mPlayPos] , null, null);
if (crsr == null || crsr.getCount() == 0) {
// wait a bit and try again
SystemClock.sleep(3000);
crsr = getContentResolver().query(
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
mCursorCols, "_id=" + mPlayList[mPlayPos] , null, null);
}
if (crsr != null) {
crsr.close();
}
// Make sure we don't auto-skip to the next song, since that
// also starts playback. What could happen in that case is:
// - music is paused
// - go to UMS and delete some files, including the currently playing one
// - come back from UMS
// (time passes)
// - music app is killed for some reason (out of memory)
// - music service is restarted, service restores state, doesn't find
// the "current" file, goes to the next and: playback starts on its
// own, potentially at some random inconvenient time.
mOpenFailedCounter = 20;
mQuietMode = true;
openCurrentAndNext();
mQuietMode = false;
if (!mPlayer.isInitialized()) {
// couldn't restore the saved state
mPlayListLen = 0;
return;
}
long seekpos = mPreferences.getLong("seekpos", 0);
seek(seekpos >= 0 && seekpos < duration() ? seekpos : 0);
Log.d(LOGTAG, "restored queue, currently at position "
+ position() + "/" + duration()
+ " (requested " + seekpos + ")");
int repmode = mPreferences.getInt("repeatmode", REPEAT_NONE);
if (repmode != REPEAT_ALL && repmode != REPEAT_CURRENT) {
repmode = REPEAT_NONE;
}
mRepeatMode = repmode;
int shufmode = mPreferences.getInt("shufflemode", SHUFFLE_NONE);
if (shufmode != SHUFFLE_AUTO && shufmode != SHUFFLE_NORMAL) {
shufmode = SHUFFLE_NONE;
}
if (shufmode != SHUFFLE_NONE) {
// in shuffle mode we need to restore the history too
q = mPreferences.getString("history", "");
qlen = q != null ? q.length() : 0;
if (qlen > 1) {
plen = 0;
n = 0;
shift = 0;
mHistory.clear();
for (int i = 0; i < qlen; i++) {
char c = q.charAt(i);
if (c == ';') {
if (n >= mPlayListLen) {
// bogus history data
mHistory.clear();
break;
}
mHistory.add(n);
n = 0;
shift = 0;
} else {
if (c >= '0' && c <= '9') {
n += ((c - '0') << shift);
} else if (c >= 'a' && c <= 'f') {
n += ((10 + c - 'a') << shift);
} else {
// bogus history data
mHistory.clear();
break;
}
shift += 4;
}
}
}
}
if (shufmode == SHUFFLE_AUTO) {
if (! makeAutoShuffleList()) {
shufmode = SHUFFLE_NONE;
}
}
mShuffleMode = shufmode;
}
}
@Override
public IBinder onBind(Intent intent) {
mDelayedStopHandler.removeCallbacksAndMessages(null);
mServiceInUse = true;
return mBinder;
}
@Override
public void onRebind(Intent intent) {
mDelayedStopHandler.removeCallbacksAndMessages(null);
mServiceInUse = true;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
mServiceStartId = startId;
mDelayedStopHandler.removeCallbacksAndMessages(null);
if (intent != null) {
String action = intent.getAction();
String cmd = intent.getStringExtra("command");
MusicUtils.debugLog("onStartCommand " + action + " / " + cmd);
if (CMDNEXT.equals(cmd) || NEXT_ACTION.equals(action)) {
gotoNext(true);
} else if (CMDPREVIOUS.equals(cmd) || PREVIOUS_ACTION.equals(action)) {
if (position() < 2000) {
prev();
} else {
seek(0);
play();
}
} else if (CMDTOGGLEPAUSE.equals(cmd) || TOGGLEPAUSE_ACTION.equals(action)) {
if (isPlaying()) {
pause();
mPausedByTransientLossOfFocus = false;
} else {
play();
}
} else if (CMDPAUSE.equals(cmd) || PAUSE_ACTION.equals(action)) {
pause();
mPausedByTransientLossOfFocus = false;
} else if (CMDPLAY.equals(cmd)) {
play();
} else if (CMDSTOP.equals(cmd)) {
pause();
mPausedByTransientLossOfFocus = false;
seek(0);
}
}
// make sure the service will shut down on its own if it was
// just started but not bound to and nothing is playing
mDelayedStopHandler.removeCallbacksAndMessages(null);
Message msg = mDelayedStopHandler.obtainMessage();
mDelayedStopHandler.sendMessageDelayed(msg, IDLE_DELAY);
return START_STICKY;
}
@Override
public boolean onUnbind(Intent intent) {
mServiceInUse = false;
// Take a snapshot of the current playlist
saveQueue(true);
if (isPlaying() || mPausedByTransientLossOfFocus) {
// something is currently playing, or will be playing once
// an in-progress action requesting audio focus ends, so don't stop the service now.
return true;
}
// If there is a playlist but playback is paused, then wait a while
// before stopping the service, so that pause/resume isn't slow.
// Also delay stopping the service if we're transitioning between tracks.
if (mPlayListLen > 0 || mMediaplayerHandler.hasMessages(TRACK_ENDED)) {
Message msg = mDelayedStopHandler.obtainMessage();
mDelayedStopHandler.sendMessageDelayed(msg, IDLE_DELAY);
return true;
}
// No active playlist, OK to stop the service right now
stopSelf(mServiceStartId);
return true;
}
private Handler mDelayedStopHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
// Check again to make sure nothing is playing right now
if (isPlaying() || mPausedByTransientLossOfFocus || mServiceInUse
|| mMediaplayerHandler.hasMessages(TRACK_ENDED)) {
return;
}
// save the queue again, because it might have changed
// since the user exited the music app (because of
// party-shuffle or because the play-position changed)
saveQueue(true);
stopSelf(mServiceStartId);
}
};
/**
* Called when we receive a ACTION_MEDIA_EJECT notification.
*
* @param storagePath path to mount point for the removed media
*/
public void closeExternalStorageFiles(String storagePath) {
// stop playback and clean up if the SD card is going to be unmounted.
stop(true);
notifyChange(QUEUE_CHANGED);
notifyChange(META_CHANGED);
}
/**
* Registers an intent to listen for ACTION_MEDIA_EJECT notifications.
* The intent will call closeExternalStorageFiles() if the external media
* is going to be ejected, so applications can clean up any files they have open.
*/
public void registerExternalStorageListener() {
if (mUnmountReceiver == null) {
mUnmountReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(Intent.ACTION_MEDIA_EJECT)) {
saveQueue(true);
mQueueIsSaveable = false;
closeExternalStorageFiles(intent.getData().getPath());
} else if (action.equals(Intent.ACTION_MEDIA_MOUNTED)) {
mMediaMountedCount++;
mCardId = MusicUtils.getCardId(MediaPlaybackService.this);
reloadQueue();
mQueueIsSaveable = true;
notifyChange(QUEUE_CHANGED);
notifyChange(META_CHANGED);
}
}
};
IntentFilter iFilter = new IntentFilter();
iFilter.addAction(Intent.ACTION_MEDIA_EJECT);
iFilter.addAction(Intent.ACTION_MEDIA_MOUNTED);
iFilter.addDataScheme("file");
registerReceiver(mUnmountReceiver, iFilter);
}
}
/**
* Notify the change-receivers that something has changed.
* The intent that is sent contains the following data
* for the currently playing track:
* "id" - Integer: the database row ID
* "artist" - String: the name of the artist
* "album" - String: the name of the album
* "track" - String: the name of the track
* The intent has an action that is one of
* "com.android.music.metachanged"
* "com.android.music.queuechanged",
* "com.android.music.playbackcomplete"
* "com.android.music.playstatechanged"
* respectively indicating that a new track has
* started playing, that the playback queue has
* changed, that playback has stopped because
* the last file in the list has been played,
* or that the play-state changed (paused/resumed).
*/
private void notifyChange(String what) {
Intent i = new Intent(what);
i.putExtra("id", Long.valueOf(getAudioId()));
i.putExtra("artist", getArtistName());
i.putExtra("album",getAlbumName());
i.putExtra("track", getTrackName());
i.putExtra("playing", isPlaying());
sendStickyBroadcast(i);
if (what.equals(PLAYSTATE_CHANGED)) {
// mRemoteControlClient.setPlaybackState(isPlaying() ?
// RemoteControlClient.PLAYSTATE_PLAYING : RemoteControlClient.PLAYSTATE_PAUSED);
} else if (what.equals(META_CHANGED)) {
// RemoteControlClient.MetadataEditor ed = mRemoteControlClient.editMetadata(true);
// ed.putString(MediaMetadataRetriever.METADATA_KEY_TITLE, getTrackName());
// ed.putString(MediaMetadataRetriever.METADATA_KEY_ALBUM, getAlbumName());
// ed.putString(MediaMetadataRetriever.METADATA_KEY_ARTIST, getArtistName());
// ed.putLong(MediaMetadataRetriever.METADATA_KEY_DURATION, duration());
// Bitmap b = MusicUtils.getArtwork(this, getAudioId(), getAlbumId(), false);
// if (b != null) {
// ed.putBitmap(MetadataEditor.BITMAP_KEY_ARTWORK, b);
// }
// ed.apply();
}
if (what.equals(QUEUE_CHANGED)) {
saveQueue(true);
} else {
saveQueue(false);
}
// Share this notification directly with our widgets
mAppWidgetProvider.notifyChange(this, what);
}
private void ensurePlayListCapacity(int size) {
if (mPlayList == null || size > mPlayList.length) {
// reallocate at 2x requested size so we don't
// need to grow and copy the array for every
// insert
long [] newlist = new long[size * 2];
int len = mPlayList != null ? mPlayList.length : mPlayListLen;
for (int i = 0; i < len; i++) {
newlist[i] = mPlayList[i];
}
mPlayList = newlist;
}
// FIXME: shrink the array when the needed size is much smaller
// than the allocated size
}
// insert the list of songs at the specified position in the playlist
private void addToPlayList(long [] list, int position) {
int addlen = list.length;
if (position < 0) { // overwrite
mPlayListLen = 0;
position = 0;
}
ensurePlayListCapacity(mPlayListLen + addlen);
if (position > mPlayListLen) {
position = mPlayListLen;
}
// move part of list after insertion point
int tailsize = mPlayListLen - position;
for (int i = tailsize ; i > 0 ; i--) {
mPlayList[position + i] = mPlayList[position + i - addlen];
}
// copy list into playlist
for (int i = 0; i < addlen; i++) {
mPlayList[position + i] = list[i];
}
mPlayListLen += addlen;
if (mPlayListLen == 0) {
mCursor.close();
mCursor = null;
notifyChange(META_CHANGED);
}
}
/**
* Appends a list of tracks to the current playlist.
* If nothing is playing currently, playback will be started at
* the first track.
* If the action is NOW, playback will switch to the first of
* the new tracks immediately.
* @param list The list of tracks to append.
* @param action NOW, NEXT or LAST
*/
public void enqueue(long [] list, int action) {
synchronized(this) {
if (action == NEXT && mPlayPos + 1 < mPlayListLen) {
addToPlayList(list, mPlayPos + 1);
notifyChange(QUEUE_CHANGED);
} else {
// action == LAST || action == NOW || mPlayPos + 1 == mPlayListLen
addToPlayList(list, Integer.MAX_VALUE);
notifyChange(QUEUE_CHANGED);
if (action == NOW) {
mPlayPos = mPlayListLen - list.length;
openCurrentAndNext();
play();
notifyChange(META_CHANGED);
return;
}
}
if (mPlayPos < 0) {
mPlayPos = 0;
openCurrentAndNext();
play();
notifyChange(META_CHANGED);
}
}
}
/**
* Replaces the current playlist with a new list,
* and prepares for starting playback at the specified
* position in the list, or a random position if the
* specified position is 0.
* @param list The new list of tracks.
*/
public void open(long [] list, int position) {
synchronized (this) {
if (mShuffleMode == SHUFFLE_AUTO) {
mShuffleMode = SHUFFLE_NORMAL;
}
long oldId = getAudioId();
int listlength = list.length;
boolean newlist = true;
if (mPlayListLen == listlength) {
// possible fast path: list might be the same
newlist = false;
for (int i = 0; i < listlength; i++) {
if (list[i] != mPlayList[i]) {
newlist = true;
break;
}
}
}
if (newlist) {
addToPlayList(list, -1);
notifyChange(QUEUE_CHANGED);
}
int oldpos = mPlayPos;
if (position >= 0) {
mPlayPos = position;
} else {
mPlayPos = mRand.nextInt(mPlayListLen);
}
mHistory.clear();
saveBookmarkIfNeeded();
openCurrentAndNext();
if (oldId != getAudioId()) {
notifyChange(META_CHANGED);
}
}
}
/**
* Moves the item at index1 to index2.
* @param index1
* @param index2
*/
public void moveQueueItem(int index1, int index2) {
synchronized (this) {
if (index1 >= mPlayListLen) {
index1 = mPlayListLen - 1;
}
if (index2 >= mPlayListLen) {
index2 = mPlayListLen - 1;
}
if (index1 < index2) {
long tmp = mPlayList[index1];
for (int i = index1; i < index2; i++) {
mPlayList[i] = mPlayList[i+1];
}
mPlayList[index2] = tmp;
if (mPlayPos == index1) {
mPlayPos = index2;
} else if (mPlayPos >= index1 && mPlayPos <= index2) {
mPlayPos--;
}
} else if (index2 < index1) {
long tmp = mPlayList[index1];
for (int i = index1; i > index2; i--) {
mPlayList[i] = mPlayList[i-1];
}
mPlayList[index2] = tmp;
if (mPlayPos == index1) {
mPlayPos = index2;
} else if (mPlayPos >= index2 && mPlayPos <= index1) {
mPlayPos++;
}
}
notifyChange(QUEUE_CHANGED);
}
}
/**
* Returns the current play list
* @return An array of integers containing the IDs of the tracks in the play list
*/
public long [] getQueue() {
synchronized (this) {
int len = mPlayListLen;
long [] list = new long[len];
for (int i = 0; i < len; i++) {
list[i] = mPlayList[i];
}
return list;
}
}
private Cursor getCursorForId(long lid) {
String id = String.valueOf(lid);
Cursor c = getContentResolver().query(
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
mCursorCols, "_id=" + id , null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
private void openCurrentAndNext() {
synchronized (this) {
if (mCursor != null) {
mCursor.close();
mCursor = null;
}
if (mPlayListLen == 0) {
return;
}
stop(false);
mCursor = getCursorForId(mPlayList[mPlayPos]);
while(true) {
if (mCursor != null && mCursor.getCount() != 0 &&
open(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI + "/" +
mCursor.getLong(IDCOLIDX))) {
break;
}
// if we get here then opening the file failed. We can close the cursor now, because
// we're either going to create a new one next, or stop trying
if (mCursor != null) {
mCursor.close();
mCursor = null;
}
if (mOpenFailedCounter++ < 10 && mPlayListLen > 1) {
int pos = getNextPosition(false);
if (pos < 0) {
gotoIdleState();
if (mIsSupposedToBePlaying) {
mIsSupposedToBePlaying = false;
notifyChange(PLAYSTATE_CHANGED);
}
return;
}
mPlayPos = pos;
stop(false);
mPlayPos = pos;
mCursor = getCursorForId(mPlayList[mPlayPos]);
} else {
mOpenFailedCounter = 0;
if (!mQuietMode) {
Toast.makeText(this, R.string.playback_failed, Toast.LENGTH_SHORT).show();
}
Log.d(LOGTAG, "Failed to open file for playback");
gotoIdleState();
if (mIsSupposedToBePlaying) {
mIsSupposedToBePlaying = false;
notifyChange(PLAYSTATE_CHANGED);
}
return;
}
}
// go to bookmark if needed
if (isPodcast()) {
long bookmark = getBookmark();
// Start playing a little bit before the bookmark,
// so it's easier to get back in to the narrative.
seek(bookmark - 5000);
}
setNextTrack();
}
}
private void setNextTrack() {
mNextPlayPos = getNextPosition(false);
if (mNextPlayPos >= 0) {
long id = mPlayList[mNextPlayPos];
mPlayer.setNextDataSource(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI + "/" + id);
}
}
/**
* Opens the specified file and readies it for playback.
*
* @param path The full path of the file to be opened.
*/
public boolean open(String path) {
synchronized (this) {
if (path == null) {
return false;
}
// if mCursor is null, try to associate path with a database cursor
if (mCursor == null) {
ContentResolver resolver = getContentResolver();
Uri uri;
String where;
String selectionArgs[];
if (path.startsWith("content://media/")) {
uri = Uri.parse(path);
where = null;
selectionArgs = null;
} else {
uri = MediaStore.Audio.Media.getContentUriForPath(path);
where = MediaStore.Audio.Media.DATA + "=?";
selectionArgs = new String[] { path };
}
try {
mCursor = resolver.query(uri, mCursorCols, where, selectionArgs, null);
if (mCursor != null) {
if (mCursor.getCount() == 0) {
mCursor.close();
mCursor = null;
} else {
mCursor.moveToNext();
ensurePlayListCapacity(1);
mPlayListLen = 1;
mPlayList[0] = mCursor.getLong(IDCOLIDX);
mPlayPos = 0;
}
}
} catch (UnsupportedOperationException ex) {
}
}
mFileToPlay = path;
mPlayer.setDataSource(mFileToPlay);
if (mPlayer.isInitialized()) {
mOpenFailedCounter = 0;
return true;
}
stop(true);
return false;
}
}
/**
* Starts playback of a previously opened file.
*/
public void play() {
mAudioManager.requestAudioFocus(mAudioFocusListener, AudioManager.STREAM_MUSIC,
AudioManager.AUDIOFOCUS_GAIN);
mAudioManager.registerMediaButtonEventReceiver(new ComponentName(this.getPackageName(),
MediaButtonIntentReceiver.class.getName()));
if (mPlayer.isInitialized()) {
// if we are at the end of the song, go to the next song first
long duration = mPlayer.duration();
if (mRepeatMode != REPEAT_CURRENT && duration > 2000 &&
mPlayer.position() >= duration - 2000) {
gotoNext(true);
}
mPlayer.start();
// make sure we fade in, in case a previous fadein was stopped because
// of another focus loss
mMediaplayerHandler.removeMessages(FADEDOWN);
mMediaplayerHandler.sendEmptyMessage(FADEUP);
updateNotification();
if (!mIsSupposedToBePlaying) {
mIsSupposedToBePlaying = true;
notifyChange(PLAYSTATE_CHANGED);
}
} else if (mPlayListLen <= 0) {
// This is mostly so that if you press 'play' on a bluetooth headset
// without every having played anything before, it will still play
// something.
setShuffleMode(SHUFFLE_AUTO);
}
}
private void updateNotification() {
RemoteViews views = new RemoteViews(getPackageName(), R.layout.statusbar);
views.setImageViewResource(R.id.icon, R.drawable.stat_notify_musicplayer);
if (getAudioId() < 0) {
// streaming
views.setTextViewText(R.id.trackname, getPath());
views.setTextViewText(R.id.artistalbum, null);
} else {
String artist = getArtistName();
views.setTextViewText(R.id.trackname, getTrackName());
if (artist == null || artist.equals(MediaStore.UNKNOWN_STRING)) {
artist = getString(R.string.unknown_artist_name);
}
String album = getAlbumName();
if (album == null || album.equals(MediaStore.UNKNOWN_STRING)) {
album = getString(R.string.unknown_album_name);
}
views.setTextViewText(R.id.artistalbum,
getString(R.string.notification_artist_album, artist, album)
);
}
Notification status = new Notification();
status.contentView = views;
status.flags |= Notification.FLAG_ONGOING_EVENT;
status.icon = R.drawable.stat_notify_musicplayer;
status.contentIntent = PendingIntent.getActivity(this, 0,
new Intent("com.android.music.PLAYBACK_VIEWER")
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK), 0);
startForeground(PLAYBACKSERVICE_STATUS, status);
}
private void stop(boolean remove_status_icon) {
if (mPlayer.isInitialized()) {
mPlayer.stop();
}
mFileToPlay = null;
if (mCursor != null) {
mCursor.close();
mCursor = null;
}
if (remove_status_icon) {
gotoIdleState();
} else {
stopForeground(false);
}
if (remove_status_icon) {
mIsSupposedToBePlaying = false;
}
}
/**
* Stops playback.
*/
public void stop() {
stop(true);
}
/**
* Pauses playback (call play() to resume)
*/
public void pause() {
synchronized(this) {
mMediaplayerHandler.removeMessages(FADEUP);
if (isPlaying()) {
mPlayer.pause();
gotoIdleState();
mIsSupposedToBePlaying = false;
notifyChange(PLAYSTATE_CHANGED);
saveBookmarkIfNeeded();
}
}
}
/** Returns whether something is currently playing
*
* @return true if something is playing (or will be playing shortly, in case
* we're currently transitioning between tracks), false if not.
*/
public boolean isPlaying() {
return mIsSupposedToBePlaying;
}
/*
Desired behavior for prev/next/shuffle:
- NEXT will move to the next track in the list when not shuffling, and to
a track randomly picked from the not-yet-played tracks when shuffling.
If all tracks have already been played, pick from the full set, but
avoid picking the previously played track if possible.
- when shuffling, PREV will go to the previously played track. Hitting PREV
again will go to the track played before that, etc. When the start of the
history has been reached, PREV is a no-op.
When not shuffling, PREV will go to the sequentially previous track (the
difference with the shuffle-case is mainly that when not shuffling, the
user can back up to tracks that are not in the history).
Example:
When playing an album with 10 tracks from the start, and enabling shuffle
while playing track 5, the remaining tracks (6-10) will be shuffled, e.g.
the final play order might be 1-2-3-4-5-8-10-6-9-7.
When hitting 'prev' 8 times while playing track 7 in this example, the
user will go to tracks 9-6-10-8-5-4-3-2. If the user then hits 'next',
a random track will be picked again. If at any time user disables shuffling
the next/previous track will be picked in sequential order again.
*/
public void prev() {
synchronized (this) {
if (mShuffleMode == SHUFFLE_NORMAL) {
// go to previously-played track and remove it from the history
int histsize = mHistory.size();
if (histsize == 0) {
// prev is a no-op
return;
}
Integer pos = mHistory.remove(histsize - 1);
mPlayPos = pos.intValue();
} else {
if (mPlayPos > 0) {
mPlayPos--;
} else {
mPlayPos = mPlayListLen - 1;
}
}
saveBookmarkIfNeeded();
stop(false);
openCurrentAndNext();
play();
notifyChange(META_CHANGED);
}
}
/**
* Get the next position to play. Note that this may actually modify mPlayPos
* if playback is in SHUFFLE_AUTO mode and the shuffle list window needed to
* be adjusted. Either way, the return value is the next value that should be
* assigned to mPlayPos;
*/
private int getNextPosition(boolean force) {
if (mRepeatMode == REPEAT_CURRENT) {
if (mPlayPos < 0) return 0;
return mPlayPos;
} else if (mShuffleMode == SHUFFLE_NORMAL) {
// Pick random next track from the not-yet-played ones
// TODO: make it work right after adding/removing items in the queue.
// Store the current file in the history, but keep the history at a
// reasonable size
if (mPlayPos >= 0) {
mHistory.add(mPlayPos);
}
if (mHistory.size() > MAX_HISTORY_SIZE) {
mHistory.removeElementAt(0);
}
int numTracks = mPlayListLen;
int[] tracks = new int[numTracks];
for (int i=0;i < numTracks; i++) {
tracks[i] = i;
}
int numHistory = mHistory.size();
int numUnplayed = numTracks;
for (int i=0;i < numHistory; i++) {
int idx = mHistory.get(i).intValue();
if (idx < numTracks && tracks[idx] >= 0) {
numUnplayed--;
tracks[idx] = -1;
}
}
// 'numUnplayed' now indicates how many tracks have not yet
// been played, and 'tracks' contains the indices of those
// tracks.
if (numUnplayed <=0) {
// everything's already been played
if (mRepeatMode == REPEAT_ALL || force) {
//pick from full set
numUnplayed = numTracks;
for (int i=0;i < numTracks; i++) {
tracks[i] = i;
}
} else {
// all done
return -1;
}
}
int skip = mRand.nextInt(numUnplayed);
int cnt = -1;
while (true) {
while (tracks[++cnt] < 0)
;
skip--;
if (skip < 0) {
break;
}
}
return cnt;
} else if (mShuffleMode == SHUFFLE_AUTO) {
doAutoShuffleUpdate();
return mPlayPos + 1;
} else {
if (mPlayPos >= mPlayListLen - 1) {
// we're at the end of the list
if (mRepeatMode == REPEAT_NONE && !force) {
// all done
return -1;
} else if (mRepeatMode == REPEAT_ALL || force) {
return 0;
}
return -1;
} else {
return mPlayPos + 1;
}
}
}
public void gotoNext(boolean force) {
synchronized (this) {
if (mPlayListLen <= 0) {
Log.d(LOGTAG, "No play queue");
return;
}
int pos = getNextPosition(force);
if (pos < 0) {
gotoIdleState();
if (mIsSupposedToBePlaying) {
mIsSupposedToBePlaying = false;
notifyChange(PLAYSTATE_CHANGED);
}
return;
}
mPlayPos = pos;
saveBookmarkIfNeeded();
stop(false);
mPlayPos = pos;
openCurrentAndNext();
play();
notifyChange(META_CHANGED);
}
}
private void gotoIdleState() {
mDelayedStopHandler.removeCallbacksAndMessages(null);
Message msg = mDelayedStopHandler.obtainMessage();
mDelayedStopHandler.sendMessageDelayed(msg, IDLE_DELAY);
stopForeground(true);
}
private void saveBookmarkIfNeeded() {
try {
if (isPodcast()) {
long pos = position();
long bookmark = getBookmark();
long duration = duration();
if ((pos < bookmark && (pos + 10000) > bookmark) ||
(pos > bookmark && (pos - 10000) < bookmark)) {
// The existing bookmark is close to the current
// position, so don't update it.
return;
}
if (pos < 15000 || (pos + 10000) > duration) {
// if we're near the start or end, clear the bookmark
pos = 0;
}
// write 'pos' to the bookmark field
ContentValues values = new ContentValues();
values.put(MediaStore.Audio.Media.BOOKMARK, pos);
Uri uri = ContentUris.withAppendedId(
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, mCursor.getLong(IDCOLIDX));
getContentResolver().update(uri, values, null, null);
}
} catch (SQLiteException ex) {
}
}
// Make sure there are at least 5 items after the currently playing item
// and no more than 10 items before.
private void doAutoShuffleUpdate() {
boolean notify = false;
// remove old entries
if (mPlayPos > 10) {
removeTracks(0, mPlayPos - 9);
notify = true;
}
// add new entries if needed
int to_add = 7 - (mPlayListLen - (mPlayPos < 0 ? -1 : mPlayPos));
for (int i = 0; i < to_add; i++) {
// pick something at random from the list
int lookback = mHistory.size();
int idx = -1;
while(true) {
idx = mRand.nextInt(mAutoShuffleList.length);
if (!wasRecentlyUsed(idx, lookback)) {
break;
}
lookback /= 2;
}
mHistory.add(idx);
if (mHistory.size() > MAX_HISTORY_SIZE) {
mHistory.remove(0);
}
ensurePlayListCapacity(mPlayListLen + 1);
mPlayList[mPlayListLen++] = mAutoShuffleList[idx];
notify = true;
}
if (notify) {
notifyChange(QUEUE_CHANGED);
}
}
// check that the specified idx is not in the history (but only look at at
// most lookbacksize entries in the history)
private boolean wasRecentlyUsed(int idx, int lookbacksize) {
// early exit to prevent infinite loops in case idx == mPlayPos
if (lookbacksize == 0) {
return false;
}
int histsize = mHistory.size();
if (histsize < lookbacksize) {
Log.d(LOGTAG, "lookback too big");
lookbacksize = histsize;
}
int maxidx = histsize - 1;
for (int i = 0; i < lookbacksize; i++) {
long entry = mHistory.get(maxidx - i);
if (entry == idx) {
return true;
}
}
return false;
}
// A simple variation of Random that makes sure that the
// value it returns is not equal to the value it returned
// previously, unless the interval is 1.
private static class Shuffler {
private int mPrevious;
private Random mRandom = new Random();
public int nextInt(int interval) {
int ret;
do {
ret = mRandom.nextInt(interval);
} while (ret == mPrevious && interval > 1);
mPrevious = ret;
return ret;
}
};
private boolean makeAutoShuffleList() {
ContentResolver res = getContentResolver();
Cursor c = null;
try {
c = res.query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
new String[] {MediaStore.Audio.Media._ID}, MediaStore.Audio.Media.IS_MUSIC + "=1",
null, null);
if (c == null || c.getCount() == 0) {
return false;
}
int len = c.getCount();
long [] list = new long[len];
for (int i = 0; i < len; i++) {
c.moveToNext();
list[i] = c.getLong(0);
}
mAutoShuffleList = list;
return true;
} catch (RuntimeException ex) {
} finally {
if (c != null) {
c.close();
}
}
return false;
}
/**
* Removes the range of tracks specified from the play list. If a file within the range is
* the file currently being played, playback will move to the next file after the
* range.
* @param first The first file to be removed
* @param last The last file to be removed
* @return the number of tracks deleted
*/
public int removeTracks(int first, int last) {
int numremoved = removeTracksInternal(first, last);
if (numremoved > 0) {
notifyChange(QUEUE_CHANGED);
}
return numremoved;
}
private int removeTracksInternal(int first, int last) {
synchronized (this) {
if (last < first) return 0;
if (first < 0) first = 0;
if (last >= mPlayListLen) last = mPlayListLen - 1;
boolean gotonext = false;
if (first <= mPlayPos && mPlayPos <= last) {
mPlayPos = first;
gotonext = true;
} else if (mPlayPos > last) {
mPlayPos -= (last - first + 1);
}
int num = mPlayListLen - last - 1;
for (int i = 0; i < num; i++) {
mPlayList[first + i] = mPlayList[last + 1 + i];
}
mPlayListLen -= last - first + 1;
if (gotonext) {
if (mPlayListLen == 0) {
stop(true);
mPlayPos = -1;
if (mCursor != null) {
mCursor.close();
mCursor = null;
}
} else {
if (mPlayPos >= mPlayListLen) {
mPlayPos = 0;
}
boolean wasPlaying = isPlaying();
stop(false);
openCurrentAndNext();
if (wasPlaying) {
play();
}
}
notifyChange(META_CHANGED);
}
return last - first + 1;
}
}
/**
* Removes all instances of the track with the given id
* from the playlist.
* @param id The id to be removed
* @return how many instances of the track were removed
*/
public int removeTrack(long id) {
int numremoved = 0;
synchronized (this) {
for (int i = 0; i < mPlayListLen; i++) {
if (mPlayList[i] == id) {
numremoved += removeTracksInternal(i, i);
i--;
}
}
}
if (numremoved > 0) {
notifyChange(QUEUE_CHANGED);
}
return numremoved;
}
public void setShuffleMode(int shufflemode) {
synchronized(this) {
if (mShuffleMode == shufflemode && mPlayListLen > 0) {
return;
}
mShuffleMode = shufflemode;
if (mShuffleMode == SHUFFLE_AUTO) {
if (makeAutoShuffleList()) {
mPlayListLen = 0;
doAutoShuffleUpdate();
mPlayPos = 0;
openCurrentAndNext();
play();
notifyChange(META_CHANGED);
return;
} else {
// failed to build a list of files to shuffle
mShuffleMode = SHUFFLE_NONE;
}
}
saveQueue(false);
}
}
public int getShuffleMode() {
return mShuffleMode;
}
public void setRepeatMode(int repeatmode) {
synchronized(this) {
mRepeatMode = repeatmode;
setNextTrack();
saveQueue(false);
}
}
public int getRepeatMode() {
return mRepeatMode;
}
public int getMediaMountedCount() {
return mMediaMountedCount;
}
/**
* Returns the path of the currently playing file, or null if
* no file is currently playing.
*/
public String getPath() {
return mFileToPlay;
}
/**
* Returns the rowid of the currently playing file, or -1 if
* no file is currently playing.
*/
public long getAudioId() {
synchronized (this) {
if (mPlayPos >= 0 && mPlayer.isInitialized()) {
return mPlayList[mPlayPos];
}
}
return -1;
}
/**
* Returns the position in the queue
* @return the position in the queue
*/
public int getQueuePosition() {
synchronized(this) {
return mPlayPos;
}
}
/**
* Starts playing the track at the given position in the queue.
* @param pos The position in the queue of the track that will be played.
*/
public void setQueuePosition(int pos) {
synchronized(this) {
stop(false);
mPlayPos = pos;
openCurrentAndNext();
play();
notifyChange(META_CHANGED);
if (mShuffleMode == SHUFFLE_AUTO) {
doAutoShuffleUpdate();
}
}
}
public String getArtistName() {
synchronized(this) {
if (mCursor == null) {
return null;
}
return mCursor.getString(mCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ARTIST));
}
}
public long getArtistId() {
synchronized (this) {
if (mCursor == null) {
return -1;
}
return mCursor.getLong(mCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ARTIST_ID));
}
}
public String getAlbumName() {
synchronized (this) {
if (mCursor == null) {
return null;
}
return mCursor.getString(mCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM));
}
}
public long getAlbumId() {
synchronized (this) {
if (mCursor == null) {
return -1;
}
return mCursor.getLong(mCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM_ID));
}
}
public String getTrackName() {
synchronized (this) {
if (mCursor == null) {
return null;
}
return mCursor.getString(mCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.TITLE));
}
}
private boolean isPodcast() {
synchronized (this) {
if (mCursor == null) {
return false;
}
return (mCursor.getInt(PODCASTCOLIDX) > 0);
}
}
private long getBookmark() {
synchronized (this) {
if (mCursor == null) {
return 0;
}
return mCursor.getLong(BOOKMARKCOLIDX);
}
}
/**
* Returns the duration of the file in milliseconds.
* Currently this method returns -1 for the duration of MIDI files.
*/
public long duration() {
if (mPlayer.isInitialized()) {
return mPlayer.duration();
}
return -1;
}
/**
* Returns the current playback position in milliseconds
*/
public long position() {
if (mPlayer.isInitialized()) {
return mPlayer.position();
}
return -1;
}
/**
* Seeks to the position specified.
*
* @param pos The position to seek to, in milliseconds
*/
public long seek(long pos) {
if (mPlayer.isInitialized()) {
if (pos < 0) pos = 0;
if (pos > mPlayer.duration()) pos = mPlayer.duration();
return mPlayer.seek(pos);
}
return -1;
}
/**
* Sets the audio session ID.
*
* @param sessionId: the audio session ID.
*/
public void setAudioSessionId(int sessionId) {
synchronized (this) {
mPlayer.setAudioSessionId(sessionId);
}
}
/**
* Returns the audio session ID.
*/
public int getAudioSessionId() {
synchronized (this) {
return mPlayer.getAudioSessionId();
}
}
/**
* Provides a unified interface for dealing with midi files and
* other media files.
*/
private class MultiPlayer {
private CompatMediaPlayer mCurrentMediaPlayer = new CompatMediaPlayer();
private CompatMediaPlayer mNextMediaPlayer;
private Handler mHandler;
private boolean mIsInitialized = false;
public MultiPlayer() {
mCurrentMediaPlayer.setWakeMode(MediaPlaybackService.this, PowerManager.PARTIAL_WAKE_LOCK);
}
public void setDataSource(String path) {
mIsInitialized = setDataSourceImpl(mCurrentMediaPlayer, path);
if (mIsInitialized) {
setNextDataSource(null);
}
}
private boolean setDataSourceImpl(MediaPlayer player, String path) {
try {
player.reset();
player.setOnPreparedListener(null);
if (path.startsWith("content://")) {
player.setDataSource(MediaPlaybackService.this, Uri.parse(path));
} else {
player.setDataSource(path);
}
player.setAudioStreamType(AudioManager.STREAM_MUSIC);
player.prepare();
} catch (IOException ex) {
// TODO: notify the user why the file couldn't be opened
return false;
} catch (IllegalArgumentException ex) {
// TODO: notify the user why the file couldn't be opened
return false;
}
player.setOnCompletionListener(listener);
player.setOnErrorListener(errorListener);
Intent i = new Intent(AudioEffect.ACTION_OPEN_AUDIO_EFFECT_CONTROL_SESSION);
i.putExtra(AudioEffect.EXTRA_AUDIO_SESSION, getAudioSessionId());
i.putExtra(AudioEffect.EXTRA_PACKAGE_NAME, getPackageName());
sendBroadcast(i);
return true;
}
public void setNextDataSource(String path) {
mCurrentMediaPlayer.setNextMediaPlayer(null);
if (mNextMediaPlayer != null) {
mNextMediaPlayer.release();
mNextMediaPlayer = null;
}
if (path == null) {
return;
}
mNextMediaPlayer = new CompatMediaPlayer();
mNextMediaPlayer.setWakeMode(MediaPlaybackService.this, PowerManager.PARTIAL_WAKE_LOCK);
mNextMediaPlayer.setAudioSessionId(getAudioSessionId());
if (setDataSourceImpl(mNextMediaPlayer, path)) {
mCurrentMediaPlayer.setNextMediaPlayer(mNextMediaPlayer);
} else {
// failed to open next, we'll transition the old fashioned way,
// which will skip over the faulty file
mNextMediaPlayer.release();
mNextMediaPlayer = null;
}
}
public boolean isInitialized() {
return mIsInitialized;
}
public void start() {
MusicUtils.debugLog(new Exception("MultiPlayer.start called"));
mCurrentMediaPlayer.start();
}
public void stop() {
mCurrentMediaPlayer.reset();
mIsInitialized = false;
}
/**
* You CANNOT use this player anymore after calling release()
*/
public void release() {
stop();
mCurrentMediaPlayer.release();
}
public void pause() {
mCurrentMediaPlayer.pause();
}
public void setHandler(Handler handler) {
mHandler = handler;
}
MediaPlayer.OnCompletionListener listener = new MediaPlayer.OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
if (mp == mCurrentMediaPlayer && mNextMediaPlayer != null) {
mCurrentMediaPlayer.release();
mCurrentMediaPlayer = mNextMediaPlayer;
mNextMediaPlayer = null;
mHandler.sendEmptyMessage(TRACK_WENT_TO_NEXT);
} else {
// Acquire a temporary wakelock, since when we return from
// this callback the MediaPlayer will release its wakelock
// and allow the device to go to sleep.
// This temporary wakelock is released when the RELEASE_WAKELOCK
// message is processed, but just in case, put a timeout on it.
mWakeLock.acquire(30000);
mHandler.sendEmptyMessage(TRACK_ENDED);
mHandler.sendEmptyMessage(RELEASE_WAKELOCK);
}
}
};
MediaPlayer.OnErrorListener errorListener = new MediaPlayer.OnErrorListener() {
public boolean onError(MediaPlayer mp, int what, int extra) {
switch (what) {
case MediaPlayer.MEDIA_ERROR_SERVER_DIED:
mIsInitialized = false;
mCurrentMediaPlayer.release();
// Creating a new MediaPlayer and settings its wakemode does not
// require the media service, so it's OK to do this now, while the
// service is still being restarted
mCurrentMediaPlayer = new CompatMediaPlayer();
mCurrentMediaPlayer.setWakeMode(MediaPlaybackService.this, PowerManager.PARTIAL_WAKE_LOCK);
mHandler.sendMessageDelayed(mHandler.obtainMessage(SERVER_DIED), 2000);
return true;
default:
Log.d("MultiPlayer", "Error: " + what + "," + extra);
break;
}
return false;
}
};
public long duration() {
return mCurrentMediaPlayer.getDuration();
}
public long position() {
return mCurrentMediaPlayer.getCurrentPosition();
}
public long seek(long whereto) {
mCurrentMediaPlayer.seekTo((int) whereto);
return whereto;
}
public void setVolume(float vol) {
mCurrentMediaPlayer.setVolume(vol, vol);
}
public void setAudioSessionId(int sessionId) {
mCurrentMediaPlayer.setAudioSessionId(sessionId);
}
public int getAudioSessionId() {
return mCurrentMediaPlayer.getAudioSessionId();
}
}
static class CompatMediaPlayer extends MediaPlayer implements OnCompletionListener {
private boolean mCompatMode = true;
private MediaPlayer mNextPlayer;
private OnCompletionListener mCompletion;
public CompatMediaPlayer() {
try {
MediaPlayer.class.getMethod("setNextMediaPlayer", MediaPlayer.class);
mCompatMode = false;
} catch (NoSuchMethodException e) {
mCompatMode = true;
super.setOnCompletionListener(this);
}
}
public void setNextMediaPlayer(MediaPlayer next) {
if (mCompatMode) {
mNextPlayer = next;
} else {
super.setNextMediaPlayer(next);
}
}
@Override
public void setOnCompletionListener(OnCompletionListener listener) {
if (mCompatMode) {
mCompletion = listener;
} else {
super.setOnCompletionListener(listener);
}
}
@Override
public void onCompletion(MediaPlayer mp) {
if (mNextPlayer != null) {
// as it turns out, starting a new MediaPlayer on the completion
// of a previous player ends up slightly overlapping the two
// playbacks, so slightly delaying the start of the next player
// gives a better user experience
SystemClock.sleep(50);
mNextPlayer.start();
}
mCompletion.onCompletion(this);
}
}
/*
* By making this a static class with a WeakReference to the Service, we
* ensure that the Service can be GCd even when the system process still
* has a remote reference to the stub.
*/
static class ServiceStub extends IMediaPlaybackService.Stub {
WeakReference<MediaPlaybackService> mService;
ServiceStub(MediaPlaybackService service) {
mService = new WeakReference<MediaPlaybackService>(service);
}
public void openFile(String path)
{
mService.get().open(path);
}
public void open(long [] list, int position) {
mService.get().open(list, position);
}
public int getQueuePosition() {
return mService.get().getQueuePosition();
}
public void setQueuePosition(int index) {
mService.get().setQueuePosition(index);
}
public boolean isPlaying() {
return mService.get().isPlaying();
}
public void stop() {
mService.get().stop();
}
public void pause() {
mService.get().pause();
}
public void play() {
mService.get().play();
}
public void prev() {
mService.get().prev();
}
public void next() {
mService.get().gotoNext(true);
}
public String getTrackName() {
return mService.get().getTrackName();
}
public String getAlbumName() {
return mService.get().getAlbumName();
}
public long getAlbumId() {
return mService.get().getAlbumId();
}
public String getArtistName() {
return mService.get().getArtistName();
}
public long getArtistId() {
return mService.get().getArtistId();
}
public void enqueue(long [] list , int action) {
mService.get().enqueue(list, action);
}
public long [] getQueue() {
return mService.get().getQueue();
}
public void moveQueueItem(int from, int to) {
mService.get().moveQueueItem(from, to);
}
public String getPath() {
return mService.get().getPath();
}
public long getAudioId() {
return mService.get().getAudioId();
}
public long position() {
return mService.get().position();
}
public long duration() {
return mService.get().duration();
}
public long seek(long pos) {
return mService.get().seek(pos);
}
public void setShuffleMode(int shufflemode) {
mService.get().setShuffleMode(shufflemode);
}
public int getShuffleMode() {
return mService.get().getShuffleMode();
}
public int removeTracks(int first, int last) {
return mService.get().removeTracks(first, last);
}
public int removeTrack(long id) {
return mService.get().removeTrack(id);
}
public void setRepeatMode(int repeatmode) {
mService.get().setRepeatMode(repeatmode);
}
public int getRepeatMode() {
return mService.get().getRepeatMode();
}
public int getMediaMountedCount() {
return mService.get().getMediaMountedCount();
}
public int getAudioSessionId() {
return mService.get().getAudioSessionId();
}
}
@Override
protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
writer.println("" + mPlayListLen + " items in queue, currently at index " + mPlayPos);
writer.println("Currently loaded:");
writer.println(getArtistName());
writer.println(getAlbumName());
writer.println(getTrackName());
writer.println(getPath());
writer.println("playing: " + mIsSupposedToBePlaying);
writer.println("actual: " + mPlayer.mCurrentMediaPlayer.isPlaying());
writer.println("shuffle mode: " + mShuffleMode);
MusicUtils.debugDump(writer);
}
private final IBinder mBinder = new ServiceStub(this);
}
| private void reloadQueue() {
String q = null;
boolean newstyle = false;
int id = mCardId;
if (mPreferences.contains("cardid")) {
newstyle = true;
id = mPreferences.getInt("cardid", ~mCardId);
}
if (id == mCardId) {
// Only restore the saved playlist if the card is still
// the same one as when the playlist was saved
q = mPreferences.getString("queue", "");
}
int qlen = q != null ? q.length() : 0;
if (qlen > 1) {
//Log.i("@@@@ service", "loaded queue: " + q);
int plen = 0;
int n = 0;
int shift = 0;
for (int i = 0; i < qlen; i++) {
char c = q.charAt(i);
if (c == ';') {
ensurePlayListCapacity(plen + 1);
mPlayList[plen] = n;
plen++;
n = 0;
shift = 0;
} else {
if (c >= '0' && c <= '9') {
n += ((c - '0') << shift);
} else if (c >= 'a' && c <= 'f') {
n += ((10 + c - 'a') << shift);
} else {
// bogus playlist data
plen = 0;
break;
}
shift += 4;
}
}
mPlayListLen = plen;
int pos = mPreferences.getInt("curpos", 0);
if (pos < 0 || pos >= mPlayListLen) {
// The saved playlist is bogus, discard it
mPlayListLen = 0;
return;
}
mPlayPos = pos;
// When reloadQueue is called in response to a card-insertion,
// we might not be able to query the media provider right away.
// To deal with this, try querying for the current file, and if
// that fails, wait a while and try again. If that too fails,
// assume there is a problem and don't restore the state.
Cursor crsr = MusicUtils.query(this,
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
new String [] {"_id"}, "_id=" + mPlayList[mPlayPos] , null, null);
if (crsr == null || crsr.getCount() == 0) {
// wait a bit and try again
SystemClock.sleep(3000);
crsr = getContentResolver().query(
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
mCursorCols, "_id=" + mPlayList[mPlayPos] , null, null);
}
if (crsr != null) {
crsr.close();
}
// Make sure we don't auto-skip to the next song, since that
// also starts playback. What could happen in that case is:
// - music is paused
// - go to UMS and delete some files, including the currently playing one
// - come back from UMS
// (time passes)
// - music app is killed for some reason (out of memory)
// - music service is restarted, service restores state, doesn't find
// the "current" file, goes to the next and: playback starts on its
// own, potentially at some random inconvenient time.
mOpenFailedCounter = 20;
mQuietMode = true;
openCurrentAndNext();
mQuietMode = false;
if (!mPlayer.isInitialized()) {
// couldn't restore the saved state
mPlayListLen = 0;
return;
}
long seekpos = mPreferences.getLong("seekpos", 0);
seek(seekpos >= 0 && seekpos < duration() ? seekpos : 0);
Log.d(LOGTAG, "restored queue, currently at position "
+ position() + "/" + duration()
+ " (requested " + seekpos + ")");
int repmode = mPreferences.getInt("repeatmode", REPEAT_NONE);
if (repmode != REPEAT_ALL && repmode != REPEAT_CURRENT) {
repmode = REPEAT_NONE;
}
mRepeatMode = repmode;
int shufmode = mPreferences.getInt("shufflemode", SHUFFLE_NONE);
if (shufmode != SHUFFLE_AUTO && shufmode != SHUFFLE_NORMAL) {
shufmode = SHUFFLE_NONE;
}
if (shufmode != SHUFFLE_NONE) {
// in shuffle mode we need to restore the history too
q = mPreferences.getString("history", "");
qlen = q != null ? q.length() : 0;
if (qlen > 1) {
plen = 0;
n = 0;
shift = 0;
mHistory.clear();
for (int i = 0; i < qlen; i++) {
char c = q.charAt(i);
if (c == ';') {
if (n >= mPlayListLen) {
// bogus history data
mHistory.clear();
break;
}
mHistory.add(n);
n = 0;
shift = 0;
} else {
if (c >= '0' && c <= '9') {
n += ((c - '0') << shift);
} else if (c >= 'a' && c <= 'f') {
n += ((10 + c - 'a') << shift);
} else {
// bogus history data
mHistory.clear();
break;
}
shift += 4;
}
}
}
}
if (shufmode == SHUFFLE_AUTO) {
if (! makeAutoShuffleList()) {
shufmode = SHUFFLE_NONE;
}
}
mShuffleMode = shufmode;
}
}
@Override
public IBinder onBind(Intent intent) {
mDelayedStopHandler.removeCallbacksAndMessages(null);
mServiceInUse = true;
return mBinder;
}
@Override
public void onRebind(Intent intent) {
mDelayedStopHandler.removeCallbacksAndMessages(null);
mServiceInUse = true;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
mServiceStartId = startId;
mDelayedStopHandler.removeCallbacksAndMessages(null);
if (intent != null) {
String action = intent.getAction();
String cmd = intent.getStringExtra("command");
MusicUtils.debugLog("onStartCommand " + action + " / " + cmd);
if (CMDNEXT.equals(cmd) || NEXT_ACTION.equals(action)) {
gotoNext(true);
} else if (CMDPREVIOUS.equals(cmd) || PREVIOUS_ACTION.equals(action)) {
if (position() < 2000) {
prev();
} else {
seek(0);
play();
}
} else if (CMDTOGGLEPAUSE.equals(cmd) || TOGGLEPAUSE_ACTION.equals(action)) {
if (isPlaying()) {
pause();
mPausedByTransientLossOfFocus = false;
} else {
play();
}
} else if (CMDPAUSE.equals(cmd) || PAUSE_ACTION.equals(action)) {
pause();
mPausedByTransientLossOfFocus = false;
} else if (CMDPLAY.equals(cmd)) {
play();
} else if (CMDSTOP.equals(cmd)) {
pause();
mPausedByTransientLossOfFocus = false;
seek(0);
}
}
// make sure the service will shut down on its own if it was
// just started but not bound to and nothing is playing
mDelayedStopHandler.removeCallbacksAndMessages(null);
Message msg = mDelayedStopHandler.obtainMessage();
mDelayedStopHandler.sendMessageDelayed(msg, IDLE_DELAY);
return START_STICKY;
}
@Override
public boolean onUnbind(Intent intent) {
mServiceInUse = false;
// Take a snapshot of the current playlist
saveQueue(true);
if (isPlaying() || mPausedByTransientLossOfFocus) {
// something is currently playing, or will be playing once
// an in-progress action requesting audio focus ends, so don't stop the service now.
return true;
}
// If there is a playlist but playback is paused, then wait a while
// before stopping the service, so that pause/resume isn't slow.
// Also delay stopping the service if we're transitioning between tracks.
if (mPlayListLen > 0 || mMediaplayerHandler.hasMessages(TRACK_ENDED)) {
Message msg = mDelayedStopHandler.obtainMessage();
mDelayedStopHandler.sendMessageDelayed(msg, IDLE_DELAY);
return true;
}
// No active playlist, OK to stop the service right now
stopSelf(mServiceStartId);
return true;
}
private Handler mDelayedStopHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
// Check again to make sure nothing is playing right now
if (isPlaying() || mPausedByTransientLossOfFocus || mServiceInUse
|| mMediaplayerHandler.hasMessages(TRACK_ENDED)) {
return;
}
// save the queue again, because it might have changed
// since the user exited the music app (because of
// party-shuffle or because the play-position changed)
saveQueue(true);
stopSelf(mServiceStartId);
}
};
/**
* Called when we receive a ACTION_MEDIA_EJECT notification.
*
* @param storagePath path to mount point for the removed media
*/
public void closeExternalStorageFiles(String storagePath) {
// stop playback and clean up if the SD card is going to be unmounted.
stop(true);
notifyChange(QUEUE_CHANGED);
notifyChange(META_CHANGED);
}
/**
* Registers an intent to listen for ACTION_MEDIA_EJECT notifications.
* The intent will call closeExternalStorageFiles() if the external media
* is going to be ejected, so applications can clean up any files they have open.
*/
public void registerExternalStorageListener() {
if (mUnmountReceiver == null) {
mUnmountReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(Intent.ACTION_MEDIA_EJECT)) {
saveQueue(true);
mQueueIsSaveable = false;
closeExternalStorageFiles(intent.getData().getPath());
} else if (action.equals(Intent.ACTION_MEDIA_MOUNTED)) {
mMediaMountedCount++;
mCardId = MusicUtils.getCardId(MediaPlaybackService.this);
reloadQueue();
mQueueIsSaveable = true;
notifyChange(QUEUE_CHANGED);
notifyChange(META_CHANGED);
}
}
};
IntentFilter iFilter = new IntentFilter();
iFilter.addAction(Intent.ACTION_MEDIA_EJECT);
iFilter.addAction(Intent.ACTION_MEDIA_MOUNTED);
iFilter.addDataScheme("file");
registerReceiver(mUnmountReceiver, iFilter);
}
}
/**
* Notify the change-receivers that something has changed.
* The intent that is sent contains the following data
* for the currently playing track:
* "id" - Integer: the database row ID
* "artist" - String: the name of the artist
* "album" - String: the name of the album
* "track" - String: the name of the track
* The intent has an action that is one of
* "com.android.music.metachanged"
* "com.android.music.queuechanged",
* "com.android.music.playbackcomplete"
* "com.android.music.playstatechanged"
* respectively indicating that a new track has
* started playing, that the playback queue has
* changed, that playback has stopped because
* the last file in the list has been played,
* or that the play-state changed (paused/resumed).
*/
private void notifyChange(String what) {
Intent i = new Intent(what);
i.putExtra("id", Long.valueOf(getAudioId()));
i.putExtra("artist", getArtistName());
i.putExtra("album",getAlbumName());
i.putExtra("track", getTrackName());
i.putExtra("playing", isPlaying());
sendStickyBroadcast(i);
if (what.equals(PLAYSTATE_CHANGED)) {
// mRemoteControlClient.setPlaybackState(isPlaying() ?
// RemoteControlClient.PLAYSTATE_PLAYING : RemoteControlClient.PLAYSTATE_PAUSED);
} else if (what.equals(META_CHANGED)) {
// RemoteControlClient.MetadataEditor ed = mRemoteControlClient.editMetadata(true);
// ed.putString(MediaMetadataRetriever.METADATA_KEY_TITLE, getTrackName());
// ed.putString(MediaMetadataRetriever.METADATA_KEY_ALBUM, getAlbumName());
// ed.putString(MediaMetadataRetriever.METADATA_KEY_ARTIST, getArtistName());
// ed.putLong(MediaMetadataRetriever.METADATA_KEY_DURATION, duration());
// Bitmap b = MusicUtils.getArtwork(this, getAudioId(), getAlbumId(), false);
// if (b != null) {
// ed.putBitmap(MetadataEditor.BITMAP_KEY_ARTWORK, b);
// }
// ed.apply();
}
if (what.equals(QUEUE_CHANGED)) {
saveQueue(true);
} else {
saveQueue(false);
}
// Share this notification directly with our widgets
mAppWidgetProvider.notifyChange(this, what);
}
private void ensurePlayListCapacity(int size) {
if (mPlayList == null || size > mPlayList.length) {
// reallocate at 2x requested size so we don't
// need to grow and copy the array for every
// insert
long [] newlist = new long[size * 2];
int len = mPlayList != null ? mPlayList.length : mPlayListLen;
for (int i = 0; i < len; i++) {
newlist[i] = mPlayList[i];
}
mPlayList = newlist;
}
// FIXME: shrink the array when the needed size is much smaller
// than the allocated size
}
// insert the list of songs at the specified position in the playlist
private void addToPlayList(long [] list, int position) {
int addlen = list.length;
if (position < 0) { // overwrite
mPlayListLen = 0;
position = 0;
}
ensurePlayListCapacity(mPlayListLen + addlen);
if (position > mPlayListLen) {
position = mPlayListLen;
}
// move part of list after insertion point
int tailsize = mPlayListLen - position;
for (int i = tailsize ; i > 0 ; i--) {
mPlayList[position + i] = mPlayList[position + i - addlen];
}
// copy list into playlist
for (int i = 0; i < addlen; i++) {
mPlayList[position + i] = list[i];
}
mPlayListLen += addlen;
if (mPlayListLen == 0) {
mCursor.close();
mCursor = null;
notifyChange(META_CHANGED);
}
}
/**
* Appends a list of tracks to the current playlist.
* If nothing is playing currently, playback will be started at
* the first track.
* If the action is NOW, playback will switch to the first of
* the new tracks immediately.
* @param list The list of tracks to append.
* @param action NOW, NEXT or LAST
*/
public void enqueue(long [] list, int action) {
synchronized(this) {
if (action == NEXT && mPlayPos + 1 < mPlayListLen) {
addToPlayList(list, mPlayPos + 1);
notifyChange(QUEUE_CHANGED);
} else {
// action == LAST || action == NOW || mPlayPos + 1 == mPlayListLen
addToPlayList(list, Integer.MAX_VALUE);
notifyChange(QUEUE_CHANGED);
if (action == NOW) {
mPlayPos = mPlayListLen - list.length;
openCurrentAndNext();
play();
notifyChange(META_CHANGED);
return;
}
}
if (mPlayPos < 0) {
mPlayPos = 0;
openCurrentAndNext();
play();
notifyChange(META_CHANGED);
}
}
}
/**
* Replaces the current playlist with a new list,
* and prepares for starting playback at the specified
* position in the list, or a random position if the
* specified position is 0.
* @param list The new list of tracks.
*/
public void open(long [] list, int position) {
synchronized (this) {
if (mShuffleMode == SHUFFLE_AUTO) {
mShuffleMode = SHUFFLE_NORMAL;
}
long oldId = getAudioId();
int listlength = list.length;
boolean newlist = true;
if (mPlayListLen == listlength) {
// possible fast path: list might be the same
newlist = false;
for (int i = 0; i < listlength; i++) {
if (list[i] != mPlayList[i]) {
newlist = true;
break;
}
}
}
if (newlist) {
addToPlayList(list, -1);
notifyChange(QUEUE_CHANGED);
}
int oldpos = mPlayPos;
if (position >= 0) {
mPlayPos = position;
} else {
mPlayPos = mRand.nextInt(mPlayListLen);
}
mHistory.clear();
saveBookmarkIfNeeded();
openCurrentAndNext();
if (oldId != getAudioId()) {
notifyChange(META_CHANGED);
}
}
}
/**
* Moves the item at index1 to index2.
* @param index1
* @param index2
*/
public void moveQueueItem(int index1, int index2) {
synchronized (this) {
if (index1 >= mPlayListLen) {
index1 = mPlayListLen - 1;
}
if (index2 >= mPlayListLen) {
index2 = mPlayListLen - 1;
}
if (index1 < index2) {
long tmp = mPlayList[index1];
for (int i = index1; i < index2; i++) {
mPlayList[i] = mPlayList[i+1];
}
mPlayList[index2] = tmp;
if (mPlayPos == index1) {
mPlayPos = index2;
} else if (mPlayPos >= index1 && mPlayPos <= index2) {
mPlayPos--;
}
} else if (index2 < index1) {
long tmp = mPlayList[index1];
for (int i = index1; i > index2; i--) {
mPlayList[i] = mPlayList[i-1];
}
mPlayList[index2] = tmp;
if (mPlayPos == index1) {
mPlayPos = index2;
} else if (mPlayPos >= index2 && mPlayPos <= index1) {
mPlayPos++;
}
}
notifyChange(QUEUE_CHANGED);
}
}
/**
* Returns the current play list
* @return An array of integers containing the IDs of the tracks in the play list
*/
public long [] getQueue() {
synchronized (this) {
int len = mPlayListLen;
long [] list = new long[len];
for (int i = 0; i < len; i++) {
list[i] = mPlayList[i];
}
return list;
}
}
private Cursor getCursorForId(long lid) {
String id = String.valueOf(lid);
Cursor c = getContentResolver().query(
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
mCursorCols, "_id=" + id , null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
private void openCurrentAndNext() {
synchronized (this) {
if (mCursor != null) {
mCursor.close();
mCursor = null;
}
if (mPlayListLen == 0) {
return;
}
stop(false);
mCursor = getCursorForId(mPlayList[mPlayPos]);
while(true) {
if (mCursor != null && mCursor.getCount() != 0 &&
open(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI + "/" +
mCursor.getLong(IDCOLIDX))) {
break;
}
// if we get here then opening the file failed. We can close the cursor now, because
// we're either going to create a new one next, or stop trying
if (mCursor != null) {
mCursor.close();
mCursor = null;
}
if (mOpenFailedCounter++ < 10 && mPlayListLen > 1) {
int pos = getNextPosition(false);
if (pos < 0) {
gotoIdleState();
if (mIsSupposedToBePlaying) {
mIsSupposedToBePlaying = false;
notifyChange(PLAYSTATE_CHANGED);
}
return;
}
mPlayPos = pos;
stop(false);
mPlayPos = pos;
mCursor = getCursorForId(mPlayList[mPlayPos]);
} else {
mOpenFailedCounter = 0;
if (!mQuietMode) {
Toast.makeText(this, R.string.playback_failed, Toast.LENGTH_SHORT).show();
}
Log.d(LOGTAG, "Failed to open file for playback");
gotoIdleState();
if (mIsSupposedToBePlaying) {
mIsSupposedToBePlaying = false;
notifyChange(PLAYSTATE_CHANGED);
}
return;
}
}
// go to bookmark if needed
if (isPodcast()) {
long bookmark = getBookmark();
// Start playing a little bit before the bookmark,
// so it's easier to get back in to the narrative.
seek(bookmark - 5000);
}
setNextTrack();
}
}
private void setNextTrack() {
mNextPlayPos = getNextPosition(false);
if (mNextPlayPos >= 0) {
long id = mPlayList[mNextPlayPos];
mPlayer.setNextDataSource(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI + "/" + id);
} else {
mPlayer.setNextDataSource(null);
}
}
/**
* Opens the specified file and readies it for playback.
*
* @param path The full path of the file to be opened.
*/
public boolean open(String path) {
synchronized (this) {
if (path == null) {
return false;
}
// if mCursor is null, try to associate path with a database cursor
if (mCursor == null) {
ContentResolver resolver = getContentResolver();
Uri uri;
String where;
String selectionArgs[];
if (path.startsWith("content://media/")) {
uri = Uri.parse(path);
where = null;
selectionArgs = null;
} else {
uri = MediaStore.Audio.Media.getContentUriForPath(path);
where = MediaStore.Audio.Media.DATA + "=?";
selectionArgs = new String[] { path };
}
try {
mCursor = resolver.query(uri, mCursorCols, where, selectionArgs, null);
if (mCursor != null) {
if (mCursor.getCount() == 0) {
mCursor.close();
mCursor = null;
} else {
mCursor.moveToNext();
ensurePlayListCapacity(1);
mPlayListLen = 1;
mPlayList[0] = mCursor.getLong(IDCOLIDX);
mPlayPos = 0;
}
}
} catch (UnsupportedOperationException ex) {
}
}
mFileToPlay = path;
mPlayer.setDataSource(mFileToPlay);
if (mPlayer.isInitialized()) {
mOpenFailedCounter = 0;
return true;
}
stop(true);
return false;
}
}
/**
* Starts playback of a previously opened file.
*/
public void play() {
mAudioManager.requestAudioFocus(mAudioFocusListener, AudioManager.STREAM_MUSIC,
AudioManager.AUDIOFOCUS_GAIN);
mAudioManager.registerMediaButtonEventReceiver(new ComponentName(this.getPackageName(),
MediaButtonIntentReceiver.class.getName()));
if (mPlayer.isInitialized()) {
// if we are at the end of the song, go to the next song first
long duration = mPlayer.duration();
if (mRepeatMode != REPEAT_CURRENT && duration > 2000 &&
mPlayer.position() >= duration - 2000) {
gotoNext(true);
}
mPlayer.start();
// make sure we fade in, in case a previous fadein was stopped because
// of another focus loss
mMediaplayerHandler.removeMessages(FADEDOWN);
mMediaplayerHandler.sendEmptyMessage(FADEUP);
updateNotification();
if (!mIsSupposedToBePlaying) {
mIsSupposedToBePlaying = true;
notifyChange(PLAYSTATE_CHANGED);
}
} else if (mPlayListLen <= 0) {
// This is mostly so that if you press 'play' on a bluetooth headset
// without every having played anything before, it will still play
// something.
setShuffleMode(SHUFFLE_AUTO);
}
}
private void updateNotification() {
RemoteViews views = new RemoteViews(getPackageName(), R.layout.statusbar);
views.setImageViewResource(R.id.icon, R.drawable.stat_notify_musicplayer);
if (getAudioId() < 0) {
// streaming
views.setTextViewText(R.id.trackname, getPath());
views.setTextViewText(R.id.artistalbum, null);
} else {
String artist = getArtistName();
views.setTextViewText(R.id.trackname, getTrackName());
if (artist == null || artist.equals(MediaStore.UNKNOWN_STRING)) {
artist = getString(R.string.unknown_artist_name);
}
String album = getAlbumName();
if (album == null || album.equals(MediaStore.UNKNOWN_STRING)) {
album = getString(R.string.unknown_album_name);
}
views.setTextViewText(R.id.artistalbum,
getString(R.string.notification_artist_album, artist, album)
);
}
Notification status = new Notification();
status.contentView = views;
status.flags |= Notification.FLAG_ONGOING_EVENT;
status.icon = R.drawable.stat_notify_musicplayer;
status.contentIntent = PendingIntent.getActivity(this, 0,
new Intent("com.android.music.PLAYBACK_VIEWER")
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK), 0);
startForeground(PLAYBACKSERVICE_STATUS, status);
}
private void stop(boolean remove_status_icon) {
if (mPlayer.isInitialized()) {
mPlayer.stop();
}
mFileToPlay = null;
if (mCursor != null) {
mCursor.close();
mCursor = null;
}
if (remove_status_icon) {
gotoIdleState();
} else {
stopForeground(false);
}
if (remove_status_icon) {
mIsSupposedToBePlaying = false;
}
}
/**
* Stops playback.
*/
public void stop() {
stop(true);
}
/**
* Pauses playback (call play() to resume)
*/
public void pause() {
synchronized(this) {
mMediaplayerHandler.removeMessages(FADEUP);
if (isPlaying()) {
mPlayer.pause();
gotoIdleState();
mIsSupposedToBePlaying = false;
notifyChange(PLAYSTATE_CHANGED);
saveBookmarkIfNeeded();
}
}
}
/** Returns whether something is currently playing
*
* @return true if something is playing (or will be playing shortly, in case
* we're currently transitioning between tracks), false if not.
*/
public boolean isPlaying() {
return mIsSupposedToBePlaying;
}
/*
Desired behavior for prev/next/shuffle:
- NEXT will move to the next track in the list when not shuffling, and to
a track randomly picked from the not-yet-played tracks when shuffling.
If all tracks have already been played, pick from the full set, but
avoid picking the previously played track if possible.
- when shuffling, PREV will go to the previously played track. Hitting PREV
again will go to the track played before that, etc. When the start of the
history has been reached, PREV is a no-op.
When not shuffling, PREV will go to the sequentially previous track (the
difference with the shuffle-case is mainly that when not shuffling, the
user can back up to tracks that are not in the history).
Example:
When playing an album with 10 tracks from the start, and enabling shuffle
while playing track 5, the remaining tracks (6-10) will be shuffled, e.g.
the final play order might be 1-2-3-4-5-8-10-6-9-7.
When hitting 'prev' 8 times while playing track 7 in this example, the
user will go to tracks 9-6-10-8-5-4-3-2. If the user then hits 'next',
a random track will be picked again. If at any time user disables shuffling
the next/previous track will be picked in sequential order again.
*/
public void prev() {
synchronized (this) {
if (mShuffleMode == SHUFFLE_NORMAL) {
// go to previously-played track and remove it from the history
int histsize = mHistory.size();
if (histsize == 0) {
// prev is a no-op
return;
}
Integer pos = mHistory.remove(histsize - 1);
mPlayPos = pos.intValue();
} else {
if (mPlayPos > 0) {
mPlayPos--;
} else {
mPlayPos = mPlayListLen - 1;
}
}
saveBookmarkIfNeeded();
stop(false);
openCurrentAndNext();
play();
notifyChange(META_CHANGED);
}
}
/**
* Get the next position to play. Note that this may actually modify mPlayPos
* if playback is in SHUFFLE_AUTO mode and the shuffle list window needed to
* be adjusted. Either way, the return value is the next value that should be
* assigned to mPlayPos;
*/
private int getNextPosition(boolean force) {
if (mRepeatMode == REPEAT_CURRENT) {
if (mPlayPos < 0) return 0;
return mPlayPos;
} else if (mShuffleMode == SHUFFLE_NORMAL) {
// Pick random next track from the not-yet-played ones
// TODO: make it work right after adding/removing items in the queue.
// Store the current file in the history, but keep the history at a
// reasonable size
if (mPlayPos >= 0) {
mHistory.add(mPlayPos);
}
if (mHistory.size() > MAX_HISTORY_SIZE) {
mHistory.removeElementAt(0);
}
int numTracks = mPlayListLen;
int[] tracks = new int[numTracks];
for (int i=0;i < numTracks; i++) {
tracks[i] = i;
}
int numHistory = mHistory.size();
int numUnplayed = numTracks;
for (int i=0;i < numHistory; i++) {
int idx = mHistory.get(i).intValue();
if (idx < numTracks && tracks[idx] >= 0) {
numUnplayed--;
tracks[idx] = -1;
}
}
// 'numUnplayed' now indicates how many tracks have not yet
// been played, and 'tracks' contains the indices of those
// tracks.
if (numUnplayed <=0) {
// everything's already been played
if (mRepeatMode == REPEAT_ALL || force) {
//pick from full set
numUnplayed = numTracks;
for (int i=0;i < numTracks; i++) {
tracks[i] = i;
}
} else {
// all done
return -1;
}
}
int skip = mRand.nextInt(numUnplayed);
int cnt = -1;
while (true) {
while (tracks[++cnt] < 0)
;
skip--;
if (skip < 0) {
break;
}
}
return cnt;
} else if (mShuffleMode == SHUFFLE_AUTO) {
doAutoShuffleUpdate();
return mPlayPos + 1;
} else {
if (mPlayPos >= mPlayListLen - 1) {
// we're at the end of the list
if (mRepeatMode == REPEAT_NONE && !force) {
// all done
return -1;
} else if (mRepeatMode == REPEAT_ALL || force) {
return 0;
}
return -1;
} else {
return mPlayPos + 1;
}
}
}
public void gotoNext(boolean force) {
synchronized (this) {
if (mPlayListLen <= 0) {
Log.d(LOGTAG, "No play queue");
return;
}
int pos = getNextPosition(force);
if (pos < 0) {
gotoIdleState();
if (mIsSupposedToBePlaying) {
mIsSupposedToBePlaying = false;
notifyChange(PLAYSTATE_CHANGED);
}
return;
}
mPlayPos = pos;
saveBookmarkIfNeeded();
stop(false);
mPlayPos = pos;
openCurrentAndNext();
play();
notifyChange(META_CHANGED);
}
}
private void gotoIdleState() {
mDelayedStopHandler.removeCallbacksAndMessages(null);
Message msg = mDelayedStopHandler.obtainMessage();
mDelayedStopHandler.sendMessageDelayed(msg, IDLE_DELAY);
stopForeground(true);
}
private void saveBookmarkIfNeeded() {
try {
if (isPodcast()) {
long pos = position();
long bookmark = getBookmark();
long duration = duration();
if ((pos < bookmark && (pos + 10000) > bookmark) ||
(pos > bookmark && (pos - 10000) < bookmark)) {
// The existing bookmark is close to the current
// position, so don't update it.
return;
}
if (pos < 15000 || (pos + 10000) > duration) {
// if we're near the start or end, clear the bookmark
pos = 0;
}
// write 'pos' to the bookmark field
ContentValues values = new ContentValues();
values.put(MediaStore.Audio.Media.BOOKMARK, pos);
Uri uri = ContentUris.withAppendedId(
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, mCursor.getLong(IDCOLIDX));
getContentResolver().update(uri, values, null, null);
}
} catch (SQLiteException ex) {
}
}
// Make sure there are at least 5 items after the currently playing item
// and no more than 10 items before.
private void doAutoShuffleUpdate() {
boolean notify = false;
// remove old entries
if (mPlayPos > 10) {
removeTracks(0, mPlayPos - 9);
notify = true;
}
// add new entries if needed
int to_add = 7 - (mPlayListLen - (mPlayPos < 0 ? -1 : mPlayPos));
for (int i = 0; i < to_add; i++) {
// pick something at random from the list
int lookback = mHistory.size();
int idx = -1;
while(true) {
idx = mRand.nextInt(mAutoShuffleList.length);
if (!wasRecentlyUsed(idx, lookback)) {
break;
}
lookback /= 2;
}
mHistory.add(idx);
if (mHistory.size() > MAX_HISTORY_SIZE) {
mHistory.remove(0);
}
ensurePlayListCapacity(mPlayListLen + 1);
mPlayList[mPlayListLen++] = mAutoShuffleList[idx];
notify = true;
}
if (notify) {
notifyChange(QUEUE_CHANGED);
}
}
// check that the specified idx is not in the history (but only look at at
// most lookbacksize entries in the history)
private boolean wasRecentlyUsed(int idx, int lookbacksize) {
// early exit to prevent infinite loops in case idx == mPlayPos
if (lookbacksize == 0) {
return false;
}
int histsize = mHistory.size();
if (histsize < lookbacksize) {
Log.d(LOGTAG, "lookback too big");
lookbacksize = histsize;
}
int maxidx = histsize - 1;
for (int i = 0; i < lookbacksize; i++) {
long entry = mHistory.get(maxidx - i);
if (entry == idx) {
return true;
}
}
return false;
}
// A simple variation of Random that makes sure that the
// value it returns is not equal to the value it returned
// previously, unless the interval is 1.
private static class Shuffler {
private int mPrevious;
private Random mRandom = new Random();
public int nextInt(int interval) {
int ret;
do {
ret = mRandom.nextInt(interval);
} while (ret == mPrevious && interval > 1);
mPrevious = ret;
return ret;
}
};
private boolean makeAutoShuffleList() {
ContentResolver res = getContentResolver();
Cursor c = null;
try {
c = res.query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
new String[] {MediaStore.Audio.Media._ID}, MediaStore.Audio.Media.IS_MUSIC + "=1",
null, null);
if (c == null || c.getCount() == 0) {
return false;
}
int len = c.getCount();
long [] list = new long[len];
for (int i = 0; i < len; i++) {
c.moveToNext();
list[i] = c.getLong(0);
}
mAutoShuffleList = list;
return true;
} catch (RuntimeException ex) {
} finally {
if (c != null) {
c.close();
}
}
return false;
}
/**
* Removes the range of tracks specified from the play list. If a file within the range is
* the file currently being played, playback will move to the next file after the
* range.
* @param first The first file to be removed
* @param last The last file to be removed
* @return the number of tracks deleted
*/
public int removeTracks(int first, int last) {
int numremoved = removeTracksInternal(first, last);
if (numremoved > 0) {
notifyChange(QUEUE_CHANGED);
}
return numremoved;
}
private int removeTracksInternal(int first, int last) {
synchronized (this) {
if (last < first) return 0;
if (first < 0) first = 0;
if (last >= mPlayListLen) last = mPlayListLen - 1;
boolean gotonext = false;
if (first <= mPlayPos && mPlayPos <= last) {
mPlayPos = first;
gotonext = true;
} else if (mPlayPos > last) {
mPlayPos -= (last - first + 1);
}
int num = mPlayListLen - last - 1;
for (int i = 0; i < num; i++) {
mPlayList[first + i] = mPlayList[last + 1 + i];
}
mPlayListLen -= last - first + 1;
if (gotonext) {
if (mPlayListLen == 0) {
stop(true);
mPlayPos = -1;
if (mCursor != null) {
mCursor.close();
mCursor = null;
}
} else {
if (mPlayPos >= mPlayListLen) {
mPlayPos = 0;
}
boolean wasPlaying = isPlaying();
stop(false);
openCurrentAndNext();
if (wasPlaying) {
play();
}
}
notifyChange(META_CHANGED);
}
return last - first + 1;
}
}
/**
* Removes all instances of the track with the given id
* from the playlist.
* @param id The id to be removed
* @return how many instances of the track were removed
*/
public int removeTrack(long id) {
int numremoved = 0;
synchronized (this) {
for (int i = 0; i < mPlayListLen; i++) {
if (mPlayList[i] == id) {
numremoved += removeTracksInternal(i, i);
i--;
}
}
}
if (numremoved > 0) {
notifyChange(QUEUE_CHANGED);
}
return numremoved;
}
public void setShuffleMode(int shufflemode) {
synchronized(this) {
if (mShuffleMode == shufflemode && mPlayListLen > 0) {
return;
}
mShuffleMode = shufflemode;
if (mShuffleMode == SHUFFLE_AUTO) {
if (makeAutoShuffleList()) {
mPlayListLen = 0;
doAutoShuffleUpdate();
mPlayPos = 0;
openCurrentAndNext();
play();
notifyChange(META_CHANGED);
return;
} else {
// failed to build a list of files to shuffle
mShuffleMode = SHUFFLE_NONE;
}
}
saveQueue(false);
}
}
public int getShuffleMode() {
return mShuffleMode;
}
public void setRepeatMode(int repeatmode) {
synchronized(this) {
mRepeatMode = repeatmode;
setNextTrack();
saveQueue(false);
}
}
public int getRepeatMode() {
return mRepeatMode;
}
public int getMediaMountedCount() {
return mMediaMountedCount;
}
/**
* Returns the path of the currently playing file, or null if
* no file is currently playing.
*/
public String getPath() {
return mFileToPlay;
}
/**
* Returns the rowid of the currently playing file, or -1 if
* no file is currently playing.
*/
public long getAudioId() {
synchronized (this) {
if (mPlayPos >= 0 && mPlayer.isInitialized()) {
return mPlayList[mPlayPos];
}
}
return -1;
}
/**
* Returns the position in the queue
* @return the position in the queue
*/
public int getQueuePosition() {
synchronized(this) {
return mPlayPos;
}
}
/**
* Starts playing the track at the given position in the queue.
* @param pos The position in the queue of the track that will be played.
*/
public void setQueuePosition(int pos) {
synchronized(this) {
stop(false);
mPlayPos = pos;
openCurrentAndNext();
play();
notifyChange(META_CHANGED);
if (mShuffleMode == SHUFFLE_AUTO) {
doAutoShuffleUpdate();
}
}
}
public String getArtistName() {
synchronized(this) {
if (mCursor == null) {
return null;
}
return mCursor.getString(mCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ARTIST));
}
}
public long getArtistId() {
synchronized (this) {
if (mCursor == null) {
return -1;
}
return mCursor.getLong(mCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ARTIST_ID));
}
}
public String getAlbumName() {
synchronized (this) {
if (mCursor == null) {
return null;
}
return mCursor.getString(mCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM));
}
}
public long getAlbumId() {
synchronized (this) {
if (mCursor == null) {
return -1;
}
return mCursor.getLong(mCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM_ID));
}
}
public String getTrackName() {
synchronized (this) {
if (mCursor == null) {
return null;
}
return mCursor.getString(mCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.TITLE));
}
}
private boolean isPodcast() {
synchronized (this) {
if (mCursor == null) {
return false;
}
return (mCursor.getInt(PODCASTCOLIDX) > 0);
}
}
private long getBookmark() {
synchronized (this) {
if (mCursor == null) {
return 0;
}
return mCursor.getLong(BOOKMARKCOLIDX);
}
}
/**
* Returns the duration of the file in milliseconds.
* Currently this method returns -1 for the duration of MIDI files.
*/
public long duration() {
if (mPlayer.isInitialized()) {
return mPlayer.duration();
}
return -1;
}
/**
* Returns the current playback position in milliseconds
*/
public long position() {
if (mPlayer.isInitialized()) {
return mPlayer.position();
}
return -1;
}
/**
* Seeks to the position specified.
*
* @param pos The position to seek to, in milliseconds
*/
public long seek(long pos) {
if (mPlayer.isInitialized()) {
if (pos < 0) pos = 0;
if (pos > mPlayer.duration()) pos = mPlayer.duration();
return mPlayer.seek(pos);
}
return -1;
}
/**
* Sets the audio session ID.
*
* @param sessionId: the audio session ID.
*/
public void setAudioSessionId(int sessionId) {
synchronized (this) {
mPlayer.setAudioSessionId(sessionId);
}
}
/**
* Returns the audio session ID.
*/
public int getAudioSessionId() {
synchronized (this) {
return mPlayer.getAudioSessionId();
}
}
/**
* Provides a unified interface for dealing with midi files and
* other media files.
*/
private class MultiPlayer {
private CompatMediaPlayer mCurrentMediaPlayer = new CompatMediaPlayer();
private CompatMediaPlayer mNextMediaPlayer;
private Handler mHandler;
private boolean mIsInitialized = false;
public MultiPlayer() {
mCurrentMediaPlayer.setWakeMode(MediaPlaybackService.this, PowerManager.PARTIAL_WAKE_LOCK);
}
public void setDataSource(String path) {
mIsInitialized = setDataSourceImpl(mCurrentMediaPlayer, path);
if (mIsInitialized) {
setNextDataSource(null);
}
}
private boolean setDataSourceImpl(MediaPlayer player, String path) {
try {
player.reset();
player.setOnPreparedListener(null);
if (path.startsWith("content://")) {
player.setDataSource(MediaPlaybackService.this, Uri.parse(path));
} else {
player.setDataSource(path);
}
player.setAudioStreamType(AudioManager.STREAM_MUSIC);
player.prepare();
} catch (IOException ex) {
// TODO: notify the user why the file couldn't be opened
return false;
} catch (IllegalArgumentException ex) {
// TODO: notify the user why the file couldn't be opened
return false;
}
player.setOnCompletionListener(listener);
player.setOnErrorListener(errorListener);
Intent i = new Intent(AudioEffect.ACTION_OPEN_AUDIO_EFFECT_CONTROL_SESSION);
i.putExtra(AudioEffect.EXTRA_AUDIO_SESSION, getAudioSessionId());
i.putExtra(AudioEffect.EXTRA_PACKAGE_NAME, getPackageName());
sendBroadcast(i);
return true;
}
public void setNextDataSource(String path) {
mCurrentMediaPlayer.setNextMediaPlayer(null);
if (mNextMediaPlayer != null) {
mNextMediaPlayer.release();
mNextMediaPlayer = null;
}
if (path == null) {
return;
}
mNextMediaPlayer = new CompatMediaPlayer();
mNextMediaPlayer.setWakeMode(MediaPlaybackService.this, PowerManager.PARTIAL_WAKE_LOCK);
mNextMediaPlayer.setAudioSessionId(getAudioSessionId());
if (setDataSourceImpl(mNextMediaPlayer, path)) {
mCurrentMediaPlayer.setNextMediaPlayer(mNextMediaPlayer);
} else {
// failed to open next, we'll transition the old fashioned way,
// which will skip over the faulty file
mNextMediaPlayer.release();
mNextMediaPlayer = null;
}
}
public boolean isInitialized() {
return mIsInitialized;
}
public void start() {
MusicUtils.debugLog(new Exception("MultiPlayer.start called"));
mCurrentMediaPlayer.start();
}
public void stop() {
mCurrentMediaPlayer.reset();
mIsInitialized = false;
}
/**
* You CANNOT use this player anymore after calling release()
*/
public void release() {
stop();
mCurrentMediaPlayer.release();
}
public void pause() {
mCurrentMediaPlayer.pause();
}
public void setHandler(Handler handler) {
mHandler = handler;
}
MediaPlayer.OnCompletionListener listener = new MediaPlayer.OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
if (mp == mCurrentMediaPlayer && mNextMediaPlayer != null) {
mCurrentMediaPlayer.release();
mCurrentMediaPlayer = mNextMediaPlayer;
mNextMediaPlayer = null;
mHandler.sendEmptyMessage(TRACK_WENT_TO_NEXT);
} else {
// Acquire a temporary wakelock, since when we return from
// this callback the MediaPlayer will release its wakelock
// and allow the device to go to sleep.
// This temporary wakelock is released when the RELEASE_WAKELOCK
// message is processed, but just in case, put a timeout on it.
mWakeLock.acquire(30000);
mHandler.sendEmptyMessage(TRACK_ENDED);
mHandler.sendEmptyMessage(RELEASE_WAKELOCK);
}
}
};
MediaPlayer.OnErrorListener errorListener = new MediaPlayer.OnErrorListener() {
public boolean onError(MediaPlayer mp, int what, int extra) {
switch (what) {
case MediaPlayer.MEDIA_ERROR_SERVER_DIED:
mIsInitialized = false;
mCurrentMediaPlayer.release();
// Creating a new MediaPlayer and settings its wakemode does not
// require the media service, so it's OK to do this now, while the
// service is still being restarted
mCurrentMediaPlayer = new CompatMediaPlayer();
mCurrentMediaPlayer.setWakeMode(MediaPlaybackService.this, PowerManager.PARTIAL_WAKE_LOCK);
mHandler.sendMessageDelayed(mHandler.obtainMessage(SERVER_DIED), 2000);
return true;
default:
Log.d("MultiPlayer", "Error: " + what + "," + extra);
break;
}
return false;
}
};
public long duration() {
return mCurrentMediaPlayer.getDuration();
}
public long position() {
return mCurrentMediaPlayer.getCurrentPosition();
}
public long seek(long whereto) {
mCurrentMediaPlayer.seekTo((int) whereto);
return whereto;
}
public void setVolume(float vol) {
mCurrentMediaPlayer.setVolume(vol, vol);
}
public void setAudioSessionId(int sessionId) {
mCurrentMediaPlayer.setAudioSessionId(sessionId);
}
public int getAudioSessionId() {
return mCurrentMediaPlayer.getAudioSessionId();
}
}
static class CompatMediaPlayer extends MediaPlayer implements OnCompletionListener {
private boolean mCompatMode = true;
private MediaPlayer mNextPlayer;
private OnCompletionListener mCompletion;
public CompatMediaPlayer() {
try {
MediaPlayer.class.getMethod("setNextMediaPlayer", MediaPlayer.class);
mCompatMode = false;
} catch (NoSuchMethodException e) {
mCompatMode = true;
super.setOnCompletionListener(this);
}
}
public void setNextMediaPlayer(MediaPlayer next) {
if (mCompatMode) {
mNextPlayer = next;
} else {
super.setNextMediaPlayer(next);
}
}
@Override
public void setOnCompletionListener(OnCompletionListener listener) {
if (mCompatMode) {
mCompletion = listener;
} else {
super.setOnCompletionListener(listener);
}
}
@Override
public void onCompletion(MediaPlayer mp) {
if (mNextPlayer != null) {
// as it turns out, starting a new MediaPlayer on the completion
// of a previous player ends up slightly overlapping the two
// playbacks, so slightly delaying the start of the next player
// gives a better user experience
SystemClock.sleep(50);
mNextPlayer.start();
}
mCompletion.onCompletion(this);
}
}
/*
* By making this a static class with a WeakReference to the Service, we
* ensure that the Service can be GCd even when the system process still
* has a remote reference to the stub.
*/
static class ServiceStub extends IMediaPlaybackService.Stub {
WeakReference<MediaPlaybackService> mService;
ServiceStub(MediaPlaybackService service) {
mService = new WeakReference<MediaPlaybackService>(service);
}
public void openFile(String path)
{
mService.get().open(path);
}
public void open(long [] list, int position) {
mService.get().open(list, position);
}
public int getQueuePosition() {
return mService.get().getQueuePosition();
}
public void setQueuePosition(int index) {
mService.get().setQueuePosition(index);
}
public boolean isPlaying() {
return mService.get().isPlaying();
}
public void stop() {
mService.get().stop();
}
public void pause() {
mService.get().pause();
}
public void play() {
mService.get().play();
}
public void prev() {
mService.get().prev();
}
public void next() {
mService.get().gotoNext(true);
}
public String getTrackName() {
return mService.get().getTrackName();
}
public String getAlbumName() {
return mService.get().getAlbumName();
}
public long getAlbumId() {
return mService.get().getAlbumId();
}
public String getArtistName() {
return mService.get().getArtistName();
}
public long getArtistId() {
return mService.get().getArtistId();
}
public void enqueue(long [] list , int action) {
mService.get().enqueue(list, action);
}
public long [] getQueue() {
return mService.get().getQueue();
}
public void moveQueueItem(int from, int to) {
mService.get().moveQueueItem(from, to);
}
public String getPath() {
return mService.get().getPath();
}
public long getAudioId() {
return mService.get().getAudioId();
}
public long position() {
return mService.get().position();
}
public long duration() {
return mService.get().duration();
}
public long seek(long pos) {
return mService.get().seek(pos);
}
public void setShuffleMode(int shufflemode) {
mService.get().setShuffleMode(shufflemode);
}
public int getShuffleMode() {
return mService.get().getShuffleMode();
}
public int removeTracks(int first, int last) {
return mService.get().removeTracks(first, last);
}
public int removeTrack(long id) {
return mService.get().removeTrack(id);
}
public void setRepeatMode(int repeatmode) {
mService.get().setRepeatMode(repeatmode);
}
public int getRepeatMode() {
return mService.get().getRepeatMode();
}
public int getMediaMountedCount() {
return mService.get().getMediaMountedCount();
}
public int getAudioSessionId() {
return mService.get().getAudioSessionId();
}
}
@Override
protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
writer.println("" + mPlayListLen + " items in queue, currently at index " + mPlayPos);
writer.println("Currently loaded:");
writer.println(getArtistName());
writer.println(getAlbumName());
writer.println(getTrackName());
writer.println(getPath());
writer.println("playing: " + mIsSupposedToBePlaying);
writer.println("actual: " + mPlayer.mCurrentMediaPlayer.isPlaying());
writer.println("shuffle mode: " + mShuffleMode);
MusicUtils.debugDump(writer);
}
private final IBinder mBinder = new ServiceStub(this);
}
|
diff --git a/src/rajawali/primitives/Sphere.java b/src/rajawali/primitives/Sphere.java
index 2bfcf4f4..3055df16 100644
--- a/src/rajawali/primitives/Sphere.java
+++ b/src/rajawali/primitives/Sphere.java
@@ -1,160 +1,160 @@
package rajawali.primitives;
import rajawali.BaseObject3D;
/**
* A sphere primitive. The constructor takes two boolean arguments that indicate whether certain buffers should be
* created or not. Not creating these buffers can reduce memory footprint.
* <p>
* When creating solid color sphere both <code>createTextureCoordinates</code> and <code>createVertexColorBuffer</code>
* can be set to <code>false</code>.
* <p>
* When creating a textured sphere <code>createTextureCoordinates</code> should be set to <code>true</code> and
* <code>createVertexColorBuffer</code> should be set to <code>false</code>.
* <p>
* When creating a sphere without a texture but with different colors per texture <code>createTextureCoordinates</code>
* should be set to <code>false</code> and <code>createVertexColorBuffer</code> should be set to <code>true</code>.
*
* @author dennis.ippel
*
*/
public class Sphere extends BaseObject3D {
private final float PI = (float) Math.PI;
private float mRadius;
private int mSegmentsW;
private int mSegmentsH;
private boolean mCreateTextureCoords;
private boolean mCreateVertexColorBuffer;
/**
* Creates a sphere primitive. Calling this constructor will create texture coordinates but no vertex color buffer.
*
* @param radius
* The radius of the sphere
* @param segmentsW
* The number of vertical segments
* @param segmentsH
* The number of horizontal segments
*/
public Sphere(float radius, int segmentsW, int segmentsH) {
this(radius, segmentsW, segmentsH, true, false);
}
/**
* Creates a sphere primitive.
*
* @param radius
* The radius of the sphere
* @param segmentsW
* The number of vertical segments
* @param segmentsH
* The number of horizontal segments
* @param createTextureCoordinates
* A boolean that indicates whether the texture coordinates should be calculated or not.
* @param createVertexColorBuffer
* A boolean that indicates whether a vertex color buffer should be created or not.
*/
public Sphere(float radius, int segmentsW, int segmentsH, boolean createTextureCoordinates,
boolean createVertexColorBuffer) {
super();
mRadius = radius;
mSegmentsW = segmentsW;
mSegmentsH = segmentsH;
mCreateTextureCoords = createTextureCoordinates;
mCreateVertexColorBuffer = createVertexColorBuffer;
init();
}
protected void init() {
int numVertices = (mSegmentsW + 1) * (mSegmentsH + 1);
int numIndices = 2 * mSegmentsW * (mSegmentsH - 1) * 3;
float[] vertices = new float[numVertices * 3];
float[] normals = new float[numVertices * 3];
int[] indices = new int[numIndices];
int i, j;
int vertIndex = 0, index = 0;
final float normLen = 1.0f / mRadius;
for (j = 0; j <= mSegmentsH; ++j) {
float horAngle = PI * j / mSegmentsH;
float z = mRadius * (float) Math.cos(horAngle);
float ringRadius = mRadius * (float) Math.sin(horAngle);
for (i = 0; i <= mSegmentsW; ++i) {
float verAngle = 2.0f * PI * i / mSegmentsW;
float x = ringRadius * (float) Math.cos(verAngle);
float y = ringRadius * (float) Math.sin(verAngle);
normals[vertIndex] = x * normLen;
vertices[vertIndex++] = x;
normals[vertIndex] = z * normLen;
vertices[vertIndex++] = z;
normals[vertIndex] = y * normLen;
vertices[vertIndex++] = y;
if (i > 0 && j > 0) {
int a = (mSegmentsW + 1) * j + i;
int b = (mSegmentsW + 1) * j + i - 1;
int c = (mSegmentsW + 1) * (j - 1) + i - 1;
int d = (mSegmentsW + 1) * (j - 1) + i;
if (j == mSegmentsH) {
indices[index++] = a;
indices[index++] = c;
indices[index++] = d;
} else if (j == 1) {
indices[index++] = a;
indices[index++] = b;
indices[index++] = c;
} else {
indices[index++] = a;
indices[index++] = b;
indices[index++] = c;
indices[index++] = a;
indices[index++] = c;
indices[index++] = d;
}
}
}
}
float[] textureCoords = null;
if (mCreateTextureCoords) {
int numUvs = (mSegmentsH + 1) * (mSegmentsW + 1) * 2;
textureCoords = new float[numUvs];
numUvs = 0;
for (j = 0; j <= mSegmentsH; ++j) {
- for (i = 0; i <= mSegmentsW; ++i) {
- textureCoords[numUvs++] = -(float) i / mSegmentsW;
+ for (i = mSegmentsW; i >= 0; --i) {
+ textureCoords[numUvs++] = (float) i / mSegmentsW;
textureCoords[numUvs++] = (float) j / mSegmentsH;
}
}
}
float[] colors = null;
if (mCreateVertexColorBuffer)
{
int numColors = numVertices * 4;
colors = new float[numColors];
for (j = 0; j < numColors; j += 4)
{
colors[j] = 1.0f;
colors[j + 1] = 0;
colors[j + 2] = 0;
colors[j + 3] = 1.0f;
}
}
setData(vertices, normals, textureCoords, colors, indices);
vertices = null;
normals = null;
textureCoords = null;
indices = null;
}
}
| true | true | protected void init() {
int numVertices = (mSegmentsW + 1) * (mSegmentsH + 1);
int numIndices = 2 * mSegmentsW * (mSegmentsH - 1) * 3;
float[] vertices = new float[numVertices * 3];
float[] normals = new float[numVertices * 3];
int[] indices = new int[numIndices];
int i, j;
int vertIndex = 0, index = 0;
final float normLen = 1.0f / mRadius;
for (j = 0; j <= mSegmentsH; ++j) {
float horAngle = PI * j / mSegmentsH;
float z = mRadius * (float) Math.cos(horAngle);
float ringRadius = mRadius * (float) Math.sin(horAngle);
for (i = 0; i <= mSegmentsW; ++i) {
float verAngle = 2.0f * PI * i / mSegmentsW;
float x = ringRadius * (float) Math.cos(verAngle);
float y = ringRadius * (float) Math.sin(verAngle);
normals[vertIndex] = x * normLen;
vertices[vertIndex++] = x;
normals[vertIndex] = z * normLen;
vertices[vertIndex++] = z;
normals[vertIndex] = y * normLen;
vertices[vertIndex++] = y;
if (i > 0 && j > 0) {
int a = (mSegmentsW + 1) * j + i;
int b = (mSegmentsW + 1) * j + i - 1;
int c = (mSegmentsW + 1) * (j - 1) + i - 1;
int d = (mSegmentsW + 1) * (j - 1) + i;
if (j == mSegmentsH) {
indices[index++] = a;
indices[index++] = c;
indices[index++] = d;
} else if (j == 1) {
indices[index++] = a;
indices[index++] = b;
indices[index++] = c;
} else {
indices[index++] = a;
indices[index++] = b;
indices[index++] = c;
indices[index++] = a;
indices[index++] = c;
indices[index++] = d;
}
}
}
}
float[] textureCoords = null;
if (mCreateTextureCoords) {
int numUvs = (mSegmentsH + 1) * (mSegmentsW + 1) * 2;
textureCoords = new float[numUvs];
numUvs = 0;
for (j = 0; j <= mSegmentsH; ++j) {
for (i = 0; i <= mSegmentsW; ++i) {
textureCoords[numUvs++] = -(float) i / mSegmentsW;
textureCoords[numUvs++] = (float) j / mSegmentsH;
}
}
}
float[] colors = null;
if (mCreateVertexColorBuffer)
{
int numColors = numVertices * 4;
colors = new float[numColors];
for (j = 0; j < numColors; j += 4)
{
colors[j] = 1.0f;
colors[j + 1] = 0;
colors[j + 2] = 0;
colors[j + 3] = 1.0f;
}
}
setData(vertices, normals, textureCoords, colors, indices);
vertices = null;
normals = null;
textureCoords = null;
indices = null;
}
| protected void init() {
int numVertices = (mSegmentsW + 1) * (mSegmentsH + 1);
int numIndices = 2 * mSegmentsW * (mSegmentsH - 1) * 3;
float[] vertices = new float[numVertices * 3];
float[] normals = new float[numVertices * 3];
int[] indices = new int[numIndices];
int i, j;
int vertIndex = 0, index = 0;
final float normLen = 1.0f / mRadius;
for (j = 0; j <= mSegmentsH; ++j) {
float horAngle = PI * j / mSegmentsH;
float z = mRadius * (float) Math.cos(horAngle);
float ringRadius = mRadius * (float) Math.sin(horAngle);
for (i = 0; i <= mSegmentsW; ++i) {
float verAngle = 2.0f * PI * i / mSegmentsW;
float x = ringRadius * (float) Math.cos(verAngle);
float y = ringRadius * (float) Math.sin(verAngle);
normals[vertIndex] = x * normLen;
vertices[vertIndex++] = x;
normals[vertIndex] = z * normLen;
vertices[vertIndex++] = z;
normals[vertIndex] = y * normLen;
vertices[vertIndex++] = y;
if (i > 0 && j > 0) {
int a = (mSegmentsW + 1) * j + i;
int b = (mSegmentsW + 1) * j + i - 1;
int c = (mSegmentsW + 1) * (j - 1) + i - 1;
int d = (mSegmentsW + 1) * (j - 1) + i;
if (j == mSegmentsH) {
indices[index++] = a;
indices[index++] = c;
indices[index++] = d;
} else if (j == 1) {
indices[index++] = a;
indices[index++] = b;
indices[index++] = c;
} else {
indices[index++] = a;
indices[index++] = b;
indices[index++] = c;
indices[index++] = a;
indices[index++] = c;
indices[index++] = d;
}
}
}
}
float[] textureCoords = null;
if (mCreateTextureCoords) {
int numUvs = (mSegmentsH + 1) * (mSegmentsW + 1) * 2;
textureCoords = new float[numUvs];
numUvs = 0;
for (j = 0; j <= mSegmentsH; ++j) {
for (i = mSegmentsW; i >= 0; --i) {
textureCoords[numUvs++] = (float) i / mSegmentsW;
textureCoords[numUvs++] = (float) j / mSegmentsH;
}
}
}
float[] colors = null;
if (mCreateVertexColorBuffer)
{
int numColors = numVertices * 4;
colors = new float[numColors];
for (j = 0; j < numColors; j += 4)
{
colors[j] = 1.0f;
colors[j + 1] = 0;
colors[j + 2] = 0;
colors[j + 3] = 1.0f;
}
}
setData(vertices, normals, textureCoords, colors, indices);
vertices = null;
normals = null;
textureCoords = null;
indices = null;
}
|
diff --git a/MemoMeme/src/com/memomeme/activities/NewUser.java b/MemoMeme/src/com/memomeme/activities/NewUser.java
index 8e6ea99..993ffe7 100644
--- a/MemoMeme/src/com/memomeme/activities/NewUser.java
+++ b/MemoMeme/src/com/memomeme/activities/NewUser.java
@@ -1,44 +1,45 @@
package com.memomeme.activities;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class NewUser extends Activity {
EditText etNewUser;
Button bSubmit;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.new_user);
initViews();
initListeners();
}
private void initViews() {
etNewUser = (EditText) findViewById(R.id.editTextNewUser);
bSubmit = (Button) findViewById(R.id.buttonSubmitUser);
}
private void initListeners() {
bSubmit.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO creating db user
startActivity(new Intent(v.getContext(), Game.class));
+ finish();
}
});
}
@Override
protected void onResume() {
super.onResume();
}
}
| true | true | private void initListeners() {
bSubmit.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO creating db user
startActivity(new Intent(v.getContext(), Game.class));
}
});
}
| private void initListeners() {
bSubmit.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO creating db user
startActivity(new Intent(v.getContext(), Game.class));
finish();
}
});
}
|
diff --git a/src/com/android/bluetooth/pbap/BluetoothPbapVcardManager.java b/src/com/android/bluetooth/pbap/BluetoothPbapVcardManager.java
index f51f284..1b00ae5 100644
--- a/src/com/android/bluetooth/pbap/BluetoothPbapVcardManager.java
+++ b/src/com/android/bluetooth/pbap/BluetoothPbapVcardManager.java
@@ -1,571 +1,572 @@
/*
* Copyright (c) 2008-2009, Motorola, Inc.
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* - Neither the name of the Motorola, Inc. nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
package com.android.bluetooth.pbap;
import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.pim.vcard.VCardComposer;
import android.pim.vcard.VCardConfig;
import android.pim.vcard.VCardComposer.OneEntryHandler;
import android.provider.CallLog;
import android.provider.CallLog.Calls;
import android.provider.ContactsContract.CommonDataKinds;
import android.provider.ContactsContract.Contacts;
import android.provider.ContactsContract.Data;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.text.TextUtils;
import android.util.Log;
import com.android.bluetooth.R;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import javax.obex.Operation;
import javax.obex.ResponseCodes;
public class BluetoothPbapVcardManager {
private static final String TAG = "BluetoothPbapVcardManager";
private static final boolean V = BluetoothPbapService.VERBOSE;
private ContentResolver mResolver;
private Context mContext;
private StringBuilder mVcardResults = null;
static final String[] PHONES_PROJECTION = new String[] {
Data._ID, // 0
CommonDataKinds.Phone.TYPE, // 1
CommonDataKinds.Phone.LABEL, // 2
CommonDataKinds.Phone.NUMBER, // 3
Contacts.DISPLAY_NAME, // 4
};
private static final int ID_COLUMN_INDEX = 0;
private static final int PHONE_TYPE_COLUMN_INDEX = 1;
private static final int PHONE_LABEL_COLUMN_INDEX = 2;
private static final int PHONE_NUMBER_COLUMN_INDEX = 3;
private static final int CONTACTS_DISPLAY_NAME_COLUMN_INDEX = 4;
static final String SORT_ORDER_PHONE_NUMBER = CommonDataKinds.Phone.NUMBER + " ASC";
static final String[] CONTACTS_PROJECTION = new String[] {
Contacts._ID, // 0
Contacts.DISPLAY_NAME, // 1
};
static final int CONTACTS_ID_COLUMN_INDEX = 0;
static final int CONTACTS_NAME_COLUMN_INDEX = 1;
// call histories use dynamic handles, and handles should order by date; the
// most recently one should be the first handle. In table "calls", _id and
// date are consistent in ordering, to implement simply, we sort by _id
// here.
static final String CALLLOG_SORT_ORDER = Calls._ID + " DESC";
private static final String CLAUSE_ONLY_VISIBLE = Contacts.IN_VISIBLE_GROUP + "=1";
public BluetoothPbapVcardManager(final Context context) {
mContext = context;
mResolver = mContext.getContentResolver();
}
public final String getOwnerPhoneNumberVcard(final boolean vcardType21) {
BluetoothPbapCallLogComposer composer = new BluetoothPbapCallLogComposer(mContext, false);
String name = BluetoothPbapService.getLocalPhoneName();
String number = BluetoothPbapService.getLocalPhoneNum();
String vcard = composer.composeVCardForPhoneOwnNumber(Phone.TYPE_MOBILE, name, number,
vcardType21);
return vcard;
}
public final int getPhonebookSize(final int type) {
int size;
switch (type) {
case BluetoothPbapObexServer.ContentType.PHONEBOOK:
size = getContactsSize();
break;
default:
size = getCallHistorySize(type);
break;
}
if (V) Log.v(TAG, "getPhonebookSzie size = " + size + " type = " + type);
return size;
}
public final int getContactsSize() {
final Uri myUri = Contacts.CONTENT_URI;
int size = 0;
Cursor contactCursor = null;
try {
contactCursor = mResolver.query(myUri, null, CLAUSE_ONLY_VISIBLE, null, null);
if (contactCursor != null) {
size = contactCursor.getCount() + 1; // always has the 0.vcf
}
} finally {
if (contactCursor != null) {
contactCursor.close();
}
}
return size;
}
public final int getCallHistorySize(final int type) {
final Uri myUri = CallLog.Calls.CONTENT_URI;
String selection = BluetoothPbapObexServer.createSelectionPara(type);
int size = 0;
Cursor callCursor = null;
try {
callCursor = mResolver.query(myUri, null, selection, null,
CallLog.Calls.DEFAULT_SORT_ORDER);
if (callCursor != null) {
size = callCursor.getCount();
}
} finally {
if (callCursor != null) {
callCursor.close();
}
}
return size;
}
public final ArrayList<String> loadCallHistoryList(final int type) {
final Uri myUri = CallLog.Calls.CONTENT_URI;
String selection = BluetoothPbapObexServer.createSelectionPara(type);
String[] projection = new String[] {
Calls.NUMBER, Calls.CACHED_NAME
};
final int CALLS_NUMBER_COLUMN_INDEX = 0;
final int CALLS_NAME_COLUMN_INDEX = 1;
Cursor callCursor = null;
ArrayList<String> list = new ArrayList<String>();
try {
callCursor = mResolver.query(myUri, projection, selection, null,
CALLLOG_SORT_ORDER);
if (callCursor != null) {
for (callCursor.moveToFirst(); !callCursor.isAfterLast();
callCursor.moveToNext()) {
String name = callCursor.getString(CALLS_NAME_COLUMN_INDEX);
if (TextUtils.isEmpty(name)) {
// name not found,use number instead
name = callCursor.getString(CALLS_NUMBER_COLUMN_INDEX);
}
list.add(name);
}
}
} finally {
if (callCursor != null) {
callCursor.close();
}
}
return list;
}
public final ArrayList<String> getPhonebookNameList(final int orderByWhat) {
ArrayList<String> nameList = new ArrayList<String>();
nameList.add(BluetoothPbapService.getLocalPhoneName());
final Uri myUri = Contacts.CONTENT_URI;
Cursor contactCursor = null;
try {
if (orderByWhat == BluetoothPbapObexServer.ORDER_BY_INDEXED) {
contactCursor = mResolver.query(myUri, CONTACTS_PROJECTION, CLAUSE_ONLY_VISIBLE,
null, Contacts._ID);
} else if (orderByWhat == BluetoothPbapObexServer.ORDER_BY_ALPHABETICAL) {
contactCursor = mResolver.query(myUri, CONTACTS_PROJECTION, CLAUSE_ONLY_VISIBLE,
null, Contacts.DISPLAY_NAME);
}
if (contactCursor != null) {
for (contactCursor.moveToFirst(); !contactCursor.isAfterLast(); contactCursor
.moveToNext()) {
String name = contactCursor.getString(CONTACTS_NAME_COLUMN_INDEX);
if (TextUtils.isEmpty(name)) {
name = mContext.getString(android.R.string.unknownName);
}
nameList.add(name);
}
}
} finally {
if (contactCursor != null) {
contactCursor.close();
}
}
return nameList;
}
public final ArrayList<String> getPhonebookNumberList() {
ArrayList<String> numberList = new ArrayList<String>();
numberList.add(BluetoothPbapService.getLocalPhoneNum());
final Uri myUri = Phone.CONTENT_URI;
Cursor phoneCursor = null;
try {
phoneCursor = mResolver.query(myUri, PHONES_PROJECTION, CLAUSE_ONLY_VISIBLE, null,
SORT_ORDER_PHONE_NUMBER);
if (phoneCursor != null) {
for (phoneCursor.moveToFirst(); !phoneCursor.isAfterLast(); phoneCursor
.moveToNext()) {
String number = phoneCursor.getString(PHONE_NUMBER_COLUMN_INDEX);
if (TextUtils.isEmpty(number)) {
number = mContext.getString(R.string.defaultnumber);
}
numberList.add(number);
}
}
} finally {
if (phoneCursor != null) {
phoneCursor.close();
}
}
return numberList;
}
public final int composeAndSendCallLogVcards(final int type, final Operation op,
final int startPoint, final int endPoint, final boolean vcardType21) {
if (startPoint < 1 || startPoint > endPoint) {
Log.e(TAG, "internal error: startPoint or endPoint is not correct.");
return ResponseCodes.OBEX_HTTP_INTERNAL_ERROR;
}
String typeSelection = BluetoothPbapObexServer.createSelectionPara(type);
final Uri myUri = CallLog.Calls.CONTENT_URI;
final String[] CALLLOG_PROJECTION = new String[] {
CallLog.Calls._ID, // 0
};
final int ID_COLUMN_INDEX = 0;
Cursor callsCursor = null;
long startPointId = 0;
long endPointId = 0;
try {
// Need test to see if order by _ID is ok here, or by date?
callsCursor = mResolver.query(myUri, CALLLOG_PROJECTION, typeSelection, null,
CALLLOG_SORT_ORDER);
if (callsCursor != null) {
callsCursor.moveToPosition(startPoint - 1);
startPointId = callsCursor.getLong(ID_COLUMN_INDEX);
if (V) Log.v(TAG, "Call Log query startPointId = " + startPointId);
if (startPoint == endPoint) {
endPointId = startPointId;
} else {
callsCursor.moveToPosition(endPoint - 1);
endPointId = callsCursor.getLong(ID_COLUMN_INDEX);
}
if (V) Log.v(TAG, "Call log query endPointId = " + endPointId);
}
} finally {
if (callsCursor != null) {
callsCursor.close();
}
}
String recordSelection;
if (startPoint == endPoint) {
recordSelection = Calls._ID + "=" + startPointId;
} else {
// The query to call table is by "_id DESC" order, so change
// correspondingly.
recordSelection = Calls._ID + ">=" + endPointId + " AND " + Calls._ID + "<="
+ startPointId;
}
String selection;
if (typeSelection == null) {
selection = recordSelection;
} else {
selection = "(" + typeSelection + ") AND (" + recordSelection + ")";
}
if (V) Log.v(TAG, "Call log query selection is: " + selection);
return composeAndSendVCards(op, selection, vcardType21, null, false);
}
public final int composeAndSendPhonebookVcards(final Operation op, final int startPoint,
final int endPoint, final boolean vcardType21, String ownerVCard) {
if (startPoint < 1 || startPoint > endPoint) {
Log.e(TAG, "internal error: startPoint or endPoint is not correct.");
return ResponseCodes.OBEX_HTTP_INTERNAL_ERROR;
}
final Uri myUri = Contacts.CONTENT_URI;
Cursor contactCursor = null;
long startPointId = 0;
long endPointId = 0;
try {
contactCursor = mResolver.query(myUri, CONTACTS_PROJECTION, CLAUSE_ONLY_VISIBLE, null,
Contacts._ID);
if (contactCursor != null) {
contactCursor.moveToPosition(startPoint - 1);
startPointId = contactCursor.getLong(CONTACTS_ID_COLUMN_INDEX);
if (V) Log.v(TAG, "Query startPointId = " + startPointId);
if (startPoint == endPoint) {
endPointId = startPointId;
} else {
contactCursor.moveToPosition(endPoint - 1);
endPointId = contactCursor.getLong(CONTACTS_ID_COLUMN_INDEX);
}
if (V) Log.v(TAG, "Query endPointId = " + endPointId);
}
} finally {
if (contactCursor != null) {
contactCursor.close();
}
}
final String selection;
if (startPoint == endPoint) {
selection = Contacts._ID + "=" + startPointId + " AND " + CLAUSE_ONLY_VISIBLE;
} else {
selection = Contacts._ID + ">=" + startPointId + " AND " + Contacts._ID + "<="
+ endPointId + " AND " + CLAUSE_ONLY_VISIBLE;
}
if (V) Log.v(TAG, "Query selection is: " + selection);
return composeAndSendVCards(op, selection, vcardType21, ownerVCard, true);
}
public final int composeAndSendPhonebookOneVcard(final Operation op, final int offset,
final boolean vcardType21, String ownerVCard, int orderByWhat) {
if (offset < 1) {
Log.e(TAG, "Internal error: offset is not correct.");
return ResponseCodes.OBEX_HTTP_INTERNAL_ERROR;
}
final Uri myUri = Contacts.CONTENT_URI;
Cursor contactCursor = null;
String selection = null;
long contactId = 0;
if (orderByWhat == BluetoothPbapObexServer.ORDER_BY_INDEXED) {
try {
contactCursor = mResolver.query(myUri, CONTACTS_PROJECTION, CLAUSE_ONLY_VISIBLE,
null, Contacts._ID);
if (contactCursor != null) {
contactCursor.moveToPosition(offset - 1);
contactId = contactCursor.getLong(CONTACTS_ID_COLUMN_INDEX);
if (V) Log.v(TAG, "Query startPointId = " + contactId);
}
} finally {
if (contactCursor != null) {
contactCursor.close();
}
}
} else if (orderByWhat == BluetoothPbapObexServer.ORDER_BY_ALPHABETICAL) {
try {
contactCursor = mResolver.query(myUri, CONTACTS_PROJECTION, CLAUSE_ONLY_VISIBLE,
null, Contacts.DISPLAY_NAME);
if (contactCursor != null) {
contactCursor.moveToPosition(offset - 1);
contactId = contactCursor.getLong(CONTACTS_ID_COLUMN_INDEX);
if (V) Log.v(TAG, "Query startPointId = " + contactId);
}
} finally {
if (contactCursor != null) {
contactCursor.close();
}
}
} else {
Log.e(TAG, "Parameter orderByWhat is not supported!");
return ResponseCodes.OBEX_HTTP_INTERNAL_ERROR;
}
selection = Contacts._ID + "=" + contactId;
if (V) Log.v(TAG, "Query selection is: " + selection);
return composeAndSendVCards(op, selection, vcardType21, ownerVCard, true);
}
public final int composeAndSendVCards(final Operation op, final String selection,
final boolean vcardType21, String ownerVCard, boolean isContacts) {
long timestamp = 0;
if (V) timestamp = System.currentTimeMillis();
if (isContacts) {
VCardComposer composer = null;
try {
// Currently only support Generic Vcard 2.1 and 3.0
int vcardType;
if (vcardType21) {
vcardType = VCardConfig.VCARD_TYPE_V21_GENERIC_UTF8;
} else {
vcardType = VCardConfig.VCARD_TYPE_V30_GENERIC_UTF8;
}
composer = new VCardComposer(mContext, vcardType, true);
+ composer.addHandler(new HandlerForStringBuffer(op, ownerVCard));
if (!composer.init(Contacts.CONTENT_URI, selection, null, null)) {
return ResponseCodes.OBEX_HTTP_INTERNAL_ERROR;
}
while (!composer.isAfterLast()) {
if (!composer.createOneEntry()) {
Log.e(TAG, "Failed to read a contact. Error reason: "
+ composer.getErrorReason());
return ResponseCodes.OBEX_HTTP_INTERNAL_ERROR;
}
}
} finally {
if (composer != null) {
composer.terminate();
}
}
} else { // CallLog
BluetoothPbapCallLogComposer composer = null;
try {
composer = new BluetoothPbapCallLogComposer(mContext, true);
composer.addHandler(new HandlerForStringBuffer(op, ownerVCard));
if (!composer.init(CallLog.Calls.CONTENT_URI, selection, null, null)) {
return ResponseCodes.OBEX_HTTP_INTERNAL_ERROR;
}
while (!composer.isAfterLast()) {
if (!composer.createOneEntry()) {
Log.e(TAG, "Failed to read a contact. Error reason: "
+ composer.getErrorReason());
return ResponseCodes.OBEX_HTTP_INTERNAL_ERROR;
}
}
} finally {
if (composer != null) {
composer.terminate();
}
}
}
if (V) Log.v(TAG, "Total vcard composing and sending out takes "
+ (System.currentTimeMillis() - timestamp) + " ms");
return ResponseCodes.OBEX_HTTP_OK;
}
/**
* Handler to emit VCard String to PCE once size grow to maxPacketSize.
*/
public class HandlerForStringBuffer implements OneEntryHandler {
@SuppressWarnings("hiding")
private Operation operation;
private OutputStream outputStream;
private int maxPacketSize;
private String phoneOwnVCard = null;
public HandlerForStringBuffer(Operation op, String ownerVCard) {
operation = op;
maxPacketSize = operation.getMaxPacketSize();
if (V) Log.v(TAG, "getMaxPacketSize() = " + maxPacketSize);
if (ownerVCard != null) {
phoneOwnVCard = ownerVCard;
if (V) Log.v(TAG, "phone own number vcard:");
if (V) Log.v(TAG, phoneOwnVCard);
}
}
public boolean onInit(Context context) {
try {
outputStream = operation.openOutputStream();
mVcardResults = new StringBuilder();
if (phoneOwnVCard != null) {
mVcardResults.append(phoneOwnVCard);
}
} catch (IOException e) {
Log.e(TAG, "open outputstrem failed" + e.toString());
return false;
}
if (V) Log.v(TAG, "openOutputStream() ok.");
return true;
}
public boolean onEntryCreated(String vcard) {
int vcardLen = vcard.length();
if (V) Log.v(TAG, "The length of this vcard is: " + vcardLen);
mVcardResults.append(vcard);
int vcardStringLen = mVcardResults.toString().length();
if (V) Log.v(TAG, "The length of this vcardResults is: " + vcardStringLen);
if (vcardStringLen >= maxPacketSize) {
long timestamp = 0;
int position = 0;
// Need while loop to handle the big vcard case
while (position < (vcardStringLen - maxPacketSize)) {
if (V) timestamp = System.currentTimeMillis();
String subStr = mVcardResults.toString().substring(position,
position + maxPacketSize);
try {
outputStream.write(subStr.getBytes(), 0, maxPacketSize);
} catch (IOException e) {
Log.e(TAG, "write outputstrem failed" + e.toString());
return false;
}
if (V) Log.v(TAG, "Sending vcard String " + maxPacketSize + " bytes took "
+ (System.currentTimeMillis() - timestamp) + " ms");
position += maxPacketSize;
}
mVcardResults.delete(0, position);
}
return true;
}
public void onTerminate() {
// Send out last packet
String lastStr = mVcardResults.toString();
try {
outputStream.write(lastStr.getBytes(), 0, lastStr.length());
} catch (IOException e) {
Log.e(TAG, "write outputstrem failed" + e.toString());
}
if (V) Log.v(TAG, "Last packet sent out, sending process complete!");
if (!BluetoothPbapObexServer.closeStream(outputStream, operation)) {
if (V) Log.v(TAG, "CloseStream failed!");
} else {
if (V) Log.v(TAG, "CloseStream ok!");
}
}
}
}
| true | true | public final int composeAndSendVCards(final Operation op, final String selection,
final boolean vcardType21, String ownerVCard, boolean isContacts) {
long timestamp = 0;
if (V) timestamp = System.currentTimeMillis();
if (isContacts) {
VCardComposer composer = null;
try {
// Currently only support Generic Vcard 2.1 and 3.0
int vcardType;
if (vcardType21) {
vcardType = VCardConfig.VCARD_TYPE_V21_GENERIC_UTF8;
} else {
vcardType = VCardConfig.VCARD_TYPE_V30_GENERIC_UTF8;
}
composer = new VCardComposer(mContext, vcardType, true);
if (!composer.init(Contacts.CONTENT_URI, selection, null, null)) {
return ResponseCodes.OBEX_HTTP_INTERNAL_ERROR;
}
while (!composer.isAfterLast()) {
if (!composer.createOneEntry()) {
Log.e(TAG, "Failed to read a contact. Error reason: "
+ composer.getErrorReason());
return ResponseCodes.OBEX_HTTP_INTERNAL_ERROR;
}
}
} finally {
if (composer != null) {
composer.terminate();
}
}
} else { // CallLog
BluetoothPbapCallLogComposer composer = null;
try {
composer = new BluetoothPbapCallLogComposer(mContext, true);
composer.addHandler(new HandlerForStringBuffer(op, ownerVCard));
if (!composer.init(CallLog.Calls.CONTENT_URI, selection, null, null)) {
return ResponseCodes.OBEX_HTTP_INTERNAL_ERROR;
}
while (!composer.isAfterLast()) {
if (!composer.createOneEntry()) {
Log.e(TAG, "Failed to read a contact. Error reason: "
+ composer.getErrorReason());
return ResponseCodes.OBEX_HTTP_INTERNAL_ERROR;
}
}
} finally {
if (composer != null) {
composer.terminate();
}
}
}
if (V) Log.v(TAG, "Total vcard composing and sending out takes "
+ (System.currentTimeMillis() - timestamp) + " ms");
return ResponseCodes.OBEX_HTTP_OK;
}
| public final int composeAndSendVCards(final Operation op, final String selection,
final boolean vcardType21, String ownerVCard, boolean isContacts) {
long timestamp = 0;
if (V) timestamp = System.currentTimeMillis();
if (isContacts) {
VCardComposer composer = null;
try {
// Currently only support Generic Vcard 2.1 and 3.0
int vcardType;
if (vcardType21) {
vcardType = VCardConfig.VCARD_TYPE_V21_GENERIC_UTF8;
} else {
vcardType = VCardConfig.VCARD_TYPE_V30_GENERIC_UTF8;
}
composer = new VCardComposer(mContext, vcardType, true);
composer.addHandler(new HandlerForStringBuffer(op, ownerVCard));
if (!composer.init(Contacts.CONTENT_URI, selection, null, null)) {
return ResponseCodes.OBEX_HTTP_INTERNAL_ERROR;
}
while (!composer.isAfterLast()) {
if (!composer.createOneEntry()) {
Log.e(TAG, "Failed to read a contact. Error reason: "
+ composer.getErrorReason());
return ResponseCodes.OBEX_HTTP_INTERNAL_ERROR;
}
}
} finally {
if (composer != null) {
composer.terminate();
}
}
} else { // CallLog
BluetoothPbapCallLogComposer composer = null;
try {
composer = new BluetoothPbapCallLogComposer(mContext, true);
composer.addHandler(new HandlerForStringBuffer(op, ownerVCard));
if (!composer.init(CallLog.Calls.CONTENT_URI, selection, null, null)) {
return ResponseCodes.OBEX_HTTP_INTERNAL_ERROR;
}
while (!composer.isAfterLast()) {
if (!composer.createOneEntry()) {
Log.e(TAG, "Failed to read a contact. Error reason: "
+ composer.getErrorReason());
return ResponseCodes.OBEX_HTTP_INTERNAL_ERROR;
}
}
} finally {
if (composer != null) {
composer.terminate();
}
}
}
if (V) Log.v(TAG, "Total vcard composing and sending out takes "
+ (System.currentTimeMillis() - timestamp) + " ms");
return ResponseCodes.OBEX_HTTP_OK;
}
|
diff --git a/modules/weblounge-preview/src/main/java/ch/entwine/weblounge/preview/imagemagick/ImageMagickPreviewGenerator.java b/modules/weblounge-preview/src/main/java/ch/entwine/weblounge/preview/imagemagick/ImageMagickPreviewGenerator.java
index 2458466eb..9ce68d590 100644
--- a/modules/weblounge-preview/src/main/java/ch/entwine/weblounge/preview/imagemagick/ImageMagickPreviewGenerator.java
+++ b/modules/weblounge-preview/src/main/java/ch/entwine/weblounge/preview/imagemagick/ImageMagickPreviewGenerator.java
@@ -1,355 +1,356 @@
/*
* Weblounge: Web Content Management System
* Copyright (c) 2003 - 2011 The Weblounge Team
* http://entwinemedia.com/weblounge
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package ch.entwine.weblounge.preview.imagemagick;
import ch.entwine.weblounge.common.content.Resource;
import ch.entwine.weblounge.common.content.ResourceContent;
import ch.entwine.weblounge.common.content.image.ImagePreviewGenerator;
import ch.entwine.weblounge.common.content.image.ImageResource;
import ch.entwine.weblounge.common.content.image.ImageStyle;
import ch.entwine.weblounge.common.impl.content.image.ImageStyleUtils;
import ch.entwine.weblounge.common.language.Language;
import ch.entwine.weblounge.common.site.Environment;
import ch.entwine.weblounge.common.site.ImageScalingMode;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.im4java.core.ConvertCmd;
import org.im4java.core.IMOperation;
import org.im4java.core.Info;
import org.im4java.process.OutputConsumer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Utility class used for dealing with images and image styles.
*/
public final class ImageMagickPreviewGenerator implements ImagePreviewGenerator {
/** The logging facility */
private static final Logger logger = LoggerFactory.getLogger(ImageMagickPreviewGenerator.class);
/** List of supported formats (cached) */
private Map<String, Boolean> supportedFormats = new HashMap<String, Boolean>();
/** Flag to indicate whether format detection is supported */
private boolean formatDecetionSupported = true;
/**
* {@inheritDoc}
*
* @see ch.entwine.weblounge.common.content.PreviewGenerator#supports(ch.entwine.weblounge.common.content.Resource)
*/
public boolean supports(Resource<?> resource) {
return (resource instanceof ImageResource);
}
/**
* {@inheritDoc}
*
* @see ch.entwine.weblounge.common.content.PreviewGenerator#supports(java.lang.String)
*/
public boolean supports(String format) {
if (format == null)
throw new IllegalArgumentException("Format cannot be null");
if (!formatDecetionSupported)
return true;
// Check for verified support
if (supportedFormats.containsKey(format))
return supportedFormats.get(format);
// Reach out to ImageMagick
ConvertCmd imageMagick = new ConvertCmd();
IMOperation op = new IMOperation();
op.identify().list("format");
try {
final Pattern p = Pattern.compile("[\\s]+" + format.toUpperCase() + "[\\s]+rw");
final Boolean[] supported = new Boolean[1];
imageMagick.setOutputConsumer(new OutputConsumer() {
public void consumeOutput(InputStream is) throws IOException {
String output = IOUtils.toString(is);
Matcher m = p.matcher(output);
supported[0] = new Boolean(m.find());
}
});
imageMagick.run(op);
// Cache the result
supportedFormats.put(format, supported[0]);
return supported[0];
} catch (Throwable t) {
logger.warn("Error looking up formats supported by ImageMagick: {}", t.getMessage());
formatDecetionSupported = false;
logger.info("ImageMagick format lookup failed, assuming support for all formats");
return true;
}
}
/**
* {@inheritDoc}
*
* @see ch.entwine.weblounge.common.content.PreviewGenerator#createPreview(ch.entwine.weblounge.common.content.Resource,
* ch.entwine.weblounge.common.site.Environment,
* ch.entwine.weblounge.common.language.Language,
* ch.entwine.weblounge.common.content.image.ImageStyle, String,
* java.io.InputStream, java.io.OutputStream)
*/
public void createPreview(Resource<?> resource, Environment environment,
Language language, ImageStyle style, String format, InputStream is,
OutputStream os) throws IOException {
if (format == null) {
if (resource == null)
throw new IllegalArgumentException("Resource cannot be null");
if (resource.getContent(language) == null) {
logger.warn("Skipping creation of preview for {} in language '{}': no content", resource, language.getIdentifier());
return;
}
String mimetype = resource.getContent(language).getMimetype();
logger.trace("Image preview is generated using the resource's mimetype '{}'", mimetype);
format = mimetype.substring(mimetype.indexOf("/") + 1);
}
style(is, os, format, style);
}
/**
* {@inheritDoc}
*
* @see ch.entwine.weblounge.common.content.image.ImagePreviewGenerator#createPreview(java.io.File,
* ch.entwine.weblounge.common.site.Environment,
* ch.entwine.weblounge.common.language.Language,
* ch.entwine.weblounge.common.content.image.ImageStyle,
* java.lang.String, java.io.InputStream, java.io.OutputStream)
*/
public void createPreview(File imageFile, Environment environment,
Language language, ImageStyle style, String format, InputStream is,
OutputStream os) throws IOException {
if (format == null) {
if (imageFile == null)
throw new IllegalArgumentException("Image file cannot be null");
format = FilenameUtils.getExtension(imageFile.getName());
logger.trace("Image preview is generated as '{}'", format);
}
style(is, os, format, style);
}
/**
* {@inheritDoc}
*
* @see ch.entwine.weblounge.common.content.PreviewGenerator#getContentType(ch.entwine.weblounge.common.content.Resource,
* ch.entwine.weblounge.common.language.Language,
* ch.entwine.weblounge.common.content.image.ImageStyle)
*/
public String getContentType(Resource<?> resource, Language language,
ImageStyle style) {
String mimetype = resource.getContent(language).getMimetype();
return mimetype;
}
/**
* {@inheritDoc}
*
* @see ch.entwine.weblounge.common.content.PreviewGenerator#getSuffix(ch.entwine.weblounge.common.content.Resource,
* ch.entwine.weblounge.common.language.Language,
* ch.entwine.weblounge.common.content.image.ImageStyle)
*/
public String getSuffix(Resource<?> resource, Language language,
ImageStyle style) {
// Load the resource
ResourceContent content = resource.getContent(language);
if (content == null) {
content = resource.getOriginalContent();
if (content == null) {
logger.warn("Trying to get filename suffix for {}, which has no content", resource);
return null;
}
}
// Get the file name
String filename = content.getFilename();
if (StringUtils.isBlank(filename)) {
logger.warn("Trying to get filename suffix for {}, which has no filename", resource);
return null;
}
// Add the file identifier name
if (StringUtils.isNotBlank(style.getIdentifier())) {
filename += "-" + style.getIdentifier();
}
return FilenameUtils.getExtension(filename);
}
/**
* {@inheritDoc}
*
* @see ch.entwine.weblounge.common.content.PreviewGenerator#getPriority()
*/
public int getPriority() {
return 100;
}
/**
* Resizes the given image to what is defined by the image style and writes
* the result to the output stream.
*
* @param is
* the input stream
* @param os
* the output stream
* @param format
* the image format
* @param style
* the style
* @throws IllegalArgumentException
* if the image is in an unsupported format
* @throws IOException
* if reading from or writing to the stream fails
* @throws OutOfMemoryError
* if the image is too large to be processed in memory
*/
@SuppressWarnings("cast")
private void style(InputStream is, OutputStream os, String format,
ImageStyle style) throws IllegalArgumentException, IOException,
OutOfMemoryError {
// Is an image style permitted?
if (style == null)
throw new IllegalArgumentException("Image style cannot be null");
// Do we need to do any work at all?
if (ImageScalingMode.None.equals(style.getScalingMode())) {
logger.trace("No scaling needed, performing a noop stream copy");
IOUtils.copy(is, os);
return;
}
File originalFile = File.createTempFile("image-", "." + format);
File scaledFile = File.createTempFile("image-scaled", "." + format);
File croppedFile = File.createTempFile("image-cropped", "." + format);
try {
File finalFile = null;
FileOutputStream fos = new FileOutputStream(originalFile);
IOUtils.copy(is, fos);
IOUtils.closeQuietly(fos);
IOUtils.closeQuietly(is);
// Load the image from the temporary file
Info imageInfo = new Info(originalFile.getAbsolutePath(), true);
// Get the original image size
int imageWidth = imageInfo.getImageWidth();
int imageHeight = imageInfo.getImageHeight();
// Prepare for processing
ConvertCmd imageMagick = new ConvertCmd();
// Resizing
float scale = ImageStyleUtils.getScale(imageWidth, imageHeight, style);
int scaledWidth = Math.round(scale * imageWidth);
int scaledHeight = Math.round(scale * imageHeight);
int cropX = 0;
int cropY = 0;
// If either one of scaledWidth or scaledHeight is < 1.0, then
// the scale needs to be adapted to scale to 1.0 exactly and accomplish
// the rest by cropping.
if (scaledWidth < 1.0f) {
scale = 1.0f / imageWidth;
scaledWidth = 1;
cropY = imageHeight - scaledHeight;
scaledHeight = Math.round(imageHeight * scale);
} else if (scaledHeight < 1.0f) {
scale = 1.0f / imageHeight;
scaledHeight = 1;
cropX = imageWidth - scaledWidth;
scaledWidth = Math.round(imageWidth * scale);
}
// Do the scaling
IMOperation scaleOp = new IMOperation();
scaleOp.addImage(originalFile.getAbsolutePath());
scaleOp.resize((int) scaledWidth, (int) scaledHeight);
scaleOp.addImage(scaledFile.getAbsolutePath());
imageMagick.run(scaleOp);
finalFile = scaledFile;
// Cropping
cropX = (int) Math.max(cropX, Math.ceil(ImageStyleUtils.getCropX(scaledWidth, scaledHeight, style)));
cropY = (int) Math.max(cropY, Math.ceil(ImageStyleUtils.getCropY(scaledWidth, scaledHeight, style)));
if ((cropX > 0 && Math.floor(cropX / 2.0f) > 0) || (cropY > 0 && Math.floor(cropY / 2.0f) > 0)) {
int croppedLeft = (int) (cropX > 0 ? ((float) Math.floor(cropX / 2.0f)) : 0.0f);
int croppedTop = (int) (cropY > 0 ? ((float) Math.floor(cropY / 2.0f)) : 0.0f);
int croppedWidth = (int) (scaledWidth - Math.max(cropX, 0.0f));
int croppedHeight = (int) (scaledHeight - Math.max(cropY, 0.0f));
// Do the cropping
IMOperation cropOperation = new IMOperation();
cropOperation.addImage(scaledFile.getAbsolutePath());
cropOperation.crop(croppedWidth, croppedHeight, croppedLeft, croppedTop);
+ cropOperation.p_repage(); // Reset the page canvas and position to match the actual cropped image
cropOperation.addImage(croppedFile.getAbsolutePath());
imageMagick.run(cropOperation);
finalFile = croppedFile;
}
// Write resized/cropped image encoded as JPEG to the output stream
FileInputStream fis = null;
try {
fis = new FileInputStream(finalFile);
IOUtils.copy(fis, os);
} finally {
IOUtils.closeQuietly(fis);
}
} catch (Throwable t) {
throw new IllegalArgumentException(t.getMessage());
} finally {
FileUtils.deleteQuietly(originalFile);
FileUtils.deleteQuietly(scaledFile);
FileUtils.deleteQuietly(croppedFile);
}
}
}
| true | true | private void style(InputStream is, OutputStream os, String format,
ImageStyle style) throws IllegalArgumentException, IOException,
OutOfMemoryError {
// Is an image style permitted?
if (style == null)
throw new IllegalArgumentException("Image style cannot be null");
// Do we need to do any work at all?
if (ImageScalingMode.None.equals(style.getScalingMode())) {
logger.trace("No scaling needed, performing a noop stream copy");
IOUtils.copy(is, os);
return;
}
File originalFile = File.createTempFile("image-", "." + format);
File scaledFile = File.createTempFile("image-scaled", "." + format);
File croppedFile = File.createTempFile("image-cropped", "." + format);
try {
File finalFile = null;
FileOutputStream fos = new FileOutputStream(originalFile);
IOUtils.copy(is, fos);
IOUtils.closeQuietly(fos);
IOUtils.closeQuietly(is);
// Load the image from the temporary file
Info imageInfo = new Info(originalFile.getAbsolutePath(), true);
// Get the original image size
int imageWidth = imageInfo.getImageWidth();
int imageHeight = imageInfo.getImageHeight();
// Prepare for processing
ConvertCmd imageMagick = new ConvertCmd();
// Resizing
float scale = ImageStyleUtils.getScale(imageWidth, imageHeight, style);
int scaledWidth = Math.round(scale * imageWidth);
int scaledHeight = Math.round(scale * imageHeight);
int cropX = 0;
int cropY = 0;
// If either one of scaledWidth or scaledHeight is < 1.0, then
// the scale needs to be adapted to scale to 1.0 exactly and accomplish
// the rest by cropping.
if (scaledWidth < 1.0f) {
scale = 1.0f / imageWidth;
scaledWidth = 1;
cropY = imageHeight - scaledHeight;
scaledHeight = Math.round(imageHeight * scale);
} else if (scaledHeight < 1.0f) {
scale = 1.0f / imageHeight;
scaledHeight = 1;
cropX = imageWidth - scaledWidth;
scaledWidth = Math.round(imageWidth * scale);
}
// Do the scaling
IMOperation scaleOp = new IMOperation();
scaleOp.addImage(originalFile.getAbsolutePath());
scaleOp.resize((int) scaledWidth, (int) scaledHeight);
scaleOp.addImage(scaledFile.getAbsolutePath());
imageMagick.run(scaleOp);
finalFile = scaledFile;
// Cropping
cropX = (int) Math.max(cropX, Math.ceil(ImageStyleUtils.getCropX(scaledWidth, scaledHeight, style)));
cropY = (int) Math.max(cropY, Math.ceil(ImageStyleUtils.getCropY(scaledWidth, scaledHeight, style)));
if ((cropX > 0 && Math.floor(cropX / 2.0f) > 0) || (cropY > 0 && Math.floor(cropY / 2.0f) > 0)) {
int croppedLeft = (int) (cropX > 0 ? ((float) Math.floor(cropX / 2.0f)) : 0.0f);
int croppedTop = (int) (cropY > 0 ? ((float) Math.floor(cropY / 2.0f)) : 0.0f);
int croppedWidth = (int) (scaledWidth - Math.max(cropX, 0.0f));
int croppedHeight = (int) (scaledHeight - Math.max(cropY, 0.0f));
// Do the cropping
IMOperation cropOperation = new IMOperation();
cropOperation.addImage(scaledFile.getAbsolutePath());
cropOperation.crop(croppedWidth, croppedHeight, croppedLeft, croppedTop);
cropOperation.addImage(croppedFile.getAbsolutePath());
imageMagick.run(cropOperation);
finalFile = croppedFile;
}
// Write resized/cropped image encoded as JPEG to the output stream
FileInputStream fis = null;
try {
fis = new FileInputStream(finalFile);
IOUtils.copy(fis, os);
} finally {
IOUtils.closeQuietly(fis);
}
} catch (Throwable t) {
throw new IllegalArgumentException(t.getMessage());
} finally {
FileUtils.deleteQuietly(originalFile);
FileUtils.deleteQuietly(scaledFile);
FileUtils.deleteQuietly(croppedFile);
}
}
| private void style(InputStream is, OutputStream os, String format,
ImageStyle style) throws IllegalArgumentException, IOException,
OutOfMemoryError {
// Is an image style permitted?
if (style == null)
throw new IllegalArgumentException("Image style cannot be null");
// Do we need to do any work at all?
if (ImageScalingMode.None.equals(style.getScalingMode())) {
logger.trace("No scaling needed, performing a noop stream copy");
IOUtils.copy(is, os);
return;
}
File originalFile = File.createTempFile("image-", "." + format);
File scaledFile = File.createTempFile("image-scaled", "." + format);
File croppedFile = File.createTempFile("image-cropped", "." + format);
try {
File finalFile = null;
FileOutputStream fos = new FileOutputStream(originalFile);
IOUtils.copy(is, fos);
IOUtils.closeQuietly(fos);
IOUtils.closeQuietly(is);
// Load the image from the temporary file
Info imageInfo = new Info(originalFile.getAbsolutePath(), true);
// Get the original image size
int imageWidth = imageInfo.getImageWidth();
int imageHeight = imageInfo.getImageHeight();
// Prepare for processing
ConvertCmd imageMagick = new ConvertCmd();
// Resizing
float scale = ImageStyleUtils.getScale(imageWidth, imageHeight, style);
int scaledWidth = Math.round(scale * imageWidth);
int scaledHeight = Math.round(scale * imageHeight);
int cropX = 0;
int cropY = 0;
// If either one of scaledWidth or scaledHeight is < 1.0, then
// the scale needs to be adapted to scale to 1.0 exactly and accomplish
// the rest by cropping.
if (scaledWidth < 1.0f) {
scale = 1.0f / imageWidth;
scaledWidth = 1;
cropY = imageHeight - scaledHeight;
scaledHeight = Math.round(imageHeight * scale);
} else if (scaledHeight < 1.0f) {
scale = 1.0f / imageHeight;
scaledHeight = 1;
cropX = imageWidth - scaledWidth;
scaledWidth = Math.round(imageWidth * scale);
}
// Do the scaling
IMOperation scaleOp = new IMOperation();
scaleOp.addImage(originalFile.getAbsolutePath());
scaleOp.resize((int) scaledWidth, (int) scaledHeight);
scaleOp.addImage(scaledFile.getAbsolutePath());
imageMagick.run(scaleOp);
finalFile = scaledFile;
// Cropping
cropX = (int) Math.max(cropX, Math.ceil(ImageStyleUtils.getCropX(scaledWidth, scaledHeight, style)));
cropY = (int) Math.max(cropY, Math.ceil(ImageStyleUtils.getCropY(scaledWidth, scaledHeight, style)));
if ((cropX > 0 && Math.floor(cropX / 2.0f) > 0) || (cropY > 0 && Math.floor(cropY / 2.0f) > 0)) {
int croppedLeft = (int) (cropX > 0 ? ((float) Math.floor(cropX / 2.0f)) : 0.0f);
int croppedTop = (int) (cropY > 0 ? ((float) Math.floor(cropY / 2.0f)) : 0.0f);
int croppedWidth = (int) (scaledWidth - Math.max(cropX, 0.0f));
int croppedHeight = (int) (scaledHeight - Math.max(cropY, 0.0f));
// Do the cropping
IMOperation cropOperation = new IMOperation();
cropOperation.addImage(scaledFile.getAbsolutePath());
cropOperation.crop(croppedWidth, croppedHeight, croppedLeft, croppedTop);
cropOperation.p_repage(); // Reset the page canvas and position to match the actual cropped image
cropOperation.addImage(croppedFile.getAbsolutePath());
imageMagick.run(cropOperation);
finalFile = croppedFile;
}
// Write resized/cropped image encoded as JPEG to the output stream
FileInputStream fis = null;
try {
fis = new FileInputStream(finalFile);
IOUtils.copy(fis, os);
} finally {
IOUtils.closeQuietly(fis);
}
} catch (Throwable t) {
throw new IllegalArgumentException(t.getMessage());
} finally {
FileUtils.deleteQuietly(originalFile);
FileUtils.deleteQuietly(scaledFile);
FileUtils.deleteQuietly(croppedFile);
}
}
|
diff --git a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/patch/AdapterFactory.java b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/patch/AdapterFactory.java
index 419530c82..6fab0e281 100644
--- a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/patch/AdapterFactory.java
+++ b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/patch/AdapterFactory.java
@@ -1,57 +1,62 @@
/*******************************************************************************
* Copyright (c) 2009, 2010 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.team.internal.ui.synchronize.patch;
import org.eclipse.compare.internal.patch.*;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.mapping.ResourceMapping;
import org.eclipse.core.runtime.IAdapterFactory;
import org.eclipse.team.ui.mapping.ISynchronizationCompareAdapter;
import org.eclipse.ui.model.IWorkbenchAdapter;
public class AdapterFactory implements IAdapterFactory {
private IWorkbenchAdapter modelAdapter = new PatchWorkbenchAdapter();
private ISynchronizationCompareAdapter compareAdapter;
public Object getAdapter(Object adaptableObject, Class adapterType) {
if (adapterType == ResourceMapping.class) {
if (adaptableObject instanceof PatchProjectDiffNode) {
return new DiffProjectResourceMapping(
((PatchProjectDiffNode) adaptableObject)
.getDiffProject());
}
if (adaptableObject instanceof PatchFileDiffNode) {
return new FilePatchResourceMapping(
((PatchFileDiffNode) adaptableObject).getDiffResult());
}
if (adaptableObject instanceof HunkDiffNode) {
return new HunkResourceMapping(((HunkDiffNode) adaptableObject)
.getHunkResult());
}
}
if (adapterType == IWorkbenchAdapter.class)
return modelAdapter;
if (adapterType == ISynchronizationCompareAdapter.class
&& adaptableObject instanceof PatchModelProvider) {
if (compareAdapter == null) {
compareAdapter = new PatchCompareAdapter();
}
return compareAdapter;
}
+ if (adapterType == IResource.class) {
+ if (adaptableObject instanceof PatchFileDiffNode) {
+ return ((PatchFileDiffNode) adaptableObject).getResource();
+ }
+ }
return null;
}
public Class[] getAdapterList() {
return new Class[] { ResourceMapping.class, IWorkbenchAdapter.class,
IResource.class };
}
}
| true | true | public Object getAdapter(Object adaptableObject, Class adapterType) {
if (adapterType == ResourceMapping.class) {
if (adaptableObject instanceof PatchProjectDiffNode) {
return new DiffProjectResourceMapping(
((PatchProjectDiffNode) adaptableObject)
.getDiffProject());
}
if (adaptableObject instanceof PatchFileDiffNode) {
return new FilePatchResourceMapping(
((PatchFileDiffNode) adaptableObject).getDiffResult());
}
if (adaptableObject instanceof HunkDiffNode) {
return new HunkResourceMapping(((HunkDiffNode) adaptableObject)
.getHunkResult());
}
}
if (adapterType == IWorkbenchAdapter.class)
return modelAdapter;
if (adapterType == ISynchronizationCompareAdapter.class
&& adaptableObject instanceof PatchModelProvider) {
if (compareAdapter == null) {
compareAdapter = new PatchCompareAdapter();
}
return compareAdapter;
}
return null;
}
| public Object getAdapter(Object adaptableObject, Class adapterType) {
if (adapterType == ResourceMapping.class) {
if (adaptableObject instanceof PatchProjectDiffNode) {
return new DiffProjectResourceMapping(
((PatchProjectDiffNode) adaptableObject)
.getDiffProject());
}
if (adaptableObject instanceof PatchFileDiffNode) {
return new FilePatchResourceMapping(
((PatchFileDiffNode) adaptableObject).getDiffResult());
}
if (adaptableObject instanceof HunkDiffNode) {
return new HunkResourceMapping(((HunkDiffNode) adaptableObject)
.getHunkResult());
}
}
if (adapterType == IWorkbenchAdapter.class)
return modelAdapter;
if (adapterType == ISynchronizationCompareAdapter.class
&& adaptableObject instanceof PatchModelProvider) {
if (compareAdapter == null) {
compareAdapter = new PatchCompareAdapter();
}
return compareAdapter;
}
if (adapterType == IResource.class) {
if (adaptableObject instanceof PatchFileDiffNode) {
return ((PatchFileDiffNode) adaptableObject).getResource();
}
}
return null;
}
|
diff --git a/src/com/bigpupdev/synodroid/ui/SearchFragment.java b/src/com/bigpupdev/synodroid/ui/SearchFragment.java
index 21350fa..1823865 100644
--- a/src/com/bigpupdev/synodroid/ui/SearchFragment.java
+++ b/src/com/bigpupdev/synodroid/ui/SearchFragment.java
@@ -1,526 +1,526 @@
package com.bigpupdev.synodroid.ui;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.SearchManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Message;
import android.provider.SearchRecentSuggestions;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager.BadTokenException;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.SimpleCursorAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import com.bigpupdev.synodroid.R;
import com.bigpupdev.synodroid.Synodroid;
import com.bigpupdev.synodroid.action.AddTaskAction;
import com.bigpupdev.synodroid.action.SetSearchEngines;
import com.bigpupdev.synodroid.data.DSMVersion;
import com.bigpupdev.synodroid.data.SearchEngine;
import com.bigpupdev.synodroid.protocol.ResponseHandler;
import com.bigpupdev.synodroid.utils.SearchViewBinder;
import com.bigpupdev.synodroid.utils.SynodroidDSMSearch;
import com.bigpupdev.synodroid.utils.SynodroidSearchSuggestion;
public class SearchFragment extends SynodroidFragment {
private static final String PREFERENCE_GENERAL = "general_cat";
private static final String PREFERENCE_SEARCH_SOURCE = "general_cat.search_source";
private static final String PREFERENCE_SEARCH_ORDER = "general_cat.search_order";
private static final String TORRENT_SEARCH_URL_DL = "http://transdroid.org/latest-search";
private static final String TORRENT_SEARCH_URL_DL_MARKET = "market://details?id=org.transdroid.search";
private final String[] from = new String[] { "NAME", "SIZE", "ADDED", "LEECHERS", "SEEDERS", "TORRENTURL" };
private final int[] to = new int[] { R.id.result_title, R.id.result_size, R.id.result_date, R.id.result_leechers, R.id.result_seeds, R.id.result_url };
private TextView emptyText;
private Button btnInstall;
private Button btnAlternate;
private Spinner SpinnerSource, SpinnerSort;
private ArrayAdapter<CharSequence> AdapterSource, AdapterSort;
private String[] SortOrder = { "Combined", "BySeeders" };
private String lastSearch = "";
private ListView resList;
/**
* Activity creation
*/
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final Activity a = getActivity();
try{
if (((Synodroid)a.getApplication()).DEBUG) Log.d(Synodroid.DS_TAG,"SearchFragment: Creating search fragment.");
}catch (Exception ex){/*DO NOTHING*/}
if (savedInstanceState != null)
lastSearch = savedInstanceState.getString("lastSearch");
else
lastSearch = "";
RelativeLayout searchContent = (RelativeLayout) inflater.inflate(R.layout.torrent_search, null, false);
resList = (ListView) searchContent.findViewById(R.id.resList);
emptyText = (TextView) searchContent.findViewById(R.id.empty);
btnInstall = (Button) searchContent.findViewById(R.id.btnTorSearchInst);
btnAlternate = (Button) searchContent.findViewById(R.id.btnTorSearchInstAlternate);
SpinnerSource = (Spinner) searchContent.findViewById(R.id.srcSpinner);
SpinnerSort = (Spinner) searchContent.findViewById(R.id.sortSpinner);
AdapterSource = new ArrayAdapter<CharSequence>(a, android.R.layout.simple_spinner_item);
AdapterSource.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
SpinnerSource.setAdapter(AdapterSource);
AdapterSort = new ArrayAdapter<CharSequence>(a, android.R.layout.simple_spinner_item);
AdapterSort.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
SpinnerSort.setAdapter(AdapterSort);
SharedPreferences preferences = a.getSharedPreferences(PREFERENCE_GENERAL, Activity.MODE_PRIVATE);
String pref_src = preferences.getString(PREFERENCE_SEARCH_SOURCE, "DSM Search");
String pref_order = preferences.getString(PREFERENCE_SEARCH_ORDER, "BySeeders");
int lastOrder = 0;
int lastSource = 0;
for (int i = 0; i < SortOrder.length; i++) {
if (pref_order.equals(SortOrder[i])) {
lastOrder = i;
}
AdapterSort.add(SortOrder[i]);
}
// Gather the supported torrent sites
StringBuilder s = new StringBuilder();
List<Object[]> sites = getSupportedSites();
if (sites != null) {
for (Object[] site :sites){
int i = 0;
s.append((String) site[1]);
s.append("\n");
if (pref_src.equals((String) site[1])) {
lastSource = i;
}
AdapterSource.add((String) site[1]);
i++;
}
emptyText.setText(getString(R.string.sites) + "\n" + s.toString());
btnInstall.setVisibility(Button.GONE);
btnAlternate.setVisibility(Button.GONE);
resList.setVisibility(ListView.GONE);
} else {
SpinnerSort.setVisibility(Spinner.GONE);
SpinnerSource.setVisibility(Spinner.GONE);
resList.setVisibility(ListView.GONE);
emptyText.setText(R.string.provider_missing);
btnInstall.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent goToMarket = null;
goToMarket = new Intent(Intent.ACTION_VIEW, Uri.parse(TORRENT_SEARCH_URL_DL_MARKET));
try {
startActivity(goToMarket);
} catch (Exception e) {
AlertDialog.Builder builder = new AlertDialog.Builder(a);
// By default the message is "Error Unknown"
builder.setMessage(R.string.err_nomarket);
builder.setTitle(getString(R.string.connect_error_title)).setCancelable(false).setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog errorDialog = builder.create();
try {
errorDialog.show();
} catch (BadTokenException ex) {
// Unable to show dialog probably because intent has been closed. Ignoring...
}
}
}
});
btnAlternate.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent goToMarket = null;
goToMarket = new Intent(Intent.ACTION_VIEW, Uri.parse(TORRENT_SEARCH_URL_DL));
try {
startActivity(goToMarket);
} catch (Exception e) {
AlertDialog.Builder builder = new AlertDialog.Builder(a);
// By default the message is "Error Unknown"
builder.setMessage(R.string.err_nobrowser);
builder.setTitle(getString(R.string.connect_error_title)).setCancelable(false).setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog errorDialog = builder.create();
try {
errorDialog.show();
} catch (BadTokenException ex) {
// Unable to show dialog probably because intent has been closed. Ignoring...
}
}
}
});
}
SpinnerSource.setSelection(lastSource);
SpinnerSort.setSelection(lastOrder);
SpinnerSource.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
String source = ((TextView) arg1).getText().toString();
SharedPreferences preferences = a.getSharedPreferences(PREFERENCE_GENERAL, Activity.MODE_PRIVATE);
- if (!source.equals(preferences.getString(PREFERENCE_SEARCH_SOURCE, source))){
+ if (!source.equals(preferences.getString(PREFERENCE_SEARCH_SOURCE, "DSM Search"))){
preferences.edit().putString(PREFERENCE_SEARCH_SOURCE, source).commit();
if (!lastSearch.equals("")) {
new TorrentSearchTask().execute(lastSearch);
}
}
}
public void onNothingSelected(AdapterView<?> arg0) {
}
});
SpinnerSort.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
String order = ((TextView) arg1).getText().toString();
SharedPreferences preferences = a.getSharedPreferences(PREFERENCE_GENERAL, Activity.MODE_PRIVATE);
- if (!order.equals(preferences.getString(PREFERENCE_SEARCH_ORDER, order))){
+ if (!order.equals(preferences.getString(PREFERENCE_SEARCH_ORDER, "BySeeders"))){
preferences.edit().putString(PREFERENCE_SEARCH_ORDER, order).commit();
if (!lastSearch.equals("")) {
new TorrentSearchTask().execute(lastSearch);
}
}
}
public void onNothingSelected(AdapterView<?> arg0) {
}
});
resList.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
final RelativeLayout rl = (RelativeLayout) arg1;
TextView itemValue = (TextView) rl.findViewById(R.id.result_title);
TextView itemSize = (TextView) rl.findViewById(R.id.result_size);
TextView itemSeed = (TextView) rl.findViewById(R.id.result_seeds);
TextView itemLeech = (TextView) rl.findViewById(R.id.result_leechers);
TextView itemDate = (TextView) rl.findViewById(R.id.result_date);
LayoutInflater inflater = (LayoutInflater) a.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View layout = (View) inflater.inflate(R.layout.search_dialog, null);
final TextView msgView = (TextView) layout.findViewById(R.id.msg);
final TextView tView = (TextView) layout.findViewById(R.id.title);
final TextView sView = (TextView) layout.findViewById(R.id.size);
final TextView seedView = (TextView) layout.findViewById(R.id.seed);
final TextView leechView = (TextView) layout.findViewById(R.id.leech);
final TextView dateView = (TextView) layout.findViewById(R.id.date);
tView.setText(itemValue.getText());
sView.setText(itemSize.getText());
seedView.setText(itemSeed.getText());
leechView.setText(itemLeech.getText());
dateView.setText(itemDate.getText());
msgView.setText(getString(R.string.dialog_message_confirm_add));
Dialog d = new AlertDialog.Builder(a)
.setTitle(R.string.dialog_title_confirm)
.setView(layout)
.setNegativeButton(android.R.string.no, null)
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
TextView tv = (TextView) rl.findViewById(R.id.result_url);
Uri uri = Uri.parse(tv.getText().toString());
AddTaskAction addTask = new AddTaskAction(uri, true, true);
Synodroid app = (Synodroid) getActivity().getApplication();
app.executeAction(SearchFragment.this, addTask, true);
}
}).create();
try {
d.show();
} catch (BadTokenException e) {
try{
if (((Synodroid)getActivity().getApplication()).DEBUG) Log.e(Synodroid.DS_TAG, "SearchFragment: " + e.getMessage());
}
catch (Exception ex){/*DO NOTHING*/}
// Unable to show dialog probably because intent has been closed. Ignoring...
}
}
});
return searchContent;
}
private List<Object[]> getSupportedSites() {
// Create the URI of the TorrentSitesProvider
String uriString = "content://org.transdroid.search.torrentsitesprovider/sites";
Uri uri = Uri.parse(uriString);
// Then query all torrent sites (no selection nor projection nor sort):
Cursor sites = getActivity().managedQuery(uri, null, null, null, null);
Synodroid app = (Synodroid) getActivity().getApplication();
List<Object[]> ret = new ArrayList<Object[]>();
if (app.getServer().getDsmVersion().greaterThen(DSMVersion.VERSION3_1)){
Object[] values = new Object[4];
values[0] = 11223344;
values[1] = "DSM Search";
values[2] = "DSM Search";
values[3] = null;
ret.add(values);
}
if (sites != null){
if (sites.moveToFirst()) {
do {
Object[] values = new Object[4];
values[0] = sites.getInt(0);
values[1] = sites.getString(1);
values[2] = sites.getString(2);
values[3] = sites.getString(3);
ret.add(values);
} while (sites.moveToNext());
}
}
if (ret.size() == 0){
return null;
}
return ret;
}
/*
* (non-Javadoc)
*
* @see android.app.Activity#onResume()
*/
@Override
public void onResume() {
super.onResume();
Activity a = this.getActivity();
Intent intent = a.getIntent();
String action = intent.getAction();
if (Intent.ACTION_SEARCH.equals(action)) {
try{
if (((Synodroid)a.getApplication()).DEBUG) Log.d(Synodroid.DS_TAG,"SearchFragment: New search intent received.");
}
catch (Exception ex){/*DO NOTHING*/}
if ((intent.getFlags() & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) == 0) {
if (getSupportedSites() != null) {
String searchKeywords = intent.getStringExtra(SearchManager.QUERY);
lastSearch = searchKeywords;
if (!searchKeywords.equals("")) {
new TorrentSearchTask().execute(searchKeywords);
SearchRecentSuggestions suggestions = new SearchRecentSuggestions(a, SynodroidSearchSuggestion.AUTHORITY, SynodroidSearchSuggestion.MODE);
suggestions.saveRecentQuery(searchKeywords, null);
} else {
emptyText.setText(R.string.no_keyword);
emptyText.setVisibility(TextView.VISIBLE);
resList.setVisibility(TextView.GONE);
}
}
else {
try{
if (((Synodroid)a.getApplication()).DEBUG) Log.d(Synodroid.DS_TAG,"SearchFragment: No providers available to handle intent.");
}
catch (Exception ex){/*DO NOTHING*/}
AlertDialog.Builder builder = new AlertDialog.Builder(a);
builder.setMessage(R.string.err_provider_missing);
builder.setTitle(getString(R.string.connect_error_title)).setCancelable(false).setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog errorDialog = builder.create();
try {
errorDialog.show();
} catch (BadTokenException e) {
// Unable to show dialog probably because intent has been closed. Ignoring...
}
}
}
else{
try{
if (((Synodroid)a.getApplication()).DEBUG) Log.d(Synodroid.DS_TAG,"SearchFragment: This was an old intent. Skipping it...");
}
catch (Exception ex){/*DO NOTHING*/}
}
//Mark intent as already processed
intent.setFlags(Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY);
a.setIntent(intent);
}
else if (intent.getBooleanExtra("start_search", false)){
getActivity().onSearchRequested();
}
}
private class TorrentSearchTask extends AsyncTask<String, Void, Cursor> {
@Override
protected void onPreExecute() {
emptyText.setVisibility(TextView.VISIBLE);
emptyText.setText(getString(R.string.searching) + " " + lastSearch);
resList.setVisibility(ListView.GONE);
resList.setAdapter(null);
}
@Override
protected Cursor doInBackground(String... params) {
try {
SharedPreferences preferences = getActivity().getSharedPreferences(PREFERENCE_GENERAL, Activity.MODE_PRIVATE);
String pref_src = preferences.getString(PREFERENCE_SEARCH_SOURCE, "DSM Search");
String pref_order = preferences.getString(PREFERENCE_SEARCH_ORDER, "BySeeders");
if (pref_src.equals("DSM Search")){
Synodroid app = (Synodroid) getActivity().getApplication();
return getActivity().managedQuery(Uri.parse(SynodroidDSMSearch.CONTENT_URI+params[0]), null, null, new String[] { app.getServer().getDsmVersion().getTitle(), app.getServer().getCookies(), app.getServer().getUrl(), String.valueOf(app.DEBUG), "0", "50"}, pref_order);
}
else{
// Create the URI of the TorrentProvider
String uriString = "content://org.transdroid.search.torrentsearchprovider/search/" + params[0];
Uri uri = Uri.parse(uriString);
// Then query for this specific record (no selection nor projection nor sort):
return getActivity().managedQuery(uri, null, "SITE = ?", new String[] { pref_src }, pref_order);
}
} catch (Exception e) {
return null;
}
}
@Override
protected void onPostExecute(Cursor cur) {
try{
if (cur == null) {
emptyText.setVisibility(TextView.VISIBLE);
resList.setVisibility(ListView.GONE);
emptyText.setText(getString(R.string.no_results) + " " + lastSearch);
} else {// Show results in the list
if (cur.getCount() == 0) {
emptyText.setVisibility(TextView.VISIBLE);
resList.setVisibility(ListView.GONE);
emptyText.setText(getString(R.string.no_results) + " " + lastSearch);
} else {
emptyText.setVisibility(TextView.GONE);
resList.setVisibility(ListView.VISIBLE);
SimpleCursorAdapter cursor = new SimpleCursorAdapter(getActivity(), R.layout.search_row, cur, from, to);
cursor.setViewBinder(new SearchViewBinder());
resList.setAdapter(cursor);
}
}
}
catch (Exception e){
try{
if (((Synodroid)getActivity().getApplication()).DEBUG) Log.e(Synodroid.DS_TAG, "SearchFragment: Activity was killed before the searchresult came back...");
}
catch (Exception ex){/*DO NOTHING*/}
}
}
}
@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
// Save UI state changes to the savedInstanceState.
// This bundle will be passed to onCreate if the process is
// killed and restarted.
savedInstanceState.putString("lastSearch", lastSearch);
// etc.
super.onSaveInstanceState(savedInstanceState);
}
public void handleMessage(Message msg) {
// Update tasks
if (msg.what == ResponseHandler.MSG_TASK_DL_WAIT){
Toast toast = Toast.makeText(getActivity(), getString(R.string.wait_for_download), Toast.LENGTH_SHORT);
toast.show();
}
else if (msg.what == ResponseHandler.MSG_SE_LIST_RETRIEVED) {
final Activity a = getActivity();
try{
if (((Synodroid)a.getApplication()).DEBUG) Log.d(Synodroid.DS_TAG,"DownloadFragment: Received search engine listing message.");
}catch (Exception ex){/*DO NOTHING*/}
@SuppressWarnings("unchecked")
List<SearchEngine> seList = (List<SearchEngine>) msg.obj;
final CharSequence[] seNames = new CharSequence[seList.size()];
final boolean[] seSelection = new boolean[seList.size()];
for (int iLoop = 0; iLoop < seList.size(); iLoop++) {
SearchEngine se = seList.get(iLoop);
seNames[iLoop] = se.name;
seSelection[iLoop] = se.enabled;
}
AlertDialog.Builder builder = new AlertDialog.Builder(a);
builder.setTitle(getString(R.string.search_engine_title));
builder.setMultiChoiceItems(seNames, seSelection, new DialogInterface.OnMultiChoiceClickListener() {
public void onClick(DialogInterface dialog, int which, boolean isChecked) {
seSelection[which] = isChecked;
}
});
builder.setPositiveButton(R.string.button_ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
List<SearchEngine> newList = new ArrayList<SearchEngine>();
for (int iLoop = 0; iLoop < seNames.length; iLoop++) {
SearchEngine se = new SearchEngine();
se.name = (String) seNames[iLoop];
se.enabled = seSelection[iLoop];
newList.add(se);
}
dialog.dismiss();final Activity a = getActivity();
Synodroid app = (Synodroid) a.getApplication();
app.executeAsynchronousAction(SearchFragment.this, new SetSearchEngines(newList), true);
}
});
builder.setNegativeButton(R.string.button_cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
AlertDialog alert = builder.create();
try {
alert.show();
} catch (BadTokenException e) {
// Unable to show dialog probably because intent has been closed. Ignoring...
}
}
}
}
| false | true | public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final Activity a = getActivity();
try{
if (((Synodroid)a.getApplication()).DEBUG) Log.d(Synodroid.DS_TAG,"SearchFragment: Creating search fragment.");
}catch (Exception ex){/*DO NOTHING*/}
if (savedInstanceState != null)
lastSearch = savedInstanceState.getString("lastSearch");
else
lastSearch = "";
RelativeLayout searchContent = (RelativeLayout) inflater.inflate(R.layout.torrent_search, null, false);
resList = (ListView) searchContent.findViewById(R.id.resList);
emptyText = (TextView) searchContent.findViewById(R.id.empty);
btnInstall = (Button) searchContent.findViewById(R.id.btnTorSearchInst);
btnAlternate = (Button) searchContent.findViewById(R.id.btnTorSearchInstAlternate);
SpinnerSource = (Spinner) searchContent.findViewById(R.id.srcSpinner);
SpinnerSort = (Spinner) searchContent.findViewById(R.id.sortSpinner);
AdapterSource = new ArrayAdapter<CharSequence>(a, android.R.layout.simple_spinner_item);
AdapterSource.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
SpinnerSource.setAdapter(AdapterSource);
AdapterSort = new ArrayAdapter<CharSequence>(a, android.R.layout.simple_spinner_item);
AdapterSort.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
SpinnerSort.setAdapter(AdapterSort);
SharedPreferences preferences = a.getSharedPreferences(PREFERENCE_GENERAL, Activity.MODE_PRIVATE);
String pref_src = preferences.getString(PREFERENCE_SEARCH_SOURCE, "DSM Search");
String pref_order = preferences.getString(PREFERENCE_SEARCH_ORDER, "BySeeders");
int lastOrder = 0;
int lastSource = 0;
for (int i = 0; i < SortOrder.length; i++) {
if (pref_order.equals(SortOrder[i])) {
lastOrder = i;
}
AdapterSort.add(SortOrder[i]);
}
// Gather the supported torrent sites
StringBuilder s = new StringBuilder();
List<Object[]> sites = getSupportedSites();
if (sites != null) {
for (Object[] site :sites){
int i = 0;
s.append((String) site[1]);
s.append("\n");
if (pref_src.equals((String) site[1])) {
lastSource = i;
}
AdapterSource.add((String) site[1]);
i++;
}
emptyText.setText(getString(R.string.sites) + "\n" + s.toString());
btnInstall.setVisibility(Button.GONE);
btnAlternate.setVisibility(Button.GONE);
resList.setVisibility(ListView.GONE);
} else {
SpinnerSort.setVisibility(Spinner.GONE);
SpinnerSource.setVisibility(Spinner.GONE);
resList.setVisibility(ListView.GONE);
emptyText.setText(R.string.provider_missing);
btnInstall.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent goToMarket = null;
goToMarket = new Intent(Intent.ACTION_VIEW, Uri.parse(TORRENT_SEARCH_URL_DL_MARKET));
try {
startActivity(goToMarket);
} catch (Exception e) {
AlertDialog.Builder builder = new AlertDialog.Builder(a);
// By default the message is "Error Unknown"
builder.setMessage(R.string.err_nomarket);
builder.setTitle(getString(R.string.connect_error_title)).setCancelable(false).setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog errorDialog = builder.create();
try {
errorDialog.show();
} catch (BadTokenException ex) {
// Unable to show dialog probably because intent has been closed. Ignoring...
}
}
}
});
btnAlternate.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent goToMarket = null;
goToMarket = new Intent(Intent.ACTION_VIEW, Uri.parse(TORRENT_SEARCH_URL_DL));
try {
startActivity(goToMarket);
} catch (Exception e) {
AlertDialog.Builder builder = new AlertDialog.Builder(a);
// By default the message is "Error Unknown"
builder.setMessage(R.string.err_nobrowser);
builder.setTitle(getString(R.string.connect_error_title)).setCancelable(false).setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog errorDialog = builder.create();
try {
errorDialog.show();
} catch (BadTokenException ex) {
// Unable to show dialog probably because intent has been closed. Ignoring...
}
}
}
});
}
SpinnerSource.setSelection(lastSource);
SpinnerSort.setSelection(lastOrder);
SpinnerSource.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
String source = ((TextView) arg1).getText().toString();
SharedPreferences preferences = a.getSharedPreferences(PREFERENCE_GENERAL, Activity.MODE_PRIVATE);
if (!source.equals(preferences.getString(PREFERENCE_SEARCH_SOURCE, source))){
preferences.edit().putString(PREFERENCE_SEARCH_SOURCE, source).commit();
if (!lastSearch.equals("")) {
new TorrentSearchTask().execute(lastSearch);
}
}
}
public void onNothingSelected(AdapterView<?> arg0) {
}
});
SpinnerSort.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
String order = ((TextView) arg1).getText().toString();
SharedPreferences preferences = a.getSharedPreferences(PREFERENCE_GENERAL, Activity.MODE_PRIVATE);
if (!order.equals(preferences.getString(PREFERENCE_SEARCH_ORDER, order))){
preferences.edit().putString(PREFERENCE_SEARCH_ORDER, order).commit();
if (!lastSearch.equals("")) {
new TorrentSearchTask().execute(lastSearch);
}
}
}
public void onNothingSelected(AdapterView<?> arg0) {
}
});
resList.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
final RelativeLayout rl = (RelativeLayout) arg1;
TextView itemValue = (TextView) rl.findViewById(R.id.result_title);
TextView itemSize = (TextView) rl.findViewById(R.id.result_size);
TextView itemSeed = (TextView) rl.findViewById(R.id.result_seeds);
TextView itemLeech = (TextView) rl.findViewById(R.id.result_leechers);
TextView itemDate = (TextView) rl.findViewById(R.id.result_date);
LayoutInflater inflater = (LayoutInflater) a.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View layout = (View) inflater.inflate(R.layout.search_dialog, null);
final TextView msgView = (TextView) layout.findViewById(R.id.msg);
final TextView tView = (TextView) layout.findViewById(R.id.title);
final TextView sView = (TextView) layout.findViewById(R.id.size);
final TextView seedView = (TextView) layout.findViewById(R.id.seed);
final TextView leechView = (TextView) layout.findViewById(R.id.leech);
final TextView dateView = (TextView) layout.findViewById(R.id.date);
tView.setText(itemValue.getText());
sView.setText(itemSize.getText());
seedView.setText(itemSeed.getText());
leechView.setText(itemLeech.getText());
dateView.setText(itemDate.getText());
msgView.setText(getString(R.string.dialog_message_confirm_add));
Dialog d = new AlertDialog.Builder(a)
.setTitle(R.string.dialog_title_confirm)
.setView(layout)
.setNegativeButton(android.R.string.no, null)
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
TextView tv = (TextView) rl.findViewById(R.id.result_url);
Uri uri = Uri.parse(tv.getText().toString());
AddTaskAction addTask = new AddTaskAction(uri, true, true);
Synodroid app = (Synodroid) getActivity().getApplication();
app.executeAction(SearchFragment.this, addTask, true);
}
}).create();
try {
d.show();
} catch (BadTokenException e) {
try{
if (((Synodroid)getActivity().getApplication()).DEBUG) Log.e(Synodroid.DS_TAG, "SearchFragment: " + e.getMessage());
}
catch (Exception ex){/*DO NOTHING*/}
// Unable to show dialog probably because intent has been closed. Ignoring...
}
}
});
return searchContent;
}
| public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final Activity a = getActivity();
try{
if (((Synodroid)a.getApplication()).DEBUG) Log.d(Synodroid.DS_TAG,"SearchFragment: Creating search fragment.");
}catch (Exception ex){/*DO NOTHING*/}
if (savedInstanceState != null)
lastSearch = savedInstanceState.getString("lastSearch");
else
lastSearch = "";
RelativeLayout searchContent = (RelativeLayout) inflater.inflate(R.layout.torrent_search, null, false);
resList = (ListView) searchContent.findViewById(R.id.resList);
emptyText = (TextView) searchContent.findViewById(R.id.empty);
btnInstall = (Button) searchContent.findViewById(R.id.btnTorSearchInst);
btnAlternate = (Button) searchContent.findViewById(R.id.btnTorSearchInstAlternate);
SpinnerSource = (Spinner) searchContent.findViewById(R.id.srcSpinner);
SpinnerSort = (Spinner) searchContent.findViewById(R.id.sortSpinner);
AdapterSource = new ArrayAdapter<CharSequence>(a, android.R.layout.simple_spinner_item);
AdapterSource.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
SpinnerSource.setAdapter(AdapterSource);
AdapterSort = new ArrayAdapter<CharSequence>(a, android.R.layout.simple_spinner_item);
AdapterSort.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
SpinnerSort.setAdapter(AdapterSort);
SharedPreferences preferences = a.getSharedPreferences(PREFERENCE_GENERAL, Activity.MODE_PRIVATE);
String pref_src = preferences.getString(PREFERENCE_SEARCH_SOURCE, "DSM Search");
String pref_order = preferences.getString(PREFERENCE_SEARCH_ORDER, "BySeeders");
int lastOrder = 0;
int lastSource = 0;
for (int i = 0; i < SortOrder.length; i++) {
if (pref_order.equals(SortOrder[i])) {
lastOrder = i;
}
AdapterSort.add(SortOrder[i]);
}
// Gather the supported torrent sites
StringBuilder s = new StringBuilder();
List<Object[]> sites = getSupportedSites();
if (sites != null) {
for (Object[] site :sites){
int i = 0;
s.append((String) site[1]);
s.append("\n");
if (pref_src.equals((String) site[1])) {
lastSource = i;
}
AdapterSource.add((String) site[1]);
i++;
}
emptyText.setText(getString(R.string.sites) + "\n" + s.toString());
btnInstall.setVisibility(Button.GONE);
btnAlternate.setVisibility(Button.GONE);
resList.setVisibility(ListView.GONE);
} else {
SpinnerSort.setVisibility(Spinner.GONE);
SpinnerSource.setVisibility(Spinner.GONE);
resList.setVisibility(ListView.GONE);
emptyText.setText(R.string.provider_missing);
btnInstall.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent goToMarket = null;
goToMarket = new Intent(Intent.ACTION_VIEW, Uri.parse(TORRENT_SEARCH_URL_DL_MARKET));
try {
startActivity(goToMarket);
} catch (Exception e) {
AlertDialog.Builder builder = new AlertDialog.Builder(a);
// By default the message is "Error Unknown"
builder.setMessage(R.string.err_nomarket);
builder.setTitle(getString(R.string.connect_error_title)).setCancelable(false).setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog errorDialog = builder.create();
try {
errorDialog.show();
} catch (BadTokenException ex) {
// Unable to show dialog probably because intent has been closed. Ignoring...
}
}
}
});
btnAlternate.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent goToMarket = null;
goToMarket = new Intent(Intent.ACTION_VIEW, Uri.parse(TORRENT_SEARCH_URL_DL));
try {
startActivity(goToMarket);
} catch (Exception e) {
AlertDialog.Builder builder = new AlertDialog.Builder(a);
// By default the message is "Error Unknown"
builder.setMessage(R.string.err_nobrowser);
builder.setTitle(getString(R.string.connect_error_title)).setCancelable(false).setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog errorDialog = builder.create();
try {
errorDialog.show();
} catch (BadTokenException ex) {
// Unable to show dialog probably because intent has been closed. Ignoring...
}
}
}
});
}
SpinnerSource.setSelection(lastSource);
SpinnerSort.setSelection(lastOrder);
SpinnerSource.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
String source = ((TextView) arg1).getText().toString();
SharedPreferences preferences = a.getSharedPreferences(PREFERENCE_GENERAL, Activity.MODE_PRIVATE);
if (!source.equals(preferences.getString(PREFERENCE_SEARCH_SOURCE, "DSM Search"))){
preferences.edit().putString(PREFERENCE_SEARCH_SOURCE, source).commit();
if (!lastSearch.equals("")) {
new TorrentSearchTask().execute(lastSearch);
}
}
}
public void onNothingSelected(AdapterView<?> arg0) {
}
});
SpinnerSort.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
String order = ((TextView) arg1).getText().toString();
SharedPreferences preferences = a.getSharedPreferences(PREFERENCE_GENERAL, Activity.MODE_PRIVATE);
if (!order.equals(preferences.getString(PREFERENCE_SEARCH_ORDER, "BySeeders"))){
preferences.edit().putString(PREFERENCE_SEARCH_ORDER, order).commit();
if (!lastSearch.equals("")) {
new TorrentSearchTask().execute(lastSearch);
}
}
}
public void onNothingSelected(AdapterView<?> arg0) {
}
});
resList.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
final RelativeLayout rl = (RelativeLayout) arg1;
TextView itemValue = (TextView) rl.findViewById(R.id.result_title);
TextView itemSize = (TextView) rl.findViewById(R.id.result_size);
TextView itemSeed = (TextView) rl.findViewById(R.id.result_seeds);
TextView itemLeech = (TextView) rl.findViewById(R.id.result_leechers);
TextView itemDate = (TextView) rl.findViewById(R.id.result_date);
LayoutInflater inflater = (LayoutInflater) a.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View layout = (View) inflater.inflate(R.layout.search_dialog, null);
final TextView msgView = (TextView) layout.findViewById(R.id.msg);
final TextView tView = (TextView) layout.findViewById(R.id.title);
final TextView sView = (TextView) layout.findViewById(R.id.size);
final TextView seedView = (TextView) layout.findViewById(R.id.seed);
final TextView leechView = (TextView) layout.findViewById(R.id.leech);
final TextView dateView = (TextView) layout.findViewById(R.id.date);
tView.setText(itemValue.getText());
sView.setText(itemSize.getText());
seedView.setText(itemSeed.getText());
leechView.setText(itemLeech.getText());
dateView.setText(itemDate.getText());
msgView.setText(getString(R.string.dialog_message_confirm_add));
Dialog d = new AlertDialog.Builder(a)
.setTitle(R.string.dialog_title_confirm)
.setView(layout)
.setNegativeButton(android.R.string.no, null)
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
TextView tv = (TextView) rl.findViewById(R.id.result_url);
Uri uri = Uri.parse(tv.getText().toString());
AddTaskAction addTask = new AddTaskAction(uri, true, true);
Synodroid app = (Synodroid) getActivity().getApplication();
app.executeAction(SearchFragment.this, addTask, true);
}
}).create();
try {
d.show();
} catch (BadTokenException e) {
try{
if (((Synodroid)getActivity().getApplication()).DEBUG) Log.e(Synodroid.DS_TAG, "SearchFragment: " + e.getMessage());
}
catch (Exception ex){/*DO NOTHING*/}
// Unable to show dialog probably because intent has been closed. Ignoring...
}
}
});
return searchContent;
}
|
diff --git a/src/org/geometerplus/fbreader/network/opds/OPDSCustomNetworkLink.java b/src/org/geometerplus/fbreader/network/opds/OPDSCustomNetworkLink.java
index e570ba93..330bc317 100644
--- a/src/org/geometerplus/fbreader/network/opds/OPDSCustomNetworkLink.java
+++ b/src/org/geometerplus/fbreader/network/opds/OPDSCustomNetworkLink.java
@@ -1,160 +1,160 @@
/*
* Copyright (C) 2010-2011 Geometer Plus <[email protected]>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
package org.geometerplus.fbreader.network.opds;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;
import org.geometerplus.zlibrary.core.network.ZLNetworkManager;
import org.geometerplus.zlibrary.core.network.ZLNetworkException;
import org.geometerplus.zlibrary.core.network.ZLNetworkRequest;
import org.geometerplus.zlibrary.core.util.ZLMiscUtil;
import org.geometerplus.fbreader.network.ICustomNetworkLink;
import org.geometerplus.fbreader.network.NetworkException;
import org.geometerplus.fbreader.network.urlInfo.*;
public class OPDSCustomNetworkLink extends OPDSNetworkLink implements ICustomNetworkLink {
private boolean myHasChanges;
private static String removeWWWPrefix(String siteName) {
if (siteName != null && siteName.startsWith("www.")) {
return siteName.substring(4);
}
return siteName;
}
public OPDSCustomNetworkLink(int id, String siteName, String title, String summary, String language, UrlInfoCollection<UrlInfoWithDate> infos) {
super(id, removeWWWPrefix(siteName), title, summary, language, infos);
}
public boolean hasChanges() {
return myHasChanges;
}
public void resetChanges() {
myHasChanges = false;
}
public final void setSiteName(String name) {
myHasChanges = myHasChanges || !ZLMiscUtil.equals(mySiteName, name);
mySiteName = name;
}
public final void setSummary(String summary) {
myHasChanges = myHasChanges || !ZLMiscUtil.equals(mySummary, summary);
mySummary = summary;
}
public final void setTitle(String title) {
myHasChanges = myHasChanges || !ZLMiscUtil.equals(myTitle, title);
myTitle = title;
}
public final void setUrl(UrlInfo.Type type, String url) {
myInfos.removeAllInfos(type);
myInfos.addInfo(new UrlInfoWithDate(type, url));
myHasChanges = true;
}
public final void removeUrl(UrlInfo.Type type) {
myHasChanges = myHasChanges || myInfos.getInfo(type) != null;
myInfos.removeAllInfos(type);
}
public boolean isObsolete(long milliSeconds) {
final long old = System.currentTimeMillis() - milliSeconds;
Date updateDate = getUrlInfo(UrlInfo.Type.Search).Updated;
if (updateDate == null || updateDate.getTime() < old) {
return true;
}
updateDate = getUrlInfo(UrlInfo.Type.Image).Updated;
if (updateDate == null || updateDate.getTime() < old) {
return true;
}
return false;
}
public void reloadInfo(final boolean urlsOnly, boolean quietly) throws ZLNetworkException {
final LinkedList<String> opensearchDescriptionURLs = new LinkedList<String>();
final List<OpenSearchDescription> descriptions = Collections.synchronizedList(new LinkedList<OpenSearchDescription>());
ZLNetworkException error = null;
try {
ZLNetworkManager.Instance().perform(new ZLNetworkRequest(getUrl(UrlInfo.Type.Catalog), quietly) {
@Override
public void handleStream(InputStream inputStream, int length) throws IOException, ZLNetworkException {
final OPDSCatalogInfoHandler info = new OPDSCatalogInfoHandler(getURL(), OPDSCustomNetworkLink.this, opensearchDescriptionURLs);
new OPDSXMLReader(info, false).read(inputStream);
if (!info.FeedStarted) {
throw new ZLNetworkException(NetworkException.ERROR_NOT_AN_OPDS);
}
if (info.Title == null) {
throw new ZLNetworkException(NetworkException.ERROR_NO_REQUIRED_INFORMATION);
}
setUrl(UrlInfo.Type.Image, info.Icon);
if (info.DirectOpenSearchDescription != null) {
descriptions.add(info.DirectOpenSearchDescription);
}
if (!urlsOnly) {
myTitle = info.Title.toString();
mySummary = info.Summary != null ? info.Summary.toString() : null;
}
}
});
} catch (ZLNetworkException e) {
error = e;
}
if (!opensearchDescriptionURLs.isEmpty()) {
LinkedList<ZLNetworkRequest> requests = new LinkedList<ZLNetworkRequest>();
for (String url: opensearchDescriptionURLs) {
- requests.add(new ZLNetworkRequest(url) {
+ requests.add(new ZLNetworkRequest(url, quietly) {
@Override
public void handleStream(InputStream inputStream, int length) throws IOException, ZLNetworkException {
new OpenSearchXMLReader(getURL(), descriptions).read(inputStream);
}
});
}
try {
ZLNetworkManager.Instance().perform(requests);
} catch (ZLNetworkException e) {
if (error == null) {
error = e;
}
}
}
if (!descriptions.isEmpty()) {
// TODO: May be do not use '%s'??? Use Description instead??? (this needs to rewrite SEARCH engine logic a little)
setUrl(UrlInfo.Type.Search, descriptions.get(0).makeQuery("%s"));
} else {
setUrl(UrlInfo.Type.Search, null);
}
if (error != null) {
throw error;
}
}
}
| true | true | public void reloadInfo(final boolean urlsOnly, boolean quietly) throws ZLNetworkException {
final LinkedList<String> opensearchDescriptionURLs = new LinkedList<String>();
final List<OpenSearchDescription> descriptions = Collections.synchronizedList(new LinkedList<OpenSearchDescription>());
ZLNetworkException error = null;
try {
ZLNetworkManager.Instance().perform(new ZLNetworkRequest(getUrl(UrlInfo.Type.Catalog), quietly) {
@Override
public void handleStream(InputStream inputStream, int length) throws IOException, ZLNetworkException {
final OPDSCatalogInfoHandler info = new OPDSCatalogInfoHandler(getURL(), OPDSCustomNetworkLink.this, opensearchDescriptionURLs);
new OPDSXMLReader(info, false).read(inputStream);
if (!info.FeedStarted) {
throw new ZLNetworkException(NetworkException.ERROR_NOT_AN_OPDS);
}
if (info.Title == null) {
throw new ZLNetworkException(NetworkException.ERROR_NO_REQUIRED_INFORMATION);
}
setUrl(UrlInfo.Type.Image, info.Icon);
if (info.DirectOpenSearchDescription != null) {
descriptions.add(info.DirectOpenSearchDescription);
}
if (!urlsOnly) {
myTitle = info.Title.toString();
mySummary = info.Summary != null ? info.Summary.toString() : null;
}
}
});
} catch (ZLNetworkException e) {
error = e;
}
if (!opensearchDescriptionURLs.isEmpty()) {
LinkedList<ZLNetworkRequest> requests = new LinkedList<ZLNetworkRequest>();
for (String url: opensearchDescriptionURLs) {
requests.add(new ZLNetworkRequest(url) {
@Override
public void handleStream(InputStream inputStream, int length) throws IOException, ZLNetworkException {
new OpenSearchXMLReader(getURL(), descriptions).read(inputStream);
}
});
}
try {
ZLNetworkManager.Instance().perform(requests);
} catch (ZLNetworkException e) {
if (error == null) {
error = e;
}
}
}
if (!descriptions.isEmpty()) {
// TODO: May be do not use '%s'??? Use Description instead??? (this needs to rewrite SEARCH engine logic a little)
setUrl(UrlInfo.Type.Search, descriptions.get(0).makeQuery("%s"));
} else {
setUrl(UrlInfo.Type.Search, null);
}
if (error != null) {
throw error;
}
}
| public void reloadInfo(final boolean urlsOnly, boolean quietly) throws ZLNetworkException {
final LinkedList<String> opensearchDescriptionURLs = new LinkedList<String>();
final List<OpenSearchDescription> descriptions = Collections.synchronizedList(new LinkedList<OpenSearchDescription>());
ZLNetworkException error = null;
try {
ZLNetworkManager.Instance().perform(new ZLNetworkRequest(getUrl(UrlInfo.Type.Catalog), quietly) {
@Override
public void handleStream(InputStream inputStream, int length) throws IOException, ZLNetworkException {
final OPDSCatalogInfoHandler info = new OPDSCatalogInfoHandler(getURL(), OPDSCustomNetworkLink.this, opensearchDescriptionURLs);
new OPDSXMLReader(info, false).read(inputStream);
if (!info.FeedStarted) {
throw new ZLNetworkException(NetworkException.ERROR_NOT_AN_OPDS);
}
if (info.Title == null) {
throw new ZLNetworkException(NetworkException.ERROR_NO_REQUIRED_INFORMATION);
}
setUrl(UrlInfo.Type.Image, info.Icon);
if (info.DirectOpenSearchDescription != null) {
descriptions.add(info.DirectOpenSearchDescription);
}
if (!urlsOnly) {
myTitle = info.Title.toString();
mySummary = info.Summary != null ? info.Summary.toString() : null;
}
}
});
} catch (ZLNetworkException e) {
error = e;
}
if (!opensearchDescriptionURLs.isEmpty()) {
LinkedList<ZLNetworkRequest> requests = new LinkedList<ZLNetworkRequest>();
for (String url: opensearchDescriptionURLs) {
requests.add(new ZLNetworkRequest(url, quietly) {
@Override
public void handleStream(InputStream inputStream, int length) throws IOException, ZLNetworkException {
new OpenSearchXMLReader(getURL(), descriptions).read(inputStream);
}
});
}
try {
ZLNetworkManager.Instance().perform(requests);
} catch (ZLNetworkException e) {
if (error == null) {
error = e;
}
}
}
if (!descriptions.isEmpty()) {
// TODO: May be do not use '%s'??? Use Description instead??? (this needs to rewrite SEARCH engine logic a little)
setUrl(UrlInfo.Type.Search, descriptions.get(0).makeQuery("%s"));
} else {
setUrl(UrlInfo.Type.Search, null);
}
if (error != null) {
throw error;
}
}
|
diff --git a/fm-workbench/agree/com.rockwellcollins.atc.agree.analysis/src/com/rockwellcollins/atc/agree/analysis/AgreeAnnexEmitter.java b/fm-workbench/agree/com.rockwellcollins.atc.agree.analysis/src/com/rockwellcollins/atc/agree/analysis/AgreeAnnexEmitter.java
index ffdeb4b2..819bc20e 100644
--- a/fm-workbench/agree/com.rockwellcollins.atc.agree.analysis/src/com/rockwellcollins/atc/agree/analysis/AgreeAnnexEmitter.java
+++ b/fm-workbench/agree/com.rockwellcollins.atc.agree.analysis/src/com/rockwellcollins/atc/agree/analysis/AgreeAnnexEmitter.java
@@ -1,2154 +1,2154 @@
package com.rockwellcollins.atc.agree.analysis;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import jkind.lustre.BinaryExpr;
import jkind.lustre.BinaryOp;
import jkind.lustre.BoolExpr;
import jkind.lustre.CondactExpr;
import jkind.lustre.Equation;
import jkind.lustre.Expr;
import jkind.lustre.IdExpr;
import jkind.lustre.IfThenElseExpr;
import jkind.lustre.IntExpr;
import jkind.lustre.NamedType;
import jkind.lustre.Node;
import jkind.lustre.NodeCallExpr;
import jkind.lustre.RealExpr;
import jkind.lustre.Type;
import jkind.lustre.UnaryExpr;
import jkind.lustre.UnaryOp;
import jkind.lustre.VarDecl;
import org.eclipse.emf.ecore.EObject;
import org.osate.aadl2.AnnexSubclause;
import org.osate.aadl2.BooleanLiteral;
import org.osate.aadl2.BusAccess;
import org.osate.aadl2.ComponentClassifier;
import org.osate.aadl2.ComponentImplementation;
import org.osate.aadl2.ComponentType;
import org.osate.aadl2.ConnectedElement;
import org.osate.aadl2.Connection;
import org.osate.aadl2.ConnectionEnd;
import org.osate.aadl2.Context;
import org.osate.aadl2.DataAccess;
import org.osate.aadl2.DataImplementation;
import org.osate.aadl2.DataPort;
import org.osate.aadl2.DataSubcomponent;
import org.osate.aadl2.DataSubcomponentType;
import org.osate.aadl2.DataType;
import org.osate.aadl2.DirectedFeature;
import org.osate.aadl2.DirectionType;
import org.osate.aadl2.EnumerationLiteral;
import org.osate.aadl2.EventDataPort;
import org.osate.aadl2.Feature;
import org.osate.aadl2.FeatureGroup;
import org.osate.aadl2.FeatureGroupType;
import org.osate.aadl2.FeatureType;
import org.osate.aadl2.IntegerLiteral;
import org.osate.aadl2.NamedElement;
import org.osate.aadl2.NamedValue;
import org.osate.aadl2.Property;
import org.osate.aadl2.PropertyExpression;
import org.osate.aadl2.RealLiteral;
import org.osate.aadl2.StringLiteral;
import org.osate.aadl2.Subcomponent;
import org.osate.aadl2.ThreadSubcomponent;
import org.osate.aadl2.instance.ComponentInstance;
import org.osate.aadl2.instance.ConnectionInstance;
import org.osate.aadl2.instance.FeatureCategory;
import org.osate.aadl2.instance.FeatureInstance;
import org.osate.aadl2.modelsupport.resources.OsateResourceUtil;
import org.osate.aadl2.properties.PropertyDoesNotApplyToHolderException;
import org.osate.annexsupport.AnnexUtil;
import org.osate.xtext.aadl2.properties.util.EMFIndexRetrieval;
import org.osate.xtext.aadl2.properties.util.PropertyUtils;
import com.google.inject.name.Named;
import com.rockwellcollins.atc.agree.agree.AgreeContract;
import com.rockwellcollins.atc.agree.agree.AgreeContractSubclause;
import com.rockwellcollins.atc.agree.agree.AgreePackage;
import com.rockwellcollins.atc.agree.agree.Arg;
import com.rockwellcollins.atc.agree.agree.AssertStatement;
import com.rockwellcollins.atc.agree.agree.AssumeStatement;
import com.rockwellcollins.atc.agree.agree.BoolLitExpr;
import com.rockwellcollins.atc.agree.agree.CalenStatement;
import com.rockwellcollins.atc.agree.agree.ConstStatement;
import com.rockwellcollins.atc.agree.agree.EqStatement;
import com.rockwellcollins.atc.agree.agree.FnCallExpr;
import com.rockwellcollins.atc.agree.agree.FnDefExpr;
import com.rockwellcollins.atc.agree.agree.GetPropertyExpr;
import com.rockwellcollins.atc.agree.agree.GuaranteeStatement;
import com.rockwellcollins.atc.agree.agree.IntLitExpr;
import com.rockwellcollins.atc.agree.agree.LemmaStatement;
import com.rockwellcollins.atc.agree.agree.LiftStatement;
import com.rockwellcollins.atc.agree.agree.NestedDotID;
import com.rockwellcollins.atc.agree.agree.NodeBodyExpr;
import com.rockwellcollins.atc.agree.agree.NodeDefExpr;
import com.rockwellcollins.atc.agree.agree.NodeEq;
import com.rockwellcollins.atc.agree.agree.NodeLemma;
import com.rockwellcollins.atc.agree.agree.NodeStmt;
import com.rockwellcollins.atc.agree.agree.ParamStatement;
import com.rockwellcollins.atc.agree.agree.PreExpr;
import com.rockwellcollins.atc.agree.agree.PrevExpr;
import com.rockwellcollins.atc.agree.agree.PropertyStatement;
import com.rockwellcollins.atc.agree.agree.RealLitExpr;
import com.rockwellcollins.atc.agree.agree.SpecStatement;
import com.rockwellcollins.atc.agree.agree.SynchStatement;
import com.rockwellcollins.atc.agree.agree.ThisExpr;
import com.rockwellcollins.atc.agree.agree.util.AgreeSwitch;
import com.rockwellcollins.atc.agree.analysis.AgreeFeature.ConnType;
import com.rockwellcollins.atc.agree.analysis.AgreeFeature.Direction;
import com.rockwellcollins.atc.agree.analysis.AgreeLayout.SigType;
public class AgreeAnnexEmitter extends AgreeSwitch<Expr> {
//lists of all the jkind expressions from the annex
public final List<Expr> assumpExpressions = new ArrayList<>();
public final List<Equation> guarExpressions = new ArrayList<>();
public final List<Expr> assertExpressions = new ArrayList<>();
public final List<Equation> propExpressions = new ArrayList<>();
public final List<Equation> eqExpressions = new ArrayList<>();
public final List<Equation> constExpressions = new ArrayList<>();
public final List<Node> nodeDefExpressions = new ArrayList<>();
public final List<Equation> connExpressions = new ArrayList<>();
//this set keeps track of all the left hand sides of connection
//expressions
public final Set<String> connLHS = new HashSet<>();
public final String sysGuarTag = "__SYS_GUARANTEE_";
//reference map used for hyperlinking from the console
public final Map<String, EObject> refMap = new HashMap<>();
//used for preventing name collision, and for pretty printing aadl variables
private final String jKindNameTag;
private final String aadlNameTag;
private final String clockIDPrefix = "__CLOCK_";
private final String queueInClockPrefix ="__QUEUE_IN_CLOCK_";
private final String queueOutClockPrefix ="__QUEUE_OUT_CLOCK_";
private final String queueCountPrefix = "__QUEUE_COUNT_";
private final Map<EventDataPort, List<IdExpr>> queueInClockMap = new HashMap<>();
private final Map<EventDataPort, List<IdExpr>> queueOutClockMap = new HashMap<>();
private final Map<EventDataPort, List<IdExpr>> queueCountMap = new HashMap<>();
//used for pretty printing jkind -> aadl variables
public final Map<String, String> varRenaming = new HashMap<>();
//used for printing results
public final AgreeLayout layout;
private final String category;
//keeps track of new variables
private final Set<AgreeVarDecl> inputVars = new HashSet<>();
private final Set<AgreeVarDecl> internalVars = new HashSet<>();
private final Set<AgreeVarDecl> outputVars = new HashSet<>();
private final Map<String, List<AgreeQueueElement>> queueMap = new HashMap<>();
//the special string used to replace the "." characters in aadl
private final String dotChar = "__";
//the current subcomponent
public Subcomponent curComp;
//the current implementation
private ComponentInstance curInst;
//print errors and warnings here
public final AgreeLogger log = new AgreeLogger();
//used to keep track of the different properties
public List<String> assumProps = null;
public List<String> consistProps = null;
public List<String> guarProps = null;
//during recursive analysis we do not want to use lifts
//when proving top level components
private boolean ignoreLifts;
//the depth of which to check consistency
private int consistUnrollDepth = 5;
//TODO: do something more robust about this later
//holds initial values for types
private Map<String, Expr> initTypeMap = new HashMap<>();
private BoolExpr initBool = new BoolExpr(true);
private RealExpr initReal = new RealExpr(new BigDecimal("0.0"));
private IntExpr initInt = new IntExpr(BigInteger.ZERO);
//the node generated by the getComponentNode() call;
public AgreeNode agreeNode = null;
private int synchrony = 0;
private List<IdExpr> calendar = new ArrayList<IdExpr>();
private boolean simultaneity = true;
private final Map<FeatureInstance, List<AgreeFeature>> featInstToAgreeFeatMap = new HashMap<>();
public AgreeAnnexEmitter(ComponentInstance compInst,
AgreeLayout layout,
String category,
String jPrefix,
String aPrefix,
boolean ignoreLifts,
boolean topLevel){
this.layout = layout;
this.curInst = compInst;
this.category = category;
this.ignoreLifts = ignoreLifts;
initTypeMap.put("bool", initBool);
initTypeMap.put("real", initReal);
initTypeMap.put("int", initInt);
if(!layout.getCategories().contains(category)){
layout.addCategory(category);
}
curComp = curInst.getSubcomponent();
jKindNameTag = jPrefix;
aadlNameTag = aPrefix;
ComponentClassifier compClass = compInst.getComponentClassifier();
//get information about all the features of this component and its subcomponents
recordFeatures(compInst);
//populates the connection equivalences if we are at the top level
//this is only here to make sure that "LIFT" statements work correctly
if(topLevel){
setConnExprs((ComponentImplementation)compClass, jPrefix, aPrefix);
//this function must be called after the previous function
setEventPortQueues();
}
}
private void recordFeatures(ComponentInstance compInst) {
for(FeatureInstance featInst : compInst.getFeatureInstances()){
List<AgreeFeature> featList = recordFeatures_Helper(jKindNameTag, aadlNameTag, featInst);
//add features to the correct input var or output var location
for(AgreeFeature agreeFeat : featList){
AgreeVarDecl varDecl = new AgreeVarDecl(agreeFeat.lustreString,
agreeFeat.aadlString, agreeFeat.varType);
switch(agreeFeat.direction){
case IN:
inputVars.add(varDecl);
layout.addElement(category, agreeFeat.aadlString, AgreeLayout.SigType.INPUT);
break;
case OUT:
outputVars.add(varDecl);
layout.addElement(category, agreeFeat.aadlString, AgreeLayout.SigType.OUTPUT);
}
addToRenaming(agreeFeat.lustreString, agreeFeat.aadlString);
refMap.put(agreeFeat.aadlString, agreeFeat.feature);
}
//featInstToAgreeFeatMap.put(featInst, featList);
}
//get information about all the features of this components subcomponents
for(ComponentInstance subCompInst : compInst.getComponentInstances()){
for(FeatureInstance featInst : subCompInst.getFeatureInstances()){
List<AgreeFeature> featList = recordFeatures_Helper(jKindNameTag + subCompInst.getName() + dotChar,
aadlNameTag + subCompInst.getName() + ".",featInst);
for(AgreeFeature agreeFeat : featList){
AgreeVarDecl varDecl = new AgreeVarDecl(agreeFeat.lustreString,
agreeFeat.aadlString, agreeFeat.varType);
switch(agreeFeat.direction){
case IN:
inputVars.add(varDecl);
layout.addElement(category, agreeFeat.aadlString, AgreeLayout.SigType.INPUT);
break;
case OUT:
outputVars.add(varDecl);
layout.addElement(category, agreeFeat.aadlString, AgreeLayout.SigType.OUTPUT);
}
addToRenaming(agreeFeat.lustreString, agreeFeat.aadlString);
refMap.put(agreeFeat.aadlString, agreeFeat.feature);
}
//featInstToAgreeFeatMap.put(featInst, featList);
}
}
}
private void addToRenamingAll(Map<String, String> renamings) {
for(Entry<String,String> entry :renamings.entrySet()){
addToRenaming(entry.getKey(),entry.getValue());
}
}
private void addToRenaming(String key, String value){
if(varRenaming.containsValue(value)){
//TODO: this could be done another way if its to slow
for(Entry<String,String> entry : varRenaming.entrySet()){
if(entry.getValue().equals(value) && !entry.getKey().equals(key)){
throw new AgreeException("There is a name collision with a multiple variables"
+ ", assumptions, or guarantees named '"+value+"' which will cause "
+ "issues with reporting results");
}
}
}
varRenaming.put(key, value);
}
private void setEventPortQueues() {
//queueSignalEqualityAssertion
for(String destStr : queueMap.keySet()){
List<AgreeQueueElement> queueList = queueMap.get(destStr);
AgreeQueueElement firstQueue = queueList.get(0);
long queueSize = firstQueue.queueSize;
if(queueSize < 0){
throw new AgreeException("The feature '"+firstQueue.aDest+"' must have a queue size specified");
}
Type type = firstQueue.type;
int numInputs = queueList.size();
Node queueNode = AgreeCalendarUtils.queueNode("__Queue_Node_"+destStr, type, (int)queueSize);
Node inputMultiplex = AgreeCalendarUtils.queueMultiplexNode("__Queue_Mult_"+destStr, type, numInputs);
nodeDefExpressions.add(queueNode);
nodeDefExpressions.add(inputMultiplex);
List<Expr> queueMultInputs = new ArrayList<>();
List<Expr> queueInputs = new ArrayList<>();
Expr queueClockInExpr = new BoolExpr(false);
for(AgreeQueueElement agreeQueEl : queueList){
//do some sanity checks
if(firstQueue.destConn != agreeQueEl.destConn){
throw new AgreeException("Something went wrong with book keeping during queue creation");
}
String jCat = agreeQueEl.sourCategory == null ? jKindNameTag : jKindNameTag + agreeQueEl.sourCategory+dotChar;
String aCat = agreeQueEl.sourCategory == null ? aadlNameTag : aadlNameTag + agreeQueEl.sourCategory+".";
IdExpr clockInId = new IdExpr(queueInClockPrefix+jCat+agreeQueEl.sourConn.getName());
AgreeVarDecl clockInVar =
new AgreeVarDecl(clockInId.id,
queueInClockPrefix+aCat+agreeQueEl.sourConn.getName()
, NamedType.BOOL.toString());
//if the clock input hasn't been created yet,
//do reference mapping and add it to the map
//of input clocks
if(!inputVars.contains(clockInVar)){
inputVars.add(clockInVar);
addToRenaming(clockInVar.jKindStr, clockInVar.aadlStr);
refMap.put(clockInVar.aadlStr, agreeQueEl.sourConn);
layout.addElement(category, clockInVar.aadlStr, AgreeLayout.SigType.INPUT);
List<IdExpr> clockInIds = queueInClockMap.get(agreeQueEl.sourConn);
if(clockInIds == null){
clockInIds = new ArrayList<>();
queueInClockMap.put(agreeQueEl.sourConn, clockInIds);
}
clockInIds.add(clockInId);
}
queueMultInputs.add(new IdExpr(agreeQueEl.jSour));
queueMultInputs.add(clockInId);
queueClockInExpr = new BinaryExpr(queueClockInExpr, BinaryOp.OR, clockInId);
}
//add all the stuff for the queue multiplexer
NodeCallExpr queueMultCall = new NodeCallExpr(inputMultiplex.id, queueMultInputs);
IdExpr queueInputId = new IdExpr("__QUEUE_INPUT_"+destStr);
AgreeVarDecl queueInputVar =
new AgreeVarDecl(queueInputId.id, queueInputId.id, type.toString());
internalVars.add(queueInputVar);
Equation multEq = new Equation(queueInputId, queueMultCall);
addConnection(multEq);
//add all the stuff for the queuenode call
String jCat = firstQueue.destCategory == null ? jKindNameTag : jKindNameTag + firstQueue.destCategory+dotChar;
String aCat = firstQueue.destCategory == null ? aadlNameTag : aadlNameTag + firstQueue.destCategory+".";
IdExpr clockOutId = new IdExpr(queueOutClockPrefix+jCat+firstQueue.destConn.getName());
AgreeVarDecl clockOutVar =
new AgreeVarDecl(clockOutId.id,
queueOutClockPrefix+aCat+firstQueue.destConn.getName(),
NamedType.BOOL.toString());
//if the clock output hasn't been created yet,
//do reference mapping and add it to the map
//of output clocks
if(!inputVars.contains(clockOutVar)){
inputVars.add(clockOutVar);
addToRenaming(clockOutVar.jKindStr, clockOutVar.aadlStr);
refMap.put(clockOutVar.aadlStr, firstQueue.destConn);
layout.addElement(category, clockOutVar.aadlStr, AgreeLayout.SigType.INPUT);
List<IdExpr> clockOutIds = queueInClockMap.get(firstQueue.destConn);
if(clockOutIds == null){
clockOutIds = new ArrayList<>();
queueOutClockMap.put(firstQueue.destConn, clockOutIds);
}
clockOutIds.add(clockOutId);
}
queueInputs.add(queueInputId);
queueInputs.add(queueClockInExpr);
queueInputs.add(clockOutId);
NodeCallExpr queueCall = new NodeCallExpr(queueNode.id, queueInputs);
IdExpr queueElsId = new IdExpr(queueCountPrefix+destStr);
AgreeVarDecl queueElsVar =
new AgreeVarDecl(queueElsId.id,
queueElsId.id,
NamedType.INT.toString());
internalVars.add(queueElsVar);
List<IdExpr> countIds = queueCountMap.get(firstQueue.destConn);
if(countIds == null){
countIds = new ArrayList<>();
queueCountMap.put(firstQueue.destConn, countIds);
}
countIds.add(queueElsId);
IdExpr singleQueueCountId = new IdExpr(queueCountPrefix+jCat+firstQueue.destConn.getName());
AgreeVarDecl singleQueueCountVar =
new AgreeVarDecl(singleQueueCountId.id,
queueCountPrefix+aCat+firstQueue.destConn.getName(),
NamedType.INT.toString());
if(!inputVars.contains(singleQueueCountVar)){
inputVars.add(singleQueueCountVar);
addToRenaming(singleQueueCountVar.jKindStr, singleQueueCountVar.aadlStr);
refMap.put(singleQueueCountVar.aadlStr, firstQueue.destConn);
layout.addElement(category, singleQueueCountVar.aadlStr, AgreeLayout.SigType.INPUT);
countIds.add(singleQueueCountId);
}
//finally, call the node
List<IdExpr> queueLhs = new ArrayList<>();
queueLhs.add(queueElsId);
queueLhs.add(new IdExpr(destStr));
Equation queueEq = new Equation(queueLhs, queueCall);
connExpressions.add(queueEq);
}
}
// ************** CASE STATEMENTS **********************
public Expr getQueueCountID(String jVarPrefix, String aVarPrefix, NamedElement comp){
EventDataPort port = (EventDataPort)comp;
//a variable of the same name as this should be created by setEventPortQueues()
//in the AgreeAnnexEmitter which created "this" AgreeAnnexEmitter
AgreeVarDecl countVar = new AgreeVarDecl(queueCountPrefix+jVarPrefix,
queueCountPrefix+aVarPrefix,
NamedType.INT.toString());
IdExpr countIdExpr = new IdExpr(countVar.jKindStr);
//if we have already made the expression then don't make it again
if(inputVars.contains(countVar)){
return countIdExpr;
}
inputVars.add(countVar);
addToRenaming(countVar.jKindStr,countVar.aadlStr);
refMap.put(countVar.aadlStr, port);
layout.addElement(category, countVar.aadlStr, AgreeLayout.SigType.INPUT);
return countIdExpr;
}
public Expr getQueueRemoveID(String jVarPrefix, String aVarPrefix, NamedElement comp){
EventDataPort port = (EventDataPort)comp;
//a variable of the same name as this should be created by setEventPortQueues()
//in the AgreeAnnexEmitter which created "this" AgreeAnnexEmitter
AgreeVarDecl removeVar = new AgreeVarDecl(queueOutClockPrefix+jVarPrefix,
queueOutClockPrefix+aVarPrefix,
NamedType.BOOL.toString());
IdExpr removeIdExpr = new IdExpr(removeVar.jKindStr);
//if we have already made the expression then don't make it again
if(inputVars.contains(removeVar)){
return removeIdExpr;
}
inputVars.add(removeVar);
addToRenaming(removeVar.jKindStr,removeVar.aadlStr);
refMap.put(removeVar.aadlStr, port);
layout.addElement(category, removeVar.aadlStr, AgreeLayout.SigType.INPUT);
return removeIdExpr;
}
public Expr getQueueInsertID(String jVarPrefix, String aVarPrefix, NamedElement comp){
EventDataPort port = (EventDataPort)comp;
//a variable of the same name as this should be created by setEventPortQueues()
//in the AgreeAnnexEmitter which created "this" AgreeAnnexEmitter
AgreeVarDecl insertVar = new AgreeVarDecl(queueInClockPrefix+jVarPrefix,
queueInClockPrefix+aVarPrefix,
NamedType.BOOL.toString());
IdExpr insertIdExpr = new IdExpr(insertVar.jKindStr);
//if we have already made the expression then don't make it again
if(inputVars.contains(insertVar)){
return insertIdExpr;
}
inputVars.add(insertVar);
addToRenaming(insertVar.jKindStr,insertVar.aadlStr);
refMap.put(insertVar.aadlStr, port);
layout.addElement(category, insertVar.aadlStr, AgreeLayout.SigType.INPUT);
return insertIdExpr;
}
public Expr getClockID(NamedElement comp){
//IdExpr clockId = new IdExpr(clockIDPrefix+comp.getName());
//a variable of the same name as this should be created by setEventPortQueues()
//in the AgreeAnnexEmitter which created "this" AgreeAnnexEmitter
AgreeVarDecl clockVar = new AgreeVarDecl(clockIDPrefix+comp.getName(),
clockIDPrefix+comp.getName(),
NamedType.BOOL.toString());
IdExpr clockId = new IdExpr(clockVar.jKindStr);
//if we have already made the expression then don't make it again
if(inputVars.contains(clockVar)){
return clockId;
}
inputVars.add(clockVar);
addToRenaming(clockVar.jKindStr,clockVar.aadlStr);
refMap.put(clockVar.aadlStr, comp);
layout.addElement(category, clockVar.aadlStr, AgreeLayout.SigType.INPUT);
return clockId;
}
@Override
public Expr caseCalenStatement(CalenStatement calen){
for(NamedElement namedEl : calen.getEls()){
IdExpr clockId = new IdExpr(clockIDPrefix+namedEl.getName());
this.calendar.add(clockId);
}
return null;
}
@Override
public Expr caseSynchStatement(SynchStatement sync){
if(sync instanceof CalenStatement){
return null;
}
this.synchrony = Integer.valueOf(sync.getVal());
String simVal = sync.getSim();
if(simVal != null){
this.simultaneity = !simVal.equals("no_simult");
}
return null;
}
@Override
public Expr caseLiftStatement(LiftStatement lift){
if(ignoreLifts){
return null;
}
NestedDotID nestId = lift.getSubcomp();
Subcomponent subComp = (Subcomponent)nestId.getBase();
ComponentInstance subCompInst = curInst.findSubcomponentInstance(subComp);
ComponentImplementation subCompImpl = subComp.getComponentImplementation();
ComponentType subCompType = subCompImpl.getType();
AgreeAnnexEmitter subEmitter = new AgreeAnnexEmitter(
subCompInst, layout, category,
jKindNameTag + subComp.getName() + dotChar,
aadlNameTag + subComp.getFullName() + ".", false, true);
for (AnnexSubclause annex : AnnexUtil.getAllAnnexSubclauses(subCompImpl, AgreePackage.eINSTANCE.getAgreeContractSubclause())) {
if (annex instanceof AgreeContractSubclause) {
subEmitter.doSwitch(annex);
}
}
for (AnnexSubclause annex : AnnexUtil.getAllAnnexSubclauses(subCompType, AgreePackage.eINSTANCE.getAgreeContractSubclause())) {
if (annex instanceof AgreeContractSubclause) {
subEmitter.doSwitch(annex);
}
}
connExpressions.addAll(subEmitter.connExpressions);
guarExpressions.addAll(subEmitter.guarExpressions);
assumpExpressions.addAll(subEmitter.assumpExpressions);
constExpressions.addAll(subEmitter.constExpressions);
assertExpressions.addAll(subEmitter.assertExpressions);
eqExpressions.addAll(subEmitter.eqExpressions);
nodeDefExpressions.addAll(subEmitter.nodeDefExpressions);
propExpressions.addAll(subEmitter.propExpressions);
subEmitter.inputVars.removeAll(internalVars);
subEmitter.outputVars.removeAll(internalVars);
inputVars.removeAll(subEmitter.internalVars);
outputVars.removeAll(subEmitter.internalVars);
inputVars.addAll(subEmitter.inputVars);
outputVars.addAll(subEmitter.outputVars);
internalVars.addAll(subEmitter.internalVars);
addToRenamingAll(subEmitter.varRenaming);
refMap.putAll(subEmitter.refMap);
return null;
}
@Override
public Expr caseAgreeContractSubclause(AgreeContractSubclause contract) {
return doSwitch(contract.getContract());
}
@Override
public Expr caseAgreeContract(AgreeContract contract) {
for (SpecStatement spec : contract.getSpecs()) {
doSwitch(spec);
}
return null;
}
@Override
public Expr caseAssumeStatement(AssumeStatement state) {
Expr expr = doSwitch(state.getExpr());
assumpExpressions.add(expr);
return expr;
}
@Override
public Expr caseLemmaStatement(LemmaStatement state) {
Expr expr = doSwitch(state.getExpr());
String guarStr = state.getStr();
guarStr = guarStr.replace("\"", "");
refMap.put(guarStr, state);
IdExpr strId = new IdExpr(guarStr);
Equation eq = new Equation(strId, expr);
guarExpressions.add(eq);
return expr;
}
@Override
public Expr caseGuaranteeStatement(GuaranteeStatement state) {
Expr expr = doSwitch(state.getExpr());
String guarStr = state.getStr();
guarStr = guarStr.replace("\"", "");
refMap.put(guarStr, state);
IdExpr strId = new IdExpr(guarStr);
Equation eq = new Equation(strId, expr);
guarExpressions.add(eq);
return expr;
}
@Override
public Expr caseAssertStatement(AssertStatement state) {
Expr expr = doSwitch(state.getExpr());
assertExpressions.add(expr);
return expr;
}
@Override
public Expr casePropertyStatement(PropertyStatement state) {
Expr expr = doSwitch(state.getExpr());
AgreeVarDecl varDecl = new AgreeVarDecl();
varDecl.jKindStr = jKindNameTag + state.getName();
varDecl.aadlStr = aadlNameTag + state.getName();
varDecl.type = "bool";
layout.addElement(category, varDecl.aadlStr, AgreeLayout.SigType.OUTPUT);
addToRenaming(varDecl.jKindStr, varDecl.aadlStr);
refMap.put(varDecl.aadlStr, state);
internalVars.add(varDecl);
IdExpr id = new IdExpr(varDecl.jKindStr);
Equation eq = new Equation(id, expr);
propExpressions.add(eq);
return expr;
}
@Override
public Expr caseEqStatement(EqStatement state) {
Expr expr = null;
if(state.getExpr() != null){
//this is an explicitly defined variable
expr = doSwitch(state.getExpr());
}
List<IdExpr> varIds = new ArrayList<IdExpr>();
for (Arg arg : state.getLhs()) {
String baseName = arg.getName();
AgreeVarDecl varDecl = new AgreeVarDecl();
varDecl.jKindStr = jKindNameTag + baseName;
IdExpr idExpr = new IdExpr(varDecl.jKindStr);
varIds.add(idExpr);
varDecl.aadlStr = aadlNameTag + baseName;
varDecl.type = arg.getType().getString();
layout.addElement(category, varDecl.aadlStr, AgreeLayout.SigType.OUTPUT);
addToRenaming(varDecl.jKindStr, varDecl.aadlStr);
refMap.put(varDecl.aadlStr, state);
if(expr != null){
internalVars.add(varDecl);
}else{
//the variable is implicitly defined
//inputVars.add(varDecl);
outputVars.add(varDecl);
}
}
if(expr != null){
Equation eq = new Equation(varIds, expr);
eqExpressions.add(eq);
}
return null;
}
@Override
public Expr caseBinaryExpr(com.rockwellcollins.atc.agree.agree.BinaryExpr expr) {
Expr leftExpr = doSwitch(expr.getLeft());
Expr rightExpr = doSwitch(expr.getRight());
String op = expr.getOp();
BinaryOp binOp = null;
switch (op) {
case "+":
binOp = BinaryOp.PLUS;
break;
case "-":
binOp = BinaryOp.MINUS;
break;
case "*":
binOp = BinaryOp.MULTIPLY;
break;
case "/":
binOp = BinaryOp.DIVIDE;
break;
case "mod":
binOp = BinaryOp.MODULUS;
break;
case "div":
binOp = BinaryOp.INT_DIVIDE;
break;
case "<=>":
case "=":
binOp = BinaryOp.EQUAL;
break;
case "!=":
case "<>":
binOp = BinaryOp.NOTEQUAL;
break;
case ">":
binOp = BinaryOp.GREATER;
break;
case "<":
binOp = BinaryOp.LESS;
break;
case ">=":
binOp = BinaryOp.GREATEREQUAL;
break;
case "<=":
binOp = BinaryOp.LESSEQUAL;
break;
case "or":
binOp = BinaryOp.OR;
break;
case "and":
binOp = BinaryOp.AND;
break;
case "xor":
binOp = BinaryOp.XOR;
break;
case "=>":
binOp = BinaryOp.IMPLIES;
break;
case "->":
binOp = BinaryOp.ARROW;
break;
}
assert (binOp != null);
BinaryExpr binExpr = new BinaryExpr(leftExpr, binOp, rightExpr);
return binExpr;
}
@Override
public Expr caseBoolLitExpr(BoolLitExpr expr) {
return new BoolExpr(expr.getVal().getValue());
}
@Override
public Expr caseFnCallExpr(FnCallExpr expr) {
NestedDotID dotId = expr.getFn();
NamedElement namedEl = AgreeEmitterUtilities.getFinalNestId(dotId);
String fnName = jKindNameTag + namedEl.getName();
boolean found = false;
for(Node node : nodeDefExpressions){
if(node.id.equals(fnName)){
found = true;
break;
}
}
if(!found){
NestedDotID fn = expr.getFn();
doSwitch(AgreeEmitterUtilities.getFinalNestId(fn));
}
List<Expr> argResults = new ArrayList<Expr>();
for (com.rockwellcollins.atc.agree.agree.Expr argExpr : expr.getArgs()) {
argResults.add(doSwitch(argExpr));
}
NodeCallExpr nodeCall = new NodeCallExpr(fnName, argResults);
return nodeCall;
}
// TODO: ordering nodes/functions in dependency order
@Override
public Expr caseNodeDefExpr(NodeDefExpr expr) {
// System.out.println("Visiting caseNodeDefExpr");
String nodeName = jKindNameTag + expr.getName();
for(Node node : nodeDefExpressions){
if(node.id.equals(nodeName)){
return null;
}
}
List<VarDecl> inputs = AgreeEmitterUtilities.argsToVarDeclList(jKindNameTag, expr.getArgs());
List<VarDecl> outputs = AgreeEmitterUtilities.argsToVarDeclList(jKindNameTag, expr.getRets());
NodeBodyExpr body = expr.getNodeBody();
List<VarDecl> internals = AgreeEmitterUtilities.argsToVarDeclList(jKindNameTag, body.getLocs());
List<Equation> eqs = new ArrayList<Equation>();
List<String> props = new ArrayList<String>();
String lemmaName = "nodeLemma";
int lemmaIndex = 0;
for (NodeStmt stmt : body.getStmts()) {
if (stmt instanceof NodeLemma) {
NodeLemma nodeLemma = (NodeLemma) stmt;
//String propName = ((NodeLemma) stmt).getStr();
String propName = lemmaName + lemmaIndex++;
props.add(propName);
IdExpr eqId = new IdExpr(propName);
Expr eqExpr = doSwitch(nodeLemma.getExpr());
Equation eq = new Equation(eqId, eqExpr);
eqs.add(eq);
VarDecl lemmaVar = new VarDecl(propName, NamedType.BOOL);
internals.add(lemmaVar);
} else if (stmt instanceof NodeEq) {
eqs.add(nodeEqToEq((NodeEq) stmt));
}
}
nodeDefExpressions.add(new Node(nodeName, inputs, outputs, internals, eqs, props));
return null;
}
//helper method for the above method
private Equation nodeEqToEq(NodeEq nodeEq) {
Expr expr = doSwitch(nodeEq.getExpr());
List<IdExpr> ids = new ArrayList<IdExpr>();
for (Arg arg : nodeEq.getLhs()) {
ids.add(new IdExpr(jKindNameTag + arg.getName()));
}
Equation eq = new Equation(ids, expr);
return eq;
}
@Override
public Expr caseFnDefExpr(FnDefExpr expr) {
String nodeName = jKindNameTag + expr.getName();
for(Node node : nodeDefExpressions){
if(node.id.equals(nodeName)){
return null;
}
}
List<VarDecl> inputs = AgreeEmitterUtilities.argsToVarDeclList(jKindNameTag, expr.getArgs());
Expr bodyExpr = doSwitch(expr.getExpr());
Type outType = new NamedType(expr.getType().getString());
VarDecl outVar = new VarDecl("_outvar", outType);
List<VarDecl> outputs = Collections.singletonList(outVar);
Equation eq = new Equation(new IdExpr("_outvar"), bodyExpr);
List<Equation> eqs = Collections.singletonList(eq);
Node node = new Node(nodeName, inputs, outputs, Collections.<VarDecl> emptyList(), eqs);
nodeDefExpressions.add(node);
return null;
}
// TODO: place node definition here.
@Override
public Expr caseGetPropertyExpr(GetPropertyExpr expr) {
NamedElement propName = namedElFromId(expr.getProp());
NamedElement compName = namedElFromId(expr.getComponent());
Property prop = (Property) propName;
PropertyExpression propVal = AgreeEmitterUtilities.getPropExpression(compName, prop);
if(propVal == null){
throw new AgreeException("Could not locate property value '"+
prop.getFullName()+"' in component '"+compName.getName()+"'. Is it possible "
+ "that a 'this' statement is used in a context in which it wasn't supposed to?");
}
Expr res = null;
if (propVal != null) {
if (propVal instanceof StringLiteral) {
// StringLiteral value = (StringLiteral) propVal;
// nodeStr += value.getValue() + ")";
throw new AgreeException("Property value for '" + prop.getFullName()
+ "' cannot be of string type");
} else if (propVal instanceof NamedValue) {
// NamedValue namedVal = (NamedValue) propVal;
// AbstractNamedValue absVal = namedVal.getNamedValue();
// assert (absVal instanceof EnumerationLiteral);
// EnumerationLiteral enVal = (EnumerationLiteral) absVal;
throw new AgreeException("Property value for '" + prop.getFullName()
+ "' cannot be of enumeration type");
} else if (propVal instanceof BooleanLiteral) {
BooleanLiteral value = (BooleanLiteral) propVal;
res = new BoolExpr(value.getValue());
} else if (propVal instanceof IntegerLiteral) {
IntegerLiteral value = (IntegerLiteral) propVal;
res = new IntExpr(BigInteger.valueOf((long) value.getScaledValue()));
} else {
assert (propVal instanceof RealLiteral);
RealLiteral value = (RealLiteral) propVal;
res = new RealExpr(BigDecimal.valueOf(value.getValue()));
}
}
assert (res != null);
return res;
}
//helper method for above
private NamedElement namedElFromId(EObject obj) {
if (obj instanceof NestedDotID) {
return AgreeEmitterUtilities.getFinalNestId((NestedDotID) obj);
} else if (obj instanceof com.rockwellcollins.atc.agree.agree.IdExpr) {
return ((com.rockwellcollins.atc.agree.agree.IdExpr) obj).getId();
} else {
assert (obj instanceof ThisExpr);
ThisExpr thisExpr = (ThisExpr)obj;
ComponentInstance compInst = curInst;
NestedDotID nestId = thisExpr.getSubThis();
while(nestId != null){
NamedElement base = nestId.getBase();
if(base instanceof Subcomponent){
compInst = compInst.findSubcomponentInstance((Subcomponent)base);
nestId = nestId.getSub();
}else{
assert(base instanceof FeatureGroup);
FeatureInstance featInst = compInst.findFeatureInstance((Feature)base);
while(nestId.getSub() != null){
nestId = nestId.getSub();
assert(nestId.getBase() instanceof Feature);
Feature subFeat = (Feature)nestId.getBase();
FeatureInstance eqFeatInst = null;
for(FeatureInstance subFeatInst : featInst.getFeatureInstances()){
if(subFeatInst.getFeature().equals(subFeat)){
eqFeatInst = subFeatInst;
break;
}
}
featInst = eqFeatInst;
}
return featInst;
}
}
return compInst;
}
}
@Override
public Expr caseIdExpr(com.rockwellcollins.atc.agree.agree.IdExpr expr) {
//I'm pretty sure this is dead code now
assert(false);
// just make an expression of the NamedElement
return new IdExpr(jKindNameTag + expr.getId().getName());
}
@Override
public Expr caseThisExpr(ThisExpr expr) {
assert (false);
return null;
// return new NamedElementExpr(curComp);
}
@Override
public Expr caseIfThenElseExpr(com.rockwellcollins.atc.agree.agree.IfThenElseExpr expr) {
Expr condExpr = doSwitch(expr.getA());
Expr thenExpr = doSwitch(expr.getB());
Expr elseExpr = doSwitch(expr.getC());
Expr result = new IfThenElseExpr(condExpr, thenExpr, elseExpr);
return result;
}
@Override
public Expr caseIntLitExpr(IntLitExpr expr) {
return new IntExpr(BigInteger.valueOf(Integer.parseInt(expr.getVal())));
}
@Override
public Expr caseNestedDotID(NestedDotID Id) {
NestedDotID orgId = Id;
String jKindVar = "";
String aadlVar = "";
while (Id.getSub() != null) {
jKindVar += Id.getBase().getName() + dotChar;
aadlVar += Id.getBase().getName() + ".";
Id = Id.getSub();
}
NamedElement namedEl = Id.getBase();
String tag = Id.getTag();
if(tag != null){
String jVarPrefix = this.jKindNameTag + jKindVar + namedEl.getName();
String aVarPrefix = this.aadlNameTag + aadlVar + namedEl.getName();
switch(tag){
case "CLK":
return getClockID(namedEl);
case "COUNT":
return getQueueCountID(jVarPrefix, aVarPrefix, namedEl);
case "INSERT":
return getQueueInsertID(jVarPrefix, aVarPrefix, namedEl);
case "REMOVE":
return getQueueRemoveID(jVarPrefix, aVarPrefix, namedEl);
default:
throw new AgreeException("use of uknown tag: '"+tag+"' in expression: '"+aadlVar+tag+"'");
}
}
//special case for constants
if(namedEl instanceof ConstStatement){
return doSwitch(((ConstStatement)namedEl).getExpr());
}
String baseName = namedEl.getName();
jKindVar = jKindNameTag + jKindVar + Id.getBase().getName();
aadlVar = aadlNameTag + aadlVar + Id.getBase().getName();
IdExpr result = new IdExpr(jKindVar);
// hack for making sure all inputs have been created
if (namedEl instanceof DataSubcomponent || namedEl instanceof DataPort) {
AgreeVarDecl tempStrType = new AgreeVarDecl();
tempStrType.jKindStr = jKindVar;
if (!inputVars.contains(tempStrType) && !internalVars.contains(tempStrType) && !outputVars.contains(tempStrType)) {
assert(false); //this code should now be unreachable
log.logWarning("In component '"
+ orgId.getBase().getContainingClassifier().getFullName() + "', Port '"
+ jKindVar + "' is not connected to anything. Considering it to be"
+ " an unconstrained primary input.");
// this code just creates a new PI
if(namedEl instanceof DataSubcomponent){
tempStrType = AgreeEmitterUtilities.dataTypeToVarType((DataSubcomponent) namedEl);
}else{
DataType dataType = (DataType) ((DataPort)namedEl).getDataFeatureClassifier();
String typeStr = AgreeEmitterUtilities.dataTypeToVarType(dataType);
tempStrType = new AgreeVarDecl();
tempStrType.type = typeStr;
}
tempStrType.jKindStr = jKindVar;
tempStrType.aadlStr = aadlVar;
layout.addElement(category, aadlVar, AgreeLayout.SigType.INPUT);
addToRenaming(jKindVar, aadlVar);
refMap.put(aadlVar, Id);
inputVars.add(tempStrType);
//have to keep track of outputs for condacts
boolean reverseDirection = false;
if(orgId.getBase() instanceof FeatureGroup){
FeatureGroup featGroup = (FeatureGroup)orgId.getBase();
reverseDirection = featGroup.isInverse();
}
if(namedEl instanceof DataSubcomponent){
NestedDotID tempId = orgId;
while(!(tempId.getBase() instanceof DirectedFeature)){
tempId = orgId.getSub();
}
DirectionType direction = ((DirectedFeature)tempId.getBase()).getDirection();
if((direction == DirectionType.OUT && !reverseDirection)
|| (direction == DirectionType.IN && reverseDirection)){
outputVars.add(tempStrType);
}
}else{
DirectionType direction = ((DirectedFeature)namedEl).getDirection();
if((direction == DirectionType.OUT && !reverseDirection)
|| (direction == DirectionType.IN && reverseDirection)){
outputVars.add(tempStrType);
}
}
}
}
return result;
}
@Override
public Expr casePreExpr(PreExpr expr) {
Expr res = doSwitch(expr.getExpr());
return new UnaryExpr(UnaryOp.PRE, res);
}
@Override
public Expr casePrevExpr(PrevExpr expr) {
Expr delayExpr = doSwitch(expr.getDelay());
Expr initExpr = doSwitch(expr.getInit());
Expr preExpr = new UnaryExpr(UnaryOp.PRE, delayExpr);
Expr res = new BinaryExpr(initExpr, BinaryOp.ARROW, preExpr);
return res;
}
@Override
public Expr caseRealLitExpr(RealLitExpr expr) {
return new RealExpr(BigDecimal.valueOf(Double.parseDouble(expr.getVal())));
}
@Override
public Expr caseUnaryExpr(com.rockwellcollins.atc.agree.agree.UnaryExpr expr) {
Expr subExpr = doSwitch(expr.getExpr());
Expr res = null;
switch (expr.getOp()) {
case "-":
res = new UnaryExpr(UnaryOp.NEGATIVE, subExpr);
break;
case "not":
res = new UnaryExpr(UnaryOp.NOT, subExpr);
break;
default:
assert (false);
}
return res;
}
//********* end case statements ************//
//********* begin lustre generation *******//
// fills the connExpressions lists with expressions
// that equate variables that are connected to one another
private void setConnExprs(ComponentImplementation compImpl, String initJStr, String initAStr) {
// use for checking delay
Property commTimingProp = EMFIndexRetrieval.getPropertyDefinitionInWorkspace(
OsateResourceUtil.getResourceSet(), "Communication_Properties::Timing");
for (Connection conn : compImpl.getAllConnections()) {
ConnectedElement absConnDest = conn.getDestination();
ConnectedElement absConnSour = conn.getSource();
boolean delayed = false;
try{
EnumerationLiteral lit = PropertyUtils.getEnumLiteral(conn, commTimingProp);
delayed = lit.getName().equals("delayed");
}catch(PropertyDoesNotApplyToHolderException e){
delayed = false;
}
Context destContext = absConnDest.getContext();
Context sourContext = absConnSour.getContext();
//only make connections to things that have annexs
if(destContext != null && destContext instanceof Subcomponent){
if(!AgreeEmitterUtilities.containsAgreeAnnex((Subcomponent)destContext)){
continue;
}
}
if(sourContext != null && sourContext instanceof Subcomponent){
if(!AgreeEmitterUtilities.containsAgreeAnnex((Subcomponent)sourContext)){
continue;
}
}
makeConnectionExpressions(absConnSour, absConnDest);
}
}
private void makeConnectionExpressions(
ConnectedElement absConnSour, ConnectedElement absConnDest) {
ConnectionEnd destConn = absConnDest.getConnectionEnd();
ConnectionEnd sourConn = absConnSour.getConnectionEnd();
//we currently don't handle data accesses or buss accesses
if(destConn instanceof DataAccess
|| sourConn instanceof DataAccess
|| destConn instanceof BusAccess
|| sourConn instanceof BusAccess){
return;
}
Context destContext = absConnDest.getContext();
Context sourContext = absConnSour.getContext();
// String sourName = (sourContext == null) ? category : sourContext.getName();
// String destName = (destContext == null) ? category : destContext.getName();
ComponentInstance sourInst = null;
FeatureInstance sourBaseFeatInst = null;
if(sourContext == null){
sourInst = curInst;
}else if(sourContext instanceof Subcomponent){
sourInst = curInst.findSubcomponentInstance((Subcomponent)sourContext);
}else{
sourBaseFeatInst = curInst.findFeatureInstance((FeatureGroup)sourContext);
}
ComponentInstance destInst = null;
FeatureInstance destBaseFeatInst = null;
if(destContext == null){
destInst = curInst;
}else if(destContext instanceof Subcomponent){
destInst = curInst.findSubcomponentInstance((Subcomponent)destContext);
}else{
destBaseFeatInst = curInst.findFeatureInstance((FeatureGroup)destContext);
}
//get the corresponding feature instances
FeatureInstance sourFeatInst = null;
FeatureInstance destFeatInst = null;
List<FeatureInstance> sourFeatInsts = (sourInst == null) ?
sourBaseFeatInst.getFeatureInstances() :
sourInst.getFeatureInstances();
List<FeatureInstance> destFeatInsts = (destInst == null) ?
destBaseFeatInst.getFeatureInstances() :
destInst.getFeatureInstances();
for(FeatureInstance featInst : sourFeatInsts){
if(featInst.getFeature() == sourConn){
sourFeatInst = featInst;
break;
}
}
for(FeatureInstance featInst : destFeatInsts){
if(featInst.getFeature() == destConn){
destFeatInst = featInst;
break;
}
}
//grabs the subnames for all the connections
List<AgreeFeature> destConns = featInstToAgreeFeatMap.get(destFeatInst);
List<AgreeFeature> sourConns = featInstToAgreeFeatMap.get(sourFeatInst);
String lhsLustreName = null;
String rhsLustreName = null;
String lhsAadlName = null;
String rhsAadlName = null;
int i;
assert(destConns.size() == sourConns.size());
for(i = 0; i < destConns.size(); i++){
AgreeFeature agreeDestConn = destConns.get(i);
AgreeFeature agreeSourConn = sourConns.get(i);
//assert(agreeDestConn.lustreString == agreeSourConn.lustreString);
//assert(agreeDestConn.aadlString == agreeSourConn.aadlString);
assert(agreeDestConn.varType == agreeSourConn.varType);
- if(sourContext == null){
+ if(sourContext == null || sourContext instanceof FeatureGroup){
switch(agreeDestConn.direction){
case IN:
lhsLustreName = agreeDestConn.lustreString;
lhsAadlName = agreeDestConn.aadlString;
rhsLustreName = agreeSourConn.lustreString;
rhsAadlName = agreeSourConn.aadlString;
break;
case OUT:
lhsLustreName = agreeSourConn.lustreString;
lhsAadlName = agreeSourConn.aadlString;
rhsLustreName = agreeDestConn.lustreString;
rhsAadlName = agreeDestConn.aadlString;
}
- }else if(destContext == null){
+ }else if(destContext == null || destContext instanceof FeatureGroup){
switch(agreeDestConn.direction){
case IN:
lhsLustreName = agreeSourConn.lustreString;
lhsAadlName = agreeSourConn.aadlString;
rhsLustreName = agreeDestConn.lustreString;
rhsAadlName = agreeDestConn.aadlString;
break;
case OUT:
lhsLustreName = agreeDestConn.lustreString;
lhsAadlName = agreeDestConn.aadlString;
rhsLustreName = agreeSourConn.lustreString;
rhsAadlName = agreeSourConn.aadlString;
}
}else{
switch(agreeDestConn.direction){
case IN:
lhsLustreName = agreeDestConn.lustreString;
lhsAadlName = agreeDestConn.aadlString;
rhsLustreName = agreeSourConn.lustreString;
rhsAadlName = agreeSourConn.aadlString;
break;
case OUT:
lhsLustreName = agreeSourConn.lustreString;
lhsAadlName = agreeSourConn.aadlString;
rhsLustreName = agreeDestConn.lustreString;
rhsAadlName = agreeDestConn.aadlString;
}
}
if(agreeDestConn.connType == AgreeFeature.ConnType.QUEUE){
String sourInstName;
if(sourInst == null){
sourInstName = sourBaseFeatInst.getName();
}else if(sourInst == curInst){
sourInstName = null;
}else{
sourInstName = sourInst.getName();
}
String destInstName;
if(destInst == null){
destInstName = destBaseFeatInst.getName();
}else if(destInst == curInst){
destInstName = null;
}else{
destInstName = destInst.getName();
}
AgreeQueueElement agreeQueueElem = new AgreeQueueElement(rhsLustreName,
rhsAadlName,
lhsLustreName,
lhsAadlName,
new NamedType(agreeDestConn.varType),
(EventDataPort)agreeSourConn.feature,
(EventDataPort)agreeDestConn.feature,
sourInstName,
destInstName,
agreeDestConn.queueSize);
if(queueMap.containsKey(lhsLustreName)){
List<AgreeQueueElement> queues = queueMap.get(lhsLustreName);
queues.add(agreeQueueElem);
}else{
List<AgreeQueueElement> queues = new ArrayList<AgreeQueueElement>();
queues.add(agreeQueueElem);
queueMap.put(lhsLustreName, queues);
}
}else{
Equation connEq = new Equation(new IdExpr(lhsLustreName), new IdExpr(rhsLustreName));
addConnection(connEq);;
}
//add left hand side expressions as internal variables
AgreeVarDecl agreeVar = new AgreeVarDecl(lhsLustreName, lhsAadlName, agreeSourConn.varType);
internalVars.add(agreeVar);
}
}
private List<AgreeFeature> recordFeatures_Helper(String jPrefix, String aPrefix, FeatureInstance featInst){
List<AgreeFeature> agreeConns = new ArrayList<>();
long queueSize = -1;
if(featInst.getCategory() == FeatureCategory.FEATURE_GROUP){
for(FeatureInstance subFeatInst : featInst.getFeatureInstances()){
agreeConns.addAll(recordFeatures_Helper(featInst.getName()+dotChar,
featInst.getName()+".", subFeatInst));
}
if(((FeatureGroup)featInst.getFeature()).isInverse()){
for(AgreeFeature agreeConn : agreeConns){
switch(agreeConn.direction){
case IN:
agreeConn.direction = Direction.OUT;
break;
case OUT:
agreeConn.direction = Direction.IN;
break;
}
}
}
}else if(featInst.getCategory() == FeatureCategory.DATA_PORT
|| featInst.getCategory() == FeatureCategory.EVENT_DATA_PORT){
DataSubcomponentType dataClass;
if(featInst.getFeature() instanceof DataPort){
DataPort dataPort = (DataPort)featInst.getFeature();
dataClass = dataPort.getDataFeatureClassifier();
}else{
EventDataPort eventDataPort = (EventDataPort)featInst.getFeature();
dataClass = eventDataPort.getDataFeatureClassifier();
}
Set<AgreeVarDecl> tempSet = new HashSet<>();
Direction direction = AgreeFeature.Direction.IN;
if(featInst.getDirection() == DirectionType.IN){
direction = AgreeFeature.Direction.IN;
}else if (featInst.getDirection() == DirectionType.OUT){
direction = AgreeFeature.Direction.OUT;
}else{
//we don't handle in-out data ports
return agreeConns;
//throw new AgreeException("unable to handle in-out direction type on port '"+featInst.getName()+"'");
}
if(dataClass instanceof DataType){
AgreeVarDecl agreeVar =
new AgreeVarDecl("",
"", AgreeEmitterUtilities.dataTypeToVarType((DataType)dataClass));
if(agreeVar.type != null){
tempSet.add(agreeVar);
}
}else{
getAllDataNames((DataImplementation)dataClass, tempSet);
}
ConnType connType;
if(featInst.getCategory() == FeatureCategory.EVENT_DATA_PORT){
connType = AgreeFeature.ConnType.QUEUE;
Property queueSizeProp = EMFIndexRetrieval.getPropertyDefinitionInWorkspace(
OsateResourceUtil.getResourceSet(), "Communication_Properties::Queue_Size");
try{
queueSize = PropertyUtils.getIntegerValue(featInst, queueSizeProp);
}catch(PropertyDoesNotApplyToHolderException e){}
}else{
connType = AgreeFeature.ConnType.IMMEDIATE;
}
for(AgreeVarDecl var : tempSet){
AgreeFeature agreeConn = new AgreeFeature();
agreeConn.feature = featInst.getFeature();
agreeConn.varType = var.type;
assert(var.type != null);
agreeConn.lustreString = (var.jKindStr == "") ? featInst.getName() : featInst.getName() + dotChar + var.jKindStr;
agreeConn.aadlString = (var.aadlStr == "") ? featInst.getName() : featInst.getName() + "." + var.aadlStr;
agreeConn.connType = connType;
agreeConn.direction = direction;
agreeConn.queueSize = queueSize;
agreeConns.add(agreeConn);
}
}else{
//TODO: handle other types of ports
//throw new AgreeException("unsure how to handled port '"+featInst.getName()+"'");
}
for(AgreeFeature agreeConn : agreeConns){
if(agreeConn.lustreString == ""){
agreeConn.lustreString = jPrefix;
}else{
agreeConn.lustreString = jPrefix + agreeConn.lustreString;
}
if(agreeConn.aadlString == ""){
agreeConn.aadlString = aPrefix;
}else{
agreeConn.aadlString = aPrefix + agreeConn.aadlString;
}
}
featInstToAgreeFeatMap.put(featInst, agreeConns);
return agreeConns;
}
private void getAllDataNames(DataImplementation dataImpl, Set<AgreeVarDecl> subStrTypes) {
for (Subcomponent sub : dataImpl.getAllSubcomponents()) {
if (sub instanceof DataSubcomponent) {
Set<AgreeVarDecl> newStrTypes = new HashSet<AgreeVarDecl>();
ComponentClassifier subImpl = sub.getAllClassifier();
if (subImpl instanceof DataImplementation) {
getAllDataNames((DataImplementation) subImpl, newStrTypes);
for (AgreeVarDecl strType : newStrTypes) {
AgreeVarDecl newStrType = new AgreeVarDecl();
newStrType.jKindStr = sub.getName() + dotChar + strType.jKindStr;
newStrType.aadlStr = sub.getName() + "." + strType.aadlStr;
newStrType.type = strType.type;
subStrTypes.add(newStrType);
}
} else {
AgreeVarDecl newStrType = AgreeEmitterUtilities.dataTypeToVarType((DataSubcomponent) sub);
if (newStrType != null && newStrType.type != null) {
subStrTypes.add(newStrType);
}
}
}
}
}
public AgreeNode getComponentNode(){
if(agreeNode != null){
return agreeNode;
}
List<Equation> eqs = new ArrayList<Equation>();
List<VarDecl> inputs = new ArrayList<VarDecl>();
List<VarDecl> outputs = new ArrayList<VarDecl>();
List<Node> nodeSet = new ArrayList<Node>();
nodeSet.addAll(this.nodeDefExpressions);
eqs.addAll(this.constExpressions);
eqs.addAll(this.eqExpressions);
eqs.addAll(this.propExpressions);
//convert the variables
for(AgreeVarDecl aVar : inputVars){
inputs.add(new VarDecl(aVar.jKindStr, new NamedType(aVar.type)));
}
for(AgreeVarDecl aVar : outputVars){
inputs.add(new VarDecl(aVar.jKindStr, new NamedType(aVar.type)));
}
for(AgreeVarDecl aVar : internalVars){
outputs.add(new VarDecl(aVar.jKindStr, new NamedType(aVar.type)));
}
//create equations for assumptions, assertions, and guarantees
List<Expr> guarVars = new ArrayList<>();
int i = 0;
for(Equation eq : this.guarExpressions){
IdExpr id = new IdExpr("__GUAR_"+category+"_"+i++);
VarDecl guarVar = new VarDecl(id.id, NamedType.BOOL);
outputs.add(guarVar);
guarVars.add(id);
eqs.add(new Equation(id, eq.expr));
}
List<Expr> asserVars = new ArrayList<>();
i = 0;
for(Expr expr : this.assertExpressions){
IdExpr id = new IdExpr("__ASSER_"+category+"_"+i++);
VarDecl asserVar = new VarDecl(id.id, NamedType.BOOL);
outputs.add(asserVar);
asserVars.add(id);
eqs.add(new Equation(id, expr));
}
List<Expr> assumVars = new ArrayList<>();
i = 0;
for(Expr expr : this.assumpExpressions){
IdExpr id = new IdExpr("__ASSUM_"+category+"_"+i++);
VarDecl assumVar = new VarDecl(id.id, NamedType.BOOL);
outputs.add(assumVar);
assumVars.add(id);
eqs.add(new Equation(id, expr));
}
Node node = new Node("__NODE_"+this.category, inputs, outputs, Collections.EMPTY_LIST, eqs);
VarDecl clockVar = new VarDecl(clockIDPrefix+this.curComp.getName(), NamedType.BOOL);
List<Node> agreeNodes = new ArrayList<>(this.nodeDefExpressions);
agreeNodes.add(node);
agreeNode = new AgreeNode(inputs, outputs, assumVars,
asserVars, guarVars, agreeNodes, node, clockVar);
return agreeNode;
}
public List<Node> getLustreWithCondacts(List<AgreeAnnexEmitter> subEmitters){
// first print out the functions which will be
// other nodes
assumProps = new ArrayList<String>();
consistProps = new ArrayList<String>();
guarProps = new ArrayList<String>();
// start constructing the top level node
List<Equation> eqs = new ArrayList<Equation>();
List<VarDecl> inputs = new ArrayList<VarDecl>();
List<Expr> clocks = new ArrayList<>();
List<VarDecl> outputs = new ArrayList<VarDecl>();
List<VarDecl> internals = new ArrayList<VarDecl>();
List<String> properties = new ArrayList<String>();
List<Node> nodeSet = new ArrayList<Node>();
nodeSet.addAll(this.nodeDefExpressions);
eqs.addAll(this.constExpressions);
eqs.addAll(this.eqExpressions);
eqs.addAll(this.propExpressions);
eqs.addAll(this.connExpressions);
Set<AgreeVarDecl> agreeInputVars = new HashSet<>();
Set<AgreeVarDecl> agreeInternalVars = new HashSet<>();
agreeInputVars.addAll(this.inputVars);
agreeInputVars.addAll(this.outputVars);
agreeInternalVars.addAll(this.internalVars);
addSubEmitterVars(subEmitters, eqs, inputs, clocks, nodeSet,
agreeInputVars, agreeInternalVars);
//warn about combinational cycles
AgreeEmitterUtilities.logCycleWarning(this, eqs, false);
agreeInputVars.removeAll(agreeInternalVars);
//convert the variables
for(AgreeVarDecl aVar : agreeInputVars){
inputs.add(new VarDecl(aVar.jKindStr, new NamedType(aVar.type)));
}
for(AgreeVarDecl aVar : agreeInternalVars){
internals.add(new VarDecl(aVar.jKindStr, new NamedType(aVar.type)));
}
IdExpr totalCompHistId = new IdExpr("_TOTAL_COMP_HIST");
IdExpr sysAssumpHistId = new IdExpr("_SYSTEM_ASSUMP_HIST");
internals.add(new VarDecl(totalCompHistId.id, new NamedType("bool")));
internals.add(new VarDecl(sysAssumpHistId.id, new NamedType("bool")));
// total component history
Expr totalCompHist = new BoolExpr(true);
for(AgreeAnnexEmitter subEmitter : subEmitters){
totalCompHist = new BinaryExpr(totalCompHist, BinaryOp.AND, AgreeEmitterUtilities.getLustreContract(subEmitter));
}
eqs.add(AgreeEmitterUtilities.getLustreHistory(totalCompHist, totalCompHistId));
// system assumptions
Expr sysAssumpHist = AgreeEmitterUtilities.getLustreAssumptionsAndAssertions(this);
eqs.add(AgreeEmitterUtilities.getLustreHistory(sysAssumpHist, sysAssumpHistId));
//make the closure map for proving assumptions
Map<Subcomponent, Set<Subcomponent>> closureMap = new HashMap<>();
for(AgreeAnnexEmitter subEmitter : subEmitters){
Set<Subcomponent> outputClosure = new HashSet<Subcomponent>();
outputClosure.add(subEmitter.curComp);
ComponentImplementation compImpl = (ComponentImplementation) curInst.getComponentClassifier();
AgreeEmitterUtilities.getOutputClosure(compImpl.getAllConnections(), outputClosure);
closureMap.put(subEmitter.curComp, outputClosure);
}
//make a counter for checking finite consistency
IdExpr countId = addConsistencyConstraints(eqs, internals);
//get the equations that guarantee that every clock has ticked atleast once
List<Equation> tickEqs = AgreeCalendarUtils.getAllClksHaveTicked("__ALL_TICKED", "__CLK_TICKED", clocks);
//add all the new clock tick variables to the internal variables list
for(Equation eq : tickEqs){
internals.add(new VarDecl(eq.lhs.get(0).id, NamedType.BOOL));
}
eqs.addAll(tickEqs);
IdExpr allClksTickedExpr = tickEqs.get(tickEqs.size()-1).lhs.get(0);
// get the individual history variables and create assumption properties
addSubcomponentAssumptions(subEmitters, eqs, internals, properties,
totalCompHist, sysAssumpHistId, allClksTickedExpr, closureMap, countId);
// create individual properties for guarantees
int i = 0;
for (Equation guar : guarExpressions) {
String guarName = guar.lhs.get(0).id;
IdExpr sysGuaranteesId = new IdExpr(sysGuarTag + i);
internals.add(new VarDecl(sysGuaranteesId.id, new NamedType("bool")));
Expr totalSysGuarExpr = new BinaryExpr(sysAssumpHistId, BinaryOp.AND, totalCompHistId);
totalSysGuarExpr = new BinaryExpr(totalSysGuarExpr, BinaryOp.AND, allClksTickedExpr);
totalSysGuarExpr = new BinaryExpr(totalSysGuarExpr, BinaryOp.IMPLIES, guar.expr);
Equation finalGuar = new Equation(sysGuaranteesId, totalSysGuarExpr);
eqs.add(finalGuar);
properties.add(sysGuaranteesId.id);
guarProps.add(sysGuaranteesId.id);
addToRenaming(sysGuaranteesId.id, guarName);
layout.addElement(category, "Component Guarantee " + i++, AgreeLayout.SigType.OUTPUT);
}
//check for contradiction in total component history
addTotalCompHistoryConsist(eqs, internals, properties, totalCompHistId,
countId);
//create the assertions for the clocks
List<Expr> assertions = getClockAssertions(clocks, nodeSet);
//assert equivalence between queue clocks and such
Expr queueClockVarEquivAssertion = getQueueClockCountVarEquivAssertion();
assertions.add(queueClockVarEquivAssertion);
//assert that inserts and removes don't take place while a component isn't being clocked
Expr queueInsertRemoveAtomicAssertion = getQueueInsertRemoveAtomicAssertion(subEmitters);
assertions.add(queueInsertRemoveAtomicAssertion);
Node topNode = new Node("_MAIN", inputs, outputs, internals, eqs, properties, assertions);
nodeSet.add(topNode);
return nodeSet;
}
private List<Expr> getClockAssertions(List<Expr> clocks, List<Node> nodeSet) {
if(clocks.size() == 0){
//just return a blank list if there are no clocks
return new ArrayList<>();
}
Expr clockAssertion;
if(this.synchrony > 0){
Node dfaNode = AgreeCalendarUtils.getDFANode("__dfa_node_"+this.category, this.synchrony);
Node calNode = AgreeCalendarUtils.getCalendarNode("__calendar_node_"+this.category, clocks.size());
nodeSet.add(dfaNode);
nodeSet.add(calNode);
clockAssertion = new NodeCallExpr(calNode.id, clocks);
//don't let multiple clocks tick together
if(!this.simultaneity){
Expr onlyOneTick = AgreeCalendarUtils.getSingleTick(clocks);
clockAssertion = new BinaryExpr(clockAssertion, BinaryOp.AND, onlyOneTick);
}
}else if(this.calendar.size() > 0){
Node calNode = AgreeCalendarUtils.getExplicitCalendarNode("__calendar_node_"+this.category, calendar, clocks);
nodeSet.add(calNode);
clockAssertion = new NodeCallExpr(calNode.id, clocks);
}else{
clockAssertion = new BoolExpr(true);
for(Expr expr : clocks){
clockAssertion = new BinaryExpr(expr, BinaryOp.AND, clockAssertion);
}
}
//also assert that some clock ticks
Expr clockTickAssertion = new BoolExpr(false);
for(Expr expr : clocks){
clockTickAssertion = new BinaryExpr(expr, BinaryOp.OR, clockTickAssertion);
}
List<Expr> assertions = new ArrayList<>();
assertions.add(clockAssertion);
assertions.add(clockTickAssertion);
return assertions;
}
private void addTotalCompHistoryConsist(List<Equation> eqs,
List<VarDecl> internals, List<String> properties,
IdExpr totalCompHistId, IdExpr countId) {
IdExpr notTotalCompHistId = new IdExpr("_TOTAL_COMP_FINITE_CONSIST");
Expr finiteConsist = AgreeEmitterUtilities.getFinteConsistancy(totalCompHistId, countId, consistUnrollDepth);
Equation contrConsistEq = new Equation(notTotalCompHistId, finiteConsist);
internals.add(new VarDecl(notTotalCompHistId.id, new NamedType("bool")));
eqs.add(contrConsistEq);
properties.add(notTotalCompHistId.id);
consistProps.add(notTotalCompHistId.id);
//reversePropStatus.add(true);
addToRenaming(notTotalCompHistId.id, "Total Contract Consistent");
//layout.addElement("Top", "Total Contract Consistants", AgreeLayout.SigType.OUTPUT);
layout.addElement(category, "Total Contract Consistents", AgreeLayout.SigType.OUTPUT);
}
private IdExpr addConsistencyConstraints(List<Equation> eqs,
List<VarDecl> internals) {
IdExpr countId = new IdExpr("__CONSIST_COUNTER");
internals.add(new VarDecl(countId.id, new NamedType("int")));
Expr countPre = new BinaryExpr(new UnaryExpr(UnaryOp.PRE, countId), BinaryOp.PLUS, new IntExpr(BigInteger.ONE));
countPre = new BinaryExpr(new IntExpr(BigInteger.ZERO), BinaryOp.ARROW, countPre);
Equation contEq = new Equation(countId, countPre);
eqs.add(contEq);
return countId;
}
private void addSubEmitterVars(List<AgreeAnnexEmitter> subEmitters,
List<Equation> eqs, List<VarDecl> inputs, List<Expr> clocks,
List<Node> nodeSet, Set<AgreeVarDecl> agreeInputVars,
Set<AgreeVarDecl> agreeInternalVars) {
for(AgreeAnnexEmitter subEmitter : subEmitters){
AgreeNode agreeNode = subEmitter.getComponentNode();
nodeSet.addAll(agreeNode.nodes);
List<Expr> initOutputs = new ArrayList<>();
List<Expr> nodeInputs = new ArrayList<>();
List<IdExpr> nodeOutputs = new ArrayList<>();
//if the clock was explicitly referenced it may
//have already been created. Don't add it to the
//input list if it was already created
IdExpr clockExpr = new IdExpr(agreeNode.clockVar.id);
AgreeVarDecl agreeInputVar = new AgreeVarDecl(agreeNode.clockVar.id, null, null);
if(!this.inputVars.contains(agreeInputVar)){
inputs.add(agreeNode.clockVar);
//make it so the clock is visible in the counter example
addToRenaming(clockExpr.id, clockExpr.id);
refMap.put(clockExpr.id, subEmitter.curComp);
layout.addElement(subEmitter.category, clockExpr.id, SigType.INPUT);
}
clocks.add(clockExpr);
agreeInputVars.addAll(subEmitter.inputVars);
agreeInternalVars.addAll(subEmitter.internalVars);
//also add new assumption, assertion, and guarantee vars
for(Expr expr : agreeNode.assertions){
IdExpr varId = (IdExpr)expr;
AgreeVarDecl agreeVar = new AgreeVarDecl();
agreeVar.aadlStr = agreeVar.jKindStr = varId.id;
agreeVar.type = "bool";
agreeInternalVars.add(agreeVar);
}
for(Expr expr : agreeNode.assumptions){
IdExpr varId = (IdExpr)expr;
AgreeVarDecl agreeVar = new AgreeVarDecl();
agreeVar.aadlStr = agreeVar.jKindStr = varId.id;
agreeVar.type = "bool";
agreeInternalVars.add(agreeVar);
}
for(Expr expr : agreeNode.guarantees){
IdExpr varId = (IdExpr)expr;
AgreeVarDecl agreeVar = new AgreeVarDecl();
agreeVar.aadlStr = agreeVar.jKindStr = varId.id;
agreeVar.type = "bool";
agreeInternalVars.add(agreeVar);
}
//TODO: set different initial values for outputs
for(VarDecl var : agreeNode.outputs){
NamedType type = (NamedType)var.type;
//queue in and out variables need to be false initially
//if(var.id.startsWith(queueInClockPrefix)
// || var.id.startsWith(queueOutClockPrefix)){
// initOutputs.add(new BoolExpr(false));
//}else{
initOutputs.add(initTypeMap.get(type.name));
nodeOutputs.add(new IdExpr(var.id));
//}
}
for(VarDecl var : agreeNode.inputs){
nodeInputs.add(new IdExpr(var.id));
}
NodeCallExpr nodeCall = new NodeCallExpr(agreeNode.mainNode.id, nodeInputs);
CondactExpr condact = new CondactExpr(clockExpr, nodeCall, initOutputs);
Equation condactEq = new Equation(nodeOutputs, condact);
eqs.add(condactEq);
addToRenamingAll(subEmitter.varRenaming);
refMap.putAll(subEmitter.refMap);
//create the hold equations for the subcomponent outputs
for(AgreeVarDecl varDec : subEmitter.outputVars){
AgreeVarDecl dummyAgreeVar = new AgreeVarDecl();
dummyAgreeVar.type = varDec.type;
dummyAgreeVar.jKindStr = "___DUMMY_" + varDec.jKindStr;
agreeInputVars.add(dummyAgreeVar);
agreeInternalVars.add(varDec);
IdExpr dummyId = new IdExpr(dummyAgreeVar.jKindStr);
IdExpr clockId = new IdExpr(agreeNode.clockVar.id);
IdExpr outId = new IdExpr(varDec.jKindStr);
Expr preExpr = new BinaryExpr(dummyId, BinaryOp.ARROW, new UnaryExpr(UnaryOp.PRE, outId));
Expr ifElse = new IfThenElseExpr(clockId, dummyId, preExpr);
Equation clockOutEq = new Equation(outId, ifElse);
eqs.add(clockOutEq);
}
}
}
private void addSubcomponentAssumptions(List<AgreeAnnexEmitter> subEmitters,
List<Equation> eqs, List<VarDecl> internals,
List<String> properties, Expr totalCompHist, Expr sysAssumpHist,
IdExpr allClksTickedExpr, Map<Subcomponent, Set<Subcomponent>> closureMap, IdExpr countId) {
for(AgreeAnnexEmitter subEmitter : subEmitters){
Expr higherContracts = new BoolExpr(true);
Set<Subcomponent> closureSubs = closureMap.get(subEmitter.curComp);
for(AgreeAnnexEmitter closureEmitter : subEmitters){
if(closureSubs.contains(closureEmitter.curComp)){
continue;
}
higherContracts = new BinaryExpr(higherContracts, BinaryOp.AND,
AgreeEmitterUtilities.getLustreContract(closureEmitter));
}
Expr contrAssumps = AgreeEmitterUtilities.getLustreAssumptions(subEmitter);
IdExpr compId = new IdExpr("_Hist_" + subEmitter.category);
internals.add(new VarDecl(compId.id, new NamedType("bool")));
Expr leftSide = new UnaryExpr(UnaryOp.PRE, totalCompHist);
leftSide = new BinaryExpr(new BoolExpr(true), BinaryOp.ARROW, leftSide);
leftSide = new BinaryExpr(sysAssumpHist, BinaryOp.AND, leftSide);
leftSide = new BinaryExpr(higherContracts, BinaryOp.AND, leftSide);
IdExpr clockVarId = new IdExpr(subEmitter.agreeNode.clockVar.id);
leftSide = new BinaryExpr(clockVarId, BinaryOp.AND, leftSide);
Expr contrHistExpr = new BinaryExpr(leftSide, BinaryOp.IMPLIES, contrAssumps);
Equation contrHist = new Equation(compId, contrHistExpr);
eqs.add(contrHist);
properties.add(compId.id);
assumProps.add(compId.id);
String propertyName = subEmitter.category + " Assumptions";
addToRenaming(compId.id, propertyName);
//layout.addElement("Top", propertyName, AgreeLayout.SigType.OUTPUT);
layout.addElement(category, propertyName, AgreeLayout.SigType.OUTPUT);
//add a property that is true if the contract is a contradiction
IdExpr contrHistId = new IdExpr("__CONTR_HIST_" + subEmitter.category);
IdExpr consistId = new IdExpr("__NULL_CONTR_HIST_" + subEmitter.category);
Expr contExpr = AgreeEmitterUtilities.getLustreContract(subEmitter);
Equation contHist = AgreeEmitterUtilities.getLustreHistory(contExpr, contrHistId);
Expr finiteConsist = AgreeEmitterUtilities.getFinteConsistancy(contrHistId, countId, consistUnrollDepth);
Equation contrConsistEq = new Equation(consistId, finiteConsist);
eqs.add(contrConsistEq);
eqs.add(contHist);
internals.add(new VarDecl(contrHistId.id, new NamedType("bool")));
internals.add(new VarDecl(consistId.id, new NamedType("bool")));
properties.add(consistId.id);
consistProps.add(consistId.id);
//reversePropStatus.add(true);
String contractName = subEmitter.category + " Consistent";
addToRenaming(consistId.id, contractName);
//layout.addElement("Top", contractName, AgreeLayout.SigType.OUTPUT);
layout.addElement(category, contractName, AgreeLayout.SigType.OUTPUT);
}
}
private Expr getQueueInsertRemoveAtomicAssertion(List<AgreeAnnexEmitter> subEmitters){
Expr assertExpr = new BoolExpr(true);
for(AgreeAnnexEmitter subEmitter : subEmitters){
Subcomponent subComp = subEmitter.curComp;
IdExpr clockId = new IdExpr(clockIDPrefix+subComp.getName());
Expr notClock = new UnaryExpr(UnaryOp.NOT, clockId);
for(Feature feat : subComp.getComponentType().getAllFeatures()){
if(feat instanceof EventDataPort){
EventDataPort eventPort = (EventDataPort)feat;
List<IdExpr> inClocks = queueInClockMap.get(eventPort);
if(inClocks != null){
for(IdExpr id : inClocks){
Expr notId = new UnaryExpr(UnaryOp.NOT, id);
Expr impExpr = new BinaryExpr(notClock, BinaryOp.IMPLIES, notId);
assertExpr = new BinaryExpr(assertExpr, BinaryOp.AND, impExpr);
}
}
List<IdExpr> outClocks = queueOutClockMap.get(eventPort);
if(outClocks != null){
for(IdExpr id : outClocks){
Expr notId = new UnaryExpr(UnaryOp.NOT, id);
Expr impExpr = new BinaryExpr(notClock, BinaryOp.IMPLIES, notId);
assertExpr = new BinaryExpr(assertExpr, BinaryOp.AND, impExpr);
}
}
}
}
}
return assertExpr;
}
private Expr getQueueClockCountVarEquivAssertion(){
Expr andEquivExpr = new BoolExpr(true);
for(Entry<EventDataPort, List<IdExpr>> entries : queueInClockMap.entrySet()){
List<IdExpr> Ids = entries.getValue();
Expr prevEquivExpr = Ids.get(0);
for(IdExpr id : Ids){
Expr eqExpr = new BinaryExpr(prevEquivExpr, BinaryOp.EQUAL, id);
andEquivExpr = new BinaryExpr(andEquivExpr, BinaryOp.AND, eqExpr);
prevEquivExpr = id;
}
}
for(Entry<EventDataPort, List<IdExpr>> entries : queueOutClockMap.entrySet()){
List<IdExpr> Ids = entries.getValue();
Expr prevEquivExpr = Ids.get(0);
for(IdExpr id : Ids){
Expr eqExpr = new BinaryExpr(prevEquivExpr, BinaryOp.EQUAL, id);
andEquivExpr = new BinaryExpr(andEquivExpr, BinaryOp.AND, eqExpr);
prevEquivExpr = id;
}
}
for(Entry<EventDataPort, List<IdExpr>> entries : queueCountMap.entrySet()){
List<IdExpr> Ids = entries.getValue();
Expr prevEquivExpr = Ids.get(0);
for(IdExpr id : Ids){
Expr eqExpr = new BinaryExpr(prevEquivExpr, BinaryOp.EQUAL, id);
andEquivExpr = new BinaryExpr(andEquivExpr, BinaryOp.AND, eqExpr);
prevEquivExpr = id;
}
}
return andEquivExpr;
}
private void addConnection(Equation connEq){
if(connEq.lhs.size() != 1){
throw new AgreeException("attemp to add connection expression with a "
+ "left hand side not equal to one");
}
String connStr = connEq.lhs.get(0).id;
if(connLHS.contains(connStr)){
throw new AgreeException("multiple assignments of connection variable '"+connStr+"'");
}
connLHS.add(connStr);
connExpressions.add(connEq);
}
}
| false | true | private void makeConnectionExpressions(
ConnectedElement absConnSour, ConnectedElement absConnDest) {
ConnectionEnd destConn = absConnDest.getConnectionEnd();
ConnectionEnd sourConn = absConnSour.getConnectionEnd();
//we currently don't handle data accesses or buss accesses
if(destConn instanceof DataAccess
|| sourConn instanceof DataAccess
|| destConn instanceof BusAccess
|| sourConn instanceof BusAccess){
return;
}
Context destContext = absConnDest.getContext();
Context sourContext = absConnSour.getContext();
// String sourName = (sourContext == null) ? category : sourContext.getName();
// String destName = (destContext == null) ? category : destContext.getName();
ComponentInstance sourInst = null;
FeatureInstance sourBaseFeatInst = null;
if(sourContext == null){
sourInst = curInst;
}else if(sourContext instanceof Subcomponent){
sourInst = curInst.findSubcomponentInstance((Subcomponent)sourContext);
}else{
sourBaseFeatInst = curInst.findFeatureInstance((FeatureGroup)sourContext);
}
ComponentInstance destInst = null;
FeatureInstance destBaseFeatInst = null;
if(destContext == null){
destInst = curInst;
}else if(destContext instanceof Subcomponent){
destInst = curInst.findSubcomponentInstance((Subcomponent)destContext);
}else{
destBaseFeatInst = curInst.findFeatureInstance((FeatureGroup)destContext);
}
//get the corresponding feature instances
FeatureInstance sourFeatInst = null;
FeatureInstance destFeatInst = null;
List<FeatureInstance> sourFeatInsts = (sourInst == null) ?
sourBaseFeatInst.getFeatureInstances() :
sourInst.getFeatureInstances();
List<FeatureInstance> destFeatInsts = (destInst == null) ?
destBaseFeatInst.getFeatureInstances() :
destInst.getFeatureInstances();
for(FeatureInstance featInst : sourFeatInsts){
if(featInst.getFeature() == sourConn){
sourFeatInst = featInst;
break;
}
}
for(FeatureInstance featInst : destFeatInsts){
if(featInst.getFeature() == destConn){
destFeatInst = featInst;
break;
}
}
//grabs the subnames for all the connections
List<AgreeFeature> destConns = featInstToAgreeFeatMap.get(destFeatInst);
List<AgreeFeature> sourConns = featInstToAgreeFeatMap.get(sourFeatInst);
String lhsLustreName = null;
String rhsLustreName = null;
String lhsAadlName = null;
String rhsAadlName = null;
int i;
assert(destConns.size() == sourConns.size());
for(i = 0; i < destConns.size(); i++){
AgreeFeature agreeDestConn = destConns.get(i);
AgreeFeature agreeSourConn = sourConns.get(i);
//assert(agreeDestConn.lustreString == agreeSourConn.lustreString);
//assert(agreeDestConn.aadlString == agreeSourConn.aadlString);
assert(agreeDestConn.varType == agreeSourConn.varType);
if(sourContext == null){
switch(agreeDestConn.direction){
case IN:
lhsLustreName = agreeDestConn.lustreString;
lhsAadlName = agreeDestConn.aadlString;
rhsLustreName = agreeSourConn.lustreString;
rhsAadlName = agreeSourConn.aadlString;
break;
case OUT:
lhsLustreName = agreeSourConn.lustreString;
lhsAadlName = agreeSourConn.aadlString;
rhsLustreName = agreeDestConn.lustreString;
rhsAadlName = agreeDestConn.aadlString;
}
}else if(destContext == null){
switch(agreeDestConn.direction){
case IN:
lhsLustreName = agreeSourConn.lustreString;
lhsAadlName = agreeSourConn.aadlString;
rhsLustreName = agreeDestConn.lustreString;
rhsAadlName = agreeDestConn.aadlString;
break;
case OUT:
lhsLustreName = agreeDestConn.lustreString;
lhsAadlName = agreeDestConn.aadlString;
rhsLustreName = agreeSourConn.lustreString;
rhsAadlName = agreeSourConn.aadlString;
}
}else{
switch(agreeDestConn.direction){
case IN:
lhsLustreName = agreeDestConn.lustreString;
lhsAadlName = agreeDestConn.aadlString;
rhsLustreName = agreeSourConn.lustreString;
rhsAadlName = agreeSourConn.aadlString;
break;
case OUT:
lhsLustreName = agreeSourConn.lustreString;
lhsAadlName = agreeSourConn.aadlString;
rhsLustreName = agreeDestConn.lustreString;
rhsAadlName = agreeDestConn.aadlString;
}
}
if(agreeDestConn.connType == AgreeFeature.ConnType.QUEUE){
String sourInstName;
if(sourInst == null){
sourInstName = sourBaseFeatInst.getName();
}else if(sourInst == curInst){
sourInstName = null;
}else{
sourInstName = sourInst.getName();
}
String destInstName;
if(destInst == null){
destInstName = destBaseFeatInst.getName();
}else if(destInst == curInst){
destInstName = null;
}else{
destInstName = destInst.getName();
}
AgreeQueueElement agreeQueueElem = new AgreeQueueElement(rhsLustreName,
rhsAadlName,
lhsLustreName,
lhsAadlName,
new NamedType(agreeDestConn.varType),
(EventDataPort)agreeSourConn.feature,
(EventDataPort)agreeDestConn.feature,
sourInstName,
destInstName,
agreeDestConn.queueSize);
if(queueMap.containsKey(lhsLustreName)){
List<AgreeQueueElement> queues = queueMap.get(lhsLustreName);
queues.add(agreeQueueElem);
}else{
List<AgreeQueueElement> queues = new ArrayList<AgreeQueueElement>();
queues.add(agreeQueueElem);
queueMap.put(lhsLustreName, queues);
}
}else{
Equation connEq = new Equation(new IdExpr(lhsLustreName), new IdExpr(rhsLustreName));
addConnection(connEq);;
}
//add left hand side expressions as internal variables
AgreeVarDecl agreeVar = new AgreeVarDecl(lhsLustreName, lhsAadlName, agreeSourConn.varType);
internalVars.add(agreeVar);
}
}
| private void makeConnectionExpressions(
ConnectedElement absConnSour, ConnectedElement absConnDest) {
ConnectionEnd destConn = absConnDest.getConnectionEnd();
ConnectionEnd sourConn = absConnSour.getConnectionEnd();
//we currently don't handle data accesses or buss accesses
if(destConn instanceof DataAccess
|| sourConn instanceof DataAccess
|| destConn instanceof BusAccess
|| sourConn instanceof BusAccess){
return;
}
Context destContext = absConnDest.getContext();
Context sourContext = absConnSour.getContext();
// String sourName = (sourContext == null) ? category : sourContext.getName();
// String destName = (destContext == null) ? category : destContext.getName();
ComponentInstance sourInst = null;
FeatureInstance sourBaseFeatInst = null;
if(sourContext == null){
sourInst = curInst;
}else if(sourContext instanceof Subcomponent){
sourInst = curInst.findSubcomponentInstance((Subcomponent)sourContext);
}else{
sourBaseFeatInst = curInst.findFeatureInstance((FeatureGroup)sourContext);
}
ComponentInstance destInst = null;
FeatureInstance destBaseFeatInst = null;
if(destContext == null){
destInst = curInst;
}else if(destContext instanceof Subcomponent){
destInst = curInst.findSubcomponentInstance((Subcomponent)destContext);
}else{
destBaseFeatInst = curInst.findFeatureInstance((FeatureGroup)destContext);
}
//get the corresponding feature instances
FeatureInstance sourFeatInst = null;
FeatureInstance destFeatInst = null;
List<FeatureInstance> sourFeatInsts = (sourInst == null) ?
sourBaseFeatInst.getFeatureInstances() :
sourInst.getFeatureInstances();
List<FeatureInstance> destFeatInsts = (destInst == null) ?
destBaseFeatInst.getFeatureInstances() :
destInst.getFeatureInstances();
for(FeatureInstance featInst : sourFeatInsts){
if(featInst.getFeature() == sourConn){
sourFeatInst = featInst;
break;
}
}
for(FeatureInstance featInst : destFeatInsts){
if(featInst.getFeature() == destConn){
destFeatInst = featInst;
break;
}
}
//grabs the subnames for all the connections
List<AgreeFeature> destConns = featInstToAgreeFeatMap.get(destFeatInst);
List<AgreeFeature> sourConns = featInstToAgreeFeatMap.get(sourFeatInst);
String lhsLustreName = null;
String rhsLustreName = null;
String lhsAadlName = null;
String rhsAadlName = null;
int i;
assert(destConns.size() == sourConns.size());
for(i = 0; i < destConns.size(); i++){
AgreeFeature agreeDestConn = destConns.get(i);
AgreeFeature agreeSourConn = sourConns.get(i);
//assert(agreeDestConn.lustreString == agreeSourConn.lustreString);
//assert(agreeDestConn.aadlString == agreeSourConn.aadlString);
assert(agreeDestConn.varType == agreeSourConn.varType);
if(sourContext == null || sourContext instanceof FeatureGroup){
switch(agreeDestConn.direction){
case IN:
lhsLustreName = agreeDestConn.lustreString;
lhsAadlName = agreeDestConn.aadlString;
rhsLustreName = agreeSourConn.lustreString;
rhsAadlName = agreeSourConn.aadlString;
break;
case OUT:
lhsLustreName = agreeSourConn.lustreString;
lhsAadlName = agreeSourConn.aadlString;
rhsLustreName = agreeDestConn.lustreString;
rhsAadlName = agreeDestConn.aadlString;
}
}else if(destContext == null || destContext instanceof FeatureGroup){
switch(agreeDestConn.direction){
case IN:
lhsLustreName = agreeSourConn.lustreString;
lhsAadlName = agreeSourConn.aadlString;
rhsLustreName = agreeDestConn.lustreString;
rhsAadlName = agreeDestConn.aadlString;
break;
case OUT:
lhsLustreName = agreeDestConn.lustreString;
lhsAadlName = agreeDestConn.aadlString;
rhsLustreName = agreeSourConn.lustreString;
rhsAadlName = agreeSourConn.aadlString;
}
}else{
switch(agreeDestConn.direction){
case IN:
lhsLustreName = agreeDestConn.lustreString;
lhsAadlName = agreeDestConn.aadlString;
rhsLustreName = agreeSourConn.lustreString;
rhsAadlName = agreeSourConn.aadlString;
break;
case OUT:
lhsLustreName = agreeSourConn.lustreString;
lhsAadlName = agreeSourConn.aadlString;
rhsLustreName = agreeDestConn.lustreString;
rhsAadlName = agreeDestConn.aadlString;
}
}
if(agreeDestConn.connType == AgreeFeature.ConnType.QUEUE){
String sourInstName;
if(sourInst == null){
sourInstName = sourBaseFeatInst.getName();
}else if(sourInst == curInst){
sourInstName = null;
}else{
sourInstName = sourInst.getName();
}
String destInstName;
if(destInst == null){
destInstName = destBaseFeatInst.getName();
}else if(destInst == curInst){
destInstName = null;
}else{
destInstName = destInst.getName();
}
AgreeQueueElement agreeQueueElem = new AgreeQueueElement(rhsLustreName,
rhsAadlName,
lhsLustreName,
lhsAadlName,
new NamedType(agreeDestConn.varType),
(EventDataPort)agreeSourConn.feature,
(EventDataPort)agreeDestConn.feature,
sourInstName,
destInstName,
agreeDestConn.queueSize);
if(queueMap.containsKey(lhsLustreName)){
List<AgreeQueueElement> queues = queueMap.get(lhsLustreName);
queues.add(agreeQueueElem);
}else{
List<AgreeQueueElement> queues = new ArrayList<AgreeQueueElement>();
queues.add(agreeQueueElem);
queueMap.put(lhsLustreName, queues);
}
}else{
Equation connEq = new Equation(new IdExpr(lhsLustreName), new IdExpr(rhsLustreName));
addConnection(connEq);;
}
//add left hand side expressions as internal variables
AgreeVarDecl agreeVar = new AgreeVarDecl(lhsLustreName, lhsAadlName, agreeSourConn.varType);
internalVars.add(agreeVar);
}
}
|
diff --git a/CompleteMyTaskTest/src/ca/ualberta/cs/completemytask/test/CreateTaskTest.java b/CompleteMyTaskTest/src/ca/ualberta/cs/completemytask/test/CreateTaskTest.java
index fcd3556..75812c6 100644
--- a/CompleteMyTaskTest/src/ca/ualberta/cs/completemytask/test/CreateTaskTest.java
+++ b/CompleteMyTaskTest/src/ca/ualberta/cs/completemytask/test/CreateTaskTest.java
@@ -1,86 +1,86 @@
package ca.ualberta.cs.completemytask.test;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import ca.ualberta.cs.completemytask.R;
import ca.ualberta.cs.completemytask.activities.AddTaskActivity;
import ca.ualberta.cs.completemytask.userdata.Task;
import ca.ualberta.cs.completemytask.userdata.TaskManager;
import android.test.ActivityInstrumentationTestCase2;
import android.test.UiThreadTest;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
public class CreateTaskTest extends ActivityInstrumentationTestCase2<AddTaskActivity> {
private AddTaskActivity main;
private Button addButton;
// Task Info
private String taskName = "Test Task";
private String taskDescription = "Test Description";
private boolean testNeedsComment = true;
private boolean testNeedsPhoto = true;
private boolean testNeedsAudio = false;
public CreateTaskTest() {
super(AddTaskActivity.class);
}
protected void setUp() throws Exception {
super.setUp();
this.main = getActivity();
this.addButton = (Button) this.main.findViewById(R.id.AddTaskButton);
}
@UiThreadTest
public void testAddTask() {
// Edit Text Views
EditText taskNameEditText = (EditText) main.findViewById(R.id.EditTaskName);
taskNameEditText.setText(taskName);
EditText taskDescriptionEditText = (EditText) main.findViewById(R.id.EditTaskDescription);
taskDescriptionEditText.setText(taskDescription);
// Check box views
CheckBox textRequirementCheckbox = (CheckBox) main.findViewById(R.id.TextRequirementCheckbox);
textRequirementCheckbox.setChecked(testNeedsComment);
CheckBox photoRequirementCheckbox = (CheckBox) main.findViewById(R.id.PictureRequirementCheckbox);
photoRequirementCheckbox.setChecked(testNeedsPhoto);
CheckBox audioRequirementCheckbox = (CheckBox) main.findViewById(R.id.AudioRequirementCheckbox);
audioRequirementCheckbox.setChecked(testNeedsAudio);
CountDownLatch latch = new CountDownLatch(1);
try {
latch.await(2, TimeUnit.SECONDS);
addButton.performClick();
latch.await(2, TimeUnit.SECONDS);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
boolean foundTask = false;
for(Task task : TaskManager.getInstance().getTaskArray()) {
if(task.getName().equals(taskName)) {
foundTask = true;
assertTrue("Wrong Description", task.getDescription().endsWith(taskDescription));
- assertTrue("No ID", task.getId() == null);
+ assertNull("No ID", task.getId());
assertTrue("Failed isComplete", task.isComplete() == false);
assertTrue("Failed needs Comment", task.needsComment() == testNeedsComment);
assertTrue("Failed needs Photo", task.needsPhoto() == testNeedsPhoto);
assertTrue("Failed needs Comment", task.needsAudio() == testNeedsAudio);
}
}
assertTrue("Task Not Found", foundTask);
}
}
| true | true | public void testAddTask() {
// Edit Text Views
EditText taskNameEditText = (EditText) main.findViewById(R.id.EditTaskName);
taskNameEditText.setText(taskName);
EditText taskDescriptionEditText = (EditText) main.findViewById(R.id.EditTaskDescription);
taskDescriptionEditText.setText(taskDescription);
// Check box views
CheckBox textRequirementCheckbox = (CheckBox) main.findViewById(R.id.TextRequirementCheckbox);
textRequirementCheckbox.setChecked(testNeedsComment);
CheckBox photoRequirementCheckbox = (CheckBox) main.findViewById(R.id.PictureRequirementCheckbox);
photoRequirementCheckbox.setChecked(testNeedsPhoto);
CheckBox audioRequirementCheckbox = (CheckBox) main.findViewById(R.id.AudioRequirementCheckbox);
audioRequirementCheckbox.setChecked(testNeedsAudio);
CountDownLatch latch = new CountDownLatch(1);
try {
latch.await(2, TimeUnit.SECONDS);
addButton.performClick();
latch.await(2, TimeUnit.SECONDS);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
boolean foundTask = false;
for(Task task : TaskManager.getInstance().getTaskArray()) {
if(task.getName().equals(taskName)) {
foundTask = true;
assertTrue("Wrong Description", task.getDescription().endsWith(taskDescription));
assertTrue("No ID", task.getId() == null);
assertTrue("Failed isComplete", task.isComplete() == false);
assertTrue("Failed needs Comment", task.needsComment() == testNeedsComment);
assertTrue("Failed needs Photo", task.needsPhoto() == testNeedsPhoto);
assertTrue("Failed needs Comment", task.needsAudio() == testNeedsAudio);
}
}
assertTrue("Task Not Found", foundTask);
}
| public void testAddTask() {
// Edit Text Views
EditText taskNameEditText = (EditText) main.findViewById(R.id.EditTaskName);
taskNameEditText.setText(taskName);
EditText taskDescriptionEditText = (EditText) main.findViewById(R.id.EditTaskDescription);
taskDescriptionEditText.setText(taskDescription);
// Check box views
CheckBox textRequirementCheckbox = (CheckBox) main.findViewById(R.id.TextRequirementCheckbox);
textRequirementCheckbox.setChecked(testNeedsComment);
CheckBox photoRequirementCheckbox = (CheckBox) main.findViewById(R.id.PictureRequirementCheckbox);
photoRequirementCheckbox.setChecked(testNeedsPhoto);
CheckBox audioRequirementCheckbox = (CheckBox) main.findViewById(R.id.AudioRequirementCheckbox);
audioRequirementCheckbox.setChecked(testNeedsAudio);
CountDownLatch latch = new CountDownLatch(1);
try {
latch.await(2, TimeUnit.SECONDS);
addButton.performClick();
latch.await(2, TimeUnit.SECONDS);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
boolean foundTask = false;
for(Task task : TaskManager.getInstance().getTaskArray()) {
if(task.getName().equals(taskName)) {
foundTask = true;
assertTrue("Wrong Description", task.getDescription().endsWith(taskDescription));
assertNull("No ID", task.getId());
assertTrue("Failed isComplete", task.isComplete() == false);
assertTrue("Failed needs Comment", task.needsComment() == testNeedsComment);
assertTrue("Failed needs Photo", task.needsPhoto() == testNeedsPhoto);
assertTrue("Failed needs Comment", task.needsAudio() == testNeedsAudio);
}
}
assertTrue("Task Not Found", foundTask);
}
|
diff --git a/tests/frontend/org/voltdb/quarantine/TestExportSuiteTestExportAndDroppedTableThenShutdown.java b/tests/frontend/org/voltdb/quarantine/TestExportSuiteTestExportAndDroppedTableThenShutdown.java
index 9dfb07302..ce404f73a 100644
--- a/tests/frontend/org/voltdb/quarantine/TestExportSuiteTestExportAndDroppedTableThenShutdown.java
+++ b/tests/frontend/org/voltdb/quarantine/TestExportSuiteTestExportAndDroppedTableThenShutdown.java
@@ -1,388 +1,388 @@
/* This file is part of VoltDB.
* Copyright (C) 2008-2012 VoltDB Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
package org.voltdb.quarantine;
import java.io.File;
import org.voltdb.BackendTarget;
import org.voltdb.VoltDB.Configuration;
import org.voltdb.client.Client;
import org.voltdb.client.ClientResponse;
import org.voltdb.client.ProcedureCallback;
import org.voltdb.compiler.VoltProjectBuilder;
import org.voltdb.compiler.VoltProjectBuilder.GroupInfo;
import org.voltdb.compiler.VoltProjectBuilder.ProcedureInfo;
import org.voltdb.compiler.VoltProjectBuilder.UserInfo;
import org.voltdb.export.ExportTestClient;
import org.voltdb.exportclient.ExportClientException;
import org.voltdb.regressionsuites.LocalCluster;
import org.voltdb.regressionsuites.MultiConfigSuiteBuilder;
import org.voltdb.regressionsuites.RegressionSuite;
import org.voltdb.regressionsuites.TestOrderBySuite;
import org.voltdb.regressionsuites.TestSQLTypesSuite;
import org.voltdb.regressionsuites.VoltServerConfig;
import org.voltdb.utils.MiscUtils;
import org.voltdb.utils.VoltFile;
import org.voltdb_testprocs.regressionsuites.sqltypesprocs.Insert;
import org.voltdb_testprocs.regressionsuites.sqltypesprocs.InsertAddedTable;
import org.voltdb_testprocs.regressionsuites.sqltypesprocs.InsertBase;
import org.voltdb_testprocs.regressionsuites.sqltypesprocs.RollbackInsert;
import org.voltdb_testprocs.regressionsuites.sqltypesprocs.Update_Export;
/**
* End to end Export tests using the RawProcessor and the ExportSinkServer.
*
* Note, this test reuses the TestSQLTypesSuite schema and procedures.
* Each table in that schema, to the extent the DDL is supported by the
* DB, really needs an Export round trip test.
*/
public class TestExportSuiteTestExportAndDroppedTableThenShutdown extends RegressionSuite {
private ExportTestClient m_tester;
/** Shove a table name and pkey in front of row data */
private Object[] convertValsToParams(String tableName, final int i,
final Object[] rowdata)
{
final Object[] params = new Object[rowdata.length + 2];
params[0] = tableName;
params[1] = i;
for (int ii=0; ii < rowdata.length; ++ii)
params[ii+2] = rowdata[ii];
return params;
}
/** Push pkey into expected row data */
private Object[] convertValsToRow(final int i, final char op,
final Object[] rowdata) {
final Object[] row = new Object[rowdata.length + 2];
row[0] = (byte)(op == 'I' ? 1 : 0);
row[1] = i;
for (int ii=0; ii < rowdata.length; ++ii)
row[ii+2] = rowdata[ii];
return row;
}
/** Push pkey into expected row data */
@SuppressWarnings("unused")
private Object[] convertValsToLoaderRow(final int i, final Object[] rowdata) {
final Object[] row = new Object[rowdata.length + 1];
row[0] = i;
for (int ii=0; ii < rowdata.length; ++ii)
row[ii+1] = rowdata[ii];
return row;
}
private void quiesce(final Client client)
throws Exception
{
client.drain();
client.callProcedure("@Quiesce");
}
private void quiesceAndVerifyRetryWorkOnIOException(final Client client, ExportTestClient tester)
throws Exception
{
quiesce(client);
while (true) {
try {
tester.work();
} catch (ExportClientException e) {
boolean success = reconnect(tester);
assertTrue(success);
System.out.println(e.toString());
continue;
}
break;
}
assertTrue(tester.allRowsVerified());
assertTrue(tester.verifyExportOffsets());
}
@Override
public void setUp() throws Exception
{
m_username = "default";
m_password = "password";
VoltFile.recursivelyDelete(new File("/tmp/" + System.getProperty("user.name")));
File f = new File("/tmp/" + System.getProperty("user.name"));
f.mkdirs();
super.setUp();
callbackSucceded = true;
m_tester = new ExportTestClient(getServerConfig().getNodeCount(), port(0));
m_tester.addCredentials("export", "export");
try {
m_tester.connect();
} catch (ExportClientException e) {
e.printStackTrace();
assertTrue(false);
}
}
@Override
public void tearDown() throws Exception {
super.tearDown();
m_tester.disconnect();
assertTrue(callbackSucceded);
}
private boolean callbackSucceded = true;
class RollbackCallback implements ProcedureCallback {
@Override
public void clientCallback(ClientResponse clientResponse) {
if (clientResponse.getStatus() != ClientResponse.USER_ABORT) {
callbackSucceded = false;
System.err.println(clientResponse.getException());
}
}
}
private boolean reconnect(ExportTestClient client) throws ExportClientException {
for (int ii = 0; ii < 3; ii++) {
m_tester.disconnect();
m_tester.reserveVerifiers();
boolean success = client.connect();
if (success) return true;
}
return false;
}
// Test Export of a DROPPED table. Queues some data to a table.
// Then drops the table and restarts the server. Verifies that Export can successfully
// drain the dropped table. IE, drop table doesn't lose Export data.
//
public void testExportAndDroppedTableThenShutdown() throws Exception {
System.out.println("testExportAndDroppedTableThenShutdown");
Client client = getClient();
for (int i=0; i < 10; i++) {
final Object[] rowdata = TestSQLTypesSuite.m_midValues;
m_tester.addRow( m_tester.m_generationsSeen.first(), "NO_NULLS", i, convertValsToRow(i, 'I', rowdata));
final Object[] params = convertValsToParams("NO_NULLS", i, rowdata);
client.callProcedure("Insert", params);
}
// now drop the no-nulls table
final String newCatalogURL = Configuration.getPathToCatalogForTest("export-ddl-sans-nonulls.jar");
final String deploymentURL = Configuration.getPathToCatalogForTest("export-ddl-sans-nonulls.xml");
final ClientResponse callProcedure = client.updateApplicationCatalog(new File(newCatalogURL),
new File(deploymentURL));
assertTrue(callProcedure.getStatus() == ClientResponse.SUCCESS);
quiesce(client);
m_config.shutDown();
m_config.startUp(false);
client = getClient();
/**
* There will be 3 disconnects. Once for the shutdown, once for first generation,
* another for the 2nd generation created by the catalog change. The predicate is a complex
* way of saying make sure that the tester has created verifiers for
*/
for (int ii = 0; m_tester.m_generationsSeen.size() < 3 ||
m_tester.m_verifiers.get(m_tester.m_generationsSeen.last()).size() < 6; ii++) {
Thread.sleep(500);
boolean threwException = false;
try {
m_tester.work(1000);
} catch (ExportClientException e) {
boolean success = reconnect(m_tester);
assertTrue(success);
System.out.println(e.toString());
threwException = true;
}
if (ii < 3) {
assertTrue(threwException);
}
}
for (int i=10; i < 20; i++) {
final Object[] rowdata = TestSQLTypesSuite.m_midValues;
m_tester.addRow( m_tester.m_generationsSeen.last(), "NO_NULLS", i, convertValsToRow(i, 'I', rowdata));
final Object[] params = convertValsToParams("NO_NULLS", i, rowdata);
client.callProcedure("Insert", params);
}
client.drain();
// must still be able to verify the export data.
quiesceAndVerifyRetryWorkOnIOException(client, m_tester);
}
static final GroupInfo GROUPS[] = new GroupInfo[] {
new GroupInfo("export", false, false, false),
new GroupInfo("proc", true, true, true),
new GroupInfo("admin", true, true, true)
};
static final UserInfo[] USERS = new UserInfo[] {
new UserInfo("export", "export", new String[]{"export"}),
new UserInfo("default", "password", new String[]{"proc"}),
new UserInfo("admin", "admin", new String[]{"proc", "admin"})
};
/*
* Test suite boilerplate
*/
static final ProcedureInfo[] PROCEDURES = {
new ProcedureInfo( new String[]{"proc"}, Insert.class),
new ProcedureInfo( new String[]{"proc"}, InsertBase.class),
new ProcedureInfo( new String[]{"proc"}, RollbackInsert.class),
new ProcedureInfo( new String[]{"proc"}, Update_Export.class)
};
static final ProcedureInfo[] PROCEDURES2 = {
new ProcedureInfo( new String[]{"proc"}, Update_Export.class)
};
static final ProcedureInfo[] PROCEDURES3 = {
new ProcedureInfo( new String[]{"proc"}, InsertAddedTable.class)
};
public TestExportSuiteTestExportAndDroppedTableThenShutdown(final String name) {
super(name);
}
public static void main(final String args[]) {
org.junit.runner.JUnitCore.runClasses(TestOrderBySuite.class);
}
static public junit.framework.Test suite() throws Exception
{
VoltServerConfig config;
final MultiConfigSuiteBuilder builder =
new MultiConfigSuiteBuilder(TestExportSuiteTestExportAndDroppedTableThenShutdown.class);
VoltProjectBuilder project = new VoltProjectBuilder();
project.setSecurityEnabled(true);
project.addGroups(GROUPS);
project.addUsers(USERS);
- project.addSchema(TestSQLTypesSuite.class.getResource("sqltypessuite-ddl.sql"));
- project.addSchema(TestSQLTypesSuite.class.getResource("sqltypessuite-nonulls-ddl.sql"));
+ project.addSchema(TestSQLTypesSuite.class.getResource("sqltypessuite-export-ddl.sql"));
+ project.addSchema(TestSQLTypesSuite.class.getResource("sqltypessuite-nonulls-export-ddl.sql"));
project.addExport("org.voltdb.export.processors.RawProcessor",
true /*enabled*/,
java.util.Arrays.asList(new String[]{"export"}));
// "WITH_DEFAULTS" is a non-exported persistent table
project.setTableAsExportOnly("ALLOW_NULLS");
project.setTableAsExportOnly("NO_NULLS");
project.addPartitionInfo("NO_NULLS", "PKEY");
project.addPartitionInfo("ALLOW_NULLS", "PKEY");
project.addPartitionInfo("WITH_DEFAULTS", "PKEY");
project.addPartitionInfo("WITH_NULL_DEFAULTS", "PKEY");
project.addPartitionInfo("EXPRESSIONS_WITH_NULLS", "PKEY");
project.addPartitionInfo("EXPRESSIONS_NO_NULLS", "PKEY");
project.addPartitionInfo("JUMBO_ROW", "PKEY");
project.addProcedures(PROCEDURES);
// JNI, single server
// Use the cluster only config. Multiple topologies with the extra catalog for the
// Add drop tests is harder. Restrict to the single (complex) topology.
//
// config = new LocalSingleProcessServer("export-ddl.jar", 2,
// BackendTarget.NATIVE_EE_JNI);
// config.compile(project);
// builder.addServerConfig(config);
/*
* compile the catalog all tests start with
*/
config = new LocalCluster("export-ddl-cluster-rep.jar", 2, 3, 1,
BackendTarget.NATIVE_EE_JNI, LocalCluster.FailureState.ALL_RUNNING, true);
boolean compile = config.compile(project);
assertTrue(compile);
builder.addServerConfig(config);
/*
* compile a catalog without the NO_NULLS table for add/drop tests
*/
config = new LocalCluster("export-ddl-sans-nonulls.jar", 2, 3, 1,
BackendTarget.NATIVE_EE_JNI, LocalCluster.FailureState.ALL_RUNNING, true);
project = new VoltProjectBuilder();
project.addGroups(GROUPS);
project.addUsers(USERS);
- project.addSchema(TestSQLTypesSuite.class.getResource("sqltypessuite-ddl.sql"));
+ project.addSchema(TestSQLTypesSuite.class.getResource("sqltypessuite-export-ddl.sql"));
project.addExport("org.voltdb.export.processors.RawProcessor",
true, //enabled
java.util.Arrays.asList(new String[]{"export"}));
// "WITH_DEFAULTS" is a non-exported persistent table
project.setTableAsExportOnly("ALLOW_NULLS");
// and then project builder as normal
project.addPartitionInfo("ALLOW_NULLS", "PKEY");
project.addPartitionInfo("WITH_DEFAULTS", "PKEY");
project.addPartitionInfo("WITH_NULL_DEFAULTS", "PKEY");
project.addPartitionInfo("EXPRESSIONS_WITH_NULLS", "PKEY");
project.addPartitionInfo("EXPRESSIONS_NO_NULLS", "PKEY");
project.addPartitionInfo("JUMBO_ROW", "PKEY");
project.addProcedures(PROCEDURES2);
compile = config.compile(project);
MiscUtils.copyFile(project.getPathToDeployment(),
Configuration.getPathToCatalogForTest("export-ddl-sans-nonulls.xml"));
assertTrue(compile);
/*
* compile a catalog with an added table for add/drop tests
*/
config = new LocalCluster("export-ddl-addedtable.jar", 2, 3, 1,
BackendTarget.NATIVE_EE_JNI, LocalCluster.FailureState.ALL_RUNNING, true);
project = new VoltProjectBuilder();
project.addGroups(GROUPS);
project.addUsers(USERS);
- project.addSchema(TestSQLTypesSuite.class.getResource("sqltypessuite-ddl.sql"));
- project.addSchema(TestSQLTypesSuite.class.getResource("sqltypessuite-nonulls-ddl.sql"));
- project.addSchema(TestSQLTypesSuite.class.getResource("sqltypessuite-addedtable-ddl.sql"));
+ project.addSchema(TestSQLTypesSuite.class.getResource("sqltypessuite-export-ddl.sql"));
+ project.addSchema(TestSQLTypesSuite.class.getResource("sqltypessuite-nonulls-export-ddl.sql"));
+ project.addSchema(TestSQLTypesSuite.class.getResource("sqltypessuite-addedtable-export-ddl.sql"));
project.addExport("org.voltdb.export.processors.RawProcessor",
true /*enabled*/,
java.util.Arrays.asList(new String[]{"export"}));
// "WITH_DEFAULTS" is a non-exported persistent table
project.setTableAsExportOnly("ALLOW_NULLS"); // persistent table
project.setTableAsExportOnly("ADDED_TABLE"); // persistent table
project.setTableAsExportOnly("NO_NULLS"); // streamed table
// and then project builder as normal
project.addPartitionInfo("ALLOW_NULLS", "PKEY");
project.addPartitionInfo("ADDED_TABLE", "PKEY");
project.addPartitionInfo("WITH_DEFAULTS", "PKEY");
project.addPartitionInfo("WITH_NULL_DEFAULTS", "PKEY");
project.addPartitionInfo("EXPRESSIONS_WITH_NULLS", "PKEY");
project.addPartitionInfo("EXPRESSIONS_NO_NULLS", "PKEY");
project.addPartitionInfo("JUMBO_ROW", "PKEY");
project.addPartitionInfo("NO_NULLS", "PKEY");
project.addProcedures(PROCEDURES);
project.addProcedures(PROCEDURES3);
compile = config.compile(project);
MiscUtils.copyFile(project.getPathToDeployment(),
Configuration.getPathToCatalogForTest("export-ddl-addedtable.xml"));
assertTrue(compile);
return builder;
}
}
| false | true | static public junit.framework.Test suite() throws Exception
{
VoltServerConfig config;
final MultiConfigSuiteBuilder builder =
new MultiConfigSuiteBuilder(TestExportSuiteTestExportAndDroppedTableThenShutdown.class);
VoltProjectBuilder project = new VoltProjectBuilder();
project.setSecurityEnabled(true);
project.addGroups(GROUPS);
project.addUsers(USERS);
project.addSchema(TestSQLTypesSuite.class.getResource("sqltypessuite-ddl.sql"));
project.addSchema(TestSQLTypesSuite.class.getResource("sqltypessuite-nonulls-ddl.sql"));
project.addExport("org.voltdb.export.processors.RawProcessor",
true /*enabled*/,
java.util.Arrays.asList(new String[]{"export"}));
// "WITH_DEFAULTS" is a non-exported persistent table
project.setTableAsExportOnly("ALLOW_NULLS");
project.setTableAsExportOnly("NO_NULLS");
project.addPartitionInfo("NO_NULLS", "PKEY");
project.addPartitionInfo("ALLOW_NULLS", "PKEY");
project.addPartitionInfo("WITH_DEFAULTS", "PKEY");
project.addPartitionInfo("WITH_NULL_DEFAULTS", "PKEY");
project.addPartitionInfo("EXPRESSIONS_WITH_NULLS", "PKEY");
project.addPartitionInfo("EXPRESSIONS_NO_NULLS", "PKEY");
project.addPartitionInfo("JUMBO_ROW", "PKEY");
project.addProcedures(PROCEDURES);
// JNI, single server
// Use the cluster only config. Multiple topologies with the extra catalog for the
// Add drop tests is harder. Restrict to the single (complex) topology.
//
// config = new LocalSingleProcessServer("export-ddl.jar", 2,
// BackendTarget.NATIVE_EE_JNI);
// config.compile(project);
// builder.addServerConfig(config);
/*
* compile the catalog all tests start with
*/
config = new LocalCluster("export-ddl-cluster-rep.jar", 2, 3, 1,
BackendTarget.NATIVE_EE_JNI, LocalCluster.FailureState.ALL_RUNNING, true);
boolean compile = config.compile(project);
assertTrue(compile);
builder.addServerConfig(config);
/*
* compile a catalog without the NO_NULLS table for add/drop tests
*/
config = new LocalCluster("export-ddl-sans-nonulls.jar", 2, 3, 1,
BackendTarget.NATIVE_EE_JNI, LocalCluster.FailureState.ALL_RUNNING, true);
project = new VoltProjectBuilder();
project.addGroups(GROUPS);
project.addUsers(USERS);
project.addSchema(TestSQLTypesSuite.class.getResource("sqltypessuite-ddl.sql"));
project.addExport("org.voltdb.export.processors.RawProcessor",
true, //enabled
java.util.Arrays.asList(new String[]{"export"}));
// "WITH_DEFAULTS" is a non-exported persistent table
project.setTableAsExportOnly("ALLOW_NULLS");
// and then project builder as normal
project.addPartitionInfo("ALLOW_NULLS", "PKEY");
project.addPartitionInfo("WITH_DEFAULTS", "PKEY");
project.addPartitionInfo("WITH_NULL_DEFAULTS", "PKEY");
project.addPartitionInfo("EXPRESSIONS_WITH_NULLS", "PKEY");
project.addPartitionInfo("EXPRESSIONS_NO_NULLS", "PKEY");
project.addPartitionInfo("JUMBO_ROW", "PKEY");
project.addProcedures(PROCEDURES2);
compile = config.compile(project);
MiscUtils.copyFile(project.getPathToDeployment(),
Configuration.getPathToCatalogForTest("export-ddl-sans-nonulls.xml"));
assertTrue(compile);
/*
* compile a catalog with an added table for add/drop tests
*/
config = new LocalCluster("export-ddl-addedtable.jar", 2, 3, 1,
BackendTarget.NATIVE_EE_JNI, LocalCluster.FailureState.ALL_RUNNING, true);
project = new VoltProjectBuilder();
project.addGroups(GROUPS);
project.addUsers(USERS);
project.addSchema(TestSQLTypesSuite.class.getResource("sqltypessuite-ddl.sql"));
project.addSchema(TestSQLTypesSuite.class.getResource("sqltypessuite-nonulls-ddl.sql"));
project.addSchema(TestSQLTypesSuite.class.getResource("sqltypessuite-addedtable-ddl.sql"));
project.addExport("org.voltdb.export.processors.RawProcessor",
true /*enabled*/,
java.util.Arrays.asList(new String[]{"export"}));
// "WITH_DEFAULTS" is a non-exported persistent table
project.setTableAsExportOnly("ALLOW_NULLS"); // persistent table
project.setTableAsExportOnly("ADDED_TABLE"); // persistent table
project.setTableAsExportOnly("NO_NULLS"); // streamed table
// and then project builder as normal
project.addPartitionInfo("ALLOW_NULLS", "PKEY");
project.addPartitionInfo("ADDED_TABLE", "PKEY");
project.addPartitionInfo("WITH_DEFAULTS", "PKEY");
project.addPartitionInfo("WITH_NULL_DEFAULTS", "PKEY");
project.addPartitionInfo("EXPRESSIONS_WITH_NULLS", "PKEY");
project.addPartitionInfo("EXPRESSIONS_NO_NULLS", "PKEY");
project.addPartitionInfo("JUMBO_ROW", "PKEY");
project.addPartitionInfo("NO_NULLS", "PKEY");
project.addProcedures(PROCEDURES);
project.addProcedures(PROCEDURES3);
compile = config.compile(project);
MiscUtils.copyFile(project.getPathToDeployment(),
Configuration.getPathToCatalogForTest("export-ddl-addedtable.xml"));
assertTrue(compile);
return builder;
}
| static public junit.framework.Test suite() throws Exception
{
VoltServerConfig config;
final MultiConfigSuiteBuilder builder =
new MultiConfigSuiteBuilder(TestExportSuiteTestExportAndDroppedTableThenShutdown.class);
VoltProjectBuilder project = new VoltProjectBuilder();
project.setSecurityEnabled(true);
project.addGroups(GROUPS);
project.addUsers(USERS);
project.addSchema(TestSQLTypesSuite.class.getResource("sqltypessuite-export-ddl.sql"));
project.addSchema(TestSQLTypesSuite.class.getResource("sqltypessuite-nonulls-export-ddl.sql"));
project.addExport("org.voltdb.export.processors.RawProcessor",
true /*enabled*/,
java.util.Arrays.asList(new String[]{"export"}));
// "WITH_DEFAULTS" is a non-exported persistent table
project.setTableAsExportOnly("ALLOW_NULLS");
project.setTableAsExportOnly("NO_NULLS");
project.addPartitionInfo("NO_NULLS", "PKEY");
project.addPartitionInfo("ALLOW_NULLS", "PKEY");
project.addPartitionInfo("WITH_DEFAULTS", "PKEY");
project.addPartitionInfo("WITH_NULL_DEFAULTS", "PKEY");
project.addPartitionInfo("EXPRESSIONS_WITH_NULLS", "PKEY");
project.addPartitionInfo("EXPRESSIONS_NO_NULLS", "PKEY");
project.addPartitionInfo("JUMBO_ROW", "PKEY");
project.addProcedures(PROCEDURES);
// JNI, single server
// Use the cluster only config. Multiple topologies with the extra catalog for the
// Add drop tests is harder. Restrict to the single (complex) topology.
//
// config = new LocalSingleProcessServer("export-ddl.jar", 2,
// BackendTarget.NATIVE_EE_JNI);
// config.compile(project);
// builder.addServerConfig(config);
/*
* compile the catalog all tests start with
*/
config = new LocalCluster("export-ddl-cluster-rep.jar", 2, 3, 1,
BackendTarget.NATIVE_EE_JNI, LocalCluster.FailureState.ALL_RUNNING, true);
boolean compile = config.compile(project);
assertTrue(compile);
builder.addServerConfig(config);
/*
* compile a catalog without the NO_NULLS table for add/drop tests
*/
config = new LocalCluster("export-ddl-sans-nonulls.jar", 2, 3, 1,
BackendTarget.NATIVE_EE_JNI, LocalCluster.FailureState.ALL_RUNNING, true);
project = new VoltProjectBuilder();
project.addGroups(GROUPS);
project.addUsers(USERS);
project.addSchema(TestSQLTypesSuite.class.getResource("sqltypessuite-export-ddl.sql"));
project.addExport("org.voltdb.export.processors.RawProcessor",
true, //enabled
java.util.Arrays.asList(new String[]{"export"}));
// "WITH_DEFAULTS" is a non-exported persistent table
project.setTableAsExportOnly("ALLOW_NULLS");
// and then project builder as normal
project.addPartitionInfo("ALLOW_NULLS", "PKEY");
project.addPartitionInfo("WITH_DEFAULTS", "PKEY");
project.addPartitionInfo("WITH_NULL_DEFAULTS", "PKEY");
project.addPartitionInfo("EXPRESSIONS_WITH_NULLS", "PKEY");
project.addPartitionInfo("EXPRESSIONS_NO_NULLS", "PKEY");
project.addPartitionInfo("JUMBO_ROW", "PKEY");
project.addProcedures(PROCEDURES2);
compile = config.compile(project);
MiscUtils.copyFile(project.getPathToDeployment(),
Configuration.getPathToCatalogForTest("export-ddl-sans-nonulls.xml"));
assertTrue(compile);
/*
* compile a catalog with an added table for add/drop tests
*/
config = new LocalCluster("export-ddl-addedtable.jar", 2, 3, 1,
BackendTarget.NATIVE_EE_JNI, LocalCluster.FailureState.ALL_RUNNING, true);
project = new VoltProjectBuilder();
project.addGroups(GROUPS);
project.addUsers(USERS);
project.addSchema(TestSQLTypesSuite.class.getResource("sqltypessuite-export-ddl.sql"));
project.addSchema(TestSQLTypesSuite.class.getResource("sqltypessuite-nonulls-export-ddl.sql"));
project.addSchema(TestSQLTypesSuite.class.getResource("sqltypessuite-addedtable-export-ddl.sql"));
project.addExport("org.voltdb.export.processors.RawProcessor",
true /*enabled*/,
java.util.Arrays.asList(new String[]{"export"}));
// "WITH_DEFAULTS" is a non-exported persistent table
project.setTableAsExportOnly("ALLOW_NULLS"); // persistent table
project.setTableAsExportOnly("ADDED_TABLE"); // persistent table
project.setTableAsExportOnly("NO_NULLS"); // streamed table
// and then project builder as normal
project.addPartitionInfo("ALLOW_NULLS", "PKEY");
project.addPartitionInfo("ADDED_TABLE", "PKEY");
project.addPartitionInfo("WITH_DEFAULTS", "PKEY");
project.addPartitionInfo("WITH_NULL_DEFAULTS", "PKEY");
project.addPartitionInfo("EXPRESSIONS_WITH_NULLS", "PKEY");
project.addPartitionInfo("EXPRESSIONS_NO_NULLS", "PKEY");
project.addPartitionInfo("JUMBO_ROW", "PKEY");
project.addPartitionInfo("NO_NULLS", "PKEY");
project.addProcedures(PROCEDURES);
project.addProcedures(PROCEDURES3);
compile = config.compile(project);
MiscUtils.copyFile(project.getPathToDeployment(),
Configuration.getPathToCatalogForTest("export-ddl-addedtable.xml"));
assertTrue(compile);
return builder;
}
|
diff --git a/src/BinaryTree.java b/src/BinaryTree.java
index a1fa5b9..24c44b7 100644
--- a/src/BinaryTree.java
+++ b/src/BinaryTree.java
@@ -1,166 +1,166 @@
/**
* User: Gifflen
* Child = [2i+1] [2i+2]
* Parent = [(i-1)/2]
*/
public class BinaryTree<E> {
final private int LEFT = 1;
final private int RIGHT = 2;
final private int[] BRANCHES = {LEFT,RIGHT};
//private E[] arrayContainer;
private Object[] arrayContainer;
private Object[] branchData;
public BinaryTree() {
arrayContainer = new Object[10];
}
public void getDataAtIndex(int index){
E node = getData(index);
branchData = getBranches(index);
if (node!=null){
System.out.println(" "+node+" ");
System.out.println(" / \\");
for(Object data: branchData)
System.out.print(data+" ");
System.out.println();
}else{
- System.out.println("Tree Does not exit");
+ System.out.println("Tree Does not exist");
}
}
public E getData(int index){
try{
return (E) arrayContainer[index];
}catch (ArrayIndexOutOfBoundsException e){
return null;
}
}
private Object[] getBranches(int index){
branchData = new Object[BRANCHES.length];
for(int side: BRANCHES){
E data = getData(2*index+side);
branchData[side-1]= data;
}
return branchData;
}
private static int getIndex(int index,int side){
return (2*index+side);
}
public int getLeftIndex(int index){
return getIndex(index, LEFT);
}
public int getRightIndex(int index){
return getIndex(index,RIGHT);
}
public E getLeftData(int index){
return getData(this.getLeftIndex(index));
}
public E getRightData(int index){
return getData(this.getRightIndex(index));
}
private int getExtremeIndex(int index,int side){
int branchIndex = getIndex(index,side);
E data = this.getData(branchIndex);
if (data!=null){
return getExtremeIndex(branchIndex, side);
}else{
return index;
}
}
public int getLeftMostIndex(int index){
return this.getExtremeIndex(index, LEFT);
}
public int getRightMostIndex(int index){
return this.getExtremeIndex(index, RIGHT);
}
public E getLeftMostData(int index){
return getData(this.getLeftMostIndex(index));
}
public E getRightMostData(int index){
return getData(this.getRightMostIndex(index));
}
public boolean isLeaf(int index){
return (getLeftData(index) == null) && (getRightData(index) == null);
}
//TODO: move data back up the tree if a removal is occurring.
private void removeIndex(int index){
arrayContainer[index] = null;
}
public void removeLeft(int index){
removeIndex(getLeftIndex(index));
}
public void removeRight(int index){
removeIndex(getRightIndex(index));
}
public void removeLeftMost(int index){
removeIndex(getLeftMostIndex(index));
}
public void removeRightMost(int index){
removeIndex(getRightMostIndex(index));
}
public void addNode(E data){
boolean added=false;
for(int i = 0; i<arrayContainer.length;i++){
if (arrayContainer[i]==null){
arrayContainer[i] = data;
added = true;
break;
}
}
if(!added){
expandSize();
this.addNode(data);
}
}
public void removeLast(){
for(int i = arrayContainer.length-1; i>=0;i--){
if (arrayContainer[i]!=null){
arrayContainer[i]=null;
break;
}
}
}
private void expandSize(){
Object[] newContainer = new Object[arrayContainer.length*2] ;
System.arraycopy(arrayContainer, 0, newContainer, 0, arrayContainer.length);
arrayContainer = newContainer;
}
public int getDepth(){
int depth = 0;
int counter = 1;
while(counter<=arrayContainer.length&&arrayContainer[counter-1]!=null){
counter+=counter;
depth++;
}
return depth;
}
public void totalTreeCall(){
}
}
| true | true | public void getDataAtIndex(int index){
E node = getData(index);
branchData = getBranches(index);
if (node!=null){
System.out.println(" "+node+" ");
System.out.println(" / \\");
for(Object data: branchData)
System.out.print(data+" ");
System.out.println();
}else{
System.out.println("Tree Does not exit");
}
}
| public void getDataAtIndex(int index){
E node = getData(index);
branchData = getBranches(index);
if (node!=null){
System.out.println(" "+node+" ");
System.out.println(" / \\");
for(Object data: branchData)
System.out.print(data+" ");
System.out.println();
}else{
System.out.println("Tree Does not exist");
}
}
|
diff --git a/apps/routerconsole/java/src/net/i2p/router/web/ConfigTunnelsHelper.java b/apps/routerconsole/java/src/net/i2p/router/web/ConfigTunnelsHelper.java
index fe17164d3..98141771b 100644
--- a/apps/routerconsole/java/src/net/i2p/router/web/ConfigTunnelsHelper.java
+++ b/apps/routerconsole/java/src/net/i2p/router/web/ConfigTunnelsHelper.java
@@ -1,198 +1,198 @@
package net.i2p.router.web;
import java.util.Iterator;
import java.util.Properties;
import java.util.Set;
import net.i2p.data.Destination;
import net.i2p.router.RouterContext;
import net.i2p.router.TunnelPoolSettings;
public class ConfigTunnelsHelper {
private RouterContext _context;
/**
* Configure this bean to query a particular router context
*
* @param contextId begging few characters of the routerHash, or null to pick
* the first one we come across.
*/
public void setContextId(String contextId) {
try {
_context = ContextHelper.getContext(contextId);
} catch (Throwable t) {
t.printStackTrace();
}
}
public ConfigTunnelsHelper() {}
public String getForm() {
StringBuffer buf = new StringBuffer(1024);
buf.append("<table border=\"1\">\n");
TunnelPoolSettings exploratoryIn = _context.tunnelManager().getInboundSettings();
TunnelPoolSettings exploratoryOut = _context.tunnelManager().getOutboundSettings();
buf.append("<input type=\"hidden\" name=\"pool.0\" value=\"exploratory\" >");
renderForm(buf, 0, "exploratory", "Exploratory tunnels", exploratoryIn, exploratoryOut);
int cur = 1;
Set clients = _context.clientManager().listClients();
for (Iterator iter = clients.iterator(); iter.hasNext(); ) {
Destination dest = (Destination)iter.next();
TunnelPoolSettings in = _context.tunnelManager().getInboundSettings(dest.calculateHash());
TunnelPoolSettings out = _context.tunnelManager().getOutboundSettings(dest.calculateHash());
if ( (in == null) || (out == null) ) continue;
String name = in.getDestinationNickname();
if (name == null)
name = out.getDestinationNickname();
if (name == null)
name = dest.calculateHash().toBase64().substring(0,6);
String prefix = dest.calculateHash().toBase64().substring(0,4);
buf.append("<input type=\"hidden\" name=\"pool.").append(cur).append("\" value=\"");
buf.append(dest.calculateHash().toBase64()).append("\" >");
renderForm(buf, cur, prefix, "Client tunnels for " + name, in, out);
cur++;
}
buf.append("</table>\n");
return buf.toString();
}
private static final int WARN_LENGTH = 4;
private static final int MAX_LENGTH = 4;
private static final int MAX_QUANTITY = 3;
private static final int MAX_VARIANCE = 2;
private static final int MIN_NEG_VARIANCE = -1;
private void renderForm(StringBuffer buf, int index, String prefix, String name, TunnelPoolSettings in, TunnelPoolSettings out) {
buf.append("<tr><td colspan=\"3\"><b><a name=\"").append(prefix).append("\">");
buf.append(name).append("</a></b></td></tr>\n");
if (in.getLength() <= 0 ||
in.getLength() + in.getLengthVariance() <= 0 ||
out.getLength() <= 0 ||
out.getLength() + out.getLengthVariance() <= 0)
buf.append("<tr><td colspan=\"3\"><font color=\"red\">ANONYMITY WARNING - Settings include 0-hop tunnels</font></td></tr>");
if (in.getLength() + Math.abs(in.getLengthVariance()) >= WARN_LENGTH ||
out.getLength() + Math.abs(out.getLengthVariance()) >= WARN_LENGTH)
buf.append("<tr><td colspan=\"3\"><font color=\"red\">PERFORMANCE WARNING - Settings include very long tunnels</font></td></tr>");
buf.append("<tr><td></td><td><b>Inbound</b></td><td><b>Outbound</b></td></tr>\n");
// tunnel depth
buf.append("<tr><td>Depth</td>\n");
buf.append("<td><select name=\"").append(index).append(".depthInbound\">\n");
int now = in.getLength();
renderOptions(buf, 0, MAX_LENGTH, now, "", "hop");
if (now > MAX_LENGTH)
renderOptions(buf, now, now, now, "", "hop");
buf.append("</select></td>\n");
buf.append("<td><select name=\"").append(index).append(".depthOutbound\">\n");
now = out.getLength();
renderOptions(buf, 0, MAX_LENGTH, now, "", "hop");
if (now > MAX_LENGTH)
renderOptions(buf, now, now, now, "", "hop");
buf.append("</select></td>\n");
buf.append("</tr>\n");
// tunnel depth variance
buf.append("<tr><td>Randomization</td>\n");
buf.append("<td><select name=\"").append(index).append(".varianceInbound\">\n");
now = in.getLengthVariance();
renderOptions(buf, 0, 0, now, "", "hop");
renderOptions(buf, 1, MAX_VARIANCE, now, "+ 0-", "hop");
renderOptions(buf, MIN_NEG_VARIANCE, -1, now, "+/- 0", "hop");
if (now > MAX_VARIANCE)
renderOptions(buf, now, now, now, "+ 0-", "hop");
else if (now < MIN_NEG_VARIANCE)
renderOptions(buf, now, now, now, "+/- 0", "hop");
buf.append("</select></td>\n");
buf.append("<td><select name=\"").append(index).append(".varianceOutbound\">\n");
now = out.getLengthVariance();
renderOptions(buf, 0, 0, now, "", "hop");
renderOptions(buf, 1, MAX_VARIANCE, now, "+ 0-", "hop");
renderOptions(buf, MIN_NEG_VARIANCE, -1, now, "+/- 0", "hop");
if (now > MAX_VARIANCE)
renderOptions(buf, now, now, now, "+ 0-", "hop");
else if (now < MIN_NEG_VARIANCE)
renderOptions(buf, now, now, now, "+/- 0", "hop");
buf.append("</select></td>\n");
// tunnel quantity
buf.append("<tr><td>Quantity</td>\n");
buf.append("<td><select name=\"").append(index).append(".quantityInbound\">\n");
now = in.getQuantity();
renderOptions(buf, 1, MAX_QUANTITY, now, "", "tunnel");
if (now > MAX_QUANTITY)
renderOptions(buf, now, now, now, "", "tunnel");
buf.append("</select></td>\n");
buf.append("<td><select name=\"").append(index).append(".quantityOutbound\">\n");
now = out.getQuantity();
renderOptions(buf, 1, MAX_QUANTITY, now, "", "tunnel");
if (now > MAX_QUANTITY)
renderOptions(buf, now, now, now, "", "tunnel");
buf.append("</select></td>\n");
buf.append("</tr>\n");
// tunnel backup quantity
buf.append("<tr><td>Backup quantity</td>\n");
buf.append("<td><select name=\"").append(index).append(".backupInbound\">\n");
now = in.getBackupQuantity();
renderOptions(buf, 0, MAX_QUANTITY, now, "", "tunnel");
if (now > MAX_QUANTITY)
renderOptions(buf, now, now, now, "", "tunnel");
buf.append("</select></td>\n");
buf.append("<td><select name=\"").append(index).append(".backupOutbound\">\n");
- now = in.getBackupQuantity();
+ now = out.getBackupQuantity();
renderOptions(buf, 0, MAX_QUANTITY, now, "", "tunnel");
if (now > MAX_QUANTITY)
renderOptions(buf, now, now, now, "", "tunnel");
buf.append("</select></td>\n");
buf.append("</tr>\n");
// custom options
buf.append("<tr><td>Inbound options:</td>\n");
buf.append("<td colspan=\"2\"><input name=\"").append(index);
buf.append(".inboundOptions\" type=\"text\" size=\"40\" ");
buf.append("value=\"");
Properties props = in.getUnknownOptions();
for (Iterator iter = props.keySet().iterator(); iter.hasNext(); ) {
String prop = (String)iter.next();
String val = (String)props.getProperty(prop);
buf.append(prop).append("=").append(val).append(" ");
}
buf.append("\"/></td></tr>\n");
buf.append("<tr><td>Outbound options:</td>\n");
buf.append("<td colspan=\"2\"><input name=\"").append(index);
buf.append(".outboundOptions\" type=\"text\" size=\"40\" ");
buf.append("value=\"");
props = in.getUnknownOptions();
for (Iterator iter = props.keySet().iterator(); iter.hasNext(); ) {
String prop = (String)iter.next();
String val = (String)props.getProperty(prop);
buf.append(prop).append("=").append(val).append(" ");
}
buf.append("\"/></td></tr>\n");
buf.append("<tr><td colspan=\"3\"><hr /></td></tr>\n");
}
private void renderOptions(StringBuffer buf, int min, int max, int now, String prefix, String name) {
for (int i = min; i <= max; i++) {
buf.append("<option value=\"").append(i).append("\" ");
if (i == now)
buf.append("selected=\"true\" ");
buf.append(">").append(prefix).append(i).append(' ').append(name);
if (i != 1 && i != -1)
buf.append('s');
buf.append("</option>\n");
}
}
}
| true | true | private void renderForm(StringBuffer buf, int index, String prefix, String name, TunnelPoolSettings in, TunnelPoolSettings out) {
buf.append("<tr><td colspan=\"3\"><b><a name=\"").append(prefix).append("\">");
buf.append(name).append("</a></b></td></tr>\n");
if (in.getLength() <= 0 ||
in.getLength() + in.getLengthVariance() <= 0 ||
out.getLength() <= 0 ||
out.getLength() + out.getLengthVariance() <= 0)
buf.append("<tr><td colspan=\"3\"><font color=\"red\">ANONYMITY WARNING - Settings include 0-hop tunnels</font></td></tr>");
if (in.getLength() + Math.abs(in.getLengthVariance()) >= WARN_LENGTH ||
out.getLength() + Math.abs(out.getLengthVariance()) >= WARN_LENGTH)
buf.append("<tr><td colspan=\"3\"><font color=\"red\">PERFORMANCE WARNING - Settings include very long tunnels</font></td></tr>");
buf.append("<tr><td></td><td><b>Inbound</b></td><td><b>Outbound</b></td></tr>\n");
// tunnel depth
buf.append("<tr><td>Depth</td>\n");
buf.append("<td><select name=\"").append(index).append(".depthInbound\">\n");
int now = in.getLength();
renderOptions(buf, 0, MAX_LENGTH, now, "", "hop");
if (now > MAX_LENGTH)
renderOptions(buf, now, now, now, "", "hop");
buf.append("</select></td>\n");
buf.append("<td><select name=\"").append(index).append(".depthOutbound\">\n");
now = out.getLength();
renderOptions(buf, 0, MAX_LENGTH, now, "", "hop");
if (now > MAX_LENGTH)
renderOptions(buf, now, now, now, "", "hop");
buf.append("</select></td>\n");
buf.append("</tr>\n");
// tunnel depth variance
buf.append("<tr><td>Randomization</td>\n");
buf.append("<td><select name=\"").append(index).append(".varianceInbound\">\n");
now = in.getLengthVariance();
renderOptions(buf, 0, 0, now, "", "hop");
renderOptions(buf, 1, MAX_VARIANCE, now, "+ 0-", "hop");
renderOptions(buf, MIN_NEG_VARIANCE, -1, now, "+/- 0", "hop");
if (now > MAX_VARIANCE)
renderOptions(buf, now, now, now, "+ 0-", "hop");
else if (now < MIN_NEG_VARIANCE)
renderOptions(buf, now, now, now, "+/- 0", "hop");
buf.append("</select></td>\n");
buf.append("<td><select name=\"").append(index).append(".varianceOutbound\">\n");
now = out.getLengthVariance();
renderOptions(buf, 0, 0, now, "", "hop");
renderOptions(buf, 1, MAX_VARIANCE, now, "+ 0-", "hop");
renderOptions(buf, MIN_NEG_VARIANCE, -1, now, "+/- 0", "hop");
if (now > MAX_VARIANCE)
renderOptions(buf, now, now, now, "+ 0-", "hop");
else if (now < MIN_NEG_VARIANCE)
renderOptions(buf, now, now, now, "+/- 0", "hop");
buf.append("</select></td>\n");
// tunnel quantity
buf.append("<tr><td>Quantity</td>\n");
buf.append("<td><select name=\"").append(index).append(".quantityInbound\">\n");
now = in.getQuantity();
renderOptions(buf, 1, MAX_QUANTITY, now, "", "tunnel");
if (now > MAX_QUANTITY)
renderOptions(buf, now, now, now, "", "tunnel");
buf.append("</select></td>\n");
buf.append("<td><select name=\"").append(index).append(".quantityOutbound\">\n");
now = out.getQuantity();
renderOptions(buf, 1, MAX_QUANTITY, now, "", "tunnel");
if (now > MAX_QUANTITY)
renderOptions(buf, now, now, now, "", "tunnel");
buf.append("</select></td>\n");
buf.append("</tr>\n");
// tunnel backup quantity
buf.append("<tr><td>Backup quantity</td>\n");
buf.append("<td><select name=\"").append(index).append(".backupInbound\">\n");
now = in.getBackupQuantity();
renderOptions(buf, 0, MAX_QUANTITY, now, "", "tunnel");
if (now > MAX_QUANTITY)
renderOptions(buf, now, now, now, "", "tunnel");
buf.append("</select></td>\n");
buf.append("<td><select name=\"").append(index).append(".backupOutbound\">\n");
now = in.getBackupQuantity();
renderOptions(buf, 0, MAX_QUANTITY, now, "", "tunnel");
if (now > MAX_QUANTITY)
renderOptions(buf, now, now, now, "", "tunnel");
buf.append("</select></td>\n");
buf.append("</tr>\n");
// custom options
buf.append("<tr><td>Inbound options:</td>\n");
buf.append("<td colspan=\"2\"><input name=\"").append(index);
buf.append(".inboundOptions\" type=\"text\" size=\"40\" ");
buf.append("value=\"");
Properties props = in.getUnknownOptions();
for (Iterator iter = props.keySet().iterator(); iter.hasNext(); ) {
String prop = (String)iter.next();
String val = (String)props.getProperty(prop);
buf.append(prop).append("=").append(val).append(" ");
}
buf.append("\"/></td></tr>\n");
buf.append("<tr><td>Outbound options:</td>\n");
buf.append("<td colspan=\"2\"><input name=\"").append(index);
buf.append(".outboundOptions\" type=\"text\" size=\"40\" ");
buf.append("value=\"");
props = in.getUnknownOptions();
for (Iterator iter = props.keySet().iterator(); iter.hasNext(); ) {
String prop = (String)iter.next();
String val = (String)props.getProperty(prop);
buf.append(prop).append("=").append(val).append(" ");
}
buf.append("\"/></td></tr>\n");
buf.append("<tr><td colspan=\"3\"><hr /></td></tr>\n");
}
| private void renderForm(StringBuffer buf, int index, String prefix, String name, TunnelPoolSettings in, TunnelPoolSettings out) {
buf.append("<tr><td colspan=\"3\"><b><a name=\"").append(prefix).append("\">");
buf.append(name).append("</a></b></td></tr>\n");
if (in.getLength() <= 0 ||
in.getLength() + in.getLengthVariance() <= 0 ||
out.getLength() <= 0 ||
out.getLength() + out.getLengthVariance() <= 0)
buf.append("<tr><td colspan=\"3\"><font color=\"red\">ANONYMITY WARNING - Settings include 0-hop tunnels</font></td></tr>");
if (in.getLength() + Math.abs(in.getLengthVariance()) >= WARN_LENGTH ||
out.getLength() + Math.abs(out.getLengthVariance()) >= WARN_LENGTH)
buf.append("<tr><td colspan=\"3\"><font color=\"red\">PERFORMANCE WARNING - Settings include very long tunnels</font></td></tr>");
buf.append("<tr><td></td><td><b>Inbound</b></td><td><b>Outbound</b></td></tr>\n");
// tunnel depth
buf.append("<tr><td>Depth</td>\n");
buf.append("<td><select name=\"").append(index).append(".depthInbound\">\n");
int now = in.getLength();
renderOptions(buf, 0, MAX_LENGTH, now, "", "hop");
if (now > MAX_LENGTH)
renderOptions(buf, now, now, now, "", "hop");
buf.append("</select></td>\n");
buf.append("<td><select name=\"").append(index).append(".depthOutbound\">\n");
now = out.getLength();
renderOptions(buf, 0, MAX_LENGTH, now, "", "hop");
if (now > MAX_LENGTH)
renderOptions(buf, now, now, now, "", "hop");
buf.append("</select></td>\n");
buf.append("</tr>\n");
// tunnel depth variance
buf.append("<tr><td>Randomization</td>\n");
buf.append("<td><select name=\"").append(index).append(".varianceInbound\">\n");
now = in.getLengthVariance();
renderOptions(buf, 0, 0, now, "", "hop");
renderOptions(buf, 1, MAX_VARIANCE, now, "+ 0-", "hop");
renderOptions(buf, MIN_NEG_VARIANCE, -1, now, "+/- 0", "hop");
if (now > MAX_VARIANCE)
renderOptions(buf, now, now, now, "+ 0-", "hop");
else if (now < MIN_NEG_VARIANCE)
renderOptions(buf, now, now, now, "+/- 0", "hop");
buf.append("</select></td>\n");
buf.append("<td><select name=\"").append(index).append(".varianceOutbound\">\n");
now = out.getLengthVariance();
renderOptions(buf, 0, 0, now, "", "hop");
renderOptions(buf, 1, MAX_VARIANCE, now, "+ 0-", "hop");
renderOptions(buf, MIN_NEG_VARIANCE, -1, now, "+/- 0", "hop");
if (now > MAX_VARIANCE)
renderOptions(buf, now, now, now, "+ 0-", "hop");
else if (now < MIN_NEG_VARIANCE)
renderOptions(buf, now, now, now, "+/- 0", "hop");
buf.append("</select></td>\n");
// tunnel quantity
buf.append("<tr><td>Quantity</td>\n");
buf.append("<td><select name=\"").append(index).append(".quantityInbound\">\n");
now = in.getQuantity();
renderOptions(buf, 1, MAX_QUANTITY, now, "", "tunnel");
if (now > MAX_QUANTITY)
renderOptions(buf, now, now, now, "", "tunnel");
buf.append("</select></td>\n");
buf.append("<td><select name=\"").append(index).append(".quantityOutbound\">\n");
now = out.getQuantity();
renderOptions(buf, 1, MAX_QUANTITY, now, "", "tunnel");
if (now > MAX_QUANTITY)
renderOptions(buf, now, now, now, "", "tunnel");
buf.append("</select></td>\n");
buf.append("</tr>\n");
// tunnel backup quantity
buf.append("<tr><td>Backup quantity</td>\n");
buf.append("<td><select name=\"").append(index).append(".backupInbound\">\n");
now = in.getBackupQuantity();
renderOptions(buf, 0, MAX_QUANTITY, now, "", "tunnel");
if (now > MAX_QUANTITY)
renderOptions(buf, now, now, now, "", "tunnel");
buf.append("</select></td>\n");
buf.append("<td><select name=\"").append(index).append(".backupOutbound\">\n");
now = out.getBackupQuantity();
renderOptions(buf, 0, MAX_QUANTITY, now, "", "tunnel");
if (now > MAX_QUANTITY)
renderOptions(buf, now, now, now, "", "tunnel");
buf.append("</select></td>\n");
buf.append("</tr>\n");
// custom options
buf.append("<tr><td>Inbound options:</td>\n");
buf.append("<td colspan=\"2\"><input name=\"").append(index);
buf.append(".inboundOptions\" type=\"text\" size=\"40\" ");
buf.append("value=\"");
Properties props = in.getUnknownOptions();
for (Iterator iter = props.keySet().iterator(); iter.hasNext(); ) {
String prop = (String)iter.next();
String val = (String)props.getProperty(prop);
buf.append(prop).append("=").append(val).append(" ");
}
buf.append("\"/></td></tr>\n");
buf.append("<tr><td>Outbound options:</td>\n");
buf.append("<td colspan=\"2\"><input name=\"").append(index);
buf.append(".outboundOptions\" type=\"text\" size=\"40\" ");
buf.append("value=\"");
props = in.getUnknownOptions();
for (Iterator iter = props.keySet().iterator(); iter.hasNext(); ) {
String prop = (String)iter.next();
String val = (String)props.getProperty(prop);
buf.append(prop).append("=").append(val).append(" ");
}
buf.append("\"/></td></tr>\n");
buf.append("<tr><td colspan=\"3\"><hr /></td></tr>\n");
}
|
diff --git a/asm/src/org/aspectj/asm/internal/JDTLikeHandleProvider.java b/asm/src/org/aspectj/asm/internal/JDTLikeHandleProvider.java
index 7c8e6253f..c20428d67 100644
--- a/asm/src/org/aspectj/asm/internal/JDTLikeHandleProvider.java
+++ b/asm/src/org/aspectj/asm/internal/JDTLikeHandleProvider.java
@@ -1,322 +1,322 @@
/********************************************************************
* Copyright (c) 2006 Contributors. All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Eclipse Public License v1.0
* which accompanies this distribution and is available at
* http://eclipse.org/legal/epl-v10.html
*
* Contributors: IBM Corporation - initial API and implementation
* Helen Hawkins - initial version
*******************************************************************/
package org.aspectj.asm.internal;
import java.io.File;
import java.util.Iterator;
import java.util.List;
import org.aspectj.asm.AsmManager;
import org.aspectj.asm.IElementHandleProvider;
import org.aspectj.asm.IProgramElement;
import org.aspectj.bridge.ISourceLocation;
/**
* Creates JDT-like handles, for example
*
* method with string argument: <tjp{Demo.java[Demo~main~\[QString; method with generic argument:
* <pkg{MyClass.java[MyClass~myMethod~QList\<QString;>; an aspect: <pkg*A1.aj}A1 advice with Integer arg:
* <pkg*A8.aj}A8&afterReturning&QInteger; method call: <pkg*A10.aj[C~m1?method-call(void pkg.C.m2())
*
*/
public class JDTLikeHandleProvider implements IElementHandleProvider {
private final AsmManager asm;
// Need to keep our own count of the number of initializers
// because this information cannot be gained from the ipe.
private int initializerCounter = 0;
private final char[] empty = new char[] {};
private final char[] countDelim = new char[] { HandleProviderDelimiter.COUNT.getDelimiter() };
private final String backslash = "\\";
private final String emptyString = "";
public JDTLikeHandleProvider(AsmManager asm) {
this.asm = asm;
}
public String createHandleIdentifier(IProgramElement ipe) {
// AjBuildManager.setupModel --> top of the tree is either
// <root> or the .lst file
if (ipe == null || (ipe.getKind().equals(IProgramElement.Kind.FILE_JAVA) && ipe.getName().equals("<root>"))) {
return "";
} else if (ipe.getHandleIdentifier(false) != null) {
// have already created the handle for this ipe
// therefore just return it
return ipe.getHandleIdentifier();
} else if (ipe.getKind().equals(IProgramElement.Kind.FILE_LST)) {
String configFile = asm.getHierarchy().getConfigFile();
int start = configFile.lastIndexOf(File.separator);
int end = configFile.lastIndexOf(".lst");
if (end != -1) {
configFile = configFile.substring(start + 1, end);
} else {
configFile = new StringBuffer("=").append(configFile.substring(start + 1)).toString();
}
ipe.setHandleIdentifier(configFile);
return configFile;
} else if (ipe.getKind() == IProgramElement.Kind.SOURCE_FOLDER) {
StringBuffer sb = new StringBuffer();
sb.append(createHandleIdentifier(ipe.getParent())).append("/");
sb.append(ipe.getName());
String handle = sb.toString();
ipe.setHandleIdentifier(handle);
return handle;
}
IProgramElement parent = ipe.getParent();
if (parent != null && parent.getKind().equals(IProgramElement.Kind.IMPORT_REFERENCE)) {
// want to miss out '#import declaration' in the handle
parent = ipe.getParent().getParent();
}
StringBuffer handle = new StringBuffer();
// add the handle for the parent
handle.append(createHandleIdentifier(parent));
// add the correct delimiter for this ipe
handle.append(HandleProviderDelimiter.getDelimiter(ipe));
// add the name and any parameters unless we're an initializer
// (initializer's names are '...')
if (!ipe.getKind().equals(IProgramElement.Kind.INITIALIZER)) {
if (ipe.getKind() == IProgramElement.Kind.CLASS && ipe.getName().endsWith("{..}")) {
// format: 'new Runnable() {..}' but its anon-y-mouse
// dont append anything, there may be a count to follow though (!<n>)
} else {
if (ipe.getKind() == IProgramElement.Kind.INTER_TYPE_CONSTRUCTOR) {
handle.append(ipe.getName()).append("_new").append(getParameters(ipe));
} else {
// if (ipe.getKind() == IProgramElement.Kind.PACKAGE && ipe.getName().equals("DEFAULT")) {
// // the delimiter will be in there, but skip the word DEFAULT as it is just a placeholder
// } else {
handle.append(ipe.getName()).append(getParameters(ipe));
}
// }
}
}
// add the count, for example '!2' if its the second ipe of its
// kind in the aspect
handle.append(getCount(ipe));
ipe.setHandleIdentifier(handle.toString());
return handle.toString();
}
private String getParameters(IProgramElement ipe) {
if (ipe.getParameterSignatures() == null || ipe.getParameterSignatures().isEmpty()) {
return "";
}
StringBuffer sb = new StringBuffer();
List parameterTypes = ipe.getParameterSignatures();
for (Iterator iter = parameterTypes.iterator(); iter.hasNext();) {
char[] element = (char[]) iter.next();
sb.append(HandleProviderDelimiter.getDelimiter(ipe));
if (element[0] == HandleProviderDelimiter.TYPE.getDelimiter()) {
// its an array
sb.append(HandleProviderDelimiter.ESCAPE.getDelimiter());
sb.append(HandleProviderDelimiter.TYPE.getDelimiter());
sb.append(NameConvertor.getTypeName(CharOperation.subarray(element, 1, element.length)));
} else if (element[0] == NameConvertor.PARAMETERIZED) {
// its a parameterized type
sb.append(NameConvertor.createShortName(element));
} else {
sb.append(NameConvertor.getTypeName(element));
}
}
return sb.toString();
}
/**
* Determine a count to be suffixed to the handle, this is only necessary for identical looking entries at the same level in the
* model (for example two anonymous class declarations). The format is !<n> where n will be greater than 2.
*
* @param ipe the program element for which the handle is being constructed
* @return a char suffix that will either be empty or of the form "!<n>"
*/
private char[] getCount(IProgramElement ipe) {
// TODO could optimize this code
char[] byteCodeName = ipe.getBytecodeName().toCharArray();
if (ipe.getKind().isDeclare()) {
int index = CharOperation.lastIndexOf('_', byteCodeName);
if (index != -1) {
return convertCount(CharOperation.subarray(byteCodeName, index + 1, byteCodeName.length));
}
} else if (ipe.getKind().equals(IProgramElement.Kind.ADVICE)) {
// Look at any peer advice
int count = 1;
List kids = ipe.getParent().getChildren();
String ipeSig = ipe.getBytecodeSignature();
for (Iterator iterator = kids.iterator(); iterator.hasNext();) {
IProgramElement object = (IProgramElement) iterator.next();
if (object.equals(ipe)) {
break;
}
if (object.getKind() == ipe.getKind()) {
if (object.getName().equals(ipe.getName())) {
String sig1 = object.getBytecodeSignature();
- if (sig1 == null && ipeSig == null || sig1.equals(ipeSig)) {
+ if (sig1 == null && ipeSig == null || (sig1 != null && sig1.equals(ipeSig))) {
String existingHandle = object.getHandleIdentifier();
int suffixPosition = existingHandle.indexOf('!');
if (suffixPosition != -1) {
count = new Integer(existingHandle.substring(suffixPosition + 1)).intValue() + 1;
} else {
if (count == 1) {
count = 2;
}
}
}
}
}
}
if (count > 1) {
return CharOperation.concat(countDelim, new Integer(count).toString().toCharArray());
}
} else if (ipe.getKind().equals(IProgramElement.Kind.INITIALIZER)) {
return String.valueOf(++initializerCounter).toCharArray();
} else if (ipe.getKind().equals(IProgramElement.Kind.CODE)) {
int index = CharOperation.lastIndexOf('!', byteCodeName);
if (index != -1) {
return convertCount(CharOperation.subarray(byteCodeName, index + 1, byteCodeName.length));
}
} else if (ipe.getKind() == IProgramElement.Kind.CLASS) {
// depends on previous children
int count = 1;
List kids = ipe.getParent().getChildren();
if (ipe.getName().endsWith("{..}")) {
// only depends on previous anonymous children, name irrelevant
for (Iterator iterator = kids.iterator(); iterator.hasNext();) {
IProgramElement object = (IProgramElement) iterator.next();
if (object.equals(ipe)) {
break;
}
if (object.getKind() == ipe.getKind()) {
if (object.getName().endsWith("{..}")) {
String existingHandle = object.getHandleIdentifier();
int suffixPosition = existingHandle.indexOf('!');
if (suffixPosition != -1) {
count = new Integer(existingHandle.substring(suffixPosition + 1)).intValue() + 1;
} else {
if (count == 1) {
count = 2;
}
}
}
}
}
} else {
for (Iterator iterator = kids.iterator(); iterator.hasNext();) {
IProgramElement object = (IProgramElement) iterator.next();
if (object.equals(ipe)) {
break;
}
if (object.getKind() == ipe.getKind()) {
if (object.getName().equals(ipe.getName())) {
String existingHandle = object.getHandleIdentifier();
int suffixPosition = existingHandle.indexOf('!');
if (suffixPosition != -1) {
count = new Integer(existingHandle.substring(suffixPosition + 1)).intValue() + 1;
} else {
if (count == 1) {
count = 2;
}
}
}
}
}
}
if (count > 1) {
return CharOperation.concat(countDelim, new Integer(count).toString().toCharArray());
}
}
return empty;
}
/**
* Only returns the count if it's not equal to 1
*/
private char[] convertCount(char[] c) {
if ((c.length == 1 && c[0] != ' ' && c[0] != '1') || c.length > 1) {
return CharOperation.concat(countDelim, c);
}
return empty;
}
public String getFileForHandle(String handle) {
IProgramElement node = asm.getHierarchy().getElement(handle);
if (node != null) {
return asm.getCanonicalFilePath(node.getSourceLocation().getSourceFile());
} else if (handle.charAt(0) == HandleProviderDelimiter.ASPECT_CU.getDelimiter()
|| handle.charAt(0) == HandleProviderDelimiter.COMPILATIONUNIT.getDelimiter()) {
// it's something like *MyAspect.aj or {MyClass.java. In other words
// it's a file node that's been created with no children and no
// parent
return backslash + handle.substring(1);
}
return emptyString;
}
public int getLineNumberForHandle(String handle) {
IProgramElement node = asm.getHierarchy().getElement(handle);
if (node != null) {
return node.getSourceLocation().getLine();
} else if (handle.charAt(0) == HandleProviderDelimiter.ASPECT_CU.getDelimiter()
|| handle.charAt(0) == HandleProviderDelimiter.COMPILATIONUNIT.getDelimiter()) {
// it's something like *MyAspect.aj or {MyClass.java. In other words
// it's a file node that's been created with no children and no
// parent
return 1;
}
return -1;
}
public int getOffSetForHandle(String handle) {
IProgramElement node = asm.getHierarchy().getElement(handle);
if (node != null) {
return node.getSourceLocation().getOffset();
} else if (handle.charAt(0) == HandleProviderDelimiter.ASPECT_CU.getDelimiter()
|| handle.charAt(0) == HandleProviderDelimiter.COMPILATIONUNIT.getDelimiter()) {
// it's something like *MyAspect.aj or {MyClass.java. In other words
// it's a file node that's been created with no children and no
// parent
return 0;
}
return -1;
}
public String createHandleIdentifier(ISourceLocation location) {
IProgramElement node = asm.getHierarchy().findElementForSourceLine(location);
if (node != null) {
return createHandleIdentifier(node);
}
return null;
}
public String createHandleIdentifier(File sourceFile, int line, int column, int offset) {
IProgramElement node = asm.getHierarchy().findElementForOffSet(sourceFile.getAbsolutePath(), line, offset);
if (node != null) {
return createHandleIdentifier(node);
}
return null;
}
public boolean dependsOnLocation() {
// handles are independent of soureLocations therefore return false
return false;
}
public void initialize() {
// reset the initializer count. This ensures we return the
// same handle as JDT for initializers.
initializerCounter = 0;
}
}
| true | true | private char[] getCount(IProgramElement ipe) {
// TODO could optimize this code
char[] byteCodeName = ipe.getBytecodeName().toCharArray();
if (ipe.getKind().isDeclare()) {
int index = CharOperation.lastIndexOf('_', byteCodeName);
if (index != -1) {
return convertCount(CharOperation.subarray(byteCodeName, index + 1, byteCodeName.length));
}
} else if (ipe.getKind().equals(IProgramElement.Kind.ADVICE)) {
// Look at any peer advice
int count = 1;
List kids = ipe.getParent().getChildren();
String ipeSig = ipe.getBytecodeSignature();
for (Iterator iterator = kids.iterator(); iterator.hasNext();) {
IProgramElement object = (IProgramElement) iterator.next();
if (object.equals(ipe)) {
break;
}
if (object.getKind() == ipe.getKind()) {
if (object.getName().equals(ipe.getName())) {
String sig1 = object.getBytecodeSignature();
if (sig1 == null && ipeSig == null || sig1.equals(ipeSig)) {
String existingHandle = object.getHandleIdentifier();
int suffixPosition = existingHandle.indexOf('!');
if (suffixPosition != -1) {
count = new Integer(existingHandle.substring(suffixPosition + 1)).intValue() + 1;
} else {
if (count == 1) {
count = 2;
}
}
}
}
}
}
if (count > 1) {
return CharOperation.concat(countDelim, new Integer(count).toString().toCharArray());
}
} else if (ipe.getKind().equals(IProgramElement.Kind.INITIALIZER)) {
return String.valueOf(++initializerCounter).toCharArray();
} else if (ipe.getKind().equals(IProgramElement.Kind.CODE)) {
int index = CharOperation.lastIndexOf('!', byteCodeName);
if (index != -1) {
return convertCount(CharOperation.subarray(byteCodeName, index + 1, byteCodeName.length));
}
} else if (ipe.getKind() == IProgramElement.Kind.CLASS) {
// depends on previous children
int count = 1;
List kids = ipe.getParent().getChildren();
if (ipe.getName().endsWith("{..}")) {
// only depends on previous anonymous children, name irrelevant
for (Iterator iterator = kids.iterator(); iterator.hasNext();) {
IProgramElement object = (IProgramElement) iterator.next();
if (object.equals(ipe)) {
break;
}
if (object.getKind() == ipe.getKind()) {
if (object.getName().endsWith("{..}")) {
String existingHandle = object.getHandleIdentifier();
int suffixPosition = existingHandle.indexOf('!');
if (suffixPosition != -1) {
count = new Integer(existingHandle.substring(suffixPosition + 1)).intValue() + 1;
} else {
if (count == 1) {
count = 2;
}
}
}
}
}
} else {
for (Iterator iterator = kids.iterator(); iterator.hasNext();) {
IProgramElement object = (IProgramElement) iterator.next();
if (object.equals(ipe)) {
break;
}
if (object.getKind() == ipe.getKind()) {
if (object.getName().equals(ipe.getName())) {
String existingHandle = object.getHandleIdentifier();
int suffixPosition = existingHandle.indexOf('!');
if (suffixPosition != -1) {
count = new Integer(existingHandle.substring(suffixPosition + 1)).intValue() + 1;
} else {
if (count == 1) {
count = 2;
}
}
}
}
}
}
if (count > 1) {
return CharOperation.concat(countDelim, new Integer(count).toString().toCharArray());
}
}
return empty;
}
| private char[] getCount(IProgramElement ipe) {
// TODO could optimize this code
char[] byteCodeName = ipe.getBytecodeName().toCharArray();
if (ipe.getKind().isDeclare()) {
int index = CharOperation.lastIndexOf('_', byteCodeName);
if (index != -1) {
return convertCount(CharOperation.subarray(byteCodeName, index + 1, byteCodeName.length));
}
} else if (ipe.getKind().equals(IProgramElement.Kind.ADVICE)) {
// Look at any peer advice
int count = 1;
List kids = ipe.getParent().getChildren();
String ipeSig = ipe.getBytecodeSignature();
for (Iterator iterator = kids.iterator(); iterator.hasNext();) {
IProgramElement object = (IProgramElement) iterator.next();
if (object.equals(ipe)) {
break;
}
if (object.getKind() == ipe.getKind()) {
if (object.getName().equals(ipe.getName())) {
String sig1 = object.getBytecodeSignature();
if (sig1 == null && ipeSig == null || (sig1 != null && sig1.equals(ipeSig))) {
String existingHandle = object.getHandleIdentifier();
int suffixPosition = existingHandle.indexOf('!');
if (suffixPosition != -1) {
count = new Integer(existingHandle.substring(suffixPosition + 1)).intValue() + 1;
} else {
if (count == 1) {
count = 2;
}
}
}
}
}
}
if (count > 1) {
return CharOperation.concat(countDelim, new Integer(count).toString().toCharArray());
}
} else if (ipe.getKind().equals(IProgramElement.Kind.INITIALIZER)) {
return String.valueOf(++initializerCounter).toCharArray();
} else if (ipe.getKind().equals(IProgramElement.Kind.CODE)) {
int index = CharOperation.lastIndexOf('!', byteCodeName);
if (index != -1) {
return convertCount(CharOperation.subarray(byteCodeName, index + 1, byteCodeName.length));
}
} else if (ipe.getKind() == IProgramElement.Kind.CLASS) {
// depends on previous children
int count = 1;
List kids = ipe.getParent().getChildren();
if (ipe.getName().endsWith("{..}")) {
// only depends on previous anonymous children, name irrelevant
for (Iterator iterator = kids.iterator(); iterator.hasNext();) {
IProgramElement object = (IProgramElement) iterator.next();
if (object.equals(ipe)) {
break;
}
if (object.getKind() == ipe.getKind()) {
if (object.getName().endsWith("{..}")) {
String existingHandle = object.getHandleIdentifier();
int suffixPosition = existingHandle.indexOf('!');
if (suffixPosition != -1) {
count = new Integer(existingHandle.substring(suffixPosition + 1)).intValue() + 1;
} else {
if (count == 1) {
count = 2;
}
}
}
}
}
} else {
for (Iterator iterator = kids.iterator(); iterator.hasNext();) {
IProgramElement object = (IProgramElement) iterator.next();
if (object.equals(ipe)) {
break;
}
if (object.getKind() == ipe.getKind()) {
if (object.getName().equals(ipe.getName())) {
String existingHandle = object.getHandleIdentifier();
int suffixPosition = existingHandle.indexOf('!');
if (suffixPosition != -1) {
count = new Integer(existingHandle.substring(suffixPosition + 1)).intValue() + 1;
} else {
if (count == 1) {
count = 2;
}
}
}
}
}
}
if (count > 1) {
return CharOperation.concat(countDelim, new Integer(count).toString().toCharArray());
}
}
return empty;
}
|
diff --git a/org.dawnsci.plotting/src/org/dawnsci/plotting/tools/InfoPixelLabelProvider.java b/org.dawnsci.plotting/src/org/dawnsci/plotting/tools/InfoPixelLabelProvider.java
index 088a73162..699cfdf87 100644
--- a/org.dawnsci.plotting/src/org/dawnsci/plotting/tools/InfoPixelLabelProvider.java
+++ b/org.dawnsci.plotting/src/org/dawnsci/plotting/tools/InfoPixelLabelProvider.java
@@ -1,201 +1,201 @@
/*
* Copyright 2012 Diamond Light Source Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Copyright 2012 Diamond Light Source Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.dawnsci.plotting.tools;
import org.dawnsci.plotting.api.region.IRegion;
import org.dawnsci.plotting.api.region.IRegion.RegionType;
import org.dawnsci.plotting.api.tool.IToolPage.ToolPageRole;
import org.dawnsci.plotting.api.trace.IImageTrace;
import org.dawnsci.plotting.api.trace.TraceUtils;
import org.eclipse.jface.viewers.ColumnLabelProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import uk.ac.diamond.scisoft.analysis.dataset.AbstractDataset;
import uk.ac.diamond.scisoft.analysis.diffraction.DetectorProperties;
import uk.ac.diamond.scisoft.analysis.diffraction.DiffractionCrystalEnvironment;
import uk.ac.diamond.scisoft.analysis.diffraction.QSpace;
import uk.ac.diamond.scisoft.analysis.io.IDiffractionMetadata;
import uk.ac.diamond.scisoft.analysis.io.IMetaData;
import uk.ac.diamond.scisoft.analysis.roi.PointROI;
public class InfoPixelLabelProvider extends ColumnLabelProvider {
private final int column;
private final InfoPixelTool tool;
private static final Logger logger = LoggerFactory.getLogger(InfoPixelLabelProvider.class);
public InfoPixelLabelProvider(InfoPixelTool tool, int i) {
this.column = i;
this.tool = tool;
}
@Override
public String getText(Object element) {
//TODO could use ToolPageRole on the tool to separate 1D and 2D cases better
double xIndex = 0.0;
double yIndex = 0.0;
double xLabel = Double.NaN;
double yLabel = Double.NaN;
final IImageTrace trace = tool.getImageTrace();
try {
if (element instanceof IRegion){
final IRegion region = (IRegion)element;
if (region.getRegionType()==RegionType.POINT) {
PointROI pr = (PointROI)tool.getBounds(region);
xIndex = pr.getPointX();
yIndex = pr.getPointY();
// Sometimes the image can have axes set. In this case we need the point
// ROI in the axes coordinates
if (trace!=null) {
try {
pr = (PointROI)trace.getRegionInAxisCoordinates(pr);
xLabel = pr.getPointX();
yLabel = pr.getPointY();
} catch (Exception aie) {
return "-";
}
}
} else {
xIndex = tool.getXValues()[0];
yIndex = tool.getYValues()[0];
- final double[] dp = new double[]{tool.getXValues()[0], tool.getXValues()[0]};
+ final double[] dp = new double[]{xIndex, yIndex};
try {
if (trace!=null) trace.getPointInAxisCoordinates(dp);
xLabel = dp[0];
yLabel = dp[1];
} catch (Exception aie) {
return "-";
}
}
}else {
return null;
}
if (Double.isNaN(xLabel)) xLabel = xIndex;
if (Double.isNaN(yLabel)) yLabel = yIndex;
IDiffractionMetadata dmeta = null;
AbstractDataset set = null;
if (trace!=null) {
set = (AbstractDataset)trace.getData();
final IMetaData meta = set.getMetadata();
if (meta instanceof IDiffractionMetadata) {
dmeta = (IDiffractionMetadata)meta;
}
}
QSpace qSpace = null;
Vector3dutil vectorUtil= null;
if (dmeta != null) {
try {
DetectorProperties detector2dProperties = dmeta.getDetector2DProperties();
DiffractionCrystalEnvironment diffractionCrystalEnvironment = dmeta.getDiffractionCrystalEnvironment();
if (!(detector2dProperties == null)){
qSpace = new QSpace(detector2dProperties,
diffractionCrystalEnvironment);
vectorUtil = new Vector3dutil(qSpace, xIndex, yIndex);
}
} catch (Exception e) {
logger.error("Could not create a detector properties object from metadata", e);
}
}
final boolean isCustom = TraceUtils.isCustomAxes(trace) || tool.getToolPageRole() == ToolPageRole.ROLE_1D;
switch(column) {
case 0: // "Point Id"
return ( ( (IRegion)element).getRegionType() == RegionType.POINT) ? ((IRegion)element).getName(): "";
case 1: // "X position"
return isCustom ? String.format("% 4.4f", xLabel)
: String.format("% 4d", (int)Math.floor(xLabel));
case 2: // "Y position"
return isCustom ? String.format("% 4.4f", yLabel)
: String.format("% 4d", (int)Math.floor(yLabel));
case 3: // "Data value"
//if (set == null || vectorUtil==null || vectorUtil.getQMask(qSpace, x, y) == null) return "-";
if (set == null) return "-";
return String.format("% 4.4f", set.getDouble((int)Math.floor(yIndex), (int) Math.floor(xIndex)));
case 4: // q X
//if (vectorUtil==null || vectorUtil.getQMask(qSpace, x, y) == null) return "-";
if (vectorUtil==null ) return "-";
return String.format("% 4.4f", vectorUtil.getQx());
case 5: // q Y
//if (vectorUtil==null ||vectorUtil.getQMask(qSpace, x, y) == null) return "-";
if (vectorUtil==null) return "-";
return String.format("% 4.4f", vectorUtil.getQy());
case 6: // q Z
//if (vectorUtil==null ||vectorUtil.getQMask(qSpace, x, y) == null) return "-";
if (vectorUtil==null) return "-";
return String.format("% 4.4f", vectorUtil.getQz());
case 7: // 20
if (vectorUtil==null || qSpace == null) return "-";
return String.format("% 3.3f", Math.toDegrees(vectorUtil.getQScatteringAngle(qSpace)));
case 8: // resolution
//if (vectorUtil==null ||vectorUtil.getQMask(qSpace, x, y) == null) return "-";
if (vectorUtil==null ) return "-";
return String.format("% 4.4f", (2*Math.PI)/vectorUtil.getQlength());
case 9: // Dataset name
if (set == null) return "-";
return set.getName();
default:
return "Not found";
}
} catch (Throwable ne) {
// Must not throw anything from this method - user sees millions of messages!
logger.error("Cannot get label!", ne);
return "";
}
}
@Override
public String getToolTipText(Object element) {
return "Any selection region can be used in information box tool.";
}
}
| true | true | public String getText(Object element) {
//TODO could use ToolPageRole on the tool to separate 1D and 2D cases better
double xIndex = 0.0;
double yIndex = 0.0;
double xLabel = Double.NaN;
double yLabel = Double.NaN;
final IImageTrace trace = tool.getImageTrace();
try {
if (element instanceof IRegion){
final IRegion region = (IRegion)element;
if (region.getRegionType()==RegionType.POINT) {
PointROI pr = (PointROI)tool.getBounds(region);
xIndex = pr.getPointX();
yIndex = pr.getPointY();
// Sometimes the image can have axes set. In this case we need the point
// ROI in the axes coordinates
if (trace!=null) {
try {
pr = (PointROI)trace.getRegionInAxisCoordinates(pr);
xLabel = pr.getPointX();
yLabel = pr.getPointY();
} catch (Exception aie) {
return "-";
}
}
} else {
xIndex = tool.getXValues()[0];
yIndex = tool.getYValues()[0];
final double[] dp = new double[]{tool.getXValues()[0], tool.getXValues()[0]};
try {
if (trace!=null) trace.getPointInAxisCoordinates(dp);
xLabel = dp[0];
yLabel = dp[1];
} catch (Exception aie) {
return "-";
}
}
}else {
return null;
}
if (Double.isNaN(xLabel)) xLabel = xIndex;
if (Double.isNaN(yLabel)) yLabel = yIndex;
IDiffractionMetadata dmeta = null;
AbstractDataset set = null;
if (trace!=null) {
set = (AbstractDataset)trace.getData();
final IMetaData meta = set.getMetadata();
if (meta instanceof IDiffractionMetadata) {
dmeta = (IDiffractionMetadata)meta;
}
}
QSpace qSpace = null;
Vector3dutil vectorUtil= null;
if (dmeta != null) {
try {
DetectorProperties detector2dProperties = dmeta.getDetector2DProperties();
DiffractionCrystalEnvironment diffractionCrystalEnvironment = dmeta.getDiffractionCrystalEnvironment();
if (!(detector2dProperties == null)){
qSpace = new QSpace(detector2dProperties,
diffractionCrystalEnvironment);
vectorUtil = new Vector3dutil(qSpace, xIndex, yIndex);
}
} catch (Exception e) {
logger.error("Could not create a detector properties object from metadata", e);
}
}
final boolean isCustom = TraceUtils.isCustomAxes(trace) || tool.getToolPageRole() == ToolPageRole.ROLE_1D;
switch(column) {
case 0: // "Point Id"
return ( ( (IRegion)element).getRegionType() == RegionType.POINT) ? ((IRegion)element).getName(): "";
case 1: // "X position"
return isCustom ? String.format("% 4.4f", xLabel)
: String.format("% 4d", (int)Math.floor(xLabel));
case 2: // "Y position"
return isCustom ? String.format("% 4.4f", yLabel)
: String.format("% 4d", (int)Math.floor(yLabel));
case 3: // "Data value"
//if (set == null || vectorUtil==null || vectorUtil.getQMask(qSpace, x, y) == null) return "-";
if (set == null) return "-";
return String.format("% 4.4f", set.getDouble((int)Math.floor(yIndex), (int) Math.floor(xIndex)));
case 4: // q X
//if (vectorUtil==null || vectorUtil.getQMask(qSpace, x, y) == null) return "-";
if (vectorUtil==null ) return "-";
return String.format("% 4.4f", vectorUtil.getQx());
case 5: // q Y
//if (vectorUtil==null ||vectorUtil.getQMask(qSpace, x, y) == null) return "-";
if (vectorUtil==null) return "-";
return String.format("% 4.4f", vectorUtil.getQy());
case 6: // q Z
//if (vectorUtil==null ||vectorUtil.getQMask(qSpace, x, y) == null) return "-";
if (vectorUtil==null) return "-";
return String.format("% 4.4f", vectorUtil.getQz());
case 7: // 20
if (vectorUtil==null || qSpace == null) return "-";
return String.format("% 3.3f", Math.toDegrees(vectorUtil.getQScatteringAngle(qSpace)));
case 8: // resolution
//if (vectorUtil==null ||vectorUtil.getQMask(qSpace, x, y) == null) return "-";
if (vectorUtil==null ) return "-";
return String.format("% 4.4f", (2*Math.PI)/vectorUtil.getQlength());
case 9: // Dataset name
if (set == null) return "-";
return set.getName();
default:
return "Not found";
}
} catch (Throwable ne) {
// Must not throw anything from this method - user sees millions of messages!
logger.error("Cannot get label!", ne);
return "";
}
}
| public String getText(Object element) {
//TODO could use ToolPageRole on the tool to separate 1D and 2D cases better
double xIndex = 0.0;
double yIndex = 0.0;
double xLabel = Double.NaN;
double yLabel = Double.NaN;
final IImageTrace trace = tool.getImageTrace();
try {
if (element instanceof IRegion){
final IRegion region = (IRegion)element;
if (region.getRegionType()==RegionType.POINT) {
PointROI pr = (PointROI)tool.getBounds(region);
xIndex = pr.getPointX();
yIndex = pr.getPointY();
// Sometimes the image can have axes set. In this case we need the point
// ROI in the axes coordinates
if (trace!=null) {
try {
pr = (PointROI)trace.getRegionInAxisCoordinates(pr);
xLabel = pr.getPointX();
yLabel = pr.getPointY();
} catch (Exception aie) {
return "-";
}
}
} else {
xIndex = tool.getXValues()[0];
yIndex = tool.getYValues()[0];
final double[] dp = new double[]{xIndex, yIndex};
try {
if (trace!=null) trace.getPointInAxisCoordinates(dp);
xLabel = dp[0];
yLabel = dp[1];
} catch (Exception aie) {
return "-";
}
}
}else {
return null;
}
if (Double.isNaN(xLabel)) xLabel = xIndex;
if (Double.isNaN(yLabel)) yLabel = yIndex;
IDiffractionMetadata dmeta = null;
AbstractDataset set = null;
if (trace!=null) {
set = (AbstractDataset)trace.getData();
final IMetaData meta = set.getMetadata();
if (meta instanceof IDiffractionMetadata) {
dmeta = (IDiffractionMetadata)meta;
}
}
QSpace qSpace = null;
Vector3dutil vectorUtil= null;
if (dmeta != null) {
try {
DetectorProperties detector2dProperties = dmeta.getDetector2DProperties();
DiffractionCrystalEnvironment diffractionCrystalEnvironment = dmeta.getDiffractionCrystalEnvironment();
if (!(detector2dProperties == null)){
qSpace = new QSpace(detector2dProperties,
diffractionCrystalEnvironment);
vectorUtil = new Vector3dutil(qSpace, xIndex, yIndex);
}
} catch (Exception e) {
logger.error("Could not create a detector properties object from metadata", e);
}
}
final boolean isCustom = TraceUtils.isCustomAxes(trace) || tool.getToolPageRole() == ToolPageRole.ROLE_1D;
switch(column) {
case 0: // "Point Id"
return ( ( (IRegion)element).getRegionType() == RegionType.POINT) ? ((IRegion)element).getName(): "";
case 1: // "X position"
return isCustom ? String.format("% 4.4f", xLabel)
: String.format("% 4d", (int)Math.floor(xLabel));
case 2: // "Y position"
return isCustom ? String.format("% 4.4f", yLabel)
: String.format("% 4d", (int)Math.floor(yLabel));
case 3: // "Data value"
//if (set == null || vectorUtil==null || vectorUtil.getQMask(qSpace, x, y) == null) return "-";
if (set == null) return "-";
return String.format("% 4.4f", set.getDouble((int)Math.floor(yIndex), (int) Math.floor(xIndex)));
case 4: // q X
//if (vectorUtil==null || vectorUtil.getQMask(qSpace, x, y) == null) return "-";
if (vectorUtil==null ) return "-";
return String.format("% 4.4f", vectorUtil.getQx());
case 5: // q Y
//if (vectorUtil==null ||vectorUtil.getQMask(qSpace, x, y) == null) return "-";
if (vectorUtil==null) return "-";
return String.format("% 4.4f", vectorUtil.getQy());
case 6: // q Z
//if (vectorUtil==null ||vectorUtil.getQMask(qSpace, x, y) == null) return "-";
if (vectorUtil==null) return "-";
return String.format("% 4.4f", vectorUtil.getQz());
case 7: // 20
if (vectorUtil==null || qSpace == null) return "-";
return String.format("% 3.3f", Math.toDegrees(vectorUtil.getQScatteringAngle(qSpace)));
case 8: // resolution
//if (vectorUtil==null ||vectorUtil.getQMask(qSpace, x, y) == null) return "-";
if (vectorUtil==null ) return "-";
return String.format("% 4.4f", (2*Math.PI)/vectorUtil.getQlength());
case 9: // Dataset name
if (set == null) return "-";
return set.getName();
default:
return "Not found";
}
} catch (Throwable ne) {
// Must not throw anything from this method - user sees millions of messages!
logger.error("Cannot get label!", ne);
return "";
}
}
|
diff --git a/plugins/org.eclipse.birt.report.engine/src/org/eclipse/birt/report/engine/layout/pdf/util/HTML2Content.java b/plugins/org.eclipse.birt.report.engine/src/org/eclipse/birt/report/engine/layout/pdf/util/HTML2Content.java
index 8438fd6f2..031d5592d 100644
--- a/plugins/org.eclipse.birt.report.engine/src/org/eclipse/birt/report/engine/layout/pdf/util/HTML2Content.java
+++ b/plugins/org.eclipse.birt.report.engine/src/org/eclipse/birt/report/engine/layout/pdf/util/HTML2Content.java
@@ -1,597 +1,599 @@
/***********************************************************************
* Copyright (c) 2004 Actuate Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Actuate Corporation - initial API and implementation
***********************************************************************/
package org.eclipse.birt.report.engine.layout.pdf.util;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Stack;
import org.eclipse.birt.report.engine.content.IContainerContent;
import org.eclipse.birt.report.engine.content.IContent;
import org.eclipse.birt.report.engine.content.IForeignContent;
import org.eclipse.birt.report.engine.content.IImageContent;
import org.eclipse.birt.report.engine.content.ILabelContent;
import org.eclipse.birt.report.engine.content.IStyle;
import org.eclipse.birt.report.engine.content.impl.ActionContent;
import org.eclipse.birt.report.engine.content.impl.ContainerContent;
import org.eclipse.birt.report.engine.content.impl.ImageContent;
import org.eclipse.birt.report.engine.content.impl.LabelContent;
import org.eclipse.birt.report.engine.content.impl.ReportContent;
import org.eclipse.birt.report.engine.content.impl.TextContent;
import org.eclipse.birt.report.engine.css.dom.StyleDeclaration;
import org.eclipse.birt.report.engine.css.engine.value.css.CSSValueConstants;
import org.eclipse.birt.report.engine.ir.DimensionType;
import org.eclipse.birt.report.engine.parser.TextParser;
import org.eclipse.birt.report.engine.util.FileUtil;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
public class HTML2Content
{
protected static final HashMap tag2Style = new HashMap( );
protected static final HashSet htmlDisplayMode = new HashSet( );
protected static final HashSet supportedHTMLElementTags = new HashSet();
protected static final HashMap textTypeMapping = new HashMap( );
protected ActionContent action = null;
protected String rootPath;
protected Stack inlineContainerStack = new Stack();
static
{
tag2Style.put( "code", //$NON-NLS-1$
"font-family: monospace"); //$NON-NLS-1$
tag2Style.put( "em", //$NON-NLS-1$
"font-style: italic"); //$NON-NLS-1$
tag2Style.put( "h1", //$NON-NLS-1$
"font-size: 2em; margin-top: 0.67em; margin-bottom:0.67em; font-weight: bold; page-break-after: avoid"); //$NON-NLS-1$
tag2Style.put( "h2", //$NON-NLS-1$
"font-size: 1.5em; margin-top: 0.75em; margin-bottom:0.75em; font-weight: bold; page-break-after: avoid"); //$NON-NLS-1$
tag2Style.put( "h3", //$NON-NLS-1$
"font-size: 1.17em; margin-top: 0.83em; margin-bottom:0.83em; font-weight: bold; page-break-after: avoid"); //$NON-NLS-1$
tag2Style.put( "h4", //$NON-NLS-1$
"font-size: 1.12em; margin-top: 1.12em; margin-bottom:1.12em; font-weight: bold; page-break-after: avoid"); //$NON-NLS-1$
tag2Style.put( "h5", //$NON-NLS-1$
"font-size: 0.83em; margin-top: 1.5em; margin-bottom:1.5em; font-weight: bold; page-break-after: avoid"); //$NON-NLS-1$
tag2Style.put( "h6", //$NON-NLS-1$
"font-size: 0.75em; margin-top: 1.67em; margin-bottom:1.67em; font-weight: bold; page-break-after: avoid"); //$NON-NLS-1$
tag2Style.put( "pre", //$NON-NLS-1$
"font-family: monospace; white-space: no-wrap; "); //$NON-NLS-1$
tag2Style.put( "strong", //$NON-NLS-1$
"font-weight: bold"); //$NON-NLS-1$
tag2Style.put( "sub", //$NON-NLS-1$
"vertical-align: bottom; font-size: 75%"); //$NON-NLS-1$
tag2Style.put( "sup", //$NON-NLS-1$
"vertical-align: top; font-size: 75%"); //$NON-NLS-1$
tag2Style.put( "tt", //$NON-NLS-1$
"font-family: monospace;"); //$NON-NLS-1$
tag2Style.put( "center", //$NON-NLS-1$
"text-align: center;"); //$NON-NLS-1$
tag2Style.put( "i", //$NON-NLS-1$
"font-style: italic;"); //$NON-NLS-1$
tag2Style.put( "b", //$NON-NLS-1$
"font-weight: bold;"); //$NON-NLS-1$
tag2Style.put( "p", //$NON-NLS-1$
"margin-top: 1.33em; margin-bottom: 1.33em"); //$NON-NLS-1$
tag2Style.put( "u", //$NON-NLS-1$
"text-decoration: underline;"); //$NON-NLS-1$
tag2Style.put( "del", //$NON-NLS-1$
"text-decoration: line-through;"); //$NON-NLS-1$
supportedHTMLElementTags.add("H1"); //$NON-NLS-1$
supportedHTMLElementTags.add("H2"); //$NON-NLS-1$
supportedHTMLElementTags.add("H3"); //$NON-NLS-1$
supportedHTMLElementTags.add("H4"); //$NON-NLS-1$
supportedHTMLElementTags.add("H5"); //$NON-NLS-1$
supportedHTMLElementTags.add("H6"); //$NON-NLS-1$
supportedHTMLElementTags.add("A"); //$NON-NLS-1$
supportedHTMLElementTags.add("B"); //$NON-NLS-1$
supportedHTMLElementTags.add("BODY"); //$NON-NLS-1$
supportedHTMLElementTags.add("BR"); //$NON-NLS-1$
supportedHTMLElementTags.add("CENTER"); //$NON-NLS-1$
supportedHTMLElementTags.add("CODE"); //$NON-NLS-1$
supportedHTMLElementTags.add("DD"); //$NON-NLS-1$
supportedHTMLElementTags.add("DEL"); //$NON-NLS-1$
supportedHTMLElementTags.add("DIV"); //$NON-NLS-1$
supportedHTMLElementTags.add("DL"); //$NON-NLS-1$
supportedHTMLElementTags.add("DT"); //$NON-NLS-1$
supportedHTMLElementTags.add("FONT"); //$NON-NLS-1$
supportedHTMLElementTags.add("EM"); //$NON-NLS-1$
supportedHTMLElementTags.add("HEAD"); //$NON-NLS-1$
supportedHTMLElementTags.add("HTML"); //$NON-NLS-1$
supportedHTMLElementTags.add("I"); //$NON-NLS-1$
supportedHTMLElementTags.add("IMAGE"); //$NON-NLS-1$
supportedHTMLElementTags.add("IMG"); //$NON-NLS-1$
supportedHTMLElementTags.add("INS"); //$NON-NLS-1$
supportedHTMLElementTags.add("LI"); //$NON-NLS-1$
supportedHTMLElementTags.add("OL"); //$NON-NLS-1$
supportedHTMLElementTags.add("PRE"); //$NON-NLS-1$
supportedHTMLElementTags.add("P"); //$NON-NLS-1$
supportedHTMLElementTags.add("SPAN"); //$NON-NLS-1$
supportedHTMLElementTags.add("STRONG"); //$NON-NLS-1$
supportedHTMLElementTags.add("SUB"); //$NON-NLS-1$
supportedHTMLElementTags.add("SUP"); //$NON-NLS-1$
supportedHTMLElementTags.add("TITLE"); //$NON-NLS-1$
supportedHTMLElementTags.add("UL"); //$NON-NLS-1$
supportedHTMLElementTags.add("TT"); //$NON-NLS-1$
supportedHTMLElementTags.add("U"); //$NON-NLS-1$
//block-level elements
htmlDisplayMode.add( "dd" ); //$NON-NLS-1$
htmlDisplayMode.add( "div" ); //$NON-NLS-1$
htmlDisplayMode.add( "dl" ); //$NON-NLS-1$
htmlDisplayMode.add( "dt" ); //$NON-NLS-1$
htmlDisplayMode.add( "h1" ); //$NON-NLS-1$
htmlDisplayMode.add( "h2" ); //$NON-NLS-1$
htmlDisplayMode.add( "h3" ); //$NON-NLS-1$
htmlDisplayMode.add( "h4" ); //$NON-NLS-1$
htmlDisplayMode.add( "h5" ); //$NON-NLS-1$
htmlDisplayMode.add( "h6" ); //$NON-NLS-1$
htmlDisplayMode.add( "hr" ); //$NON-NLS-1$
htmlDisplayMode.add( "ol" ); //$NON-NLS-1$
htmlDisplayMode.add( "p" ); //$NON-NLS-1$
htmlDisplayMode.add( "pre" ); //$NON-NLS-1$
htmlDisplayMode.add( "ul" ); //$NON-NLS-1$
htmlDisplayMode.add( "li" ); //$NON-NLS-1$
htmlDisplayMode.add( "body" ); //$NON-NLS-1$
htmlDisplayMode.add( "center" ); //$NON-NLS-1$
textTypeMapping.put( IForeignContent.HTML_TYPE, TextParser.TEXT_TYPE_HTML );
textTypeMapping.put( IForeignContent.TEXT_TYPE, TextParser.TEXT_TYPE_PLAIN );
textTypeMapping.put( IForeignContent.UNKNOWN_TYPE, TextParser.TEXT_TYPE_AUTO );
}
public HTML2Content( String rootPath)
{
this.rootPath = rootPath;
}
public void html2Content( IForeignContent foreign)
{
processForeignData(foreign);
}
protected void processForeignData( IForeignContent foreign )
{
if(foreign.getChildren( )!=null && foreign.getChildren( ).size( )>0)
{
return;
}
HashMap styleMap = new HashMap( );
HTMLStyleProcessor htmlProcessor = new HTMLStyleProcessor( this.rootPath );
Object rawValue = foreign.getRawValue();
Document doc = null;
if ( null != rawValue )
{
doc = new TextParser( ).parse( foreign.getRawValue( ).toString( ),
( String )textTypeMapping.get( foreign.getRawType( ) ) );
}
Element body = null;
if ( doc != null )
{
Node node = doc.getFirstChild( );
//The following must be true
if ( node instanceof Element )
{
body = (Element) node;
}
}
if ( body != null )
{
htmlProcessor.execute( body, styleMap );
processNodes( body, checkEscapeSpace( doc ), styleMap, foreign );
}
}
/**
* Visits the children nodes of the specific node
*
* @param visitor
* the ITextNodeVisitor instance
* @param ele
* the specific node
* @param needEscape
* the flag indicating the content needs escaping
*/
private void processNodes( Element ele, boolean needEscape, HashMap cssStyles, IContent content )
{
int level=0;
for ( Node node = ele.getFirstChild( ); node != null; node = node
.getNextSibling( ) )
{
if ( node.getNodeName( ).equals( "value-of" ) ) //$NON-NLS-1$
{
if ( node.getFirstChild( ) instanceof Element )
{
processNodes( (Element) node.getFirstChild( ), checkEscapeSpace( node ), cssStyles, content );
}
}
else if ( node.getNodeName( ).equals( "image" ) ) //$NON-NLS-1$
{
if ( node.getFirstChild( ) instanceof Element )
{
processNodes( (Element) node.getFirstChild( ), needEscape, cssStyles, content);
}
}
else if(node.getNodeType() == Node.TEXT_NODE)
{
ILabelContent label = new LabelContent((ReportContent)content.getReportContent());
addChild(content, label);
label.setText(node.getNodeValue());
StyleDeclaration inlineStyle = new StyleDeclaration(content.getCSSEngine());
inlineStyle.setProperty( IStyle.STYLE_DISPLAY, CSSValueConstants.INLINE_VALUE );
//support del, ins and u
Node pNode = node.getParentNode();
if(pNode!=null)
{
if("u".equalsIgnoreCase(pNode.getNodeName()) || "ins".equalsIgnoreCase(pNode.getNodeName())) //$NON-NLS-1$//$NON-NLS-2$
{
inlineStyle.setTextUnderline("underline"); //$NON-NLS-1$
}
else if("del".equalsIgnoreCase(pNode.getNodeName())) //$NON-NLS-1$
{
inlineStyle.setTextLineThrough("line-through"); //$NON-NLS-1$
}
else if("sub".equalsIgnoreCase(pNode.getNodeName())) //$NON-NLS-1$
{
inlineStyle.setVerticalAlign( "bottom"); //$NON-NLS-1$
}
else if("sup".equalsIgnoreCase(pNode.getNodeName())) //$NON-NLS-1$
{
inlineStyle.setVerticalAlign( "top"); //$NON-NLS-1$
}
}
label.setInlineStyle(inlineStyle);
if(action!=null)
{
label.setHyperlinkAction(action);
}
}
else if(supportedHTMLElementTags.contains(node.getNodeName().toUpperCase()) && node.getNodeType()== Node.ELEMENT_NODE)
{
handleElement((Element)node, needEscape, cssStyles, content, ++level);
}
}
}
private void handleElement(Element ele, boolean needEscape, HashMap cssStyles, IContent content, int index)
{
IStyle cssStyle = ( IStyle ) cssStyles.get( ele );
if ( cssStyle != null )
{
if ( "none".equals( cssStyle.getDisplay() ) ) //$NON-NLS-1$
{
//Check if the display mode is none.
return;
}
}
String tagName = ele.getTagName();
if ( tagName.toLowerCase().equals( "a" ) ) //$NON-NLS-1$
{
IContainerContent container = new ContainerContent((ReportContent)content.getReportContent());
container.setParent(content);//FIXME addChild to replace?
handleStyle(ele, cssStyles, container);
ActionContent oldAction = action;
handleAnchor( ele, container );
processNodes( ele, needEscape, cssStyles, container );
this.action = oldAction;
}
else if(tagName.toLowerCase().equals( "img" )) //$NON-NLS-1$
{
outputImg( ele, cssStyles, content);
}
else if ( tagName.toLowerCase().equals( "br" ) ) //$NON-NLS-1$
{
ILabelContent label = new LabelContent((ReportContent)content.getReportContent());
addChild(content, label);
label.setText("\n"); //$NON-NLS-1$
StyleDeclaration inlineStyle = new StyleDeclaration(content.getCSSEngine());
inlineStyle.setProperty( IStyle.STYLE_DISPLAY, CSSValueConstants.INLINE_VALUE );
label.setInlineStyle( inlineStyle );
}
else if (tagName.toLowerCase().equals("li") //$NON-NLS-1$
&& ele.getParentNode().getNodeType() == Node.ELEMENT_NODE)
{
StyleDeclaration style = new StyleDeclaration(content.getCSSEngine());
style.setProperty( IStyle.STYLE_DISPLAY, CSSValueConstants.BLOCK_VALUE );
style.setProperty( IStyle.STYLE_VERTICAL_ALIGN, CSSValueConstants.MIDDLE_VALUE );
IContainerContent container = new ContainerContent((ReportContent)content.getReportContent());
container.setInlineStyle(style);
addChild(content, container);
handleStyle(ele, cssStyles, container);
TextContent text = new TextContent((ReportContent)content.getReportContent());
addChild(container, text);
if(ele.getParentNode().getNodeName().equals("ol")) //$NON-NLS-1$
{
text.setText(new Integer(index).toString()+". "); //$NON-NLS-1$
}
else if(ele.getParentNode().getNodeName().equals("ul")) //$NON-NLS-1$
{
text.setText(" • " ); //$NON-NLS-1$
}
style = new StyleDeclaration(content.getCSSEngine());
style.setProperty( IStyle.STYLE_DISPLAY, CSSValueConstants.INLINE_VALUE );
+ style.setProperty( IStyle.STYLE_VERTICAL_ALIGN, CSSValueConstants.TOP_VALUE );
text.setInlineStyle(style);
IContainerContent childContainer = new ContainerContent((ReportContent)content.getReportContent());
addChild(container, childContainer);
childContainer.setInlineStyle(style);
processNodes( ele, needEscape, cssStyles, childContainer );
}
else if (tagName.toLowerCase().equals("dd") || tagName.toLowerCase().equals("dt")) //$NON-NLS-1$ //$NON-NLS-2$
{
IContainerContent container = new ContainerContent((ReportContent)content.getReportContent());
addChild(content, container);
handleStyle(ele, cssStyles, container);
if (tagName.toLowerCase().equals("dd")) //$NON-NLS-1$
{
StyleDeclaration style = new StyleDeclaration(content.getCSSEngine());
style.setProperty( IStyle.STYLE_DISPLAY, CSSValueConstants.INLINE_VALUE );
+ style.setProperty( IStyle.STYLE_VERTICAL_ALIGN, CSSValueConstants.TOP_VALUE );
TextContent text = new TextContent((ReportContent) content
.getReportContent());
addChild(content, text);
if (ele.getParentNode().getNodeName().equals("dl")) //$NON-NLS-1$
{
text.setText(""); //$NON-NLS-1$
}
style.setTextIndent("3em"); //$NON-NLS-1$
text.setInlineStyle(style);
IContainerContent childContainer = new ContainerContent((ReportContent)content.getReportContent());
childContainer.setInlineStyle(style);
addChild(container, childContainer);
processNodes( ele, needEscape, cssStyles, container );
}
else
{
processNodes(ele, needEscape, cssStyles, container);
}
}
else
{
IContainerContent container = new ContainerContent((ReportContent)content.getReportContent());
handleStyle(ele, cssStyles, container);
if(htmlDisplayMode.contains(ele.getTagName()))
{
addChild(content, container);
processNodes( ele, needEscape, cssStyles, container );
}
else
{
if(inlineContainerStack.isEmpty( ))
{
container.setParent( content );
}
else
{
container.setParent( ( IContent) inlineContainerStack.peek( ));
}
inlineContainerStack.push( container );
processNodes( ele, needEscape, cssStyles, content );
inlineContainerStack.pop( );
}
}
}
/**
* Checks if the content inside the DOM should be escaped.
*
* @param doc
* the root of the DOM tree
* @return true if the content needs escaping, otherwise false.
*/
private boolean checkEscapeSpace( Node doc )
{
String textType = null;
if ( doc != null && doc.getFirstChild( ) != null
&& doc.getFirstChild( ) instanceof Element )
{
textType = ( (Element) doc.getFirstChild( ) )
.getAttribute( "text-type" ); //$NON-NLS-1$
return ( !TextParser.TEXT_TYPE_HTML.equalsIgnoreCase( textType ) );
}
return true;
}
/**
* Outputs the A element
*
* @param ele
* the A element instance
*/
protected void handleAnchor( Element ele, IContent content )
{
// If the "id" attribute is not empty, then use it,
// otherwise use the "name" attribute.
if ( ele.getAttribute( "id" ).trim( ).length( ) != 0 ) //$NON-NLS-1$
{
content.setBookmark(ele.getAttribute( "id" )); //$NON-NLS-1$
}
else
{
content.setBookmark(ele.getAttribute( "name" ));//$NON-NLS-1$
}
if ( ele.getAttribute( "href" ).length( ) > 0 ) //$NON-NLS-1$
{
String href = ele.getAttribute( "href" ); //$NON-NLS-1$
if(null!=href && !"".equals(href)) //$NON-NLS-1$
{
ActionContent action = new ActionContent();
if(href.startsWith("#")) //$NON-NLS-1$
{
action.setBookmark(href.substring(1));
}
else
{
action.setHyperlink(href, ele.getAttribute("target")); //$NON-NLS-1$
}
content.setHyperlinkAction(action);
this.action = action;
}
}
}
private void handleStyle(Element ele, HashMap cssStyles, IContent content)
{
String tagName = ele.getTagName();
StyleDeclaration style = new StyleDeclaration(content.getCSSEngine());
if("font".equals(tagName)) //$NON-NLS-1$
{
String attr = ele.getAttribute("size"); //$NON-NLS-1$
if(null!=attr && !"".equals(attr)) //$NON-NLS-1$
{
style.setFontSize(attr);
}
attr = ele.getAttribute("color"); //$NON-NLS-1$
if(null!=attr && !"".equals(attr)) //$NON-NLS-1$
{
style.setColor(attr);
}
attr = ele.getAttribute("face"); //$NON-NLS-1$
if(null!=attr && !"".equals(attr)) //$NON-NLS-1$
{
style.setFontFamily(attr);
}
}
if(htmlDisplayMode.contains(tagName))
{
style.setDisplay("block"); //$NON-NLS-1$
}
else
{
style.setDisplay("inline"); //$NON-NLS-1$
}
IStyle inlineStyle = (IStyle)cssStyles.get(ele);
if(inlineStyle!=null)
{
style.setProperties(inlineStyle);
}
if(tag2Style.containsKey(ele.getTagName()))
{
StyleDeclaration tagStyle = (StyleDeclaration)content.getCSSEngine().parseStyleDeclaration((String)tag2Style.get(ele.getTagName()));
if(tagStyle!=null)
{
style.setProperties(tagStyle);
}
}
content.setInlineStyle(style);
}
/**
* Outputs the image
*
* @param ele
* the IMG element instance
*/
protected void outputImg( Element ele, HashMap cssStyles, IContent content )
{
String src = ele.getAttribute( "src" ); //$NON-NLS-1$
if(src!=null)
{
IImageContent image = new ImageContent(content);
addChild(content, image);
handleStyle(ele, cssStyles, image);
if( !FileUtil.isLocalResource( src ) )
{
image.setImageSource(IImageContent.IMAGE_URI);
image.setURI(src);
}
else
{
src = FileUtil.getAbsolutePath(rootPath, src);
image.setImageSource(IImageContent.IMAGE_FILE);
image.setURI(src);
}
if(null!=ele.getAttribute("width") && !"".equals(ele.getAttribute("width"))) //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
{
image.setWidth(DimensionType.parserUnit(ele.getAttribute("width"))); //$NON-NLS-1$
}
if(ele.getAttribute("height")!=null &&! "".equals(ele.getAttribute("height"))) //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
{
image.setWidth(DimensionType.parserUnit(ele.getAttribute("height"))); //$NON-NLS-1$
}
if(ele.getAttribute("alt")!=null && !"".equals(ele.getAttribute("alt"))) //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
{
image.setAltText(ele.getAttribute("alt")); //$NON-NLS-1$
}
}
}
protected void addChild(IContent parent, IContent child)
{
if(parent!=null && child!=null)
{
Collection children = parent.getChildren( );
if(!children.contains( child ))
{
children.add( child );
if(inlineContainerStack.isEmpty( ))
{
child.setParent( parent );
}
else
{
child.setParent( ( IContent) inlineContainerStack.peek( ));
}
}
}
}
}
| false | true | private void handleElement(Element ele, boolean needEscape, HashMap cssStyles, IContent content, int index)
{
IStyle cssStyle = ( IStyle ) cssStyles.get( ele );
if ( cssStyle != null )
{
if ( "none".equals( cssStyle.getDisplay() ) ) //$NON-NLS-1$
{
//Check if the display mode is none.
return;
}
}
String tagName = ele.getTagName();
if ( tagName.toLowerCase().equals( "a" ) ) //$NON-NLS-1$
{
IContainerContent container = new ContainerContent((ReportContent)content.getReportContent());
container.setParent(content);//FIXME addChild to replace?
handleStyle(ele, cssStyles, container);
ActionContent oldAction = action;
handleAnchor( ele, container );
processNodes( ele, needEscape, cssStyles, container );
this.action = oldAction;
}
else if(tagName.toLowerCase().equals( "img" )) //$NON-NLS-1$
{
outputImg( ele, cssStyles, content);
}
else if ( tagName.toLowerCase().equals( "br" ) ) //$NON-NLS-1$
{
ILabelContent label = new LabelContent((ReportContent)content.getReportContent());
addChild(content, label);
label.setText("\n"); //$NON-NLS-1$
StyleDeclaration inlineStyle = new StyleDeclaration(content.getCSSEngine());
inlineStyle.setProperty( IStyle.STYLE_DISPLAY, CSSValueConstants.INLINE_VALUE );
label.setInlineStyle( inlineStyle );
}
else if (tagName.toLowerCase().equals("li") //$NON-NLS-1$
&& ele.getParentNode().getNodeType() == Node.ELEMENT_NODE)
{
StyleDeclaration style = new StyleDeclaration(content.getCSSEngine());
style.setProperty( IStyle.STYLE_DISPLAY, CSSValueConstants.BLOCK_VALUE );
style.setProperty( IStyle.STYLE_VERTICAL_ALIGN, CSSValueConstants.MIDDLE_VALUE );
IContainerContent container = new ContainerContent((ReportContent)content.getReportContent());
container.setInlineStyle(style);
addChild(content, container);
handleStyle(ele, cssStyles, container);
TextContent text = new TextContent((ReportContent)content.getReportContent());
addChild(container, text);
if(ele.getParentNode().getNodeName().equals("ol")) //$NON-NLS-1$
{
text.setText(new Integer(index).toString()+". "); //$NON-NLS-1$
}
else if(ele.getParentNode().getNodeName().equals("ul")) //$NON-NLS-1$
{
text.setText(" • " ); //$NON-NLS-1$
}
style = new StyleDeclaration(content.getCSSEngine());
style.setProperty( IStyle.STYLE_DISPLAY, CSSValueConstants.INLINE_VALUE );
text.setInlineStyle(style);
IContainerContent childContainer = new ContainerContent((ReportContent)content.getReportContent());
addChild(container, childContainer);
childContainer.setInlineStyle(style);
processNodes( ele, needEscape, cssStyles, childContainer );
}
else if (tagName.toLowerCase().equals("dd") || tagName.toLowerCase().equals("dt")) //$NON-NLS-1$ //$NON-NLS-2$
{
IContainerContent container = new ContainerContent((ReportContent)content.getReportContent());
addChild(content, container);
handleStyle(ele, cssStyles, container);
if (tagName.toLowerCase().equals("dd")) //$NON-NLS-1$
{
StyleDeclaration style = new StyleDeclaration(content.getCSSEngine());
style.setProperty( IStyle.STYLE_DISPLAY, CSSValueConstants.INLINE_VALUE );
TextContent text = new TextContent((ReportContent) content
.getReportContent());
addChild(content, text);
if (ele.getParentNode().getNodeName().equals("dl")) //$NON-NLS-1$
{
text.setText(""); //$NON-NLS-1$
}
style.setTextIndent("3em"); //$NON-NLS-1$
text.setInlineStyle(style);
IContainerContent childContainer = new ContainerContent((ReportContent)content.getReportContent());
childContainer.setInlineStyle(style);
addChild(container, childContainer);
processNodes( ele, needEscape, cssStyles, container );
}
else
{
processNodes(ele, needEscape, cssStyles, container);
}
}
else
{
IContainerContent container = new ContainerContent((ReportContent)content.getReportContent());
handleStyle(ele, cssStyles, container);
if(htmlDisplayMode.contains(ele.getTagName()))
{
addChild(content, container);
processNodes( ele, needEscape, cssStyles, container );
}
else
{
if(inlineContainerStack.isEmpty( ))
{
container.setParent( content );
}
else
{
container.setParent( ( IContent) inlineContainerStack.peek( ));
}
inlineContainerStack.push( container );
processNodes( ele, needEscape, cssStyles, content );
inlineContainerStack.pop( );
}
}
}
| private void handleElement(Element ele, boolean needEscape, HashMap cssStyles, IContent content, int index)
{
IStyle cssStyle = ( IStyle ) cssStyles.get( ele );
if ( cssStyle != null )
{
if ( "none".equals( cssStyle.getDisplay() ) ) //$NON-NLS-1$
{
//Check if the display mode is none.
return;
}
}
String tagName = ele.getTagName();
if ( tagName.toLowerCase().equals( "a" ) ) //$NON-NLS-1$
{
IContainerContent container = new ContainerContent((ReportContent)content.getReportContent());
container.setParent(content);//FIXME addChild to replace?
handleStyle(ele, cssStyles, container);
ActionContent oldAction = action;
handleAnchor( ele, container );
processNodes( ele, needEscape, cssStyles, container );
this.action = oldAction;
}
else if(tagName.toLowerCase().equals( "img" )) //$NON-NLS-1$
{
outputImg( ele, cssStyles, content);
}
else if ( tagName.toLowerCase().equals( "br" ) ) //$NON-NLS-1$
{
ILabelContent label = new LabelContent((ReportContent)content.getReportContent());
addChild(content, label);
label.setText("\n"); //$NON-NLS-1$
StyleDeclaration inlineStyle = new StyleDeclaration(content.getCSSEngine());
inlineStyle.setProperty( IStyle.STYLE_DISPLAY, CSSValueConstants.INLINE_VALUE );
label.setInlineStyle( inlineStyle );
}
else if (tagName.toLowerCase().equals("li") //$NON-NLS-1$
&& ele.getParentNode().getNodeType() == Node.ELEMENT_NODE)
{
StyleDeclaration style = new StyleDeclaration(content.getCSSEngine());
style.setProperty( IStyle.STYLE_DISPLAY, CSSValueConstants.BLOCK_VALUE );
style.setProperty( IStyle.STYLE_VERTICAL_ALIGN, CSSValueConstants.MIDDLE_VALUE );
IContainerContent container = new ContainerContent((ReportContent)content.getReportContent());
container.setInlineStyle(style);
addChild(content, container);
handleStyle(ele, cssStyles, container);
TextContent text = new TextContent((ReportContent)content.getReportContent());
addChild(container, text);
if(ele.getParentNode().getNodeName().equals("ol")) //$NON-NLS-1$
{
text.setText(new Integer(index).toString()+". "); //$NON-NLS-1$
}
else if(ele.getParentNode().getNodeName().equals("ul")) //$NON-NLS-1$
{
text.setText(" • " ); //$NON-NLS-1$
}
style = new StyleDeclaration(content.getCSSEngine());
style.setProperty( IStyle.STYLE_DISPLAY, CSSValueConstants.INLINE_VALUE );
style.setProperty( IStyle.STYLE_VERTICAL_ALIGN, CSSValueConstants.TOP_VALUE );
text.setInlineStyle(style);
IContainerContent childContainer = new ContainerContent((ReportContent)content.getReportContent());
addChild(container, childContainer);
childContainer.setInlineStyle(style);
processNodes( ele, needEscape, cssStyles, childContainer );
}
else if (tagName.toLowerCase().equals("dd") || tagName.toLowerCase().equals("dt")) //$NON-NLS-1$ //$NON-NLS-2$
{
IContainerContent container = new ContainerContent((ReportContent)content.getReportContent());
addChild(content, container);
handleStyle(ele, cssStyles, container);
if (tagName.toLowerCase().equals("dd")) //$NON-NLS-1$
{
StyleDeclaration style = new StyleDeclaration(content.getCSSEngine());
style.setProperty( IStyle.STYLE_DISPLAY, CSSValueConstants.INLINE_VALUE );
style.setProperty( IStyle.STYLE_VERTICAL_ALIGN, CSSValueConstants.TOP_VALUE );
TextContent text = new TextContent((ReportContent) content
.getReportContent());
addChild(content, text);
if (ele.getParentNode().getNodeName().equals("dl")) //$NON-NLS-1$
{
text.setText(""); //$NON-NLS-1$
}
style.setTextIndent("3em"); //$NON-NLS-1$
text.setInlineStyle(style);
IContainerContent childContainer = new ContainerContent((ReportContent)content.getReportContent());
childContainer.setInlineStyle(style);
addChild(container, childContainer);
processNodes( ele, needEscape, cssStyles, container );
}
else
{
processNodes(ele, needEscape, cssStyles, container);
}
}
else
{
IContainerContent container = new ContainerContent((ReportContent)content.getReportContent());
handleStyle(ele, cssStyles, container);
if(htmlDisplayMode.contains(ele.getTagName()))
{
addChild(content, container);
processNodes( ele, needEscape, cssStyles, container );
}
else
{
if(inlineContainerStack.isEmpty( ))
{
container.setParent( content );
}
else
{
container.setParent( ( IContent) inlineContainerStack.peek( ));
}
inlineContainerStack.push( container );
processNodes( ele, needEscape, cssStyles, content );
inlineContainerStack.pop( );
}
}
}
|
diff --git a/wrapper/core/src/main/java/org/apache/karaf/wrapper/internal/WrapperServiceImpl.java b/wrapper/core/src/main/java/org/apache/karaf/wrapper/internal/WrapperServiceImpl.java
index 204bd75ea..3b4efc9a8 100644
--- a/wrapper/core/src/main/java/org/apache/karaf/wrapper/internal/WrapperServiceImpl.java
+++ b/wrapper/core/src/main/java/org/apache/karaf/wrapper/internal/WrapperServiceImpl.java
@@ -1,413 +1,413 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.karaf.wrapper.internal;
import org.apache.karaf.wrapper.WrapperService;
import org.fusesource.jansi.Ansi;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import java.util.jar.JarOutputStream;
import java.util.zip.ZipEntry;
/**
* Default implementation of the wrapper service.
*/
public class WrapperServiceImpl implements WrapperService {
private final static Logger LOGGER = LoggerFactory.getLogger(WrapperServiceImpl.class);
public void install() throws Exception {
install("karaf", "", "", "AUTO_START");
}
public File[] install(String name, String displayName, String description, String startType) throws Exception {
File base = new File(System.getProperty("karaf.base"));
File bin = new File(base, "bin");
File etc = new File(base, "etc");
File lib = new File(base, "lib");
if (name == null) {
name = base.getName();
}
HashMap<String, String> props = new HashMap<String, String>();
props.put("${karaf.home}", System.getProperty("karaf.home"));
props.put("${karaf.base}", base.getPath());
props.put("${karaf.data}", System.getProperty("karaf.data"));
props.put("${name}", name);
props.put("${displayName}", displayName);
props.put("${description}", description);
props.put("${startType}", startType);
String os = System.getProperty("os.name", "Unknown");
File serviceFile = null;
File wrapperConf = null;
if (os.startsWith("Win")) {
mkdir(bin);
- copyResourceTo(new File(bin, name + "-wrapper.exec"), "windows/karaf-wrapper.exec", false);
+ copyResourceTo(new File(bin, name + "-wrapper.exe"), "windows/karaf-wrapper.exe", false);
serviceFile = new File(bin, name + "-service.bat");
wrapperConf = new File(etc, name + "-wrapper.conf");
copyFilteredResourceTo(wrapperConf, "windows/karaf-wrapper.conf", props);
copyFilteredResourceTo(serviceFile, "windows/karaf-service.bat", props);
mkdir(lib);
copyResourceTo(new File(lib, "wrapper.dll"), "windows/wrapper.dll", false);
} else if (os.startsWith("Mac OS X")) {
mkdir(bin);
File file = new File(bin, name + "-wrapper");
copyResourceTo(file, "macosx/karaf-wrapper", false);
chmod(file, "a+x");
serviceFile = new File(bin, name + "-service");
copyFilteredResourceTo(serviceFile, "unix/karaf-service", props);
chmod(serviceFile, "a+x");
wrapperConf = new File(etc, name + "-wrapper.conf");
copyFilteredResourceTo(wrapperConf, "unix/karaf-wrapper.conf", props);
mkdir(lib);
copyResourceTo(new File(lib, "libwrapper.jnilib"), "macosx/libwrapper.jnilib", false);
} else if (os.startsWith("Linux")) {
String arch = System.getProperty("os.arch");
if (arch.equalsIgnoreCase("amd64") || arch.equalsIgnoreCase("x86_64")) {
mkdir(bin);
File file = new File(bin, name + "-wrapper");
copyResourceTo(file, "linux64/karaf-wrapper", false);
chmod(file, "a+x");
serviceFile = new File(bin, name + "-service");
copyResourceTo(file, "unix/karaf-service", false);
chmod(file, "a+x");
wrapperConf = new File(etc, name + "-wrapper.conf");
copyFilteredResourceTo(wrapperConf, "unix/karaf-wrapper.conf", props);
mkdir(lib);
copyResourceTo(new File(lib, "libwrapper.so"), "linux64/libwrapper.so", false);
} else {
mkdir(bin);
File file = new File(bin, name + "-wrapper");
copyResourceTo(file, "linux/karaf-wrapper", false);
chmod(file, "a+x");
serviceFile = new File(bin, name + "-service");
copyFilteredResourceTo(serviceFile, "unix/karaf-service", props);
chmod(serviceFile, "a+x");
wrapperConf = new File(etc, name + "-wrapper.conf");
copyFilteredResourceTo(wrapperConf, "unix/karaf-wrapper.conf", props);
mkdir(lib);
copyResourceTo(new File(lib, "libwrapper.so"), "linux/libwrapper.so", false);
}
} else if (os.startsWith("AIX")) {
String arch = System.getProperty("os.arch");
if (arch.equalsIgnoreCase("ppc64")) {
mkdir(bin);
File file = new File(bin, name + "-wrapper");
copyResourceTo(file, "aix/ppc64/karaf-wrapper", false);
chmod(file, "a+x");
serviceFile = new File(bin, name + "-service");
copyResourceTo(file, "unix/karaf-service", false);
chmod(file, "a+x");
wrapperConf = new File(etc, name + "-wrapper.conf");
copyFilteredResourceTo(wrapperConf, "unix/karaf-wrapper.conf", props);
mkdir(lib);
copyResourceTo(new File(lib, "libwrapper.a"), "aix/ppc64/libwrapper.a", false);
} else {
mkdir(bin);
File file = new File(bin, name + "-wrapper");
copyResourceTo(file, "aix/ppc32/karaf-wrapper", false);
chmod(file, "a+x");
serviceFile = new File(bin, name + "-service");
copyResourceTo(file, "unix/karaf-service", false);
chmod(file, "a+x");
wrapperConf = new File(etc, name + "-wrapper.conf");
copyFilteredResourceTo(wrapperConf, "unix/karaf-wrapper.conf", props);
mkdir(lib);
copyResourceTo(new File(lib, "libwrapper.a"), "aix/ppc32/libwrapper.a", false);
}
} else if (os.startsWith("Solaris") || os.startsWith("SunOS")) {
String arch = System.getProperty("os.arch");
if (arch.equalsIgnoreCase("sparc")) {
mkdir(bin);
File file = new File(bin, name + "-wrapper");
copyResourceTo(file, "solaris/sparc64/karaf-wrapper", false);
chmod(file, "a+x");
serviceFile = new File(bin, name + "-service");
copyResourceTo(file, "unix/karaf-service", false);
chmod(file, "a+x");
wrapperConf = new File(etc, name + "-wrapper.conf");
copyFilteredResourceTo(wrapperConf, "unix/karaf-wrapper.conf", props);
mkdir(lib);
copyResourceTo(new File(lib, "libwrapper.so"), "solaris/sparc64/libwrapper.so", false);
} else if (arch.equalsIgnoreCase("x86")) {
mkdir(bin);
File file = new File(bin, name + "-wrapper");
copyResourceTo(file, "solaris/x86/karaf-wrapper", false);
chmod(file, "a+x");
serviceFile = new File(bin, name + "-service");
copyResourceTo(file, "unix/karaf-service", false);
chmod(file, "a+x");
wrapperConf = new File(etc, name + "-wrapper.conf");
copyFilteredResourceTo(wrapperConf, "unix/karaf-wrapper.conf", props);
mkdir(lib);
copyResourceTo(new File(lib, "libwrapper.so"), "solaris/x86/libwrapper.so", false);
} else {
mkdir(bin);
File file = new File(bin, name + "-wrapper");
copyResourceTo(file, "solaris/sparc32/karaf-wrapper", false);
chmod(file, "a+x");
serviceFile = new File(bin, name + "-service");
copyResourceTo(file, "unix/karaf-service", false);
chmod(file, "a+x");
wrapperConf = new File(etc, name + "-wrapper.conf");
copyFilteredResourceTo(wrapperConf, "unix/karaf-wrapper.conf", props);
mkdir(lib);
copyResourceTo(new File(lib, "libwrapper.so"), "solaris/sparc32/libwrapper.so", false);
}
} else if (os.startsWith("HP-UX") || os.startsWith("HPUX")) {
mkdir(bin);
File file = new File(bin, name + "-wrapper");
copyResourceTo(file, "hpux/parisc64/karaf-wrapper", false);
chmod(file, "a+x");
serviceFile = new File(bin, name + "-service");
copyResourceTo(file, "unix/karaf-service", false);
chmod(file, "a+x");
wrapperConf = new File(etc, name + "-wrapper.conf");
copyFilteredResourceTo(wrapperConf, "unix/karaf-wrapper.conf", props);
mkdir(lib);
copyResourceTo(new File(lib, "libwrapper.sl"), "hpux/parisc64/libwrapper.sl", false);
} else {
throw new IllegalStateException("Your operating system '" + os + "' is not currently supported.");
}
// install the wrapper jar to the lib directory
mkdir(lib);
copyResourceTo(new File(lib, "karaf-wrapper.jar"), "all/karaf-wrapper.jar", false);
mkdir(etc);
createJar(new File(lib, "karaf-wrapper-main.jar"), "org/apache/karaf/wrapper/internal/Main.class");
File[] wrapperPaths = new File[2];
wrapperPaths[0] = wrapperConf;
wrapperPaths[1] = serviceFile;
return wrapperPaths;
}
private void mkdir(File file) {
if (!file.exists()) {
LOGGER.info("Creating missing directory: {}", file.getPath());
System.out.println(Ansi.ansi().a("Creating missing directory: ")
.a(Ansi.Attribute.INTENSITY_BOLD).a(file.getPath()).a(Ansi.Attribute.RESET).toString());
file.mkdirs();
}
}
private void copyResourceTo(File outFile, String resource, boolean text) throws Exception {
if (!outFile.exists()) {
LOGGER.info("Creating file: {}", outFile.getPath());
System.out.println(Ansi.ansi().a("Creating file: ")
.a(Ansi.Attribute.INTENSITY_BOLD).a(outFile.getPath()).a(Ansi.Attribute.RESET).toString());
InputStream is = WrapperServiceImpl.class.getResourceAsStream(resource);
if (is == null) {
throw new IllegalArgumentException("Resource " + resource + " doesn't exist");
}
try {
if (text) {
// read it line at a time so what we can use the platform line ending when we write it out
PrintStream out = new PrintStream(new FileOutputStream(outFile));
try {
Scanner scanner = new Scanner(is);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
LOGGER.info("writing: {}", line);
out.println(line);
}
} finally {
safeClose(out);
}
} else {
// binary resource so just write it out the way it came in
FileOutputStream out = new FileOutputStream(outFile);
try {
int c = 0;
while ((c = is.read()) >= 0) {
out.write(c);
}
} finally {
safeClose(out);
}
}
} finally {
safeClose(is);
}
} else {
LOGGER.warn("File already exists. Move it out of the way if you wish to recreate it: {}", outFile.getPath());
System.out.println(Ansi.ansi()
.fg(Ansi.Color.RED).a("File already exists").a(Ansi.Attribute.RESET)
.a(". Move it out of the way if you wish to recreate it: ").a(outFile.getPath()).toString());
}
}
private void copyFilteredResourceTo(File outFile, String resource, HashMap<String, String> props) throws Exception {
if (!outFile.exists()) {
LOGGER.info("Creating file: {}", outFile.getPath());
System.out.println(Ansi.ansi().a("Creating file: ")
.a(Ansi.Attribute.INTENSITY_BOLD).a(outFile.getPath()).a(Ansi.Attribute.RESET).toString());
InputStream is = WrapperServiceImpl.class.getResourceAsStream(resource);
if (is == null) {
throw new IllegalArgumentException("Resource " + resource + " doesn't exist");
}
try {
// read it line at a time so that we can use the platform line ending when we write it out
PrintStream out = new PrintStream(new FileOutputStream(outFile));
try {
Scanner scanner = new Scanner(is);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
line = filter(line, props);
out.println(line);
}
} finally {
safeClose(out);
}
} finally {
safeClose(is);
}
} else {
LOGGER.warn("File already exists. Move it out of the way if you wish to recreate it: {}", outFile.getPath());
System.out.println(Ansi.ansi()
.fg(Ansi.Color.RED).a("File already exists").a(Ansi.Attribute.RESET)
.a(". Move it out of the way if you wish to recreate it: ").a(outFile.getPath()).toString());
}
}
private void safeClose(InputStream is) throws IOException {
if (is == null)
return;
try {
is.close();
} catch (Throwable ignore) {
// nothing to do
}
}
private void safeClose(OutputStream is) throws IOException {
if (is == null)
return;
try {
is.close();
} catch (Throwable ignore) {
// nothing to do
}
}
private String filter(String line, HashMap<String, String> props) {
for (Map.Entry<String, String> i : props.entrySet()) {
int p1 = line.indexOf(i.getKey());
if (p1 >= 0) {
String l1 = line.substring(0, p1);
String l2 = line.substring(p1 + i.getKey().length());
line = l1 + i.getValue() + l2;
}
}
return line;
}
private int chmod(File serviceFile, String mode) throws Exception {
ProcessBuilder builder = new ProcessBuilder();
builder.command("chmod", mode, serviceFile.getCanonicalPath());
Process p = builder.start();
PumpStreamHandler handler = new PumpStreamHandler(System.in, System.out, System.err);
handler.attach(p);
handler.start();
int status = p.waitFor();
handler.stop();
return status;
}
private void createJar(File outFile, String resource) throws Exception {
if (!outFile.exists()) {
LOGGER.info("Creating file: {}", outFile.getPath());
System.out.println(Ansi.ansi().a("Creating file: ")
.a(Ansi.Attribute.INTENSITY_BOLD).a(outFile.getPath()).a(Ansi.Attribute.RESET).toString());
InputStream is = getClass().getClassLoader().getResourceAsStream(resource);
if (is == null) {
throw new IllegalStateException("Resource " + resource + " not found!");
}
try {
JarOutputStream jar = new JarOutputStream(new FileOutputStream(outFile));
int idx = resource.indexOf('/');
while (idx > 0) {
jar.putNextEntry(new ZipEntry(resource.substring(0, idx)));
jar.closeEntry();
idx = resource.indexOf('/', idx + 1);
}
jar.putNextEntry(new ZipEntry(resource));
int c;
while ((c = is.read()) >= 0) {
jar.write(c);
}
jar.closeEntry();
jar.close();
} finally {
safeClose(is);
}
}
}
}
| true | true | public File[] install(String name, String displayName, String description, String startType) throws Exception {
File base = new File(System.getProperty("karaf.base"));
File bin = new File(base, "bin");
File etc = new File(base, "etc");
File lib = new File(base, "lib");
if (name == null) {
name = base.getName();
}
HashMap<String, String> props = new HashMap<String, String>();
props.put("${karaf.home}", System.getProperty("karaf.home"));
props.put("${karaf.base}", base.getPath());
props.put("${karaf.data}", System.getProperty("karaf.data"));
props.put("${name}", name);
props.put("${displayName}", displayName);
props.put("${description}", description);
props.put("${startType}", startType);
String os = System.getProperty("os.name", "Unknown");
File serviceFile = null;
File wrapperConf = null;
if (os.startsWith("Win")) {
mkdir(bin);
copyResourceTo(new File(bin, name + "-wrapper.exec"), "windows/karaf-wrapper.exec", false);
serviceFile = new File(bin, name + "-service.bat");
wrapperConf = new File(etc, name + "-wrapper.conf");
copyFilteredResourceTo(wrapperConf, "windows/karaf-wrapper.conf", props);
copyFilteredResourceTo(serviceFile, "windows/karaf-service.bat", props);
mkdir(lib);
copyResourceTo(new File(lib, "wrapper.dll"), "windows/wrapper.dll", false);
} else if (os.startsWith("Mac OS X")) {
mkdir(bin);
File file = new File(bin, name + "-wrapper");
copyResourceTo(file, "macosx/karaf-wrapper", false);
chmod(file, "a+x");
serviceFile = new File(bin, name + "-service");
copyFilteredResourceTo(serviceFile, "unix/karaf-service", props);
chmod(serviceFile, "a+x");
wrapperConf = new File(etc, name + "-wrapper.conf");
copyFilteredResourceTo(wrapperConf, "unix/karaf-wrapper.conf", props);
mkdir(lib);
copyResourceTo(new File(lib, "libwrapper.jnilib"), "macosx/libwrapper.jnilib", false);
} else if (os.startsWith("Linux")) {
String arch = System.getProperty("os.arch");
if (arch.equalsIgnoreCase("amd64") || arch.equalsIgnoreCase("x86_64")) {
mkdir(bin);
File file = new File(bin, name + "-wrapper");
copyResourceTo(file, "linux64/karaf-wrapper", false);
chmod(file, "a+x");
serviceFile = new File(bin, name + "-service");
copyResourceTo(file, "unix/karaf-service", false);
chmod(file, "a+x");
wrapperConf = new File(etc, name + "-wrapper.conf");
copyFilteredResourceTo(wrapperConf, "unix/karaf-wrapper.conf", props);
mkdir(lib);
copyResourceTo(new File(lib, "libwrapper.so"), "linux64/libwrapper.so", false);
} else {
mkdir(bin);
File file = new File(bin, name + "-wrapper");
copyResourceTo(file, "linux/karaf-wrapper", false);
chmod(file, "a+x");
serviceFile = new File(bin, name + "-service");
copyFilteredResourceTo(serviceFile, "unix/karaf-service", props);
chmod(serviceFile, "a+x");
wrapperConf = new File(etc, name + "-wrapper.conf");
copyFilteredResourceTo(wrapperConf, "unix/karaf-wrapper.conf", props);
mkdir(lib);
copyResourceTo(new File(lib, "libwrapper.so"), "linux/libwrapper.so", false);
}
} else if (os.startsWith("AIX")) {
String arch = System.getProperty("os.arch");
if (arch.equalsIgnoreCase("ppc64")) {
mkdir(bin);
File file = new File(bin, name + "-wrapper");
copyResourceTo(file, "aix/ppc64/karaf-wrapper", false);
chmod(file, "a+x");
serviceFile = new File(bin, name + "-service");
copyResourceTo(file, "unix/karaf-service", false);
chmod(file, "a+x");
wrapperConf = new File(etc, name + "-wrapper.conf");
copyFilteredResourceTo(wrapperConf, "unix/karaf-wrapper.conf", props);
mkdir(lib);
copyResourceTo(new File(lib, "libwrapper.a"), "aix/ppc64/libwrapper.a", false);
} else {
mkdir(bin);
File file = new File(bin, name + "-wrapper");
copyResourceTo(file, "aix/ppc32/karaf-wrapper", false);
chmod(file, "a+x");
serviceFile = new File(bin, name + "-service");
copyResourceTo(file, "unix/karaf-service", false);
chmod(file, "a+x");
wrapperConf = new File(etc, name + "-wrapper.conf");
copyFilteredResourceTo(wrapperConf, "unix/karaf-wrapper.conf", props);
mkdir(lib);
copyResourceTo(new File(lib, "libwrapper.a"), "aix/ppc32/libwrapper.a", false);
}
} else if (os.startsWith("Solaris") || os.startsWith("SunOS")) {
String arch = System.getProperty("os.arch");
if (arch.equalsIgnoreCase("sparc")) {
mkdir(bin);
File file = new File(bin, name + "-wrapper");
copyResourceTo(file, "solaris/sparc64/karaf-wrapper", false);
chmod(file, "a+x");
serviceFile = new File(bin, name + "-service");
copyResourceTo(file, "unix/karaf-service", false);
chmod(file, "a+x");
wrapperConf = new File(etc, name + "-wrapper.conf");
copyFilteredResourceTo(wrapperConf, "unix/karaf-wrapper.conf", props);
mkdir(lib);
copyResourceTo(new File(lib, "libwrapper.so"), "solaris/sparc64/libwrapper.so", false);
} else if (arch.equalsIgnoreCase("x86")) {
mkdir(bin);
File file = new File(bin, name + "-wrapper");
copyResourceTo(file, "solaris/x86/karaf-wrapper", false);
chmod(file, "a+x");
serviceFile = new File(bin, name + "-service");
copyResourceTo(file, "unix/karaf-service", false);
chmod(file, "a+x");
wrapperConf = new File(etc, name + "-wrapper.conf");
copyFilteredResourceTo(wrapperConf, "unix/karaf-wrapper.conf", props);
mkdir(lib);
copyResourceTo(new File(lib, "libwrapper.so"), "solaris/x86/libwrapper.so", false);
} else {
mkdir(bin);
File file = new File(bin, name + "-wrapper");
copyResourceTo(file, "solaris/sparc32/karaf-wrapper", false);
chmod(file, "a+x");
serviceFile = new File(bin, name + "-service");
copyResourceTo(file, "unix/karaf-service", false);
chmod(file, "a+x");
wrapperConf = new File(etc, name + "-wrapper.conf");
copyFilteredResourceTo(wrapperConf, "unix/karaf-wrapper.conf", props);
mkdir(lib);
copyResourceTo(new File(lib, "libwrapper.so"), "solaris/sparc32/libwrapper.so", false);
}
} else if (os.startsWith("HP-UX") || os.startsWith("HPUX")) {
mkdir(bin);
File file = new File(bin, name + "-wrapper");
copyResourceTo(file, "hpux/parisc64/karaf-wrapper", false);
chmod(file, "a+x");
serviceFile = new File(bin, name + "-service");
copyResourceTo(file, "unix/karaf-service", false);
chmod(file, "a+x");
wrapperConf = new File(etc, name + "-wrapper.conf");
copyFilteredResourceTo(wrapperConf, "unix/karaf-wrapper.conf", props);
mkdir(lib);
copyResourceTo(new File(lib, "libwrapper.sl"), "hpux/parisc64/libwrapper.sl", false);
} else {
throw new IllegalStateException("Your operating system '" + os + "' is not currently supported.");
}
// install the wrapper jar to the lib directory
mkdir(lib);
copyResourceTo(new File(lib, "karaf-wrapper.jar"), "all/karaf-wrapper.jar", false);
mkdir(etc);
createJar(new File(lib, "karaf-wrapper-main.jar"), "org/apache/karaf/wrapper/internal/Main.class");
File[] wrapperPaths = new File[2];
wrapperPaths[0] = wrapperConf;
wrapperPaths[1] = serviceFile;
return wrapperPaths;
}
| public File[] install(String name, String displayName, String description, String startType) throws Exception {
File base = new File(System.getProperty("karaf.base"));
File bin = new File(base, "bin");
File etc = new File(base, "etc");
File lib = new File(base, "lib");
if (name == null) {
name = base.getName();
}
HashMap<String, String> props = new HashMap<String, String>();
props.put("${karaf.home}", System.getProperty("karaf.home"));
props.put("${karaf.base}", base.getPath());
props.put("${karaf.data}", System.getProperty("karaf.data"));
props.put("${name}", name);
props.put("${displayName}", displayName);
props.put("${description}", description);
props.put("${startType}", startType);
String os = System.getProperty("os.name", "Unknown");
File serviceFile = null;
File wrapperConf = null;
if (os.startsWith("Win")) {
mkdir(bin);
copyResourceTo(new File(bin, name + "-wrapper.exe"), "windows/karaf-wrapper.exe", false);
serviceFile = new File(bin, name + "-service.bat");
wrapperConf = new File(etc, name + "-wrapper.conf");
copyFilteredResourceTo(wrapperConf, "windows/karaf-wrapper.conf", props);
copyFilteredResourceTo(serviceFile, "windows/karaf-service.bat", props);
mkdir(lib);
copyResourceTo(new File(lib, "wrapper.dll"), "windows/wrapper.dll", false);
} else if (os.startsWith("Mac OS X")) {
mkdir(bin);
File file = new File(bin, name + "-wrapper");
copyResourceTo(file, "macosx/karaf-wrapper", false);
chmod(file, "a+x");
serviceFile = new File(bin, name + "-service");
copyFilteredResourceTo(serviceFile, "unix/karaf-service", props);
chmod(serviceFile, "a+x");
wrapperConf = new File(etc, name + "-wrapper.conf");
copyFilteredResourceTo(wrapperConf, "unix/karaf-wrapper.conf", props);
mkdir(lib);
copyResourceTo(new File(lib, "libwrapper.jnilib"), "macosx/libwrapper.jnilib", false);
} else if (os.startsWith("Linux")) {
String arch = System.getProperty("os.arch");
if (arch.equalsIgnoreCase("amd64") || arch.equalsIgnoreCase("x86_64")) {
mkdir(bin);
File file = new File(bin, name + "-wrapper");
copyResourceTo(file, "linux64/karaf-wrapper", false);
chmod(file, "a+x");
serviceFile = new File(bin, name + "-service");
copyResourceTo(file, "unix/karaf-service", false);
chmod(file, "a+x");
wrapperConf = new File(etc, name + "-wrapper.conf");
copyFilteredResourceTo(wrapperConf, "unix/karaf-wrapper.conf", props);
mkdir(lib);
copyResourceTo(new File(lib, "libwrapper.so"), "linux64/libwrapper.so", false);
} else {
mkdir(bin);
File file = new File(bin, name + "-wrapper");
copyResourceTo(file, "linux/karaf-wrapper", false);
chmod(file, "a+x");
serviceFile = new File(bin, name + "-service");
copyFilteredResourceTo(serviceFile, "unix/karaf-service", props);
chmod(serviceFile, "a+x");
wrapperConf = new File(etc, name + "-wrapper.conf");
copyFilteredResourceTo(wrapperConf, "unix/karaf-wrapper.conf", props);
mkdir(lib);
copyResourceTo(new File(lib, "libwrapper.so"), "linux/libwrapper.so", false);
}
} else if (os.startsWith("AIX")) {
String arch = System.getProperty("os.arch");
if (arch.equalsIgnoreCase("ppc64")) {
mkdir(bin);
File file = new File(bin, name + "-wrapper");
copyResourceTo(file, "aix/ppc64/karaf-wrapper", false);
chmod(file, "a+x");
serviceFile = new File(bin, name + "-service");
copyResourceTo(file, "unix/karaf-service", false);
chmod(file, "a+x");
wrapperConf = new File(etc, name + "-wrapper.conf");
copyFilteredResourceTo(wrapperConf, "unix/karaf-wrapper.conf", props);
mkdir(lib);
copyResourceTo(new File(lib, "libwrapper.a"), "aix/ppc64/libwrapper.a", false);
} else {
mkdir(bin);
File file = new File(bin, name + "-wrapper");
copyResourceTo(file, "aix/ppc32/karaf-wrapper", false);
chmod(file, "a+x");
serviceFile = new File(bin, name + "-service");
copyResourceTo(file, "unix/karaf-service", false);
chmod(file, "a+x");
wrapperConf = new File(etc, name + "-wrapper.conf");
copyFilteredResourceTo(wrapperConf, "unix/karaf-wrapper.conf", props);
mkdir(lib);
copyResourceTo(new File(lib, "libwrapper.a"), "aix/ppc32/libwrapper.a", false);
}
} else if (os.startsWith("Solaris") || os.startsWith("SunOS")) {
String arch = System.getProperty("os.arch");
if (arch.equalsIgnoreCase("sparc")) {
mkdir(bin);
File file = new File(bin, name + "-wrapper");
copyResourceTo(file, "solaris/sparc64/karaf-wrapper", false);
chmod(file, "a+x");
serviceFile = new File(bin, name + "-service");
copyResourceTo(file, "unix/karaf-service", false);
chmod(file, "a+x");
wrapperConf = new File(etc, name + "-wrapper.conf");
copyFilteredResourceTo(wrapperConf, "unix/karaf-wrapper.conf", props);
mkdir(lib);
copyResourceTo(new File(lib, "libwrapper.so"), "solaris/sparc64/libwrapper.so", false);
} else if (arch.equalsIgnoreCase("x86")) {
mkdir(bin);
File file = new File(bin, name + "-wrapper");
copyResourceTo(file, "solaris/x86/karaf-wrapper", false);
chmod(file, "a+x");
serviceFile = new File(bin, name + "-service");
copyResourceTo(file, "unix/karaf-service", false);
chmod(file, "a+x");
wrapperConf = new File(etc, name + "-wrapper.conf");
copyFilteredResourceTo(wrapperConf, "unix/karaf-wrapper.conf", props);
mkdir(lib);
copyResourceTo(new File(lib, "libwrapper.so"), "solaris/x86/libwrapper.so", false);
} else {
mkdir(bin);
File file = new File(bin, name + "-wrapper");
copyResourceTo(file, "solaris/sparc32/karaf-wrapper", false);
chmod(file, "a+x");
serviceFile = new File(bin, name + "-service");
copyResourceTo(file, "unix/karaf-service", false);
chmod(file, "a+x");
wrapperConf = new File(etc, name + "-wrapper.conf");
copyFilteredResourceTo(wrapperConf, "unix/karaf-wrapper.conf", props);
mkdir(lib);
copyResourceTo(new File(lib, "libwrapper.so"), "solaris/sparc32/libwrapper.so", false);
}
} else if (os.startsWith("HP-UX") || os.startsWith("HPUX")) {
mkdir(bin);
File file = new File(bin, name + "-wrapper");
copyResourceTo(file, "hpux/parisc64/karaf-wrapper", false);
chmod(file, "a+x");
serviceFile = new File(bin, name + "-service");
copyResourceTo(file, "unix/karaf-service", false);
chmod(file, "a+x");
wrapperConf = new File(etc, name + "-wrapper.conf");
copyFilteredResourceTo(wrapperConf, "unix/karaf-wrapper.conf", props);
mkdir(lib);
copyResourceTo(new File(lib, "libwrapper.sl"), "hpux/parisc64/libwrapper.sl", false);
} else {
throw new IllegalStateException("Your operating system '" + os + "' is not currently supported.");
}
// install the wrapper jar to the lib directory
mkdir(lib);
copyResourceTo(new File(lib, "karaf-wrapper.jar"), "all/karaf-wrapper.jar", false);
mkdir(etc);
createJar(new File(lib, "karaf-wrapper-main.jar"), "org/apache/karaf/wrapper/internal/Main.class");
File[] wrapperPaths = new File[2];
wrapperPaths[0] = wrapperConf;
wrapperPaths[1] = serviceFile;
return wrapperPaths;
}
|
diff --git a/src/cytoscape/data/readers/GMLReader.java b/src/cytoscape/data/readers/GMLReader.java
index af5cfdf05..e3d6324d7 100644
--- a/src/cytoscape/data/readers/GMLReader.java
+++ b/src/cytoscape/data/readers/GMLReader.java
@@ -1,295 +1,295 @@
// GMLReader.java
/** Copyright (c) 2002 Institute for Systems Biology and the Whitehead Institute
**
** This library is free software; you can redistribute it and/or modify it
** under the terms of the GNU Lesser General Public License as published
** by the Free Software Foundation; either version 2.1 of the License, or
** any later version.
**
** This library is distributed in the hope that it will be useful, but
** WITHOUT ANY WARRANTY, WITHOUT EVEN THE IMPLIED WARRANTY OF
** MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. The software and
** documentation provided hereunder is on an "as is" basis, and the
** Institute for Systems Biology and the Whitehead Institute
** have no obligations to provide maintenance, support,
** updates, enhancements or modifications. In no event shall the
** Institute for Systems Biology and the Whitehead Institute
** be liable to any party for direct, indirect, special,
** incidental or consequential damages, including lost profits, arising
** out of the use of this software and its documentation, even if the
** Institute for Systems Biology and the Whitehead Institute
** have been advised of the possibility of such damage. See
** the GNU Lesser General Public License for more details.
**
** You should have received a copy of the GNU Lesser General Public License
** along with this library; if not, write to the Free Software Foundation,
** Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
**/
//-------------------------------------------------------------------------------------
// $Revision$
// $Date$
// $Author$
//-----------------------------------------------------------------------------------
package cytoscape.data.readers;
//-----------------------------------------------------------------------------------------
import java.util.*;
import giny.model.*;
import giny.view.*;
import cytoscape.data.CyNetwork;
import cytoscape.util.GinyFactory;
import cytoscape.data.GraphObjAttributes;
// add text here
//-------------------------------------------------------------------------------------
/**
* Reader for graph in GML format. Given the filename provides the graph and
* attributes objects constructed from the file.
*/
public class GMLReader implements GraphReader {
private String filename;
GraphObjAttributes edgeAttributes;// = new GraphObjAttributes ();
GraphObjAttributes nodeAttributes;// = new GraphObjAttributes ();
//GraphObjAttributes gmlGraphicsAtt = new GraphObjAttributes ();
RootGraph rootGraph;
GMLTree gmlTree;
/**
* @param filename The GML file to be read in
*/
public GMLReader ( String filename ) {
this.filename = filename;
//read();
}
/**
* Equivalent to read(), as names in a GML file are not currently canonicalized.
*/
public void read ( boolean canonicalize ) {
read();
}
/**
* This will read AND create a Graph from the file specified in the constructor
*/
public void read () {
//move this to later when we know how many nodes
//edges we are going to add
//rootGraph = GinyFactory.createRootGraph();
// create and read the GML file
gmlTree = new GMLTree(filename);
nodeAttributes = new GraphObjAttributes();
edgeAttributes = new GraphObjAttributes();
// gmlGraphicsAtt = new GraphObjAttributes();
Vector nodeIds = gmlTree.getVector("graph|node|id","|",GMLTree.INTEGER);
Vector nodeLabels = gmlTree.getVector("graph|node|label","|",GMLTree.STRING);
// in case gml node ids are not ordered consecutively (0..n)
Hashtable nodeNameMap = new Hashtable(nodeIds.size());
for(int i=0; i<nodeIds.size(); i++) {
nodeNameMap.put(nodeIds.get(i), nodeLabels.get(i));
}
Vector edgeSources = gmlTree.getVector("graph|edge|source","|",GMLTree.INTEGER);
Vector edgeTargets = gmlTree.getVector("graph|edge|target","|",GMLTree.INTEGER);
Vector edgeLabels = gmlTree.getVector("graph|edge|label","|",GMLTree.STRING);
//Use the number of ids to get the number of nodes in hte graph
//Use the number of source ids to get the number of edges in hte graph
//(since every edge must have some source node)
rootGraph = GinyFactory.createRootGraph(nodeIds.size(),edgeSources.size());
//---------------------------------------------------------------------------
// set a default edge type if it's not defined in the GML file
// need a better system for defining the default...
String et = "pp";
if(edgeLabels.isEmpty()) {
for(int i=0; i < edgeSources.size(); i++) {
edgeLabels.add(et);
}
}
//---------------------------------------------------------------------------
// loop through all of the nodes (using a hash to avoid duplicates)
// adding nodes to the rootGraph.
// Create the nodeName mapping in nodeAttributes
//---------------------------------------------------------------------------
//Hashtable nodeHash = new Hashtable ();
Hashtable gmlId2GINYId = new Hashtable();
String nodeName, interactionType;
rootGraph.createNodes(nodeIds.size());
//for(int i=0; i<nodeIds.size(); i++) {
for (Iterator nodeIt = rootGraph.nodesIterator(),idIt = nodeIds.iterator();nodeIt.hasNext();) {
//nodeName = (String) nodeNameMap.get(nodeIds.get(i));
Integer gmlId = (Integer)idIt.next();
nodeName = (String)nodeNameMap.get(gmlId);
//if(canonicalize) nodeName = canonicalizeName(nodeName);
//if (!nodeHash.containsKey(nodeName)) {
//Node node = rootGraph.getNode(rootGraph.createNode());
Node node = (Node)nodeIt.next();
node.setIdentifier(nodeName);
//nodeHash.put(nodeName, node);
gmlId2GINYId.put(gmlId,new Integer(node.getRootGraphIndex()));
nodeAttributes.addNameMapping(nodeName, node);
//}
}
//Vector nodeHeight = gmlTree.getVector("graph|node|graphics|h","|",GMLTree.DOUBLE);
//Vector nodeWidth = gmlTree.getVector("graph|node|graphics|w","|",GMLTree.DOUBLE);
//Vector nodeType = gmlTree.getVector("graph|node|graphics|type","|",GMLTree.STRING);
//if( (nodeHeight.size() == nodeIds.size()) &&
//(nodeWidth.size() == nodeIds.size()) &&
//(nodeType.size() == nodeIds.size())
//) {
//for(int i=0; i<nodeIds.size(); i++) {
//nodeName = (String) nodeNameMap.get(nodeIds.get(i));
//gmlGraphicsAtt.set("node.h", nodeName, (Double) nodeHeight.get(i));
//gmlGraphicsAtt.set("node.w", nodeName, (Double) nodeWidth.get(i));
//gmlGraphicsAtt.set("node.type", nodeName, (String) nodeType.get(i));
//}
//}
//---------------------------------------------------------------------------
// loop over the interactions creating edges between all sources and their
// respective targets.
// for each edge, save the source-target pair, and their interaction type,
// in edgeAttributes -- a hash of a hash of name-value pairs, like this:
// ??? edgeAttributes ["interaction"] = interactionHash
// ??? interactionHash [sourceNode::targetNode] = "pd"
//---------------------------------------------------------------------------
int [] sources,targets;
sources = new int[edgeSources.size()];
targets = new int[edgeTargets.size()];
//Vector edgeNames = new Vector(edgeSources.size());
for (int i=0; i < edgeSources.size(); i++) {
//Node sourceNode = (Node) nodeHash.get(sourceName);
//Node targetNode = (Node) nodeHash.get(targetName);
sources[i] = ((Integer)gmlId2GINYId.get(edgeSources.get(i))).intValue();
targets[i] = ((Integer)gmlId2GINYId.get(edgeTargets.get(i))).intValue();
//Edge edge = rootGraph.getEdge(rootGraph.createEdge(sourceNode, targetNode));
//int edge = rootGraph.createEdge(sourceID,targetID);
//determine the name for the edge
//sourceName = (String) nodeNameMap.get(edgeSources.get(i));
//targetName = (String) nodeNameMap.get(edgeTargets.get(i));
//interactionType = (String) edgeLabels.get(i);
//edgeName = sourceName + " (" + interactionType + ") " + targetName;
//int previousMatchingEntries = edgeAttributes.countIdentical(edgeName);
//if (previousMatchingEntries > 0)
//edgeName = edgeName + "_" + previousMatchingEntries;
//edgeAttributes.add("interaction", edgeName, interactionType);
//edgeAttributes.addNameMapping(edgeName, edge);
}
rootGraph.createEdges(sources,targets,false);
- for ( Iterator edgeIt = rootGraph.edgesIterator(),sourceIt = edgeSources.iterator(),targetIt = edgeTargets.iterator(),labelIt = edgeLabels.iterator();labelIt.hasNext();) {
+ for ( Iterator edgeIt = rootGraph.edgesList().iterator(),sourceIt = edgeSources.iterator(),targetIt = edgeTargets.iterator(),labelIt = edgeLabels.iterator();edgeIt.hasNext();) {
interactionType = (String)labelIt.next();
String edgeName = ""+nodeNameMap.get(sourceIt.next())+" ("+interactionType+") "+nodeNameMap.get(targetIt.next());
int previousMatchingEntries = edgeAttributes.countIdentical(edgeName);
if (previousMatchingEntries > 0){
edgeName = edgeName + "_" + previousMatchingEntries;
}
edgeAttributes.add("interaction", edgeName, interactionType);
edgeAttributes.addNameMapping(edgeName, edgeIt.next());
} // end of for ()
} // read
/**
* @return null, there is no GML reader available outside of Y-Files right now
*/
public RootGraph getRootGraph () {
return rootGraph;
}
/**
* @return the node attributes that were read in from the GML file.
*/
public GraphObjAttributes getNodeAttributes () {
return nodeAttributes;
}
/**
* @return the edge attributes that were read in from the GML file.
*/
public GraphObjAttributes getEdgeAttributes () {
return edgeAttributes;
}
/**
* @return the gmlGraphics attributes that were read in from the GML file.
*/
//public GraphObjAttributes getGMLAttributes () {
// return gmlGraphicsAtt;
//}
//------------------------------------------------------------------------------
// called only when we have a CyWindow
//
// GMLReader.layoutByGML(geometryFilename, cyWindow.getView(), cyWindow.getNetwork());
//
//public static void layoutByGML(String geometryFilename, GraphView myView, CyNetwork myNetwork){
public void layout(GraphView myView){
if(gmlTree == null){
throw new RuntimeException("Failed to read gml file on initialization");
}
else {
Vector nodeLabels = gmlTree.getVector("graph|node|label","|",GMLTree.STRING);
Vector nodeX = gmlTree.getVector("graph|node|graphics|x","|",GMLTree.DOUBLE);
Vector nodeY = gmlTree.getVector("graph|node|graphics|y","|",GMLTree.DOUBLE);
Vector nodeHeight = gmlTree.getVector("graph|node|graphics|h","|",GMLTree.DOUBLE);
Vector nodeWidth = gmlTree.getVector("graph|node|graphics|w","|",GMLTree.DOUBLE);
Vector nodeType = gmlTree.getVector("graph|node|graphics|type","|",GMLTree.STRING);
if( (nodeLabels.size() == myView.getRootGraph().getNodeCount()) &&
(nodeX.size() == myView.getRootGraph().getNodeCount()) &&
(nodeY.size() == myView.getRootGraph().getNodeCount()) ) {
//Iterator it = nodeLabels.iterator();
//GraphObjAttributes nodeAttributes = myNetwork.getNodeAttributes();
//for(int i=0;i<nodeLabels.size();i++){
String ELLIPSE = "ellipse";
String RECTANGLE = "rectangle";
int i=0;
for (Iterator nodeIt = rootGraph.nodesIterator();nodeIt.hasNext();i++) {
Node current = (Node)nodeIt.next();
String nodeName = (String)nodeLabels.get(i);
if ( !current.getIdentifier().equals(nodeName)) {
throw new RuntimeException("Unexpected node ordering when laying out");
} // end of if ()
Number X = (Number) nodeX.get(i);
Number Y = (Number) nodeY.get(i);
//get the node associated with that node label
//Node current = (Node)nodeAttributes.getGraphObject(nodeName);
NodeView currentView = myView.getNodeView(current);
currentView.setXPosition(X.doubleValue());
currentView.setYPosition(Y.doubleValue());
if( nodeHeight.size() == nodeLabels.size() )
currentView.setHeight( ((Double) nodeHeight.get(i)).doubleValue());
if( nodeWidth.size() == nodeLabels.size() )
currentView.setWidth( ((Double) nodeWidth.get(i)).doubleValue());
if( nodeType.size() == nodeLabels.size() ) {
String nType = (String) nodeType.get(i);
if( nType.equals(ELLIPSE) ) currentView.setShape(NodeView.ELLIPSE);
else if( nType.equals(RECTANGLE) ) currentView.setShape(NodeView.RECTANGLE);
}
}
}
}
}
}
| true | true | public void read () {
//move this to later when we know how many nodes
//edges we are going to add
//rootGraph = GinyFactory.createRootGraph();
// create and read the GML file
gmlTree = new GMLTree(filename);
nodeAttributes = new GraphObjAttributes();
edgeAttributes = new GraphObjAttributes();
// gmlGraphicsAtt = new GraphObjAttributes();
Vector nodeIds = gmlTree.getVector("graph|node|id","|",GMLTree.INTEGER);
Vector nodeLabels = gmlTree.getVector("graph|node|label","|",GMLTree.STRING);
// in case gml node ids are not ordered consecutively (0..n)
Hashtable nodeNameMap = new Hashtable(nodeIds.size());
for(int i=0; i<nodeIds.size(); i++) {
nodeNameMap.put(nodeIds.get(i), nodeLabels.get(i));
}
Vector edgeSources = gmlTree.getVector("graph|edge|source","|",GMLTree.INTEGER);
Vector edgeTargets = gmlTree.getVector("graph|edge|target","|",GMLTree.INTEGER);
Vector edgeLabels = gmlTree.getVector("graph|edge|label","|",GMLTree.STRING);
//Use the number of ids to get the number of nodes in hte graph
//Use the number of source ids to get the number of edges in hte graph
//(since every edge must have some source node)
rootGraph = GinyFactory.createRootGraph(nodeIds.size(),edgeSources.size());
//---------------------------------------------------------------------------
// set a default edge type if it's not defined in the GML file
// need a better system for defining the default...
String et = "pp";
if(edgeLabels.isEmpty()) {
for(int i=0; i < edgeSources.size(); i++) {
edgeLabels.add(et);
}
}
//---------------------------------------------------------------------------
// loop through all of the nodes (using a hash to avoid duplicates)
// adding nodes to the rootGraph.
// Create the nodeName mapping in nodeAttributes
//---------------------------------------------------------------------------
//Hashtable nodeHash = new Hashtable ();
Hashtable gmlId2GINYId = new Hashtable();
String nodeName, interactionType;
rootGraph.createNodes(nodeIds.size());
//for(int i=0; i<nodeIds.size(); i++) {
for (Iterator nodeIt = rootGraph.nodesIterator(),idIt = nodeIds.iterator();nodeIt.hasNext();) {
//nodeName = (String) nodeNameMap.get(nodeIds.get(i));
Integer gmlId = (Integer)idIt.next();
nodeName = (String)nodeNameMap.get(gmlId);
//if(canonicalize) nodeName = canonicalizeName(nodeName);
//if (!nodeHash.containsKey(nodeName)) {
//Node node = rootGraph.getNode(rootGraph.createNode());
Node node = (Node)nodeIt.next();
node.setIdentifier(nodeName);
//nodeHash.put(nodeName, node);
gmlId2GINYId.put(gmlId,new Integer(node.getRootGraphIndex()));
nodeAttributes.addNameMapping(nodeName, node);
//}
}
//Vector nodeHeight = gmlTree.getVector("graph|node|graphics|h","|",GMLTree.DOUBLE);
//Vector nodeWidth = gmlTree.getVector("graph|node|graphics|w","|",GMLTree.DOUBLE);
//Vector nodeType = gmlTree.getVector("graph|node|graphics|type","|",GMLTree.STRING);
//if( (nodeHeight.size() == nodeIds.size()) &&
//(nodeWidth.size() == nodeIds.size()) &&
//(nodeType.size() == nodeIds.size())
//) {
//for(int i=0; i<nodeIds.size(); i++) {
//nodeName = (String) nodeNameMap.get(nodeIds.get(i));
//gmlGraphicsAtt.set("node.h", nodeName, (Double) nodeHeight.get(i));
//gmlGraphicsAtt.set("node.w", nodeName, (Double) nodeWidth.get(i));
//gmlGraphicsAtt.set("node.type", nodeName, (String) nodeType.get(i));
//}
//}
//---------------------------------------------------------------------------
// loop over the interactions creating edges between all sources and their
// respective targets.
// for each edge, save the source-target pair, and their interaction type,
// in edgeAttributes -- a hash of a hash of name-value pairs, like this:
// ??? edgeAttributes ["interaction"] = interactionHash
// ??? interactionHash [sourceNode::targetNode] = "pd"
//---------------------------------------------------------------------------
int [] sources,targets;
sources = new int[edgeSources.size()];
targets = new int[edgeTargets.size()];
//Vector edgeNames = new Vector(edgeSources.size());
for (int i=0; i < edgeSources.size(); i++) {
//Node sourceNode = (Node) nodeHash.get(sourceName);
//Node targetNode = (Node) nodeHash.get(targetName);
sources[i] = ((Integer)gmlId2GINYId.get(edgeSources.get(i))).intValue();
targets[i] = ((Integer)gmlId2GINYId.get(edgeTargets.get(i))).intValue();
//Edge edge = rootGraph.getEdge(rootGraph.createEdge(sourceNode, targetNode));
//int edge = rootGraph.createEdge(sourceID,targetID);
//determine the name for the edge
//sourceName = (String) nodeNameMap.get(edgeSources.get(i));
//targetName = (String) nodeNameMap.get(edgeTargets.get(i));
//interactionType = (String) edgeLabels.get(i);
//edgeName = sourceName + " (" + interactionType + ") " + targetName;
//int previousMatchingEntries = edgeAttributes.countIdentical(edgeName);
//if (previousMatchingEntries > 0)
//edgeName = edgeName + "_" + previousMatchingEntries;
//edgeAttributes.add("interaction", edgeName, interactionType);
//edgeAttributes.addNameMapping(edgeName, edge);
}
rootGraph.createEdges(sources,targets,false);
for ( Iterator edgeIt = rootGraph.edgesIterator(),sourceIt = edgeSources.iterator(),targetIt = edgeTargets.iterator(),labelIt = edgeLabels.iterator();labelIt.hasNext();) {
interactionType = (String)labelIt.next();
String edgeName = ""+nodeNameMap.get(sourceIt.next())+" ("+interactionType+") "+nodeNameMap.get(targetIt.next());
int previousMatchingEntries = edgeAttributes.countIdentical(edgeName);
if (previousMatchingEntries > 0){
edgeName = edgeName + "_" + previousMatchingEntries;
}
edgeAttributes.add("interaction", edgeName, interactionType);
edgeAttributes.addNameMapping(edgeName, edgeIt.next());
} // end of for ()
} // read
| public void read () {
//move this to later when we know how many nodes
//edges we are going to add
//rootGraph = GinyFactory.createRootGraph();
// create and read the GML file
gmlTree = new GMLTree(filename);
nodeAttributes = new GraphObjAttributes();
edgeAttributes = new GraphObjAttributes();
// gmlGraphicsAtt = new GraphObjAttributes();
Vector nodeIds = gmlTree.getVector("graph|node|id","|",GMLTree.INTEGER);
Vector nodeLabels = gmlTree.getVector("graph|node|label","|",GMLTree.STRING);
// in case gml node ids are not ordered consecutively (0..n)
Hashtable nodeNameMap = new Hashtable(nodeIds.size());
for(int i=0; i<nodeIds.size(); i++) {
nodeNameMap.put(nodeIds.get(i), nodeLabels.get(i));
}
Vector edgeSources = gmlTree.getVector("graph|edge|source","|",GMLTree.INTEGER);
Vector edgeTargets = gmlTree.getVector("graph|edge|target","|",GMLTree.INTEGER);
Vector edgeLabels = gmlTree.getVector("graph|edge|label","|",GMLTree.STRING);
//Use the number of ids to get the number of nodes in hte graph
//Use the number of source ids to get the number of edges in hte graph
//(since every edge must have some source node)
rootGraph = GinyFactory.createRootGraph(nodeIds.size(),edgeSources.size());
//---------------------------------------------------------------------------
// set a default edge type if it's not defined in the GML file
// need a better system for defining the default...
String et = "pp";
if(edgeLabels.isEmpty()) {
for(int i=0; i < edgeSources.size(); i++) {
edgeLabels.add(et);
}
}
//---------------------------------------------------------------------------
// loop through all of the nodes (using a hash to avoid duplicates)
// adding nodes to the rootGraph.
// Create the nodeName mapping in nodeAttributes
//---------------------------------------------------------------------------
//Hashtable nodeHash = new Hashtable ();
Hashtable gmlId2GINYId = new Hashtable();
String nodeName, interactionType;
rootGraph.createNodes(nodeIds.size());
//for(int i=0; i<nodeIds.size(); i++) {
for (Iterator nodeIt = rootGraph.nodesIterator(),idIt = nodeIds.iterator();nodeIt.hasNext();) {
//nodeName = (String) nodeNameMap.get(nodeIds.get(i));
Integer gmlId = (Integer)idIt.next();
nodeName = (String)nodeNameMap.get(gmlId);
//if(canonicalize) nodeName = canonicalizeName(nodeName);
//if (!nodeHash.containsKey(nodeName)) {
//Node node = rootGraph.getNode(rootGraph.createNode());
Node node = (Node)nodeIt.next();
node.setIdentifier(nodeName);
//nodeHash.put(nodeName, node);
gmlId2GINYId.put(gmlId,new Integer(node.getRootGraphIndex()));
nodeAttributes.addNameMapping(nodeName, node);
//}
}
//Vector nodeHeight = gmlTree.getVector("graph|node|graphics|h","|",GMLTree.DOUBLE);
//Vector nodeWidth = gmlTree.getVector("graph|node|graphics|w","|",GMLTree.DOUBLE);
//Vector nodeType = gmlTree.getVector("graph|node|graphics|type","|",GMLTree.STRING);
//if( (nodeHeight.size() == nodeIds.size()) &&
//(nodeWidth.size() == nodeIds.size()) &&
//(nodeType.size() == nodeIds.size())
//) {
//for(int i=0; i<nodeIds.size(); i++) {
//nodeName = (String) nodeNameMap.get(nodeIds.get(i));
//gmlGraphicsAtt.set("node.h", nodeName, (Double) nodeHeight.get(i));
//gmlGraphicsAtt.set("node.w", nodeName, (Double) nodeWidth.get(i));
//gmlGraphicsAtt.set("node.type", nodeName, (String) nodeType.get(i));
//}
//}
//---------------------------------------------------------------------------
// loop over the interactions creating edges between all sources and their
// respective targets.
// for each edge, save the source-target pair, and their interaction type,
// in edgeAttributes -- a hash of a hash of name-value pairs, like this:
// ??? edgeAttributes ["interaction"] = interactionHash
// ??? interactionHash [sourceNode::targetNode] = "pd"
//---------------------------------------------------------------------------
int [] sources,targets;
sources = new int[edgeSources.size()];
targets = new int[edgeTargets.size()];
//Vector edgeNames = new Vector(edgeSources.size());
for (int i=0; i < edgeSources.size(); i++) {
//Node sourceNode = (Node) nodeHash.get(sourceName);
//Node targetNode = (Node) nodeHash.get(targetName);
sources[i] = ((Integer)gmlId2GINYId.get(edgeSources.get(i))).intValue();
targets[i] = ((Integer)gmlId2GINYId.get(edgeTargets.get(i))).intValue();
//Edge edge = rootGraph.getEdge(rootGraph.createEdge(sourceNode, targetNode));
//int edge = rootGraph.createEdge(sourceID,targetID);
//determine the name for the edge
//sourceName = (String) nodeNameMap.get(edgeSources.get(i));
//targetName = (String) nodeNameMap.get(edgeTargets.get(i));
//interactionType = (String) edgeLabels.get(i);
//edgeName = sourceName + " (" + interactionType + ") " + targetName;
//int previousMatchingEntries = edgeAttributes.countIdentical(edgeName);
//if (previousMatchingEntries > 0)
//edgeName = edgeName + "_" + previousMatchingEntries;
//edgeAttributes.add("interaction", edgeName, interactionType);
//edgeAttributes.addNameMapping(edgeName, edge);
}
rootGraph.createEdges(sources,targets,false);
for ( Iterator edgeIt = rootGraph.edgesList().iterator(),sourceIt = edgeSources.iterator(),targetIt = edgeTargets.iterator(),labelIt = edgeLabels.iterator();edgeIt.hasNext();) {
interactionType = (String)labelIt.next();
String edgeName = ""+nodeNameMap.get(sourceIt.next())+" ("+interactionType+") "+nodeNameMap.get(targetIt.next());
int previousMatchingEntries = edgeAttributes.countIdentical(edgeName);
if (previousMatchingEntries > 0){
edgeName = edgeName + "_" + previousMatchingEntries;
}
edgeAttributes.add("interaction", edgeName, interactionType);
edgeAttributes.addNameMapping(edgeName, edgeIt.next());
} // end of for ()
} // read
|
diff --git a/src/main/java/org/grouplens/ratingvalue/MutualInformationMetric.java b/src/main/java/org/grouplens/ratingvalue/MutualInformationMetric.java
index 223b302..f5b847a 100644
--- a/src/main/java/org/grouplens/ratingvalue/MutualInformationMetric.java
+++ b/src/main/java/org/grouplens/ratingvalue/MutualInformationMetric.java
@@ -1,117 +1,116 @@
package org.grouplens.ratingvalue;
import it.unimi.dsi.fastutil.longs.Long2DoubleMap;
import org.grouplens.lenskit.data.pref.PreferenceDomain;
import org.grouplens.lenskit.eval.AlgorithmInstance;
import org.grouplens.lenskit.eval.data.traintest.TTDataSet;
import org.grouplens.lenskit.eval.metrics.AbstractTestUserMetric;
import org.grouplens.lenskit.eval.metrics.TestUserMetricAccumulator;
import org.grouplens.lenskit.eval.traintest.TestUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
*/
public class MutualInformationMetric extends AbstractTestUserMetric {
private static final Logger logger = LoggerFactory.getLogger(MutualInformationMetric.class);
private String name = "MI";
private PreferenceDomain inDomain;
private PreferenceDomain outDomain;
private double sumValues;
private int numValues;
private boolean corrected = false;
public MutualInformationMetric(PreferenceDomain domain, boolean corrected) {
this.inDomain = domain;
this.outDomain = domain;
this.corrected = corrected;
}
public MutualInformationMetric(PreferenceDomain inDomain, PreferenceDomain outDomain, boolean corrected) {
this.inDomain = inDomain;
this.outDomain = outDomain;
this.corrected = corrected;
}
public MutualInformationMetric(String name, PreferenceDomain inDomain, PreferenceDomain outDomain, boolean corrected) {
this.name = name;
this.inDomain = inDomain;
this.outDomain = outDomain;
this.corrected = corrected;
}
@Override
public TestUserMetricAccumulator makeAccumulator(AlgorithmInstance algorithm, TTDataSet dataSet) {
return new Accum();
}
@Override
public String[] getColumnLabels() {
return new String[] { name, name + ".ByUser" };
}
@Override
public String[] getUserColumnLabels() {
return new String[] { name };
}
public double getMean() {
if (numValues == 0) {
return 0.0;
} else {
return sumValues / numValues;
}
}
class Accum implements TestUserMetricAccumulator {
MutualInformationCounter counter;
private double userMutualInformationSum;
private int nratings = 0;
private int nusers = 0;
public Accum() {
this.counter = new MutualInformationCounter(inDomain, outDomain, corrected);
}
@Override
public String[] evaluate(TestUser user) {
int n = 0;
MutualInformationCounter userCounter = new MutualInformationCounter(inDomain, outDomain, corrected);
// overall
for (Long2DoubleMap.Entry e: user.getTestRatings().fast()) {
if (Double.isNaN(e.getDoubleValue())) continue;
-// double predicted = Utils.binRating(domain, e.getDoubleValue());
double actual = e.getDoubleValue();
double predicted = user.getPredictions().get(e.getLongKey());
- counter.count(predicted, actual);
- userCounter.count(predicted, actual);
+ counter.count(actual, predicted);
+ userCounter.count(actual, predicted);
n++;
}
if (n > 0) {
nratings += n;
nusers += 1;
double uc = userCounter.calculate();
userMutualInformationSum += uc;
return new String[]{Double.toString(uc)};
} else {
return null;
}
}
@Override
public String[] finalResults() {
double v = counter.calculate();
double uv = userMutualInformationSum / nusers;
logger.info("{}: overall {}, by-user {}", new Object[] {name, v, uv});
sumValues += v;
numValues++;
return new String[]{
Double.toString(v),
Double.toString(uv)
};
}
}
}
| false | true | public String[] evaluate(TestUser user) {
int n = 0;
MutualInformationCounter userCounter = new MutualInformationCounter(inDomain, outDomain, corrected);
// overall
for (Long2DoubleMap.Entry e: user.getTestRatings().fast()) {
if (Double.isNaN(e.getDoubleValue())) continue;
// double predicted = Utils.binRating(domain, e.getDoubleValue());
double actual = e.getDoubleValue();
double predicted = user.getPredictions().get(e.getLongKey());
counter.count(predicted, actual);
userCounter.count(predicted, actual);
n++;
}
if (n > 0) {
nratings += n;
nusers += 1;
double uc = userCounter.calculate();
userMutualInformationSum += uc;
return new String[]{Double.toString(uc)};
} else {
return null;
}
}
| public String[] evaluate(TestUser user) {
int n = 0;
MutualInformationCounter userCounter = new MutualInformationCounter(inDomain, outDomain, corrected);
// overall
for (Long2DoubleMap.Entry e: user.getTestRatings().fast()) {
if (Double.isNaN(e.getDoubleValue())) continue;
double actual = e.getDoubleValue();
double predicted = user.getPredictions().get(e.getLongKey());
counter.count(actual, predicted);
userCounter.count(actual, predicted);
n++;
}
if (n > 0) {
nratings += n;
nusers += 1;
double uc = userCounter.calculate();
userMutualInformationSum += uc;
return new String[]{Double.toString(uc)};
} else {
return null;
}
}
|
diff --git a/src/com/joulespersecond/oba/ObaContext.java b/src/com/joulespersecond/oba/ObaContext.java
index 9486d30a..a7614736 100644
--- a/src/com/joulespersecond/oba/ObaContext.java
+++ b/src/com/joulespersecond/oba/ObaContext.java
@@ -1,115 +1,115 @@
/*
* Copyright (C) 2012 Paul Watts ([email protected])
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.joulespersecond.oba;
import com.joulespersecond.oba.elements.ObaRegion;
import com.joulespersecond.oba.region.RegionUtils;
import com.joulespersecond.seattlebusbot.Application;
import com.joulespersecond.seattlebusbot.BuildConfig;
import android.content.Context;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Log;
public class ObaContext {
private static final String TAG = "ObaContext";
private String mApiKey = "v1_BktoDJ2gJlu6nLM6LsT9H8IUbWc=cGF1bGN3YXR0c0BnbWFpbC5jb20=";
private int mAppVer = 0;
private String mAppUid = null;
private ObaConnectionFactory mConnectionFactory = ObaDefaultConnectionFactory.getInstance();
private ObaRegion mRegion;
public ObaContext() {
}
public void setAppInfo(int version, String uuid) {
mAppVer = version;
mAppUid = uuid;
}
public void setAppInfo(Uri.Builder builder) {
if (mAppVer != 0) {
builder.appendQueryParameter("app_ver", String.valueOf(mAppVer));
}
if (mAppUid != null) {
builder.appendQueryParameter("app_uid", mAppUid);
}
}
public void setApiKey(String apiKey) {
mApiKey = apiKey;
}
public String getApiKey() {
return mApiKey;
}
public void setRegion(ObaRegion region) {
mRegion = region;
}
public ObaRegion getRegion() {
return mRegion;
}
/**
* Connection factory
*/
public ObaConnectionFactory setConnectionFactory(ObaConnectionFactory factory) {
ObaConnectionFactory prev = mConnectionFactory;
mConnectionFactory = factory;
return prev;
}
public ObaConnectionFactory getConnectionFactory() {
return mConnectionFactory;
}
public void setBaseUrl(Context context, Uri.Builder builder) {
// If there is a custom preference, then use that.
String serverName = Application.getCustomApiUrl();
if (!TextUtils.isEmpty(serverName)) {
builder.encodedAuthority(serverName);
builder.scheme("http");
if (BuildConfig.DEBUG) { Log.d(TAG, "Using custom API URL set by user '" + serverName + "'."); }
} else if (mRegion != null) {
if (BuildConfig.DEBUG) { Log.d(TAG, "Using region base URL '" + mRegion.getObaBaseUrl() + "'."); }
- Uri base = Uri.parse(mRegion.getObaBaseUrl() + builder.build().getEncodedPath());
+ Uri base = Uri.parse(mRegion.getObaBaseUrl() + builder.build().getPath());
builder.scheme(base.getScheme());
builder.authority(base.getAuthority());
builder.encodedPath(base.getEncodedPath());
} else {
String fallBack = "api.onebusaway.org";
Log.e(TAG, "Accessing default fallback '" + fallBack + "' ...this is wrong!!");
// Current fallback for existing users?
builder.scheme("http");
builder.authority(fallBack);
}
}
@Override
public ObaContext clone() {
ObaContext result = new ObaContext();
result.setApiKey(mApiKey);
result.setAppInfo(mAppVer, mAppUid);
result.setConnectionFactory(mConnectionFactory);
return result;
}
}
| true | true | public void setBaseUrl(Context context, Uri.Builder builder) {
// If there is a custom preference, then use that.
String serverName = Application.getCustomApiUrl();
if (!TextUtils.isEmpty(serverName)) {
builder.encodedAuthority(serverName);
builder.scheme("http");
if (BuildConfig.DEBUG) { Log.d(TAG, "Using custom API URL set by user '" + serverName + "'."); }
} else if (mRegion != null) {
if (BuildConfig.DEBUG) { Log.d(TAG, "Using region base URL '" + mRegion.getObaBaseUrl() + "'."); }
Uri base = Uri.parse(mRegion.getObaBaseUrl() + builder.build().getEncodedPath());
builder.scheme(base.getScheme());
builder.authority(base.getAuthority());
builder.encodedPath(base.getEncodedPath());
} else {
String fallBack = "api.onebusaway.org";
Log.e(TAG, "Accessing default fallback '" + fallBack + "' ...this is wrong!!");
// Current fallback for existing users?
builder.scheme("http");
builder.authority(fallBack);
}
}
| public void setBaseUrl(Context context, Uri.Builder builder) {
// If there is a custom preference, then use that.
String serverName = Application.getCustomApiUrl();
if (!TextUtils.isEmpty(serverName)) {
builder.encodedAuthority(serverName);
builder.scheme("http");
if (BuildConfig.DEBUG) { Log.d(TAG, "Using custom API URL set by user '" + serverName + "'."); }
} else if (mRegion != null) {
if (BuildConfig.DEBUG) { Log.d(TAG, "Using region base URL '" + mRegion.getObaBaseUrl() + "'."); }
Uri base = Uri.parse(mRegion.getObaBaseUrl() + builder.build().getPath());
builder.scheme(base.getScheme());
builder.authority(base.getAuthority());
builder.encodedPath(base.getEncodedPath());
} else {
String fallBack = "api.onebusaway.org";
Log.e(TAG, "Accessing default fallback '" + fallBack + "' ...this is wrong!!");
// Current fallback for existing users?
builder.scheme("http");
builder.authority(fallBack);
}
}
|
diff --git a/src/com/android/contacts/model/EntityDelta.java b/src/com/android/contacts/model/EntityDelta.java
index 5b039df0f..9eb777920 100644
--- a/src/com/android/contacts/model/EntityDelta.java
+++ b/src/com/android/contacts/model/EntityDelta.java
@@ -1,845 +1,846 @@
/*
* Copyright (C) 2009 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.contacts.model;
import com.google.android.collect.Lists;
import com.google.android.collect.Maps;
import com.google.android.collect.Sets;
import android.content.ContentProviderOperation;
import android.content.ContentValues;
import android.content.Entity;
import android.content.ContentProviderOperation.Builder;
import android.content.Entity.NamedContentValues;
import android.net.Uri;
import android.os.Parcel;
import android.os.Parcelable;
import android.provider.BaseColumns;
import android.provider.ContactsContract;
import android.provider.ContactsContract.Data;
import android.provider.ContactsContract.RawContacts;
import android.provider.ContactsContract.CommonDataKinds.GroupMembership;
import android.util.Log;
import android.view.View;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
/**
* Contains an {@link Entity} and records any modifications separately so the
* original {@link Entity} can be swapped out with a newer version and the
* changes still cleanly applied.
* <p>
* One benefit of this approach is that we can build changes entirely on an
* empty {@link Entity}, which then becomes an insert {@link RawContacts} case.
* <p>
* When applying modifications over an {@link Entity}, we try finding the
* original {@link Data#_ID} rows where the modifications took place. If those
* rows are missing from the new {@link Entity}, we know the original data must
* be deleted, but to preserve the user modifications we treat as an insert.
*/
public class EntityDelta implements Parcelable {
// TODO: optimize by using contentvalues pool, since we allocate so many of them
private static final String TAG = "EntityDelta";
private static final boolean LOGV = true;
/**
* Direct values from {@link Entity#getEntityValues()}.
*/
private ValuesDelta mValues;
/**
* Internal map of children values from {@link Entity#getSubValues()}, which
* we store here sorted into {@link Data#MIMETYPE} bins.
*/
private HashMap<String, ArrayList<ValuesDelta>> mEntries = Maps.newHashMap();
public EntityDelta() {
}
public EntityDelta(ValuesDelta values) {
mValues = values;
}
/**
* Build an {@link EntityDelta} using the given {@link Entity} as a
* starting point; the "before" snapshot.
*/
public static EntityDelta fromBefore(Entity before) {
final EntityDelta entity = new EntityDelta();
entity.mValues = ValuesDelta.fromBefore(before.getEntityValues());
entity.mValues.setIdColumn(RawContacts._ID);
for (NamedContentValues namedValues : before.getSubValues()) {
entity.addEntry(ValuesDelta.fromBefore(namedValues.values));
}
return entity;
}
/**
* Merge the "after" values from the given {@link EntityDelta} onto the
* "before" state represented by this {@link EntityDelta}, discarding any
* existing "after" states. This is typically used when re-parenting changes
* onto an updated {@link Entity}.
*/
public static EntityDelta mergeAfter(EntityDelta local, EntityDelta remote) {
// Bail early if trying to merge delete with missing local
final ValuesDelta remoteValues = remote.mValues;
if (local == null && (remoteValues.isDelete() || remoteValues.isTransient())) return null;
// Create local version if none exists yet
if (local == null) local = new EntityDelta();
if (LOGV) {
final Long localVersion = (local.mValues == null) ? null : local.mValues
.getAsLong(RawContacts.VERSION);
final Long remoteVersion = remote.mValues.getAsLong(RawContacts.VERSION);
Log.d(TAG, "Re-parenting from original version " + remoteVersion + " to "
+ localVersion);
}
// Create values if needed, and merge "after" changes
local.mValues = ValuesDelta.mergeAfter(local.mValues, remote.mValues);
// Find matching local entry for each remote values, or create
for (ArrayList<ValuesDelta> mimeEntries : remote.mEntries.values()) {
for (ValuesDelta remoteEntry : mimeEntries) {
final Long childId = remoteEntry.getId();
// Find or create local match and merge
final ValuesDelta localEntry = local.getEntry(childId);
final ValuesDelta merged = ValuesDelta.mergeAfter(localEntry, remoteEntry);
if (localEntry == null && merged != null) {
// No local entry before, so insert
local.addEntry(merged);
}
}
}
return local;
}
public ValuesDelta getValues() {
return mValues;
}
public boolean isContactInsert() {
return mValues.isInsert();
}
/**
* Get the {@link ValuesDelta} child marked as {@link Data#IS_PRIMARY},
* which may return null when no entry exists.
*/
public ValuesDelta getPrimaryEntry(String mimeType) {
final ArrayList<ValuesDelta> mimeEntries = getMimeEntries(mimeType, false);
if (mimeEntries == null) return null;
for (ValuesDelta entry : mimeEntries) {
if (entry.isPrimary()) {
return entry;
}
}
// When no direct primary, return something
return mimeEntries.size() > 0 ? mimeEntries.get(0) : null;
}
/**
* calls {@link #getSuperPrimaryEntry(String, boolean)} with true
* @see #getSuperPrimaryEntry(String, boolean)
*/
public ValuesDelta getSuperPrimaryEntry(String mimeType) {
return getSuperPrimaryEntry(mimeType, true);
}
/**
* Returns the super-primary entry for the given mime type
* @param forceSelection if true, will try to return some value even if a super-primary
* doesn't exist (may be a primary, or just a random item
* @return
*/
public ValuesDelta getSuperPrimaryEntry(String mimeType, boolean forceSelection) {
final ArrayList<ValuesDelta> mimeEntries = getMimeEntries(mimeType, false);
if (mimeEntries == null) return null;
ValuesDelta primary = null;
for (ValuesDelta entry : mimeEntries) {
if (entry.isSuperPrimary()) {
return entry;
} else if (entry.isPrimary()) {
primary = entry;
}
}
if (!forceSelection) {
return null;
}
// When no direct super primary, return something
if (primary != null) {
return primary;
}
return mimeEntries.size() > 0 ? mimeEntries.get(0) : null;
}
/**
* Return the list of child {@link ValuesDelta} from our optimized map,
* creating the list if requested.
*/
private ArrayList<ValuesDelta> getMimeEntries(String mimeType, boolean lazyCreate) {
ArrayList<ValuesDelta> mimeEntries = mEntries.get(mimeType);
if (mimeEntries == null && lazyCreate) {
mimeEntries = Lists.newArrayList();
mEntries.put(mimeType, mimeEntries);
}
return mimeEntries;
}
public ArrayList<ValuesDelta> getMimeEntries(String mimeType) {
return getMimeEntries(mimeType, false);
}
public int getMimeEntriesCount(String mimeType, boolean onlyVisible) {
final ArrayList<ValuesDelta> mimeEntries = getMimeEntries(mimeType);
if (mimeEntries == null) return 0;
int count = 0;
for (ValuesDelta child : mimeEntries) {
// Skip deleted items when requesting only visible
if (onlyVisible && !child.isVisible()) continue;
count++;
}
return count;
}
public boolean hasMimeEntries(String mimeType) {
return mEntries.containsKey(mimeType);
}
public ValuesDelta addEntry(ValuesDelta entry) {
final String mimeType = entry.getMimetype();
getMimeEntries(mimeType, true).add(entry);
return entry;
}
/**
* Find entry with the given {@link BaseColumns#_ID} value.
*/
public ValuesDelta getEntry(Long childId) {
if (childId == null) {
// Requesting an "insert" entry, which has no "before"
return null;
}
// Search all children for requested entry
for (ArrayList<ValuesDelta> mimeEntries : mEntries.values()) {
for (ValuesDelta entry : mimeEntries) {
if (childId.equals(entry.getId())) {
return entry;
}
}
}
return null;
}
/**
* Return the total number of {@link ValuesDelta} contained.
*/
public int getEntryCount(boolean onlyVisible) {
int count = 0;
for (String mimeType : mEntries.keySet()) {
count += getMimeEntriesCount(mimeType, onlyVisible);
}
return count;
}
@Override
public boolean equals(Object object) {
if (object instanceof EntityDelta) {
final EntityDelta other = (EntityDelta)object;
// Equality failed if parent values different
if (!other.mValues.equals(mValues)) return false;
for (ArrayList<ValuesDelta> mimeEntries : mEntries.values()) {
for (ValuesDelta child : mimeEntries) {
// Equality failed if any children unmatched
if (!other.containsEntry(child)) return false;
}
}
// Passed all tests, so equal
return true;
}
return false;
}
private boolean containsEntry(ValuesDelta entry) {
for (ArrayList<ValuesDelta> mimeEntries : mEntries.values()) {
for (ValuesDelta child : mimeEntries) {
// Contained if we find any child that matches
if (child.equals(entry)) return true;
}
}
return false;
}
/**
* Mark this entire object deleted, including any {@link ValuesDelta}.
*/
public void markDeleted() {
this.mValues.markDeleted();
for (ArrayList<ValuesDelta> mimeEntries : mEntries.values()) {
for (ValuesDelta child : mimeEntries) {
child.markDeleted();
}
}
}
@Override
public String toString() {
final StringBuilder builder = new StringBuilder();
builder.append("\n(");
builder.append(mValues.toString());
builder.append(") = {");
for (ArrayList<ValuesDelta> mimeEntries : mEntries.values()) {
for (ValuesDelta child : mimeEntries) {
builder.append("\n\t");
child.toString(builder);
}
}
builder.append("\n}\n");
return builder.toString();
}
/**
* Consider building the given {@link ContentProviderOperation.Builder} and
* appending it to the given list, which only happens if builder is valid.
*/
private void possibleAdd(ArrayList<ContentProviderOperation> diff,
ContentProviderOperation.Builder builder) {
if (builder != null) {
diff.add(builder.build());
}
}
/**
* Build a list of {@link ContentProviderOperation} that will assert any
* "before" state hasn't changed. This is maintained separately so that all
* asserts can take place before any updates occur.
*/
public void buildAssert(ArrayList<ContentProviderOperation> buildInto) {
final boolean isContactInsert = mValues.isInsert();
if (!isContactInsert) {
// Assert version is consistent while persisting changes
final Long beforeId = mValues.getId();
final Long beforeVersion = mValues.getAsLong(RawContacts.VERSION);
if (beforeId == null || beforeVersion == null) return;
final ContentProviderOperation.Builder builder = ContentProviderOperation
.newAssertQuery(RawContacts.CONTENT_URI);
builder.withSelection(RawContacts._ID + "=" + beforeId, null);
builder.withValue(RawContacts.VERSION, beforeVersion);
buildInto.add(builder.build());
}
}
/**
* Build a list of {@link ContentProviderOperation} that will transform the
* current "before" {@link Entity} state into the modified state which this
* {@link EntityDelta} represents.
*/
public void buildDiff(ArrayList<ContentProviderOperation> buildInto) {
final int firstIndex = buildInto.size();
final boolean isContactInsert = mValues.isInsert();
final boolean isContactDelete = mValues.isDelete();
final boolean isContactUpdate = !isContactInsert && !isContactDelete;
final Long beforeId = mValues.getId();
Builder builder;
if (isContactInsert) {
// TODO: for now simply disabling aggregation when a new contact is
// created on the phone. In the future, will show aggregation suggestions
// after saving the contact.
mValues.put(RawContacts.AGGREGATION_MODE, RawContacts.AGGREGATION_MODE_SUSPENDED);
}
// Build possible operation at Contact level
builder = mValues.buildDiff(RawContacts.CONTENT_URI);
possibleAdd(buildInto, builder);
// Build operations for all children
for (ArrayList<ValuesDelta> mimeEntries : mEntries.values()) {
for (ValuesDelta child : mimeEntries) {
// Ignore children if parent was deleted
if (isContactDelete) continue;
builder = child.buildDiff(Data.CONTENT_URI);
if (child.isInsert()) {
if (isContactInsert) {
// Parent is brand new insert, so back-reference _id
builder.withValueBackReference(Data.RAW_CONTACT_ID, firstIndex);
} else {
// Inserting under existing, so fill with known _id
builder.withValue(Data.RAW_CONTACT_ID, beforeId);
}
} else if (isContactInsert && builder != null) {
// Child must be insert when Contact insert
throw new IllegalArgumentException("When parent insert, child must be also");
}
possibleAdd(buildInto, builder);
}
}
final boolean addedOperations = buildInto.size() > firstIndex;
if (addedOperations && isContactUpdate) {
// Suspend aggregation while persisting updates
builder = buildSetAggregationMode(beforeId, RawContacts.AGGREGATION_MODE_SUSPENDED);
buildInto.add(firstIndex, builder.build());
// Restore aggregation mode as last operation
builder = buildSetAggregationMode(beforeId, RawContacts.AGGREGATION_MODE_DEFAULT);
buildInto.add(builder.build());
} else if (isContactInsert) {
// Restore aggregation mode as last operation
builder = ContentProviderOperation.newUpdate(RawContacts.CONTENT_URI);
builder.withValue(RawContacts.AGGREGATION_MODE, RawContacts.AGGREGATION_MODE_DEFAULT);
builder.withSelection(RawContacts._ID + "=?", new String[1]);
builder.withSelectionBackReference(0, firstIndex);
+ buildInto.add(builder.build());
}
}
/**
* Build a {@link ContentProviderOperation} that changes
* {@link RawContacts#AGGREGATION_MODE} to the given value.
*/
protected Builder buildSetAggregationMode(Long beforeId, int mode) {
Builder builder = ContentProviderOperation.newUpdate(RawContacts.CONTENT_URI);
builder.withValue(RawContacts.AGGREGATION_MODE, mode);
builder.withSelection(RawContacts._ID + "=" + beforeId, null);
return builder;
}
/** {@inheritDoc} */
public int describeContents() {
// Nothing special about this parcel
return 0;
}
/** {@inheritDoc} */
public void writeToParcel(Parcel dest, int flags) {
final int size = this.getEntryCount(false);
dest.writeInt(size);
dest.writeParcelable(mValues, flags);
for (ArrayList<ValuesDelta> mimeEntries : mEntries.values()) {
for (ValuesDelta child : mimeEntries) {
dest.writeParcelable(child, flags);
}
}
}
public void readFromParcel(Parcel source) {
final ClassLoader loader = getClass().getClassLoader();
final int size = source.readInt();
mValues = source.<ValuesDelta> readParcelable(loader);
for (int i = 0; i < size; i++) {
final ValuesDelta child = source.<ValuesDelta> readParcelable(loader);
this.addEntry(child);
}
}
public static final Parcelable.Creator<EntityDelta> CREATOR = new Parcelable.Creator<EntityDelta>() {
public EntityDelta createFromParcel(Parcel in) {
final EntityDelta state = new EntityDelta();
state.readFromParcel(in);
return state;
}
public EntityDelta[] newArray(int size) {
return new EntityDelta[size];
}
};
/**
* Type of {@link ContentValues} that maintains both an original state and a
* modified version of that state. This allows us to build insert, update,
* or delete operations based on a "before" {@link Entity} snapshot.
*/
public static class ValuesDelta implements Parcelable {
protected ContentValues mBefore;
protected ContentValues mAfter;
protected String mIdColumn = BaseColumns._ID;
private boolean mFromTemplate;
/**
* Next value to assign to {@link #mIdColumn} when building an insert
* operation through {@link #fromAfter(ContentValues)}. This is used so
* we can concretely reference this {@link ValuesDelta} before it has
* been persisted.
*/
protected static int sNextInsertId = -1;
protected ValuesDelta() {
}
/**
* Create {@link ValuesDelta}, using the given object as the
* "before" state, usually from an {@link Entity}.
*/
public static ValuesDelta fromBefore(ContentValues before) {
final ValuesDelta entry = new ValuesDelta();
entry.mBefore = before;
entry.mAfter = new ContentValues();
return entry;
}
/**
* Create {@link ValuesDelta}, using the given object as the "after"
* state, usually when we are inserting a row instead of updating.
*/
public static ValuesDelta fromAfter(ContentValues after) {
final ValuesDelta entry = new ValuesDelta();
entry.mBefore = null;
entry.mAfter = after;
// Assign temporary id which is dropped before insert.
entry.mAfter.put(entry.mIdColumn, sNextInsertId--);
return entry;
}
public ContentValues getAfter() {
return mAfter;
}
public String getAsString(String key) {
if (mAfter != null && mAfter.containsKey(key)) {
return mAfter.getAsString(key);
} else if (mBefore != null && mBefore.containsKey(key)) {
return mBefore.getAsString(key);
} else {
return null;
}
}
public byte[] getAsByteArray(String key) {
if (mAfter != null && mAfter.containsKey(key)) {
return mAfter.getAsByteArray(key);
} else if (mBefore != null && mBefore.containsKey(key)) {
return mBefore.getAsByteArray(key);
} else {
return null;
}
}
public Long getAsLong(String key) {
if (mAfter != null && mAfter.containsKey(key)) {
return mAfter.getAsLong(key);
} else if (mBefore != null && mBefore.containsKey(key)) {
return mBefore.getAsLong(key);
} else {
return null;
}
}
public Integer getAsInteger(String key) {
return getAsInteger(key, null);
}
public Integer getAsInteger(String key, Integer defaultValue) {
if (mAfter != null && mAfter.containsKey(key)) {
return mAfter.getAsInteger(key);
} else if (mBefore != null && mBefore.containsKey(key)) {
return mBefore.getAsInteger(key);
} else {
return defaultValue;
}
}
public String getMimetype() {
return getAsString(Data.MIMETYPE);
}
public Long getId() {
return getAsLong(mIdColumn);
}
public void setIdColumn(String idColumn) {
mIdColumn = idColumn;
}
public boolean isPrimary() {
final Long isPrimary = getAsLong(Data.IS_PRIMARY);
return isPrimary == null ? false : isPrimary != 0;
}
public void setFromTemplate(boolean isFromTemplate) {
mFromTemplate = isFromTemplate;
}
public boolean isFromTemplate() {
return mFromTemplate;
}
public boolean isSuperPrimary() {
final Long isSuperPrimary = getAsLong(Data.IS_SUPER_PRIMARY);
return isSuperPrimary == null ? false : isSuperPrimary != 0;
}
public boolean beforeExists() {
return (mBefore != null && mBefore.containsKey(mIdColumn));
}
public boolean isVisible() {
// When "after" is present, then visible
return (mAfter != null);
}
public boolean isDelete() {
// When "after" is wiped, action is "delete"
return beforeExists() && (mAfter == null);
}
public boolean isTransient() {
// When no "before" or "after", is transient
return (mBefore == null) && (mAfter == null);
}
public boolean isUpdate() {
// When "after" has some changes, action is "update"
return beforeExists() && (mAfter != null && mAfter.size() > 0);
}
public boolean isNoop() {
// When "after" has no changes, action is no-op
return beforeExists() && (mAfter != null && mAfter.size() == 0);
}
public boolean isInsert() {
// When no "before" id, and has "after", action is "insert"
return !beforeExists() && (mAfter != null);
}
public void markDeleted() {
mAfter = null;
}
/**
* Ensure that our internal structure is ready for storing updates.
*/
private void ensureUpdate() {
if (mAfter == null) {
mAfter = new ContentValues();
}
}
public void put(String key, String value) {
ensureUpdate();
mAfter.put(key, value);
}
public void put(String key, byte[] value) {
ensureUpdate();
mAfter.put(key, value);
}
public void put(String key, int value) {
ensureUpdate();
mAfter.put(key, value);
}
/**
* Return set of all keys defined through this object.
*/
public Set<String> keySet() {
final HashSet<String> keys = Sets.newHashSet();
if (mBefore != null) {
for (Map.Entry<String, Object> entry : mBefore.valueSet()) {
keys.add(entry.getKey());
}
}
if (mAfter != null) {
for (Map.Entry<String, Object> entry : mAfter.valueSet()) {
keys.add(entry.getKey());
}
}
return keys;
}
/**
* Return complete set of "before" and "after" values mixed together,
* giving full state regardless of edits.
*/
public ContentValues getCompleteValues() {
final ContentValues values = new ContentValues();
if (mBefore != null) {
values.putAll(mBefore);
}
if (mAfter != null) {
values.putAll(mAfter);
}
if (values.containsKey(GroupMembership.GROUP_ROW_ID)) {
// Clear to avoid double-definitions, and prefer rows
values.remove(GroupMembership.GROUP_SOURCE_ID);
}
return values;
}
/**
* Merge the "after" values from the given {@link ValuesDelta},
* discarding any existing "after" state. This is typically used when
* re-parenting changes onto an updated {@link Entity}.
*/
public static ValuesDelta mergeAfter(ValuesDelta local, ValuesDelta remote) {
// Bail early if trying to merge delete with missing local
if (local == null && (remote.isDelete() || remote.isTransient())) return null;
// Create local version if none exists yet
if (local == null) local = new ValuesDelta();
if (!local.beforeExists()) {
// Any "before" record is missing, so take all values as "insert"
local.mAfter = remote.getCompleteValues();
} else {
// Existing "update" with only "after" values
local.mAfter = remote.mAfter;
}
return local;
}
@Override
public boolean equals(Object object) {
if (object instanceof ValuesDelta) {
// Only exactly equal with both are identical subsets
final ValuesDelta other = (ValuesDelta)object;
return this.subsetEquals(other) && other.subsetEquals(this);
}
return false;
}
@Override
public String toString() {
final StringBuilder builder = new StringBuilder();
toString(builder);
return builder.toString();
}
/**
* Helper for building string representation, leveraging the given
* {@link StringBuilder} to minimize allocations.
*/
public void toString(StringBuilder builder) {
builder.append("{ ");
for (String key : this.keySet()) {
builder.append(key);
builder.append("=");
builder.append(this.getAsString(key));
builder.append(", ");
}
builder.append("}");
}
/**
* Check if the given {@link ValuesDelta} is both a subset of this
* object, and any defined keys have equal values.
*/
public boolean subsetEquals(ValuesDelta other) {
for (String key : this.keySet()) {
final String ourValue = this.getAsString(key);
final String theirValue = other.getAsString(key);
if (ourValue == null) {
// If they have value when we're null, no match
if (theirValue != null) return false;
} else {
// If both values defined and aren't equal, no match
if (!ourValue.equals(theirValue)) return false;
}
}
// All values compared and matched
return true;
}
/**
* Build a {@link ContentProviderOperation} that will transform our
* "before" state into our "after" state, using insert, update, or
* delete as needed.
*/
public ContentProviderOperation.Builder buildDiff(Uri targetUri) {
Builder builder = null;
if (isInsert()) {
// Changed values are "insert" back-referenced to Contact
mAfter.remove(mIdColumn);
builder = ContentProviderOperation.newInsert(targetUri);
builder.withValues(mAfter);
} else if (isDelete()) {
// When marked for deletion and "before" exists, then "delete"
builder = ContentProviderOperation.newDelete(targetUri);
builder.withSelection(mIdColumn + "=" + getId(), null);
} else if (isUpdate()) {
// When has changes and "before" exists, then "update"
builder = ContentProviderOperation.newUpdate(targetUri);
builder.withSelection(mIdColumn + "=" + getId(), null);
builder.withValues(mAfter);
}
return builder;
}
/** {@inheritDoc} */
public int describeContents() {
// Nothing special about this parcel
return 0;
}
/** {@inheritDoc} */
public void writeToParcel(Parcel dest, int flags) {
dest.writeParcelable(mBefore, flags);
dest.writeParcelable(mAfter, flags);
dest.writeString(mIdColumn);
}
public void readFromParcel(Parcel source) {
final ClassLoader loader = getClass().getClassLoader();
mBefore = source.<ContentValues> readParcelable(loader);
mAfter = source.<ContentValues> readParcelable(loader);
mIdColumn = source.readString();
}
public static final Parcelable.Creator<ValuesDelta> CREATOR = new Parcelable.Creator<ValuesDelta>() {
public ValuesDelta createFromParcel(Parcel in) {
final ValuesDelta values = new ValuesDelta();
values.readFromParcel(in);
return values;
}
public ValuesDelta[] newArray(int size) {
return new ValuesDelta[size];
}
};
}
}
| true | true | public void buildDiff(ArrayList<ContentProviderOperation> buildInto) {
final int firstIndex = buildInto.size();
final boolean isContactInsert = mValues.isInsert();
final boolean isContactDelete = mValues.isDelete();
final boolean isContactUpdate = !isContactInsert && !isContactDelete;
final Long beforeId = mValues.getId();
Builder builder;
if (isContactInsert) {
// TODO: for now simply disabling aggregation when a new contact is
// created on the phone. In the future, will show aggregation suggestions
// after saving the contact.
mValues.put(RawContacts.AGGREGATION_MODE, RawContacts.AGGREGATION_MODE_SUSPENDED);
}
// Build possible operation at Contact level
builder = mValues.buildDiff(RawContacts.CONTENT_URI);
possibleAdd(buildInto, builder);
// Build operations for all children
for (ArrayList<ValuesDelta> mimeEntries : mEntries.values()) {
for (ValuesDelta child : mimeEntries) {
// Ignore children if parent was deleted
if (isContactDelete) continue;
builder = child.buildDiff(Data.CONTENT_URI);
if (child.isInsert()) {
if (isContactInsert) {
// Parent is brand new insert, so back-reference _id
builder.withValueBackReference(Data.RAW_CONTACT_ID, firstIndex);
} else {
// Inserting under existing, so fill with known _id
builder.withValue(Data.RAW_CONTACT_ID, beforeId);
}
} else if (isContactInsert && builder != null) {
// Child must be insert when Contact insert
throw new IllegalArgumentException("When parent insert, child must be also");
}
possibleAdd(buildInto, builder);
}
}
final boolean addedOperations = buildInto.size() > firstIndex;
if (addedOperations && isContactUpdate) {
// Suspend aggregation while persisting updates
builder = buildSetAggregationMode(beforeId, RawContacts.AGGREGATION_MODE_SUSPENDED);
buildInto.add(firstIndex, builder.build());
// Restore aggregation mode as last operation
builder = buildSetAggregationMode(beforeId, RawContacts.AGGREGATION_MODE_DEFAULT);
buildInto.add(builder.build());
} else if (isContactInsert) {
// Restore aggregation mode as last operation
builder = ContentProviderOperation.newUpdate(RawContacts.CONTENT_URI);
builder.withValue(RawContacts.AGGREGATION_MODE, RawContacts.AGGREGATION_MODE_DEFAULT);
builder.withSelection(RawContacts._ID + "=?", new String[1]);
builder.withSelectionBackReference(0, firstIndex);
}
}
| public void buildDiff(ArrayList<ContentProviderOperation> buildInto) {
final int firstIndex = buildInto.size();
final boolean isContactInsert = mValues.isInsert();
final boolean isContactDelete = mValues.isDelete();
final boolean isContactUpdate = !isContactInsert && !isContactDelete;
final Long beforeId = mValues.getId();
Builder builder;
if (isContactInsert) {
// TODO: for now simply disabling aggregation when a new contact is
// created on the phone. In the future, will show aggregation suggestions
// after saving the contact.
mValues.put(RawContacts.AGGREGATION_MODE, RawContacts.AGGREGATION_MODE_SUSPENDED);
}
// Build possible operation at Contact level
builder = mValues.buildDiff(RawContacts.CONTENT_URI);
possibleAdd(buildInto, builder);
// Build operations for all children
for (ArrayList<ValuesDelta> mimeEntries : mEntries.values()) {
for (ValuesDelta child : mimeEntries) {
// Ignore children if parent was deleted
if (isContactDelete) continue;
builder = child.buildDiff(Data.CONTENT_URI);
if (child.isInsert()) {
if (isContactInsert) {
// Parent is brand new insert, so back-reference _id
builder.withValueBackReference(Data.RAW_CONTACT_ID, firstIndex);
} else {
// Inserting under existing, so fill with known _id
builder.withValue(Data.RAW_CONTACT_ID, beforeId);
}
} else if (isContactInsert && builder != null) {
// Child must be insert when Contact insert
throw new IllegalArgumentException("When parent insert, child must be also");
}
possibleAdd(buildInto, builder);
}
}
final boolean addedOperations = buildInto.size() > firstIndex;
if (addedOperations && isContactUpdate) {
// Suspend aggregation while persisting updates
builder = buildSetAggregationMode(beforeId, RawContacts.AGGREGATION_MODE_SUSPENDED);
buildInto.add(firstIndex, builder.build());
// Restore aggregation mode as last operation
builder = buildSetAggregationMode(beforeId, RawContacts.AGGREGATION_MODE_DEFAULT);
buildInto.add(builder.build());
} else if (isContactInsert) {
// Restore aggregation mode as last operation
builder = ContentProviderOperation.newUpdate(RawContacts.CONTENT_URI);
builder.withValue(RawContacts.AGGREGATION_MODE, RawContacts.AGGREGATION_MODE_DEFAULT);
builder.withSelection(RawContacts._ID + "=?", new String[1]);
builder.withSelectionBackReference(0, firstIndex);
buildInto.add(builder.build());
}
}
|
diff --git a/src/main/java/org/cloudifysource/quality/iTests/test/cli/cloudify/cloud/byon/agentrestart/AutoRestartAgentDisabledTest.java b/src/main/java/org/cloudifysource/quality/iTests/test/cli/cloudify/cloud/byon/agentrestart/AutoRestartAgentDisabledTest.java
index 7ed23c96..6f9194b4 100644
--- a/src/main/java/org/cloudifysource/quality/iTests/test/cli/cloudify/cloud/byon/agentrestart/AutoRestartAgentDisabledTest.java
+++ b/src/main/java/org/cloudifysource/quality/iTests/test/cli/cloudify/cloud/byon/agentrestart/AutoRestartAgentDisabledTest.java
@@ -1,57 +1,57 @@
package org.cloudifysource.quality.iTests.test.cli.cloudify.cloud.byon.agentrestart;
import java.util.concurrent.TimeUnit;
import iTests.framework.utils.LogUtils;
import iTests.framework.utils.MavenUtils;
import iTests.framework.utils.SSHUtils;
import org.cloudifysource.dsl.utils.IPUtils;
import org.openspaces.admin.pu.ProcessingUnit;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
public class AutoRestartAgentDisabledTest extends AbstractAgentMaintenanceModeTest {
private static final String LIST_CRONTAB_TASKS = "crontab -l";
@BeforeClass(alwaysRun = true)
protected void bootstrap() throws Exception {
super.bootstrap();
}
@Test(timeOut = DEFAULT_TEST_TIMEOUT * 4, enabled = true)
public void testRestartAgentDisabled() throws Exception {
final ProcessingUnit pu = admin.getProcessingUnits()
.waitFor("rest", DEFAULT_WAIT_MINUTES, TimeUnit.MINUTES);
pu.waitFor(1);
final String hostName = pu.getInstances()[0].getMachine().getHostName();
final String ip = IPUtils.resolveHostNameToIp(hostName);
LogUtils.log("listing all crontab scheduled tasks");
final String output = SSHUtils.runCommand(ip, DEFAULT_TEST_TIMEOUT / 2,
LIST_CRONTAB_TASKS,
MavenUtils.username,
- MavenUtils.password);
+ MavenUtils.password, true);
LogUtils.log(output);
assertTrue("crontab contains auto restart agent task",
!output.contains("@reboot nohup /tmp/tgrid/gigaspaces/tools/cli/cloudify.sh start-management"));
}
@Override
protected void customizeCloud() throws Exception {
super.customizeCloud();
getService().setSudo(false);
getService().getProperties().put("keyFile", "testKey.pem");
getService().getAdditionalPropsToReplace().put("autoRestartAgent true", "autoRestartAgent false");
}
@Override
@AfterClass(alwaysRun = true)
protected void teardown() throws Exception {
uninstallServiceIfFound(SERVICE_NAME);
super.teardown();
}
}
| true | true | public void testRestartAgentDisabled() throws Exception {
final ProcessingUnit pu = admin.getProcessingUnits()
.waitFor("rest", DEFAULT_WAIT_MINUTES, TimeUnit.MINUTES);
pu.waitFor(1);
final String hostName = pu.getInstances()[0].getMachine().getHostName();
final String ip = IPUtils.resolveHostNameToIp(hostName);
LogUtils.log("listing all crontab scheduled tasks");
final String output = SSHUtils.runCommand(ip, DEFAULT_TEST_TIMEOUT / 2,
LIST_CRONTAB_TASKS,
MavenUtils.username,
MavenUtils.password);
LogUtils.log(output);
assertTrue("crontab contains auto restart agent task",
!output.contains("@reboot nohup /tmp/tgrid/gigaspaces/tools/cli/cloudify.sh start-management"));
}
| public void testRestartAgentDisabled() throws Exception {
final ProcessingUnit pu = admin.getProcessingUnits()
.waitFor("rest", DEFAULT_WAIT_MINUTES, TimeUnit.MINUTES);
pu.waitFor(1);
final String hostName = pu.getInstances()[0].getMachine().getHostName();
final String ip = IPUtils.resolveHostNameToIp(hostName);
LogUtils.log("listing all crontab scheduled tasks");
final String output = SSHUtils.runCommand(ip, DEFAULT_TEST_TIMEOUT / 2,
LIST_CRONTAB_TASKS,
MavenUtils.username,
MavenUtils.password, true);
LogUtils.log(output);
assertTrue("crontab contains auto restart agent task",
!output.contains("@reboot nohup /tmp/tgrid/gigaspaces/tools/cli/cloudify.sh start-management"));
}
|
diff --git a/elasticsearch/impl/src/test/org/sakaiproject/search/elasticsearch/ElasticSearchTest.java b/elasticsearch/impl/src/test/org/sakaiproject/search/elasticsearch/ElasticSearchTest.java
index 07989b40..8322cab2 100644
--- a/elasticsearch/impl/src/test/org/sakaiproject/search/elasticsearch/ElasticSearchTest.java
+++ b/elasticsearch/impl/src/test/org/sakaiproject/search/elasticsearch/ElasticSearchTest.java
@@ -1,547 +1,548 @@
package org.sakaiproject.search.elasticsearch;
import com.github.javafaker.Faker;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Answers;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.sakaiproject.authz.api.SecurityService;
import org.sakaiproject.component.api.ServerConfigurationService;
import org.sakaiproject.event.api.*;
import org.sakaiproject.search.api.EntityContentProducer;
import org.sakaiproject.search.api.InvalidSearchQueryException;
import org.sakaiproject.search.api.SearchList;
import org.sakaiproject.search.api.SearchResult;
import org.sakaiproject.search.elasticsearch.filter.SearchItemFilter;
import org.sakaiproject.search.elasticsearch.filter.impl.SearchSecurityFilter;
import org.sakaiproject.search.model.SearchBuilderItem;
import org.sakaiproject.site.api.Site;
import org.sakaiproject.site.api.SiteService;
import org.sakaiproject.tool.api.SessionManager;
import org.sakaiproject.user.api.UserDirectoryService;
import java.util.*;
import static org.junit.Assert.*;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.*;
/**
*
*
* Read this thread http://stackoverflow.com/questions/12935810/integration-test-elastic-search-timing-issue-document-not-found
*
* You have to call refresh on the index after you make any changes, before you query it. Because ES
* waits a second for more data to arrive.
*
*
* User: jbush
* Date: 1/16/13
* Time: 9:10 PM
* To change this template use File | Settings | File Templates.
*/
@RunWith(MockitoJUnitRunner.class)
public class ElasticSearchTest {
ElasticSearchService elasticSearchService;
@Mock
EventTrackingService eventTrackingService;
@Mock(answer = Answers.RETURNS_DEEP_STUBS)
ServerConfigurationService serverConfigurationService;
@Mock
SessionManager sessionManager;
@Mock
UserDirectoryService userDirectoryService;
@Mock
NotificationService notificationService;
@Mock
SiteService siteService;
@Mock
SecurityService securityService;
@Mock
NotificationEdit notificationEdit;
ElasticSearchIndexBuilder elasticSearchIndexBuilder;
@Mock
Notification notification;
@Mock
Event event;
@Mock
EntityContentProducer entityContentProducer;
@Mock
Site site;
List<String> siteIds = new ArrayList<String>();
Faker faker = new Faker();
String siteId = faker.phoneNumber();
String resourceName = faker.name() + " key keyboard";
String url = "http://localhost/test123";
private Map<String, Resource> resources = new HashMap();
private List<Event> events = new ArrayList();
List<Site> sites = new ArrayList<Site>();
SearchSecurityFilter filter = new SearchSecurityFilter();
@After
public void tearDown() {
elasticSearchService.destroy();
}
public void createTestResources() {
String content = "asdf organ organize organizations " + generateContent();
Resource resource = new Resource(content, siteId, resourceName);
resources.put(resourceName, resource);
when(event.getResource()).thenReturn(resource.getName());
events.add(event);
when(entityContentProducer.matches(event)).thenReturn(true);
when(entityContentProducer.matches(resourceName)).thenReturn(true);
when(entityContentProducer.getSiteId(resourceName)).thenReturn(siteId);
when(entityContentProducer.getAction(event)).thenReturn(SearchBuilderItem.ACTION_ADD);
when(entityContentProducer.getContent(resourceName)).thenReturn(content);
when(entityContentProducer.getType(resourceName)).thenReturn("sakai:content");
when(entityContentProducer.getId(resourceName)).thenReturn(resourceName);
when(entityContentProducer.getTitle(resourceName)).thenReturn(resourceName);
for (int i=0;i<105;i++) {
String name = faker.name();
Event newEvent = mock(Event.class);
Resource resource1 = new Resource(generateContent(), faker.phoneNumber(), name);
resources.put(name, resource1);
events.add(newEvent);
when(newEvent.getResource()).thenReturn(resource1.getName());
when(newEvent.getContext()).thenReturn(siteId);
when(entityContentProducer.matches(name)).thenReturn(true);
when(entityContentProducer.matches(newEvent)).thenReturn(true);
when(entityContentProducer.getSiteId(name)).thenReturn(resource1.getSiteId());
when(entityContentProducer.getAction(newEvent)).thenReturn(SearchBuilderItem.ACTION_ADD);
when(entityContentProducer.getContent(name)).thenReturn(resource1.getContent());
when(entityContentProducer.getType(name)).thenReturn("sakai:content");
when(entityContentProducer.getId(name)).thenReturn(name);
when(entityContentProducer.canRead(any(String.class))).thenReturn(true);
}
when(entityContentProducer.getSiteContentIterator(siteId)).thenReturn(resources.keySet().iterator());
}
private String generateContent() {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < 10; i++) {
sb.append(faker.paragraph(10) + " ");
}
return sb.toString();
}
@Before
public void setUp() throws Exception {
createTestResources();
when(site.getId()).thenReturn(siteId);
when(siteService.getSite(site.getId())).thenReturn(site);
sites.add(site);
when(serverConfigurationService.getBoolean("search.enable", false)).thenReturn(true);
when(serverConfigurationService.getConfigData().getItems()).thenReturn(new ArrayList());
when(serverConfigurationService.getServerId()).thenReturn("server1");
when(serverConfigurationService.getServerName()).thenReturn("clusterName");
when(serverConfigurationService.getString("elasticsearch.index.number_of_shards")).thenReturn("1");
when(serverConfigurationService.getString("elasticsearch.index.number_of_replicas")).thenReturn("0");
when(serverConfigurationService.getSakaiHomePath()).thenReturn(System.getProperty("java.io.tmpdir") + "/" + new Date().getTime());
when(notificationService.addTransientNotification()).thenReturn(notificationEdit);
siteIds.add(siteId);
when(siteService.getSites(SiteService.SelectionType.ANY, null, null, null, SiteService.SortType.NONE, null)).thenReturn(sites);
when(siteService.isSpecialSite(siteId)).thenReturn(false);
elasticSearchIndexBuilder = new ElasticSearchIndexBuilder();
elasticSearchIndexBuilder.setTestMode(true);
elasticSearchIndexBuilder.setOnlyIndexSearchToolSites(false);
elasticSearchIndexBuilder.setExcludeUserSites(false);
elasticSearchIndexBuilder.setSecurityService(securityService);
elasticSearchIndexBuilder.setSiteService(siteService);
elasticSearchIndexBuilder.setServerConfigurationService(serverConfigurationService);
elasticSearchIndexBuilder.setDelay(200);
elasticSearchIndexBuilder.setPeriod(10);
elasticSearchIndexBuilder.setContentIndexBatchSize(50);
elasticSearchIndexBuilder.setBulkRequestSize(20);
elasticSearchIndexBuilder.setMapping("{\n" +
" \"sakai_doc\": {\n" +
" \"_source\": {\n" +
" \"enabled\": false\n" +
" },\n" +
"\n" +
" \"properties\": {\n" +
" \"siteid\": {\n" +
" \"type\": \"string\",\n" +
" \"index\": \"not_analyzed\",\n" +
" \"store\": \"yes\"\n" +
" },\n" +
" \"title\": {\n" +
" \"type\": \"string\",\n" +
" \"store\": \"yes\",\n" +
" \"term_vector\" : \"with_positions_offsets\",\n" +
" \"search_analyzer\": \"str_search_analyzer\",\n" +
" \"index_analyzer\": \"str_index_analyzer\"\n" +
" },\n" +
" \"url\": {\n" +
" \"type\": \"string\",\n" +
" \"index\": \"not_analyzed\",\n" +
" \"store\": \"yes\"\n" +
" },\n" +
" \"reference\": {\n" +
" \"type\": \"string\",\n" +
" \"index\": \"not_analyzed\",\n" +
" \"store\": \"yes\"\n" +
" },\n" +
" \"id\": {\n" +
" \"type\": \"string\",\n" +
" \"index\": \"not_analyzed\",\n" +
" \"store\": \"yes\"\n" +
" },\n" +
" \"tool\": {\n" +
" \"type\": \"string\",\n" +
" \"index\": \"not_analyzed\",\n" +
" \"store\": \"yes\"\n" +
" },\n" +
" \"container\": {\n" +
" \"type\": \"string\",\n" +
" \"index\": \"not_analyzed\",\n" +
" \"store\": \"yes\"\n" +
" },\n" +
" \"type\": {\n" +
" \"type\": \"string\",\n" +
" \"index\": \"not_analyzed\",\n" +
" \"store\": \"yes\"\n" +
" },\n" +
" \"subtype\": {\n" +
" \"type\": \"string\",\n" +
" \"index\": \"not_analyzed\",\n" +
" \"store\": \"yes\"\n" +
" },\n" +
" \"contents\": {\n" +
" \"type\": \"string\",\n" +
" \"analyzer\": \"snowball\",\n" +
" \"index\": \"analyzed\",\n" +
" \"store\": \"no\"\n" +
" }\n" +
" }\n" +
" }\n" +
"}");
elasticSearchIndexBuilder.setIndexSettings("{\n" +
" \"analysis\": {\n" +
" \"filter\": {\n" +
" \"substring\": {\n" +
" \"type\": \"nGram\",\n" +
" \"min_gram\": 1,\n" +
" \"max_gram\": 20\n" +
" }\n" +
" },\n" +
" \"analyzer\": {\n" +
" \"snowball\": {\n" +
" \"type\": \"snowball\",\n" +
" \"language\": \"English\"\n" +
" },\n" +
" \"str_search_analyzer\": {\n" +
" \"tokenizer\": \"keyword\",\n" +
" \"filter\": [\"lowercase\"]\n" +
" },\n" +
" \"str_index_analyzer\": {\n" +
" \"tokenizer\": \"keyword\",\n" +
" \"filter\": [\"lowercase\", \"substring\"]\n" +
" }\n" +
" }\n" +
" }\n" +
"}\n" +
"\n");
elasticSearchIndexBuilder.init();
elasticSearchService = new ElasticSearchService();
elasticSearchService.setTriggerFunctions(new ArrayList<String>());
elasticSearchService.setEventTrackingService(eventTrackingService);
elasticSearchService.setServerConfigurationService(serverConfigurationService);
elasticSearchService.setSessionManager(sessionManager);
elasticSearchService.setUserDirectoryService(userDirectoryService);
elasticSearchService.setNotificationService(notificationService);
elasticSearchService.setSiteService(siteService);
elasticSearchService.setIndexBuilder(elasticSearchIndexBuilder);
elasticSearchIndexBuilder.setOnlyIndexSearchToolSites(false);
filter.setSearchIndexBuilder(elasticSearchIndexBuilder);
elasticSearchService.setFilter(filter);
+ elasticSearchService.setLocalNode(true);
elasticSearchIndexBuilder.setIgnoredSites("!admin,~admin");
elasticSearchService.init();
elasticSearchIndexBuilder.assureIndex();
elasticSearchIndexBuilder.registerEntityContentProducer(entityContentProducer);
}
@Test
public void testAddingResourceWithNoContent(){
Resource resource = new Resource(null, "xyz", "resource_with_no_content");
when(event.getResource()).thenReturn(resource.getName());
when(entityContentProducer.matches("resource_with_no_content")).thenReturn(false);
List resourceList = new ArrayList();
resourceList.add(resource);
when(entityContentProducer.getSiteContentIterator("xyz")).thenReturn(resourceList.iterator());
elasticSearchIndexBuilder.addResource(notification, event);
assertTrue(elasticSearchService.getNDocs() == 0);
}
private void addResources() {
for (Event event : events) {
try {
elasticSearchIndexBuilder.addResource(notification, event);
} catch (Exception e) {
e.printStackTrace();
assertFalse("problem adding event: " + event.getEvent(), true);
}
}
}
@Test
public void testAddResource() {
elasticSearchIndexBuilder.addResource(notification, event);
addResources();
elasticSearchIndexBuilder.refreshIndex();
assertTrue("the number of docs is " + elasticSearchService.getNDocs() + " expecting 106.",
elasticSearchService.getNDocs() == 106);
}
@Test
public void testGetSearchSuggestions() {
elasticSearchIndexBuilder.addResource(notification, event);
elasticSearchIndexBuilder.refreshIndex();
String[] suggestions = elasticSearchService.getSearchSuggestions("key", siteId, false);
List suggestionList = Arrays.asList(suggestions);
assertTrue(suggestionList.contains(resourceName));
suggestions = elasticSearchService.getSearchSuggestions("keyboard", siteId, false);
suggestionList = Arrays.asList(suggestions);
assertTrue(suggestionList.contains(resourceName));
}
@Test
public void deleteDoc(){
assertTrue(elasticSearchService.getNDocs() == 0);
elasticSearchIndexBuilder.addResource(notification, event);
elasticSearchIndexBuilder.refreshIndex();
assertTrue(elasticSearchService.getNDocs() == 1);
elasticSearchIndexBuilder.deleteDocument(resourceName, siteId);
elasticSearchIndexBuilder.refreshIndex();
assertTrue(elasticSearchService.getNDocs() == 0);
try {
SearchList list = elasticSearchService.search("asdf", siteIds, 0, 10);
assertFalse(list.size() > 0 );
} catch (InvalidSearchQueryException e) {
e.printStackTrace();
fail();
}
}
@Test
public void deleteAllDocumentForSite(){
elasticSearchIndexBuilder.addResource(notification, event);
addResources();
elasticSearchIndexBuilder.deleteAllDocumentForSite(siteId);
elasticSearchIndexBuilder.refreshIndex();
try {
SearchList list = elasticSearchService.search("asdf", siteIds, 0, 10);
assertFalse(list.size() > 0);
} catch (InvalidSearchQueryException e) {
e.printStackTrace();
fail();
}
assertTrue(elasticSearchService.getPendingDocs() == 0);
}
protected void wait(int millis) {
try {
Thread.sleep(millis);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
@Test
public void testSearch() {
elasticSearchIndexBuilder.addResource(notification, event);
addResources();
elasticSearchIndexBuilder.refreshIndex();
try {
SearchList list = elasticSearchService.search("asdf", siteIds, 0, 10);
assertNotNull(list.get(0) ) ;
assertEquals(list.get(0).getReference(),resourceName);
SearchResult result = list.get(0);
assertTrue(result.getSearchResult().toLowerCase().contains("<b>"));
} catch (InvalidSearchQueryException e) {
e.printStackTrace();
fail();
}
}
@Test
public void testRebuildSiteIndex() {
elasticSearchIndexBuilder.addResource(notification, event);
addResources();
elasticSearchIndexBuilder.rebuildIndex(siteId);
elasticSearchIndexBuilder.setContentIndexBatchSize(200);
elasticSearchIndexBuilder.setBulkRequestSize(400);
elasticSearchIndexBuilder.refreshIndex();
elasticSearchIndexBuilder.processContentQueue();
elasticSearchIndexBuilder.refreshIndex();
System.out.println(elasticSearchService.getNDocs());
assertTrue(elasticSearchService.getNDocs() == 106);
}
@Test
public void testRefreshSite(){
elasticSearchIndexBuilder.setContentIndexBatchSize(200);
elasticSearchIndexBuilder.setBulkRequestSize(20);
elasticSearchIndexBuilder.addResource(notification, event);
addResources();
elasticSearchIndexBuilder.refreshIndex();
elasticSearchIndexBuilder.processContentQueue();
elasticSearchIndexBuilder.refreshIndex();
assertTrue(elasticSearchService.getNDocs() == 106);
elasticSearchService.refreshSite(siteId);
assertTrue("the number of pending docs is " + elasticSearchIndexBuilder.getPendingDocuments() + ", expecting 0.",
elasticSearchIndexBuilder.getPendingDocuments() == 0);
assertTrue(elasticSearchService.getNDocs() == 106);
}
@Test
public void testRefresh() {
elasticSearchIndexBuilder.addResource(notification, event);
addResources();
elasticSearchService.refreshInstance();
assertTrue(elasticSearchService.getNDocs() == 106);
}
@Test
public void testRebuild(){
elasticSearchIndexBuilder.setContentIndexBatchSize(200);
elasticSearchIndexBuilder.setBulkRequestSize(400);
elasticSearchIndexBuilder.addResource(notification, event);
// add in a resource with no content
String resourceName = "billy bob";
Resource resource = new Resource(null, siteId, resourceName);
resources.put(resourceName, resource);
Event newEvent = mock(Event.class);
when(newEvent.getResource()).thenReturn(resource.getName());
events.add(newEvent);
when(entityContentProducer.matches(newEvent)).thenReturn(true);
when(entityContentProducer.matches(resourceName)).thenReturn(true);
when(entityContentProducer.getSiteId(resourceName)).thenReturn(siteId);
when(entityContentProducer.getAction(newEvent)).thenReturn(SearchBuilderItem.ACTION_ADD);
when(entityContentProducer.getContent(resourceName)).thenReturn(null);
when(entityContentProducer.getType(resourceName)).thenReturn("sakai:content");
when(entityContentProducer.getId(resourceName)).thenReturn(resourceName);
when(entityContentProducer.getTitle(resourceName)).thenReturn(resourceName);
addResources();
when(entityContentProducer.getSiteContentIterator(siteId)).thenReturn(resources.keySet().iterator());
elasticSearchService.rebuildInstance();
//assertTrue(elasticSearchIndexBuilder.getPendingDocuments() > 0);
elasticSearchIndexBuilder.refreshIndex();
elasticSearchIndexBuilder.processContentQueue();
elasticSearchIndexBuilder.refreshIndex();
verify(entityContentProducer, atLeast(106)).getContent(any(String.class));
assertTrue("pending doc=" + elasticSearchIndexBuilder.getPendingDocuments() + ", expecting 0",
elasticSearchIndexBuilder.getPendingDocuments() == 0);
assertTrue("num doc=" + elasticSearchService.getNDocs() + ", expecting 106.", elasticSearchService.getNDocs() == 106);
}
public class Resource {
private String content;
private String siteId;
private String name;
Resource(String content, String siteId, String name) {
this.content = content;
this.siteId = siteId;
this.name = name;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getSiteId() {
return siteId;
}
public void setSiteId(String siteId) {
this.siteId = siteId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
}
| true | true | public void setUp() throws Exception {
createTestResources();
when(site.getId()).thenReturn(siteId);
when(siteService.getSite(site.getId())).thenReturn(site);
sites.add(site);
when(serverConfigurationService.getBoolean("search.enable", false)).thenReturn(true);
when(serverConfigurationService.getConfigData().getItems()).thenReturn(new ArrayList());
when(serverConfigurationService.getServerId()).thenReturn("server1");
when(serverConfigurationService.getServerName()).thenReturn("clusterName");
when(serverConfigurationService.getString("elasticsearch.index.number_of_shards")).thenReturn("1");
when(serverConfigurationService.getString("elasticsearch.index.number_of_replicas")).thenReturn("0");
when(serverConfigurationService.getSakaiHomePath()).thenReturn(System.getProperty("java.io.tmpdir") + "/" + new Date().getTime());
when(notificationService.addTransientNotification()).thenReturn(notificationEdit);
siteIds.add(siteId);
when(siteService.getSites(SiteService.SelectionType.ANY, null, null, null, SiteService.SortType.NONE, null)).thenReturn(sites);
when(siteService.isSpecialSite(siteId)).thenReturn(false);
elasticSearchIndexBuilder = new ElasticSearchIndexBuilder();
elasticSearchIndexBuilder.setTestMode(true);
elasticSearchIndexBuilder.setOnlyIndexSearchToolSites(false);
elasticSearchIndexBuilder.setExcludeUserSites(false);
elasticSearchIndexBuilder.setSecurityService(securityService);
elasticSearchIndexBuilder.setSiteService(siteService);
elasticSearchIndexBuilder.setServerConfigurationService(serverConfigurationService);
elasticSearchIndexBuilder.setDelay(200);
elasticSearchIndexBuilder.setPeriod(10);
elasticSearchIndexBuilder.setContentIndexBatchSize(50);
elasticSearchIndexBuilder.setBulkRequestSize(20);
elasticSearchIndexBuilder.setMapping("{\n" +
" \"sakai_doc\": {\n" +
" \"_source\": {\n" +
" \"enabled\": false\n" +
" },\n" +
"\n" +
" \"properties\": {\n" +
" \"siteid\": {\n" +
" \"type\": \"string\",\n" +
" \"index\": \"not_analyzed\",\n" +
" \"store\": \"yes\"\n" +
" },\n" +
" \"title\": {\n" +
" \"type\": \"string\",\n" +
" \"store\": \"yes\",\n" +
" \"term_vector\" : \"with_positions_offsets\",\n" +
" \"search_analyzer\": \"str_search_analyzer\",\n" +
" \"index_analyzer\": \"str_index_analyzer\"\n" +
" },\n" +
" \"url\": {\n" +
" \"type\": \"string\",\n" +
" \"index\": \"not_analyzed\",\n" +
" \"store\": \"yes\"\n" +
" },\n" +
" \"reference\": {\n" +
" \"type\": \"string\",\n" +
" \"index\": \"not_analyzed\",\n" +
" \"store\": \"yes\"\n" +
" },\n" +
" \"id\": {\n" +
" \"type\": \"string\",\n" +
" \"index\": \"not_analyzed\",\n" +
" \"store\": \"yes\"\n" +
" },\n" +
" \"tool\": {\n" +
" \"type\": \"string\",\n" +
" \"index\": \"not_analyzed\",\n" +
" \"store\": \"yes\"\n" +
" },\n" +
" \"container\": {\n" +
" \"type\": \"string\",\n" +
" \"index\": \"not_analyzed\",\n" +
" \"store\": \"yes\"\n" +
" },\n" +
" \"type\": {\n" +
" \"type\": \"string\",\n" +
" \"index\": \"not_analyzed\",\n" +
" \"store\": \"yes\"\n" +
" },\n" +
" \"subtype\": {\n" +
" \"type\": \"string\",\n" +
" \"index\": \"not_analyzed\",\n" +
" \"store\": \"yes\"\n" +
" },\n" +
" \"contents\": {\n" +
" \"type\": \"string\",\n" +
" \"analyzer\": \"snowball\",\n" +
" \"index\": \"analyzed\",\n" +
" \"store\": \"no\"\n" +
" }\n" +
" }\n" +
" }\n" +
"}");
elasticSearchIndexBuilder.setIndexSettings("{\n" +
" \"analysis\": {\n" +
" \"filter\": {\n" +
" \"substring\": {\n" +
" \"type\": \"nGram\",\n" +
" \"min_gram\": 1,\n" +
" \"max_gram\": 20\n" +
" }\n" +
" },\n" +
" \"analyzer\": {\n" +
" \"snowball\": {\n" +
" \"type\": \"snowball\",\n" +
" \"language\": \"English\"\n" +
" },\n" +
" \"str_search_analyzer\": {\n" +
" \"tokenizer\": \"keyword\",\n" +
" \"filter\": [\"lowercase\"]\n" +
" },\n" +
" \"str_index_analyzer\": {\n" +
" \"tokenizer\": \"keyword\",\n" +
" \"filter\": [\"lowercase\", \"substring\"]\n" +
" }\n" +
" }\n" +
" }\n" +
"}\n" +
"\n");
elasticSearchIndexBuilder.init();
elasticSearchService = new ElasticSearchService();
elasticSearchService.setTriggerFunctions(new ArrayList<String>());
elasticSearchService.setEventTrackingService(eventTrackingService);
elasticSearchService.setServerConfigurationService(serverConfigurationService);
elasticSearchService.setSessionManager(sessionManager);
elasticSearchService.setUserDirectoryService(userDirectoryService);
elasticSearchService.setNotificationService(notificationService);
elasticSearchService.setSiteService(siteService);
elasticSearchService.setIndexBuilder(elasticSearchIndexBuilder);
elasticSearchIndexBuilder.setOnlyIndexSearchToolSites(false);
filter.setSearchIndexBuilder(elasticSearchIndexBuilder);
elasticSearchService.setFilter(filter);
elasticSearchIndexBuilder.setIgnoredSites("!admin,~admin");
elasticSearchService.init();
elasticSearchIndexBuilder.assureIndex();
elasticSearchIndexBuilder.registerEntityContentProducer(entityContentProducer);
}
| public void setUp() throws Exception {
createTestResources();
when(site.getId()).thenReturn(siteId);
when(siteService.getSite(site.getId())).thenReturn(site);
sites.add(site);
when(serverConfigurationService.getBoolean("search.enable", false)).thenReturn(true);
when(serverConfigurationService.getConfigData().getItems()).thenReturn(new ArrayList());
when(serverConfigurationService.getServerId()).thenReturn("server1");
when(serverConfigurationService.getServerName()).thenReturn("clusterName");
when(serverConfigurationService.getString("elasticsearch.index.number_of_shards")).thenReturn("1");
when(serverConfigurationService.getString("elasticsearch.index.number_of_replicas")).thenReturn("0");
when(serverConfigurationService.getSakaiHomePath()).thenReturn(System.getProperty("java.io.tmpdir") + "/" + new Date().getTime());
when(notificationService.addTransientNotification()).thenReturn(notificationEdit);
siteIds.add(siteId);
when(siteService.getSites(SiteService.SelectionType.ANY, null, null, null, SiteService.SortType.NONE, null)).thenReturn(sites);
when(siteService.isSpecialSite(siteId)).thenReturn(false);
elasticSearchIndexBuilder = new ElasticSearchIndexBuilder();
elasticSearchIndexBuilder.setTestMode(true);
elasticSearchIndexBuilder.setOnlyIndexSearchToolSites(false);
elasticSearchIndexBuilder.setExcludeUserSites(false);
elasticSearchIndexBuilder.setSecurityService(securityService);
elasticSearchIndexBuilder.setSiteService(siteService);
elasticSearchIndexBuilder.setServerConfigurationService(serverConfigurationService);
elasticSearchIndexBuilder.setDelay(200);
elasticSearchIndexBuilder.setPeriod(10);
elasticSearchIndexBuilder.setContentIndexBatchSize(50);
elasticSearchIndexBuilder.setBulkRequestSize(20);
elasticSearchIndexBuilder.setMapping("{\n" +
" \"sakai_doc\": {\n" +
" \"_source\": {\n" +
" \"enabled\": false\n" +
" },\n" +
"\n" +
" \"properties\": {\n" +
" \"siteid\": {\n" +
" \"type\": \"string\",\n" +
" \"index\": \"not_analyzed\",\n" +
" \"store\": \"yes\"\n" +
" },\n" +
" \"title\": {\n" +
" \"type\": \"string\",\n" +
" \"store\": \"yes\",\n" +
" \"term_vector\" : \"with_positions_offsets\",\n" +
" \"search_analyzer\": \"str_search_analyzer\",\n" +
" \"index_analyzer\": \"str_index_analyzer\"\n" +
" },\n" +
" \"url\": {\n" +
" \"type\": \"string\",\n" +
" \"index\": \"not_analyzed\",\n" +
" \"store\": \"yes\"\n" +
" },\n" +
" \"reference\": {\n" +
" \"type\": \"string\",\n" +
" \"index\": \"not_analyzed\",\n" +
" \"store\": \"yes\"\n" +
" },\n" +
" \"id\": {\n" +
" \"type\": \"string\",\n" +
" \"index\": \"not_analyzed\",\n" +
" \"store\": \"yes\"\n" +
" },\n" +
" \"tool\": {\n" +
" \"type\": \"string\",\n" +
" \"index\": \"not_analyzed\",\n" +
" \"store\": \"yes\"\n" +
" },\n" +
" \"container\": {\n" +
" \"type\": \"string\",\n" +
" \"index\": \"not_analyzed\",\n" +
" \"store\": \"yes\"\n" +
" },\n" +
" \"type\": {\n" +
" \"type\": \"string\",\n" +
" \"index\": \"not_analyzed\",\n" +
" \"store\": \"yes\"\n" +
" },\n" +
" \"subtype\": {\n" +
" \"type\": \"string\",\n" +
" \"index\": \"not_analyzed\",\n" +
" \"store\": \"yes\"\n" +
" },\n" +
" \"contents\": {\n" +
" \"type\": \"string\",\n" +
" \"analyzer\": \"snowball\",\n" +
" \"index\": \"analyzed\",\n" +
" \"store\": \"no\"\n" +
" }\n" +
" }\n" +
" }\n" +
"}");
elasticSearchIndexBuilder.setIndexSettings("{\n" +
" \"analysis\": {\n" +
" \"filter\": {\n" +
" \"substring\": {\n" +
" \"type\": \"nGram\",\n" +
" \"min_gram\": 1,\n" +
" \"max_gram\": 20\n" +
" }\n" +
" },\n" +
" \"analyzer\": {\n" +
" \"snowball\": {\n" +
" \"type\": \"snowball\",\n" +
" \"language\": \"English\"\n" +
" },\n" +
" \"str_search_analyzer\": {\n" +
" \"tokenizer\": \"keyword\",\n" +
" \"filter\": [\"lowercase\"]\n" +
" },\n" +
" \"str_index_analyzer\": {\n" +
" \"tokenizer\": \"keyword\",\n" +
" \"filter\": [\"lowercase\", \"substring\"]\n" +
" }\n" +
" }\n" +
" }\n" +
"}\n" +
"\n");
elasticSearchIndexBuilder.init();
elasticSearchService = new ElasticSearchService();
elasticSearchService.setTriggerFunctions(new ArrayList<String>());
elasticSearchService.setEventTrackingService(eventTrackingService);
elasticSearchService.setServerConfigurationService(serverConfigurationService);
elasticSearchService.setSessionManager(sessionManager);
elasticSearchService.setUserDirectoryService(userDirectoryService);
elasticSearchService.setNotificationService(notificationService);
elasticSearchService.setSiteService(siteService);
elasticSearchService.setIndexBuilder(elasticSearchIndexBuilder);
elasticSearchIndexBuilder.setOnlyIndexSearchToolSites(false);
filter.setSearchIndexBuilder(elasticSearchIndexBuilder);
elasticSearchService.setFilter(filter);
elasticSearchService.setLocalNode(true);
elasticSearchIndexBuilder.setIgnoredSites("!admin,~admin");
elasticSearchService.init();
elasticSearchIndexBuilder.assureIndex();
elasticSearchIndexBuilder.registerEntityContentProducer(entityContentProducer);
}
|
diff --git a/INS/src/fr/utc/nf33/ins/EntryPointsActivity.java b/INS/src/fr/utc/nf33/ins/EntryPointsActivity.java
index 6a8bca7..4880948 100644
--- a/INS/src/fr/utc/nf33/ins/EntryPointsActivity.java
+++ b/INS/src/fr/utc/nf33/ins/EntryPointsActivity.java
@@ -1,135 +1,135 @@
/**
*
*/
package fr.utc.nf33.ins;
import java.util.List;
import android.app.ListActivity;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.support.v4.content.LocalBroadcastManager;
import android.widget.ArrayAdapter;
import fr.utc.nf33.ins.location.Building;
import fr.utc.nf33.ins.location.CloseBuildingsService;
import fr.utc.nf33.ins.location.CloseBuildingsService.LocalBinder;
import fr.utc.nf33.ins.location.LocationHelper;
import fr.utc.nf33.ins.location.LocationIntent;
import fr.utc.nf33.ins.location.SnrService;
/**
*
* @author
*
*/
public final class EntryPointsActivity extends ListActivity {
//
private ServiceConnection mCloseBuildingsConnection;
//
private CloseBuildingsService mCloseBuildingsService;
//
private BroadcastReceiver mNewCloseBuildingsReceiver;
//
private BroadcastReceiver mNewSnrReceiver;
//
private ServiceConnection mSnrConnection;
@Override
protected final void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_entry_points);
}
@Override
protected final void onStart() {
super.onStart();
// Connect to the SNR Service.
Intent snrIntent = new Intent(this, SnrService.class);
mSnrConnection = new ServiceConnection() {
@Override
public final void onServiceConnected(ComponentName name, IBinder service) {
}
@Override
public final void onServiceDisconnected(ComponentName name) {
}
};
bindService(snrIntent, mSnrConnection, Context.BIND_AUTO_CREATE);
// Connect to the Close Buildings Service.
Intent closeBuildingsIntent = new Intent(this, CloseBuildingsService.class);
mCloseBuildingsConnection = new ServiceConnection() {
@Override
public final void onServiceConnected(ComponentName name, IBinder service) {
mCloseBuildingsService = ((LocalBinder) service).getService();
List<Building> buildings = mCloseBuildingsService.getCloseBuildings();
if (buildings == null) return;
setListAdapter(new ArrayAdapter<Building>(EntryPointsActivity.this,
- R.id.entry_points_list_item_text, buildings));
+ R.layout.entry_points_list_item, buildings));
}
@Override
public final void onServiceDisconnected(ComponentName name) {
}
};
bindService(closeBuildingsIntent, mCloseBuildingsConnection, Context.BIND_AUTO_CREATE);
// Register receivers.
LocalBroadcastManager lbm = LocalBroadcastManager.getInstance(this);
mNewCloseBuildingsReceiver = new BroadcastReceiver() {
@Override
public final void onReceive(Context context, Intent intent) {
List<Building> buildings = mCloseBuildingsService.getCloseBuildings();
if (buildings == null) return;
setListAdapter(new ArrayAdapter<Building>(EntryPointsActivity.this,
- R.id.entry_points_list_item_text, buildings));
+ R.layout.entry_points_list_item, buildings));
}
};
lbm.registerReceiver(mNewCloseBuildingsReceiver,
LocationIntent.NewCloseBuildings.newIntentFilter());
mNewSnrReceiver = new BroadcastReceiver() {
@Override
public final void onReceive(Context context, Intent intent) {
float snr = intent.getFloatExtra(LocationIntent.NewSnr.EXTRA_SNR, 0);
List<Building> buildings = mCloseBuildingsService.getCloseBuildings();
if (LocationHelper.shouldGoIndoor(snr, buildings))
startActivity(new Intent(EntryPointsActivity.this, IndoorActivity.class));
}
};
lbm.registerReceiver(mNewSnrReceiver, LocationIntent.NewSnr.newIntentFilter());
}
@Override
protected final void onStop() {
super.onStop();
// Unregister receivers.
LocalBroadcastManager lbm = LocalBroadcastManager.getInstance(this);
lbm.unregisterReceiver(mNewCloseBuildingsReceiver);
mNewCloseBuildingsReceiver = null;
lbm.unregisterReceiver(mNewSnrReceiver);
mNewSnrReceiver = null;
// Disconnect from the Close Buildings Service.
unbindService(mCloseBuildingsConnection);
mCloseBuildingsConnection = null;
mCloseBuildingsService = null;
// Disconnect from the SNR Service.
unbindService(mSnrConnection);
mSnrConnection = null;
}
}
| false | true | protected final void onStart() {
super.onStart();
// Connect to the SNR Service.
Intent snrIntent = new Intent(this, SnrService.class);
mSnrConnection = new ServiceConnection() {
@Override
public final void onServiceConnected(ComponentName name, IBinder service) {
}
@Override
public final void onServiceDisconnected(ComponentName name) {
}
};
bindService(snrIntent, mSnrConnection, Context.BIND_AUTO_CREATE);
// Connect to the Close Buildings Service.
Intent closeBuildingsIntent = new Intent(this, CloseBuildingsService.class);
mCloseBuildingsConnection = new ServiceConnection() {
@Override
public final void onServiceConnected(ComponentName name, IBinder service) {
mCloseBuildingsService = ((LocalBinder) service).getService();
List<Building> buildings = mCloseBuildingsService.getCloseBuildings();
if (buildings == null) return;
setListAdapter(new ArrayAdapter<Building>(EntryPointsActivity.this,
R.id.entry_points_list_item_text, buildings));
}
@Override
public final void onServiceDisconnected(ComponentName name) {
}
};
bindService(closeBuildingsIntent, mCloseBuildingsConnection, Context.BIND_AUTO_CREATE);
// Register receivers.
LocalBroadcastManager lbm = LocalBroadcastManager.getInstance(this);
mNewCloseBuildingsReceiver = new BroadcastReceiver() {
@Override
public final void onReceive(Context context, Intent intent) {
List<Building> buildings = mCloseBuildingsService.getCloseBuildings();
if (buildings == null) return;
setListAdapter(new ArrayAdapter<Building>(EntryPointsActivity.this,
R.id.entry_points_list_item_text, buildings));
}
};
lbm.registerReceiver(mNewCloseBuildingsReceiver,
LocationIntent.NewCloseBuildings.newIntentFilter());
mNewSnrReceiver = new BroadcastReceiver() {
@Override
public final void onReceive(Context context, Intent intent) {
float snr = intent.getFloatExtra(LocationIntent.NewSnr.EXTRA_SNR, 0);
List<Building> buildings = mCloseBuildingsService.getCloseBuildings();
if (LocationHelper.shouldGoIndoor(snr, buildings))
startActivity(new Intent(EntryPointsActivity.this, IndoorActivity.class));
}
};
lbm.registerReceiver(mNewSnrReceiver, LocationIntent.NewSnr.newIntentFilter());
}
| protected final void onStart() {
super.onStart();
// Connect to the SNR Service.
Intent snrIntent = new Intent(this, SnrService.class);
mSnrConnection = new ServiceConnection() {
@Override
public final void onServiceConnected(ComponentName name, IBinder service) {
}
@Override
public final void onServiceDisconnected(ComponentName name) {
}
};
bindService(snrIntent, mSnrConnection, Context.BIND_AUTO_CREATE);
// Connect to the Close Buildings Service.
Intent closeBuildingsIntent = new Intent(this, CloseBuildingsService.class);
mCloseBuildingsConnection = new ServiceConnection() {
@Override
public final void onServiceConnected(ComponentName name, IBinder service) {
mCloseBuildingsService = ((LocalBinder) service).getService();
List<Building> buildings = mCloseBuildingsService.getCloseBuildings();
if (buildings == null) return;
setListAdapter(new ArrayAdapter<Building>(EntryPointsActivity.this,
R.layout.entry_points_list_item, buildings));
}
@Override
public final void onServiceDisconnected(ComponentName name) {
}
};
bindService(closeBuildingsIntent, mCloseBuildingsConnection, Context.BIND_AUTO_CREATE);
// Register receivers.
LocalBroadcastManager lbm = LocalBroadcastManager.getInstance(this);
mNewCloseBuildingsReceiver = new BroadcastReceiver() {
@Override
public final void onReceive(Context context, Intent intent) {
List<Building> buildings = mCloseBuildingsService.getCloseBuildings();
if (buildings == null) return;
setListAdapter(new ArrayAdapter<Building>(EntryPointsActivity.this,
R.layout.entry_points_list_item, buildings));
}
};
lbm.registerReceiver(mNewCloseBuildingsReceiver,
LocationIntent.NewCloseBuildings.newIntentFilter());
mNewSnrReceiver = new BroadcastReceiver() {
@Override
public final void onReceive(Context context, Intent intent) {
float snr = intent.getFloatExtra(LocationIntent.NewSnr.EXTRA_SNR, 0);
List<Building> buildings = mCloseBuildingsService.getCloseBuildings();
if (LocationHelper.shouldGoIndoor(snr, buildings))
startActivity(new Intent(EntryPointsActivity.this, IndoorActivity.class));
}
};
lbm.registerReceiver(mNewSnrReceiver, LocationIntent.NewSnr.newIntentFilter());
}
|
diff --git a/src/org/ab/nativelayer/MainView.java b/src/org/ab/nativelayer/MainView.java
index 0161afe..e64ded8 100644
--- a/src/org/ab/nativelayer/MainView.java
+++ b/src/org/ab/nativelayer/MainView.java
@@ -1,332 +1,333 @@
package org.ab.nativelayer;
import java.nio.ByteBuffer;
import java.nio.ShortBuffer;
import java.util.List;
import java.util.Vector;
import org.ab.c64.FrodoC64;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.preference.PreferenceManager;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyCharacterMap;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
public class MainView extends SurfaceView implements SurfaceHolder.Callback {
private static List<Integer> queuedCodes;
public String id;
private static ByteBuffer drawCanvasBuffer;
static ShortBuffer drawCanvasBufferAsShort;
private int bufferWidth;
private int bufferHeight;
private int width;
private int height;
public void startEmulation() {
((MainActivity) getContext()).startEmulation();
}
protected SurfaceHolder mSurfaceHolder;
protected static Bitmap mainScreen;
protected float scaleX;
protected float scaleY;
protected boolean coordsChanged;
Matrix matrixScreen;
public void initMatrix() {
if (width < height) {
scaleY = scaleX;
} else {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getContext());
String scale = prefs.getString("scale", "stretched");
pixels = 0;
pixelsH = 0;
if ("scaled".equals(scale)) {
scaleX = scaleY;
pixels = (int) ((width - bufferWidth*scaleX) / 2);
} else if ("1x".equals(scale)) {
scaleX = 1.0f;
scaleY = 1.0f;
pixels = (int) ((width - bufferWidth*scaleX) / 2);
pixelsH = (int) ((height - bufferHeight*scaleX) / 2);
} else if ("2x".equals(scale)) {
scaleX = 2.0f;
scaleY = 2.0f;
pixels = (int) ((width - bufferWidth*scaleX) / 2);
pixelsH = (int) ((height - bufferHeight*scaleX) / 2);
}
}
matrixScreen = new Matrix();
matrixScreen.setScale(scaleX, scaleY);
matrixScreen.postTranslate(pixels, pixelsH);
}
public void surfaceCreated(SurfaceHolder holder) {
Log.i(id, "Surface created");
bufferWidth = ((MainActivity) getContext()).getWidth();
bufferHeight = ((MainActivity) getContext()).getHeight();
//if (mainScreen == null) {
mainScreen = Bitmap.createBitmap(bufferWidth,bufferHeight, Bitmap.Config.RGB_565);
Log.i(id, "Create screen buffers");
drawCanvasBuffer = ByteBuffer.allocateDirect(bufferWidth * bufferHeight * 2);
drawCanvasBufferAsShort = drawCanvasBuffer.asShortBuffer();
((FrodoC64) getContext()).initScreenData(drawCanvasBufferAsShort, bufferWidth, bufferHeight, 0, 0, ((FrodoC64) getContext()).isBorder()?1:0);
//}
if (MainActivity.emulationThread == null) {
MainActivity.emulationThread = new Thread() {
public void run() {
Log.i(id, "Emulation thread started");
startEmulation();
Log.i(id, "Emulation thread exited");
}
};
MainActivity.emulationThread.start();
}
//updater = new ScreenUpdater(this);
}
public void surfaceDestroyed(SurfaceHolder holder) {
Log.i(id, "Surface destroyed");
if (updater != null)
updater.stop();
}
public void emulatorReady() {
}
public void stop() {
Log.i(id, "Stopping..");
if (MainActivity.emulationThread != null)
MainActivity.emulationThread.interrupt();
MainActivity.emulationThread = null;
}
long t = System.currentTimeMillis();
int frames;
public void checkFPS() {
if (frames % 20 == 0) {
long t2 = System.currentTimeMillis();
Log.i("uae", "FPS: " + 20000 / (t2 - t));
t = t2;
}
frames++;
}
public void requestRender() {
if (updater != null) {
updater.render();
} else {
// checkFPS();
Canvas c = null;
try {
c = mSurfaceHolder.lockCanvas(null);
synchronized (mSurfaceHolder) {
+ drawCanvasBufferAsShort.position(0);
mainScreen.copyPixelsFromBuffer(drawCanvasBufferAsShort);
if (c != null) {
c.drawBitmap(mainScreen, matrixScreen, null);
if (((MainActivity) getContext()).vKeyPad != null)
((MainActivity) getContext()).vKeyPad.draw(c);
}
}
} finally {
// do this in a finally so that if an exception is thrown
// during the above, we don't leave the Surface in an
// inconsistent state
if (c != null) {
mSurfaceHolder.unlockCanvasAndPost(c);
}
}
}
}
ScreenUpdater updater;
public MainView(Context context, AttributeSet attrs) {
super(context, attrs);
setFocusable(true);
setFocusableInTouchMode(true);
mSurfaceHolder = getHolder();
mSurfaceHolder.addCallback(this);
id = ((MainActivity) getContext()).getID();
if (queuedCodes == null)
queuedCodes = new Vector<Integer>();
}
protected synchronized void key(int real_keycode, boolean down) {
if (real_keycode >> 16 > 0) {
// two codes!
int code1 = real_keycode >> 16;
int code2 = real_keycode & 0x0000ffff;
if (down) {
((FrodoC64) getContext()).sendKey(-code1-2);
((FrodoC64) getContext()).sendKey(-code2-2);
} else {
((FrodoC64) getContext()).sendKey(code2);
((FrodoC64) getContext()).sendKey(code1);
}
} else
((FrodoC64) getContext()).sendKey(down?-real_keycode-2:real_keycode);
}
public int waitEvent() {
if (queuedCodes.size() == 0)
return -1;
else {
int c = queuedCodes.remove(0);
//Log.i("frodoc64", "c:" + c);
return c;
}
}
public boolean keyDown(int keyCode, KeyEvent event) {
boolean b = actionKey(true, keyCode);
sleepAfterInputEvent();
return b;
}
public boolean keyUp(int keyCode, KeyEvent event) {
boolean b = actionKey(false, keyCode);
sleepAfterInputEvent();
return b;
}
/*
public boolean touchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
((MainActivity) getContext()).manageTouchKeyboard(true);
return true;
}
return false;
}
*/
protected void sleepAfterInputEvent() {
/*try {
Thread.sleep(16);
} catch (InterruptedException e) {
e.printStackTrace();
}*/
}
public boolean actionKey(boolean down, int keycode) {
int real = ((MainActivity) getContext()).getRealKeycode(keycode, down);
if (real == Integer.MAX_VALUE) {
return true;
} else if (real == Integer.MIN_VALUE) {
return false;
} else {
key(real, down);
return true;
}
}
public boolean isOpenGL() {
return false;
}
public void setOpenGL(boolean openGL) {
}
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
coordsChanged = true;
this.width = width;
this.height = height;
scaleX = (float) (width-pixels)/bufferWidth;
scaleY = (float) height/bufferHeight;
initMatrix();
if (updater != null)
updater.start();
if (((MainActivity) getContext()).vKeyPad != null)
((MainActivity) getContext()).vKeyPad.resize(width, height);
}
private int pixels;
private int pixelsH;
public void shiftImage(int leftDPIs) {
if (leftDPIs > 0) {
DisplayMetrics metrics = new DisplayMetrics();
((MainActivity) getContext()).getWindowManager().getDefaultDisplay().getMetrics(metrics);
pixels = (int) (leftDPIs * metrics.density + 0.5f);
Log.i("frodo64", "pixels: " + pixels);
scaleX = (float) (width-pixels)/bufferWidth;
scaleY = (float) height/bufferHeight;
coordsChanged = true;
} else {
pixels = 0;
scaleX = (float) width/bufferWidth;
scaleY = (float) height/bufferHeight;
coordsChanged = true;
}
initMatrix();
}
public void init(Context context) {
}
@Override
public boolean onTouchEvent(MotionEvent event) {
/*if (event.getAction() == MotionEvent.ACTION_UP) {
return true;
}
return false;*/
if (((MainActivity) getContext()).vKeyPad != null) {
boolean b = ((MainActivity) getContext()).vKeyPad.onTouch(event, false);
return b;
}
return false;
}
}
| true | true | public void requestRender() {
if (updater != null) {
updater.render();
} else {
// checkFPS();
Canvas c = null;
try {
c = mSurfaceHolder.lockCanvas(null);
synchronized (mSurfaceHolder) {
mainScreen.copyPixelsFromBuffer(drawCanvasBufferAsShort);
if (c != null) {
c.drawBitmap(mainScreen, matrixScreen, null);
if (((MainActivity) getContext()).vKeyPad != null)
((MainActivity) getContext()).vKeyPad.draw(c);
}
}
} finally {
// do this in a finally so that if an exception is thrown
// during the above, we don't leave the Surface in an
// inconsistent state
if (c != null) {
mSurfaceHolder.unlockCanvasAndPost(c);
}
}
}
}
| public void requestRender() {
if (updater != null) {
updater.render();
} else {
// checkFPS();
Canvas c = null;
try {
c = mSurfaceHolder.lockCanvas(null);
synchronized (mSurfaceHolder) {
drawCanvasBufferAsShort.position(0);
mainScreen.copyPixelsFromBuffer(drawCanvasBufferAsShort);
if (c != null) {
c.drawBitmap(mainScreen, matrixScreen, null);
if (((MainActivity) getContext()).vKeyPad != null)
((MainActivity) getContext()).vKeyPad.draw(c);
}
}
} finally {
// do this in a finally so that if an exception is thrown
// during the above, we don't leave the Surface in an
// inconsistent state
if (c != null) {
mSurfaceHolder.unlockCanvasAndPost(c);
}
}
}
}
|
diff --git a/src/test/java/de/undercouch/citeproc/helper/tool/OptionParserTest.java b/src/test/java/de/undercouch/citeproc/helper/tool/OptionParserTest.java
index 60ac9c6..c45d6c9 100644
--- a/src/test/java/de/undercouch/citeproc/helper/tool/OptionParserTest.java
+++ b/src/test/java/de/undercouch/citeproc/helper/tool/OptionParserTest.java
@@ -1,175 +1,175 @@
// Copyright 2013 Michel Kraemer
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package de.undercouch.citeproc.helper.tool;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.util.List;
import org.junit.Test;
import de.undercouch.citeproc.helper.tool.Option.ArgumentType;
/**
* Tests the command-line interface parser
* @author Michel Kraemer
*/
public class OptionParserTest {
private static class SimpleCommand implements Command {
private static final OptionGroup<Integer> options = new OptionBuilder<Integer>()
.add(0, "arg1", "argument 1")
.add(1, "arg2", "argument 2")
.build();
@Override
public int run(String[] args) throws OptionParserException {
//should not throw
OptionParser.Result<Integer> r = OptionParser.parse(args, options, null);
assertEquals(0, r.getRemainingArgs().length);
return 0;
}
}
private static final OptionGroup<Integer> SIMPLE_OPTIONS = new OptionBuilder<Integer>()
.add(0, "opt", "o", "option 1")
.add(1, "oarg", "a", "option with arg", "ARG", ArgumentType.STRING)
.build();
/**
* Tests if the parser can parse a simple command
* @throws Exception if something goes wrong
*/
@Test
public void simpleCommand() throws Exception {
OptionGroup<Integer> options = new OptionBuilder<Integer>()
.addCommand(0, "simple", "simple command")
.build();
OptionParser.Result<Integer> result = OptionParser.parse(
new String[] { "simple" }, options, null);
List<Value<Integer>> values = result.getValues();
assertEquals(1, values.size());
assertEquals(0, values.get(0).getId().intValue());
}
/**
* Tests if the parser can parse a command with arguments
* @throws Exception if something goes wrong
*/
@Test
public void commandWithArguments() throws Exception {
OptionGroup<Integer> options = new OptionBuilder<Integer>()
.addCommand(0, "simple", "simple command")
.build();
OptionParser.Result<Integer> result = OptionParser.parse(
new String[] { "simple", "--arg1", "--arg2" }, options, null);
List<Value<Integer>> values = result.getValues();
assertEquals(1, values.size());
assertEquals(0, values.get(0).getId().intValue());
assertArrayEquals(new String[] { "--arg1", "--arg2" }, result.getRemainingArgs());
new SimpleCommand().run(result.getRemainingArgs());
}
/**
* Tests if the parser can parse simple options
* @throws Exception if something goes wrong
*/
@Test
public void simpleOptions() throws Exception {
OptionParser.Result<Integer> result = OptionParser.parse(
new String[] { "--opt", "-o", "--oarg", "test" }, SIMPLE_OPTIONS, null);
List<Value<Integer>> values = result.getValues();
assertEquals(3, values.size());
assertEquals(0, values.get(0).getId().intValue());
assertEquals(0, values.get(1).getId().intValue());
assertEquals(1, values.get(2).getId().intValue());
assertEquals("test", values.get(2).getValue().toString());
}
/**
* Tests if the parser fails to parse an unknown option
* @throws Exception if something goes wrong
*/
@Test(expected = InvalidOptionException.class)
public void unknownOption() throws Exception {
OptionParser.parse(new String[] { "--bla" }, SIMPLE_OPTIONS, null);
}
/**
* Tests if the parser fails to parse an unknown default argument
* @throws Exception if something goes wrong
*/
@Test(expected = InvalidOptionException.class)
public void unknownDefault() throws Exception {
OptionParser.parse(new String[] { "default" }, SIMPLE_OPTIONS, null);
}
/**
* Tests if the parser can parse a default argument
* @throws Exception if something goes wrong
*/
@Test
public void defaultValue() throws Exception {
OptionParser.Result<Integer> result = OptionParser.parse(
new String[] { "--opt", "default" }, SIMPLE_OPTIONS, -1);
List<Value<Integer>> values = result.getValues();
assertEquals(2, values.size());
assertEquals(0, values.get(0).getId().intValue());
assertEquals(-1, values.get(1).getId().intValue());
assertEquals("default", values.get(1).getValue().toString());
}
/**
* Tests if usage information is printed out correctly
* @throws Exception if something goes wrong
*/
@Test
public void usage() throws Exception {
OptionGroup<Integer> options = new OptionBuilder<Integer>()
.add(0, "opt", "o", "option 1")
.add(1, "oarg", "a", "option with arg", "ARG", ArgumentType.STRING)
.add(new OptionBuilder<Integer>("Group:")
.add(3, "b", "group option b")
.add(4, "c", "group option c")
.build()
)
.addCommand(5, "command", "command 1")
.addCommand(5, "bla", "command 2")
.build();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PrintStream ps = new PrintStream(baos, true, "UTF-8");
OptionParser.usage("test", "desc", options, ps);
ps.flush();
String str = baos.toString("UTF-8");
- String n = System.lineSeparator();
+ String n = System.getProperty("line.separator");
assertEquals("Usage: test" + n
+ "desc" + n
+ n
+ " -o,--opt option 1" + n
+ " -a,--oarg <ARG> option with arg" + n
+ n
+ "Group:" + n
+ " --b group option b" + n
+ " --c group option c" + n
+ n
+ "Commands:" + n
+ " command command 1" + n
+ " bla command 2" + n, str);
}
}
| true | true | public void usage() throws Exception {
OptionGroup<Integer> options = new OptionBuilder<Integer>()
.add(0, "opt", "o", "option 1")
.add(1, "oarg", "a", "option with arg", "ARG", ArgumentType.STRING)
.add(new OptionBuilder<Integer>("Group:")
.add(3, "b", "group option b")
.add(4, "c", "group option c")
.build()
)
.addCommand(5, "command", "command 1")
.addCommand(5, "bla", "command 2")
.build();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PrintStream ps = new PrintStream(baos, true, "UTF-8");
OptionParser.usage("test", "desc", options, ps);
ps.flush();
String str = baos.toString("UTF-8");
String n = System.lineSeparator();
assertEquals("Usage: test" + n
+ "desc" + n
+ n
+ " -o,--opt option 1" + n
+ " -a,--oarg <ARG> option with arg" + n
+ n
+ "Group:" + n
+ " --b group option b" + n
+ " --c group option c" + n
+ n
+ "Commands:" + n
+ " command command 1" + n
+ " bla command 2" + n, str);
}
| public void usage() throws Exception {
OptionGroup<Integer> options = new OptionBuilder<Integer>()
.add(0, "opt", "o", "option 1")
.add(1, "oarg", "a", "option with arg", "ARG", ArgumentType.STRING)
.add(new OptionBuilder<Integer>("Group:")
.add(3, "b", "group option b")
.add(4, "c", "group option c")
.build()
)
.addCommand(5, "command", "command 1")
.addCommand(5, "bla", "command 2")
.build();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PrintStream ps = new PrintStream(baos, true, "UTF-8");
OptionParser.usage("test", "desc", options, ps);
ps.flush();
String str = baos.toString("UTF-8");
String n = System.getProperty("line.separator");
assertEquals("Usage: test" + n
+ "desc" + n
+ n
+ " -o,--opt option 1" + n
+ " -a,--oarg <ARG> option with arg" + n
+ n
+ "Group:" + n
+ " --b group option b" + n
+ " --c group option c" + n
+ n
+ "Commands:" + n
+ " command command 1" + n
+ " bla command 2" + n, str);
}
|
diff --git a/src/hello/FizzBuzz.java b/src/hello/FizzBuzz.java
index 8454e2c..b7e54ee 100644
--- a/src/hello/FizzBuzz.java
+++ b/src/hello/FizzBuzz.java
@@ -1,11 +1,11 @@
package hello;
public class FizzBuzz {
public String fizzbuzz(int i) {
- if (i == 3) return "Fizz";
+ if (i % 3 == 0) return "Fizz";
if (i == 5) return "Buzz";
return null;
}
}
| true | true | public String fizzbuzz(int i) {
if (i == 3) return "Fizz";
if (i == 5) return "Buzz";
return null;
}
| public String fizzbuzz(int i) {
if (i % 3 == 0) return "Fizz";
if (i == 5) return "Buzz";
return null;
}
|
diff --git a/org.osate.xtext.aadl2.errormodel/src/org/osate/xtext/aadl2/errormodel/naming/ErrorModelQualifiedNameProvider.java b/org.osate.xtext.aadl2.errormodel/src/org/osate/xtext/aadl2/errormodel/naming/ErrorModelQualifiedNameProvider.java
index a948e91d..2d29f386 100644
--- a/org.osate.xtext.aadl2.errormodel/src/org/osate/xtext/aadl2/errormodel/naming/ErrorModelQualifiedNameProvider.java
+++ b/org.osate.xtext.aadl2.errormodel/src/org/osate/xtext/aadl2/errormodel/naming/ErrorModelQualifiedNameProvider.java
@@ -1,37 +1,38 @@
package org.osate.xtext.aadl2.errormodel.naming;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.xtext.naming.DefaultDeclarativeQualifiedNameProvider;
import org.eclipse.xtext.naming.QualifiedName;
import org.osate.aadl2.AadlPackage;
import org.osate.aadl2.NamedElement;
import org.osate.xtext.aadl2.errormodel.errorModel.ErrorBehaviorStateMachine;
import org.osate.xtext.aadl2.errormodel.errorModel.ErrorModelLibrary;
import org.osate.xtext.aadl2.errormodel.errorModel.ErrorType;
import org.osate.xtext.aadl2.errormodel.errorModel.TypeMappingSet;
import org.osate.xtext.aadl2.errormodel.errorModel.TypeSet;
import org.osate.xtext.aadl2.errormodel.errorModel.TypeTransformationSet;
public class ErrorModelQualifiedNameProvider extends DefaultDeclarativeQualifiedNameProvider {
// Enable to limit indexing to global items
// Duplicates checking only applies to global items
@Override
public QualifiedName getFullyQualifiedName(final EObject obj) {
if (obj instanceof ErrorBehaviorStateMachine || obj instanceof TypeMappingSet || obj instanceof ErrorModelLibrary
|| obj instanceof ErrorType || obj instanceof TypeSet || obj instanceof TypeTransformationSet){
+ if (((NamedElement)obj).getName() == null) return null;
return getConverter().toQualifiedName(getTheName((NamedElement)obj));
}
return null;
}
protected String getTheName(NamedElement namedElement){
NamedElement root = namedElement.getElementRoot();
if (namedElement instanceof ErrorModelLibrary){
return root.getName() + "::"+"emv2";
}
return root.getName() + "::emv2::" + namedElement.getName();
}
}
| true | true | public QualifiedName getFullyQualifiedName(final EObject obj) {
if (obj instanceof ErrorBehaviorStateMachine || obj instanceof TypeMappingSet || obj instanceof ErrorModelLibrary
|| obj instanceof ErrorType || obj instanceof TypeSet || obj instanceof TypeTransformationSet){
return getConverter().toQualifiedName(getTheName((NamedElement)obj));
}
return null;
}
| public QualifiedName getFullyQualifiedName(final EObject obj) {
if (obj instanceof ErrorBehaviorStateMachine || obj instanceof TypeMappingSet || obj instanceof ErrorModelLibrary
|| obj instanceof ErrorType || obj instanceof TypeSet || obj instanceof TypeTransformationSet){
if (((NamedElement)obj).getName() == null) return null;
return getConverter().toQualifiedName(getTheName((NamedElement)obj));
}
return null;
}
|
diff --git a/H-sektionen/src/se/chalmers/h_sektionen/adapters/NewsAdapter.java b/H-sektionen/src/se/chalmers/h_sektionen/adapters/NewsAdapter.java
index 1cd028d..3636fe9 100644
--- a/H-sektionen/src/se/chalmers/h_sektionen/adapters/NewsAdapter.java
+++ b/H-sektionen/src/se/chalmers/h_sektionen/adapters/NewsAdapter.java
@@ -1,102 +1,102 @@
package se.chalmers.h_sektionen.adapters;
import java.util.ArrayList;
import java.util.Collection;
import se.chalmers.h_sektionen.R;
import se.chalmers.h_sektionen.containers.NewsItem;
import se.chalmers.h_sektionen.utils.CacheCompass;
import se.chalmers.h_sektionen.utils.PicLoaderThread;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class NewsAdapter extends ArrayAdapter<NewsItem> {
private ArrayList<NewsItem> objects;
public NewsAdapter(Context context, int resource, ArrayList<NewsItem> objects){
super(context, resource, objects);
this.objects = objects;
}
public ArrayList<NewsItem> getItems(){
return objects;
}
/**
* Overrided and added manually because method unsupported in target API.
*/
@Override
public void addAll(Collection<? extends NewsItem> collection){
for (NewsItem item : collection){
objects.add(item);
}
}
public View getView(int position, View convertView, ViewGroup parent){
//Assign the view we are converting to a local variable
View v = convertView;
// first check to see if the view is null. if so, we have to inflate it.
// to inflate it basically means to render, or show, the view.
if(v == null){
LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = inflater.inflate(R.layout.news_feed_item, null);
}
NewsItem item = objects.get(position);
if (item != null){
TextView message = (TextView) v.findViewById(R.id.item_message);
TextView date = (TextView) v.findViewById(R.id.item_date);
ImageView image = (ImageView) v.findViewById(R.id.item_image);
if (message != null){
message.setText(item.getMessage());
}
if (date != null){
date.setText(item.getDate());
}
if (image != null){
//Remove current image
image.setImageBitmap(null);
//Check if post has image adress
if (item.getImageAdr()!=null && !item.getImageAdr().equals("")) {
//Download image if not in cache
if(CacheCompass.getInstance(getContext()).getBitmapCache().get(item.getImageAdr())==null){
PicLoaderThread pcl =new PicLoaderThread(item.getImageAdr());
pcl.start();
try {
pcl.join();
image.setImageBitmap(pcl.getPicture());
CacheCompass.getInstance(getContext()).getBitmapCache().put(item.getImageAdr(), pcl.getPicture());
- } catch (InterruptedException e) {}
+ } catch (Exception e) {}
} else {
//If already in cache, get from cache
image.setImageBitmap(CacheCompass.getInstance(getContext()).getBitmapCache().get(item.getImageAdr()));
}
}
}
}
return v;
}
}
| true | true | public View getView(int position, View convertView, ViewGroup parent){
//Assign the view we are converting to a local variable
View v = convertView;
// first check to see if the view is null. if so, we have to inflate it.
// to inflate it basically means to render, or show, the view.
if(v == null){
LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = inflater.inflate(R.layout.news_feed_item, null);
}
NewsItem item = objects.get(position);
if (item != null){
TextView message = (TextView) v.findViewById(R.id.item_message);
TextView date = (TextView) v.findViewById(R.id.item_date);
ImageView image = (ImageView) v.findViewById(R.id.item_image);
if (message != null){
message.setText(item.getMessage());
}
if (date != null){
date.setText(item.getDate());
}
if (image != null){
//Remove current image
image.setImageBitmap(null);
//Check if post has image adress
if (item.getImageAdr()!=null && !item.getImageAdr().equals("")) {
//Download image if not in cache
if(CacheCompass.getInstance(getContext()).getBitmapCache().get(item.getImageAdr())==null){
PicLoaderThread pcl =new PicLoaderThread(item.getImageAdr());
pcl.start();
try {
pcl.join();
image.setImageBitmap(pcl.getPicture());
CacheCompass.getInstance(getContext()).getBitmapCache().put(item.getImageAdr(), pcl.getPicture());
} catch (InterruptedException e) {}
} else {
//If already in cache, get from cache
image.setImageBitmap(CacheCompass.getInstance(getContext()).getBitmapCache().get(item.getImageAdr()));
}
}
}
}
return v;
}
| public View getView(int position, View convertView, ViewGroup parent){
//Assign the view we are converting to a local variable
View v = convertView;
// first check to see if the view is null. if so, we have to inflate it.
// to inflate it basically means to render, or show, the view.
if(v == null){
LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = inflater.inflate(R.layout.news_feed_item, null);
}
NewsItem item = objects.get(position);
if (item != null){
TextView message = (TextView) v.findViewById(R.id.item_message);
TextView date = (TextView) v.findViewById(R.id.item_date);
ImageView image = (ImageView) v.findViewById(R.id.item_image);
if (message != null){
message.setText(item.getMessage());
}
if (date != null){
date.setText(item.getDate());
}
if (image != null){
//Remove current image
image.setImageBitmap(null);
//Check if post has image adress
if (item.getImageAdr()!=null && !item.getImageAdr().equals("")) {
//Download image if not in cache
if(CacheCompass.getInstance(getContext()).getBitmapCache().get(item.getImageAdr())==null){
PicLoaderThread pcl =new PicLoaderThread(item.getImageAdr());
pcl.start();
try {
pcl.join();
image.setImageBitmap(pcl.getPicture());
CacheCompass.getInstance(getContext()).getBitmapCache().put(item.getImageAdr(), pcl.getPicture());
} catch (Exception e) {}
} else {
//If already in cache, get from cache
image.setImageBitmap(CacheCompass.getInstance(getContext()).getBitmapCache().get(item.getImageAdr()));
}
}
}
}
return v;
}
|
diff --git a/server/src/edu/rpi/cct/webdav/servlet/common/GetMethod.java b/server/src/edu/rpi/cct/webdav/servlet/common/GetMethod.java
index 3af3b1d..5b683ba 100644
--- a/server/src/edu/rpi/cct/webdav/servlet/common/GetMethod.java
+++ b/server/src/edu/rpi/cct/webdav/servlet/common/GetMethod.java
@@ -1,322 +1,322 @@
/*
Copyright (c) 2000-2005 University of Washington. All rights reserved.
Redistribution and use of this distribution in source and binary forms,
with or without modification, are permitted provided that:
The above copyright notice and this permission notice appear in
all copies and supporting documentation;
The name, identifiers, and trademarks of the University of Washington
are not used in advertising or publicity without the express prior
written permission of the University of Washington;
Recipients acknowledge that this distribution is made available as a
research courtesy, "as is", potentially with defects, without
any obligation on the part of the University of Washington to
provide support, services, or repair;
THE UNIVERSITY OF WASHINGTON DISCLAIMS ALL WARRANTIES, EXPRESS OR
IMPLIED, WITH REGARD TO THIS SOFTWARE, INCLUDING WITHOUT LIMITATION
ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE, AND IN NO EVENT SHALL THE UNIVERSITY OF
WASHINGTON BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL
DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
PROFITS, WHETHER IN AN ACTION OF CONTRACT, TORT (INCLUDING
NEGLIGENCE) OR STRICT LIABILITY, ARISING OUT OF OR IN CONNECTION WITH
THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
/* **********************************************************************
Copyright 2005 Rensselaer Polytechnic Institute. All worldwide rights reserved.
Redistribution and use of this distribution in source and binary forms,
with or without modification, are permitted provided that:
The above copyright notice and this permission notice appear in all
copies and supporting documentation;
The name, identifiers, and trademarks of Rensselaer Polytechnic
Institute are not used in advertising or publicity without the
express prior written permission of Rensselaer Polytechnic Institute;
DISCLAIMER: The software is distributed" AS IS" without any express or
implied warranty, including but not limited to, any implied warranties
of merchantability or fitness for a particular purpose or any warrant)'
of non-infringement of any current or pending patent rights. The authors
of the software make no representations about the suitability of this
software for any particular purpose. The entire risk as to the quality
and performance of the software is with the user. Should the software
prove defective, the user assumes the cost of all necessary servicing,
repair or correction. In particular, neither Rensselaer Polytechnic
Institute, nor the authors of the software are liable for any indirect,
special, consequential, or incidental damages related to the software,
to the maximum extent the law permits.
*/
package edu.rpi.cct.webdav.servlet.common;
import edu.rpi.cct.webdav.servlet.shared.WebdavException;
import edu.rpi.cct.webdav.servlet.shared.WebdavNsIntf;
import edu.rpi.cct.webdav.servlet.shared.WebdavNsNode;
import java.io.CharArrayReader;
import java.io.Reader;
import java.io.Writer;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/** Class called to handle GET
*
* Get the content of a node. Note this is subclassed by HeadMethod which
* overrides init and sets doContent false.
*
* @author Mike Douglass [email protected]
*/
public class GetMethod extends MethodBase {
protected boolean doContent;
/** size of buffer used for copying content to response.
*/
private static final int bufferSize = 4096;
/* (non-Javadoc)
* @see edu.rpi.cct.webdav.servlet.common.MethodBase#init()
*/
public void init() {
doContent = true;
}
public void doMethod(HttpServletRequest req,
HttpServletResponse resp) throws WebdavException {
if (debug) {
trace("GetMethod: doMethod");
}
try {
if (getNsIntf().specialUri(req, resp, getResourceUri(req))) {
return;
}
//String reqContentType = req.getContentType();
//boolean reqHtml = "text/html".equals(reqContentType);
WebdavNsNode node = getNsIntf().getNode(getResourceUri(req),
WebdavNsIntf.existanceMust,
WebdavNsIntf.nodeTypeUnknown);
if ((node == null) || !node.getExists()) {
resp.setStatus(HttpServletResponse.SC_NOT_FOUND);
return;
}
String etag = Headers.ifNoneMatch(req);
if ((etag != null) && (!node.isCollection()) &&
(etag.equals(node.getEtagValue(true)))) {
- resp.setStatus(HttpServletResponse.SC_PRECONDITION_FAILED);
+ resp.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
return;
}
Writer out;
/** Get the content now to set up length, type etc.
*/
Reader in = null;
String contentType;
int contentLength;
if (node.isCollection()) {
if (getNsIntf().getDirectoryBrowsingDisallowed()) {
throw new WebdavException(HttpServletResponse.SC_FORBIDDEN);
}
String content = generateHtml(req, node);
in = new CharArrayReader(content.toCharArray());
contentType = "text/html";
contentLength = content.getBytes().length;
} else {
in = getNsIntf().getContent(node);
contentType = node.getContentType();
contentLength = node.getContentLen();
}
if (doContent) {
out = resp.getWriter();
} else {
out = null;
}
resp.setHeader("ETag", node.getEtagValue(true));
if (node.getLastmodDate() != null) {
resp.addHeader("Last-Modified", node.getLastmodDate().toString());
}
resp.setContentType(contentType);
resp.setContentLength(contentLength);
if (doContent) {
if (in == null) {
if (debug) {
debugMsg("status: " + HttpServletResponse.SC_NO_CONTENT);
}
resp.setStatus(HttpServletResponse.SC_NO_CONTENT);
} else {
if (debug) {
debugMsg("send content - length=" + node.getContentLen());
}
writeContent(in, out);
}
}
} catch (WebdavException we) {
throw we;
} catch (Throwable t) {
throw new WebdavException(t);
}
}
private void writeContent(Reader in, Writer out)
throws WebdavException {
try {
char[] buff = new char[bufferSize];
int len;
while (true) {
len = in.read(buff);
if (len < 0) {
break;
}
out.write(buff, 0, len);
}
} catch (Throwable t) {
throw new WebdavException(t);
} finally {
try {
in.close();
} catch (Throwable t) {}
try {
out.close();
} catch (Throwable t) {}
}
}
/** Return a String giving an HTML representation of the directory.
*
* TODO
*
* <p>Use some form of template to generate an internationalized form of the
* listing. We don't need a great deal to start with. It will also allow us to
* provide stylesheets, images etc. Probably place it in the resources directory.
*
* @param req
* @param node WebdavNsNode
* @return Reader
* @throws WebdavException
*/
protected String generateHtml(HttpServletRequest req,
WebdavNsNode node) throws WebdavException {
try {
Sbuff sb = new Sbuff();
sb.lines(new String[] {"<html>",
" <head>"});
/* Need some styles I guess */
sb.append(" <title>");
sb.append(node.getDisplayname());
sb.line("</title>");
sb.lines(new String[] {"</head>",
"<body>"});
sb.append(" <h1>");
sb.append(node.getDisplayname());
sb.line("</h1>");
sb.line(" <hr>");
sb.line(" <table width=\"100%\" +" +
"cellspacing=\"0\"" +
" cellpadding=\"4\"");
for (WebdavNsNode child: getNsIntf().getChildren(node)) {
/* icon would be nice */
sb.line("<tr>");
if (node.isCollection()) {
/* folder */
} else {
/* calendar? */
}
sb.line(" <td align=\"left\">");
sb.append("<a href=\"");
sb.append(req.getContextPath());
sb.append(child.getUri());
sb.append("\">");
sb.append(child.getDisplayname());
sb.line("</a>");
sb.line("</td>");
sb.line(" <td align=\"left\">");
String lastMod = child.getLastmodDate();
if (lastMod != null) {
sb.line(lastMod);
} else {
sb.line(" ");
}
sb.line("</td>");
sb.append("</tr>\r\n");
}
sb.line("</table>");
/* Could use a footer */
sb.line("</body>");
sb.line("</html>");
return sb.toString();
} catch (Throwable t) {
throw new WebdavException(t);
}
}
private static class Sbuff {
StringBuffer sb = new StringBuffer();
/**
* @param ss
*/
public void lines(String[] ss) {
for (int i = 0; i < ss.length; i++) {
line(ss[i]);
}
}
/**
* @param s
*/
public void line(String s) {
sb.append(s);
sb.append("\r\n");
}
/**
* @param s
*/
public void append(String s) {
sb.append(s);
}
public String toString() {
return sb.toString();
}
}
}
| true | true | public void doMethod(HttpServletRequest req,
HttpServletResponse resp) throws WebdavException {
if (debug) {
trace("GetMethod: doMethod");
}
try {
if (getNsIntf().specialUri(req, resp, getResourceUri(req))) {
return;
}
//String reqContentType = req.getContentType();
//boolean reqHtml = "text/html".equals(reqContentType);
WebdavNsNode node = getNsIntf().getNode(getResourceUri(req),
WebdavNsIntf.existanceMust,
WebdavNsIntf.nodeTypeUnknown);
if ((node == null) || !node.getExists()) {
resp.setStatus(HttpServletResponse.SC_NOT_FOUND);
return;
}
String etag = Headers.ifNoneMatch(req);
if ((etag != null) && (!node.isCollection()) &&
(etag.equals(node.getEtagValue(true)))) {
resp.setStatus(HttpServletResponse.SC_PRECONDITION_FAILED);
return;
}
Writer out;
/** Get the content now to set up length, type etc.
*/
Reader in = null;
String contentType;
int contentLength;
if (node.isCollection()) {
if (getNsIntf().getDirectoryBrowsingDisallowed()) {
throw new WebdavException(HttpServletResponse.SC_FORBIDDEN);
}
String content = generateHtml(req, node);
in = new CharArrayReader(content.toCharArray());
contentType = "text/html";
contentLength = content.getBytes().length;
} else {
in = getNsIntf().getContent(node);
contentType = node.getContentType();
contentLength = node.getContentLen();
}
if (doContent) {
out = resp.getWriter();
} else {
out = null;
}
resp.setHeader("ETag", node.getEtagValue(true));
if (node.getLastmodDate() != null) {
resp.addHeader("Last-Modified", node.getLastmodDate().toString());
}
resp.setContentType(contentType);
resp.setContentLength(contentLength);
if (doContent) {
if (in == null) {
if (debug) {
debugMsg("status: " + HttpServletResponse.SC_NO_CONTENT);
}
resp.setStatus(HttpServletResponse.SC_NO_CONTENT);
} else {
if (debug) {
debugMsg("send content - length=" + node.getContentLen());
}
writeContent(in, out);
}
}
} catch (WebdavException we) {
throw we;
} catch (Throwable t) {
throw new WebdavException(t);
}
}
| public void doMethod(HttpServletRequest req,
HttpServletResponse resp) throws WebdavException {
if (debug) {
trace("GetMethod: doMethod");
}
try {
if (getNsIntf().specialUri(req, resp, getResourceUri(req))) {
return;
}
//String reqContentType = req.getContentType();
//boolean reqHtml = "text/html".equals(reqContentType);
WebdavNsNode node = getNsIntf().getNode(getResourceUri(req),
WebdavNsIntf.existanceMust,
WebdavNsIntf.nodeTypeUnknown);
if ((node == null) || !node.getExists()) {
resp.setStatus(HttpServletResponse.SC_NOT_FOUND);
return;
}
String etag = Headers.ifNoneMatch(req);
if ((etag != null) && (!node.isCollection()) &&
(etag.equals(node.getEtagValue(true)))) {
resp.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
return;
}
Writer out;
/** Get the content now to set up length, type etc.
*/
Reader in = null;
String contentType;
int contentLength;
if (node.isCollection()) {
if (getNsIntf().getDirectoryBrowsingDisallowed()) {
throw new WebdavException(HttpServletResponse.SC_FORBIDDEN);
}
String content = generateHtml(req, node);
in = new CharArrayReader(content.toCharArray());
contentType = "text/html";
contentLength = content.getBytes().length;
} else {
in = getNsIntf().getContent(node);
contentType = node.getContentType();
contentLength = node.getContentLen();
}
if (doContent) {
out = resp.getWriter();
} else {
out = null;
}
resp.setHeader("ETag", node.getEtagValue(true));
if (node.getLastmodDate() != null) {
resp.addHeader("Last-Modified", node.getLastmodDate().toString());
}
resp.setContentType(contentType);
resp.setContentLength(contentLength);
if (doContent) {
if (in == null) {
if (debug) {
debugMsg("status: " + HttpServletResponse.SC_NO_CONTENT);
}
resp.setStatus(HttpServletResponse.SC_NO_CONTENT);
} else {
if (debug) {
debugMsg("send content - length=" + node.getContentLen());
}
writeContent(in, out);
}
}
} catch (WebdavException we) {
throw we;
} catch (Throwable t) {
throw new WebdavException(t);
}
}
|
diff --git a/src/org/pentaho/agilebi/modeler/util/MultiTableModelerSource.java b/src/org/pentaho/agilebi/modeler/util/MultiTableModelerSource.java
index c600646..dc3370b 100644
--- a/src/org/pentaho/agilebi/modeler/util/MultiTableModelerSource.java
+++ b/src/org/pentaho/agilebi/modeler/util/MultiTableModelerSource.java
@@ -1,195 +1,196 @@
/*
* This program is free software; you can redistribute it and/or modify it under the
* terms of the GNU Lesser General Public License, version 2.1 as published by the Free Software
* Foundation.
*
* You should have received a copy of the GNU Lesser General Public License along with this
* program; if not, you can obtain a copy at http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html
* or from the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Lesser General Public License for more details.
*
* Copyright (c) 2011 Pentaho Corporation.. All rights reserved.
*
* @author Ezequiel Cuellar
*/
package org.pentaho.agilebi.modeler.util;
import org.pentaho.agilebi.modeler.ModelerException;
import org.pentaho.agilebi.modeler.ModelerWorkspace;
import org.pentaho.di.core.database.DatabaseMeta;
import org.pentaho.metadata.automodel.SchemaTable;
import org.pentaho.metadata.model.*;
import org.pentaho.metadata.model.concept.types.LocalizedString;
import org.pentaho.metadata.model.concept.types.RelationshipType;
import org.pentaho.pms.core.exception.PentahoMetadataException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.List;
public class MultiTableModelerSource implements ISpoonModelerSource {
private ModelGenerator generator;
private DatabaseMeta databaseMeta;
private List<LogicalRelationship> joinTemplates;
private String datasourceName;
public static final String SOURCE_TYPE = MultiTableModelerSource.class.getSimpleName();
private static Logger logger = LoggerFactory.getLogger(MultiTableModelerSource.class);
public MultiTableModelerSource(DatabaseMeta databaseMeta, List<LogicalRelationship> joinTemplates, String datasourceName) {
this.datasourceName = datasourceName;
this.databaseMeta = databaseMeta;
this.joinTemplates = joinTemplates;
this.generator = new ModelGenerator();
}
@Override
public Domain generateDomain() throws ModelerException {
return this.generateDomain(this.databaseMeta, this.joinTemplates);
}
@Override
public Domain generateDomain(boolean dualModelingMode) throws ModelerException {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
@Override
public String getDatabaseName() {
String name = null;
if (this.databaseMeta != null) {
name = this.databaseMeta.getDatabaseName();
}
return name;
}
@Override
public void initialize(Domain domain) throws ModelerException {
}
@Override
public void serializeIntoDomain(Domain d) {
LogicalModel lm = d.getLogicalModels().get(0);
lm.setProperty("source_type", SOURCE_TYPE);
}
@Override
public String getSchemaName() {
return null;
}
@Override
public String getTableName() {
return null;
}
@Override
public DatabaseMeta getDatabaseMeta() {
return this.databaseMeta;
}
public Domain generateDomain(DatabaseMeta databaseMeta, List<LogicalRelationship> joinTemplates) {
Domain domain = null;
try {
// Generate domain based on the table names.
String locale = LocalizedString.DEFAULT_LOCALE;
this.generator.setLocale(locale);
this.generator.setDatabaseMeta(databaseMeta);
this.generator.setModelName(datasourceName);
List<SchemaTable> schemas = new ArrayList<SchemaTable>();
for (LogicalRelationship joinTemplate : joinTemplates) {
schemas.add(new SchemaTable("", joinTemplate.getFromTable().getName(locale)));
schemas.add(new SchemaTable("", joinTemplate.getToTable().getName(locale)));
}
SchemaTable tableNames[] = new SchemaTable[schemas.size()];
tableNames = schemas.toArray(tableNames);
this.generator.setTableNames(tableNames);
domain = this.generator.generateDomain();
domain.setId(datasourceName);
// Automodel to create categories
ModelerWorkspaceHelper helper = new ModelerWorkspaceHelper(locale);
ModelerWorkspace workspace = new ModelerWorkspace(helper);
workspace.setModelName(datasourceName);
workspace.setDomain(domain);
// Create and add LogicalRelationships to the LogicalModel from the
// domain.
LogicalModel logicalModel = domain.getLogicalModels().get(0);
// TODO do this with messages
logicalModel.setName(new LocalizedString(locale, datasourceName));
logicalModel.setDescription(new LocalizedString(locale, "This is the data model for "
+ datasourceName));
LogicalTable businessTable = logicalModel.getLogicalTables().get(0);
businessTable.setName(new LocalizedString(locale, datasourceName));
for (LogicalRelationship joinTemplate : joinTemplates) {
String lTable = joinTemplate.getFromTable().getName(locale);
String rTable = joinTemplate.getToTable().getName(locale);
LogicalTable fromTable = null;
LogicalColumn fromColumn = null;
LogicalTable toTable = null;
LogicalColumn toColumn = null;
for (LogicalTable logicalTable : logicalModel.getLogicalTables()) {
if (logicalTable.getName(locale).equals(lTable)) {
fromTable = logicalTable;
for (LogicalColumn logicalColumn : fromTable.getLogicalColumns()) {
if (logicalColumn.getName(locale).equals(joinTemplate.getFromColumn().getName(locale))) {
fromColumn = logicalColumn;
}
}
}
if (logicalTable.getName(locale).equals(rTable)) {
toTable = logicalTable;
for (LogicalColumn logicalColumn : toTable.getLogicalColumns()) {
if (logicalColumn.getName(locale).equals(joinTemplate.getToColumn().getName(locale))) {
toColumn = logicalColumn;
}
}
}
}
LogicalRelationship logicalRelationship = new LogicalRelationship();
// TODO is this INNER JOIN?
logicalRelationship.setRelationshipType(RelationshipType._1_1);
logicalRelationship.setFromTable(fromTable);
logicalRelationship.setFromColumn(fromColumn);
logicalRelationship.setToTable(toTable);
logicalRelationship.setToColumn(toColumn);
logicalModel.addLogicalRelationship(logicalRelationship);
}
helper.autoModelMultiTableRelational(workspace);
+ workspace.setModelName(datasourceName);
helper.populateDomain(workspace);
} catch (PentahoMetadataException e) {
e.printStackTrace();
logger.info(e.getLocalizedMessage());
} catch (ModelerException e) {
e.printStackTrace();
logger.info(e.getLocalizedMessage());
} catch (Exception e) {
e.printStackTrace();
logger.info(e.getLocalizedMessage());
}
return domain;
}
}
| true | true | public Domain generateDomain(DatabaseMeta databaseMeta, List<LogicalRelationship> joinTemplates) {
Domain domain = null;
try {
// Generate domain based on the table names.
String locale = LocalizedString.DEFAULT_LOCALE;
this.generator.setLocale(locale);
this.generator.setDatabaseMeta(databaseMeta);
this.generator.setModelName(datasourceName);
List<SchemaTable> schemas = new ArrayList<SchemaTable>();
for (LogicalRelationship joinTemplate : joinTemplates) {
schemas.add(new SchemaTable("", joinTemplate.getFromTable().getName(locale)));
schemas.add(new SchemaTable("", joinTemplate.getToTable().getName(locale)));
}
SchemaTable tableNames[] = new SchemaTable[schemas.size()];
tableNames = schemas.toArray(tableNames);
this.generator.setTableNames(tableNames);
domain = this.generator.generateDomain();
domain.setId(datasourceName);
// Automodel to create categories
ModelerWorkspaceHelper helper = new ModelerWorkspaceHelper(locale);
ModelerWorkspace workspace = new ModelerWorkspace(helper);
workspace.setModelName(datasourceName);
workspace.setDomain(domain);
// Create and add LogicalRelationships to the LogicalModel from the
// domain.
LogicalModel logicalModel = domain.getLogicalModels().get(0);
// TODO do this with messages
logicalModel.setName(new LocalizedString(locale, datasourceName));
logicalModel.setDescription(new LocalizedString(locale, "This is the data model for "
+ datasourceName));
LogicalTable businessTable = logicalModel.getLogicalTables().get(0);
businessTable.setName(new LocalizedString(locale, datasourceName));
for (LogicalRelationship joinTemplate : joinTemplates) {
String lTable = joinTemplate.getFromTable().getName(locale);
String rTable = joinTemplate.getToTable().getName(locale);
LogicalTable fromTable = null;
LogicalColumn fromColumn = null;
LogicalTable toTable = null;
LogicalColumn toColumn = null;
for (LogicalTable logicalTable : logicalModel.getLogicalTables()) {
if (logicalTable.getName(locale).equals(lTable)) {
fromTable = logicalTable;
for (LogicalColumn logicalColumn : fromTable.getLogicalColumns()) {
if (logicalColumn.getName(locale).equals(joinTemplate.getFromColumn().getName(locale))) {
fromColumn = logicalColumn;
}
}
}
if (logicalTable.getName(locale).equals(rTable)) {
toTable = logicalTable;
for (LogicalColumn logicalColumn : toTable.getLogicalColumns()) {
if (logicalColumn.getName(locale).equals(joinTemplate.getToColumn().getName(locale))) {
toColumn = logicalColumn;
}
}
}
}
LogicalRelationship logicalRelationship = new LogicalRelationship();
// TODO is this INNER JOIN?
logicalRelationship.setRelationshipType(RelationshipType._1_1);
logicalRelationship.setFromTable(fromTable);
logicalRelationship.setFromColumn(fromColumn);
logicalRelationship.setToTable(toTable);
logicalRelationship.setToColumn(toColumn);
logicalModel.addLogicalRelationship(logicalRelationship);
}
helper.autoModelMultiTableRelational(workspace);
helper.populateDomain(workspace);
} catch (PentahoMetadataException e) {
e.printStackTrace();
logger.info(e.getLocalizedMessage());
} catch (ModelerException e) {
e.printStackTrace();
logger.info(e.getLocalizedMessage());
} catch (Exception e) {
e.printStackTrace();
logger.info(e.getLocalizedMessage());
}
return domain;
}
| public Domain generateDomain(DatabaseMeta databaseMeta, List<LogicalRelationship> joinTemplates) {
Domain domain = null;
try {
// Generate domain based on the table names.
String locale = LocalizedString.DEFAULT_LOCALE;
this.generator.setLocale(locale);
this.generator.setDatabaseMeta(databaseMeta);
this.generator.setModelName(datasourceName);
List<SchemaTable> schemas = new ArrayList<SchemaTable>();
for (LogicalRelationship joinTemplate : joinTemplates) {
schemas.add(new SchemaTable("", joinTemplate.getFromTable().getName(locale)));
schemas.add(new SchemaTable("", joinTemplate.getToTable().getName(locale)));
}
SchemaTable tableNames[] = new SchemaTable[schemas.size()];
tableNames = schemas.toArray(tableNames);
this.generator.setTableNames(tableNames);
domain = this.generator.generateDomain();
domain.setId(datasourceName);
// Automodel to create categories
ModelerWorkspaceHelper helper = new ModelerWorkspaceHelper(locale);
ModelerWorkspace workspace = new ModelerWorkspace(helper);
workspace.setModelName(datasourceName);
workspace.setDomain(domain);
// Create and add LogicalRelationships to the LogicalModel from the
// domain.
LogicalModel logicalModel = domain.getLogicalModels().get(0);
// TODO do this with messages
logicalModel.setName(new LocalizedString(locale, datasourceName));
logicalModel.setDescription(new LocalizedString(locale, "This is the data model for "
+ datasourceName));
LogicalTable businessTable = logicalModel.getLogicalTables().get(0);
businessTable.setName(new LocalizedString(locale, datasourceName));
for (LogicalRelationship joinTemplate : joinTemplates) {
String lTable = joinTemplate.getFromTable().getName(locale);
String rTable = joinTemplate.getToTable().getName(locale);
LogicalTable fromTable = null;
LogicalColumn fromColumn = null;
LogicalTable toTable = null;
LogicalColumn toColumn = null;
for (LogicalTable logicalTable : logicalModel.getLogicalTables()) {
if (logicalTable.getName(locale).equals(lTable)) {
fromTable = logicalTable;
for (LogicalColumn logicalColumn : fromTable.getLogicalColumns()) {
if (logicalColumn.getName(locale).equals(joinTemplate.getFromColumn().getName(locale))) {
fromColumn = logicalColumn;
}
}
}
if (logicalTable.getName(locale).equals(rTable)) {
toTable = logicalTable;
for (LogicalColumn logicalColumn : toTable.getLogicalColumns()) {
if (logicalColumn.getName(locale).equals(joinTemplate.getToColumn().getName(locale))) {
toColumn = logicalColumn;
}
}
}
}
LogicalRelationship logicalRelationship = new LogicalRelationship();
// TODO is this INNER JOIN?
logicalRelationship.setRelationshipType(RelationshipType._1_1);
logicalRelationship.setFromTable(fromTable);
logicalRelationship.setFromColumn(fromColumn);
logicalRelationship.setToTable(toTable);
logicalRelationship.setToColumn(toColumn);
logicalModel.addLogicalRelationship(logicalRelationship);
}
helper.autoModelMultiTableRelational(workspace);
workspace.setModelName(datasourceName);
helper.populateDomain(workspace);
} catch (PentahoMetadataException e) {
e.printStackTrace();
logger.info(e.getLocalizedMessage());
} catch (ModelerException e) {
e.printStackTrace();
logger.info(e.getLocalizedMessage());
} catch (Exception e) {
e.printStackTrace();
logger.info(e.getLocalizedMessage());
}
return domain;
}
|
diff --git a/hazelcast/src/main/java/com/hazelcast/partition/PartitionRuntimeState.java b/hazelcast/src/main/java/com/hazelcast/partition/PartitionRuntimeState.java
index afef84c583..137ff2f6d7 100644
--- a/hazelcast/src/main/java/com/hazelcast/partition/PartitionRuntimeState.java
+++ b/hazelcast/src/main/java/com/hazelcast/partition/PartitionRuntimeState.java
@@ -1,243 +1,243 @@
/*
* Copyright (c) 2008-2013, Hazelcast, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hazelcast.partition;
import com.hazelcast.cluster.MemberInfo;
import com.hazelcast.logging.ILogger;
import com.hazelcast.nio.Address;
import com.hazelcast.nio.ObjectDataInput;
import com.hazelcast.nio.ObjectDataOutput;
import com.hazelcast.nio.serialization.DataSerializable;
import com.hazelcast.util.Clock;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
public class PartitionRuntimeState implements DataSerializable {
protected final ArrayList<MemberInfo> members = new ArrayList<MemberInfo>(100);
private final Collection<ShortPartitionInfo> partitionInfos = new LinkedList<ShortPartitionInfo>();
private ILogger logger;
private long masterTime = Clock.currentTimeMillis();
private int version;
private Collection<MigrationInfo> completedMigrations;
private Address endpoint;
public PartitionRuntimeState() {
}
public PartitionRuntimeState(ILogger logger,
Collection<MemberInfo> memberInfos,
InternalPartition[] partitions,
Collection<MigrationInfo> migrationInfos,
long masterTime, int version) {
this.logger = logger;
this.masterTime = masterTime;
this.version = version;
final Map<Address, Integer> addressIndexes = new HashMap<Address, Integer>(memberInfos.size());
int memberIndex = 0;
for (MemberInfo memberInfo : memberInfos) {
addMemberInfo(memberInfo, addressIndexes, memberIndex);
memberIndex++;
}
setPartitions(partitions, addressIndexes);
completedMigrations = migrationInfos != null ? migrationInfos : new ArrayList<MigrationInfo>(0);
}
protected void addMemberInfo(MemberInfo memberInfo, Map<Address, Integer> addressIndexes, int memberIndex) {
members.add(memberIndex, memberInfo);
addressIndexes.put(memberInfo.getAddress(), memberIndex);
}
protected void setPartitions(InternalPartition[] partitions, Map<Address, Integer> addressIndexes) {
List<String> unmatchAddresses = new LinkedList<String>();
for (InternalPartition partition : partitions) {
ShortPartitionInfo partitionInfo = new ShortPartitionInfo(partition.getPartitionId());
for (int index = 0; index < InternalPartition.MAX_REPLICA_COUNT; index++) {
Address address = partition.getReplicaAddress(index);
if (address == null) {
partitionInfo.addressIndexes[index] = -1;
} else {
Integer knownIndex = addressIndexes.get(address);
if (knownIndex == null && index == 0) {
unmatchAddresses.add(address + ":" + partition);
}
if (knownIndex == null) {
partitionInfo.addressIndexes[index] = -1;
} else {
partitionInfo.addressIndexes[index] = knownIndex;
}
}
}
partitionInfos.add(partitionInfo);
}
if (!unmatchAddresses.isEmpty()) {
//it can happen that the master address at any given moment is not known. Perhaps because
//of migration, perhaps because the system has not yet been initialized.
- logger.warning("Unknown owner addresses in partition state! " +
- unmatchAddresses);
+ logger.warning("Unknown owner addresses in partition state! "
+ + unmatchAddresses);
}
}
public PartitionInfo[] getPartitions() {
int size = partitionInfos.size();
PartitionInfo[] result = new PartitionInfo[size];
for (ShortPartitionInfo partitionInfo : partitionInfos) {
Address[] replicas = new Address[InternalPartition.MAX_REPLICA_COUNT];
int partitionId = partitionInfo.partitionId;
result[partitionId] = new PartitionInfo(partitionId, replicas);
int[] addressIndexes = partitionInfo.addressIndexes;
for (int c = 0; c < addressIndexes.length; c++) {
int index = addressIndexes[c];
if (index != -1) {
replicas[c] = members.get(index).getAddress();
}
}
}
return result;
}
public List<MemberInfo> getMembers() {
return members;
}
public long getMasterTime() {
return masterTime;
}
public Address getEndpoint() {
return endpoint;
}
public void setEndpoint(final Address endpoint) {
this.endpoint = endpoint;
}
public Collection<MigrationInfo> getCompletedMigrations() {
return completedMigrations != null ? completedMigrations : Collections.<MigrationInfo>emptyList();
}
@Override
public void readData(ObjectDataInput in) throws IOException {
masterTime = in.readLong();
version = in.readInt();
int size = in.readInt();
final Map<Address, Integer> addressIndexes = new HashMap<Address, Integer>(size);
int memberIndex = 0;
while (size-- > 0) {
MemberInfo memberInfo = new MemberInfo();
memberInfo.readData(in);
addMemberInfo(memberInfo, addressIndexes, memberIndex);
memberIndex++;
}
int partitionCount = in.readInt();
for (int i = 0; i < partitionCount; i++) {
ShortPartitionInfo spi = new ShortPartitionInfo();
spi.readData(in);
partitionInfos.add(spi);
}
int k = in.readInt();
if (k > 0) {
completedMigrations = new ArrayList<MigrationInfo>(k);
for (int i = 0; i < k; i++) {
MigrationInfo cm = new MigrationInfo();
cm.readData(in);
completedMigrations.add(cm);
}
}
}
@Override
public void writeData(ObjectDataOutput out) throws IOException {
out.writeLong(masterTime);
out.writeInt(version);
int memberSize = members.size();
out.writeInt(memberSize);
for (MemberInfo memberInfo : members) {
memberInfo.writeData(out);
}
out.writeInt(partitionInfos.size());
for (ShortPartitionInfo spi : partitionInfos) {
spi.writeData(out);
}
if (completedMigrations != null) {
int k = completedMigrations.size();
out.writeInt(k);
for (MigrationInfo cm : completedMigrations) {
cm.writeData(out);
}
} else {
out.writeInt(0);
}
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder("PartitionRuntimeState [" + version + "]{\n");
for (MemberInfo address : members) {
sb.append(address).append('\n');
}
sb.append(", completedMigrations=").append(completedMigrations);
sb.append('}');
return sb.toString();
}
public int getVersion() {
return version;
}
private static class ShortPartitionInfo implements DataSerializable {
int partitionId;
final int[] addressIndexes = new int[InternalPartition.MAX_REPLICA_COUNT];
ShortPartitionInfo(int partitionId) {
this.partitionId = partitionId;
}
ShortPartitionInfo() {
}
@Override
public void writeData(ObjectDataOutput out) throws IOException {
out.writeInt(partitionId);
for (int i = 0; i < InternalPartition.MAX_REPLICA_COUNT; i++) {
out.writeInt(addressIndexes[i]);
}
}
@Override
public void readData(ObjectDataInput in) throws IOException {
partitionId = in.readInt();
for (int i = 0; i < InternalPartition.MAX_REPLICA_COUNT; i++) {
addressIndexes[i] = in.readInt();
}
}
}
}
| true | true | protected void setPartitions(InternalPartition[] partitions, Map<Address, Integer> addressIndexes) {
List<String> unmatchAddresses = new LinkedList<String>();
for (InternalPartition partition : partitions) {
ShortPartitionInfo partitionInfo = new ShortPartitionInfo(partition.getPartitionId());
for (int index = 0; index < InternalPartition.MAX_REPLICA_COUNT; index++) {
Address address = partition.getReplicaAddress(index);
if (address == null) {
partitionInfo.addressIndexes[index] = -1;
} else {
Integer knownIndex = addressIndexes.get(address);
if (knownIndex == null && index == 0) {
unmatchAddresses.add(address + ":" + partition);
}
if (knownIndex == null) {
partitionInfo.addressIndexes[index] = -1;
} else {
partitionInfo.addressIndexes[index] = knownIndex;
}
}
}
partitionInfos.add(partitionInfo);
}
if (!unmatchAddresses.isEmpty()) {
//it can happen that the master address at any given moment is not known. Perhaps because
//of migration, perhaps because the system has not yet been initialized.
logger.warning("Unknown owner addresses in partition state! " +
unmatchAddresses);
}
}
| protected void setPartitions(InternalPartition[] partitions, Map<Address, Integer> addressIndexes) {
List<String> unmatchAddresses = new LinkedList<String>();
for (InternalPartition partition : partitions) {
ShortPartitionInfo partitionInfo = new ShortPartitionInfo(partition.getPartitionId());
for (int index = 0; index < InternalPartition.MAX_REPLICA_COUNT; index++) {
Address address = partition.getReplicaAddress(index);
if (address == null) {
partitionInfo.addressIndexes[index] = -1;
} else {
Integer knownIndex = addressIndexes.get(address);
if (knownIndex == null && index == 0) {
unmatchAddresses.add(address + ":" + partition);
}
if (knownIndex == null) {
partitionInfo.addressIndexes[index] = -1;
} else {
partitionInfo.addressIndexes[index] = knownIndex;
}
}
}
partitionInfos.add(partitionInfo);
}
if (!unmatchAddresses.isEmpty()) {
//it can happen that the master address at any given moment is not known. Perhaps because
//of migration, perhaps because the system has not yet been initialized.
logger.warning("Unknown owner addresses in partition state! "
+ unmatchAddresses);
}
}
|
diff --git a/src/main/java/com/jetdrone/vertx/yoke/middleware/BodyParser.java b/src/main/java/com/jetdrone/vertx/yoke/middleware/BodyParser.java
index 1fc8b4f5..2945a807 100644
--- a/src/main/java/com/jetdrone/vertx/yoke/middleware/BodyParser.java
+++ b/src/main/java/com/jetdrone/vertx/yoke/middleware/BodyParser.java
@@ -1,145 +1,145 @@
package com.jetdrone.vertx.yoke.middleware;
import com.jetdrone.vertx.yoke.Middleware;
import io.netty.handler.codec.http.DefaultHttpContent;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.LastHttpContent;
import io.netty.handler.codec.http.QueryStringDecoder;
import io.netty.handler.codec.http.multipart.*;
import io.netty.handler.codec.http.multipart.HttpPostRequestDecoder.*;
import org.vertx.java.core.Handler;
import org.vertx.java.core.buffer.Buffer;
import org.vertx.java.core.json.DecodeException;
import org.vertx.java.core.json.JsonArray;
import org.vertx.java.core.json.JsonObject;
import java.io.IOException;
import java.util.*;
public class BodyParser extends Middleware {
private final HttpDataFactory factory = new DefaultHttpDataFactory(DefaultHttpDataFactory.MINSIZE);
@Override
public void handle(final YokeHttpServerRequest request, final Handler<Object> next) {
final String method = request.method();
// GET and HEAD have no body
if ("GET".equals(method) || "HEAD".equals(method)) {
next.handle(null);
} else {
final String contentType = request.headers().get("content-type");
if (contentType != null) {
final Buffer buffer = new Buffer(0);
request.dataHandler(new Handler<Buffer>() {
@Override
public void handle(Buffer event) {
if (request.bodyLengthLimit() != -1) {
if (buffer.length() < request.bodyLengthLimit()) {
buffer.appendBuffer(event);
} else {
request.dataHandler(null);
request.endHandler(null);
next.handle(413);
}
} else {
buffer.appendBuffer(event);
}
}
});
request.endHandler(new Handler<Void>() {
@Override
public void handle(Void _void) {
if (contentType.contains("application/json")) {
try {
String jsonString = buffer.toString("UTF-8");
if (jsonString.length() > 0) {
switch (jsonString.charAt(0)) {
case '{':
request.body(new JsonObject(jsonString));
next.handle(null);
break;
case '[':
request.body(new JsonArray(jsonString));
next.handle(null);
break;
default:
next.handle(400);
}
} else {
next.handle(400);
}
} catch (DecodeException ex) {
next.handle(ex);
}
} else if (contentType.contains("application/x-www-form-urlencoded")) {
QueryStringDecoder queryStringDecoder = new QueryStringDecoder(buffer.toString("UTF-8"));
request.body(queryStringDecoder.parameters());
next.handle(null);
} else if (contentType.contains("multipart/form-data")) {
HttpPostRequestDecoder decoder = null;
try {
HttpRequest nettyReq = request.nettyRequest();
decoder = new HttpPostRequestDecoder(factory, nettyReq);
decoder.offer(new DefaultHttpContent(buffer.getByteBuf()));
decoder.offer(LastHttpContent.EMPTY_LAST_CONTENT);
for (InterfaceHttpData data : decoder.getBodyHttpDatas()) {
switch (data.getHttpDataType()) {
case Attribute:
if (request.body() == null) {
request.body(new HashMap<String, Object>());
}
final Attribute attribute = (Attribute) data;
final Map<String, Object> mapBody = request.mapBody();
Object value = mapBody.get(attribute.getName());
if (value == null) {
mapBody.put(attribute.getName(), attribute.getValue());
} else {
if (value instanceof List) {
- ((List<?>) value).add(attribute.getValue());
+ ((List<String>) value).add(attribute.getValue());
} else {
List<String> l = new ArrayList<>();
l.add((String) value);
l.add(attribute.getValue());
mapBody.put(attribute.getName(), l);
}
}
break;
case FileUpload:
if (request.files() == null) {
request.files(new HashMap<String, FileUpload>());
}
FileUpload fileUpload = (FileUpload) data;
request.files().put(fileUpload.getName(), fileUpload);
break;
default:
System.err.println(data);
}
}
next.handle(null);
// clean up
decoder.cleanFiles();
} catch (ErrorDataDecoderException | NotEnoughDataDecoderException | IncompatibleDataDecoderException | IOException e) {
// clean up
if (decoder != null) {
decoder.cleanFiles();
}
next.handle(e);
}
} else {
next.handle(null);
}
}
});
}
}
}
}
| true | true | public void handle(final YokeHttpServerRequest request, final Handler<Object> next) {
final String method = request.method();
// GET and HEAD have no body
if ("GET".equals(method) || "HEAD".equals(method)) {
next.handle(null);
} else {
final String contentType = request.headers().get("content-type");
if (contentType != null) {
final Buffer buffer = new Buffer(0);
request.dataHandler(new Handler<Buffer>() {
@Override
public void handle(Buffer event) {
if (request.bodyLengthLimit() != -1) {
if (buffer.length() < request.bodyLengthLimit()) {
buffer.appendBuffer(event);
} else {
request.dataHandler(null);
request.endHandler(null);
next.handle(413);
}
} else {
buffer.appendBuffer(event);
}
}
});
request.endHandler(new Handler<Void>() {
@Override
public void handle(Void _void) {
if (contentType.contains("application/json")) {
try {
String jsonString = buffer.toString("UTF-8");
if (jsonString.length() > 0) {
switch (jsonString.charAt(0)) {
case '{':
request.body(new JsonObject(jsonString));
next.handle(null);
break;
case '[':
request.body(new JsonArray(jsonString));
next.handle(null);
break;
default:
next.handle(400);
}
} else {
next.handle(400);
}
} catch (DecodeException ex) {
next.handle(ex);
}
} else if (contentType.contains("application/x-www-form-urlencoded")) {
QueryStringDecoder queryStringDecoder = new QueryStringDecoder(buffer.toString("UTF-8"));
request.body(queryStringDecoder.parameters());
next.handle(null);
} else if (contentType.contains("multipart/form-data")) {
HttpPostRequestDecoder decoder = null;
try {
HttpRequest nettyReq = request.nettyRequest();
decoder = new HttpPostRequestDecoder(factory, nettyReq);
decoder.offer(new DefaultHttpContent(buffer.getByteBuf()));
decoder.offer(LastHttpContent.EMPTY_LAST_CONTENT);
for (InterfaceHttpData data : decoder.getBodyHttpDatas()) {
switch (data.getHttpDataType()) {
case Attribute:
if (request.body() == null) {
request.body(new HashMap<String, Object>());
}
final Attribute attribute = (Attribute) data;
final Map<String, Object> mapBody = request.mapBody();
Object value = mapBody.get(attribute.getName());
if (value == null) {
mapBody.put(attribute.getName(), attribute.getValue());
} else {
if (value instanceof List) {
((List<?>) value).add(attribute.getValue());
} else {
List<String> l = new ArrayList<>();
l.add((String) value);
l.add(attribute.getValue());
mapBody.put(attribute.getName(), l);
}
}
break;
case FileUpload:
if (request.files() == null) {
request.files(new HashMap<String, FileUpload>());
}
FileUpload fileUpload = (FileUpload) data;
request.files().put(fileUpload.getName(), fileUpload);
break;
default:
System.err.println(data);
}
}
next.handle(null);
// clean up
decoder.cleanFiles();
} catch (ErrorDataDecoderException | NotEnoughDataDecoderException | IncompatibleDataDecoderException | IOException e) {
// clean up
if (decoder != null) {
decoder.cleanFiles();
}
next.handle(e);
}
} else {
next.handle(null);
}
}
});
}
}
}
| public void handle(final YokeHttpServerRequest request, final Handler<Object> next) {
final String method = request.method();
// GET and HEAD have no body
if ("GET".equals(method) || "HEAD".equals(method)) {
next.handle(null);
} else {
final String contentType = request.headers().get("content-type");
if (contentType != null) {
final Buffer buffer = new Buffer(0);
request.dataHandler(new Handler<Buffer>() {
@Override
public void handle(Buffer event) {
if (request.bodyLengthLimit() != -1) {
if (buffer.length() < request.bodyLengthLimit()) {
buffer.appendBuffer(event);
} else {
request.dataHandler(null);
request.endHandler(null);
next.handle(413);
}
} else {
buffer.appendBuffer(event);
}
}
});
request.endHandler(new Handler<Void>() {
@Override
public void handle(Void _void) {
if (contentType.contains("application/json")) {
try {
String jsonString = buffer.toString("UTF-8");
if (jsonString.length() > 0) {
switch (jsonString.charAt(0)) {
case '{':
request.body(new JsonObject(jsonString));
next.handle(null);
break;
case '[':
request.body(new JsonArray(jsonString));
next.handle(null);
break;
default:
next.handle(400);
}
} else {
next.handle(400);
}
} catch (DecodeException ex) {
next.handle(ex);
}
} else if (contentType.contains("application/x-www-form-urlencoded")) {
QueryStringDecoder queryStringDecoder = new QueryStringDecoder(buffer.toString("UTF-8"));
request.body(queryStringDecoder.parameters());
next.handle(null);
} else if (contentType.contains("multipart/form-data")) {
HttpPostRequestDecoder decoder = null;
try {
HttpRequest nettyReq = request.nettyRequest();
decoder = new HttpPostRequestDecoder(factory, nettyReq);
decoder.offer(new DefaultHttpContent(buffer.getByteBuf()));
decoder.offer(LastHttpContent.EMPTY_LAST_CONTENT);
for (InterfaceHttpData data : decoder.getBodyHttpDatas()) {
switch (data.getHttpDataType()) {
case Attribute:
if (request.body() == null) {
request.body(new HashMap<String, Object>());
}
final Attribute attribute = (Attribute) data;
final Map<String, Object> mapBody = request.mapBody();
Object value = mapBody.get(attribute.getName());
if (value == null) {
mapBody.put(attribute.getName(), attribute.getValue());
} else {
if (value instanceof List) {
((List<String>) value).add(attribute.getValue());
} else {
List<String> l = new ArrayList<>();
l.add((String) value);
l.add(attribute.getValue());
mapBody.put(attribute.getName(), l);
}
}
break;
case FileUpload:
if (request.files() == null) {
request.files(new HashMap<String, FileUpload>());
}
FileUpload fileUpload = (FileUpload) data;
request.files().put(fileUpload.getName(), fileUpload);
break;
default:
System.err.println(data);
}
}
next.handle(null);
// clean up
decoder.cleanFiles();
} catch (ErrorDataDecoderException | NotEnoughDataDecoderException | IncompatibleDataDecoderException | IOException e) {
// clean up
if (decoder != null) {
decoder.cleanFiles();
}
next.handle(e);
}
} else {
next.handle(null);
}
}
});
}
}
}
|
diff --git a/test/cs3246/a2/test/SobelOperatorTest.java b/test/cs3246/a2/test/SobelOperatorTest.java
index 9ce2936..cec0d41 100644
--- a/test/cs3246/a2/test/SobelOperatorTest.java
+++ b/test/cs3246/a2/test/SobelOperatorTest.java
@@ -1,33 +1,36 @@
package cs3246.a2.test;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
import cs3246.a2.SobelOperator;
public class SobelOperatorTest {
public static void main(String[] args) {
try {
BufferedImage image = ImageIO.read(new File("image/test.jpg"));
SobelOperator sobel = new SobelOperator(image);
sobel.compute();
sobel.normalizeGradient();
double[][] gradient = sobel.getGradient();
int x = sobel.getSizeX();
int y = sobel.getSizeY();
BufferedImage imageConverted = new BufferedImage(x, y, BufferedImage.TYPE_BYTE_GRAY);
for (int i=0; i<x; i++) {
for (int j=0; j<y; j++) {
- imageConverted.setRGB(i, j, (int) (gradient[i][j] * 255));
+ int argb = 0;
+ int grey = (int) (gradient[i][j] * 255);
+ argb = (grey << 16) | (grey << 8) | grey;
+ imageConverted.setRGB(i, j, argb);
}
}
ImageIO.write(imageConverted, "bmp", new File("image/edge.bmp"));
} catch (Exception e) {
e.printStackTrace();
}
}
}
| true | true | public static void main(String[] args) {
try {
BufferedImage image = ImageIO.read(new File("image/test.jpg"));
SobelOperator sobel = new SobelOperator(image);
sobel.compute();
sobel.normalizeGradient();
double[][] gradient = sobel.getGradient();
int x = sobel.getSizeX();
int y = sobel.getSizeY();
BufferedImage imageConverted = new BufferedImage(x, y, BufferedImage.TYPE_BYTE_GRAY);
for (int i=0; i<x; i++) {
for (int j=0; j<y; j++) {
imageConverted.setRGB(i, j, (int) (gradient[i][j] * 255));
}
}
ImageIO.write(imageConverted, "bmp", new File("image/edge.bmp"));
} catch (Exception e) {
e.printStackTrace();
}
}
| public static void main(String[] args) {
try {
BufferedImage image = ImageIO.read(new File("image/test.jpg"));
SobelOperator sobel = new SobelOperator(image);
sobel.compute();
sobel.normalizeGradient();
double[][] gradient = sobel.getGradient();
int x = sobel.getSizeX();
int y = sobel.getSizeY();
BufferedImage imageConverted = new BufferedImage(x, y, BufferedImage.TYPE_BYTE_GRAY);
for (int i=0; i<x; i++) {
for (int j=0; j<y; j++) {
int argb = 0;
int grey = (int) (gradient[i][j] * 255);
argb = (grey << 16) | (grey << 8) | grey;
imageConverted.setRGB(i, j, argb);
}
}
ImageIO.write(imageConverted, "bmp", new File("image/edge.bmp"));
} catch (Exception e) {
e.printStackTrace();
}
}
|
diff --git a/NeverBreak/src/com/github/thebiologist13/FarmListener.java b/NeverBreak/src/com/github/thebiologist13/FarmListener.java
index ac3ccdd..44da1e6 100644
--- a/NeverBreak/src/com/github/thebiologist13/FarmListener.java
+++ b/NeverBreak/src/com/github/thebiologist13/FarmListener.java
@@ -1,70 +1,70 @@
package com.github.thebiologist13;
import java.util.List;
import java.util.logging.Logger;
import net.minecraft.server.Material;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.inventory.ItemStack;
public class FarmListener implements Listener {
private FileConfiguration config;
Logger log = Logger.getLogger("Minecraft");
public FarmListener(NeverBreak neverBreak) {
config = neverBreak.getCustomConfig();
}
@EventHandler
public void onPlayerFarm(PlayerInteractEvent ev) {
//Player
Player p = ev.getPlayer();
- if(ev.getAction() == Action.RIGHT_CLICK_BLOCK) {
+ if(!(ev.getAction() == Action.RIGHT_CLICK_BLOCK)) {
return;
}
if(!(ev.getClickedBlock().getType().equals(Material.GRASS)) ||
!(ev.getMaterial().equals(Material.EARTH))) {
return;
}
//Item player has in hand
ItemStack stack = p.getItemInHand();
//Items that NeverBreak can be used with
List<?> items = config.getList("items");
//Loop for all items from config
for(Object o : items) {
//Make sure that it is specifying data IDs
if(o instanceof Integer) {
//If item in hand matches one from config
if(stack.getTypeId() == (Integer) o) {
//If a mode has been set for the player
if(ToggleCommand.mode.containsKey(p)) {
//If that mode is true
if(ToggleCommand.mode.get(p) == true) {
//Set the item to -1 durability
stack.setDurability((short) -128);
//If that mode is false, proceed as normal
} else {
//Unless it was set to REALLY unused, then make the durability 0 again
if(stack.getDurability() < 0 ) {
stack.setDurability((short) 0);
}
}
}
}
//Continue if not a data ID
} else {
continue;
}
}
}
}
| true | true | public void onPlayerFarm(PlayerInteractEvent ev) {
//Player
Player p = ev.getPlayer();
if(ev.getAction() == Action.RIGHT_CLICK_BLOCK) {
return;
}
if(!(ev.getClickedBlock().getType().equals(Material.GRASS)) ||
!(ev.getMaterial().equals(Material.EARTH))) {
return;
}
//Item player has in hand
ItemStack stack = p.getItemInHand();
//Items that NeverBreak can be used with
List<?> items = config.getList("items");
//Loop for all items from config
for(Object o : items) {
//Make sure that it is specifying data IDs
if(o instanceof Integer) {
//If item in hand matches one from config
if(stack.getTypeId() == (Integer) o) {
//If a mode has been set for the player
if(ToggleCommand.mode.containsKey(p)) {
//If that mode is true
if(ToggleCommand.mode.get(p) == true) {
//Set the item to -1 durability
stack.setDurability((short) -128);
//If that mode is false, proceed as normal
} else {
//Unless it was set to REALLY unused, then make the durability 0 again
if(stack.getDurability() < 0 ) {
stack.setDurability((short) 0);
}
}
}
}
//Continue if not a data ID
} else {
continue;
}
}
}
| public void onPlayerFarm(PlayerInteractEvent ev) {
//Player
Player p = ev.getPlayer();
if(!(ev.getAction() == Action.RIGHT_CLICK_BLOCK)) {
return;
}
if(!(ev.getClickedBlock().getType().equals(Material.GRASS)) ||
!(ev.getMaterial().equals(Material.EARTH))) {
return;
}
//Item player has in hand
ItemStack stack = p.getItemInHand();
//Items that NeverBreak can be used with
List<?> items = config.getList("items");
//Loop for all items from config
for(Object o : items) {
//Make sure that it is specifying data IDs
if(o instanceof Integer) {
//If item in hand matches one from config
if(stack.getTypeId() == (Integer) o) {
//If a mode has been set for the player
if(ToggleCommand.mode.containsKey(p)) {
//If that mode is true
if(ToggleCommand.mode.get(p) == true) {
//Set the item to -1 durability
stack.setDurability((short) -128);
//If that mode is false, proceed as normal
} else {
//Unless it was set to REALLY unused, then make the durability 0 again
if(stack.getDurability() < 0 ) {
stack.setDurability((short) 0);
}
}
}
}
//Continue if not a data ID
} else {
continue;
}
}
}
|
diff --git a/wallet/src/de/schildbach/wallet/ui/PeerListFragment.java b/wallet/src/de/schildbach/wallet/ui/PeerListFragment.java
index 9d86b59..b69e0c5 100644
--- a/wallet/src/de/schildbach/wallet/ui/PeerListFragment.java
+++ b/wallet/src/de/schildbach/wallet/ui/PeerListFragment.java
@@ -1,239 +1,239 @@
/*
* Copyright 2012-2013 the original author or authors.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.schildbach.wallet.ui;
import java.util.List;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.support.v4.app.LoaderManager.LoaderCallbacks;
import android.support.v4.content.AsyncTaskLoader;
import android.support.v4.content.Loader;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import com.actionbarsherlock.app.SherlockListFragment;
import com.google.bitcoin.core.Peer;
import com.google.bitcoin.core.VersionMessage;
import de.schildbach.wallet.service.BlockchainService;
import de.schildbach.wallet.service.BlockchainServiceImpl;
import de.schildbach.wallet_test.R;
/**
* @author Andreas Schildbach
*/
public final class PeerListFragment extends SherlockListFragment implements LoaderCallbacks<List<Peer>>
{
private AbstractWalletActivity activity;
private BlockchainService service;
private ArrayAdapter<Peer> adapter;
private final Handler handler = new Handler();
private static final long REFRESH_MS = 1000;
@Override
public void onAttach(final Activity activity)
{
super.onAttach(activity);
this.activity = (AbstractWalletActivity) activity;
}
@Override
public void onActivityCreated(final Bundle savedInstanceState)
{
super.onActivityCreated(savedInstanceState);
activity.bindService(new Intent(activity, BlockchainServiceImpl.class), serviceConnection, Context.BIND_AUTO_CREATE);
}
@Override
public void onViewCreated(final View view, final Bundle savedInstanceState)
{
super.onViewCreated(view, savedInstanceState);
setEmptyText(getString(R.string.peer_list_fragment_empty));
}
@Override
public void onCreate(final Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
adapter = new ArrayAdapter<Peer>(activity, 0)
{
@Override
public View getView(final int position, View row, final ViewGroup parent)
{
if (row == null)
row = getLayoutInflater(null).inflate(R.layout.peer_list_row, null);
final Peer peer = getItem(position);
final VersionMessage versionMessage = peer.getPeerVersionMessage();
final boolean isDownloading = peer.getDownloadData();
final TextView rowIp = (TextView) row.findViewById(R.id.peer_list_row_ip);
rowIp.setText(peer.getAddress().getAddr().getHostAddress());
final TextView rowHeight = (TextView) row.findViewById(R.id.peer_list_row_height);
- final long bestHeight = versionMessage.bestHeight;
+ final long bestHeight = peer.getBestHeight();
rowHeight.setText(bestHeight > 0 ? bestHeight + " blocks" : null);
rowHeight.setTypeface(isDownloading ? Typeface.DEFAULT_BOLD : Typeface.DEFAULT);
final TextView rowVersion = (TextView) row.findViewById(R.id.peer_list_row_version);
rowVersion.setText(versionMessage.subVer);
rowVersion.setTypeface(isDownloading ? Typeface.DEFAULT_BOLD : Typeface.DEFAULT);
return row;
}
@Override
public boolean isEnabled(final int position)
{
return false;
}
};
setListAdapter(adapter);
}
@Override
public void onResume()
{
super.onResume();
handler.postDelayed(new Runnable()
{
public void run()
{
adapter.notifyDataSetChanged();
handler.postDelayed(this, REFRESH_MS);
}
}, REFRESH_MS);
}
@Override
public void onPause()
{
handler.removeCallbacksAndMessages(null);
super.onPause();
}
@Override
public void onDestroy()
{
activity.unbindService(serviceConnection);
super.onDestroy();
}
public Loader<List<Peer>> onCreateLoader(final int id, final Bundle args)
{
return new PeerLoader(activity, service);
}
public void onLoadFinished(final Loader<List<Peer>> loader, final List<Peer> peers)
{
adapter.clear();
if (peers != null)
for (final Peer peer : peers)
adapter.add(peer);
}
public void onLoaderReset(final Loader<List<Peer>> loader)
{
adapter.clear();
}
private final ServiceConnection serviceConnection = new ServiceConnection()
{
public void onServiceConnected(final ComponentName name, final IBinder binder)
{
service = ((BlockchainServiceImpl.LocalBinder) binder).getService();
getLoaderManager().initLoader(0, null, PeerListFragment.this);
}
public void onServiceDisconnected(final ComponentName name)
{
getLoaderManager().destroyLoader(0);
service = null;
}
};
private static class PeerLoader extends AsyncTaskLoader<List<Peer>>
{
private Context context;
private BlockchainService service;
private PeerLoader(final Context context, final BlockchainService service)
{
super(context);
this.context = context;
this.service = service;
}
@Override
protected void onStartLoading()
{
super.onStartLoading();
context.registerReceiver(broadcastReceiver, new IntentFilter(BlockchainService.ACTION_PEER_STATE));
}
@Override
protected void onStopLoading()
{
context.unregisterReceiver(broadcastReceiver);
super.onStopLoading();
}
@Override
public List<Peer> loadInBackground()
{
return service.getConnectedPeers();
}
private final BroadcastReceiver broadcastReceiver = new BroadcastReceiver()
{
@Override
public void onReceive(final Context context, final Intent intent)
{
forceLoad();
}
};
}
}
| true | true | public void onCreate(final Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
adapter = new ArrayAdapter<Peer>(activity, 0)
{
@Override
public View getView(final int position, View row, final ViewGroup parent)
{
if (row == null)
row = getLayoutInflater(null).inflate(R.layout.peer_list_row, null);
final Peer peer = getItem(position);
final VersionMessage versionMessage = peer.getPeerVersionMessage();
final boolean isDownloading = peer.getDownloadData();
final TextView rowIp = (TextView) row.findViewById(R.id.peer_list_row_ip);
rowIp.setText(peer.getAddress().getAddr().getHostAddress());
final TextView rowHeight = (TextView) row.findViewById(R.id.peer_list_row_height);
final long bestHeight = versionMessage.bestHeight;
rowHeight.setText(bestHeight > 0 ? bestHeight + " blocks" : null);
rowHeight.setTypeface(isDownloading ? Typeface.DEFAULT_BOLD : Typeface.DEFAULT);
final TextView rowVersion = (TextView) row.findViewById(R.id.peer_list_row_version);
rowVersion.setText(versionMessage.subVer);
rowVersion.setTypeface(isDownloading ? Typeface.DEFAULT_BOLD : Typeface.DEFAULT);
return row;
}
@Override
public boolean isEnabled(final int position)
{
return false;
}
};
setListAdapter(adapter);
}
| public void onCreate(final Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
adapter = new ArrayAdapter<Peer>(activity, 0)
{
@Override
public View getView(final int position, View row, final ViewGroup parent)
{
if (row == null)
row = getLayoutInflater(null).inflate(R.layout.peer_list_row, null);
final Peer peer = getItem(position);
final VersionMessage versionMessage = peer.getPeerVersionMessage();
final boolean isDownloading = peer.getDownloadData();
final TextView rowIp = (TextView) row.findViewById(R.id.peer_list_row_ip);
rowIp.setText(peer.getAddress().getAddr().getHostAddress());
final TextView rowHeight = (TextView) row.findViewById(R.id.peer_list_row_height);
final long bestHeight = peer.getBestHeight();
rowHeight.setText(bestHeight > 0 ? bestHeight + " blocks" : null);
rowHeight.setTypeface(isDownloading ? Typeface.DEFAULT_BOLD : Typeface.DEFAULT);
final TextView rowVersion = (TextView) row.findViewById(R.id.peer_list_row_version);
rowVersion.setText(versionMessage.subVer);
rowVersion.setTypeface(isDownloading ? Typeface.DEFAULT_BOLD : Typeface.DEFAULT);
return row;
}
@Override
public boolean isEnabled(final int position)
{
return false;
}
};
setListAdapter(adapter);
}
|
diff --git a/projects/base/src/main/java/org/muis/base/layout/BoxLayout.java b/projects/base/src/main/java/org/muis/base/layout/BoxLayout.java
index 0644f503..d2c1f742 100644
--- a/projects/base/src/main/java/org/muis/base/layout/BoxLayout.java
+++ b/projects/base/src/main/java/org/muis/base/layout/BoxLayout.java
@@ -1,309 +1,309 @@
package org.muis.base.layout;
import static org.muis.core.layout.LayoutAttributes.*;
import java.awt.Rectangle;
import org.muis.core.MuisElement;
import org.muis.core.MuisLayout;
import org.muis.core.layout.*;
import org.muis.core.style.LayoutStyles;
import org.muis.core.style.Size;
import org.muis.util.CompoundListener;
/**
* Lays out children one-by-one along a given {@link LayoutAttributes#direction direction} ({@link Direction#DOWN DOWN} by default), with a
* given {@link LayoutAttributes#alignment alignment} along the opposite axis. {@link LayoutAttributes#width},
* {@link LayoutAttributes#height}, {@link LayoutAttributes#minWidth}, and {@link LayoutAttributes#minHeight} may be used to help determine
* the sizes of children.
*/
public class BoxLayout implements MuisLayout {
private final CompoundListener.MultiElementCompoundListener theListener;
/** Creates a box layout */
public BoxLayout() {
theListener = CompoundListener.create(this);
theListener.acceptAll(direction, alignment, crossAlignment).onChange(CompoundListener.layout);
theListener.child().acceptAll(width, minWidth, maxWidth, height, minHeight, maxHeight).onChange(CompoundListener.layout);
}
@Override
public void initChildren(MuisElement parent, MuisElement [] children) {
theListener.listenerFor(parent);
}
@Override
public void childAdded(MuisElement parent, MuisElement child) {
}
@Override
public void childRemoved(MuisElement parent, MuisElement child) {
}
@Override
public void remove(MuisElement parent) {
theListener.dropFor(parent);
}
@Override
public SizeGuide getWSizer(MuisElement parent, MuisElement [] children) {
Direction dir = parent.atts().get(direction, Direction.RIGHT);
Size margin = parent.getStyle().getSelf().get(LayoutStyles.margin);
Size padding = parent.getStyle().getSelf().get(LayoutStyles.padding);
switch (dir) {
case UP:
case DOWN:
return getCrossSizer(children, dir.getOrientation(), margin);
case LEFT:
case RIGHT:
return getMainSizer(children, dir.getOrientation(), margin, padding);
}
throw new IllegalStateException("Unrecognized layout direction: " + dir);
}
@Override
public SizeGuide getHSizer(MuisElement parent, MuisElement [] children) {
Direction dir = parent.atts().get(direction, Direction.RIGHT);
Size margin = parent.getStyle().getSelf().get(LayoutStyles.margin);
Size padding = parent.getStyle().getSelf().get(LayoutStyles.padding);
switch (dir) {
case UP:
case DOWN:
return getMainSizer(children, dir.getOrientation(), margin, padding);
case LEFT:
case RIGHT:
return getCrossSizer(children, dir.getOrientation(), margin);
}
throw new IllegalStateException("Unrecognized layout direction: " + dir);
}
/**
* Gets the size policy in the main direction of the container
*
* @param children The children to get the sizer for
* @param orient The orientation for the layout
* @param margin The margin size for the parent
* @param padding The padding size for the parent
* @return The size policy for the children
*/
protected SizeGuide getMainSizer(final MuisElement [] children, final Orientation orient, final Size margin, final Size padding) {
return new SizeGuide() {
@Override
public int getMin(int crossSize, boolean csMax) {
return get(LayoutGuideType.min, crossSize, csMax);
}
@Override
public int getMinPreferred(int crossSize, boolean csMax) {
return get(LayoutGuideType.minPref, crossSize, csMax);
}
@Override
public int getPreferred(int crossSize, boolean csMax) {
return get(LayoutGuideType.pref, crossSize, csMax);
}
@Override
public int getMaxPreferred(int crossSize, boolean csMax) {
return get(LayoutGuideType.maxPref, crossSize, csMax);
}
@Override
public int getMax(int crossSize, boolean csMax) {
return get(LayoutGuideType.max, crossSize, csMax);
}
@Override
public int get(LayoutGuideType type, int crossSize, boolean csMax) {
return BaseLayoutUtils.getBoxLayoutSize(children, orient, type, crossSize, csMax, margin, margin, padding, padding);
}
@Override
public int getBaseline(int size) {
return 0;
}
};
}
/**
* Gets the size policy in the non-main direction of the container
*
* @param children The children to get the sizer for
* @param orient The orientation for the layout (not the cross direction of the layout)
* @param margin The margin size for the parent
* @return The size policy for the children
*/
protected SizeGuide getCrossSizer(final MuisElement [] children, final Orientation orient, final Size margin) {
return new SizeGuide() {
@Override
public int getMin(int crossSize, boolean csMax) {
return get(LayoutGuideType.min, crossSize, csMax);
}
@Override
public int getMinPreferred(int crossSize, boolean csMax) {
return get(LayoutGuideType.minPref, crossSize, csMax);
}
@Override
public int getPreferred(int crossSize, boolean csMax) {
return get(LayoutGuideType.pref, crossSize, csMax);
}
@Override
public int getMaxPreferred(int crossSize, boolean csMax) {
return get(LayoutGuideType.maxPref, crossSize, csMax);
}
@Override
public int getMax(int crossSize, boolean csMax) {
return get(LayoutGuideType.max, crossSize, csMax);
}
@Override
public int get(LayoutGuideType type, int crossSize, boolean csMax) {
LayoutSize ret = new LayoutSize();
BaseLayoutUtils.getBoxLayoutCrossSize(children, orient, type, crossSize, csMax, ret);
ret.add(margin);
ret.add(margin);
return ret.getTotal();
}
@Override
public int getBaseline(int size) {
return 0;
}
};
}
@Override
public void layout(MuisElement parent, final MuisElement [] children) {
final Direction dir = parent.atts().get(direction, Direction.RIGHT);
Alignment align = parent.atts().get(alignment, Alignment.begin);
Alignment crossAlign = parent.atts().get(crossAlignment, Alignment.begin);
final Size margin = parent.getStyle().getSelf().get(LayoutStyles.margin);
final Size padding = parent.getStyle().getSelf().get(LayoutStyles.padding);
final int parallelSize = parent.bounds().get(dir.getOrientation()).getSize();
final int crossSize = parent.bounds().get(dir.getOrientation().opposite()).getSize();
final int crossSizeWOMargin = crossSize - margin.evaluate(crossSize) * 2;
LayoutUtils.LayoutInterpolation<LayoutSize []> result = LayoutUtils.interpolate(new LayoutUtils.LayoutChecker<LayoutSize []>() {
@Override
public LayoutSize [] getLayoutValue(LayoutGuideType type) {
LayoutSize [] ret = new LayoutSize[children.length];
for(int i = 0; i < ret.length; i++) {
ret[i] = new LayoutSize();
LayoutUtils.getSize(children[i], dir.getOrientation(), type, parallelSize, crossSizeWOMargin, true, ret[i]);
}
return ret;
}
@Override
public int getSize(LayoutSize [] layoutValue) {
LayoutSize ret = new LayoutSize();
ret.add(margin);
ret.add(margin);
for(int i = 0; i < layoutValue.length; i++) {
if(i > 0)
ret.add(padding);
ret.add(layoutValue[i]);
}
return ret.getTotal(parallelSize);
}
}, parallelSize, true, align == Alignment.justify);
Rectangle [] bounds = new Rectangle[children.length];
for(int c = 0; c < children.length; c++) {
bounds[c] = new Rectangle();
int mainSize = result.lowerValue[c].getTotal(parallelSize);
if(result.proportion > 0)
mainSize += Math.round(result.proportion
* (result.upperValue[c].getTotal(parallelSize) - result.lowerValue[c].getTotal(parallelSize)));
LayoutUtils.setSize(bounds[c], dir.getOrientation(), mainSize);
int prefCrossSize = LayoutUtils.getSize(children[c], dir.getOrientation().opposite(), LayoutGuideType.pref, crossSize,
mainSize, false, null);
int oppSize;
if(crossSize < prefCrossSize) {
int minCrossSize = LayoutUtils.getSize(children[c], dir.getOrientation().opposite(), LayoutGuideType.min, crossSize,
mainSize, false, null);
if(crossSize < minCrossSize)
oppSize = minCrossSize;
else
oppSize = crossSize;
} else if(align == Alignment.justify) {
int maxCrossSize = LayoutUtils.getSize(children[c], dir.getOrientation().opposite(), LayoutGuideType.max, crossSize,
mainSize, false, null);
if(crossSize < maxCrossSize)
oppSize = crossSize;
else
oppSize = maxCrossSize;
} else
oppSize = prefCrossSize;
LayoutUtils.setSize(bounds[c], dir.getOrientation().opposite(), oppSize);
}
// Main alignment
switch (align) {
case begin:
case end:
int pos = 0;
for(int c = 0; c < children.length; c++) {
int childPos = pos;
if(c == 0)
childPos += margin.evaluate(parallelSize);
else
childPos += padding.evaluate(parallelSize);
LayoutUtils.setPos(bounds[c], dir.getOrientation(), align == Alignment.begin ? childPos : parallelSize - childPos
- LayoutUtils.getSize(bounds[c], dir.getOrientation()));
pos = childPos + LayoutUtils.getSize(bounds[c], dir.getOrientation());
}
break;
case center:
case justify:
int freeSpace = parallelSize;
freeSpace -= margin.evaluate(parallelSize);
for(int c = 0; c < bounds.length; c++) {
if(c > 0)
freeSpace -= padding.evaluate(parallelSize);
freeSpace -= LayoutUtils.getSize(bounds[c], dir.getOrientation());
}
pos = 0;
int usedSpace = 0;
for(int c = 0; c < children.length; c++) {
int extraSpace = (freeSpace - usedSpace) / (children.length + 1 - c);
int childPos = pos + extraSpace;
if(c == 0)
childPos += margin.evaluate(parallelSize);
else
childPos += padding.evaluate(parallelSize);
LayoutUtils.setPos(bounds[c], dir.getOrientation(), align == Alignment.begin ? childPos : parallelSize - childPos
- LayoutUtils.getSize(bounds[c], dir.getOrientation()));
pos = childPos + LayoutUtils.getSize(bounds[c], dir.getOrientation());
usedSpace += extraSpace;
}
}
// Cross alignment
switch (crossAlign) {
case begin:
for(Rectangle bound : bounds)
LayoutUtils.setPos(bound, dir.getOrientation().opposite(), margin.evaluate(crossSize));
break;
case end:
for(Rectangle bound : bounds)
LayoutUtils.setPos(bound, dir.getOrientation().opposite(),
crossSize - LayoutUtils.getSize(bound, dir.getOrientation().opposite()) - margin.evaluate(crossSize));
break;
case center:
case justify:
for(Rectangle bound : bounds)
LayoutUtils.setPos(bound, dir.getOrientation().opposite(),
- margin.evaluate(crossSize) + (crossSize - LayoutUtils.getSize(bound, dir.getOrientation().opposite())) / 2);
+ margin.evaluate(crossSize) + (crossSizeWOMargin - LayoutUtils.getSize(bound, dir.getOrientation().opposite())) / 2);
}
for(int c = 0; c < children.length; c++)
children[c].bounds().setBounds(bounds[c].x, bounds[c].y, bounds[c].width, bounds[c].height);
}
}
| true | true | public void layout(MuisElement parent, final MuisElement [] children) {
final Direction dir = parent.atts().get(direction, Direction.RIGHT);
Alignment align = parent.atts().get(alignment, Alignment.begin);
Alignment crossAlign = parent.atts().get(crossAlignment, Alignment.begin);
final Size margin = parent.getStyle().getSelf().get(LayoutStyles.margin);
final Size padding = parent.getStyle().getSelf().get(LayoutStyles.padding);
final int parallelSize = parent.bounds().get(dir.getOrientation()).getSize();
final int crossSize = parent.bounds().get(dir.getOrientation().opposite()).getSize();
final int crossSizeWOMargin = crossSize - margin.evaluate(crossSize) * 2;
LayoutUtils.LayoutInterpolation<LayoutSize []> result = LayoutUtils.interpolate(new LayoutUtils.LayoutChecker<LayoutSize []>() {
@Override
public LayoutSize [] getLayoutValue(LayoutGuideType type) {
LayoutSize [] ret = new LayoutSize[children.length];
for(int i = 0; i < ret.length; i++) {
ret[i] = new LayoutSize();
LayoutUtils.getSize(children[i], dir.getOrientation(), type, parallelSize, crossSizeWOMargin, true, ret[i]);
}
return ret;
}
@Override
public int getSize(LayoutSize [] layoutValue) {
LayoutSize ret = new LayoutSize();
ret.add(margin);
ret.add(margin);
for(int i = 0; i < layoutValue.length; i++) {
if(i > 0)
ret.add(padding);
ret.add(layoutValue[i]);
}
return ret.getTotal(parallelSize);
}
}, parallelSize, true, align == Alignment.justify);
Rectangle [] bounds = new Rectangle[children.length];
for(int c = 0; c < children.length; c++) {
bounds[c] = new Rectangle();
int mainSize = result.lowerValue[c].getTotal(parallelSize);
if(result.proportion > 0)
mainSize += Math.round(result.proportion
* (result.upperValue[c].getTotal(parallelSize) - result.lowerValue[c].getTotal(parallelSize)));
LayoutUtils.setSize(bounds[c], dir.getOrientation(), mainSize);
int prefCrossSize = LayoutUtils.getSize(children[c], dir.getOrientation().opposite(), LayoutGuideType.pref, crossSize,
mainSize, false, null);
int oppSize;
if(crossSize < prefCrossSize) {
int minCrossSize = LayoutUtils.getSize(children[c], dir.getOrientation().opposite(), LayoutGuideType.min, crossSize,
mainSize, false, null);
if(crossSize < minCrossSize)
oppSize = minCrossSize;
else
oppSize = crossSize;
} else if(align == Alignment.justify) {
int maxCrossSize = LayoutUtils.getSize(children[c], dir.getOrientation().opposite(), LayoutGuideType.max, crossSize,
mainSize, false, null);
if(crossSize < maxCrossSize)
oppSize = crossSize;
else
oppSize = maxCrossSize;
} else
oppSize = prefCrossSize;
LayoutUtils.setSize(bounds[c], dir.getOrientation().opposite(), oppSize);
}
// Main alignment
switch (align) {
case begin:
case end:
int pos = 0;
for(int c = 0; c < children.length; c++) {
int childPos = pos;
if(c == 0)
childPos += margin.evaluate(parallelSize);
else
childPos += padding.evaluate(parallelSize);
LayoutUtils.setPos(bounds[c], dir.getOrientation(), align == Alignment.begin ? childPos : parallelSize - childPos
- LayoutUtils.getSize(bounds[c], dir.getOrientation()));
pos = childPos + LayoutUtils.getSize(bounds[c], dir.getOrientation());
}
break;
case center:
case justify:
int freeSpace = parallelSize;
freeSpace -= margin.evaluate(parallelSize);
for(int c = 0; c < bounds.length; c++) {
if(c > 0)
freeSpace -= padding.evaluate(parallelSize);
freeSpace -= LayoutUtils.getSize(bounds[c], dir.getOrientation());
}
pos = 0;
int usedSpace = 0;
for(int c = 0; c < children.length; c++) {
int extraSpace = (freeSpace - usedSpace) / (children.length + 1 - c);
int childPos = pos + extraSpace;
if(c == 0)
childPos += margin.evaluate(parallelSize);
else
childPos += padding.evaluate(parallelSize);
LayoutUtils.setPos(bounds[c], dir.getOrientation(), align == Alignment.begin ? childPos : parallelSize - childPos
- LayoutUtils.getSize(bounds[c], dir.getOrientation()));
pos = childPos + LayoutUtils.getSize(bounds[c], dir.getOrientation());
usedSpace += extraSpace;
}
}
// Cross alignment
switch (crossAlign) {
case begin:
for(Rectangle bound : bounds)
LayoutUtils.setPos(bound, dir.getOrientation().opposite(), margin.evaluate(crossSize));
break;
case end:
for(Rectangle bound : bounds)
LayoutUtils.setPos(bound, dir.getOrientation().opposite(),
crossSize - LayoutUtils.getSize(bound, dir.getOrientation().opposite()) - margin.evaluate(crossSize));
break;
case center:
case justify:
for(Rectangle bound : bounds)
LayoutUtils.setPos(bound, dir.getOrientation().opposite(),
margin.evaluate(crossSize) + (crossSize - LayoutUtils.getSize(bound, dir.getOrientation().opposite())) / 2);
}
for(int c = 0; c < children.length; c++)
children[c].bounds().setBounds(bounds[c].x, bounds[c].y, bounds[c].width, bounds[c].height);
}
| public void layout(MuisElement parent, final MuisElement [] children) {
final Direction dir = parent.atts().get(direction, Direction.RIGHT);
Alignment align = parent.atts().get(alignment, Alignment.begin);
Alignment crossAlign = parent.atts().get(crossAlignment, Alignment.begin);
final Size margin = parent.getStyle().getSelf().get(LayoutStyles.margin);
final Size padding = parent.getStyle().getSelf().get(LayoutStyles.padding);
final int parallelSize = parent.bounds().get(dir.getOrientation()).getSize();
final int crossSize = parent.bounds().get(dir.getOrientation().opposite()).getSize();
final int crossSizeWOMargin = crossSize - margin.evaluate(crossSize) * 2;
LayoutUtils.LayoutInterpolation<LayoutSize []> result = LayoutUtils.interpolate(new LayoutUtils.LayoutChecker<LayoutSize []>() {
@Override
public LayoutSize [] getLayoutValue(LayoutGuideType type) {
LayoutSize [] ret = new LayoutSize[children.length];
for(int i = 0; i < ret.length; i++) {
ret[i] = new LayoutSize();
LayoutUtils.getSize(children[i], dir.getOrientation(), type, parallelSize, crossSizeWOMargin, true, ret[i]);
}
return ret;
}
@Override
public int getSize(LayoutSize [] layoutValue) {
LayoutSize ret = new LayoutSize();
ret.add(margin);
ret.add(margin);
for(int i = 0; i < layoutValue.length; i++) {
if(i > 0)
ret.add(padding);
ret.add(layoutValue[i]);
}
return ret.getTotal(parallelSize);
}
}, parallelSize, true, align == Alignment.justify);
Rectangle [] bounds = new Rectangle[children.length];
for(int c = 0; c < children.length; c++) {
bounds[c] = new Rectangle();
int mainSize = result.lowerValue[c].getTotal(parallelSize);
if(result.proportion > 0)
mainSize += Math.round(result.proportion
* (result.upperValue[c].getTotal(parallelSize) - result.lowerValue[c].getTotal(parallelSize)));
LayoutUtils.setSize(bounds[c], dir.getOrientation(), mainSize);
int prefCrossSize = LayoutUtils.getSize(children[c], dir.getOrientation().opposite(), LayoutGuideType.pref, crossSize,
mainSize, false, null);
int oppSize;
if(crossSize < prefCrossSize) {
int minCrossSize = LayoutUtils.getSize(children[c], dir.getOrientation().opposite(), LayoutGuideType.min, crossSize,
mainSize, false, null);
if(crossSize < minCrossSize)
oppSize = minCrossSize;
else
oppSize = crossSize;
} else if(align == Alignment.justify) {
int maxCrossSize = LayoutUtils.getSize(children[c], dir.getOrientation().opposite(), LayoutGuideType.max, crossSize,
mainSize, false, null);
if(crossSize < maxCrossSize)
oppSize = crossSize;
else
oppSize = maxCrossSize;
} else
oppSize = prefCrossSize;
LayoutUtils.setSize(bounds[c], dir.getOrientation().opposite(), oppSize);
}
// Main alignment
switch (align) {
case begin:
case end:
int pos = 0;
for(int c = 0; c < children.length; c++) {
int childPos = pos;
if(c == 0)
childPos += margin.evaluate(parallelSize);
else
childPos += padding.evaluate(parallelSize);
LayoutUtils.setPos(bounds[c], dir.getOrientation(), align == Alignment.begin ? childPos : parallelSize - childPos
- LayoutUtils.getSize(bounds[c], dir.getOrientation()));
pos = childPos + LayoutUtils.getSize(bounds[c], dir.getOrientation());
}
break;
case center:
case justify:
int freeSpace = parallelSize;
freeSpace -= margin.evaluate(parallelSize);
for(int c = 0; c < bounds.length; c++) {
if(c > 0)
freeSpace -= padding.evaluate(parallelSize);
freeSpace -= LayoutUtils.getSize(bounds[c], dir.getOrientation());
}
pos = 0;
int usedSpace = 0;
for(int c = 0; c < children.length; c++) {
int extraSpace = (freeSpace - usedSpace) / (children.length + 1 - c);
int childPos = pos + extraSpace;
if(c == 0)
childPos += margin.evaluate(parallelSize);
else
childPos += padding.evaluate(parallelSize);
LayoutUtils.setPos(bounds[c], dir.getOrientation(), align == Alignment.begin ? childPos : parallelSize - childPos
- LayoutUtils.getSize(bounds[c], dir.getOrientation()));
pos = childPos + LayoutUtils.getSize(bounds[c], dir.getOrientation());
usedSpace += extraSpace;
}
}
// Cross alignment
switch (crossAlign) {
case begin:
for(Rectangle bound : bounds)
LayoutUtils.setPos(bound, dir.getOrientation().opposite(), margin.evaluate(crossSize));
break;
case end:
for(Rectangle bound : bounds)
LayoutUtils.setPos(bound, dir.getOrientation().opposite(),
crossSize - LayoutUtils.getSize(bound, dir.getOrientation().opposite()) - margin.evaluate(crossSize));
break;
case center:
case justify:
for(Rectangle bound : bounds)
LayoutUtils.setPos(bound, dir.getOrientation().opposite(),
margin.evaluate(crossSize) + (crossSizeWOMargin - LayoutUtils.getSize(bound, dir.getOrientation().opposite())) / 2);
}
for(int c = 0; c < children.length; c++)
children[c].bounds().setBounds(bounds[c].x, bounds[c].y, bounds[c].width, bounds[c].height);
}
|
diff --git a/disunity-cli/src/main/java/info/ata4/disunity/cli/command/BundleBuildCommand.java b/disunity-cli/src/main/java/info/ata4/disunity/cli/command/BundleBuildCommand.java
index 7e00d87..4bb9c15 100644
--- a/disunity-cli/src/main/java/info/ata4/disunity/cli/command/BundleBuildCommand.java
+++ b/disunity-cli/src/main/java/info/ata4/disunity/cli/command/BundleBuildCommand.java
@@ -1,45 +1,45 @@
/*
** 2014 December 16
**
** The author disclaims copyright to this source code. In place of
** a legal notice, here is a blessing:
** May you do good and not evil.
** May you find forgiveness for yourself and forgive others.
** May you share freely, never taking more than you give.
*/
package info.ata4.disunity.cli.command;
import com.beust.jcommander.Parameter;
import com.beust.jcommander.Parameters;
import info.ata4.disunity.cli.converters.PathConverter;
import info.ata4.io.util.PathUtils;
import info.ata4.unity.assetbundle.AssetBundleUtils;
import java.io.IOException;
import java.nio.file.Path;
/**
*
* @author Nico Bergemann <barracuda415 at yahoo.de>
*/
@Parameters(
commandNames = "bundle-build",
commandDescription = "Builds an asset bundle from a .json property file."
)
public class BundleBuildCommand extends SingleFileCommand {
@Parameter(
names = {"-o", "--output"},
description = "Asset bundle output file",
converter = PathConverter.class
)
private Path outFile;
@Override
public void handleFile(Path file) throws IOException {
if (outFile == null) {
String fileName = PathUtils.getBaseName(file);
- outFile = file.getParent().resolve(fileName);
+ outFile = file.getParent().resolve(fileName + ".unity3d");
}
AssetBundleUtils.build(file, outFile);
}
}
| true | true | public void handleFile(Path file) throws IOException {
if (outFile == null) {
String fileName = PathUtils.getBaseName(file);
outFile = file.getParent().resolve(fileName);
}
AssetBundleUtils.build(file, outFile);
}
| public void handleFile(Path file) throws IOException {
if (outFile == null) {
String fileName = PathUtils.getBaseName(file);
outFile = file.getParent().resolve(fileName + ".unity3d");
}
AssetBundleUtils.build(file, outFile);
}
|
diff --git a/com.upnp.mediaplayer/src/org/rpi/mpdplayer/StatusMonitor.java b/com.upnp.mediaplayer/src/org/rpi/mpdplayer/StatusMonitor.java
index 42fe7a9..0f35473 100644
--- a/com.upnp.mediaplayer/src/org/rpi/mpdplayer/StatusMonitor.java
+++ b/com.upnp.mediaplayer/src/org/rpi/mpdplayer/StatusMonitor.java
@@ -1,233 +1,235 @@
package org.rpi.mpdplayer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Observable;
import java.util.Observer;
import org.apache.log4j.Logger;
import org.rpi.config.Config;
import org.rpi.mplayer.TrackInfo;
import org.rpi.player.events.EventBase;
import org.rpi.player.events.EventCurrentTrackFinishing;
import org.rpi.player.events.EventDurationUpdate;
import org.rpi.player.events.EventStatusChanged;
import org.rpi.player.events.EventTimeUpdate;
import org.rpi.player.events.EventTrackChanged;
import org.rpi.player.events.EventUpdateTrackMetaText;
import org.rpi.player.events.EventVolumeChanged;
public class StatusMonitor extends Observable implements Runnable, Observer {
private static Logger log = Logger.getLogger(StatusMonitor.class);
private TCPConnector tcp = null;
private boolean isRunning = true;
private boolean sentFinishingEvent = false;
private String current_songid = "";
private String current_state = "";
private String current_time = "";
private String current_duration = "";
private String current_title = "";
private String current_volume = "";
private TrackInfo ti = null;
public StatusMonitor(TCPConnector tcp) {
this.tcp = tcp;
ti = new TrackInfo();
ti.addObserver(this);
}
@Override
public void run() {
int iCount = 0;
while (isRunning()) {
List<String> commands = new ArrayList<String>();
commands.add(tcp.createCommand("status"));
commands.add(tcp.createCommand("currentsong"));
boolean bSongChanged = false;
HashMap<String, String> res = tcp.sendCommand(tcp.createCommandList(commands));
String value = "";
value = res.get("songid");
if (value != null && !current_songid.equalsIgnoreCase(value)) {
log.debug("Song Changed From : " + current_songid + " To: " + value);
EventTrackChanged ev = new EventTrackChanged();
ev.setMPD_id(value);
fireEvent(ev);
current_songid = value;
sentFinishingEvent = false;
bSongChanged = true;
}
value = res.get("state");
if (value != null) {
if (value.equalsIgnoreCase("PLAY")) {
value = "Playing";
} else if (value.equalsIgnoreCase("STOP")) {
value = "Stopped";
} else if (value.equalsIgnoreCase("PAUSE")) {
value = "Paused";
}
if (value != null && !current_state.equalsIgnoreCase(value)) {
log.debug("Status Changed From : " + current_state + " To: " + value);
current_state = value;
setStatus(value);
} else {
if (bSongChanged) {
if (value != null) {
setStatus(value);
}
}
}
}
value = res.get("time");
if(value !=null)
{
String[] splits = value.split(":");
String mTime = splits[0];
String mDuration = splits[1];
long lDuration = 0;
long lTime = 0;
lDuration = Long.valueOf(mDuration).longValue();
if (mTime != null && !current_time.equalsIgnoreCase(mTime)) {
EventTimeUpdate e = new EventTimeUpdate();
lTime = Long.valueOf(mTime).longValue();
e.setTime(lTime);
fireEvent(e);
current_time = mTime;
}
if (mDuration != null && !current_duration.equalsIgnoreCase(mDuration)) {
EventDurationUpdate e = new EventDurationUpdate();
e.setDuration(lDuration);
fireEvent(e);
current_duration = mDuration;
}
if (lTime > 0 && lDuration > 0) {
if ((lDuration - lTime) < Config.mpd_preload_timer) {
if (!sentFinishingEvent) {
EventCurrentTrackFinishing ev = new EventCurrentTrackFinishing();
fireEvent(ev);
sentFinishingEvent = true;
}
}
}
}
String volume = res.get("volume");
if(volume !=null)
{
if (!current_volume.equalsIgnoreCase(volume)) {
EventVolumeChanged ev = new EventVolumeChanged();
long l = Long.valueOf(volume).longValue();
+ if(l < 0)
+ l=0;
ev.setVolume(l);
fireEvent(ev);
current_volume = volume;
}
}
String full_title = res.get("Title");
if (full_title !=null && !current_title.equalsIgnoreCase(full_title)) {
String artist = "";
String title = full_title;
try {
String fulls[] = full_title.split("-");
if (fulls.length > 1) {
title = fulls[0].trim();
artist = fulls[1].trim();
if (artist.endsWith("'")) {
artist = artist.substring(0, artist.length() - 1);
}
}
} catch (Exception e) {
}
EventUpdateTrackMetaText ev = new EventUpdateTrackMetaText();
ev.setArtist(artist);
ev.setTitle(title);
fireEvent(ev);
current_title = full_title;
}
if (bSongChanged) {
ti.setUpdated(false);
}
String audio = res.get("audio");
if(audio !=null)
{
if (!ti.isUpdated() || iCount > 5) {
if (iCount > 5) {
ti.setUpdated(false);
iCount = 0;
}
String[] splits = audio.split(":");
try {
String sample = splits[0];
long sr = Long.valueOf(sample).longValue();
ti.setSampleRate(sr);
ti.setCodec(" ");
long duration = Long.valueOf(current_duration).longValue();
ti.setDuration(duration);
if (splits.length > 1) {
String depth = splits[1];
long dep = Long.valueOf(depth).longValue();
ti.setBitDepth(dep);
ti.setCodec("" + dep + " bits");
}
} catch (Exception e) {
}
}
if (res.containsKey("bitrate")) {
String bitrate = res.get("bitrate");
try {
long br = Long.valueOf(bitrate).longValue();
ti.setBitrate(br);
} catch (Exception e) {
}
}
if (ti.isSet()) {
ti.setUpdated(true);
}
iCount++;
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
log.error(e);
}
}
}
public boolean isRunning() {
return isRunning;
}
public void setRunning(boolean isRunning) {
this.isRunning = isRunning;
}
public synchronized void setStatus(String value) {
EventStatusChanged ev = new EventStatusChanged();
ev.setStatus(value);
fireEvent(ev);
}
private void fireEvent(EventBase ev) {
setChanged();
notifyObservers(ev);
}
@Override
public void update(Observable o, Object evt) {
EventBase e = (EventBase) evt;
fireEvent(e);
}
}
| true | true | public void run() {
int iCount = 0;
while (isRunning()) {
List<String> commands = new ArrayList<String>();
commands.add(tcp.createCommand("status"));
commands.add(tcp.createCommand("currentsong"));
boolean bSongChanged = false;
HashMap<String, String> res = tcp.sendCommand(tcp.createCommandList(commands));
String value = "";
value = res.get("songid");
if (value != null && !current_songid.equalsIgnoreCase(value)) {
log.debug("Song Changed From : " + current_songid + " To: " + value);
EventTrackChanged ev = new EventTrackChanged();
ev.setMPD_id(value);
fireEvent(ev);
current_songid = value;
sentFinishingEvent = false;
bSongChanged = true;
}
value = res.get("state");
if (value != null) {
if (value.equalsIgnoreCase("PLAY")) {
value = "Playing";
} else if (value.equalsIgnoreCase("STOP")) {
value = "Stopped";
} else if (value.equalsIgnoreCase("PAUSE")) {
value = "Paused";
}
if (value != null && !current_state.equalsIgnoreCase(value)) {
log.debug("Status Changed From : " + current_state + " To: " + value);
current_state = value;
setStatus(value);
} else {
if (bSongChanged) {
if (value != null) {
setStatus(value);
}
}
}
}
value = res.get("time");
if(value !=null)
{
String[] splits = value.split(":");
String mTime = splits[0];
String mDuration = splits[1];
long lDuration = 0;
long lTime = 0;
lDuration = Long.valueOf(mDuration).longValue();
if (mTime != null && !current_time.equalsIgnoreCase(mTime)) {
EventTimeUpdate e = new EventTimeUpdate();
lTime = Long.valueOf(mTime).longValue();
e.setTime(lTime);
fireEvent(e);
current_time = mTime;
}
if (mDuration != null && !current_duration.equalsIgnoreCase(mDuration)) {
EventDurationUpdate e = new EventDurationUpdate();
e.setDuration(lDuration);
fireEvent(e);
current_duration = mDuration;
}
if (lTime > 0 && lDuration > 0) {
if ((lDuration - lTime) < Config.mpd_preload_timer) {
if (!sentFinishingEvent) {
EventCurrentTrackFinishing ev = new EventCurrentTrackFinishing();
fireEvent(ev);
sentFinishingEvent = true;
}
}
}
}
String volume = res.get("volume");
if(volume !=null)
{
if (!current_volume.equalsIgnoreCase(volume)) {
EventVolumeChanged ev = new EventVolumeChanged();
long l = Long.valueOf(volume).longValue();
ev.setVolume(l);
fireEvent(ev);
current_volume = volume;
}
}
String full_title = res.get("Title");
if (full_title !=null && !current_title.equalsIgnoreCase(full_title)) {
String artist = "";
String title = full_title;
try {
String fulls[] = full_title.split("-");
if (fulls.length > 1) {
title = fulls[0].trim();
artist = fulls[1].trim();
if (artist.endsWith("'")) {
artist = artist.substring(0, artist.length() - 1);
}
}
} catch (Exception e) {
}
EventUpdateTrackMetaText ev = new EventUpdateTrackMetaText();
ev.setArtist(artist);
ev.setTitle(title);
fireEvent(ev);
current_title = full_title;
}
if (bSongChanged) {
ti.setUpdated(false);
}
String audio = res.get("audio");
if(audio !=null)
{
if (!ti.isUpdated() || iCount > 5) {
if (iCount > 5) {
ti.setUpdated(false);
iCount = 0;
}
String[] splits = audio.split(":");
try {
String sample = splits[0];
long sr = Long.valueOf(sample).longValue();
ti.setSampleRate(sr);
ti.setCodec(" ");
long duration = Long.valueOf(current_duration).longValue();
ti.setDuration(duration);
if (splits.length > 1) {
String depth = splits[1];
long dep = Long.valueOf(depth).longValue();
ti.setBitDepth(dep);
ti.setCodec("" + dep + " bits");
}
} catch (Exception e) {
}
}
if (res.containsKey("bitrate")) {
String bitrate = res.get("bitrate");
try {
long br = Long.valueOf(bitrate).longValue();
ti.setBitrate(br);
} catch (Exception e) {
}
}
if (ti.isSet()) {
ti.setUpdated(true);
}
iCount++;
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
log.error(e);
}
}
}
| public void run() {
int iCount = 0;
while (isRunning()) {
List<String> commands = new ArrayList<String>();
commands.add(tcp.createCommand("status"));
commands.add(tcp.createCommand("currentsong"));
boolean bSongChanged = false;
HashMap<String, String> res = tcp.sendCommand(tcp.createCommandList(commands));
String value = "";
value = res.get("songid");
if (value != null && !current_songid.equalsIgnoreCase(value)) {
log.debug("Song Changed From : " + current_songid + " To: " + value);
EventTrackChanged ev = new EventTrackChanged();
ev.setMPD_id(value);
fireEvent(ev);
current_songid = value;
sentFinishingEvent = false;
bSongChanged = true;
}
value = res.get("state");
if (value != null) {
if (value.equalsIgnoreCase("PLAY")) {
value = "Playing";
} else if (value.equalsIgnoreCase("STOP")) {
value = "Stopped";
} else if (value.equalsIgnoreCase("PAUSE")) {
value = "Paused";
}
if (value != null && !current_state.equalsIgnoreCase(value)) {
log.debug("Status Changed From : " + current_state + " To: " + value);
current_state = value;
setStatus(value);
} else {
if (bSongChanged) {
if (value != null) {
setStatus(value);
}
}
}
}
value = res.get("time");
if(value !=null)
{
String[] splits = value.split(":");
String mTime = splits[0];
String mDuration = splits[1];
long lDuration = 0;
long lTime = 0;
lDuration = Long.valueOf(mDuration).longValue();
if (mTime != null && !current_time.equalsIgnoreCase(mTime)) {
EventTimeUpdate e = new EventTimeUpdate();
lTime = Long.valueOf(mTime).longValue();
e.setTime(lTime);
fireEvent(e);
current_time = mTime;
}
if (mDuration != null && !current_duration.equalsIgnoreCase(mDuration)) {
EventDurationUpdate e = new EventDurationUpdate();
e.setDuration(lDuration);
fireEvent(e);
current_duration = mDuration;
}
if (lTime > 0 && lDuration > 0) {
if ((lDuration - lTime) < Config.mpd_preload_timer) {
if (!sentFinishingEvent) {
EventCurrentTrackFinishing ev = new EventCurrentTrackFinishing();
fireEvent(ev);
sentFinishingEvent = true;
}
}
}
}
String volume = res.get("volume");
if(volume !=null)
{
if (!current_volume.equalsIgnoreCase(volume)) {
EventVolumeChanged ev = new EventVolumeChanged();
long l = Long.valueOf(volume).longValue();
if(l < 0)
l=0;
ev.setVolume(l);
fireEvent(ev);
current_volume = volume;
}
}
String full_title = res.get("Title");
if (full_title !=null && !current_title.equalsIgnoreCase(full_title)) {
String artist = "";
String title = full_title;
try {
String fulls[] = full_title.split("-");
if (fulls.length > 1) {
title = fulls[0].trim();
artist = fulls[1].trim();
if (artist.endsWith("'")) {
artist = artist.substring(0, artist.length() - 1);
}
}
} catch (Exception e) {
}
EventUpdateTrackMetaText ev = new EventUpdateTrackMetaText();
ev.setArtist(artist);
ev.setTitle(title);
fireEvent(ev);
current_title = full_title;
}
if (bSongChanged) {
ti.setUpdated(false);
}
String audio = res.get("audio");
if(audio !=null)
{
if (!ti.isUpdated() || iCount > 5) {
if (iCount > 5) {
ti.setUpdated(false);
iCount = 0;
}
String[] splits = audio.split(":");
try {
String sample = splits[0];
long sr = Long.valueOf(sample).longValue();
ti.setSampleRate(sr);
ti.setCodec(" ");
long duration = Long.valueOf(current_duration).longValue();
ti.setDuration(duration);
if (splits.length > 1) {
String depth = splits[1];
long dep = Long.valueOf(depth).longValue();
ti.setBitDepth(dep);
ti.setCodec("" + dep + " bits");
}
} catch (Exception e) {
}
}
if (res.containsKey("bitrate")) {
String bitrate = res.get("bitrate");
try {
long br = Long.valueOf(bitrate).longValue();
ti.setBitrate(br);
} catch (Exception e) {
}
}
if (ti.isSet()) {
ti.setUpdated(true);
}
iCount++;
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
log.error(e);
}
}
}
|
diff --git a/hot-deploy/opentaps-tests/src/org/opentaps/tests/financials/FinancialsTests.java b/hot-deploy/opentaps-tests/src/org/opentaps/tests/financials/FinancialsTests.java
index 4df509299..a4f407943 100644
--- a/hot-deploy/opentaps-tests/src/org/opentaps/tests/financials/FinancialsTests.java
+++ b/hot-deploy/opentaps-tests/src/org/opentaps/tests/financials/FinancialsTests.java
@@ -1,2773 +1,2773 @@
/*
* Copyright (c) 2006 - 2009 Open Source Strategies, Inc.
*
* Opentaps is free software: you can redistribute it and/or modify it
* under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Opentaps is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Opentaps. If not, see <http://www.gnu.org/licenses/>.
*/
package org.opentaps.tests.financials;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.TimeZone;
import com.opensourcestrategies.financials.accounts.AccountsHelper;
import com.opensourcestrategies.financials.util.UtilCOGS;
import com.opensourcestrategies.financials.util.UtilFinancial;
import javolution.util.FastMap;
import org.ofbiz.base.util.Debug;
import org.ofbiz.base.util.GeneralException;
import org.ofbiz.base.util.UtilDateTime;
import org.ofbiz.base.util.UtilMisc;
import org.ofbiz.entity.GenericValue;
import org.ofbiz.entity.condition.EntityCondition;
import org.ofbiz.entity.condition.EntityOperator;
import org.ofbiz.entity.util.EntityUtil;
import org.opentaps.common.order.PurchaseOrderFactory;
import org.opentaps.domain.DomainsDirectory;
import org.opentaps.domain.DomainsLoader;
import org.opentaps.base.entities.AccountBalanceHistory;
import org.opentaps.base.entities.AcctgTransEntry;
import org.opentaps.base.entities.CustomTimePeriod;
import org.opentaps.base.entities.GlAccountHistory;
import org.opentaps.base.entities.InventoryItemValueHistory;
import org.opentaps.base.entities.InvoiceAdjustmentGlAccount;
import org.opentaps.base.entities.InvoiceAdjustmentType;
import org.opentaps.base.entities.SupplierProduct;
import org.opentaps.domain.billing.invoice.Invoice;
import org.opentaps.domain.billing.invoice.InvoiceRepositoryInterface;
import org.opentaps.domain.billing.payment.Payment;
import org.opentaps.domain.billing.payment.PaymentRepositoryInterface;
import org.opentaps.domain.inventory.InventoryDomainInterface;
import org.opentaps.domain.inventory.InventoryItem;
import org.opentaps.domain.inventory.InventoryRepositoryInterface;
import org.opentaps.domain.ledger.AccountingTransaction;
import org.opentaps.domain.ledger.AccountingTransaction.TagBalance;
import org.opentaps.domain.ledger.GeneralLedgerAccount;
import org.opentaps.domain.ledger.LedgerRepositoryInterface;
import org.opentaps.domain.order.Order;
import org.opentaps.domain.order.OrderRepositoryInterface;
import org.opentaps.domain.organization.Organization;
import org.opentaps.domain.organization.OrganizationRepositoryInterface;
import org.opentaps.domain.purchasing.PurchasingRepositoryInterface;
import org.opentaps.financials.domain.billing.invoice.InvoiceRepository;
import org.opentaps.foundation.entity.hibernate.Query;
import org.opentaps.foundation.entity.hibernate.Session;
import org.opentaps.foundation.infrastructure.Infrastructure;
import org.opentaps.foundation.infrastructure.User;
import org.opentaps.tests.analytics.tests.TestObjectGenerator;
import org.opentaps.tests.warehouse.InventoryAsserts;
/**
* General financial tests. If there is a large chunk of test cases that are related, please
* place them in a separate class.
*
* These tests are designed to run over and over again on the same database.
*/
public class FinancialsTests extends FinancialsTestCase {
private static final String MODULE = FinancialsTests.class.getName();
/** userLogin for inventory operations. */
private GenericValue demowarehouse1 = null;
/** Facility and inventory owner. */
private static final String facilityContactMechId = "9200";
private static final String testLedgerOrganizationPartyId = "LEDGER-TEST";
private static final String testLedgerTransId = "LEDGER-TEST-1"; // pre-stored transactions
private static final int LOOP_TESTS = 1000;
private TimeZone timeZone = TimeZone.getDefault();
private Locale locale = Locale.getDefault();
@Override
public void setUp() throws Exception {
super.setUp();
User = admin;
demowarehouse1 = delegator.findByPrimaryKeyCache("UserLogin", UtilMisc.toMap("userLoginId", "demowarehouse1"));
}
@Override
public void tearDown() throws Exception {
demowarehouse1 = null;
super.tearDown();
}
/**
* Test organizationRepository's getAllFiscalTimePeriods returns correct number of time periods.
* @throws GeneralException if an error occurs
*/
public void testGetAllCustomTimePeriods() throws GeneralException {
OrganizationRepositoryInterface orgRepository = organizationDomain.getOrganizationRepository();
List<CustomTimePeriod> timePeriods = orgRepository.getAllFiscalTimePeriods(testLedgerOrganizationPartyId);
// check that the number of time periods is same as that in LedgerPostingTestData.xml
assertEquals("Correct number of time periods found for [" + testLedgerOrganizationPartyId + "]", timePeriods.size(), 12);
}
/**
* Verify that the AccountingTransaction getDebitTotal() and getCreditTotal() methods are correct.
* @throws GeneralException if an error occurs
*/
public void testAccountingTransactionDebitCreditTotals() throws GeneralException {
LedgerRepositoryInterface ledgerRepository = ledgerDomain.getLedgerRepository();
AccountingTransaction ledgerTestTrans = ledgerRepository.getAccountingTransaction(testLedgerTransId);
assertEquals("Transaction [" + testLedgerTransId + "] debit total is not correct", ledgerTestTrans.getDebitTotal(), new BigDecimal("300.0"));
assertEquals("Transaction [" + testLedgerTransId + "] credit total is not correct", ledgerTestTrans.getCreditTotal(), new BigDecimal("300.0"));
}
/**
* Verify key ledger posting features:
* 1. transactions will not post before scheduled date
* 2. correct debit/credit balances will be set for all time periods
* 3. will not post transactions which have already been posted
* @throws GeneralException if an error occurs
*/
@SuppressWarnings("unchecked")
public void testLedgerPosting() throws GeneralException {
DomainsDirectory dd = new DomainsLoader(new Infrastructure(dispatcher), new User(demofinadmin)).loadDomainsDirectory();
LedgerRepositoryInterface ledgerRepository = ledgerDomain.getLedgerRepository();
OrganizationRepositoryInterface organizationRepository = dd.getOrganizationDomain().getOrganizationRepository();
AccountingTransaction ledgerTestTrans = ledgerRepository.getAccountingTransaction(testLedgerTransId);
Map postToLedgerParams = UtilMisc.toMap("acctgTransId", testLedgerTransId, "userLogin", demofinadmin);
// verify that a transaction which is supposed to post in the future cannot be posted
ledgerTestTrans.setScheduledPostingDate(UtilDateTime.addDaysToTimestamp(UtilDateTime.nowTimestamp(), 10));
ledgerRepository.update(ledgerTestTrans);
runAndAssertServiceError("postAcctgTrans", postToLedgerParams);
// verify that it can post without the scheduled posting date
postToLedgerParams = UtilMisc.toMap("acctgTransId", testLedgerTransId, "userLogin", demofinadmin);
ledgerTestTrans.setScheduledPostingDate(null);
ledgerRepository.update(ledgerTestTrans);
runAndAssertServiceSuccess("postAcctgTrans", postToLedgerParams);
// verify AcctgTrans.getPostedAmount() is 300.00
ledgerTestTrans = ledgerRepository.getAccountingTransaction(testLedgerTransId);
assertEquals("AcctgTrans.getPostedAmount() should be 300.00", new BigDecimal("300.0"), ledgerTestTrans.getPostedAmount());
// the test transaction should only post to these time periods
List timePeriodsWithPosting = UtilMisc.toList("LT2008", "LT2008Q1", "LT2008FEB");
// verify that the GL Account History is correctly updated for each time period by checking each entry of the
// AcctgTrans and verifying that its GL account is correct for all available time periods
List<CustomTimePeriod> availableTimePeriods = organizationRepository.getAllFiscalTimePeriods(testLedgerOrganizationPartyId);
List<? extends AcctgTransEntry> transEntries = ledgerTestTrans.getAcctgTransEntrys();
for (AcctgTransEntry entry : transEntries) {
for (CustomTimePeriod period : availableTimePeriods) {
GlAccountHistory accountHistory = ledgerRepository.getAccountHistory(entry.getGlAccountId(), testLedgerOrganizationPartyId, period.getCustomTimePeriodId());
// verify that only the correct time periods were posted to
if (timePeriodsWithPosting.contains(period.getCustomTimePeriodId())) {
assertNotNull("Time period [" + period.getCustomTimePeriodId() + "] was posted to for gl account [" + entry.getGlAccountId(), accountHistory);
GeneralLedgerAccount glAccount = ledgerRepository.getLedgerAccount(entry.getGlAccountId(), testLedgerOrganizationPartyId);
if (glAccount.isDebitAccount()) {
assertEquals("Posted debits do not equal for " + accountHistory + " and " + entry, accountHistory.getPostedDebits(), entry.getAmount());
} else {
assertEquals("Posted credits do not equal for " + accountHistory + " and " + entry, accountHistory.getPostedCredits(), entry.getAmount());
}
} else {
assertNull("Time period [" + period.getCustomTimePeriodId() + "] was not posted to for gl account [" + entry.getGlAccountId(), accountHistory);
}
}
}
// verify that we cannot post it again
postToLedgerParams = UtilMisc.toMap("acctgTransId", testLedgerTransId, "userLogin", demofinadmin);
runAndAssertServiceError("postAcctgTrans", postToLedgerParams);
}
/**
* Tests posting a transaction that is globally balanced but unbalanced regarding tag1 because of a missing tag (which is configured for STATEMENT_DETAILS).
* Specifically one entry has a tag 1 debit 5000, and the corresponding credit entry has no tag 1.
* @throws GeneralException if an error occurs
*/
public void testLedgerPostingTagBalanceMissing() throws GeneralException {
// check the transaction cannot be posted
Map<String, Object> input = new HashMap<String, Object>();
input.put("userLogin", demofinadmin);
input.put("acctgTransId", "BAD-STATEMENT-TEST-1");
runAndAssertServiceError("postAcctgTrans", input);
// check the accounting transaction canPost() method
LedgerRepositoryInterface ledgerRepository = ledgerDomain.getLedgerRepository();
AccountingTransaction trans = ledgerRepository.getAccountingTransaction("BAD-STATEMENT-TEST-1");
assertFalse("Transaction BAD-STATEMENT-TEST-1 should not be marked as able to post.", trans.canPost());
// check the error is related to the unbalanced tag 1
TagBalance tagNotBalance = trans.accountingTagsBalance();
assertEquals("Transaction BAD-STATEMENT-TEST-1 tag 1 should be unbalanced", 1, tagNotBalance.getIndex());
assertEquals("Transaction BAD-STATEMENT-TEST-1 tag 1 should be unbalanced", new BigDecimal(5000), tagNotBalance.getBalance().abs());
}
/**
* tests posting a transaction that is globally balanced but unbalanced regarding tag1 because of a mismatched tag (which is configured for STATEMENT_DETAILS).
* Specifically the credit and debit entries both has a tag 1 but not the same tag value.
* @throws GeneralException if an error occurs
*/
public void testLedgerPostingTagBalanceMismatched() throws GeneralException {
// check the transaction cannot be posted
Map<String, Object> input = new HashMap<String, Object>();
input.put("userLogin", demofinadmin);
input.put("acctgTransId", "BAD-STATEMENT-TEST-2");
runAndAssertServiceError("postAcctgTrans", input);
// check the accounting transaction canPost() method
LedgerRepositoryInterface ledgerRepository = ledgerDomain.getLedgerRepository();
AccountingTransaction trans = ledgerRepository.getAccountingTransaction("BAD-STATEMENT-TEST-2");
assertFalse("Transaction BAD-STATEMENT-TEST-2 should not be marked as able to post.", trans.canPost());
// check the error is related to the unbalanced tag 1
TagBalance tagNotBalance = trans.accountingTagsBalance();
assertEquals("Transaction BAD-STATEMENT-TEST-2 tag 1 should be unbalanced", 1, tagNotBalance.getIndex());
assertEquals("Transaction BAD-STATEMENT-TEST-2 tag 1 should be unbalanced", new BigDecimal(1200), tagNotBalance.getBalance().abs());
}
/**
* Test getting the right GL Account for GlAccountTypeId and organization.
* @throws GeneralException if an error occurs
*/
public void testGlAccountTypeSetting() throws GeneralException {
LedgerRepositoryInterface ledgerRepository = ledgerDomain.getLedgerRepository();
GeneralLedgerAccount glAccount = ledgerRepository.getDefaultLedgerAccount("ACCOUNTS_RECEIVABLE", testLedgerOrganizationPartyId);
// this hardcoded gl account ID Needs to be the same as that defined in hot-deploy/opentaps-tests/data/financials/LedgerPostingTestData.xml
assertEquals("Incorrect Accounts Receivables account for [" + testLedgerOrganizationPartyId + "]", "120000", glAccount.getGlAccountId());
}
/**
* Test the sending of a paycheck [DEMOPAYCHECK1] and compares the resulting GL transaction
* to the reference transaction DEMOPAYCHECK1 in PayrollEntries.xml.
*
* Note that this is a test between an initial demo paycheck and an expected result set,
* so we are not testing the logic in creating a paycheck, but rather the ledger posting
* logic. The idea is to test the part of the system which is difficult for humans to
* validate immediately. Bugs in the posting process may surface after many months, so
* this makes for a perfect unit test subject.
* @throws GeneralException if an error occurs
*/
@SuppressWarnings("unchecked")
public void testPaycheckTransactions() throws GeneralException {
// before we begin, note the time so we can easily find the transaction
Timestamp start = UtilDateTime.nowTimestamp();
FinancialAsserts fa = new FinancialAsserts(this, organizationPartyId, demofinadmin);
GenericValue paycheck = delegator.findByPrimaryKey("Payment", UtilMisc.toMap("paymentId", "DEMOPAYCHECK1"));
assertNotNull("Paycheck with ID [DEMOPAYCHECK1] not found.", paycheck);
// set the status to "not paid" so we can send it
paycheck.set("statusId", "PMNT_NOT_PAID");
paycheck.store();
// mark the payment as sent
fa.updatePaymentStatus(paycheck.getString("paymentId"), "PMNT_SENT");
// get the transaction with the assistance of our start timestamp. Note that this requires the DEMOPAYCHECK1 not to have an effectiveDate of its own
// or it would be posted with transactionDate = payment.effectiveDate
Set transactions = getAcctgTransSinceDate(UtilMisc.toList(EntityCondition.makeCondition("paymentId", EntityOperator.EQUALS, paycheck.get("paymentId"))), start, delegator);
assertNotEmpty("Paycheck transaction not created.", transactions);
// assert transaction equivalence with the reference transaction
assertTransactionEquivalence(transactions, UtilMisc.toList("PAYCHECKTEST1"));
}
/**
* Test receives a few serialized and non-serialized items of product, write off
* some quantity of product as damaged and checks average cost after.
* @throws GeneralException if an error occurs
*/
@SuppressWarnings("unchecked")
public void testProductAverageCost() throws GeneralException {
// create product for inventory operations
Map<String, Object> callContext = new HashMap<String, Object>();
callContext.put("productTypeId", "FINISHED_GOOD");
callContext.put("internalName", "Product for use in Average Cost Unit Tests");
callContext.put("isVirtual", "N");
callContext.put("isVariant", "N");
callContext.put("userLogin", demowarehouse1);
Map<String, Object> product = runAndAssertServiceSuccess("createProduct", callContext);
String productId = (String) product.get("productId");
assertEquals("Failed to create test product.", true, productId != null);
Timestamp startTime = UtilDateTime.nowTimestamp();
BigDecimal expectedAvgCost = null;
BigDecimal calculatedAvgCost = null;
InventoryAsserts inventoryAsserts = new InventoryAsserts(this, "WebStoreWarehouse", organizationPartyId, demowarehouse1);
final BigDecimal acceptedDelta = new BigDecimal("0.009");
// common parameters for receiveInventoryProduct service
Map<String, Object> commonParameters = new HashMap<String, Object>();
commonParameters.put("productId", productId);
commonParameters.put("facilityId", "WebStoreWarehouse");
commonParameters.put("currencyUomId", "USD");
commonParameters.put("datetimeReceived", startTime);
commonParameters.put("quantityRejected", BigDecimal.ZERO);
commonParameters.put("userLogin", demowarehouse1);
/*
* receives 10 products at $15, average cost = 15 [10 x 15$]
*/
Map<String, Object> input = new HashMap<String, Object>();
input.putAll(commonParameters);
input.putAll(UtilMisc.toMap("inventoryItemTypeId", "NON_SERIAL_INV_ITEM", "unitCost", new BigDecimal("15"), "quantityAccepted", new BigDecimal("10")));
Map output = runAndAssertServiceSuccess("receiveInventoryProduct", input);
calculatedAvgCost = UtilCOGS.getProductAverageCost(productId, organizationPartyId, demowarehouse1, delegator, dispatcher);
assertNotNull("The product [" + productId + "] average cost cannot be null", calculatedAvgCost);
calculatedAvgCost = calculatedAvgCost.setScale(DECIMALS, ROUNDING);
expectedAvgCost = new BigDecimal("15");
assertEquals("After receipt 10 products [" + productId + "] at $15 calculated average cost doesn't equal expected one with inadmissible error.", expectedAvgCost, calculatedAvgCost, acceptedDelta);
inventoryAsserts.assertInventoryValuesEqual(productId);
// we'll write this inventory off later
String inventoryItemIdVar = (String) output.get("inventoryItemId");
pause("allow distinct product average cost timestamps");
/*
* receives 10 products at $20, average cost = 17.5 [10 x 15$ + 10 x 20$]
*/
input = new HashMap<String, Object>();
input.putAll(commonParameters);
input.putAll(UtilMisc.toMap("inventoryItemTypeId", "NON_SERIAL_INV_ITEM", "unitCost", new BigDecimal("20"), "quantityAccepted", new BigDecimal("10")));
output = runAndAssertServiceSuccess("receiveInventoryProduct", input);
calculatedAvgCost = UtilCOGS.getProductAverageCost(productId, organizationPartyId, demowarehouse1, delegator, dispatcher);
assertNotNull("The product [" + productId + "] average cost cannot be null", calculatedAvgCost);
calculatedAvgCost = calculatedAvgCost.setScale(DECIMALS, ROUNDING);
expectedAvgCost = new BigDecimal("17.5");
assertEquals("After receipt 10 products [" + productId + "] at $20 calculated average cost doesn't equal expected one with inadmissible error.", expectedAvgCost, calculatedAvgCost, acceptedDelta);
inventoryAsserts.assertInventoryValuesEqual(productId);
String inventoryItemIdForRevalue1 = (String) output.get("inventoryItemId");
pause("allow distinct product average cost timestamps");
/*
* receives 1 serialized product at $10, average cost = 17.142857 [10 x 15$ + 10 x 20$ + 1 x 10$]
*/
input = new HashMap<String, Object>();
input.putAll(commonParameters);
input.putAll(UtilMisc.toMap("inventoryItemTypeId", "SERIALIZED_INV_ITEM", "unitCost", new BigDecimal("10"), "quantityAccepted", BigDecimal.ONE));
runAndAssertServiceSuccess("receiveInventoryProduct", input);
calculatedAvgCost = UtilCOGS.getProductAverageCost(productId, organizationPartyId, demowarehouse1, delegator, dispatcher);
assertNotNull("The product [" + productId + "] average cost cannot be null", calculatedAvgCost);
calculatedAvgCost = calculatedAvgCost.setScale(DECIMALS, ROUNDING);
expectedAvgCost = new BigDecimal("17.142");
assertEquals("After receipt 1 serialized product [" + productId + "] at $10 calculated average cost doesn't equal expected one with inadmissible error.", expectedAvgCost, calculatedAvgCost, acceptedDelta);
inventoryAsserts.assertInventoryValuesEqual(productId);
pause("allow distinct product average cost timestamps");
/*
* receives 1 serialized product at $12, average cost = 16.909091 [10 x 15$ + 10 x 20$ + 1 x 10$ +1 x 12$]
*/
input = new HashMap<String, Object>();
input.putAll(commonParameters);
input.putAll(UtilMisc.toMap("inventoryItemTypeId", "SERIALIZED_INV_ITEM", "unitCost", new BigDecimal("12"), "quantityAccepted", BigDecimal.ONE));
runAndAssertServiceSuccess("receiveInventoryProduct", input);
calculatedAvgCost = UtilCOGS.getProductAverageCost(productId, organizationPartyId, demowarehouse1, delegator, dispatcher);
assertNotNull("The product [" + productId + "] average cost cannot be null", calculatedAvgCost);
calculatedAvgCost = calculatedAvgCost.setScale(DECIMALS, ROUNDING);
expectedAvgCost = new BigDecimal("16.909");
assertEquals("After receipt 1 serialized product [" + productId + "] at $12 calculated average cost doesn't equal expected one with inadmissible error.", expectedAvgCost, calculatedAvgCost, acceptedDelta);
inventoryAsserts.assertInventoryValuesEqual(productId);
pause("allow distinct product average cost timestamps");
/*
* Create variance -5 products from inventory item at $15, average cost = 16.909091 [10 x 15$ + 10 x 20$ + 1 x 10$ + 1 x 12$ - 5 x avg] doesn't change the average cost
*/
BigDecimal varianceQuantity = new BigDecimal("-5");
input = UtilMisc.<String, Object>toMap("userLogin", demowarehouse1, "inventoryItemId", inventoryItemIdVar, "quantityOnHandVar", varianceQuantity, "availableToPromiseVar", varianceQuantity, "varianceReasonId", "VAR_DAMAGED");
runAndAssertServiceSuccess("createPhysicalInventoryAndVariance", input);
calculatedAvgCost = UtilCOGS.getProductAverageCost(productId, organizationPartyId, demowarehouse1, delegator, dispatcher);
assertNotNull("The product [" + productId + "] average cost cannot be null", calculatedAvgCost);
calculatedAvgCost = calculatedAvgCost.setScale(DECIMALS, ROUNDING);
expectedAvgCost = new BigDecimal("16.909");
assertEquals("After creating variance for -5 products [" + productId + "] calculated average cost doesn't equal expected one with inadmissible error.", expectedAvgCost, calculatedAvgCost, acceptedDelta);
inventoryAsserts.assertInventoryValuesEqual(productId);
pause("allow distinct product average cost timestamps");
/*
* Create variance -3 products from inventory item at $15, average cost = 16.909091 [10 x 15$ + 10 x 20$ + 1 x 10$ + 1 x 12$ - 8 x avg] doesn't change the average cost
*/
varianceQuantity = new BigDecimal("-3");
input = UtilMisc.<String, Object>toMap("userLogin", demowarehouse1, "inventoryItemId", inventoryItemIdVar, "quantityOnHandVar", varianceQuantity, "availableToPromiseVar", varianceQuantity, "varianceReasonId", "VAR_DAMAGED");
runAndAssertServiceSuccess("createPhysicalInventoryAndVariance", input);
calculatedAvgCost = UtilCOGS.getProductAverageCost(productId, organizationPartyId, demowarehouse1, delegator, dispatcher);
assertNotNull("The product [" + productId + "] average cost cannot be null", calculatedAvgCost);
calculatedAvgCost = calculatedAvgCost.setScale(DECIMALS, ROUNDING);
expectedAvgCost = new BigDecimal("16.909");
assertEquals("After creating variance for -3 products [" + productId + "] calculated average cost doesn't equal expected one with inadmissible error.", expectedAvgCost, calculatedAvgCost, acceptedDelta);
inventoryAsserts.assertInventoryValuesEqual(productId);
pause("allow distinct product average cost timestamps");
/*
* receives 3 products at $11 average cost = 15.865882 [10 x 15$ + 10 x 20$ + 1 x 10$ + 1 x 12$ + 3 x 11$ - 8 x 16.91]
*/
input = new HashMap<String, Object>();
input.putAll(commonParameters);
input.putAll(UtilMisc.toMap("inventoryItemTypeId", "NON_SERIAL_INV_ITEM", "unitCost", new BigDecimal("11"), "quantityAccepted", new BigDecimal("3")));
runAndAssertServiceSuccess("receiveInventoryProduct", input);
calculatedAvgCost = UtilCOGS.getProductAverageCost(productId, organizationPartyId, demowarehouse1, delegator, dispatcher);
assertNotNull("The product [" + productId + "] average cost cannot be null", calculatedAvgCost);
calculatedAvgCost = calculatedAvgCost.setScale(DECIMALS, ROUNDING);
expectedAvgCost = new BigDecimal("15.866");
assertEquals("After receipt 3 products [" + productId + "] at $11 calculated average cost doesn't equal expected one with inadmissible error.", expectedAvgCost, calculatedAvgCost, acceptedDelta);
inventoryAsserts.assertInventoryValuesEqual(productId);
pause("allow distinct product average cost timestamps");
/*
* receives 1 serialized products at $22 average cost = 16.206667 [10 x 15$ + 10 x 20$ + 1 x 10$ + 1 x 12$ + 3 x 11$ + 1 x 22$ - 8 x 16.91]
*/
input = new HashMap<String, Object>();
input.putAll(commonParameters);
input.putAll(UtilMisc.toMap("inventoryItemTypeId", "SERIALIZED_INV_ITEM", "unitCost", new BigDecimal("22"), "quantityAccepted", new BigDecimal("1")));
output = runAndAssertServiceSuccess("receiveInventoryProduct", input);
calculatedAvgCost = UtilCOGS.getProductAverageCost(productId, organizationPartyId, demowarehouse1, delegator, dispatcher);
assertNotNull("The product [" + productId + "] average cost cannot be null", calculatedAvgCost);
calculatedAvgCost = calculatedAvgCost.setScale(DECIMALS, ROUNDING);
expectedAvgCost = new BigDecimal("16.207");
assertEquals("After receipt 1 serialized product [" + productId + "] at $22 calculated average cost doesn't equal expected one with inadmissible error.", expectedAvgCost, calculatedAvgCost, acceptedDelta);
inventoryAsserts.assertInventoryValuesEqual(productId);
String inventoryItemIdForRevalue2 = (String) output.get("inventoryItemId");
pause("allow distinct product average cost timestamps");
/*
* revalue inventoryItemIdForRevalue1 to $10 average cost = 10.651111 [10 x 15$ + 10 x 10$ + 1 x 10$ + 1 x 12$ + 3 x 11$ + 1 x 22$ - 8 x 16.91]
*/
input = new HashMap<String, Object>();
input.put("inventoryItemId", inventoryItemIdForRevalue1);
input.put("productId", productId);
input.put("ownerPartyId", organizationPartyId);
input.put("userLogin", demowarehouse1);
input.put("unitCost", new BigDecimal("10.0"));
input.put("currencyUomId", "USD");
input.put("inventoryItemTypeId", "NON_SERIAL_INV_ITEM");
runAndAssertServiceSuccess("updateInventoryItem", input);
calculatedAvgCost = UtilCOGS.getProductAverageCost(productId, organizationPartyId, demowarehouse1, delegator, dispatcher);
assertNotNull("The product [" + productId + "] average cost cannot be null", calculatedAvgCost);
calculatedAvgCost = calculatedAvgCost.setScale(DECIMALS, ROUNDING);
expectedAvgCost = new BigDecimal("10.651");
assertEquals("After revalue 10 products [" + productId + "] at $20 to $10 calculated average cost doesn't equal expected one with inadmissible error.", expectedAvgCost, calculatedAvgCost, acceptedDelta);
inventoryAsserts.assertInventoryValuesEqual(productId);
pause("allow distinct product average cost timestamps");
/*
* revalue inventoryItemIdForRevalue2 to $10
*/
input = new HashMap<String, Object>();
input.put("inventoryItemId", inventoryItemIdForRevalue2);
input.put("productId", productId);
input.put("ownerPartyId", organizationPartyId);
input.put("userLogin", demowarehouse1);
input.put("unitCost", new BigDecimal("10.0"));
input.put("currencyUomId", "USD");
input.put("inventoryItemTypeId", "SERIALIZED_INV_ITEM");
runAndAssertServiceSuccess("updateInventoryItem", input);
calculatedAvgCost = UtilCOGS.getProductAverageCost(productId, organizationPartyId, demowarehouse1, delegator, dispatcher);
assertNotNull("The product [" + productId + "] average cost cannot be null", calculatedAvgCost);
calculatedAvgCost = calculatedAvgCost.setScale(DECIMALS, ROUNDING);
expectedAvgCost = new BigDecimal("9.984");
assertEquals("After revalue 1 serialized product [" + productId + "] at $22 to $10 calculated average cost doesn't equal expected one with inadmissible error.", expectedAvgCost, calculatedAvgCost, acceptedDelta);
inventoryAsserts.assertInventoryValuesEqual(productId);
}
/**
* This test verifies that products average cost will be correct after
* a large number of transactions in rapid succession of each other.
* @throws GeneralException if an error occurs
*/
@SuppressWarnings("unchecked")
public void testProductAverageCostLongRunning() throws GeneralException {
// Create a new product
Map<String, Object> callContext = new HashMap<String, Object>();
callContext.put("productTypeId", "FINISHED_GOOD");
callContext.put("internalName", "Product for use in Average Cost Long Running Tests");
callContext.put("isVirtual", "N");
callContext.put("isVariant", "N");
callContext.put("userLogin", demowarehouse1);
Map<String, Object> product = runAndAssertServiceSuccess("createProduct", callContext);
String productId = (String) product.get("productId");
// track two values: total quantity and total value of the product. Initially, both should be zero
BigDecimal totalQuantity = BigDecimal.ZERO;
BigDecimal totalValue = BigDecimal.ZERO;
// common parameters for receiveInventoryProduct service
Map<String, Object> commonParameters = new HashMap<String, Object>();
commonParameters.put("productId", productId);
commonParameters.put("facilityId", "WebStoreWarehouse");
commonParameters.put("currencyUomId", "USD");
commonParameters.put("quantityRejected", BigDecimal.ZERO);
commonParameters.put("userLogin", demowarehouse1);
// for i = 1 to 1000
for (int i = 1; i < LOOP_TESTS; i++) {
// q (quantity) = i, uc (unit cost) = i mod 1000
// receive q of product at unit cost = uc
BigDecimal q = new BigDecimal(i);
BigDecimal uc = new BigDecimal(i % 1000);
Map<String, Object> input = new HashMap<String, Object>();
input.putAll(commonParameters);
input.putAll(UtilMisc.toMap("inventoryItemTypeId", "NON_SERIAL_INV_ITEM"
, "unitCost", uc, "quantityAccepted" , q
, "datetimeReceived", UtilDateTime.nowTimestamp()));
runAndAssertServiceSuccess("receiveInventoryProduct", input);
// update total quantity (add q) and total value (add q*uc)
totalQuantity = totalQuantity.add(q);
totalValue = totalValue.add(q.multiply(uc));
// Verify that the average cost of the product from UtilCOGS.getProductAverageCost is equal to (total value)/(total quantity) to within 5 decimal places
BigDecimal productAverageCost = UtilCOGS.getProductAverageCost(productId, organizationPartyId, demowarehouse1, delegator, dispatcher);
BigDecimal expectedAvgCost = totalValue.divide(totalQuantity, DECIMALS, BigDecimal.ROUND_HALF_DOWN);
assertEquals("Product [" + productId + "] average cost should be " + expectedAvgCost + ".", expectedAvgCost, productAverageCost.setScale(DECIMALS, BigDecimal.ROUND_HALF_DOWN));
}
}
/**
* This test verifies that products average cost will be correct after
* a large number of transactions in rapid succession of each other.
* @throws GeneralException if an error occurs
*/
@SuppressWarnings("unchecked")
public void testInventoryItemValueHistoryLongRunning() throws GeneralException {
// Create a new product
Map<String, Object> callContext = new HashMap<String, Object>();
callContext.put("productTypeId", "FINISHED_GOOD");
callContext.put("internalName", "Product for use in testInventoryItemValueHistoryLongRunning");
callContext.put("isVirtual", "N");
callContext.put("isVariant", "N");
callContext.put("userLogin", demowarehouse1);
Map<String, Object> product = runAndAssertServiceSuccess("createProduct", callContext);
String productId = (String) product.get("productId");
// receive 1 of the product at unit cost 0.1
Map<String, Object> commonParameters = new HashMap<String, Object>();
commonParameters.put("productId", productId);
commonParameters.put("facilityId", "WebStoreWarehouse");
commonParameters.put("currencyUomId", "USD");
commonParameters.put("quantityRejected", BigDecimal.ZERO);
commonParameters.put("userLogin", demowarehouse1);
Map<String, Object> input = new HashMap<String, Object>();
input.putAll(commonParameters);
input.putAll(UtilMisc.toMap("inventoryItemTypeId", "NON_SERIAL_INV_ITEM"
, "unitCost", new BigDecimal("0.1"), "quantityAccepted" , new BigDecimal("1.0")
, "datetimeReceived", UtilDateTime.nowTimestamp()));
Map output = runAndAssertServiceSuccess("receiveInventoryProduct", input);
String inventoryItemId = (String) output.get("inventoryItemId");
// track the previous inventory item unit cost
List<GenericValue> inventoryItems = delegator.findByAnd("InventoryItem", UtilMisc.toMap("inventoryItemId", inventoryItemId));
GenericValue firstInventoryItem = inventoryItems.get(0);
BigDecimal previousUnitCost = firstInventoryItem.getBigDecimal("unitCost");
Debug.logInfo("previousUnitCost : " + previousUnitCost, MODULE);
pause("allow distinct product average cost timestamps");
DomainsLoader dl = new DomainsLoader(new Infrastructure(dispatcher), new User(User));
InventoryDomainInterface inventoryDomain = dl.loadDomainsDirectory().getInventoryDomain();
InventoryRepositoryInterface inventoryRepository = inventoryDomain.getInventoryRepository();
// for i = 1 to 1000
// update the inventory item.unit cost to i
for (int i = 1; i < LOOP_TESTS; i++) {
firstInventoryItem.set("unitCost", new BigDecimal(i));
firstInventoryItem.store();
// Verify that the previous inventory item unit cost is the same as the one retrieved from InventoryItem
InventoryItem item = inventoryRepository.getInventoryItemById(firstInventoryItem.getString("inventoryItemId"));
InventoryItemValueHistory inventoryItemValueHistory = inventoryRepository.getLastInventoryItemValueHistoryByInventoryItem(item);
BigDecimal inventoryItemValueHistoryUnitCost = inventoryItemValueHistory.getUnitCost();
assertEquals("Product [" + productId + "] previous inventory item unit cost should be " + previousUnitCost + ".", previousUnitCost, inventoryItemValueHistoryUnitCost);
}
}
/**
* Test that the transactionDate of accounting transaction will be the invoice's invoiceDate, not the current timestamp.
* @throws GeneralException if an error occurs
*/
public void testInvoiceTransactionPostingDate() throws GeneralException {
// create a customer
String customerPartyId = createPartyFromTemplate("DemoAccount1", "account for testing invoice posting transaction date");
// create a sales invoice to the customer 30 days in the future
FinancialAsserts financialAsserts = new FinancialAsserts(this, organizationPartyId, demofinadmin);
Timestamp invoiceDate = UtilDateTime.adjustTimestamp(UtilDateTime.nowTimestamp(), Calendar.DAY_OF_YEAR, 30, timeZone, locale);
String invoiceId = financialAsserts.createInvoice(customerPartyId, "SALES_INVOICE", invoiceDate, null, null, null);
financialAsserts.createInvoiceItem(invoiceId, "INV_FPROD_ITEM", "GZ-1000", new BigDecimal("2.0"), new BigDecimal("15.0"));
// set invoice to READY
financialAsserts.updateInvoiceStatus(invoiceId, "INVOICE_READY");
// check that the accounting transaction's transactionDate is the same as the invoice's invoiceDate
LedgerRepositoryInterface ledgerRepository = ledgerDomain.getLedgerRepository();
List<AccountingTransaction> invoiceAcctgTransList = ledgerRepository.findList(AccountingTransaction.class, ledgerRepository.map(org.opentaps.base.entities.AcctgTrans.Fields.invoiceId, invoiceId));
assertNotNull("An accounting transaction was not found for invoice [" + invoiceId + "]", invoiceAcctgTransList);
AccountingTransaction acctgTrans = invoiceAcctgTransList.get(0);
// note: it is important to get the actual invoiceDate stored in the Invoice entity, not the invoiceDate from above
// for example, mysql might store 2009-06-12 12:46:30.309 as 2009-06-12 12:46:30.0, so your comparison won't equal
InvoiceRepositoryInterface repository = billingDomain.getInvoiceRepository();
Invoice invoice = repository.getInvoiceById(invoiceId);
assertEquals("Transaction date and invoice date do not equal", acctgTrans.getTransactionDate(), invoice.getInvoiceDate());
}
/**
* Test to verify that payments are posted to the effectiveDate of the payment.
* @throws GeneralException if an error occurs
*/
public void testPaymentTransactionPostingDate() throws GeneralException {
String customerPartyId = createPartyFromTemplate("DemoAccount1", "account for testing payment posting transaction date");
FinancialAsserts financialAsserts = new FinancialAsserts(this, organizationPartyId, demofinadmin);
Timestamp paymentDate = UtilDateTime.adjustTimestamp(UtilDateTime.nowTimestamp(), Calendar.DAY_OF_YEAR, 30, timeZone, locale);
String paymentId = financialAsserts.createPayment(new BigDecimal("1.0"), customerPartyId, "CUSTOMER_PAYMENT", "CASH");
PaymentRepositoryInterface paymentRepository = billingDomain.getPaymentRepository();
Payment payment = paymentRepository.getPaymentById(paymentId);
payment.setEffectiveDate(paymentDate);
paymentRepository.createOrUpdate(payment);
financialAsserts.updatePaymentStatus(paymentId, "PMNT_RECEIVED");
LedgerRepositoryInterface ledgerRepository = ledgerDomain.getLedgerRepository();
List<AccountingTransaction> paymentAcctgTransList = ledgerRepository.findList(AccountingTransaction.class, ledgerRepository.map(org.opentaps.base.entities.AcctgTrans.Fields.paymentId, paymentId));
assertNotNull("An accounting transaction was not found for payment [" + paymentId + "]", paymentAcctgTransList);
AccountingTransaction acctgTrans = paymentAcctgTransList.get(0);
payment = paymentRepository.getPaymentById(paymentId);
assertEquals("Transaction date and invoice date do not equal", acctgTrans.getTransactionDate(), payment.getEffectiveDate());
}
/**
* Tests basic methods of Invoice class for sales invoice.
* @exception GeneralException if an error occurs
*/
public void testInvoiceMethodsForSalesInvoice() throws GeneralException {
//create a SALES_INVOICE from Company to another party
InvoiceRepositoryInterface repository = billingDomain.getInvoiceRepository();
String customerPartyId = createPartyFromTemplate("DemoAccount1", "Account for testInvoiceMethodsForSalesInvoice");
FinancialAsserts financialAsserts = new FinancialAsserts(this, organizationPartyId, demofinadmin);
// create invoice
String invoiceId = financialAsserts.createInvoice(customerPartyId, "SALES_INVOICE", UtilDateTime.nowTimestamp(), null, null, null);
financialAsserts.createInvoiceItem(invoiceId, "INV_FPROD_ITEM", "GZ-1000", new BigDecimal("2.0"), new BigDecimal("15.0"));
// Check the Invoice.isReceivable() is true
Invoice invoice = repository.getInvoiceById(invoiceId);
assertTrue("Invoice with ID [" + invoiceId + "] should be receivable.", invoice.isReceivable());
// Check the Invoice.isPayable() is false
assertFalse("Invoice with ID [" + invoiceId + "] should not payable.", invoice.isPayable());
// Check the Invoice.getOrganizationPartyId() is Company
assertEquals("Invoice.getOrganizationPartyId() should be " + organizationPartyId, organizationPartyId, invoice.getOrganizationPartyId());
// Check the Invoice.getTransactionPartyId() is the other party
assertEquals("Invoice.getTransactionPartyId() should be " + customerPartyId, customerPartyId, invoice.getTransactionPartyId());
}
/**
* Tests basic methods of Invoice class for purchase invoice.
* @exception GeneralException if an error occurs
*/
public void testInvoiceMethodsForPurchaseInvoice() throws GeneralException {
InvoiceRepositoryInterface repository = billingDomain.getInvoiceRepository();
String supplierPartyId = createPartyFromTemplate("DemoSupplier", "Account for testInvoiceMethodsForPurchaseInvoice");
FinancialAsserts financialAsserts = new FinancialAsserts(this, organizationPartyId, demofinadmin);
// create a PURCHASE_INVOICE from another party to Company
String invoiceId = financialAsserts.createInvoice(supplierPartyId, "PURCHASE_INVOICE", UtilDateTime.nowTimestamp(), null, null, null);
financialAsserts.createInvoiceItem(invoiceId, "PINV_FPROD_ITEM", "GZ-1000", new BigDecimal("100.0"), new BigDecimal("4.56"));
// Check the Invoice.isReceivable() is false
Invoice invoice = repository.getInvoiceById(invoiceId);
assertFalse("Invoice with ID [" + invoiceId + "] should not receivable.", invoice.isReceivable());
// Check the Invoice.isPayable() is true
assertTrue("Invoice with ID [" + invoiceId + "] should be payable.", invoice.isPayable());
// Check Invoice.getOrganizationPartyId() is Company
assertEquals("Invoice.getOrganizationPartyId() should be " + organizationPartyId, organizationPartyId, invoice.getOrganizationPartyId());
// Check the Invoice.getTransactionPartyId() is the other party
assertEquals("Invoice.getTransactionPartyId() should be " + supplierPartyId, supplierPartyId, invoice.getTransactionPartyId());
}
/**
* Test for sales invoice and payment.
* Note: this test relies on the status of previously created Invoices so it will fail if you run
* it a second time without rebuilding the DB
* @throws GeneralException if an error occurs
*/
@SuppressWarnings("unchecked")
public void testSalesInvoicePayment() throws GeneralException {
DomainsDirectory dd = new DomainsLoader(new Infrastructure(dispatcher), new User(demofinadmin)).loadDomainsDirectory();
InvoiceRepositoryInterface repository = dd.getBillingDomain().getInvoiceRepository();
// before we begin, note the time so we can easily find the transaction
Timestamp start = UtilDateTime.nowTimestamp();
Timestamp now = start;
// note the initial balances
String customerPartyId = createPartyFromTemplate("DemoAccount1", "Account for testSalesInvoicePayment");
FinancialAsserts financialAsserts = new FinancialAsserts(this, organizationPartyId, demofinadmin);
Map initialBalances = financialAsserts.getFinancialBalances(start);
BigDecimal balance1 = AccountsHelper.getBalanceForCustomerPartyId(customerPartyId, organizationPartyId, "ACTUAL", now, delegator);
// create invoice and set it to ready
String invoiceId = financialAsserts.createInvoice(customerPartyId, "SALES_INVOICE", UtilDateTime.nowTimestamp(), null, null, null);
financialAsserts.createInvoiceItem(invoiceId, "INV_FPROD_ITEM", "GZ-1000", new BigDecimal("2.0"), new BigDecimal("15.0"));
financialAsserts.createInvoiceItem(invoiceId, "ITM_PROMOTION_ADJ", "GZ-1000", new BigDecimal("1.0"), new BigDecimal("-10.0"));
financialAsserts.createInvoiceItem(invoiceId, "INV_FPROD_ITEM", "GZ-1001", new BigDecimal("1.0"), new BigDecimal("45.0"));
financialAsserts.createInvoiceItem(invoiceId, "ITM_SHIPPING_CHARGES", null, null, new BigDecimal("12.95"));
// Check the invoice current status
Invoice invoice = repository.getInvoiceById(invoiceId);
assertNotNull("Invoice with ID [" + invoiceId + "] not found.", invoice);
assertEquals("Invoice with ID [" + invoiceId + "] should have the INVOICE_IN_PROCESS status", "INVOICE_IN_PROCESS", invoice.getString("statusId"));
financialAsserts.updateInvoiceStatus(invoiceId, "INVOICE_READY");
now = UtilDateTime.nowTimestamp();
BigDecimal balance2 = AccountsHelper.getBalanceForCustomerPartyId(customerPartyId, organizationPartyId, "ACTUAL", now, delegator);
assertEquals("Balance for " + customerPartyId + " has not increased by 77.95", balance2.subtract(new BigDecimal("77.95")), balance1);
Map halfBalances = financialAsserts.getFinancialBalances(now);
Map expectedBalanceChanges = UtilMisc.toMap("ACCOUNTS_RECEIVABLE", "77.95");
Map accountMap = UtilFinancial.replaceGlAccountTypeWithGlAccountForOrg(organizationPartyId, expectedBalanceChanges, delegator);
assertMapDifferenceCorrect(initialBalances, halfBalances, accountMap);
// create payment and set it to received
String paymentId = financialAsserts.createPaymentAndApplication(new BigDecimal("77.95"), customerPartyId, organizationPartyId, "CUSTOMER_PAYMENT", "COMPANY_CHECK", null, invoiceId, "PMNT_NOT_PAID");
financialAsserts.updatePaymentStatus(paymentId, "PMNT_RECEIVED");
invoice = repository.getInvoiceById(invoiceId);
assertNotNull("Invoice with ID [" + invoiceId + "] not found.", invoice);
assertEquals("Invoice with ID [" + invoiceId + "] should have the INVOICE_PAID status", "INVOICE_PAID", invoice.getString("statusId"));
now = UtilDateTime.nowTimestamp();
BigDecimal balance3 = AccountsHelper.getBalanceForCustomerPartyId(customerPartyId, organizationPartyId, "ACTUAL", now, delegator);
assertEquals("Balance for " + customerPartyId + " has not decreased by 77.95", balance3.add(new BigDecimal("77.95")), balance2);
// get the transactions for the payment with the assistance of our start timestamp
Set<String> transactions = getAcctgTransSinceDate(UtilMisc.toList(EntityCondition.makeCondition("paymentId", EntityOperator.EQUALS, paymentId)), start, delegator);
assertNotEmpty(paymentId + " transaction not created.", transactions);
// assert transaction equivalence with the reference PMT_CUST_TEST-1 transaction
assertTransactionEquivalenceIgnoreParty(transactions, UtilMisc.toList("PMT_CUST_TEST-1"));
Map finalBalances = financialAsserts.getFinancialBalances(UtilDateTime.nowTimestamp());
expectedBalanceChanges = UtilMisc.toMap("ACCOUNTS_RECEIVABLE", "-77.95", "UNDEPOSITED_RECEIPTS", "77.95");
accountMap = UtilFinancial.replaceGlAccountTypeWithGlAccountForOrg(organizationPartyId, expectedBalanceChanges, delegator);
assertMapDifferenceCorrect(halfBalances, finalBalances, accountMap);
}
/**
* These tests verify what happens when you void a payment.
* 1 - get the initial balance for the customer and financial balances
* 2 - create a payment and set status to PMNT_VOID
* 3 - get the new balance for the customer and financial balances
* 4 - verify that the balance for the customer has increased by 77.95
* 5 - verify that the balance for ACCOUNTS_RECEIVABLE has increased by 77.95, and the balance for UNDEPOSITED_RECEIPTS has decreased by 77.95
*
* @throws GeneralException if an error occurs
*/
@SuppressWarnings("unchecked")
public void testVoidPayment() throws GeneralException {
DomainsDirectory dd = new DomainsLoader(new Infrastructure(dispatcher), new User(demofinadmin)).loadDomainsDirectory();
InvoiceRepositoryInterface repository = dd.getBillingDomain().getInvoiceRepository();
// before we begin, note the time so we can easily find the transaction
Timestamp start = UtilDateTime.nowTimestamp();
Timestamp now = start;
// note the initial balances
String customerPartyId = createPartyFromTemplate("DemoAccount1", "Account for testVoidPayment");
FinancialAsserts financialAsserts = new FinancialAsserts(this, organizationPartyId, demofinadmin);
Map initialBalances = financialAsserts.getFinancialBalances(start);
BigDecimal balance1 = AccountsHelper.getBalanceForCustomerPartyId(customerPartyId, organizationPartyId, "ACTUAL", now, delegator);
// create invoice and set it to ready
String invoiceId = financialAsserts.createInvoice(customerPartyId, "SALES_INVOICE", UtilDateTime.nowTimestamp(), null, null, null);
financialAsserts.createInvoiceItem(invoiceId, "INV_FPROD_ITEM", "GZ-1000", new BigDecimal("2.0"), new BigDecimal("15.0"));
financialAsserts.createInvoiceItem(invoiceId, "ITM_PROMOTION_ADJ", "GZ-1000", new BigDecimal("1.0"), new BigDecimal("-10.0"));
financialAsserts.createInvoiceItem(invoiceId, "INV_FPROD_ITEM", "GZ-1001", new BigDecimal("1.0"), new BigDecimal("45.0"));
financialAsserts.createInvoiceItem(invoiceId, "ITM_SHIPPING_CHARGES", null, null, new BigDecimal("12.95"));
// Update the Invoice status
financialAsserts.updateInvoiceStatus(invoiceId, "INVOICE_READY");
now = UtilDateTime.nowTimestamp();
BigDecimal balance2 = AccountsHelper.getBalanceForCustomerPartyId(customerPartyId, organizationPartyId, "ACTUAL", now, delegator);
assertEquals("Balance for " + customerPartyId + " has not increased by 77.95", balance2.subtract(new BigDecimal("77.95")), balance1);
Map afterSettingInvoiceReadyBalances = financialAsserts.getFinancialBalances(now);
Map expectedBalanceChanges = UtilMisc.toMap("ACCOUNTS_RECEIVABLE", "77.95");
Map accountMap = UtilFinancial.replaceGlAccountTypeWithGlAccountForOrg(organizationPartyId, expectedBalanceChanges, delegator);
assertMapDifferenceCorrect(initialBalances, afterSettingInvoiceReadyBalances, accountMap);
// create payment and set it to received
String paymentId = financialAsserts.createPaymentAndApplication(new BigDecimal("77.95"), customerPartyId, organizationPartyId, "CUSTOMER_PAYMENT", "COMPANY_CHECK", null, invoiceId, "PMNT_NOT_PAID");
financialAsserts.updatePaymentStatus(paymentId, "PMNT_RECEIVED");
Invoice invoice = repository.getInvoiceById(invoiceId);
assertNotNull("Invoice with ID [" + invoiceId + "] not found.", invoice);
assertEquals("Invoice with ID [" + invoiceId + "] should have the INVOICE_PAID status", "INVOICE_PAID", invoice.getString("statusId"));
now = UtilDateTime.nowTimestamp();
BigDecimal balance3 = AccountsHelper.getBalanceForCustomerPartyId(customerPartyId, organizationPartyId, "ACTUAL", now, delegator);
assertEquals("Balance for " + customerPartyId + " has not decrease by 77.95", balance3.add(new BigDecimal("77.95")), balance2);
// get the transactions for payment with the assistance of our start timestamp
Set<String> transactions = getAcctgTransSinceDate(UtilMisc.toList(EntityCondition.makeCondition("paymentId", EntityOperator.EQUALS, paymentId)), start, delegator);
assertNotEmpty(paymentId + " transaction not created.", transactions);
// assert transaction equivalence with the reference payment transaction
assertTransactionEquivalenceIgnoreParty(transactions, UtilMisc.toList("PMT_CUST_TEST-2"));
Map afterSettingPaymentReceivedBalances = financialAsserts.getFinancialBalances(UtilDateTime.nowTimestamp());
expectedBalanceChanges = UtilMisc.toMap("ACCOUNTS_RECEIVABLE", "-77.95", "UNDEPOSITED_RECEIPTS", "77.95");
accountMap = UtilFinancial.replaceGlAccountTypeWithGlAccountForOrg(organizationPartyId, expectedBalanceChanges, delegator);
assertMapDifferenceCorrect(afterSettingInvoiceReadyBalances, afterSettingPaymentReceivedBalances, accountMap);
pause("avoid having two invoice status with same timestamp");
// void the payment
start = UtilDateTime.nowTimestamp();
Map<String, Object> input = UtilMisc.toMap("userLogin", demofinadmin, "paymentId", paymentId);
runAndAssertServiceSuccess("voidPayment", input);
// check that the reference invoice status changed back to INVOICE_READY
invoice = repository.getInvoiceById(invoiceId);
assertNotNull("Invoice with ID [" + invoiceId + "] not found.", invoice);
assertEquals("Invoice with ID [" + invoiceId + "] should have the INVOICE_READY status", "INVOICE_READY", invoice.getString("statusId"));
// verify that the balance for the customer has increased by 77.95
now = UtilDateTime.nowTimestamp();
BigDecimal balance4 = AccountsHelper.getBalanceForCustomerPartyId(customerPartyId, organizationPartyId, "ACTUAL", now, delegator);
assertEquals("Balance for " + customerPartyId + " has not increased by 77.95", balance3, balance4.subtract(new BigDecimal("77.95")));
// get the transactions for payment with the assistance of our start timestamp
transactions = getAcctgTransSinceDate(UtilMisc.toList(EntityCondition.makeCondition("paymentId", EntityOperator.EQUALS, paymentId)), start, delegator);
assertNotEmpty(paymentId + " payment void transactions not created.", transactions);
// assert transaction equivalence with the reference PMT_CUST_TEST-2R transaction
assertTransactionEquivalenceIgnoreParty(transactions, UtilMisc.toList("PMT_CUST_TEST-2R"));
// verify that the balance for ACCOUNTS_RECEIVABLE has increased by 77.95, and the balance for UNDEPOSITED_RECEIPTS has decreased by 77.95
Map finalBalances = financialAsserts.getFinancialBalances(UtilDateTime.nowTimestamp());
expectedBalanceChanges = UtilMisc.toMap("ACCOUNTS_RECEIVABLE", "77.95", "UNDEPOSITED_RECEIPTS", "-77.95");
accountMap = UtilFinancial.replaceGlAccountTypeWithGlAccountForOrg(organizationPartyId, expectedBalanceChanges, delegator);
assertMapDifferenceCorrect(afterSettingPaymentReceivedBalances, finalBalances, accountMap);
}
/**
* This test verifies what happens when you write off an invoice.
* 1 - get the initial balance for the customer and financial balances
* 2 - create a invoice and set status to INVOICE_WRITEOFF
* 3 - get the new balance for customer DemoAccount1 and financial balances
* 4 - verify that the balance for the customer has decreased by 77.95
* 5 - verify that the balance for ACCOUNTS_RECEIVABLE has decreased by 77.95, and the balance for ACCTRECV_WRITEOFF has increased by 77.95
*
* @throws GeneralException if an error occurs
*/
@SuppressWarnings("unchecked")
public void testInvoiceWriteOff() throws GeneralException {
String customerPartyId = createPartyFromTemplate("DemoAccount1", "Account for testInvoiceWriteOff");
// before we begin, note the time so we can easily find the transaction
Timestamp start = UtilDateTime.nowTimestamp();
Timestamp now = start;
// note the initial balances
FinancialAsserts financialAsserts = new FinancialAsserts(this, organizationPartyId, demofinadmin);
Map initialBalances = financialAsserts.getFinancialBalances(start);
BigDecimal balance1 = AccountsHelper.getBalanceForCustomerPartyId(customerPartyId, organizationPartyId, "ACTUAL", now, delegator);
// create invoice and set it to ready
String invoiceId = financialAsserts.createInvoice(customerPartyId, "SALES_INVOICE", UtilDateTime.nowTimestamp(), null, null, null);
financialAsserts.createInvoiceItem(invoiceId, "INV_FPROD_ITEM", "GZ-1000", new BigDecimal("2.0"), new BigDecimal("15.0"));
financialAsserts.createInvoiceItem(invoiceId, "ITM_PROMOTION_ADJ", "GZ-1000", new BigDecimal("1.0"), new BigDecimal("-10.0"));
financialAsserts.createInvoiceItem(invoiceId, "INV_FPROD_ITEM", "GZ-1001", new BigDecimal("1.0"), new BigDecimal("45.0"));
financialAsserts.createInvoiceItem(invoiceId, "ITM_SHIPPING_CHARGES", null, null, new BigDecimal("12.95"));
financialAsserts.updateInvoiceStatus(invoiceId, "INVOICE_READY");
now = UtilDateTime.nowTimestamp();
BigDecimal balance2 = AccountsHelper.getBalanceForCustomerPartyId(customerPartyId, organizationPartyId, "ACTUAL", now, delegator);
assertEquals("Balance for " + customerPartyId + " should increase by 77.95", balance2.subtract(balance1), new BigDecimal("77.95"));
Map afterSettingInvoiceReadyBalances = financialAsserts.getFinancialBalances(now);
Map expectedBalanceChanges = UtilMisc.toMap("ACCOUNTS_RECEIVABLE", "77.95");
Map accountMap = UtilFinancial.replaceGlAccountTypeWithGlAccountForOrg(organizationPartyId, expectedBalanceChanges, delegator);
assertMapDifferenceCorrect(initialBalances, afterSettingInvoiceReadyBalances, accountMap);
// Update the Invoice status to INVOICE_WRITEOFF
start = UtilDateTime.nowTimestamp();
financialAsserts.updateInvoiceStatus(invoiceId, "INVOICE_WRITEOFF");
// verify that the balance for the customer has decreased by 77.95
now = UtilDateTime.nowTimestamp();
BigDecimal balance3 = AccountsHelper.getBalanceForCustomerPartyId(customerPartyId, organizationPartyId, "ACTUAL", now, delegator);
assertEquals("Balance for " + customerPartyId + " has not decrease by 77.95", balance3.subtract(balance2), new BigDecimal("-77.95"));
// get the transactions for INV_SALES_TEST-3 with the assistance of our start timestamp
Set<String> transactions = getAcctgTransSinceDate(UtilMisc.toList(EntityCondition.makeCondition("invoiceId", EntityOperator.EQUALS, invoiceId),
EntityCondition.makeCondition("acctgTransTypeId", EntityOperator.EQUALS, "WRITEOFF"),
EntityCondition.makeCondition("glFiscalTypeId", EntityOperator.NOT_EQUAL, "REFERENCE")), start, delegator);
assertNotEmpty(invoiceId + " invoice write off transactions not created.", transactions);
// assert transaction equivalence with the reference INV_SALES_TEST-3WO transaction
assertTransactionEquivalence(transactions, UtilMisc.toList("INV_SALES_TEST-3WO"));
// figure out what the sales invoice writeoff account is using the domain
DomainsDirectory dd = new DomainsLoader(new Infrastructure(dispatcher), new User(demofinadmin)).loadDomainsDirectory();
LedgerRepositoryInterface ledgerRepository = dd.getLedgerDomain().getLedgerRepository();
InvoiceAdjustmentGlAccount writeoffGlAcct = ledgerRepository.getInvoiceAdjustmentGlAccount(organizationPartyId, "SALES_INVOICE", "WRITEOFF");
assertNotNull(writeoffGlAcct);
// verify that the balance for ACCOUNTS_RECEIVABLE has decreased by 77.95, and the balance for ACCTRECV_WRITEOFF has increased by 77.95
Map afterWritingOffInvoiceBalances = financialAsserts.getFinancialBalances(UtilDateTime.nowTimestamp());
expectedBalanceChanges = UtilMisc.toMap("ACCOUNTS_RECEIVABLE", "-77.95");
accountMap = UtilFinancial.replaceGlAccountTypeWithGlAccountForOrg(organizationPartyId, expectedBalanceChanges, delegator);
accountMap.put(writeoffGlAcct.getGlAccountId(), "77.95");
assertMapDifferenceCorrect(afterSettingInvoiceReadyBalances, afterWritingOffInvoiceBalances, accountMap);
}
/**
* Test for purchase invoice and vendor payment.
* Note: this test relies on the status of previously created Invoices so it will fail if you run
* it a second time without rebuilding the DB
* @throws GeneralException if an error occurs
*/
@SuppressWarnings("unchecked")
public void testPurchaseInvoicePayment() throws GeneralException {
DomainsDirectory dd = new DomainsLoader(new Infrastructure(dispatcher), new User(demofinadmin)).loadDomainsDirectory();
InvoiceRepositoryInterface repository = dd.getBillingDomain().getInvoiceRepository();
// before we begin, note the time so we can easily find the transaction
Timestamp start = UtilDateTime.nowTimestamp();
Timestamp now = start;
// note the initial balances
String supplierPartyId = createPartyFromTemplate("DemoSupplier", "Supplier for testPurchaseInvoicePayment");
FinancialAsserts financialAsserts = new FinancialAsserts(this, organizationPartyId, demofinadmin);
Map initialBalances = financialAsserts.getFinancialBalances(start);
BigDecimal balance1 = AccountsHelper.getBalanceForCustomerPartyId(supplierPartyId, organizationPartyId, "ACTUAL", now, delegator);
// create invoice
String invoiceId = financialAsserts.createInvoice(supplierPartyId, "PURCHASE_INVOICE", UtilDateTime.nowTimestamp(), null, null, null);
financialAsserts.createInvoiceItem(invoiceId, "PINV_FPROD_ITEM", "GZ-1000", new BigDecimal("100.0"), new BigDecimal("4.56"));
financialAsserts.createInvoiceItem(invoiceId, "PITM_SHIP_CHARGES", new BigDecimal("1.0"), new BigDecimal("13.95"));
financialAsserts.createInvoiceItem(invoiceId, "PINV_SUPLPRD_ITEM", new BigDecimal("1.0"), new BigDecimal("56.78"));
// Check the invoice current status
Invoice invoice = repository.getInvoiceById(invoiceId);
assertNotNull("Invoice with ID [" + invoiceId + "] not found.", invoice);
assertEquals("Invoice with ID [" + invoiceId + "] should have the INVOICE_IN_PROCESS status", "INVOICE_IN_PROCESS", invoice.getString("statusId"));
// Update the Invoice status
financialAsserts.updateInvoiceStatus(invoiceId, "INVOICE_READY");
now = UtilDateTime.nowTimestamp();
BigDecimal balance2 = AccountsHelper.getBalanceForVendorPartyId(supplierPartyId, organizationPartyId, "ACTUAL", now, delegator);
assertEquals("Balance for " + supplierPartyId + " has not increase by 526.73", balance1, balance2.subtract(new BigDecimal("526.73")));
// get the transactions for INV_PURCH_TEST-1 with the assistance of our start timestamp
Set<String> transactions = getAcctgTransSinceDate(UtilMisc.toList(EntityCondition.makeCondition("invoiceId", EntityOperator.EQUALS, invoiceId)), start, delegator);
assertNotEmpty(invoiceId + " transaction not created.", transactions);
// assert transaction equivalence with the reference INV_PURCH_TEST-1 transaction
assertTransactionEquivalenceIgnoreParty(transactions, UtilMisc.toList("INV_PURCH_TEST-1"));
Map halfBalances = financialAsserts.getFinancialBalances(UtilDateTime.nowTimestamp());
Map expectedBalanceChanges = UtilMisc.toMap("ACCOUNTS_PAYABLE", "-526.73", "UNINVOICED_SHIP_RCPT", "456.0");
Map accountMap = UtilFinancial.replaceGlAccountTypeWithGlAccountForOrg(organizationPartyId, expectedBalanceChanges, delegator);
accountMap.putAll(UtilMisc.toMap("510000", "13.95", "650000", "56.78"));
assertMapDifferenceCorrect(initialBalances, halfBalances, accountMap);
// create payment and set it to sent
String paymentId = financialAsserts.createPaymentAndApplication(new BigDecimal("526.73"), organizationPartyId, supplierPartyId, "VENDOR_PAYMENT", "COMPANY_CHECK", "COCHECKING", invoiceId, "PMNT_NOT_PAID");
financialAsserts.updatePaymentStatus(paymentId, "PMNT_SENT");
invoice = repository.getInvoiceById(invoiceId);
assertNotNull("Invoice with ID [" + invoiceId + "] not found.", invoice);
assertEquals("Invoice with ID [" + invoiceId + "] should have the INVOICE_PAID status", "INVOICE_PAID", invoice.getString("statusId"));
now = UtilDateTime.nowTimestamp();
BigDecimal balance3 = AccountsHelper.getBalanceForVendorPartyId(supplierPartyId, organizationPartyId, "ACTUAL", now, delegator);
assertEquals("Balance for " + supplierPartyId + " has not decrease by 526.73", balance2, balance3.add(new BigDecimal("526.73")));
// get the transactions for PMT_VEND_TEST-1 with the assistance of our start timestamp
transactions = getAcctgTransSinceDate(UtilMisc.toList(EntityCondition.makeCondition("paymentId", EntityOperator.EQUALS, paymentId)), start, delegator);
assertNotEmpty(paymentId + " transaction not created.", transactions);
// assert transaction equivalence with the reference PMT_VEND_TEST-1 transaction
assertTransactionEquivalenceIgnoreParty(transactions, UtilMisc.toList("PMT_VEND_TEST-1"));
Map finalBalances = financialAsserts.getFinancialBalances(UtilDateTime.nowTimestamp());
expectedBalanceChanges = UtilMisc.toMap("ACCOUNTS_PAYABLE", "526.73");
accountMap = UtilFinancial.replaceGlAccountTypeWithGlAccountForOrg(organizationPartyId, expectedBalanceChanges, delegator);
assertMapDifferenceCorrect(halfBalances, finalBalances, accountMap);
}
/**
* Finance charges test:
* Setup
* 1. Create sales invoice (#1) from Company to customer1PartyId for 1 item of $100, invoiceDate = 60 days before today. Set invoice to ready.
* 2. Create sales invoice (#2) from Company to customer2PartyId for 2 items of $250 each, invoiceDate = 45 days before today. Set invoice to ready.
* 3. Create sales invoice (#3) from Company to customer1PartyId for 1 item of $250, invoiceDate = 20 days before today. Set invoice to ready.
* 4. Create sales invoice (#4) from Company to DemoPrivilegedCust for 2 items of $567.89 each, invoiceDate = 60 days before today. Set invoice to ready
* Verify basic interest calculations
* 5. Run AccountHelper.calculateFinanceCharges with grace period = 30 days and interest rate = 8.0 and verify that the results are:
* Invoice #1 - finance charge of $0.66 ((60 - 30) / 365.25 * 0.08 * 100)
* Invoice #2 - finance charge of $1.64 ((45 - 30) / 365.25 * 0.08 * 500)
* Invoice #4 - finance charge of $7.46 ((60 - 30) / 365.25 * 0.08 * 1135.78)
* Verify party classification filtering
* 6. Run AccountsHelper.calculateFinanceCharges with grace period = 30 days, interest rate = 8.0, and partyClassificationGroup = Prileged Customers, verify that:
* Only Invoice #4 shows up as before
* Verify party filtering
* 7. Run AccountsHelper.calculateFinanceCharges with grace period = 30 days, interest rate = 8.0, and partyId = DemoAccount1, verify that:
* Only Invoice #1 shows up as before
* Verify that writing off an invoice will not cause more finance charges to be collected
* 8. Set Invoice #1 status to INVOICE_WRITEOFF, Run AccountHelper.calculateFinanceCharges with grace period = 30 days and interest rate = 8.0 and verify that the results are:
* Verify only Invoice #2 and #4 show up now with amounts as above
* Verify that creating finance charges will create the right financial balance transactions
* 9. Get INTRSTINC_RECEIVABLE and INTEREST_INCOME balance for the Company and the Accounts balance for DemoCustCompany and DemoPrivilegedCust
* Run financials.createInterestInvoice on each of the invoice from step (8).
* Verify that INTRSTINC_RECEIVABLE and INTEREST_INCOME have both increased by $9.10, the balance of DemoCustCompany has increased by $1.64, the balance of DemoPrivilegedCust has increassed by $7.46
* Verify the next cycle's interest calculations are correct
* 10. Run AccountsHelper.calculateFinanceCharges 30 days further in the future (asOfDateTime parameter), and verify that the results are:
* Invoice #2 - previous finance charges = $1.64, new finance charges of $3.29 ((75 - 30) * 365.25 * 0.08 * 500 - 1.64)
* Invoice #4 - previous finance charges = $7.46, new finance charges of $7.47 ((90 - 30) * 365.25 * 0.08 * 1135.78 - 7.46)
* Verify that writing off a finance charge has the right effect on both accounting and on interest calculations
* 11. Get INTRSTINC_RECEIVABLE and the interest invoice writeoff account balances for Company and the Accounts balance for DemoPrivilegedCust.
* Write off the finance charge (invoice) created for DemoPrivilegedCust in step (9)
* Verify that both INTRSTINC_RECEIVABLE and invoice writeoff account balances have increased by $7.46
* 12. Run AccountsHelper.calculateFinanceCharges 30 days further in the future (asOfDateTime parameter), and verify that the results are:
* Invoice #2 - previous finance charges = $1.64, new finance charges of $3.29 ((75 - 30) * 365.25 * 0.08 * 500 - 1.64)
* Invoice #4 - previous finance charges = $0.00, new finance charges of $14.93 ((90 - 30) * 365.25 * 0.08 * 1135.78)
* Verify that payments would serve to reduce invoice finance charges //
* 13. Create customer payment for $250 from DemoPrivilegedCust to Company and apply it to invoice #4. Set the payment to RECEIVED.
* Run AccountsHelper.calculateFinanceCharges 30 days further in the future (asOfDateTime parameter), and verify that the results are:
* Invoice #2 - previous finance charges = $1.64, new finance charges of $3.29 ((75 - 30) * 365.25 * 0.08 * 500 - 1.64)
* Invoice #4 - previous finance charges = $0, new finance charges of $11.64 ((90 - 30) * 365.25 * 0.08 * 885.78)
*
* @throws GeneralException if an error occurs
*/
@SuppressWarnings("unchecked")
public void testFinanceCharges() throws GeneralException {
FinancialAsserts fa = new FinancialAsserts(this, organizationPartyId, demofinadmin);
/*
* Create sales invoice (#1) from Company to DemoAccount1
* for 1 item of $100, invoiceDate = 60 days before today.
* Set invoice to ready.
*/
String customer1PartyId = createPartyFromTemplate("DemoAccount1", "Account1 for testFinanceCharges");
String customer2PartyId = createPartyFromTemplate("DemoCustCompany", "Account2 for testFinanceCharges");
String invoiceId1 = fa.createInvoice(customer1PartyId, "SALES_INVOICE", UtilDateTime.adjustTimestamp(UtilDateTime.nowTimestamp(), Calendar.DAY_OF_YEAR, -60, timeZone, locale));
fa.createInvoiceItem(invoiceId1, "INV_FPROD_ITEM", "WG-1111", new BigDecimal("1.0"), new BigDecimal("100.0"));
// set invoice status to READY is successful
fa.updateInvoiceStatus(invoiceId1, "INVOICE_READY");
/*
* Create sales invoice (#2) from Company to DemoCustCompany
* for 2 items of $250 each, invoiceDate = 45 days before today.
* Set invoice to ready.
*/
String invoiceId2 = fa.createInvoice(customer2PartyId, "SALES_INVOICE", UtilDateTime.adjustTimestamp(UtilDateTime.nowTimestamp(), Calendar.DAY_OF_YEAR, -45, timeZone, locale));
fa.createInvoiceItem(invoiceId2, "INV_FPROD_ITEM", "WG-1111", new BigDecimal("2.0"), new BigDecimal("250.0"));
// set invoice status to READY is successful
fa.updateInvoiceStatus(invoiceId2, "INVOICE_READY");
/*
* Create sales invoice (#3) from Company to DemoAccount1
* for 1 item of $250, invoiceDate = 20 days before today.
* Set invoice to ready.
*/
String invoiceId3 = fa.createInvoice(customer1PartyId, "SALES_INVOICE", UtilDateTime.adjustTimestamp(UtilDateTime.nowTimestamp(), Calendar.DAY_OF_YEAR, -20, timeZone, locale));
fa.createInvoiceItem(invoiceId3, "INV_FPROD_ITEM", "WG-1111", new BigDecimal("1.0"), new BigDecimal("250.0"));
// set invoice status to READY is successful
fa.updateInvoiceStatus(invoiceId3, "INVOICE_READY");
/*
* Create sales invoice (#4) from Company to DemoPrivilegedCust
* for 2 items of $567.89 each, invoiceDate = 60 days before today.
* Set invoice to ready
*/
String invoiceId4 = fa.createInvoice("DemoPrivilegedCust", "SALES_INVOICE", UtilDateTime.adjustTimestamp(UtilDateTime.nowTimestamp(), Calendar.DAY_OF_YEAR, -60, timeZone, locale));
fa.createInvoiceItem(invoiceId4, "INV_FPROD_ITEM", "WG-1111", new BigDecimal("2.0"), new BigDecimal("567.89"));
// set invoice status to READY is successful
fa.updateInvoiceStatus(invoiceId4, "INVOICE_READY");
/*
* Verify basic interest calculations
* Run AccountHelper.calculateFinanceCharges with grace
* period = 30 days and interest rate = 8.0
*/
InvoiceRepository repository = new InvoiceRepository(delegator);
Map<Invoice, Map<String, BigDecimal>> financeCharges = AccountsHelper.calculateFinanceCharges(delegator, organizationPartyId, null, null, new BigDecimal("8.0"), UtilDateTime.nowTimestamp(), 30, timeZone, locale);
Invoice invoice1 = repository.getInvoiceById(invoiceId1);
Invoice invoice2 = repository.getInvoiceById(invoiceId2);
Invoice invoice4 = repository.getInvoiceById(invoiceId4);
// Note that these and all the tests below have a subtle test of the hashCode() function for the Invoice object, as
// the Invoices are not the same Java objects but are two objects of the same invoice, but if their hashCode() are
// equal, then they should be equal, and the Map get method should still work.
/*
* verify that the results are:
* Invoice #1 - finance charge of $0.66 ((60 - 30) / 365.25 * 0.08 * 100)
* Invoice #2 - finance charge of $1.64 ((45 - 30) / 365.25 * 0.08 * 500)
* Invoice #4 - finance charge of $7.46 ((60 - 30) / 365.25 * 0.08 * 1135.78)
*/
Map<String, BigDecimal> expectedFinanceCharges = UtilMisc.toMap(invoice1.getInvoiceId(), new BigDecimal("0.66"), invoice2.getInvoiceId(), new BigDecimal("1.64"), invoice4.getInvoiceId(), new BigDecimal("7.46"));
fa.assertFinanceCharges(financeCharges, expectedFinanceCharges);
/*
* Verify party classification filtering
* Run AccountsHelper.calculateFinanceCharges with grace
* period = 30 days, interest rate = 8.0, and
* partyClassificationGroup = Prileged Customers
*/
financeCharges = AccountsHelper.calculateFinanceCharges(delegator, organizationPartyId, null, "PRIVILEGED_CUSTOMERS", new BigDecimal("8.0"), UtilDateTime.nowTimestamp(), 30, timeZone, locale);
/*
* verify that:
* Only Invoice #4 shows up as before
*/
expectedFinanceCharges = UtilMisc.toMap(invoice1.getInvoiceId(), null, invoice2.getInvoiceId(), null, invoice4.getInvoiceId(), new BigDecimal("7.46"));
fa.assertFinanceCharges(financeCharges, expectedFinanceCharges);
/*
* Verify party filtering
* Run AccountsHelper.calculateFinanceCharges with grace
* period = 30 days, interest rate = 8.0, and
* partyId = DemoAccount1
*/
financeCharges = AccountsHelper.calculateFinanceCharges(delegator, organizationPartyId, customer1PartyId, null, new BigDecimal("8.0"), UtilDateTime.nowTimestamp(), 30, timeZone, locale);
/*
* verify that:
* Only Invoice #1 shows up as before
*/
expectedFinanceCharges = UtilMisc.toMap(invoice1.getInvoiceId(), new BigDecimal("0.66"), invoice2.getInvoiceId(), null, invoice4.getInvoiceId(), null);
fa.assertFinanceCharges(financeCharges, expectedFinanceCharges);
/*
* Verify that writing off an invoice will not
* cause more finance charges to be collected
* Set Invoice #1 status to INVOICE_WRITEOFF,
* Run AccountHelper.calculateFinanceCharges with grace
* period = 30 days and interest rate = 8.0
*/
fa.updateInvoiceStatus(invoiceId1, "INVOICE_WRITEOFF");
financeCharges = AccountsHelper.calculateFinanceCharges(delegator, organizationPartyId, null, null, new BigDecimal("8.0"), UtilDateTime.nowTimestamp(), 30, timeZone, locale);
/*
* Verify only Invoice #2 and #4
* show up now with amounts as above
*/
expectedFinanceCharges = UtilMisc.toMap(invoice1.getInvoiceId(), null, invoice2.getInvoiceId(), new BigDecimal("1.64"), invoice4.getInvoiceId(), new BigDecimal("7.46"));
fa.assertFinanceCharges(financeCharges, expectedFinanceCharges);
/*
* Verify that creating finance charges will
* create the right financial balance transactions
* Get ACCOUNTS_RECEIVABLE and INTEREST_INCOME
* balance for the Company and the Accounts balance
* for DemoCustCompany and DemoPrivilegedCust
* Run financials.createInterestInvoice on each
* of the invoice from step (8).
*/
Timestamp now = UtilDateTime.nowTimestamp();
FinancialAsserts financialAsserts = new FinancialAsserts(this, organizationPartyId, demofinadmin);
BigDecimal balance1_democustcompany = AccountsHelper.getBalanceForCustomerPartyId(customer2PartyId, organizationPartyId, "ACTUAL", now, delegator);
BigDecimal balance1_demoprivilegedcust = AccountsHelper.getBalanceForCustomerPartyId("DemoPrivilegedCust", organizationPartyId, "ACTUAL", now, delegator);
Map initialBalances = financialAsserts.getFinancialBalances(now);
financeCharges = AccountsHelper.calculateFinanceCharges(delegator, organizationPartyId, null, null, new BigDecimal("8.0"), now, 30, timeZone, locale);
Map<String, BigDecimal> financeCharge = financeCharges.get(invoice2);
Map<String, Object> input = new HashMap<String, Object>();
input.put("userLogin", demofinadmin);
input.put("partyIdFrom", invoice2.get("partyIdFrom"));
input.put("partyIdTo", invoice2.get("partyId"));
input.put("amount", financeCharge.get("interestAmount"));
input.put("currencyUomId", invoice2.get("currencyUomId"));
input.put("invoiceDate", now);
input.put("dueDate", invoice2.get("dueDate"));
input.put("description", invoice2.get("description"));
input.put("parentInvoiceId", invoice2.get("invoiceId"));
Map<String, Object> output = runAndAssertServiceSuccess("financials.createInterestInvoice", input);
financeCharge = financeCharges.get(invoice4);
input = new HashMap<String, Object>();
input.put("userLogin", demofinadmin);
input.put("partyIdFrom", invoice4.get("partyIdFrom"));
input.put("partyIdTo", invoice4.get("partyId"));
input.put("amount", financeCharge.get("interestAmount"));
input.put("currencyUomId", invoice4.get("currencyUomId"));
input.put("invoiceDate", now);
input.put("dueDate", invoice4.get("dueDate"));
input.put("description", invoice4.get("description"));
input.put("parentInvoiceId", invoice4.get("invoiceId"));
output = runAndAssertServiceSuccess("financials.createInterestInvoice", input);
String invoiceId4Interest = (String) output.get("invoiceId");
// reload invoices (to get the updated interest charged)
invoice2 = repository.getInvoiceById(invoiceId2);
invoice4 = repository.getInvoiceById(invoiceId4);
/*
* Verify that INTRSTINC_RECEIVABLE and INTEREST_INCOME
* have both increased by $9.10, the balance of
* DemoCustCompany has increased by $1.64, the
* balance of DemoPrivilegedCust has increassed by $7.46
*/
now = UtilDateTime.nowTimestamp();
BigDecimal balance2_democustcompany = AccountsHelper.getBalanceForCustomerPartyId(customer2PartyId, organizationPartyId, "ACTUAL", now, delegator);
BigDecimal balance2_demoprivilegedcust = AccountsHelper.getBalanceForCustomerPartyId("DemoPrivilegedCust", organizationPartyId, "ACTUAL", now, delegator);
assertEquals("the balance of DemoCustCompany should increased by $1.64",
balance2_democustcompany, balance1_democustcompany.add(new BigDecimal("1.64")));
assertEquals("the balance of DemoPrivilegedCust should increased by $7.46",
balance2_demoprivilegedcust, balance1_demoprivilegedcust.add(new BigDecimal("7.46")));
Map finalBalances = financialAsserts.getFinancialBalances(now);
Map expectedBalanceChanges = UtilMisc.toMap("INTRSTINC_RECEIVABLE", "9.10", "INTEREST_INCOME", "9.10");
Map accountMap = UtilFinancial.replaceGlAccountTypeWithGlAccountForOrg(organizationPartyId, expectedBalanceChanges, delegator);
assertMapDifferenceCorrect(initialBalances, finalBalances, accountMap);
/*
* Verify the next cycle's interest calculations are
* correct. Run AccountsHelper.calculateFinanceCharges 30
* days further in the future (asOfDateTime parameter)
*/
financeCharges = AccountsHelper.calculateFinanceCharges(delegator, organizationPartyId, null, null, new BigDecimal("8.0"),
UtilDateTime.adjustTimestamp(UtilDateTime.nowTimestamp(), Calendar.DAY_OF_YEAR, 30, timeZone, locale), 30, timeZone, locale);
/*
* verify that the results are:
* Invoice #2 - previous finance charges = $1.64,
* new finance charges of $3.29 ((75 - 30) * 365.25 * 0.08 * 500 - 1.64)
* Invoice #4 - previous finance charges = $7.46,
* new finance charges of $7.47 ((90 - 30) * 365.25 * 0.08 * 1135.78 - 7.46)
*/
financeCharge = financeCharges.get(invoice2);
assertNotNull("invoice #2 [" + invoice2.getInvoiceId() + "] basic interest calculations", financeCharge);
assertEquals("invoice #2 [" + invoice2.getInvoiceId() + "] basic interest calculations", new BigDecimal("3.29"), financeCharge.get("interestAmount"));
financeCharge = financeCharges.get(invoice4);
assertNotNull("invoice #4 [" + invoice4.getInvoiceId() + "] basic interest calculations", financeCharge);
assertEquals("invoice #4 [" + invoice4.getInvoiceId() + "] basic interest calculations", new BigDecimal("7.47"), financeCharge.get("interestAmount"));
/*
* Verify that writing off a finance charge has the right
* effect on both accounting and on interest calculations
* Get INTRSTINC_RECEIVABLE and interest invoice writeoff
* account balances for Company and the Accounts balance
* for DemoPrivilegedCust. Write off the finance charge
* (invoice) created for DemoPrivilegedCust in step (9)
*/
now = UtilDateTime.nowTimestamp();
balance1_demoprivilegedcust = AccountsHelper.getBalanceForCustomerPartyId("DemoPrivilegedCust", organizationPartyId, "ACTUAL", now, delegator);
initialBalances = financialAsserts.getFinancialBalances(now);
fa.updateInvoiceStatus(invoiceId4Interest, "INVOICE_WRITEOFF");
/*
* Verify that both INTRSTINC_RECEIVABLE and interest invoice writeoff account
* balances have increased by $7.46
*/
now = UtilDateTime.nowTimestamp();
finalBalances = financialAsserts.getFinancialBalances(now);
// figure out what the interest invoice writeoff account is using the domain
DomainsDirectory dd = new DomainsLoader(new Infrastructure(dispatcher), new User(demofinadmin)).loadDomainsDirectory();
LedgerRepositoryInterface ledgerRepository = dd.getLedgerDomain().getLedgerRepository();
InvoiceAdjustmentGlAccount writeoffGlAcct = ledgerRepository.getInvoiceAdjustmentGlAccount(organizationPartyId, "INTEREST_INVOICE", "WRITEOFF");
assertNotNull(writeoffGlAcct);
// interest income receivable is a debit account, so an increase is positive;
// interest income is a credit account, so an increase is negative
expectedBalanceChanges = UtilMisc.toMap("INTRSTINC_RECEIVABLE", "-7.46");
accountMap = UtilFinancial.replaceGlAccountTypeWithGlAccountForOrg(organizationPartyId, expectedBalanceChanges, delegator);
accountMap.put(writeoffGlAcct.getGlAccountId(), "7.46");
assertMapDifferenceCorrect(initialBalances, finalBalances, accountMap);
/*
* Run AccountsHelper.calculateFinanceCharges 30 days further
* in the future (asOfDateTime parameter)
*/
invoice2 = repository.getInvoiceById(invoiceId2);
invoice4 = repository.getInvoiceById(invoiceId4);
financeCharges = AccountsHelper.calculateFinanceCharges(delegator, organizationPartyId, null, null, new BigDecimal("8.0"),
UtilDateTime.adjustTimestamp(UtilDateTime.nowTimestamp(), Calendar.DAY_OF_YEAR, 30, timeZone, locale), 30, timeZone, locale);
/*
* Verify that the results are:
* Invoice #2 - previous finance charges = $1.64,
* new finance charges of $3.29 ((75 - 30) * 365.25 * 0.08 * 500 - 1.64)
* Invoice #4 - previous finance charges = $0.00,
* new finance charges of $14.93 ((90 - 30) * 365.25 * 0.08 * 1135.78)
*/
financeCharge = financeCharges.get(invoice2);
assertNotNull("invoice #2 [" + invoice2.getInvoiceId() + "] basic interest calculations", financeCharge);
assertEquals("invoice #2 [" + invoice2.getInvoiceId() + "] basic interest calculations", new BigDecimal("3.29"), financeCharge.get("interestAmount"));
financeCharge = financeCharges.get(invoice4);
assertNotNull("invoice #4 [" + invoice4.getInvoiceId() + "] basic interest calculations", financeCharge);
assertEquals("invoice #4 [" + invoice4.getInvoiceId() + "] basic interest calculations", new BigDecimal("14.93"), financeCharge.get("interestAmount"));
/*
* Verify that payments would serve to reduce invoice finance charges
* Create customer payment for $250 from DemoPrivilegedCust to Company
* and apply it to invoice #4. Set the payment to RECEIVED.
* Run AccountsHelper.calculateFinanceCharges 30 days further in the
* future (asOfDateTime parameter)
*/
financialAsserts.createPaymentAndApplication(new BigDecimal("250.0"), "DemoPrivilegedCust", organizationPartyId, "CUSTOMER_PAYMENT", "CREDIT_CARD", null, invoiceId4, "PMNT_RECEIVED");
invoice2 = repository.getInvoiceById(invoiceId2);
invoice4 = repository.getInvoiceById(invoiceId4);
financeCharges = AccountsHelper.calculateFinanceCharges(delegator, organizationPartyId, null, null, new BigDecimal("8.0"),
UtilDateTime.adjustTimestamp(UtilDateTime.nowTimestamp(), Calendar.DAY_OF_YEAR, 30, timeZone, locale), 30, timeZone, locale);
/*
* Verify that the results are:
* Invoice #2 - previous finance charges = $1.64,
* new finance charges of $3.29 ((75 - 30) * 365.25 * 0.08 * 500 - 1.64)
* Invoice #4 - previous finance charges = $0,
* new finance charges of $11.64 ((90 - 30) * 365.25 * 0.08 * 885.78)
*/
financeCharge = financeCharges.get(invoice2);
assertNotNull("invoice #2 [" + invoice2.getInvoiceId() + "] basic interest calculations", financeCharge);
assertEquals("invoice #2 [" + invoice2.getInvoiceId() + "] basic interest calculations", new BigDecimal("3.29"), financeCharge.get("interestAmount"));
financeCharge = financeCharges.get(invoice4);
assertNotNull("invoice #4 [" + invoice4.getInvoiceId() + "] basic interest calculations", financeCharge);
assertEquals("invoice #4 [" + invoice2.getInvoiceId() + "] basic interest calculations", new BigDecimal("11.64"), financeCharge.get("interestAmount"));
}
/**
* Void invoice test:
* 1. Create a sales invoice to DemoCustCompany with 2 invoice items: (a) 2.0 x "Finished good" type for $50 and (b) 1.0 "Shipping and handling" for $9.95
* 2. Get the AccountsHelper customer receivable balance of DemoCustCompany
* 3. Get the initial financial balances
* 4. Set invoice to READY
* 5. Verify that the AccountsHelper customer balance of DemoCustCompany has increased by 109.95
* 6. Verify that the balance of gl accounts 120000 increased by 109.95, 400000 increased by 100, 408000 increased by 9.95
* 7. Verify AccountsHelper.getUnpaidInvoicesForCustomer returns this invoice of list of unpaid invoices
* 8. Set invoice to VOID using opentaps.VoidInvoice service
* 9. Verify that AccountsHelper customer balance of DemoCustCompany is back to value in #2
* 10. Verify that balance of gl accounts 120000, 400000, 408000 are backed to values of #3
* 11. Verify that AccountsHelper.getUnpaidInvoicesForCustomer no longer returns this invoice in list of unpaid invoices
* @throws GeneralException if an error occurs
*/
@SuppressWarnings("unchecked")
public void testVoidInvoice() throws GeneralException {
FinancialAsserts fa = new FinancialAsserts(this, organizationPartyId, demofinadmin);
String companyPartyId = createPartyFromTemplate("DemoCustCompany", "Account for testVoidInvoice");
/*
* 1. Create a sales invoice to the Party with 2
* invoice items: (a) 2.0 x "Finished good" type for $50
* and (b) 1.0 "Shipping and handling" for $9.95
*/
String invoiceId = fa.createInvoice(companyPartyId, "SALES_INVOICE");
fa.createInvoiceItem(invoiceId, "INV_FPROD_ITEM", "WG-1111", new BigDecimal("2.0"), new BigDecimal("50.0"));
fa.createInvoiceItem(invoiceId, "ITM_SHIPPING_CHARGES", new BigDecimal("1.0"), new BigDecimal("9.95"));
/*
* 2. Get the AccountsHelper customer receivable
* balance of the Party
*/
Timestamp now = UtilDateTime.nowTimestamp();
BigDecimal balance1 = AccountsHelper.getBalanceForCustomerPartyId(companyPartyId, organizationPartyId, "ACTUAL", now, delegator);
/*
* 3. Get the initial financial balances
*/
FinancialAsserts financialAsserts = new FinancialAsserts(this, organizationPartyId, demofinadmin);
Map initialBalances = financialAsserts.getFinancialBalances(now);
/*
* 4. Set invoice to READY
*/
fa.updateInvoiceStatus(invoiceId, "INVOICE_READY");
/*
* 5. Verify that the AccountsHelper customer balance of
* the Party has increased by 109.95
*/
now = UtilDateTime.nowTimestamp();
BigDecimal balance2 = AccountsHelper.getBalanceForCustomerPartyId(companyPartyId, organizationPartyId, "ACTUAL", now, delegator);
assertEquals("Balance for " + companyPartyId + " has not increased by 109.95", balance1, balance2.subtract(new BigDecimal("109.95")));
/*
* 6. Verify that the balance of gl accounts 120000 = ACCOUNTS_RECEIVABLE
* increased by 109.95, 400000 = SALES_ACCOUNT increased by 100,
* 408000 = ITM_SHIPPING_CHARGES increased by 9.95
*/
GenericValue invoiceItemTypeForShippingCharges = delegator.findByPrimaryKey("InvoiceItemType", UtilMisc.toMap("invoiceItemTypeId", "ITM_SHIPPING_CHARGES"));
String itemShippingChargesGlAccountId = invoiceItemTypeForShippingCharges.getString("defaultGlAccountId");
Map halfBalances = financialAsserts.getFinancialBalances(now);
Map expectedBalanceChanges = UtilMisc.toMap("ACCOUNTS_RECEIVABLE", "109.95", "SALES_ACCOUNT", "100");
Map accountMap = UtilFinancial.replaceGlAccountTypeWithGlAccountForOrg(organizationPartyId, expectedBalanceChanges, delegator);
accountMap.put(itemShippingChargesGlAccountId, "9.95");
assertMapDifferenceCorrect(initialBalances, halfBalances, accountMap);
/*
* 7. Verify AccountsHelper.getUnpaidInvoicesForCustomer returns this
* invoice of list of unpaid invoices
*/
Map invoices = AccountsHelper.getUnpaidInvoicesForCustomers(organizationPartyId, UtilMisc.toList(new Integer(0)), now, delegator, timeZone, locale);
assertNotNull("Unpaid Invoices For Customers not found.", invoices);
List invoicesList = (List) invoices.get(0);
assertNotNull("Unpaid Invoices For Customers not found.", invoicesList);
Iterator invoicesIterator = invoicesList.iterator();
boolean isPresent = false;
while (invoicesIterator.hasNext()) {
Invoice invoice = (Invoice) invoicesIterator.next();
if (invoiceId.equals(invoice.getString("invoiceId"))) {
isPresent = true;
break;
}
}
assertTrue("Invoice [" + invoiceId + "] is not in the list of unpaid invoiced and shouldn't", isPresent);
/*
* 8. Set invoice to VOID using opentaps.VoidInvoice service
*/
Map<String, Object> input = new HashMap<String, Object>();
input.put("userLogin", demofinadmin);
input.put("invoiceId", invoiceId);
runAndAssertServiceSuccess("opentaps.voidInvoice", input);
/*
* 9. Verify that AccountsHelper customer balance of
* DemoCustCompany is back to value in #2
*/
now = UtilDateTime.nowTimestamp();
BigDecimal balance3 = AccountsHelper.getBalanceForCustomerPartyId(companyPartyId, organizationPartyId, "ACTUAL", now, delegator);
assertEquals("Balance for " + companyPartyId + " is not back to original value", balance1, balance3);
/*
* 10. Verify that balance of gl accounts 120000, 400000, 408000
* are backed to values of #3
*/
Map finalBalances = financialAsserts.getFinancialBalances(now);
expectedBalanceChanges = UtilMisc.toMap("ACCOUNTS_RECEIVABLE", "0", "SALES_ACCOUNT", "0");
accountMap = UtilFinancial.replaceGlAccountTypeWithGlAccountForOrg(organizationPartyId, expectedBalanceChanges, delegator);
accountMap.put(itemShippingChargesGlAccountId, "0");
assertMapDifferenceCorrect(initialBalances, finalBalances, accountMap);
/*
* 11. Verify that AccountsHelper.getUnpaidInvoicesForCustomer no
* longer returns this invoice in list of unpaid invoices
*/
now = UtilDateTime.nowTimestamp();
invoices = AccountsHelper.getUnpaidInvoicesForCustomers(organizationPartyId, UtilMisc.toList(new Integer(0)), now, delegator, timeZone, locale);
assertNotNull("Unpaid Invoices For Customers not found.", invoices);
invoicesList = (List) invoices.get(0);
assertNotNull("Unpaid Invoices For Customers not found.", invoicesList);
invoicesIterator = invoicesList.iterator();
isPresent = false;
while (invoicesIterator.hasNext()) {
Invoice invoice = (Invoice) invoicesIterator.next();
if (invoiceId.equals(invoice.getString("invoiceId"))) {
isPresent = true;
break;
}
}
assertFalse("Invoice [" + invoiceId + "] is in the list of unpaid invoiced and shouldn't", isPresent);
}
/**
* TestBasicInvoiceAdjustment
* 1. Create purchase invoice for $10
* 2. Set invoice to READY
* 3. Get financial balances and the balances
* 4. Create payment of type COMPANY_CHECK for $8 and apply payment to the invoice
* 5. Set payment to SENT
* 6. Verify that the outstanding amount of the invoice is $2 and the status of the invoice is still READY
* 7. Use createInvoiceAdjustment to create an adjustment of type EARLY_PAY_DISCT for -$2 for the invoice and call postAdjustmentToInvoice
* 8. Verify that the outstanding amount of the invoice is $0 and the status of the invoice is PAID
* 8. Find InvoiceAdjustmentGlAccount for PURCHASE_INVOICE and EARLY_PAY_DISCT and get the glAccountId
* 9. Get the financial balances
* 10. Verify the following changes in financial balances: ACCOUNTS_PAYABLE +10, BANK_STLMNT_ACCOUNT -8, InvoiceAdjustmentGlAccount.glAccountId -2
* 11. Verify that the vendor balance has decreased by $10 for the supplier since (4)
* @throws GeneralException if an error occurs
*/
@SuppressWarnings("unchecked")
public void testBasicInvoiceAdjustment() throws GeneralException {
FinancialAsserts fa = new FinancialAsserts(this, organizationPartyId, demofinadmin);
DomainsDirectory dd = new DomainsLoader(new Infrastructure(dispatcher), new User(demofinadmin)).loadDomainsDirectory();
String supplierPartyId = createPartyFromTemplate("DemoSupplier", "Supplier for testBasicInvoiceAdjustment");
// create the purchase invoice
String invoiceId = fa.createInvoice(supplierPartyId, "PURCHASE_INVOICE");
fa.createInvoiceItem(invoiceId, "INV_FPROD_ITEM", "WG-1111", new BigDecimal("1.0"), new BigDecimal("10.0"));
fa.updateInvoiceStatus(invoiceId, "INVOICE_READY");
InvoiceRepositoryInterface repository = dd.getBillingDomain().getInvoiceRepository();
Map initialBalances = fa.getFinancialBalances(UtilDateTime.nowTimestamp());
BigDecimal vendorBalance1 = AccountsHelper.getBalanceForVendorPartyId(supplierPartyId, organizationPartyId, "ACTUAL", UtilDateTime.nowTimestamp(), delegator);
fa.createPaymentAndApplication(new BigDecimal("8.0"), organizationPartyId, supplierPartyId, "VENDOR_PAYMENT", "COMPANY_CHECK", "COCHECKING", invoiceId, "PMNT_SENT");
Invoice invoice = repository.getInvoiceById(invoiceId);
assertEquals("Invoice [" + invoice.getInvoiceId() + "] is still ready", invoice.getStatusId(), "INVOICE_READY");
assertEquals("Invoice [" + invoice.getInvoiceId() + "] outstanding amt is $2", invoice.getOpenAmount(), new BigDecimal("2.0"));
// post an adjustment of -$2 of type EARLY_PAY_DISCT to the invoice
Map results = runAndAssertServiceSuccess("createInvoiceAdjustment", UtilMisc.toMap("userLogin", demofinadmin, "invoiceId", invoiceId, "invoiceAdjustmentTypeId", "EARLY_PAY_DISCT", "adjustmentAmount", new BigDecimal("-2.0")));
String invoiceAdjustmentId = (String) results.get("invoiceAdjustmentId");
assertNotNull(invoiceAdjustmentId);
invoice = repository.getInvoiceById(invoiceId);
assertEquals("Invoice [" + invoice.getInvoiceId() + "] outstanding amt is $0", BigDecimal.ZERO, invoice.getOpenAmount());
assertEquals("Invoice [" + invoice.getInvoiceId() + "] is paid", "INVOICE_PAID", invoice.getStatusId());
GenericValue mapping = delegator.findByPrimaryKey("InvoiceAdjustmentGlAccount", UtilMisc.toMap("invoiceTypeId", "PURCHASE_INVOICE", "invoiceAdjustmentTypeId", "EARLY_PAY_DISCT", "organizationPartyId", organizationPartyId));
assertNotNull(mapping);
String glAccountId = mapping.getString("glAccountId");
assertNotNull(glAccountId);
// ensure the balances are correct
Map finalBalances = fa.getFinancialBalances(UtilDateTime.nowTimestamp());
Map expectedBalanceChanges = UtilMisc.toMap("ACCOUNTS_PAYABLE", "10.0", "BANK_STLMNT_ACCOUNT", "-8");
Map accountMap = UtilFinancial.replaceGlAccountTypeWithGlAccountForOrg(organizationPartyId, expectedBalanceChanges, delegator);
accountMap.put(glAccountId, "-2");
assertMapDifferenceCorrect(initialBalances, finalBalances, accountMap);
BigDecimal vendorBalance2 = AccountsHelper.getBalanceForVendorPartyId(supplierPartyId, organizationPartyId, "ACTUAL", UtilDateTime.nowTimestamp(), delegator);
assertEquals("Vendor balance has decreased by $10", vendorBalance2.subtract(vendorBalance1), new BigDecimal("-10"));
}
/**
* TestInvoiceAdjustmentWithPayment
* 1. Create sales invoice for $10
* 2. Set invoice to READY
* 3. Get financial balances and customer balances
* 4. Create payment of type COMPANY_CHECK for $6 and apply payment to the invoice
* 5. Set payment to RECEIVED
* 6. Use createInvoiceAdjustment to create an adjustment of type CASH_DISCOUNT for -$2 for the invoice and call postAdjustmentToInvoice
* 7. Create payment of type CASH for $2 and apply payment to the invoice
* 8. Verify that the outstanding amount of the invoice is $0 and the status of the invoice is PAID
* 9. Find InvoiceAdjustmentGlAccount for SALES_INVOICE and CASH_DISCOUNT and get the glAccountId
* 10. Get the financial balances and customer balances
* 11. Verify the following changes in financial balances: ACCOUNTS_RECEIVABLE -10, UNDEPOSITED_RECEIPT +8, InvoiceAdjustmentGlAccount.glAccountId -2
* 12. Verify that the customer balance has decreased by $10 for the customer since (4)
* @throws GeneralException if an error occurs
*/
@SuppressWarnings("unchecked")
public void testInvoiceAdjustmentWithPayment() throws GeneralException {
FinancialAsserts fa = new FinancialAsserts(this, organizationPartyId, demofinadmin);
String customerPartyId = createPartyFromTemplate("DemoCustomer", "Customer for testInvoiceAdjustmentWithPayment");
String invoiceId = fa.createInvoice(customerPartyId, "SALES_INVOICE");
fa.createInvoiceItem(invoiceId, "INV_FPROD_ITEM", "WG-1111", new BigDecimal("1.0"), new BigDecimal("10.0"));
fa.updateInvoiceStatus(invoiceId, "INVOICE_READY");
InvoiceRepository repository = new InvoiceRepository(delegator);
Map initialBalances = fa.getFinancialBalances(UtilDateTime.nowTimestamp());
BigDecimal custBalance1 = AccountsHelper.getBalanceForCustomerPartyId(customerPartyId, organizationPartyId, "ACTUAL", UtilDateTime.nowTimestamp(), delegator);
// company check payment from customer of $6
fa.createPaymentAndApplication(new BigDecimal("6.0"), customerPartyId, organizationPartyId, "CUSTOMER_PAYMENT", "COMPANY_CHECK", null, invoiceId, "PMNT_RECEIVED");
Invoice invoice = repository.getInvoiceById(invoiceId);
assertEquals("Invoice [" + invoice.getInvoiceId() + "] is still ready", invoice.getStatusId(), "INVOICE_READY");
assertEquals("Invoice [" + invoice.getInvoiceId() + "] outstanding amt is $4", invoice.getOpenAmount(), new BigDecimal("4.0"));
// post an adjustment of -$2 of type CASH_DISCOUNT to the invoice
Map results = runAndAssertServiceSuccess("createInvoiceAdjustment", UtilMisc.toMap("userLogin", demofinadmin, "invoiceId", invoiceId, "invoiceAdjustmentTypeId", "CASH_DISCOUNT", "adjustmentAmount", new BigDecimal("-2.0")));
String invoiceAdjustmentId = (String) results.get("invoiceAdjustmentId");
assertNotNull(invoiceAdjustmentId);
// another customer payment for the remaining $2, which should pay off the invoice
fa.createPaymentAndApplication(new BigDecimal("2.0"), customerPartyId, organizationPartyId, "CUSTOMER_PAYMENT", "CASH", null, invoiceId, "PMNT_RECEIVED");
invoice = repository.getInvoiceById(invoiceId);
assertEquals("Invoice [" + invoice.getInvoiceId() + "] is paid", "INVOICE_PAID", invoice.getStatusId());
assertEquals("Invoice [" + invoice.getInvoiceId() + "] outstanding amt is $0", BigDecimal.ZERO, invoice.getOpenAmount());
// get the cash discount gl account for sales invoices
GenericValue mapping = delegator.findByPrimaryKey("InvoiceAdjustmentGlAccount", UtilMisc.toMap("invoiceTypeId", "SALES_INVOICE", "invoiceAdjustmentTypeId", "CASH_DISCOUNT", "organizationPartyId", organizationPartyId));
assertNotNull(mapping);
String glAccountId = mapping.getString("glAccountId");
assertNotNull(glAccountId);
// ensure the balances are correct
Map finalBalances = fa.getFinancialBalances(UtilDateTime.nowTimestamp());
Map expectedBalanceChanges = UtilMisc.toMap("ACCOUNTS_RECEIVABLE", "-10.0", "UNDEPOSITED_RECEIPTS", "+8");
Map accountMap = UtilFinancial.replaceGlAccountTypeWithGlAccountForOrg(organizationPartyId, expectedBalanceChanges, delegator);
accountMap.put(glAccountId, "+2");
assertMapDifferenceCorrect(initialBalances, finalBalances, accountMap);
BigDecimal custBalance2 = AccountsHelper.getBalanceForCustomerPartyId(customerPartyId, organizationPartyId, "ACTUAL", UtilDateTime.nowTimestamp(), delegator);
assertEquals("Customer balance has decreased by $10", custBalance2.subtract(custBalance1), new BigDecimal("-10"));
}
/**
*This test checks that payment applications to an adjusted invoice is based on the invoice total including the adjusted amount
*/
public void testPaymentApplicationToAdjustedInvoice() {
// create a customer party
// create sales invoice to the customer for $10
// set the invoice to READY
// create an adjustment of CASH_DISCOUNT of -2 for the invoice
// verify that the invoice total amount is $8
// verify that the invoice outstanding amount is $8
// create a payment (P1) of $4 and apply it to the invoice
// create a second payment (P2) of $5 and apply $4 to the invoice
// verify that the invoice total is still $8 by the outstanding amount is $0
// verify the status of the invoice is PAID
}
/**
* TestAdjustmentToCancelledInvoice: this test should verify that adjustments to cancelled invoices are not posted to the ledger
* 1. Create sales invoice for $10 (do not set to ready)
* 2. Create adjustment of EARLY_PAY_DISCOUNT for $2 on invoice from (1)
* 3. Get financials balances
* 4. Get accounts receivable balances for customer of invoice from (1)
* 5. Set status of invoice from (1) to INVOICE_CANCELLED
* 6. Get financial balances
* 7. Get accounts receivable balances for customer of invoice from (1)
* 8. Verify that the changes in ACCOUNTS_RECEIVABLE and InvoiceAdjustmentGlAccount.glAccountId for Company, EARLY_PAY_DISCOUNT are both 0
* 9. Verify that the change in customer balance for customer is 0
* @throws GeneralException if an error occurs
*/
@SuppressWarnings("unchecked")
public void testAdjustmentToCancelledInvoice() throws GeneralException {
FinancialAsserts fa = new FinancialAsserts(this, organizationPartyId, demofinadmin);
String customerPartyId = createPartyFromTemplate("DemoCustCompany", "Customer for testAdjustmentToCancelledInvoice");
String invoiceId = fa.createInvoice(customerPartyId, "SALES_INVOICE");
fa.createInvoiceItem(invoiceId, "INV_FPROD_ITEM", "WG-1111", new BigDecimal("1.0"), new BigDecimal("10.0"));
// post an adjustment of $2 of type EARLY_PAY_DISCT to the invoice
Map results = runAndAssertServiceSuccess("createInvoiceAdjustment", UtilMisc.toMap("userLogin", demofinadmin, "invoiceId", invoiceId, "invoiceAdjustmentTypeId", "EARLY_PAY_DISCT", "adjustmentAmount", new BigDecimal("2.0")));
String invoiceAdjustmentId = (String) results.get("invoiceAdjustmentId");
assertNotNull(invoiceAdjustmentId);
// get balances, cancel
Map initialBalances = fa.getFinancialBalances(UtilDateTime.nowTimestamp());
BigDecimal custBalances1 = AccountsHelper.getBalanceForCustomerPartyId(customerPartyId, organizationPartyId, "ACTUAL", UtilDateTime.nowTimestamp(), delegator);
fa.updateInvoiceStatus(invoiceId, "INVOICE_CANCELLED");
// get the early pay discount gl account for sales invoices
GenericValue mapping = delegator.findByPrimaryKey("InvoiceAdjustmentGlAccount", UtilMisc.toMap("invoiceTypeId", "SALES_INVOICE", "invoiceAdjustmentTypeId", "EARLY_PAY_DISCT", "organizationPartyId", organizationPartyId));
assertNotNull(mapping);
String glAccountId = mapping.getString("glAccountId");
assertNotNull(glAccountId);
// the pause above should be sufficient to get the final balances
Map finalBalances = fa.getFinancialBalances(UtilDateTime.nowTimestamp());
BigDecimal custBalances2 = AccountsHelper.getBalanceForCustomerPartyId(customerPartyId, organizationPartyId, "ACTUAL", UtilDateTime.nowTimestamp(), delegator);
// check balances are 0.0 throughout
Map expectedBalanceChanges = UtilMisc.toMap("ACCOUNTS_RECEIVABLE", "0");
Map accountMap = UtilFinancial.replaceGlAccountTypeWithGlAccountForOrg(organizationPartyId, expectedBalanceChanges, delegator);
accountMap.put(glAccountId, "0.0");
assertMapDifferenceCorrect(initialBalances, finalBalances, accountMap);
assertEquals("Customer balance has not changed", custBalances2.subtract(custBalances1), BigDecimal.ZERO);
}
/**
* TestAdjustPotVoidForInvoice: test alternate workflow: adjust invoice, post invoice, and void the invoice
* 1. Create sales invoice for $10
* 2. Create adjustment of CASH_DISCOUNT for -$2 on invoice
* 3. Create adjustment of EARLY_PAY_DISCOUNT of -$0.50 on invoice
* 4. Get financials balances
* 5. Get accounts receivables balance for customer of invoice from (1)
* 6. Get InvoiceAdjustmentGlAccount for Company, EARLY_PAY_DISCOUNT and Company, CASH_DISCOUNT
* 7. Set invoice to INVOICE_READY
* 8. Verify ACCOUNTS_RECEIVABLES +7.50, InvoiceAdjustmentGlAccount(Company, CASH_DISCOUNT) +2.0, InvoiceAdjustmentGlAccount(Company, EARLY_PAY_DISCOUNT) +0.50 since (4)
* 9. Verify that accounts receivable balance of customer has increased by 7.50
* 10. Set Invoice to INVOICE_VOID
* 11. Verify ACCOUNTS_RECEIVABLES +0, InvoiceAdjustmentGlAccount(Company, EARLY_PAY_DISCOUNT) +0, InvoiceAdjustmentGlAccount(Company, CASH_DISCOUNT) 0 since (4)
* @throws GeneralException if an error occurs
*/
@SuppressWarnings("unchecked")
public void testAdjustPostVoidForInvoice() throws GeneralException {
FinancialAsserts fa = new FinancialAsserts(this, organizationPartyId, demofinadmin);
String customerPartyId = createPartyFromTemplate("DemoCustCompany", "Customer for testAdjustPostVoidForInvoice");
String invoiceId = fa.createInvoice(customerPartyId, "SALES_INVOICE");
fa.createInvoiceItem(invoiceId, "INV_FPROD_ITEM", "WG-1111", new BigDecimal("1.0"), new BigDecimal("10.0"));
// post an adjustment of $2 of type CASH_DISCOUNT to the invoice
Map results = runAndAssertServiceSuccess("createInvoiceAdjustment", UtilMisc.toMap("userLogin", demofinadmin, "invoiceId", invoiceId, "invoiceAdjustmentTypeId", "CASH_DISCOUNT", "adjustmentAmount", new BigDecimal("-2.0")));
String invoiceAdjustmentId1 = (String) results.get("invoiceAdjustmentId");
assertNotNull(invoiceAdjustmentId1);
// post an adjustment of $0.50 of type EARLY_PAY_DISCT to the invoice
results = runAndAssertServiceSuccess("createInvoiceAdjustment", UtilMisc.toMap("userLogin", demofinadmin, "invoiceId", invoiceId, "invoiceAdjustmentTypeId", "EARLY_PAY_DISCT", "adjustmentAmount", new BigDecimal("-0.50")));
String invoiceAdjustmentId2 = (String) results.get("invoiceAdjustmentId");
assertNotNull(invoiceAdjustmentId2);
// get balances, set to ready
Map initialBalances = fa.getFinancialBalances(UtilDateTime.nowTimestamp());
BigDecimal custBalances1 = AccountsHelper.getBalanceForCustomerPartyId(customerPartyId, organizationPartyId, "ACTUAL", UtilDateTime.nowTimestamp(), delegator);
fa.updateInvoiceStatus(invoiceId, "INVOICE_READY");
// get the early pay discount and cash gl accounts for sales invoices (note: they might be the same account)
GenericValue mapping = delegator.findByPrimaryKey("InvoiceAdjustmentGlAccount", UtilMisc.toMap("invoiceTypeId", "SALES_INVOICE", "invoiceAdjustmentTypeId", "EARLY_PAY_DISCT", "organizationPartyId", organizationPartyId));
assertNotNull(mapping);
String earlyPayGlAccountId = mapping.getString("glAccountId");
assertNotNull(earlyPayGlAccountId);
mapping = delegator.findByPrimaryKey("InvoiceAdjustmentGlAccount", UtilMisc.toMap("invoiceTypeId", "SALES_INVOICE", "invoiceAdjustmentTypeId", "CASH_DISCOUNT", "organizationPartyId", organizationPartyId));
assertNotNull(mapping);
String cashGlAccountId = mapping.getString("glAccountId");
assertNotNull(cashGlAccountId);
// the pause above should be sufficient to get the final balances
Map middleBalances = fa.getFinancialBalances(UtilDateTime.nowTimestamp());
BigDecimal custBalances2 = AccountsHelper.getBalanceForCustomerPartyId(customerPartyId, organizationPartyId, "ACTUAL", UtilDateTime.nowTimestamp(), delegator);
// check balances are +7.50 to AR, +2 to early pay, -0.5 to cash and that the AR balance of customer is 7.50
Map expectedBalanceChanges = UtilMisc.toMap("ACCOUNTS_RECEIVABLE", "7.50");
Map accountMap = UtilFinancial.replaceGlAccountTypeWithGlAccountForOrg(organizationPartyId, expectedBalanceChanges, delegator);
if (cashGlAccountId.equals(earlyPayGlAccountId)) {
accountMap.put(cashGlAccountId, "2.50");
} else {
accountMap.put(cashGlAccountId, "2.0");
accountMap.put(earlyPayGlAccountId, "0.50");
}
assertMapDifferenceCorrect(initialBalances, middleBalances, accountMap);
assertEquals("Customer balance as expected", custBalances2.subtract(custBalances1), new BigDecimal("7.50"));
// void invoices and get balances again
fa.updateInvoiceStatus(invoiceId, "INVOICE_VOIDED");
Map finalBalances = fa.getFinancialBalances(UtilDateTime.nowTimestamp());
BigDecimal custBalances3 = AccountsHelper.getBalanceForCustomerPartyId(customerPartyId, organizationPartyId, "ACTUAL", UtilDateTime.nowTimestamp(), delegator);
// check balances are all 0 compared to initial
expectedBalanceChanges = UtilMisc.toMap("ACCOUNTS_RECEIVABLE", "0");
accountMap = UtilFinancial.replaceGlAccountTypeWithGlAccountForOrg(organizationPartyId, expectedBalanceChanges, delegator);
accountMap.put(earlyPayGlAccountId, "0.0");
accountMap.put(cashGlAccountId, "0");
assertMapDifferenceCorrect(initialBalances, finalBalances, accountMap);
assertEquals("Customer balance net 0", custBalances3.subtract(custBalances1), BigDecimal.ZERO);
}
/**
* Test for accounts receivable invoice aging and customer balances
*
* 1. Create parties Customer A, Customer B, Customer C
* 2. Create invoices:
* (a) Create sales invoice #1 from Company to Customer A for $100, invoice date 91 days before current date, due date 30 days after invoice date
* (b) Create sales invoice #2 from Company to Customer A for $50, invoice date 25 days before current date, due date 30 days after invoice date
* (c) Create sales invoice #3 from Company to Customer B for $150, invoice date 55 days before current date, due date 60 days after invoice date
* (d) Create sales invoice #4 from Company to Customer C for $170, invoice date 120 days before current date, due date 30 days after invoice date
* (e) Create sales invoice #5 from Company to Customer B for $210, invoice date 15 days before current date, due date 7 days after invoice date
* (f) Create sales invoice #6 from Company to Customer A for $500, invoice date 36 days before current date, due date 30 days after invoice date
* (g) Create sales invoice #7 from Company to Customer C for $228, invoice date 42 days before current date, due date 45 days after invoice date
* (h) Create sales invoice #8 from Company to Customer B for $65, invoice date 15 days before current date, due date 30 days after invoice date
* (i) Create sales invoice #9 from Company to Customer A for $156, invoice date 6 days before current date, due date 15 days after invoice date
* (j) Create sales invoice #10 from Company to Customer C for $550, invoice date 33 days before current date, due date 15 days after invoice date
* (k) Create sales invoice #11 from Company to Customer B for $90, invoice date 62 days before current date, due date 90 days after invoice date
* 3. Cancel invoice #2
* 4. Set all other invoices to READY
* 5. Set invoice #6 to VOID
* 6. Set invoice #10 to WRITEOFF
* 7. Receive a payment of $65 for invoice #8
* 8. Receive a payment of $65 for invoice #11
* 9. Create sales invoice #12 for Company to Customer A for $1000, invoice date now and due 30 days after invoicing, but do not set this invoice to READY
* 10. Run AccountsHelper.getBalancesForAllCustomers and verify the following:
* (a) balance of Customer A is $256
* (b) balance of Customer B is $385
* (c) balance of Customer C is $398
* 11. Run AccountsHelper.getUnpaidInvoicesForCustomers and verify:
* (a) 0-30 day bucket has invoices #5 and #9
* (b) 30-60 day bucket has invoices #3 and #7
* (c) 60-90 day bucket has invoice #11
* (d) 90+ day bucket has invoices #1 and #4
* 12. Create parties Customer D and Customer E
* 13. Create more sales invoices:
* (a) Invoice #13 from Company to Customer D for $200, invoice date today, due in 30 days after invoice date
* (b) Invoice #14 from Company to Customer D for $300, invoice date today, due in 60 days after invoice date
* (c) Invoice #15 from Company to Customer E for $155, invoice date 58 days before today, due in 50 days after invoice date
* (d) Invoice #16 from Company to Customer E for $266, invoice date 72 days before today, due in 30 days after invoice date
* (e) Invoice #17 from Company to Customer E for $377, invoice date 115 days before today, due in 30 days after invoice date
* (f) Invoice #18 from Company to Customer E for $488, invoice date 135 days before today, due in 30 days after invoice date
* (g) Invoice #19 from Company to Customer E for $599, invoice date 160 days before today, due in 30 days after invoice date
* (h) Invoice #20 from Company to Customer E for $44, invoice date 20 days before today, no due date (null)
* 14. Set all invoices from (13) to ready.
* 15. Get customer statement (AccountsHelper.customerStatement) with useAgingDate=true and verify
* (a) Customer A: isPastDue = true, current = $156, 30 - 60 days = 0, 60 - 90 days = $100, 90 - 120 days = 0, over 120 days = 0, total open amount = $256
* (b) Customer B: isPastDue = false, current = $385, 30 - 60 days = 0, 60 - 90 days = 0, 90 - 120 days = 0, over 120 days = 0, total open amount = $385
* (c) Customer C: isPastDue = true, current = $228, 30 - 60 days = 0, 60 - 90 days = 0, 90 - 120 days = $170, over 120 days = 0, total open amount = $398
* (d) Customer D: isPastDue = false, current = $500, 30 - 60 days = 0, 60 - 90 days = 0, 90 - 120 days = 0, over 120 days = 0, total open amount = $500
* (e) Customer E: isPastDue = true, current = $199, 30 - 60 days = 266, 60 - 90 days = 377, 90 - 120 days = 488, over 120 days = 599, total open amount = $1929
* 16. Get customer statement (AccountsHelper.customerStatement) with useAgingDate=false and verify
* (a) Customer A: isPastDue = true, current = $156, 30 - 60 days = 0, 60 - 90 days = 0, 90 - 120 days = $100, over 120 days = 0, total open amount = $256
* (b) Customer B: isPastDue = true, current = $210, 30 - 60 days = 150, 60 - 90 days = 25, 90 - 120 days = 0, over 120 days = 0, total open amount = $385
* (c) Customer C: isPastDue = true, current = 0, 30 - 60 days = 228, 60 - 90 days = 0, 90 - 120 days = 0, over 120 days = $170, total open amount = $398
* (d) Customer D: isPastDue = false, current = $500, 30 - 60 days = 0, 60 - 90 days = 0, 90 - 120 days = 0, over 120 days = 0, total open amount = $500
* (e) Customer E: isPastDue = true, current = $44, 30 - 60 days = 155, 60 - 90 days = 266, 90 - 120 days = 377, over 120 days = 1087, total open amount = $1929
* @throws GeneralException if an error occurs
*/
@SuppressWarnings("unchecked")
public void testAccountsReceivableInvoiceAgingAndCustomerBalances() throws GeneralException {
/*
* 1. Create parties Customer A, Customer B, Customer C
*/
TestObjectGenerator generator = new TestObjectGenerator(delegator, dispatcher);
List<String> customerId = generator.getContacts(3);
assertNotNull("Three customers should be generated", customerId);
/*
* 2. Create invoices
*/
FinancialAsserts fa = new FinancialAsserts(this, organizationPartyId, demofinadmin);
/*
* (a) Create sales invoice #1 from Company to Customer A for $100, invoice date 91 days before current date, due date 30 days after invoice date
*/
String invoiceId1 = fa.createInvoice(customerId.get(0), "SALES_INVOICE", UtilDateTime.adjustTimestamp(UtilDateTime.nowTimestamp(), Calendar.DAY_OF_YEAR, -91, timeZone, locale), UtilDateTime.adjustTimestamp(UtilDateTime.nowTimestamp(), Calendar.DAY_OF_YEAR, -91 + 30, timeZone, locale), null, null, "invoiceId1");
fa.createInvoiceItem(invoiceId1, "INV_FPROD_ITEM", "WG-1111", new BigDecimal("1.0"), new BigDecimal("100.0"));
/*
* (b) Create sales invoice #2 from Company to Customer A for $50, invoice date 25 days before current date, due date 30 days after invoice date
*/
String invoiceId2 = fa.createInvoice(customerId.get(0), "SALES_INVOICE", UtilDateTime.adjustTimestamp(UtilDateTime.nowTimestamp(), Calendar.DAY_OF_YEAR, -25, timeZone, locale), UtilDateTime.adjustTimestamp(UtilDateTime.nowTimestamp(), Calendar.DAY_OF_YEAR, -25 + 30, timeZone, locale), null, null, "invoiceId2");
fa.createInvoiceItem(invoiceId2, "INV_FPROD_ITEM", "WG-1111", new BigDecimal("1.0"), new BigDecimal("50.0"));
/*
* (c) Create sales invoice #3 from Company to Customer B for $150, invoice date 55 days before current date, due date 60 days after invoice date
*/
String invoiceId3 = fa.createInvoice(customerId.get(1), "SALES_INVOICE", UtilDateTime.adjustTimestamp(UtilDateTime.nowTimestamp(), Calendar.DAY_OF_YEAR, -55, timeZone, locale), UtilDateTime.adjustTimestamp(UtilDateTime.nowTimestamp(), Calendar.DAY_OF_YEAR, -55 + 60, timeZone, locale), null, null, "invoiceId3");
fa.createInvoiceItem(invoiceId3, "INV_FPROD_ITEM", "WG-1111", new BigDecimal("1.0"), new BigDecimal("150.0"));
/*
* (d) Create sales invoice #4 from Company to Customer C for $170, invoice date 120 days before current date, due date 30 days after invoice date
*/
String invoiceId4 = fa.createInvoice(customerId.get(2), "SALES_INVOICE", UtilDateTime.adjustTimestamp(UtilDateTime.nowTimestamp(), Calendar.DAY_OF_YEAR, -120, timeZone, locale), UtilDateTime.adjustTimestamp(UtilDateTime.nowTimestamp(), Calendar.DAY_OF_YEAR, -120 + 30, timeZone, locale), null, null, "invoiceId4");
fa.createInvoiceItem(invoiceId4, "INV_FPROD_ITEM", "WG-1111", new BigDecimal("1.0"), new BigDecimal("170.0"));
/*
* (e) Create sales invoice #5 from Company to Customer B for $210, invoice date 15 days before current date, due date 7 days after invoice date
*/
String invoiceId5 = fa.createInvoice(customerId.get(1), "SALES_INVOICE", UtilDateTime.adjustTimestamp(UtilDateTime.nowTimestamp(), Calendar.DAY_OF_YEAR, -15, timeZone, locale), UtilDateTime.adjustTimestamp(UtilDateTime.nowTimestamp(), Calendar.DAY_OF_YEAR, -15 + 7, timeZone, locale), null, null, "invoiceId5");
fa.createInvoiceItem(invoiceId5, "INV_FPROD_ITEM", "WG-1111", new BigDecimal("1.0"), new BigDecimal("210.0"));
/*
* (f) Create sales invoice #6 from Company to Customer A for $500, invoice date 36 days before current date, due date 30 days after invoice date
*/
String invoiceId6 = fa.createInvoice(customerId.get(0), "SALES_INVOICE", UtilDateTime.adjustTimestamp(UtilDateTime.nowTimestamp(), Calendar.DAY_OF_YEAR, -36, timeZone, locale), UtilDateTime.adjustTimestamp(UtilDateTime.nowTimestamp(), Calendar.DAY_OF_YEAR, -36 + 30, timeZone, locale), null, null, "invoiceId6");
fa.createInvoiceItem(invoiceId6, "INV_FPROD_ITEM", "WG-1111", new BigDecimal("1.0"), new BigDecimal("500.0"));
/*
* (g) Create sales invoice #7 from Company to Customer C for $228, invoice date 42 days before current date, due date 45 days after invoice date
*/
String invoiceId7 = fa.createInvoice(customerId.get(2), "SALES_INVOICE", UtilDateTime.adjustTimestamp(UtilDateTime.nowTimestamp(), Calendar.DAY_OF_YEAR, -42, timeZone, locale), UtilDateTime.adjustTimestamp(UtilDateTime.nowTimestamp(), Calendar.DAY_OF_YEAR, -42 + 45, timeZone, locale), null, null, "invoiceId7");
fa.createInvoiceItem(invoiceId7, "INV_FPROD_ITEM", "WG-1111", new BigDecimal("1.0"), new BigDecimal("228.0"));
/*
* (h) Create sales invoice #8 from Company to Customer B for $65, invoice date 15 days before current date, due date 30 days after invoice date
*/
String invoiceId8 = fa.createInvoice(customerId.get(1), "SALES_INVOICE", UtilDateTime.adjustTimestamp(UtilDateTime.nowTimestamp(), Calendar.DAY_OF_YEAR, -15, timeZone, locale), UtilDateTime.adjustTimestamp(UtilDateTime.nowTimestamp(), Calendar.DAY_OF_YEAR, -15 + 30, timeZone, locale), null, null, "invoiceId8");
fa.createInvoiceItem(invoiceId8, "INV_FPROD_ITEM", "WG-1111", new BigDecimal("1.0"), new BigDecimal("65.0"));
/*
* (i) Create sales invoice #9 from Company to Customer A for $156, invoice date 6 days before current date, due date 15 days after invoice date
*/
String invoiceId9 = fa.createInvoice(customerId.get(0), "SALES_INVOICE", UtilDateTime.adjustTimestamp(UtilDateTime.nowTimestamp(), Calendar.DAY_OF_YEAR, -6, timeZone, locale), UtilDateTime.adjustTimestamp(UtilDateTime.nowTimestamp(), Calendar.DAY_OF_YEAR, -6 + 15, timeZone, locale), null, null, "invoiceId9");
fa.createInvoiceItem(invoiceId9, "INV_FPROD_ITEM", "WG-1111", new BigDecimal("1.0"), new BigDecimal("156.0"));
/*
* (j) Create sales invoice #10 from Company to Customer C for $550, invoice date 33 days before current date, due date 15 days after invoice date
*/
String invoiceId10 = fa.createInvoice(customerId.get(2), "SALES_INVOICE", UtilDateTime.adjustTimestamp(UtilDateTime.nowTimestamp(), Calendar.DAY_OF_YEAR, -33, timeZone, locale), UtilDateTime.adjustTimestamp(UtilDateTime.nowTimestamp(), Calendar.DAY_OF_YEAR, -33 + 15, timeZone, locale), null, null, "invoiceId10");
fa.createInvoiceItem(invoiceId10, "INV_FPROD_ITEM", "WG-1111", new BigDecimal("1.0"), new BigDecimal("550.0"));
/*
* (k) Create sales invoice #11 from Company to Customer B for $90, invoice date 62 days before current date, due date 90 days after invoice date
*/
String invoiceId11 = fa.createInvoice(customerId.get(1), "SALES_INVOICE", UtilDateTime.adjustTimestamp(UtilDateTime.nowTimestamp(), Calendar.DAY_OF_YEAR, -62, timeZone, locale), UtilDateTime.adjustTimestamp(UtilDateTime.nowTimestamp(), Calendar.DAY_OF_YEAR, -62 + 90, timeZone, locale), null, null, "invoiceId11");
fa.createInvoiceItem(invoiceId11, "INV_FPROD_ITEM", "WG-1111", new BigDecimal("1.0"), new BigDecimal("90.0"));
/*
* 3. Cancel invoice #2
*/
fa.updateInvoiceStatus(invoiceId2, "INVOICE_CANCELLED");
/*
* 4. Set all other invoices to READY
*/
fa.updateInvoiceStatus(invoiceId1, "INVOICE_READY");
fa.updateInvoiceStatus(invoiceId3, "INVOICE_READY");
fa.updateInvoiceStatus(invoiceId4, "INVOICE_READY");
fa.updateInvoiceStatus(invoiceId5, "INVOICE_READY");
fa.updateInvoiceStatus(invoiceId6, "INVOICE_READY");
fa.updateInvoiceStatus(invoiceId7, "INVOICE_READY");
fa.updateInvoiceStatus(invoiceId8, "INVOICE_READY");
fa.updateInvoiceStatus(invoiceId9, "INVOICE_READY");
fa.updateInvoiceStatus(invoiceId10, "INVOICE_READY");
fa.updateInvoiceStatus(invoiceId11, "INVOICE_READY");
/*
* 5. Set invoice #6 to VOID
*/
Map<String, Object> input = new HashMap<String, Object>();
input.put("userLogin", demofinadmin);
input.put("invoiceId", invoiceId6);
runAndAssertServiceSuccess("opentaps.voidInvoice", input);
/*
* 6. Set invoice #10 to WRITEOFF
*/
fa.updateInvoiceStatus(invoiceId10, "INVOICE_WRITEOFF");
/*
* 7. Receive a payment of $65 for invoice #8
*/
fa.createPaymentAndApplication(new BigDecimal("65.0"), customerId.get(1), organizationPartyId, "CUSTOMER_PAYMENT", "CREDIT_CARD", null, invoiceId8, "PMNT_RECEIVED");
/*
* 8. Receive a payment of $65 for invoice #11
*/
fa.createPaymentAndApplication(new BigDecimal("65.0"), customerId.get(1), organizationPartyId, "CUSTOMER_PAYMENT", "CREDIT_CARD", null, invoiceId11, "PMNT_RECEIVED");
/*
* 9. Create sales invoice #12 for Company to Customer A for $1000, invoice date now and due 30 days after invoicing, but do not set this invoice to READY
*/
String invoiceId12 = fa.createInvoice(customerId.get(0), "SALES_INVOICE", UtilDateTime.nowTimestamp(), UtilDateTime.adjustTimestamp(UtilDateTime.nowTimestamp(), Calendar.DAY_OF_YEAR, 30, timeZone, locale), null, null, "invoiceId12");
fa.createInvoiceItem(invoiceId12, "INV_FPROD_ITEM", "WG-1111", new BigDecimal("1.0"), new BigDecimal("1000.0"));
/*
* 10. Run AccountsHelper.getBalancesForAllCustomers and verify the following:
*/
Map<String, BigDecimal> balances = AccountsHelper.getBalancesForAllCustomers(organizationPartyId, "ACTUAL", UtilDateTime.nowTimestamp(), delegator);
/*
* (a) balance of Customer A is $256
*/
assertEquals("balance of Customer " + customerId.get(0) + " is " + balances.get(customerId.get(0)) + " and not $256", balances.get(customerId.get(0)), new BigDecimal("256.00"));
/*
* (b) balance of Customer B is $385
*/
assertEquals("balance of Customer " + customerId.get(1) + " is " + balances.get(customerId.get(1)) + " and not $385", balances.get(customerId.get(1)), new BigDecimal("385.00"));
/*
* (c) balance of Customer C is $398
*/
assertEquals("balance of Customer " + customerId.get(2) + " is " + balances.get(customerId.get(0)) + " and not $398", balances.get(customerId.get(2)), new BigDecimal("398.00"));
/*
* 11. Run AccountsHelper.getUnpaidInvoicesForCustomers and verify:
*/
- Map<Integer, List> invoices = AccountsHelper.getUnpaidInvoicesForCustomers(organizationPartyId, UtilMisc.toList(new Integer(30), new Integer(60), new Integer(90), new Integer(9999)), UtilDateTime.nowTimestamp(), delegator, timeZone, locale);
+ Map<Integer, List<Invoice>> invoices = AccountsHelper.getUnpaidInvoicesForCustomers(organizationPartyId, UtilMisc.toList(new Integer(30), new Integer(60), new Integer(90), new Integer(9999)), UtilDateTime.nowTimestamp(), delegator, timeZone, locale);
assertNotNull("Unpaid Invoices For Customers not found.", invoices);
/*
* (b) 0-30 day bucket has invoices #5 and #9
*/
List<Invoice> invoicesList = invoices.get(30);
assertNotNull("Unpaid Invoices For Customers not found.", invoicesList);
boolean isPresent5 = false;
boolean isPresent9 = false;
for (Invoice invoice : invoicesList) {
if (invoiceId5.equals(invoice.getString("invoiceId"))) {
isPresent5 = true;
}
if (invoiceId9.equals(invoice.getString("invoiceId"))) {
isPresent9 = true;
}
}
assertTrue("Invoice " + invoiceId5 + " is not present in 0-30 day bucket", isPresent5);
assertTrue("Invoice " + invoiceId9 + " is not present in 0-30 day bucket", isPresent9);
/*
* (c) 30-60 day bucket has invoice #3 and #7
*/
invoicesList = invoices.get(60);
assertNotNull("Unpaid Invoices For Customers not found.", invoicesList);
boolean isPresent3 = false;
boolean isPresent7 = false;
for (Invoice invoice : invoicesList) {
if (invoiceId3.equals(invoice.getString("invoiceId"))) {
isPresent3 = true;
}
if (invoiceId7.equals(invoice.getString("invoiceId"))) {
isPresent7 = true;
}
}
assertTrue("Invoice " + invoiceId3 + " is not present in 30-60 day bucket", isPresent3);
assertTrue("Invoice " + invoiceId7 + " is not present in 30-60 day bucket", isPresent7);
/*
* (d) 60-90 day bucket has invoices #11
*/
invoicesList = invoices.get(90);
assertNotNull("Unpaid Invoices For Customers not found.", invoicesList);
boolean isPresent11 = false;
for (Invoice invoice : invoicesList) {
if (invoiceId11.equals(invoice.getString("invoiceId"))) {
isPresent11 = true;
}
}
assertTrue("Invoice " + invoiceId11 + " is not present in 60-90 day bucket", isPresent11);
/*
* (d) 90+ day bucket has invoices #1 and #4
*/
invoicesList = invoices.get(9999);
assertNotNull("Unpaid Invoices For Customers not found.", invoicesList);
boolean isPresent1 = false;
boolean isPresent4 = false;
for (Invoice invoice : invoicesList) {
if (invoiceId1.equals(invoice.getString("invoiceId"))) {
isPresent1 = true;
}
if (invoiceId4.equals(invoice.getString("invoiceId"))) {
isPresent4 = true;
}
}
assertTrue("Invoice " + invoiceId1 + " is not present in 90+ day bucket", isPresent1);
assertTrue("Invoice " + invoiceId4 + " is not present in 90+ day bucket", isPresent4);
/*
* 12. Create parties Customer D and Customer E
*/
List<String> extraCustomerIds = generator.getContacts(2);
assertNotNull("Two customers should be generated", extraCustomerIds);
assertEquals(2, extraCustomerIds.size());
customerId.addAll(extraCustomerIds);
/*
* 13. Create more sales invoices
*
* (a) Invoice #13 from Company to Customer D for $200, invoice date today, due in 30 days after invoice date
*/
String invoice13 = fa.createInvoice(customerId.get(3), "SALES_INVOICE", UtilDateTime.nowTimestamp(), UtilDateTime.adjustTimestamp(UtilDateTime.nowTimestamp(), Calendar.DAY_OF_YEAR, 30, timeZone, locale), null, null, "invoiceId13");
fa.createInvoiceItem(invoice13, "INV_FPROD_ITEM", "WG-1111", new BigDecimal("2.0"), new BigDecimal("100.0"));
/*
* (b) Invoice #14 from Company to Customer D for $300, invoice date today, due in 60 days after invoice date
*/
String invoice14 = fa.createInvoice(customerId.get(3), "SALES_INVOICE", UtilDateTime.nowTimestamp(), UtilDateTime.adjustTimestamp(UtilDateTime.nowTimestamp(), Calendar.DAY_OF_YEAR, 60, timeZone, locale), null, null, "invoice14");
fa.createInvoiceItem(invoice14, "INV_FPROD_ITEM", "WG-1111", new BigDecimal("3.0"), new BigDecimal("100.0"));
/*
* (c) Invoice #15 from Company to Customer E for $155, invoice date 58 days before today, due in 50 days after invoice date
*/
String invoice15 = fa.createInvoice(customerId.get(4), "SALES_INVOICE", UtilDateTime.adjustTimestamp(UtilDateTime.nowTimestamp(), Calendar.DAY_OF_YEAR, -58, timeZone, locale), UtilDateTime.adjustTimestamp(UtilDateTime.nowTimestamp(), Calendar.DAY_OF_YEAR, -58 + 50, timeZone, locale), null, null, "invoice15");
fa.createInvoiceItem(invoice15, "INV_FPROD_ITEM", "WG-1111", new BigDecimal("1.0"), new BigDecimal("155.0"));
/*
* (d) Invoice #16 from Company to Customer E for $266, invoice date 72 days before today, due in 30 days after invoice date
*/
String invoice16 = fa.createInvoice(customerId.get(4), "SALES_INVOICE", UtilDateTime.adjustTimestamp(UtilDateTime.nowTimestamp(), Calendar.DAY_OF_YEAR, -72, timeZone, locale), UtilDateTime.adjustTimestamp(UtilDateTime.nowTimestamp(), Calendar.DAY_OF_YEAR, -72 + 30, timeZone, locale), null, null, "invoice16");
fa.createInvoiceItem(invoice16, "INV_FPROD_ITEM", "WG-1111", new BigDecimal("1.0"), new BigDecimal("266.0"));
/*
* (e) Invoice #17 from Company to Customer E for $377, invoice date 115 days before today, due in 30 days after invoice date
*/
String invoice17 = fa.createInvoice(customerId.get(4), "SALES_INVOICE", UtilDateTime.adjustTimestamp(UtilDateTime.nowTimestamp(), Calendar.DAY_OF_YEAR, -115, timeZone, locale), UtilDateTime.adjustTimestamp(UtilDateTime.nowTimestamp(), Calendar.DAY_OF_YEAR, -115 + 30, timeZone, locale), null, null, "invoice17");
fa.createInvoiceItem(invoice17, "INV_FPROD_ITEM", "WG-1111", new BigDecimal("1.0"), new BigDecimal("377.0"));
/*
* (f) Invoice #18 from Company to Customer E for $488, invoice date 135 days before today, due in 30 days after invoice date
*/
String invoice18 = fa.createInvoice(customerId.get(4), "SALES_INVOICE", UtilDateTime.adjustTimestamp(UtilDateTime.nowTimestamp(), Calendar.DAY_OF_YEAR, -135, timeZone, locale), UtilDateTime.adjustTimestamp(UtilDateTime.nowTimestamp(), Calendar.DAY_OF_YEAR, -135 + 30, timeZone, locale), null, null, "invoice18");
fa.createInvoiceItem(invoice18, "INV_FPROD_ITEM", "WG-1111", new BigDecimal("1.0"), new BigDecimal("488.0"));
/*
* (g) Invoice #19 from Company to Customer E for $599, invoice date 160 days before today, due in 30 days after invoice date
*/
String invoice19 = fa.createInvoice(customerId.get(4), "SALES_INVOICE", UtilDateTime.adjustTimestamp(UtilDateTime.nowTimestamp(), Calendar.DAY_OF_YEAR, -160, timeZone, locale), UtilDateTime.adjustTimestamp(UtilDateTime.nowTimestamp(), Calendar.DAY_OF_YEAR, -160 + 30, timeZone, locale), null, null, "invoice19");
fa.createInvoiceItem(invoice19, "INV_FPROD_ITEM", "WG-1111", new BigDecimal("1.0"), new BigDecimal("599.0"));
/*
* (h) Invoice #20 from Company to Customer E for $44, invoice date 20 days before today, no due date (null)
*/
String invoice20 = fa.createInvoice(customerId.get(4), "SALES_INVOICE", UtilDateTime.adjustTimestamp(UtilDateTime.nowTimestamp(), Calendar.DAY_OF_YEAR, -20, timeZone, locale), null, null, null, "invoice20");
fa.createInvoiceItem(invoice20, "INV_FPROD_ITEM", "WG-1111", new BigDecimal("1.0"), new BigDecimal("44.0"));
/*
* 14. Set all invoices from (13) to ready.
*/
fa.updateInvoiceStatus(invoice13, "INVOICE_READY");
fa.updateInvoiceStatus(invoice14, "INVOICE_READY");
fa.updateInvoiceStatus(invoice15, "INVOICE_READY");
fa.updateInvoiceStatus(invoice16, "INVOICE_READY");
fa.updateInvoiceStatus(invoice17, "INVOICE_READY");
fa.updateInvoiceStatus(invoice18, "INVOICE_READY");
fa.updateInvoiceStatus(invoice19, "INVOICE_READY");
fa.updateInvoiceStatus(invoice20, "INVOICE_READY");
/*
* 15. Get customer statement (AccountsHelper.customerStatement) with useAgingDate=true and verify
*/
DomainsLoader dl = new DomainsLoader(new Infrastructure(dispatcher), new User(demofinadmin));
Map<String, Object> partyData = FastMap.newInstance();
AccountsHelper.customerStatement(dl, organizationPartyId, UtilMisc.toSet(customerId), UtilDateTime.nowTimestamp(), 30, true, partyData, locale, timeZone);
assertNotNull("Failed to create customer statement.", partyData);
/*
* (a) Customer A: isPastDue = true, current = $156, 30 - 60 days = 0, 60 - 90 days = $100, 90 - 120 days = 0, over 120 days = 0, total open amount = $256
*/
verifyCustomerStatement(customerId.get(0), partyData, true, new BigDecimal("156.0"), new BigDecimal("0.0"), new BigDecimal("100.0"), new BigDecimal("0.0"), new BigDecimal("0.0"), new BigDecimal("256.0"));
/*
* (b) Customer B: isPastDue = false, current = $385, 30 - 60 days = 0, 60 - 90 days = 0, 90 - 120 days = 0, over 120 days = 0, total open amount = $385
*/
verifyCustomerStatement(customerId.get(1), partyData, false, new BigDecimal("385.0"), new BigDecimal("0.0"), new BigDecimal("0.0"), new BigDecimal("0.0"), new BigDecimal("0.0"), new BigDecimal("385.0"));
/*
* (c) Customer C: isPastDue = true, current = $228, 30 - 60 days = 0, 60 - 90 days = 0, 90 - 120 days = $170, over 120 days = 0, total open amount = $398
*/
verifyCustomerStatement(customerId.get(2), partyData, true, new BigDecimal("228.0"), new BigDecimal("0.0"), new BigDecimal("0.0"), new BigDecimal("170.0"), new BigDecimal("0.0"), new BigDecimal("398.0"));
/*
* (d) Customer D: isPastDue = false, current = $500, 30 - 60 days = 0, 60 - 90 days = 0, 90 - 120 days = 0, over 120 days = 0, total open amount = $500
*/
verifyCustomerStatement(customerId.get(3), partyData, false, new BigDecimal("500.0"), new BigDecimal("0.0"), new BigDecimal("0.0"), new BigDecimal("0.0"), new BigDecimal("0.0"), new BigDecimal("500.0"));
/*
* (e) Customer E: isPastDue = true, current = $199, 30 - 60 days = 266, 60 - 90 days = 377, 90 - 120 days = 488, over 120 days = 599, total open amount = $1929
*/
verifyCustomerStatement(customerId.get(4), partyData, true, new BigDecimal("199.0"), new BigDecimal("266.0"), new BigDecimal("377.0"), new BigDecimal("488.0"), new BigDecimal("599.0"), new BigDecimal("1929.0"));
/*
* 16. Get customer statement (AccountsHelper.customerStatement) with useAgingDate=false and verify
*/
partyData = FastMap.newInstance();
AccountsHelper.customerStatement(dl, organizationPartyId, UtilMisc.toSet(customerId), UtilDateTime.nowTimestamp(), 30, false, partyData, locale, timeZone);
assertNotNull("Failed to create customer statement.", partyData);
/*
* (a) Customer A: isPastDue = true, current = $156, 30 - 60 days = 0, 60 - 90 days = 0, 90 - 120 days = $100, over 120 days = 0, total open amount = $256
*/
verifyCustomerStatement(customerId.get(0), partyData, true, new BigDecimal("156.0"), new BigDecimal("0.0"), new BigDecimal("0.0"), new BigDecimal("100.0"), new BigDecimal("0.0"), new BigDecimal("256.0"));
/*
* (b) Customer B: isPastDue = true, current = $210, 30 - 60 days = 150, 60 - 90 days = 25, 90 - 120 days = 0, over 120 days = 0, total open amount = $385
*/
verifyCustomerStatement(customerId.get(1), partyData, true, new BigDecimal("210.0"), new BigDecimal("150.0"), new BigDecimal("25.0"), new BigDecimal("0.0"), new BigDecimal("0.0"), new BigDecimal("385.0"));
/*
* (c) Customer C: isPastDue = true, current = 0, 30 - 60 days = 228, 60 - 90 days = 0, 90 - 120 days = 0, over 120 days = $170, total open amount = $398
* Note that invoice #4 from above is in the over 120 day bucket because it is dated 120 days before current timestamp, but aging calculation start at beginning of today
*/
verifyCustomerStatement(customerId.get(2), partyData, true, new BigDecimal("0.0"), new BigDecimal("228.0"), new BigDecimal("0.0"), new BigDecimal("0.0"), new BigDecimal("170.0"), new BigDecimal("398.0"));
/*
* (d) Customer D: isPastDue = false, current = $500, 30 - 60 days = 0, 60 - 90 days = 0, 90 - 120 days = 0, over 120 days = 0, total open amount = $500
*/
verifyCustomerStatement(customerId.get(3), partyData, false, new BigDecimal("500.0"), new BigDecimal("0.0"), new BigDecimal("0.0"), new BigDecimal("0.0"), new BigDecimal("0.0"), new BigDecimal("500.0"));
/*
* (e) Customer E: isPastDue = true, current = $44, 30 - 60 days = 155, 60 - 90 days = 266, 90 - 120 days = 377, over 120 days = 1087, total open amount = $1929
*/
verifyCustomerStatement(customerId.get(4), partyData, true, new BigDecimal("44.0"), new BigDecimal("155.0"), new BigDecimal("266.0"), new BigDecimal("377.0"), new BigDecimal("1087.0"), new BigDecimal("1929.0"));
}
private void verifyCustomerStatement(String partyId, Map<String, Object> partyData, boolean isPastDue, BigDecimal current, BigDecimal over30, BigDecimal over60, BigDecimal over90, BigDecimal over120, BigDecimal totalOpen) {
assertEquals("Customer " + partyId + " should have past due invoices but isPastDue flag incorrect.", Boolean.valueOf(isPastDue), partyData.get(partyId + "is_past_due"));
assertEquals("Current value for customer " + partyId + " is incorrect.", current, (BigDecimal) partyData.get(String.format("%1$scurrent", partyId)));
assertEquals("Over 30 days past due amount is wrong.", over30, (BigDecimal) partyData.get(String.format("%1$sover_1N", partyId)));
assertEquals("Over 60 days past due amount is wrong.", over60, (BigDecimal) partyData.get(String.format("%1$sover_2N", partyId)));
assertEquals("Over 90 days past due amount is wrong.", over90, (BigDecimal) partyData.get(String.format("%1$sover_3N", partyId)));
assertEquals("Over 120 days past due amount is wrong.", over120, (BigDecimal) partyData.get(String.format("%1$sover_4N", partyId)));
assertEquals("Total open amount is wrong.", totalOpen, (BigDecimal) partyData.get(String.format("%1$stotal_open", partyId)));
}
/**
* Tests setInvoiceReadyAndCheckIfPaid service on an in process invoice, verifying that it sets it to INVOICE_READY,
* and the GL and customer outstanding balance are increased.
* @throws GeneralException if an error occurs
*/
@SuppressWarnings("unchecked")
public void testSetInvoiceReadyAndCheckIfPaidToInvoiceReady() throws GeneralException {
FinancialAsserts fa = new FinancialAsserts(this, organizationPartyId, demofinadmin);
String customerPartyId = createPartyFromTemplate("DemoCustCompany", "Customer for testSetInvoiceReadyAndCheckIfPaidToInvoiceReady");
BigDecimal invoiceAmount = new BigDecimal("10.0");
// create the invoice
String invoiceId = fa.createInvoice(customerPartyId, "SALES_INVOICE");
fa.createInvoiceItem(invoiceId, "INV_FPROD_ITEM", "WG-1111", new BigDecimal("1.0"), invoiceAmount);
// get initial balances
Map initialBalances = fa.getFinancialBalances(UtilDateTime.nowTimestamp());
BigDecimal initialCustomerBalance = AccountsHelper.getBalanceForCustomerPartyId(customerPartyId, organizationPartyId, "ACTUAL", UtilDateTime.nowTimestamp(), delegator);
// set to ready and check if paid
runAndAssertServiceSuccess("setInvoiceReadyAndCheckIfPaid", UtilMisc.toMap("invoiceId", invoiceId, "userLogin", demofinadmin));
// get final balances
Map finalBalances = fa.getFinancialBalances(UtilDateTime.nowTimestamp());
BigDecimal finalCustomerBalance = AccountsHelper.getBalanceForCustomerPartyId(customerPartyId, organizationPartyId, "ACTUAL", UtilDateTime.nowTimestamp(), delegator);
// check customer outstanding balance is right
assertEquals("Customer balance has increased by the right amount", (finalCustomerBalance.subtract(initialCustomerBalance)).setScale(DECIMALS, ROUNDING), invoiceAmount);
// check AR has increased by $10
Map expectedBalanceChanges = UtilMisc.toMap("ACCOUNTS_RECEIVABLE", "10.0");
Map accountMap = UtilFinancial.replaceGlAccountTypeWithGlAccountForOrg(organizationPartyId, expectedBalanceChanges, delegator);
assertMapDifferenceCorrect(initialBalances, finalBalances, accountMap);
// check invoice is PAID
Invoice invoice = invoiceRepository.getInvoiceById(invoiceId);
assertTrue("Invoice [" + invoiceId + "] is ready", invoice.isReady());
}
/**
* Tests setInvoiceReadyAndCheckIfPaid service on a cancelled invoice, verifying that it returns an error,
* and the GL and customer outstanding balance are unchanged.
* @throws GeneralException if an error occurs
*/
@SuppressWarnings("unchecked")
public void testSetInvoiceReadyAndCheckIfPaidForCancelledInvoice() throws GeneralException {
FinancialAsserts fa = new FinancialAsserts(this, organizationPartyId, demofinadmin);
String customerPartyId = createPartyFromTemplate("DemoCustCompany", "Customer for testSetInvoiceReadyAndCheckIfPaidForCancelledInvoice");
BigDecimal invoiceAmount = new BigDecimal("10.0");
// create the invoice
String invoiceId = fa.createInvoice(customerPartyId, "SALES_INVOICE");
fa.createInvoiceItem(invoiceId, "INV_FPROD_ITEM", "WG-1111", new BigDecimal("1.0"), invoiceAmount);
// get initial balances
Map initialBalances = fa.getFinancialBalances(UtilDateTime.nowTimestamp());
BigDecimal initialCustomerBalance = AccountsHelper.getBalanceForCustomerPartyId(customerPartyId, organizationPartyId, "ACTUAL", UtilDateTime.nowTimestamp(), delegator);
// now cancel the invoice
fa.updateInvoiceStatus(invoiceId, "INVOICE_CANCELLED");
// this should fail
runAndAssertServiceError("setInvoiceReadyAndCheckIfPaid", UtilMisc.toMap("invoiceId", invoiceId, "userLogin", demofinadmin));
// get the final balances
Map finalBalances = fa.getFinancialBalances(UtilDateTime.nowTimestamp());
BigDecimal finalCustomerBalance = AccountsHelper.getBalanceForCustomerPartyId(customerPartyId, organizationPartyId, "ACTUAL", UtilDateTime.nowTimestamp(), delegator);
// but the customer balance and accounts receivable totals should not have changed
assertEquals("Customer balance is unchanged", (finalCustomerBalance.subtract(initialCustomerBalance)).setScale(DECIMALS, ROUNDING), BigDecimal.ZERO);
Map expectedBalanceChanges = UtilMisc.toMap("ACCOUNTS_RECEIVABLE", "0.0");
Map accountMap = UtilFinancial.replaceGlAccountTypeWithGlAccountForOrg(organizationPartyId, expectedBalanceChanges, delegator);
assertMapDifferenceCorrect(initialBalances, finalBalances, accountMap);
// and the invoice should stay cancelled
Invoice invoice = invoiceRepository.getInvoiceById(invoiceId);
assertTrue("Invoice [" + invoiceId + "] is cancelled", invoice.isCancelled());
}
/**
* Tests setInvoiceReadyAndCheckIfPaid service on an invoice with payments already applied, verifying that it causes invoice to be PAID
* and the GL and customer outstanding balance are unchanged, but there is now money received (in undeposited receipts).
* @throws GeneralException if an error occurs
*/
@SuppressWarnings("unchecked")
public void testSetInvoiceReadyAndCheckIfPaidForInvoiceWithPayments() throws GeneralException {
FinancialAsserts fa = new FinancialAsserts(this, organizationPartyId, demofinadmin);
String customerPartyId = createPartyFromTemplate("DemoCustCompany", "Customer for testSetInvoiceReadyAndCheckIfPaidForInvoiceWithPayments");
BigDecimal invoiceAmount = new BigDecimal("10.0");
// create the invoice
String invoiceId = fa.createInvoice(customerPartyId, "SALES_INVOICE");
fa.createInvoiceItem(invoiceId, "INV_FPROD_ITEM", "WG-1111", new BigDecimal("1.0"), invoiceAmount);
// get initial balances
Map initialBalances = fa.getFinancialBalances(UtilDateTime.nowTimestamp());
BigDecimal initialCustomerBalance = AccountsHelper.getBalanceForCustomerPartyId(customerPartyId, organizationPartyId, "ACTUAL", UtilDateTime.nowTimestamp(), delegator);
// now create a payment and apply it to the invoice
fa.createPaymentAndApplication(invoiceAmount, customerPartyId, organizationPartyId, "CUSTOMER_PAYMENT", "PERSONAL_CHECK", null, invoiceId, "PMNT_RECEIVED");
// now set the invoice ready
runAndAssertServiceSuccess("setInvoiceReadyAndCheckIfPaid", UtilMisc.toMap("invoiceId", invoiceId, "userLogin", demofinadmin));
// get final balances
Map finalBalances = fa.getFinancialBalances(UtilDateTime.nowTimestamp());
BigDecimal finalCustomerBalance = AccountsHelper.getBalanceForCustomerPartyId(customerPartyId, organizationPartyId, "ACTUAL", UtilDateTime.nowTimestamp(), delegator);
// customer's balance should be unchanged
assertEquals("Customer balance is unchanged", (finalCustomerBalance.subtract(initialCustomerBalance)).setScale(DECIMALS, ROUNDING), BigDecimal.ZERO);
// AR should be unchanged (invoice is already paid), but we should have $10 in undeposited receipts
Map expectedBalanceChanges = UtilMisc.toMap("ACCOUNTS_RECEIVABLE", "0.0", "UNDEPOSITED_RECEIPTS", "+10");
Map accountMap = UtilFinancial.replaceGlAccountTypeWithGlAccountForOrg(organizationPartyId, expectedBalanceChanges, delegator);
assertMapDifferenceCorrect(initialBalances, finalBalances, accountMap);
// and invoice should be paid
Invoice invoice = invoiceRepository.getInvoiceById(invoiceId);
assertTrue("Invoice [" + invoiceId + "] is paid", invoice.isPaid());
}
/**
* This test verifies that when the organization uses standard costing, the difference between the standard cost and
* purchase invoice price for the item is charged off as a purchase price variance. There should be no change to
* uninvoiced shipment receipt.
* @exception GeneralException if an error occurs
*/
@SuppressWarnings("unchecked")
public void testPurchasingVarianceWithStandardCost() throws GeneralException {
// Set the organization costing method to standard costing
setStandardCostingMethod("STANDARD_COSTING");
// Get initial Financial balances
FinancialAsserts financialAsserts = new FinancialAsserts(this, organizationPartyId, demofinadmin);
Map initialBalances = financialAsserts.getFinancialBalances(UtilDateTime.nowTimestamp());
// Create a new product
GenericValue testProduct = createTestProduct("Test Purchasing Variance With Standard Cost Product", demowarehouse1);
String productId = testProduct.getString("productId");
// set its supplier product record for DemoSupplier to $10
createMainSupplierForProduct(productId, "DemoSupplier", new BigDecimal("10.0"), "USD", new BigDecimal("1.0"), admin);
// set its standard cost (EST_STD_MAT_COST) to $35
runAndAssertServiceSuccess("createCostComponent", UtilMisc.<String, Object>toMap("userLogin", admin, "productId", productId, "costComponentTypeId", "EST_STD_MAT_COST", "cost", new BigDecimal("35.0"), "costUomId", "USD"));
// Create a purchase order for 75 of this product from DemoSupplier
Map<GenericValue, BigDecimal> orderSpec = new HashMap<GenericValue, BigDecimal>();
orderSpec.put(testProduct, new BigDecimal("75.0"));
PurchaseOrderFactory pof = testCreatesPurchaseOrder(orderSpec, delegator.findByPrimaryKey("Party", UtilMisc.toMap("partyId", "DemoSupplier")), facilityContactMechId);
String orderId = pof.getOrderId();
GenericValue pOrder = delegator.findByPrimaryKeyCache("OrderHeader", UtilMisc.toMap("orderId", orderId));
// approve the purchase order
pof.approveOrder();
// receive all 75 units of the product from the purchase order
runAndAssertServiceSuccess("warehouse.issueOrderItemToShipmentAndReceiveAgainstPO", createTestInputParametersForReceiveInventoryAgainstPurchaseOrder(pOrder, demowarehouse1));
// Find the invoice
OrderRepositoryInterface orderRepository = orderDomain.getOrderRepository();
Order order = orderRepository.getOrderById(orderId);
List<Invoice> invoices = order.getInvoices();
assertEquals("Should only have one invoice.", invoices.size(), 1);
Invoice invoice = invoices.get(0);
// set the amount of the product on the invoice to $11.25
GenericValue invoiceItem = EntityUtil.getOnly(delegator.findByAnd("InvoiceItem", UtilMisc.toMap("invoiceId", invoice.getInvoiceId(), "productId", productId, "invoiceItemTypeId", "PINV_FPROD_ITEM")));
Map<String, Object> input = UtilMisc.<String, Object>toMap("userLogin", admin, "invoiceId", invoice.getInvoiceId(), "productId", productId, "invoiceItemTypeId", "PINV_FPROD_ITEM", "amount", new BigDecimal("11.25"));
input.put("invoiceItemSeqId", invoiceItem.get("invoiceItemSeqId"));
input.put("quantity", invoiceItem.get("quantity"));
runAndAssertServiceSuccess("updateInvoiceItem", input);
// add a second invoice item of "PITM_SHIP_CHARGES" for $58.39
input = UtilMisc.<String, Object>toMap("userLogin", admin, "invoiceId", invoice.getInvoiceId(), "invoiceItemTypeId", "PITM_SHIP_CHARGES", "amount", new BigDecimal("58.39"));
runAndAssertServiceSuccess("createInvoiceItem", input);
// set the invoice as ready
financialAsserts.updateInvoiceStatus(invoice.getInvoiceId(), "INVOICE_READY");
// Get the final financial balances
Map finalBalances = financialAsserts.getFinancialBalances(UtilDateTime.nowTimestamp());
// verify the following changes:
// ACCOUNTS_PAYABLE -902.14
// glAccountId=510000 58.39
// INVENTORY_ACCOUNT 2625.00
// PURCHASE_PRICE_VAR -1781.25
// UNINVOICED_SHIP_RCPT 0.00
Map expectedBalanceChanges = UtilMisc.toMap("ACCOUNTS_PAYABLE", "-902.14",
"INVENTORY_ACCOUNT", "2625.00",
"PURCHASE_PRICE_VAR", "-1781.25",
"UNINVOICED_SHIP_RCPT", "0.0");
expectedBalanceChanges = UtilFinancial.replaceGlAccountTypeWithGlAccountForOrg(organizationPartyId, expectedBalanceChanges, delegator);
expectedBalanceChanges.put("510000", "58.39");
printMapDifferences(initialBalances, finalBalances);
assertMapDifferenceCorrect(initialBalances, finalBalances, expectedBalanceChanges);
}
/**
* This test verifies that when creating an invoice item, if the productId is not null, then If invoiceItemTypeId is null, then use the ProductInvoiceItemType to fill in the invoiceItemTypeId (see below for this entity)
* If description is null, then use Product productName to fill in the description
* If amount is null, then call calculateProductPrice and fill in then amount.
* when updating an invoice item, if the new productId is different than the old productId
* @exception GeneralException if an error occurs
*/
@SuppressWarnings("unchecked")
public void testCreateAndUpdateInvoiceItem() throws GeneralException {
//create a SALES_INVOICE from Company to another party
InvoiceRepositoryInterface repository = billingDomain.getInvoiceRepository();
String customerPartyId = createPartyFromTemplate("DemoAccount1", "Account for testCreateAndUpdateInvoiceItem");
FinancialAsserts financialAsserts = new FinancialAsserts(this, organizationPartyId, demofinadmin);
String productId1 = "GZ-1000";
String productId2 = "GZ-1001";
// 1 creating invoice item with productId but without invoiceItemTypeId, description, price gets the right values
String invoiceId = financialAsserts.createInvoice(customerPartyId, "SALES_INVOICE", UtilDateTime.nowTimestamp(), null, null, null);
financialAsserts.createInvoiceItem(invoiceId, null, productId1, new BigDecimal("1.0"), null);
Invoice invoice = invoiceRepository.getInvoiceById(invoiceId);
GenericValue product1 = delegator.findByPrimaryKey("Product", UtilMisc.toMap("productId", productId1));
String invoiceItemTypeId1 = repository.getInvoiceItemTypeIdForProduct(invoice, domainsDirectory.getProductDomain().getProductRepository().getProductById(productId1));
String description1 = product1.getString("productName");
String uomId = invoice.getCurrencyUomId();
Map results = dispatcher.runSync("calculateProductPrice", UtilMisc.toMap("product", product1, "currencyUomId", uomId));
BigDecimal price1 = (BigDecimal) results.get("price");
BigDecimal amount1 = price1.setScale(DECIMALS, ROUNDING);
GenericValue product2 = delegator.findByPrimaryKey("Product", UtilMisc.toMap("productId", productId2));
String invoiceItemTypeId2 = repository.getInvoiceItemTypeIdForProduct(invoice, domainsDirectory.getProductDomain().getProductRepository().getProductById("GZ-1001"));
String description2 = product2.getString("productName");
results = dispatcher.runSync("calculateProductPrice", UtilMisc.toMap("product", product2, "currencyUomId", uomId));
BigDecimal price2 = (BigDecimal) results.get("price");
BigDecimal amount2 = price2.setScale(DECIMALS, ROUNDING);
GenericValue invoiceItem = EntityUtil.getOnly(delegator.findByAnd("InvoiceItem", UtilMisc.toMap("invoiceId", invoice.getInvoiceId(), "productId", productId1)));
assertEquals("invoiceItemTypeId is wrong.", invoiceItemTypeId1, invoiceItem.getString("invoiceItemTypeId"));
assertEquals("description is wrong.", description1, invoiceItem.getString("description"));
assertEquals("amount is wrong.", amount1, invoiceItem.getBigDecimal("amount").setScale(DECIMALS, ROUNDING));
// 2 you can also create invoice item with override invoiceItemTypeId, description, price
financialAsserts.createInvoiceItem(invoiceId, "ITM_SHIPPING_CHARGES", null, new BigDecimal("1.0"), new BigDecimal("45.0"), "testUpdateInvoiceItem description");
invoiceItem = EntityUtil.getOnly(delegator.findByAnd("InvoiceItem", UtilMisc.toMap("invoiceId", invoice.getInvoiceId(), "invoiceItemTypeId", "ITM_SHIPPING_CHARGES")));
assertEquals("invoiceItemTypeId is wrong.", "ITM_SHIPPING_CHARGES", invoiceItem.getString("invoiceItemTypeId"));
assertEquals("description is wrong.", "testUpdateInvoiceItem description", invoiceItem.getString("description"));
assertEquals("amount is wrong.", new BigDecimal("45.0"), invoiceItem.getBigDecimal("amount").setScale(DECIMALS, ROUNDING));
// 3 updating invoice item causes the right values to be filled in
financialAsserts.updateInvoiceItem(invoiceId, invoiceItem.getString("invoiceItemSeqId"), null, productId2, new BigDecimal("2.0"), null, null, null);
invoiceItem = EntityUtil.getOnly(delegator.findByAnd("InvoiceItem", UtilMisc.toMap("invoiceId", invoice.getInvoiceId(), "productId", productId2)));
assertEquals("invoiceItemTypeId is wrong.", invoiceItemTypeId2, invoiceItem.getString("invoiceItemTypeId"));
assertEquals("description is wrong.", description2, invoiceItem.getString("description"));
assertEquals("amount is wrong.", amount2, invoiceItem.getBigDecimal("amount").setScale(DECIMALS, ROUNDING));
// 4 you can update invoice item afterwards with override values
financialAsserts.updateInvoiceItem(invoiceId, invoiceItem.getString("invoiceItemSeqId"), "INV_FPROD_ITEM", productId2, new BigDecimal("2.0"), new BigDecimal("51.99"), "testUpdateInvoiceItem description", null);
invoiceItem = EntityUtil.getOnly(delegator.findByAnd("InvoiceItem", UtilMisc.toMap("invoiceId", invoice.getInvoiceId(), "productId", productId2)));
assertEquals("invoiceItemTypeId is wrong.", "INV_FPROD_ITEM", invoiceItem.getString("invoiceItemTypeId"));
assertEquals("description is wrong.", "testUpdateInvoiceItem description", invoiceItem.getString("description"));
assertEquals("amount is wrong.", new BigDecimal("51.99"), invoiceItem.getBigDecimal("amount").setScale(DECIMALS, ROUNDING));
// verify for PURCHASE_INVOICE
String supplierProductId1 = "SUPPLY-001";
String supplierProductId2 = "ASSET-001";
product1 = delegator.findByPrimaryKey("Product", UtilMisc.toMap("productId", supplierProductId1));
product2 = delegator.findByPrimaryKey("Product", UtilMisc.toMap("productId", supplierProductId2));
PurchasingRepositoryInterface purchasingRepository = purchasingDomain.getPurchasingRepository();
SupplierProduct demoSupplierProduct1 = purchasingRepository.getSupplierProduct("DemoSupplier", supplierProductId1, new BigDecimal("500.0"), "USD");
SupplierProduct demoSupplierProduct2 = purchasingRepository.getSupplierProduct("DemoSupplier", supplierProductId2, new BigDecimal("500.0"), "USD");
// 5 create a PURCHASE_INVOICE from Company to supplierParty
String purchaseInvoiceId = financialAsserts.createInvoice("DemoSupplier", "PURCHASE_INVOICE", UtilDateTime.nowTimestamp(), null, null, null);
financialAsserts.createInvoiceItem(purchaseInvoiceId, null, supplierProductId1, new BigDecimal("500.0"), null);
Invoice purchaseInvoice = repository.getInvoiceById(purchaseInvoiceId);
String purchaseInvoiceItemTypeId1 = repository.getInvoiceItemTypeIdForProduct(purchaseInvoice, domainsDirectory.getProductDomain().getProductRepository().getProductById(supplierProductId1));
String purchaseDescription1 = demoSupplierProduct1.getSupplierProductName()==null ? product1.getString("productName") : demoSupplierProduct1.getSupplierProductId() + " " + demoSupplierProduct1.getSupplierProductName();
BigDecimal purchaseAmount1 = demoSupplierProduct1.getLastPrice();
String purchaseInvoiceItemTypeId2 = repository.getInvoiceItemTypeIdForProduct(purchaseInvoice, domainsDirectory.getProductDomain().getProductRepository().getProductById(supplierProductId2));
String purchaseDescription2 = demoSupplierProduct2.getSupplierProductName()==null ? product2.getString("productName") : demoSupplierProduct2.getSupplierProductId() + " " + demoSupplierProduct2.getSupplierProductName();
BigDecimal purchaseAmount2 = demoSupplierProduct2.getLastPrice();
invoiceItem = EntityUtil.getOnly(delegator.findByAnd("InvoiceItem", UtilMisc.toMap("invoiceId", purchaseInvoice.getInvoiceId(), "productId", supplierProductId1)));
assertEquals("invoiceItemTypeId is wrong.", purchaseInvoiceItemTypeId1, invoiceItem.getString("invoiceItemTypeId"));
assertEquals("description is wrong.", purchaseDescription1, invoiceItem.getString("description"));
assertEquals("amount is wrong.", purchaseAmount1, invoiceItem.getBigDecimal("amount").setScale(DECIMALS, ROUNDING));
// 6 you can also create invoice item with override invoiceItemTypeId, description, price
financialAsserts.createInvoiceItem(purchaseInvoiceId, "ITM_SHIPPING_CHARGES", null, new BigDecimal("1.0"), new BigDecimal("45.0"), "testUpdateInvoiceItem description");
invoiceItem = EntityUtil.getOnly(delegator.findByAnd("InvoiceItem", UtilMisc.toMap("invoiceId", purchaseInvoice.getInvoiceId(), "invoiceItemTypeId", "ITM_SHIPPING_CHARGES")));
assertEquals("invoiceItemTypeId is wrong.", "ITM_SHIPPING_CHARGES", invoiceItem.getString("invoiceItemTypeId"));
assertEquals("description is wrong.", "testUpdateInvoiceItem description", invoiceItem.getString("description"));
assertEquals("amount is wrong.", new BigDecimal("45.0"), invoiceItem.getBigDecimal("amount").setScale(DECIMALS, ROUNDING));
// 7 updating invoice item causes the right values to be filled in
financialAsserts.updateInvoiceItem(purchaseInvoiceId, invoiceItem.getString("invoiceItemSeqId"), null, supplierProductId2, new BigDecimal("500.0"), null, null, null);
invoiceItem = EntityUtil.getOnly(delegator.findByAnd("InvoiceItem", UtilMisc.toMap("invoiceId", purchaseInvoice.getInvoiceId(), "productId", supplierProductId2)));
assertEquals("invoiceItemTypeId is wrong.", purchaseInvoiceItemTypeId2, invoiceItem.getString("invoiceItemTypeId"));
assertEquals("description is wrong.", purchaseDescription2, invoiceItem.getString("description"));
assertEquals("amount is wrong.", purchaseAmount2, invoiceItem.getBigDecimal("amount").setScale(DECIMALS, ROUNDING));
// 8 you can update invoice item afterwards with override values
financialAsserts.updateInvoiceItem(purchaseInvoiceId, invoiceItem.getString("invoiceItemSeqId"), "PINV_FPROD_ITEM", supplierProductId2, new BigDecimal("2.0"), new BigDecimal("199.99"), "testUpdateInvoiceItem description", null);
invoiceItem = EntityUtil.getOnly(delegator.findByAnd("InvoiceItem", UtilMisc.toMap("invoiceId", purchaseInvoice.getInvoiceId(), "productId", supplierProductId2)));
assertEquals("invoiceItemTypeId is wrong.", "PINV_FPROD_ITEM", invoiceItem.getString("invoiceItemTypeId"));
assertEquals("description is wrong.", "testUpdateInvoiceItem description", invoiceItem.getString("description"));
assertEquals("amount is wrong.", new BigDecimal("199.99"), invoiceItem.getBigDecimal("amount").setScale(DECIMALS, ROUNDING));
}
/**
* This test verifies captureAccountBalancesSnapshot service can take snapshot for account balance.
* @exception Exception if an error occurs
*/
@SuppressWarnings("unchecked")
public void testAccountBalancesSnapshot() throws Exception {
// create a test party from DemoAccount1 template
String customerPartyId = createPartyFromTemplate("DemoAccount1", "Account for testAccountBalancesSnapshot");
Debug.logInfo("testAccountBalancesSnapshot method create partyId " + customerPartyId, MODULE);
// run captureAccountBalancesSnapshot
Map inputParams = UtilMisc.toMap("userLogin", demofinadmin);
runAndAssertServiceSuccess("captureAccountBalancesSnapshot", inputParams);
// verify that there is no account balance history record for test party
Session session = new Infrastructure(dispatcher).getSession();
String hql = "from AccountBalanceHistory eo where eo.partyId = :partyId order by eo.asOfDatetime desc";
Query query = session.createQuery(hql);
query.setString("partyId", customerPartyId);
List<AccountBalanceHistory> list = query.list();
assertEmpty("There is no account balance history record for " + customerPartyId, list);
// create a SALES_INVOICE from Company to test party for $100 and set it to READY
FinancialAsserts financialAsserts = new FinancialAsserts(this, organizationPartyId, demofinadmin);
String invoiceId = financialAsserts.createInvoice(customerPartyId, "SALES_INVOICE", UtilDateTime.nowTimestamp(), null, null, null);
financialAsserts.createInvoiceItem(invoiceId, "INV_FPROD_ITEM", "GZ-1000", new BigDecimal("1.0"), new BigDecimal("100.0"));
financialAsserts.updateInvoiceStatus(invoiceId, "INVOICE_READY");
// run captureAccountBalancesSnapshot
inputParams = UtilMisc.toMap("userLogin", demofinadmin);
runAndAssertServiceSuccess("captureAccountBalancesSnapshot", inputParams);
// verify that there is a new account balance history record for test party and Company for 100
list = query.list();
assertEquals("There is a new account balance history record for Company and " + customerPartyId, 1, list.size());
AccountBalanceHistory accountBalanceHistory = list.get(0);
assertEquals("There is a new account balance history record for Company and " + customerPartyId + " for 100.0", new BigDecimal("100.0"), accountBalanceHistory.getTotalBalance());
pause("mysql timestamp pause");
// create a CUSTOMER_PAYMENT from Company to test party for $50 and set it to RECEIVED
String paymentId = financialAsserts.createPaymentAndApplication(new BigDecimal("50.0"), customerPartyId, organizationPartyId, "CUSTOMER_PAYMENT", "COMPANY_CHECK", null, invoiceId, "PMNT_NOT_PAID");
financialAsserts.updatePaymentStatus(paymentId, "PMNT_RECEIVED");
// run captureAccountBalancesSnapshot
inputParams = UtilMisc.toMap("userLogin", demofinadmin);
runAndAssertServiceSuccess("captureAccountBalancesSnapshot", inputParams);
// verify that there is a new account balance history record for test party and Company for 50
list = query.list();
assertEquals("There are two account balance history records for Company and " + customerPartyId, 2, list.size());
accountBalanceHistory = list.get(0);
assertEquals("There is a new account balance history record for Company and " + customerPartyId + " for 50.0", new BigDecimal("50.0"), accountBalanceHistory.getTotalBalance());
}
/**
* This test verifies that an unbalanced transaction cannot be posted, this uses the unbalanced test transaction LEDGER-TEST-2.
* @exception Exception if an error occurs
*/
@SuppressWarnings("unchecked")
public void testCannotPostAcctgTrans() throws Exception {
LedgerRepositoryInterface ledgerRepository = ledgerDomain.getLedgerRepository();
AccountingTransaction transaction = ledgerRepository.getAccountingTransaction("LEDGER-TEST-2");
// check canPost()
assertFalse("canPost() should not return true for LEDGER-TEST-2.", transaction.canPost());
// check that the service returns an error
Map input = UtilMisc.toMap("userLogin", demofinadmin, "acctgTransId", "LEDGER-TEST-2");
runAndAssertServiceError("postAcctgTrans", input);
}
/**
* This test verifies that we can get correct InvoiceAdjustmentType by InvoiceRepository.getInvoiceAdjustmentTypes method.
* @exception Exception if an error occurs
*/
public void testGetInvoiceAdjustmentTypes() throws Exception {
// create a sales invoice
String customerPartyId = createPartyFromTemplate("DemoAccount1", "test for InvoiceRepository.getInvoiceAdjustmentTypes");
FinancialAsserts financialAsserts = new FinancialAsserts(this, organizationPartyId, demofinadmin);
Timestamp invoiceDate = UtilDateTime.adjustTimestamp(UtilDateTime.nowTimestamp(), Calendar.DAY_OF_YEAR, 30, timeZone, locale);
String invoiceId = financialAsserts.createInvoice(customerPartyId, "SALES_INVOICE", invoiceDate, null, null, null);
financialAsserts.createInvoiceItem(invoiceId, "INV_FPROD_ITEM", "GZ-1000", new BigDecimal("2.0"), new BigDecimal("15.0"));
//verify that the correct list (three rec) of invoice adjustment types are returned for Company
Organization organizationCompany = organizationRepository.getOrganizationById(organizationPartyId);
Organization organizationCompanySub2 = organizationRepository.getOrganizationById("CompanySub2");
InvoiceRepositoryInterface invoiceRepository = billingDomain.getInvoiceRepository();
Invoice invoice = invoiceRepository.getInvoiceById(invoiceId);
List<InvoiceAdjustmentType> invoiceAdjustmentTypes = invoiceRepository.getInvoiceAdjustmentTypes(organizationCompany, invoice);
assertEquals("There should have three InvoiceAdjustmentType records for [" + organizationPartyId + "]", 3, invoiceAdjustmentTypes.size());
//verify none invoice adjustment types are returned for Company
invoiceAdjustmentTypes = invoiceRepository.getInvoiceAdjustmentTypes(organizationCompanySub2, invoice);
assertEquals("There should hasn't any InvoiceAdjustmentType record for [CompanySub2]", 0, invoiceAdjustmentTypes.size());
}
/**
* Test the Invoice fields calculation.
* @exception Exception if an error occurs
*/
public void testInvoiceFieldsCalculation() throws Exception {
// create a sales invoice
String customerPartyId = createPartyFromTemplate("DemoAccount1", "test for InvoiceFieldsCalculation");
FinancialAsserts financialAsserts = new FinancialAsserts(this, organizationPartyId, demofinadmin);
InvoiceRepositoryInterface invoiceRepository = billingDomain.getInvoiceRepository();
// create an invoice with one item and total 24
String invoiceId = financialAsserts.createInvoice(customerPartyId, "SALES_INVOICE");
financialAsserts.createInvoiceItem(invoiceId, "INV_FPROD_ITEM", "GZ-1000", new BigDecimal("2.0"), new BigDecimal("12.0"));
// check the invoice amounts at this point
Invoice invoice = invoiceRepository.getInvoiceById(invoiceId);
assertEquals("Invoice total incorrect for invoice [" + invoiceId + "]", invoice.getInvoiceTotal(), new BigDecimal("24"));
assertEquals("Open amount incorrect for invoice [" + invoiceId + "]", invoice.getOpenAmount(), new BigDecimal("24"));
assertEquals("Pending Open amount incorrect for invoice [" + invoiceId + "]", invoice.getPendingOpenAmount(), new BigDecimal("24"));
assertEquals("Applied amount incorrect for invoice [" + invoiceId + "]", invoice.getAppliedAmount(), BigDecimal.ZERO);
assertEquals("Pending Applied amount incorrect for invoice [" + invoiceId + "]", invoice.getPendingAppliedAmount(), BigDecimal.ZERO);
assertEquals("Adjusted amount incorrect for invoice [" + invoiceId + "]", invoice.getAdjustedAmount(), BigDecimal.ZERO);
assertEquals("Adjusted amount incorrect for invoice [" + invoiceId + "]", invoice.getInvoiceAdjustedTotal(), new BigDecimal("24"));
// create a payment and application of 5
String paymentId = financialAsserts.createPaymentAndApplication(new BigDecimal("5"), customerPartyId, organizationPartyId, "CUSTOMER_PAYMENT", "COMPANY_CHECK", null, invoiceId, "PMNT_NOT_PAID");
// check the invoice amounts at this point
// since an application is created but the payment was not received yet, it should only modify the pending amounts
invoice = invoiceRepository.getInvoiceById(invoiceId);
assertEquals("Invoice total incorrect for invoice [" + invoiceId + "]", invoice.getInvoiceTotal(), new BigDecimal("24"));
assertEquals("Open amount incorrect for invoice [" + invoiceId + "]", invoice.getOpenAmount(), new BigDecimal("24"));
assertEquals("Pending Open amount incorrect for invoice [" + invoiceId + "]", invoice.getPendingOpenAmount(), new BigDecimal("19"));
assertEquals("Applied amount incorrect for invoice [" + invoiceId + "]", invoice.getAppliedAmount(), BigDecimal.ZERO);
assertEquals("Pending Applied amount incorrect for invoice [" + invoiceId + "]", invoice.getPendingAppliedAmount(), new BigDecimal("5"));
assertEquals("Adjusted amount incorrect for invoice [" + invoiceId + "]", invoice.getAdjustedAmount(), BigDecimal.ZERO);
assertEquals("Adjusted amount incorrect for invoice [" + invoiceId + "]", invoice.getInvoiceAdjustedTotal(), new BigDecimal("24"));
// create an invoice adjustment as a -2 discount
runAndAssertServiceSuccess("createInvoiceAdjustment", UtilMisc.toMap("userLogin", demofinadmin, "invoiceId", invoiceId, "invoiceAdjustmentTypeId", "EARLY_PAY_DISCT", "adjustmentAmount", new BigDecimal("-2.0")));
// check the invoice amounts at this point
// this modifies the adjusted amount, adjusted total and open amounts
invoice = invoiceRepository.getInvoiceById(invoiceId);
assertEquals("Invoice total incorrect for invoice [" + invoiceId + "]", invoice.getInvoiceTotal(), new BigDecimal("24"));
assertEquals("Open amount incorrect for invoice [" + invoiceId + "]", invoice.getOpenAmount(), new BigDecimal("22"));
assertEquals("Pending Open amount incorrect for invoice [" + invoiceId + "]", invoice.getPendingOpenAmount(), new BigDecimal("17"));
assertEquals("Applied amount incorrect for invoice [" + invoiceId + "]", invoice.getAppliedAmount(), BigDecimal.ZERO);
assertEquals("Pending Applied amount incorrect for invoice [" + invoiceId + "]", invoice.getPendingAppliedAmount(), new BigDecimal("5"));
assertEquals("Adjusted amount incorrect for invoice [" + invoiceId + "]", invoice.getAdjustedAmount(), new BigDecimal("-2"));
assertEquals("Adjusted amount incorrect for invoice [" + invoiceId + "]", invoice.getInvoiceAdjustedTotal(), new BigDecimal("22"));
// create a second payment and application of 7
String paymentId2 = financialAsserts.createPaymentAndApplication(new BigDecimal("7"), customerPartyId, organizationPartyId, "CUSTOMER_PAYMENT", "COMPANY_CHECK", null, invoiceId, "PMNT_NOT_PAID");
// check the invoice amounts at this point
invoice = invoiceRepository.getInvoiceById(invoiceId);
assertEquals("Invoice total incorrect for invoice [" + invoiceId + "]", invoice.getInvoiceTotal(), new BigDecimal("24"));
assertEquals("Open amount incorrect for invoice [" + invoiceId + "]", invoice.getOpenAmount(), new BigDecimal("22"));
assertEquals("Pending Open amount incorrect for invoice [" + invoiceId + "]", invoice.getPendingOpenAmount(), new BigDecimal("10"));
assertEquals("Applied amount incorrect for invoice [" + invoiceId + "]", invoice.getAppliedAmount(), BigDecimal.ZERO);
assertEquals("Pending Applied amount incorrect for invoice [" + invoiceId + "]", invoice.getPendingAppliedAmount(), new BigDecimal("12"));
assertEquals("Adjusted amount incorrect for invoice [" + invoiceId + "]", invoice.getAdjustedAmount(), new BigDecimal("-2"));
assertEquals("Adjusted amount incorrect for invoice [" + invoiceId + "]", invoice.getInvoiceAdjustedTotal(), new BigDecimal("22"));
// mark the first payment as received
financialAsserts.updatePaymentStatus(paymentId, "PMNT_RECEIVED");
// check the invoice amounts at this point
invoice = invoiceRepository.getInvoiceById(invoiceId);
assertEquals("Invoice total incorrect for invoice [" + invoiceId + "]", invoice.getInvoiceTotal(), new BigDecimal("24"));
assertEquals("Open amount incorrect for invoice [" + invoiceId + "]", invoice.getOpenAmount(), new BigDecimal("17"));
assertEquals("Pending Open amount incorrect for invoice [" + invoiceId + "]", invoice.getPendingOpenAmount(), new BigDecimal("10"));
assertEquals("Applied amount incorrect for invoice [" + invoiceId + "]", invoice.getAppliedAmount(), new BigDecimal("5"));
assertEquals("Pending Applied amount incorrect for invoice [" + invoiceId + "]", invoice.getPendingAppliedAmount(), new BigDecimal("7"));
assertEquals("Adjusted amount incorrect for invoice [" + invoiceId + "]", invoice.getAdjustedAmount(), new BigDecimal("-2"));
assertEquals("Adjusted amount incorrect for invoice [" + invoiceId + "]", invoice.getInvoiceAdjustedTotal(), new BigDecimal("22"));
// add an invoice item of 3x5 15
financialAsserts.createInvoiceItem(invoiceId, "INV_FPROD_ITEM", "GZ-1005", new BigDecimal("3.0"), new BigDecimal("5.0"));
// check the invoice amounts at this point
invoice = invoiceRepository.getInvoiceById(invoiceId);
assertEquals("Invoice total incorrect for invoice [" + invoiceId + "]", invoice.getInvoiceTotal(), new BigDecimal("39"));
assertEquals("Open amount incorrect for invoice [" + invoiceId + "]", invoice.getOpenAmount(), new BigDecimal("32"));
assertEquals("Pending Open amount incorrect for invoice [" + invoiceId + "]", invoice.getPendingOpenAmount(), new BigDecimal("25"));
assertEquals("Applied amount incorrect for invoice [" + invoiceId + "]", invoice.getAppliedAmount(), new BigDecimal("5"));
assertEquals("Pending Applied amount incorrect for invoice [" + invoiceId + "]", invoice.getPendingAppliedAmount(), new BigDecimal("7"));
assertEquals("Adjusted amount incorrect for invoice [" + invoiceId + "]", invoice.getAdjustedAmount(), new BigDecimal("-2"));
assertEquals("Adjusted amount incorrect for invoice [" + invoiceId + "]", invoice.getInvoiceAdjustedTotal(), new BigDecimal("37"));
// mark the second payment as received
financialAsserts.updatePaymentStatus(paymentId2, "PMNT_RECEIVED");
// set the invoice ready
runAndAssertServiceSuccess("setInvoiceReadyAndCheckIfPaid", UtilMisc.toMap("invoiceId", invoiceId, "userLogin", demofinadmin));
// check the invoice amounts at this point
invoice = invoiceRepository.getInvoiceById(invoiceId);
assertEquals("Invoice total incorrect for invoice [" + invoiceId + "]", invoice.getInvoiceTotal(), new BigDecimal("39"));
assertEquals("Open amount incorrect for invoice [" + invoiceId + "]", invoice.getOpenAmount(), new BigDecimal("25"));
assertEquals("Pending Open amount incorrect for invoice [" + invoiceId + "]", invoice.getPendingOpenAmount(), new BigDecimal("25"));
assertEquals("Applied amount incorrect for invoice [" + invoiceId + "]", invoice.getAppliedAmount(), new BigDecimal("12"));
assertEquals("Pending Applied amount incorrect for invoice [" + invoiceId + "]", invoice.getPendingAppliedAmount(), BigDecimal.ZERO);
assertEquals("Adjusted amount incorrect for invoice [" + invoiceId + "]", invoice.getAdjustedAmount(), new BigDecimal("-2"));
assertEquals("Adjusted amount incorrect for invoice [" + invoiceId + "]", invoice.getInvoiceAdjustedTotal(), new BigDecimal("37"));
// create a final payment and application of 25, and receive it
String paymentId3 = financialAsserts.createPaymentAndApplication(new BigDecimal("25"), customerPartyId, organizationPartyId, "CUSTOMER_PAYMENT", "COMPANY_CHECK", null, invoiceId, "PMNT_NOT_PAID");
financialAsserts.updatePaymentStatus(paymentId3, "PMNT_RECEIVED");
// check the invoice amounts at this point
invoice = invoiceRepository.getInvoiceById(invoiceId);
assertEquals("Invoice total incorrect for invoice [" + invoiceId + "]", invoice.getInvoiceTotal(), new BigDecimal("39"));
assertEquals("Open amount incorrect for invoice [" + invoiceId + "]", invoice.getOpenAmount(), BigDecimal.ZERO);
assertEquals("Pending Open amount incorrect for invoice [" + invoiceId + "]", invoice.getPendingOpenAmount(), BigDecimal.ZERO);
assertEquals("Applied amount incorrect for invoice [" + invoiceId + "]", invoice.getAppliedAmount(), new BigDecimal("37"));
assertEquals("Pending Applied amount incorrect for invoice [" + invoiceId + "]", invoice.getPendingAppliedAmount(), BigDecimal.ZERO);
assertEquals("Adjusted amount incorrect for invoice [" + invoiceId + "]", invoice.getAdjustedAmount(), new BigDecimal("-2"));
assertEquals("Adjusted amount incorrect for invoice [" + invoiceId + "]", invoice.getInvoiceAdjustedTotal(), new BigDecimal("37"));
// check that the invoice is marked as PAID
assertTrue("Invoice [" + invoiceId + "] is paid", invoice.isPaid());
}
}
| true | true | public void testAccountsReceivableInvoiceAgingAndCustomerBalances() throws GeneralException {
/*
* 1. Create parties Customer A, Customer B, Customer C
*/
TestObjectGenerator generator = new TestObjectGenerator(delegator, dispatcher);
List<String> customerId = generator.getContacts(3);
assertNotNull("Three customers should be generated", customerId);
/*
* 2. Create invoices
*/
FinancialAsserts fa = new FinancialAsserts(this, organizationPartyId, demofinadmin);
/*
* (a) Create sales invoice #1 from Company to Customer A for $100, invoice date 91 days before current date, due date 30 days after invoice date
*/
String invoiceId1 = fa.createInvoice(customerId.get(0), "SALES_INVOICE", UtilDateTime.adjustTimestamp(UtilDateTime.nowTimestamp(), Calendar.DAY_OF_YEAR, -91, timeZone, locale), UtilDateTime.adjustTimestamp(UtilDateTime.nowTimestamp(), Calendar.DAY_OF_YEAR, -91 + 30, timeZone, locale), null, null, "invoiceId1");
fa.createInvoiceItem(invoiceId1, "INV_FPROD_ITEM", "WG-1111", new BigDecimal("1.0"), new BigDecimal("100.0"));
/*
* (b) Create sales invoice #2 from Company to Customer A for $50, invoice date 25 days before current date, due date 30 days after invoice date
*/
String invoiceId2 = fa.createInvoice(customerId.get(0), "SALES_INVOICE", UtilDateTime.adjustTimestamp(UtilDateTime.nowTimestamp(), Calendar.DAY_OF_YEAR, -25, timeZone, locale), UtilDateTime.adjustTimestamp(UtilDateTime.nowTimestamp(), Calendar.DAY_OF_YEAR, -25 + 30, timeZone, locale), null, null, "invoiceId2");
fa.createInvoiceItem(invoiceId2, "INV_FPROD_ITEM", "WG-1111", new BigDecimal("1.0"), new BigDecimal("50.0"));
/*
* (c) Create sales invoice #3 from Company to Customer B for $150, invoice date 55 days before current date, due date 60 days after invoice date
*/
String invoiceId3 = fa.createInvoice(customerId.get(1), "SALES_INVOICE", UtilDateTime.adjustTimestamp(UtilDateTime.nowTimestamp(), Calendar.DAY_OF_YEAR, -55, timeZone, locale), UtilDateTime.adjustTimestamp(UtilDateTime.nowTimestamp(), Calendar.DAY_OF_YEAR, -55 + 60, timeZone, locale), null, null, "invoiceId3");
fa.createInvoiceItem(invoiceId3, "INV_FPROD_ITEM", "WG-1111", new BigDecimal("1.0"), new BigDecimal("150.0"));
/*
* (d) Create sales invoice #4 from Company to Customer C for $170, invoice date 120 days before current date, due date 30 days after invoice date
*/
String invoiceId4 = fa.createInvoice(customerId.get(2), "SALES_INVOICE", UtilDateTime.adjustTimestamp(UtilDateTime.nowTimestamp(), Calendar.DAY_OF_YEAR, -120, timeZone, locale), UtilDateTime.adjustTimestamp(UtilDateTime.nowTimestamp(), Calendar.DAY_OF_YEAR, -120 + 30, timeZone, locale), null, null, "invoiceId4");
fa.createInvoiceItem(invoiceId4, "INV_FPROD_ITEM", "WG-1111", new BigDecimal("1.0"), new BigDecimal("170.0"));
/*
* (e) Create sales invoice #5 from Company to Customer B for $210, invoice date 15 days before current date, due date 7 days after invoice date
*/
String invoiceId5 = fa.createInvoice(customerId.get(1), "SALES_INVOICE", UtilDateTime.adjustTimestamp(UtilDateTime.nowTimestamp(), Calendar.DAY_OF_YEAR, -15, timeZone, locale), UtilDateTime.adjustTimestamp(UtilDateTime.nowTimestamp(), Calendar.DAY_OF_YEAR, -15 + 7, timeZone, locale), null, null, "invoiceId5");
fa.createInvoiceItem(invoiceId5, "INV_FPROD_ITEM", "WG-1111", new BigDecimal("1.0"), new BigDecimal("210.0"));
/*
* (f) Create sales invoice #6 from Company to Customer A for $500, invoice date 36 days before current date, due date 30 days after invoice date
*/
String invoiceId6 = fa.createInvoice(customerId.get(0), "SALES_INVOICE", UtilDateTime.adjustTimestamp(UtilDateTime.nowTimestamp(), Calendar.DAY_OF_YEAR, -36, timeZone, locale), UtilDateTime.adjustTimestamp(UtilDateTime.nowTimestamp(), Calendar.DAY_OF_YEAR, -36 + 30, timeZone, locale), null, null, "invoiceId6");
fa.createInvoiceItem(invoiceId6, "INV_FPROD_ITEM", "WG-1111", new BigDecimal("1.0"), new BigDecimal("500.0"));
/*
* (g) Create sales invoice #7 from Company to Customer C for $228, invoice date 42 days before current date, due date 45 days after invoice date
*/
String invoiceId7 = fa.createInvoice(customerId.get(2), "SALES_INVOICE", UtilDateTime.adjustTimestamp(UtilDateTime.nowTimestamp(), Calendar.DAY_OF_YEAR, -42, timeZone, locale), UtilDateTime.adjustTimestamp(UtilDateTime.nowTimestamp(), Calendar.DAY_OF_YEAR, -42 + 45, timeZone, locale), null, null, "invoiceId7");
fa.createInvoiceItem(invoiceId7, "INV_FPROD_ITEM", "WG-1111", new BigDecimal("1.0"), new BigDecimal("228.0"));
/*
* (h) Create sales invoice #8 from Company to Customer B for $65, invoice date 15 days before current date, due date 30 days after invoice date
*/
String invoiceId8 = fa.createInvoice(customerId.get(1), "SALES_INVOICE", UtilDateTime.adjustTimestamp(UtilDateTime.nowTimestamp(), Calendar.DAY_OF_YEAR, -15, timeZone, locale), UtilDateTime.adjustTimestamp(UtilDateTime.nowTimestamp(), Calendar.DAY_OF_YEAR, -15 + 30, timeZone, locale), null, null, "invoiceId8");
fa.createInvoiceItem(invoiceId8, "INV_FPROD_ITEM", "WG-1111", new BigDecimal("1.0"), new BigDecimal("65.0"));
/*
* (i) Create sales invoice #9 from Company to Customer A for $156, invoice date 6 days before current date, due date 15 days after invoice date
*/
String invoiceId9 = fa.createInvoice(customerId.get(0), "SALES_INVOICE", UtilDateTime.adjustTimestamp(UtilDateTime.nowTimestamp(), Calendar.DAY_OF_YEAR, -6, timeZone, locale), UtilDateTime.adjustTimestamp(UtilDateTime.nowTimestamp(), Calendar.DAY_OF_YEAR, -6 + 15, timeZone, locale), null, null, "invoiceId9");
fa.createInvoiceItem(invoiceId9, "INV_FPROD_ITEM", "WG-1111", new BigDecimal("1.0"), new BigDecimal("156.0"));
/*
* (j) Create sales invoice #10 from Company to Customer C for $550, invoice date 33 days before current date, due date 15 days after invoice date
*/
String invoiceId10 = fa.createInvoice(customerId.get(2), "SALES_INVOICE", UtilDateTime.adjustTimestamp(UtilDateTime.nowTimestamp(), Calendar.DAY_OF_YEAR, -33, timeZone, locale), UtilDateTime.adjustTimestamp(UtilDateTime.nowTimestamp(), Calendar.DAY_OF_YEAR, -33 + 15, timeZone, locale), null, null, "invoiceId10");
fa.createInvoiceItem(invoiceId10, "INV_FPROD_ITEM", "WG-1111", new BigDecimal("1.0"), new BigDecimal("550.0"));
/*
* (k) Create sales invoice #11 from Company to Customer B for $90, invoice date 62 days before current date, due date 90 days after invoice date
*/
String invoiceId11 = fa.createInvoice(customerId.get(1), "SALES_INVOICE", UtilDateTime.adjustTimestamp(UtilDateTime.nowTimestamp(), Calendar.DAY_OF_YEAR, -62, timeZone, locale), UtilDateTime.adjustTimestamp(UtilDateTime.nowTimestamp(), Calendar.DAY_OF_YEAR, -62 + 90, timeZone, locale), null, null, "invoiceId11");
fa.createInvoiceItem(invoiceId11, "INV_FPROD_ITEM", "WG-1111", new BigDecimal("1.0"), new BigDecimal("90.0"));
/*
* 3. Cancel invoice #2
*/
fa.updateInvoiceStatus(invoiceId2, "INVOICE_CANCELLED");
/*
* 4. Set all other invoices to READY
*/
fa.updateInvoiceStatus(invoiceId1, "INVOICE_READY");
fa.updateInvoiceStatus(invoiceId3, "INVOICE_READY");
fa.updateInvoiceStatus(invoiceId4, "INVOICE_READY");
fa.updateInvoiceStatus(invoiceId5, "INVOICE_READY");
fa.updateInvoiceStatus(invoiceId6, "INVOICE_READY");
fa.updateInvoiceStatus(invoiceId7, "INVOICE_READY");
fa.updateInvoiceStatus(invoiceId8, "INVOICE_READY");
fa.updateInvoiceStatus(invoiceId9, "INVOICE_READY");
fa.updateInvoiceStatus(invoiceId10, "INVOICE_READY");
fa.updateInvoiceStatus(invoiceId11, "INVOICE_READY");
/*
* 5. Set invoice #6 to VOID
*/
Map<String, Object> input = new HashMap<String, Object>();
input.put("userLogin", demofinadmin);
input.put("invoiceId", invoiceId6);
runAndAssertServiceSuccess("opentaps.voidInvoice", input);
/*
* 6. Set invoice #10 to WRITEOFF
*/
fa.updateInvoiceStatus(invoiceId10, "INVOICE_WRITEOFF");
/*
* 7. Receive a payment of $65 for invoice #8
*/
fa.createPaymentAndApplication(new BigDecimal("65.0"), customerId.get(1), organizationPartyId, "CUSTOMER_PAYMENT", "CREDIT_CARD", null, invoiceId8, "PMNT_RECEIVED");
/*
* 8. Receive a payment of $65 for invoice #11
*/
fa.createPaymentAndApplication(new BigDecimal("65.0"), customerId.get(1), organizationPartyId, "CUSTOMER_PAYMENT", "CREDIT_CARD", null, invoiceId11, "PMNT_RECEIVED");
/*
* 9. Create sales invoice #12 for Company to Customer A for $1000, invoice date now and due 30 days after invoicing, but do not set this invoice to READY
*/
String invoiceId12 = fa.createInvoice(customerId.get(0), "SALES_INVOICE", UtilDateTime.nowTimestamp(), UtilDateTime.adjustTimestamp(UtilDateTime.nowTimestamp(), Calendar.DAY_OF_YEAR, 30, timeZone, locale), null, null, "invoiceId12");
fa.createInvoiceItem(invoiceId12, "INV_FPROD_ITEM", "WG-1111", new BigDecimal("1.0"), new BigDecimal("1000.0"));
/*
* 10. Run AccountsHelper.getBalancesForAllCustomers and verify the following:
*/
Map<String, BigDecimal> balances = AccountsHelper.getBalancesForAllCustomers(organizationPartyId, "ACTUAL", UtilDateTime.nowTimestamp(), delegator);
/*
* (a) balance of Customer A is $256
*/
assertEquals("balance of Customer " + customerId.get(0) + " is " + balances.get(customerId.get(0)) + " and not $256", balances.get(customerId.get(0)), new BigDecimal("256.00"));
/*
* (b) balance of Customer B is $385
*/
assertEquals("balance of Customer " + customerId.get(1) + " is " + balances.get(customerId.get(1)) + " and not $385", balances.get(customerId.get(1)), new BigDecimal("385.00"));
/*
* (c) balance of Customer C is $398
*/
assertEquals("balance of Customer " + customerId.get(2) + " is " + balances.get(customerId.get(0)) + " and not $398", balances.get(customerId.get(2)), new BigDecimal("398.00"));
/*
* 11. Run AccountsHelper.getUnpaidInvoicesForCustomers and verify:
*/
Map<Integer, List> invoices = AccountsHelper.getUnpaidInvoicesForCustomers(organizationPartyId, UtilMisc.toList(new Integer(30), new Integer(60), new Integer(90), new Integer(9999)), UtilDateTime.nowTimestamp(), delegator, timeZone, locale);
assertNotNull("Unpaid Invoices For Customers not found.", invoices);
/*
* (b) 0-30 day bucket has invoices #5 and #9
*/
List<Invoice> invoicesList = invoices.get(30);
assertNotNull("Unpaid Invoices For Customers not found.", invoicesList);
boolean isPresent5 = false;
boolean isPresent9 = false;
for (Invoice invoice : invoicesList) {
if (invoiceId5.equals(invoice.getString("invoiceId"))) {
isPresent5 = true;
}
if (invoiceId9.equals(invoice.getString("invoiceId"))) {
isPresent9 = true;
}
}
assertTrue("Invoice " + invoiceId5 + " is not present in 0-30 day bucket", isPresent5);
assertTrue("Invoice " + invoiceId9 + " is not present in 0-30 day bucket", isPresent9);
/*
* (c) 30-60 day bucket has invoice #3 and #7
*/
invoicesList = invoices.get(60);
assertNotNull("Unpaid Invoices For Customers not found.", invoicesList);
boolean isPresent3 = false;
boolean isPresent7 = false;
for (Invoice invoice : invoicesList) {
if (invoiceId3.equals(invoice.getString("invoiceId"))) {
isPresent3 = true;
}
if (invoiceId7.equals(invoice.getString("invoiceId"))) {
isPresent7 = true;
}
}
assertTrue("Invoice " + invoiceId3 + " is not present in 30-60 day bucket", isPresent3);
assertTrue("Invoice " + invoiceId7 + " is not present in 30-60 day bucket", isPresent7);
/*
* (d) 60-90 day bucket has invoices #11
*/
invoicesList = invoices.get(90);
assertNotNull("Unpaid Invoices For Customers not found.", invoicesList);
boolean isPresent11 = false;
for (Invoice invoice : invoicesList) {
if (invoiceId11.equals(invoice.getString("invoiceId"))) {
isPresent11 = true;
}
}
assertTrue("Invoice " + invoiceId11 + " is not present in 60-90 day bucket", isPresent11);
/*
* (d) 90+ day bucket has invoices #1 and #4
*/
invoicesList = invoices.get(9999);
assertNotNull("Unpaid Invoices For Customers not found.", invoicesList);
boolean isPresent1 = false;
boolean isPresent4 = false;
for (Invoice invoice : invoicesList) {
if (invoiceId1.equals(invoice.getString("invoiceId"))) {
isPresent1 = true;
}
if (invoiceId4.equals(invoice.getString("invoiceId"))) {
isPresent4 = true;
}
}
assertTrue("Invoice " + invoiceId1 + " is not present in 90+ day bucket", isPresent1);
assertTrue("Invoice " + invoiceId4 + " is not present in 90+ day bucket", isPresent4);
/*
* 12. Create parties Customer D and Customer E
*/
List<String> extraCustomerIds = generator.getContacts(2);
assertNotNull("Two customers should be generated", extraCustomerIds);
assertEquals(2, extraCustomerIds.size());
customerId.addAll(extraCustomerIds);
/*
* 13. Create more sales invoices
*
* (a) Invoice #13 from Company to Customer D for $200, invoice date today, due in 30 days after invoice date
*/
String invoice13 = fa.createInvoice(customerId.get(3), "SALES_INVOICE", UtilDateTime.nowTimestamp(), UtilDateTime.adjustTimestamp(UtilDateTime.nowTimestamp(), Calendar.DAY_OF_YEAR, 30, timeZone, locale), null, null, "invoiceId13");
fa.createInvoiceItem(invoice13, "INV_FPROD_ITEM", "WG-1111", new BigDecimal("2.0"), new BigDecimal("100.0"));
/*
* (b) Invoice #14 from Company to Customer D for $300, invoice date today, due in 60 days after invoice date
*/
String invoice14 = fa.createInvoice(customerId.get(3), "SALES_INVOICE", UtilDateTime.nowTimestamp(), UtilDateTime.adjustTimestamp(UtilDateTime.nowTimestamp(), Calendar.DAY_OF_YEAR, 60, timeZone, locale), null, null, "invoice14");
fa.createInvoiceItem(invoice14, "INV_FPROD_ITEM", "WG-1111", new BigDecimal("3.0"), new BigDecimal("100.0"));
/*
* (c) Invoice #15 from Company to Customer E for $155, invoice date 58 days before today, due in 50 days after invoice date
*/
String invoice15 = fa.createInvoice(customerId.get(4), "SALES_INVOICE", UtilDateTime.adjustTimestamp(UtilDateTime.nowTimestamp(), Calendar.DAY_OF_YEAR, -58, timeZone, locale), UtilDateTime.adjustTimestamp(UtilDateTime.nowTimestamp(), Calendar.DAY_OF_YEAR, -58 + 50, timeZone, locale), null, null, "invoice15");
fa.createInvoiceItem(invoice15, "INV_FPROD_ITEM", "WG-1111", new BigDecimal("1.0"), new BigDecimal("155.0"));
/*
* (d) Invoice #16 from Company to Customer E for $266, invoice date 72 days before today, due in 30 days after invoice date
*/
String invoice16 = fa.createInvoice(customerId.get(4), "SALES_INVOICE", UtilDateTime.adjustTimestamp(UtilDateTime.nowTimestamp(), Calendar.DAY_OF_YEAR, -72, timeZone, locale), UtilDateTime.adjustTimestamp(UtilDateTime.nowTimestamp(), Calendar.DAY_OF_YEAR, -72 + 30, timeZone, locale), null, null, "invoice16");
fa.createInvoiceItem(invoice16, "INV_FPROD_ITEM", "WG-1111", new BigDecimal("1.0"), new BigDecimal("266.0"));
/*
* (e) Invoice #17 from Company to Customer E for $377, invoice date 115 days before today, due in 30 days after invoice date
*/
String invoice17 = fa.createInvoice(customerId.get(4), "SALES_INVOICE", UtilDateTime.adjustTimestamp(UtilDateTime.nowTimestamp(), Calendar.DAY_OF_YEAR, -115, timeZone, locale), UtilDateTime.adjustTimestamp(UtilDateTime.nowTimestamp(), Calendar.DAY_OF_YEAR, -115 + 30, timeZone, locale), null, null, "invoice17");
fa.createInvoiceItem(invoice17, "INV_FPROD_ITEM", "WG-1111", new BigDecimal("1.0"), new BigDecimal("377.0"));
/*
* (f) Invoice #18 from Company to Customer E for $488, invoice date 135 days before today, due in 30 days after invoice date
*/
String invoice18 = fa.createInvoice(customerId.get(4), "SALES_INVOICE", UtilDateTime.adjustTimestamp(UtilDateTime.nowTimestamp(), Calendar.DAY_OF_YEAR, -135, timeZone, locale), UtilDateTime.adjustTimestamp(UtilDateTime.nowTimestamp(), Calendar.DAY_OF_YEAR, -135 + 30, timeZone, locale), null, null, "invoice18");
fa.createInvoiceItem(invoice18, "INV_FPROD_ITEM", "WG-1111", new BigDecimal("1.0"), new BigDecimal("488.0"));
/*
* (g) Invoice #19 from Company to Customer E for $599, invoice date 160 days before today, due in 30 days after invoice date
*/
String invoice19 = fa.createInvoice(customerId.get(4), "SALES_INVOICE", UtilDateTime.adjustTimestamp(UtilDateTime.nowTimestamp(), Calendar.DAY_OF_YEAR, -160, timeZone, locale), UtilDateTime.adjustTimestamp(UtilDateTime.nowTimestamp(), Calendar.DAY_OF_YEAR, -160 + 30, timeZone, locale), null, null, "invoice19");
fa.createInvoiceItem(invoice19, "INV_FPROD_ITEM", "WG-1111", new BigDecimal("1.0"), new BigDecimal("599.0"));
/*
* (h) Invoice #20 from Company to Customer E for $44, invoice date 20 days before today, no due date (null)
*/
String invoice20 = fa.createInvoice(customerId.get(4), "SALES_INVOICE", UtilDateTime.adjustTimestamp(UtilDateTime.nowTimestamp(), Calendar.DAY_OF_YEAR, -20, timeZone, locale), null, null, null, "invoice20");
fa.createInvoiceItem(invoice20, "INV_FPROD_ITEM", "WG-1111", new BigDecimal("1.0"), new BigDecimal("44.0"));
/*
* 14. Set all invoices from (13) to ready.
*/
fa.updateInvoiceStatus(invoice13, "INVOICE_READY");
fa.updateInvoiceStatus(invoice14, "INVOICE_READY");
fa.updateInvoiceStatus(invoice15, "INVOICE_READY");
fa.updateInvoiceStatus(invoice16, "INVOICE_READY");
fa.updateInvoiceStatus(invoice17, "INVOICE_READY");
fa.updateInvoiceStatus(invoice18, "INVOICE_READY");
fa.updateInvoiceStatus(invoice19, "INVOICE_READY");
fa.updateInvoiceStatus(invoice20, "INVOICE_READY");
/*
* 15. Get customer statement (AccountsHelper.customerStatement) with useAgingDate=true and verify
*/
DomainsLoader dl = new DomainsLoader(new Infrastructure(dispatcher), new User(demofinadmin));
Map<String, Object> partyData = FastMap.newInstance();
AccountsHelper.customerStatement(dl, organizationPartyId, UtilMisc.toSet(customerId), UtilDateTime.nowTimestamp(), 30, true, partyData, locale, timeZone);
assertNotNull("Failed to create customer statement.", partyData);
/*
* (a) Customer A: isPastDue = true, current = $156, 30 - 60 days = 0, 60 - 90 days = $100, 90 - 120 days = 0, over 120 days = 0, total open amount = $256
*/
verifyCustomerStatement(customerId.get(0), partyData, true, new BigDecimal("156.0"), new BigDecimal("0.0"), new BigDecimal("100.0"), new BigDecimal("0.0"), new BigDecimal("0.0"), new BigDecimal("256.0"));
/*
* (b) Customer B: isPastDue = false, current = $385, 30 - 60 days = 0, 60 - 90 days = 0, 90 - 120 days = 0, over 120 days = 0, total open amount = $385
*/
verifyCustomerStatement(customerId.get(1), partyData, false, new BigDecimal("385.0"), new BigDecimal("0.0"), new BigDecimal("0.0"), new BigDecimal("0.0"), new BigDecimal("0.0"), new BigDecimal("385.0"));
/*
* (c) Customer C: isPastDue = true, current = $228, 30 - 60 days = 0, 60 - 90 days = 0, 90 - 120 days = $170, over 120 days = 0, total open amount = $398
*/
verifyCustomerStatement(customerId.get(2), partyData, true, new BigDecimal("228.0"), new BigDecimal("0.0"), new BigDecimal("0.0"), new BigDecimal("170.0"), new BigDecimal("0.0"), new BigDecimal("398.0"));
/*
* (d) Customer D: isPastDue = false, current = $500, 30 - 60 days = 0, 60 - 90 days = 0, 90 - 120 days = 0, over 120 days = 0, total open amount = $500
*/
verifyCustomerStatement(customerId.get(3), partyData, false, new BigDecimal("500.0"), new BigDecimal("0.0"), new BigDecimal("0.0"), new BigDecimal("0.0"), new BigDecimal("0.0"), new BigDecimal("500.0"));
/*
* (e) Customer E: isPastDue = true, current = $199, 30 - 60 days = 266, 60 - 90 days = 377, 90 - 120 days = 488, over 120 days = 599, total open amount = $1929
*/
verifyCustomerStatement(customerId.get(4), partyData, true, new BigDecimal("199.0"), new BigDecimal("266.0"), new BigDecimal("377.0"), new BigDecimal("488.0"), new BigDecimal("599.0"), new BigDecimal("1929.0"));
/*
* 16. Get customer statement (AccountsHelper.customerStatement) with useAgingDate=false and verify
*/
partyData = FastMap.newInstance();
AccountsHelper.customerStatement(dl, organizationPartyId, UtilMisc.toSet(customerId), UtilDateTime.nowTimestamp(), 30, false, partyData, locale, timeZone);
assertNotNull("Failed to create customer statement.", partyData);
/*
* (a) Customer A: isPastDue = true, current = $156, 30 - 60 days = 0, 60 - 90 days = 0, 90 - 120 days = $100, over 120 days = 0, total open amount = $256
*/
verifyCustomerStatement(customerId.get(0), partyData, true, new BigDecimal("156.0"), new BigDecimal("0.0"), new BigDecimal("0.0"), new BigDecimal("100.0"), new BigDecimal("0.0"), new BigDecimal("256.0"));
/*
* (b) Customer B: isPastDue = true, current = $210, 30 - 60 days = 150, 60 - 90 days = 25, 90 - 120 days = 0, over 120 days = 0, total open amount = $385
*/
verifyCustomerStatement(customerId.get(1), partyData, true, new BigDecimal("210.0"), new BigDecimal("150.0"), new BigDecimal("25.0"), new BigDecimal("0.0"), new BigDecimal("0.0"), new BigDecimal("385.0"));
/*
* (c) Customer C: isPastDue = true, current = 0, 30 - 60 days = 228, 60 - 90 days = 0, 90 - 120 days = 0, over 120 days = $170, total open amount = $398
* Note that invoice #4 from above is in the over 120 day bucket because it is dated 120 days before current timestamp, but aging calculation start at beginning of today
*/
verifyCustomerStatement(customerId.get(2), partyData, true, new BigDecimal("0.0"), new BigDecimal("228.0"), new BigDecimal("0.0"), new BigDecimal("0.0"), new BigDecimal("170.0"), new BigDecimal("398.0"));
/*
* (d) Customer D: isPastDue = false, current = $500, 30 - 60 days = 0, 60 - 90 days = 0, 90 - 120 days = 0, over 120 days = 0, total open amount = $500
*/
verifyCustomerStatement(customerId.get(3), partyData, false, new BigDecimal("500.0"), new BigDecimal("0.0"), new BigDecimal("0.0"), new BigDecimal("0.0"), new BigDecimal("0.0"), new BigDecimal("500.0"));
/*
* (e) Customer E: isPastDue = true, current = $44, 30 - 60 days = 155, 60 - 90 days = 266, 90 - 120 days = 377, over 120 days = 1087, total open amount = $1929
*/
verifyCustomerStatement(customerId.get(4), partyData, true, new BigDecimal("44.0"), new BigDecimal("155.0"), new BigDecimal("266.0"), new BigDecimal("377.0"), new BigDecimal("1087.0"), new BigDecimal("1929.0"));
}
| public void testAccountsReceivableInvoiceAgingAndCustomerBalances() throws GeneralException {
/*
* 1. Create parties Customer A, Customer B, Customer C
*/
TestObjectGenerator generator = new TestObjectGenerator(delegator, dispatcher);
List<String> customerId = generator.getContacts(3);
assertNotNull("Three customers should be generated", customerId);
/*
* 2. Create invoices
*/
FinancialAsserts fa = new FinancialAsserts(this, organizationPartyId, demofinadmin);
/*
* (a) Create sales invoice #1 from Company to Customer A for $100, invoice date 91 days before current date, due date 30 days after invoice date
*/
String invoiceId1 = fa.createInvoice(customerId.get(0), "SALES_INVOICE", UtilDateTime.adjustTimestamp(UtilDateTime.nowTimestamp(), Calendar.DAY_OF_YEAR, -91, timeZone, locale), UtilDateTime.adjustTimestamp(UtilDateTime.nowTimestamp(), Calendar.DAY_OF_YEAR, -91 + 30, timeZone, locale), null, null, "invoiceId1");
fa.createInvoiceItem(invoiceId1, "INV_FPROD_ITEM", "WG-1111", new BigDecimal("1.0"), new BigDecimal("100.0"));
/*
* (b) Create sales invoice #2 from Company to Customer A for $50, invoice date 25 days before current date, due date 30 days after invoice date
*/
String invoiceId2 = fa.createInvoice(customerId.get(0), "SALES_INVOICE", UtilDateTime.adjustTimestamp(UtilDateTime.nowTimestamp(), Calendar.DAY_OF_YEAR, -25, timeZone, locale), UtilDateTime.adjustTimestamp(UtilDateTime.nowTimestamp(), Calendar.DAY_OF_YEAR, -25 + 30, timeZone, locale), null, null, "invoiceId2");
fa.createInvoiceItem(invoiceId2, "INV_FPROD_ITEM", "WG-1111", new BigDecimal("1.0"), new BigDecimal("50.0"));
/*
* (c) Create sales invoice #3 from Company to Customer B for $150, invoice date 55 days before current date, due date 60 days after invoice date
*/
String invoiceId3 = fa.createInvoice(customerId.get(1), "SALES_INVOICE", UtilDateTime.adjustTimestamp(UtilDateTime.nowTimestamp(), Calendar.DAY_OF_YEAR, -55, timeZone, locale), UtilDateTime.adjustTimestamp(UtilDateTime.nowTimestamp(), Calendar.DAY_OF_YEAR, -55 + 60, timeZone, locale), null, null, "invoiceId3");
fa.createInvoiceItem(invoiceId3, "INV_FPROD_ITEM", "WG-1111", new BigDecimal("1.0"), new BigDecimal("150.0"));
/*
* (d) Create sales invoice #4 from Company to Customer C for $170, invoice date 120 days before current date, due date 30 days after invoice date
*/
String invoiceId4 = fa.createInvoice(customerId.get(2), "SALES_INVOICE", UtilDateTime.adjustTimestamp(UtilDateTime.nowTimestamp(), Calendar.DAY_OF_YEAR, -120, timeZone, locale), UtilDateTime.adjustTimestamp(UtilDateTime.nowTimestamp(), Calendar.DAY_OF_YEAR, -120 + 30, timeZone, locale), null, null, "invoiceId4");
fa.createInvoiceItem(invoiceId4, "INV_FPROD_ITEM", "WG-1111", new BigDecimal("1.0"), new BigDecimal("170.0"));
/*
* (e) Create sales invoice #5 from Company to Customer B for $210, invoice date 15 days before current date, due date 7 days after invoice date
*/
String invoiceId5 = fa.createInvoice(customerId.get(1), "SALES_INVOICE", UtilDateTime.adjustTimestamp(UtilDateTime.nowTimestamp(), Calendar.DAY_OF_YEAR, -15, timeZone, locale), UtilDateTime.adjustTimestamp(UtilDateTime.nowTimestamp(), Calendar.DAY_OF_YEAR, -15 + 7, timeZone, locale), null, null, "invoiceId5");
fa.createInvoiceItem(invoiceId5, "INV_FPROD_ITEM", "WG-1111", new BigDecimal("1.0"), new BigDecimal("210.0"));
/*
* (f) Create sales invoice #6 from Company to Customer A for $500, invoice date 36 days before current date, due date 30 days after invoice date
*/
String invoiceId6 = fa.createInvoice(customerId.get(0), "SALES_INVOICE", UtilDateTime.adjustTimestamp(UtilDateTime.nowTimestamp(), Calendar.DAY_OF_YEAR, -36, timeZone, locale), UtilDateTime.adjustTimestamp(UtilDateTime.nowTimestamp(), Calendar.DAY_OF_YEAR, -36 + 30, timeZone, locale), null, null, "invoiceId6");
fa.createInvoiceItem(invoiceId6, "INV_FPROD_ITEM", "WG-1111", new BigDecimal("1.0"), new BigDecimal("500.0"));
/*
* (g) Create sales invoice #7 from Company to Customer C for $228, invoice date 42 days before current date, due date 45 days after invoice date
*/
String invoiceId7 = fa.createInvoice(customerId.get(2), "SALES_INVOICE", UtilDateTime.adjustTimestamp(UtilDateTime.nowTimestamp(), Calendar.DAY_OF_YEAR, -42, timeZone, locale), UtilDateTime.adjustTimestamp(UtilDateTime.nowTimestamp(), Calendar.DAY_OF_YEAR, -42 + 45, timeZone, locale), null, null, "invoiceId7");
fa.createInvoiceItem(invoiceId7, "INV_FPROD_ITEM", "WG-1111", new BigDecimal("1.0"), new BigDecimal("228.0"));
/*
* (h) Create sales invoice #8 from Company to Customer B for $65, invoice date 15 days before current date, due date 30 days after invoice date
*/
String invoiceId8 = fa.createInvoice(customerId.get(1), "SALES_INVOICE", UtilDateTime.adjustTimestamp(UtilDateTime.nowTimestamp(), Calendar.DAY_OF_YEAR, -15, timeZone, locale), UtilDateTime.adjustTimestamp(UtilDateTime.nowTimestamp(), Calendar.DAY_OF_YEAR, -15 + 30, timeZone, locale), null, null, "invoiceId8");
fa.createInvoiceItem(invoiceId8, "INV_FPROD_ITEM", "WG-1111", new BigDecimal("1.0"), new BigDecimal("65.0"));
/*
* (i) Create sales invoice #9 from Company to Customer A for $156, invoice date 6 days before current date, due date 15 days after invoice date
*/
String invoiceId9 = fa.createInvoice(customerId.get(0), "SALES_INVOICE", UtilDateTime.adjustTimestamp(UtilDateTime.nowTimestamp(), Calendar.DAY_OF_YEAR, -6, timeZone, locale), UtilDateTime.adjustTimestamp(UtilDateTime.nowTimestamp(), Calendar.DAY_OF_YEAR, -6 + 15, timeZone, locale), null, null, "invoiceId9");
fa.createInvoiceItem(invoiceId9, "INV_FPROD_ITEM", "WG-1111", new BigDecimal("1.0"), new BigDecimal("156.0"));
/*
* (j) Create sales invoice #10 from Company to Customer C for $550, invoice date 33 days before current date, due date 15 days after invoice date
*/
String invoiceId10 = fa.createInvoice(customerId.get(2), "SALES_INVOICE", UtilDateTime.adjustTimestamp(UtilDateTime.nowTimestamp(), Calendar.DAY_OF_YEAR, -33, timeZone, locale), UtilDateTime.adjustTimestamp(UtilDateTime.nowTimestamp(), Calendar.DAY_OF_YEAR, -33 + 15, timeZone, locale), null, null, "invoiceId10");
fa.createInvoiceItem(invoiceId10, "INV_FPROD_ITEM", "WG-1111", new BigDecimal("1.0"), new BigDecimal("550.0"));
/*
* (k) Create sales invoice #11 from Company to Customer B for $90, invoice date 62 days before current date, due date 90 days after invoice date
*/
String invoiceId11 = fa.createInvoice(customerId.get(1), "SALES_INVOICE", UtilDateTime.adjustTimestamp(UtilDateTime.nowTimestamp(), Calendar.DAY_OF_YEAR, -62, timeZone, locale), UtilDateTime.adjustTimestamp(UtilDateTime.nowTimestamp(), Calendar.DAY_OF_YEAR, -62 + 90, timeZone, locale), null, null, "invoiceId11");
fa.createInvoiceItem(invoiceId11, "INV_FPROD_ITEM", "WG-1111", new BigDecimal("1.0"), new BigDecimal("90.0"));
/*
* 3. Cancel invoice #2
*/
fa.updateInvoiceStatus(invoiceId2, "INVOICE_CANCELLED");
/*
* 4. Set all other invoices to READY
*/
fa.updateInvoiceStatus(invoiceId1, "INVOICE_READY");
fa.updateInvoiceStatus(invoiceId3, "INVOICE_READY");
fa.updateInvoiceStatus(invoiceId4, "INVOICE_READY");
fa.updateInvoiceStatus(invoiceId5, "INVOICE_READY");
fa.updateInvoiceStatus(invoiceId6, "INVOICE_READY");
fa.updateInvoiceStatus(invoiceId7, "INVOICE_READY");
fa.updateInvoiceStatus(invoiceId8, "INVOICE_READY");
fa.updateInvoiceStatus(invoiceId9, "INVOICE_READY");
fa.updateInvoiceStatus(invoiceId10, "INVOICE_READY");
fa.updateInvoiceStatus(invoiceId11, "INVOICE_READY");
/*
* 5. Set invoice #6 to VOID
*/
Map<String, Object> input = new HashMap<String, Object>();
input.put("userLogin", demofinadmin);
input.put("invoiceId", invoiceId6);
runAndAssertServiceSuccess("opentaps.voidInvoice", input);
/*
* 6. Set invoice #10 to WRITEOFF
*/
fa.updateInvoiceStatus(invoiceId10, "INVOICE_WRITEOFF");
/*
* 7. Receive a payment of $65 for invoice #8
*/
fa.createPaymentAndApplication(new BigDecimal("65.0"), customerId.get(1), organizationPartyId, "CUSTOMER_PAYMENT", "CREDIT_CARD", null, invoiceId8, "PMNT_RECEIVED");
/*
* 8. Receive a payment of $65 for invoice #11
*/
fa.createPaymentAndApplication(new BigDecimal("65.0"), customerId.get(1), organizationPartyId, "CUSTOMER_PAYMENT", "CREDIT_CARD", null, invoiceId11, "PMNT_RECEIVED");
/*
* 9. Create sales invoice #12 for Company to Customer A for $1000, invoice date now and due 30 days after invoicing, but do not set this invoice to READY
*/
String invoiceId12 = fa.createInvoice(customerId.get(0), "SALES_INVOICE", UtilDateTime.nowTimestamp(), UtilDateTime.adjustTimestamp(UtilDateTime.nowTimestamp(), Calendar.DAY_OF_YEAR, 30, timeZone, locale), null, null, "invoiceId12");
fa.createInvoiceItem(invoiceId12, "INV_FPROD_ITEM", "WG-1111", new BigDecimal("1.0"), new BigDecimal("1000.0"));
/*
* 10. Run AccountsHelper.getBalancesForAllCustomers and verify the following:
*/
Map<String, BigDecimal> balances = AccountsHelper.getBalancesForAllCustomers(organizationPartyId, "ACTUAL", UtilDateTime.nowTimestamp(), delegator);
/*
* (a) balance of Customer A is $256
*/
assertEquals("balance of Customer " + customerId.get(0) + " is " + balances.get(customerId.get(0)) + " and not $256", balances.get(customerId.get(0)), new BigDecimal("256.00"));
/*
* (b) balance of Customer B is $385
*/
assertEquals("balance of Customer " + customerId.get(1) + " is " + balances.get(customerId.get(1)) + " and not $385", balances.get(customerId.get(1)), new BigDecimal("385.00"));
/*
* (c) balance of Customer C is $398
*/
assertEquals("balance of Customer " + customerId.get(2) + " is " + balances.get(customerId.get(0)) + " and not $398", balances.get(customerId.get(2)), new BigDecimal("398.00"));
/*
* 11. Run AccountsHelper.getUnpaidInvoicesForCustomers and verify:
*/
Map<Integer, List<Invoice>> invoices = AccountsHelper.getUnpaidInvoicesForCustomers(organizationPartyId, UtilMisc.toList(new Integer(30), new Integer(60), new Integer(90), new Integer(9999)), UtilDateTime.nowTimestamp(), delegator, timeZone, locale);
assertNotNull("Unpaid Invoices For Customers not found.", invoices);
/*
* (b) 0-30 day bucket has invoices #5 and #9
*/
List<Invoice> invoicesList = invoices.get(30);
assertNotNull("Unpaid Invoices For Customers not found.", invoicesList);
boolean isPresent5 = false;
boolean isPresent9 = false;
for (Invoice invoice : invoicesList) {
if (invoiceId5.equals(invoice.getString("invoiceId"))) {
isPresent5 = true;
}
if (invoiceId9.equals(invoice.getString("invoiceId"))) {
isPresent9 = true;
}
}
assertTrue("Invoice " + invoiceId5 + " is not present in 0-30 day bucket", isPresent5);
assertTrue("Invoice " + invoiceId9 + " is not present in 0-30 day bucket", isPresent9);
/*
* (c) 30-60 day bucket has invoice #3 and #7
*/
invoicesList = invoices.get(60);
assertNotNull("Unpaid Invoices For Customers not found.", invoicesList);
boolean isPresent3 = false;
boolean isPresent7 = false;
for (Invoice invoice : invoicesList) {
if (invoiceId3.equals(invoice.getString("invoiceId"))) {
isPresent3 = true;
}
if (invoiceId7.equals(invoice.getString("invoiceId"))) {
isPresent7 = true;
}
}
assertTrue("Invoice " + invoiceId3 + " is not present in 30-60 day bucket", isPresent3);
assertTrue("Invoice " + invoiceId7 + " is not present in 30-60 day bucket", isPresent7);
/*
* (d) 60-90 day bucket has invoices #11
*/
invoicesList = invoices.get(90);
assertNotNull("Unpaid Invoices For Customers not found.", invoicesList);
boolean isPresent11 = false;
for (Invoice invoice : invoicesList) {
if (invoiceId11.equals(invoice.getString("invoiceId"))) {
isPresent11 = true;
}
}
assertTrue("Invoice " + invoiceId11 + " is not present in 60-90 day bucket", isPresent11);
/*
* (d) 90+ day bucket has invoices #1 and #4
*/
invoicesList = invoices.get(9999);
assertNotNull("Unpaid Invoices For Customers not found.", invoicesList);
boolean isPresent1 = false;
boolean isPresent4 = false;
for (Invoice invoice : invoicesList) {
if (invoiceId1.equals(invoice.getString("invoiceId"))) {
isPresent1 = true;
}
if (invoiceId4.equals(invoice.getString("invoiceId"))) {
isPresent4 = true;
}
}
assertTrue("Invoice " + invoiceId1 + " is not present in 90+ day bucket", isPresent1);
assertTrue("Invoice " + invoiceId4 + " is not present in 90+ day bucket", isPresent4);
/*
* 12. Create parties Customer D and Customer E
*/
List<String> extraCustomerIds = generator.getContacts(2);
assertNotNull("Two customers should be generated", extraCustomerIds);
assertEquals(2, extraCustomerIds.size());
customerId.addAll(extraCustomerIds);
/*
* 13. Create more sales invoices
*
* (a) Invoice #13 from Company to Customer D for $200, invoice date today, due in 30 days after invoice date
*/
String invoice13 = fa.createInvoice(customerId.get(3), "SALES_INVOICE", UtilDateTime.nowTimestamp(), UtilDateTime.adjustTimestamp(UtilDateTime.nowTimestamp(), Calendar.DAY_OF_YEAR, 30, timeZone, locale), null, null, "invoiceId13");
fa.createInvoiceItem(invoice13, "INV_FPROD_ITEM", "WG-1111", new BigDecimal("2.0"), new BigDecimal("100.0"));
/*
* (b) Invoice #14 from Company to Customer D for $300, invoice date today, due in 60 days after invoice date
*/
String invoice14 = fa.createInvoice(customerId.get(3), "SALES_INVOICE", UtilDateTime.nowTimestamp(), UtilDateTime.adjustTimestamp(UtilDateTime.nowTimestamp(), Calendar.DAY_OF_YEAR, 60, timeZone, locale), null, null, "invoice14");
fa.createInvoiceItem(invoice14, "INV_FPROD_ITEM", "WG-1111", new BigDecimal("3.0"), new BigDecimal("100.0"));
/*
* (c) Invoice #15 from Company to Customer E for $155, invoice date 58 days before today, due in 50 days after invoice date
*/
String invoice15 = fa.createInvoice(customerId.get(4), "SALES_INVOICE", UtilDateTime.adjustTimestamp(UtilDateTime.nowTimestamp(), Calendar.DAY_OF_YEAR, -58, timeZone, locale), UtilDateTime.adjustTimestamp(UtilDateTime.nowTimestamp(), Calendar.DAY_OF_YEAR, -58 + 50, timeZone, locale), null, null, "invoice15");
fa.createInvoiceItem(invoice15, "INV_FPROD_ITEM", "WG-1111", new BigDecimal("1.0"), new BigDecimal("155.0"));
/*
* (d) Invoice #16 from Company to Customer E for $266, invoice date 72 days before today, due in 30 days after invoice date
*/
String invoice16 = fa.createInvoice(customerId.get(4), "SALES_INVOICE", UtilDateTime.adjustTimestamp(UtilDateTime.nowTimestamp(), Calendar.DAY_OF_YEAR, -72, timeZone, locale), UtilDateTime.adjustTimestamp(UtilDateTime.nowTimestamp(), Calendar.DAY_OF_YEAR, -72 + 30, timeZone, locale), null, null, "invoice16");
fa.createInvoiceItem(invoice16, "INV_FPROD_ITEM", "WG-1111", new BigDecimal("1.0"), new BigDecimal("266.0"));
/*
* (e) Invoice #17 from Company to Customer E for $377, invoice date 115 days before today, due in 30 days after invoice date
*/
String invoice17 = fa.createInvoice(customerId.get(4), "SALES_INVOICE", UtilDateTime.adjustTimestamp(UtilDateTime.nowTimestamp(), Calendar.DAY_OF_YEAR, -115, timeZone, locale), UtilDateTime.adjustTimestamp(UtilDateTime.nowTimestamp(), Calendar.DAY_OF_YEAR, -115 + 30, timeZone, locale), null, null, "invoice17");
fa.createInvoiceItem(invoice17, "INV_FPROD_ITEM", "WG-1111", new BigDecimal("1.0"), new BigDecimal("377.0"));
/*
* (f) Invoice #18 from Company to Customer E for $488, invoice date 135 days before today, due in 30 days after invoice date
*/
String invoice18 = fa.createInvoice(customerId.get(4), "SALES_INVOICE", UtilDateTime.adjustTimestamp(UtilDateTime.nowTimestamp(), Calendar.DAY_OF_YEAR, -135, timeZone, locale), UtilDateTime.adjustTimestamp(UtilDateTime.nowTimestamp(), Calendar.DAY_OF_YEAR, -135 + 30, timeZone, locale), null, null, "invoice18");
fa.createInvoiceItem(invoice18, "INV_FPROD_ITEM", "WG-1111", new BigDecimal("1.0"), new BigDecimal("488.0"));
/*
* (g) Invoice #19 from Company to Customer E for $599, invoice date 160 days before today, due in 30 days after invoice date
*/
String invoice19 = fa.createInvoice(customerId.get(4), "SALES_INVOICE", UtilDateTime.adjustTimestamp(UtilDateTime.nowTimestamp(), Calendar.DAY_OF_YEAR, -160, timeZone, locale), UtilDateTime.adjustTimestamp(UtilDateTime.nowTimestamp(), Calendar.DAY_OF_YEAR, -160 + 30, timeZone, locale), null, null, "invoice19");
fa.createInvoiceItem(invoice19, "INV_FPROD_ITEM", "WG-1111", new BigDecimal("1.0"), new BigDecimal("599.0"));
/*
* (h) Invoice #20 from Company to Customer E for $44, invoice date 20 days before today, no due date (null)
*/
String invoice20 = fa.createInvoice(customerId.get(4), "SALES_INVOICE", UtilDateTime.adjustTimestamp(UtilDateTime.nowTimestamp(), Calendar.DAY_OF_YEAR, -20, timeZone, locale), null, null, null, "invoice20");
fa.createInvoiceItem(invoice20, "INV_FPROD_ITEM", "WG-1111", new BigDecimal("1.0"), new BigDecimal("44.0"));
/*
* 14. Set all invoices from (13) to ready.
*/
fa.updateInvoiceStatus(invoice13, "INVOICE_READY");
fa.updateInvoiceStatus(invoice14, "INVOICE_READY");
fa.updateInvoiceStatus(invoice15, "INVOICE_READY");
fa.updateInvoiceStatus(invoice16, "INVOICE_READY");
fa.updateInvoiceStatus(invoice17, "INVOICE_READY");
fa.updateInvoiceStatus(invoice18, "INVOICE_READY");
fa.updateInvoiceStatus(invoice19, "INVOICE_READY");
fa.updateInvoiceStatus(invoice20, "INVOICE_READY");
/*
* 15. Get customer statement (AccountsHelper.customerStatement) with useAgingDate=true and verify
*/
DomainsLoader dl = new DomainsLoader(new Infrastructure(dispatcher), new User(demofinadmin));
Map<String, Object> partyData = FastMap.newInstance();
AccountsHelper.customerStatement(dl, organizationPartyId, UtilMisc.toSet(customerId), UtilDateTime.nowTimestamp(), 30, true, partyData, locale, timeZone);
assertNotNull("Failed to create customer statement.", partyData);
/*
* (a) Customer A: isPastDue = true, current = $156, 30 - 60 days = 0, 60 - 90 days = $100, 90 - 120 days = 0, over 120 days = 0, total open amount = $256
*/
verifyCustomerStatement(customerId.get(0), partyData, true, new BigDecimal("156.0"), new BigDecimal("0.0"), new BigDecimal("100.0"), new BigDecimal("0.0"), new BigDecimal("0.0"), new BigDecimal("256.0"));
/*
* (b) Customer B: isPastDue = false, current = $385, 30 - 60 days = 0, 60 - 90 days = 0, 90 - 120 days = 0, over 120 days = 0, total open amount = $385
*/
verifyCustomerStatement(customerId.get(1), partyData, false, new BigDecimal("385.0"), new BigDecimal("0.0"), new BigDecimal("0.0"), new BigDecimal("0.0"), new BigDecimal("0.0"), new BigDecimal("385.0"));
/*
* (c) Customer C: isPastDue = true, current = $228, 30 - 60 days = 0, 60 - 90 days = 0, 90 - 120 days = $170, over 120 days = 0, total open amount = $398
*/
verifyCustomerStatement(customerId.get(2), partyData, true, new BigDecimal("228.0"), new BigDecimal("0.0"), new BigDecimal("0.0"), new BigDecimal("170.0"), new BigDecimal("0.0"), new BigDecimal("398.0"));
/*
* (d) Customer D: isPastDue = false, current = $500, 30 - 60 days = 0, 60 - 90 days = 0, 90 - 120 days = 0, over 120 days = 0, total open amount = $500
*/
verifyCustomerStatement(customerId.get(3), partyData, false, new BigDecimal("500.0"), new BigDecimal("0.0"), new BigDecimal("0.0"), new BigDecimal("0.0"), new BigDecimal("0.0"), new BigDecimal("500.0"));
/*
* (e) Customer E: isPastDue = true, current = $199, 30 - 60 days = 266, 60 - 90 days = 377, 90 - 120 days = 488, over 120 days = 599, total open amount = $1929
*/
verifyCustomerStatement(customerId.get(4), partyData, true, new BigDecimal("199.0"), new BigDecimal("266.0"), new BigDecimal("377.0"), new BigDecimal("488.0"), new BigDecimal("599.0"), new BigDecimal("1929.0"));
/*
* 16. Get customer statement (AccountsHelper.customerStatement) with useAgingDate=false and verify
*/
partyData = FastMap.newInstance();
AccountsHelper.customerStatement(dl, organizationPartyId, UtilMisc.toSet(customerId), UtilDateTime.nowTimestamp(), 30, false, partyData, locale, timeZone);
assertNotNull("Failed to create customer statement.", partyData);
/*
* (a) Customer A: isPastDue = true, current = $156, 30 - 60 days = 0, 60 - 90 days = 0, 90 - 120 days = $100, over 120 days = 0, total open amount = $256
*/
verifyCustomerStatement(customerId.get(0), partyData, true, new BigDecimal("156.0"), new BigDecimal("0.0"), new BigDecimal("0.0"), new BigDecimal("100.0"), new BigDecimal("0.0"), new BigDecimal("256.0"));
/*
* (b) Customer B: isPastDue = true, current = $210, 30 - 60 days = 150, 60 - 90 days = 25, 90 - 120 days = 0, over 120 days = 0, total open amount = $385
*/
verifyCustomerStatement(customerId.get(1), partyData, true, new BigDecimal("210.0"), new BigDecimal("150.0"), new BigDecimal("25.0"), new BigDecimal("0.0"), new BigDecimal("0.0"), new BigDecimal("385.0"));
/*
* (c) Customer C: isPastDue = true, current = 0, 30 - 60 days = 228, 60 - 90 days = 0, 90 - 120 days = 0, over 120 days = $170, total open amount = $398
* Note that invoice #4 from above is in the over 120 day bucket because it is dated 120 days before current timestamp, but aging calculation start at beginning of today
*/
verifyCustomerStatement(customerId.get(2), partyData, true, new BigDecimal("0.0"), new BigDecimal("228.0"), new BigDecimal("0.0"), new BigDecimal("0.0"), new BigDecimal("170.0"), new BigDecimal("398.0"));
/*
* (d) Customer D: isPastDue = false, current = $500, 30 - 60 days = 0, 60 - 90 days = 0, 90 - 120 days = 0, over 120 days = 0, total open amount = $500
*/
verifyCustomerStatement(customerId.get(3), partyData, false, new BigDecimal("500.0"), new BigDecimal("0.0"), new BigDecimal("0.0"), new BigDecimal("0.0"), new BigDecimal("0.0"), new BigDecimal("500.0"));
/*
* (e) Customer E: isPastDue = true, current = $44, 30 - 60 days = 155, 60 - 90 days = 266, 90 - 120 days = 377, over 120 days = 1087, total open amount = $1929
*/
verifyCustomerStatement(customerId.get(4), partyData, true, new BigDecimal("44.0"), new BigDecimal("155.0"), new BigDecimal("266.0"), new BigDecimal("377.0"), new BigDecimal("1087.0"), new BigDecimal("1929.0"));
}
|
diff --git a/src/Model/Scheduler.java b/src/Model/Scheduler.java
index 167c1d3..b7a2347 100644
--- a/src/Model/Scheduler.java
+++ b/src/Model/Scheduler.java
@@ -1,126 +1,126 @@
package Model;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
public class Scheduler {
private List<Pair<Task, Integer>> executionLog;
private List<SThread> threads, freeThreads;
private long begin, end;
private List<Node> lock;
private Graph graph;
private double timeElapsed;
public void addExecution(int thread, Task task){
executionLog.add(new Pair(task, thread));
}
//TODO make it work for many threads
public void execute() throws Exception {
begin = System.currentTimeMillis();
executeAux();
}
private void executeAux() throws Exception {
if(graph == null) return;
while(graph.hasOrphan() || !allThreadsFree()){
while(graph.hasOrphan() && this.hasFreeThread()){
//Bind a thread and a task and run it
Node node = graph.popOrphan();
SThread t = this.popFreeThread();
this.addExecution(threads.indexOf(t), node.getTask());
//System.out.println("NumParents:"+node.getNumParents()+" "+node.getTaskName());
t.addTask(node);
t.setLock(lock);
t.start();
}
synchronized(lock){
//System.out.println("waiting");
- lock.wait();
- //System.out.print("I explored all orphans"+lock.size()+"\n");
- //for(int i = 0; i < lock.size(); i++)
- // System.out.println(lock.get(i));
+ if(!allThreadsFree()){
+ lock.wait();
+ }
+ //System.out.println("going");
while(!lock.isEmpty()){
Node n = lock.get(0);
graph.removeNode(n);
lock.remove(n);
}
}
}
// synchronized(lock){
// while(!allThreadsFree()){
// System.out.println("waiting the completion");
// lock.wait();
// }
// }
end = System.currentTimeMillis();
timeElapsed += (end-begin)/1000.;
//System.out.println("NumThreads:"+numThreadsRunning);
}
//It removes a thread from the free threads list and execute a task on it
private synchronized SThread popFreeThread() throws Exception {
if(freeThreads.isEmpty()) throw new Exception("Trying to use more threads than what is available.");
SThread t = freeThreads.get(0);
freeThreads.remove(0);
return t;
}
public boolean hasFreeThread() {
return !freeThreads.isEmpty();
}
public boolean allThreadsFree(){
return freeThreads.size() == threads.size();
}
public void addFreeThread(SThread thread){
SThread newt = new SThread(this);
this.freeThreads.add(0, newt);
Collections.replaceAll(this.threads, thread, newt);
}
public synchronized SThread getThread(int index){
return this.threads.get(index);
}
public Graph getGraph(){
return graph;
}
public int getNumThreads(){
return this.threads.size();
}
public double getTimeElapsed(){ return timeElapsed;}
public Scheduler(int numThreads, Graph g){
executionLog = new LinkedList();
this.graph = g;
this.lock = new LinkedList();
this.threads = new LinkedList();
this.freeThreads = new LinkedList();
this.timeElapsed = 0;
for(int i = 0; i < numThreads; i++){
SThread n = new SThread(this);
this.threads.add(n);
this.freeThreads.add(n);
}
}
public Scheduler(int numThreads){
this(numThreads, null);
}
@Override
public String toString(){
String out = "Schedule:\n";
for(Pair<Task, Integer> order: executionLog){
out += String.format("\tTask: %s\t Thread: %s Status: %s\n", order.getKey().getName(), order.getValue(), order.getKey().getStatus());
}
out += String.format("----------------\nElapsed: %7.3f sec\n", timeElapsed);
return out;
}
}
| true | true | private void executeAux() throws Exception {
if(graph == null) return;
while(graph.hasOrphan() || !allThreadsFree()){
while(graph.hasOrphan() && this.hasFreeThread()){
//Bind a thread and a task and run it
Node node = graph.popOrphan();
SThread t = this.popFreeThread();
this.addExecution(threads.indexOf(t), node.getTask());
//System.out.println("NumParents:"+node.getNumParents()+" "+node.getTaskName());
t.addTask(node);
t.setLock(lock);
t.start();
}
synchronized(lock){
//System.out.println("waiting");
lock.wait();
//System.out.print("I explored all orphans"+lock.size()+"\n");
//for(int i = 0; i < lock.size(); i++)
// System.out.println(lock.get(i));
while(!lock.isEmpty()){
Node n = lock.get(0);
graph.removeNode(n);
lock.remove(n);
}
}
}
// synchronized(lock){
// while(!allThreadsFree()){
// System.out.println("waiting the completion");
// lock.wait();
// }
// }
end = System.currentTimeMillis();
timeElapsed += (end-begin)/1000.;
//System.out.println("NumThreads:"+numThreadsRunning);
}
| private void executeAux() throws Exception {
if(graph == null) return;
while(graph.hasOrphan() || !allThreadsFree()){
while(graph.hasOrphan() && this.hasFreeThread()){
//Bind a thread and a task and run it
Node node = graph.popOrphan();
SThread t = this.popFreeThread();
this.addExecution(threads.indexOf(t), node.getTask());
//System.out.println("NumParents:"+node.getNumParents()+" "+node.getTaskName());
t.addTask(node);
t.setLock(lock);
t.start();
}
synchronized(lock){
//System.out.println("waiting");
if(!allThreadsFree()){
lock.wait();
}
//System.out.println("going");
while(!lock.isEmpty()){
Node n = lock.get(0);
graph.removeNode(n);
lock.remove(n);
}
}
}
// synchronized(lock){
// while(!allThreadsFree()){
// System.out.println("waiting the completion");
// lock.wait();
// }
// }
end = System.currentTimeMillis();
timeElapsed += (end-begin)/1000.;
//System.out.println("NumThreads:"+numThreadsRunning);
}
|
diff --git a/src/net/zschech/gwt/comet/rebind/CometSerializerGenerator.java b/src/net/zschech/gwt/comet/rebind/CometSerializerGenerator.java
index 7170a2f..0ce5ed9 100644
--- a/src/net/zschech/gwt/comet/rebind/CometSerializerGenerator.java
+++ b/src/net/zschech/gwt/comet/rebind/CometSerializerGenerator.java
@@ -1,158 +1,159 @@
/*
* Copyright 2009 Richard Zschech.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package net.zschech.gwt.comet.rebind;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.Serializable;
import java.util.List;
import net.zschech.gwt.comet.client.SerialMode;
import net.zschech.gwt.comet.client.SerialTypes;
import com.google.gwt.core.ext.Generator;
import com.google.gwt.core.ext.GeneratorContext;
import com.google.gwt.core.ext.TreeLogger;
import com.google.gwt.core.ext.UnableToCompleteException;
import com.google.gwt.core.ext.typeinfo.JClassType;
import com.google.gwt.core.ext.typeinfo.JField;
import com.google.gwt.core.ext.typeinfo.JType;
import com.google.gwt.core.ext.typeinfo.NotFoundException;
import com.google.gwt.core.ext.typeinfo.TypeOracle;
import com.google.gwt.dev.javac.TypeOracleMediator;
import com.google.gwt.dev.util.collect.Lists;
import com.google.gwt.rpc.linker.RpcDataArtifact;
import com.google.gwt.user.client.rpc.impl.Serializer;
import com.google.gwt.user.rebind.ClassSourceFileComposerFactory;
import com.google.gwt.user.rebind.SourceWriter;
import com.google.gwt.user.rebind.rpc.SerializableTypeOracle;
import com.google.gwt.user.rebind.rpc.SerializableTypeOracleBuilder;
import com.google.gwt.user.rebind.rpc.SerializationUtils;
import com.google.gwt.user.rebind.rpc.TypeSerializerCreator;
public class CometSerializerGenerator extends Generator {
@Override
public String generate(TreeLogger logger, GeneratorContext context, String typeName) throws UnableToCompleteException {
TypeOracle typeOracle = context.getTypeOracle();
// Create the CometSerializer impl
String packageName = "comet";
String className = typeName.replace('.', '_') + "Impl";
PrintWriter printWriter = context.tryCreate(logger, packageName, className);
if (printWriter != null) {
try {
JClassType type = typeOracle.getType(typeName);
SerialTypes annotation = type.getAnnotation(SerialTypes.class);
if (annotation == null) {
logger.log(TreeLogger.ERROR, "No SerialTypes annotation on CometSerializer type: " + typeName);
throw new UnableToCompleteException();
}
SerializableTypeOracleBuilder typesSentToBrowserBuilder = new SerializableTypeOracleBuilder(logger, context.getPropertyOracle(), typeOracle);
SerializableTypeOracleBuilder typesSentFromBrowserBuilder = new SerializableTypeOracleBuilder(logger, context.getPropertyOracle(), typeOracle);
for (Class<? extends Serializable> serializable : annotation.value()) {
int rank = 0;
if (serializable.isArray()) {
while (serializable.isArray()) {
serializable = (Class<? extends Serializable>) serializable.getComponentType();
rank++;
}
}
JType resolvedType = typeOracle.getType(serializable.getCanonicalName());
while (rank > 0) {
resolvedType = typeOracle.getArrayType(resolvedType);
rank--;
}
typesSentToBrowserBuilder.addRootType(logger, resolvedType);
}
OutputStream pathInfo = context.tryCreateResource(logger, typeName + ".rpc.log");
PrintWriter writer = new PrintWriter(new OutputStreamWriter(pathInfo));
writer.write("====================================\n");
writer.write("Types potentially sent from browser:\n");
writer.write("====================================\n\n");
writer.flush();
typesSentToBrowserBuilder.setLogOutputWriter(writer);
SerializableTypeOracle typesSentFromBrowser = typesSentFromBrowserBuilder.build(logger);
writer.write("===================================\n");
writer.write("Types potentially sent from server:\n");
writer.write("===================================\n\n");
writer.flush();
typesSentFromBrowserBuilder.setLogOutputWriter(writer);
SerializableTypeOracle typesSentToBrowser = typesSentToBrowserBuilder.build(logger);
writer.close();
if (pathInfo != null) {
context.commitResource(logger, pathInfo).setPrivate(true);
}
// Create the serializer
- TypeSerializerCreator tsc = new TypeSerializerCreator(logger, typesSentFromBrowser, typesSentToBrowser, context, "comet." + typeName.replace('.', '_') + "Serializer");
+ String modifiedTypeName = typeName.replace('.', '_') + "Serializer";
+ TypeSerializerCreator tsc = new TypeSerializerCreator(logger, typesSentFromBrowser, typesSentToBrowser, context, "comet." + modifiedTypeName, modifiedTypeName);
String realize = tsc.realize(logger);
// Create the CometSerializer impl
ClassSourceFileComposerFactory composerFactory = new ClassSourceFileComposerFactory(packageName, className);
composerFactory.addImport(Serializer.class.getName());
composerFactory.addImport(SerialMode.class.getName());
composerFactory.setSuperclass(typeName);
// TODO is the SERIALIZER required for DE RPC?
SourceWriter sourceWriter = composerFactory.createSourceWriter(context, printWriter);
sourceWriter.print("private Serializer SERIALIZER = new " + realize + "();");
sourceWriter.print("protected Serializer getSerializer() {return SERIALIZER;}");
sourceWriter.print("public SerialMode getMode() {return SerialMode." + annotation.mode().name() + ";}");
sourceWriter.commit(logger);
if (annotation.mode() == SerialMode.DE_RPC) {
RpcDataArtifact data = new RpcDataArtifact(type.getQualifiedSourceName());
for (JType t : typesSentToBrowser.getSerializableTypes()) {
if (!(t instanceof JClassType)) {
continue;
}
JField[] serializableFields = SerializationUtils.getSerializableFields(context.getTypeOracle(), (JClassType) t);
List<String> names = Lists.create();
for (int i = 0, j = serializableFields.length; i < j; i++) {
names = Lists.add(names, serializableFields[i].getName());
}
data.setFields(TypeOracleMediator.computeBinaryClassName(t), names);
}
context.commitArtifact(logger, data);
}
}
catch (NotFoundException e) {
logger.log(TreeLogger.ERROR, "", e);
throw new UnableToCompleteException();
}
}
return packageName + '.' + className;
}
}
| true | true | public String generate(TreeLogger logger, GeneratorContext context, String typeName) throws UnableToCompleteException {
TypeOracle typeOracle = context.getTypeOracle();
// Create the CometSerializer impl
String packageName = "comet";
String className = typeName.replace('.', '_') + "Impl";
PrintWriter printWriter = context.tryCreate(logger, packageName, className);
if (printWriter != null) {
try {
JClassType type = typeOracle.getType(typeName);
SerialTypes annotation = type.getAnnotation(SerialTypes.class);
if (annotation == null) {
logger.log(TreeLogger.ERROR, "No SerialTypes annotation on CometSerializer type: " + typeName);
throw new UnableToCompleteException();
}
SerializableTypeOracleBuilder typesSentToBrowserBuilder = new SerializableTypeOracleBuilder(logger, context.getPropertyOracle(), typeOracle);
SerializableTypeOracleBuilder typesSentFromBrowserBuilder = new SerializableTypeOracleBuilder(logger, context.getPropertyOracle(), typeOracle);
for (Class<? extends Serializable> serializable : annotation.value()) {
int rank = 0;
if (serializable.isArray()) {
while (serializable.isArray()) {
serializable = (Class<? extends Serializable>) serializable.getComponentType();
rank++;
}
}
JType resolvedType = typeOracle.getType(serializable.getCanonicalName());
while (rank > 0) {
resolvedType = typeOracle.getArrayType(resolvedType);
rank--;
}
typesSentToBrowserBuilder.addRootType(logger, resolvedType);
}
OutputStream pathInfo = context.tryCreateResource(logger, typeName + ".rpc.log");
PrintWriter writer = new PrintWriter(new OutputStreamWriter(pathInfo));
writer.write("====================================\n");
writer.write("Types potentially sent from browser:\n");
writer.write("====================================\n\n");
writer.flush();
typesSentToBrowserBuilder.setLogOutputWriter(writer);
SerializableTypeOracle typesSentFromBrowser = typesSentFromBrowserBuilder.build(logger);
writer.write("===================================\n");
writer.write("Types potentially sent from server:\n");
writer.write("===================================\n\n");
writer.flush();
typesSentFromBrowserBuilder.setLogOutputWriter(writer);
SerializableTypeOracle typesSentToBrowser = typesSentToBrowserBuilder.build(logger);
writer.close();
if (pathInfo != null) {
context.commitResource(logger, pathInfo).setPrivate(true);
}
// Create the serializer
TypeSerializerCreator tsc = new TypeSerializerCreator(logger, typesSentFromBrowser, typesSentToBrowser, context, "comet." + typeName.replace('.', '_') + "Serializer");
String realize = tsc.realize(logger);
// Create the CometSerializer impl
ClassSourceFileComposerFactory composerFactory = new ClassSourceFileComposerFactory(packageName, className);
composerFactory.addImport(Serializer.class.getName());
composerFactory.addImport(SerialMode.class.getName());
composerFactory.setSuperclass(typeName);
// TODO is the SERIALIZER required for DE RPC?
SourceWriter sourceWriter = composerFactory.createSourceWriter(context, printWriter);
sourceWriter.print("private Serializer SERIALIZER = new " + realize + "();");
sourceWriter.print("protected Serializer getSerializer() {return SERIALIZER;}");
sourceWriter.print("public SerialMode getMode() {return SerialMode." + annotation.mode().name() + ";}");
sourceWriter.commit(logger);
if (annotation.mode() == SerialMode.DE_RPC) {
RpcDataArtifact data = new RpcDataArtifact(type.getQualifiedSourceName());
for (JType t : typesSentToBrowser.getSerializableTypes()) {
if (!(t instanceof JClassType)) {
continue;
}
JField[] serializableFields = SerializationUtils.getSerializableFields(context.getTypeOracle(), (JClassType) t);
List<String> names = Lists.create();
for (int i = 0, j = serializableFields.length; i < j; i++) {
names = Lists.add(names, serializableFields[i].getName());
}
data.setFields(TypeOracleMediator.computeBinaryClassName(t), names);
}
context.commitArtifact(logger, data);
}
}
catch (NotFoundException e) {
logger.log(TreeLogger.ERROR, "", e);
throw new UnableToCompleteException();
}
}
return packageName + '.' + className;
}
| public String generate(TreeLogger logger, GeneratorContext context, String typeName) throws UnableToCompleteException {
TypeOracle typeOracle = context.getTypeOracle();
// Create the CometSerializer impl
String packageName = "comet";
String className = typeName.replace('.', '_') + "Impl";
PrintWriter printWriter = context.tryCreate(logger, packageName, className);
if (printWriter != null) {
try {
JClassType type = typeOracle.getType(typeName);
SerialTypes annotation = type.getAnnotation(SerialTypes.class);
if (annotation == null) {
logger.log(TreeLogger.ERROR, "No SerialTypes annotation on CometSerializer type: " + typeName);
throw new UnableToCompleteException();
}
SerializableTypeOracleBuilder typesSentToBrowserBuilder = new SerializableTypeOracleBuilder(logger, context.getPropertyOracle(), typeOracle);
SerializableTypeOracleBuilder typesSentFromBrowserBuilder = new SerializableTypeOracleBuilder(logger, context.getPropertyOracle(), typeOracle);
for (Class<? extends Serializable> serializable : annotation.value()) {
int rank = 0;
if (serializable.isArray()) {
while (serializable.isArray()) {
serializable = (Class<? extends Serializable>) serializable.getComponentType();
rank++;
}
}
JType resolvedType = typeOracle.getType(serializable.getCanonicalName());
while (rank > 0) {
resolvedType = typeOracle.getArrayType(resolvedType);
rank--;
}
typesSentToBrowserBuilder.addRootType(logger, resolvedType);
}
OutputStream pathInfo = context.tryCreateResource(logger, typeName + ".rpc.log");
PrintWriter writer = new PrintWriter(new OutputStreamWriter(pathInfo));
writer.write("====================================\n");
writer.write("Types potentially sent from browser:\n");
writer.write("====================================\n\n");
writer.flush();
typesSentToBrowserBuilder.setLogOutputWriter(writer);
SerializableTypeOracle typesSentFromBrowser = typesSentFromBrowserBuilder.build(logger);
writer.write("===================================\n");
writer.write("Types potentially sent from server:\n");
writer.write("===================================\n\n");
writer.flush();
typesSentFromBrowserBuilder.setLogOutputWriter(writer);
SerializableTypeOracle typesSentToBrowser = typesSentToBrowserBuilder.build(logger);
writer.close();
if (pathInfo != null) {
context.commitResource(logger, pathInfo).setPrivate(true);
}
// Create the serializer
String modifiedTypeName = typeName.replace('.', '_') + "Serializer";
TypeSerializerCreator tsc = new TypeSerializerCreator(logger, typesSentFromBrowser, typesSentToBrowser, context, "comet." + modifiedTypeName, modifiedTypeName);
String realize = tsc.realize(logger);
// Create the CometSerializer impl
ClassSourceFileComposerFactory composerFactory = new ClassSourceFileComposerFactory(packageName, className);
composerFactory.addImport(Serializer.class.getName());
composerFactory.addImport(SerialMode.class.getName());
composerFactory.setSuperclass(typeName);
// TODO is the SERIALIZER required for DE RPC?
SourceWriter sourceWriter = composerFactory.createSourceWriter(context, printWriter);
sourceWriter.print("private Serializer SERIALIZER = new " + realize + "();");
sourceWriter.print("protected Serializer getSerializer() {return SERIALIZER;}");
sourceWriter.print("public SerialMode getMode() {return SerialMode." + annotation.mode().name() + ";}");
sourceWriter.commit(logger);
if (annotation.mode() == SerialMode.DE_RPC) {
RpcDataArtifact data = new RpcDataArtifact(type.getQualifiedSourceName());
for (JType t : typesSentToBrowser.getSerializableTypes()) {
if (!(t instanceof JClassType)) {
continue;
}
JField[] serializableFields = SerializationUtils.getSerializableFields(context.getTypeOracle(), (JClassType) t);
List<String> names = Lists.create();
for (int i = 0, j = serializableFields.length; i < j; i++) {
names = Lists.add(names, serializableFields[i].getName());
}
data.setFields(TypeOracleMediator.computeBinaryClassName(t), names);
}
context.commitArtifact(logger, data);
}
}
catch (NotFoundException e) {
logger.log(TreeLogger.ERROR, "", e);
throw new UnableToCompleteException();
}
}
return packageName + '.' + className;
}
|
diff --git a/src/test/java/com/educo/tests/TestCases/SyllabusPageTests.java b/src/test/java/com/educo/tests/TestCases/SyllabusPageTests.java
index 4e2c830..149f99e 100644
--- a/src/test/java/com/educo/tests/TestCases/SyllabusPageTests.java
+++ b/src/test/java/com/educo/tests/TestCases/SyllabusPageTests.java
@@ -1,92 +1,92 @@
package com.educo.tests.TestCases;
import com.educo.tests.Helpers.Staticprovider;
import com.educo.tests.PageOBjects.InsHomePage.InsHomePageObjects;
import com.educo.tests.PageOBjects.LoginPage.UsaLoginPageObjects;
import com.educo.tests.PageOBjects.Tools.SyllabusPageObjects;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.openqa.selenium.support.PageFactory;
import org.testng.annotations.*;
import java.net.MalformedURLException;
/**
* Created with IntelliJ IDEA.
* User: admin
* Date: 8/9/13
* Time: 12:25 PM
* To change this template use File | Settings | File Templates.
*/
public class SyllabusPageTests {
public WebDriver driver;
@Parameters({"browser"})
@BeforeClass
public void propsetup(@Optional("Chrome") String browser) {
com.educo.tests.Common.Properties.Properties.setProperties();
}
@BeforeTest
public void b4test() {
System.out.println("@BeforeTest");
}
@Parameters({"browser"})
@BeforeMethod
- public void setup(@Optional("firefox") String browser) throws MalformedURLException, InterruptedException {
+ public void setup(@Optional("chrome") String browser) throws MalformedURLException, InterruptedException {
com.educo.tests.Common.Properties.Properties.setProperties();
DesiredCapabilities capability = null;
if (browser.equalsIgnoreCase("chrome")) {
System.out.println("chrome");
System.setProperty("webdriver.chrome.driver", "C://ChromeDriver//chromedriver.exe");
capability = DesiredCapabilities.chrome();
capability.setBrowserName("chrome");
capability.setPlatform(org.openqa.selenium.Platform.ANY);
//driver = new RemoteWebDriver(capability);
driver = new ChromeDriver();
}
if (browser.equalsIgnoreCase("Firefox")) {
System.out.println("Firefox");
capability = DesiredCapabilities.firefox();
capability.setBrowserName("firefox");
capability.setPlatform(org.openqa.selenium.Platform.WINDOWS);
driver = new FirefoxDriver();
System.out.println(driver);
}
System.setProperty("webdriver.chrome.driver", "C://ChromeDriver//chromedriver.exe");
// driver = new RemoteWebDriver(new URL("http://localhost:4444/wd/hub"), capability);
}
//test
@AfterTest
public void afterclass() {
driver.quit();
}
@Test(dataProviderClass = Staticprovider.class,dataProvider = "UsaLogin")
public void Syllabustest(String EmailInsUsa,String Password,String Profname) throws Exception {
InsHomePageObjects insHomePageObjects = PageFactory.initElements(driver, InsHomePageObjects.class);
UsaLoginPageObjects LoginPagePageobj= PageFactory.initElements(driver, UsaLoginPageObjects.class);
SyllabusPageObjects syllabusPageObjects=PageFactory.initElements(driver,SyllabusPageObjects.class);
LoginPagePageobj.openUsaPage();
LoginPagePageobj.login(EmailInsUsa, Password);
insHomePageObjects.SelectSection();
syllabusPageObjects.GoToSyllabusPage();
syllabusPageObjects.AddSyllabus();
syllabusPageObjects.AddResponseSheet();
syllabusPageObjects.addQuestion();
}
}
| true | true | public void setup(@Optional("firefox") String browser) throws MalformedURLException, InterruptedException {
com.educo.tests.Common.Properties.Properties.setProperties();
DesiredCapabilities capability = null;
if (browser.equalsIgnoreCase("chrome")) {
System.out.println("chrome");
System.setProperty("webdriver.chrome.driver", "C://ChromeDriver//chromedriver.exe");
capability = DesiredCapabilities.chrome();
capability.setBrowserName("chrome");
capability.setPlatform(org.openqa.selenium.Platform.ANY);
//driver = new RemoteWebDriver(capability);
driver = new ChromeDriver();
}
if (browser.equalsIgnoreCase("Firefox")) {
System.out.println("Firefox");
capability = DesiredCapabilities.firefox();
capability.setBrowserName("firefox");
capability.setPlatform(org.openqa.selenium.Platform.WINDOWS);
driver = new FirefoxDriver();
System.out.println(driver);
}
System.setProperty("webdriver.chrome.driver", "C://ChromeDriver//chromedriver.exe");
// driver = new RemoteWebDriver(new URL("http://localhost:4444/wd/hub"), capability);
}
| public void setup(@Optional("chrome") String browser) throws MalformedURLException, InterruptedException {
com.educo.tests.Common.Properties.Properties.setProperties();
DesiredCapabilities capability = null;
if (browser.equalsIgnoreCase("chrome")) {
System.out.println("chrome");
System.setProperty("webdriver.chrome.driver", "C://ChromeDriver//chromedriver.exe");
capability = DesiredCapabilities.chrome();
capability.setBrowserName("chrome");
capability.setPlatform(org.openqa.selenium.Platform.ANY);
//driver = new RemoteWebDriver(capability);
driver = new ChromeDriver();
}
if (browser.equalsIgnoreCase("Firefox")) {
System.out.println("Firefox");
capability = DesiredCapabilities.firefox();
capability.setBrowserName("firefox");
capability.setPlatform(org.openqa.selenium.Platform.WINDOWS);
driver = new FirefoxDriver();
System.out.println(driver);
}
System.setProperty("webdriver.chrome.driver", "C://ChromeDriver//chromedriver.exe");
// driver = new RemoteWebDriver(new URL("http://localhost:4444/wd/hub"), capability);
}
|
diff --git a/core/src/visad/bom/ShadowImageByRefFunctionTypeJ3D.java b/core/src/visad/bom/ShadowImageByRefFunctionTypeJ3D.java
index f9e64786c..2899375be 100644
--- a/core/src/visad/bom/ShadowImageByRefFunctionTypeJ3D.java
+++ b/core/src/visad/bom/ShadowImageByRefFunctionTypeJ3D.java
@@ -1,2137 +1,2137 @@
//
// ShadowImageByRefFunctionTypeJ3D.java
//
/*
VisAD system for interactive analysis and visualization of numerical
data. Copyright (C) 1996 - 2009 Bill Hibbard, Curtis Rueden, Tom
Rink, Dave Glowacki, Steve Emmerson, Tom Whittaker, Don Murray, and
Tommy Jasmin.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the Free
Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
MA 02111-1307, USA
*/
package visad.bom;
import visad.*;
import visad.data.CachedBufferedByteImage;
import visad.java3d.*;
import visad.data.mcidas.BaseMapAdapter;
import visad.data.mcidas.AreaAdapter;
import visad.data.gif.GIFForm;
import visad.util.Util;
import javax.media.j3d.*;
import java.io.*;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.Vector;
import java.util.Iterator;
import java.util.ArrayList;
import java.rmi.*;
import java.net.URL;
import java.awt.event.*;
import javax.swing.*;
import java.awt.color.*;
import java.awt.image.*;
/**
The ShadowImageFunctionTypeJ3D class shadows the FunctionType class for
ImageRendererJ3D, within a DataDisplayLink, under Java3D.<P>
*/
public class ShadowImageByRefFunctionTypeJ3D extends ShadowFunctionTypeJ3D {
private static final int MISSING1 = Byte.MIN_VALUE; // least byte
private VisADImageNode imgNode = null;
private VisADImageNode prevImgNode = null;
private int prevDataWidth = -1;
private int prevDataHeight = -1;
private int prevNumImages = -1;
//- Ghansham (New variables introduced to preserve scaled values and colorTables)
private byte scaled_Bytes[][]; //scaled byte values
private float scaled_Floats[][]; //scaled Float Values
private float rset_scalarmap_lookup[][]; //GHANSHAM:30AUG2011 create a lookup for rset FlatField range values
private byte[][] itable; //For single band
private byte[][] fast_table; //For fast_lookup
private byte[][][] threeD_itable; //for multiband
private float[][] color_values; //special case
private boolean first_time; //This variable indicates the first tile of the image.
//------------------------------------------------------------------------------
AnimationControlJ3D animControl = null;
private boolean reuse = false;
private boolean reuseImages = false;
int[] inherited_values = null;
ShadowFunctionOrSetType adaptedShadowType = null;
int levelOfDifficulty = -1;
//REUSE GEOMETRY/COLORBYTE VARIABLES (STARTS HERE)
boolean regen_colbytes = false;
boolean regen_geom = false;
boolean apply_alpha = false;
//REUSE GEOMETRY/COLORBYTE VARIABLES (ENDS HERE)
public ShadowImageByRefFunctionTypeJ3D(MathType t, DataDisplayLink link, ShadowType parent)
throws VisADException, RemoteException {
super(t, link, parent);
}
public ShadowImageByRefFunctionTypeJ3D(MathType t, DataDisplayLink link, ShadowType parent,
int[] inherited_values, ShadowFunctionOrSetType adaptedShadowType, int levelOfDifficulty)
throws VisADException, RemoteException {
super(t, link, parent);
this.inherited_values = inherited_values;
this.adaptedShadowType = adaptedShadowType;
this.levelOfDifficulty = levelOfDifficulty;
}
//REUSE GEOMETRY/COLORBYTE UTILITY METHODS (STARTS HERE)
/*This method returns two things:
1. whether any spatial maps has return true in checkTicks() function
2. Current ZAxis value
*/
private Object[] findSpatialMapTicksAndCurrZValue(ShadowFunctionOrSetType MyAdaptedShadowType, DisplayImpl display,
float default_values[], float value_array[], int valueToScalar[], DataRenderer renderer,
DataDisplayLink link, int valueArrayLength) throws VisADException, DisplayException {
ShadowRealTupleType Domain = MyAdaptedShadowType.getDomain();
ShadowRealType[] DomainComponents = MyAdaptedShadowType.getDomainComponents();
ShadowRealTupleType domain_reference = Domain.getReference();
ShadowRealType[] DC = DomainComponents;
if (domain_reference != null && domain_reference.getMappedDisplayScalar()) {
DC = MyAdaptedShadowType.getDomainReferenceComponents();
}
int[] tuple_index = new int[3];
DisplayTupleType spatial_tuple = null;
boolean spatial_maps_check_ticks = false;
for (int i=0; i<DC.length; i++) {
Enumeration maps = DC[i].getSelectedMapVector().elements();
ScalarMap map = (ScalarMap) maps.nextElement();
if (map.checkTicks(renderer, link)) {
spatial_maps_check_ticks = true;
}
DisplayRealType real = map.getDisplayScalar();
spatial_tuple = real.getTuple();
if (spatial_tuple == null) {
/*throw new DisplayException("texture with bad tuple: " +
"ShadowImageFunctionTypeJ3D.doTransform");*/
return null;
}
tuple_index[i] = real.getTupleIndex();
if (maps.hasMoreElements()) {
/*throw new DisplayException("texture with multiple spatial: " +
"ShadowImageFunctionTypeJ3D.doTransform");*/
return null;
}
}
// get spatial index not mapped from domain_set
tuple_index[2] = 3 - (tuple_index[0] + tuple_index[1]);
DisplayRealType real = (DisplayRealType) spatial_tuple.getComponent(tuple_index[2]);
int value2_index = display.getDisplayScalarIndex(real);
float value2 = default_values[value2_index];
for (int i=0; i<valueArrayLength; i++) {
if (inherited_values[i] > 0 && real.equals(display.getDisplayScalar(valueToScalar[i])) ) {
value2 = value_array[i];
break;
}
}
tuple_index = null;
Object ret_values[] = new Object[2];
ret_values[0] = spatial_maps_check_ticks;
ret_values[1] = value2;
return ret_values;
}
/*This method retuns whether any of the rangemap has return true in checkTicks()*/
private boolean findRadianceMapColorControlCheckTicks(ScalarMap cmap, ScalarMap cmaps[], DataRenderer renderer, DataDisplayLink link) {
BaseColorControl cc;
boolean color_map_changed = false;
if (cmap!= null) {
cc = (BaseColorControl) cmap.getControl();
color_map_changed = (cmap.checkTicks(renderer, link) || cc.checkTicks(renderer,link));
} else if (cmaps !=null) {
for (int i = 0; i < cmaps.length; i++) {
cc = (BaseColorControl) cmaps[i].getControl();
if (null != cc) {
if (cc.checkTicks(renderer,link) || cmaps[i].checkTicks(renderer, link)) {
color_map_changed = true;
break;
}
} else {
if (cmaps[i].checkTicks(renderer, link)) {
color_map_changed = true;
break;
}
}
}
}
return color_map_changed;
}
/*This method just applies the texture on the already generated geometry.
This is used when only colorbytes are generated and geometry is reused.
This does away with buildTexture(Linear/Curve) when geometry is reused */
private void applyTexture(Shape3D shape, VisADImageTile tile, boolean apply_alpha, float constant_alpha) {
Appearance app = shape.getAppearance();
if (regen_colbytes) {
if (animControl == null) {
imgNode.setCurrent(0);
}
}
if (apply_alpha) {
TransparencyAttributes transp_attribs = app.getTransparencyAttributes();
if (null == transp_attribs) {
transp_attribs = new TransparencyAttributes();
transp_attribs.setTransparencyMode(TransparencyAttributes.BLENDED);
transp_attribs.setTransparency(constant_alpha);
transp_attribs.setCapability(TransparencyAttributes.ALLOW_VALUE_WRITE);
app.setTransparencyAttributes(transp_attribs);
} else {
transp_attribs.setTransparency(constant_alpha);
}
}
}
/* This is the real nasty logic that decides following things:
1. Regenerate gometry
2. Regenerate ColorBytes
3. Change in alpha
Before doing this it inializes range ScalarMaps, constant_alpha value.
It also takes out the terminal ShadowType required in case of animations
*/
//GHANSHAM:30AUG2011 Changed the signaure of initRegenFlags.. passing the ShadowFunctionOrSetType, constant_lapha, cmap and cmaps
private void initRegenFlags(ImageRendererJ3D imgRenderer, ShadowFunctionOrSetType MyAdaptedShadowType,
float constant_alpha, ScalarMap cmap, ScalarMap cmaps[], Data data, DisplayImpl display,
float default_values[], float[] value_array, int []valueToScalar, int valueArrayLength,
DataDisplayLink link, int curved_size) throws BadMappingException, VisADException {
/*The nasty logic starts from here
Retrieves the curve size, zaxis value, alpha, ff hashcode value from Renderer class.
Compares them with current values and does other checks.
Finally store the current values for above variables in the renderer class.*/
int last_curve_size = imgRenderer.getLastCurveSize();
float last_zaxis_value = imgRenderer.getLastZAxisValue();
float last_alpha_value = imgRenderer.getLastAlphaValue();
long last_data_hash_code = imgRenderer.getLastDataHashCode();
long current_data_hash_code = data.hashCode();
boolean last_adjust_projection_seam = imgRenderer.getLastAdjustProjectionSeam(); //27FEB2012: Projection Seam Change Bug Fix
boolean current_adjust_projection_seam = adaptedShadowType.getAdjustProjectionSeam(); //27FEB2012: Projection Seam Change Bug Fix
Object map_ticks_z_value[] = findSpatialMapTicksAndCurrZValue(MyAdaptedShadowType, display, default_values, value_array, valueToScalar, imgRenderer, link, valueArrayLength);
if (null == map_ticks_z_value) {
return;
}
float current_zaxis_value = Float.parseFloat(map_ticks_z_value[1].toString());
if ((-1 != last_curve_size) && Float.isNaN(last_zaxis_value) && (-1 == last_data_hash_code)) { //First Time
regen_colbytes = true;
regen_geom = true;
apply_alpha = true;
} else {
boolean data_hash_code_changed = (current_data_hash_code != last_data_hash_code);
if (data_hash_code_changed) { //dataref.setData()
regen_colbytes = true;
regen_geom = true;
apply_alpha =true;
} else {
boolean spatial_maps_check_ticks = Boolean.parseBoolean(map_ticks_z_value[0].toString());
boolean zaxis_value_changed = (Float.compare(last_zaxis_value, current_zaxis_value) != 0);
boolean curve_texture_value_change = (last_curve_size != curved_size);
boolean alpha_changed = (Float.compare(constant_alpha, last_alpha_value) != 0);
boolean radiancemap_colcontrol_check_ticks = findRadianceMapColorControlCheckTicks(cmap, cmaps, imgRenderer, link);
boolean projection_seam_changed = (current_adjust_projection_seam != last_adjust_projection_seam); //27FEB2012: Projection Seam Change Bug Fix
if (spatial_maps_check_ticks || zaxis_value_changed || curve_texture_value_change || projection_seam_changed) { //change in geometry 27FEB2012: Projection Seam Change Bug Fix
regen_geom = true;
} else if (alpha_changed) { //change in alpha value
apply_alpha = true;
} else if (radiancemap_colcontrol_check_ticks) { //change in Radiance ScalarMaps or ColorTable
regen_colbytes = true;
} else { //Assuming that ff.setSamples() has been called.
regen_colbytes = true;
}
}
}
imgRenderer.setLastCurveSize(curved_size);
imgRenderer.setLastZAxisValue(current_zaxis_value);
imgRenderer.setLastAlphaValue(constant_alpha);
imgRenderer.setLastAdjustProjectionSeam(current_adjust_projection_seam); //27FEB2012: Projection Seam Change Bug Fix
imgRenderer.setLastDataHashCode(current_data_hash_code);
}
//REUSE GEOMETRY/COLORBYTE UTILITY METHODS (ENDS HERE)
// transform data into a depiction under group
public boolean doTransform(Object group, Data data, float[] value_array,
float[] default_values, DataRenderer renderer)
throws VisADException, RemoteException {
DataDisplayLink link = renderer.getLink();
// return if data is missing or no ScalarMaps
if (data.isMissing()) {
((ImageRendererJ3D) renderer).markMissingVisADBranch();
return false;
}
if (levelOfDifficulty == -1) {
levelOfDifficulty = getLevelOfDifficulty();
}
if (levelOfDifficulty == NOTHING_MAPPED) return false;
if (group instanceof BranchGroup && ((BranchGroup) group).numChildren() > 0) {
Node g = ((BranchGroup) group).getChild(0);
// WLH 06 Feb 06 - support switch in a branch group.
if (g instanceof BranchGroup && ((BranchGroup) g).numChildren() > 0) {
reuseImages = true;
}
}
DisplayImpl display = getDisplay();
int cMapCurveSize = (int) default_values[display.getDisplayScalarIndex(Display.CurvedSize)];
int curved_size = (cMapCurveSize > 0) ? cMapCurveSize : display.getGraphicsModeControl().getCurvedSize();
// length of ValueArray
int valueArrayLength = display.getValueArrayLength();
// mapping from ValueArray to DisplayScalar
int[] valueToScalar = display.getValueToScalar();
//GHANSHAM:30AUG2011 Restrutured the code to extract the constant_alpha, cmap, cmaps and ShadowFunctionType so that they can be passed to initRegenFlags method
if (adaptedShadowType == null) {
adaptedShadowType = (ShadowFunctionOrSetType) getAdaptedShadowType();
}
boolean anyContour = adaptedShadowType.getAnyContour();
boolean anyFlow = adaptedShadowType.getAnyFlow();
boolean anyShape = adaptedShadowType.getAnyShape();
boolean anyText = adaptedShadowType.getAnyText();
if (anyContour || anyFlow || anyShape || anyText) {
throw new BadMappingException("no contour, flow, shape or text allowed");
}
FlatField imgFlatField = null;
Set domain_set = ((Field) data).getDomainSet();
ShadowRealType[] DomainComponents = adaptedShadowType.getDomainComponents();
int numImages = 1;
if (!adaptedShadowType.getIsTerminal()) {
Vector domain_maps = DomainComponents[0].getSelectedMapVector();
ScalarMap amap = null;
if (domain_set.getDimension() == 1 && domain_maps.size() == 1) {
ScalarMap map = (ScalarMap) domain_maps.elementAt(0);
if (Display.Animation.equals(map.getDisplayScalar())) {
amap = map;
}
}
if (amap == null) {
throw new BadMappingException("time must be mapped to Animation");
}
animControl = (AnimationControlJ3D) amap.getControl();
numImages = domain_set.getLength();
adaptedShadowType = (ShadowFunctionOrSetType) adaptedShadowType.getRange();
DomainComponents = adaptedShadowType.getDomainComponents();
imgFlatField = (FlatField) ((FieldImpl)data).getSample(0);
} else {
imgFlatField = (FlatField)data;
}
// check that range is single RealType mapped to RGB only
ShadowRealType[] RangeComponents = adaptedShadowType.getRangeComponents();
int rangesize = RangeComponents.length;
if (rangesize != 1 && rangesize != 3) {
throw new BadMappingException("image values must single or triple");
}
ScalarMap cmap = null;
ScalarMap[] cmaps = null;
int[] permute = {-1, -1, -1};
boolean hasAlpha = false;
if (rangesize == 1) {
Vector mvector = RangeComponents[0].getSelectedMapVector();
if (mvector.size() != 1) {
throw new BadMappingException("image values must be mapped to RGB only");
}
cmap = (ScalarMap) mvector.elementAt(0);
if (Display.RGB.equals(cmap.getDisplayScalar())) {
} else if (Display.RGBA.equals(cmap.getDisplayScalar())) {
hasAlpha = true;
} else {
throw new BadMappingException("image values must be mapped to RGB or RGBA");
}
} else {
cmaps = new ScalarMap[3];
for (int i=0; i<3; i++) {
Vector mvector = RangeComponents[i].getSelectedMapVector();
if (mvector.size() != 1) {
throw new BadMappingException("image values must be mapped to color only");
}
cmaps[i] = (ScalarMap) mvector.elementAt(0);
if (Display.Red.equals(cmaps[i].getDisplayScalar())) {
permute[0] = i;
} else if (Display.Green.equals(cmaps[i].getDisplayScalar())) {
permute[1] = i;
} else if (Display.Blue.equals(cmaps[i].getDisplayScalar())) {
permute[2] = i;
} else if (Display.RGB.equals(cmaps[i].getDisplayScalar())) { //Inserted by Ghansham for Mapping all the three scalarMaps to Display.RGB (starts here)
permute[i] = i;
} else { ////Inserted by Ghansham for Mapping all the three scalarMaps to Display.RGB(ends here)
throw new BadMappingException("image values must be mapped to Red, Green or Blue only");
}
}
if (permute[0] < 0 || permute[1] < 0 || permute[2] < 0) {
throw new BadMappingException("image values must be mapped to Red, Green or Blue only");
}
//Inserted by Ghansham for Checking that all should be mapped to Display.RGB or not even a single one should be mapped to Display.RGB(starts here)
//This is to check if there is a single Display.RGB ScalarMap
int indx = -1;
for (int i = 0; i < 3; i++) {
if (cmaps[i].getDisplayScalar().equals(Display.RGB)) {
indx = i;
break;
}
}
if (indx != -1){ //if there is a even a single Display.RGB ScalarMap, others must also Display.RGB only
for (int i = 0; i < 3; i++) {
if (i !=indx && !(cmaps[i].getDisplayScalar().equals(Display.RGB))) {
throw new BadMappingException("image values must be mapped to (Red, Green, Blue) or (RGB,RGB,RGB) only");
}
}
}
//Inserted by Ghansham for Checking that all should be mapped to Display.RGB or not even a single one should be mapped to Display.RGB(Ends here)
}
float constant_alpha = default_values[display.getDisplayScalarIndex(Display.Alpha)];
int color_length;
ImageRendererJ3D imgRenderer = (ImageRendererJ3D) renderer;
int imageType = imgRenderer.getSuggestedBufImageType();
if (imageType == BufferedImage.TYPE_4BYTE_ABGR) {
color_length = 4;
if (!hasAlpha) {
color_length = 3;
imageType = BufferedImage.TYPE_3BYTE_BGR;
}
} else if (imageType == BufferedImage.TYPE_3BYTE_BGR) {
color_length = 3;
} else if (imageType == BufferedImage.TYPE_USHORT_GRAY) {
color_length = 2;
} else if (imageType == BufferedImage.TYPE_BYTE_GRAY) {
color_length = 1;
} else {
// we shouldn't ever get here because the renderer validates the
// imageType before we get it, but just in case...
throw new VisADException("renderer returned unsupported image type");
}
if (color_length == 4) constant_alpha = Float.NaN; // WLH 6 May 2003
//REUSE GEOMETRY/COLORBYTE LOGIC (STARTS HERE)
regen_colbytes = false;
regen_geom = false;
apply_alpha = false;
initRegenFlags((ImageRendererJ3D)renderer, adaptedShadowType, constant_alpha, cmap, cmaps, data, display, default_values, value_array, valueToScalar, valueArrayLength, link, curved_size);
if(!reuseImages) {
regen_geom = true;
regen_colbytes = true;
apply_alpha = true;
}
/**
System.err.println("Regenerate Color Bytes:" + regen_colbytes);
System.err.println("Regenerate Geometry:" + regen_geom);
System.err.println("Apply Alpha:" + apply_alpha);
System.err.println("ReuseImages:" + reuseImages);
*/
//REUSE GEOMETRY/COLORBYTE LOGIC (ENDS HERE)
prevImgNode = ((ImageRendererJ3D)renderer).getImageNode();
BranchGroup bgImages = null;
/*REUSE GEOM/COLBYTE: Replaced reuse with reuseImages. Earlier else part of this decision was never being used.
The reason was reuse was always set to false. Compare with your version.
Added one extra line in the else part where I extract the bgImages from the switch.
Now else part occurs when either reuse_colbytes or regen_geom is true.
But when regen_colbytes and regen_geom both are true, then I assume that a new flatfield is set so
go with the if part.
*/
if (!reuseImages || (regen_colbytes && regen_geom)) { //REUSE GEOM/COLBYTE:Earlier reuse variable was used. Replaced it with reuseImages.
//Added regen_colbytes and regen_geom.
//This is used when either its first time or full new data has been with different dims.
BranchGroup branch = new BranchGroup();
branch.setCapability(BranchGroup.ALLOW_DETACH);
branch.setCapability(BranchGroup.ALLOW_CHILDREN_EXTEND);
branch.setCapability(BranchGroup.ALLOW_CHILDREN_READ);
branch.setCapability(BranchGroup.ALLOW_CHILDREN_WRITE);
Switch swit = (Switch) makeSwitch();
imgNode = new VisADImageNode();
bgImages = new BranchGroup();
bgImages.setCapability(BranchGroup.ALLOW_DETACH);
bgImages.setCapability(BranchGroup.ALLOW_CHILDREN_EXTEND);
bgImages.setCapability(BranchGroup.ALLOW_CHILDREN_READ);
bgImages.setCapability(BranchGroup.ALLOW_CHILDREN_WRITE);
swit.addChild(bgImages);
swit.setWhichChild(0);
branch.addChild(swit);
imgNode.setBranch(branch);
imgNode.setSwitch(swit);
((ImageRendererJ3D)renderer).setImageNode(imgNode);
if ( ((BranchGroup) group).numChildren() > 0 ) {
((BranchGroup)group).setChild(branch, 0);
} else {
((BranchGroup)group).addChild(branch);
/*
// make sure group is live. group not empty (above addChild)
if (group instanceof BranchGroup) {
((ImageRendererJ3D) renderer).setBranchEarly((BranchGroup) group);
}
*/
}
} else { //REUSE GEOM/COLBYTE: If its not the first time. And the dims have not changed but either color bytes or geometry has changed.
imgNode = ((ImageRendererJ3D)renderer).getImageNode();
bgImages = (BranchGroup) imgNode.getSwitch().getChild(0); //REUSE GEOM/COLBYTE:Extract the bgImages from the avaialable switch
}
GraphicsModeControl mode = (GraphicsModeControl)
display.getGraphicsModeControl().clone();
// get some precomputed values useful for transform
// mapping from ValueArray to MapVector
int[] valueToMap = display.getValueToMap();
Vector MapVector = display.getMapVector();
Unit[] dataUnits = null;
CoordinateSystem dataCoordinateSystem = null;
- if (numImages > 1) {
+ if (animControl != null) {
Switch swit = new SwitchNotify(imgNode, numImages);
((AVControlJ3D) animControl).addPair((Switch) swit, domain_set, renderer);
((AVControlJ3D) animControl).init();
}
domain_set = imgFlatField.getDomainSet();
dataUnits = ((Function) imgFlatField).getDomainUnits();
dataCoordinateSystem =
((Function) imgFlatField).getDomainCoordinateSystem();
int domain_length = domain_set.getLength();
int[] lengths = ((GriddedSet) domain_set).getLengths();
int data_width = lengths[0];
int data_height = lengths[1];
imgNode.numImages = numImages;
imgNode.data_width = data_width;
imgNode.data_height = data_height;
int texture_width_max = link.getDisplay().getDisplayRenderer().getTextureWidthMax();
int texture_height_max = link.getDisplay().getDisplayRenderer().getTextureWidthMax();
int texture_width = textureWidth(data_width);
int texture_height = textureHeight(data_height);
if (reuseImages) {
if (prevImgNode.numImages != numImages ||
prevImgNode.data_width != data_width || prevImgNode.data_height != data_height) {
reuseImages = false;
}
}
if (reuseImages) {
imgNode.numChildren = prevImgNode.numChildren;
imgNode.imageTiles = prevImgNode.imageTiles;
}
else {
Mosaic mosaic = new Mosaic(data_height, texture_height_max, data_width, texture_width_max);
for (Iterator iter = mosaic.iterator(); iter.hasNext();) {
Tile tile = (Tile) iter.next();
imgNode.addTile(new VisADImageTile(numImages, tile.height, tile.y_start, tile.width, tile.x_start));
}
}
prevImgNode = imgNode;
ShadowRealTupleType Domain = adaptedShadowType.getDomain();
Unit[] domain_units = ((RealTupleType) Domain.getType()).getDefaultUnits();
float[] constant_color = null;
// check that domain is only spatial
if (!Domain.getAllSpatial() || Domain.getMultipleDisplayScalar()) {
throw new BadMappingException("domain must be only spatial");
}
// check domain and determine whether it is square or curved texture
boolean isTextureMap = adaptedShadowType.getIsTextureMap() &&
(domain_set instanceof Linear2DSet ||
(domain_set instanceof LinearNDSet &&
domain_set.getDimension() == 2)) &&
(domain_set.getManifoldDimension() == 2);
boolean curvedTexture = adaptedShadowType.getCurvedTexture() &&
!isTextureMap &&
curved_size > 0 &&
(domain_set instanceof Gridded2DSet ||
(domain_set instanceof GriddedSet &&
domain_set.getDimension() == 2)) &&
(domain_set.getManifoldDimension() == 2);
if (group instanceof BranchGroup) {
((ImageRendererJ3D) renderer).setBranchEarly((BranchGroup) group);
}
first_time =true; //Ghansham: this variable just indicates to makeColorBytes whether it's the first tile of the image
boolean branch_added = false;
if (isTextureMap) { // linear texture
if (imgNode.getNumTiles() == 1) {
VisADImageTile tile = imgNode.getTile(0);
if (regen_colbytes) { //REUSE COLBYTES: regenerate only if required
makeColorBytesDriver(imgFlatField, cmap, cmaps, constant_alpha, RangeComponents, color_length, domain_length, permute,
data_width, data_height, imageType, tile, 0);
}
if (regen_geom) { //REUSE : REGEN GEOM regenerate the geometry
buildLinearTexture(bgImages, domain_set, dataUnits, domain_units, default_values, DomainComponents,
valueArrayLength, inherited_values, valueToScalar, mode, constant_alpha,
value_array, constant_color, display, tile);
} else { //REUSE Reuse the branch fully along with geometry. Just apply the colorbytes(Buffered Image)
BranchGroup Branch_L1 = (BranchGroup) bgImages.getChild(0);
Shape3D shape = (Shape3D) Branch_L1.getChild(0);
applyTexture(shape, tile, apply_alpha, constant_alpha);
}
}
else {
BranchGroup branch = null;
//if (!reuseImages || (regen_colbytes && regen_geom)) { //REUSE: Make a fresh branch
if (!reuseImages) {
branch = new BranchGroup();
branch.setCapability(BranchGroup.ALLOW_DETACH);
branch.setCapability(BranchGroup.ALLOW_CHILDREN_EXTEND);
branch.setCapability(BranchGroup.ALLOW_CHILDREN_READ);
branch.setCapability(BranchGroup.ALLOW_CHILDREN_WRITE);
} else { //REUSE the branch
branch = (BranchGroup) bgImages.getChild(0);
}
int branch_tile_indx = 0; //REUSE: to get the branch for a tile in case of multi-tile rendering
for (Iterator iter = imgNode.getTileIterator(); iter.hasNext();) {
VisADImageTile tile = (VisADImageTile) iter.next();
if (regen_colbytes) { //REUSE COLBYTES: regenerate only if required
makeColorBytesDriver(imgFlatField, cmap, cmaps, constant_alpha, RangeComponents, color_length, domain_length, permute,
data_width, data_height, imageType, tile, 0);
first_time = false; //Ghansham: setting 'first_time' variable false after the first tile has been generated
}
if (regen_geom) { //REUSE: Regenerate the geometry
float[][] g00 = ((GriddedSet)domain_set).gridToValue(
new float[][] {{tile.xStart}, {tile.yStart}});
float[][] g11 = ((GriddedSet)domain_set).gridToValue(
new float[][] {{tile.xStart+tile.width-1}, {tile.yStart+tile.height-1}});
double x0 = g00[0][0];
double x1 = g11[0][0];
double y0 = g00[1][0];
double y1 = g11[1][0];
Set dset = new Linear2DSet(x0, x1, tile.width, y0, y1, tile.height);
BranchGroup branch1 = null;
if (!reuseImages || (regen_colbytes && regen_geom)) { //REUSE: Make a fresh branch for each tile
branch1 = new BranchGroup();
branch1.setCapability(BranchGroup.ALLOW_DETACH);
branch1.setCapability(BranchGroup.ALLOW_CHILDREN_EXTEND);
branch1.setCapability(BranchGroup.ALLOW_CHILDREN_READ);
branch1.setCapability(BranchGroup.ALLOW_CHILDREN_WRITE);
} else { //REUSE: Reuse the already built branch for each tile
branch1 = (BranchGroup) branch.getChild(branch_tile_indx);
}
buildLinearTexture(branch1, dset, dataUnits, domain_units, default_values, DomainComponents,
valueArrayLength, inherited_values, valueToScalar, mode, constant_alpha,
value_array, constant_color, display, tile);
if (!reuseImages|| (regen_colbytes && regen_geom)) {
branch.addChild(branch1);
}
g00 = null;
g11 = null;
dset = null;
} else { //REUSE Reuse the branch fully along with geometry. Just apply the colorbytes(Buffered Image)
BranchGroup branch1 = (BranchGroup) branch.getChild(branch_tile_indx);
BranchGroup branch2 = (BranchGroup) branch1.getChild(0); //Beause we create a branch in textureToGroup
Shape3D shape = (Shape3D) branch2.getChild(0);
applyTexture(shape, tile, apply_alpha, constant_alpha);
}
if (0 == branch_tile_indx) { //Add the branch to get rendered as early as possible
if (!reuseImages || (regen_colbytes && regen_geom)) { //REUSE : Add a new branch if created
if (((Group) bgImages).numChildren() > 0) {
((Group) bgImages).setChild(branch, 0);
} else {
((Group) bgImages).addChild(branch);
}
}
}
branch_tile_indx++;
}
}
} // end if (isTextureMap)
else if (curvedTexture) {
int[] lens = ((GriddedSet)domain_set).getLengths();
int[] domain_lens = lens;
if (imgNode.getNumTiles() == 1) {
VisADImageTile tile = imgNode.getTile(0);
if (regen_colbytes) { //REUSE COLBYTES: regenerate only if required
makeColorBytesDriver(imgFlatField, cmap, cmaps, constant_alpha, RangeComponents, color_length, domain_length, permute,
data_width, data_height, imageType, tile, 0);
}
if (regen_geom) { //REUSE: REGEN GEOM regenerate
buildCurvedTexture(bgImages, domain_set, dataUnits, domain_units, default_values, DomainComponents,
valueArrayLength, inherited_values, valueToScalar, mode, constant_alpha,
value_array, constant_color, display, curved_size, Domain,
dataCoordinateSystem, renderer, adaptedShadowType, new int[] {0,0},
domain_lens[0], domain_lens[1], null, domain_lens[0], domain_lens[1], tile);
} else { //REUSE Reuse the branch fully along with geometry. Just apply the colorbytes(Buffered Image)
BranchGroup Branch_L1 = (BranchGroup) bgImages.getChild(0);
Shape3D shape = (Shape3D) Branch_L1.getChild(0);
applyTexture(shape, tile, apply_alpha, constant_alpha);
}
}
else
{
float[][] samples = ((GriddedSet)domain_set).getSamples(false);
BranchGroup branch = null;
if (!reuseImages || (regen_colbytes && regen_geom)) { //REUSE: Make a fresh branch
branch = new BranchGroup();
branch.setCapability(BranchGroup.ALLOW_DETACH);
branch.setCapability(BranchGroup.ALLOW_CHILDREN_EXTEND);
branch.setCapability(BranchGroup.ALLOW_CHILDREN_READ);
branch.setCapability(BranchGroup.ALLOW_CHILDREN_WRITE);
} else { //REUSE: Reuse already built branch
branch = (BranchGroup) bgImages.getChild(0);
}
int branch_tile_indx = 0; //REUSE: to get the branch for a tile in case of multi-tile rendering
for (Iterator iter = imgNode.getTileIterator(); iter.hasNext();) {
VisADImageTile tile = (VisADImageTile) iter.next();
if (regen_colbytes) { //REUSE COLBYTES: regenerate only if required
makeColorBytesDriver(imgFlatField, cmap, cmaps, constant_alpha, RangeComponents, color_length, domain_length, permute,
data_width, data_height, imageType, tile, 0);
first_time = false; //Ghansham: setting 'first_time' variable false after the first tile has been generated
}
if (regen_geom) { //REUSE REGEN GEOM regenerate geometry
BranchGroup branch1 = null;
if (!reuseImages || (regen_colbytes && regen_geom)) { //REUSE: Make a fresh branch group for each tile
branch1 = new BranchGroup();
branch1.setCapability(BranchGroup.ALLOW_DETACH);
branch1.setCapability(BranchGroup.ALLOW_CHILDREN_EXTEND);
branch1.setCapability(BranchGroup.ALLOW_CHILDREN_READ);
branch1.setCapability(BranchGroup.ALLOW_CHILDREN_WRITE);
} else { //REUSE: Reuse the already existing branch for each tile
branch1 = (BranchGroup) branch.getChild(branch_tile_indx);
}
buildCurvedTexture(branch1, null, dataUnits, domain_units, default_values, DomainComponents,
valueArrayLength, inherited_values, valueToScalar, mode, constant_alpha,
value_array, constant_color, display, curved_size, Domain,
dataCoordinateSystem, renderer, adaptedShadowType,
new int[] {tile.xStart,tile.yStart}, tile.width, tile.height,
samples, domain_lens[0], domain_lens[1], tile);
if (!reuseImages || (regen_colbytes && regen_geom)) { //REUSE: Add newly created branch
branch.addChild(branch1);
}
} else { //REUSE Reuse the branch fully along with geometry. Just apply the colorbytes(Buffered Image)
BranchGroup branch1 = (BranchGroup) branch.getChild(branch_tile_indx);
BranchGroup branch2 = (BranchGroup) branch1.getChild(0);
Shape3D shape = (Shape3D) branch2.getChild(0);
applyTexture(shape, tile, apply_alpha, constant_alpha);
}
if (0 == branch_tile_indx) { //Add the branch to get rendered as early as possible
if (!reuseImages || (regen_colbytes && regen_geom)) { //REUSE : Add a new branch if created
if (((Group) bgImages).numChildren() > 0) {
((Group) bgImages).setChild(branch, 0);
} else {
((Group) bgImages).addChild(branch);
}
}
}
branch_tile_indx++;
}
}
} // end if (curvedTexture)
else { // !isTextureMap && !curvedTexture
throw new BadMappingException("must be texture map or curved texture map");
}
// make sure group is live. group not empty (above addChild)
/*if (group instanceof BranchGroup) {
((ImageRendererJ3D) renderer).setBranchEarly((BranchGroup) group);
}*/
for (int k=1; k<numImages; k++) {
FlatField ff = (FlatField) ((Field)data).getSample(k);
CoordinateSystem dcs = ff.getDomainCoordinateSystem();
GriddedSet domSet = (GriddedSet) ff.getDomainSet();
int[] lens = domSet.getLengths();
// if image dimensions, or dataCoordinateSystem not equal to first image, resample to first
if (regen_colbytes) { //REUSE COLBYTES: resample the flatfield only if colorbytes need to be regenerated
if ( (lens[0] != data_width || lens[1] != data_height) || !(dcs.equals(dataCoordinateSystem))) {
ff = (FlatField) ff.resample(imgFlatField.getDomainSet(), Data.NEAREST_NEIGHBOR, Data.NO_ERRORS);
}
}
first_time = true;
scaled_Bytes = null; //scaled byte values
scaled_Floats = null; //scaled Float Values
fast_table = null;
rset_scalarmap_lookup = null; //GHANSHAM:30AUG2011 create a lookup for rset FlatField range values
itable = null; //For single band
threeD_itable = null; //for multiband
color_values = null; //special case
for (Iterator iter = imgNode.getTileIterator(); iter.hasNext();) {
VisADImageTile tile = (VisADImageTile) iter.next();
if(regen_colbytes) { //REUSE COLBYTES: regenerate colobytes only if required
makeColorBytesDriver(ff, cmap, cmaps, constant_alpha, RangeComponents, color_length, domain_length, permute,
data_width, data_height, imageType, tile, k);
first_time = false;
}
//image.bytesChanged(byteData);
}
}
cmaps = null;
first_time = true;
scaled_Bytes = null; //scaled byte values
scaled_Floats = null; //scaled Float Values
fast_table = null;
rset_scalarmap_lookup = null; //GHANSHAM:30AUG2011 create a lookup for rset FlatField range values
itable = null; //For single band
threeD_itable = null; //for multiband
color_values = null; //special case
ensureNotEmpty(bgImages);
return false;
}
// This function calls makeColorBytes function (Ghansham)
public void makeColorBytesDriver(Data imgFlatField, ScalarMap cmap, ScalarMap[] cmaps, float constant_alpha,
ShadowRealType[] RangeComponents, int color_length, int domain_length, int[] permute,
int data_width, int data_height,
int imageType, VisADImageTile tile, int image_index) throws VisADException, RemoteException {
BufferedImage image = null;
byte byteData[] = null;
int tile_width = tile.width;
int tile_height = tile.height;
int xStart = tile.xStart;
int yStart = tile.yStart;
int texture_width = textureWidth(tile_width);
int texture_height = textureHeight(tile_height);
if (!reuseImages) {
image = createImageByRef(texture_width, texture_height, imageType);
tile.setImage(image_index, image);
} else {
//image = (CachedBufferedByteImage) tile.getImage(0);
image = (BufferedImage) tile.getImage(image_index);
}
java.awt.image.Raster raster = image.getRaster();
DataBuffer db = raster.getDataBuffer();
byteData = ((DataBufferByte)db).getData();
java.util.Arrays.fill(byteData, (byte)0);
makeColorBytes(imgFlatField, cmap, cmaps, constant_alpha, RangeComponents, color_length, domain_length, permute,
byteData,
data_width, data_height, tile_width, tile_height, xStart, yStart, texture_width, texture_height);
}
/* New version contributed by Ghansham (ISRO)
This function scales the flatfield values and the colortable for the first tile only using the first_time variable. Rest of the time it only
uses scaled values and color table to generate colorbytes for respective tile. Just see the first_time variable use. That is the only difference between
this function and earlier function makeColorBytes(). Some new class variables have been introduced to preserve scaled values and colortable.
They are made null after all the tiles for a single image has been generated. At the end of doTransform(), they are made null.
*/
public void makeColorBytes(Data data, ScalarMap cmap, ScalarMap[] cmaps, float constant_alpha,
ShadowRealType[] RangeComponents, int color_length, int domain_length, int[] permute,
byte[] byteData, int data_width, int data_height, int tile_width, int tile_height, int xStart, int yStart,
int texture_width, int texture_height)
throws VisADException, RemoteException {
if (cmap != null) {
BaseColorControl control = (BaseColorControl) cmap.getControl();
float[][] table = control.getTable();
Set rset = null;
boolean is_default_unit = false;
if (data instanceof FlatField) {
// for fast byte color lookup, need:
// 1. range data values are packed in bytes
//bytes = ((FlatField) data).grabBytes();
if (first_time) {
scaled_Bytes = ((FlatField) data).grabBytes();
}
// 2. range set is Linear1DSet
Set[] rsets = ((FlatField) data). getRangeSets();
if (rsets != null) rset = rsets[0];
// 3. data Unit equals default Unit
RealType rtype = (RealType) RangeComponents[0].getType();
Unit def_unit = rtype.getDefaultUnit();
if (def_unit == null) {
is_default_unit = true;
} else {
Unit[][] data_units = ((FlatField) data).getRangeUnits();
Unit data_unit = (data_units == null) ? null : data_units[0][0];
is_default_unit = def_unit.equals(data_unit);
}
}
if (table != null) {
// combine color table RGB components into ints
if (first_time) {
itable = new byte[table[0].length][4];
// int r, g, b, a = 255;
int r, g, b;
int c = (int) (255.0 * (1.0f - constant_alpha));
int a = (c < 0) ? 0 : ((c > 255) ? 255 : c);
for (int j=0; j<table[0].length; j++) {
c = (int) (255.0 * table[0][j]);
r = (c < 0) ? 0 : ((c > 255) ? 255 : c);
c = (int) (255.0 * table[1][j]);
g = (c < 0) ? 0 : ((c > 255) ? 255 : c);
c = (int) (255.0 * table[2][j]);
b = (c < 0) ? 0 : ((c > 255) ? 255 : c);
if (color_length == 4) {
c = (int) (255.0 * table[3][j]);
a = (c < 0) ? 0 : ((c > 255) ? 255 : c);
}
itable[j][0] = (byte) r;
itable[j][1] = (byte) g;
itable[j][2] = (byte) b;
itable[j][3] = (byte) a;
}
}
int tblEnd = table[0].length - 1;
// get scale for color table
int table_scale = table[0].length;
if (data instanceof ImageFlatField && scaled_Bytes != null && is_default_unit) {
if (ImageFlatField.DEBUG) {
System.err.println("ShadowImageFunctionTypeJ3D.doTransform: " + "cmap != null: looking up color values");
}
// avoid unpacking floats for ImageFlatFields
if (first_time) {
scaled_Bytes[0]= cmap.scaleValues(scaled_Bytes[0], table_scale);
}
// fast lookup from byte values to color bytes
byte[] bytes0 = scaled_Bytes[0];
int k =0;
int color_length_times_texture_width = texture_width*color_length;
for (int y=0; y<tile_height; y++) {
int image_col_factor = (y+yStart)*data_width + xStart;
k= y*color_length_times_texture_width;
for (int x=0; x<tile_width; x++) {
int i = x + image_col_factor;
int j = bytes0[i] & 0xff; // unsigned
// clip to table
int ndx = j < 0 ? 0 : (j > tblEnd ? tblEnd : j);
if (color_length == 4) {
byteData[k] = itable[ndx][3];
byteData[k+1] = itable[ndx][2];
byteData[k+2] = itable[ndx][1];
byteData[k+3] = itable[ndx][0];
}
if (color_length == 3) {
byteData[k] = itable[ndx][2];
byteData[k+1] = itable[ndx][1];
byteData[k+2] = itable[ndx][0];
}
if (color_length == 1) {
byteData[k] = itable[ndx][0];
}
k += color_length;
}
}
} else if (scaled_Bytes != null && scaled_Bytes[0] != null && is_default_unit && rset != null && rset instanceof Linear1DSet) {
// fast since FlatField with bytes, data Unit equals default
// Unit and range set is Linear1DSet
// get "scale and offset" for Linear1DSet
if (first_time) {
double first = ((Linear1DSet) rset).getFirst();
double step = ((Linear1DSet) rset).getStep();
// get scale and offset for ScalarMap
double[] so = new double[2];
double[] da = new double[2];
double[] di = new double[2];
cmap.getScale(so, da, di);
double scale = so[0];
double offset = so[1];
// combine scales and offsets for Set, ScalarMap and color table
float mult = (float) (table_scale * scale * step);
float add = (float) (table_scale * (offset + scale * first));
// build table for fast color lookup
fast_table = new byte[256][];
for (int j=0; j<256; j++) {
int index = j - 1;
if (index >= 0) { // not missing
int k = (int) (add + mult * index);
// clip to table
int ndx = k < 0 ? 0 : (k > tblEnd ? tblEnd : k);
fast_table[j] = itable[ndx];
}
}
}
// now do fast lookup from byte values to color bytes
byte[] bytes0 = scaled_Bytes[0];
int k = 0;
int color_length_times_texture_width = texture_width*color_length;
for (int y=0; y<tile_height; y++) {
int image_col_factor = (y+yStart)*data_width + xStart;
k = y*color_length_times_texture_width;
for (int x=0; x<tile_width; x++) {
int i = x + image_col_factor;
int ndx = ((int) bytes0[i]) - MISSING1;
if (color_length == 4) {
byteData[k] = itable[ndx][3];
byteData[k+1] = itable[ndx][2];
byteData[k+2] = itable[ndx][1];
byteData[k+3] = itable[ndx][0];
}
if (color_length == 3) {
byteData[k] = itable[ndx][2];
byteData[k+1] = itable[ndx][1];
byteData[k+2] = itable[ndx][0];
}
if (color_length == 1) {
byteData[k] = itable[ndx][0];
}
k+=color_length;
}
}
} else {
// medium speed way to build texture colors
if (first_time) {
scaled_Bytes = null;
scaled_Floats = ((Field) data).getFloats(false);
//GHANSHAM:30AUG2011 If rset can be used to create a lookup for range values, create them
if (rset instanceof Integer1DSet) {
rset_scalarmap_lookup = new float[1][rset.getLength()];
for (int i = 0; i < rset_scalarmap_lookup[0].length; i++) {
rset_scalarmap_lookup[0][i] = i;
}
rset_scalarmap_lookup[0] = cmap.scaleValues(rset_scalarmap_lookup[0], false);
} else {
scaled_Floats[0] = cmap.scaleValues(scaled_Floats[0]);
}
}
// now do fast lookup from byte values to color bytes
float[] values0 = scaled_Floats[0];
int k = 0;
int color_length_times_texture_width = texture_width*color_length;
int image_col_offset = yStart*data_width + xStart;
int image_col_factor = 0;
for (int y=0; y<tile_height; y++) {
image_col_factor = y*data_width+image_col_offset;
k = y*color_length_times_texture_width;
for (int x=0; x<tile_width; x++) {
int i = x + image_col_factor;
if (!Float.isNaN(values0[i])) { // not missing
int j = 0;
//GHANSHAM:30AUG2011 Use the rset lookup to find scaled Range Values
if (null != rset_scalarmap_lookup && null != rset_scalarmap_lookup[0]) {
j = (int) (table_scale*rset_scalarmap_lookup[0][(int)values0[i]]);
} else {
j = (int) (table_scale*values0[i]);
}
// clip to table
int ndx = j < 0 ? 0 : (j > tblEnd ? tblEnd : j);
if (color_length == 4) {
byteData[k] = itable[ndx][3];
byteData[k+1] = itable[ndx][2];
byteData[k+2] = itable[ndx][1];
byteData[k+3] = itable[ndx][0];
}
if (color_length == 3) {
byteData[k] = itable[ndx][2];
byteData[k+1] = itable[ndx][1];
byteData[k+2] = itable[ndx][0];
}
if (color_length == 1) {
byteData[k] = itable[ndx][0];
}
}
k+=color_length;
}
}
}
} else { // if (table == null)
// slower, more general way to build texture colors
if (first_time) {
// call lookupValues which will use function since table == null
scaled_Bytes = null;
itable = null;
scaled_Floats = ((Field) data).getFloats(false);
scaled_Floats[0] = cmap.scaleValues(scaled_Floats[0]);
color_values = control.lookupValues(scaled_Floats[0]);
}
// combine color RGB components into bytes
// int r, g, b, a = 255;
int r, g, b;
int c = (int) (255.0 * (1.0f - constant_alpha));
int a = (c < 0) ? 0 : ((c > 255) ? 255 : c);
int k = 0;
int color_length_times_texture_width = texture_width*color_length;
int image_col_offset = yStart*data_width + xStart;
int image_col_factor = 0;
for (int y=0; y<tile_height; y++) {
image_col_factor = y*data_width+image_col_offset;
k = y*color_length_times_texture_width;
for (int x=0; x<tile_width; x++) {
int i = x + image_col_factor;
if (!Float.isNaN(scaled_Floats[0][i])) { // not missing
c = (int) (255.0 * color_values[0][i]);
r = (c < 0) ? 0 : ((c > 255) ? 255 : c);
c = (int) (255.0 * color_values[1][i]);
g = (c < 0) ? 0 : ((c > 255) ? 255 : c);
c = (int) (255.0 * color_values[2][i]);
b = (c < 0) ? 0 : ((c > 255) ? 255 : c);
if (color_length == 4) {
c = (int) (255.0 * color_values[3][i]);
a = (c < 0) ? 0 : ((c > 255) ? 255 : c);
}
if (color_length == 4) {
byteData[k] = (byte) a;
byteData[k+1] = (byte) b;
byteData[k+2] = (byte) g;
byteData[k+3] = (byte) r;
}
if (color_length == 3) {
byteData[k] = (byte) b;
byteData[k+1] = (byte) g;
byteData[k+2] = (byte) r;
}
if (color_length == 1) {
byteData[k] = (byte) b;
}
}
k+=color_length;
}
}
}
} else if (cmaps != null) {
Set rsets[] = null;
if (data instanceof ImageFlatField) {
if (first_time) {
scaled_Bytes = ((FlatField) data).grabBytes();
}
}
//GHANSHAM:30AUG2011 Extract rsets from RGB FlatField
if (data instanceof FlatField) {
rsets = ((FlatField) data). getRangeSets();
}
boolean isRGBRGBRGB = ((cmaps[0].getDisplayScalar() == Display.RGB) && (cmaps[1].getDisplayScalar() == Display.RGB) && (cmaps[2].getDisplayScalar() == Display.RGB));
int r, g, b, c;
int tableEnd = 0;
if (first_time) {
if (isRGBRGBRGB) { //Inserted by Ghansham (starts here)
int map_indx;
threeD_itable = new byte[cmaps.length][][];
for (map_indx = 0; map_indx < cmaps.length; map_indx++) {
BaseColorControl basecolorcontrol = (BaseColorControl)cmaps[map_indx].getControl();
float color_table[][] = basecolorcontrol.getTable();
threeD_itable[map_indx] = new byte[color_table[0].length][3];
int table_indx;
for(table_indx = 0; table_indx < threeD_itable[map_indx].length; table_indx++) {
c = (int) (255.0 * color_table[0][table_indx]);
r = (c < 0) ? 0 : ((c > 255) ? 255 : c);
c = (int) (255.0 * color_table[1][table_indx]);
g = (c < 0) ? 0 : ((c > 255) ? 255 : c);
c = (int) (255.0 * color_table[2][table_indx]);
b = (c < 0) ? 0 : ((c > 255) ? 255 : c);
threeD_itable[map_indx][table_indx][0] = (byte) r;
threeD_itable[map_indx][table_indx][1] = (byte) g;
threeD_itable[map_indx][table_indx][2] = (byte) b;
}
}
}
}
if (scaled_Bytes != null) {
// grab bytes directly from ImageFlatField
if (ImageFlatField.DEBUG) {
System.err.println("ShadowImageFunctionTypeJ3D.doTransform: " + "cmaps != null: grab bytes directly");
}
//Inserted by Ghansham starts here
//IFF:Assume that FlatField is of type (element,line)->(R,G,B) with (Display.RGB,Display.RGB,Display.RGB) as mapping
if (cmaps[0].getDisplayScalar() == Display.RGB && cmaps[1].getDisplayScalar() == Display.RGB && cmaps[2].getDisplayScalar() == Display.RGB) {
int map_indx = 0;
for (map_indx = 0; map_indx < cmaps.length; map_indx++) {
int table_length = threeD_itable[0].length;
int color_indx = permute[map_indx];
if (first_time) {
scaled_Bytes[color_indx] = cmaps[color_indx].scaleValues(scaled_Bytes[color_indx], table_length);
}
int domainLength = scaled_Bytes[color_indx].length;
int tblEnd = table_length - 1;
int data_indx = 0;
int texture_index = 0;
int image_col_offset = yStart*data_width + xStart;
int image_col_factor = 0;
for (int y=0; y<tile_height; y++) {
image_col_factor = y*data_width + image_col_offset;
for (int x=0; x<tile_width; x++) {
data_indx = x + image_col_factor;
texture_index = x + y*texture_width;
texture_index *= color_length;
int j = scaled_Bytes[color_indx][data_indx] & 0xff; // unsigned
// clip to table
int ndx = j < 0 ? 0 : (j > tblEnd ? tblEnd : j);
byteData[texture_index+(color_length-color_indx-1)]=threeD_itable[map_indx][ndx][map_indx]; //Check if this logic works well
}
}
}
} else { //Inserted by Ghansham (Ends here)
int data_indx = 0;
int texture_index = 0;
int offset=0;
c = 0;
if (color_length == 4) {
c = (int) (255.0 * (1.0f - constant_alpha));
}
//IFF:with (Red,Green,Blue) or (Red,Green,Blue,Alpha) as mapping
int color_length_times_texture_width = color_length*texture_width;
int image_col_offset = yStart*data_width + xStart;
int image_col_factor = 0;
for (int y=0; y<tile_height; y++) {
image_col_factor = y*data_width + image_col_offset;
texture_index = y*color_length_times_texture_width;
for (int x=0; x<tile_width; x++) {
data_indx = x + image_col_factor;
if (color_length == 4) {
byteData[texture_index] = (byte)c; //a
byteData[texture_index+1] = scaled_Bytes[2][data_indx]; //b
byteData[texture_index+2] = scaled_Bytes[1][data_indx]; //g
byteData[texture_index+3] = scaled_Bytes[0][data_indx]; //r
} else {
byteData[texture_index] = scaled_Bytes[2][data_indx]; //b
byteData[texture_index+1] = scaled_Bytes[1][data_indx]; //g
byteData[texture_index+2] = scaled_Bytes[0][data_indx]; //r
}
texture_index += color_length;
}
}
}
} else {
if (first_time) {
float[][] values = ((Field) data).getFloats(false);
scaled_Floats = new float[3][];
for (int i = 0; i < scaled_Floats.length; i++) {
//GHANSHAM:30AUG2011 Use the rset lookup to find scaled Range Values
if (rsets != null) {
if (rsets[permute[i]] instanceof Integer1DSet) {
if (null == rset_scalarmap_lookup) {
rset_scalarmap_lookup = new float[3][];
}
rset_scalarmap_lookup[i] = new float[rsets[permute[i]].getLength()];
for (int j = 0; j < rset_scalarmap_lookup[i].length; j++) {
rset_scalarmap_lookup[i][j] = j;
}
rset_scalarmap_lookup[i] = cmaps[permute[i]].scaleValues(rset_scalarmap_lookup[i], false);
scaled_Floats[i] = values[permute[i]];
} else {
scaled_Floats[i] = cmaps[permute[i]].scaleValues(values[permute[i]]);
}
} else {
scaled_Floats[i] = cmaps[permute[i]].scaleValues(values[permute[i]]);
}
}
}
c = (int) (255.0 * (1.0f - constant_alpha));
int a = (c < 0) ? 0 : ((c > 255) ? 255 : c);
int m = 0;
//GHANSHAM:30AUG2011 Create tableLengths for each of the tables separately rather than single table_length. More safe
int RGB_tableEnd[] = null;;
if (isRGBRGBRGB) {
RGB_tableEnd = new int[threeD_itable.length];
for (int indx = 0; indx < threeD_itable.length; indx++) {
RGB_tableEnd[indx]= threeD_itable[indx].length - 1;
}
}
int k = 0;
int color_length_times_texture_width = color_length*texture_width;
int image_col_offset = yStart*data_width + xStart;
int image_col_factor = 0;
for (int y=0; y<tile_height; y++) {
image_col_factor = y*data_width + image_col_offset;
k = y*color_length_times_texture_width;
for (int x=0; x<tile_width; x++) {
int i = x + image_col_factor;
if (!Float.isNaN(scaled_Floats[0][i]) && !Float.isNaN(scaled_Floats[1][i]) && !Float.isNaN(scaled_Floats[2][i])) { // not missing
r=0;g=0;b=0;
if (isRGBRGBRGB) { //Inserted by Ghansham (start here)
int indx = -1;
//GHANSHAM:30AUG2011 Use the rset_scalarmap lookup to find scaled Range Values
if (rset_scalarmap_lookup != null && rset_scalarmap_lookup[0] != null) {
indx = (int)(RGB_tableEnd[0] * rset_scalarmap_lookup[0][(int)scaled_Floats[0][i]]);
} else{
indx = (int)(RGB_tableEnd[0] * scaled_Floats[0][i]);
}
indx = (indx < 0) ? 0 : ((indx > RGB_tableEnd[0]) ? RGB_tableEnd[0] : indx);
r = threeD_itable[0][indx][0];
//GHANSHAM:30AUG2011 Use the rset_scalarmap lookup to find scaled Range Values
if (rset_scalarmap_lookup != null && rset_scalarmap_lookup[1] != null) {
indx = (int)(RGB_tableEnd[1] * rset_scalarmap_lookup[1][(int)scaled_Floats[1][i]]);
} else{
indx = (int)(RGB_tableEnd[1] * scaled_Floats[1][i]);
}
indx = (indx < 0) ? 0 : ((indx > RGB_tableEnd[1]) ? RGB_tableEnd[1] : indx);
g = threeD_itable[1][indx][1];
//GHANSHAM:30AUG2011 Use the rset_scalarmap lookup to find scaled Range Values
if (rset_scalarmap_lookup != null && rset_scalarmap_lookup[2] != null) {
indx = (int)(RGB_tableEnd[2] * rset_scalarmap_lookup[2][(int)scaled_Floats[2][i]]);
} else {
indx = (int)(RGB_tableEnd[2] * scaled_Floats[2][i]);
}
indx = (indx < 0) ? 0 : ((indx > RGB_tableEnd[2]) ? RGB_tableEnd[2] : indx);
b = threeD_itable[2][indx][2];
} else { //Inserted by Ghansham (ends here)
//GHANSHAM:30AUG2011 Use the rset_scalarmap lookup to find scaled Range Values
if (rset_scalarmap_lookup != null && rset_scalarmap_lookup[0] != null) {
c=(int) (255.0 * rset_scalarmap_lookup[0][(int)scaled_Floats[0][i]]);
} else {
c = (int) (255.0 * scaled_Floats[0][i]);
}
r = (c < 0) ? 0 : ((c > 255) ? 255 : c);
//GHANSHAM:30AUG2011 Use the rset_scalarmap lookup to find scaled Range Values
if (rset_scalarmap_lookup != null && rset_scalarmap_lookup[1] != null) {
c=(int) (255.0 * rset_scalarmap_lookup[1][(int)scaled_Floats[1][i]]);
} else {
c = (int) (255.0 * scaled_Floats[1][i]);
}
g = (c < 0) ? 0 : ((c > 255) ? 255 : c);
//GHANSHAM:30AUG2011 Use the rset_scalarmap lookup to find scaled Range Values
if (rset_scalarmap_lookup != null && rset_scalarmap_lookup[2] != null) {
c=(int) (255.0 * rset_scalarmap_lookup[2][(int)scaled_Floats[2][i]]);
} else {
c = (int) (255.0 * scaled_Floats[2][i]);
}
b = (c < 0) ? 0 : ((c > 255) ? 255 : c);
}
if (color_length == 4) {
byteData[k] = (byte) a;
byteData[k+1] = (byte) b;
byteData[k+2] = (byte) g;
byteData[k+3] = (byte) r;
} if (color_length == 3) {
byteData[k] = (byte) b;
byteData[k+1] = (byte) g;
byteData[k+2] = (byte) r;
}
if (color_length == 1) {
byteData[k] = (byte) b;
}
}
k+=color_length;
}
}
RGB_tableEnd = null;
}
} else {
throw new BadMappingException("cmap == null and cmaps == null ??");
}
}
public void buildCurvedTexture(Object group, Set domain_set, Unit[] dataUnits, Unit[] domain_units,
float[] default_values, ShadowRealType[] DomainComponents,
int valueArrayLength, int[] inherited_values, int[] valueToScalar,
GraphicsModeControl mode, float constant_alpha, float[] value_array,
float[] constant_color, DisplayImpl display,
int curved_size, ShadowRealTupleType Domain, CoordinateSystem dataCoordinateSystem,
DataRenderer renderer, ShadowFunctionOrSetType adaptedShadowType,
int[] start, int lenX, int lenY, float[][] samples, int bigX, int bigY,
VisADImageTile tile)
throws VisADException, DisplayException {
float[] coordinates = null;
float[] texCoords = null;
int data_width = 0;
int data_height = 0;
int texture_width = 1;
int texture_height = 1;
int[] lengths = null;
// get domain_set sizes
if (domain_set != null) {
lengths = ((GriddedSet) domain_set).getLengths();
}
else {
lengths = new int[] {lenX, lenY};
}
data_width = lengths[0];
data_height = lengths[1];
// texture sizes must be powers of two on older graphics cards.
texture_width = textureWidth(data_width);
texture_height = textureHeight(data_height);
// transform for any CoordinateSystem in data (Field) Domain
ShadowRealTupleType domain_reference = Domain.getReference();
ShadowRealType[] DC = DomainComponents;
if (domain_reference != null &&
domain_reference.getMappedDisplayScalar()) {
RealTupleType ref = (RealTupleType) domain_reference.getType();
renderer.setEarthSpatialData(Domain, domain_reference, ref,
ref.getDefaultUnits(), (RealTupleType) Domain.getType(),
new CoordinateSystem[] {dataCoordinateSystem},
domain_units);
// ShadowRealTypes of DomainReference
DC = adaptedShadowType.getDomainReferenceComponents();
}
else {
RealTupleType ref = (domain_reference == null) ? null :
(RealTupleType) domain_reference.getType();
Unit[] ref_units = (ref == null) ? null : ref.getDefaultUnits();
renderer.setEarthSpatialData(Domain, domain_reference, ref,
ref_units, (RealTupleType) Domain.getType(),
new CoordinateSystem[] {dataCoordinateSystem},
domain_units);
}
int[] tuple_index = new int[3];
int[] spatial_value_indices = {-1, -1, -1};
ScalarMap[] spatial_maps = new ScalarMap[3];
DisplayTupleType spatial_tuple = null;
for (int i=0; i<DC.length; i++) {
Enumeration maps =
DC[i].getSelectedMapVector().elements();
ScalarMap map = (ScalarMap) maps.nextElement();
DisplayRealType real = map.getDisplayScalar();
spatial_tuple = real.getTuple();
if (spatial_tuple == null) {
throw new DisplayException("texture with bad tuple: " +
"ShadowImageFunctionTypeJ3D.doTransform");
}
// get spatial index
tuple_index[i] = real.getTupleIndex();
spatial_value_indices[tuple_index[i]] = map.getValueIndex();
spatial_maps[tuple_index[i]] = map;
if (maps.hasMoreElements()) {
throw new DisplayException("texture with multiple spatial: " +
"ShadowImageFunctionTypeJ3D.doTransform");
}
} // end for (int i=0; i<DC.length; i++)
// get spatial index not mapped from domain_set
tuple_index[2] = 3 - (tuple_index[0] + tuple_index[1]);
DisplayRealType real =
(DisplayRealType) spatial_tuple.getComponent(tuple_index[2]);
int value2_index = display.getDisplayScalarIndex(real);
float value2 = default_values[value2_index];
for (int i=0; i<valueArrayLength; i++) {
if (inherited_values[i] > 0 &&
real.equals(display.getDisplayScalar(valueToScalar[i])) ) {
value2 = value_array[i];
break;
}
}
boolean useLinearTexture = false;
double[] scale = null;
double[] offset = null;
CoordinateSystem coord = null;
if (spatial_tuple.equals(Display.DisplaySpatialCartesianTuple)) {
// inside 'if (anyFlow) {}' in ShadowType.assembleSpatial()
renderer.setEarthSpatialDisplay(null, spatial_tuple, display,
spatial_value_indices, default_values, null);
} else {
coord = spatial_tuple.getCoordinateSystem();
if (coord instanceof CachingCoordinateSystem) {
coord = ((CachingCoordinateSystem)coord).getCachedCoordinateSystem();
}
if (coord instanceof InverseLinearScaledCS) {
InverseLinearScaledCS invCS = (InverseLinearScaledCS)coord;
useLinearTexture = (invCS.getInvertedCoordinateSystem()).equals(dataCoordinateSystem);
scale = invCS.getScale();
offset = invCS.getOffset();
}
// inside 'if (anyFlow) {}' in ShadowType.assembleSpatial()
renderer.setEarthSpatialDisplay(coord, spatial_tuple, display,
spatial_value_indices, default_values, null);
}
if (useLinearTexture) {
float scaleX = (float) scale[0];
float scaleY = (float) scale[1];
float offsetX = (float) offset[0];
float offsetY = (float) offset[1];
float[][] xyCoords = null;
if (domain_set != null) {
xyCoords = getBounds(domain_set, data_width, data_height, scaleX, offsetX, scaleY, offsetY);
} else {
//If there is tiling in linear texture domain set is coming null if number of tiles is greater than 1
//Code inserted by Ghansham (starts here)
int indx0 = (start[0]) + (start[1])*bigX;
int indx1 = (start[0]) + (start[1] + lenY-1)*bigX;
int indx2 = (start[0] + lenX -1) + (start[1] + lenY - 1)*bigX;
int indx3 = (start[0] + lenX -1 ) + (start[1])*bigX;
float x0 = samples[0][indx0];
float y0 = samples[1][indx0];
float x1 = samples[0][indx1];
float y1 = samples[1][indx1];
float x2 = samples[0][indx2];
float y2 = samples[1][indx2];
float x3 = samples[0][indx3];
float y3 = samples[1][indx3];
xyCoords = new float[2][4];
xyCoords[0][0] = (x0 - offsetX)/scaleX;
xyCoords[1][0] = (y0 - offsetY)/scaleY;
xyCoords[0][1] = (x1 - offsetX)/scaleX;
xyCoords[1][1] = (y1 - offsetY)/scaleY;
xyCoords[0][2] = (x2 - offsetX)/scaleX;
xyCoords[1][2] = (y2 - offsetY)/scaleY;
xyCoords[0][3] = (x3 - offsetX)/scaleX;
xyCoords[1][3] = (y3 - offsetY)/scaleY;
//Code inserted by Ghansham (Ends here)
}
// create VisADQuadArray that texture is mapped onto
coordinates = new float[12];
// corner 0 (-1,1)
coordinates[tuple_index[0]] = xyCoords[0][0];
coordinates[tuple_index[1]] = xyCoords[1][0];
coordinates[tuple_index[2]] = value2;
// corner 1 (-1,-1)
coordinates[3+tuple_index[0]] = xyCoords[0][1];
coordinates[3+tuple_index[1]] = xyCoords[1][1];
coordinates[3 + tuple_index[2]] = value2;
// corner 2 (1, -1)
coordinates[6+tuple_index[0]] = xyCoords[0][2];
coordinates[6+tuple_index[1]] = xyCoords[1][2];
coordinates[6 + tuple_index[2]] = value2;
// corner 3 (1,1)
coordinates[9+tuple_index[0]] = xyCoords[0][3];
coordinates[9+tuple_index[1]] = xyCoords[1][3];
coordinates[9 + tuple_index[2]] = value2;
// move image back in Java3D 2-D mode
adjustZ(coordinates);
texCoords = new float[8];
float ratiow = ((float) data_width) / ((float) texture_width);
float ratioh = ((float) data_height) / ((float) texture_height);
boolean yUp = true;
setTexCoords(texCoords, ratiow, ratioh, yUp);
VisADQuadArray qarray = new VisADQuadArray();
qarray.vertexCount = 4;
qarray.coordinates = coordinates;
qarray.texCoords = texCoords;
/*REUSE GEOM/COLORBYTES:I have replaced reuse with reuseImages.
And here in the else logic I have added a few more lines.
The else part of this never got executed because reuse was always false.
Now else part gets executed when reuse is true and either regen_geom or regen_colbytes is true.
It just applies geometry to the already available texture.
When both are true then if part gets executed.
*/
//if (!reuse)
if (!reuseImages || (regen_colbytes && regen_geom)) { //REUSE GEOM/COLORBYTES: Earlier reuse variable was used. Replaced it with reuseImages and regeom_colbytes and regen_geom
BufferedImage image = tile.getImage(0);
textureToGroup(group, qarray, image, mode, constant_alpha,
constant_color, texture_width, texture_height, true, true, tile);
} else { //REUSE GEOM/COLORBYTES: reuse the colorbytes just apply the geometry
int num_children = ((BranchGroup) group).numChildren();
if (num_children > 0) {
BranchGroup branch1 = (BranchGroup) ((BranchGroup) group).getChild(0); //This the branch group created by textureToGroup Function
Shape3D shape = (Shape3D) branch1.getChild(0);
shape.setGeometry(((DisplayImplJ3D) display).makeGeometry(qarray));
}
if (animControl == null) {
imgNode.setCurrent(0);
}
}
}
else {
// compute size of triangle array to map texture onto
int size = (data_width + data_height) / 2;
curved_size = Math.max(1, Math.min(curved_size, size / 32));
int nwidth = 2 + (data_width - 1) / curved_size;
int nheight = 2 + (data_height - 1) / curved_size;
// compute locations of triangle vertices in texture
int nn = nwidth * nheight;
int[] is = new int[nwidth];
int[] js = new int[nheight];
for (int i=0; i<nwidth; i++) {
is[i] = Math.min(i * curved_size, data_width - 1);
}
for (int j=0; j<nheight; j++) {
js[j] = Math.min(j * curved_size, data_height - 1);
}
// get spatial coordinates at triangle vertices
int k = 0;
float[][] spline_domain = null;
if (domain_set == null) {
//Ghansham: We generate the indices for the samples directly from 'is' and 'js' array
spline_domain = new float[2][nn];
int kk = 0;
int ndx = 0;
int col_factor = 0;
for (int j = 0; j < nheight; j++) {
col_factor = (start[1] + js[j]) * bigX;
for (int i = 0; i < nwidth; i++) {
ndx = (start[0] + is[i]) + col_factor;
spline_domain[0][kk] = samples[0][ndx];
spline_domain[1][kk] = samples[1][ndx];
kk++;
}
}
}
else {
int[] indices = new int[nn]; //Ghansham:Calculate indices only if there is a single tile in the full image
k=0;
int col_factor;
for (int j=0; j<nheight; j++) {
col_factor = data_width * js[j];
for (int i=0; i<nwidth; i++) {
indices[k] = is[i] + col_factor;
k++;
}
}
spline_domain = domain_set.indexToValue(indices);
indices = null;
}
spline_domain = Unit.convertTuple(spline_domain, dataUnits, domain_units, false);
if (domain_reference != null
&& domain_reference.getMappedDisplayScalar()) {
RealTupleType ref = (RealTupleType) domain_reference.getType();
spline_domain =
CoordinateSystem.transformCoordinates(
ref, null, ref.getDefaultUnits(), null,
(RealTupleType) Domain.getType(), dataCoordinateSystem,
domain_units, null, spline_domain);
}
float[][] spatial_values = new float[3][];
spatial_values[tuple_index[0]] = spline_domain[0];
spatial_values[tuple_index[1]] = spline_domain[1];
for (int i = 0; i < 3; i++) {
if (spatial_maps[i] != null) {
spatial_values[i] = spatial_maps[i].scaleValues(spatial_values[i], false);
}
}
if (!spatial_tuple.equals(Display.DisplaySpatialCartesianTuple)) {
spatial_values = coord.toReference(spatial_values);
}
boolean isSpherical = spatial_tuple.equals(Display.DisplaySpatialSphericalTuple);
boolean spatial_all_select = true;
if (isSpherical) {
for (int i=0; i<nn; i++) {
if (Float.isNaN(spatial_values[0][i]) || Float.isNaN(spatial_values[1][i]) || Float.isNaN(spatial_values[2][i])) {
spatial_all_select = false;
break;
}
}
} else {
if (Float.isNaN(value2)) {
spatial_all_select = false;
} else {
for (int i=0; i<nn; i++) {
if (Float.isNaN(spatial_values[0][i]) || Float.isNaN(spatial_values[1][i])) {
spatial_all_select = false;
break;
}
}
}
}
VisADTriangleStripArray tarray = new VisADTriangleStripArray();
tarray.stripVertexCounts = new int[nheight - 1];
java.util.Arrays.fill(tarray.stripVertexCounts, 2 * nwidth);
int len = (nheight - 1) * (2 * nwidth);
tarray.vertexCount = len;
tarray.coordinates = new float[3 * len];
tarray.texCoords = new float[2 * len];
int m = 0;
k = 0;
int kt = 0;
float y_coord = 0f;
float y_coord2 = 0f;
float x_coord = 0f;
for (int j=0; j<nheight-1; j++) {
if (0 ==j){
y_coord = (0.5f + js[j])/texture_height;
} else {
y_coord = y_coord2;
}
y_coord2 = (0.5f + js[j+1])/texture_height;
for (int i=0; i<nwidth; i++) {
tarray.coordinates[k++] = spatial_values[0][m];
tarray.coordinates[k++] = spatial_values[1][m];
tarray.coordinates[k++] = value2;
tarray.coordinates[k++] = spatial_values[0][m+nwidth];
tarray.coordinates[k++] = spatial_values[1][m+nwidth];
tarray.coordinates[k++] = value2;
x_coord = (0.5f + is[i])/texture_width;
tarray.texCoords[kt++] = x_coord;
tarray.texCoords[kt++] = y_coord;
tarray.texCoords[kt++] = x_coord;
tarray.texCoords[kt++] = y_coord2;
m += 1;
}
}
is = null;
js = null;
spatial_values[0] = null;
spatial_values[1] = null;
spatial_values[2] = null;
spatial_values = null;
spline_domain[0] = null;
spline_domain[1] = null;
spline_domain = null;
// do surgery to remove any missing spatial coordinates in texture
if (!spatial_all_select) {
tarray = (VisADTriangleStripArray) tarray.removeMissing();
}
// do surgery along any longitude split (e.g., date line) in texture
if (adaptedShadowType.getAdjustProjectionSeam()) {
tarray = (VisADTriangleStripArray) tarray.adjustLongitude(renderer);
tarray = (VisADTriangleStripArray) tarray.adjustSeam(renderer);
}
/*REUSE GEOM/COLORBYTES:I have replaced reuse with reuseImages.
And here in the else logic I have added a few more lines.
The else part of this never got executed because reuse was always false.
Now else part gets executed when reuseImages is true or either regen_geom or regen_colbytes is true.
It just applies geometry to the already available texture.
When both regen_geom or regen_colbytes are true then if part gets executed.
*/
// add texture as sub-node of group in scene graph
//if (!reuse)
if (!reuseImages || (regen_colbytes && regen_geom)) { //REUSE GEOM/COLORBYTES: Earlier reuse variable was used. Replaced it with reuseImages and regeom_colbytes and regen_geom
BufferedImage image = tile.getImage(0);
textureToGroup(group, tarray, image, mode, constant_alpha, constant_color, texture_width, texture_height, true, true, tile);
} else { //REUSE GEOM/COLORBYTES: Reuse the colorbytes and just apply the geometry
int num_children = ((BranchGroup) group).numChildren();
if (num_children > 0) {
BranchGroup branch1 = (BranchGroup) ((BranchGroup) group).getChild(0); //This is the branch group created by textureToGroup Function
Shape3D shape = (Shape3D) branch1.getChild(0);
shape.setGeometry(((DisplayImplJ3D) display).makeGeometry(tarray));
}
if (animControl == null) {
imgNode.setCurrent(0);
}
}
}
tuple_index = null;
// System.out.println("end curved texture " + (System.currentTimeMillis() - link.start_time));
}
public void buildLinearTexture(Object group, Set domain_set, Unit[] dataUnits, Unit[] domain_units,
float[] default_values, ShadowRealType[] DomainComponents,
int valueArrayLength, int[] inherited_values, int[] valueToScalar,
GraphicsModeControl mode, float constant_alpha,
float[] value_array, float[] constant_color, DisplayImpl display,
VisADImageTile tile)
throws VisADException, DisplayException {
float[] coordinates = null;
float[] texCoords = null;
float[] normals = null;
int data_width = 0;
int data_height = 0;
int texture_width = 1;
int texture_height = 1;
Linear1DSet X = null;
Linear1DSet Y = null;
if (domain_set instanceof Linear2DSet) {
X = ((Linear2DSet) domain_set).getX();
Y = ((Linear2DSet) domain_set).getY();
}
else {
X = ((LinearNDSet) domain_set).getLinear1DComponent(0);
Y = ((LinearNDSet) domain_set).getLinear1DComponent(1);
}
float[][] limits = new float[2][2];
limits[0][0] = (float) X.getFirst();
limits[0][1] = (float) X.getLast();
limits[1][0] = (float) Y.getFirst();
limits[1][1] = (float) Y.getLast();
// get domain_set sizes
data_width = X.getLength();
data_height = Y.getLength();
// texture sizes must be powers of two on older graphics cards
texture_width = textureWidth(data_width);
texture_height = textureHeight(data_height);
// WLH 27 Jan 2003
float half_width = 0.5f / ((float) (data_width - 1));
float half_height = 0.5f / ((float) (data_height - 1));
half_width = (limits[0][1] - limits[0][0]) * half_width;
half_height = (limits[1][1] - limits[1][0]) * half_height;
limits[0][0] -= half_width;
limits[0][1] += half_width;
limits[1][0] -= half_height;
limits[1][1] += half_height;
// convert values to default units (used in display)
limits = Unit.convertTuple(limits, dataUnits, domain_units);
int[] tuple_index = new int[3];
if (DomainComponents.length != 2) {
throw new DisplayException("texture domain dimension != 2:" +
"ShadowFunctionOrSetType.doTransform");
}
// find the spatial ScalarMaps
for (int i=0; i<DomainComponents.length; i++) {
Enumeration maps = DomainComponents[i].getSelectedMapVector().elements();
ScalarMap map = (ScalarMap) maps.nextElement();
// scale values
limits[i] = map.scaleValues(limits[i]);
DisplayRealType real = map.getDisplayScalar();
DisplayTupleType tuple = real.getTuple();
if (tuple == null ||
!tuple.equals(Display.DisplaySpatialCartesianTuple)) {
throw new DisplayException("texture with bad tuple: " +
"ShadowFunctionOrSetType.doTransform");
}
// get spatial index
tuple_index[i] = real.getTupleIndex();
if (maps.hasMoreElements()) {
throw new DisplayException("texture with multiple spatial: " +
"ShadowFunctionOrSetType.doTransform");
}
} // end for (int i=0; i<DomainComponents.length; i++)
// get spatial index not mapped from domain_set
tuple_index[2] = 3 - (tuple_index[0] + tuple_index[1]);
DisplayRealType real = (DisplayRealType)
Display.DisplaySpatialCartesianTuple.getComponent(tuple_index[2]);
int value2_index = display.getDisplayScalarIndex(real);
float value2 = default_values[value2_index];
for (int i=0; i<valueArrayLength; i++) {
if (inherited_values[i] > 0 &&
real.equals(display.getDisplayScalar(valueToScalar[i])) ) {
// value for unmapped spatial dimension
value2 = value_array[i];
break;
}
}
// create VisADQuadArray that texture is mapped onto
coordinates = new float[12];
// corner 0
coordinates[tuple_index[0]] = limits[0][0];
coordinates[tuple_index[1]] = limits[1][0];
coordinates[tuple_index[2]] = value2;
// corner 1
coordinates[3 + tuple_index[0]] = limits[0][0];
coordinates[3 + tuple_index[1]] = limits[1][1];
coordinates[3 + tuple_index[2]] = value2;
// corner 2
coordinates[6 + tuple_index[0]] = limits[0][1];
coordinates[6 + tuple_index[1]] = limits[1][1];
coordinates[6 + tuple_index[2]] = value2;
// corner 3
coordinates[9 + tuple_index[0]] = limits[0][1];
coordinates[9 + tuple_index[1]] = limits[1][0];
coordinates[9 + tuple_index[2]] = value2;
// move image back in Java3D 2-D mode
adjustZ(coordinates);
texCoords = new float[8];
float ratiow = ((float) data_width) / ((float) texture_width);
float ratioh = ((float) data_height) / ((float) texture_height);
boolean yUp = true;
setTexCoords(texCoords, ratiow, ratioh, yUp);
VisADQuadArray qarray = new VisADQuadArray();
qarray.vertexCount = 4;
qarray.coordinates = coordinates;
qarray.texCoords = texCoords;
/*REUSE GEOM/COLORBYTES:I have replaced reuse with reuseImages.
And here in the else logic I have added a few more lines.
The else part of this never got executed because reuse was always false.
Now else part gets executed when reuse is true and either regen_geom or regen_colbytes is true.
It just applies geometry to the already available texture.
When both are true then if part gets executed.
*/
// add texture as sub-node of group in scene graph
if (!reuseImages|| (regen_colbytes && regen_geom)) { //REUSE GEOM/COLORBYTES: Earlier reuse variable was used. Replaced it with reuseImages and regeom_colbytes and regen_geom
BufferedImage image = tile.getImage(0);
textureToGroup(group, qarray, image, mode, constant_alpha,
constant_color, texture_width, texture_height, true, true, tile);
}
else {
int num_children = ((BranchGroup) group).numChildren();
if (num_children > 0) { //REUSE GEOM/COLORBYTES: Reuse the colorbytes and apply geometry
BranchGroup branch1 = (BranchGroup) ((BranchGroup) group).getChild(0); //This the branch group created by textureToGroup Function
Shape3D shape = (Shape3D) branch1.getChild(0);
shape.setGeometry(((DisplayImplJ3D) display).makeGeometry(qarray));
}
if (animControl == null) {
imgNode.setCurrent(0);
}
}
}
//public CachedBufferedByteImage createImageByRef(final int texture_width, final int texture_height, final int imageType) {
public BufferedImage createImageByRef(final int texture_width, final int texture_height, final int imageType) {
return new BufferedImage(texture_width, texture_height, imageType);
}
public static float[][] getBounds(Set domain_set, float data_width, float data_height,
float scaleX, float offsetX, float scaleY, float offsetY)
throws VisADException
{
float[][] xyCoords = new float[2][4];
float[][] coords0 = ((GriddedSet)domain_set).gridToValue(new float[][] {{0f},{0f}});
float[][] coords1 = ((GriddedSet)domain_set).gridToValue(new float[][] {{0f},{(float)(data_height-1)}});
float[][] coords2 = ((GriddedSet)domain_set).gridToValue(new float[][] {{(data_width-1f)},{(data_height-1f)}});
float[][] coords3 = ((GriddedSet)domain_set).gridToValue(new float[][] {{(data_width-1f)},{0f}});
float x0 = coords0[0][0];
float y0 = coords0[1][0];
float x1 = coords1[0][0];
float y1 = coords1[1][0];
float x2 = coords2[0][0];
float y2 = coords2[1][0];
float x3 = coords3[0][0];
float y3 = coords3[1][0];
xyCoords[0][0] = (x0 - offsetX)/scaleX;
xyCoords[1][0] = (y0 - offsetY)/scaleY;
xyCoords[0][1] = (x1 - offsetX)/scaleX;
xyCoords[1][1] = (y1 - offsetY)/scaleY;
xyCoords[0][2] = (x2 - offsetX)/scaleX;
xyCoords[1][2] = (y2 - offsetY)/scaleY;
xyCoords[0][3] = (x3 - offsetX)/scaleX;
xyCoords[1][3] = (y3 - offsetY)/scaleY;
return xyCoords;
}
}
class SwitchNotify extends Switch {
VisADImageNode imgNode;
int numChildren;
Switch swit;
SwitchNotify(VisADImageNode imgNode, int numChildren) {
super();
this.imgNode = imgNode;
this.numChildren = numChildren;
this.swit = imgNode.getSwitch();
}
public int numChildren() {
return numChildren;
}
public void setWhichChild(int index) {
if (index == Switch.CHILD_NONE) {
swit.setWhichChild(Switch.CHILD_NONE);
}
else if (index >= 0) {
if ( swit.getWhichChild() == Switch.CHILD_NONE) {
swit.setWhichChild(0);
}
imgNode.setCurrent(index);
}
}
}
class Mosaic {
Tile[][] tiles;
ArrayList<Tile> tileList = new ArrayList<Tile>();
int n_x_sub = 1;
int n_y_sub = 1;
Mosaic(int lenY, int limitY, int lenX, int limitX) {
int y_sub_len = limitY;
n_y_sub = lenY/y_sub_len;
if (n_y_sub == 0) n_y_sub++;
if ((lenY - n_y_sub*y_sub_len) > 4) n_y_sub += 1;
int[][] y_start_stop = new int[n_y_sub][2];
for (int k = 0; k < n_y_sub-1; k++) {
y_start_stop[k][0] = k*y_sub_len - k;
y_start_stop[k][1] = ((k+1)*y_sub_len - 1) - k;
// check that we don't exceed limit
if ( ((y_start_stop[k][1]-y_start_stop[k][0])+1) > limitY) {
y_start_stop[k][1] -= 1; //too big, take away gap fill
}
}
int k = n_y_sub-1;
y_start_stop[k][0] = k*y_sub_len - k;
y_start_stop[k][1] = lenY - 1 - k;
int x_sub_len = limitX;
n_x_sub = lenX/x_sub_len;
if (n_x_sub == 0) n_x_sub++;
if ((lenX - n_x_sub*x_sub_len) > 4) n_x_sub += 1;
int[][] x_start_stop = new int[n_x_sub][2];
for (k = 0; k < n_x_sub-1; k++) {
x_start_stop[k][0] = k*x_sub_len - k;
x_start_stop[k][1] = ((k+1)*x_sub_len - 1) - k;
// check that we don't exceed limit
if ( ((x_start_stop[k][1]-x_start_stop[k][0])+1) > limitX) {
x_start_stop[k][1] -= 1; //too big, take away gap fill
}
}
k = n_x_sub-1;
x_start_stop[k][0] = k*x_sub_len - k;
x_start_stop[k][1] = lenX - 1 - k;
tiles = new Tile[n_y_sub][n_x_sub];
for (int j=0; j<n_y_sub; j++) {
for (int i=0; i<n_x_sub; i++) {
tiles[j][i] =
new Tile(y_start_stop[j][0], y_start_stop[j][1], x_start_stop[i][0], x_start_stop[i][1]);
tileList.add(tiles[j][i]);
}
}
}
Iterator iterator() {
return tileList.iterator();
}
}
class Tile {
int y_start;
int x_start;
int y_stop;
int x_stop;
int height;
int width;
Tile(int y_start, int y_stop, int x_start, int x_stop) {
this.y_start = y_start;
this.y_stop = y_stop;
this.x_start = x_start;
this.x_stop = x_stop;
height = y_stop - y_start + 1;
width = x_stop - x_start + 1;
}
}
| true | true | public boolean doTransform(Object group, Data data, float[] value_array,
float[] default_values, DataRenderer renderer)
throws VisADException, RemoteException {
DataDisplayLink link = renderer.getLink();
// return if data is missing or no ScalarMaps
if (data.isMissing()) {
((ImageRendererJ3D) renderer).markMissingVisADBranch();
return false;
}
if (levelOfDifficulty == -1) {
levelOfDifficulty = getLevelOfDifficulty();
}
if (levelOfDifficulty == NOTHING_MAPPED) return false;
if (group instanceof BranchGroup && ((BranchGroup) group).numChildren() > 0) {
Node g = ((BranchGroup) group).getChild(0);
// WLH 06 Feb 06 - support switch in a branch group.
if (g instanceof BranchGroup && ((BranchGroup) g).numChildren() > 0) {
reuseImages = true;
}
}
DisplayImpl display = getDisplay();
int cMapCurveSize = (int) default_values[display.getDisplayScalarIndex(Display.CurvedSize)];
int curved_size = (cMapCurveSize > 0) ? cMapCurveSize : display.getGraphicsModeControl().getCurvedSize();
// length of ValueArray
int valueArrayLength = display.getValueArrayLength();
// mapping from ValueArray to DisplayScalar
int[] valueToScalar = display.getValueToScalar();
//GHANSHAM:30AUG2011 Restrutured the code to extract the constant_alpha, cmap, cmaps and ShadowFunctionType so that they can be passed to initRegenFlags method
if (adaptedShadowType == null) {
adaptedShadowType = (ShadowFunctionOrSetType) getAdaptedShadowType();
}
boolean anyContour = adaptedShadowType.getAnyContour();
boolean anyFlow = adaptedShadowType.getAnyFlow();
boolean anyShape = adaptedShadowType.getAnyShape();
boolean anyText = adaptedShadowType.getAnyText();
if (anyContour || anyFlow || anyShape || anyText) {
throw new BadMappingException("no contour, flow, shape or text allowed");
}
FlatField imgFlatField = null;
Set domain_set = ((Field) data).getDomainSet();
ShadowRealType[] DomainComponents = adaptedShadowType.getDomainComponents();
int numImages = 1;
if (!adaptedShadowType.getIsTerminal()) {
Vector domain_maps = DomainComponents[0].getSelectedMapVector();
ScalarMap amap = null;
if (domain_set.getDimension() == 1 && domain_maps.size() == 1) {
ScalarMap map = (ScalarMap) domain_maps.elementAt(0);
if (Display.Animation.equals(map.getDisplayScalar())) {
amap = map;
}
}
if (amap == null) {
throw new BadMappingException("time must be mapped to Animation");
}
animControl = (AnimationControlJ3D) amap.getControl();
numImages = domain_set.getLength();
adaptedShadowType = (ShadowFunctionOrSetType) adaptedShadowType.getRange();
DomainComponents = adaptedShadowType.getDomainComponents();
imgFlatField = (FlatField) ((FieldImpl)data).getSample(0);
} else {
imgFlatField = (FlatField)data;
}
// check that range is single RealType mapped to RGB only
ShadowRealType[] RangeComponents = adaptedShadowType.getRangeComponents();
int rangesize = RangeComponents.length;
if (rangesize != 1 && rangesize != 3) {
throw new BadMappingException("image values must single or triple");
}
ScalarMap cmap = null;
ScalarMap[] cmaps = null;
int[] permute = {-1, -1, -1};
boolean hasAlpha = false;
if (rangesize == 1) {
Vector mvector = RangeComponents[0].getSelectedMapVector();
if (mvector.size() != 1) {
throw new BadMappingException("image values must be mapped to RGB only");
}
cmap = (ScalarMap) mvector.elementAt(0);
if (Display.RGB.equals(cmap.getDisplayScalar())) {
} else if (Display.RGBA.equals(cmap.getDisplayScalar())) {
hasAlpha = true;
} else {
throw new BadMappingException("image values must be mapped to RGB or RGBA");
}
} else {
cmaps = new ScalarMap[3];
for (int i=0; i<3; i++) {
Vector mvector = RangeComponents[i].getSelectedMapVector();
if (mvector.size() != 1) {
throw new BadMappingException("image values must be mapped to color only");
}
cmaps[i] = (ScalarMap) mvector.elementAt(0);
if (Display.Red.equals(cmaps[i].getDisplayScalar())) {
permute[0] = i;
} else if (Display.Green.equals(cmaps[i].getDisplayScalar())) {
permute[1] = i;
} else if (Display.Blue.equals(cmaps[i].getDisplayScalar())) {
permute[2] = i;
} else if (Display.RGB.equals(cmaps[i].getDisplayScalar())) { //Inserted by Ghansham for Mapping all the three scalarMaps to Display.RGB (starts here)
permute[i] = i;
} else { ////Inserted by Ghansham for Mapping all the three scalarMaps to Display.RGB(ends here)
throw new BadMappingException("image values must be mapped to Red, Green or Blue only");
}
}
if (permute[0] < 0 || permute[1] < 0 || permute[2] < 0) {
throw new BadMappingException("image values must be mapped to Red, Green or Blue only");
}
//Inserted by Ghansham for Checking that all should be mapped to Display.RGB or not even a single one should be mapped to Display.RGB(starts here)
//This is to check if there is a single Display.RGB ScalarMap
int indx = -1;
for (int i = 0; i < 3; i++) {
if (cmaps[i].getDisplayScalar().equals(Display.RGB)) {
indx = i;
break;
}
}
if (indx != -1){ //if there is a even a single Display.RGB ScalarMap, others must also Display.RGB only
for (int i = 0; i < 3; i++) {
if (i !=indx && !(cmaps[i].getDisplayScalar().equals(Display.RGB))) {
throw new BadMappingException("image values must be mapped to (Red, Green, Blue) or (RGB,RGB,RGB) only");
}
}
}
//Inserted by Ghansham for Checking that all should be mapped to Display.RGB or not even a single one should be mapped to Display.RGB(Ends here)
}
float constant_alpha = default_values[display.getDisplayScalarIndex(Display.Alpha)];
int color_length;
ImageRendererJ3D imgRenderer = (ImageRendererJ3D) renderer;
int imageType = imgRenderer.getSuggestedBufImageType();
if (imageType == BufferedImage.TYPE_4BYTE_ABGR) {
color_length = 4;
if (!hasAlpha) {
color_length = 3;
imageType = BufferedImage.TYPE_3BYTE_BGR;
}
} else if (imageType == BufferedImage.TYPE_3BYTE_BGR) {
color_length = 3;
} else if (imageType == BufferedImage.TYPE_USHORT_GRAY) {
color_length = 2;
} else if (imageType == BufferedImage.TYPE_BYTE_GRAY) {
color_length = 1;
} else {
// we shouldn't ever get here because the renderer validates the
// imageType before we get it, but just in case...
throw new VisADException("renderer returned unsupported image type");
}
if (color_length == 4) constant_alpha = Float.NaN; // WLH 6 May 2003
//REUSE GEOMETRY/COLORBYTE LOGIC (STARTS HERE)
regen_colbytes = false;
regen_geom = false;
apply_alpha = false;
initRegenFlags((ImageRendererJ3D)renderer, adaptedShadowType, constant_alpha, cmap, cmaps, data, display, default_values, value_array, valueToScalar, valueArrayLength, link, curved_size);
if(!reuseImages) {
regen_geom = true;
regen_colbytes = true;
apply_alpha = true;
}
/**
System.err.println("Regenerate Color Bytes:" + regen_colbytes);
System.err.println("Regenerate Geometry:" + regen_geom);
System.err.println("Apply Alpha:" + apply_alpha);
System.err.println("ReuseImages:" + reuseImages);
*/
//REUSE GEOMETRY/COLORBYTE LOGIC (ENDS HERE)
prevImgNode = ((ImageRendererJ3D)renderer).getImageNode();
BranchGroup bgImages = null;
/*REUSE GEOM/COLBYTE: Replaced reuse with reuseImages. Earlier else part of this decision was never being used.
The reason was reuse was always set to false. Compare with your version.
Added one extra line in the else part where I extract the bgImages from the switch.
Now else part occurs when either reuse_colbytes or regen_geom is true.
But when regen_colbytes and regen_geom both are true, then I assume that a new flatfield is set so
go with the if part.
*/
if (!reuseImages || (regen_colbytes && regen_geom)) { //REUSE GEOM/COLBYTE:Earlier reuse variable was used. Replaced it with reuseImages.
//Added regen_colbytes and regen_geom.
//This is used when either its first time or full new data has been with different dims.
BranchGroup branch = new BranchGroup();
branch.setCapability(BranchGroup.ALLOW_DETACH);
branch.setCapability(BranchGroup.ALLOW_CHILDREN_EXTEND);
branch.setCapability(BranchGroup.ALLOW_CHILDREN_READ);
branch.setCapability(BranchGroup.ALLOW_CHILDREN_WRITE);
Switch swit = (Switch) makeSwitch();
imgNode = new VisADImageNode();
bgImages = new BranchGroup();
bgImages.setCapability(BranchGroup.ALLOW_DETACH);
bgImages.setCapability(BranchGroup.ALLOW_CHILDREN_EXTEND);
bgImages.setCapability(BranchGroup.ALLOW_CHILDREN_READ);
bgImages.setCapability(BranchGroup.ALLOW_CHILDREN_WRITE);
swit.addChild(bgImages);
swit.setWhichChild(0);
branch.addChild(swit);
imgNode.setBranch(branch);
imgNode.setSwitch(swit);
((ImageRendererJ3D)renderer).setImageNode(imgNode);
if ( ((BranchGroup) group).numChildren() > 0 ) {
((BranchGroup)group).setChild(branch, 0);
} else {
((BranchGroup)group).addChild(branch);
/*
// make sure group is live. group not empty (above addChild)
if (group instanceof BranchGroup) {
((ImageRendererJ3D) renderer).setBranchEarly((BranchGroup) group);
}
*/
}
} else { //REUSE GEOM/COLBYTE: If its not the first time. And the dims have not changed but either color bytes or geometry has changed.
imgNode = ((ImageRendererJ3D)renderer).getImageNode();
bgImages = (BranchGroup) imgNode.getSwitch().getChild(0); //REUSE GEOM/COLBYTE:Extract the bgImages from the avaialable switch
}
GraphicsModeControl mode = (GraphicsModeControl)
display.getGraphicsModeControl().clone();
// get some precomputed values useful for transform
// mapping from ValueArray to MapVector
int[] valueToMap = display.getValueToMap();
Vector MapVector = display.getMapVector();
Unit[] dataUnits = null;
CoordinateSystem dataCoordinateSystem = null;
if (numImages > 1) {
Switch swit = new SwitchNotify(imgNode, numImages);
((AVControlJ3D) animControl).addPair((Switch) swit, domain_set, renderer);
((AVControlJ3D) animControl).init();
}
domain_set = imgFlatField.getDomainSet();
dataUnits = ((Function) imgFlatField).getDomainUnits();
dataCoordinateSystem =
((Function) imgFlatField).getDomainCoordinateSystem();
int domain_length = domain_set.getLength();
int[] lengths = ((GriddedSet) domain_set).getLengths();
int data_width = lengths[0];
int data_height = lengths[1];
imgNode.numImages = numImages;
imgNode.data_width = data_width;
imgNode.data_height = data_height;
int texture_width_max = link.getDisplay().getDisplayRenderer().getTextureWidthMax();
int texture_height_max = link.getDisplay().getDisplayRenderer().getTextureWidthMax();
int texture_width = textureWidth(data_width);
int texture_height = textureHeight(data_height);
if (reuseImages) {
if (prevImgNode.numImages != numImages ||
prevImgNode.data_width != data_width || prevImgNode.data_height != data_height) {
reuseImages = false;
}
}
if (reuseImages) {
imgNode.numChildren = prevImgNode.numChildren;
imgNode.imageTiles = prevImgNode.imageTiles;
}
else {
Mosaic mosaic = new Mosaic(data_height, texture_height_max, data_width, texture_width_max);
for (Iterator iter = mosaic.iterator(); iter.hasNext();) {
Tile tile = (Tile) iter.next();
imgNode.addTile(new VisADImageTile(numImages, tile.height, tile.y_start, tile.width, tile.x_start));
}
}
prevImgNode = imgNode;
ShadowRealTupleType Domain = adaptedShadowType.getDomain();
Unit[] domain_units = ((RealTupleType) Domain.getType()).getDefaultUnits();
float[] constant_color = null;
// check that domain is only spatial
if (!Domain.getAllSpatial() || Domain.getMultipleDisplayScalar()) {
throw new BadMappingException("domain must be only spatial");
}
// check domain and determine whether it is square or curved texture
boolean isTextureMap = adaptedShadowType.getIsTextureMap() &&
(domain_set instanceof Linear2DSet ||
(domain_set instanceof LinearNDSet &&
domain_set.getDimension() == 2)) &&
(domain_set.getManifoldDimension() == 2);
boolean curvedTexture = adaptedShadowType.getCurvedTexture() &&
!isTextureMap &&
curved_size > 0 &&
(domain_set instanceof Gridded2DSet ||
(domain_set instanceof GriddedSet &&
domain_set.getDimension() == 2)) &&
(domain_set.getManifoldDimension() == 2);
if (group instanceof BranchGroup) {
((ImageRendererJ3D) renderer).setBranchEarly((BranchGroup) group);
}
first_time =true; //Ghansham: this variable just indicates to makeColorBytes whether it's the first tile of the image
boolean branch_added = false;
if (isTextureMap) { // linear texture
if (imgNode.getNumTiles() == 1) {
VisADImageTile tile = imgNode.getTile(0);
if (regen_colbytes) { //REUSE COLBYTES: regenerate only if required
makeColorBytesDriver(imgFlatField, cmap, cmaps, constant_alpha, RangeComponents, color_length, domain_length, permute,
data_width, data_height, imageType, tile, 0);
}
if (regen_geom) { //REUSE : REGEN GEOM regenerate the geometry
buildLinearTexture(bgImages, domain_set, dataUnits, domain_units, default_values, DomainComponents,
valueArrayLength, inherited_values, valueToScalar, mode, constant_alpha,
value_array, constant_color, display, tile);
} else { //REUSE Reuse the branch fully along with geometry. Just apply the colorbytes(Buffered Image)
BranchGroup Branch_L1 = (BranchGroup) bgImages.getChild(0);
Shape3D shape = (Shape3D) Branch_L1.getChild(0);
applyTexture(shape, tile, apply_alpha, constant_alpha);
}
}
else {
BranchGroup branch = null;
//if (!reuseImages || (regen_colbytes && regen_geom)) { //REUSE: Make a fresh branch
if (!reuseImages) {
branch = new BranchGroup();
branch.setCapability(BranchGroup.ALLOW_DETACH);
branch.setCapability(BranchGroup.ALLOW_CHILDREN_EXTEND);
branch.setCapability(BranchGroup.ALLOW_CHILDREN_READ);
branch.setCapability(BranchGroup.ALLOW_CHILDREN_WRITE);
} else { //REUSE the branch
branch = (BranchGroup) bgImages.getChild(0);
}
int branch_tile_indx = 0; //REUSE: to get the branch for a tile in case of multi-tile rendering
for (Iterator iter = imgNode.getTileIterator(); iter.hasNext();) {
VisADImageTile tile = (VisADImageTile) iter.next();
if (regen_colbytes) { //REUSE COLBYTES: regenerate only if required
makeColorBytesDriver(imgFlatField, cmap, cmaps, constant_alpha, RangeComponents, color_length, domain_length, permute,
data_width, data_height, imageType, tile, 0);
first_time = false; //Ghansham: setting 'first_time' variable false after the first tile has been generated
}
if (regen_geom) { //REUSE: Regenerate the geometry
float[][] g00 = ((GriddedSet)domain_set).gridToValue(
new float[][] {{tile.xStart}, {tile.yStart}});
float[][] g11 = ((GriddedSet)domain_set).gridToValue(
new float[][] {{tile.xStart+tile.width-1}, {tile.yStart+tile.height-1}});
double x0 = g00[0][0];
double x1 = g11[0][0];
double y0 = g00[1][0];
double y1 = g11[1][0];
Set dset = new Linear2DSet(x0, x1, tile.width, y0, y1, tile.height);
BranchGroup branch1 = null;
if (!reuseImages || (regen_colbytes && regen_geom)) { //REUSE: Make a fresh branch for each tile
branch1 = new BranchGroup();
branch1.setCapability(BranchGroup.ALLOW_DETACH);
branch1.setCapability(BranchGroup.ALLOW_CHILDREN_EXTEND);
branch1.setCapability(BranchGroup.ALLOW_CHILDREN_READ);
branch1.setCapability(BranchGroup.ALLOW_CHILDREN_WRITE);
} else { //REUSE: Reuse the already built branch for each tile
branch1 = (BranchGroup) branch.getChild(branch_tile_indx);
}
buildLinearTexture(branch1, dset, dataUnits, domain_units, default_values, DomainComponents,
valueArrayLength, inherited_values, valueToScalar, mode, constant_alpha,
value_array, constant_color, display, tile);
if (!reuseImages|| (regen_colbytes && regen_geom)) {
branch.addChild(branch1);
}
g00 = null;
g11 = null;
dset = null;
} else { //REUSE Reuse the branch fully along with geometry. Just apply the colorbytes(Buffered Image)
BranchGroup branch1 = (BranchGroup) branch.getChild(branch_tile_indx);
BranchGroup branch2 = (BranchGroup) branch1.getChild(0); //Beause we create a branch in textureToGroup
Shape3D shape = (Shape3D) branch2.getChild(0);
applyTexture(shape, tile, apply_alpha, constant_alpha);
}
if (0 == branch_tile_indx) { //Add the branch to get rendered as early as possible
if (!reuseImages || (regen_colbytes && regen_geom)) { //REUSE : Add a new branch if created
if (((Group) bgImages).numChildren() > 0) {
((Group) bgImages).setChild(branch, 0);
} else {
((Group) bgImages).addChild(branch);
}
}
}
branch_tile_indx++;
}
}
} // end if (isTextureMap)
else if (curvedTexture) {
int[] lens = ((GriddedSet)domain_set).getLengths();
int[] domain_lens = lens;
if (imgNode.getNumTiles() == 1) {
VisADImageTile tile = imgNode.getTile(0);
if (regen_colbytes) { //REUSE COLBYTES: regenerate only if required
makeColorBytesDriver(imgFlatField, cmap, cmaps, constant_alpha, RangeComponents, color_length, domain_length, permute,
data_width, data_height, imageType, tile, 0);
}
if (regen_geom) { //REUSE: REGEN GEOM regenerate
buildCurvedTexture(bgImages, domain_set, dataUnits, domain_units, default_values, DomainComponents,
valueArrayLength, inherited_values, valueToScalar, mode, constant_alpha,
value_array, constant_color, display, curved_size, Domain,
dataCoordinateSystem, renderer, adaptedShadowType, new int[] {0,0},
domain_lens[0], domain_lens[1], null, domain_lens[0], domain_lens[1], tile);
} else { //REUSE Reuse the branch fully along with geometry. Just apply the colorbytes(Buffered Image)
BranchGroup Branch_L1 = (BranchGroup) bgImages.getChild(0);
Shape3D shape = (Shape3D) Branch_L1.getChild(0);
applyTexture(shape, tile, apply_alpha, constant_alpha);
}
}
else
{
float[][] samples = ((GriddedSet)domain_set).getSamples(false);
BranchGroup branch = null;
if (!reuseImages || (regen_colbytes && regen_geom)) { //REUSE: Make a fresh branch
branch = new BranchGroup();
branch.setCapability(BranchGroup.ALLOW_DETACH);
branch.setCapability(BranchGroup.ALLOW_CHILDREN_EXTEND);
branch.setCapability(BranchGroup.ALLOW_CHILDREN_READ);
branch.setCapability(BranchGroup.ALLOW_CHILDREN_WRITE);
} else { //REUSE: Reuse already built branch
branch = (BranchGroup) bgImages.getChild(0);
}
int branch_tile_indx = 0; //REUSE: to get the branch for a tile in case of multi-tile rendering
for (Iterator iter = imgNode.getTileIterator(); iter.hasNext();) {
VisADImageTile tile = (VisADImageTile) iter.next();
if (regen_colbytes) { //REUSE COLBYTES: regenerate only if required
makeColorBytesDriver(imgFlatField, cmap, cmaps, constant_alpha, RangeComponents, color_length, domain_length, permute,
data_width, data_height, imageType, tile, 0);
first_time = false; //Ghansham: setting 'first_time' variable false after the first tile has been generated
}
if (regen_geom) { //REUSE REGEN GEOM regenerate geometry
BranchGroup branch1 = null;
if (!reuseImages || (regen_colbytes && regen_geom)) { //REUSE: Make a fresh branch group for each tile
branch1 = new BranchGroup();
branch1.setCapability(BranchGroup.ALLOW_DETACH);
branch1.setCapability(BranchGroup.ALLOW_CHILDREN_EXTEND);
branch1.setCapability(BranchGroup.ALLOW_CHILDREN_READ);
branch1.setCapability(BranchGroup.ALLOW_CHILDREN_WRITE);
} else { //REUSE: Reuse the already existing branch for each tile
branch1 = (BranchGroup) branch.getChild(branch_tile_indx);
}
buildCurvedTexture(branch1, null, dataUnits, domain_units, default_values, DomainComponents,
valueArrayLength, inherited_values, valueToScalar, mode, constant_alpha,
value_array, constant_color, display, curved_size, Domain,
dataCoordinateSystem, renderer, adaptedShadowType,
new int[] {tile.xStart,tile.yStart}, tile.width, tile.height,
samples, domain_lens[0], domain_lens[1], tile);
if (!reuseImages || (regen_colbytes && regen_geom)) { //REUSE: Add newly created branch
branch.addChild(branch1);
}
} else { //REUSE Reuse the branch fully along with geometry. Just apply the colorbytes(Buffered Image)
BranchGroup branch1 = (BranchGroup) branch.getChild(branch_tile_indx);
BranchGroup branch2 = (BranchGroup) branch1.getChild(0);
Shape3D shape = (Shape3D) branch2.getChild(0);
applyTexture(shape, tile, apply_alpha, constant_alpha);
}
if (0 == branch_tile_indx) { //Add the branch to get rendered as early as possible
if (!reuseImages || (regen_colbytes && regen_geom)) { //REUSE : Add a new branch if created
if (((Group) bgImages).numChildren() > 0) {
((Group) bgImages).setChild(branch, 0);
} else {
((Group) bgImages).addChild(branch);
}
}
}
branch_tile_indx++;
}
}
} // end if (curvedTexture)
else { // !isTextureMap && !curvedTexture
throw new BadMappingException("must be texture map or curved texture map");
}
// make sure group is live. group not empty (above addChild)
/*if (group instanceof BranchGroup) {
((ImageRendererJ3D) renderer).setBranchEarly((BranchGroup) group);
}*/
| public boolean doTransform(Object group, Data data, float[] value_array,
float[] default_values, DataRenderer renderer)
throws VisADException, RemoteException {
DataDisplayLink link = renderer.getLink();
// return if data is missing or no ScalarMaps
if (data.isMissing()) {
((ImageRendererJ3D) renderer).markMissingVisADBranch();
return false;
}
if (levelOfDifficulty == -1) {
levelOfDifficulty = getLevelOfDifficulty();
}
if (levelOfDifficulty == NOTHING_MAPPED) return false;
if (group instanceof BranchGroup && ((BranchGroup) group).numChildren() > 0) {
Node g = ((BranchGroup) group).getChild(0);
// WLH 06 Feb 06 - support switch in a branch group.
if (g instanceof BranchGroup && ((BranchGroup) g).numChildren() > 0) {
reuseImages = true;
}
}
DisplayImpl display = getDisplay();
int cMapCurveSize = (int) default_values[display.getDisplayScalarIndex(Display.CurvedSize)];
int curved_size = (cMapCurveSize > 0) ? cMapCurveSize : display.getGraphicsModeControl().getCurvedSize();
// length of ValueArray
int valueArrayLength = display.getValueArrayLength();
// mapping from ValueArray to DisplayScalar
int[] valueToScalar = display.getValueToScalar();
//GHANSHAM:30AUG2011 Restrutured the code to extract the constant_alpha, cmap, cmaps and ShadowFunctionType so that they can be passed to initRegenFlags method
if (adaptedShadowType == null) {
adaptedShadowType = (ShadowFunctionOrSetType) getAdaptedShadowType();
}
boolean anyContour = adaptedShadowType.getAnyContour();
boolean anyFlow = adaptedShadowType.getAnyFlow();
boolean anyShape = adaptedShadowType.getAnyShape();
boolean anyText = adaptedShadowType.getAnyText();
if (anyContour || anyFlow || anyShape || anyText) {
throw new BadMappingException("no contour, flow, shape or text allowed");
}
FlatField imgFlatField = null;
Set domain_set = ((Field) data).getDomainSet();
ShadowRealType[] DomainComponents = adaptedShadowType.getDomainComponents();
int numImages = 1;
if (!adaptedShadowType.getIsTerminal()) {
Vector domain_maps = DomainComponents[0].getSelectedMapVector();
ScalarMap amap = null;
if (domain_set.getDimension() == 1 && domain_maps.size() == 1) {
ScalarMap map = (ScalarMap) domain_maps.elementAt(0);
if (Display.Animation.equals(map.getDisplayScalar())) {
amap = map;
}
}
if (amap == null) {
throw new BadMappingException("time must be mapped to Animation");
}
animControl = (AnimationControlJ3D) amap.getControl();
numImages = domain_set.getLength();
adaptedShadowType = (ShadowFunctionOrSetType) adaptedShadowType.getRange();
DomainComponents = adaptedShadowType.getDomainComponents();
imgFlatField = (FlatField) ((FieldImpl)data).getSample(0);
} else {
imgFlatField = (FlatField)data;
}
// check that range is single RealType mapped to RGB only
ShadowRealType[] RangeComponents = adaptedShadowType.getRangeComponents();
int rangesize = RangeComponents.length;
if (rangesize != 1 && rangesize != 3) {
throw new BadMappingException("image values must single or triple");
}
ScalarMap cmap = null;
ScalarMap[] cmaps = null;
int[] permute = {-1, -1, -1};
boolean hasAlpha = false;
if (rangesize == 1) {
Vector mvector = RangeComponents[0].getSelectedMapVector();
if (mvector.size() != 1) {
throw new BadMappingException("image values must be mapped to RGB only");
}
cmap = (ScalarMap) mvector.elementAt(0);
if (Display.RGB.equals(cmap.getDisplayScalar())) {
} else if (Display.RGBA.equals(cmap.getDisplayScalar())) {
hasAlpha = true;
} else {
throw new BadMappingException("image values must be mapped to RGB or RGBA");
}
} else {
cmaps = new ScalarMap[3];
for (int i=0; i<3; i++) {
Vector mvector = RangeComponents[i].getSelectedMapVector();
if (mvector.size() != 1) {
throw new BadMappingException("image values must be mapped to color only");
}
cmaps[i] = (ScalarMap) mvector.elementAt(0);
if (Display.Red.equals(cmaps[i].getDisplayScalar())) {
permute[0] = i;
} else if (Display.Green.equals(cmaps[i].getDisplayScalar())) {
permute[1] = i;
} else if (Display.Blue.equals(cmaps[i].getDisplayScalar())) {
permute[2] = i;
} else if (Display.RGB.equals(cmaps[i].getDisplayScalar())) { //Inserted by Ghansham for Mapping all the three scalarMaps to Display.RGB (starts here)
permute[i] = i;
} else { ////Inserted by Ghansham for Mapping all the three scalarMaps to Display.RGB(ends here)
throw new BadMappingException("image values must be mapped to Red, Green or Blue only");
}
}
if (permute[0] < 0 || permute[1] < 0 || permute[2] < 0) {
throw new BadMappingException("image values must be mapped to Red, Green or Blue only");
}
//Inserted by Ghansham for Checking that all should be mapped to Display.RGB or not even a single one should be mapped to Display.RGB(starts here)
//This is to check if there is a single Display.RGB ScalarMap
int indx = -1;
for (int i = 0; i < 3; i++) {
if (cmaps[i].getDisplayScalar().equals(Display.RGB)) {
indx = i;
break;
}
}
if (indx != -1){ //if there is a even a single Display.RGB ScalarMap, others must also Display.RGB only
for (int i = 0; i < 3; i++) {
if (i !=indx && !(cmaps[i].getDisplayScalar().equals(Display.RGB))) {
throw new BadMappingException("image values must be mapped to (Red, Green, Blue) or (RGB,RGB,RGB) only");
}
}
}
//Inserted by Ghansham for Checking that all should be mapped to Display.RGB or not even a single one should be mapped to Display.RGB(Ends here)
}
float constant_alpha = default_values[display.getDisplayScalarIndex(Display.Alpha)];
int color_length;
ImageRendererJ3D imgRenderer = (ImageRendererJ3D) renderer;
int imageType = imgRenderer.getSuggestedBufImageType();
if (imageType == BufferedImage.TYPE_4BYTE_ABGR) {
color_length = 4;
if (!hasAlpha) {
color_length = 3;
imageType = BufferedImage.TYPE_3BYTE_BGR;
}
} else if (imageType == BufferedImage.TYPE_3BYTE_BGR) {
color_length = 3;
} else if (imageType == BufferedImage.TYPE_USHORT_GRAY) {
color_length = 2;
} else if (imageType == BufferedImage.TYPE_BYTE_GRAY) {
color_length = 1;
} else {
// we shouldn't ever get here because the renderer validates the
// imageType before we get it, but just in case...
throw new VisADException("renderer returned unsupported image type");
}
if (color_length == 4) constant_alpha = Float.NaN; // WLH 6 May 2003
//REUSE GEOMETRY/COLORBYTE LOGIC (STARTS HERE)
regen_colbytes = false;
regen_geom = false;
apply_alpha = false;
initRegenFlags((ImageRendererJ3D)renderer, adaptedShadowType, constant_alpha, cmap, cmaps, data, display, default_values, value_array, valueToScalar, valueArrayLength, link, curved_size);
if(!reuseImages) {
regen_geom = true;
regen_colbytes = true;
apply_alpha = true;
}
/**
System.err.println("Regenerate Color Bytes:" + regen_colbytes);
System.err.println("Regenerate Geometry:" + regen_geom);
System.err.println("Apply Alpha:" + apply_alpha);
System.err.println("ReuseImages:" + reuseImages);
*/
//REUSE GEOMETRY/COLORBYTE LOGIC (ENDS HERE)
prevImgNode = ((ImageRendererJ3D)renderer).getImageNode();
BranchGroup bgImages = null;
/*REUSE GEOM/COLBYTE: Replaced reuse with reuseImages. Earlier else part of this decision was never being used.
The reason was reuse was always set to false. Compare with your version.
Added one extra line in the else part where I extract the bgImages from the switch.
Now else part occurs when either reuse_colbytes or regen_geom is true.
But when regen_colbytes and regen_geom both are true, then I assume that a new flatfield is set so
go with the if part.
*/
if (!reuseImages || (regen_colbytes && regen_geom)) { //REUSE GEOM/COLBYTE:Earlier reuse variable was used. Replaced it with reuseImages.
//Added regen_colbytes and regen_geom.
//This is used when either its first time or full new data has been with different dims.
BranchGroup branch = new BranchGroup();
branch.setCapability(BranchGroup.ALLOW_DETACH);
branch.setCapability(BranchGroup.ALLOW_CHILDREN_EXTEND);
branch.setCapability(BranchGroup.ALLOW_CHILDREN_READ);
branch.setCapability(BranchGroup.ALLOW_CHILDREN_WRITE);
Switch swit = (Switch) makeSwitch();
imgNode = new VisADImageNode();
bgImages = new BranchGroup();
bgImages.setCapability(BranchGroup.ALLOW_DETACH);
bgImages.setCapability(BranchGroup.ALLOW_CHILDREN_EXTEND);
bgImages.setCapability(BranchGroup.ALLOW_CHILDREN_READ);
bgImages.setCapability(BranchGroup.ALLOW_CHILDREN_WRITE);
swit.addChild(bgImages);
swit.setWhichChild(0);
branch.addChild(swit);
imgNode.setBranch(branch);
imgNode.setSwitch(swit);
((ImageRendererJ3D)renderer).setImageNode(imgNode);
if ( ((BranchGroup) group).numChildren() > 0 ) {
((BranchGroup)group).setChild(branch, 0);
} else {
((BranchGroup)group).addChild(branch);
/*
// make sure group is live. group not empty (above addChild)
if (group instanceof BranchGroup) {
((ImageRendererJ3D) renderer).setBranchEarly((BranchGroup) group);
}
*/
}
} else { //REUSE GEOM/COLBYTE: If its not the first time. And the dims have not changed but either color bytes or geometry has changed.
imgNode = ((ImageRendererJ3D)renderer).getImageNode();
bgImages = (BranchGroup) imgNode.getSwitch().getChild(0); //REUSE GEOM/COLBYTE:Extract the bgImages from the avaialable switch
}
GraphicsModeControl mode = (GraphicsModeControl)
display.getGraphicsModeControl().clone();
// get some precomputed values useful for transform
// mapping from ValueArray to MapVector
int[] valueToMap = display.getValueToMap();
Vector MapVector = display.getMapVector();
Unit[] dataUnits = null;
CoordinateSystem dataCoordinateSystem = null;
if (animControl != null) {
Switch swit = new SwitchNotify(imgNode, numImages);
((AVControlJ3D) animControl).addPair((Switch) swit, domain_set, renderer);
((AVControlJ3D) animControl).init();
}
domain_set = imgFlatField.getDomainSet();
dataUnits = ((Function) imgFlatField).getDomainUnits();
dataCoordinateSystem =
((Function) imgFlatField).getDomainCoordinateSystem();
int domain_length = domain_set.getLength();
int[] lengths = ((GriddedSet) domain_set).getLengths();
int data_width = lengths[0];
int data_height = lengths[1];
imgNode.numImages = numImages;
imgNode.data_width = data_width;
imgNode.data_height = data_height;
int texture_width_max = link.getDisplay().getDisplayRenderer().getTextureWidthMax();
int texture_height_max = link.getDisplay().getDisplayRenderer().getTextureWidthMax();
int texture_width = textureWidth(data_width);
int texture_height = textureHeight(data_height);
if (reuseImages) {
if (prevImgNode.numImages != numImages ||
prevImgNode.data_width != data_width || prevImgNode.data_height != data_height) {
reuseImages = false;
}
}
if (reuseImages) {
imgNode.numChildren = prevImgNode.numChildren;
imgNode.imageTiles = prevImgNode.imageTiles;
}
else {
Mosaic mosaic = new Mosaic(data_height, texture_height_max, data_width, texture_width_max);
for (Iterator iter = mosaic.iterator(); iter.hasNext();) {
Tile tile = (Tile) iter.next();
imgNode.addTile(new VisADImageTile(numImages, tile.height, tile.y_start, tile.width, tile.x_start));
}
}
prevImgNode = imgNode;
ShadowRealTupleType Domain = adaptedShadowType.getDomain();
Unit[] domain_units = ((RealTupleType) Domain.getType()).getDefaultUnits();
float[] constant_color = null;
// check that domain is only spatial
if (!Domain.getAllSpatial() || Domain.getMultipleDisplayScalar()) {
throw new BadMappingException("domain must be only spatial");
}
// check domain and determine whether it is square or curved texture
boolean isTextureMap = adaptedShadowType.getIsTextureMap() &&
(domain_set instanceof Linear2DSet ||
(domain_set instanceof LinearNDSet &&
domain_set.getDimension() == 2)) &&
(domain_set.getManifoldDimension() == 2);
boolean curvedTexture = adaptedShadowType.getCurvedTexture() &&
!isTextureMap &&
curved_size > 0 &&
(domain_set instanceof Gridded2DSet ||
(domain_set instanceof GriddedSet &&
domain_set.getDimension() == 2)) &&
(domain_set.getManifoldDimension() == 2);
if (group instanceof BranchGroup) {
((ImageRendererJ3D) renderer).setBranchEarly((BranchGroup) group);
}
first_time =true; //Ghansham: this variable just indicates to makeColorBytes whether it's the first tile of the image
boolean branch_added = false;
if (isTextureMap) { // linear texture
if (imgNode.getNumTiles() == 1) {
VisADImageTile tile = imgNode.getTile(0);
if (regen_colbytes) { //REUSE COLBYTES: regenerate only if required
makeColorBytesDriver(imgFlatField, cmap, cmaps, constant_alpha, RangeComponents, color_length, domain_length, permute,
data_width, data_height, imageType, tile, 0);
}
if (regen_geom) { //REUSE : REGEN GEOM regenerate the geometry
buildLinearTexture(bgImages, domain_set, dataUnits, domain_units, default_values, DomainComponents,
valueArrayLength, inherited_values, valueToScalar, mode, constant_alpha,
value_array, constant_color, display, tile);
} else { //REUSE Reuse the branch fully along with geometry. Just apply the colorbytes(Buffered Image)
BranchGroup Branch_L1 = (BranchGroup) bgImages.getChild(0);
Shape3D shape = (Shape3D) Branch_L1.getChild(0);
applyTexture(shape, tile, apply_alpha, constant_alpha);
}
}
else {
BranchGroup branch = null;
//if (!reuseImages || (regen_colbytes && regen_geom)) { //REUSE: Make a fresh branch
if (!reuseImages) {
branch = new BranchGroup();
branch.setCapability(BranchGroup.ALLOW_DETACH);
branch.setCapability(BranchGroup.ALLOW_CHILDREN_EXTEND);
branch.setCapability(BranchGroup.ALLOW_CHILDREN_READ);
branch.setCapability(BranchGroup.ALLOW_CHILDREN_WRITE);
} else { //REUSE the branch
branch = (BranchGroup) bgImages.getChild(0);
}
int branch_tile_indx = 0; //REUSE: to get the branch for a tile in case of multi-tile rendering
for (Iterator iter = imgNode.getTileIterator(); iter.hasNext();) {
VisADImageTile tile = (VisADImageTile) iter.next();
if (regen_colbytes) { //REUSE COLBYTES: regenerate only if required
makeColorBytesDriver(imgFlatField, cmap, cmaps, constant_alpha, RangeComponents, color_length, domain_length, permute,
data_width, data_height, imageType, tile, 0);
first_time = false; //Ghansham: setting 'first_time' variable false after the first tile has been generated
}
if (regen_geom) { //REUSE: Regenerate the geometry
float[][] g00 = ((GriddedSet)domain_set).gridToValue(
new float[][] {{tile.xStart}, {tile.yStart}});
float[][] g11 = ((GriddedSet)domain_set).gridToValue(
new float[][] {{tile.xStart+tile.width-1}, {tile.yStart+tile.height-1}});
double x0 = g00[0][0];
double x1 = g11[0][0];
double y0 = g00[1][0];
double y1 = g11[1][0];
Set dset = new Linear2DSet(x0, x1, tile.width, y0, y1, tile.height);
BranchGroup branch1 = null;
if (!reuseImages || (regen_colbytes && regen_geom)) { //REUSE: Make a fresh branch for each tile
branch1 = new BranchGroup();
branch1.setCapability(BranchGroup.ALLOW_DETACH);
branch1.setCapability(BranchGroup.ALLOW_CHILDREN_EXTEND);
branch1.setCapability(BranchGroup.ALLOW_CHILDREN_READ);
branch1.setCapability(BranchGroup.ALLOW_CHILDREN_WRITE);
} else { //REUSE: Reuse the already built branch for each tile
branch1 = (BranchGroup) branch.getChild(branch_tile_indx);
}
buildLinearTexture(branch1, dset, dataUnits, domain_units, default_values, DomainComponents,
valueArrayLength, inherited_values, valueToScalar, mode, constant_alpha,
value_array, constant_color, display, tile);
if (!reuseImages|| (regen_colbytes && regen_geom)) {
branch.addChild(branch1);
}
g00 = null;
g11 = null;
dset = null;
} else { //REUSE Reuse the branch fully along with geometry. Just apply the colorbytes(Buffered Image)
BranchGroup branch1 = (BranchGroup) branch.getChild(branch_tile_indx);
BranchGroup branch2 = (BranchGroup) branch1.getChild(0); //Beause we create a branch in textureToGroup
Shape3D shape = (Shape3D) branch2.getChild(0);
applyTexture(shape, tile, apply_alpha, constant_alpha);
}
if (0 == branch_tile_indx) { //Add the branch to get rendered as early as possible
if (!reuseImages || (regen_colbytes && regen_geom)) { //REUSE : Add a new branch if created
if (((Group) bgImages).numChildren() > 0) {
((Group) bgImages).setChild(branch, 0);
} else {
((Group) bgImages).addChild(branch);
}
}
}
branch_tile_indx++;
}
}
} // end if (isTextureMap)
else if (curvedTexture) {
int[] lens = ((GriddedSet)domain_set).getLengths();
int[] domain_lens = lens;
if (imgNode.getNumTiles() == 1) {
VisADImageTile tile = imgNode.getTile(0);
if (regen_colbytes) { //REUSE COLBYTES: regenerate only if required
makeColorBytesDriver(imgFlatField, cmap, cmaps, constant_alpha, RangeComponents, color_length, domain_length, permute,
data_width, data_height, imageType, tile, 0);
}
if (regen_geom) { //REUSE: REGEN GEOM regenerate
buildCurvedTexture(bgImages, domain_set, dataUnits, domain_units, default_values, DomainComponents,
valueArrayLength, inherited_values, valueToScalar, mode, constant_alpha,
value_array, constant_color, display, curved_size, Domain,
dataCoordinateSystem, renderer, adaptedShadowType, new int[] {0,0},
domain_lens[0], domain_lens[1], null, domain_lens[0], domain_lens[1], tile);
} else { //REUSE Reuse the branch fully along with geometry. Just apply the colorbytes(Buffered Image)
BranchGroup Branch_L1 = (BranchGroup) bgImages.getChild(0);
Shape3D shape = (Shape3D) Branch_L1.getChild(0);
applyTexture(shape, tile, apply_alpha, constant_alpha);
}
}
else
{
float[][] samples = ((GriddedSet)domain_set).getSamples(false);
BranchGroup branch = null;
if (!reuseImages || (regen_colbytes && regen_geom)) { //REUSE: Make a fresh branch
branch = new BranchGroup();
branch.setCapability(BranchGroup.ALLOW_DETACH);
branch.setCapability(BranchGroup.ALLOW_CHILDREN_EXTEND);
branch.setCapability(BranchGroup.ALLOW_CHILDREN_READ);
branch.setCapability(BranchGroup.ALLOW_CHILDREN_WRITE);
} else { //REUSE: Reuse already built branch
branch = (BranchGroup) bgImages.getChild(0);
}
int branch_tile_indx = 0; //REUSE: to get the branch for a tile in case of multi-tile rendering
for (Iterator iter = imgNode.getTileIterator(); iter.hasNext();) {
VisADImageTile tile = (VisADImageTile) iter.next();
if (regen_colbytes) { //REUSE COLBYTES: regenerate only if required
makeColorBytesDriver(imgFlatField, cmap, cmaps, constant_alpha, RangeComponents, color_length, domain_length, permute,
data_width, data_height, imageType, tile, 0);
first_time = false; //Ghansham: setting 'first_time' variable false after the first tile has been generated
}
if (regen_geom) { //REUSE REGEN GEOM regenerate geometry
BranchGroup branch1 = null;
if (!reuseImages || (regen_colbytes && regen_geom)) { //REUSE: Make a fresh branch group for each tile
branch1 = new BranchGroup();
branch1.setCapability(BranchGroup.ALLOW_DETACH);
branch1.setCapability(BranchGroup.ALLOW_CHILDREN_EXTEND);
branch1.setCapability(BranchGroup.ALLOW_CHILDREN_READ);
branch1.setCapability(BranchGroup.ALLOW_CHILDREN_WRITE);
} else { //REUSE: Reuse the already existing branch for each tile
branch1 = (BranchGroup) branch.getChild(branch_tile_indx);
}
buildCurvedTexture(branch1, null, dataUnits, domain_units, default_values, DomainComponents,
valueArrayLength, inherited_values, valueToScalar, mode, constant_alpha,
value_array, constant_color, display, curved_size, Domain,
dataCoordinateSystem, renderer, adaptedShadowType,
new int[] {tile.xStart,tile.yStart}, tile.width, tile.height,
samples, domain_lens[0], domain_lens[1], tile);
if (!reuseImages || (regen_colbytes && regen_geom)) { //REUSE: Add newly created branch
branch.addChild(branch1);
}
} else { //REUSE Reuse the branch fully along with geometry. Just apply the colorbytes(Buffered Image)
BranchGroup branch1 = (BranchGroup) branch.getChild(branch_tile_indx);
BranchGroup branch2 = (BranchGroup) branch1.getChild(0);
Shape3D shape = (Shape3D) branch2.getChild(0);
applyTexture(shape, tile, apply_alpha, constant_alpha);
}
if (0 == branch_tile_indx) { //Add the branch to get rendered as early as possible
if (!reuseImages || (regen_colbytes && regen_geom)) { //REUSE : Add a new branch if created
if (((Group) bgImages).numChildren() > 0) {
((Group) bgImages).setChild(branch, 0);
} else {
((Group) bgImages).addChild(branch);
}
}
}
branch_tile_indx++;
}
}
} // end if (curvedTexture)
else { // !isTextureMap && !curvedTexture
throw new BadMappingException("must be texture map or curved texture map");
}
// make sure group is live. group not empty (above addChild)
/*if (group instanceof BranchGroup) {
((ImageRendererJ3D) renderer).setBranchEarly((BranchGroup) group);
}*/
|
diff --git a/source/de/anomic/http/httpdFileHandler.java b/source/de/anomic/http/httpdFileHandler.java
index 03716ddc4..38f8cb078 100644
--- a/source/de/anomic/http/httpdFileHandler.java
+++ b/source/de/anomic/http/httpdFileHandler.java
@@ -1,1019 +1,1026 @@
// httpdFileHandler.java
// -----------------------
// (C) by Michael Peter Christen; [email protected]
// first published on http://www.anomic.de
// Frankfurt, Germany, 2004, 2005
// last major change: 05.10.2005
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
/*
Class documentation:
this class provides a file servlet and CGI interface
for the httpd server.
Whenever this server is addressed to load a local file,
this class searches for the file in the local path as
configured in the setting property 'rootPath'
The servlet loads the file and returns it to the client.
Every file can also act as an template for the built-in
CGI interface. There is no specific path for CGI functions.
CGI functionality is triggered, if for the file to-be-served
'template.html' also a file 'template.class' exists. Then,
the class file is called with the GET/POST properties that
are attached to the http call.
Possible variable hand-over are:
- form method GET
- form method POST, enctype text/plain
- form method POST, enctype multipart/form-data
The class that creates the CGI respond must have at least one
static method of the form
public static java.util.Hashtable respond(java.util.HashMap, serverSwitch)
In the HashMap, the GET/POST variables are handed over.
The return value is a Property object that contains replacement
key/value pairs for the patterns in the template file.
The templates must have the form
either '#['<name>']#' for single attributes, or
'#{'<enumname>'}#' and '#{/'<enumname>'}#' for enumerations of
values '#['<value>']#'.
A single value in repetitions/enumerations in the template has
the property key '_'<enumname><count>'_'<value>
Please see also the example files 'test.html' and 'test.java'
*/
package de.anomic.http;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.lang.ref.SoftReference;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URLDecoder;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import java.util.zip.GZIPOutputStream;
import de.anomic.htmlFilter.htmlFilterContentScraper;
import de.anomic.htmlFilter.htmlFilterInputStream;
import de.anomic.plasma.plasmaParser;
import de.anomic.plasma.plasmaSwitchboard;
import de.anomic.plasma.plasmaSwitchboardConstants;
import de.anomic.server.serverByteBuffer;
import de.anomic.server.serverClassLoader;
import de.anomic.server.serverCore;
import de.anomic.server.serverDate;
import de.anomic.server.serverFileUtils;
import de.anomic.server.serverObjects;
import de.anomic.server.serverSwitch;
import de.anomic.server.servletProperties;
import de.anomic.server.logging.serverLog;
import de.anomic.yacy.yacyURL;
import de.anomic.ymage.ymageMatrix;
public final class httpdFileHandler {
private static final boolean safeServletsMode = false; // if true then all servlets are called synchronized
private static final Properties mimeTable = new Properties();
// create a class loader
private static final serverClassLoader provider = new serverClassLoader(/*this.getClass().getClassLoader()*/);
private static serverSwitch<?> switchboard = null;
private static plasmaSwitchboard sb = plasmaSwitchboard.getSwitchboard();
private static File htRootPath = null;
private static File htDocsPath = null;
private static File htTemplatePath = null;
private static String[] defaultFiles = null;
private static File htDefaultPath = null;
private static File htLocalePath = null;
private static final HashMap<File, SoftReference<byte[]>> templateCache;
private static final HashMap<File, SoftReference<Method>> templateMethodCache;
public static final boolean useTemplateCache;
//private Properties connectionProperties = null;
// creating a logger
private static final serverLog theLogger = new serverLog("FILEHANDLER");
static {
final serverSwitch<?> theSwitchboard = plasmaSwitchboard.getSwitchboard();
useTemplateCache = theSwitchboard.getConfig("enableTemplateCache","true").equalsIgnoreCase("true");
templateCache = (useTemplateCache)? new HashMap<File, SoftReference<byte[]>>() : new HashMap<File, SoftReference<byte[]>>(0);
templateMethodCache = (useTemplateCache) ? new HashMap<File, SoftReference<Method>>() : new HashMap<File, SoftReference<Method>>(0);
if (httpdFileHandler.switchboard == null) {
httpdFileHandler.switchboard = theSwitchboard;
if (mimeTable.size() == 0) {
// load the mime table
final String mimeTablePath = theSwitchboard.getConfig("mimeConfig","");
BufferedInputStream mimeTableInputStream = null;
try {
serverLog.logConfig("HTTPDFiles", "Loading mime mapping file " + mimeTablePath);
mimeTableInputStream = new BufferedInputStream(new FileInputStream(new File(theSwitchboard.getRootPath(), mimeTablePath)));
mimeTable.load(mimeTableInputStream);
} catch (final Exception e) {
serverLog.logSevere("HTTPDFiles", "ERROR: path to configuration file or configuration invalid\n" + e);
System.exit(1);
} finally {
if (mimeTableInputStream != null) try { mimeTableInputStream.close(); } catch (final Exception e1) {}
}
}
// create default files array
initDefaultPath();
// create a htRootPath: system pages
if (htRootPath == null) {
htRootPath = new File(theSwitchboard.getRootPath(), theSwitchboard.getConfig(plasmaSwitchboardConstants.HTROOT_PATH, plasmaSwitchboardConstants.HTROOT_PATH_DEFAULT));
if (!(htRootPath.exists())) htRootPath.mkdir();
}
// create a htDocsPath: user defined pages
if (htDocsPath == null) {
htDocsPath = theSwitchboard.getConfigPath(plasmaSwitchboardConstants.HTDOCS_PATH, plasmaSwitchboardConstants.HTDOCS_PATH_DEFAULT);
if (!(htDocsPath.exists())) htDocsPath.mkdirs();
}
// create a repository path
final File repository = new File(htDocsPath, "repository");
if (!repository.exists()) repository.mkdirs();
// create a htTemplatePath
if (htTemplatePath == null) {
htTemplatePath = theSwitchboard.getConfigPath("htTemplatePath","htroot/env/templates");
if (!(htTemplatePath.exists())) htTemplatePath.mkdir();
}
//This is now handles by #%env/templates/foo%#
//if (templates.size() == 0) templates.putAll(httpTemplate.loadTemplates(htTemplatePath));
// create htLocaleDefault, htLocalePath
if (htDefaultPath == null) htDefaultPath = theSwitchboard.getConfigPath("htDefaultPath", "htroot");
if (htLocalePath == null) htLocalePath = theSwitchboard.getConfigPath("locale.translated_html", "DATA/LOCALE/htroot");
}
}
public static final void initDefaultPath() {
// create default files array
defaultFiles = switchboard.getConfig("defaultFiles","index.html").split(",");
if (defaultFiles.length == 0) defaultFiles = new String[] {"index.html"};
}
/** Returns a path to the localized or default file according to the locale.language (from he switchboard)
* @param path relative from htroot */
public static File getLocalizedFile(final String path){
return getLocalizedFile(path, switchboard.getConfig("locale.language","default"));
}
/** Returns a path to the localized or default file according to the parameter localeSelection
* @param path relative from htroot
* @param localeSelection language of localized file; locale.language from switchboard is used if localeSelection.equals("") */
public static File getLocalizedFile(final String path, final String localeSelection){
if (htDefaultPath == null) htDefaultPath = switchboard.getConfigPath("htDefaultPath","htroot");
if (htLocalePath == null) htLocalePath = switchboard.getConfigPath("locale.translated_html","DATA/LOCALE/htroot");
if (!(localeSelection.equals("default"))) {
final File localePath = new File(htLocalePath, localeSelection + '/' + path);
if (localePath.exists()) // avoid "NoSuchFile" troubles if the "localeSelection" is misspelled
return localePath;
}
return new File(htDefaultPath, path);
}
// private void textMessage(OutputStream out, int retcode, String body) throws IOException {
// httpd.sendRespondHeader(
// this.connectionProperties, // the connection properties
// out, // the output stream
// "HTTP/1.1", // the http version that should be used
// retcode, // the http status code
// null, // the http status message
// "text/plain", // the mimetype
// body.length(), // the content length
// httpc.nowDate(), // the modification date
// null, // the expires date
// null, // cookies
// null, // content encoding
// null); // transfer encoding
// out.write(body.getBytes());
// out.flush();
// }
private static final httpResponseHeader getDefaultHeaders(final String path) {
final httpResponseHeader headers = new httpResponseHeader();
String ext;
int pos;
if ((pos = path.lastIndexOf('.')) < 0) {
ext = "";
} else {
ext = path.substring(pos + 1).toLowerCase();
}
headers.put(httpResponseHeader.SERVER, "AnomicHTTPD (www.anomic.de)");
headers.put(httpResponseHeader.DATE, HttpClient.dateString(new Date()));
if(!(plasmaParser.mediaExtContains(ext))){
headers.put(httpResponseHeader.PRAGMA, "no-cache");
}
return headers;
}
public static void doGet(final Properties conProp, final httpRequestHeader requestHeader, final OutputStream response) {
doResponse(conProp, requestHeader, response, null);
}
public static void doHead(final Properties conProp, final httpRequestHeader requestHeader, final OutputStream response) {
doResponse(conProp, requestHeader, response, null);
}
public static void doPost(final Properties conProp, final httpRequestHeader requestHeader, final OutputStream response, final InputStream body) {
doResponse(conProp, requestHeader, response, body);
}
public static void doResponse(final Properties conProp, final httpRequestHeader requestHeader, final OutputStream out, final InputStream body) {
String path = null;
try {
// getting some connection properties
final String method = conProp.getProperty(httpHeader.CONNECTION_PROP_METHOD);
path = conProp.getProperty(httpHeader.CONNECTION_PROP_PATH);
String argsString = conProp.getProperty(httpHeader.CONNECTION_PROP_ARGS); // is null if no args were given
final String httpVersion = conProp.getProperty(httpHeader.CONNECTION_PROP_HTTP_VER);
final String clientIP = conProp.getProperty(httpHeader.CONNECTION_PROP_CLIENTIP, "unknown-host");
// check hack attacks in path
if (path.indexOf("..") >= 0) {
httpd.sendRespondError(conProp,out,4,403,null,"Access not allowed",null);
return;
}
// url decoding of path
try {
path = URLDecoder.decode(path, "UTF-8");
} catch (final UnsupportedEncodingException e) {
// This should never occur
assert(false) : "UnsupportedEncodingException: " + e.getMessage();
}
// check again hack attacks in path
if (path.indexOf("..") >= 0) {
httpd.sendRespondError(conProp,out,4,403,null,"Access not allowed",null);
return;
}
// check permission/granted access
String authorization = requestHeader.get(httpRequestHeader.AUTHORIZATION);
if (authorization != null && authorization.length() == 0) authorization = null;
final String adminAccountBase64MD5 = switchboard.getConfig(httpd.ADMIN_ACCOUNT_B64MD5, "");
int pos = path.lastIndexOf(".");
final boolean adminAccountForLocalhost = sb.getConfigBool("adminAccountForLocalhost", false);
final String refererHost = requestHeader.refererHost();
final boolean accessFromLocalhost = serverCore.isLocalhost(clientIP) && (refererHost.length() == 0 || serverCore.isLocalhost(refererHost));
final boolean grantedForLocalhost = adminAccountForLocalhost && accessFromLocalhost;
final boolean protectedPage = (path.substring(0,(pos==-1)?path.length():pos)).endsWith("_p");
final boolean accountEmpty = adminAccountBase64MD5.length() == 0;
if (!grantedForLocalhost && protectedPage && !accountEmpty) {
// authentication required
if (authorization == null) {
// no authorization given in response. Ask for that
final httpResponseHeader responseHeader = getDefaultHeaders(path);
responseHeader.put(httpRequestHeader.WWW_AUTHENTICATE,"Basic realm=\"admin log-in\"");
//httpd.sendRespondHeader(conProp,out,httpVersion,401,headers);
final servletProperties tp=new servletProperties();
tp.put("returnto", path);
//TODO: separate error page Wrong Login / No Login
httpd.sendRespondError(conProp, out, 5, 401, "Wrong Authentication", "", new File("proxymsg/authfail.inc"), tp, null, responseHeader);
return;
} else if (
(httpd.staticAdminAuthenticated(authorization.trim().substring(6), switchboard) == 4) ||
(sb.userDB.hasAdminRight(authorization, conProp.getProperty(httpHeader.CONNECTION_PROP_CLIENTIP), requestHeader.getHeaderCookies()))) {
//Authentication successful. remove brute-force flag
serverCore.bfHost.remove(conProp.getProperty(httpHeader.CONNECTION_PROP_CLIENTIP));
} else {
// a wrong authentication was given or the userDB user does not have admin access. Ask again
serverLog.logInfo("HTTPD", "Wrong log-in for account 'admin' in http file handler for path '" + path + "' from host '" + clientIP + "'");
final Integer attempts = serverCore.bfHost.get(clientIP);
if (attempts == null)
serverCore.bfHost.put(clientIP, Integer.valueOf(1));
else
serverCore.bfHost.put(clientIP, Integer.valueOf(attempts.intValue() + 1));
final httpResponseHeader headers = getDefaultHeaders(path);
headers.put(httpRequestHeader.WWW_AUTHENTICATE,"Basic realm=\"admin log-in\"");
httpd.sendRespondHeader(conProp,out,httpVersion,401,headers);
return;
}
}
// parse arguments
serverObjects args = new serverObjects();
int argc = 0;
if (argsString == null) {
// no args here, maybe a POST with multipart extension
int length = requestHeader.getContentLength();
//System.out.println("HEADER: " + requestHeader.toString()); // DEBUG
if (method.equals(httpHeader.METHOD_POST)) {
// if its a POST, it can be either multipart or as args in the body
if ((requestHeader.containsKey(httpHeader.CONTENT_TYPE)) &&
(requestHeader.get(httpHeader.CONTENT_TYPE).toLowerCase().startsWith("multipart"))) {
// parse multipart
final HashMap<String, byte[]> files = httpd.parseMultipart(requestHeader, args, body);
// integrate these files into the args
if (files != null) {
final Iterator<Map.Entry<String, byte[]>> fit = files.entrySet().iterator();
Map.Entry<String, byte[]> entry;
while (fit.hasNext()) {
entry = fit.next();
args.put(entry.getKey() + "$file", entry.getValue());
}
}
argc = Integer.parseInt(requestHeader.get("ARGC"));
} else {
// parse args in body
argc = httpd.parseArgs(args, body, length);
}
} else {
// no args
argsString = null;
args = null;
argc = 0;
}
} else {
// simple args in URL (stuff after the "?")
argc = httpd.parseArgs(args, argsString);
}
// check for cross site scripting - attacks in request arguments
if (args != null && argc > 0) {
// check all values for occurrences of script values
final Iterator<String> e = args.values().iterator(); // enumeration of values
String val;
while (e.hasNext()) {
val = e.next();
if ((val != null) && (val.indexOf("<script") >= 0)) {
// deny request
httpd.sendRespondError(conProp,out,4,403,null,"bad post values",null);
return;
}
}
}
// we are finished with parsing
// the result of value hand-over is in args and argc
if (path.length() == 0) {
httpd.sendRespondError(conProp,out,4,400,null,"Bad Request",null);
out.flush();
return;
}
File targetClass=null;
// locate the file
if (!(path.startsWith("/"))) path = "/" + path; // attach leading slash
// a different language can be desired (by i.e. ConfigBasic.html) than the one stored in the locale.language
String localeSelection = switchboard.getConfig("locale.language","default");
if (args != null && (args.containsKey("language"))) {
// TODO 9.11.06 Bost: a class with information about available languages is needed.
// the indexOf(".") is just a workaround because there from ConfigLanguage.html commes "de.lng" and
// from ConfigBasic.html comes just "de" in the "language" parameter
localeSelection = args.get("language", localeSelection);
if (localeSelection.indexOf(".") != -1)
localeSelection = localeSelection.substring(0, localeSelection.indexOf("."));
}
File targetFile = getLocalizedFile(path, localeSelection);
final String targetExt = conProp.getProperty("EXT","");
targetClass = rewriteClassFile(new File(htDefaultPath, path));
if (path.endsWith("/")) {
String testpath;
// attach default file name
for (int i = 0; i < defaultFiles.length; i++) {
testpath = path + defaultFiles[i];
targetFile = getOverlayedFile(testpath);
targetClass = getOverlayedClass(testpath);
if (targetFile.exists()) {
path = testpath;
break;
}
}
//no defaultfile, send a dirlisting
if (targetFile == null || !targetFile.exists()) {
final StringBuffer aBuffer = new StringBuffer();
aBuffer.append("<html>\n<head>\n</head>\n<body>\n<h1>Index of " + path + "</h1>\n <ul>\n");
final File dir = new File(htDocsPath, path);
String[] list = dir.list();
if (list == null) list = new String[0]; // should not occur!
File f;
String size;
long sz;
String headline, author, description;
int images, links;
htmlFilterContentScraper scraper;
for (int i = 0; i < list.length; i++) {
f = new File(dir, list[i]);
if (f.isDirectory()) {
aBuffer.append(" <li><a href=\"" + path + list[i] + "/\">" + list[i] + "/</a><br></li>\n");
} else {
if (list[i].endsWith("html") || (list[i].endsWith("htm"))) {
scraper = htmlFilterContentScraper.parseResource(f);
headline = scraper.getTitle();
author = scraper.getAuthor();
description = scraper.getDescription();
images = scraper.getImages().size();
links = scraper.getAnchors().size();
} else {
headline = null;
author = null;
description = null;
images = 0;
links = 0;
}
sz = f.length();
if (sz < 1024) {
size = sz + " bytes";
} else if (sz < 1024 * 1024) {
size = (sz / 1024) + " KB";
} else {
size = (sz / 1024 / 1024) + " MB";
}
aBuffer.append(" <li>");
if ((headline != null) && (headline.length() > 0)) aBuffer.append("<a href=\"" + list[i] + "\"><b>" + headline + "</b></a><br>");
aBuffer.append("<a href=\"" + path + list[i] + "\">" + list[i] + "</a><br>");
if ((author != null) && (author.length() > 0)) aBuffer.append("Author: " + author + "<br>");
if ((description != null) && (description.length() > 0)) aBuffer.append("Description: " + description + "<br>");
aBuffer.append(serverDate.formatShortDay(new Date(f.lastModified())) + ", " + size + ((images > 0) ? ", " + images + " images" : "") + ((links > 0) ? ", " + links + " links" : "") + "<br></li>\n");
}
}
aBuffer.append(" </ul>\n</body>\n</html>\n");
// write the list to the client
httpd.sendRespondHeader(conProp, out, httpVersion, 200, null, "text/html", aBuffer.length(), new Date(dir.lastModified()), null, new httpResponseHeader(), null, null, true);
if (!method.equals(httpHeader.METHOD_HEAD)) {
out.write(aBuffer.toString().getBytes("UTF-8"));
}
return;
}
} else {
//XXX: you cannot share a .png/.gif file with a name like a class in htroot.
if ( !(targetFile.exists()) && !((path.endsWith("png")||path.endsWith("gif")||path.endsWith(".stream"))&&targetClass!=null ) ){
targetFile = new File(htDocsPath, path);
targetClass = rewriteClassFile(new File(htDocsPath, path));
}
}
//File targetClass = rewriteClassFile(targetFile);
//We need tp here
servletProperties tp = new servletProperties();
Date targetDate;
boolean nocache = false;
if ((targetClass != null) && (path.endsWith("png"))) {
// call an image-servlet to produce an on-the-fly - generated image
Object img = null;
try {
requestHeader.put(httpHeader.CONNECTION_PROP_CLIENTIP, conProp.getProperty(httpHeader.CONNECTION_PROP_CLIENTIP));
requestHeader.put(httpHeader.CONNECTION_PROP_PATH, path);
// in case that there are no args given, args = null or empty hashmap
img = invokeServlet(targetClass, requestHeader, args);
} catch (final InvocationTargetException e) {
theLogger.logSevere("INTERNAL ERROR: " + e.toString() + ":" +
e.getMessage() +
" target exception at " + targetClass + ": " +
e.getTargetException().toString() + ":" +
e.getTargetException().getMessage() +
"; java.awt.graphicsenv='" + System.getProperty("java.awt.graphicsenv","") + "'",e);
targetClass = null;
}
if (img == null) {
// error with image generation; send file-not-found
httpd.sendRespondError(conProp, out, 3, 404, "File not Found", null, null);
} else {
if (img instanceof ymageMatrix) {
final ymageMatrix yp = (ymageMatrix) img;
// send an image to client
targetDate = new Date(System.currentTimeMillis());
nocache = true;
final String mimeType = mimeTable.getProperty(targetExt, "text/html");
final serverByteBuffer result = ymageMatrix.exportImage(yp.getImage(), targetExt);
// write the array to the client
httpd.sendRespondHeader(conProp, out, httpVersion, 200, null, mimeType, result.length(), targetDate, null, null, null, null, nocache);
if (!method.equals(httpHeader.METHOD_HEAD)) {
result.writeTo(out);
}
}
if (img instanceof Image) {
final Image i = (Image) img;
// send an image to client
targetDate = new Date(System.currentTimeMillis());
nocache = true;
final String mimeType = mimeTable.getProperty(targetExt, "text/html");
// generate an byte array from the generated image
int width = i.getWidth(null); if (width < 0) width = 96; // bad hack
int height = i.getHeight(null); if (height < 0) height = 96; // bad hack
final BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
bi.createGraphics().drawImage(i, 0, 0, width, height, null);
final serverByteBuffer result = ymageMatrix.exportImage(bi, targetExt);
// write the array to the client
httpd.sendRespondHeader(conProp, out, httpVersion, 200, null, mimeType, result.length(), targetDate, null, null, null, null, nocache);
if (!method.equals(httpHeader.METHOD_HEAD)) {
result.writeTo(out);
}
}
}
} else if ((targetClass != null) && (path.endsWith(".stream"))) {
// call rewrite-class
requestHeader.put(httpHeader.CONNECTION_PROP_CLIENTIP, conProp.getProperty(httpHeader.CONNECTION_PROP_CLIENTIP));
requestHeader.put(httpHeader.CONNECTION_PROP_PATH, path);
//requestHeader.put(httpHeader.CONNECTION_PROP_INPUTSTREAM, body);
//requestHeader.put(httpHeader.CONNECTION_PROP_OUTPUTSTREAM, out);
httpd.sendRespondHeader(conProp, out, httpVersion, 200, null);
// in case that there are no args given, args = null or empty hashmap
/* servletProperties tp = (servlerObjects) */ invokeServlet(targetClass, requestHeader, args);
forceConnectionClose(conProp);
return;
} else if ((targetFile.exists()) && (targetFile.canRead())) {
// we have found a file that can be written to the client
// if this file uses templates, then we use the template
// re-write - method to create an result
String mimeType = mimeTable.getProperty(targetExt,"text/html");
final boolean zipContent = requestHeader.acceptGzip() && httpd.shallTransportZipped("." + conProp.getProperty("EXT",""));
if (path.endsWith("html") ||
path.endsWith("htm") ||
path.endsWith("xml") ||
path.endsWith("rdf") ||
path.endsWith("rss") ||
path.endsWith("csv") ||
path.endsWith("pac") ||
path.endsWith("src") ||
path.endsWith("vcf") ||
path.endsWith("/") ||
path.equals("/robots.txt")) {
/*targetFile = getLocalizedFile(path);
if (!(targetFile.exists())) {
// try to find that file in the htDocsPath
File trialFile = new File(htDocsPath, path);
if (trialFile.exists()) targetFile = trialFile;
}*/
// call rewrite-class
if (targetClass == null) {
targetDate = new Date(targetFile.lastModified());
} else {
// CGI-class: call the class to create a property for rewriting
try {
requestHeader.put(httpHeader.CONNECTION_PROP_CLIENTIP, conProp.getProperty(httpHeader.CONNECTION_PROP_CLIENTIP));
requestHeader.put(httpHeader.CONNECTION_PROP_PATH, path);
// in case that there are no args given, args = null or empty hashmap
final Object tmp = invokeServlet(targetClass, requestHeader, args);
if (tmp == null) {
// if no args given, then tp will be an empty Hashtable object (not null)
tp = new servletProperties();
} else if (tmp instanceof servletProperties) {
tp = (servletProperties) tmp;
} else {
tp = new servletProperties((serverObjects) tmp);
}
// check if the servlets requests authentification
if (tp.containsKey(servletProperties.ACTION_AUTHENTICATE)) {
// handle brute-force protection
if (authorization != null) {
serverLog.logInfo("HTTPD", "dynamic log-in for account 'admin' in http file handler for path '" + path + "' from host '" + clientIP + "'");
final Integer attempts = serverCore.bfHost.get(clientIP);
if (attempts == null)
serverCore.bfHost.put(clientIP, Integer.valueOf(1));
else
serverCore.bfHost.put(clientIP, Integer.valueOf(attempts.intValue() + 1));
}
// send authentication request to browser
final httpResponseHeader headers = getDefaultHeaders(path);
headers.put(httpRequestHeader.WWW_AUTHENTICATE,"Basic realm=\"" + tp.get(servletProperties.ACTION_AUTHENTICATE, "") + "\"");
httpd.sendRespondHeader(conProp,out,httpVersion,401,headers);
return;
} else if (tp.containsKey(servletProperties.ACTION_LOCATION)) {
String location = tp.get(servletProperties.ACTION_LOCATION, "");
if (location.length() == 0) location = path;
final httpResponseHeader headers = getDefaultHeaders(path);
headers.setCookieVector(tp.getOutgoingHeader().getCookieVector()); //put the cookies into the new header TODO: can we put all headerlines, without trouble?
headers.put(httpHeader.LOCATION,location);
httpd.sendRespondHeader(conProp,out,httpVersion,302,headers);
return;
}
// add the application version, the uptime and the client name to every rewrite table
tp.put(servletProperties.PEER_STAT_VERSION, switchboard.getConfig("version", ""));
tp.put(servletProperties.PEER_STAT_UPTIME, ((System.currentTimeMillis() - serverCore.startupTime) / 1000) / 60); // uptime in minutes
tp.putHTML(servletProperties.PEER_STAT_CLIENTNAME, switchboard.getConfig("peerName", "anomic"));
tp.put(servletProperties.PEER_STAT_MYTIME, serverDate.formatShortSecond());
//System.out.println("respond props: " + ((tp == null) ? "null" : tp.toString())); // debug
} catch (final InvocationTargetException e) {
if (e.getCause() instanceof InterruptedException) {
throw new InterruptedException(e.getCause().getMessage());
}
theLogger.logSevere("INTERNAL ERROR: " + e.toString() + ":" +
e.getMessage() +
" target exception at " + targetClass + ": " +
e.getTargetException().toString() + ":" +
e.getTargetException().getMessage(),e);
targetClass = null;
throw e;
}
targetDate = new Date(System.currentTimeMillis());
nocache = true;
}
// rewrite the file
InputStream fis = null;
// read the file/template
byte[] templateContent = null;
if (useTemplateCache) {
final long fileSize = targetFile.length();
if (fileSize <= 512 * 1024) {
// read from cache
SoftReference<byte[]> ref = templateCache.get(targetFile);
if (ref != null) {
templateContent = ref.get();
if (templateContent == null) templateCache.remove(targetFile);
}
if (templateContent == null) {
// loading the content of the template file into
// a byte array
templateContent = serverFileUtils.read(targetFile);
// storing the content into the cache
ref = new SoftReference<byte[]>(templateContent);
templateCache.put(targetFile, ref);
if (theLogger.isFinest()) theLogger.logFinest("Cache MISS for file " + targetFile);
} else {
if (theLogger.isFinest()) theLogger.logFinest("Cache HIT for file " + targetFile);
}
// creating an inputstream needed by the template
// rewrite function
fis = new ByteArrayInputStream(templateContent);
templateContent = null;
} else {
// read from file directly
fis = new BufferedInputStream(new FileInputStream(targetFile));
}
} else {
fis = new BufferedInputStream(new FileInputStream(targetFile));
}
- // detect charset of html-files
- if(path.endsWith("html") || path.endsWith("htm")) {
- // save position
- fis.mark(1000);
- // scrape document to look up charset
- final htmlFilterInputStream htmlFilter = new htmlFilterInputStream(fis,"UTF-8",new yacyURL("http://localhost", null),null,false);
- final String charset = plasmaParser.patchCharsetEncoding(htmlFilter.detectCharset());
- // reset position
- fis.reset();
- if(charset != null)
- mimeType = mimeType + "; charset="+charset;
+ if(mimeType.startsWith("text")) {
+ // every text-file distributed by yacy is UTF-8
+ if(!path.startsWith("/repository")) {
+ mimeType = mimeType + "; charset=UTF-8";
+ } else {
+ // detect charset of html-files
+ if((path.endsWith("html") || path.endsWith("htm"))) {
+ // save position
+ fis.mark(1000);
+ // scrape document to look up charset
+ final htmlFilterInputStream htmlFilter = new htmlFilterInputStream(fis,"UTF-8",new yacyURL("http://localhost", null),null,false);
+ final String charset = plasmaParser.patchCharsetEncoding(htmlFilter.detectCharset());
+ if(charset != null)
+ mimeType = mimeType + "; charset="+charset;
+ // reset position
+ fis.reset();
+ }
+ }
}
// write the array to the client
// we can do that either in standard mode (whole thing completely) or in chunked mode
// since yacy clients do not understand chunked mode (yet), we use this only for communication with the administrator
final boolean yacyClient = requestHeader.userAgent().startsWith("yacy");
final boolean chunked = !method.equals(httpHeader.METHOD_HEAD) && !yacyClient && httpVersion.equals(httpHeader.HTTP_VERSION_1_1);
if (chunked) {
// send page in chunks and parse SSIs
final serverByteBuffer o = new serverByteBuffer();
// apply templates
httpTemplate.writeTemplate(fis, o, tp, "-UNRESOLVED_PATTERN-".getBytes("UTF-8"));
httpd.sendRespondHeader(conProp, out, httpVersion, 200, null, mimeType, -1, targetDate, null, tp.getOutgoingHeader(), null, "chunked", nocache);
// send the content in chunked parts, see RFC 2616 section 3.6.1
final httpChunkedOutputStream chos = new httpChunkedOutputStream(out);
httpSSI.writeSSI(o, chos, authorization, clientIP);
//chos.write(result);
chos.finish();
} else {
// send page as whole thing, SSIs are not possible
final String contentEncoding = (zipContent) ? "gzip" : null;
// apply templates
final serverByteBuffer o1 = new serverByteBuffer();
httpTemplate.writeTemplate(fis, o1, tp, "-UNRESOLVED_PATTERN-".getBytes("UTF-8"));
final serverByteBuffer o = new serverByteBuffer();
if (zipContent) {
GZIPOutputStream zippedOut = new GZIPOutputStream(o);
httpSSI.writeSSI(o1, zippedOut, authorization, clientIP);
//httpTemplate.writeTemplate(fis, zippedOut, tp, "-UNRESOLVED_PATTERN-".getBytes("UTF-8"));
zippedOut.finish();
zippedOut.flush();
zippedOut.close();
zippedOut = null;
} else {
httpSSI.writeSSI(o1, o, authorization, clientIP);
//httpTemplate.writeTemplate(fis, o, tp, "-UNRESOLVED_PATTERN-".getBytes("UTF-8"));
}
if (method.equals(httpHeader.METHOD_HEAD)) {
httpd.sendRespondHeader(conProp, out,
httpVersion, 200, null, mimeType, o.length(),
targetDate, null, tp.getOutgoingHeader(),
contentEncoding, null, nocache);
} else {
final byte[] result = o.getBytes(); // this interrupts streaming (bad idea!)
httpd.sendRespondHeader(conProp, out,
httpVersion, 200, null, mimeType, result.length,
targetDate, null, tp.getOutgoingHeader(),
contentEncoding, null, nocache);
serverFileUtils.copy(result, out);
}
}
} else { // no html
int statusCode = 200;
int rangeStartOffset = 0;
httpResponseHeader header = new httpResponseHeader();
// adding the accept ranges header
header.put(httpHeader.ACCEPT_RANGES, "bytes");
// reading the files md5 hash if availabe and use it as ETAG of the resource
String targetMD5 = null;
final File targetMd5File = new File(targetFile + ".md5");
try {
if (targetMd5File.exists()) {
//String description = null;
targetMD5 = new String(serverFileUtils.read(targetMd5File));
pos = targetMD5.indexOf('\n');
if (pos >= 0) {
//description = targetMD5.substring(pos + 1);
targetMD5 = targetMD5.substring(0, pos);
}
// using the checksum as ETAG header
header.put(httpHeader.ETAG, targetMD5);
}
} catch (final IOException e) {
e.printStackTrace();
}
if (requestHeader.containsKey(httpHeader.RANGE)) {
final Object ifRange = requestHeader.ifRange();
if ((ifRange == null)||
(ifRange instanceof Date && targetFile.lastModified() == ((Date)ifRange).getTime()) ||
(ifRange instanceof String && ifRange.equals(targetMD5))) {
final String rangeHeaderVal = requestHeader.get(httpHeader.RANGE).trim();
if (rangeHeaderVal.startsWith("bytes=")) {
final String rangesVal = rangeHeaderVal.substring("bytes=".length());
final String[] ranges = rangesVal.split(",");
if ((ranges.length == 1)&&(ranges[0].endsWith("-"))) {
rangeStartOffset = Integer.valueOf(ranges[0].substring(0,ranges[0].length()-1)).intValue();
statusCode = 206;
if (header == null) header = new httpResponseHeader();
header.put(httpHeader.CONTENT_RANGE, "bytes " + rangeStartOffset + "-" + (targetFile.length()-1) + "/" + targetFile.length());
}
}
}
}
// write the file to the client
targetDate = new Date(targetFile.lastModified());
final long contentLength = (zipContent)?-1:targetFile.length()-rangeStartOffset;
final String contentEncoding = (zipContent)?"gzip":null;
final String transferEncoding = (!httpVersion.equals(httpHeader.HTTP_VERSION_1_1))?null:(zipContent)?"chunked":null;
if (!httpVersion.equals(httpHeader.HTTP_VERSION_1_1) && zipContent) forceConnectionClose(conProp);
httpd.sendRespondHeader(conProp, out, httpVersion, statusCode, null, mimeType, contentLength, targetDate, null, header, contentEncoding, transferEncoding, nocache);
if (!method.equals(httpHeader.METHOD_HEAD)) {
httpChunkedOutputStream chunkedOut = null;
GZIPOutputStream zipped = null;
OutputStream newOut = out;
if (transferEncoding != null) {
chunkedOut = new httpChunkedOutputStream(newOut);
newOut = chunkedOut;
}
if (contentEncoding != null) {
zipped = new GZIPOutputStream(newOut);
newOut = zipped;
}
serverFileUtils.copyRange(targetFile, newOut, rangeStartOffset);
if (zipped != null) {
zipped.flush();
zipped.finish();
}
if (chunkedOut != null) {
chunkedOut.finish();
}
// flush all
try {newOut.flush();}catch (final Exception e) {}
// wait a little time until everything closes so that clients can read from the streams/sockets
if ((contentLength >= 0) && ((String)requestHeader.get(httpRequestHeader.CONNECTION, "close")).indexOf("keep-alive") == -1) {
// in case that the client knows the size in advance (contentLength present) the waiting will have no effect on the interface performance
// but if the client waits on a connection interruption this will slow down.
try {Thread.sleep(2000);} catch (final InterruptedException e) {} // FIXME: is this necessary?
}
}
// check mime type again using the result array: these are 'magics'
// if (serverByteBuffer.equals(result, 1, "PNG".getBytes())) mimeType = mimeTable.getProperty("png","text/html");
// else if (serverByteBuffer.equals(result, 0, "GIF89".getBytes())) mimeType = mimeTable.getProperty("gif","text/html");
// else if (serverByteBuffer.equals(result, 6, "JFIF".getBytes())) mimeType = mimeTable.getProperty("jpg","text/html");
//System.out.print("MAGIC:"); for (int i = 0; i < 10; i++) System.out.print(Integer.toHexString((int) result[i]) + ","); System.out.println();
}
} else {
httpd.sendRespondError(conProp,out,3,404,"File not Found",null,null);
return;
}
} catch (final Exception e) {
try {
// doing some errorhandling ...
int httpStatusCode = 400;
final String httpStatusText = null;
final StringBuffer errorMessage = new StringBuffer();
Exception errorExc = null;
final String errorMsg = e.getMessage();
if (
(e instanceof InterruptedException) ||
((errorMsg != null) && (errorMsg.startsWith("Socket closed")) && (Thread.currentThread().isInterrupted()))
) {
errorMessage.append("Interruption detected while processing query.");
httpStatusCode = 503;
} else {
if ((errorMsg != null) &&
(
errorMsg.startsWith("Broken pipe") ||
errorMsg.startsWith("Connection reset") ||
errorMsg.startsWith("Software caused connection abort")
)) {
// client closed the connection, so we just end silently
errorMessage.append("Client unexpectedly closed connection while processing query.");
} else if ((errorMsg != null) && (errorMsg.startsWith("Connection timed out"))) {
errorMessage.append("Connection timed out.");
} else {
errorMessage.append("Unexpected error while processing query.");
httpStatusCode = 500;
errorExc = e;
}
}
errorMessage.append("\nSession: ").append(Thread.currentThread().getName())
.append("\nQuery: ").append(path)
.append("\nClient: ").append(conProp.getProperty(httpHeader.CONNECTION_PROP_CLIENTIP,"unknown"))
.append("\nReason: ").append(e.toString());
if (!conProp.containsKey(httpHeader.CONNECTION_PROP_PROXY_RESPOND_HEADER)) {
// sending back an error message to the client
// if we have not already send an http header
httpd.sendRespondError(conProp,out, 4, httpStatusCode, httpStatusText, new String(errorMessage),errorExc);
} else {
// otherwise we close the connection
forceConnectionClose(conProp);
}
// if it is an unexpected error we log it
if (httpStatusCode == 500) {
theLogger.logWarning(new String(errorMessage),e);
}
} catch (final Exception ee) {
forceConnectionClose(conProp);
}
} finally {
try {out.flush();}catch (final Exception e) {}
}
}
public static final File getOverlayedClass(final String path) {
File targetClass;
targetClass = rewriteClassFile(new File(htDefaultPath, path)); //works for default and localized files
if (targetClass == null || !targetClass.exists()) {
//works for htdocs
targetClass=rewriteClassFile(new File(htDocsPath, path));
}
return targetClass;
}
public static final File getOverlayedFile(final String path) {
File targetFile;
targetFile = getLocalizedFile(path);
if (!targetFile.exists()) {
targetFile = new File(htDocsPath, path);
}
return targetFile;
}
private static final void forceConnectionClose(final Properties conprop) {
if (conprop != null) {
conprop.setProperty(httpHeader.CONNECTION_PROP_PERSISTENT,"close");
}
}
private static final File rewriteClassFile(final File template) {
try {
String f = template.getCanonicalPath();
final int p = f.lastIndexOf(".");
if (p < 0) return null;
f = f.substring(0, p) + ".class";
//System.out.println("constructed class path " + f);
final File cf = new File(f);
if (cf.exists()) return cf;
return null;
} catch (final IOException e) {
return null;
}
}
private static final Method rewriteMethod(final File classFile) {
Method m = null;
// now make a class out of the stream
try {
if (useTemplateCache) {
final SoftReference<Method> ref = templateMethodCache.get(classFile);
if (ref != null) {
m = ref.get();
if (m == null) {
templateMethodCache.remove(classFile);
} else {
return m;
}
}
}
final Class<?> c = provider.loadClass(classFile);
final Class<?>[] params = new Class[] {
httpRequestHeader.class,
serverObjects.class,
serverSwitch.class };
m = c.getMethod("respond", params);
if (useTemplateCache) {
// storing the method into the cache
final SoftReference<Method> ref = new SoftReference<Method>(m);
templateMethodCache.put(classFile, ref);
}
} catch (final ClassNotFoundException e) {
System.out.println("INTERNAL ERROR: class " + classFile + " is missing:" + e.getMessage());
} catch (final NoSuchMethodException e) {
System.out.println("INTERNAL ERROR: method respond not found in class " + classFile + ": " + e.getMessage());
}
//System.out.println("found method: " + m.toString());
return m;
}
public static final Object invokeServlet(final File targetClass, final httpRequestHeader request, final serverObjects args) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {
Object result;
if (safeServletsMode) synchronized (switchboard) {
result = rewriteMethod(targetClass).invoke(null, new Object[] {request, args, switchboard});
} else {
result = rewriteMethod(targetClass).invoke(null, new Object[] {request, args, switchboard});
}
return result;
}
// public void doConnect(Properties conProp, httpHeader requestHeader, InputStream clientIn, OutputStream clientOut) {
// throw new UnsupportedOperationException();
// }
}
| true | true | public static void doResponse(final Properties conProp, final httpRequestHeader requestHeader, final OutputStream out, final InputStream body) {
String path = null;
try {
// getting some connection properties
final String method = conProp.getProperty(httpHeader.CONNECTION_PROP_METHOD);
path = conProp.getProperty(httpHeader.CONNECTION_PROP_PATH);
String argsString = conProp.getProperty(httpHeader.CONNECTION_PROP_ARGS); // is null if no args were given
final String httpVersion = conProp.getProperty(httpHeader.CONNECTION_PROP_HTTP_VER);
final String clientIP = conProp.getProperty(httpHeader.CONNECTION_PROP_CLIENTIP, "unknown-host");
// check hack attacks in path
if (path.indexOf("..") >= 0) {
httpd.sendRespondError(conProp,out,4,403,null,"Access not allowed",null);
return;
}
// url decoding of path
try {
path = URLDecoder.decode(path, "UTF-8");
} catch (final UnsupportedEncodingException e) {
// This should never occur
assert(false) : "UnsupportedEncodingException: " + e.getMessage();
}
// check again hack attacks in path
if (path.indexOf("..") >= 0) {
httpd.sendRespondError(conProp,out,4,403,null,"Access not allowed",null);
return;
}
// check permission/granted access
String authorization = requestHeader.get(httpRequestHeader.AUTHORIZATION);
if (authorization != null && authorization.length() == 0) authorization = null;
final String adminAccountBase64MD5 = switchboard.getConfig(httpd.ADMIN_ACCOUNT_B64MD5, "");
int pos = path.lastIndexOf(".");
final boolean adminAccountForLocalhost = sb.getConfigBool("adminAccountForLocalhost", false);
final String refererHost = requestHeader.refererHost();
final boolean accessFromLocalhost = serverCore.isLocalhost(clientIP) && (refererHost.length() == 0 || serverCore.isLocalhost(refererHost));
final boolean grantedForLocalhost = adminAccountForLocalhost && accessFromLocalhost;
final boolean protectedPage = (path.substring(0,(pos==-1)?path.length():pos)).endsWith("_p");
final boolean accountEmpty = adminAccountBase64MD5.length() == 0;
if (!grantedForLocalhost && protectedPage && !accountEmpty) {
// authentication required
if (authorization == null) {
// no authorization given in response. Ask for that
final httpResponseHeader responseHeader = getDefaultHeaders(path);
responseHeader.put(httpRequestHeader.WWW_AUTHENTICATE,"Basic realm=\"admin log-in\"");
//httpd.sendRespondHeader(conProp,out,httpVersion,401,headers);
final servletProperties tp=new servletProperties();
tp.put("returnto", path);
//TODO: separate error page Wrong Login / No Login
httpd.sendRespondError(conProp, out, 5, 401, "Wrong Authentication", "", new File("proxymsg/authfail.inc"), tp, null, responseHeader);
return;
} else if (
(httpd.staticAdminAuthenticated(authorization.trim().substring(6), switchboard) == 4) ||
(sb.userDB.hasAdminRight(authorization, conProp.getProperty(httpHeader.CONNECTION_PROP_CLIENTIP), requestHeader.getHeaderCookies()))) {
//Authentication successful. remove brute-force flag
serverCore.bfHost.remove(conProp.getProperty(httpHeader.CONNECTION_PROP_CLIENTIP));
} else {
// a wrong authentication was given or the userDB user does not have admin access. Ask again
serverLog.logInfo("HTTPD", "Wrong log-in for account 'admin' in http file handler for path '" + path + "' from host '" + clientIP + "'");
final Integer attempts = serverCore.bfHost.get(clientIP);
if (attempts == null)
serverCore.bfHost.put(clientIP, Integer.valueOf(1));
else
serverCore.bfHost.put(clientIP, Integer.valueOf(attempts.intValue() + 1));
final httpResponseHeader headers = getDefaultHeaders(path);
headers.put(httpRequestHeader.WWW_AUTHENTICATE,"Basic realm=\"admin log-in\"");
httpd.sendRespondHeader(conProp,out,httpVersion,401,headers);
return;
}
}
// parse arguments
serverObjects args = new serverObjects();
int argc = 0;
if (argsString == null) {
// no args here, maybe a POST with multipart extension
int length = requestHeader.getContentLength();
//System.out.println("HEADER: " + requestHeader.toString()); // DEBUG
if (method.equals(httpHeader.METHOD_POST)) {
// if its a POST, it can be either multipart or as args in the body
if ((requestHeader.containsKey(httpHeader.CONTENT_TYPE)) &&
(requestHeader.get(httpHeader.CONTENT_TYPE).toLowerCase().startsWith("multipart"))) {
// parse multipart
final HashMap<String, byte[]> files = httpd.parseMultipart(requestHeader, args, body);
// integrate these files into the args
if (files != null) {
final Iterator<Map.Entry<String, byte[]>> fit = files.entrySet().iterator();
Map.Entry<String, byte[]> entry;
while (fit.hasNext()) {
entry = fit.next();
args.put(entry.getKey() + "$file", entry.getValue());
}
}
argc = Integer.parseInt(requestHeader.get("ARGC"));
} else {
// parse args in body
argc = httpd.parseArgs(args, body, length);
}
} else {
// no args
argsString = null;
args = null;
argc = 0;
}
} else {
// simple args in URL (stuff after the "?")
argc = httpd.parseArgs(args, argsString);
}
// check for cross site scripting - attacks in request arguments
if (args != null && argc > 0) {
// check all values for occurrences of script values
final Iterator<String> e = args.values().iterator(); // enumeration of values
String val;
while (e.hasNext()) {
val = e.next();
if ((val != null) && (val.indexOf("<script") >= 0)) {
// deny request
httpd.sendRespondError(conProp,out,4,403,null,"bad post values",null);
return;
}
}
}
// we are finished with parsing
// the result of value hand-over is in args and argc
if (path.length() == 0) {
httpd.sendRespondError(conProp,out,4,400,null,"Bad Request",null);
out.flush();
return;
}
File targetClass=null;
// locate the file
if (!(path.startsWith("/"))) path = "/" + path; // attach leading slash
// a different language can be desired (by i.e. ConfigBasic.html) than the one stored in the locale.language
String localeSelection = switchboard.getConfig("locale.language","default");
if (args != null && (args.containsKey("language"))) {
// TODO 9.11.06 Bost: a class with information about available languages is needed.
// the indexOf(".") is just a workaround because there from ConfigLanguage.html commes "de.lng" and
// from ConfigBasic.html comes just "de" in the "language" parameter
localeSelection = args.get("language", localeSelection);
if (localeSelection.indexOf(".") != -1)
localeSelection = localeSelection.substring(0, localeSelection.indexOf("."));
}
File targetFile = getLocalizedFile(path, localeSelection);
final String targetExt = conProp.getProperty("EXT","");
targetClass = rewriteClassFile(new File(htDefaultPath, path));
if (path.endsWith("/")) {
String testpath;
// attach default file name
for (int i = 0; i < defaultFiles.length; i++) {
testpath = path + defaultFiles[i];
targetFile = getOverlayedFile(testpath);
targetClass = getOverlayedClass(testpath);
if (targetFile.exists()) {
path = testpath;
break;
}
}
//no defaultfile, send a dirlisting
if (targetFile == null || !targetFile.exists()) {
final StringBuffer aBuffer = new StringBuffer();
aBuffer.append("<html>\n<head>\n</head>\n<body>\n<h1>Index of " + path + "</h1>\n <ul>\n");
final File dir = new File(htDocsPath, path);
String[] list = dir.list();
if (list == null) list = new String[0]; // should not occur!
File f;
String size;
long sz;
String headline, author, description;
int images, links;
htmlFilterContentScraper scraper;
for (int i = 0; i < list.length; i++) {
f = new File(dir, list[i]);
if (f.isDirectory()) {
aBuffer.append(" <li><a href=\"" + path + list[i] + "/\">" + list[i] + "/</a><br></li>\n");
} else {
if (list[i].endsWith("html") || (list[i].endsWith("htm"))) {
scraper = htmlFilterContentScraper.parseResource(f);
headline = scraper.getTitle();
author = scraper.getAuthor();
description = scraper.getDescription();
images = scraper.getImages().size();
links = scraper.getAnchors().size();
} else {
headline = null;
author = null;
description = null;
images = 0;
links = 0;
}
sz = f.length();
if (sz < 1024) {
size = sz + " bytes";
} else if (sz < 1024 * 1024) {
size = (sz / 1024) + " KB";
} else {
size = (sz / 1024 / 1024) + " MB";
}
aBuffer.append(" <li>");
if ((headline != null) && (headline.length() > 0)) aBuffer.append("<a href=\"" + list[i] + "\"><b>" + headline + "</b></a><br>");
aBuffer.append("<a href=\"" + path + list[i] + "\">" + list[i] + "</a><br>");
if ((author != null) && (author.length() > 0)) aBuffer.append("Author: " + author + "<br>");
if ((description != null) && (description.length() > 0)) aBuffer.append("Description: " + description + "<br>");
aBuffer.append(serverDate.formatShortDay(new Date(f.lastModified())) + ", " + size + ((images > 0) ? ", " + images + " images" : "") + ((links > 0) ? ", " + links + " links" : "") + "<br></li>\n");
}
}
aBuffer.append(" </ul>\n</body>\n</html>\n");
// write the list to the client
httpd.sendRespondHeader(conProp, out, httpVersion, 200, null, "text/html", aBuffer.length(), new Date(dir.lastModified()), null, new httpResponseHeader(), null, null, true);
if (!method.equals(httpHeader.METHOD_HEAD)) {
out.write(aBuffer.toString().getBytes("UTF-8"));
}
return;
}
} else {
//XXX: you cannot share a .png/.gif file with a name like a class in htroot.
if ( !(targetFile.exists()) && !((path.endsWith("png")||path.endsWith("gif")||path.endsWith(".stream"))&&targetClass!=null ) ){
targetFile = new File(htDocsPath, path);
targetClass = rewriteClassFile(new File(htDocsPath, path));
}
}
//File targetClass = rewriteClassFile(targetFile);
//We need tp here
servletProperties tp = new servletProperties();
Date targetDate;
boolean nocache = false;
if ((targetClass != null) && (path.endsWith("png"))) {
// call an image-servlet to produce an on-the-fly - generated image
Object img = null;
try {
requestHeader.put(httpHeader.CONNECTION_PROP_CLIENTIP, conProp.getProperty(httpHeader.CONNECTION_PROP_CLIENTIP));
requestHeader.put(httpHeader.CONNECTION_PROP_PATH, path);
// in case that there are no args given, args = null or empty hashmap
img = invokeServlet(targetClass, requestHeader, args);
} catch (final InvocationTargetException e) {
theLogger.logSevere("INTERNAL ERROR: " + e.toString() + ":" +
e.getMessage() +
" target exception at " + targetClass + ": " +
e.getTargetException().toString() + ":" +
e.getTargetException().getMessage() +
"; java.awt.graphicsenv='" + System.getProperty("java.awt.graphicsenv","") + "'",e);
targetClass = null;
}
if (img == null) {
// error with image generation; send file-not-found
httpd.sendRespondError(conProp, out, 3, 404, "File not Found", null, null);
} else {
if (img instanceof ymageMatrix) {
final ymageMatrix yp = (ymageMatrix) img;
// send an image to client
targetDate = new Date(System.currentTimeMillis());
nocache = true;
final String mimeType = mimeTable.getProperty(targetExt, "text/html");
final serverByteBuffer result = ymageMatrix.exportImage(yp.getImage(), targetExt);
// write the array to the client
httpd.sendRespondHeader(conProp, out, httpVersion, 200, null, mimeType, result.length(), targetDate, null, null, null, null, nocache);
if (!method.equals(httpHeader.METHOD_HEAD)) {
result.writeTo(out);
}
}
if (img instanceof Image) {
final Image i = (Image) img;
// send an image to client
targetDate = new Date(System.currentTimeMillis());
nocache = true;
final String mimeType = mimeTable.getProperty(targetExt, "text/html");
// generate an byte array from the generated image
int width = i.getWidth(null); if (width < 0) width = 96; // bad hack
int height = i.getHeight(null); if (height < 0) height = 96; // bad hack
final BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
bi.createGraphics().drawImage(i, 0, 0, width, height, null);
final serverByteBuffer result = ymageMatrix.exportImage(bi, targetExt);
// write the array to the client
httpd.sendRespondHeader(conProp, out, httpVersion, 200, null, mimeType, result.length(), targetDate, null, null, null, null, nocache);
if (!method.equals(httpHeader.METHOD_HEAD)) {
result.writeTo(out);
}
}
}
} else if ((targetClass != null) && (path.endsWith(".stream"))) {
// call rewrite-class
requestHeader.put(httpHeader.CONNECTION_PROP_CLIENTIP, conProp.getProperty(httpHeader.CONNECTION_PROP_CLIENTIP));
requestHeader.put(httpHeader.CONNECTION_PROP_PATH, path);
//requestHeader.put(httpHeader.CONNECTION_PROP_INPUTSTREAM, body);
//requestHeader.put(httpHeader.CONNECTION_PROP_OUTPUTSTREAM, out);
httpd.sendRespondHeader(conProp, out, httpVersion, 200, null);
// in case that there are no args given, args = null or empty hashmap
/* servletProperties tp = (servlerObjects) */ invokeServlet(targetClass, requestHeader, args);
forceConnectionClose(conProp);
return;
} else if ((targetFile.exists()) && (targetFile.canRead())) {
// we have found a file that can be written to the client
// if this file uses templates, then we use the template
// re-write - method to create an result
String mimeType = mimeTable.getProperty(targetExt,"text/html");
final boolean zipContent = requestHeader.acceptGzip() && httpd.shallTransportZipped("." + conProp.getProperty("EXT",""));
if (path.endsWith("html") ||
path.endsWith("htm") ||
path.endsWith("xml") ||
path.endsWith("rdf") ||
path.endsWith("rss") ||
path.endsWith("csv") ||
path.endsWith("pac") ||
path.endsWith("src") ||
path.endsWith("vcf") ||
path.endsWith("/") ||
path.equals("/robots.txt")) {
/*targetFile = getLocalizedFile(path);
if (!(targetFile.exists())) {
// try to find that file in the htDocsPath
File trialFile = new File(htDocsPath, path);
if (trialFile.exists()) targetFile = trialFile;
}*/
// call rewrite-class
if (targetClass == null) {
targetDate = new Date(targetFile.lastModified());
} else {
// CGI-class: call the class to create a property for rewriting
try {
requestHeader.put(httpHeader.CONNECTION_PROP_CLIENTIP, conProp.getProperty(httpHeader.CONNECTION_PROP_CLIENTIP));
requestHeader.put(httpHeader.CONNECTION_PROP_PATH, path);
// in case that there are no args given, args = null or empty hashmap
final Object tmp = invokeServlet(targetClass, requestHeader, args);
if (tmp == null) {
// if no args given, then tp will be an empty Hashtable object (not null)
tp = new servletProperties();
} else if (tmp instanceof servletProperties) {
tp = (servletProperties) tmp;
} else {
tp = new servletProperties((serverObjects) tmp);
}
// check if the servlets requests authentification
if (tp.containsKey(servletProperties.ACTION_AUTHENTICATE)) {
// handle brute-force protection
if (authorization != null) {
serverLog.logInfo("HTTPD", "dynamic log-in for account 'admin' in http file handler for path '" + path + "' from host '" + clientIP + "'");
final Integer attempts = serverCore.bfHost.get(clientIP);
if (attempts == null)
serverCore.bfHost.put(clientIP, Integer.valueOf(1));
else
serverCore.bfHost.put(clientIP, Integer.valueOf(attempts.intValue() + 1));
}
// send authentication request to browser
final httpResponseHeader headers = getDefaultHeaders(path);
headers.put(httpRequestHeader.WWW_AUTHENTICATE,"Basic realm=\"" + tp.get(servletProperties.ACTION_AUTHENTICATE, "") + "\"");
httpd.sendRespondHeader(conProp,out,httpVersion,401,headers);
return;
} else if (tp.containsKey(servletProperties.ACTION_LOCATION)) {
String location = tp.get(servletProperties.ACTION_LOCATION, "");
if (location.length() == 0) location = path;
final httpResponseHeader headers = getDefaultHeaders(path);
headers.setCookieVector(tp.getOutgoingHeader().getCookieVector()); //put the cookies into the new header TODO: can we put all headerlines, without trouble?
headers.put(httpHeader.LOCATION,location);
httpd.sendRespondHeader(conProp,out,httpVersion,302,headers);
return;
}
// add the application version, the uptime and the client name to every rewrite table
tp.put(servletProperties.PEER_STAT_VERSION, switchboard.getConfig("version", ""));
tp.put(servletProperties.PEER_STAT_UPTIME, ((System.currentTimeMillis() - serverCore.startupTime) / 1000) / 60); // uptime in minutes
tp.putHTML(servletProperties.PEER_STAT_CLIENTNAME, switchboard.getConfig("peerName", "anomic"));
tp.put(servletProperties.PEER_STAT_MYTIME, serverDate.formatShortSecond());
//System.out.println("respond props: " + ((tp == null) ? "null" : tp.toString())); // debug
} catch (final InvocationTargetException e) {
if (e.getCause() instanceof InterruptedException) {
throw new InterruptedException(e.getCause().getMessage());
}
theLogger.logSevere("INTERNAL ERROR: " + e.toString() + ":" +
e.getMessage() +
" target exception at " + targetClass + ": " +
e.getTargetException().toString() + ":" +
e.getTargetException().getMessage(),e);
targetClass = null;
throw e;
}
targetDate = new Date(System.currentTimeMillis());
nocache = true;
}
// rewrite the file
InputStream fis = null;
// read the file/template
byte[] templateContent = null;
if (useTemplateCache) {
final long fileSize = targetFile.length();
if (fileSize <= 512 * 1024) {
// read from cache
SoftReference<byte[]> ref = templateCache.get(targetFile);
if (ref != null) {
templateContent = ref.get();
if (templateContent == null) templateCache.remove(targetFile);
}
if (templateContent == null) {
// loading the content of the template file into
// a byte array
templateContent = serverFileUtils.read(targetFile);
// storing the content into the cache
ref = new SoftReference<byte[]>(templateContent);
templateCache.put(targetFile, ref);
if (theLogger.isFinest()) theLogger.logFinest("Cache MISS for file " + targetFile);
} else {
if (theLogger.isFinest()) theLogger.logFinest("Cache HIT for file " + targetFile);
}
// creating an inputstream needed by the template
// rewrite function
fis = new ByteArrayInputStream(templateContent);
templateContent = null;
} else {
// read from file directly
fis = new BufferedInputStream(new FileInputStream(targetFile));
}
} else {
fis = new BufferedInputStream(new FileInputStream(targetFile));
}
// detect charset of html-files
if(path.endsWith("html") || path.endsWith("htm")) {
// save position
fis.mark(1000);
// scrape document to look up charset
final htmlFilterInputStream htmlFilter = new htmlFilterInputStream(fis,"UTF-8",new yacyURL("http://localhost", null),null,false);
final String charset = plasmaParser.patchCharsetEncoding(htmlFilter.detectCharset());
// reset position
fis.reset();
if(charset != null)
mimeType = mimeType + "; charset="+charset;
}
// write the array to the client
// we can do that either in standard mode (whole thing completely) or in chunked mode
// since yacy clients do not understand chunked mode (yet), we use this only for communication with the administrator
final boolean yacyClient = requestHeader.userAgent().startsWith("yacy");
final boolean chunked = !method.equals(httpHeader.METHOD_HEAD) && !yacyClient && httpVersion.equals(httpHeader.HTTP_VERSION_1_1);
if (chunked) {
// send page in chunks and parse SSIs
final serverByteBuffer o = new serverByteBuffer();
// apply templates
httpTemplate.writeTemplate(fis, o, tp, "-UNRESOLVED_PATTERN-".getBytes("UTF-8"));
httpd.sendRespondHeader(conProp, out, httpVersion, 200, null, mimeType, -1, targetDate, null, tp.getOutgoingHeader(), null, "chunked", nocache);
// send the content in chunked parts, see RFC 2616 section 3.6.1
final httpChunkedOutputStream chos = new httpChunkedOutputStream(out);
httpSSI.writeSSI(o, chos, authorization, clientIP);
//chos.write(result);
chos.finish();
} else {
// send page as whole thing, SSIs are not possible
final String contentEncoding = (zipContent) ? "gzip" : null;
// apply templates
final serverByteBuffer o1 = new serverByteBuffer();
httpTemplate.writeTemplate(fis, o1, tp, "-UNRESOLVED_PATTERN-".getBytes("UTF-8"));
final serverByteBuffer o = new serverByteBuffer();
if (zipContent) {
GZIPOutputStream zippedOut = new GZIPOutputStream(o);
httpSSI.writeSSI(o1, zippedOut, authorization, clientIP);
//httpTemplate.writeTemplate(fis, zippedOut, tp, "-UNRESOLVED_PATTERN-".getBytes("UTF-8"));
zippedOut.finish();
zippedOut.flush();
zippedOut.close();
zippedOut = null;
} else {
httpSSI.writeSSI(o1, o, authorization, clientIP);
//httpTemplate.writeTemplate(fis, o, tp, "-UNRESOLVED_PATTERN-".getBytes("UTF-8"));
}
if (method.equals(httpHeader.METHOD_HEAD)) {
httpd.sendRespondHeader(conProp, out,
httpVersion, 200, null, mimeType, o.length(),
targetDate, null, tp.getOutgoingHeader(),
contentEncoding, null, nocache);
} else {
final byte[] result = o.getBytes(); // this interrupts streaming (bad idea!)
httpd.sendRespondHeader(conProp, out,
httpVersion, 200, null, mimeType, result.length,
targetDate, null, tp.getOutgoingHeader(),
contentEncoding, null, nocache);
serverFileUtils.copy(result, out);
}
}
} else { // no html
int statusCode = 200;
int rangeStartOffset = 0;
httpResponseHeader header = new httpResponseHeader();
// adding the accept ranges header
header.put(httpHeader.ACCEPT_RANGES, "bytes");
// reading the files md5 hash if availabe and use it as ETAG of the resource
String targetMD5 = null;
final File targetMd5File = new File(targetFile + ".md5");
try {
if (targetMd5File.exists()) {
//String description = null;
targetMD5 = new String(serverFileUtils.read(targetMd5File));
pos = targetMD5.indexOf('\n');
if (pos >= 0) {
//description = targetMD5.substring(pos + 1);
targetMD5 = targetMD5.substring(0, pos);
}
// using the checksum as ETAG header
header.put(httpHeader.ETAG, targetMD5);
}
} catch (final IOException e) {
e.printStackTrace();
}
if (requestHeader.containsKey(httpHeader.RANGE)) {
final Object ifRange = requestHeader.ifRange();
if ((ifRange == null)||
(ifRange instanceof Date && targetFile.lastModified() == ((Date)ifRange).getTime()) ||
(ifRange instanceof String && ifRange.equals(targetMD5))) {
final String rangeHeaderVal = requestHeader.get(httpHeader.RANGE).trim();
if (rangeHeaderVal.startsWith("bytes=")) {
final String rangesVal = rangeHeaderVal.substring("bytes=".length());
final String[] ranges = rangesVal.split(",");
if ((ranges.length == 1)&&(ranges[0].endsWith("-"))) {
rangeStartOffset = Integer.valueOf(ranges[0].substring(0,ranges[0].length()-1)).intValue();
statusCode = 206;
if (header == null) header = new httpResponseHeader();
header.put(httpHeader.CONTENT_RANGE, "bytes " + rangeStartOffset + "-" + (targetFile.length()-1) + "/" + targetFile.length());
}
}
}
}
// write the file to the client
targetDate = new Date(targetFile.lastModified());
final long contentLength = (zipContent)?-1:targetFile.length()-rangeStartOffset;
final String contentEncoding = (zipContent)?"gzip":null;
final String transferEncoding = (!httpVersion.equals(httpHeader.HTTP_VERSION_1_1))?null:(zipContent)?"chunked":null;
if (!httpVersion.equals(httpHeader.HTTP_VERSION_1_1) && zipContent) forceConnectionClose(conProp);
httpd.sendRespondHeader(conProp, out, httpVersion, statusCode, null, mimeType, contentLength, targetDate, null, header, contentEncoding, transferEncoding, nocache);
if (!method.equals(httpHeader.METHOD_HEAD)) {
httpChunkedOutputStream chunkedOut = null;
GZIPOutputStream zipped = null;
OutputStream newOut = out;
if (transferEncoding != null) {
chunkedOut = new httpChunkedOutputStream(newOut);
newOut = chunkedOut;
}
if (contentEncoding != null) {
zipped = new GZIPOutputStream(newOut);
newOut = zipped;
}
serverFileUtils.copyRange(targetFile, newOut, rangeStartOffset);
if (zipped != null) {
zipped.flush();
zipped.finish();
}
if (chunkedOut != null) {
chunkedOut.finish();
}
// flush all
try {newOut.flush();}catch (final Exception e) {}
// wait a little time until everything closes so that clients can read from the streams/sockets
if ((contentLength >= 0) && ((String)requestHeader.get(httpRequestHeader.CONNECTION, "close")).indexOf("keep-alive") == -1) {
// in case that the client knows the size in advance (contentLength present) the waiting will have no effect on the interface performance
// but if the client waits on a connection interruption this will slow down.
try {Thread.sleep(2000);} catch (final InterruptedException e) {} // FIXME: is this necessary?
}
}
// check mime type again using the result array: these are 'magics'
// if (serverByteBuffer.equals(result, 1, "PNG".getBytes())) mimeType = mimeTable.getProperty("png","text/html");
// else if (serverByteBuffer.equals(result, 0, "GIF89".getBytes())) mimeType = mimeTable.getProperty("gif","text/html");
// else if (serverByteBuffer.equals(result, 6, "JFIF".getBytes())) mimeType = mimeTable.getProperty("jpg","text/html");
//System.out.print("MAGIC:"); for (int i = 0; i < 10; i++) System.out.print(Integer.toHexString((int) result[i]) + ","); System.out.println();
}
} else {
httpd.sendRespondError(conProp,out,3,404,"File not Found",null,null);
return;
}
} catch (final Exception e) {
try {
// doing some errorhandling ...
int httpStatusCode = 400;
final String httpStatusText = null;
final StringBuffer errorMessage = new StringBuffer();
Exception errorExc = null;
final String errorMsg = e.getMessage();
if (
(e instanceof InterruptedException) ||
((errorMsg != null) && (errorMsg.startsWith("Socket closed")) && (Thread.currentThread().isInterrupted()))
) {
errorMessage.append("Interruption detected while processing query.");
httpStatusCode = 503;
} else {
if ((errorMsg != null) &&
(
errorMsg.startsWith("Broken pipe") ||
errorMsg.startsWith("Connection reset") ||
errorMsg.startsWith("Software caused connection abort")
)) {
// client closed the connection, so we just end silently
errorMessage.append("Client unexpectedly closed connection while processing query.");
} else if ((errorMsg != null) && (errorMsg.startsWith("Connection timed out"))) {
errorMessage.append("Connection timed out.");
} else {
errorMessage.append("Unexpected error while processing query.");
httpStatusCode = 500;
errorExc = e;
}
}
errorMessage.append("\nSession: ").append(Thread.currentThread().getName())
.append("\nQuery: ").append(path)
.append("\nClient: ").append(conProp.getProperty(httpHeader.CONNECTION_PROP_CLIENTIP,"unknown"))
.append("\nReason: ").append(e.toString());
if (!conProp.containsKey(httpHeader.CONNECTION_PROP_PROXY_RESPOND_HEADER)) {
// sending back an error message to the client
// if we have not already send an http header
httpd.sendRespondError(conProp,out, 4, httpStatusCode, httpStatusText, new String(errorMessage),errorExc);
} else {
// otherwise we close the connection
forceConnectionClose(conProp);
}
// if it is an unexpected error we log it
if (httpStatusCode == 500) {
theLogger.logWarning(new String(errorMessage),e);
}
} catch (final Exception ee) {
forceConnectionClose(conProp);
}
} finally {
try {out.flush();}catch (final Exception e) {}
}
}
| public static void doResponse(final Properties conProp, final httpRequestHeader requestHeader, final OutputStream out, final InputStream body) {
String path = null;
try {
// getting some connection properties
final String method = conProp.getProperty(httpHeader.CONNECTION_PROP_METHOD);
path = conProp.getProperty(httpHeader.CONNECTION_PROP_PATH);
String argsString = conProp.getProperty(httpHeader.CONNECTION_PROP_ARGS); // is null if no args were given
final String httpVersion = conProp.getProperty(httpHeader.CONNECTION_PROP_HTTP_VER);
final String clientIP = conProp.getProperty(httpHeader.CONNECTION_PROP_CLIENTIP, "unknown-host");
// check hack attacks in path
if (path.indexOf("..") >= 0) {
httpd.sendRespondError(conProp,out,4,403,null,"Access not allowed",null);
return;
}
// url decoding of path
try {
path = URLDecoder.decode(path, "UTF-8");
} catch (final UnsupportedEncodingException e) {
// This should never occur
assert(false) : "UnsupportedEncodingException: " + e.getMessage();
}
// check again hack attacks in path
if (path.indexOf("..") >= 0) {
httpd.sendRespondError(conProp,out,4,403,null,"Access not allowed",null);
return;
}
// check permission/granted access
String authorization = requestHeader.get(httpRequestHeader.AUTHORIZATION);
if (authorization != null && authorization.length() == 0) authorization = null;
final String adminAccountBase64MD5 = switchboard.getConfig(httpd.ADMIN_ACCOUNT_B64MD5, "");
int pos = path.lastIndexOf(".");
final boolean adminAccountForLocalhost = sb.getConfigBool("adminAccountForLocalhost", false);
final String refererHost = requestHeader.refererHost();
final boolean accessFromLocalhost = serverCore.isLocalhost(clientIP) && (refererHost.length() == 0 || serverCore.isLocalhost(refererHost));
final boolean grantedForLocalhost = adminAccountForLocalhost && accessFromLocalhost;
final boolean protectedPage = (path.substring(0,(pos==-1)?path.length():pos)).endsWith("_p");
final boolean accountEmpty = adminAccountBase64MD5.length() == 0;
if (!grantedForLocalhost && protectedPage && !accountEmpty) {
// authentication required
if (authorization == null) {
// no authorization given in response. Ask for that
final httpResponseHeader responseHeader = getDefaultHeaders(path);
responseHeader.put(httpRequestHeader.WWW_AUTHENTICATE,"Basic realm=\"admin log-in\"");
//httpd.sendRespondHeader(conProp,out,httpVersion,401,headers);
final servletProperties tp=new servletProperties();
tp.put("returnto", path);
//TODO: separate error page Wrong Login / No Login
httpd.sendRespondError(conProp, out, 5, 401, "Wrong Authentication", "", new File("proxymsg/authfail.inc"), tp, null, responseHeader);
return;
} else if (
(httpd.staticAdminAuthenticated(authorization.trim().substring(6), switchboard) == 4) ||
(sb.userDB.hasAdminRight(authorization, conProp.getProperty(httpHeader.CONNECTION_PROP_CLIENTIP), requestHeader.getHeaderCookies()))) {
//Authentication successful. remove brute-force flag
serverCore.bfHost.remove(conProp.getProperty(httpHeader.CONNECTION_PROP_CLIENTIP));
} else {
// a wrong authentication was given or the userDB user does not have admin access. Ask again
serverLog.logInfo("HTTPD", "Wrong log-in for account 'admin' in http file handler for path '" + path + "' from host '" + clientIP + "'");
final Integer attempts = serverCore.bfHost.get(clientIP);
if (attempts == null)
serverCore.bfHost.put(clientIP, Integer.valueOf(1));
else
serverCore.bfHost.put(clientIP, Integer.valueOf(attempts.intValue() + 1));
final httpResponseHeader headers = getDefaultHeaders(path);
headers.put(httpRequestHeader.WWW_AUTHENTICATE,"Basic realm=\"admin log-in\"");
httpd.sendRespondHeader(conProp,out,httpVersion,401,headers);
return;
}
}
// parse arguments
serverObjects args = new serverObjects();
int argc = 0;
if (argsString == null) {
// no args here, maybe a POST with multipart extension
int length = requestHeader.getContentLength();
//System.out.println("HEADER: " + requestHeader.toString()); // DEBUG
if (method.equals(httpHeader.METHOD_POST)) {
// if its a POST, it can be either multipart or as args in the body
if ((requestHeader.containsKey(httpHeader.CONTENT_TYPE)) &&
(requestHeader.get(httpHeader.CONTENT_TYPE).toLowerCase().startsWith("multipart"))) {
// parse multipart
final HashMap<String, byte[]> files = httpd.parseMultipart(requestHeader, args, body);
// integrate these files into the args
if (files != null) {
final Iterator<Map.Entry<String, byte[]>> fit = files.entrySet().iterator();
Map.Entry<String, byte[]> entry;
while (fit.hasNext()) {
entry = fit.next();
args.put(entry.getKey() + "$file", entry.getValue());
}
}
argc = Integer.parseInt(requestHeader.get("ARGC"));
} else {
// parse args in body
argc = httpd.parseArgs(args, body, length);
}
} else {
// no args
argsString = null;
args = null;
argc = 0;
}
} else {
// simple args in URL (stuff after the "?")
argc = httpd.parseArgs(args, argsString);
}
// check for cross site scripting - attacks in request arguments
if (args != null && argc > 0) {
// check all values for occurrences of script values
final Iterator<String> e = args.values().iterator(); // enumeration of values
String val;
while (e.hasNext()) {
val = e.next();
if ((val != null) && (val.indexOf("<script") >= 0)) {
// deny request
httpd.sendRespondError(conProp,out,4,403,null,"bad post values",null);
return;
}
}
}
// we are finished with parsing
// the result of value hand-over is in args and argc
if (path.length() == 0) {
httpd.sendRespondError(conProp,out,4,400,null,"Bad Request",null);
out.flush();
return;
}
File targetClass=null;
// locate the file
if (!(path.startsWith("/"))) path = "/" + path; // attach leading slash
// a different language can be desired (by i.e. ConfigBasic.html) than the one stored in the locale.language
String localeSelection = switchboard.getConfig("locale.language","default");
if (args != null && (args.containsKey("language"))) {
// TODO 9.11.06 Bost: a class with information about available languages is needed.
// the indexOf(".") is just a workaround because there from ConfigLanguage.html commes "de.lng" and
// from ConfigBasic.html comes just "de" in the "language" parameter
localeSelection = args.get("language", localeSelection);
if (localeSelection.indexOf(".") != -1)
localeSelection = localeSelection.substring(0, localeSelection.indexOf("."));
}
File targetFile = getLocalizedFile(path, localeSelection);
final String targetExt = conProp.getProperty("EXT","");
targetClass = rewriteClassFile(new File(htDefaultPath, path));
if (path.endsWith("/")) {
String testpath;
// attach default file name
for (int i = 0; i < defaultFiles.length; i++) {
testpath = path + defaultFiles[i];
targetFile = getOverlayedFile(testpath);
targetClass = getOverlayedClass(testpath);
if (targetFile.exists()) {
path = testpath;
break;
}
}
//no defaultfile, send a dirlisting
if (targetFile == null || !targetFile.exists()) {
final StringBuffer aBuffer = new StringBuffer();
aBuffer.append("<html>\n<head>\n</head>\n<body>\n<h1>Index of " + path + "</h1>\n <ul>\n");
final File dir = new File(htDocsPath, path);
String[] list = dir.list();
if (list == null) list = new String[0]; // should not occur!
File f;
String size;
long sz;
String headline, author, description;
int images, links;
htmlFilterContentScraper scraper;
for (int i = 0; i < list.length; i++) {
f = new File(dir, list[i]);
if (f.isDirectory()) {
aBuffer.append(" <li><a href=\"" + path + list[i] + "/\">" + list[i] + "/</a><br></li>\n");
} else {
if (list[i].endsWith("html") || (list[i].endsWith("htm"))) {
scraper = htmlFilterContentScraper.parseResource(f);
headline = scraper.getTitle();
author = scraper.getAuthor();
description = scraper.getDescription();
images = scraper.getImages().size();
links = scraper.getAnchors().size();
} else {
headline = null;
author = null;
description = null;
images = 0;
links = 0;
}
sz = f.length();
if (sz < 1024) {
size = sz + " bytes";
} else if (sz < 1024 * 1024) {
size = (sz / 1024) + " KB";
} else {
size = (sz / 1024 / 1024) + " MB";
}
aBuffer.append(" <li>");
if ((headline != null) && (headline.length() > 0)) aBuffer.append("<a href=\"" + list[i] + "\"><b>" + headline + "</b></a><br>");
aBuffer.append("<a href=\"" + path + list[i] + "\">" + list[i] + "</a><br>");
if ((author != null) && (author.length() > 0)) aBuffer.append("Author: " + author + "<br>");
if ((description != null) && (description.length() > 0)) aBuffer.append("Description: " + description + "<br>");
aBuffer.append(serverDate.formatShortDay(new Date(f.lastModified())) + ", " + size + ((images > 0) ? ", " + images + " images" : "") + ((links > 0) ? ", " + links + " links" : "") + "<br></li>\n");
}
}
aBuffer.append(" </ul>\n</body>\n</html>\n");
// write the list to the client
httpd.sendRespondHeader(conProp, out, httpVersion, 200, null, "text/html", aBuffer.length(), new Date(dir.lastModified()), null, new httpResponseHeader(), null, null, true);
if (!method.equals(httpHeader.METHOD_HEAD)) {
out.write(aBuffer.toString().getBytes("UTF-8"));
}
return;
}
} else {
//XXX: you cannot share a .png/.gif file with a name like a class in htroot.
if ( !(targetFile.exists()) && !((path.endsWith("png")||path.endsWith("gif")||path.endsWith(".stream"))&&targetClass!=null ) ){
targetFile = new File(htDocsPath, path);
targetClass = rewriteClassFile(new File(htDocsPath, path));
}
}
//File targetClass = rewriteClassFile(targetFile);
//We need tp here
servletProperties tp = new servletProperties();
Date targetDate;
boolean nocache = false;
if ((targetClass != null) && (path.endsWith("png"))) {
// call an image-servlet to produce an on-the-fly - generated image
Object img = null;
try {
requestHeader.put(httpHeader.CONNECTION_PROP_CLIENTIP, conProp.getProperty(httpHeader.CONNECTION_PROP_CLIENTIP));
requestHeader.put(httpHeader.CONNECTION_PROP_PATH, path);
// in case that there are no args given, args = null or empty hashmap
img = invokeServlet(targetClass, requestHeader, args);
} catch (final InvocationTargetException e) {
theLogger.logSevere("INTERNAL ERROR: " + e.toString() + ":" +
e.getMessage() +
" target exception at " + targetClass + ": " +
e.getTargetException().toString() + ":" +
e.getTargetException().getMessage() +
"; java.awt.graphicsenv='" + System.getProperty("java.awt.graphicsenv","") + "'",e);
targetClass = null;
}
if (img == null) {
// error with image generation; send file-not-found
httpd.sendRespondError(conProp, out, 3, 404, "File not Found", null, null);
} else {
if (img instanceof ymageMatrix) {
final ymageMatrix yp = (ymageMatrix) img;
// send an image to client
targetDate = new Date(System.currentTimeMillis());
nocache = true;
final String mimeType = mimeTable.getProperty(targetExt, "text/html");
final serverByteBuffer result = ymageMatrix.exportImage(yp.getImage(), targetExt);
// write the array to the client
httpd.sendRespondHeader(conProp, out, httpVersion, 200, null, mimeType, result.length(), targetDate, null, null, null, null, nocache);
if (!method.equals(httpHeader.METHOD_HEAD)) {
result.writeTo(out);
}
}
if (img instanceof Image) {
final Image i = (Image) img;
// send an image to client
targetDate = new Date(System.currentTimeMillis());
nocache = true;
final String mimeType = mimeTable.getProperty(targetExt, "text/html");
// generate an byte array from the generated image
int width = i.getWidth(null); if (width < 0) width = 96; // bad hack
int height = i.getHeight(null); if (height < 0) height = 96; // bad hack
final BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
bi.createGraphics().drawImage(i, 0, 0, width, height, null);
final serverByteBuffer result = ymageMatrix.exportImage(bi, targetExt);
// write the array to the client
httpd.sendRespondHeader(conProp, out, httpVersion, 200, null, mimeType, result.length(), targetDate, null, null, null, null, nocache);
if (!method.equals(httpHeader.METHOD_HEAD)) {
result.writeTo(out);
}
}
}
} else if ((targetClass != null) && (path.endsWith(".stream"))) {
// call rewrite-class
requestHeader.put(httpHeader.CONNECTION_PROP_CLIENTIP, conProp.getProperty(httpHeader.CONNECTION_PROP_CLIENTIP));
requestHeader.put(httpHeader.CONNECTION_PROP_PATH, path);
//requestHeader.put(httpHeader.CONNECTION_PROP_INPUTSTREAM, body);
//requestHeader.put(httpHeader.CONNECTION_PROP_OUTPUTSTREAM, out);
httpd.sendRespondHeader(conProp, out, httpVersion, 200, null);
// in case that there are no args given, args = null or empty hashmap
/* servletProperties tp = (servlerObjects) */ invokeServlet(targetClass, requestHeader, args);
forceConnectionClose(conProp);
return;
} else if ((targetFile.exists()) && (targetFile.canRead())) {
// we have found a file that can be written to the client
// if this file uses templates, then we use the template
// re-write - method to create an result
String mimeType = mimeTable.getProperty(targetExt,"text/html");
final boolean zipContent = requestHeader.acceptGzip() && httpd.shallTransportZipped("." + conProp.getProperty("EXT",""));
if (path.endsWith("html") ||
path.endsWith("htm") ||
path.endsWith("xml") ||
path.endsWith("rdf") ||
path.endsWith("rss") ||
path.endsWith("csv") ||
path.endsWith("pac") ||
path.endsWith("src") ||
path.endsWith("vcf") ||
path.endsWith("/") ||
path.equals("/robots.txt")) {
/*targetFile = getLocalizedFile(path);
if (!(targetFile.exists())) {
// try to find that file in the htDocsPath
File trialFile = new File(htDocsPath, path);
if (trialFile.exists()) targetFile = trialFile;
}*/
// call rewrite-class
if (targetClass == null) {
targetDate = new Date(targetFile.lastModified());
} else {
// CGI-class: call the class to create a property for rewriting
try {
requestHeader.put(httpHeader.CONNECTION_PROP_CLIENTIP, conProp.getProperty(httpHeader.CONNECTION_PROP_CLIENTIP));
requestHeader.put(httpHeader.CONNECTION_PROP_PATH, path);
// in case that there are no args given, args = null or empty hashmap
final Object tmp = invokeServlet(targetClass, requestHeader, args);
if (tmp == null) {
// if no args given, then tp will be an empty Hashtable object (not null)
tp = new servletProperties();
} else if (tmp instanceof servletProperties) {
tp = (servletProperties) tmp;
} else {
tp = new servletProperties((serverObjects) tmp);
}
// check if the servlets requests authentification
if (tp.containsKey(servletProperties.ACTION_AUTHENTICATE)) {
// handle brute-force protection
if (authorization != null) {
serverLog.logInfo("HTTPD", "dynamic log-in for account 'admin' in http file handler for path '" + path + "' from host '" + clientIP + "'");
final Integer attempts = serverCore.bfHost.get(clientIP);
if (attempts == null)
serverCore.bfHost.put(clientIP, Integer.valueOf(1));
else
serverCore.bfHost.put(clientIP, Integer.valueOf(attempts.intValue() + 1));
}
// send authentication request to browser
final httpResponseHeader headers = getDefaultHeaders(path);
headers.put(httpRequestHeader.WWW_AUTHENTICATE,"Basic realm=\"" + tp.get(servletProperties.ACTION_AUTHENTICATE, "") + "\"");
httpd.sendRespondHeader(conProp,out,httpVersion,401,headers);
return;
} else if (tp.containsKey(servletProperties.ACTION_LOCATION)) {
String location = tp.get(servletProperties.ACTION_LOCATION, "");
if (location.length() == 0) location = path;
final httpResponseHeader headers = getDefaultHeaders(path);
headers.setCookieVector(tp.getOutgoingHeader().getCookieVector()); //put the cookies into the new header TODO: can we put all headerlines, without trouble?
headers.put(httpHeader.LOCATION,location);
httpd.sendRespondHeader(conProp,out,httpVersion,302,headers);
return;
}
// add the application version, the uptime and the client name to every rewrite table
tp.put(servletProperties.PEER_STAT_VERSION, switchboard.getConfig("version", ""));
tp.put(servletProperties.PEER_STAT_UPTIME, ((System.currentTimeMillis() - serverCore.startupTime) / 1000) / 60); // uptime in minutes
tp.putHTML(servletProperties.PEER_STAT_CLIENTNAME, switchboard.getConfig("peerName", "anomic"));
tp.put(servletProperties.PEER_STAT_MYTIME, serverDate.formatShortSecond());
//System.out.println("respond props: " + ((tp == null) ? "null" : tp.toString())); // debug
} catch (final InvocationTargetException e) {
if (e.getCause() instanceof InterruptedException) {
throw new InterruptedException(e.getCause().getMessage());
}
theLogger.logSevere("INTERNAL ERROR: " + e.toString() + ":" +
e.getMessage() +
" target exception at " + targetClass + ": " +
e.getTargetException().toString() + ":" +
e.getTargetException().getMessage(),e);
targetClass = null;
throw e;
}
targetDate = new Date(System.currentTimeMillis());
nocache = true;
}
// rewrite the file
InputStream fis = null;
// read the file/template
byte[] templateContent = null;
if (useTemplateCache) {
final long fileSize = targetFile.length();
if (fileSize <= 512 * 1024) {
// read from cache
SoftReference<byte[]> ref = templateCache.get(targetFile);
if (ref != null) {
templateContent = ref.get();
if (templateContent == null) templateCache.remove(targetFile);
}
if (templateContent == null) {
// loading the content of the template file into
// a byte array
templateContent = serverFileUtils.read(targetFile);
// storing the content into the cache
ref = new SoftReference<byte[]>(templateContent);
templateCache.put(targetFile, ref);
if (theLogger.isFinest()) theLogger.logFinest("Cache MISS for file " + targetFile);
} else {
if (theLogger.isFinest()) theLogger.logFinest("Cache HIT for file " + targetFile);
}
// creating an inputstream needed by the template
// rewrite function
fis = new ByteArrayInputStream(templateContent);
templateContent = null;
} else {
// read from file directly
fis = new BufferedInputStream(new FileInputStream(targetFile));
}
} else {
fis = new BufferedInputStream(new FileInputStream(targetFile));
}
if(mimeType.startsWith("text")) {
// every text-file distributed by yacy is UTF-8
if(!path.startsWith("/repository")) {
mimeType = mimeType + "; charset=UTF-8";
} else {
// detect charset of html-files
if((path.endsWith("html") || path.endsWith("htm"))) {
// save position
fis.mark(1000);
// scrape document to look up charset
final htmlFilterInputStream htmlFilter = new htmlFilterInputStream(fis,"UTF-8",new yacyURL("http://localhost", null),null,false);
final String charset = plasmaParser.patchCharsetEncoding(htmlFilter.detectCharset());
if(charset != null)
mimeType = mimeType + "; charset="+charset;
// reset position
fis.reset();
}
}
}
// write the array to the client
// we can do that either in standard mode (whole thing completely) or in chunked mode
// since yacy clients do not understand chunked mode (yet), we use this only for communication with the administrator
final boolean yacyClient = requestHeader.userAgent().startsWith("yacy");
final boolean chunked = !method.equals(httpHeader.METHOD_HEAD) && !yacyClient && httpVersion.equals(httpHeader.HTTP_VERSION_1_1);
if (chunked) {
// send page in chunks and parse SSIs
final serverByteBuffer o = new serverByteBuffer();
// apply templates
httpTemplate.writeTemplate(fis, o, tp, "-UNRESOLVED_PATTERN-".getBytes("UTF-8"));
httpd.sendRespondHeader(conProp, out, httpVersion, 200, null, mimeType, -1, targetDate, null, tp.getOutgoingHeader(), null, "chunked", nocache);
// send the content in chunked parts, see RFC 2616 section 3.6.1
final httpChunkedOutputStream chos = new httpChunkedOutputStream(out);
httpSSI.writeSSI(o, chos, authorization, clientIP);
//chos.write(result);
chos.finish();
} else {
// send page as whole thing, SSIs are not possible
final String contentEncoding = (zipContent) ? "gzip" : null;
// apply templates
final serverByteBuffer o1 = new serverByteBuffer();
httpTemplate.writeTemplate(fis, o1, tp, "-UNRESOLVED_PATTERN-".getBytes("UTF-8"));
final serverByteBuffer o = new serverByteBuffer();
if (zipContent) {
GZIPOutputStream zippedOut = new GZIPOutputStream(o);
httpSSI.writeSSI(o1, zippedOut, authorization, clientIP);
//httpTemplate.writeTemplate(fis, zippedOut, tp, "-UNRESOLVED_PATTERN-".getBytes("UTF-8"));
zippedOut.finish();
zippedOut.flush();
zippedOut.close();
zippedOut = null;
} else {
httpSSI.writeSSI(o1, o, authorization, clientIP);
//httpTemplate.writeTemplate(fis, o, tp, "-UNRESOLVED_PATTERN-".getBytes("UTF-8"));
}
if (method.equals(httpHeader.METHOD_HEAD)) {
httpd.sendRespondHeader(conProp, out,
httpVersion, 200, null, mimeType, o.length(),
targetDate, null, tp.getOutgoingHeader(),
contentEncoding, null, nocache);
} else {
final byte[] result = o.getBytes(); // this interrupts streaming (bad idea!)
httpd.sendRespondHeader(conProp, out,
httpVersion, 200, null, mimeType, result.length,
targetDate, null, tp.getOutgoingHeader(),
contentEncoding, null, nocache);
serverFileUtils.copy(result, out);
}
}
} else { // no html
int statusCode = 200;
int rangeStartOffset = 0;
httpResponseHeader header = new httpResponseHeader();
// adding the accept ranges header
header.put(httpHeader.ACCEPT_RANGES, "bytes");
// reading the files md5 hash if availabe and use it as ETAG of the resource
String targetMD5 = null;
final File targetMd5File = new File(targetFile + ".md5");
try {
if (targetMd5File.exists()) {
//String description = null;
targetMD5 = new String(serverFileUtils.read(targetMd5File));
pos = targetMD5.indexOf('\n');
if (pos >= 0) {
//description = targetMD5.substring(pos + 1);
targetMD5 = targetMD5.substring(0, pos);
}
// using the checksum as ETAG header
header.put(httpHeader.ETAG, targetMD5);
}
} catch (final IOException e) {
e.printStackTrace();
}
if (requestHeader.containsKey(httpHeader.RANGE)) {
final Object ifRange = requestHeader.ifRange();
if ((ifRange == null)||
(ifRange instanceof Date && targetFile.lastModified() == ((Date)ifRange).getTime()) ||
(ifRange instanceof String && ifRange.equals(targetMD5))) {
final String rangeHeaderVal = requestHeader.get(httpHeader.RANGE).trim();
if (rangeHeaderVal.startsWith("bytes=")) {
final String rangesVal = rangeHeaderVal.substring("bytes=".length());
final String[] ranges = rangesVal.split(",");
if ((ranges.length == 1)&&(ranges[0].endsWith("-"))) {
rangeStartOffset = Integer.valueOf(ranges[0].substring(0,ranges[0].length()-1)).intValue();
statusCode = 206;
if (header == null) header = new httpResponseHeader();
header.put(httpHeader.CONTENT_RANGE, "bytes " + rangeStartOffset + "-" + (targetFile.length()-1) + "/" + targetFile.length());
}
}
}
}
// write the file to the client
targetDate = new Date(targetFile.lastModified());
final long contentLength = (zipContent)?-1:targetFile.length()-rangeStartOffset;
final String contentEncoding = (zipContent)?"gzip":null;
final String transferEncoding = (!httpVersion.equals(httpHeader.HTTP_VERSION_1_1))?null:(zipContent)?"chunked":null;
if (!httpVersion.equals(httpHeader.HTTP_VERSION_1_1) && zipContent) forceConnectionClose(conProp);
httpd.sendRespondHeader(conProp, out, httpVersion, statusCode, null, mimeType, contentLength, targetDate, null, header, contentEncoding, transferEncoding, nocache);
if (!method.equals(httpHeader.METHOD_HEAD)) {
httpChunkedOutputStream chunkedOut = null;
GZIPOutputStream zipped = null;
OutputStream newOut = out;
if (transferEncoding != null) {
chunkedOut = new httpChunkedOutputStream(newOut);
newOut = chunkedOut;
}
if (contentEncoding != null) {
zipped = new GZIPOutputStream(newOut);
newOut = zipped;
}
serverFileUtils.copyRange(targetFile, newOut, rangeStartOffset);
if (zipped != null) {
zipped.flush();
zipped.finish();
}
if (chunkedOut != null) {
chunkedOut.finish();
}
// flush all
try {newOut.flush();}catch (final Exception e) {}
// wait a little time until everything closes so that clients can read from the streams/sockets
if ((contentLength >= 0) && ((String)requestHeader.get(httpRequestHeader.CONNECTION, "close")).indexOf("keep-alive") == -1) {
// in case that the client knows the size in advance (contentLength present) the waiting will have no effect on the interface performance
// but if the client waits on a connection interruption this will slow down.
try {Thread.sleep(2000);} catch (final InterruptedException e) {} // FIXME: is this necessary?
}
}
// check mime type again using the result array: these are 'magics'
// if (serverByteBuffer.equals(result, 1, "PNG".getBytes())) mimeType = mimeTable.getProperty("png","text/html");
// else if (serverByteBuffer.equals(result, 0, "GIF89".getBytes())) mimeType = mimeTable.getProperty("gif","text/html");
// else if (serverByteBuffer.equals(result, 6, "JFIF".getBytes())) mimeType = mimeTable.getProperty("jpg","text/html");
//System.out.print("MAGIC:"); for (int i = 0; i < 10; i++) System.out.print(Integer.toHexString((int) result[i]) + ","); System.out.println();
}
} else {
httpd.sendRespondError(conProp,out,3,404,"File not Found",null,null);
return;
}
} catch (final Exception e) {
try {
// doing some errorhandling ...
int httpStatusCode = 400;
final String httpStatusText = null;
final StringBuffer errorMessage = new StringBuffer();
Exception errorExc = null;
final String errorMsg = e.getMessage();
if (
(e instanceof InterruptedException) ||
((errorMsg != null) && (errorMsg.startsWith("Socket closed")) && (Thread.currentThread().isInterrupted()))
) {
errorMessage.append("Interruption detected while processing query.");
httpStatusCode = 503;
} else {
if ((errorMsg != null) &&
(
errorMsg.startsWith("Broken pipe") ||
errorMsg.startsWith("Connection reset") ||
errorMsg.startsWith("Software caused connection abort")
)) {
// client closed the connection, so we just end silently
errorMessage.append("Client unexpectedly closed connection while processing query.");
} else if ((errorMsg != null) && (errorMsg.startsWith("Connection timed out"))) {
errorMessage.append("Connection timed out.");
} else {
errorMessage.append("Unexpected error while processing query.");
httpStatusCode = 500;
errorExc = e;
}
}
errorMessage.append("\nSession: ").append(Thread.currentThread().getName())
.append("\nQuery: ").append(path)
.append("\nClient: ").append(conProp.getProperty(httpHeader.CONNECTION_PROP_CLIENTIP,"unknown"))
.append("\nReason: ").append(e.toString());
if (!conProp.containsKey(httpHeader.CONNECTION_PROP_PROXY_RESPOND_HEADER)) {
// sending back an error message to the client
// if we have not already send an http header
httpd.sendRespondError(conProp,out, 4, httpStatusCode, httpStatusText, new String(errorMessage),errorExc);
} else {
// otherwise we close the connection
forceConnectionClose(conProp);
}
// if it is an unexpected error we log it
if (httpStatusCode == 500) {
theLogger.logWarning(new String(errorMessage),e);
}
} catch (final Exception ee) {
forceConnectionClose(conProp);
}
} finally {
try {out.flush();}catch (final Exception e) {}
}
}
|
diff --git a/runtime/ceylon/language/count.java b/runtime/ceylon/language/count.java
index 98e0f82f..6538c1e8 100644
--- a/runtime/ceylon/language/count.java
+++ b/runtime/ceylon/language/count.java
@@ -1,28 +1,28 @@
package ceylon.language;
import com.redhat.ceylon.compiler.java.metadata.Ceylon;
import com.redhat.ceylon.compiler.java.metadata.Method;
import com.redhat.ceylon.compiler.java.metadata.Name;
import com.redhat.ceylon.compiler.java.metadata.Sequenced;
import com.redhat.ceylon.compiler.java.metadata.TypeInfo;
@Ceylon(major = 1)
@Method
public final class count {
private count() {
}
@TypeInfo("ceylon.language.Integer")
public static long count(@Name("values") @Sequenced
@TypeInfo("ceylon.language.Iterable<ceylon.language.Boolean>")
final Iterable<? extends Boolean> values) {
long count=0;
java.lang.Object $tmp;
for (Iterator<? extends Boolean> $val$iter$0 = values.getIterator();
!(($tmp = $val$iter$0.next()) instanceof Finished);) {
- if (!((Boolean)$tmp).booleanValue()) count++;
+ if (((Boolean)$tmp).booleanValue()) count++;
}
return count;
}
}
| true | true | public static long count(@Name("values") @Sequenced
@TypeInfo("ceylon.language.Iterable<ceylon.language.Boolean>")
final Iterable<? extends Boolean> values) {
long count=0;
java.lang.Object $tmp;
for (Iterator<? extends Boolean> $val$iter$0 = values.getIterator();
!(($tmp = $val$iter$0.next()) instanceof Finished);) {
if (!((Boolean)$tmp).booleanValue()) count++;
}
return count;
}
| public static long count(@Name("values") @Sequenced
@TypeInfo("ceylon.language.Iterable<ceylon.language.Boolean>")
final Iterable<? extends Boolean> values) {
long count=0;
java.lang.Object $tmp;
for (Iterator<? extends Boolean> $val$iter$0 = values.getIterator();
!(($tmp = $val$iter$0.next()) instanceof Finished);) {
if (((Boolean)$tmp).booleanValue()) count++;
}
return count;
}
|
diff --git a/runtime/org.eclipse.emf.texo.server/src/org/eclipse/emf/texo/server/store/EntityManagerProvider.java b/runtime/org.eclipse.emf.texo.server/src/org/eclipse/emf/texo/server/store/EntityManagerProvider.java
index 20077191..75d0725f 100644
--- a/runtime/org.eclipse.emf.texo.server/src/org/eclipse/emf/texo/server/store/EntityManagerProvider.java
+++ b/runtime/org.eclipse.emf.texo.server/src/org/eclipse/emf/texo/server/store/EntityManagerProvider.java
@@ -1,202 +1,202 @@
/**
* <copyright>
*
* Copyright (c) 2011 Springsite BV (The Netherlands) and others
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Martin Taal - Initial API and implementation
*
* </copyright>
*
* $Id: EntityManagerProvider.java,v 1.7 2011/09/26 19:48:10 mtaal Exp $
*/
package org.eclipse.emf.texo.server.store;
import java.util.HashMap;
import java.util.Map;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import org.eclipse.emf.texo.component.ComponentProvider;
import org.eclipse.emf.texo.component.TexoComponent;
import org.eclipse.emf.texo.component.TexoStaticSingleton;
/**
* Class which provides an entity manager.
*
* @author <a href="[email protected]">Martin Taal</a>
*/
public class EntityManagerProvider implements TexoComponent, TexoStaticSingleton {
public static final String ECLIPSELINK_CLASSLOADER_OPTION = "eclipselink.classloader"; //$NON-NLS-1$
public static final String MULTITENANT_PROPERTY_DEFAULT = "eclipselink.tenant-id"; //$NON-NLS-1$
private static EntityManagerProvider instance = ComponentProvider.getInstance().newInstance(
EntityManagerProvider.class);
public static EntityManagerProvider getInstance() {
return instance;
}
public static void setInstance(EntityManagerProvider entityManagerProvider) {
instance = entityManagerProvider;
}
private ThreadLocal<EntityManager> currentEntityManager = new ThreadLocal<EntityManager>();
private EntityManagerFactory entityManagerFactory;
private String persistenceUnitName;
private Map<Object, Object> persistenceOptions = new HashMap<Object, Object>();
private boolean useCurrentEntityManagerPattern = false;
/**
* Creates the internally used {@link EntityManagerFactory} if it is not already set. It uses the persistenceUnitName
* (and if set the persistenceOptions).
*
* Is called automatically when retrieving an {@link EntityManager} through the {@link #getEntityManager()} method.
*/
public void initialize() {
if (entityManagerFactory != null) {
return;
}
if (persistenceOptions != null) {
if (!persistenceOptions.containsKey(ECLIPSELINK_CLASSLOADER_OPTION)) {
persistenceOptions.put(ECLIPSELINK_CLASSLOADER_OPTION, EntityManagerProvider.class.getClassLoader());
}
- persistenceOptions.put(MULTITENANT_PROPERTY_DEFAULT, "texo");
+ persistenceOptions.put(MULTITENANT_PROPERTY_DEFAULT, "texo"); //$NON-NLS-1$
entityManagerFactory = Persistence.createEntityManagerFactory(persistenceUnitName, persistenceOptions);
} else {
entityManagerFactory = Persistence.createEntityManagerFactory(persistenceUnitName);
}
}
/**
* This method should return a new {@link EntityManager} instance. It is called once for each request at the beginning
* of the processing of a request.
*
* @see #releaseEntityManager(EntityManager)
*/
public EntityManager createEntityManager() {
initialize();
return entityManagerFactory.createEntityManager();
}
/**
* If {@link #isUseCurrentEntityManagerPattern()} is true then the entity manager stored in a threadlocal is returned
* (see {@link #getCurrentEntityManager()}), otherwise always a new entity manager is returned (see
* {@link #createEntityManager()}.
*/
public EntityManager getEntityManager() {
if (isUseCurrentEntityManagerPattern()) {
return getCurrentEntityManager();
}
return createEntityManager();
}
/**
* Maintains an {@link EntityManager} in a ThreadLocal. Will check a {@link ThreadLocal} to see if an EntityManager is
* present there. If not, one is created, set in the ThreadLocal and returned.
*
* When an EntityManager is created this method automatically begins a transaction also!
*
* When finished with the entity manager, at the end of the Thread call
* {@link EntityManagerProvider#clearCurrentEntityManager()}.
*
* Note that it is especially important in servlet environments to clear the entity manager at the end of the request
* as Tomcat and maybe other servlet containers will re-use thread objects for subsequent requests.
*
* @return a new {@link EntityManager} or the {@link EntityManager} currently stored in the thread if there is one
*/
public EntityManager getCurrentEntityManager() {
if (currentEntityManager.get() != null) {
return currentEntityManager.get();
}
currentEntityManager.set(createEntityManager());
currentEntityManager.get().getTransaction().begin();
return currentEntityManager.get();
}
/**
* Set the entity manager in the thread local, if there is a current entity manager in the threadlocal then it is
* closed before the new one is set.
*
* @see #getCurrentEntityManager()
*/
public void setCurrentEntityManager(EntityManager entityManager) {
if (currentEntityManager.get() != null) {
currentEntityManager.get().close();
}
currentEntityManager.set(entityManager);
}
/**
* Clears the entity manager from the current thread and closes it if this was not already done.
*/
public void clearCurrentEntityManager() {
if (currentEntityManager.get() != null) {
if (currentEntityManager.get().isOpen()) {
currentEntityManager.get().close();
}
currentEntityManager.set(null);
}
}
/**
* @return true if there is an EntityManager in the current thread.
*/
public boolean hasCurrentEntityManager() {
return null != currentEntityManager.get();
}
/**
* Can be used to close/release an entity manager. Is called when the entity manager can be closed. It will also be
* called if the processing resulted in errors/exceptions.
*
* The default implementation calls {@link EntityManager#close()}.
*
* @param entityManager
*/
public void releaseEntityManager(EntityManager entityManager) {
if (entityManager.isOpen()) {
entityManager.close();
}
}
public EntityManagerFactory getEntityManagerFactory() {
return entityManagerFactory;
}
public void setEntityManagerFactory(EntityManagerFactory entityManagerFactory) {
this.entityManagerFactory = entityManagerFactory;
}
public String getPersistenceUnitName() {
return persistenceUnitName;
}
public void setPersistenceUnitName(String persistenceUnitName) {
this.persistenceUnitName = persistenceUnitName;
}
public Map<Object, Object> getPersistenceOptions() {
return persistenceOptions;
}
public void setPersistenceOptions(Map<Object, Object> persistenceOptions) {
this.persistenceOptions = persistenceOptions;
}
public boolean isUseCurrentEntityManagerPattern() {
return useCurrentEntityManagerPattern;
}
public void setUseCurrentEntityManagerPattern(boolean useCurrentEntityManagerPattern) {
this.useCurrentEntityManagerPattern = useCurrentEntityManagerPattern;
}
}
| true | true | public void initialize() {
if (entityManagerFactory != null) {
return;
}
if (persistenceOptions != null) {
if (!persistenceOptions.containsKey(ECLIPSELINK_CLASSLOADER_OPTION)) {
persistenceOptions.put(ECLIPSELINK_CLASSLOADER_OPTION, EntityManagerProvider.class.getClassLoader());
}
persistenceOptions.put(MULTITENANT_PROPERTY_DEFAULT, "texo");
entityManagerFactory = Persistence.createEntityManagerFactory(persistenceUnitName, persistenceOptions);
} else {
entityManagerFactory = Persistence.createEntityManagerFactory(persistenceUnitName);
}
}
| public void initialize() {
if (entityManagerFactory != null) {
return;
}
if (persistenceOptions != null) {
if (!persistenceOptions.containsKey(ECLIPSELINK_CLASSLOADER_OPTION)) {
persistenceOptions.put(ECLIPSELINK_CLASSLOADER_OPTION, EntityManagerProvider.class.getClassLoader());
}
persistenceOptions.put(MULTITENANT_PROPERTY_DEFAULT, "texo"); //$NON-NLS-1$
entityManagerFactory = Persistence.createEntityManagerFactory(persistenceUnitName, persistenceOptions);
} else {
entityManagerFactory = Persistence.createEntityManagerFactory(persistenceUnitName);
}
}
|
diff --git a/src/update/UpdateManager.java b/src/update/UpdateManager.java
index f4d67c6..f39be07 100644
--- a/src/update/UpdateManager.java
+++ b/src/update/UpdateManager.java
@@ -1,119 +1,121 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package update;
import game.Game;
import game.GameObject;
import game.StandardManager;
import java.util.ArrayList;
import java.util.Iterator;
import org.lwjgl.Sys;
import util.DebugMessages;
/**
*
* @author Andy
*/
public class UpdateManager extends StandardManager implements Runnable {
long lastTime;
ArrayList<Updateable> entities;
private long updateTime;
private Thread updateThread;
static final int defaultUpdateTime = 1000 / 60;
static UpdateManager instance;
@Override
public void create() {
super.create();
updateThread = new Thread(this);
this.updateTime = defaultUpdateTime;
lastTime = getTime();
entities = new ArrayList<Updateable>();
}
@Override
public void destroy() {
super.destroy();
try {
updateThread.join();
} catch (Exception e) {
e.printStackTrace();
}
}
public static UpdateManager getInstance() {
if(instance == null) {
instance = new UpdateManager();
}
return instance;
}
public void start() {
updateThread.start();
}
@Override
public void run() {
while (Game.isRunning()) {
DebugMessages.getInstance().write("UpdateManager Running");
long currentTime = getTime();
long deltaTime = currentTime - lastTime;
update((int) deltaTime);
lastTime = currentTime;
try {
Thread.sleep(updateTime);
} catch (Exception e) {
e.printStackTrace();
}
}
}
public void update(int delta) {
DebugMessages.getInstance().write("Delta: " + delta + " FPS: " + (1000 / delta));
DebugMessages.getInstance().write("Updates starting");
input.InputManager.getInstance().processInputs();
- Iterator<Updateable> iter = entities.iterator();
- while (iter.hasNext()) {
- Updateable e = iter.next();
- boolean remove = e.update(delta);
- if (remove) {
- iter.remove();
+ ArrayList<Updateable> copy = new ArrayList<Updateable>(entities);
+ ArrayList<Updateable> toRemove = new ArrayList<Updateable>();
+ for(Updateable u : copy) {
+ if(u.update(delta)) {
+ toRemove.add(u);
}
}
+ for(Updateable u : toRemove) {
+ remove(u);
+ }
DebugMessages.getInstance().write("Updates finished");
}
public static long getTime() {
return (Sys.getTime() * 1000) / Sys.getTimerResolution();
}
@Override
public boolean add(GameObject obj) {
if (obj instanceof Updateable) {
entities.add((Updateable)obj);
return true;
}
return false;
}
@Override
public void remove(GameObject obj) {
if(entities.contains(obj)) {
entities.remove(obj);
}
}
public void remove(Updateable obj) {
if (entities.contains(obj)) {
entities.remove(obj);
}
}
}
| false | true | public void update(int delta) {
DebugMessages.getInstance().write("Delta: " + delta + " FPS: " + (1000 / delta));
DebugMessages.getInstance().write("Updates starting");
input.InputManager.getInstance().processInputs();
Iterator<Updateable> iter = entities.iterator();
while (iter.hasNext()) {
Updateable e = iter.next();
boolean remove = e.update(delta);
if (remove) {
iter.remove();
}
}
DebugMessages.getInstance().write("Updates finished");
}
| public void update(int delta) {
DebugMessages.getInstance().write("Delta: " + delta + " FPS: " + (1000 / delta));
DebugMessages.getInstance().write("Updates starting");
input.InputManager.getInstance().processInputs();
ArrayList<Updateable> copy = new ArrayList<Updateable>(entities);
ArrayList<Updateable> toRemove = new ArrayList<Updateable>();
for(Updateable u : copy) {
if(u.update(delta)) {
toRemove.add(u);
}
}
for(Updateable u : toRemove) {
remove(u);
}
DebugMessages.getInstance().write("Updates finished");
}
|
diff --git a/bennu-plugin/src/main/java/pt/ist/bennu/plugin/BennuMojo.java b/bennu-plugin/src/main/java/pt/ist/bennu/plugin/BennuMojo.java
index a56fa276..3e8f59e0 100644
--- a/bennu-plugin/src/main/java/pt/ist/bennu/plugin/BennuMojo.java
+++ b/bennu-plugin/src/main/java/pt/ist/bennu/plugin/BennuMojo.java
@@ -1,140 +1,139 @@
package pt.ist.bennu.plugin;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import org.apache.commons.io.FileUtils;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.model.Resource;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.project.MavenProject;
import org.codehaus.plexus.util.DirectoryScanner;
import org.codehaus.plexus.util.StringUtils;
/**
* Generate base classes from the DML files
*
* @goal update-web-fragment
*
* @phase generate-sources
*
* @requiresDependencyResolution runtime
*/
public class BennuMojo extends AbstractMojo {
private static final String OPEN_NAME_TAG = "<name>";
private static final String CLOSE_NAME_TAG = "</name>";
private static final String NEW_LINE_CHAR = "\n";
private static final String TEMPLATE_START = "<!-- [START OF BENNU GENERATED FRAGMENT] -->";
private static final String TEMPLATE_END = "<!-- [END OF BENNU GENERATED FRAGMENT] -->";
/**
* Maven Project
*
* @parameter default-value="${project}"
*/
private MavenProject mavenProject;
/**
* web-fragment.xml file
*
* @parameter expression="${webFragment}"
* default-value="${basedir}/src/main/resources/META-INF/web-fragment.xml"
*/
private File webFragment;
@Override
public void execute() throws MojoExecutionException {
if (mavenProject.getArtifact().getType().equals("pom"))
return;
try {
if (webFragment.exists()) {
String template = FileUtils.readFileToString(webFragment);
int start = template.indexOf(TEMPLATE_START);
int numSpaces = getIndentation(template, start);
if (start != -1) {
int end = template.indexOf(TEMPLATE_END, start);
if (end != -1) {
try (PrintWriter printWriter = new PrintWriter(webFragment)) {
printWriter.append(template.substring(0, start + TEMPLATE_START.length()));
printWriter.append(NEW_LINE_CHAR);
printWriter.append(getModuleDependenciesAsStrings(numSpaces));
printWriter.append(template.substring(end));
}
} else {
throw new MojoExecutionException("Missing template end comment: " + TEMPLATE_END);
}
} else {
throw new MojoExecutionException("Missing template start comment: " + TEMPLATE_START);
}
} else {
- throw new MojoExecutionException("File: " + webFragment.getAbsolutePath()
- + " not found. No depency injection could be made");
+ getLog().info("File: " + webFragment.getAbsolutePath() + " not found. No depency injection could be made");
}
} catch (IOException e) {
throw new MojoExecutionException(null, e);
}
List<Resource> resources = mavenProject.getResources();
StringBuilder messages = new StringBuilder();
for (Resource resource : resources) {
DirectoryScanner scanner = new DirectoryScanner();
scanner.setBasedir(resource.getDirectory());
scanner.setIncludes(new String[] { "resources/*.properties" });
scanner.scan();
for (String resourceFile : scanner.getIncludedFiles()) {
if (!resourceFile.contains("_")) {
messages.append(resourceFile.substring("resources/".length(), resourceFile.length() - ".properties".length()));
messages.append("\n");
}
}
}
String output = mavenProject.getBuild().getOutputDirectory() + File.separatorChar + mavenProject.getArtifactId()
+ File.separatorChar + ".messageResources";
try {
FileUtils.writeStringToFile(new File(output), messages.toString(), "UTF-8");
} catch (IOException e) {
throw new MojoExecutionException(null, e);
}
}
public String getModuleDependenciesAsStrings(int indentation) throws MojoExecutionException {
StringBuilder stringBuilder = new StringBuilder();
String indentSpace = StringUtils.repeat(" ", indentation - 1);
for (Artifact artifact : mavenProject.getArtifacts()) {
if (isWebModule(artifact)) {
stringBuilder.append(indentSpace);
stringBuilder.append(OPEN_NAME_TAG);
stringBuilder.append(artifact.getArtifactId());
stringBuilder.append(CLOSE_NAME_TAG);
stringBuilder.append(NEW_LINE_CHAR);
}
}
stringBuilder.append(indentSpace);
return stringBuilder.toString();
}
public boolean isWebModule(Artifact artifact) throws MojoExecutionException {
if (artifact.getType().equals("pom")) {
return false;
}
try (JarFile artifactJar = new JarFile(artifact.getFile())) {
JarEntry webFragmentFile = artifactJar.getJarEntry("META-INF/web-fragment.xml");
return webFragmentFile != null;
} catch (IOException ex) {
throw new MojoExecutionException("Could not load jar file from artifact");
}
}
private int getIndentation(String template, int i) {
return i - template.lastIndexOf(NEW_LINE_CHAR, i);
}
}
| true | true | public void execute() throws MojoExecutionException {
if (mavenProject.getArtifact().getType().equals("pom"))
return;
try {
if (webFragment.exists()) {
String template = FileUtils.readFileToString(webFragment);
int start = template.indexOf(TEMPLATE_START);
int numSpaces = getIndentation(template, start);
if (start != -1) {
int end = template.indexOf(TEMPLATE_END, start);
if (end != -1) {
try (PrintWriter printWriter = new PrintWriter(webFragment)) {
printWriter.append(template.substring(0, start + TEMPLATE_START.length()));
printWriter.append(NEW_LINE_CHAR);
printWriter.append(getModuleDependenciesAsStrings(numSpaces));
printWriter.append(template.substring(end));
}
} else {
throw new MojoExecutionException("Missing template end comment: " + TEMPLATE_END);
}
} else {
throw new MojoExecutionException("Missing template start comment: " + TEMPLATE_START);
}
} else {
throw new MojoExecutionException("File: " + webFragment.getAbsolutePath()
+ " not found. No depency injection could be made");
}
} catch (IOException e) {
throw new MojoExecutionException(null, e);
}
List<Resource> resources = mavenProject.getResources();
StringBuilder messages = new StringBuilder();
for (Resource resource : resources) {
DirectoryScanner scanner = new DirectoryScanner();
scanner.setBasedir(resource.getDirectory());
scanner.setIncludes(new String[] { "resources/*.properties" });
scanner.scan();
for (String resourceFile : scanner.getIncludedFiles()) {
if (!resourceFile.contains("_")) {
messages.append(resourceFile.substring("resources/".length(), resourceFile.length() - ".properties".length()));
messages.append("\n");
}
}
}
String output = mavenProject.getBuild().getOutputDirectory() + File.separatorChar + mavenProject.getArtifactId()
+ File.separatorChar + ".messageResources";
try {
FileUtils.writeStringToFile(new File(output), messages.toString(), "UTF-8");
} catch (IOException e) {
throw new MojoExecutionException(null, e);
}
}
| public void execute() throws MojoExecutionException {
if (mavenProject.getArtifact().getType().equals("pom"))
return;
try {
if (webFragment.exists()) {
String template = FileUtils.readFileToString(webFragment);
int start = template.indexOf(TEMPLATE_START);
int numSpaces = getIndentation(template, start);
if (start != -1) {
int end = template.indexOf(TEMPLATE_END, start);
if (end != -1) {
try (PrintWriter printWriter = new PrintWriter(webFragment)) {
printWriter.append(template.substring(0, start + TEMPLATE_START.length()));
printWriter.append(NEW_LINE_CHAR);
printWriter.append(getModuleDependenciesAsStrings(numSpaces));
printWriter.append(template.substring(end));
}
} else {
throw new MojoExecutionException("Missing template end comment: " + TEMPLATE_END);
}
} else {
throw new MojoExecutionException("Missing template start comment: " + TEMPLATE_START);
}
} else {
getLog().info("File: " + webFragment.getAbsolutePath() + " not found. No depency injection could be made");
}
} catch (IOException e) {
throw new MojoExecutionException(null, e);
}
List<Resource> resources = mavenProject.getResources();
StringBuilder messages = new StringBuilder();
for (Resource resource : resources) {
DirectoryScanner scanner = new DirectoryScanner();
scanner.setBasedir(resource.getDirectory());
scanner.setIncludes(new String[] { "resources/*.properties" });
scanner.scan();
for (String resourceFile : scanner.getIncludedFiles()) {
if (!resourceFile.contains("_")) {
messages.append(resourceFile.substring("resources/".length(), resourceFile.length() - ".properties".length()));
messages.append("\n");
}
}
}
String output = mavenProject.getBuild().getOutputDirectory() + File.separatorChar + mavenProject.getArtifactId()
+ File.separatorChar + ".messageResources";
try {
FileUtils.writeStringToFile(new File(output), messages.toString(), "UTF-8");
} catch (IOException e) {
throw new MojoExecutionException(null, e);
}
}
|
diff --git a/clitest/src/main/java/com/redhat/qe/jon/clitest/base/CliEngine.java b/clitest/src/main/java/com/redhat/qe/jon/clitest/base/CliEngine.java
index 970d04d9..27fc14af 100644
--- a/clitest/src/main/java/com/redhat/qe/jon/clitest/base/CliEngine.java
+++ b/clitest/src/main/java/com/redhat/qe/jon/clitest/base/CliEngine.java
@@ -1,399 +1,399 @@
package com.redhat.qe.jon.clitest.base;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.Enumeration;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.commons.lang3.StringUtils;
import org.testng.annotations.AfterTest;
import org.testng.annotations.Optional;
import com.redhat.qe.jon.clitest.tasks.CliTasks;
import com.redhat.qe.jon.clitest.tasks.CliTasksException;
public class CliEngine extends CliTestScript{
private static Logger _logger = Logger.getLogger(CliEngine.class.getName());
public static String cliShLocation;
public static String rhqCliJavaHome;
public static String rhqTarget;
/**
* CLI test run listener
*/
public static CliTestRunListener runListener;
private String cliUsername;
private String cliPassword;
protected CliTasks cliTasks;
/**
* this handles console output of latest test run
*/
protected String consoleOutput;
private String jsFileName;
private static String remoteFileLocation = "/tmp/";
public static boolean isVersionSet = false;
//@Parameters({"rhq.target","cli.username","cli.password","js.file","cli.args","expected.result","make.failure"})
public void loadSetup(@Optional String rhqTarget, @Optional String cliUsername, @Optional String cliPassword, @Optional String makeFailure) throws IOException{
if(rhqTarget != null)
CliEngine.rhqTarget = rhqTarget;
if(cliUsername != null)
this.cliUsername = cliUsername;
if(cliPassword != null)
this.cliPassword = cliPassword;
}
private URL findResource(String path) {
try {
_logger.fine("Looking up resource "+path);
if (path.startsWith("/")) {
// we have to strip starting "/" because otherwise getClassLoader().getResources(path) finds nothing
path = path.substring(1);
}
Enumeration<URL> resources = getClass().getClassLoader().getResources(path);
URL candidate = null;
if (!resources.hasMoreElements()) {
return null;
}
while (resources.hasMoreElements()) {
URL el = resources.nextElement();
_logger.fine("Found "+el.getFile());
if (new File(el.getFile()).exists()) {
candidate = el;
}
}
if (candidate==null) {
candidate = getClass().getClassLoader().getResources(path).nextElement();
}
_logger.fine("Returning "+candidate.getFile());
return candidate;
} catch (IOException e) {
return null;
}
}
private String getResourceFileName(String path) throws CliTasksException {
if (path.startsWith("http://") || path.startsWith("https://")) {
try {
File file = File.createTempFile("temp", ".js");
file.deleteOnExit();
cliTasks.runCommand("wget -nv --no-check-certificate '"+path+"' -O "+file.getAbsolutePath()+" 2>&1");
return file.getAbsolutePath();
} catch (IOException e) {
throw new CliTasksException("Unable to create temporary file", e);
}
}
- else if (path.startsWith("file://")) {
+ else if (path.startsWith("file:/")) {
try {
File file = new File(new URI(path));
return file.getAbsolutePath();
} catch (URISyntaxException e) {
e.printStackTrace();
}
}
URL resource = null;
resource = findResource(path);
if (resource==null) {
_logger.fine("Appending js-files/ to resource path");
resource = findResource("js-files/"+path);
}
if (resource==null) {
throw new RuntimeException("Unable to retrieve either ["+path+"] or [js-files/"+path+"] resource on classpath!");
}
if (new File(resource.getFile()).exists()) {
return resource.getFile();
}
try {
_logger.fine("Copying resource "+resource.getFile()+" from JAR");
File file = File.createTempFile("temp", ".tmp");
file.deleteOnExit();
InputStream is = resource.openStream();
OutputStream os = new FileOutputStream(file);
final byte[] buf = new byte[1024];
int len = 0;
while ((len = is.read(buf)) > 0) {
os.write(buf, 0, len);
}
is.close();
os.close();
return file.getAbsolutePath();
}
catch (IOException ex) {
throw new RuntimeException("Unable to copy ["+path+"] resource from classpath!");
}
}
/**
* parameters resSrc and resDest must have same count of items and are processed together (resSrc[0] will be copied to resDst[0])
* @param rhqTarget
* @param cliUsername
* @param cliPassword
* @param jsFile to be executed
* @param cliArgs arguments passed
* @param expectedResult comma-separated list of messages that are expected as output
* @param makeFilure comma-separated list of messages - if these are found in output, test fails
* @param jsDepends comma-separated list of other JS files that are required/imported by <b>jsFile</b>
* @param resSrc comma-separated list of source paths
* @param resDst comma-separated list of source paths (must be same size as resSrc)
* @throws IOException
* @throws CliTasksException
*/
public void runJSfile(@Optional String rhqTarget, @Optional String cliUsername, @Optional String cliPassword, String jsFile, @Optional String cliArgs, @Optional String expectedResult, @Optional String makeFilure,@Optional String jsDepends,@Optional String resSrc, @Optional String resDst) throws IOException, CliTasksException{
loadSetup(rhqTarget, cliUsername, cliPassword, makeFilure);
cliTasks = CliTasks.getCliTasks();
// process additional resource files
if (resSrc!=null && resDst!=null) {
prepareResources(resSrc, resDst);
}
String jsFilePath = getResourceFileName(jsFile);
jsFileName = new File(jsFilePath).getName();
// upload JS file to remote host first
cliTasks.copyFile(jsFilePath, remoteFileLocation);
if (jsDepends!=null) {
prepareDependencies(jsFile, jsDepends,jsFilePath);
}
String command = "export RHQ_CLI_JAVA_HOME="+rhqCliJavaHome+"; ";
// autodetect RHQ_CLI_JAVA_HOME if not defined
if (StringUtils.trimToNull(rhqCliJavaHome)==null) {
rhqCliJavaHome = cliTasks.runCommand("echo $JAVA_HOME").trim();
if ("".equals(rhqCliJavaHome)) {
log.info("Neither RHQ_CLI_JAVA_HOME nor JAVA_HOME environment variables were defined, trying to get java exe file location");
command = "export RHQ_CLI_JAVA_EXE_FILE_PATH=`which java`; ";
}else{
_logger.log(Level.INFO,"Environment variable RHQ_CLI_JAVA_HOME was autodetected using JAVA_HOME variable");
command = "export RHQ_CLI_JAVA_HOME="+rhqCliJavaHome+"; ";
}
}
// workaround #913135 for JON 3.2 ALPHA build !!!! export RHQ_CLI_ADDITIONAL_JAVA_OPTS=-Drhq.client.version-check=false;
command += "export RHQ_CLI_ADDITIONAL_JAVA_OPTS=-Drhq.client.version-check=false; "+CliEngine.cliShLocation+" -s "+CliEngine.rhqTarget+" -u "+this.cliUsername+" -p "+this.cliPassword+" -f "+remoteFileLocation+jsFileName;
if(cliArgs != null){
command +=" "+cliArgs;
}
// get live output in log file on server
command +=" | tee -a /tmp/cli-automation.log";
consoleOutput = cliTasks.runCommand(command);
_logger.log(Level.INFO, consoleOutput);
if(!isVersionSet && consoleOutput.length()>25){
System.setProperty("rhq.build.version", consoleOutput.substring(consoleOutput.indexOf("Remote server version is:")+25, consoleOutput.indexOf("Login successful")).trim());
isVersionSet = true;
_logger.log(Level.INFO, "RHQ/JON Version: "+System.getProperty("rhq.build.version"));
}
if(makeFilure != null){
cliTasks.validateErrorString(consoleOutput , makeFilure);
}
if(expectedResult != null){
cliTasks.validateExpectedResultString(consoleOutput , expectedResult);
}
}
public CliTestRunner createJSRunner(String jsFile) {
return new CliTestRunner(this).jsFile(jsFile);
}
public final CliTestRunner createJSSnippetRunner(String jsSnippet) {
return createJSRunner(null).jsSnippet(jsSnippet);
}
public void runJSfile(String jsFile,String cliArgs,String expectedResult,String jsDepends,String resSrc, String resDes)
throws IOException, CliTasksException{
runJSfile(null, "rhqadmin", "rhqadmin", jsFile, cliArgs, expectedResult, null, jsDepends, resSrc, resDes);
}
public void runJSfile(String jsFile,String cliArgs,String expectedResult,String jsDepends) throws IOException, CliTasksException{
runJSfile(jsFile, cliArgs, expectedResult, jsDepends, null, null);
}
public void runJSfile(String jsFile,String cliArgs,String expectedResult) throws IOException, CliTasksException{
runJSfile(jsFile, cliArgs, expectedResult, null);
}
public void runJSfile(String jsFile,String expectedResult) throws IOException, CliTasksException{
runJSfile(jsFile, null, expectedResult);
}
public void runJSfile(String jsFile) throws IOException, CliTasksException{
runJSfile(jsFile, "Login successful");
}
/**
* runs given javascript snippet
* @param snippet
* @param rhqTarget
* @param cliUsername
* @param cliPassword
* @param cliArgs
* @param expectedResult
* @param makeFilure
* @param jsDepends
* @param resSrc
* @param resDst
* @return text output of CLI client running this snippet
* @throws IOException
* @throws CliTasksException
*/
public String runJSSnippet(String snippet, String rhqTarget,
String cliUsername, String cliPassword, String cliArgs,
String expectedResult, String makeFilure, String jsDepends,
String resSrc, String resDst) throws IOException, CliTasksException {
File tempFile = File.createTempFile("snippet", "js");
PrintWriter pw = new PrintWriter(tempFile);
pw.println(snippet);
pw.close();
runJSfile(rhqTarget, cliUsername, cliPassword, tempFile.toURI()
.toString(), cliArgs, expectedResult, makeFilure, jsDepends,
resSrc, resDst);
return consoleOutput;
}
protected void prepareResources(String resSrc, String resDst)
throws CliTasksException, IOException {
_logger.info("Processing additional resources...");
String[] sources = resSrc.split(",");
String[] dests = resDst.split(",");
if (sources.length!=dests.length) {
throw new CliTasksException("res.src parameter must be same length as res.dst, please update your testng configuration!");
}
for (int i=0;i<sources.length;i++) {
String src = sources[i];
File dst = new File(dests[i]);
String destDir = dst.getParent();
if (destDir==null) {
destDir="/tmp";
}
else if (!dst.isAbsolute()) {
destDir="/tmp/"+destDir;
}
cliTasks.runCommand("mkdir -p "+destDir);
if (src.startsWith("http")) {
cliTasks.runCommand("wget -nv "+src+" -O "+destDir+"/"+dst.getName()+" 2>&1");
}
else {
String resource = getResourceFileName(src);
if (resource==null) {
throw new CliTasksException("Resource file "+src+" does not exist!");
}
if (runListener!=null) {
try {
File newResource = runListener.onResourceProcessed(src, new File(resource));
if (newResource!=null && newResource.exists() && newResource.isFile()) {
_logger.fine("Resource ["+resource+"] has been processed by listener, new result ["+newResource.getAbsolutePath()+"]");
resource = newResource.getAbsolutePath();
}
else {
throw new Exception("Resource file processed by listener is invalid (either null, non-existing or non-file)");
}
} catch (Exception ex) {
_logger.log(Level.WARNING, "CliTestRunListener failed, using original resource. Error : "+ex.getMessage(), ex);
}
}
cliTasks.copyFile(resource, destDir,dst.getName());
}
}
}
protected void prepareDependencies(String jsFile, String jsDepends, String mainJsFilePath)
throws IOException, CliTasksException {
int longestDepNameLength=0;
Map<String,Integer> lines = new LinkedHashMap<String, Integer>();
_logger.info("Preparing JS file depenencies ... "+jsDepends);
for (String dependency : jsDepends.split(",")) {
if (dependency.length()>longestDepNameLength) {
longestDepNameLength = dependency.length();
}
String jsFilePath = getResourceFileName(dependency);
lines.put(dependency, getFileLineCount(jsFilePath));
cliTasks.copyFile(jsFilePath, remoteFileLocation, "_tmp.js");
// as CLI does not support including, we must merge the files manually
cliTasks.runCommand("cat "+remoteFileLocation+"_tmp.js >> "+remoteFileLocation+"_deps.js");
}
cliTasks.runCommand("rm "+remoteFileLocation+"_tmp.js");
// finally merge main jsFile
cliTasks.runCommand("cat "+remoteFileLocation+jsFileName+" >> "+remoteFileLocation+"_deps.js && mv "+remoteFileLocation+"_deps.js "+remoteFileLocation+jsFileName);
_logger.info("JS file depenencies ready");
_logger.info("Output file has been merged from JS files as follows:");
int current = 0;
lines.put(jsFile, getFileLineCount(mainJsFilePath));
if (jsFile.length()>longestDepNameLength) {
longestDepNameLength = jsFile.length();
}
_logger.info("===========================");
for (String dep : lines.keySet()) {
_logger.info("JS File: "+dep+createSpaces(longestDepNameLength-dep.length())+" lines: "+current+" - "+(current+lines.get(dep)));
current+=lines.get(dep)+1;
}
_logger.info("===========================");
}
public void waitFor(int ms) {
waitFor(ms, "Waiting");
}
public void waitFor(int ms,String message) {
log.fine(message+" "+(ms/1000)+"s");
if(ms<=0) {
ms = 1;
}
try {
Thread.currentThread().join(ms);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@AfterTest
public void deleteJSFile(){
try {
CliTasks.getCliTasks().runCommand("rm -rf '"+remoteFileLocation+jsFileName+"'", 1000*60*3);
} catch (CliTasksException ex) {
_logger.log(Level.WARNING, "Exception on remote File deletion!, ", ex);
}
}
private String createSpaces(int length) {
StringBuilder sb = new StringBuilder();
while (length>0) {
sb.append(" ");
length--;
}
return sb.toString();
}
private int getFileLineCount(String path) {
BufferedReader reader = null;
int lines = 0;
try {
reader = new BufferedReader(new FileReader(path));
while (reader.readLine() != null) lines++;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
reader.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return lines;
}
}
| true | true | private String getResourceFileName(String path) throws CliTasksException {
if (path.startsWith("http://") || path.startsWith("https://")) {
try {
File file = File.createTempFile("temp", ".js");
file.deleteOnExit();
cliTasks.runCommand("wget -nv --no-check-certificate '"+path+"' -O "+file.getAbsolutePath()+" 2>&1");
return file.getAbsolutePath();
} catch (IOException e) {
throw new CliTasksException("Unable to create temporary file", e);
}
}
else if (path.startsWith("file://")) {
try {
File file = new File(new URI(path));
return file.getAbsolutePath();
} catch (URISyntaxException e) {
e.printStackTrace();
}
}
URL resource = null;
resource = findResource(path);
if (resource==null) {
_logger.fine("Appending js-files/ to resource path");
resource = findResource("js-files/"+path);
}
if (resource==null) {
throw new RuntimeException("Unable to retrieve either ["+path+"] or [js-files/"+path+"] resource on classpath!");
}
if (new File(resource.getFile()).exists()) {
return resource.getFile();
}
try {
_logger.fine("Copying resource "+resource.getFile()+" from JAR");
File file = File.createTempFile("temp", ".tmp");
file.deleteOnExit();
InputStream is = resource.openStream();
OutputStream os = new FileOutputStream(file);
final byte[] buf = new byte[1024];
int len = 0;
while ((len = is.read(buf)) > 0) {
os.write(buf, 0, len);
}
is.close();
os.close();
return file.getAbsolutePath();
}
catch (IOException ex) {
throw new RuntimeException("Unable to copy ["+path+"] resource from classpath!");
}
}
| private String getResourceFileName(String path) throws CliTasksException {
if (path.startsWith("http://") || path.startsWith("https://")) {
try {
File file = File.createTempFile("temp", ".js");
file.deleteOnExit();
cliTasks.runCommand("wget -nv --no-check-certificate '"+path+"' -O "+file.getAbsolutePath()+" 2>&1");
return file.getAbsolutePath();
} catch (IOException e) {
throw new CliTasksException("Unable to create temporary file", e);
}
}
else if (path.startsWith("file:/")) {
try {
File file = new File(new URI(path));
return file.getAbsolutePath();
} catch (URISyntaxException e) {
e.printStackTrace();
}
}
URL resource = null;
resource = findResource(path);
if (resource==null) {
_logger.fine("Appending js-files/ to resource path");
resource = findResource("js-files/"+path);
}
if (resource==null) {
throw new RuntimeException("Unable to retrieve either ["+path+"] or [js-files/"+path+"] resource on classpath!");
}
if (new File(resource.getFile()).exists()) {
return resource.getFile();
}
try {
_logger.fine("Copying resource "+resource.getFile()+" from JAR");
File file = File.createTempFile("temp", ".tmp");
file.deleteOnExit();
InputStream is = resource.openStream();
OutputStream os = new FileOutputStream(file);
final byte[] buf = new byte[1024];
int len = 0;
while ((len = is.read(buf)) > 0) {
os.write(buf, 0, len);
}
is.close();
os.close();
return file.getAbsolutePath();
}
catch (IOException ex) {
throw new RuntimeException("Unable to copy ["+path+"] resource from classpath!");
}
}
|
diff --git a/src/wikipathways/org/pathvisio/wikipathways/WikiPathways.java b/src/wikipathways/org/pathvisio/wikipathways/WikiPathways.java
index 7fa3d520..17f98a91 100644
--- a/src/wikipathways/org/pathvisio/wikipathways/WikiPathways.java
+++ b/src/wikipathways/org/pathvisio/wikipathways/WikiPathways.java
@@ -1,490 +1,491 @@
// PathVisio,
// a tool for data visualization and analysis using Biological Pathways
// Copyright 2006-2007 BiGCaT Bioinformatics
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
package org.pathvisio.wikipathways;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.CookieHandler;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.swing.Action;
import javax.swing.event.HyperlinkEvent;
import javax.swing.event.HyperlinkListener;
import org.apache.commons.codec.binary.Base64;
import org.apache.xmlrpc.XmlRpcException;
import org.apache.xmlrpc.XmlRpcRequest;
import org.apache.xmlrpc.client.XmlRpcClient;
import org.apache.xmlrpc.client.XmlRpcClientConfigImpl;
import org.apache.xmlrpc.client.XmlRpcClientException;
import org.apache.xmlrpc.client.XmlRpcHttpClientConfig;
import org.apache.xmlrpc.client.XmlRpcHttpTransport;
import org.apache.xmlrpc.client.XmlRpcTransport;
import org.apache.xmlrpc.client.XmlRpcTransportFactory;
import org.apache.xmlrpc.common.XmlRpcStreamRequestConfig;
import org.apache.xmlrpc.util.HttpUtil;
import org.pathvisio.ApplicationEvent;
import org.pathvisio.Engine;
import org.pathvisio.Globals;
import org.pathvisio.Engine.ApplicationEventListener;
import org.pathvisio.data.DBConnector;
import org.pathvisio.data.DBConnectorDerbyServer;
import org.pathvisio.data.GdbManager;
import org.pathvisio.debug.Logger;
import org.pathvisio.gui.swing.MainPanel;
import org.pathvisio.gui.swing.SwingEngine;
import org.pathvisio.gui.swing.actions.CommonActions;
import org.pathvisio.gui.wikipathways.Actions;
import org.pathvisio.model.ConverterException;
import org.pathvisio.model.Organism;
import org.pathvisio.model.Pathway;
import org.pathvisio.model.PathwayElement;
import org.pathvisio.model.Pathway.StatusFlagEvent;
import org.pathvisio.model.Pathway.StatusFlagListener;
import org.pathvisio.preferences.GlobalPreference;
import org.pathvisio.util.ProgressKeeper;
import org.pathvisio.util.RunnableWithProgress;
import org.pathvisio.view.VPathway;
import org.xml.sax.SAXException;
/**
* Base class that handles WikiPathways related actions for the pathway editor applet
* @author thomas
*
*/
public class WikiPathways implements ApplicationEventListener, StatusFlagListener {
public static final String COMMENT_DESCRIPTION = "WikiPathways-description";
public static final String COMMENT_CATEGORY = "WikiPathways-category";
UserInterfaceHandler uiHandler;
HashMap<String, String> cookie;
File localFile;
/**
* Keep track of changes with respect to the remote version of the pathway
* (because the {@link Pathway#hasChanged()} also depends on locally saved version
*/
boolean remoteChanged;
boolean initPerformed;
boolean isInit;
MainPanel mainPanel;
public WikiPathways(UserInterfaceHandler uiHandler) {
this.uiHandler = uiHandler;
cookie = new HashMap<String, String>();
Engine.getCurrent().addApplicationEventListener(this);
}
public void setUiHandler(UserInterfaceHandler uih) {
uiHandler = uih;
}
public void init(ProgressKeeper progress, URL base) throws Exception {
isInit = true;
progress.setTaskName("Starting editor");
WikiPathwaysInit.init();
WikiPathwaysInit.registerXmlRpcExporters(new URL(getRpcURL()), Engine.getCurrent());
loadCookies(base);
for(Parameter p : Parameter.values()) {
//Check for required
if(p.isRequired()) {
assert p.getValue() != null :
"Missing required argument '" + p.name() + "'";
}
}
progress.report("Loading pathway...");
if(isNew()) { //Create new pathway
Logger.log.trace("WIKIPATHWAYS INIT: new pathway");
Engine.getCurrent().newPathway();
//Set the initial information
Pathway p = Engine.getCurrent().getActivePathway();
PathwayElement info = p.getMappInfo();
info.setMapInfoName(Parameter.PW_NAME.getValue());
info.setAuthor(Parameter.USER.getValue());
info.setOrganism(Parameter.PW_SPECIES.getValue());
} else { //Download and open the pathway
Logger.log.trace("WIKIPATHWAYS INIT: open pathway");
Engine.getCurrent().openPathway(new URL(getPwURL()));
+ Engine.getCurrent().getActivePathway().setSourceFile(null); //To trigger save as
}
//Register status flag listener to override changed flag for local saves
Engine.getCurrent().getActivePathway().addStatusFlagListener(this);
initVPathway();
if(isReadOnly()) {
uiHandler.showInfo("Read-only",
"You are not logged in to " + Globals.SERVER_NAME +
" so the pathway will be opened in read-only mode");
}
progress.report("Connecting to database...");
//Connect to the gene database
DBConnector connector = new DBConnectorDerbyServer(Parameter.GDB_SERVER.getValue(), 1527);
Engine.getCurrent().setDBConnector(connector, DBConnector.TYPE_GDB);
GdbManager.setGeneDb(getPwSpecies());
GdbManager.setMetaboliteDb("metabolites");
isInit = false;
initPerformed = true;
}
public boolean initPerformed() {
return initPerformed;
}
public boolean isInit() {
return isInit;
}
public void initVPathway() {
Engine e = Engine.getCurrent();
Pathway p = e.getActivePathway();
VPathway vp = e.getActiveVPathway();
if(p != null && vp == null) {
Logger.log.trace("Create VPathway");
e.createVPathway(p);
}
vp = e.getActiveVPathway();
if(vp != null) {
vp.setEditMode(!isReadOnly());
}
}
/**
* Returns true when the pathway has changed with respect to the
* last saved wiki version
*/
public boolean hasChanged() {
return remoteChanged || Engine.getCurrent().getActivePathway().hasChanged();
}
public String getPwName() {
return Parameter.PW_NAME.getValue();
}
public String getPwSpecies() {
return Parameter.PW_SPECIES.getValue();
}
public String getPwURL() {
return Parameter.PW_URL.getValue();
}
public String getRpcURL() {
return Parameter.RPC_URL.getValue();
}
public String getUser() {
return Parameter.USER.getValue();
}
public void addCookie(String key, String value) {
cookie.put(key, value);
}
public void loadCookies(URL url) {
Logger.log.trace("Loading cookies");
try {
CookieHandler handler = CookieHandler.getDefault();
if (handler != null) {
Map<String, List<String>> headers = handler.get(url.toURI(), new HashMap<String, List<String>>());
if(headers == null) {
Logger.log.error("Unable to load cookies: headers null");
return;
}
List<String> values = headers.get("Cookie");
for (String c : values) {
String[] cvalues = c.split(";");
for(String cv : cvalues) {
String[] keyvalue = cv.split("=");
if(keyvalue.length == 2) {
Logger.log.trace("COOKIE: " + keyvalue[0] + " | " + keyvalue[1]);
addCookie(keyvalue[0].trim(), keyvalue[1].trim());
}
}
}
}
} catch(Exception e) {
Logger.log.error("Unable to load cookies", e);
}
}
public boolean isNew() {
return Parameter.PW_NEW.getValue() != null;
}
public boolean isReadOnly() {
return getUser() == null;
}
protected File getLocalFile() {
if(localFile == null) {
try {
localFile = File.createTempFile("tmp", ".gpml");
} catch(Exception e) {
return null;
}
}
return localFile;
}
public UserInterfaceHandler getUserInterfaceHandler() {
return uiHandler;
}
public boolean saveUI(String description) {
Pathway pathway = Engine.getCurrent().getActivePathway();
if(!remoteChanged && !pathway.hasChanged()) {
uiHandler.showInfo("Save pathway", "You didn't make any changes");
return false;
}
if(pathway != null) {
if(description == null) {
description = uiHandler.askInput("Specify description", "Give a description of your changes");
}
final String finalDescription = description;
Logger.log.trace("Save description: " + description);
if(description != null) {
RunnableWithProgress<Boolean> r = new RunnableWithProgress<Boolean>() {
public Boolean excecuteCode() {
getProgressKeeper().setTaskName("Saving pathway");
try {
saveToWiki(finalDescription);
return true;
} catch (Exception e) {
Logger.log.error("Unable to save pathway", e);
uiHandler.showError("Unable to save pathway", e.getClass() +
"\n See error log (" + GlobalPreference.FILE_LOG.getValue() + ") for details");
}
return false;
}
};
uiHandler.runWithProgress(r, "", ProgressKeeper.PROGRESS_UNKNOWN, false, true);
return r.get();
}
}
return false;
}
protected void saveToWiki(String description) throws XmlRpcException, IOException, ConverterException {
if(remoteChanged || Engine.getCurrent().getActivePathway().hasChanged()) {
File gpmlFile = getLocalFile();
//Save current pathway to local file
Engine.getCurrent().savePathway(gpmlFile);
remoteChanged = true; //In case we get an error, save changes next time
saveToWiki(description, gpmlFile);
remoteChanged = false; //Save successful, don't save next time
} else {
Logger.log.trace("No changes made, ignoring save");
throw new ConverterException("You didn't make any changes");
}
}
protected void saveToWiki(String description, File gpmlFile) throws XmlRpcException, IOException {
XmlRpcClientConfigImpl config = new XmlRpcClientConfigImpl();
config.setServerURL(new URL(getRpcURL()));
XmlRpcClient client = new XmlRpcClient();
XmlRpcCookieTransportFactory ctf = new XmlRpcCookieTransportFactory(client);
XmlRpcCookieHttpTransport ct = (XmlRpcCookieHttpTransport)ctf.getTransport();
for(String key : cookie.keySet()) {
Logger.log.trace("Setting cookie: " + key + "=" + cookie.get(key));
ct.addCookie(key, cookie.get(key));
}
client.setTransportFactory(ctf);
client.setConfig(config);
RandomAccessFile raf = new RandomAccessFile(gpmlFile, "r");
byte[] data = new byte[(int)raf.length()];
raf.readFully(data);
byte[] data64 = Base64.encodeBase64(data);
Object[] params = new Object[]{ getPwName(), getPwSpecies(), description, data64 };
client.execute("WikiPathways.updatePathway", params);
}
static class XmlRpcCookieTransportFactory implements XmlRpcTransportFactory {
private final XmlRpcCookieHttpTransport TRANSPORT;
public XmlRpcCookieTransportFactory(XmlRpcClient pClient) {
TRANSPORT = new XmlRpcCookieHttpTransport(pClient);
}
public XmlRpcTransport getTransport() { return TRANSPORT; }
}
/** Implementation of an HTTP transport that supports sending cookies with the
* HTTP header, based on the {@link java.net.HttpURLConnection} class.
*/
public static class XmlRpcCookieHttpTransport extends XmlRpcHttpTransport {
private static final String userAgent = USER_AGENT + " (Sun HTTP Transport, mod Thomas)";
private static final String cookieHeader = "Cookie";
private URLConnection conn;
private HashMap<String, String> cookie;
public XmlRpcCookieHttpTransport(XmlRpcClient pClient) {
super(pClient, userAgent);
cookie = new HashMap<String, String>();
}
public void addCookie(String key, String value) {
cookie.put(key, value);
}
protected void setCookies() {
String cookieString = null;
for(String key : cookie.keySet()) {
cookieString = (cookieString == null ? "" : cookieString + "; ") + key + "=" + cookie.get(key);
}
if(cookieString != null) {
conn.setRequestProperty(cookieHeader, cookieString);
}
}
public Object sendRequest(XmlRpcRequest pRequest) throws XmlRpcException {
XmlRpcHttpClientConfig config = (XmlRpcHttpClientConfig) pRequest.getConfig();
try {
conn = config.getServerURL().openConnection();
conn.setUseCaches(false);
conn.setDoInput(true);
conn.setDoOutput(true);
setCookies();
} catch (IOException e) {
throw new XmlRpcException("Failed to create URLConnection: " + e.getMessage(), e);
}
return super.sendRequest(pRequest);
}
protected void setRequestHeader(String pHeader, String pValue) {
conn.setRequestProperty(pHeader, pValue);
}
protected void close() throws XmlRpcClientException {
if (conn instanceof HttpURLConnection) {
((HttpURLConnection) conn).disconnect();
}
}
protected boolean isResponseGzipCompressed(XmlRpcStreamRequestConfig pConfig) {
return HttpUtil.isUsingGzipEncoding(conn.getHeaderField("Content-Encoding"));
}
protected InputStream getInputStream() throws XmlRpcException {
try {
return conn.getInputStream();
} catch (IOException e) {
throw new XmlRpcException("Failed to create input stream: " + e.getMessage(), e);
}
}
protected void writeRequest(ReqWriter pWriter) throws IOException, XmlRpcException, SAXException {
pWriter.write(conn.getOutputStream());
}
}
public MainPanel getMainPanel() {
if(mainPanel == null) {
prepareMainPanel();
}
return mainPanel;
}
public MainPanel prepareMainPanel() {
CommonActions actions = SwingEngine.getCurrent().getActions();
Set<Action> hide = new HashSet<Action>();
//Disable some actions
if(!isNew()) hide.add(actions.importAction);
Action saveAction = new Actions.ExitAction(uiHandler, this, true, null);
Action discardAction = new Actions.ExitAction(uiHandler, this, false, null);
mainPanel = new MainPanel(hide);
mainPanel.getToolBar().addSeparator();
mainPanel.addToToolbar(saveAction, MainPanel.TB_GROUP_SHOW_IF_EDITMODE);
mainPanel.addToToolbar(discardAction);
mainPanel.getBackpagePane().addHyperlinkListener(new HyperlinkListener() {
public void hyperlinkUpdate(HyperlinkEvent e) {
if(e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
uiHandler.showDocument(e.getURL(), "_blank");
}
}
});
SwingEngine.getCurrent().setApplicationPanel(mainPanel);
return mainPanel;
}
public void applicationEvent(ApplicationEvent e) {
Pathway p = null;
switch(e.getType()) {
case ApplicationEvent.PATHWAY_NEW:
p = (Pathway)e.getSource();
p.getMappInfo().setOrganism(Organism.fromShortName(getPwSpecies()).latinName());
p.getMappInfo().setMapInfoName(getPwName());
break;
case ApplicationEvent.PATHWAY_OPENED:
p = (Pathway)e.getSource();
//Force species name to be te same as on wikipathways
String impSpecies = p.getMappInfo().getOrganism();
Organism impOrg = Organism.fromLatinName(impSpecies);
Organism wikiOrg = Organism.fromShortName(getPwSpecies());
if(!wikiOrg.equals(impOrg)) {
uiHandler.showError("Invalid species",
"The species of the pathway you imported differs from the" +
" species for the " + Globals.SERVER_NAME + " pathway you are editing.\n" +
"It will be changed from '" + impSpecies + "' to '" + wikiOrg.latinName() + "'");
p.getMappInfo().setOrganism(wikiOrg.latinName());
}
break;
}
}
public void statusFlagChanged(StatusFlagEvent e) {
//Set our own flag to true if changes are detected
if(e.getNewStatus()) {
remoteChanged = true;
}
}
}
| true | true | public void init(ProgressKeeper progress, URL base) throws Exception {
isInit = true;
progress.setTaskName("Starting editor");
WikiPathwaysInit.init();
WikiPathwaysInit.registerXmlRpcExporters(new URL(getRpcURL()), Engine.getCurrent());
loadCookies(base);
for(Parameter p : Parameter.values()) {
//Check for required
if(p.isRequired()) {
assert p.getValue() != null :
"Missing required argument '" + p.name() + "'";
}
}
progress.report("Loading pathway...");
if(isNew()) { //Create new pathway
Logger.log.trace("WIKIPATHWAYS INIT: new pathway");
Engine.getCurrent().newPathway();
//Set the initial information
Pathway p = Engine.getCurrent().getActivePathway();
PathwayElement info = p.getMappInfo();
info.setMapInfoName(Parameter.PW_NAME.getValue());
info.setAuthor(Parameter.USER.getValue());
info.setOrganism(Parameter.PW_SPECIES.getValue());
} else { //Download and open the pathway
Logger.log.trace("WIKIPATHWAYS INIT: open pathway");
Engine.getCurrent().openPathway(new URL(getPwURL()));
}
//Register status flag listener to override changed flag for local saves
Engine.getCurrent().getActivePathway().addStatusFlagListener(this);
initVPathway();
if(isReadOnly()) {
uiHandler.showInfo("Read-only",
"You are not logged in to " + Globals.SERVER_NAME +
" so the pathway will be opened in read-only mode");
}
progress.report("Connecting to database...");
//Connect to the gene database
DBConnector connector = new DBConnectorDerbyServer(Parameter.GDB_SERVER.getValue(), 1527);
Engine.getCurrent().setDBConnector(connector, DBConnector.TYPE_GDB);
GdbManager.setGeneDb(getPwSpecies());
GdbManager.setMetaboliteDb("metabolites");
isInit = false;
initPerformed = true;
}
| public void init(ProgressKeeper progress, URL base) throws Exception {
isInit = true;
progress.setTaskName("Starting editor");
WikiPathwaysInit.init();
WikiPathwaysInit.registerXmlRpcExporters(new URL(getRpcURL()), Engine.getCurrent());
loadCookies(base);
for(Parameter p : Parameter.values()) {
//Check for required
if(p.isRequired()) {
assert p.getValue() != null :
"Missing required argument '" + p.name() + "'";
}
}
progress.report("Loading pathway...");
if(isNew()) { //Create new pathway
Logger.log.trace("WIKIPATHWAYS INIT: new pathway");
Engine.getCurrent().newPathway();
//Set the initial information
Pathway p = Engine.getCurrent().getActivePathway();
PathwayElement info = p.getMappInfo();
info.setMapInfoName(Parameter.PW_NAME.getValue());
info.setAuthor(Parameter.USER.getValue());
info.setOrganism(Parameter.PW_SPECIES.getValue());
} else { //Download and open the pathway
Logger.log.trace("WIKIPATHWAYS INIT: open pathway");
Engine.getCurrent().openPathway(new URL(getPwURL()));
Engine.getCurrent().getActivePathway().setSourceFile(null); //To trigger save as
}
//Register status flag listener to override changed flag for local saves
Engine.getCurrent().getActivePathway().addStatusFlagListener(this);
initVPathway();
if(isReadOnly()) {
uiHandler.showInfo("Read-only",
"You are not logged in to " + Globals.SERVER_NAME +
" so the pathway will be opened in read-only mode");
}
progress.report("Connecting to database...");
//Connect to the gene database
DBConnector connector = new DBConnectorDerbyServer(Parameter.GDB_SERVER.getValue(), 1527);
Engine.getCurrent().setDBConnector(connector, DBConnector.TYPE_GDB);
GdbManager.setGeneDb(getPwSpecies());
GdbManager.setMetaboliteDb("metabolites");
isInit = false;
initPerformed = true;
}
|
diff --git a/examples/kilim/examples/Ping.java b/examples/kilim/examples/Ping.java
index 6b32958..8fcc578 100644
--- a/examples/kilim/examples/Ping.java
+++ b/examples/kilim/examples/Ping.java
@@ -1,147 +1,147 @@
/* Copyright (c) 2006, Sriram Srinivasan
*
* You may distribute this software under the terms of the license
* specified in the file "License"
*/
package kilim.examples;
import java.io.EOFException;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import kilim.Pausable;
import kilim.Scheduler;
import kilim.nio.EndPoint;
import kilim.nio.NioSelectorScheduler;
import kilim.nio.SessionTask;
/**
* Example showing kilim's support for NIO.
* Usage: java kilim.examples.Ping -server in one window
* and java kilim.examples.Ping -client in one or more windows.
* The client sends a number of 100 byte packets which are then echoed by the server.
*/
public class Ping {
static int PACKET_LEN = 100;
static boolean server = false;
static int port = 7262;
public static void main(String args[]) throws Exception {
if (args.length == 0) {
usage();
} else if (args[0].equalsIgnoreCase("-server")) {
server = true;
} else if (args[0].equalsIgnoreCase("-client")) {
server = false;
} else {
usage();
}
if (args.length > 1)
parsePort(args[1]);
System.out.println("kilim.examples.Ping " + (server ? "-server " : "-client ") + port);
if (server) {
Server.run();
} else {
Client.run();
}
}
/**
* Server is a SessionTask, which means an instance of it is created by the
* NioSelectorScheduler on an incoming connection.
* The task contains an endpoint object, the bridge between the NIO system
* and Kilim's scheduling.
*/
public static class Server extends SessionTask {
public static void run() throws IOException {
Scheduler sessionScheduler = Scheduler.getDefaultScheduler(); // The scheduler/thread pool on which all tasks will be run
NioSelectorScheduler nio = new NioSelectorScheduler(); // Starts a single thread that manages the select loop
nio.listen(port, Server.class, sessionScheduler); //
}
@Override
public void execute() throws Pausable, Exception {
System.out.println("[" + this.id + "] Connection rcvd");
try {
while (true) {
EndPoint ep = getEndPoint();
ByteBuffer buf = ByteBuffer.allocate(PACKET_LEN);
buf = ep.fill(buf, PACKET_LEN); // Pauses until at least PACKET_LEN bytes have been rcvd in buf.
System.out.println("[" + this.id + "] Received pkt");
buf.flip();
ep.write(buf);
System.out.println("[" + this.id + "] Echoed pkt");
}
} catch (EOFException eofe) {
System.out.println("[" + this.id + "] Connection terminated");
} catch (IOException ioe) {
System.out.println("[" + this.id + "] IO Exception: " + ioe.getMessage());
}
}
}
/**
* The Client is a conventional Java socket application.
*/
public static class Client {
public static void run() throws IOException {
SocketChannel ch = SocketChannel.open(new InetSocketAddress("localhost", port));
// Init ping packet
ByteBuffer bb = ByteBuffer.allocate(PACKET_LEN);
for (int i = 0; i < PACKET_LEN; i++) {
bb.put((byte)i);
}
bb.flip();
// Ping 5 times
- for (int i = 0 ; i < 1; i++) {
+ for (int i = 0 ; i < 5; i++) {
System.out.print("Ping");
writePkt(ch, bb);
System.out.println(" .. ");
// Read echo
readPkt(ch, bb);
bb.flip();
System.out.println(" reply rcvd");
}
}
private static void readPkt(SocketChannel ch, ByteBuffer bb) throws IOException, EOFException {
int remaining = PACKET_LEN;
bb.clear();
while (remaining > 0) {
int n = ch.read(bb);
if (n == -1) {
ch.close();
throw new EOFException();
}
remaining -= n;
}
}
private static void writePkt(SocketChannel ch, ByteBuffer bb) throws IOException {
// Write packet
int remaining = PACKET_LEN;
while (remaining > 0) {
int n = ch.write(bb);
remaining -= n;
}
}
}
static private void usage() {
System.err.println("Run java kilim.examples.Ping -server [port] in one window");
System.err.println("and kilim.examples.Ping -client [port] in one or more");
System.exit(1);
}
static void parsePort(String portstr) {
try {
port = Integer.parseInt(portstr);
} catch (Exception e) {
usage();
}
}
}
| true | true | public static void run() throws IOException {
SocketChannel ch = SocketChannel.open(new InetSocketAddress("localhost", port));
// Init ping packet
ByteBuffer bb = ByteBuffer.allocate(PACKET_LEN);
for (int i = 0; i < PACKET_LEN; i++) {
bb.put((byte)i);
}
bb.flip();
// Ping 5 times
for (int i = 0 ; i < 1; i++) {
System.out.print("Ping");
writePkt(ch, bb);
System.out.println(" .. ");
// Read echo
readPkt(ch, bb);
bb.flip();
System.out.println(" reply rcvd");
}
}
| public static void run() throws IOException {
SocketChannel ch = SocketChannel.open(new InetSocketAddress("localhost", port));
// Init ping packet
ByteBuffer bb = ByteBuffer.allocate(PACKET_LEN);
for (int i = 0; i < PACKET_LEN; i++) {
bb.put((byte)i);
}
bb.flip();
// Ping 5 times
for (int i = 0 ; i < 5; i++) {
System.out.print("Ping");
writePkt(ch, bb);
System.out.println(" .. ");
// Read echo
readPkt(ch, bb);
bb.flip();
System.out.println(" reply rcvd");
}
}
|
diff --git a/src/com/android/camera/ActivityBase.java b/src/com/android/camera/ActivityBase.java
index ff8c246d..297c9033 100644
--- a/src/com/android/camera/ActivityBase.java
+++ b/src/com/android/camera/ActivityBase.java
@@ -1,718 +1,722 @@
/*
* Copyright (C) 2009 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.camera;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Rect;
import android.hardware.Camera.Parameters;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.DecelerateInterpolator;
import com.android.camera.ui.CameraPicker;
import com.android.camera.ui.LayoutChangeNotifier;
import com.android.camera.ui.PopupManager;
import com.android.camera.ui.RotateImageView;
import com.android.gallery3d.app.AbstractGalleryActivity;
import com.android.gallery3d.app.AppBridge;
import com.android.gallery3d.app.GalleryActionBar;
import com.android.gallery3d.app.PhotoPage;
import com.android.gallery3d.common.ApiHelper;
import com.android.gallery3d.ui.ScreenNail;
import com.android.gallery3d.util.MediaSetUtils;
import java.io.File;
/**
* Superclass of Camera and VideoCamera activities.
*/
public abstract class ActivityBase extends AbstractGalleryActivity
implements LayoutChangeNotifier.Listener {
private static final String TAG = "ActivityBase";
private static final boolean LOGV = false;
private static final int CAMERA_APP_VIEW_TOGGLE_TIME = 100; // milliseconds
private static final String ACTION_DELETE_PICTURE =
"com.android.gallery3d.action.DELETE_PICTURE";
private static final String INTENT_ACTION_STILL_IMAGE_CAMERA_SECURE =
"android.media.action.STILL_IMAGE_CAMERA_SECURE";
// The intent extra for camera from secure lock screen. True if the gallery
// should only show newly captured pictures. sSecureAlbumId does not
// increment. This is used when switching between camera, camcorder, and
// panorama. If the extra is not set, it is in the normal camera mode.
public static final String SECURE_CAMERA_EXTRA = "secure_camera";
private int mResultCodeForTesting;
private Intent mResultDataForTesting;
private OnScreenHint mStorageHint;
private View mSingleTapArea;
// The bitmap of the last captured picture thumbnail and the URI of the
// original picture.
protected Thumbnail mThumbnail;
protected int mThumbnailViewWidth; // layout width of the thumbnail
protected AsyncTask<Void, Void, Thumbnail> mLoadThumbnailTask;
// An imageview showing the last captured picture thumbnail.
protected RotateImageView mThumbnailView;
protected CameraPicker mCameraPicker;
protected boolean mOpenCameraFail;
protected boolean mCameraDisabled;
protected CameraManager.CameraProxy mCameraDevice;
protected Parameters mParameters;
// The activity is paused. The classes that extend this class should set
// mPaused the first thing in onResume/onPause.
protected boolean mPaused;
protected GalleryActionBar mActionBar;
// multiple cameras support
protected int mNumberOfCameras;
protected int mCameraId;
// The activity is going to switch to the specified camera id. This is
// needed because texture copy is done in GL thread. -1 means camera is not
// switching.
protected int mPendingSwitchCameraId = -1;
protected MyAppBridge mAppBridge;
protected ScreenNail mCameraScreenNail; // This shows camera preview.
// The view containing only camera related widgets like control panel,
// indicator bar, focus indicator and etc.
protected View mCameraAppView;
protected boolean mShowCameraAppView = true;
private Animation mCameraAppViewFadeIn;
private Animation mCameraAppViewFadeOut;
// Secure album id. This should be incremented every time the camera is
// launched from the secure lock screen. The id should be the same when
// switching between camera, camcorder, and panorama.
protected static int sSecureAlbumId;
// True if the gallery should only show newly captured pictures or recorded
// videos.
protected boolean mSecureCamera;
private long mStorageSpace = Storage.LOW_STORAGE_THRESHOLD;
private static final int UPDATE_STORAGE_HINT = 0;
private final Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case UPDATE_STORAGE_HINT:
updateStorageHint();
return;
}
}
};
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(Intent.ACTION_MEDIA_MOUNTED)
|| action.equals(Intent.ACTION_MEDIA_UNMOUNTED)
|| action.equals(Intent.ACTION_MEDIA_CHECKING)
|| action.equals(Intent.ACTION_MEDIA_SCANNER_FINISHED)) {
updateStorageSpaceAndHint();
}
}
};
private boolean mUpdateThumbnailDelayed;
private IntentFilter mDeletePictureFilter =
new IntentFilter(ACTION_DELETE_PICTURE);
private BroadcastReceiver mDeletePictureReceiver =
new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (mShowCameraAppView) {
getLastThumbnailUncached();
} else {
mUpdateThumbnailDelayed = true;
}
}
};
protected class CameraOpenThread extends Thread {
@Override
public void run() {
try {
mCameraDevice = Util.openCamera(ActivityBase.this, mCameraId);
mParameters = mCameraDevice.getParameters();
} catch (CameraHardwareException e) {
mOpenCameraFail = true;
} catch (CameraDisabledException e) {
mCameraDisabled = true;
}
}
}
@Override
public void onCreate(Bundle icicle) {
- getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
+ // Setting the flag FLAG_SECURE causes white screen and flickering on Gingerbread,
+ // so we do not set the flag.
+ if (ApiHelper.CAN_USE_FLAG_SECURE) {
+ getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
+ }
super.disableToggleStatusBar();
// Set a theme with action bar. It is not specified in manifest because
// we want to hide it by default. setTheme must happen before
// setContentView.
//
// This must be set before we call super.onCreate(), where the window's
// background is removed.
setTheme(R.style.Theme_Gallery);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
if (ApiHelper.HAS_ACTION_BAR) {
requestWindowFeature(Window.FEATURE_ACTION_BAR_OVERLAY);
} else {
requestWindowFeature(Window.FEATURE_NO_TITLE);
}
// Check if this is in the secure camera mode.
Intent intent = getIntent();
if (INTENT_ACTION_STILL_IMAGE_CAMERA_SECURE.equals(intent.getAction())) {
mSecureCamera = true;
// Use a new album when this is started from the lock screen.
sSecureAlbumId++;
} else {
mSecureCamera = intent.getBooleanExtra(SECURE_CAMERA_EXTRA, false);
}
if (mSecureCamera) {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
}
super.onCreate(icicle);
}
public boolean isPanoramaActivity() {
return false;
}
@Override
protected void onResume() {
super.onResume();
LocalBroadcastManager manager = LocalBroadcastManager.getInstance(this);
manager.registerReceiver(mDeletePictureReceiver, mDeletePictureFilter);
installIntentFilter();
if(updateStorageHintOnResume()) {
updateStorageSpace();
mHandler.sendEmptyMessageDelayed(UPDATE_STORAGE_HINT, 200);
}
}
@Override
protected void onPause() {
super.onPause();
LocalBroadcastManager manager = LocalBroadcastManager.getInstance(this);
manager.unregisterReceiver(mDeletePictureReceiver);
if (LOGV) Log.v(TAG, "onPause");
saveThumbnailToFile();
if (mLoadThumbnailTask != null) {
mLoadThumbnailTask.cancel(true);
mLoadThumbnailTask = null;
}
if (mStorageHint != null) {
mStorageHint.cancel();
mStorageHint = null;
}
unregisterReceiver(mReceiver);
// Finish the activity if in secure camera mode. Make sure a new secure
// album is used every time.
if (mSecureCamera && !isFinishing()) finish();
}
@Override
public void setContentView(int layoutResID) {
super.setContentView(layoutResID);
// getActionBar() should be after setContentView
mActionBar = new GalleryActionBar(this);
mActionBar.hide();
}
@Override
public boolean onSearchRequested() {
return false;
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
// Prevent software keyboard or voice search from showing up.
if (keyCode == KeyEvent.KEYCODE_SEARCH
|| keyCode == KeyEvent.KEYCODE_MENU) {
if (event.isLongPress()) return true;
}
if (keyCode == KeyEvent.KEYCODE_MENU && mShowCameraAppView) {
return true;
}
return super.onKeyDown(keyCode, event);
}
@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_MENU && mShowCameraAppView) {
return true;
}
return super.onKeyUp(keyCode, event);
}
protected void setResultEx(int resultCode) {
mResultCodeForTesting = resultCode;
setResult(resultCode);
}
protected void setResultEx(int resultCode, Intent data) {
mResultCodeForTesting = resultCode;
mResultDataForTesting = data;
setResult(resultCode, data);
}
public int getResultCode() {
return mResultCodeForTesting;
}
public Intent getResultData() {
return mResultDataForTesting;
}
@Override
protected void onDestroy() {
PopupManager.removeInstance(this);
super.onDestroy();
}
protected void installIntentFilter() {
// install an intent filter to receive SD card related events.
IntentFilter intentFilter =
new IntentFilter(Intent.ACTION_MEDIA_MOUNTED);
intentFilter.addAction(Intent.ACTION_MEDIA_UNMOUNTED);
intentFilter.addAction(Intent.ACTION_MEDIA_SCANNER_FINISHED);
intentFilter.addAction(Intent.ACTION_MEDIA_CHECKING);
intentFilter.addDataScheme("file");
registerReceiver(mReceiver, intentFilter);
}
protected void updateStorageSpace() {
mStorageSpace = Storage.getAvailableSpace();
}
protected long getStorageSpace() {
return mStorageSpace;
}
protected void updateStorageSpaceAndHint() {
updateStorageSpace();
updateStorageHint(mStorageSpace);
}
protected void updateStorageHint() {
updateStorageHint(mStorageSpace);
}
protected boolean updateStorageHintOnResume() {
return true;
}
protected void updateStorageHint(long storageSpace) {
String message = null;
if (storageSpace == Storage.UNAVAILABLE) {
message = getString(R.string.no_storage);
} else if (storageSpace == Storage.PREPARING) {
message = getString(R.string.preparing_sd);
} else if (storageSpace == Storage.UNKNOWN_SIZE) {
message = getString(R.string.access_sd_fail);
} else if (storageSpace <= Storage.LOW_STORAGE_THRESHOLD) {
message = getString(R.string.spaceIsLow_content);
}
if (message != null) {
if (mStorageHint == null) {
mStorageHint = OnScreenHint.makeText(this, message);
} else {
mStorageHint.setText(message);
}
mStorageHint.show();
} else if (mStorageHint != null) {
mStorageHint.cancel();
mStorageHint = null;
}
}
protected void updateThumbnailView() {
if (mThumbnail != null) {
mThumbnailView.setBitmap(mThumbnail.getBitmap());
mThumbnailView.setVisibility(View.VISIBLE);
} else {
mThumbnailView.setBitmap(null);
mThumbnailView.setVisibility(View.GONE);
}
}
protected void getLastThumbnail() {
mThumbnail = ThumbnailHolder.getLastThumbnail(getContentResolver());
// Suppose users tap the thumbnail view, go to the gallery, delete the
// image, and coming back to the camera. Thumbnail file will be invalid.
// Since the new thumbnail will be loaded in another thread later, the
// view should be set to gone to prevent from opening the invalid image.
updateThumbnailView();
if (mThumbnail == null) {
mLoadThumbnailTask = new LoadThumbnailTask(true).execute();
}
}
protected void getLastThumbnailUncached() {
if (mLoadThumbnailTask != null) mLoadThumbnailTask.cancel(true);
mLoadThumbnailTask = new LoadThumbnailTask(false).execute();
}
private class LoadThumbnailTask extends AsyncTask<Void, Void, Thumbnail> {
private boolean mLookAtCache;
public LoadThumbnailTask(boolean lookAtCache) {
mLookAtCache = lookAtCache;
}
@Override
protected Thumbnail doInBackground(Void... params) {
// Load the thumbnail from the file.
ContentResolver resolver = getContentResolver();
Thumbnail t = null;
if (mLookAtCache) {
t = Thumbnail.getLastThumbnailFromFile(getFilesDir(), resolver);
}
if (isCancelled()) return null;
if (t == null) {
Thumbnail result[] = new Thumbnail[1];
// Load the thumbnail from the media provider.
int code = Thumbnail.getLastThumbnailFromContentResolver(
resolver, result);
switch (code) {
case Thumbnail.THUMBNAIL_FOUND:
return result[0];
case Thumbnail.THUMBNAIL_NOT_FOUND:
return null;
case Thumbnail.THUMBNAIL_DELETED:
cancel(true);
return null;
}
}
return t;
}
@Override
protected void onPostExecute(Thumbnail thumbnail) {
if (isCancelled()) return;
mThumbnail = thumbnail;
updateThumbnailView();
}
}
protected void gotoGallery() {
// Move the next picture with capture animation. "1" means next.
mAppBridge.switchWithCaptureAnimation(1);
}
protected void saveThumbnailToFile() {
if (mThumbnail != null && !mThumbnail.fromFile()) {
new SaveThumbnailTask().execute(mThumbnail);
}
}
private class SaveThumbnailTask extends AsyncTask<Thumbnail, Void, Void> {
@Override
protected Void doInBackground(Thumbnail... params) {
final int n = params.length;
final File filesDir = getFilesDir();
for (int i = 0; i < n; i++) {
params[i].saveLastThumbnailToFile(filesDir);
}
return null;
}
}
// Call this after setContentView.
protected void createCameraScreenNail(boolean getPictures) {
mCameraAppView = findViewById(R.id.camera_app_root);
Bundle data = new Bundle();
String path;
if (mSecureCamera) {
path = "/secure/all/" + sSecureAlbumId;
} else {
path = "/local/all/";
// Intent mode does not show camera roll. Use 0 as a work around for
// invalid bucket id.
// TODO: add support of empty media set in gallery.
path += (getPictures ? MediaSetUtils.CAMERA_BUCKET_ID : "0");
}
data.putString(PhotoPage.KEY_MEDIA_SET_PATH, path);
data.putString(PhotoPage.KEY_MEDIA_ITEM_PATH, path);
// Send an AppBridge to gallery to enable the camera preview.
mAppBridge = new MyAppBridge();
data.putParcelable(PhotoPage.KEY_APP_BRIDGE, mAppBridge);
getStateManager().startState(PhotoPage.class, data);
mCameraScreenNail = mAppBridge.getCameraScreenNail();
}
private class HideCameraAppView implements Animation.AnimationListener {
@Override
public void onAnimationEnd(Animation animation) {
// We cannot set this as GONE because we want to receive the
// onLayoutChange() callback even when we are invisible.
mCameraAppView.setVisibility(View.INVISIBLE);
}
@Override
public void onAnimationRepeat(Animation animation) {
}
@Override
public void onAnimationStart(Animation animation) {
}
}
protected void updateCameraAppView() {
// Initialize the animation.
if (mCameraAppViewFadeIn == null) {
mCameraAppViewFadeIn = new AlphaAnimation(0f, 1f);
mCameraAppViewFadeIn.setDuration(CAMERA_APP_VIEW_TOGGLE_TIME);
mCameraAppViewFadeIn.setInterpolator(new DecelerateInterpolator());
mCameraAppViewFadeOut = new AlphaAnimation(1f, 0f);
mCameraAppViewFadeOut.setDuration(CAMERA_APP_VIEW_TOGGLE_TIME);
mCameraAppViewFadeOut.setInterpolator(new DecelerateInterpolator());
mCameraAppViewFadeOut.setAnimationListener(new HideCameraAppView());
}
if (mShowCameraAppView) {
mCameraAppView.setVisibility(View.VISIBLE);
// The "transparent region" is not recomputed when a sibling of
// SurfaceView changes visibility (unless it involves GONE). It's
// been broken since 1.0. Call requestLayout to work around it.
mCameraAppView.requestLayout();
mCameraAppView.startAnimation(mCameraAppViewFadeIn);
} else {
mCameraAppView.startAnimation(mCameraAppViewFadeOut);
}
}
protected void onFullScreenChanged(boolean full) {
if (mShowCameraAppView == full) return;
mShowCameraAppView = full;
if (mPaused || isFinishing()) return;
updateCameraAppView();
// If we received DELETE_PICTURE broadcasts while the Camera UI is
// hidden, we update the thumbnail now.
if (full && mUpdateThumbnailDelayed) {
getLastThumbnailUncached();
mUpdateThumbnailDelayed = false;
}
}
@Override
public GalleryActionBar getGalleryActionBar() {
return mActionBar;
}
// Preview frame layout has changed.
@Override
public void onLayoutChange(View v, int left, int top, int right, int bottom) {
if (mAppBridge == null) return;
int width = right - left;
int height = bottom - top;
if (ApiHelper.HAS_SURFACE_TEXTURE) {
CameraScreenNail screenNail = (CameraScreenNail) mCameraScreenNail;
if (Util.getDisplayRotation(this) % 180 == 0) {
screenNail.setPreviewFrameLayoutSize(width, height);
} else {
// Swap the width and height. Camera screen nail draw() is based on
// natural orientation, not the view system orientation.
screenNail.setPreviewFrameLayoutSize(height, width);
}
}
// Find out the coordinates of the preview frame relative to GL
// root view.
View root = (View) getGLRoot();
int[] rootLocation = new int[2];
int[] viewLocation = new int[2];
root.getLocationInWindow(rootLocation);
v.getLocationInWindow(viewLocation);
int l = viewLocation[0] - rootLocation[0];
int t = viewLocation[1] - rootLocation[1];
int r = l + width;
int b = t + height;
Rect frame = new Rect(l, t, r, b);
Log.d(TAG, "set CameraRelativeFrame as " + frame);
mAppBridge.setCameraRelativeFrame(frame);
}
protected void setSingleTapUpListener(View singleTapArea) {
mSingleTapArea = singleTapArea;
}
private boolean onSingleTapUp(int x, int y) {
// Ignore if listener is null or the camera control is invisible.
if (mSingleTapArea == null || !mShowCameraAppView) return false;
int[] relativeLocation = Util.getRelativeLocation((View) getGLRoot(),
mSingleTapArea);
x -= relativeLocation[0];
y -= relativeLocation[1];
if (x >= 0 && x < mSingleTapArea.getWidth() && y >= 0
&& y < mSingleTapArea.getHeight()) {
onSingleTapUp(mSingleTapArea, x, y);
return true;
}
return false;
}
protected void onSingleTapUp(View view, int x, int y) {
}
protected void setSwipingEnabled(boolean enabled) {
mAppBridge.setSwipingEnabled(enabled);
}
protected void notifyScreenNailChanged() {
mAppBridge.notifyScreenNailChanged();
}
protected void onPreviewTextureCopied() {
}
protected void addSecureAlbumItemIfNeeded(boolean isVideo, Uri uri) {
if (mSecureCamera) {
int id = Integer.parseInt(uri.getLastPathSegment());
mAppBridge.addSecureAlbumItem(isVideo, id);
}
}
//////////////////////////////////////////////////////////////////////////
// The is the communication interface between the Camera Application and
// the Gallery PhotoPage.
//////////////////////////////////////////////////////////////////////////
class MyAppBridge extends AppBridge implements CameraScreenNail.Listener {
@SuppressWarnings("hiding")
private ScreenNail mCameraScreenNail;
private Server mServer;
@Override
public ScreenNail attachScreenNail() {
if (mCameraScreenNail == null) {
if (ApiHelper.HAS_SURFACE_TEXTURE) {
mCameraScreenNail = new CameraScreenNail(this);
} else {
Bitmap b = BitmapFactory.decodeResource(getResources(),
R.drawable.wallpaper_picker_preview);
mCameraScreenNail = new StaticBitmapScreenNail(b);
}
}
return mCameraScreenNail;
}
@Override
public void detachScreenNail() {
mCameraScreenNail = null;
}
public ScreenNail getCameraScreenNail() {
return mCameraScreenNail;
}
// Return true if the tap is consumed.
@Override
public boolean onSingleTapUp(int x, int y) {
return ActivityBase.this.onSingleTapUp(x, y);
}
// This is used to notify that the screen nail will be drawn in full screen
// or not in next draw() call.
@Override
public void onFullScreenChanged(boolean full) {
ActivityBase.this.onFullScreenChanged(full);
}
@Override
public void requestRender() {
getGLRoot().requestRender();
}
@Override
public void onPreviewTextureCopied() {
ActivityBase.this.onPreviewTextureCopied();
}
@Override
public void setServer(Server s) {
mServer = s;
}
@Override
public boolean isPanorama() {
return ActivityBase.this.isPanoramaActivity();
}
@Override
public boolean isStaticCamera() {
return !ApiHelper.HAS_SURFACE_TEXTURE;
}
public void addSecureAlbumItem(boolean isVideo, int id) {
if (mServer != null) mServer.addSecureAlbumItem(isVideo, id);
}
private void setCameraRelativeFrame(Rect frame) {
if (mServer != null) mServer.setCameraRelativeFrame(frame);
}
private void switchWithCaptureAnimation(int offset) {
if (mServer != null) mServer.switchWithCaptureAnimation(offset);
}
private void setSwipingEnabled(boolean enabled) {
if (mServer != null) mServer.setSwipingEnabled(enabled);
}
private void notifyScreenNailChanged() {
if (mServer != null) mServer.notifyScreenNailChanged();
}
}
}
| true | true | public void onCreate(Bundle icicle) {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
super.disableToggleStatusBar();
// Set a theme with action bar. It is not specified in manifest because
// we want to hide it by default. setTheme must happen before
// setContentView.
//
// This must be set before we call super.onCreate(), where the window's
// background is removed.
setTheme(R.style.Theme_Gallery);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
if (ApiHelper.HAS_ACTION_BAR) {
requestWindowFeature(Window.FEATURE_ACTION_BAR_OVERLAY);
} else {
requestWindowFeature(Window.FEATURE_NO_TITLE);
}
// Check if this is in the secure camera mode.
Intent intent = getIntent();
if (INTENT_ACTION_STILL_IMAGE_CAMERA_SECURE.equals(intent.getAction())) {
mSecureCamera = true;
// Use a new album when this is started from the lock screen.
sSecureAlbumId++;
} else {
mSecureCamera = intent.getBooleanExtra(SECURE_CAMERA_EXTRA, false);
}
if (mSecureCamera) {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
}
super.onCreate(icicle);
}
| public void onCreate(Bundle icicle) {
// Setting the flag FLAG_SECURE causes white screen and flickering on Gingerbread,
// so we do not set the flag.
if (ApiHelper.CAN_USE_FLAG_SECURE) {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
}
super.disableToggleStatusBar();
// Set a theme with action bar. It is not specified in manifest because
// we want to hide it by default. setTheme must happen before
// setContentView.
//
// This must be set before we call super.onCreate(), where the window's
// background is removed.
setTheme(R.style.Theme_Gallery);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
if (ApiHelper.HAS_ACTION_BAR) {
requestWindowFeature(Window.FEATURE_ACTION_BAR_OVERLAY);
} else {
requestWindowFeature(Window.FEATURE_NO_TITLE);
}
// Check if this is in the secure camera mode.
Intent intent = getIntent();
if (INTENT_ACTION_STILL_IMAGE_CAMERA_SECURE.equals(intent.getAction())) {
mSecureCamera = true;
// Use a new album when this is started from the lock screen.
sSecureAlbumId++;
} else {
mSecureCamera = intent.getBooleanExtra(SECURE_CAMERA_EXTRA, false);
}
if (mSecureCamera) {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
}
super.onCreate(icicle);
}
|
diff --git a/src/edu/stuy/subsystems/Shooter.java b/src/edu/stuy/subsystems/Shooter.java
index e97c573..3c5fc74 100644
--- a/src/edu/stuy/subsystems/Shooter.java
+++ b/src/edu/stuy/subsystems/Shooter.java
@@ -1,74 +1,74 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package edu.stuy.subsystems;
import edu.stuy.RobotMap;
import edu.wpi.first.wpilibj.Encoder;
import edu.wpi.first.wpilibj.Jaguar;
import edu.wpi.first.wpilibj.PIDController;
import edu.wpi.first.wpilibj.CounterBase;
import edu.wpi.first.wpilibj.command.Subsystem;
/**
*
* @author Kevin Wang
*/
public class Shooter extends Subsystem {
private static final double KP = 0.0;
private static final double KI = 0.0;
private static final double KD = 0.0;
private Jaguar upperRoller;
private Jaguar lowerRoller;
private Encoder upperEncoder;
private Encoder lowerEncoder;
private PIDController upperController;
private PIDController lowerController;
// Put methods for controlling this subsystem
// here. Call these from Commands.
public Shooter() {
upperRoller = new Jaguar(RobotMap.UPPER_SHOOTER_ROLLER);
lowerRoller = new Jaguar(RobotMap.LOWER_SHOOTER_ROLLER);
- //upperEncoder = new Encoder(RobotMap.UPPER_ROLLER_ENCODER_A, RobotMap.UPPER_ROLLER_ENCODER_B, false, CounterBase.EncodingType.k); //TODO Fix this!
- lowerEncoder = new Encoder(RobotMap.LOWER_ROLLER_ENCODER_A, RobotMap.LOWER_ROLLER_ENCODER_B);
+ upperEncoder = new Encoder(RobotMap.UPPER_ROLLER_ENCODER_A, RobotMap.UPPER_ROLLER_ENCODER_B, false, CounterBase.EncodingType.k4X);
+ lowerEncoder = new Encoder(RobotMap.LOWER_ROLLER_ENCODER_A, RobotMap.LOWER_ROLLER_ENCODER_B, false, CounterBase.EncodingType.k4X);
upperController = new PIDController(KP, KI, KD, upperEncoder, upperRoller);
lowerController = new PIDController(KP, KI, KD, lowerEncoder, upperRoller);
upperEncoder.setDistancePerPulse(RobotMap.DISTANCE_PER_PULSE);
lowerEncoder.setDistancePerPulse(RobotMap.DISTANCE_PER_PULSE);
upperEncoder.start();
lowerEncoder.start();
}
public void initDefaultCommand() {
// Set the default command for a subsystem here.
//setDefaultCommand(new MySpecialCommand());
}
public void rollRollers(double upperSpeed, double lowerSpeed) {
upperRoller.set(upperSpeed);
lowerRoller.set(lowerSpeed);
}
public double getUpperEnc(){
return upperEncoder.getDistance();
}
public double getLowerEnc(){
return lowerEncoder.getDistance();
}
public void resetEncoders(){
upperEncoder.reset();
lowerEncoder.reset();
}
}
| true | true | public Shooter() {
upperRoller = new Jaguar(RobotMap.UPPER_SHOOTER_ROLLER);
lowerRoller = new Jaguar(RobotMap.LOWER_SHOOTER_ROLLER);
//upperEncoder = new Encoder(RobotMap.UPPER_ROLLER_ENCODER_A, RobotMap.UPPER_ROLLER_ENCODER_B, false, CounterBase.EncodingType.k); //TODO Fix this!
lowerEncoder = new Encoder(RobotMap.LOWER_ROLLER_ENCODER_A, RobotMap.LOWER_ROLLER_ENCODER_B);
upperController = new PIDController(KP, KI, KD, upperEncoder, upperRoller);
lowerController = new PIDController(KP, KI, KD, lowerEncoder, upperRoller);
upperEncoder.setDistancePerPulse(RobotMap.DISTANCE_PER_PULSE);
lowerEncoder.setDistancePerPulse(RobotMap.DISTANCE_PER_PULSE);
upperEncoder.start();
lowerEncoder.start();
}
| public Shooter() {
upperRoller = new Jaguar(RobotMap.UPPER_SHOOTER_ROLLER);
lowerRoller = new Jaguar(RobotMap.LOWER_SHOOTER_ROLLER);
upperEncoder = new Encoder(RobotMap.UPPER_ROLLER_ENCODER_A, RobotMap.UPPER_ROLLER_ENCODER_B, false, CounterBase.EncodingType.k4X);
lowerEncoder = new Encoder(RobotMap.LOWER_ROLLER_ENCODER_A, RobotMap.LOWER_ROLLER_ENCODER_B, false, CounterBase.EncodingType.k4X);
upperController = new PIDController(KP, KI, KD, upperEncoder, upperRoller);
lowerController = new PIDController(KP, KI, KD, lowerEncoder, upperRoller);
upperEncoder.setDistancePerPulse(RobotMap.DISTANCE_PER_PULSE);
lowerEncoder.setDistancePerPulse(RobotMap.DISTANCE_PER_PULSE);
upperEncoder.start();
lowerEncoder.start();
}
|
diff --git a/geoplatform-gui/core/geoplatform-configuration/src/main/java/org/geosdi/geoplatform/gui/impl/tree/ToolbarTreeClientTool.java b/geoplatform-gui/core/geoplatform-configuration/src/main/java/org/geosdi/geoplatform/gui/impl/tree/ToolbarTreeClientTool.java
index 08c3ee2a..287def5f 100644
--- a/geoplatform-gui/core/geoplatform-configuration/src/main/java/org/geosdi/geoplatform/gui/impl/tree/ToolbarTreeClientTool.java
+++ b/geoplatform-gui/core/geoplatform-configuration/src/main/java/org/geosdi/geoplatform/gui/impl/tree/ToolbarTreeClientTool.java
@@ -1,172 +1,172 @@
/*
* geo-platform
* Rich webgis framework
* http://geo-platform.org
* ====================================================================
*
* Copyright (C) 2008-2011 geoSDI Group (CNR IMAA - Potenza - ITALY).
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version. This program is distributed in the
* hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR
* A PARTICULAR PURPOSE. See the GNU General Public License
* for more details. You should have received a copy of the GNU General
* Public License along with this program. If not, see http://www.gnu.org/licenses/
*
* ====================================================================
*
* Linking this library statically or dynamically with other modules is
* making a combined work based on this library. Thus, the terms and
* conditions of the GNU General Public License cover the whole combination.
*
* As a special exception, the copyright holders of this library give you permission
* to link this library with independent modules to produce an executable, regardless
* of the license terms of these independent modules, and to copy and distribute
* the resulting executable under terms of your choice, provided that you also meet,
* for each linked independent module, the terms and conditions of the license of
* that module. An independent module is a module which is not derived from or
* based on this library. If you modify this library, you may extend this exception
* to your version of the library, but you are not obligated to do so. If you do not
* wish to do so, delete this exception statement from your version.
*
*/
package org.geosdi.geoplatform.gui.impl.tree;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.geosdi.geoplatform.gui.configuration.ActionClientTool;
import org.geosdi.geoplatform.gui.configuration.GenericClientTool;
/**
*
* @author Giuseppe La Scaleia - CNR IMAA geoSDI Group
* @email [email protected]
*/
public class ToolbarTreeClientTool {
public static final String TOOLBAR_ADD_FOLDER = "addFolder";
public static final String TOOLBAR_ADD_RASTER = "addRasterLayer";
public static final String TOOLBAR_ADD_VECTOR = "addVectorLayer";
public static final String TOOLBAR_REMOVE_ELEMENT = "removeElement";
public static final String TOOLBAR_SAVE_TREE_STATE = "saveTreeState";
public static final String TOOLBAR_PRINT_TREE_LAYERS = "printTreeLayers";
public static final String TOOLBAR_UPLOAD_SHAPE = "uploadShape";
public static final String TOOLBAR_UPLOAD_KML = "uploadKml";
public static final String TOOLBAR_LOAD_WMS_GETMAP_FROM_URL = "loadWmsGetMapFromUrl";
public static final String TOOLBAR_LOAD_KML_FROM_URL = "loadKmlFromUrl";
public static final String TOOLBAR_PREVIEW_KML_FROM_URL = "previewKmlFromUrl";
//
public static boolean USER_VIEWER; //
//
private List<GenericClientTool> clientTools = new ArrayList<GenericClientTool>();
public ToolbarTreeClientTool() {
this.buildActionTools();
}
private void buildActionTools() {
ActionClientTool addFolder = new ActionClientTool();
addFolder.setId(TOOLBAR_ADD_FOLDER);
addFolder.setType(ActionClientTool.BUTTON);
addFolder.setEnabled(false);
addFolder.setOrder(1);
ActionClientTool addRasterLayer = new ActionClientTool();
addRasterLayer.setId(TOOLBAR_ADD_RASTER);
addRasterLayer.setType(ActionClientTool.BUTTON);
addRasterLayer.setEnabled(false);
addRasterLayer.setOrder(2);
ActionClientTool addVectorLayer = new ActionClientTool();
addVectorLayer.setId(TOOLBAR_ADD_VECTOR);
addVectorLayer.setType(ActionClientTool.BUTTON);
addVectorLayer.setEnabled(false);
addVectorLayer.setOrder(3);
GenericClientTool toolbarSeparator = new GenericClientTool();
toolbarSeparator.setId("ToolbarSeparator");
toolbarSeparator.setOrder(4);
ActionClientTool removeElement = new ActionClientTool();
removeElement.setId(TOOLBAR_REMOVE_ELEMENT);
removeElement.setType(ActionClientTool.BUTTON);
removeElement.setEnabled(false);
removeElement.setOrder(5);
ActionClientTool saveTreeState = new ActionClientTool();
saveTreeState.setId(TOOLBAR_SAVE_TREE_STATE);
saveTreeState.setType(ActionClientTool.BUTTON);
saveTreeState.setEnabled(false);
saveTreeState.setOrder(6);
ActionClientTool printClientTool = new ActionClientTool();
printClientTool.setId(TOOLBAR_PRINT_TREE_LAYERS);
printClientTool.setType(ActionClientTool.BUTTON);
- printClientTool.setEnabled(false);
+ printClientTool.setEnabled(true);
printClientTool.setOrder(7);
GenericClientTool toolbarSeparator2 = new GenericClientTool();
toolbarSeparator2.setId("ToolbarSeparator");
toolbarSeparator2.setOrder(8);
ActionClientTool uploaderClientTool = new ActionClientTool();
uploaderClientTool.setId(TOOLBAR_UPLOAD_SHAPE);
uploaderClientTool.setType(ActionClientTool.BUTTON);
uploaderClientTool.setEnabled(true);
uploaderClientTool.setOrder(9);
ActionClientTool loadWmsGetMapFromURLClientTool = new ActionClientTool();
loadWmsGetMapFromURLClientTool.setId(TOOLBAR_LOAD_WMS_GETMAP_FROM_URL);
loadWmsGetMapFromURLClientTool.setType(ActionClientTool.BUTTON);
loadWmsGetMapFromURLClientTool.setEnabled(false);
loadWmsGetMapFromURLClientTool.setOrder(10);
// ActionClientTool loadKmlFromUrlClientTool = new ActionClientTool();
// loadKmlFromUrlClientTool.setId(TOOLBAR_LOAD_KML_FROM_URL);
// loadKmlFromUrlClientTool.setType(ActionClientTool.BUTTON);
// loadKmlFromUrlClientTool.setEnabled(false);
// loadKmlFromUrlClientTool.setOrder(11);
//
// ActionClientTool uploadKmlClientTool = new ActionClientTool();
// uploadKmlClientTool.setId(TOOLBAR_UPLOAD_KML);
// uploadKmlClientTool.setType(ActionClientTool.BUTTON);
// uploadKmlClientTool.setEnabled(false);
// uploadKmlClientTool.setOrder(12);
ActionClientTool previewKmlClientTool = new ActionClientTool();
previewKmlClientTool.setId(TOOLBAR_PREVIEW_KML_FROM_URL);
previewKmlClientTool.setType(ActionClientTool.BUTTON);
previewKmlClientTool.setEnabled(true);
previewKmlClientTool.setOrder(11);
this.clientTools.add(previewKmlClientTool);
// this.clientTools.add(uploadKmlClientTool);
// this.clientTools.add(loadKmlFromUrlClientTool);
this.clientTools.add(loadWmsGetMapFromURLClientTool);
this.clientTools.add(uploaderClientTool);
this.clientTools.add(toolbarSeparator2);
this.clientTools.add(printClientTool);
// System.out.println("# USER_VIEWER: " + USER_VIEWER);
if (USER_VIEWER == false) { //
this.clientTools.add(saveTreeState);
} //
this.clientTools.add(removeElement);
this.clientTools.add(toolbarSeparator);
this.clientTools.add(addFolder);
this.clientTools.add(addVectorLayer);
this.clientTools.add(addRasterLayer);
Collections.sort(clientTools);
}
/**
* @return the clientTools
*/
public List<GenericClientTool> getClientTools() {
return clientTools;
}
}
| true | true | private void buildActionTools() {
ActionClientTool addFolder = new ActionClientTool();
addFolder.setId(TOOLBAR_ADD_FOLDER);
addFolder.setType(ActionClientTool.BUTTON);
addFolder.setEnabled(false);
addFolder.setOrder(1);
ActionClientTool addRasterLayer = new ActionClientTool();
addRasterLayer.setId(TOOLBAR_ADD_RASTER);
addRasterLayer.setType(ActionClientTool.BUTTON);
addRasterLayer.setEnabled(false);
addRasterLayer.setOrder(2);
ActionClientTool addVectorLayer = new ActionClientTool();
addVectorLayer.setId(TOOLBAR_ADD_VECTOR);
addVectorLayer.setType(ActionClientTool.BUTTON);
addVectorLayer.setEnabled(false);
addVectorLayer.setOrder(3);
GenericClientTool toolbarSeparator = new GenericClientTool();
toolbarSeparator.setId("ToolbarSeparator");
toolbarSeparator.setOrder(4);
ActionClientTool removeElement = new ActionClientTool();
removeElement.setId(TOOLBAR_REMOVE_ELEMENT);
removeElement.setType(ActionClientTool.BUTTON);
removeElement.setEnabled(false);
removeElement.setOrder(5);
ActionClientTool saveTreeState = new ActionClientTool();
saveTreeState.setId(TOOLBAR_SAVE_TREE_STATE);
saveTreeState.setType(ActionClientTool.BUTTON);
saveTreeState.setEnabled(false);
saveTreeState.setOrder(6);
ActionClientTool printClientTool = new ActionClientTool();
printClientTool.setId(TOOLBAR_PRINT_TREE_LAYERS);
printClientTool.setType(ActionClientTool.BUTTON);
printClientTool.setEnabled(false);
printClientTool.setOrder(7);
GenericClientTool toolbarSeparator2 = new GenericClientTool();
toolbarSeparator2.setId("ToolbarSeparator");
toolbarSeparator2.setOrder(8);
ActionClientTool uploaderClientTool = new ActionClientTool();
uploaderClientTool.setId(TOOLBAR_UPLOAD_SHAPE);
uploaderClientTool.setType(ActionClientTool.BUTTON);
uploaderClientTool.setEnabled(true);
uploaderClientTool.setOrder(9);
ActionClientTool loadWmsGetMapFromURLClientTool = new ActionClientTool();
loadWmsGetMapFromURLClientTool.setId(TOOLBAR_LOAD_WMS_GETMAP_FROM_URL);
loadWmsGetMapFromURLClientTool.setType(ActionClientTool.BUTTON);
loadWmsGetMapFromURLClientTool.setEnabled(false);
loadWmsGetMapFromURLClientTool.setOrder(10);
// ActionClientTool loadKmlFromUrlClientTool = new ActionClientTool();
// loadKmlFromUrlClientTool.setId(TOOLBAR_LOAD_KML_FROM_URL);
// loadKmlFromUrlClientTool.setType(ActionClientTool.BUTTON);
// loadKmlFromUrlClientTool.setEnabled(false);
// loadKmlFromUrlClientTool.setOrder(11);
//
// ActionClientTool uploadKmlClientTool = new ActionClientTool();
// uploadKmlClientTool.setId(TOOLBAR_UPLOAD_KML);
// uploadKmlClientTool.setType(ActionClientTool.BUTTON);
// uploadKmlClientTool.setEnabled(false);
// uploadKmlClientTool.setOrder(12);
ActionClientTool previewKmlClientTool = new ActionClientTool();
previewKmlClientTool.setId(TOOLBAR_PREVIEW_KML_FROM_URL);
previewKmlClientTool.setType(ActionClientTool.BUTTON);
previewKmlClientTool.setEnabled(true);
previewKmlClientTool.setOrder(11);
this.clientTools.add(previewKmlClientTool);
// this.clientTools.add(uploadKmlClientTool);
// this.clientTools.add(loadKmlFromUrlClientTool);
this.clientTools.add(loadWmsGetMapFromURLClientTool);
this.clientTools.add(uploaderClientTool);
this.clientTools.add(toolbarSeparator2);
this.clientTools.add(printClientTool);
// System.out.println("# USER_VIEWER: " + USER_VIEWER);
if (USER_VIEWER == false) { //
this.clientTools.add(saveTreeState);
} //
this.clientTools.add(removeElement);
this.clientTools.add(toolbarSeparator);
this.clientTools.add(addFolder);
this.clientTools.add(addVectorLayer);
this.clientTools.add(addRasterLayer);
Collections.sort(clientTools);
}
| private void buildActionTools() {
ActionClientTool addFolder = new ActionClientTool();
addFolder.setId(TOOLBAR_ADD_FOLDER);
addFolder.setType(ActionClientTool.BUTTON);
addFolder.setEnabled(false);
addFolder.setOrder(1);
ActionClientTool addRasterLayer = new ActionClientTool();
addRasterLayer.setId(TOOLBAR_ADD_RASTER);
addRasterLayer.setType(ActionClientTool.BUTTON);
addRasterLayer.setEnabled(false);
addRasterLayer.setOrder(2);
ActionClientTool addVectorLayer = new ActionClientTool();
addVectorLayer.setId(TOOLBAR_ADD_VECTOR);
addVectorLayer.setType(ActionClientTool.BUTTON);
addVectorLayer.setEnabled(false);
addVectorLayer.setOrder(3);
GenericClientTool toolbarSeparator = new GenericClientTool();
toolbarSeparator.setId("ToolbarSeparator");
toolbarSeparator.setOrder(4);
ActionClientTool removeElement = new ActionClientTool();
removeElement.setId(TOOLBAR_REMOVE_ELEMENT);
removeElement.setType(ActionClientTool.BUTTON);
removeElement.setEnabled(false);
removeElement.setOrder(5);
ActionClientTool saveTreeState = new ActionClientTool();
saveTreeState.setId(TOOLBAR_SAVE_TREE_STATE);
saveTreeState.setType(ActionClientTool.BUTTON);
saveTreeState.setEnabled(false);
saveTreeState.setOrder(6);
ActionClientTool printClientTool = new ActionClientTool();
printClientTool.setId(TOOLBAR_PRINT_TREE_LAYERS);
printClientTool.setType(ActionClientTool.BUTTON);
printClientTool.setEnabled(true);
printClientTool.setOrder(7);
GenericClientTool toolbarSeparator2 = new GenericClientTool();
toolbarSeparator2.setId("ToolbarSeparator");
toolbarSeparator2.setOrder(8);
ActionClientTool uploaderClientTool = new ActionClientTool();
uploaderClientTool.setId(TOOLBAR_UPLOAD_SHAPE);
uploaderClientTool.setType(ActionClientTool.BUTTON);
uploaderClientTool.setEnabled(true);
uploaderClientTool.setOrder(9);
ActionClientTool loadWmsGetMapFromURLClientTool = new ActionClientTool();
loadWmsGetMapFromURLClientTool.setId(TOOLBAR_LOAD_WMS_GETMAP_FROM_URL);
loadWmsGetMapFromURLClientTool.setType(ActionClientTool.BUTTON);
loadWmsGetMapFromURLClientTool.setEnabled(false);
loadWmsGetMapFromURLClientTool.setOrder(10);
// ActionClientTool loadKmlFromUrlClientTool = new ActionClientTool();
// loadKmlFromUrlClientTool.setId(TOOLBAR_LOAD_KML_FROM_URL);
// loadKmlFromUrlClientTool.setType(ActionClientTool.BUTTON);
// loadKmlFromUrlClientTool.setEnabled(false);
// loadKmlFromUrlClientTool.setOrder(11);
//
// ActionClientTool uploadKmlClientTool = new ActionClientTool();
// uploadKmlClientTool.setId(TOOLBAR_UPLOAD_KML);
// uploadKmlClientTool.setType(ActionClientTool.BUTTON);
// uploadKmlClientTool.setEnabled(false);
// uploadKmlClientTool.setOrder(12);
ActionClientTool previewKmlClientTool = new ActionClientTool();
previewKmlClientTool.setId(TOOLBAR_PREVIEW_KML_FROM_URL);
previewKmlClientTool.setType(ActionClientTool.BUTTON);
previewKmlClientTool.setEnabled(true);
previewKmlClientTool.setOrder(11);
this.clientTools.add(previewKmlClientTool);
// this.clientTools.add(uploadKmlClientTool);
// this.clientTools.add(loadKmlFromUrlClientTool);
this.clientTools.add(loadWmsGetMapFromURLClientTool);
this.clientTools.add(uploaderClientTool);
this.clientTools.add(toolbarSeparator2);
this.clientTools.add(printClientTool);
// System.out.println("# USER_VIEWER: " + USER_VIEWER);
if (USER_VIEWER == false) { //
this.clientTools.add(saveTreeState);
} //
this.clientTools.add(removeElement);
this.clientTools.add(toolbarSeparator);
this.clientTools.add(addFolder);
this.clientTools.add(addVectorLayer);
this.clientTools.add(addRasterLayer);
Collections.sort(clientTools);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.