answer
stringlengths 17
10.2M
|
|---|
package net.emaze.dysfunctional.multiplexing;
import java.util.Iterator;
import java.util.List;
import net.emaze.dysfunctional.adapting.ArrayIterator;
import net.emaze.dysfunctional.delegates.IteratorPlucker;
import net.emaze.dysfunctional.iterations.Iterations;
import net.emaze.dysfunctional.options.Maybe;
/**
*
* @author rferranti
*/
public abstract class Multiplexing {
/**
*
* @param <E>
* @param <T>
* @param iterators
* @return
*/
public static <E, T extends Iterable<E>> Iterator<E> flatten(Iterator<T> iterators) {
return new ChainIterator<E>(Iterations.transform(iterators, new IteratorPlucker<E, T>()));
}
/**
*
* @param <E>
* @param <T>
* @param iterators
* @return
*/
public static <E, T extends Iterable<E>> Iterator<E> flatten(Iterable<T> iterators) {
return flatten(iterators.iterator());
}
/**
*
* @param <E>
* @param <T>
* @param array
* @return
*/
public static <E, T extends Iterable<E>> Iterator<E> flatten(T[] array) {
return flatten(new ArrayIterator<T>(array));
}
/**
*
* @param <E>
* @param iterators
* @return
*/
public static <E> Iterator<E> chain(Iterator<E>... iterators) {
return new ChainIterator<E>(iterators);
}
/**
*
* @param <E>
* @param iterators
* @return
*/
public static <E> Iterator<E> chain(Iterator<Iterator<E>> iterators) {
return new ChainIterator<E>(iterators);
}
/**
*
* @param <E>
* @param iterables
* @return
*/
public static <E> Iterator<E> chain(Iterable<Iterator<E>> iterables) {
return new ChainIterator<E>(iterables.iterator());
}
/**
*
* @param <E>
* @param iterators
* @return
*/
public static <E> Iterator<E> mux(Iterator<Iterator<E>> iterators) {
return new MultiplexingIterator<E>(iterators);
}
/**
*
* @param <E>
* @param iterators
* @return
*/
public static <E> Iterator<E> mux(Iterable<Iterator<E>> iterators) {
return mux(iterators.iterator());
}
/**
*
* @param <E>
* @param iterators
* @return
*/
public static <E> Iterator<E> mux(Iterator<E>[] iterators) {
return mux(new ArrayIterator<Iterator<E>>(iterators));
}
/**
*
* @param <E>
* @param iterators
* @return
*/
public static <E> Iterator<Maybe<E>> muxl(Iterator<Iterator<E>> iterators) {
return new PreciseMultiplexingIterator<E>(iterators);
}
/**
*
* @param <E>
* @param iterators
* @return
*/
public static <E> Iterator<Maybe<E>> muxl(Iterable<Iterator<E>> iterators) {
return muxl(iterators.iterator());
}
/**
*
* @param <E>
* @param iterators
* @return
*/
public static <E> Iterator<Maybe<E>> muxl(Iterator<E>[] iterators) {
return muxl(new ArrayIterator<Iterator<E>>(iterators));
}
/**
*
* @param <E>
* @param channelSize
* @param iterator
* @return
*/
public static <E> Iterator<List<E>> demux(int channelSize, Iterator<E> iterator) {
return new DemultiplexingIterator<E>(channelSize, iterator);
}
/**
*
* @param <E>
* @param channelSize
* @param iterable
* @return
*/
public static <E> Iterator<List<E>> demux(int channelSize, Iterable<E> iterable) {
return demux(channelSize, iterable.iterator());
}
/**
*
* @param <E>
* @param channelSize
* @param array
* @return
*/
public static <E> Iterator<List<E>> demux(int channelSize, E[] array) {
return demux(channelSize, new ArrayIterator<E>(array));
}
/**
*
* @param <E>
* @param channelSize
* @param iterator
* @return
*/
public static <E> Iterator<List<Maybe<E>>> demuxl(int channelSize, Iterator<Maybe<E>> iterator) {
return new PreciseDemultiplexingIterator<E>(channelSize, iterator);
}
/**
*
* @param <E>
* @param channelSize
* @param iterable
* @return
*/
public static <E> Iterator<List<Maybe<E>>> demuxl(int channelSize, Iterable<Maybe<E>> iterable) {
return new PreciseDemultiplexingIterator<E>(channelSize, iterable.iterator());
}
/**
*
* @param <E>
* @param channelSize
* @param array
* @return
*/
public static <E> Iterator<List<Maybe<E>>> demuxl(int channelSize, Maybe<E>[] array) {
return demuxl(channelSize, new ArrayIterator<Maybe<E>>(array));
}
/**
*
* @param <E>
* @param iterators
* @return
*/
public static <E> Iterator<E> roundrobin(Iterator<Iterator<E>> iterators) {
return new RoundRobinIterator<E>(iterators);
}
/**
*
* @param <E>
* @param iterators
* @return
*/
public static <E> Iterator<E> roundrobin(Iterable<Iterator<E>> iterators) {
return new RoundRobinIterator<E>(iterators.iterator());
}
/**
*
* @param <E>
* @param iterators
* @return
*/
public static <E> Iterator<E> roundrobin(Iterator<E>[] iterators) {
return new RoundRobinIterator<E>(new ArrayIterator<Iterator<E>>(iterators));
}
}
|
package org.openqa.selenium.net;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static java.util.concurrent.TimeUnit.NANOSECONDS;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Throwables;
import com.google.common.util.concurrent.SimpleTimeLimiter;
import com.google.common.util.concurrent.TimeLimiter;
import com.google.common.util.concurrent.UncheckedTimeoutException;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.logging.Logger;
/**
* Polls a URL until a HTTP 200 response is received.
*/
public class UrlChecker {
private static final Logger log = Logger.getLogger(UrlChecker.class.getName());
private static final int CONNECT_TIMEOUT_MS = 500;
private static final int READ_TIMEOUT_MS = 1000;
private static final long POLL_INTERVAL_MS = 500;
private final TimeLimiter timeLimiter;
public UrlChecker() {
this(createSimpleTimeLimiter());
}
@VisibleForTesting
UrlChecker(TimeLimiter timeLimiter) {
this.timeLimiter = timeLimiter;
}
private static TimeLimiter createSimpleTimeLimiter() {
ExecutorService executor = Executors.newFixedThreadPool(1);
return new SimpleTimeLimiter(executor);
}
public void waitUntilAvailable(long timeout, TimeUnit unit, final URL... urls)
throws TimeoutException {
long start = System.nanoTime();
log.fine("Waiting for " + urls);
try {
timeLimiter.callWithTimeout(new Callable<Void>() {
public Void call() throws InterruptedException {
HttpURLConnection connection = null;
while (true) {
for (URL url : urls) {
try {
log.fine("Polling " + url);
connection = connectToUrl(url);
if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
return null;
}
} catch (IOException e) {
// Ok, try again.
} finally {
if (connection != null) {
connection.disconnect();
}
}
}
MILLISECONDS.sleep(POLL_INTERVAL_MS);
}
}
}, timeout, unit, true);
} catch (UncheckedTimeoutException e) {
throw new TimeoutException(String.format(
"Timed out waiting for %s to be available after %d ms",
urls, MILLISECONDS.convert(System.nanoTime() - start, NANOSECONDS)), e);
} catch (Exception e) {
throw Throwables.propagate(e);
}
}
public void waitUntilUnavailable(long timeout, TimeUnit unit, final URL url)
throws TimeoutException {
long start = System.nanoTime();
log.fine("Waiting for " + url);
try {
timeLimiter.callWithTimeout(new Callable<Void>() {
public Void call() throws InterruptedException {
HttpURLConnection connection = null;
while (true) {
try {
log.fine("Polling " + url);
connection = connectToUrl(url);
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
return null;
}
} catch (IOException e) {
return null;
} finally {
if (connection != null) {
connection.disconnect();
}
}
MILLISECONDS.sleep(POLL_INTERVAL_MS);
}
}
}, timeout, unit, true);
} catch (UncheckedTimeoutException e) {
throw new TimeoutException(String.format(
"Timed out waiting for %s to become unavailable after %d ms",
url, MILLISECONDS.convert(System.nanoTime() - start, NANOSECONDS)), e);
} catch (Exception e) {
throw Throwables.propagate(e);
}
}
private HttpURLConnection connectToUrl(URL url) throws IOException {
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setConnectTimeout(CONNECT_TIMEOUT_MS);
connection.setReadTimeout(READ_TIMEOUT_MS);
connection.connect();
return connection;
}
public static class TimeoutException extends Exception {
public TimeoutException(String s, Throwable throwable) {
super(s, throwable);
}
}
}
|
package org.apache.lenya.cms.cocoon.acting;
import org.apache.avalon.framework.configuration.Configuration;
import org.apache.avalon.framework.configuration.ConfigurationException;
import org.apache.avalon.framework.parameters.Parameters;
import org.apache.avalon.framework.thread.ThreadSafe;
import org.apache.cocoon.acting.AbstractConfigurableAction;
import org.apache.cocoon.environment.Redirector;
import org.apache.cocoon.environment.Request;
import org.apache.cocoon.environment.SourceResolver;
import org.apache.cocoon.environment.http.HttpRequest;
import org.apache.cocoon.environment.ObjectModelHelper;
import org.apache.cocoon.servlet.multipart.Part;
import org.apache.cocoon.util.PostInputStream;
import org.apache.lenya.xml.DocumentHelper;
import org.apache.cocoon.xml.dom.DOMUtil;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import java.io.*;
import java.util.*;
import java.util.Enumeration;
import java.net.URL;
/**
* @author Michael Wechner
* @version $Id: HTMLFormSaveAction.java,v 1.12 2003/08/20 16:31:32 michi Exp $
*/
public class HTMLFormSaveAction extends AbstractConfigurableAction implements ThreadSafe {
/**
* Describe <code>configure</code> method here.
*
* @param conf a <code>Configuration</code> value
*
* @exception ConfigurationException if an error occurs
*/
public void configure(Configuration conf) throws ConfigurationException {
super.configure(conf);
}
/**
* Save blog entry to file
*
* @param redirector a <code>Redirector</code> value
* @param resolver a <code>SourceResolver</code> value
* @param objectModel a <code>Map</code> value
* @param source a <code>String</code> value
* @param parameters a <code>Parameters</code> value
*
* @return a <code>Map</code> value
*
* @exception Exception if an error occurs
*/
public Map act(Redirector redirector, SourceResolver resolver, Map objectModel, String source, Parameters parameters) throws Exception {
File sitemap = new File(new URL(resolver.resolveURI("").getURI()).getFile());
File file = new File(sitemap.getAbsolutePath() + File.separator + parameters.getParameter("file"));
Request request = ObjectModelHelper.getRequest(objectModel);
getLogger().error(".act(): File: " + file.getAbsolutePath());
if(request.getParameter("cancel") != null) {
getLogger().error(".act(): Cancel editing");
return null;
} else {
if(file.isFile()) {
getLogger().error(".act(): Save modifications to " + file.getAbsolutePath());
try {
Document document = DocumentHelper.readDocument(file);
Enumeration params = request.getParameterNames();
while (params.hasMoreElements()) {
String name = (String) params.nextElement();
getLogger().debug(".act(): Parameter: " + name + " (" + request.getParameter(name) + ")");
if (name.indexOf("element.") == 0) { // Update Element
String xpath = name.substring(8, name.indexOf("["));
String tagID = name.substring(name.indexOf("[") + 1, name.indexOf("]"));
xpath = xpath + "[@tagID=\"" + tagID + "\"]";
getLogger().error(".act() Update Element: XPath: " + xpath);
setNodeValue(document, request.getParameter(name), xpath);
} else if (name.equals("insert")) { // Insert Element
getLogger().error(".act(): Insert Element: " + request.getParameter("insert"));
String value = request.getParameter("insert");
String xpathSibling = value.substring(8, value.indexOf("["));
String tagID = value.substring(value.indexOf("[") + 1, value.indexOf("]"));
xpathSibling = xpathSibling + "[@tagID=\"" + tagID + "\"]";
String xpathElement = value.substring(value.indexOf("element.") + 8);
getLogger().error(".act() Sibling: XPath: " + xpathSibling);
getLogger().error(".act() Insert Element: XPath: " + xpathElement);
// FIXME: insert-after and insert-before remains to be implemented
// FIXME: insert parents and required children (see XUpdate)
new org.apache.lenya.xml.DOMUtil().addElement(document, xpathElement, "My text");
} else if (name.equals("delete")) { // Delete Element
String value = request.getParameter("delete");
String xpath = value.substring(8, value.indexOf("["));
String tagID = value.substring(value.indexOf("[") + 1, value.indexOf("]"));
xpath = xpath + "[@tagID=\"" + tagID + "\"]";
getLogger().error(".act() Delete Element: XPath: " + xpath);
//DOMUtil.deleteElement(document, xpath);
Node node = DOMUtil.getSingleNode(document.getDocumentElement(), xpath);
Node parent = node.getParentNode();
parent.removeChild(node);
}
}
DocumentHelper.writeDocument(document, file);
if(request.getParameter("save") != null) {
getLogger().error(".act(): Save");
return null;
} else {
return new HashMap();
}
} catch (Exception e) {
getLogger().error(".act(): Exception: " + e.getMessage(), e);
HashMap hmap = new HashMap();
hmap.put("message", e.getMessage());
return hmap;
}
} else {
getLogger().error(".act(): No such file: " + file.getAbsolutePath());
HashMap hmap = new HashMap();
hmap.put("message", "No such file: " + file.getAbsolutePath());
return hmap;
}
}
}
private void setNodeValue(Document document, String value, String xpath) throws Exception {
// FIXME: org.apache.xpath.compiler.XPathParser seems to have problems when namespaces are not declared within the root element. Unfortunately the XSLTs (during Cocoon transformation) are moving the namespaces to the elements which use them! One hack might be to parse the tree for namespaces (Node.getNamespaceURI), collect them and add them to the document root element, before sending it through the org.apache.xpath.compiler.XPathParser (called by XPathAPI)
// FIXME: There seems to be another problem with default namespaces
//new org.apache.lenya.xml.DOMUtil().setElementValue(document, xpath, value);
//Node node = DOMUtil.getSingleNode(document.getDocumentElement(), xpath);
Node node = org.apache.xpath.XPathAPI.selectSingleNode(document, xpath);
if (node == null) {
// FIXME: warn
getLogger().error(".setNodeValue(): Node does not exist (might have been deleted during update): " + xpath);
return;
}
// FIXME: debug
getLogger().error(".setNodeValue(): value = " + DOMUtil.getValueOfNode(node));
DOMUtil.setValueOfNode(node, value);
// FIXME: debug
getLogger().error(".setNodeValue(): value = " + DOMUtil.getValueOfNode(node));
}
}
|
package com.ds.listing.rest;
import java.util.ArrayList;
import com.ds.listing.model.Listing;
import com.ds.listing.properties.eBayAuth;
import com.ds.listing.services.ListingService;
import com.ds.listing.services.eBayListingService;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
@Path("/ebay")
public class EBayRestService {
@Inject
private eBayAuth auth;
@Inject
private ListingService listService;
@PersistenceContext(unitName="primary")
private EntityManager em;
@GET
@Path("/{page:[0-9][0-9]*/{perpage:[0-9][0-9]*}")
@Produces(MediaType.APPLICATION_JSON)
public UnsoldListData GetUnSold(@PathParam("page") int page, @PathParam("perpage") int perpage){
UnsoldListData returnData = new UnsoldListData();
ArrayList<String> retStrings = new ArrayList<>();
eBayListingService eBayService = new eBayListingService(auth.getApiContext());
ArrayList<Listing> listings = new ArrayList<>();
eBayService.getCurrentListings(page, perpage, returnData);
returnData.setListings(listings);
return returnData;
}
}
|
package com.couchbase.cblite.testapp.tests;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.Map;
import java.util.Observable;
import java.util.Observer;
import java.util.concurrent.CountDownLatch;
import junit.framework.Assert;
import android.os.AsyncTask;
import android.util.Log;
import com.couchbase.cblite.CBLBody;
import com.couchbase.cblite.CBLDatabase;
import com.couchbase.cblite.CBLRevision;
import com.couchbase.cblite.CBLStatus;
import com.couchbase.cblite.auth.CBLFacebookAuthorizer;
import com.couchbase.cblite.replicator.CBLPusher;
import com.couchbase.cblite.replicator.CBLReplicator;
import com.couchbase.cblite.support.Base64;
import org.apache.commons.io.IOUtils;
import org.apache.commons.io.output.ByteArrayOutputStream;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.entity.StringEntity;
import org.apache.http.message.BasicHeader;
public class Replicator extends CBLiteTestCase {
public static final String TAG = "Replicator";
public String testPusher() throws Throwable {
CountDownLatch replicationDoneSignal = new CountDownLatch(1);
URL remote = getReplicationURL();
String docIdTimestamp = Long.toString(System.currentTimeMillis());
// Create some documents:
Map<String, Object> documentProperties = new HashMap<String, Object>();
final String doc1Id = String.format("doc1-%s", docIdTimestamp);
documentProperties.put("_id", doc1Id);
documentProperties.put("foo", 1);
documentProperties.put("bar", false);
CBLBody body = new CBLBody(documentProperties);
CBLRevision rev1 = new CBLRevision(body, database);
CBLStatus status = new CBLStatus();
rev1 = database.putRevision(rev1, null, false, status);
Assert.assertEquals(CBLStatus.CREATED, status.getCode());
documentProperties.put("_rev", rev1.getRevId());
documentProperties.put("UPDATED", true);
@SuppressWarnings("unused")
CBLRevision rev2 = database.putRevision(new CBLRevision(documentProperties, database), rev1.getRevId(), false, status);
Assert.assertEquals(CBLStatus.CREATED, status.getCode());
documentProperties = new HashMap<String, Object>();
String doc2Id = String.format("doc2-%s", docIdTimestamp);
documentProperties.put("_id", doc2Id);
documentProperties.put("baz", 666);
documentProperties.put("fnord", true);
database.putRevision(new CBLRevision(documentProperties, database), null, false, status);
Assert.assertEquals(CBLStatus.CREATED, status.getCode());
final CBLReplicator repl = database.getReplicator(remote, true, false, server.getWorkExecutor());
((CBLPusher)repl).setCreateTarget(true);
AsyncTask replicationTask = new AsyncTask<Object, Object, Object>() {
@Override
protected Object doInBackground(Object... aParams) {
// Push them to the remote:
repl.start();
Assert.assertTrue(repl.isRunning());
return null;
}
};
replicationTask.execute();
ReplicationObserver replicationObserver = new ReplicationObserver(replicationDoneSignal);
repl.addObserver(replicationObserver);
Log.d(TAG, "Waiting for replicator to finish");
try {
replicationDoneSignal.await();
Log.d(TAG, "replicator finished");
} catch (InterruptedException e) {
e.printStackTrace();
}
// make sure doc1 is there
// TODO: make sure doc2 is there (refactoring needed)
URL replicationUrlTrailing = new URL(String.format("%s/", remote.toExternalForm()));
final URL pathToDoc = new URL(replicationUrlTrailing, doc1Id);
Log.d(TAG, "Send http request to " + pathToDoc);
final CountDownLatch httpRequestDoneSignal = new CountDownLatch(1);
AsyncTask getDocTask = new AsyncTask<Object, Object, Object>() {
@Override
protected Object doInBackground(Object... aParams) {
org.apache.http.client.HttpClient httpclient = new DefaultHttpClient();
HttpResponse response;
String responseString = null;
try {
response = httpclient.execute(new HttpGet(pathToDoc.toExternalForm()));
StatusLine statusLine = response.getStatusLine();
Assert.assertTrue(statusLine.getStatusCode() == HttpStatus.SC_OK);
if(statusLine.getStatusCode() == HttpStatus.SC_OK){
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
responseString = out.toString();
Assert.assertTrue(responseString.contains(doc1Id));
Log.d(TAG, "result: " + responseString);
} else{
//Closes the connection.
response.getEntity().getContent().close();
throw new IOException(statusLine.getReasonPhrase());
}
} catch (ClientProtocolException e) {
Assert.assertNull("Got ClientProtocolException: " + e.getLocalizedMessage(), e);
} catch (IOException e) {
Assert.assertNull("Got IOException: " + e.getLocalizedMessage(), e);
}
httpRequestDoneSignal.countDown();
return null;
}
};
getDocTask.execute();
Log.d(TAG, "Waiting for http request to finish");
try {
httpRequestDoneSignal.await();
Log.d(TAG, "http request finished");
} catch (InterruptedException e) {
e.printStackTrace();
}
Log.d(TAG, "testPusher() finished");
return docIdTimestamp;
}
public void testPusherDeletedDoc() throws Throwable {
CountDownLatch replicationDoneSignal = new CountDownLatch(1);
URL remote = getReplicationURL();
String docIdTimestamp = Long.toString(System.currentTimeMillis());
// Create some documents:
Map<String, Object> documentProperties = new HashMap<String, Object>();
final String doc1Id = String.format("doc1-%s", docIdTimestamp);
documentProperties.put("_id", doc1Id);
documentProperties.put("foo", 1);
documentProperties.put("bar", false);
CBLBody body = new CBLBody(documentProperties);
CBLRevision rev1 = new CBLRevision(body, database);
CBLStatus status = new CBLStatus();
rev1 = database.putRevision(rev1, null, false, status);
Assert.assertEquals(CBLStatus.CREATED, status.getCode());
documentProperties.put("_rev", rev1.getRevId());
documentProperties.put("UPDATED", true);
documentProperties.put("_deleted", true);
@SuppressWarnings("unused")
final CBLReplicator repl = database.getReplicator(remote, true, false, server.getWorkExecutor());
((CBLPusher)repl).setCreateTarget(true);
AsyncTask replicationTask = new AsyncTask<Object, Object, Object>() {
@Override
protected Object doInBackground(Object... aParams) {
// Push them to the remote:
repl.start();
Assert.assertTrue(repl.isRunning());
return null;
}
};
replicationTask.execute();
ReplicationObserver replicationObserver = new ReplicationObserver(replicationDoneSignal);
repl.addObserver(replicationObserver);
Log.d(TAG, "Waiting for replicator to finish");
try {
replicationDoneSignal.await();
Log.d(TAG, "replicator finished");
} catch (InterruptedException e) {
e.printStackTrace();
}
// make sure doc1 is deleted
URL replicationUrlTrailing = new URL(String.format("%s/", remote.toExternalForm()));
final URL pathToDoc = new URL(replicationUrlTrailing, doc1Id);
Log.d(TAG, "Send http request to " + pathToDoc);
final CountDownLatch httpRequestDoneSignal = new CountDownLatch(1);
AsyncTask getDocTask = new AsyncTask<Object, Object, Object>() {
@Override
protected Object doInBackground(Object... aParams) {
org.apache.http.client.HttpClient httpclient = new DefaultHttpClient();
HttpResponse response;
String responseString = null;
try {
response = httpclient.execute(new HttpGet(pathToDoc.toExternalForm()));
StatusLine statusLine = response.getStatusLine();
return statusLine;
} catch (ClientProtocolException e) {
Assert.assertNull("Got ClientProtocolException: " + e.getLocalizedMessage(), e);
} catch (IOException e) {
Assert.assertNull("Got IOException: " + e.getLocalizedMessage(), e);
}
httpRequestDoneSignal.countDown();
return null;
}
@Override
protected void onPostExecute(Object o) {
StatusLine statusLine = (StatusLine) o;
Assert.assertEquals(HttpStatus.SC_NOT_FOUND, statusLine.getStatusCode());
}
};
getDocTask.execute();
Log.d(TAG, "Waiting for http request to finish");
try {
httpRequestDoneSignal.await();
Log.d(TAG, "http request finished");
} catch (InterruptedException e) {
e.printStackTrace();
}
Log.d(TAG, "testPusherDeletedDoc() finished");
}
public void testPuller() throws Throwable {
String docIdTimestamp = Long.toString(System.currentTimeMillis());
final String doc1Id = String.format("doc1-%s", docIdTimestamp);
final String doc2Id = String.format("doc2-%s", docIdTimestamp);
addDocWithId(doc1Id, "attachment.png");
addDocWithId(doc2Id, "attachment2.png");
URL remote = getReplicationURL();
CountDownLatch replicationDoneSignal = new CountDownLatch(1);
final CBLReplicator repl = database.getReplicator(remote, false, false, server.getWorkExecutor());
AsyncTask replicationTask = new AsyncTask<Object, Object, Object>() {
@Override
protected Object doInBackground(Object... aParams) {
// Push them to the remote:
repl.start();
Assert.assertTrue(repl.isRunning());
return null;
}
};
replicationTask.execute();
ReplicationObserver replicationObserver = new ReplicationObserver(replicationDoneSignal);
repl.addObserver(replicationObserver);
Log.d(TAG, "Waiting for replicator to finish");
try {
replicationDoneSignal.await();
Log.d(TAG, "replicator finished");
} catch (InterruptedException e) {
e.printStackTrace();
}
CBLRevision doc1 = database.getDocumentWithIDAndRev(doc1Id, null, EnumSet.noneOf(CBLDatabase.TDContentOptions.class));
Assert.assertNotNull(doc1);
Assert.assertTrue(doc1.getRevId().startsWith("1-"));
Assert.assertEquals(1, doc1.getProperties().get("foo"));
CBLRevision doc2 = database.getDocumentWithIDAndRev(doc2Id, null, EnumSet.noneOf(CBLDatabase.TDContentOptions.class));
Assert.assertNotNull(doc2);
Assert.assertTrue(doc2.getRevId().startsWith("1-"));
Assert.assertEquals(1, doc2.getProperties().get("foo"));
Log.d(TAG, "testPuller() finished");
}
private void addDocWithId(String docId, String attachmentName) throws IOException {
// add attachment to document
InputStream attachmentStream = getInstrumentation().getContext().getAssets().open(attachmentName);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
IOUtils.copy(attachmentStream, baos);
String attachmentBase64 = Base64.encodeBytes(baos.toByteArray());
// push a document to server
final String doc1Json = String.format("{\"foo\":1,\"bar\":false, \"_attachments\": { \"i_use_couchdb.png\": { \"content_type\": \"image/png\", \"data\": \"%s\" } } }", attachmentBase64);
URL replicationUrlTrailingDoc1 = new URL(String.format("%s/%s", getReplicationURL().toExternalForm(), docId));
final URL pathToDoc1 = new URL(replicationUrlTrailingDoc1, docId);
Log.d(TAG, "Send http request to " + pathToDoc1);
final CountDownLatch httpRequestDoneSignal = new CountDownLatch(1);
AsyncTask getDocTask = new AsyncTask<Object, Object, Object>() {
@Override
protected Object doInBackground(Object... aParams) {
org.apache.http.client.HttpClient httpclient = new DefaultHttpClient();
HttpResponse response;
String responseString = null;
try {
HttpPut post = new HttpPut(pathToDoc1.toExternalForm());
StringEntity se = new StringEntity( doc1Json.toString() );
se.setContentType(new BasicHeader("content_type", "application/json"));
post.setEntity(se);
response = httpclient.execute(post);
StatusLine statusLine = response.getStatusLine();
Log.d(TAG, "Got response: " + statusLine);
Assert.assertTrue(statusLine.getStatusCode() == HttpStatus.SC_CREATED);
} catch (ClientProtocolException e) {
Assert.assertNull("Got ClientProtocolException: " + e.getLocalizedMessage(), e);
} catch (IOException e) {
Assert.assertNull("Got IOException: " + e.getLocalizedMessage(), e);
}
httpRequestDoneSignal.countDown();
return null;
}
};
getDocTask.execute();
Log.d(TAG, "Waiting for http request to finish");
try {
httpRequestDoneSignal.await();
Log.d(TAG, "http request finished");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void testGetReplicator() throws Throwable {
Map<String,Object> properties = new HashMap<String,Object>();
properties.put("source", DEFAULT_TEST_DB);
properties.put("target", getReplicationURL().toExternalForm());
CBLReplicator replicator = server.getManager().getReplicator(properties);
Assert.assertNotNull(replicator);
Assert.assertEquals(getReplicationURL().toExternalForm(), replicator.getRemote().toExternalForm());
Assert.assertTrue(replicator.isPush());
Assert.assertFalse(replicator.isContinuous());
Assert.assertFalse(replicator.isRunning());
// start the replicator
replicator.start();
// now lets lookup existing replicator and stop it
properties.put("cancel", true);
CBLReplicator activeReplicator = server.getManager().getReplicator(properties);
activeReplicator.stop();
Assert.assertFalse(activeReplicator.isRunning());
}
public void testGetReplicatorWithAuth() throws Throwable {
Map<String, Object> properties = getPushReplicationParsedJson();
CBLReplicator replicator = server.getManager().getReplicator(properties);
Assert.assertNotNull(replicator);
Assert.assertNotNull(replicator.getAuthorizer());
Assert.assertTrue(replicator.getAuthorizer() instanceof CBLFacebookAuthorizer);
}
public void testReplicatorErrorStatus() throws Exception {
// register bogus fb token
Map<String,Object> facebookTokenInfo = new HashMap<String,Object>();
facebookTokenInfo.put("email", "jchris@couchbase.com");
facebookTokenInfo.put("remote_url", getReplicationURL().toExternalForm());
facebookTokenInfo.put("access_token", "fake_access_token");
String destUrl = String.format("/_facebook_token", DEFAULT_TEST_DB);
Map<String,Object> result = (Map<String,Object>)sendBody(server, "POST", destUrl, facebookTokenInfo, CBLStatus.OK, null);
Log.v(TAG, String.format("result %s", result));
// start a replicator
Map<String,Object> properties = getPullReplicationParsedJson();
CBLReplicator replicator = server.getManager().getReplicator(properties);
replicator.start();
// wait a few seconds
Thread.sleep(5 * 1000);
// expect an error since it will try to contact the sync gateway with this bogus login,
// and the sync gateway will reject it.
ArrayList<Object> activeTasks = (ArrayList<Object>)send(server, "GET", "/_active_tasks", CBLStatus.OK, null);
Log.d(TAG, "activeTasks: " + activeTasks);
Map<String,Object> activeTaskReplication = (Map<String,Object>) activeTasks.get(0);
Assert.assertNotNull(activeTaskReplication.get("error"));
}
class ReplicationObserver implements Observer {
public boolean replicationFinished = false;
private CountDownLatch doneSignal;
public ReplicationObserver(CountDownLatch doneSignal) {
super();
this.doneSignal = doneSignal;
}
@Override
public void update(Observable observable, Object data) {
Log.d(TAG, "ReplicationObserver.update called. observable: " + observable);
CBLReplicator replicator = (CBLReplicator) observable;
if (!replicator.isRunning()) {
replicationFinished = true;
String msg = String.format("myobserver.update called, set replicationFinished to: %b", replicationFinished);
Log.d(TAG, msg);
doneSignal.countDown();
}
else {
String msg = String.format("myobserver.update called, but replicator still running, so ignore it");
Log.d(TAG, msg);
}
}
boolean isReplicationFinished() {
return replicationFinished;
}
}
}
|
package bwyap.familyfeud.game.state;
import bwyap.familyfeud.game.InvalidDataException;
import bwyap.familyfeud.game.QuestionSet;
import bwyap.familyfeud.res.JSONQuestionSet;
public class StateLoadQuestions extends FFState {
// ACTIONS
public static final int ACTION_LOADQUESTIONSET = 0x0;
private QuestionSet questions;
protected StateLoadQuestions(QuestionSet questions) {
super(FFStateType.LOAD_QUESTIONS);
this.questions = questions;
}
@Override
public void initState(Object data) { }
@Override
public void cleanupState() { }
@Override
public boolean executeAction(int action, Object[] data) {
switch(action) {
case ACTION_LOADQUESTIONSET:
if (data[0] instanceof JSONQuestionSet) {
loadQuestionSet((JSONQuestionSet) data[0]);
}
else throw new InvalidDataException("Expecting a {JSONQuestionSet} when using action ACTION_LOADQUESTIONSET");
break;
}
return false;
}
/**
* Load a set of questions from a JSONQuestionSet object
* @param familyName
*/
private void loadQuestionSet(JSONQuestionSet data) {
questions.loadFromJSON(data);
}
}
|
package com.facebook.litho;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.pm.ApplicationInfo;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.support.annotation.Nullable;
import android.support.annotation.VisibleForTesting;
import android.support.v4.util.LongSparseArray;
import android.support.v4.view.accessibility.AccessibilityManagerCompat;
import android.text.TextUtils;
import android.view.View;
import android.view.accessibility.AccessibilityManager;
import com.facebook.litho.config.ComponentsConfiguration;
import com.facebook.litho.displaylist.DisplayList;
import com.facebook.litho.displaylist.DisplayListException;
import com.facebook.litho.reference.BorderColorDrawableReference;
import com.facebook.litho.reference.Reference;
import com.facebook.infer.annotation.ThreadSafe;
import com.facebook.yoga.YogaConstants;
import com.facebook.yoga.YogaDirection;
import com.facebook.yoga.YogaEdge;
import static android.content.Context.ACCESSIBILITY_SERVICE;
import static android.os.Build.VERSION.SDK_INT;
import static android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH;
import static android.os.Build.VERSION_CODES.JELLY_BEAN_MR1;
import static android.os.Build.VERSION_CODES.M;
import static android.support.v4.view.ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_AUTO;
import static android.support.v4.view.ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_NO;
import static com.facebook.litho.Component.isHostSpec;
import static com.facebook.litho.Component.isLayoutSpecWithSizeSpec;
import static com.facebook.litho.Component.isMountSpec;
import static com.facebook.litho.Component.isMountViewSpec;
import static com.facebook.litho.ComponentContext.NULL_LAYOUT;
import static com.facebook.litho.ComponentLifecycle.MountType.NONE;
import static com.facebook.litho.ComponentsLogger.ACTION_SUCCESS;
import static com.facebook.litho.ComponentsLogger.EVENT_COLLECT_RESULTS;
import static com.facebook.litho.ComponentsLogger.EVENT_CREATE_LAYOUT;
import static com.facebook.litho.ComponentsLogger.EVENT_CSS_LAYOUT;
import static com.facebook.litho.ComponentsLogger.PARAM_LOG_TAG;
import static com.facebook.litho.ComponentsLogger.PARAM_TREE_DIFF_ENABLED;
import static com.facebook.litho.MountItem.FLAG_DUPLICATE_PARENT_STATE;
import static com.facebook.litho.MountState.ROOT_HOST_ID;
import static com.facebook.litho.NodeInfo.FOCUS_SET_TRUE;
import static com.facebook.litho.SizeSpec.EXACTLY;
/**
* The main role of {@link LayoutState} is to hold the output of layout calculation. This includes
* mountable outputs and visibility outputs. A centerpiece of the class is {@link
* #collectResults(InternalNode, LayoutState, DiffNode)} which prepares the before-mentioned outputs
* based on the provided {@link InternalNode} for later use in {@link MountState}.
*/
class LayoutState {
static final Comparator<LayoutOutput> sTopsComparator =
new Comparator<LayoutOutput>() {
@Override
public int compare(LayoutOutput lhs, LayoutOutput rhs) {
final int lhsTop = lhs.getBounds().top;
final int rhsTop = rhs.getBounds().top;
return lhsTop < rhsTop
? -1
: lhsTop > rhsTop
? 1
// Hosts should be higher for tops so that they are mounted first if possible.
: isHostSpec(lhs.getComponent()) == isHostSpec(rhs.getComponent())
? 0
: isHostSpec(lhs.getComponent()) ? -1 : 1;
}
};
static final Comparator<LayoutOutput> sBottomsComparator =
new Comparator<LayoutOutput>() {
@Override
public int compare(LayoutOutput lhs, LayoutOutput rhs) {
final int lhsBottom = lhs.getBounds().bottom;
final int rhsBottom = rhs.getBounds().bottom;
return lhsBottom < rhsBottom
? -1
: lhsBottom > rhsBottom
? 1
// Hosts should be lower for bottoms so that they are mounted first if possible.
: isHostSpec(lhs.getComponent()) == isHostSpec(rhs.getComponent())
? 0
: isHostSpec(lhs.getComponent()) ? 1 : -1;
}
};
private static final int[] DRAWABLE_STATE_ENABLED = new int[]{android.R.attr.state_enabled};
private static final int[] DRAWABLE_STATE_NOT_ENABLED = new int[]{};
private ComponentContext mContext;
private TransitionContext mTransitionContext;
private Component<?> mComponent;
private int mWidthSpec;
private int mHeightSpec;
private final List<LayoutOutput> mMountableOutputs = new ArrayList<>(8);
private final List<VisibilityOutput> mVisibilityOutputs = new ArrayList<>(8);
private final LongSparseArray<Integer> mOutputsIdToPositionMap = new LongSparseArray<>(8);
private final LayoutStateOutputIdCalculator mLayoutStateOutputIdCalculator;
private final ArrayList<LayoutOutput> mMountableOutputTops = new ArrayList<>();
private final ArrayList<LayoutOutput> mMountableOutputBottoms = new ArrayList<>();
private final List<TestOutput> mTestOutputs;
private InternalNode mLayoutRoot;
private DiffNode mDiffTreeRoot;
// Reference count will be initialized to 1 in init().
private final AtomicInteger mReferenceCount = new AtomicInteger(-1);
private int mWidth;
private int mHeight;
private int mCurrentX;
private int mCurrentY;
private int mCurrentLevel = 0;
// Holds the current host marker in the layout tree.
private long mCurrentHostMarker = -1;
private int mCurrentHostOutputPosition = -1;
private boolean mShouldDuplicateParentState = true;
private boolean mShouldGenerateDiffTree = false;
private int mComponentTreeId = -1;
private AccessibilityManager mAccessibilityManager;
private boolean mAccessibilityEnabled = false;
private StateHandler mStateHandler;
LayoutState() {
mLayoutStateOutputIdCalculator = new LayoutStateOutputIdCalculator();
mTestOutputs = ComponentsConfiguration.isEndToEndTestRun ? new ArrayList<TestOutput>(8) : null;
}
/**
* Acquires a new layout output for the internal node and its associated component. It returns
* null if there's no component associated with the node as the mount pass only cares about nodes
* that will potentially mount content into the component host.
*/
@Nullable
private static LayoutOutput createGenericLayoutOutput(
InternalNode node,
LayoutState layoutState) {
final Component<?> component = node.getComponent();
// Skip empty nodes and layout specs because they don't mount anything.
if (component == null || component.getLifecycle().getMountType() == NONE) {
return null;
}
return createLayoutOutput(
component,
layoutState,
node,
true /* useNodePadding */,
node.getImportantForAccessibility(),
layoutState.mShouldDuplicateParentState);
}
private static LayoutOutput createHostLayoutOutput(LayoutState layoutState, InternalNode node) {
final LayoutOutput hostOutput = createLayoutOutput(
HostComponent.create(),
layoutState,
node,
false /* useNodePadding */,
node.getImportantForAccessibility(),
node.isDuplicateParentStateEnabled());
hostOutput.getViewNodeInfo().setTransitionKey(node.getTransitionKey());
return hostOutput;
}
private static LayoutOutput createDrawableLayoutOutput(
Component<?> component,
LayoutState layoutState,
InternalNode node) {
return createLayoutOutput(
component,
layoutState,
node,
false /* useNodePadding */,
IMPORTANT_FOR_ACCESSIBILITY_NO,
layoutState.mShouldDuplicateParentState);
}
private static LayoutOutput createLayoutOutput(
Component<?> component,
LayoutState layoutState,
InternalNode node,
boolean useNodePadding,
int importantForAccessibility,
boolean duplicateParentState) {
final boolean isMountViewSpec = isMountViewSpec(component);
final LayoutOutput layoutOutput = ComponentsPools.acquireLayoutOutput();
layoutOutput.setComponent(component);
layoutOutput.setImportantForAccessibility(importantForAccessibility);
// The mount operation will need both the marker for the target host and its matching
// parent host to ensure the correct hierarchy when nesting the host views.
layoutOutput.setHostMarker(layoutState.mCurrentHostMarker);
if (layoutState.mCurrentHostOutputPosition >= 0) {
final LayoutOutput hostOutput =
layoutState.mMountableOutputs.get(layoutState.mCurrentHostOutputPosition);
final Rect hostBounds = hostOutput.getBounds();
layoutOutput.setHostTranslationX(hostBounds.left);
layoutOutput.setHostTranslationY(hostBounds.top);
}
int l = layoutState.mCurrentX + node.getX();
int t = layoutState.mCurrentY + node.getY();
int r = l + node.getWidth();
int b = t + node.getHeight();
final int paddingLeft = useNodePadding ? node.getPaddingLeft() : 0;
final int paddingTop = useNodePadding ? node.getPaddingTop() : 0;
final int paddingRight = useNodePadding ? node.getPaddingRight() : 0;
final int paddingBottom = useNodePadding ? node.getPaddingBottom() : 0;
// View mount specs are able to set their own attributes when they're mounted.
// Non-view specs (drawable and layout) always transfer their view attributes
// to their respective hosts.
// Moreover, if the component mounts a view, then we apply padding to the view itself later on.
// Otherwise, apply the padding to the bounds of the layout output.
if (isMountViewSpec) {
layoutOutput.setNodeInfo(node.getNodeInfo());
// Acquire a ViewNodeInfo, set it up and release it after passing it to the LayoutOutput.
final ViewNodeInfo viewNodeInfo = ViewNodeInfo.acquire();
viewNodeInfo.setPadding(paddingLeft, paddingTop, paddingRight, paddingBottom);
viewNodeInfo.setLayoutDirection(node.getResolvedLayoutDirection());
viewNodeInfo.setExpandedTouchBounds(node, l, t, r, b);
layoutOutput.setViewNodeInfo(viewNodeInfo);
viewNodeInfo.release();
} else {
l += paddingLeft;
t += paddingTop;
r -= paddingRight;
b -= paddingBottom;
}
layoutOutput.setBounds(l, t, r, b);
int flags = 0;
if (duplicateParentState) {
flags |= FLAG_DUPLICATE_PARENT_STATE;
}
layoutOutput.setFlags(flags);
return layoutOutput;
}
/**
* Acquires a {@link VisibilityOutput} object and computes the bounds for it using the information
* stored in the {@link InternalNode}.
*/
private static VisibilityOutput createVisibilityOutput(
InternalNode node,
LayoutState layoutState) {
final int l = layoutState.mCurrentX + node.getX();
final int t = layoutState.mCurrentY + node.getY();
final int r = l + node.getWidth();
final int b = t + node.getHeight();
final EventHandler visibleHandler = node.getVisibleHandler();
final EventHandler focusedHandler = node.getFocusedHandler();
final EventHandler fullImpressionHandler = node.getFullImpressionHandler();
final EventHandler invisibleHandler = node.getInvisibleHandler();
final VisibilityOutput visibilityOutput = ComponentsPools.acquireVisibilityOutput();
final Component<?> handlerComponent;
// Get the component from the handler that is not null. If more than one is not null, then
// getting the component from any of them works.
if (visibleHandler != null) {
handlerComponent = (Component<?>) visibleHandler.mHasEventDispatcher;
} else if (focusedHandler != null) {
handlerComponent = (Component<?>) focusedHandler.mHasEventDispatcher;
} else if (fullImpressionHandler != null) {
handlerComponent = (Component<?>) fullImpressionHandler.mHasEventDispatcher;
} else {
handlerComponent = (Component<?>) invisibleHandler.mHasEventDispatcher;
}
visibilityOutput.setComponent(handlerComponent);
visibilityOutput.setBounds(l, t, r, b);
visibilityOutput.setVisibleEventHandler(visibleHandler);
visibilityOutput.setFocusedEventHandler(focusedHandler);
visibilityOutput.setFullImpressionEventHandler(fullImpressionHandler);
visibilityOutput.setInvisibleEventHandler(invisibleHandler);
return visibilityOutput;
}
private static TestOutput createTestOutput(
InternalNode node,
LayoutState layoutState,
LayoutOutput layoutOutput) {
final int l = layoutState.mCurrentX + node.getX();
final int t = layoutState.mCurrentY + node.getY();
final int r = l + node.getWidth();
final int b = t + node.getHeight();
final TestOutput output = ComponentsPools.acquireTestOutput();
output.setTestKey(node.getTestKey());
output.setBounds(l, t, r, b);
output.setHostMarker(layoutState.mCurrentHostMarker);
if (layoutOutput != null) {
output.setLayoutOutputId(layoutOutput.getId());
}
return output;
}
private static boolean isLayoutDirectionRTL(Context context) {
ApplicationInfo applicationInfo = context.getApplicationInfo();
if ((SDK_INT >= JELLY_BEAN_MR1)
&& (applicationInfo.flags & ApplicationInfo.FLAG_SUPPORTS_RTL) != 0) {
int layoutDirection = getLayoutDirection(context);
return layoutDirection == View.LAYOUT_DIRECTION_RTL;
}
return false;
}
@TargetApi(JELLY_BEAN_MR1)
private static int getLayoutDirection(Context context) {
return context.getResources().getConfiguration().getLayoutDirection();
}
/**
* Determine if a given {@link InternalNode} within the context of a given {@link LayoutState}
* requires to be wrapped inside a view.
*
* @see #needsHostView(InternalNode, LayoutState)
*/
private static boolean hasViewContent(InternalNode node, LayoutState layoutState) {
final Component<?> component = node.getComponent();
final NodeInfo nodeInfo = node.getNodeInfo();
final boolean implementsAccessibility =
(nodeInfo != null && nodeInfo.hasAccessibilityHandlers())
|| (component != null && component.getLifecycle().implementsAccessibility());
final int importantForAccessibility = node.getImportantForAccessibility();
// A component has accessibility content if:
// 1. Accessibility is currently enabled.
// 2. Accessibility hasn't been explicitly disabled on it
// i.e. IMPORTANT_FOR_ACCESSIBILITY_NO.
// 3. Any of these conditions are true:
// - It implements accessibility support.
// - It has a content description.
// - It has importantForAccessibility set as either IMPORTANT_FOR_ACCESSIBILITY_YES
// or IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS.
// IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS should trigger an inner host
// so that such flag is applied in the resulting view hierarchy after the component
// tree is mounted. Click handling is also considered accessibility content but
// this is already covered separately i.e. click handler is not null.
final boolean hasAccessibilityContent = layoutState.mAccessibilityEnabled
&& importantForAccessibility != IMPORTANT_FOR_ACCESSIBILITY_NO
&& (implementsAccessibility
|| (nodeInfo != null && !TextUtils.isEmpty(nodeInfo.getContentDescription()))
|| importantForAccessibility != IMPORTANT_FOR_ACCESSIBILITY_AUTO);
final boolean hasTouchEventHandlers = (nodeInfo != null && nodeInfo.hasTouchEventHandlers());
final boolean hasViewTag = (nodeInfo != null && nodeInfo.getViewTag() != null);
final boolean hasViewTags = (nodeInfo != null && nodeInfo.getViewTags() != null);
final boolean isFocusableSetTrue =
(nodeInfo != null && nodeInfo.getFocusState() == FOCUS_SET_TRUE);
return hasTouchEventHandlers
|| hasViewTag
|| hasViewTags
|| hasAccessibilityContent
|| isFocusableSetTrue;
}
/**
* Collects layout outputs and release the layout tree. The layout outputs hold necessary
* information to be used by {@link MountState} to mount components into a {@link ComponentHost}.
* <p/>
* Whenever a component has view content (view tags, click handler, etc), a new host 'marker'
* is added for it. The mount pass will use the markers to decide which host should be used
* for each layout output. The root node unconditionally generates a layout output corresponding
* to the root host.
* <p/>
* The order of layout outputs follows a depth-first traversal in the tree to ensure the hosts
* will be created at the right order when mounting. The host markers will be define which host
* each mounted artifacts will be attached to.
* <p/>
* At this stage all the {@link InternalNode} for which we have LayoutOutputs that can be recycled
* will have a DiffNode associated. If the CachedMeasures are valid we'll try to recycle both the
* host and the contents (including background/foreground). In all other cases instead we'll only
* try to re-use the hosts. In some cases the host's structure might change between two updates
* even if the component is of the same type. This can happen for example when a click listener is
* added. To avoid trying to re-use the wrong host type we explicitly check that after all the
* children for a subtree have been added (this is when the actual host type is resolved). If the
* host type changed compared to the one in the DiffNode we need to refresh the ids for the whole
* subtree in order to ensure that the MountState will unmount the subtree and mount it again on
* the correct host.
* <p/>
*
* @param node InternalNode to process.
* @param layoutState the LayoutState currently operating.
* @param parentDiffNode whether this method also populates the diff tree and assigns the root
* to mDiffTreeRoot.
*/
private static void collectResults(
InternalNode node,
LayoutState layoutState,
DiffNode parentDiffNode) {
if (node.hasNewLayout()) {
node.markLayoutSeen();
}
final Component<?> component = node.getComponent();
// Early return if collecting results of a node holding a nested tree.
if (node.isNestedTreeHolder()) {
// If the nested tree is defined, it has been resolved during a measure call during
// layout calculation.
InternalNode nestedTree = resolveNestedTree(
node,
SizeSpec.makeSizeSpec(node.getWidth(), EXACTLY),
SizeSpec.makeSizeSpec(node.getHeight(), EXACTLY));
if (nestedTree == NULL_LAYOUT) {
return;
}
// Account for position of the holder node.
layoutState.mCurrentX += node.getX();
layoutState.mCurrentY += node.getY();
collectResults(nestedTree, layoutState, parentDiffNode);
layoutState.mCurrentX -= node.getX();
layoutState.mCurrentY -= node.getY();
return;
}
final boolean shouldGenerateDiffTree = layoutState.mShouldGenerateDiffTree;
final DiffNode currentDiffNode = node.getDiffNode();
final boolean shouldUseCachedOutputs =
isMountSpec(component) && currentDiffNode != null;
final boolean isCachedOutputUpdated = shouldUseCachedOutputs && node.areCachedMeasuresValid();
final DiffNode diffNode;
if (shouldGenerateDiffTree) {
diffNode = createDiffNode(node, parentDiffNode);
if (parentDiffNode == null) {
layoutState.mDiffTreeRoot = diffNode;
}
} else {
diffNode = null;
}
final boolean needsHostView = needsHostView(node, layoutState);
final long currentHostMarker = layoutState.mCurrentHostMarker;
final int currentHostOutputPosition = layoutState.mCurrentHostOutputPosition;
int hostLayoutPosition = -1;
// 1. Insert a host LayoutOutput if we have some interactive content to be attached to.
if (needsHostView) {
hostLayoutPosition = addHostLayoutOutput(node, layoutState, diffNode);
layoutState.mCurrentLevel++;
layoutState.mCurrentHostMarker =
layoutState.mMountableOutputs.get(hostLayoutPosition).getId();
layoutState.mCurrentHostOutputPosition = hostLayoutPosition;
}
// We need to take into account flattening when setting duplicate parent state. The parent after
// flattening may no longer exist. Therefore the value of duplicate parent state should only be
// true if the path between us (inclusive) and our inner/root host (exclusive) all are
// duplicate parent state.
final boolean shouldDuplicateParentState = layoutState.mShouldDuplicateParentState;
layoutState.mShouldDuplicateParentState =
needsHostView || (shouldDuplicateParentState && node.isDuplicateParentStateEnabled());
// Generate the layoutOutput for the given node.
final LayoutOutput layoutOutput = createGenericLayoutOutput(node, layoutState);
if (layoutOutput != null) {
final long previousId = shouldUseCachedOutputs ? currentDiffNode.getContent().getId() : -1;
layoutState.mLayoutStateOutputIdCalculator.calculateAndSetLayoutOutputIdAndUpdateState(
layoutOutput,
layoutState.mCurrentLevel,
LayoutOutput.TYPE_CONTENT,
previousId,
isCachedOutputUpdated);
}
// If we don't need to update this output we can safely re-use the display list from the
// previous output.
if (isCachedOutputUpdated) {
layoutOutput.setDisplayList(currentDiffNode.getContent().getDisplayList());
}
// 2. Add background if defined.
final Reference<? extends Drawable> background = node.getBackground();
if (background != null) {
if (layoutOutput != null && layoutOutput.hasViewNodeInfo()) {
layoutOutput.getViewNodeInfo().setBackground(background);
} else {
final LayoutOutput convertBackground = (currentDiffNode != null)
? currentDiffNode.getBackground()
: null;
final LayoutOutput backgroundOutput = addDrawableComponent(
node,
layoutState,
convertBackground,
background,
LayoutOutput.TYPE_BACKGROUND);
if (diffNode != null) {
diffNode.setBackground(backgroundOutput);
}
}
}
// 3. Now add the MountSpec (either View or Drawable) to the Outputs.
if (isMountSpec(component)) {
// Notify component about its final size.
component.getLifecycle().onBoundsDefined(layoutState.mContext, node, component);
addMountableOutput(layoutState, layoutOutput);
addLayoutOutputIdToPositionsMap(
layoutState.mOutputsIdToPositionMap,
layoutOutput,
layoutState.mMountableOutputs.size() - 1);
if (diffNode != null) {
diffNode.setContent(layoutOutput);
}
}
// 4. Add border color if defined.
if (node.shouldDrawBorders()) {
final LayoutOutput convertBorder = (currentDiffNode != null)
? currentDiffNode.getBorder()
: null;
final LayoutOutput borderOutput = addDrawableComponent(
node,
layoutState,
convertBorder,
getBorderColorDrawable(node),
LayoutOutput.TYPE_BORDER);
if (diffNode != null) {
diffNode.setBorder(borderOutput);
}
}
// 5. Extract the Transitions.
if (SDK_INT >= ICE_CREAM_SANDWICH) {
if (node.getTransitionKey() != null) {
layoutState
.getOrCreateTransitionContext()
.addTransitionKey(node.getTransitionKey());
}
if (component != null) {
Transition transition = component.getLifecycle().onLayoutTransition(
layoutState.mContext,
component);
if (transition != null) {
layoutState.getOrCreateTransitionContext().add(transition);
}
}
}
layoutState.mCurrentX += node.getX();
layoutState.mCurrentY += node.getY();
// We must process the nodes in order so that the layout state output order is correct.
for (int i = 0, size = node.getChildCount(); i < size; i++) {
collectResults(
node.getChildAt(i),
layoutState,
diffNode);
}
layoutState.mCurrentX -= node.getX();
layoutState.mCurrentY -= node.getY();
// 6. Add foreground if defined.
final Reference<? extends Drawable> foreground = node.getForeground();
if (foreground != null) {
if (layoutOutput != null && layoutOutput.hasViewNodeInfo() && SDK_INT >= M) {
layoutOutput.getViewNodeInfo().setForeground(foreground);
} else {
final LayoutOutput convertForeground = (currentDiffNode != null)
? currentDiffNode.getForeground()
: null;
final LayoutOutput foregroundOutput = addDrawableComponent(
node,
layoutState,
convertForeground,
foreground,
LayoutOutput.TYPE_FOREGROUND);
if (diffNode != null) {
diffNode.setForeground(foregroundOutput);
}
}
}
// 7. Add VisibilityOutputs if any visibility-related event handlers are present.
if (node.hasVisibilityHandlers()) {
final VisibilityOutput visibilityOutput = createVisibilityOutput(node, layoutState);
final long previousId =
shouldUseCachedOutputs ? currentDiffNode.getVisibilityOutput().getId() : -1;
layoutState.mLayoutStateOutputIdCalculator.calculateAndSetVisibilityOutputId(
visibilityOutput,
layoutState.mCurrentLevel,
previousId);
layoutState.mVisibilityOutputs.add(visibilityOutput);
if (diffNode != null) {
diffNode.setVisibilityOutput(visibilityOutput);
}
}
// 8. If we're in a testing environment, maintain an additional data structure with
// information about nodes that we can query later.
if (layoutState.mTestOutputs != null && !TextUtils.isEmpty(node.getTestKey())) {
final TestOutput testOutput = createTestOutput(node, layoutState, layoutOutput);
layoutState.mTestOutputs.add(testOutput);
}
// All children for the given host have been added, restore the previous
// host, level, and duplicate parent state value in the recursive queue.
if (layoutState.mCurrentHostMarker != currentHostMarker) {
layoutState.mCurrentHostMarker = currentHostMarker;
layoutState.mCurrentHostOutputPosition = currentHostOutputPosition;
layoutState.mCurrentLevel
}
layoutState.mShouldDuplicateParentState = shouldDuplicateParentState;
Collections.sort(layoutState.mMountableOutputTops, sTopsComparator);
Collections.sort(layoutState.mMountableOutputBottoms, sBottomsComparator);
}
private static void calculateAndSetHostOutputIdAndUpdateState(
InternalNode node,
LayoutOutput hostOutput,
LayoutState layoutState,
boolean isCachedOutputUpdated) {
if (layoutState.isLayoutRoot(node)) {
// The root host (ComponentView) always has ID 0 and is unconditionally
// set as dirty i.e. no need to use shouldComponentUpdate().
hostOutput.setId(ROOT_HOST_ID);
// Special case where the host marker of the root host is pointing to itself.
hostOutput.setHostMarker(ROOT_HOST_ID);
hostOutput.setUpdateState(LayoutOutput.STATE_DIRTY);
} else {
layoutState.mLayoutStateOutputIdCalculator.calculateAndSetLayoutOutputIdAndUpdateState(
hostOutput,
layoutState.mCurrentLevel,
LayoutOutput.TYPE_HOST,
-1,
isCachedOutputUpdated);
}
}
private static LayoutOutput addDrawableComponent(
InternalNode node,
LayoutState layoutState,
LayoutOutput recycle,
Reference<? extends Drawable> reference,
@LayoutOutput.LayoutOutputType int type) {
final Component<DrawableComponent> drawableComponent = DrawableComponent.create(reference);
drawableComponent.setScopedContext(
ComponentContext.withComponentScope(node.getContext(), drawableComponent));
final boolean isOutputUpdated;
if (recycle != null) {
isOutputUpdated = !drawableComponent.getLifecycle().shouldComponentUpdate(
recycle.getComponent(),
drawableComponent);
} else {
isOutputUpdated = false;
}
final long previousId = recycle != null ? recycle.getId() : -1;
final LayoutOutput output = addDrawableLayoutOutput(
drawableComponent,
layoutState,
node,
type,
previousId,
isOutputUpdated);
return output;
}
private static Reference<? extends Drawable> getBorderColorDrawable(InternalNode node) {
if (!node.shouldDrawBorders()) {
throw new RuntimeException("This node does not support drawing border color");
}
return BorderColorDrawableReference.create(node.getContext())
.color(node.getBorderColor())
.borderLeft(FastMath.round(node.mYogaNode.getLayoutBorder(YogaEdge.LEFT)))
.borderTop(FastMath.round(node.mYogaNode.getLayoutBorder(YogaEdge.TOP)))
.borderRight(FastMath.round(node.mYogaNode.getLayoutBorder(YogaEdge.RIGHT)))
.borderBottom(FastMath.round(node.mYogaNode.getLayoutBorder(YogaEdge.BOTTOM)))
.build();
}
private static void addLayoutOutputIdToPositionsMap(
LongSparseArray outputsIdToPositionMap,
LayoutOutput layoutOutput,
int position) {
if (outputsIdToPositionMap != null) {
outputsIdToPositionMap.put(layoutOutput.getId(), position);
}
}
private static LayoutOutput addDrawableLayoutOutput(
Component<DrawableComponent> drawableComponent,
LayoutState layoutState,
InternalNode node,
@LayoutOutput.LayoutOutputType int layoutOutputType,
long previousId,
boolean isCachedOutputUpdated) {
drawableComponent.getLifecycle().onBoundsDefined(
layoutState.mContext,
node,
drawableComponent);
final LayoutOutput drawableLayoutOutput = createDrawableLayoutOutput(
drawableComponent,
layoutState,
node);
layoutState.mLayoutStateOutputIdCalculator.calculateAndSetLayoutOutputIdAndUpdateState(
drawableLayoutOutput,
layoutState.mCurrentLevel,
layoutOutputType,
previousId,
isCachedOutputUpdated);
addMountableOutput(layoutState, drawableLayoutOutput);
addLayoutOutputIdToPositionsMap(
layoutState.mOutputsIdToPositionMap,
drawableLayoutOutput,
layoutState.mMountableOutputs.size() - 1);
return drawableLayoutOutput;
}
static void releaseNodeTree(InternalNode node, boolean isNestedTree) {
if (node == NULL_LAYOUT) {
throw new IllegalArgumentException("Cannot release a null node tree");
}
for (int i = node.getChildCount() - 1; i >= 0; i
final InternalNode child = node.getChildAt(i);
if (isNestedTree && node.hasNewLayout()) {
node.markLayoutSeen();
}
// A node must be detached from its parent *before* being released (otherwise the parent would
// retain a reference to a node that may get re-used by another thread)
node.removeChildAt(i);
releaseNodeTree(child, isNestedTree);
}
if (node.hasNestedTree() && node.getNestedTree() != NULL_LAYOUT) {
releaseNodeTree(node.getNestedTree(), true);
}
ComponentsPools.release(node);
}
/**
* If we have an interactive LayoutSpec or a MountSpec Drawable, we need to insert an
* HostComponent in the Outputs such as it will be used as a HostView at Mount time. View
* MountSpec are not allowed.
*
* @return The position the HostLayoutOutput was inserted.
*/
private static int addHostLayoutOutput(
InternalNode node,
LayoutState layoutState,
DiffNode diffNode) {
final Component<?> component = node.getComponent();
// Only the root host is allowed to wrap view mount specs as a layout output
// is unconditionally added for it.
if (isMountViewSpec(component) && !layoutState.isLayoutRoot(node)) {
throw new IllegalArgumentException("We shouldn't insert a host as a parent of a View");
}
final LayoutOutput hostLayoutOutput = createHostLayoutOutput(layoutState, node);
// The component of the hostLayoutOutput will be set later after all the
// children got processed.
addMountableOutput(layoutState, hostLayoutOutput);
final int hostOutputPosition = layoutState.mMountableOutputs.size() - 1;
if (diffNode != null) {
diffNode.setHost(hostLayoutOutput);
}
calculateAndSetHostOutputIdAndUpdateState(
node,
hostLayoutOutput,
layoutState,
false);
addLayoutOutputIdToPositionsMap(
layoutState.mOutputsIdToPositionMap,
hostLayoutOutput,
hostOutputPosition);
return hostOutputPosition;
}
static <T extends ComponentLifecycle> LayoutState calculate(
ComponentContext c,
Component<T> component,
int componentTreeId,
int widthSpec,
int heightSpec,
boolean shouldGenerateDiffTree,
DiffNode previousDiffTreeRoot) {
// Detect errors internal to components
component.markLayoutStarted();
LayoutState layoutState = ComponentsPools.acquireLayoutState(c);
layoutState.mShouldGenerateDiffTree = shouldGenerateDiffTree;
layoutState.mComponentTreeId = componentTreeId;
layoutState.mAccessibilityManager =
(AccessibilityManager) c.getSystemService(ACCESSIBILITY_SERVICE);
layoutState.mAccessibilityEnabled = isAccessibilityEnabled(layoutState.mAccessibilityManager);
layoutState.mComponent = component;
layoutState.mWidthSpec = widthSpec;
layoutState.mHeightSpec = heightSpec;
component.applyStateUpdates(c);
final InternalNode root = createAndMeasureTreeForComponent(
component.getScopedContext(),
component,
null, // nestedTreeHolder is null because this is measuring the root component tree.
widthSpec,
heightSpec,
previousDiffTreeRoot);
switch (SizeSpec.getMode(widthSpec)) {
case SizeSpec.EXACTLY:
layoutState.mWidth = SizeSpec.getSize(widthSpec);
break;
case SizeSpec.AT_MOST:
layoutState.mWidth = Math.min(root.getWidth(), SizeSpec.getSize(widthSpec));
break;
case SizeSpec.UNSPECIFIED:
layoutState.mWidth = root.getWidth();
break;
}
switch (SizeSpec.getMode(heightSpec)) {
case SizeSpec.EXACTLY:
layoutState.mHeight = SizeSpec.getSize(heightSpec);
break;
case SizeSpec.AT_MOST:
layoutState.mHeight = Math.min(root.getHeight(), SizeSpec.getSize(heightSpec));
break;
case SizeSpec.UNSPECIFIED:
layoutState.mHeight = root.getHeight();
break;
}
layoutState.mLayoutStateOutputIdCalculator.clear();
// Reset markers before collecting layout outputs.
layoutState.mCurrentHostMarker = -1;
final ComponentsLogger logger = c.getLogger();
if (root == NULL_LAYOUT) {
return layoutState;
}
layoutState.mLayoutRoot = root;
ComponentsSystrace.beginSection("collectResults:" + component.getSimpleName());
if (logger != null) {
logger.eventStart(EVENT_COLLECT_RESULTS, component, PARAM_LOG_TAG, c.getLogTag());
}
collectResults(root, layoutState, null);
if (logger != null) {
logger.eventEnd(EVENT_COLLECT_RESULTS, component, ACTION_SUCCESS);
}
ComponentsSystrace.endSection();
if (!ComponentsConfiguration.IS_INTERNAL_BUILD && layoutState.mLayoutRoot != null) {
releaseNodeTree(layoutState.mLayoutRoot, false /* isNestedTree */);
layoutState.mLayoutRoot = null;
}
if (ThreadUtils.isMainThread() && ComponentsConfiguration.shouldGenerateDisplayLists) {
collectDisplayLists(layoutState);
}
return layoutState;
}
void preAllocateMountContent() {
if (mMountableOutputs != null && !mMountableOutputs.isEmpty()) {
for (int i = 0, size = mMountableOutputs.size(); i < size; i++) {
final Component component = mMountableOutputs.get(i).getComponent();
if (Component.isMountViewSpec(component)) {
final ComponentLifecycle lifecycle = component.getLifecycle();
if (!lifecycle.hasBeenPreallocated()) {
final int poolSize = lifecycle.poolSize();
int insertedCount = 0;
while (insertedCount < poolSize &&
ComponentsPools.canAddMountContentToPool(mContext, lifecycle)) {
ComponentsPools.release(
mContext,
lifecycle,
lifecycle.createMountContent(mContext));
insertedCount++;
}
lifecycle.setWasPreallocated();
}
}
}
}
}
private static void collectDisplayLists(LayoutState layoutState) {
final Rect rect = new Rect();
final ComponentContext context = layoutState.mContext;
final Activity activity = findActivityInContext(context);
if (activity == null || activity.isFinishing() || isActivityDestroyed(activity)) {
return;
}
for (int i = 0, count = layoutState.getMountableOutputCount(); i < count; i++) {
final LayoutOutput output = layoutState.getMountableOutputAt(i);
final Component component = output.getComponent();
final ComponentLifecycle lifecycle = component.getLifecycle();
if (lifecycle.shouldUseDisplayList()) {
output.getMountBounds(rect);
if (output.getDisplayList() != null && output.getDisplayList().isValid()) {
// This output already has a valid DisplayList from diffing. No need to re-create it.
// Just update its bounds.
try {
output.getDisplayList().setBounds(rect.left, rect.top, rect.right, rect.bottom);
continue;
} catch (DisplayListException e) {
// Nothing to do here.
}
}
final DisplayList displayList = DisplayList.createDisplayList(
lifecycle.getClass().getSimpleName());
if (displayList != null) {
Drawable drawable =
(Drawable) ComponentsPools.acquireMountContent(context, lifecycle.getId());
if (drawable == null) {
drawable = (Drawable) lifecycle.createMountContent(context);
}
final LayoutOutput clickableOutput = findInteractiveRoot(layoutState, output);
boolean isStateEnabled = false;
if (clickableOutput != null && clickableOutput.getNodeInfo() != null) {
final NodeInfo nodeInfo = clickableOutput.getNodeInfo();
if (nodeInfo.hasTouchEventHandlers() || nodeInfo.getFocusState() == FOCUS_SET_TRUE) {
isStateEnabled = true;
}
}
if (isStateEnabled) {
drawable.setState(DRAWABLE_STATE_ENABLED);
} else {
drawable.setState(DRAWABLE_STATE_NOT_ENABLED);
}
lifecycle.mount(
context,
drawable,
component);
lifecycle.bind(context, drawable, component);
output.getMountBounds(rect);
drawable.setBounds(0, 0, rect.width(), rect.height());
try {
final Canvas canvas = displayList.start(rect.width(), rect.height());
drawable.draw(canvas);
displayList.end(canvas);
displayList.setBounds(rect.left, rect.top, rect.right, rect.bottom);
output.setDisplayList(displayList);
} catch (DisplayListException e) {
// Display list creation failed. Make sure the DisplayList for this output is set
// to null.
output.setDisplayList(null);
}
lifecycle.unbind(context, drawable, component);
lifecycle.unmount(context, drawable, component);
ComponentsPools.release(context, lifecycle, drawable);
}
}
}
}
private static LayoutOutput findInteractiveRoot(LayoutState layoutState, LayoutOutput output) {
if (output.getId() == ROOT_HOST_ID) {
return output;
}
if ((output.getFlags() & FLAG_DUPLICATE_PARENT_STATE) != 0) {
final int parentPosition = layoutState.getLayoutOutputPositionForId(output.getHostMarker());
if (parentPosition >= 0) {
final LayoutOutput parent = layoutState.mMountableOutputs.get(parentPosition);
if (parent == null) {
return null;
}
return findInteractiveRoot(layoutState, parent);
}
return null;
}
return output;
}
private static boolean isActivityDestroyed(Activity activity) {
if (SDK_INT >= JELLY_BEAN_MR1) {
return activity.isDestroyed();
}
return false;
}
private static Activity findActivityInContext(Context context) {
if (context instanceof Activity) {
return (Activity) context;
} else if (context instanceof ContextWrapper) {
return findActivityInContext(((ContextWrapper) context).getBaseContext());
}
return null;
}
@VisibleForTesting
static <T extends ComponentLifecycle> InternalNode createTree(
Component<T> component,
ComponentContext context) {
final ComponentsLogger logger = context.getLogger();
if (logger != null) {
logger.eventStart(EVENT_CREATE_LAYOUT, context, PARAM_LOG_TAG, context.getLogTag());
logger.eventAddTag(EVENT_CREATE_LAYOUT, context, component.getSimpleName());
}
final InternalNode root = (InternalNode) component.getLifecycle().createLayout(
context,
component,
true /* resolveNestedTree */);
if (logger != null) {
logger.eventEnd(EVENT_CREATE_LAYOUT, context, ACTION_SUCCESS);
}
return root;
}
@VisibleForTesting
static void measureTree(
InternalNode root,
int widthSpec,
int heightSpec,
DiffNode previousDiffTreeRoot) {
final ComponentContext context = root.getContext();
final Component component = root.getComponent();
ComponentsSystrace.beginSection("measureTree:" + component.getSimpleName());
if (YogaConstants.isUndefined(root.getStyleWidth())) {
root.setStyleWidthFromSpec(widthSpec);
}
if (YogaConstants.isUndefined(root.getStyleHeight())) {
root.setStyleHeightFromSpec(heightSpec);
}
if (previousDiffTreeRoot != null) {
ComponentsSystrace.beginSection("applyDiffNode");
applyDiffNodeToUnchangedNodes(root, previousDiffTreeRoot);
ComponentsSystrace.endSection(/* applyDiffNode */);
}
final ComponentsLogger logger = context.getLogger();
if (logger != null) {
logger.eventStart(EVENT_CSS_LAYOUT, component, PARAM_LOG_TAG, context.getLogTag());
logger.eventAddParam(
EVENT_CSS_LAYOUT,
component,
PARAM_TREE_DIFF_ENABLED,
String.valueOf(previousDiffTreeRoot != null));
}
root.calculateLayout(
SizeSpec.getMode(widthSpec) == SizeSpec.UNSPECIFIED
? YogaConstants.UNDEFINED
: SizeSpec.getSize(widthSpec),
SizeSpec.getMode(heightSpec) == SizeSpec.UNSPECIFIED
? YogaConstants.UNDEFINED
: SizeSpec.getSize(heightSpec));
if (logger != null) {
logger.eventEnd(EVENT_CSS_LAYOUT, component, ACTION_SUCCESS);
}
ComponentsSystrace.endSection(/* measureTree */);
}
/**
* Create and measure the nested tree or return the cached one for the same size specs.
*/
static InternalNode resolveNestedTree(
InternalNode nestedTreeHolder,
int widthSpec,
int heightSpec) {
final ComponentContext context = nestedTreeHolder.getContext();
final Component<?> component = nestedTreeHolder.getComponent();
InternalNode nestedTree = nestedTreeHolder.getNestedTree();
if (nestedTree == null
|| !hasCompatibleSizeSpec(
nestedTree.getLastWidthSpec(),
nestedTree.getLastHeightSpec(),
widthSpec,
heightSpec,
nestedTree.getLastMeasuredWidth(),
nestedTree.getLastMeasuredHeight())) {
if (nestedTree != null) {
if (nestedTree != NULL_LAYOUT) {
releaseNodeTree(nestedTree, true /* isNestedTree */);
}
nestedTree = null;
}
if (component.hasCachedLayout()) {
final InternalNode cachedLayout = component.getCachedLayout();
final boolean hasCompatibleLayoutDirection =
InternalNode.hasValidLayoutDirectionInNestedTree(nestedTreeHolder, cachedLayout);
// Transfer the cached layout to the node without releasing it if it's compatible.
if (hasCompatibleLayoutDirection &&
hasCompatibleSizeSpec(
cachedLayout.getLastWidthSpec(),
cachedLayout.getLastHeightSpec(),
widthSpec,
heightSpec,
cachedLayout.getLastMeasuredWidth(),
cachedLayout.getLastMeasuredHeight())) {
nestedTree = cachedLayout;
component.clearCachedLayout();
} else {
component.releaseCachedLayout();
}
}
if (nestedTree == null) {
nestedTree = createAndMeasureTreeForComponent(
context,
component,
nestedTreeHolder,
widthSpec,
heightSpec,
nestedTreeHolder.getDiffNode()); // Previously set while traversing the holder's tree.
nestedTree.setLastWidthSpec(widthSpec);
nestedTree.setLastHeightSpec(heightSpec);
nestedTree.setLastMeasuredHeight(nestedTree.getHeight());
nestedTree.setLastMeasuredWidth(nestedTree.getWidth());
}
nestedTreeHolder.setNestedTree(nestedTree);
}
// This is checking only nested tree roots however it will be moved to check all the tree roots.
InternalNode.assertContextSpecificStyleNotSet(nestedTree);
return nestedTree;
}
/**
* Create and measure a component with the given size specs.
*/
static InternalNode createAndMeasureTreeForComponent(
ComponentContext c,
Component component,
int widthSpec,
int heightSpec) {
return createAndMeasureTreeForComponent(c, component, null, widthSpec, heightSpec, null);
}
private static InternalNode createAndMeasureTreeForComponent(
ComponentContext c,
Component component,
InternalNode nestedTreeHolder, // This will be set only if we are resolving a nested tree.
int widthSpec,
int heightSpec,
DiffNode diffTreeRoot) {
// Account for the size specs in ComponentContext in case the tree is a NestedTree.
final int previousWidthSpec = c.getWidthSpec();
final int previousHeightSpec = c.getHeightSpec();
final boolean hasNestedTreeHolder = nestedTreeHolder != null;
c.setWidthSpec(widthSpec);
c.setHeightSpec(heightSpec);
if (hasNestedTreeHolder) {
c.setTreeProps(nestedTreeHolder.getPendingTreeProps());
}
final InternalNode root = createTree(
component,
c);
if (hasNestedTreeHolder) {
c.setTreeProps(null);
}
c.setWidthSpec(previousWidthSpec);
c.setHeightSpec(previousHeightSpec);
if (root == NULL_LAYOUT) {
return root;
}
// If measuring a ComponentTree with a LayoutSpecWithSizeSpec at the root, the nested tree
// holder argument will be null.
if (hasNestedTreeHolder && isLayoutSpecWithSizeSpec(component)) {
// Transfer information from the holder node to the nested tree root before measurement.
nestedTreeHolder.copyInto(root);
diffTreeRoot = nestedTreeHolder.getDiffNode();
} else if (root.getStyleDirection() == com.facebook.yoga.YogaDirection.INHERIT
&& LayoutState.isLayoutDirectionRTL(c)) {
root.layoutDirection(YogaDirection.RTL);
}
measureTree(
root,
widthSpec,
heightSpec,
diffTreeRoot);
return root;
}
static DiffNode createDiffNode(InternalNode node, DiffNode parent) {
ComponentsSystrace.beginSection("diff_node_creation");
DiffNode diffNode = ComponentsPools.acquireDiffNode();
diffNode.setLastWidthSpec(node.getLastWidthSpec());
diffNode.setLastHeightSpec(node.getLastHeightSpec());
diffNode.setLastMeasuredWidth(node.getLastMeasuredWidth());
diffNode.setLastMeasuredHeight(node.getLastMeasuredHeight());
diffNode.setComponent(node.getComponent());
if (parent != null) {
parent.addChild(diffNode);
}
ComponentsSystrace.endSection();
return diffNode;
}
boolean isCompatibleSpec(int widthSpec, int heightSpec) {
final boolean widthIsCompatible =
MeasureComparisonUtils.isMeasureSpecCompatible(
mWidthSpec,
widthSpec,
mWidth);
final boolean heightIsCompatible =
MeasureComparisonUtils.isMeasureSpecCompatible(
mHeightSpec,
heightSpec,
mHeight);
return widthIsCompatible && heightIsCompatible;
}
boolean isCompatibleAccessibility() {
return isAccessibilityEnabled(mAccessibilityManager) == mAccessibilityEnabled;
}
private static boolean isAccessibilityEnabled(AccessibilityManager accessibilityManager) {
return accessibilityManager.isEnabled() &&
AccessibilityManagerCompat.isTouchExplorationEnabled(accessibilityManager);
}
/**
* Traverses the layoutTree and the diffTree recursively. If a layoutNode has a compatible host
* type {@link LayoutState#hostIsCompatible} it assigns the DiffNode to the layout node in order
* to try to re-use the LayoutOutputs that will be generated by {@link
* LayoutState#collectResults(InternalNode, LayoutState, DiffNode)}. If a layoutNode
* component returns false when shouldComponentUpdate is called with the DiffNode Component it
* also tries to re-use the old measurements and therefore marks as valid the cachedMeasures for
* the whole component subtree.
*
* @param layoutNode the root of the LayoutTree
* @param diffNode the root of the diffTree
*
* @return true if the layout node requires updating, false if it can re-use the measurements
* from the diff node.
*/
static boolean applyDiffNodeToUnchangedNodes(InternalNode layoutNode, DiffNode diffNode) {
// Root of the main tree or of a nested tree.
final boolean isTreeRoot = layoutNode.getParent() == null;
if (isLayoutSpecWithSizeSpec(layoutNode.getComponent()) && !isTreeRoot) {
layoutNode.setDiffNode(diffNode);
return true;
}
if (!hostIsCompatible(layoutNode, diffNode)) {
return true;
}
layoutNode.setDiffNode(diffNode);
final int layoutCount = layoutNode.getChildCount();
final int diffCount = diffNode.getChildCount();
// Layout node needs to be updated if:
// - it has a different number of children.
// - one of its children needs updating.
// - the node itself declares that it needs updating.
boolean shouldUpdate = layoutCount != diffCount;
for (int i = 0; i < layoutCount && i < diffCount; i++) {
// ensure that we always run for all children.
boolean shouldUpdateChild =
applyDiffNodeToUnchangedNodes(
layoutNode.getChildAt(i),
diffNode.getChildAt(i));
shouldUpdate |= shouldUpdateChild;
}
shouldUpdate |= shouldComponentUpdate(layoutNode, diffNode);
if (!shouldUpdate) {
applyDiffNodeToLayoutNode(layoutNode, diffNode);
}
return shouldUpdate;
}
/**
* Copies the inter stage state (if any) from the DiffNode's component to the layout node's
* component, and declares that the cached measures on the diff node are valid for the layout
* node.
*/
private static void applyDiffNodeToLayoutNode(InternalNode layoutNode, DiffNode diffNode) {
final Component component = layoutNode.getComponent();
if (component != null) {
component.copyInterStageImpl(diffNode.getComponent());
}
layoutNode.setCachedMeasuresValid(true);
}
/**
* Returns true either if the two nodes have the same Component type or if both don't have a
* Component.
*/
private static boolean hostIsCompatible(InternalNode node, DiffNode diffNode) {
if (diffNode == null) {
return false;
}
return isSameComponentType(node.getComponent(), diffNode.getComponent());
}
private static boolean isSameComponentType(Component a, Component b) {
if (a == b) {
return true;
} else if (a == null || b == null) {
return false;
}
return a.getLifecycle().getClass().equals(b.getLifecycle().getClass());
}
private static boolean shouldComponentUpdate(InternalNode layoutNode, DiffNode diffNode) {
if (diffNode == null) {
return true;
}
final Component component = layoutNode.getComponent();
if (component != null) {
return component.getLifecycle().shouldComponentUpdate(component, diffNode.getComponent());
}
return true;
}
boolean isCompatibleComponentAndSpec(
int componentId,
int widthSpec,
int heightSpec) {
return mComponent.getId() == componentId && isCompatibleSpec(widthSpec, heightSpec);
}
boolean isCompatibleSize(int width, int height) {
return mWidth == width && mHeight == height;
}
boolean isComponentId(int componentId) {
return mComponent.getId() == componentId;
}
int getMountableOutputCount() {
return mMountableOutputs.size();
}
LayoutOutput getMountableOutputAt(int index) {
return mMountableOutputs.get(index);
}
ArrayList<LayoutOutput> getMountableOutputTops() {
return mMountableOutputTops;
}
ArrayList<LayoutOutput> getMountableOutputBottoms() {
return mMountableOutputBottoms;
}
int getVisibilityOutputCount() {
return mVisibilityOutputs.size();
}
VisibilityOutput getVisibilityOutputAt(int index) {
return mVisibilityOutputs.get(index);
}
int getTestOutputCount() {
return mTestOutputs == null ? 0 : mTestOutputs.size();
}
TestOutput getTestOutputAt(int index) {
return mTestOutputs == null ? null : mTestOutputs.get(index);
}
public DiffNode getDiffTree() {
return mDiffTreeRoot;
}
int getWidth() {
return mWidth;
}
int getHeight() {
return mHeight;
}
|
package com.planetmayo.debrief.satc.views;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.TreeSet;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.IToolBarManager;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.ColumnLabelProvider;
import org.eclipse.jface.viewers.IStructuredContentProvider;
import org.eclipse.jface.viewers.ITableLabelProvider;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.TableViewerColumn;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerSorter;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.IActionBars;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.part.ViewPart;
import com.planetmayo.debrief.satc.SATC_Activator;
import com.planetmayo.debrief.satc.model.generator.BoundedStatesListener;
import com.planetmayo.debrief.satc.model.generator.TrackGenerator;
import com.planetmayo.debrief.satc.model.states.BaseRange;
import com.planetmayo.debrief.satc.model.states.BaseRange.IncompatibleStateException;
import com.planetmayo.debrief.satc.model.states.BoundedState;
/**
* This sample class demonstrates how to plug-in a new workbench view. The view
* shows data obtained from the model. The sample creates a dummy model on the
* fly, but a real implementation would connect to the model available either in
* this or another plug-in (e.g. the workspace). The view is connected to the
* model using a content provider.
* <p>
* The view uses a label provider to define how model objects should be
* presented in the view. Each view can present the same model objects using
* different labels and icons, if needed. Alternatively, a single label provider
* can be shared between views in order to ensure that objects of the same type
* are presented in the same way everywhere.
* <p>
*/
public class TrackStatesView extends ViewPart
{
class NameSorter extends ViewerSorter
{
}
class ViewContentProvider implements IStructuredContentProvider
{
private TreeSet<BoundedState> _myData;
@Override
public void dispose()
{
}
@Override
public Object[] getElements(Object parent)
{
Object[] res;
if ((_myData != null) && (!_myData.isEmpty()))
{
// try getting it as a set
res = _myData.toArray();
}
else
res = null;
return res;
}
@SuppressWarnings("unchecked")
@Override
public void inputChanged(Viewer v, Object oldInput, Object newInput)
{
_myData = (TreeSet<BoundedState>) newInput;
}
}
class ViewLabelProvider extends LabelProvider implements ITableLabelProvider
{
@Override
public Image getColumnImage(Object obj, int index)
{
return getImage(obj);
}
@Override
public String getColumnText(Object obj, int index)
{
BoundedState bs = (BoundedState) obj;
return bs.getTime().toString();
// return getText(obj);
}
@Override
public Image getImage(Object obj)
{
return null;
// return PlatformUI.getWorkbench().getSharedImages()
// .getImage(ISharedImages.IMG_OBJ_ELEMENT);
}
}
/**
* The ID of the view as specified by the extension.
*/
public static final String ID = "com.planetmayo.debrief.satc.views.TrackStatesView";
private TableViewer viewer;
private TrackGenerator _generator;
private BoundedStatesListener _stateListener;
private SimpleDateFormat _df;
/**
* The constructor.
*/
public TrackStatesView()
{
// ok, start listening
_stateListener = new BoundedStatesListener()
{
@Override
public void statesBounded(Collection<BoundedState> newStates)
{
if ((newStates == null) || (newStates.isEmpty()))
viewer.setInput(null);
else
viewer.setInput(newStates);
}
@Override
public void incompatibleStatesIdentified(IncompatibleStateException e)
{
MessageDialog.openInformation(Display.getDefault().getActiveShell(),
"Bounding states", "Incompatible states found");
}
};
_df = new SimpleDateFormat("MMM/dd hh:mm:ss");
}
private void contributeToActionBars()
{
IActionBars bars = getViewSite().getActionBars();
fillLocalPullDown(bars.getMenuManager());
fillLocalToolBar(bars.getToolBarManager());
}
/**
* This is a callback that will allow us to create the viewer and initialize
* it.
*/
@Override
public void createPartControl(Composite parent)
{
viewer = new TableViewer(parent, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL);
viewer.setContentProvider(new ViewContentProvider());
viewer.setLabelProvider(new ViewLabelProvider());
viewer.setSorter(new NameSorter());
viewer.setInput(null);
viewer.getTable().setHeaderVisible(true);
viewer.setSorter(new ViewerSorter(){
@Override
public int compare(Viewer viewer, Object e1, Object e2)
{
// TODO Auto-generated method stub
BoundedState c1 = (BoundedState) e1;
BoundedState c2 = (BoundedState) e2;
return c1.compareTo(c2);
}});
// ok, sort out the columns
TableViewerColumn col1 = new TableViewerColumn(viewer, SWT.NONE);
col1.getColumn().setText("Time");
col1.getColumn().setWidth(200);
col1.setLabelProvider(new ColumnLabelProvider()
{
@Override
public String getText(Object element)
{
BoundedState bs = (BoundedState) element;
// return bs.getTime().toString();
return _df.format(bs.getTime());
}
});
// ok, sort out the columns
TableViewerColumn col2 = new TableViewerColumn(viewer, SWT.NONE);
col2.getColumn().setText("Location");
col2.getColumn().setWidth(100);
col2.setLabelProvider(new ColumnLabelProvider()
{
@Override
public String getText(Object element)
{
String res;
BoundedState bs = (BoundedState) element;
BaseRange<?> loc = bs.getLocation();
if (loc != null)
res = loc.getConstraintSummary();
else
res = "n/a";
return res;
}
});
// ok, sort out the columns
TableViewerColumn col3 = new TableViewerColumn(viewer, SWT.NONE);
col3.getColumn().setText("Speed");
col3.getColumn().setWidth(100);
col3.setLabelProvider(new ColumnLabelProvider()
{
@Override
public String getText(Object element)
{
String res;
BoundedState bs = (BoundedState) element;
BaseRange<?> loc = bs.getSpeed();
if (loc != null)
res = loc.getConstraintSummary();
else
res = "n/a";
return res;
}
});
// ok, sort out the columns
TableViewerColumn col4 = new TableViewerColumn(viewer, SWT.NONE);
col4.getColumn().setText("Course");
col4.getColumn().setWidth(100);
col4.setLabelProvider(new ColumnLabelProvider()
{
@Override
public String getText(Object element)
{
String res;
BoundedState bs = (BoundedState) element;
BaseRange<?> loc = bs.getCourse();
if (loc != null)
res = loc.getConstraintSummary();
else
res = "n/a";
return res;
}
});
// Create the help context id for the viewer's control
PlatformUI.getWorkbench().getHelpSystem()
.setHelp(viewer.getControl(), "com.planetmayo.debrief.satc.viewer");
contributeToActionBars();
// hey, see if there's a track generator to listen to
_generator = SATC_Activator.getDefault().getMockEngine().getGenerator();
// did it work?
if (_generator != null)
{
_generator.addBoundedStateListener(_stateListener);
}
}
@Override
public void dispose()
{
_generator.removeBoundedStateListener(_stateListener);
super.dispose();
}
private void fillLocalPullDown(IMenuManager manager)
{
}
private void fillLocalToolBar(IToolBarManager manager)
{
}
/**
* Passing the focus request to the viewer's control.
*/
@Override
public void setFocus()
{
viewer.getControl().setFocus();
}
}
|
package bwyap.familyfeud.gui.control;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.ListSelectionModel;
import bwyap.familyfeud.game.Family;
import bwyap.familyfeud.game.FamilyFeudGame;
import bwyap.familyfeud.game.state.StatePlay;
import bwyap.familyfeud.gui.GBC;
import bwyap.gridgame.res.ResourceLoader;
/**
* A panel used to select a family for an action
* @author bwyap
*
*/
public class ChooseFamilyPanel extends JPanel {
private static final long serialVersionUID = -5811924958007378691L;
public static final int WIDTH = WindowControlPanel.WIDTH;
public static final int HEIGHT = StatePlayPanel.HEIGHT;
private JLabel title;
private JScrollPane listScroll;
private JList<Family> list;
private DefaultListModel<Family> listModel;
private JButton select;
private int command = -1;
private FamilyFeudGame game;
public ChooseFamilyPanel(FamilyFeudGame game) {
this.game = game;
setBorder(BorderFactory.createLineBorder(Color.BLACK, 2));
setLayout(new GridBagLayout());
setPreferredSize(new Dimension(WIDTH, HEIGHT));
initComponents();
}
public void initComponents() {
title = new JLabel("FAMILIES");
title.setFont(new Font(ResourceLoader.DEFAULT_FONT_NAME, Font.BOLD, 14));
listModel = new DefaultListModel<Family>();
list = new JList<Family>(listModel);
list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
listScroll = new JScrollPane(list);
listScroll.setMinimumSize(new Dimension(WIDTH - 20, (int)(HEIGHT*0.65)));
select = new JButton("Select");
select.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (list.getSelectedIndex() > -1 && command > -1) {
game.getState().executeAction(StatePlay.ACTION_EXECUTEPLAYACTION, new Object[]{
command, list.getSelectedIndex()});
}
}
});
add(title, new GBC(0, 0));
add(listScroll, new GBC(0, 1));
add(select, new GBC(0, 2));
}
/**
* Load families into panel list
*/
public void loadFamilies() {
for (Family f : game.getFamilies()) {
listModel.addElement(f);
}
}
/**
* Set the command to execute when the select button is pressed
* @param command
*/
public void setCommand(int command) {
this.command = command;
}
/**
* Reset the families for a new game
*/
public void reset() {
listModel.clear();
}
@Override
public void setEnabled(boolean enabled) {
super.setEnabled(enabled);
select.setEnabled(enabled);
}
}
|
package net.nunnerycode.bukkit.mythicdrops.api.tiers;
import net.nunnerycode.bukkit.mythicdrops.api.enchantments.MythicEnchantment;
import org.bukkit.ChatColor;
import java.util.List;
import java.util.Map;
import java.util.Set;
public interface Tier extends Comparable<Tier> {
String getName();
String getDisplayName();
ChatColor getDisplayColor();
ChatColor getIdentificationColor();
List<String> getBaseLore();
List<String> getBonusLore();
int getMinimumBonusLore();
int getMaximumBonusLore();
Set<MythicEnchantment> getBaseEnchantments();
Set<MythicEnchantment> getBonusEnchantments();
boolean isSafeBaseEnchantments();
boolean isSafeBonusEnchantments();
boolean isAllowHighBaseEnchantments();
boolean isAllowHighBonusEnchantments();
int getMinimumBonusEnchantments();
int getMaximumBonusEnchantments();
double getMaximumDurabilityPercentage();
double getMinimumDurabilityPercentage();
@Deprecated
Map<String, Double> getWorldDropChanceMap();
double getDropChance();
@Deprecated
Map<String, Double> getWorldSpawnChanceMap();
double getSpawnChance();
@Deprecated
Map<String, Double> getWorldIdentifyChanceMap();
double getIdentifyChance();
List<String> getAllowedItemGroups();
List<String> getDisallowedItemGroups();
List<String> getAllowedItemIds();
List<String> getDisallowedItemIds();
int getMinimumSockets();
int getMaximumSockets();
double getChanceToHaveSockets();
boolean isBroadcastOnFind();
int getOptimalDistance();
int getMaximumDistance();
}
|
package com.forerunnergames.tools;
import com.google.common.collect.Iterables;
import java.util.Arrays;
import java.util.Collection;
public class Arguments
{
public static void checkHasNoNullElements (final Iterable <?> iterable, final String iterableName)
{
if (iterable != null && Iterables.contains (iterable, null))
{
Arguments.illegalArgument (iterableName, ArgumentStatus.NULL_ELEMENTS);
}
}
public static void checkHasNoNullElements (final Object[] array, final String arrayName)
{
if (array != null && Arrays.asList(array).contains (null))
{
Arguments.illegalArgument (arrayName, ArgumentStatus.NULL_ELEMENTS);
}
}
public static void checkHasNoNullOrEmptyElements (final Collection <String> strings, final String collectionName)
{
if (strings == null || strings.isEmpty())
{
return;
}
for (String s : strings)
{
if (s == null)
{
Arguments.illegalArgument (collectionName, ArgumentStatus.NULL_ELEMENTS);
}
else if (s.isEmpty())
{
Arguments.illegalArgument (collectionName, ArgumentStatus.EMPTY_ELEMENTS);
}
}
}
public static void checkHasNoNullOrEmptyElements (final String[] array, final String arrayName)
{
if (array == null)
{
return;
}
checkHasNoNullOrEmptyElements (Arrays.asList (array), arrayName);
}
public static void checkHasNoNullOrEmptyOrBlankElements (final Collection <String> strings, final String collectionName)
{
if (strings == null || strings.isEmpty())
{
return;
}
for (String s : strings)
{
if (s == null)
{
Arguments.illegalArgument (collectionName, ArgumentStatus.NULL_ELEMENTS);
}
else if (s.isEmpty())
{
Arguments.illegalArgument (collectionName, ArgumentStatus.EMPTY_ELEMENTS);
}
else if (Strings.isWhitespace (s))
{
Arguments.illegalArgument (collectionName, ArgumentStatus.BLANK_ELEMENTS);
}
}
}
public static void checkHasNoNullOrEmptyOrBlankElements (final String[] array, final String arrayName)
{
if (array == null)
{
return;
}
checkHasNoNullOrEmptyOrBlankElements (Arrays.asList (array), arrayName);
}
public static void checkIsNegative (final int value, final String valueName)
{
checkUpperExclusiveBound ((long) value, 0, valueName, "");
}
public static void checkIsNegative (final long value, final String valueName)
{
checkUpperExclusiveBound (value, 0, valueName, "");
}
public static void checkIsNotNegative (final int value, final String valueName)
{
checkLowerInclusiveBound ((long) value, 0, valueName, "");
}
public static void checkIsNotNegative (final long value, final String valueName)
{
checkLowerInclusiveBound (value, 0, valueName, "");
}
public static void checkIsTrue (final boolean condition, final String errorMessage)
{
if (! condition)
{
throw new IllegalArgumentException (errorMessage);
}
}
public static void checkIsFalse (final boolean condition, final String errorMessage)
{
checkIsTrue (! condition, errorMessage);
}
public static <T> void checkIsNotNull (final T object, final String objectName)
{
if (object == null)
{
Arguments.illegalArgument (objectName, Arguments.ArgumentStatus.NULL);
}
}
public static void checkIsNotNullOrEmpty (final String s, final String stringName)
{
if (s == null)
{
Arguments.illegalArgument (stringName, ArgumentStatus.NULL);
}
else if (s.isEmpty())
{
Arguments.illegalArgument (stringName, ArgumentStatus.EMPTY);
}
}
public static <T> void checkIsNotNullOrEmpty (final Iterable <T> iterable, final String iterableName)
{
if (iterable == null)
{
Arguments.illegalArgument (iterableName, ArgumentStatus.NULL);
}
else if (! iterable.iterator().hasNext())
{
Arguments.illegalArgument (iterableName, ArgumentStatus.EMPTY);
}
}
public static void checkIsNotNullOrEmpty (final Object[] array, final String arrayName)
{
if (array == null)
{
Arguments.illegalArgument (arrayName, ArgumentStatus.NULL);
}
else if (array.length == 0)
{
Arguments.illegalArgument (arrayName, ArgumentStatus.EMPTY);
}
}
public static void checkIsNotNullOrEmptyOrBlank (final String s, final String stringName)
{
if (s == null)
{
Arguments.illegalArgument (stringName, ArgumentStatus.NULL);
}
else if (s.isEmpty())
{
Arguments.illegalArgument (stringName, ArgumentStatus.EMPTY);
}
else if (Strings.isWhitespace (s))
{
Arguments.illegalArgument (stringName, ArgumentStatus.BLANK);
}
}
public static void checkLowerInclusiveBound (final int value, final int lowerInclusiveBound, final String valueName)
{
checkLowerInclusiveBound ((long) value, (long) lowerInclusiveBound, valueName, "");
}
public static void checkLowerInclusiveBound (final int value,
final int lowerInclusiveBound,
final String valueName,
final String lowerInclusiveBoundName)
{
checkLowerInclusiveBound ((long) value, (long) lowerInclusiveBound, valueName, lowerInclusiveBoundName);
}
public static void checkLowerInclusiveBound (final long value, final long lowerInclusiveBound, final String valueName)
{
checkLowerInclusiveBound (value, lowerInclusiveBound, valueName, "");
}
public static void checkLowerInclusiveBound (final long value,
final long lowerInclusiveBound,
final String valueName,
final String lowerInclusiveBoundName)
{
if (value < lowerInclusiveBound)
{
boundsViolation (value, lowerInclusiveBound, valueName, lowerInclusiveBoundName, BoundType.LOWER_INCLUSIVE);
}
}
public static void checkLowerInclusiveBound (final float value,
final float lowerInclusiveBound,
final String valueName)
{
checkLowerInclusiveBound ((double) value, (double) lowerInclusiveBound, valueName, "");
}
public static void checkLowerInclusiveBound (final float value,
final float lowerInclusiveBound,
final String valueName,
final String lowerInclusiveBoundName)
{
checkLowerInclusiveBound ((double) value, (double) lowerInclusiveBound, valueName, lowerInclusiveBoundName);
}
public static void checkLowerInclusiveBound (final double value,
final double lowerInclusiveBound,
final String valueName)
{
checkLowerInclusiveBound (value, lowerInclusiveBound, valueName, "");
}
public static void checkLowerInclusiveBound (final double value,
final double lowerInclusiveBound,
final String valueName,
final String lowerInclusiveBoundName)
{
if (value < lowerInclusiveBound)
{
boundsViolation (value, lowerInclusiveBound, valueName, lowerInclusiveBoundName, BoundType.LOWER_INCLUSIVE);
}
}
public static void checkLowerExclusiveBound (final int value, final int lowerExclusiveBound, final String valueName)
{
checkLowerExclusiveBound ((long) value, (long) lowerExclusiveBound, valueName, "");
}
public static void checkLowerExclusiveBound (final int value,
final int lowerExclusiveBound,
final String valueName,
final String lowerExclusiveBoundName)
{
checkLowerExclusiveBound ((long) value, (long) lowerExclusiveBound, valueName, lowerExclusiveBoundName);
}
public static void checkLowerExclusiveBound (final long value, final long lowerExclusiveBound, final String valueName)
{
checkLowerExclusiveBound (value, lowerExclusiveBound, valueName, "");
}
public static void checkLowerExclusiveBound (final long value,
final long lowerExclusiveBound,
final String valueName,
final String lowerExclusiveBoundName)
{
if (value <= lowerExclusiveBound)
{
boundsViolation (value, lowerExclusiveBound, valueName, lowerExclusiveBoundName, BoundType.LOWER_EXCLUSIVE);
}
}
public static void checkLowerExclusiveBound (final float value,
final float lowerExclusiveBound,
final String valueName)
{
checkLowerExclusiveBound ((double) value, (double) lowerExclusiveBound, valueName, "");
}
public static void checkLowerExclusiveBound (final float value,
final float lowerExclusiveBound,
final String valueName,
final String lowerExclusiveBoundName)
{
checkLowerExclusiveBound ((double) value, (double) lowerExclusiveBound, valueName, lowerExclusiveBoundName);
}
public static void checkLowerExclusiveBound (final double value,
final double lowerExclusiveBound,
final String valueName)
{
checkLowerExclusiveBound (value, lowerExclusiveBound, valueName, "");
}
public static void checkLowerExclusiveBound (final double value,
final double lowerExclusiveBound,
final String valueName,
final String lowerExclusiveBoundName)
{
if (value <= lowerExclusiveBound)
{
boundsViolation (value, lowerExclusiveBound, valueName, lowerExclusiveBoundName, BoundType.LOWER_EXCLUSIVE);
}
}
public static void checkUpperInclusiveBound (final int value, final int upperInclusiveBound, final String valueName)
{
checkUpperInclusiveBound ((long) value, (long) upperInclusiveBound, valueName, "");
}
public static void checkUpperInclusiveBound (final int value,
final int upperInclusiveBound,
final String valueName,
final String upperInclusiveBoundName)
{
checkUpperInclusiveBound ((long) value, (long) upperInclusiveBound, valueName, upperInclusiveBoundName);
}
public static void checkUpperInclusiveBound (final long value, final long upperInclusiveBound, final String valueName)
{
checkUpperInclusiveBound (value, upperInclusiveBound, valueName, "");
}
public static void checkUpperInclusiveBound (final long value,
final long upperInclusiveBound,
final String valueName,
final String upperInclusiveBoundName)
{
if (value > upperInclusiveBound)
{
boundsViolation (value, upperInclusiveBound, valueName, upperInclusiveBoundName, BoundType.UPPER_INCLUSIVE);
}
}
public static void checkUpperInclusiveBound (final float value, final float upperInclusiveBound, final String valueName)
{
checkUpperInclusiveBound ((double) value, (double) upperInclusiveBound, valueName, "");
}
public static void checkUpperInclusiveBound (final float value,
final float upperInclusiveBound,
final String valueName,
final String upperInclusiveBoundName)
{
checkUpperInclusiveBound ((double) value, (double) upperInclusiveBound, valueName, upperInclusiveBoundName);
}
public static void checkUpperInclusiveBound (final double value,
final double upperInclusiveBound,
final String valueName)
{
checkUpperInclusiveBound (value, upperInclusiveBound, valueName, "");
}
public static void checkUpperInclusiveBound (final double value,
final double upperInclusiveBound,
final String valueName,
final String upperInclusiveBoundName)
{
if (value > upperInclusiveBound)
{
boundsViolation (value, upperInclusiveBound, valueName, upperInclusiveBoundName, BoundType.UPPER_INCLUSIVE);
}
}
public static void checkUpperExclusiveBound (final int value, final int upperExclusiveBound, final String valueName)
{
checkUpperExclusiveBound ((long) value, (long) upperExclusiveBound, valueName, "");
}
public static void checkUpperExclusiveBound (final int value,
final int upperExclusiveBound,
final String valueName,
final String upperExclusiveBoundName)
{
checkUpperExclusiveBound ((long) value, (long) upperExclusiveBound, valueName, upperExclusiveBoundName);
}
public static void checkUpperExclusiveBound (final long value, final long upperExclusiveBound, final String valueName)
{
checkUpperExclusiveBound (value, upperExclusiveBound, valueName, "");
}
public static void checkUpperExclusiveBound (final long value,
final long upperExclusiveBound,
final String valueName,
final String upperExclusiveBoundName)
{
if (value >= upperExclusiveBound)
{
boundsViolation (value, upperExclusiveBound, valueName, upperExclusiveBoundName, BoundType.UPPER_EXCLUSIVE);
}
}
public static void checkUpperExclusiveBound (final float value,
final float upperExclusiveBound,
final String valueName)
{
checkUpperExclusiveBound ((double) value, (double) upperExclusiveBound, valueName, "");
}
public static void checkUpperExclusiveBound (final float value,
final float upperExclusiveBound,
final String valueName,
final String upperExclusiveBoundName)
{
checkUpperExclusiveBound ((double) value, (double) upperExclusiveBound, valueName, upperExclusiveBoundName);
}
public static void checkUpperExclusiveBound (final double value, final double upperExclusiveBound, final String valueName)
{
checkUpperExclusiveBound (value, upperExclusiveBound, valueName, "");
}
public static void checkUpperExclusiveBound (final double value,
final double upperExclusiveBound,
final String valueName,
final String upperExclusiveBoundName)
{
if (value >= upperExclusiveBound)
{
boundsViolation (value, upperExclusiveBound, valueName, upperExclusiveBoundName, BoundType.UPPER_EXCLUSIVE);
}
}
private static void boundsViolation (final Number value,
final Number bound,
final String valueName,
final String boundName,
final BoundType boundType) throws IllegalArgumentException
{
final int stackLevel = getStackLevelOfFirstClassOutsideThisClass();
throw new IllegalArgumentException (valueName + " [value: " + value + "]" + " must be " +
boundType.getMessage() + " " + boundName + " [value: " + bound + "] " +
"when invoking " + Classes.getClassName (stackLevel) + "." +
Methods.getMethodName (stackLevel) + ".");
}
private static int getStackLevelOfFirstClassOutsideThisClass()
{
final int maxStackLevel = getMaxStackLevel();
final String thisClassName = Classes.getClassName (0);
for (int stackLevel = 1; stackLevel <= maxStackLevel; ++stackLevel)
{
if (! thisClassName.equals (Classes.getClassName (stackLevel)))
{
return stackLevel - 1;
}
}
return maxStackLevel - 1;
}
private static int getMaxStackLevel()
{
return Thread.currentThread().getStackTrace().length - 1;
}
private static void illegalArgument (final String argumentName,
final ArgumentStatus argumentStatus) throws IllegalArgumentException
{
final int stackLevel = getStackLevelOfFirstClassOutsideThisClass();
throw new IllegalArgumentException ("\nLocation: " + Classes.getClassName (stackLevel) + "." +
Methods.getMethodName (stackLevel) + "\nReason: argument '" + argumentName +
"' " + argumentStatus.getMessage());
}
private enum ArgumentStatus
{
BLANK ("is blank"),
BLANK_ELEMENTS ("has blank elements"),
EMPTY ("is empty"),
EMPTY_ELEMENTS ("has empty elements"),
NULL ("is null"),
NULL_ELEMENTS ("has null elements");
private String getMessage()
{
return message;
}
private ArgumentStatus (final String message)
{
this.message = message;
}
private final String message;
}
private enum BoundType
{
LOWER_EXCLUSIVE ("strictly greater than"),
UPPER_EXCLUSIVE ("strictly less than"),
LOWER_INCLUSIVE ("greater than or equal to"),
UPPER_INCLUSIVE ("less than or equal to");
private String getMessage()
{
return message;
}
private BoundType (final String message)
{
this.message = message;
}
private final String message;
}
private Arguments()
{
Classes.instantiationNotAllowed();
}
}
|
package ch.unizh.ini.jaer.projects.rnnfilter;
import java.util.Arrays;
import org.jblas.DoubleMatrix;
import com.jogamp.opengl.GLAutoDrawable;
import ch.unizh.ini.jaer.chip.cochlea.BinauralCochleaEvent.Ear;
import ch.unizh.ini.jaer.chip.cochlea.CochleaAMSEvent;
import ch.unizh.ini.jaer.chip.cochlea.CochleaAMSEvent.FilterType;
import ch.unizh.ini.jaer.chip.cochlea.RollingCochleaGramDisplayMethod;
import com.jogamp.opengl.GL;
import com.jogamp.opengl.GL2;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.logging.Level;
import java.util.stream.IntStream;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.filechooser.FileFilter;
import javax.swing.filechooser.FileNameExtensionFilter;
import net.sf.jaer.Description;
import net.sf.jaer.DevelopmentStatus;
import net.sf.jaer.chip.AEChip;
import net.sf.jaer.event.BasicEvent;
import net.sf.jaer.event.EventPacket;
import net.sf.jaer.eventprocessing.EventFilter2D;
import net.sf.jaer.graphics.DisplayMethod;
import net.sf.jaer.graphics.FrameAnnotater;
import net.sf.jaer.graphics.MultilineAnnotationTextRenderer;
/**
* Extracts binned spike features from CochleaAMS sensor and processes them through a recurrent network
* @author jithendar
*/
@Description("Extracts binned spike features from CochleaAMS sensor and processes them through a recurrent network")
@DevelopmentStatus(DevelopmentStatus.Status.Experimental)
public class RNNfilter extends EventFilter2D implements FrameAnnotater , PropertyChangeListener{
/**
* Chooses the time length for the bin, the current network is trained on 5ms data, hence the variable is initialized appropriately
*/
private int binTimeLength = getPrefs().getInt("binTimeLength", 5000); // default value set to 5 ms
/**
* Choose whether to bin the data from both ears, when false the chooseEar variable chooses which ear to bin from
*/
private boolean useBothEars = getBoolean("useBothEars", false);
/**
* If data from only one ear is chosen, this variable gets the preference from the user
*/
private int chooseEar = getPrefs().getInt("chooseEar", 0); // 0 corresponds to left, 1 corresponds to right
/**
* Choose whether to bin the data from all the neurons, when false the chooseNeuron variable chooses the appropriate neuron
*/
private boolean useAllNeurons = getBoolean("useAllNeurons", false);
/**
* If data from only one neuron is chosen, this variable gets the preference from the user
*/
private int chooseNeuron = getPrefs().getInt("chooseNeuron", 0); // choose a value between 0 and 3, otherwise a random value will be chosen
/**
* Choose whether to bin data from both the filter types, when false the chooseFilterType chooses the appropriate filter type
*/
private boolean useBothFilterTypes = getBoolean("useBothFilterTypes", false);
/**
* If data from only one filter type is to be binned, this variable gets the preference from the user
*/
private int chooseFilterType = getPrefs().getInt("chooseFilterType", 1); // 0 corresponds to LPF, 1 corresponds to BPF
/**
* The XML file to load the RNN network from
*/
private String lastRNNXMLFile = getString("lastRNNXMLFile", "rnn_cochlea_v3b_jAER.xml");
/**
* Choose whether to display activations or not
*/
private boolean displayActivations = getBoolean("displayActivations", true);
/**
* Choose whether to display the softmax probability of the prediction
*/
private boolean displayAccuracy = getBoolean("displayAccuracy",true);
/**
* If the filter saves the feature as an array list, then choose whether to display it once the feature is recorded
*/
private boolean displayFeature = getBoolean("displayFeature",true);
/**
* If true, the frame is annotated with the label prediction only if the softmax accuracy is more than 0.9
*/
private boolean showPredictionOnlyIfGood = getBoolean("showPredictionOnlyIfGood",false);
/**
* True if the filter intends to process RNN only when you click a button, if false it is a continuous RNN processing
*/
private boolean clickToProcess = getBoolean("clickToProcess",true);
/**
* If needed to click to process RNN, choose if the RNN process happens as a batch at the end or in a continuous live setting
*/
private boolean batchRNNProcess = getBoolean("batchRNNProcess",false);
/**
* Is the filter binning the events
*/
private boolean processingEnabled = getBoolean("processingEnabled", true);
/**
* Boolean variable which checks if the filter is initialized
*/
private boolean isInitialized = false;
/**
* Number of channels (frequencies), when a user chooses a number other 64 an appropriately trained network has to be initialized
*/
private int nChannels = 64;
/**
* Number of neurons for each neuron, default value of 4
*/
private int nNeurons = 4;
/**
* Number of ears, default value of 2
*/
private int nEars = 2;
/**
* Number of filter types, default value of 2
*/
private int nFilterTypes = 2;
/**
* The last time when RNN was processed
*/
private int lastBinCompleteTime;
/**
* Array to store the binned data, this has the data from the latest bin
*/
private int[] binnedData = new int[this.getnChannels()];
/**
* When not using continuous live recording, this array list holds the list of binned data at all previous times, which is then given to an RNN network
*/
private ArrayList<int[]> binnedDataList;
/**
* RNN network for the filter
*/
protected RNNetwork rnnetwork;
/**
* Output of the network;
*/
private double[] networkOutput;
/**
* Corresponding label given the network output
*/
private int label = 12;
/**
* The ear to choose the events from, 0 for left and 1 for right
*/
private int whichEar;
/**
* The neuron to choose the events from, values in 0-3
*/
private int whichNeuron;
/**
* The filter type to choose events from, 0 for LPF and 1 for BPF
*/
private int whichFilter;
/**
* Choose which type of function you want the filter to perform, 0 stands for continuous recording, 1 stands for click and record continuous RNN processing, 2 stands for click and record batch RNN processing
*/
private int whichFunction = 3;
private boolean isFirstEventDone = false;
private int counter = 0; //counts total number of basic events
private int counter1 = 0; //counts total number of processed events
private int lastEventTime;
private int firstEventTime;
private ArrayList<Integer> rnnProcessTimeStampList;
private ArrayList<double[]> rnnOutputList;
private boolean addedDisplayMethodPropertyChangeListener=false;
private boolean screenCleared=false; // set by RollingCochleaGramDisplayMethod
//TestNumpyData testNumpyData; //debug
//private String lastTestDataXMLFile = "ti_train_cochlea_data_nozeroslices_20_jAER_input.xml"; //debug
public RNNfilter(AEChip chip) {
super(chip);
String xmlnetwork = "1. XML Network", function = "2. Filter function", parameters = "3. Parameter options", display = "4. Display";
setPropertyTooltip("loadFromXML","Load an XML file containing the network in an appropriate format");
setPropertyTooltip("runRNN","If clickToProcess is set to true, the filter will process events when this button is kept pressed, also the network will be reset when you press the button. So press the button and hold it, speak and release the button when you want the filter to stop processing.");
setPropertyTooltip("toggleBinning","If clickToProcess is set to true, this button will toggle the boolean variable - processingEnabled - which enables the events to be processed. So when processingEnabled is false, clicking on the button will make the filter start processing the events and when processingEnabled is true, clicking the button will make the filter stop processing events.");
setPropertyTooltip(xmlnetwork,"lastRNNXMLFile","The XML file containing an RNN network exported from keras/somewhere else");
setPropertyTooltip(parameters,"binTimeLength","Choose the bin size (in micro seconds) for the binning of the data, choose a network appropriately");
setPropertyTooltip(parameters,"useBothEars","Choose whether to use the events from both ears");
setPropertyTooltip(parameters,"chooseEar","If processing events from only one ear, choose which ear to process them from, 0 for left and 1 for right");
setPropertyTooltip(parameters,"useAllNeurons","Choose whether to process the events from all the neurons");
setPropertyTooltip(parameters,"chooseNeuron","If events from all neurons are not to be processed, which neuron's events should be chosen, choose a value in {0,1,2,3}");
setPropertyTooltip(parameters,"useBothFilterTypes","Choose whether to process the events from both the filter types");
setPropertyTooltip(parameters,"chooseFilterType","If processing is to be done only on one filter type, which filter type should be chosen; 0 for low pass and 1 for band pass");
setPropertyTooltip(function,"clickToProcess","True if the filter wants to only process the events when the RunRNN filter action is kept pressed; default: false");
setPropertyTooltip(function,"batchRNNProcess","True if you want to save the sound feature and then process the RNN in one go when clickToProcess is true, false otherwise; default: false");
setPropertyTooltip(function,"displayActivations","Choose whether to display the softmax activations as a bar chart");
setPropertyTooltip(function,"displayAccuracy","Choose whether to display the softmax accuracy of the current prediction");
setPropertyTooltip(function,"displayFeature","Choose whether to display any recorded feature once recording is completed");
setPropertyTooltip(function,"showPredictionOnlyIfGood","Show the output prediction only if the prediction is good (>0.9)");
setPropertyTooltip("processingEnabled","The boolean variable which enables the events to be processed");
initFilter();
}
@Override
synchronized public void annotate(GLAutoDrawable drawable) {
GL2 gl = drawable.getGL().getGL2();
if(chip.getCanvas().getDisplayMethod() instanceof RollingCochleaGramDisplayMethod ) {
// what to display on rolling cochlea gram display
return;
}
if ((this.rnnetwork != null) & (this.rnnetwork.netname != null)) {
MultilineAnnotationTextRenderer.resetToYPositionPixels(chip.getSizeY() * .1f);
MultilineAnnotationTextRenderer.setScale(.1f);
if(this.isProcessingEnabled()) {
int timeElapsed = this.lastEventTime - this.firstEventTime;
timeElapsed = (int) timeElapsed/1000;
MultilineAnnotationTextRenderer.renderMultilineString(String.join("", this.rnnetwork.netname," ; ","Time elapsed:",Double.toString(timeElapsed),"ms"));
} else {
MultilineAnnotationTextRenderer.renderMultilineString(this.rnnetwork.netname);
}
}
if (this.networkOutput != null) {
double tmpValue = RNNfilter.maxValue(this.networkOutput)*100;
tmpValue = (double)((int) tmpValue); tmpValue = tmpValue/100;
if(!this.isShowPredictionOnlyIfGood() | (this.isShowPredictionOnlyIfGood() & (tmpValue > 0.9))) {
MultilineAnnotationTextRenderer.resetToYPositionPixels(chip.getSizeY() * 1f);
MultilineAnnotationTextRenderer.setScale(.1f);
if(this.isDisplayAccuracy()) {
// MultilineAnnotationTextRenderer.renderMultilineString(String.join("", Integer.toString(this.label + 1),";",Double.toString(tmpValue)));
MultilineAnnotationTextRenderer.renderMultilineString(String.join("", Integer.toString(this.label),";",Double.toString(tmpValue)));
} else {
// MultilineAnnotationTextRenderer.renderMultilineString(Integer.toString(this.label + 1));
MultilineAnnotationTextRenderer.renderMultilineString(Integer.toString(this.label));
}
}
}
if(this.networkOutput != null & this.isDisplayActivations()) {
this.showActivations(gl, chip.getSizeX(), chip.getSizeY());
}
}
@Override
synchronized public EventPacket<?> filterPacket(EventPacket<?> in) {
for (BasicEvent e : in) {
this.counter++;
try {
if(!this.isInitialized) { initFilter(); } // making sure the filter is initialized
CochleaAMSEvent cochleaAMSEvent = ((CochleaAMSEvent) e);
//int tmpByte = e.getType();
int ear; if (cochleaAMSEvent.getEar() == Ear.LEFT) { ear = 0; } else { ear = 1; }// sets the ear variable to 0 if from left ear, 1 if right ear
int filterType; if (cochleaAMSEvent.getFilterType() == FilterType.LPF) { filterType = 0; } else { filterType = 1; }// sets the filterType variable to 0 if from low pass, 1 if from band pass
int neuron = cochleaAMSEvent.getThreshold(); // returns the index corresponding to the ganglion cell threshold level
int timeStamp = e.timestamp; // the timestamp of the event
int channel = e.x; // the channel address (0-63) of the event
if ((this.rnnetwork.initialized) & this.isProcessingEnabled()) { processEvent(timeStamp, channel, ear, neuron, filterType); }// updates the bin data and performs additional computation as and when required
} catch (Exception e1) { log.log(Level.WARNING, "In for-loop in filterPacket caught exception {0}", e1); }
}
return in;
}
@Override
public void resetFilter() {
this.resetNetwork();
this.resetBins();
switch(this.getWhichFunction()) {
case 2:
this.setProcessingEnabled(false); break;
case 1:
this.setProcessingEnabled(false); break;
case 0:
this.setProcessingEnabled(true); break;
default:
break;
}
this.rnnProcessTimeStampList = new ArrayList<>();
this.rnnOutputList = new ArrayList<>();
this.binnedDataList = new ArrayList<>();
this.counter = 0;
this.counter1 = 0;
this.isFirstEventDone = false;
this.firstEventTime = 0; this.lastEventTime = 0;
}
@Override
public void initFilter() {
this.rnnetwork = new RNNetwork();
//this.testNumpyData = new TestNumpyData(); //debug
this.resetBins();
Arrays.fill(this.binnedData, 0); // initialized the bin data array to zero
// if whichEar preference given by user is out of bounds, choose a random value
if((this.getChooseEar() > -1) & (this.getChooseEar() < this.getnEars())) { this.whichEar = this.getChooseEar();
} else { this.whichEar = (int) (Math.random() * (this.getnEars())); }
// if whichNeuron preference given by user is out of bounds, choose a random value
if((this.getChooseNeuron() > -1) & (this.getChooseNeuron() < this.getnNeurons())) { this.whichNeuron = this.getChooseNeuron();
} else { this.whichNeuron = (int) (Math.random() * (this.getnNeurons())); }
//if whichFilter preference given by user is out of bounds, choose a random value
if((this.getChooseFilterType() > -1) & (this.getChooseFilterType() < this.getnFilterTypes())) { this.whichFilter = this.getChooseFilterType();
} else { this.whichFilter = (int) (Math.random() * (this.getnFilterTypes())); }
//initializes the function of the filter from the user preferences
if(!this.clickToProcess) {
this.whichFunction = 0;
} else {
if(this.isBatchRNNProcess()) {
this.whichFunction = 2;
} else {
this.whichFunction = 1;
}
}
//sets the binning variable to either start binning right away or wait for a signal from the GUI, depending on the function
switch(this.getWhichFunction()) {
case 2:
this.setProcessingEnabled(false); break;
case 1:
this.setProcessingEnabled(false); break;
case 0:
this.setProcessingEnabled(true); break;
default:
break;
}
//this.loadTestDataFromXML(); //debug
//this.testNumpyData.testingNetwork(); //debug
this.rnnProcessTimeStampList = new ArrayList<>();
this.rnnOutputList = new ArrayList<>();
this.binnedDataList = new ArrayList<>();
this.label = 12;
this.isInitialized = true;
this.isFirstEventDone = false;
this.counter = 0;
this.counter1 = 0;
}
synchronized public void loadFromXML() {
this.setProcessingEnabled(false);
JFileChooser c = new JFileChooser(this.getLastRNNXMLFile());
FileFilter filter = new FileNameExtensionFilter("XML File", "xml");
c.addChoosableFileFilter(filter);
c.setFileFilter(filter);
c.setSelectedFile(new File(this.getLastRNNXMLFile()));
int ret = c.showOpenDialog(chip.getAeViewer());
if (ret != JFileChooser.APPROVE_OPTION) {
return;
}
File f = c.getSelectedFile();
try { this.rnnetwork.loadFromXML(f);
this.setLastRNNXMLFile(f.toString());
putString("lastRNNXMLFile", this.getLastRNNXMLFile());
//this.testNumpyData.rnnetwork.loadFromXML(c.getSelectedFile()); //debug
} catch (Exception e) { log.log(Level.WARNING, "Couldn't upload the xml file, please check. Caught exception {0}", e); }
this.resetFilter();
}
/**
* Updates the bin data and if the timeStamp is past the bin time length, either the RNN network is processed or the bin is updated in the arraylist of bins
* @param timeStamp - timestamp of the event
* @param channel - which channel is the event from
* @param ear - which ear is the event from
* @param neuron - which neuron is the event from
* @param filterType - which filter type is the event from
*/
public void processEvent(int timeStamp, int channel, int ear, int neuron, int filterType) throws IOException {
// makes sure that the address is ok
if(!isAddressOk(channel, ear, neuron, filterType)) { return; }
this.counter1++;
if(!this.isFirstEventDone) {
this.ifFirstEventNotDone(timeStamp, channel);
}
if(timeStamp < this.lastBinCompleteTime) {
switch (this.getWhichFunction()) {
case 1:
log.log(Level.SEVERE, "The present timestamp is less than a previous timestamp, this isn't supposed to happen");
this.resetFilter();
break;
case 0:
log.log(Level.SEVERE, "The present timestamp is less than a previous timestamp, this isn't supposed to happen");
this.resetFilter();
this.ifFirstEventNotDone(timeStamp, channel);
this.updateBin(channel);
break;
case 2:
log.log(Level.SEVERE, "The present timestamp is less than a previous timestamp, this isn't supposed to happen");
this.resetFilter();
break;
default:
break;
}
return;
} else {
this.lastEventTime = timeStamp;
}
// if the present spike's timestamp is within a binTimeLength of the last binned data, we update the bin
if ((timeStamp > this.lastBinCompleteTime)&(timeStamp < (this.lastBinCompleteTime + this.getBinTimeLength()))) {
this.updateBin(channel);
} else if (timeStamp > (this.lastBinCompleteTime + this.getBinTimeLength())) {
// if the timestamp is more than a binTimeLength, then reset the bins to zero
switch (this.getWhichFunction()) {
case 1:
this.updateBinnedDataListNoReset(timeStamp);
this.processRNN(timeStamp);
break;
case 0:
this.processRNN(timeStamp);
break;
case 2:
this.updateBinnedDataList(timeStamp);
break;
default:
break;
}
this.binnedData[channel]++;
}
}
/**
* Increase the updateBin counter at the given channel
* @param channel
*/
public void updateBin(int channel) {
this.binnedData[channel]++;
}
/**
* Updates the binned data list, given the latest time stamp it even adds the necessary zeros to the network
* @param timeStamp
*/
public void updateBinnedDataList(int timeStamp) {
this.binnedDataList.add(Arrays.copyOf(this.binnedData, this.getnChannels()));
this.lastBinCompleteTime += this.getBinTimeLength();
this.resetBins();
while (timeStamp > this.lastBinCompleteTime + this.getBinTimeLength()) {
int[] tmpArr = new int[this.getnChannels()];
this.binnedDataList.add(tmpArr);
this.lastBinCompleteTime += this.getBinTimeLength();
}
}
/**
* Updates the binned data list, given the latest time stamp it even adds the necessary zeros to the network, but does not reset the current bin data
* @param timeStamp
*/
public void updateBinnedDataListNoReset(int timeStamp) {
this.binnedDataList.add(Arrays.copyOf(this.binnedData, this.getnChannels()));
int tmpRNNTimeStamp = this.lastBinCompleteTime;
tmpRNNTimeStamp += this.getBinTimeLength();
while (timeStamp > tmpRNNTimeStamp + this.getBinTimeLength()) {
int[] tmpArr = new int[this.getnChannels()];
this.binnedDataList.add(tmpArr);
tmpRNNTimeStamp += this.getBinTimeLength();
}
}
/**
* Removes the zero slices from the beginning and the ending and gives the resulting binned array list of arrays; currently not used
* @return
*/
public ArrayList<int[]> processDataListSingleDigit() { // removes zero slices from the beginning and the ending
if(this.binnedDataList.isEmpty()) { return this.binnedDataList; }
boolean removeStart = true;
ArrayList<int[]> tmpBinnedDataList = new ArrayList<>();
for (int[] currentList : this.binnedDataList) {
int sum = RNNfilter.sumOfArray(currentList);
if(removeStart == true & sum != 0) {
removeStart = false;
}
if (!removeStart) {
tmpBinnedDataList.add(currentList);
}
}
// tmpBinnedDataList doesn't have zero frames at the beginning
for (int i = tmpBinnedDataList.size() - 1; i > -1; i
int sum = RNNfilter.sumOfArray(tmpBinnedDataList.get(i));
if (sum == 0) {
tmpBinnedDataList.remove(i);
} else {
break;
}
}
return tmpBinnedDataList;
}
public void resetBinnedDataList() {
this.binnedDataList = new ArrayList<int[]>();
}
/**
* Process the RNN in a batch manner
*/
public void processRNNList() {
if(this.binnedDataList.isEmpty()) { return; }
DoubleMatrix tempOutput;
tempOutput = DoubleMatrix.zeros(this.getnChannels());
for (int[] currentBinnedData : this.binnedDataList) {
tempOutput = this.rnnetwork.output(RNNfilter.intToDouble(currentBinnedData));
}
this.networkOutput = RNNfilter.DMToDouble(tempOutput);
this.label = RNNfilter.indexOfMaxValue(this.networkOutput);
}
/**
* Returns true if the channel, ear and neuron attributes of the event are ok
* @param channel1 - frequency channel of the input event
* @param ear1 - the ear the input event is from
* @param neuron1 - the neuron the input event is from
* @param filterType1 - the filterType the input event is from
* @return - true if all the inputs are not abnormal
*/
public boolean isAddressOk (int channel1, int ear1, int neuron1, int filterType1) {
if ((channel1 < 0) | (channel1 > this.getnChannels())) { return false;} // making sure the channel value is not out of bounds
if ((ear1 < 0) | (ear1 > this.getnEars())) {return false;} // making sure the ear value is out of bounds
if ((neuron1 < 0) | (neuron1 > this.getnNeurons())) {return false;} // making sure the neuron value is not out of bounds
if ((filterType1 < 0) | (filterType1 > this.getnFilterTypes())) {return false;} // making sure the filterType value is not out of bounds
if (!this.isUseBothEars()) {
if (ear1 != this.whichEar) { // if both ears are not to be used and the ear value is not what is asked for, return false
return false;
}
}
if (!this.isUseAllNeurons()) {
if (neuron1 != this.whichNeuron) { // if all neurons are not to be used and the neuron value is not what is asked for, return false
return false;
}
}
if (!this.useBothFilterTypes) {
if (filterType1 != this.whichFilter) { // if all filters are not to be used and the filter value is not what was asked for, return false
return false;
}
}
return true;
}
/**
* Processes the RNN network for continuous recording setting
* @param timeStamp - the timestamp of the present event
*/
public void processRNN(int timeStamp) {
long now = System.nanoTime();
DoubleMatrix tempOutput = this.rnnetwork.output(RNNfilter.intToDouble(this.binnedData));
long dt = System.nanoTime() - now;
//log.log(Level.INFO, String.format("%d nanoseconds for one frame computation", dt));
this.networkOutput = RNNfilter.DMToDouble(tempOutput);
if(chip.getCanvas().getDisplayMethod() instanceof RollingCochleaGramDisplayMethod){
if(!addedDisplayMethodPropertyChangeListener){
chip.getCanvas().getDisplayMethod().getSupport().addPropertyChangeListener(this);
addedDisplayMethodPropertyChangeListener=true;
}
// save outputs for rendering
if(screenCleared){
// reset memory
}
// save results
}
this.label = RNNfilter.indexOfMaxValue(this.networkOutput);
this.lastBinCompleteTime += this.getBinTimeLength();
this.resetBins();
// if the present timeStamp is very far from the last time RNN was processed, that means an appropriate number of zero bins have to be sent to the network
while (timeStamp > (this.lastBinCompleteTime + this.getBinTimeLength())) {
tempOutput = this.rnnetwork.output(RNNfilter.intToDouble(this.binnedData));
this.networkOutput = RNNfilter.DMToDouble(tempOutput);
this.rnnOutputList.add(this.networkOutput);
this.label = RNNfilter.indexOfMaxValue(this.networkOutput);
this.lastBinCompleteTime += this.getBinTimeLength();
}
}
/**
* Resets the binnedData to zero
*/
public void resetBins() {
Arrays.fill(this.binnedData, 0); // initialized the bin data array to zero
}
/**
* Resets the internal states in the network
*/
public void resetNetwork() {
this.rnnetwork.resetNetworkLayers();
}
/**
* Copies int array to a double array
* @param intArray - 1 dimensional int array
* @return doubleArray - 1 dimensional double array
*/
public static double[] intToDouble(int[] intArray) {
double[] doubleArray = new double[intArray.length];
for(int i=0; i<intArray.length; i++) {
doubleArray[i] = intArray[i];
}
return doubleArray;
}
/**
* Copies a 1 dimensional DoubleMatrix (jblas) into a 1 dimensional double array
* @param doubleMatrix - 1 dimensional double matrix, there is no check make sure the input is indeed 1 dimensional
* @return 1 dimensional double array
*/
public static double[] DMToDouble(DoubleMatrix doubleMatrix) {
int length = doubleMatrix.length;
double[] doubleArray = new double[length];
for (int i = 0;i<length;i++) {
doubleArray[i] = doubleMatrix.get(i);
}
return doubleArray;
}
/**
* Returns the index of the maximum value in the array
* @param input
* @return
*/
public static int indexOfMaxValue (double[] input) {
int index = 0;
double tmpMax = input[0];
for (int i = 1; i<input.length; i++) {
if (input[i] > tmpMax) {
tmpMax = input[i];
index = i;
}
}
return index;
}
/**
* Returns the maximum value in the array
* @param input
* @return
*/
public static double maxValue (double[] input) {
double tmpMax = input[0];
for (int i = 1; i<input.length; i++) {
if (input[i] > tmpMax) {
tmpMax = input[i];
}
}
return tmpMax;
}
/**
* Returns the maximum value in a 2D array
* @param input
* @return
*/
public static int maxValueIn2DArray (int[][] input) {
int output = 0;
int xLength = input.length;
int yLength = input[0].length;
for (int x = 0; x < xLength; x++) {
for (int y = 0; y < yLength; y++) {
if (output < input[x][y]) { output = input[x][y]; }
}
}
return output;
}
/**
* Calculates the sum of elements in an integer array
* @param input an integer array
* @return sum of elements in input integer array
*/
public static int sumOfArray (int[] input) {
int sum = 0;
for (int i : input) {
sum += i;
}
return sum;
}
/**
* Returns an array with the sum of each array in an arraylist of arrays
* @param input
* @return sum of array elements in arraylist
*/
public static int[] sumOfArrayList (ArrayList<int[]> input) {
int size = input.size();
int[] output = new int[size];
for (int i = 0;i < size;i++) {
output[i] = RNNfilter.sumOfArray(input.get(i));
}
return output;
}
/**
* Converts the arraylist holding the recorded features and prints it as an image in a new JFrame
* @param input
* @throws IOException
*/
public void printDigit (ArrayList<int[]> input) throws IOException {
if(input.isEmpty()) { return; }
int xLength = input.size();
int yLength = input.get(0).length;
int maxValue = 0;
int[][] tmpImage = new int[xLength][yLength];
for (int i = 0;i < xLength; i++) {
tmpImage[i] = input.get(i);
}
maxValue = RNNfilter.maxValueIn2DArray(tmpImage);
int[][] tmpImageScaled = RNNfilter.rescale2DArray(tmpImage, 255/maxValue);
BufferedImage newImage = new BufferedImage(xLength,yLength,BufferedImage.TYPE_INT_RGB);
for (int x = 0;x < xLength; x++) {
for (int y = 0;y < yLength; y++) {
newImage.setRGB(x, y, tmpImageScaled[x][y]);
}
}
ImageIcon icon = new ImageIcon(newImage);
ScaledImagePanel scaledImage = new ScaledImagePanel(icon);
JFrame frame = new JFrame();
frame.setSize(xLength, yLength);
frame.add(scaledImage);
frame.setVisible(true);
}
@Override
public void propertyChange(PropertyChangeEvent pce) {
if(pce.getPropertyName()==RollingCochleaGramDisplayMethod.EVENT_SCREEN_CLEARED){
screenCleared=true;
}
}
/**
* A class which helps scale the image to fit the size of the JFrame
*/
public class ScaledImagePanel extends JPanel {
ImageIcon image;
public ScaledImagePanel() {
}
public ScaledImagePanel(ImageIcon image1) {
this.image = image1;
}
@Override
protected void paintComponent(Graphics g) {
BufferedImage scaledImage = getScaledImage();
super.paintComponent(g);
g.drawImage(scaledImage, 0, 0, null);
}
private BufferedImage getScaledImage(){
BufferedImage image = new BufferedImage(getWidth(),getHeight(), BufferedImage.TYPE_INT_RGB);
Graphics2D g2d = (Graphics2D) image.createGraphics();
g2d.addRenderingHints(new RenderingHints(RenderingHints.KEY_RENDERING,RenderingHints.VALUE_RENDER_QUALITY));
g2d.drawImage(this.image.getImage(), 0, 0,getWidth(),getHeight(), null);
return image;
}
}
/**
* Rescales the values in an integer 2D array to an approximated integer 2D array
* @param input
* @param scale
* @return
*/
public static int[][] rescale2DArray (int[][] input, double scale) {
int xLength = input.length;
int yLength = input[0].length;
int[][] output = new int[xLength][yLength];
for (int x = 0;x < xLength; x++) {
for (int y = 0; y < yLength; y++) {
output[x][y] = (int) scale*input[x][y];
}
}
return output;
}
/**
* Annotates the frame with the activations of the softmax layer as a bar chart
* @param gl
* @param width
* @param height
*/
public void showActivations (GL2 gl, int width, int height) {
if (this.networkOutput == null) {
} else {
float dx = (float) (width)/this.networkOutput.length;
float dy = (float) 0.8f * (height);
gl.glBegin(GL.GL_LINE_STRIP);
for (int i = 0; i < this.networkOutput.length; i++) {
double tmpOutput = this.networkOutput[i];
double tmpOutputMax = RNNfilter.maxValue(this.networkOutput);
float y_end = (float) (1 + (dy*tmpOutput)/tmpOutputMax); // draws the relative activations of the neurons in the layer
float x_start = 1 + (dx * i);
float x_end = x_start + dx;
gl.glVertex2f(x_start, 1);
gl.glVertex2f(x_start, y_end);
gl.glVertex2f(x_end, y_end);
gl.glVertex2f(x_end, 1);
}
gl.glEnd();
}
}
/**
* @return the nChannels
*/
public int getnChannels() {
return nChannels;
}
/**
* @return the nNeurons
*/
public int getnNeurons() {
return nNeurons;
}
/**
* @return the nEars
*/
public int getnEars() {
return nEars;
}
/**
* @return the binTimeLength
*/
public int getBinTimeLength() {
return binTimeLength;
}
/**
* @param binTimeLength1 the binTimeLength to set
*/
public void setBinTimeLength(int binTimeLength1) {
getPrefs().putInt("binTimeLength",binTimeLength1);
getSupport().firePropertyChange("binTimeLength", this.binTimeLength, binTimeLength1);
this.binTimeLength = binTimeLength1;
}
/**
* @return the useBothEars
*/
public boolean isUseBothEars() {
return useBothEars;
}
/**
* @param useBothEars1 the useBothEars to set
*/
public void setUseBothEars(boolean useBothEars1) {
putBoolean("useBothEars",useBothEars1);
this.useBothEars = useBothEars1;
}
/**
* @return the chooseEar
*/
public int getChooseEar() {
return chooseEar;
}
/**
* @param chooseEar1 the chooseEar to set
*/
public void setChooseEar(int chooseEar1) {
getPrefs().putInt("chooseEar",chooseEar1);
getSupport().firePropertyChange("chooseEar", this.chooseEar, chooseEar1);
this.chooseEar = chooseEar1;
if((this.getChooseEar() > -1) & (this.getChooseEar() < this.getnEars())) { this.whichEar = this.getChooseEar();
} else { this.whichEar = (int) (Math.random() * (this.getnEars())); }
}
/**
* @return the useAllNeurons
*/
public boolean isUseAllNeurons() {
return useAllNeurons;
}
/**
* @param useAllNeurons1 the useAllNeurons to set
*/
public void setUseAllNeurons(boolean useAllNeurons1) {
putBoolean("useAllNeurons",useAllNeurons1);
this.useAllNeurons = useAllNeurons1;
}
/**
* @return the chooseNeuron
*/
public int getChooseNeuron() {
return chooseNeuron;
}
/**
* @param chooseNeuron1 the chooseNeuron to set
*/
public void setChooseNeuron(int chooseNeuron1) {
getPrefs().putInt("chooseNeuron", chooseNeuron1);
getSupport().firePropertyChange("chooseNeuron", this.chooseNeuron, chooseNeuron1);
this.chooseNeuron = chooseNeuron1;
if((this.getChooseNeuron() > -1) & (this.getChooseNeuron() < this.getnNeurons())) { this.whichNeuron = this.getChooseNeuron();
} else { this.whichNeuron = (int) (Math.random() * (this.getnNeurons())); }
}
/**
* @return the lastRNNXMLFile
*/
public String getLastRNNXMLFile() {
return lastRNNXMLFile;
}
/**
* @param lastRNNXMLFile1 the lastRNNXMLFile to set
*/
public void setLastRNNXMLFile(String lastRNNXMLFile1) {
putString("lastRNNXMLFile", lastRNNXMLFile1);
this.lastRNNXMLFile = lastRNNXMLFile1;
}
/**
* @return the binning
*/
public boolean isProcessingEnabled() {
return processingEnabled;
}
/**
* @param binning1 the binning to set
*/
public void setProcessingEnabled(boolean binning1) {
putBoolean("processingEnabled", binning1);
boolean oldBinning = this.processingEnabled;
this.processingEnabled = binning1;
support.firePropertyChange("processingEnabled", oldBinning, binning1);
}
/**
* @return the useBothFilterTypes
*/
public boolean isUseBothFilterTypes() {
return useBothFilterTypes;
}
/**
* @param useBothFilterTypes1 the useBothFilterTypes to set
*/
public void setUseBothFilterTypes(boolean useBothFilterTypes1) {
putBoolean("useBothFilterTypes", useBothFilterTypes1);
this.useBothFilterTypes = useBothFilterTypes1;
}
/**
* @return the chooseFilterType
*/
public int getChooseFilterType() {
return chooseFilterType;
}
/**
* @param chooseFilterType1 the chooseFilterType to set
*/
public void setChooseFilterType(int chooseFilterType1) {
getPrefs().putInt("chooseFilterType", chooseFilterType1);
getSupport().firePropertyChange("chooseFilterType", this.chooseFilterType, chooseFilterType1);
this.chooseFilterType = chooseFilterType1;
if((this.getChooseFilterType() > -1) & (this.getChooseFilterType() < this.getnFilterTypes())) { this.whichFilter = this.getChooseFilterType();
} else { this.whichFilter = (int) (Math.random() * (this.getnFilterTypes())); }
}
/**
* @return the nFilterTypes
*/
public int getnFilterTypes() {
return nFilterTypes;
}
/**
* @return the whichFunction
*/
public int getWhichFunction() {
return whichFunction;
}
public void ifFirstEventNotDone(int timeStamp, int channel) {
this.firstEventTime = timeStamp;
this.isFirstEventDone = true;
this.lastBinCompleteTime = timeStamp;
this.updateBin(channel);
this.lastEventTime = timeStamp;
}
/**
* @return the displayActivations
*/
public boolean isDisplayActivations() {
return displayActivations;
}
/**
* @param displayActivations the displayActivations to set
*/
public void setDisplayActivations(boolean displayActivations) {
putBoolean("displayActivations",displayActivations);
this.displayActivations = displayActivations;
}
/**
* @return the displayAccuracy
*/
public boolean isDisplayAccuracy() {
return displayAccuracy;
}
/**
* @param displayAccuracy the displayAccuracy to set
*/
public void setDisplayAccuracy(boolean displayAccuracy) {
putBoolean("displayAccuracy",displayAccuracy);
this.displayAccuracy = displayAccuracy;
}
/**
* @return the displayFeature
*/
public boolean isDisplayFeature() {
return displayFeature;
}
/**
* @param displayFeature the displayFeature to set
*/
public void setDisplayFeature(boolean displayFeature) {
putBoolean("displayFeature",displayFeature);
this.displayFeature = displayFeature;
}
/**
* @return the showPredictionOnlyIfGood
*/
public boolean isShowPredictionOnlyIfGood() {
return showPredictionOnlyIfGood;
}
/**
* @param showPredictionOnlyIfGood the showPredictionOnlyIfGood to set
*/
public void setShowPredictionOnlyIfGood(boolean showPredictionOnlyIfGood) {
putBoolean("showPredictionOnlyIfGood",showPredictionOnlyIfGood);
this.showPredictionOnlyIfGood = showPredictionOnlyIfGood;
}
/**
* @return the singleDigits
*/
public boolean isClickToProcess() {
return clickToProcess;
}
/**
* @param singleDigits the singleDigits to set
*/
public void setClickToProcess(boolean clickToProcess) {
putBoolean("clickToProcess",clickToProcess);
this.clickToProcess = clickToProcess;
if(!clickToProcess) {
this.whichFunction = 0;
} else {
if(this.isBatchRNNProcess()) {
this.whichFunction = 2;
} else {
this.whichFunction = 1;
}
}
this.resetFilter();
}
/**
* @return the batchRNNProcess
*/
public boolean isBatchRNNProcess() {
return batchRNNProcess;
}
/**
* @param batchRNNProcess the batchRNNProcess to set
*/
public void setBatchRNNProcess(boolean batchRNNProcess) {
putBoolean("batchRNNProcess",batchRNNProcess);
this.batchRNNProcess = batchRNNProcess;
if(this.clickToProcess) {
if(batchRNNProcess) {
this.whichFunction = 2;
} else {
this.whichFunction = 1;
}
}
this.resetFilter();
}
/**
* Implements a toggleBinning function which would be used to build the button with the same name
* @throws IOException
*/
synchronized public void toggleBinning() throws IOException {
if(this.getWhichFunction()==2 & this.isProcessingEnabled()==false) {
this.resetNetwork();
this.setProcessingEnabled(true);
} else if(this.getWhichFunction()==2 & this.isProcessingEnabled()==true) { // if the filter was binning the events before, then stop binning and process the digit recorded
this.setProcessingEnabled(false);
if (this.displayFeature) { this.printDigit(binnedDataList); }
this.processRNNList();
this.resetBins();
this.rnnProcessTimeStampList = new ArrayList<>();
this.rnnOutputList = new ArrayList<>();
this.binnedDataList = new ArrayList<>();
this.counter = 0;
this.counter1 = 0;
this.isFirstEventDone = false;
}
if(this.getWhichFunction() == 1 & this.isProcessingEnabled() == false) {
this.resetNetwork();
this.setProcessingEnabled(true);
} else if(this.getWhichFunction() == 1 & this.isProcessingEnabled() == true) {
this.setProcessingEnabled(false);
if(this.displayFeature) { this.printDigit(binnedDataList); }
this.resetBins();
this.rnnProcessTimeStampList = new ArrayList<>();
this.rnnOutputList = new ArrayList<>();
this.binnedDataList = new ArrayList<>();
this.counter = 0;
this.counter1 = 0;
this.isFirstEventDone = false;
}
}
/**
* Implements the toggleBinning button, runs the toggleBinning function
* @throws IOException
*/
public void doToggleBinning() throws IOException {
this.toggleBinning();
}
/**
* Implements the function which would run when the RunRNN button is pressed; as suggested by Prof. Tobi
*/
public void doPressRunRNN() {
log.info("RunRNN button pressed");
if(this.getWhichFunction() == 1 | this.getWhichFunction() == 2) {
this.resetNetwork();
this.setProcessingEnabled(true);
}
}
/**
* Implements the function which would run when the RunRNN button is released; as suggested by Prof. Tobi
* @throws IOException
*/
public void doReleaseRunRNN() throws IOException {
log.info("RunRNN button released");
if(this.getWhichFunction() == 1 | this.getWhichFunction() == 2) {
this.setProcessingEnabled(false);
if(this.displayFeature) { this.printDigit(binnedDataList); }
if(this.getWhichFunction() == 2) { this.processRNNList(); }
this.resetBins();
this.rnnProcessTimeStampList = new ArrayList<>();
this.rnnOutputList = new ArrayList<>();
this.binnedDataList = new ArrayList<>();
this.counter = 0;
this.counter1 = 0;
this.isFirstEventDone = false;
}
}
/**
* Implements the loadFromXML function as a button
*/
public void doLoadFromXML() {
this.loadFromXML();
}
}
|
package nl.yacht.lakesideresort.controller;
import nl.yacht.lakesideresort.domain.Room;
import org.springframework.stereotype.Repository;
import java.time.LocalDate;
import java.util.HashMap;
import java.util.Map;
@Repository
public class RoomRepository {
private Map<Integer, Room> roomMap = new HashMap<>();
public Room insertRoom(Room room){
this.roomMap.put(room.getRoomNumber(), room);
return room;
}
public void deleteRoom(int roomNumber){
this.roomMap.remove(roomNumber);
}
public Room createNewRoom(int roomNumber, Room.RoomType roomType, Room.RoomSize roomSize, LocalDate availableFrom){
Room r = new Room(roomNumber, roomType, roomSize, availableFrom);
this.roomMap.put(roomNumber, r);
return r;
}
public void updateRoom(int roomNumber, Room r){
updateRoom(roomNumber, r.getRoomNumber(), r.getRoomType(), r.getRoomSize());
}
public void updateRoom(int roomNumber, int newRoomNumber, Room.RoomType roomType, Room.RoomSize roomSize){
Room r = roomMap.get(roomNumber);
if(r != null){
if (roomSize != null){
r.setRoomSize(roomSize);
}
if (roomType != null) {
r.setRoomType(roomType);
}
if (newRoomNumber > 0 && newRoomNumber != roomNumber) {
r.setRoomNumber(newRoomNumber);
roomMap.remove(roomNumber);
roomMap.put(newRoomNumber, r);
}
System.out.println("Room Updated");
} else {
System.out.println("This room does not exists");
}
}
public void printRooms(){
for (Room r : this.roomMap.values()){
System.out.println("Room: " + r.getRoomNumber());
}
}
public Iterable<Room> getRooms(){
return this.roomMap.values();
}
}
|
package com.forgeessentials.util;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.item.ItemStack;
import com.forgeessentials.api.APIRegistry;
import com.forgeessentials.api.UserIdent;
import com.forgeessentials.commons.selections.Point;
import com.forgeessentials.commons.selections.WarpPoint;
import com.forgeessentials.data.v2.DataManager;
import com.forgeessentials.data.v2.Loadable;
import com.forgeessentials.util.events.FEPlayerEvent.NoPlayerInfoEvent;
import com.forgeessentials.util.selections.SelectionHandler;
import com.google.gson.annotations.Expose;
public class PlayerInfo implements Loadable
{
private static HashMap<UUID, PlayerInfo> playerInfoMap = new HashMap<UUID, PlayerInfo>();
/* General */
public final UserIdent ident;
@Expose(serialize = false)
private boolean hasFEClient = false;
/* Teleport */
private WarpPoint home;
private WarpPoint lastTeleportOrigin;
private WarpPoint lastDeathLocation;
private long lastTeleportTime = 0;
/* Selection */
private Point sel1;
private Point sel2;
private int selDim;
/* Selection wand */
@Expose(serialize = false)
private boolean wandEnabled = false;
@Expose(serialize = false)
private String wandID;
@Expose(serialize = false)
private int wandDmg;
/* Inventory groups */
private Map<String, List<ItemStack>> inventoryGroups = new HashMap<>();
private String activeInventoryGroup = "default";
/* Stats / time */
private long timePlayed = 0;
@Expose(serialize = false)
private long timePlayedRef = 0;
private Date firstLogin = new Date();
private Date lastLogin = new Date();
private Date lastLogout;
@Expose(serialize = false)
private long lastActivity = System.currentTimeMillis();
private HashMap<String, Date> namedTimeout = new HashMap<String, Date>();
private PlayerInfo(UUID uuid)
{
this.ident = UserIdent.get(uuid);
}
@Override
public void afterLoad()
{
if (namedTimeout == null)
namedTimeout = new HashMap<String, Date>();
lastActivity = System.currentTimeMillis();
if (activeInventoryGroup == null || activeInventoryGroup.isEmpty())
activeInventoryGroup = "default";
}
/**
* Notifies the PlayerInfo to save itself to the Data store.
*/
public void save()
{
DataManager.getInstance().save(this, ident.getUuid().toString());
}
public boolean isLoggedIn()
{
return ident.hasPlayer();
}
public static PlayerInfo get(UUID uuid)
{
PlayerInfo info = playerInfoMap.get(uuid);
if (info != null)
return info;
// Attempt to populate this info with some data from our storage
info = DataManager.getInstance().load(PlayerInfo.class, uuid.toString());
if (info != null)
{
playerInfoMap.put(uuid, info);
return info;
}
// Create new player info data
EntityPlayerMP player = UserIdent.getPlayerByUuid(uuid);
info = new PlayerInfo(uuid);
playerInfoMap.put(uuid, info);
if (player != null)
APIRegistry.getFEEventBus().post(new NoPlayerInfoEvent(player));
return info;
}
public static PlayerInfo get(EntityPlayer player)
{
return get(player.getPersistentID());
}
public static PlayerInfo get(UserIdent ident)
{
if (!ident.hasUuid())
return null;
return get(ident.getUuid());
}
public static Collection<PlayerInfo> getAll()
{
return playerInfoMap.values();
}
public static void login(UUID uuid)
{
PlayerInfo pi = get(uuid);
pi.lastActivity = System.currentTimeMillis();
pi.timePlayedRef = System.currentTimeMillis();
pi.lastLogin = new Date();
}
public static void logout(UUID uuid)
{
if (!playerInfoMap.containsKey(uuid))
return;
PlayerInfo pi = playerInfoMap.remove(uuid);
pi.getTimePlayed();
pi.lastLogout = new Date();
pi.timePlayedRef = 0;
pi.save();
}
public static boolean exists(UUID uuid)
{
if (playerInfoMap.containsKey(uuid))
return true;
if (DataManager.getInstance().exists(PlayerInfo.class, uuid.toString()))
return true;
return false;
}
/**
* Unload PlayerInfo and save to disk
*/
public static void discard(UUID uuid)
{
PlayerInfo info = playerInfoMap.remove(uuid);
if (info != null)
info.save();
}
/**
* Discard all PlayerInfo
*/
public static void discardAll()
{
for (PlayerInfo info : playerInfoMap.values())
info.save();
playerInfoMap.clear();
}
public Date getFirstLogin()
{
return firstLogin;
}
public Date getLastLogin()
{
return lastLogin;
}
public Date getLastLogout()
{
return lastLogout;
}
public long getTimePlayed()
{
if (isLoggedIn() && timePlayedRef != 0)
{
timePlayed += System.currentTimeMillis() - timePlayedRef;
timePlayedRef = System.currentTimeMillis();
}
return timePlayed;
}
public void setActive()
{
lastActivity = System.currentTimeMillis();
}
public void setActive(long delta)
{
lastActivity = System.currentTimeMillis() - delta;
}
public long getInactiveTime()
{
return System.currentTimeMillis() - lastActivity;
}
/* Timeouts */
/**
* Check, if a timeout passed
*
* @param name
* @return true, if the timeout passed
*/
public boolean checkTimeout(String name)
{
Date timeout = namedTimeout.get(name);
if (timeout == null)
return true;
if (timeout.after(new Date()))
return false;
namedTimeout.remove(name);
return true;
}
/**
* Get the remaining timeout in milliseconds
*/
public long getRemainingTimeout(String name)
{
Date timeout = namedTimeout.get(name);
if (timeout == null)
return 0;
return timeout.getTime() - new Date().getTime();
}
/**
* Start a named timeout. Use {@link #checkTimeout(String)} to check if the timeout has passed.
*
* @param name
* Unique name of the timeout
* @param milliseconds
* Timeout in milliseconds
*/
public void startTimeout(String name, int milliseconds)
{
Date date = new Date();
date.setTime(date.getTime() + milliseconds);
namedTimeout.put(name, date);
}
/* Wand */
public boolean isWandEnabled()
{
return wandEnabled;
}
public void setWandEnabled(boolean wandEnabled)
{
this.wandEnabled = wandEnabled;
}
public String getWandID()
{
return wandID;
}
public void setWandID(String wandID)
{
this.wandID = wandID;
}
public int getWandDmg()
{
return wandDmg;
}
public void setWandDmg(int wandDmg)
{
this.wandDmg = wandDmg;
}
/* Selection */
public Point getSel1()
{
return sel1;
}
public Point getSel2()
{
return sel2;
}
public int getSelDim()
{
return selDim;
}
public void setSel1(Point point)
{
sel1 = point;
}
public void setSel2(Point point)
{
sel2 = point;
}
public void setSelDim(int dimension)
{
selDim = dimension;
}
/* Inventory groups */
public Map<String, List<ItemStack>> getInventoryGroups()
{
return inventoryGroups;
}
public List<ItemStack> getInventoryGroupItems(String name)
{
return inventoryGroups.get(name);
}
public String getInventoryGroup()
{
return activeInventoryGroup;
}
public void setInventoryGroup(String name)
{
if (!activeInventoryGroup.equals(name))
{
// Get the new inventory
List<ItemStack> newInventory = inventoryGroups.get(name);
// Create empty inventory if it did not exist yet
if (newInventory == null)
newInventory = new ArrayList<>();
// ChatOutputHandler.felog.info(String.format("Changing inventory group for %s from %s to %s",
// ident.getUsernameOrUUID(), activeInventoryGroup, name));
/*
* ChatOutputHandler.felog.info("Items in old inventory:"); for (int i = 0; i <
* ident.getPlayer().inventory.getSizeInventory(); i++) { ItemStack itemStack =
* ident.getPlayer().inventory.getStackInSlot(i); if (itemStack != null) ChatOutputHandler.felog.info(" " +
* itemStack.getDisplayName()); } ChatOutputHandler.felog.info("Items in new inventory:"); for (ItemStack
* itemStack : newInventory) if (itemStack != null) ChatOutputHandler.felog.info(" " +
* itemStack.getDisplayName());
*/
// Swap player inventory and store the old one
inventoryGroups.put(activeInventoryGroup, PlayerUtil.swapInventory(this.ident.getPlayerMP(), newInventory));
// Clear the inventory-group that was assigned to the player (optional)
inventoryGroups.put(name, null);
// Save the new active inventory-group
activeInventoryGroup = name;
}
}
/* Teleportation */
public WarpPoint getLastTeleportOrigin()
{
return lastTeleportOrigin;
}
public void setLastTeleportOrigin(WarpPoint lastTeleportStart)
{
this.lastTeleportOrigin = lastTeleportStart;
}
public WarpPoint getLastDeathLocation()
{
return lastDeathLocation;
}
public void setLastDeathLocation(WarpPoint lastDeathLocation)
{
this.lastDeathLocation = lastDeathLocation;
}
public long getLastTeleportTime()
{
return lastTeleportTime;
}
public void setLastTeleportTime(long currentTimeMillis)
{
this.lastTeleportTime = currentTimeMillis;
}
public WarpPoint getHome()
{
return home;
}
public void setHome(WarpPoint home)
{
this.home = home;
}
/* Other */
public boolean getHasFEClient()
{
return hasFEClient;
}
public void setHasFEClient(boolean status)
{
this.hasFEClient = status;
SelectionHandler.sendUpdate(ident.getPlayerMP());
}
}
|
package com.github.mk23.jmxproxy.core;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonSerializable;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.jsontype.TypeSerializer;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
public class MBean implements JsonSerializable {
private final Map<String, History> attributes;
private final ThreadLocal<Integer> limit = new ThreadLocal<Integer>() {
@Override
protected Integer initialValue() {
return -1;
}
};
/**
* <p>Default constructor.</p>
*
* Creates a map of {@link Attribute} name to {@link History} of associated values.
*/
public MBean() {
attributes = new HashMap<String, History>();
}
/**
* <p>Inserts a new Attribute name to History association.</p>
*
* Creates a new {@link Attribute} value {@link History} object and inserts into
* the map store associating it to the specified attribute name.
*
* @param attributeName name of the {@link Attribute} used as the map key.
* @param size number of items to preserve in the associated {@link History}.
*
* @return the newly created empty {@link History} object.
*/
public final History addHistory(final String attributeName, final int size) {
if (!attributes.containsKey(attributeName)) {
History history = new History(size);
attributes.put(attributeName, history);
}
return attributes.get(attributeName);
}
/**
* <p>Sets the thread local history request limit.</p>
*
* Set the thread local limit for all {@link History} when serializing to JSON.
* Because this method returns its object, requesting serialization can be done
* with a single statement. For example:
*
* <p><code>return {@link javax.ws.rs.core.Response}.ok(mbean.setLimit(5)).build();</code></p>
*
* @param bound the number of items to retreive from {@link History} for this thread.
*
* @return this mbean object for chaining calls.
*/
public final MBean setLimit(final Integer bound) {
this.limit.set(bound);
return this;
}
/**
* <p>Getter for attribute names.</p>
*
* Extracts and returns the unique {@link java.util.Set} of all currently stored
* {@link Attribute} names.
*
* @return {@link java.util.Set} of {@link Attribute} name {@link java.lang.String}s.
*/
public final Set<String> getAttributes() {
return attributes.keySet();
}
/**
* <p>Getter for most recent attribute.</p>
*
* Fetches the most recent {@link Attribute} value for the specified name from the
* associated {@link History} in the map store.
*
* @param attribute name of the {@link Attribute} to look up in the map store.
*
* @return latest {@link Attribute} object from {@link History} if found, null otherwise.
*/
public final Attribute getAttribute(final String attribute) {
History history = attributes.get(attribute);
if (history == null) {
return null;
}
return history.getAttribute();
}
/**
* <p>Getter for a subset of historical attribute values.</p>
*
* Fetches an array, limited by the requested bound, of most recent {@link Attribute} values
* for the specified name from the associated {@link History} in the map store.
*
* @param attribute name of the {@link Attribute} to look up in the map store.
* @param bound size of the resulting array or full history if this exceeds capacity or less than 1.
*
* @return array of the latest {@link Attribute} objects from {@link History} if found, empty otherwise.
*/
public final Attribute[] getAttributes(final String attribute, final int bound) {
History history = attributes.get(attribute);
if (history == null) {
return new Attribute[0];
}
return history.getAttributes(bound);
}
/** {@inheritDoc} */
@Override
public final void serialize(
final JsonGenerator jgen,
final SerializerProvider sp
) throws IOException, JsonProcessingException {
buildJson(jgen);
}
/** {@inheritDoc} */
@Override
public final void serializeWithType(
final JsonGenerator jgen,
final SerializerProvider sp,
final TypeSerializer ts
) throws IOException, JsonProcessingException {
buildJson(jgen);
}
private void buildJson(final JsonGenerator jgen) throws IOException, JsonProcessingException {
int bound = limit.get();
jgen.writeStartObject();
for (Map.Entry<String, History> attributeEntry : attributes.entrySet()) {
if (bound < 0) {
jgen.writeObjectField(attributeEntry.getKey(), attributeEntry.getValue().getAttribute());
} else {
jgen.writeObjectField(attributeEntry.getKey(), attributeEntry.getValue().getAttributes(bound));
}
}
jgen.writeEndObject();
}
}
|
package com.java110.vo;
import com.alibaba.fastjson.JSONObject;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import java.io.Serializable;
/**
* @ClassName ResultVo
* @Description TODO
* @Author wuxw
* @Date 2020/5/28 18:41
* @Version 1.0
* add by wuxw 2020/5/28
**/
public class ResultVo implements Serializable {
public static final int CODE_ERROR = 404;
public static final int CODE_OK = 200;
public static final int CODE_MACHINE_OK = 0;
public static final int CODE_MACHINE_ERROR = -1;
public static final int CODE_UNAUTHORIZED = 401;
public static final int CODE_WECHAT_UNAUTHORIZED = 1401;
public static final int ORDER_ERROR = 500;
public static final String MSG_ERROR = "";
public static final String MSG_OK = "";
public static final String MSG_UNAUTHORIZED = "";
private int page;
private int rows;
private int records;
private int total;
private int code;
private String msg;
private Object data;
public ResultVo() {
}
public ResultVo(int code, String msg) {
this.code = code;
this.msg = msg;
}
public ResultVo(Object data) {
this.code = CODE_OK;
this.msg = MSG_OK;
this.data = data;
}
public ResultVo(int records, int total, Object data) {
this.code = CODE_OK;
this.msg = MSG_OK;
this.records = records;
this.total = total;
this.data = data;
}
public ResultVo(int code, String msg, Object data) {
this.code = code;
this.msg = msg;
this.data = data;
}
public ResultVo(int records, int total, int code, String msg, Object data) {
this.records = records;
this.total = total;
this.code = code;
this.msg = msg;
this.data = data;
}
public int getPage() {
return page;
}
public void setPage(int page) {
this.page = page;
}
public int getRows() {
return rows;
}
public void setRows(int rows) {
this.rows = rows;
}
public int getRecords() {
return records;
}
public void setRecords(int records) {
this.records = records;
}
public int getTotal() {
return total;
}
public void setTotal(int total) {
this.total = total;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
@Override
public String toString() {
return JSONObject.toJSONString(this);
}
/**
* ResponseEntity
*
* @param records
* @param total
* @param data
* @return
*/
public static ResponseEntity<String> createResponseEntity(int records, int total, Object data) {
ResultVo resultVo = new ResultVo(records, total, data);
ResponseEntity<String> responseEntity = new ResponseEntity<String>(resultVo.toString(), HttpStatus.OK);
return responseEntity;
}
/**
*
* @param url
* @return
*/
public static ResponseEntity<String> redirectPage(String url) {
HttpHeaders headers = new HttpHeaders();
headers.add(HttpHeaders.LOCATION, url);
ResponseEntity<String> responseEntity = new ResponseEntity<String>("123123", headers, HttpStatus.BAD_REQUEST);
return responseEntity;
}
/**
* ResponseEntity
*
* @param code
* @param msg
* @param data
* @return
*/
public static ResponseEntity<String> createResponseEntity(int code, String msg, Object data) {
ResultVo resultVo = new ResultVo(code, msg, data);
ResponseEntity<String> responseEntity = new ResponseEntity<String>(resultVo.toString(), HttpStatus.OK);
return responseEntity;
}
/**
* ResponseEntity
*
* @param records
* @param total
* @param code
* @param msg
* @param data
* @return
*/
public static ResponseEntity<String> createResponseEntity(int records, int total, int code, String msg, Object data) {
ResultVo resultVo = new ResultVo(records, total, code, msg, data);
ResponseEntity<String> responseEntity = new ResponseEntity<String>(resultVo.toString(), HttpStatus.OK);
return responseEntity;
}
}
|
package com.github.nsnjson.decoding;
import com.fasterxml.jackson.databind.JsonNode;
import java.util.Optional;
public class Decoder {
/**
* Decodes JSON from specified NSNJSON presentation by custom decoding.
* @param presentation NSNJSON presentation of JSON
* @param decoding custom decoding
* @return JSON
*/
public static Optional<JsonNode> decode(JsonNode presentation, Decoding decoding) {
return decoding.decode(presentation);
}
}
|
package org.apache.flume.interceptor;
import java.util.LinkedList;
import java.util.List;
import org.apache.flume.Context;
import org.apache.flume.Event;
import org.apache.flume.interceptor.service.FlumeCacheService;
import org.apache.flume.interceptor.service.ICacheService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class CacheableInterceptor implements Interceptor {
private ApplicationContext context;
private ICacheService<Event> service;
public CacheableInterceptor() {
// Get Spring context
this.context = new ClassPathXmlApplicationContext("beans.xml");
}
@Override
public void initialize() {
// Get cache service instance
service = context.getBean(ICacheService.class);
}
@Override
public Event intercept(Event event) {
// Edit the FlumeCacheService.intercept method to implement
// the transformation you want to cache.
return service.intercept(event);
}
@Override
public List<Event> intercept(List<Event> events) {
List<Event> intercepted = new LinkedList<Event>();
for (Event e : events) {
intercepted.add(intercept(e));
}
return intercepted;
}
ApplicationContext getContext() {
return context;
}
ICacheService<Event> getService() {
return service;
}
@Override
public void close() {
}
public static class Builder implements Interceptor.Builder {
public Interceptor build() {
return new CacheableInterceptor();
}
@Override
public void configure(Context context) {
}
}
}
|
package com.github.onsdigital.api.data;
import com.github.davidcarboni.ResourceUtils;
import com.github.davidcarboni.restolino.framework.Endpoint;
import com.github.onsdigital.configuration.Configuration;
import com.github.onsdigital.data.DataService;
import com.github.onsdigital.util.HostHelper;
import com.github.onsdigital.util.Validator;
import com.mashape.unirest.http.exceptions.UnirestException;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.eclipse.jetty.http.HttpStatus;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.GET;
import javax.ws.rs.core.Context;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.util.HashMap;
import java.util.Map;
import static com.mashape.unirest.http.Unirest.get;
@Endpoint
public class Data {
static boolean validated;
@GET
public Map<String, String> getData(@Context HttpServletRequest request, @Context HttpServletResponse response) throws IOException {
// Ensures ResourceUtils gets the right classloader when running
// reloadable in development:
ResourceUtils.classLoaderClass = Data.class;
// Validate all Json so that we get a warning if
// there's an issue with a file that's been edited.
if (!validated) {
Validator.validate();
validated = true;
}
// Add a five-minute cache time to static files to reduce round-trips to
// the server and increase performance whilst still allowing the system
// to be updated quite promptly if necessary:
if (!HostHelper.isLocalhost(request)) {
response.addHeader("cache-control", "public, max-age=300");
}
String collection = "";
String authenticationToken = "";
final String authenticationHeader = "X-Florence-Token";
if (request.getCookies() != null) {
for (Cookie cookie : request.getCookies()) {
if (cookie.getName().equals("collection")) {
System.out.println("Found collection cookie: " + cookie.getValue());
collection = cookie.getValue();
}
if (cookie.getName().equals("access_token")) {
System.out.println("Found access_token cookie: " + cookie.getValue());
authenticationToken = cookie.getValue();
}
}
}
InputStream data;
if (StringUtils.isEmpty(collection))
{
data = DataService.getDataStream(request.getRequestURI());
}
else {
URI uri = URI.create(request.getRequestURI());
String uriPath = DataService.cleanPath(uri);
if (uriPath.length() > 0)
{
uriPath += "/";
}
uriPath += "data.json";
try {
String url = Configuration.getZebedeeUrl() + "/content/" + collection;
System.out.println("Calling zebedee: " + url + "for path " + uriPath + " with token: " + authenticationToken);
String dataString = get(Configuration.getZebedeeUrl() + "/content/" + collection)
.header(authenticationHeader, authenticationToken)
.queryString("uri", uriPath).asString().getBody();
data = IOUtils.toInputStream(dataString);
} catch (UnirestException e) {
// Look for a data file:
System.out.println("Exception calling zebedee: " + e.getMessage());
e.printStackTrace();
data = DataService.getDataStream(request.getRequestURI());
}
}
// Output directly to the response
// (rather than deserialise and re-serialise)
response.setCharacterEncoding("UTF8");
response.setContentType("application/json");
if (data != null) {
try (InputStream input = data) {
IOUtils.copy(input, response.getOutputStream());
}
return null;
} else {
response.setStatus(HttpStatus.NOT_FOUND_404);
Map<String, String> error404 = new HashMap<>();
error404.put("message", "These are not the data you are looking for.");
error404.put("status", String.valueOf(HttpStatus.NOT_FOUND_404));
return error404;
}
}
}
|
package com.exedio.cope;
import java.util.Date;
import com.exedio.cope.CompareConditionItem.YEnum;
public class CompareConditionTest extends AbstractLibTest
{
public CompareConditionTest()
{
super(Main.compareConditionModel);
}
CompareConditionItem item1;
CompareConditionItem item2;
CompareConditionItem item3;
CompareConditionItem item4;
CompareConditionItem item5;
Date date;
private void setDate(final CompareConditionItem item, final Date date)
{
item.setDate(date);
}
private Date offset(final Date date, final long offset)
{
return new Date(date.getTime()+offset);
}
@Override
public void setUp() throws Exception
{
super.setUp();
date = new Date(1087365298214l);
deleteOnTearDown(item1 = new CompareConditionItem("string1", 1, 11l, 2.1, offset(date, -2), YEnum.V1));
deleteOnTearDown(item2 = new CompareConditionItem("string2", 2, 12l, 2.2, offset(date, -1), YEnum.V2));
deleteOnTearDown(item3 = new CompareConditionItem("string3", 3, 13l, 2.3, offset(date, 0), YEnum.V3));
deleteOnTearDown(item4 = new CompareConditionItem("string4", 4, 14l, 2.4, offset(date, +1), YEnum.V4));
deleteOnTearDown(item5 = new CompareConditionItem("string5", 5, 15l, 2.5, offset(date, +2), YEnum.V5));
}
public void testCompareConditions()
{
// test equals/hashCode
assertEquals(item1.someString.less("a"), item1.someString.less("a"));
assertNotEquals(item1.someString.less("a"), item1.someString.less("b"));
assertNotEquals(item1.someString.less("a"), item1.string.less("a"));
assertNotEquals(item1.someString.less("a"), item1.someString.lessOrEqual("a"));
// equal
assertContains(item3, item1.TYPE.search(item1.string.equal("string3")));
assertContains(item3, item1.TYPE.search(item1.intx.equal(3)));
assertContains(item3, item1.TYPE.search(item1.longx.equal(13l)));
assertContains(item3, item1.TYPE.search(item1.doublex.equal(2.3)));
assertContains(item3, item1.TYPE.search(item1.date.equal(date)));
assertContains(item3, item1.TYPE.search(item1.enumx.equal(YEnum.V3)));
// not equal
assertContains(item1, item2, item4, item5, item1.TYPE.search(item1.string.notEqual("string3")));
assertContains(item1, item2, item4, item5, item1.TYPE.search(item1.intx.notEqual(3)));
assertContains(item1, item2, item4, item5, item1.TYPE.search(item1.longx.notEqual(13l)));
assertContains(item1, item2, item4, item5, item1.TYPE.search(item1.doublex.notEqual(2.3)));
assertContains(item1, item2, item4, item5, item1.TYPE.search(item1.date.notEqual(date)));
assertContains(item1, item2, item4, item5, item1.TYPE.search(item1.enumx.notEqual(YEnum.V3)));
// less
assertContains(item1, item2, item1.TYPE.search(item1.string.less("string3")));
assertContains(item1, item2, item1.TYPE.search(item1.intx.less(3)));
assertContains(item1, item2, item1.TYPE.search(item1.longx.less(13l)));
assertContains(item1, item2, item1.TYPE.search(item1.doublex.less(2.3)));
assertContains(item1, item2, item1.TYPE.search(item1.date.less(date)));
assertContains(item1, item2, item1.TYPE.search(item1.enumx.less(YEnum.V3)));
// less or equal
assertContains(item1, item2, item3, item1.TYPE.search(item1.string.lessOrEqual("string3")));
assertContains(item1, item2, item3, item1.TYPE.search(item1.intx.lessOrEqual(3)));
assertContains(item1, item2, item3, item1.TYPE.search(item1.longx.lessOrEqual(13l)));
assertContains(item1, item2, item3, item1.TYPE.search(item1.doublex.lessOrEqual(2.3)));
assertContains(item1, item2, item3, item1.TYPE.search(item1.date.lessOrEqual(date)));
assertContains(item1, item2, item3, item1.TYPE.search(item1.enumx.lessOrEqual(YEnum.V3)));
// greater
assertContains(item4, item5, item1.TYPE.search(item1.string.greater("string3")));
assertContains(item4, item5, item1.TYPE.search(item1.intx.greater(3)));
assertContains(item4, item5, item1.TYPE.search(item1.longx.greater(13l)));
assertContains(item4, item5, item1.TYPE.search(item1.doublex.greater(2.3)));
assertContains(item4, item5, item1.TYPE.search(item1.date.greater(date)));
assertContains(item4, item5, item1.TYPE.search(item1.enumx.greater(YEnum.V3)));
// greater or equal
assertContains(item3, item4, item5, item1.TYPE.search(item1.string.greaterOrEqual("string3")));
assertContains(item3, item4, item5, item1.TYPE.search(item1.intx.greaterOrEqual(3)));
assertContains(item3, item4, item5, item1.TYPE.search(item1.longx.greaterOrEqual(13l)));
assertContains(item3, item4, item5, item1.TYPE.search(item1.doublex.greaterOrEqual(2.3)));
assertContains(item3, item4, item5, item1.TYPE.search(item1.date.greaterOrEqual(date)));
assertContains(item3, item4, item5, item1.TYPE.search(item1.enumx.greaterOrEqual(YEnum.V3)));
assertContains(item1, item3, item1.TYPE.search(item1.string.in(listg("string1", "string3", "stringNone"))));
assertContains(item1, item3, item1.TYPE.search(item1.intx.in(listg(1, 3, 25))));
assertContains(item1, item3, item1.TYPE.search(item1.longx.in(listg(11l, 13l, 255l))));
assertContains(item1, item3, item1.TYPE.search(item1.doublex.in(listg(2.1, 2.3, 25.2))));
assertContains(item1, item3, item1.TYPE.search(item1.date.in(listg(offset(date, -2), date, offset(date, +25)))));
assertContains(item1, item3, item1.TYPE.search(item1.enumx.in(listg(YEnum.V1, YEnum.V3, YEnum.VX))));
// min
assertEquals("string1", new Query<String>(item1.string.min()).searchSingleton());
assertEquals(new Integer(1), new Query<Integer>(item1.intx.min()).searchSingleton());
assertEquals(new Long(11l), new Query<Long>(item1.longx.min()).searchSingleton());
assertEquals(new Double(2.1), new Query<Double>(item1.doublex.min()).searchSingleton());
assertEquals(offset(date, -2), new Query<Date>(item1.date.min()).searchSingleton());
assertEquals(YEnum.V1, new Query<YEnum>(item1.enumx.min()).searchSingleton());
// max
assertEquals("string5", new Query<String>(item1.string.max()).searchSingleton());
assertEquals(new Integer(5), new Query<Integer>(item1.intx.max()).searchSingleton());
assertEquals(new Long(15l), new Query<Long>(item1.longx.max()).searchSingleton());
assertEquals(new Double(2.5), new Query<Double>(item1.doublex.max()).searchSingleton());
assertEquals(offset(date, +2), new Query<Date>(item1.date.max()).searchSingleton());
assertEquals(YEnum.V5, new Query<YEnum>(item1.enumx.max()).searchSingleton());
// test extremum aggregate
assertEquals(true, item1.string.min().isMinimum());
assertEquals(false, item1.string.min().isMaximum());
assertEquals(false, item1.string.max().isMinimum());
assertEquals(true, item1.string.max().isMaximum());
// sum
{
final Query<Integer> q = new Query<Integer>(item1.intx.sum());
assertEquals(new Integer(1+2+3+4+5), q.searchSingleton());
q.setCondition(item1.intx.less(4));
assertEquals(new Integer(1+2+3), q.searchSingleton());
}
{
final Query<Long> q = new Query<Long>(item1.longx.sum());
assertEquals(new Long(11+12+13+14+15), q.searchSingleton());
q.setCondition(item1.longx.less(14l));
assertEquals(new Long(11+12+13), q.searchSingleton());
}
{
final Query<Double> q = new Query<Double>(item1.doublex.sum());
assertEquals(new Double(2.1+2.2+2.3+2.4+2.5).doubleValue(), q.searchSingleton().doubleValue(), 0.000000000000005);
q.setCondition(item1.doublex.less(2.4));
assertEquals(new Double(2.1+2.2+2.3).doubleValue(), q.searchSingleton().doubleValue(), 0.000000000000005);
}
model.checkUnsupportedConstraints();
}
}
|
/**
* Simplistic abstract classes which help implement encoder and decoder that
* transform an object into another object and vice versa.
*
* @apiviz.exclude
*/
package org.jboss.netty.handler.codec.oneone;
|
package com.mattcorallo.relaynode;
import com.google.bitcoin.core.*;
import com.google.bitcoin.networkabstraction.NioClientManager;
import com.google.bitcoin.networkabstraction.NioServer;
import com.google.bitcoin.networkabstraction.StreamParser;
import com.google.bitcoin.networkabstraction.StreamParserFactory;
import com.google.bitcoin.params.MainNetParams;
import com.google.bitcoin.store.BlockStore;
import com.google.bitcoin.store.BlockStoreException;
import com.google.bitcoin.store.MemoryBlockStore;
import com.google.bitcoin.utils.Threading;
import com.google.common.base.Preconditions;
import javax.annotation.Nullable;
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.util.*;
/**
* Keeps a peer and a set of invs which it has told us about (ie that it has data for)
*/
class PeerAndInvs {
Peer p;
Set<InventoryItem> invs = new LinkedHashSet<InventoryItem>() {
@Override
public boolean add(InventoryItem e) {
boolean res = super.add(e);
if (size() > 5000)
super.remove(super.iterator().next());
return res;
}
};
public PeerAndInvs(Peer p) {
this.p = p;
p.addEventListener(new AbstractPeerEventListener() {
@Override
public Message onPreMessageReceived(Peer p, Message m) {
if (m instanceof InventoryMessage) {
for (InventoryItem item : ((InventoryMessage) m).getItems())
invs.add(item);
} else if (m instanceof Transaction)
invs.add(new InventoryItem(InventoryItem.Type.Transaction, m.getHash()));
else if (m instanceof Block)
invs.add(new InventoryItem(InventoryItem.Type.Block, m.getHash()));
return m;
}
}, Threading.SAME_THREAD);
}
public void maybeRelay(Message m) {
Preconditions.checkArgument(m instanceof Block || m instanceof Transaction);
InventoryItem item;
if (m instanceof Block)
item = new InventoryItem(InventoryItem.Type.Block, m.getHash());
else
item = new InventoryItem(InventoryItem.Type.Transaction, m.getHash());
if (!invs.contains(item)) {
try {
p.sendMessage(m);
invs.add(item);
} catch (IOException e) { /* Oops, lost them */ }
}
}
}
/**
* Keeps track of a set of PeerAndInvs
*/
class Peers {
public Set<PeerAndInvs> peers = Collections.synchronizedSet(new HashSet<PeerAndInvs>());
public boolean add(Peer p) {
final PeerAndInvs peerAndInvs = new PeerAndInvs(p);
peerAndInvs.p.addEventListener(new AbstractPeerEventListener() {
@Override
public void onPeerDisconnected(Peer peer, int peerCount) {
peers.remove(peerAndInvs);
}
});
return peers.add(peerAndInvs);
}
public int size() { return peers.size(); }
public void relayObject(Message m) {
for (PeerAndInvs p : peers)
p.maybeRelay(m);
}
}
/**
* Keeps track of the set of known blocks and transactions for relay
*/
abstract class Pool<Type extends Message> {
abstract int relayedCacheSize();
Map<Sha256Hash, Type> objects = new HashMap<Sha256Hash, Type>();
Set<Sha256Hash> objectsRelayed = new LinkedHashSet<Sha256Hash>() {
@Override
public boolean add(Sha256Hash e) {
boolean res = super.add(e);
if (size() > relayedCacheSize())
super.remove(super.iterator().next()); //TODO: right order, or inverse?
return res;
}
};
Peers trustedOutboundPeers;
public Pool(Peers trustedOutboundPeers) { this.trustedOutboundPeers = trustedOutboundPeers; }
public synchronized boolean shouldRequestInv(Sha256Hash hash) {
return !objectsRelayed.contains(hash) && !objects.containsKey(hash);
}
public synchronized void provideObject(Type m) {
if (!objectsRelayed.contains(m.getHash()))
objects.put(m.getHash(), m);
trustedOutboundPeers.relayObject(m);
}
public synchronized void invGood(Peers clients, Sha256Hash hash) {
if (!objectsRelayed.contains(hash)) {
Type o = objects.get(hash);
Preconditions.checkState(o != null);
clients.relayObject(o);
objectsRelayed.add(hash);
}
objects.remove(hash);
}
}
class BlockPool extends Pool<Block> {
public BlockPool(Peers trustedOutboundPeers) {
super(trustedOutboundPeers);
}
@Override
int relayedCacheSize() {
return 100;
}
}
class TransactionPool extends Pool<Transaction> {
public TransactionPool(Peers trustedOutboundPeers) {
super(trustedOutboundPeers);
}
@Override
int relayedCacheSize() {
return 10000;
}
}
/** Keeps track of trusted peer connections (two for each trusted peer) */
class TrustedPeerConnections {
/** We only receive messages here (listen for invs of validated data) */
public Peer inbound;
/** We only send messages here (send unvalidated data) */
public Peer outbound;
}/**
* A RelayNode which is designed to relay blocks/txn from a set of untrusted peers, through a trusted bitcoind, to the
* rest of the untrusted peers. It does no verification and trusts everything that comes from the trusted bitcoind is
* good to relay.
*/
public class RelayNode {
public static void main(String[] args) throws BlockStoreException {
new RelayNode().run(8334, 8335);
}
NetworkParameters params = MainNetParams.get();
VersionMessage versionMessage = new VersionMessage(params, 0);
Peers trustedOutboundPeers = new Peers();
TransactionPool txPool = new TransactionPool(trustedOutboundPeers);
BlockPool blockPool = new BlockPool(trustedOutboundPeers);
BlockStore blockStore = new MemoryBlockStore(params);
BlockChain blockChain;
PeerGroup trustedOutboundPeerGroup;
volatile boolean chainDownloadDone = false;
final Peers txnClients = new Peers();
final Peers blocksClients = new Peers();
PeerEventListener clientPeerListener = new AbstractPeerEventListener() {
@Override
public Message onPreMessageReceived(Peer p, Message m) {
if (m instanceof InventoryMessage) {
GetDataMessage getDataMessage = new GetDataMessage(params);
for (InventoryItem item : ((InventoryMessage)m).getItems()) {
if (item.type == InventoryItem.Type.Block) {
if (blockPool.shouldRequestInv(item.hash))
getDataMessage.addBlock(item.hash);
} else if (item.type == InventoryItem.Type.Transaction) {
if (txPool.shouldRequestInv(item.hash))
getDataMessage.addTransaction(item.hash);
}
}
if (!getDataMessage.getItems().isEmpty())
try {
p.sendMessage(getDataMessage);
} catch (IOException e) { /* Oops, lost them */ }
} else if (m instanceof Block) {
blockPool.provideObject((Block) m); // This will relay to trusted peers, just in case we reject something we shouldn't
try {
if (blockChain.add((Block) m))
blockPool.invGood(blocksClients, m.getHash());
} catch (Exception e) { /* Invalid block, don't relay it */ }
} else if (m instanceof Transaction)
txPool.provideObject((Transaction) m);
return m;
}
};
Map<InetSocketAddress, TrustedPeerConnections> trustedPeerConnectionsMap = Collections.synchronizedMap(new HashMap<InetSocketAddress, TrustedPeerConnections>());
NioClientManager trustedPeerManager = new NioClientManager();
PeerEventListener trustedPeerInboundListener = new AbstractPeerEventListener() {
@Override
public Message onPreMessageReceived(Peer p, Message m) {
if (m instanceof InventoryMessage) {
GetDataMessage getDataMessage = new GetDataMessage(params);
for (InventoryItem item : ((InventoryMessage)m).getItems()) {
if (item.type == InventoryItem.Type.Block) {
if (blockPool.shouldRequestInv(item.hash))
getDataMessage.addBlock(item.hash);
else
blockPool.invGood(blocksClients, item.hash);
} else if (item.type == InventoryItem.Type.Transaction) {
if (txPool.shouldRequestInv(item.hash))
getDataMessage.addTransaction(item.hash);
else
txPool.invGood(txnClients, item.hash);
}
}
if (!getDataMessage.getItems().isEmpty())
try {
p.sendMessage(getDataMessage);
} catch (IOException e) { /* Oops, lost them, we'll pick them back up in onPeerDisconnected */ }
} else if (m instanceof Transaction) {
txPool.provideObject((Transaction) m);
txPool.invGood(txnClients, m.getHash());
} else if (m instanceof Block) {
blockPool.provideObject((Block) m);
blockPool.invGood(blocksClients, m.getHash());
}
return m;
}
};
// Runs on USER_THREAD (which is used exclusively for reconnection attempts)
PeerEventListener trustedPeerDisconnectListener = new AbstractPeerEventListener() {
@Override
public void onPeerDisconnected(Peer peer, int peerCount) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
ConnectToTrustedPeer(peer.getAddress().toSocketAddress());
}
};
PeerEventListener trustedRelayPeerListener = new AbstractPeerEventListener() {
@Override
public Message onPreMessageReceived(Peer p, Message m) {
Preconditions.checkState(m instanceof Block);
blockPool.provideObject((Block) m);
blockPool.invGood(blocksClients, m.getHash());
return m;
}
};
public RelayNode() throws BlockStoreException {
String version = "festive flamingo";
versionMessage.appendToSubVer("RelayNode", version, null);
trustedPeerManager.startAndWait();
blockChain = new BlockChain(params, blockStore);
trustedOutboundPeerGroup = new PeerGroup(params, blockChain);
trustedOutboundPeerGroup.setUserAgent("RelayNode", version);
trustedOutboundPeerGroup.addEventListener(trustedPeerDisconnectListener, Threading.USER_THREAD);
trustedOutboundPeerGroup.startAndWait();
}
public void run(int onlyBlocksListenPort, int bothListenPort) {
// Listen for incoming client connections
try {
NioServer onlyBlocksServer = new NioServer(new StreamParserFactory() {
@Nullable
@Override
public StreamParser getNewParser(InetAddress inetAddress, int port) {
Peer p = new Peer(params, versionMessage, null, new InetSocketAddress(inetAddress, port));
p.addEventListener(clientPeerListener, Threading.SAME_THREAD);
blocksClients.add(p);
return p;
}
}, new InetSocketAddress(onlyBlocksListenPort));
NioServer bothServer = new NioServer(new StreamParserFactory() {
@Nullable
@Override
public StreamParser getNewParser(InetAddress inetAddress, int port) {
Peer p = new Peer(params, versionMessage, null, new InetSocketAddress(inetAddress, port));
p.addEventListener(clientPeerListener, Threading.SAME_THREAD);
blocksClients.add(p);
txnClients.add(p);
return p;
}
}, new InetSocketAddress(bothListenPort));
onlyBlocksServer.startAndWait();
bothServer.startAndWait();
} catch (IOException e) {
System.err.println("Failed to bind to port");
System.exit(1);
}
// Print stats
new Thread(new Runnable() {
@Override
public void run() {
printStats();
}
}).start();
WatchForUserInput();
}
public void WatchForUserInput() {
// Get user input
Scanner scanner = new Scanner(System.in);
String line;
while (true) {
line = scanner.nextLine();
if (line.equals("q")) {
synchronized (printLock) {
System.out.println("Quitting...");
// Wait...cleanup? naaaaa
System.exit(0);
}
} else if (line.startsWith("t ")) {
String[] hostPort = line.substring(2).split(":");
if (hostPort.length != 2) {
LogLine("Invalid argument");
continue;
}
try {
int port = Integer.parseInt(hostPort[1]);
InetSocketAddress addr = new InetSocketAddress(hostPort[0], port);
if (addr.isUnresolved())
LogLine("Unable to resolve host");
else {
ConnectToTrustedPeer(addr);
LogLine("Added trusted peer " + addr);
}
} catch (NumberFormatException e) {
LogLine("Invalid argument");
}
} else if (line.startsWith("r ")) {
String[] hostPort = line.substring(2).split(":");
if (hostPort.length != 2) {
LogLine("Invalid argument");
continue;
}
try {
int port = Integer.parseInt(hostPort[1]);
InetSocketAddress addr = new InetSocketAddress(hostPort[0], port);
if (addr.isUnresolved())
LogLine("Unable to resolve host");
else {
ConnectToTrustedRelayPeer(addr);
LogLine("Added trusted relay peer " + addr);
}
} catch (NumberFormatException e) {
LogLine("Invalid argument");
}
} else {
LogLine("Invalid command");
}
}
}
public void ConnectToTrustedRelayPeer(final InetSocketAddress address) {
final Peer p = new Peer(params, versionMessage, null, address);
p.addEventListener(trustedRelayPeerListener, Threading.SAME_THREAD);
p.addEventListener(new AbstractPeerEventListener() {
@Override
public void onPeerDisconnected(Peer peer, int peerCount) {
Preconditions.checkState(peer == p);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
ConnectToTrustedRelayPeer(address);
}
}, Threading.USER_THREAD);
blocksClients.add(p);
trustedPeerManager.openConnection(address, p);
}
public void ConnectToTrustedPeer(InetSocketAddress address) {
TrustedPeerConnections connections = trustedPeerConnectionsMap.get(address);
if (connections != null) {
connections.inbound.close();
connections.outbound.close();
}
connections = new TrustedPeerConnections();
connections.inbound = new Peer(params, versionMessage, null, address);
connections.inbound.addEventListener(trustedPeerInboundListener, Threading.SAME_THREAD);
connections.inbound.addEventListener(trustedPeerDisconnectListener, Threading.USER_THREAD);
trustedPeerManager.openConnection(address, connections.inbound);
connections.outbound = trustedOutboundPeerGroup.connectTo(address);
trustedOutboundPeers.add(connections.outbound);
trustedOutboundPeerGroup.startBlockChainDownload(new DownloadListener() {
@Override
protected void doneDownload() {
chainDownloadDone = true;
}
});
trustedPeerConnectionsMap.put(address, connections);
}
final Queue<String> logLines = new LinkedList<String>();
public void LogLine(String line) {
synchronized (logLines) {
logLines.add(line);
}
}
// Wouldn't want to print from multiple threads, would we?
final Object printLock = new Object();
public void printStats() {
// Things may break if your column count is too small
boolean firstIteration = true;
while (true) {
int linesPrinted = 1;
synchronized (printLock) {
synchronized (logLines) {
for (String ignored : logLines)
System.out.print("\033[1A\033[K"); // Up and make sure we're at the beginning, clear line
for (String line : logLines)
System.out.println(line);
logLines.clear();
}
if (trustedPeerConnectionsMap.isEmpty()) {
System.out.println("\nRelaying will not start until you add some trusted nodes"); linesPrinted += 2;
} else {
System.out.println("\nTrusted nodes: "); linesPrinted += 2;
for (Map.Entry<InetSocketAddress, TrustedPeerConnections> entry : trustedPeerConnectionsMap.entrySet()) {
boolean connected = true;
try {
entry.getValue().inbound.sendMessage(new Ping(0xDEADBEEF));
} catch (Exception e) {
connected = false;
}
System.out.println(" " + entry.getKey() + (connected ? " connected" : " not connected")); linesPrinted++;
}
}
System.out.println(); linesPrinted++;
System.out.println("Connected block+transaction clients: " + txnClients.size()); linesPrinted++;
System.out.println("Connected block-only clients: " + (blocksClients.size() - txnClients.size())); linesPrinted++;
System.out.println(chainDownloadDone ? "Chain download done (relaying blocks)" : "Chain download not done (not relaying blocks)"); linesPrinted++;
System.out.println(); linesPrinted++;
System.out.println("Commands:"); linesPrinted++;
System.out.println("q \t\tquit"); linesPrinted++;
System.out.println("t IP:port\t\tadd node IP:port as a trusted peer"); linesPrinted++;
System.out.println("r IP:port\t\tadd trusted relay node (via its block-only port) to relay blocks to/from"); linesPrinted++;
if (firstIteration)
System.out.println();
else
System.out.print("\033[u");
firstIteration = false;
}
try {
Thread.sleep(100);
} catch (InterruptedException e) {
System.err.println("Stats printing thread interrupted");
System.exit(1);
}
synchronized (printLock) {
System.out.print("\033[s\033[1000D"); // Save cursor position + move to first char
for (int i = 0; i < linesPrinted; i++)
System.out.print("\033[1A\033[K"); // Up+clear linesPrinted lines
System.out.print("");
}
}
}
}
|
package org.jenkinsci.plugins.slave_setup;
import antlr.ANTLRException;
import hudson.Util;
import hudson.model.labels.LabelAtom;
import hudson.model.labels.LabelExpression;
import org.apache.commons.lang.StringUtils;
import org.kohsuke.stapler.DataBoundConstructor;
import java.io.File;
/**
* Represents a setup config for one set of labels. It may have its own prepare script, files to copy and command line.
*/
public class SetupConfigItem {
/**
* the prepare script code
*/
private String prepareScript;
/**
* the directory to get the content to copy from
*/
private File filesDir;
/**
* the command line code
*/
private String commandLine;
/**
* set to true to execute setup script on save of the main jenkins configuration page
*/
private boolean deployNow;
/**
* jenkins label to be assigned to this setup config
*/
private String assignedLabelString;
/**
* Constructor uesd to create the setup config instance
* @param prepareScript
* @param filesDir
* @param commandLine
* @param deployNow
* @param assignedLabelString
*/
@DataBoundConstructor
public SetupConfigItem(String prepareScript, File filesDir, String commandLine, boolean deployNow, String assignedLabelString) {
this.prepareScript = prepareScript;
this.filesDir = filesDir;
this.commandLine = commandLine;
this.deployNow = deployNow;
this.assignedLabelString = assignedLabelString;
}
/**
* Default constructor
*/
public SetupConfigItem() {
}
/**
* Returns the prepare script code.
* @return the prepare script code
*/
public String getPrepareScript() {
return prepareScript;
}
/**
* Sets the prepare script code
* @param prepareScript
*/
public void setPrepareScript(String prepareScript) {
this.prepareScript = prepareScript;
}
/**
* Returns the directory containing the setup relevant files and sub directories
* @return
*/
public File getFilesDir() {
return filesDir;
}
/**
* Returns the command line code.
* @return the command line code
*/
public String getCommandLine() {
return commandLine;
}
/**
* Returns true if the setup config should be deployed on save of the jenkins config page.
* @return true if the setup config should be deployed on save of the jenkins config page
*/
public boolean getDeployNow() {
return this.deployNow;
}
/**
* Sets the files dir.
* @param filesDir firectory to copy the setup files and sub directories from.
*/
public void setFilesDir(File filesDir) {
if (filesDir.getPath().length() == 0) {
filesDir = null;
}
this.filesDir = filesDir;
}
/**
* sets the command line code.
* @param commandLine the command line code
*/
public void setCommandLine(String commandLine) {
this.commandLine = Util.fixEmpty(commandLine);
}
/**
* sets the deploy flag.
* @param deployNow the deploy flag
*/
public void setDeployNow(boolean deployNow) {
this.deployNow = deployNow;
}
/**
* Gets the textual representation of the assigned label as it was entered by the user.
*/
public String getAssignedLabelString() {
if (StringUtils.isEmpty(this.assignedLabelString)) {
return "";
}
try {
LabelExpression.parseExpression(this.assignedLabelString);
return this.assignedLabelString;
} catch (ANTLRException e) {
// must be old label or host name that includes whitespace or other unsafe chars
return LabelAtom.escape(this.assignedLabelString);
}
}
/**
* sets the assigned slaves' labels
* @param assignedLabelString
*/
public void setAssignedLabelString(String assignedLabelString) {
this.assignedLabelString = assignedLabelString;
}
}
|
package org.helioviewer.jhv.gui.controller;
import java.awt.Component;
import java.awt.Cursor;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.event.MouseWheelEvent;
import java.awt.event.MouseWheelListener;
import java.util.HashSet;
import org.helioviewer.jhv.camera.GL3DCamera;
import org.helioviewer.jhv.display.Displayer;
import org.helioviewer.jhv.gui.UIGlobals;
import org.helioviewer.jhv.gui.interfaces.InputControllerPlugin;
import org.helioviewer.jhv.opengl.GLInfo;
public class InputController implements MouseListener, MouseMotionListener, MouseWheelListener, KeyListener {
private static Component component;
private boolean buttonDown = false;
private long lastTime = System.currentTimeMillis();
public InputController(Component _component) {
component = _component;
component.addMouseListener(this);
component.addMouseMotionListener(this);
component.addMouseWheelListener(this);
component.addKeyListener(this);
}
private MouseEvent mouseSynthesizer(MouseEvent e) {
return new MouseEvent((Component) e.getSource(), e.getID(), e.getWhen(), e.getModifiers(),
e.getX() * GLInfo.pixelScale[0], e.getY() * GLInfo.pixelScale[1],
e.getClickCount(), e.isPopupTrigger(), e.getButton());
}
private MouseWheelEvent mouseWheelSynthesizer(MouseWheelEvent e) {
return new MouseWheelEvent((Component) e.getSource(), e.getID(), e.getWhen(), e.getModifiers(),
e.getX() * GLInfo.pixelScale[0], e.getY() * GLInfo.pixelScale[1],
e.getClickCount(), e.isPopupTrigger(), e.getScrollType(), e.getScrollAmount(), e.getWheelRotation());
}
@Override
public void mouseClicked(MouseEvent e) {
e = mouseSynthesizer(e);
for (MouseListener listener : mouseListeners)
listener.mouseClicked(e);
Displayer.getViewport().getCamera().getCurrentInteraction().mouseClicked(e);
}
@Override
public void mouseEntered(MouseEvent e) {
e = mouseSynthesizer(e);
for (MouseListener listener : mouseListeners)
listener.mouseEntered(e);
GL3DCamera camera = Displayer.getViewport().getCamera();
if (camera.getCurrentInteraction() != camera.getAnnotateInteraction()) {
component.setCursor(buttonDown ? UIGlobals.closedHandCursor : UIGlobals.openHandCursor);
}
}
@Override
public void mouseExited(MouseEvent e) {
e = mouseSynthesizer(e);
for (MouseListener listener : mouseListeners)
listener.mouseExited(e);
component.setCursor(Cursor.getDefaultCursor());
}
@Override
public void mousePressed(MouseEvent e) {
e = mouseSynthesizer(e);
for (MouseListener listener : mouseListeners)
listener.mousePressed(e);
GL3DCamera camera = Displayer.getViewport().getCamera();
if (e.getButton() == MouseEvent.BUTTON1) {
if (camera.getCurrentInteraction() != camera.getAnnotateInteraction()) {
component.setCursor(UIGlobals.closedHandCursor);
}
buttonDown = true;
}
camera.getCurrentInteraction().mousePressed(e);
}
@Override
public void mouseReleased(MouseEvent e) {
e = mouseSynthesizer(e);
for (MouseListener listener : mouseListeners)
listener.mouseReleased(e);
GL3DCamera camera = Displayer.getViewport().getCamera();
if (e.getButton() == MouseEvent.BUTTON1) {
if (camera.getCurrentInteraction() != camera.getAnnotateInteraction()) {
component.setCursor(UIGlobals.openHandCursor);
}
buttonDown = false;
}
camera.getCurrentInteraction().mouseReleased(e);
}
@Override
public void mouseDragged(MouseEvent e) {
e = mouseSynthesizer(e);
for (MouseMotionListener listener : mouseMotionListeners)
listener.mouseDragged(e);
long currentTime = System.currentTimeMillis();
if (buttonDown && currentTime - lastTime > 30) {
lastTime = currentTime;
Displayer.getViewport().getCamera().getCurrentInteraction().mouseDragged(e);
}
}
@Override
public void mouseMoved(MouseEvent e) {
e = mouseSynthesizer(e);
for (MouseMotionListener listener : mouseMotionListeners)
listener.mouseMoved(e);
Displayer.getViewport().getCamera().getCurrentInteraction().mouseMoved(e);
}
@Override
public void mouseWheelMoved(MouseWheelEvent e) {
e = mouseWheelSynthesizer(e);
for (MouseWheelListener listener : mouseWheelListeners)
listener.mouseWheelMoved(e);
Displayer.getViewport().getCamera().getCurrentInteraction().mouseWheelMoved(e);
}
@Override
public void keyTyped(KeyEvent e) {
for (KeyListener listener : keyListeners)
listener.keyTyped(e);
Displayer.getViewport().getCamera().getCurrentInteraction().keyTyped(e);
}
@Override
public void keyPressed(KeyEvent e) {
for (KeyListener listener : keyListeners)
listener.keyPressed(e);
Displayer.getViewport().getCamera().getCurrentInteraction().keyPressed(e);
}
@Override
public void keyReleased(KeyEvent e) {
for (KeyListener listener : keyListeners)
listener.keyReleased(e);
Displayer.getViewport().getCamera().getCurrentInteraction().keyReleased(e);
}
private final HashSet<MouseListener> mouseListeners = new HashSet<MouseListener>();
private final HashSet<MouseMotionListener> mouseMotionListeners = new HashSet<MouseMotionListener>();
private final HashSet<MouseWheelListener> mouseWheelListeners = new HashSet<MouseWheelListener>();
private final HashSet<KeyListener> keyListeners = new HashSet<KeyListener>();
public void addPlugin(InputControllerPlugin plugin) {
if (plugin instanceof MouseListener)
mouseListeners.add((MouseListener) plugin);
if (plugin instanceof MouseMotionListener)
mouseMotionListeners.add((MouseMotionListener) plugin);
if (plugin instanceof MouseWheelListener)
mouseWheelListeners.add((MouseWheelListener) plugin);
if (plugin instanceof KeyListener)
keyListeners.add((KeyListener) plugin);
plugin.setComponent(component);
}
public void removePlugin(InputControllerPlugin plugin) {
if (plugin instanceof MouseListener)
mouseListeners.remove((MouseListener) plugin);
if (plugin instanceof MouseMotionListener)
mouseMotionListeners.remove((MouseMotionListener) plugin);
if (plugin instanceof MouseWheelListener)
mouseWheelListeners.remove((MouseWheelListener) plugin);
if (plugin instanceof KeyListener)
keyListeners.remove((KeyListener) plugin);
plugin.setComponent(null);
}
}
|
package com.jme3.math;
import org.junit.Test;
import static org.junit.Assert.*;
import org.junit.Ignore;
import java.lang.Math;
import org.junit.Rule;
import org.junit.rules.ExpectedException;
/**
* Verifies that algorithms in {@link FastMath} are working correctly.
*
* @author Kirill Vainer
*/
public class FastMathTest {
@Rule public ExpectedException thrown = ExpectedException.none();
private int nearestPowerOfTwoSlow(int number) {
return (int) Math.pow(2, Math.ceil(Math.log(number) / Math.log(2)));
}
@Test
public void testNearestPowerOfTwo() {
for (int i = -100; i < 1; i++) {
assert FastMath.nearestPowerOfTwo(i) == 1;
}
for (int i = 1; i < 10000; i++) {
int nextPowerOf2 = FastMath.nearestPowerOfTwo(i);
assert i <= nextPowerOf2;
assert FastMath.isPowerOfTwo(nextPowerOf2);
assert nextPowerOf2 == nearestPowerOfTwoSlow(i);
}
}
private static int fastCounterClockwise(Vector2f p0, Vector2f p1, Vector2f p2) {
float result = (p1.x - p0.x) * (p2.y - p1.y) - (p1.y - p0.y) * (p2.x - p1.x);
return (int) Math.signum(result);
}
private static Vector2f randomVector() {
return new Vector2f(FastMath.nextRandomFloat(),
FastMath.nextRandomFloat());
}
@Ignore
@Test
public void testCounterClockwise() {
for (int i = 0; i < 100; i++) {
Vector2f p0 = randomVector();
Vector2f p1 = randomVector();
Vector2f p2 = randomVector();
int fastResult = fastCounterClockwise(p0, p1, p2);
int slowResult = FastMath.counterClockwise(p0, p1, p2);
assert fastResult == slowResult;
}
// duplicate test
Vector2f p0 = new Vector2f(0,0);
Vector2f p1 = new Vector2f(0,0);
Vector2f p2 = new Vector2f(0,1);
int fastResult = fastCounterClockwise(p0, p1, p2);
int slowResult = FastMath.counterClockwise(p0, p1, p2);
assertEquals(slowResult, fastResult);
}
@Test
public void testAcos() {
assertEquals((float)Math.PI, FastMath.acos(-2.0f), 0.01f);
assertEquals(0.0f, FastMath.acos(2.0f), 0.0f);
assertEquals(1.57f, FastMath.acos(0.0f), 0.01f);
assertEquals(1.047f, FastMath.acos(0.5f), 0.01f);
assertEquals(0.0f, FastMath.acos(Float.POSITIVE_INFINITY), 0.0f);
assertEquals(0x1.921fb6p+1f, FastMath.acos(-0x1p+113f), 0.01f);
}
@Test
public void testApproximateEquals() {
assertTrue(FastMath.approximateEquals(1000.0f, 1000.0f));
assertTrue(FastMath.approximateEquals(100000.0f, 100001.0f));
assertTrue(FastMath.approximateEquals(0.0f, -0.0f));
assertFalse(FastMath.approximateEquals(10000.0f, 10001.0f));
assertFalse(FastMath.approximateEquals(149.0f, 0.0f));
}
@Test
public void testAsin() {
final float HALF_PI = 0.5f * (float)Math.PI;
assertEquals(-HALF_PI, FastMath.asin(-2.0f), 0.01f);
assertEquals(HALF_PI, FastMath.asin(2.0f), 0.01f);
assertEquals(HALF_PI, FastMath.asin(Float.POSITIVE_INFINITY), 0.0f);
assertEquals(0.0f, FastMath.asin(0.0f), 0.0f);
assertEquals(0.523f, FastMath.asin(0.5f), 0.01f);
assertEquals(-1.570f, FastMath.asin(-0x1p+113f), 0.01f);
}
@Test
public void testAtan() {
assertEquals(0.0f, FastMath.atan2(0.0f, 0.0f), 0.0f);
assertEquals(0.076f, FastMath.atan2(1.0f, 13.0f), 0.01f);
}
@Test
public void testCartesianToSpherical() {
final Vector3f cartCoords = new Vector3f(1.1f, 5.8f, 8.1f);
final Vector3f store = new Vector3f(0.0f, 0.0f, 0.0f);
final Vector3f retval = FastMath.cartesianToSpherical(cartCoords, store);
assertEquals(store, retval);
assertNotNull(store);
assertEquals(10.022974f, store.getX(), 0.0f);
assertEquals(1.4358196f, store.getY(), 0.01f);
assertEquals(0.61709767f, store.getZ(), 0.0f);
assertNotNull(retval);
assertEquals(10.022974f, retval.getX(), 0.0f);
assertEquals(1.4358196f, retval.getY(), 0.01f);
assertEquals(0.61709767f, retval.getZ(), 0.0f);
}
@Test
public void testCartesianZToSpherical() {
final Vector3f cartCoords = new Vector3f(1.1f, 5.8f, 8.1f);
final Vector3f store = new Vector3f(0.0f, 0.0f, 0.0f);
final Vector3f retval = FastMath.cartesianZToSpherical(cartCoords, store);
assertEquals(store, retval);
assertNotNull(store);
assertEquals(10.022974f, store.getX(), 0.01f);
assertEquals(0.61709767f, store.getY(), 0.01f);
assertEquals(1.4358196f, store.getZ(), 0.01f);
assertNotNull(retval);
assertEquals(10.022974f, retval.getX(), 0.01f);
assertEquals(0.61709767f, retval.getY(), 0.01f);
assertEquals(1.4358196f, retval.getZ(), 0.01f);
}
@Test
public void testComputeNormal() {
final Vector3f v1 = new Vector3f(1.1f, 9.5f, -7.2f);
final Vector3f v2 = new Vector3f(Float.NaN, -0.2f, 6.1f);
final Vector3f v3 = new Vector3f(-0.5f, -0.14f, -1.8f);
final Vector3f retval = FastMath.computeNormal(v1, v2, v3);
assertNotNull(retval);
assertEquals(Float.NaN, retval.getX(), 0.0f);
assertEquals(Float.NaN, retval.getY(), 0.0f);
assertEquals(Float.NaN, retval.getZ(), 0.0f);
}
@Test
public void testComputeNormal2() {
final Vector3f v1 = new Vector3f(-0.4f, 0.1f, 2.9f);
final Vector3f v2 = new Vector3f(-0.4f, 0.1f, 2.9f);
final Vector3f v3 = new Vector3f(-1.4f, 10.1f, 2.9f);
final Vector3f retval = FastMath.computeNormal(v1, v2, v3);
assertNotNull(retval);
assertEquals(0.0f, retval.getX(), 0.0f);
assertEquals(0.0f, retval.getY(), 0.0f);
assertEquals(0.0f, retval.getZ(), 0.0f);
}
@Test
public void testConvertFloatToHalfUnsupportedOperationException() {
thrown.expect(UnsupportedOperationException.class);
FastMath.convertFloatToHalf(Float.NaN);
}
@Test
public void testConvertFloatToHalf() {
assertEquals((short)-1024, FastMath.convertFloatToHalf(Float.NEGATIVE_INFINITY));
assertEquals((short)31744, FastMath.convertFloatToHalf(Float.POSITIVE_INFINITY));
assertEquals((short)-1025, FastMath.convertFloatToHalf(-131328.0f));
assertEquals((short)-32767, FastMath.convertFloatToHalf(-0x1p-135f));
assertEquals((short)1, FastMath.convertFloatToHalf(0x1.008p-71f));
assertEquals((short)31743, FastMath.convertFloatToHalf(0x1.008p+121f));
assertEquals((short)0, FastMath.convertFloatToHalf(0.0f));
}
@Test
public void testConvertHalfToFloat() {
assertEquals(Float.POSITIVE_INFINITY, FastMath.convertHalfToFloat((short)31744), 0.0f);
assertEquals(0.0f, FastMath.convertHalfToFloat((short)0), 0.0f);
assertEquals(65504.0f, FastMath.convertHalfToFloat((short)31743), 0.0f);
assertEquals(-65536.0f, FastMath.convertHalfToFloat((short)-1024), 0.0f);
assertEquals(-65504.0f, FastMath.convertHalfToFloat((short)-1025), 0.0f);
}
@Test
public void testCopysign() {
assertEquals(-3.85186e-34, FastMath.copysign(-3.85186e-34f, -1.0f), 0.01f);
assertEquals(0.0f, FastMath.copysign(0.0f, Float.NaN), 0.0f);
assertEquals(Float.NaN, FastMath.copysign(Float.NaN, 1.0f), 0.0f);
assertEquals(0.0f, FastMath.copysign(-0.0f, -1.0f), 0.0f);
assertEquals(0.0f, FastMath.copysign(-0.0f, 0.0f), 0.0f);
assertEquals(-1.0f, FastMath.copysign(1.0f, -3.0f), 0.0f);
}
@Test
public void testCounterClockwise2() {
final Vector2f p0 = new Vector2f(0.125f, -2.14644e+09f);
final Vector2f p1 = new Vector2f(-6.375f, -3.96141e+28f);
final Vector2f p2 = new Vector2f(0.078125f, -2.14644e+09f);
assertEquals(-1, FastMath.counterClockwise(p0, p1, p2));
}
@Test
public void testCounterClockwise3() {
final Vector2f p0 = new Vector2f(2.34982e-38f, 1.25063e+27f);
final Vector2f p1 = new Vector2f(2.34982e-38f, 1.25061e+27f);
final Vector2f p2 = new Vector2f(3.51844e+13f, Float.NaN);
assertEquals(0, FastMath.counterClockwise(p0, p1, p2));
}
@Test
public void testCounterClockwise4() {
final Vector2f p0 = new Vector2f(262143.0f, 4.55504e-38f);
final Vector2f p1 = new Vector2f(262144.0f, 2.50444f);
final Vector2f p2 = new Vector2f(204349.0f, 4.77259e-38f);
assertEquals(1, FastMath.counterClockwise(p0, p1, p2));
}
@Test
public void testCounterClockwise5() {
final Vector2f p0 = new Vector2f(-1.87985e-37f, -1.16631e-38f);
final Vector2f p1 = new Vector2f(-1.87978e-37f, -1.18154e-38f);
final Vector2f p2 = new Vector2f(-6.56451e-21f, -1.40453e-38f);
assertEquals(1, FastMath.counterClockwise(p0, p1, p2));
}
@Test
public void testCounterClockwise6() {
final Vector2f p0 = new Vector2f(1.07374e+09f, 1.07374e+09f);
final Vector2f p1 = new Vector2f(1.07374e+09f, 1.07374e+09f);
final Vector2f p2 = new Vector2f(1.07374e+09f, 1.07374e+09f);
assertEquals(0, FastMath.counterClockwise(p0, p1, p2));
}
@Test
public void testDeterminant() {
assertEquals(20.0f, FastMath.determinant(
5.0, -7.0, 2.0, 2.0,
0.0, 3.0, 0.0, -4.0,
-5.0, -8.0, 0.0, 3.0,
0.0, 5.0, 0.0, -6.0), 0.0f);
assertEquals(0.0f, FastMath.determinant(
1.0, 2.0, 3.0, 4.0,
5.0, 6.0, 7.0, 8.0,
9.0, 10.0, 11.0, 12.0,
13.0, 14.0, 15.0, 16.0), 0.0f);
}
@Test
public void testExtrapolateLinear() {
final float scale = 0.0f;
final Vector3f startValue = new Vector3f(0.0f, 0.0f, 0.0f);
final Vector3f endValue = new Vector3f(0.0f, 0.0f, 0.0f);
final Vector3f store = new Vector3f(0.0f, 0.0f, 0.0f);
final Vector3f retval = FastMath.extrapolateLinear(scale, startValue, endValue, store);
assertNotNull(retval);
assertEquals(0.0f, retval.getX(), 0.0f);
assertEquals(0.0f, retval.getY(), 0.0f);
assertEquals(0.0f, retval.getZ(), 0.0f);
}
@Test
public void testExtrapolateLinear2() {
final float scale = 0.6f;
final Vector3f startValue = new Vector3f(1.6f, 3.1f, 2.2f);
final Vector3f endValue = new Vector3f(0.5f, 1.2f, 4.9f);
final Vector3f store = new Vector3f(0.0f, 0.0f, 0.0f);
final Vector3f retval = FastMath.extrapolateLinear(scale, startValue, endValue, store);
assertNotNull(retval);
assertEquals(0.94f, retval.getX(), 0.01f);
assertEquals(1.95f, retval.getY(), 0.01f);
assertEquals(3.82f, retval.getZ(), 0.01f);
}
@Test
public void testExtrapolateLinearNoStore() {
final float scale = 0.0f;
final Vector3f startValue = new Vector3f(0.0f, 0.0f, 0.0f);
final Vector3f endValue = new Vector3f(0.0f, 0.0f, 0.0f);
final Vector3f retval = FastMath.extrapolateLinear(scale, startValue, endValue);
assertNotNull(retval);
assertEquals(0.0f, retval.getX(), 0.0f);
assertEquals(0.0f, retval.getY(), 0.0f);
assertEquals(0.0f, retval.getZ(), 0.0f);
}
@Test
public void testExtrapolateLinearNoStore2() {
final float scale = 0.6f;
final Vector3f startValue = new Vector3f(1.6f, 3.1f, 2.2f);
final Vector3f endValue = new Vector3f(0.5f, 1.2f, 4.9f);
final Vector3f retval = FastMath.extrapolateLinear(scale, startValue, endValue);
assertNotNull(retval);
assertEquals(0.94f, retval.getX(), 0.01f);
assertEquals(1.95f, retval.getY(), 0.01f);
assertEquals(3.82f, retval.getZ(), 0.01f);
}
@Test
public void testInterpolateBezier() {
final float u = 0.0f;
final Vector3f p0 = new Vector3f(0.0f, 0.0f, 0.0f);
final Vector3f p1 = new Vector3f(0.0f, 0.0f, 0.0f);
final Vector3f p2 = new Vector3f(0.0f, 0.0f, 0.0f);
final Vector3f p3 = new Vector3f(0.0f, 0.0f, 0.0f);
final Vector3f store = new Vector3f(0.0f, 0.0f, 0.0f);
final Vector3f retval = FastMath.interpolateBezier(u, p0, p1, p2, p3, store);
assertNotNull(retval);
assertEquals(0.0f, retval.getX(), 0.0f);
assertEquals(0.0f, retval.getY(), 0.0f);
assertEquals(0.0f, retval.getZ(), 0.0f);
}
@Test
public void testInterpolateBezier2() {
final float u = 0.5f;
final Vector3f p0 = new Vector3f(1.0f, 2.0f, 3.0f);
final Vector3f p1 = new Vector3f(6.0f, 7.0f, 8.0f);
final Vector3f p2 = new Vector3f(2.0f, 3.0f, 4.0f);
final Vector3f p3 = new Vector3f(0.0f, 1.0f, 8.0f);
final Vector3f store = new Vector3f(1.0f, 2.0f, 3.0f);
final Vector3f retval = FastMath.interpolateBezier(u, p0, p1, p2, p3, store);
assertNotNull(retval);
assertEquals(3.125f, retval.getX(), 0.0f);
assertEquals(4.125f, retval.getY(), 0.0f);
assertEquals(5.875f, retval.getZ(), 0.0f);
}
@Test
public void testInterpolateBezierNoStore() {
final float u = 0.5f;
final Vector3f p0 = new Vector3f(1.0f, 2.0f, 3.0f);
final Vector3f p1 = new Vector3f(6.0f, 7.0f, 8.0f);
final Vector3f p2 = new Vector3f(2.0f, 3.0f, 4.0f);
final Vector3f p3 = new Vector3f(0.0f, 1.0f, 8.0f);
final Vector3f retval = FastMath.interpolateBezier(u, p0, p1, p2, p3);
assertNotNull(retval);
assertEquals(3.125f, retval.getX(), 0.0f);
assertEquals(4.125f, retval.getY(), 0.0f);
assertEquals(5.875f, retval.getZ(), 0.0f);
}
@Test
public void testInterpolateCatmullRom() {
final float u = 0.5f;
final float T = 0.5f;
final Vector3f p0 = new Vector3f(1.0f, 2.0f, 3.0f);
final Vector3f p1 = new Vector3f(6.0f, 7.0f, 8.0f);
final Vector3f p2 = new Vector3f(2.0f, 3.0f, 4.0f);
final Vector3f p3 = new Vector3f(0.0f, 1.0f, 8.0f);
final Vector3f retval = FastMath.interpolateCatmullRom(u, T, p0, p1, p2, p3);
assertNotNull(retval);
assertEquals(4.4375f, retval.getX(), 0.0f);
assertEquals(5.4375f, retval.getY(), 0.0f);
assertEquals(6.0625f, retval.getZ(), 0.0f);
}
@Test
public void testInterpolateLinear() {
final float scale = -1.00195f;
final Vector3f startValue = new Vector3f(32.0f, 0.0f, 0.0f);
final Vector3f endValue = new Vector3f(32.0f, Float.POSITIVE_INFINITY, -0.0f);
final Vector3f retval = FastMath.interpolateLinear(scale, startValue, endValue);
assertNotNull(retval);
assertEquals(32.0f, retval.getX(), 0.0f);
assertEquals(0.0f, retval.getY(), 0.0f);
assertEquals(0.0f, retval.getZ(), 0.0f);
}
@Test
public void testInterpolateLinear2() {
final float scale = 1.0842e-19f;
final Vector3f startValue = new Vector3f(0.0f, 0.0f, 1.4013e-45f);
final Vector3f endValue = new Vector3f(0.0f, 0.0f, 0.0f);
final Vector3f store = new Vector3f(0.0f, 0.0f, 0.0f);
final Vector3f retval = FastMath.interpolateLinear(scale, startValue, endValue, store);
assertEquals(store, retval);
assertNotNull(store);
assertEquals(0.0f, store.getX(), 0.0f);
assertEquals(0.0f, store.getY(), 0.0f);
assertEquals(1.4013e-45f, store.getZ(), 0.0f);
assertNotNull(retval);
assertEquals(0.0f, retval.getX(), 0.0f);
assertEquals(0.0f, retval.getY(), 0.0f);
assertEquals(1.4013e-45f, retval.getZ(), 0.0f);
}
@Test
public void testInterpolateLinear3() {
final float scale = 1.03125f;
final Vector3f startValue = new Vector3f(0.0f, 16.0f, Float.NaN);
final Vector3f endValue = new Vector3f(0.0f, 16.0f, Float.POSITIVE_INFINITY);
final Vector3f store = new Vector3f(0.0f, 0.0f, 0.0f);
final Vector3f retval = FastMath.interpolateLinear(scale, startValue, endValue, store);
assertEquals(store, retval);
assertNotNull(store);
assertEquals(0.0f, store.getX(), 0.0f);
assertEquals(16.0f, store.getY(), 0.0f);
assertEquals(Float.POSITIVE_INFINITY, store.getZ(), 0.0f);
assertNotNull(retval);
assertEquals(0.0f, retval.getX(), 0.0f);
assertEquals(16.0f, retval.getY(), 0.0f);
assertEquals(Float.POSITIVE_INFINITY, retval.getZ(), 0.0f);
}
@Test
public void testInterpolateLinear4() {
final float scale = 1.00195f;
final Vector3f startValue = new Vector3f(256.0f, Float.POSITIVE_INFINITY, Float.POSITIVE_INFINITY);
final Vector3f endValue = new Vector3f(0.0f, Float.POSITIVE_INFINITY, Float.POSITIVE_INFINITY);
final Vector3f retval = FastMath.interpolateLinear(scale, startValue, endValue);
assertNotNull(retval);
assertEquals(0.0f, retval.getX(), 0.0f);
assertEquals(Float.POSITIVE_INFINITY, retval.getY(), 0.0f);
assertEquals(Float.POSITIVE_INFINITY, retval.getZ(), 0.0f);
}
@Test
public void testInterpolateLinear5() {
final float scale = 0.309184f;
final Vector3f startValue = new Vector3f(-53.1157f, 0.0f, 1.23634f);
final Vector3f endValue = new Vector3f(-1.98571f, Float.POSITIVE_INFINITY, 3.67342e-40f);
final Vector3f retval = FastMath.interpolateLinear(scale, startValue, endValue);
assertNotNull(retval);
assertEquals(-37.3071f, retval.getX(), 0.01f);
assertEquals(Float.POSITIVE_INFINITY, retval.getY(), 0.0f);
assertEquals(0.854082f, retval.getZ(), 0.01f);
}
@Test
public void testInterpolateLinear6() {
final float scale = 0.0f;
final Vector3f startValue = new Vector3f(0.0f, 0.0f, 0.0f);
final Vector3f endValue = new Vector3f(0.0f, 0.0f, 0.0f);
final Vector3f store = new Vector3f(0.0f, 0.0f, 0.0f);
final Vector3f retval = FastMath.interpolateLinear(scale, startValue, endValue, store);
assertNotNull(retval);
assertEquals(0.0f, retval.getX(), 0.0f);
assertEquals(0.0f, retval.getY(), 0.0f);
assertEquals(0.0f, retval.getZ(), 0.0f);
}
@Test
public void testInterpolateLinear7() {
final float scale = 0.0f;
final Vector3f startValue = new Vector3f(1.4013e-45f, 0.0f, 0.0f);
final Vector3f endValue = new Vector3f(0.0f, 0.0f, 0.0f);
final Vector3f store = new Vector3f(0.0f, 0.0f, 0.0f);
final Vector3f retval = FastMath.interpolateLinear(scale, startValue, endValue, store);
assertEquals(store, retval);
assertNotNull(store);
assertEquals(1.4013e-45f, store.getX(), 0.0f);
assertEquals(0.0f, store.getY(), 0.0f);
assertEquals(0.0f, store.getZ(), 0.0f);
assertNotNull(retval);
assertEquals(1.4013e-45f, retval.getX(), 0.0f);
assertEquals(0.0f, retval.getY(), 0.0f);
assertEquals(0.0f, retval.getZ(), 0.0f);
}
@Test
public void testInterpolateLinear8() {
final float scale = 0.0f;
final Vector3f startValue = new Vector3f(0.0f, 0.0f, 0.0f);
final Vector3f endValue = new Vector3f(0.0f, 0.0f, 0.0f);
final Vector3f retval = FastMath.interpolateLinear(scale, startValue, endValue);
assertNotNull(retval);
assertEquals(0.0f, retval.getX(), 0.0f);
assertEquals(0.0f, retval.getY(), 0.0f);
assertEquals(0.0f, retval.getZ(), 0.0f);
}
@Test
public void testInterpolateLinear_float() {
assertEquals(0.0f, FastMath.interpolateLinear(2.0f, 2.93874e-39f, 0.0f), 0.0f);
assertEquals(0.0f, FastMath.interpolateLinear(0.999999f, 1.4013e-45f, 0.0f), 0.0f);
assertEquals(-2.93874e-39f, FastMath.interpolateLinear(0.0f, -2.93874e-39f, -0.0f), 0.0f);
assertEquals(0.0f, FastMath.interpolateLinear(0.0f, 0.0f, 0.0f), 0.0f);
}
@Test
public void testNormalize() {
assertEquals(0.0f, FastMath.normalize(Float.POSITIVE_INFINITY, 0.0f, 0.0f), 0.0f);
assertEquals(0.0f, FastMath.normalize(Float.NaN, 0.0f, 0.0f), 0.0f);
assertEquals(4.0f, FastMath.normalize(15.0f, 1.0f, 12.0f), 0.0f);
assertEquals(15.0f, FastMath.normalize(15.0f, 1.0f, 16.0f), 0.0f);
assertEquals(0.0f, FastMath.normalize(0.0f, 0.0f, 0.0f), 0.0f);
}
@Test
public void testPointInsideTriangle() {
final Vector2f t0 = new Vector2f(2.03f, -4.04f);
final Vector2f t1 = new Vector2f(0.12f, 5.45f);
final Vector2f t2 = new Vector2f(1.90f, 3.43f);
final Vector2f p = new Vector2f(1.28f, 3.46f);
assertEquals(-1, FastMath.pointInsideTriangle(t0, t1, t2, p));
}
@Test
public void testPointInsideTriangle2() {
final Vector2f t0 = new Vector2f(2.03f, 4.04f);
final Vector2f t1 = new Vector2f(0.12f, -5.45f);
final Vector2f t2 = new Vector2f(1.90f, -3.43f);
final Vector2f p = new Vector2f(1.90f, -3.43f);
assertEquals(1, FastMath.pointInsideTriangle(t0, t1, t2, p));
}
@Test
public void testPointInsideTriangle3() {
final Vector2f t0 = new Vector2f(-0.0f, 7.38f);
final Vector2f t1 = new Vector2f(-1.0f, 1.70f);
final Vector2f t2 = new Vector2f(Float.NaN, -4.18f);
final Vector2f p = new Vector2f(-1.0f, -2.12f);
assertEquals(1, FastMath.pointInsideTriangle(t0, t1, t2, p));
}
@Test
public void testPointInsideTriangle4() {
final Vector2f t0 = new Vector2f(4.82f, 1.35f);
final Vector2f t1 = new Vector2f(-1.36f, Float.NaN);
final Vector2f t2 = new Vector2f(-1.0f, 9.45f);
final Vector2f p = new Vector2f(2.32f, Float.NaN);
assertEquals(1, FastMath.pointInsideTriangle(t0, t1, t2, p));
}
@Test
public void testPointInsideTriangle5() {
final Vector2f t0 = new Vector2f(1.32f, 9.55f);
final Vector2f t1 = new Vector2f(Float.NaN, -2.35f);
final Vector2f t2 = new Vector2f(-5.42f, Float.NaN);
final Vector2f p = new Vector2f(-7.20f, 8.81f);
assertEquals(1, FastMath.pointInsideTriangle(t0, t1, t2, p));
}
@Test
public void testPointInsideTriangle6() {
final Vector2f t0 = new Vector2f(-0.43f, 2.54f);
final Vector2f t1 = new Vector2f(Float.NEGATIVE_INFINITY, 2.54f);
final Vector2f t2 = new Vector2f(Float.NaN, Float.POSITIVE_INFINITY);
final Vector2f p = new Vector2f(-3.19f, -0.001f);;
assertEquals(0, FastMath.pointInsideTriangle(t0, t1, t2, p));
}
@Test
public void testPointInsideTriangle7() {
final Vector2f t0 = new Vector2f(-3.32f, 1.87f);
final Vector2f t1 = new Vector2f(-2.72f, 1.87f);
final Vector2f t2 = new Vector2f(-1.27f, 1.87f);
final Vector2f p = new Vector2f(6.38f, 1.90f);
assertEquals(0, FastMath.pointInsideTriangle(t0, t1, t2, p));
}
@Test
public void testPointInsideTriangle8() {
final Vector2f t0 = new Vector2f(3.96f, -511.96f);
final Vector2f t1 = new Vector2f(-5.36f, 1.27f);
final Vector2f t2 = new Vector2f(1.56f, -7.84f);
final Vector2f p = new Vector2f(5.06f, Float.NEGATIVE_INFINITY);
assertEquals(0, FastMath.pointInsideTriangle(t0, t1, t2, p));
}
@Test
public void testSaturate() {
assertEquals(0.0f, FastMath.saturate(-2.0f), 0.0f);
assertEquals(1.0f, FastMath.saturate(1.0f), 0.0f);
assertEquals(1.0f, FastMath.saturate(7.5f), 0.0f);
assertEquals(0.0f, FastMath.saturate(0.0f), 0.0f);
assertEquals(0.5f, FastMath.saturate(0.5f), 0.0f);
assertEquals(0.75f, FastMath.saturate(0.75f), 0.0f);
}
@Test
public void testSign() {
assertEquals(-1, FastMath.sign(-2_147_483_647));
assertEquals(1, FastMath.sign(1));
assertEquals(0, FastMath.sign(0));
assertEquals(0.0f, FastMath.sign(0.0f), 0.0f);
}
@Test
public void testSphericalToCartesian() {
final Vector3f sphereCoords = new Vector3f(4.29497e+09f, 0.0f, 0.0f);
final Vector3f store = new Vector3f(0.0f, 0.0f, 0.0f);
final Vector3f retval = FastMath.sphericalToCartesian(sphereCoords, store);
assertEquals(store, retval);
assertNotNull(store);
assertEquals(4294969900f, store.getX(), 0.01f);
assertEquals(0.0f, store.getY(), 0.0f);
assertEquals(0.0f, store.getZ(), 0.0f);
assertNotNull(retval);
assertEquals(4294969900f, retval.getX(), 0.01f);
assertEquals(0.0f, retval.getY(), 0.0f);
assertEquals(0.0f, retval.getZ(), 0.0f);
}
@Test
public void testSphericalToCartesianZ() {
final Vector3f sphereCoords = new Vector3f(4.29497e+09f, 0.0f, 0.0f);
final Vector3f store = new Vector3f(0.0f, 0.0f, 0.0f);
final Vector3f retval = FastMath.sphericalToCartesianZ(sphereCoords, store);
assertEquals(store, retval);
assertNotNull(store);
assertEquals(4294969900f, store.getX(), 0.0f);
assertEquals(0.0f, store.getY(), 0.0f);
assertEquals(0.0f, store.getZ(), 0.0f);
assertNotNull(retval);
assertEquals(4294969900f, retval.getX(), 0.0f);
assertEquals(0.0f, retval.getY(), 0.0f);
assertEquals(0.0f, retval.getZ(), 0.0f);
}
}
|
/***
* Sends a canary message to every topic and partition in Kafka.
* Reads data from the tail of every topic and partition in Kafka
* Reports the availability and latency metrics for the above operations.
* Availability is defined as the percentage of total partitions that respond to each operation.
*/
public class App {
final static Logger m_logger = LoggerFactory.getLogger(App.class);
static int m_sleepTime = 30000;
static String m_cluster = "localhost";
static MetricRegistry m_metrics;
static AppProperties appProperties;
static MetaDataManagerProperties metaDataProperties;
static Collection<ServiceInstance<MetaData>> instances;
static List<String> listServers;
private static String registrationPath = Constants.DEFAULT_REGISTRATION_ROOT;
private static String ip = CommonUtils.getIpAddress();
private static String serviceSpec = "";
public static void main(String[] args) throws IOException, MetaDataManagerException, InterruptedException {
m_logger.info("Starting KafkaAvailability Tool");
IPropertiesManager appPropertiesManager = new PropertiesManager<AppProperties>("appProperties.json", AppProperties.class);
IPropertiesManager metaDataPropertiesManager = new PropertiesManager<MetaDataManagerProperties>("metadatamanagerProperties.json", MetaDataManagerProperties.class);
appProperties = (AppProperties) appPropertiesManager.getProperties();
metaDataProperties = (MetaDataManagerProperties) metaDataPropertiesManager.getProperties();
Options options = new Options();
options.addOption("r", "run", true, "Number of runs. Don't use this argument if you want to run infintely.");
options.addOption("s", "sleep", true, "Time (in milliseconds) to sleep between each run. Default is 120000");
Option clusterOption = Option.builder("c").hasArg().required(true).longOpt("cluster").desc("(REQUIRED) Cluster name").build();
options.addOption(clusterOption);
CommandLineParser parser = new DefaultParser();
HelpFormatter formatter = new HelpFormatter();
final CuratorFramework curatorFramework = CuratorClient.getCuratorFramework(metaDataProperties.zooKeeperHosts);
try {
// parse the command line arguments
CommandLine line = parser.parse(options, args);
int howManyRuns;
m_cluster = line.getOptionValue("cluster");
MDC.put("cluster", m_cluster);
CuratorManager curatorManager = CallRegister(curatorFramework);
if (line.hasOption("sleep")) {
m_sleepTime = Integer.parseInt(line.getOptionValue("sleep"));
}
if (line.hasOption("run")) {
howManyRuns = Integer.parseInt(line.getOptionValue("run"));
for (int i = 0; i < howManyRuns; i++) {
InitMetrics(m_sleepTime);
waitForChanges(curatorManager);
RunOnce(curatorFramework);
Thread.sleep(m_sleepTime);
}
} else {
while (true) {
InitMetrics(m_sleepTime);
waitForChanges(curatorManager);
RunOnce(curatorFramework);
Thread.sleep(m_sleepTime);
}
}
} catch (ParseException exp) {
// oops, something went wrong
m_logger.error("Parsing failed. Reason: " + exp.getMessage());
formatter.printHelp("KafkaAvailability", options);
} catch (Exception e) {
m_logger.error(e.getMessage(), e);
}
}
private static CuratorManager CallRegister(final CuratorFramework curatorFramework) throws Exception {
int port = ((int) (65535 * Math.random()));
serviceSpec = ip + ":" + Integer.valueOf(port).toString();
String basePath = new StringBuilder().append(registrationPath).toString();
m_logger.info("Creating client, KAT");
final CuratorManager curatorManager = new CuratorManager(curatorFramework, basePath, ip, serviceSpec);
try {
curatorManager.registerLocalService();
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
m_logger.info("Normal shutdown executing.");
curatorManager.unregisterService();
if (curatorFramework != null && (curatorFramework.getState().equals(CuratorFrameworkState.STARTED) || curatorFramework.getState().equals(CuratorFrameworkState.LATENT))) {
curatorFramework.close();
}
}
});
} catch (Exception e) {
m_logger.error(e.getMessage(), e);
}
return curatorManager;
}
private static void waitForChanges(CuratorManager curatorManager) throws Exception {
try {
listServers = curatorManager.listServiceInstance();
m_logger.info("listServers:" + Arrays.toString(listServers.toArray()));
//wait for rest clients to warm up.
Thread.sleep(30000);
curatorManager.verifyRegistrations();
} catch (Exception e) {
/* * Something bad did happen, but carry on
*/
m_logger.error(e.getMessage(), e);
}
}
private static void InitMetrics(int reportDuration) {
m_metrics = new MetricRegistry();
if (appProperties.reportToSlf4j) {
final Slf4jReporter slf4jReporter = Slf4jReporter.forRegistry(m_metrics)
.outputTo(LoggerFactory.getLogger("KafkaMetrics.Raw"))
.convertRatesTo(TimeUnit.SECONDS)
.convertDurationsTo(TimeUnit.MILLISECONDS)
.build();
slf4jReporter.start(reportDuration, TimeUnit.MILLISECONDS);
}
if (appProperties.reportToSql) {
final SqlReporter sqlReporter = SqlReporter.forRegistry(m_metrics)
.formatFor(Locale.US)
.convertRatesTo(TimeUnit.SECONDS)
.convertDurationsTo(TimeUnit.MILLISECONDS)
.build(appProperties.sqlConnectionString, m_cluster);
sqlReporter.start(reportDuration, TimeUnit.MILLISECONDS);
}
if (appProperties.reportToJmx) {
final JmxReporter jmxReporter = JmxReporter.forRegistry(m_metrics).build();
jmxReporter.start();
}
if (appProperties.reportToConsole) {
final ConsoleReporter consoleReporter = ConsoleReporter.forRegistry(m_metrics)
.convertRatesTo(TimeUnit.SECONDS)
.convertDurationsTo(TimeUnit.MILLISECONDS)
.build();
consoleReporter.start(reportDuration, TimeUnit.MILLISECONDS);
}
if (appProperties.reportToCsv) {
final CsvReporter csvReporter = CsvReporter.forRegistry(m_metrics)
.formatFor(Locale.US)
.convertRatesTo(TimeUnit.SECONDS)
.convertDurationsTo(TimeUnit.MILLISECONDS)
.build(new File(appProperties.csvDirectory));
csvReporter.start(reportDuration, TimeUnit.MILLISECONDS);
}
}
private static void RunOnce(CuratorFramework curatorFramework) throws IOException, MetaDataManagerException {
IPropertiesManager producerPropertiesManager = new PropertiesManager<ProducerProperties>("producerProperties.json", ProducerProperties.class);
IPropertiesManager metaDataPropertiesManager = new PropertiesManager<MetaDataManagerProperties>("metadatamanagerProperties.json", MetaDataManagerProperties.class);
IPropertiesManager consumerPropertiesManager = new PropertiesManager<ConsumerProperties>("consumerProperties.json", ConsumerProperties.class);
IMetaDataManager metaDataManager = new MetaDataManager(curatorFramework, metaDataPropertiesManager);
IProducer producer = new Producer(producerPropertiesManager, metaDataManager);
IConsumer consumer = new Consumer(consumerPropertiesManager, metaDataManager);
int producerTryCount = 0, clusterIPStatusTryCount = 0, gtmIPStatusTryCount = 0;
int producerFailCount = 0, clusterIPStatusFailCount = 0, gtmIPStatusFailCount = 0;
long startTime, endTime;
int numPartitionsProducer = 0, numPartitionsConsumers = 0;
//Auto creating a whitelisted topics, if not available.
metaDataManager.createWhiteListedTopics();
m_logger.info("get metadata size");
//This is full list of topics
List<kafka.javaapi.TopicMetadata> totalTopicMetadata = metaDataManager.getAllTopicPartition();
//Collections.sort(totalTopicMetadata, new TopicMetadataComparator());
List<kafka.javaapi.TopicMetadata> whiteListTopicMetadata = new ArrayList<kafka.javaapi.TopicMetadata>();
List<kafka.javaapi.TopicMetadata> allTopicMetadata = new ArrayList<kafka.javaapi.TopicMetadata>();
for (kafka.javaapi.TopicMetadata topic : totalTopicMetadata) {
for (String whiteListTopic : metaDataProperties.topicsWhitelist)
// java string compare while ignoring case
if (topic.topic().equalsIgnoreCase(whiteListTopic)) {
whiteListTopicMetadata.add(topic);
}
if ((totalTopicMetadata.indexOf(topic) % listServers.size()) == listServers.indexOf(serviceSpec)) {
allTopicMetadata.add(topic);
}
}
m_logger.info("totalTopicMetadata size:" + totalTopicMetadata.size());
m_logger.info("whiteListTopicMetadata size:" + whiteListTopicMetadata.size());
m_logger.info("allTopicMetadata size:" + allTopicMetadata.size());
m_logger.info("Starting ProducerLatency");
m_logger.info("done getting metadata size for producer");
for (kafka.javaapi.TopicMetadata topic : whiteListTopicMetadata) {
numPartitionsProducer += topic.partitionsMetadata().size();
}
final SlidingWindowReservoir producerLatencyWindow = new SlidingWindowReservoir(numPartitionsProducer);
Histogram histogramProducerLatency = new Histogram(producerLatencyWindow);
MetricNameEncoded producerLatency = new MetricNameEncoded("Producer.Latency", "all");
if (appProperties.sendProducerLatency)
m_metrics.register(new Gson().toJson(producerLatency), histogramProducerLatency);
m_logger.info("start topic partition loop");
for (kafka.javaapi.TopicMetadata item : whiteListTopicMetadata) {
m_logger.info("Starting VIP prop check." + appProperties.reportKafkaIPAvailability);
if (appProperties.reportKafkaIPAvailability) {
try {
m_logger.info("Starting VIP check.");
clusterIPStatusTryCount++;
producer.SendCanaryToKafkaIP(appProperties.kafkaClusterIP, item.topic(), false);
} catch (Exception e) {
m_logger.info("VIP check exception");
clusterIPStatusFailCount++;
m_logger.error("ClusterIPStatus -- Error Writing to Topic: {}; Exception: {}", item.topic(), e);
}
try {
gtmIPStatusTryCount++;
producer.SendCanaryToKafkaIP(appProperties.kafkaGTMIP, item.topic(), false);
} catch (Exception e) {
gtmIPStatusFailCount++;
m_logger.error("GTMIPStatus -- Error Writing to Topic: {}; Exception: {}", item.topic(), e);
}
}
m_logger.info("done with VIP prop check.");
final SlidingWindowReservoir topicLatency = new SlidingWindowReservoir(item.partitionsMetadata().size());
Histogram histogramProducerTopicLatency = new Histogram(topicLatency);
MetricNameEncoded producerTopicLatency = new MetricNameEncoded("Producer.Topic.Latency", item.topic());
if (!m_metrics.getNames().contains(new Gson().toJson(producerTopicLatency))) {
if (appProperties.sendProducerTopicLatency)
m_metrics.register(new Gson().toJson(producerTopicLatency), histogramProducerTopicLatency);
}
for (kafka.javaapi.PartitionMetadata part : item.partitionsMetadata()) {
m_logger.debug("Writing to Topic: {}; Partition: {};", item.topic(), part.partitionId());
MetricNameEncoded producerPartitionLatency = new MetricNameEncoded("Producer.Partition.Latency", item.topic() + "-" + part.partitionId());
Histogram histogramProducerPartitionLatency = new Histogram(new SlidingWindowReservoir(1));
if (!m_metrics.getNames().contains(new Gson().toJson(producerPartitionLatency))) {
if (appProperties.sendProducerPartitionLatency)
m_metrics.register(new Gson().toJson(producerPartitionLatency), histogramProducerPartitionLatency);
}
startTime = System.currentTimeMillis();
try {
producerTryCount++;
producer.SendCanaryToTopicPartition(item.topic(), Integer.toString(part.partitionId()));
endTime = System.currentTimeMillis();
} catch (Exception e) {
m_logger.error("Error Writing to Topic: {}; Partition: {}; Exception: {}", item.topic(), part.partitionId(), e);
producerFailCount++;
//now add a minute, 60000 milliseconds = 1 minute
long halfAnHourLater = System.currentTimeMillis() + 60000;
endTime = halfAnHourLater;
}
histogramProducerLatency.update(endTime - startTime);
histogramProducerTopicLatency.update(endTime - startTime);
histogramProducerPartitionLatency.update(endTime - startTime);
}
}
if (appProperties.reportKafkaIPAvailability) {
m_logger.info("About to report kafkaIPAvail:" + clusterIPStatusTryCount + " " + clusterIPStatusFailCount);
MetricNameEncoded kafkaClusterIPAvailability = new MetricNameEncoded("KafkaIP.Availability", "all");
m_metrics.register(new Gson().toJson(kafkaClusterIPAvailability), new AvailabilityGauge(clusterIPStatusTryCount, clusterIPStatusTryCount - clusterIPStatusFailCount));
MetricNameEncoded kafkaGTMIPAvailability = new MetricNameEncoded("KafkaGTMIP.Availability", "all");
m_metrics.register(new Gson().toJson(kafkaGTMIPAvailability), new AvailabilityGauge(gtmIPStatusTryCount, gtmIPStatusTryCount - gtmIPStatusFailCount));
}
if (appProperties.sendProducerAvailability) {
MetricNameEncoded producerAvailability = new MetricNameEncoded("Producer.Availability", "all");
m_metrics.register(new Gson().toJson(producerAvailability), new AvailabilityGauge(producerTryCount, producerTryCount - producerFailCount));
}
int consumerTryCount = 0;
int consumerFailCount = 0;
m_logger.info("done getting metadata size for consumer");
for (kafka.javaapi.TopicMetadata topic : allTopicMetadata) {
numPartitionsConsumers += topic.partitionsMetadata().size();
}
final SlidingWindowReservoir consumerLatencyWindow = new SlidingWindowReservoir(numPartitionsConsumers);
Histogram histogramConsumerLatency = new Histogram(consumerLatencyWindow);
if (appProperties.sendConsumerLatency) {
MetricNameEncoded consumerLatency = new MetricNameEncoded("Consumer.Latency", "all");
m_metrics.register(new Gson().toJson(consumerLatency), histogramConsumerLatency);
}
for (kafka.javaapi.TopicMetadata item : allTopicMetadata) {
final SlidingWindowReservoir topicLatency = new SlidingWindowReservoir(item.partitionsMetadata().size());
Histogram histogramConsumerTopicLatency = new Histogram(topicLatency);
MetricNameEncoded consumerTopicLatency = new MetricNameEncoded("Consumer.Topic.Latency", item.topic());
if (!m_metrics.getNames().contains(new Gson().toJson(consumerTopicLatency))) {
if (appProperties.sendConsumerTopicLatency)
m_metrics.register(new Gson().toJson(consumerTopicLatency), histogramConsumerTopicLatency);
}
for (kafka.javaapi.PartitionMetadata part : item.partitionsMetadata()) {
m_logger.debug("Reading from Topic: {}; Partition: {};", item.topic(), part.partitionId());
MetricNameEncoded consumerPartitionLatency = new MetricNameEncoded("Consumer.Partition.Latency", item.topic() + "-" + part.partitionId());
Histogram histogramConsumerPartitionLatency = new Histogram(new SlidingWindowReservoir(1));
if (!m_metrics.getNames().contains(new Gson().toJson(consumerPartitionLatency))) {
if (appProperties.sendConsumerPartitionLatency)
m_metrics.register(new Gson().toJson(consumerPartitionLatency), histogramConsumerPartitionLatency);
}
startTime = System.currentTimeMillis();
try {
consumerTryCount++;
consumer.ConsumeFromTopicPartition(item.topic(), part.partitionId());
endTime = System.currentTimeMillis();
} catch (Exception e) {
m_logger.error("Error Reading from Topic: {}; Partition: {}; Exception: {}", item.topic(), part.partitionId(), e);
consumerFailCount++;
//now add a minute, 60000 milliseconds = 1 minute
long halfAnHourLater = System.currentTimeMillis() + 60000;
endTime = halfAnHourLater;
consumerFailCount++;
}
histogramConsumerLatency.update(endTime - startTime);
histogramConsumerTopicLatency.update(endTime - startTime);
histogramConsumerPartitionLatency.update(endTime - startTime);
}
}
if (appProperties.sendConsumerAvailability) {
MetricNameEncoded consumerAvailability = new MetricNameEncoded("Consumer.Availability", "all");
m_metrics.register(new Gson().toJson(consumerAvailability), new AvailabilityGauge(consumerTryCount, consumerTryCount - consumerFailCount));
}
//Print all the topic/partition information.
m_logger.info("Printing all the topic/partition information.");
metaDataManager.printEverything();
m_logger.info("All Finished.");
((MetaDataManager) metaDataManager).close();
}
}
|
package com.adsdk.sdk.customevents;
import android.app.Activity;
import com.unity3d.ads.android.IUnityAdsListener;
import com.unity3d.ads.android.UnityAds;
public class ApplifierFullscreen extends CustomEventFullscreen {
private static boolean initialized;
private boolean shouldReportAvailability;
@Override
public void loadFullscreen(Activity activity, CustomEventFullscreenListener customEventFullscreenListener, String optionalParameters, String trackingPixel) {
String adId = optionalParameters;
listener = customEventFullscreenListener;
shouldReportAvailability = true;
this.trackingPixel = trackingPixel;
try {
Class.forName("com.unity3d.ads.android.IUnityAdsListener");
Class.forName("com.unity3d.ads.android.UnityAds");
} catch (ClassNotFoundException e) {
if (listener != null) {
listener.onFullscreenFailed();
}
return;
}
if (!initialized) {
UnityAds.init(activity, adId, createListener());
initialized = true;
} else if (UnityAds.canShowAds()){
shouldReportAvailability = false;
if (listener != null) {
listener.onFullscreenLoaded(this);
}
UnityAds.setListener(createListener());
} else {
shouldReportAvailability = false;
if (listener != null) {
listener.onFullscreenFailed();
}
}
}
private IUnityAdsListener createListener() {
return new IUnityAdsListener() {
@Override
public void onVideoStarted() {
}
@Override
public void onVideoCompleted(String arg0, boolean arg1) {
}
@Override
public void onShow() {
reportImpression();
if (listener != null) {
listener.onFullscreenOpened();
}
}
@Override
public void onHide() {
if (listener != null) {
listener.onFullscreenClosed();
}
}
@Override
public void onFetchFailed() {
if (listener != null && shouldReportAvailability) {
listener.onFullscreenFailed();
}
}
@Override
public void onFetchCompleted() {
if (listener != null && shouldReportAvailability) {
listener.onFullscreenLoaded(ApplifierFullscreen.this);
}
}
};
}
@Override
public void showFullscreen() {
if (UnityAds.canShow() && UnityAds.canShowAds()) {
UnityAds.show();
}
}
}
|
package org.helioviewer.jhv.viewmodel.metadata;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Arrays;
import java.util.HashMap;
import org.helioviewer.jhv.base.DownloadStream;
import org.helioviewer.jhv.base.FileUtils;
import org.helioviewer.jhv.base.JSONUtils;
import org.json.JSONObject;
@SuppressWarnings("serial")
public class AIAResponse {
private static final HashMap<String, Double> STANDARD_INT = new HashMap<String, Double>() {
{
put("131", 6.99685);
put("171", 4.99803);
put("193", 2.9995);
put("211", 4.99801);
put("304", 4.99941);
put("335", 6.99734);
put("94", 4.99803);
}
};
private static final HashMap<String, Double> MAX = new HashMap<String, Double>() {
{
put("131", 1200.);
put("171", 6000.);
put("193", 6000.);
put("211", 13000.);
put("304", 2000.);
put("335", 1000.);
put("94", 50.);
}
};
private static final HashMap<String, Double> HV_MAX = new HashMap<String, Double>() {
{
put("131", 500.);
put("171", 14000.);
put("193", 2500.);
put("211", 1500.);
put("304", 250.);
put("335", 80.);
put("94", 30.);
}
};
private static final HashMap<String, Double> LMSAL_MAX = new HashMap<>();
private static final String extPath = "https://raw.githubusercontent.com/mjpauly/aia/master/";
private static final String intPath = "/data/";
private static final String dataFile = "aia_rescaling_data.json";
private static boolean loaded;
private static JSONObject responseData;
private static JSONObject referenceData;
private static String firstDate;
private static String lastDate;
private static URL getExternalURL() throws MalformedURLException {
return new URL(extPath + dataFile);
}
private static URL getInternalURL() {
return FileUtils.getResourceUrl(intPath + dataFile);
}
private static JSONObject getResponseData(URL url) throws IOException {
return JSONUtils.getJSONStream(new DownloadStream(url).getInput());
}
public static void load() throws Exception {
JSONObject data = getResponseData(getInternalURL());
String[] keys = JSONObject.getNames(data);
Arrays.sort(keys);
firstDate = keys[0];
lastDate = keys[keys.length - 1];
responseData = data;
referenceData = data.getJSONObject("2010-05-01");
for (String key : STANDARD_INT.keySet())
LMSAL_MAX.put(key, MAX.get(key) / STANDARD_INT.get(key));
loaded = true;
}
static double get(String date, String pass) {
if (!loaded)
return 1;
try {
if (lastDate.compareTo(date) < 0)
date = lastDate;
else if (firstDate.compareTo(date) > 0)
date = firstDate;
String key = pass; //+ "_filtered";
if (!referenceData.has(key) || !responseData.getJSONObject(date).has(key)) // exception if date missing
return 1;
double factor, ratio = referenceData.getDouble(key) / responseData.getJSONObject(date).getDouble(key);
if ("171".equals(pass) || "1700".equals(pass))
factor = Math.sqrt(ratio);
else
factor = 1 + Math.log10(ratio) / Math.log10(HV_MAX.get(pass));
return factor;
} catch (Exception e) {
e.printStackTrace();
}
return 1;
}
}
|
package jme3test.audio;
import com.jme3.app.SimpleApplication;
import com.jme3.audio.AudioData.DataType;
import com.jme3.audio.AudioNode;
import com.jme3.audio.AudioSource;
import com.jme3.audio.LowPassFilter;
public class TestOgg extends SimpleApplication {
private AudioNode audioSource;
public static void main(String[] args){
TestOgg test = new TestOgg();
test.start();
}
@Override
public void simpleInitApp(){
System.out.println("Playing without filter");
audioSource = new AudioNode(assetManager, "Sound/Effects/Foot steps.ogg", DataType.Buffer);
audioSource.play();
}
@Override
public void simpleUpdate(float tpf){
if (audioSource.getStatus() != AudioSource.Status.Playing){
audioRenderer.deleteAudioData(audioSource.getAudioData());
System.out.println("Playing with low pass filter");
audioSource = new AudioNode(assetManager, "Sound/Effects/Foot steps.ogg", DataType.Buffer);
audioSource.setDryFilter(new LowPassFilter(1f, .1f));
audioSource.setVolume(3);
audioSource.play();
}
}
}
|
package org.kwstudios.play.ragemode.statistics;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.UUID;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.kwstudios.play.ragemode.database.MySQLConnector;
import org.kwstudios.play.ragemode.scores.PlayerPoints;
import org.kwstudios.play.ragemode.scores.RetPlayerPoints;
import org.kwstudios.play.ragemode.toolbox.ConstantHolder;
public class MySQLStats {
/**
* Adds the statistics from the given PlayerPoints instance to the database
* connection from the given MySQLConnector instance.
*
* @param playerPoints
* The PlayerPoints instance from which the statistics should be
* gotten.
* @param mySQLConnector
* The MySQLConnector instance which holds the Connection for the
* database.
*/
public static void addPlayerStatistics(PlayerPoints playerPoints, MySQLConnector mySQLConnector) {
Connection connection = mySQLConnector.getConnection();
Statement statement = null;
String query = "SELECT * FROM rm_stats_players WHERE uuid LIKE '" + playerPoints.getPlayerUUID() + "';";
int oldKills = 0;
int oldAxeKills = 0;
int oldDirectArrowKills = 0;
int oldExplosionKills = 0;
int oldKnifeKills = 0;
int oldDeaths = 0;
int oldAxeDeaths = 0;
int oldDirectArrowDeaths = 0;
int oldExplosionDeaths = 0;
int oldKnifeDeaths = 0;
int oldWins = 0;
int oldScore = 0;
int oldGames = 0;
try {
statement = connection.createStatement();
ResultSet rs = statement.executeQuery(query);
while (rs.next()) {
oldKills = rs.getInt("kills");
oldAxeKills = rs.getInt("axe_kills");
oldDirectArrowKills = rs.getInt("direct_arrow_kills");
oldExplosionKills = rs.getInt("explosion_kills");
oldKnifeKills = rs.getInt("knife_kills");
oldDeaths = rs.getInt("deaths");
oldAxeDeaths = rs.getInt("axe_deaths");
oldDirectArrowDeaths = rs.getInt("direct_arrow_deaths");
oldExplosionDeaths = rs.getInt("explosion_deaths");
oldKnifeDeaths = rs.getInt("knife_deaths");
oldWins = rs.getInt("wins");
oldScore = rs.getInt("score");
oldGames = rs.getInt("games");
}
} catch (SQLException e) {
System.out.println(
ConstantHolder.RAGEMODE_PREFIX + Bukkit.getPlayer(UUID.fromString(playerPoints.getPlayerUUID()))
+ " has no statistics yet! Creating one special row for him...");
}
if (statement != null) {
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
int newKills = oldKills + playerPoints.getKills();
int newAxeKills = oldAxeKills + playerPoints.getAxeKills();
int newDirectArrowKills = oldDirectArrowKills + playerPoints.getDirectArrowKills();
int newExplosionKills = oldExplosionKills + playerPoints.getExplosionKills();
int newKnifeKills = oldKnifeKills + playerPoints.getKnifeKills();
int newDeaths = oldDeaths + playerPoints.getDeaths();
int newAxeDeaths = oldAxeDeaths + playerPoints.getAxeDeaths();
int newDirectArrowDeaths = oldDirectArrowDeaths + playerPoints.getDirectArrowDeaths();
int newExplosionDeaths = oldExplosionDeaths + playerPoints.getExplosionDeaths();
int newKnifeDeaths = oldKnifeDeaths + playerPoints.getKnifeDeaths();
int newWins = (playerPoints.isWinner()) ? oldWins + 1 : oldWins;
int newScore = oldScore + playerPoints.getPoints();
int newGames = oldGames + 1;
double newKD = (newDeaths != 0) ? (((double) newKills) / ((double) newDeaths)) : 1;
statement = null;
query = "REPLACE INTO rm_stats_players (name, uuid, kills, axe_kills, direct_arrow_kills, explosion_kills, knife_kills, deaths, axe_deaths, direct_arrow_deaths, explosion_deaths, knife_deaths, wins, score, games, kd) VALUES ("
+ "'" + Bukkit.getPlayer(UUID.fromString(playerPoints.getPlayerUUID())).getName() + "', " + "'"
+ playerPoints.getPlayerUUID() + "', " + Integer.toString(newKills) + ", "
+ Integer.toString(newAxeKills) + ", " + Integer.toString(newDirectArrowKills) + ", "
+ Integer.toString(newExplosionKills) + ", " + Integer.toString(newKnifeKills) + ", "
+ Integer.toString(newDeaths) + ", " + Integer.toString(newAxeDeaths) + ", "
+ Integer.toString(newDirectArrowDeaths) + ", " + Integer.toString(newExplosionDeaths) + ", "
+ Integer.toString(newKnifeDeaths) + ", " + Integer.toString(newWins) + ", "
+ Integer.toString(newScore) + ", " + Integer.toString(newGames) + ", " + Double.toString(newKD) + ");";
try {
statement = connection.createStatement();
statement.executeUpdate(query);
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* Returns an RetPlayerPoints instance with the statistics from the database
* connection for the given Player.
*
* @param player
* The Player instance for which the statistic should be gotten.
* @param mySQLConnector
* The MySQLConnector which holds the Connection instance for the
* database.
* @return
*/
public static RetPlayerPoints getPlayerStatistics(String player, MySQLConnector mySQLConnector) {
Connection connection = mySQLConnector.getConnection();
Statement statement = null;
String query = "SELECT * FROM rm_stats_players WHERE uuid LIKE '" + player + "';";
int currentKills = 0;
int currentAxeKills = 0;
int currentDirectArrowKills = 0;
int currentExplosionKills = 0;
int currentKnifeKills = 0;
int currentDeaths = 0;
int currentAxeDeaths = 0;
int currentDirectArrowDeaths = 0;
int currentExplosionDeaths = 0;
int currentKnifeDeaths = 0;
int currentWins = 0;
int currentScore = 0;
int currentGames = 0;
double currentKD = 0;
try {
statement = connection.createStatement();
ResultSet rs = statement.executeQuery(query);
while (rs.next()) {
currentKills = rs.getInt("kills");
currentAxeKills = rs.getInt("axe_kills");
currentDirectArrowKills = rs.getInt("direct_arrow_kills");
currentExplosionKills = rs.getInt("explosion_kills");
currentKnifeKills = rs.getInt("knife_kills");
currentDeaths = rs.getInt("deaths");
currentAxeDeaths = rs.getInt("axe_deaths");
currentDirectArrowDeaths = rs.getInt("direct_arrow_deaths");
currentExplosionDeaths = rs.getInt("explosion_deaths");
currentKnifeDeaths = rs.getInt("knife_deaths");
currentWins = rs.getInt("wins");
currentScore = rs.getInt("score");
currentGames = rs.getInt("games");
currentKD = rs.getDouble("kd");
}
} catch (SQLException e) {
// System.out.println("Something went wrong!");
return null;
}
if (statement != null) {
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
RetPlayerPoints retPlayerPoints = new RetPlayerPoints(player);
retPlayerPoints.setKills(currentKills);
retPlayerPoints.setAxeKills(currentAxeKills);
retPlayerPoints.setDirectArrowKills(currentDirectArrowKills);
retPlayerPoints.setExplosionKills(currentExplosionKills);
retPlayerPoints.setKnifeKills(currentKnifeKills);
retPlayerPoints.setDeaths(currentDeaths);
retPlayerPoints.setAxeDeaths(currentAxeDeaths);
retPlayerPoints.setDirectArrowDeaths(currentDirectArrowDeaths);
retPlayerPoints.setExplosionDeaths(currentExplosionDeaths);
retPlayerPoints.setKnifeDeaths(currentKnifeDeaths);
retPlayerPoints.setWins(currentWins);
retPlayerPoints.setPoints(currentScore);
retPlayerPoints.setGames(currentGames);
retPlayerPoints.setKD(currentKD);
return retPlayerPoints;
}
}
|
package com.notnoop.mpns;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
import java.util.Arrays;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import javax.net.ssl.KeyManager;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import org.apache.http.HttpHost;
import org.apache.http.client.HttpClient;
import org.apache.http.conn.params.ConnRoutePNames;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import com.notnoop.mpns.internal.*;
/**
* The class is used to create instances of {@link MpnsService}.
*
* Note that this class is not synchronized. If multiple threads access a
* {@code MpnsServiceBuilder} instance concurrently, and at least on of the
* threads modifies one of the attributes structurally, it must be
* synchronized externally.
*
* Starting a new {@code MpnsService} is easy:
*
* <pre>
* MpnsService service = MPNS.newService()
* .build()
* </pre>
*/
public class MpnsServiceBuilder {
private int pooledMax = 1;
private ExecutorService executor = null;
private boolean isQueued = false;
private HttpHost proxy = null;
private HttpClient httpClient = null;
private int timeout = -1;
private MpnsDelegate delegate;
// Authenticated calls
private SecurityInfo securityInfo;
public static class SecurityInfo {
private byte[] cert;
private String password;
private String name;
private String provider;
public SecurityInfo(byte[] cert, String password, String securityName, String securityProvider) {
if( cert == null || cert.length == 0 ||
password == null || "".equals(password.trim()) ||
securityName == null || "".equals(securityName.trim()) ) {
// provider is optional
throw new IllegalArgumentException("Please provide certificate, password, and name");
}
this.cert = Arrays.copyOf(cert, cert.length);
this.password = password;
this.name = securityName;
this.provider = securityProvider;
}
public byte[] getCert() {
return cert;
}
public String getPassword() {
return password;
}
public String getName() {
return name;
}
public String getProvider() {
return provider;
}
}
/**
* Constructs a new instance of {@code MpnsServiceBuilder}
*/
public MpnsServiceBuilder() { }
public MpnsServiceBuilder withHttpProxy(String host, int port) {
this.proxy = new HttpHost(host, port);
return this;
}
// TODO: Support Proxy again
// public MpnsServiceBuilder withProxy(Proxy proxy) {
// this.proxy = proxy;
// return this;
/**
* Sets the HttpClient instance along with any configuration
*
* NOTE: This is an advanced option that should be probably be used as a
* last resort.
*
* @param httpClient the httpClient to be used
* @return this
*/
public MpnsServiceBuilder withHttpClient(HttpClient httpClient) {
this.httpClient = httpClient;
return this;
}
/**
* Constructs a pool of connections to the notification servers.
*
*/
public MpnsServiceBuilder asPool(int maxConnections) {
return asPool(Executors.newFixedThreadPool(maxConnections), maxConnections);
}
/**
* Constructs a pool of connections to the notification servers.
*
* Note: The maxConnections here is used as a hint to how many connections
* get created.
*/
public MpnsServiceBuilder asPool(ExecutorService executor, int maxConnections) {
this.pooledMax = maxConnections;
this.executor = executor;
return this;
}
/**
* Constructs a new thread with a processing queue to process
* notification requests.
*
* @return this
*/
public MpnsServiceBuilder asQueued() {
this.isQueued = true;
return this;
}
/**
* Authenticated
*/
public MpnsServiceBuilder asAuthenticated(SecurityInfo securityInfo) {
this.securityInfo = securityInfo;
return this;
}
/**
* Sets the timeout for the connection
*
* @param timeout the time out period in millis
* @return this
*/
public MpnsServiceBuilder timeout(int timeout) {
this.timeout = timeout;
return this;
}
public MpnsServiceBuilder delegate(MpnsDelegate delegate) {
this.delegate = delegate;
return this;
}
/**
* Returns a fully initialized instance of {@link MpnsService},
* according to the requested settings.
*
* @return a new instance of MpnsService
*/
public MpnsService build() {
checkInitialization();
// Client Configuration
HttpClient client;
if (httpClient != null) {
client = httpClient;
} else if (pooledMax == 1) {
client = new DefaultHttpClient();
} else {
client = new DefaultHttpClient(Utilities.poolManager(pooledMax));
}
if (proxy != null) {
client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
}
if( securityInfo != null ) {
try {
KeyStore keyStore = null;
if( securityInfo.getProvider() == null ) {
keyStore = KeyStore.getInstance(securityInfo.getName());
} else {
keyStore = KeyStore.getInstance(securityInfo.getName(), securityInfo.getProvider());
}
keyStore.load(new ByteArrayInputStream(securityInfo.getCert()),
securityInfo.getPassword().toCharArray());
KeyManagerFactory kmfactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
kmfactory.init(keyStore, securityInfo.getPassword().toCharArray());
KeyManager[] km = kmfactory.getKeyManagers();
// create SSL socket factory
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(km, null, null);
org.apache.http.conn.ssl.SSLSocketFactory sslSocketFactory = new org.apache.http.conn.ssl.SSLSocketFactory(sslContext);
Scheme https = new Scheme("https", 443, sslSocketFactory);
client.getConnectionManager().getSchemeRegistry().register(https);
} catch( Exception e ) {
throw new IllegalArgumentException(e);
}
}
if (timeout > 0) {
HttpParams params = client.getParams();
HttpConnectionParams.setConnectionTimeout(params, timeout);
HttpConnectionParams.setSoTimeout(params, timeout);
}
// Configure service
AbstractMpnsService service;
if (pooledMax == 1) {
service = new MpnsServiceImpl(client, delegate);
} else {
service = new MpnsPooledService(client, executor, delegate);
}
if (isQueued) {
service = new MpnsQueuedService(service);
}
service.start();
return service;
}
private void checkInitialization() {
if (pooledMax != 1 && executor == null) {
throw new IllegalStateException("Executor service is required for pooled connections");
}
}
}
|
package org.maptalks.gis.core.geojson.json;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.maptalks.gis.core.geojson.*;
import org.maptalks.gis.core.geojson.ext.Circle;
import org.maptalks.gis.core.geojson.ext.Ellipse;
import org.maptalks.gis.core.geojson.ext.Rectangle;
import org.maptalks.gis.core.geojson.ext.Sector;
import java.util.HashMap;
import java.util.Map;
public class GeoJSONFactory {
static Map<String, Class> geoJsonTypeMap = new HashMap<String, Class>();
static {
geoJsonTypeMap.put(GeoJsonTypes.TYPE_POINT,Point.class);
geoJsonTypeMap.put(GeoJsonTypes.TYPE_LINESTRING,LineString.class);
geoJsonTypeMap.put(GeoJsonTypes.TYPE_POLYGON,Polygon.class);
geoJsonTypeMap.put(GeoJsonTypes.TYPE_MULTIPOINT,MultiPoint.class);
geoJsonTypeMap.put(GeoJsonTypes.TYPE_MULTILINESTRING,MultiLineString.class);
geoJsonTypeMap.put(GeoJsonTypes.TYPE_MULTIPOLYGON,MultiPolygon.class);
geoJsonTypeMap.put(GeoJsonTypes.TYPE_GEOMETRYCOLLECTION,GeometryCollection.class);
//extended geojson types
geoJsonTypeMap.put(GeoJsonTypes.TYPE_EXT_CIRCLE,Circle.class);
geoJsonTypeMap.put(GeoJsonTypes.TYPE_EXT_ELLIPSE,Ellipse.class);
geoJsonTypeMap.put(GeoJsonTypes.TYPE_EXT_RECTANGLE,Rectangle.class);
geoJsonTypeMap.put(GeoJsonTypes.TYPE_EXT_SECTOR,Sector.class);
}
public static GeoJSON create(String json) {
JSONObject node = JSON.parseObject(json);
return create(node);
}
/**
* jsonFeatureCollection
* @param json
* @return
*/
public static FeatureCollection[] createFeatureCollectionArray(String json) {
JSONArray node = JSON.parseArray(json);
int size = node.size();
FeatureCollection[] result = new FeatureCollection[size];
for (int i = 0; i < size; i++) {
result[i] = ((FeatureCollection) create(((JSONObject) node.get(i))));
}
return result;
}
/**
* jsonFeature
* @param json
* @return
*/
public static Feature[] createFeatureArray(String json) {
JSONArray node = JSON.parseArray(json);
int size = node.size();
Feature[] result = new Feature[size];
for (int i = 0; i < size; i++) {
GeoJSON geojson = create(((JSONObject) node.get(i)));
if (geojson instanceof Geometry) {
result[i] = new Feature(((Geometry) geojson));
} else {
result[i] = ((Feature) geojson);
}
}
return result;
}
/**
* jsonGeometry
* @param json
* @return
*/
public static Geometry[] createGeometryArray(String json) {
JSONArray node = JSON.parseArray(json);
int size = node.size();
Geometry[] result = new Geometry[size];
for (int i = 0; i < size; i++) {
GeoJSON geojson = create(((JSONObject) node.get(i)));
if (geojson instanceof Feature) {
result[i] = ((Feature) geojson).getGeometry();
} else {
result[i] = ((Geometry) geojson);
}
}
return result;
}
private static GeoJSON create(JSONObject node) {
String type = node.getString("type");
if ("FeatureCollection".equals(type)) {
return readFeatureCollection(node);
} else if ("Feature".equals(type)) {
return readFeature(node);
} else {
return readGeometry(node, type);
}
}
private static FeatureCollection readFeatureCollection(JSONObject node) {
JSONArray jFeatures = node.getJSONArray("features");
JSONObject crsJson = node.getJSONObject("crs");
CRS crs = null;
if (crsJson != null) {
crs = JSON.toJavaObject(crsJson, CRS.class);
}
if (jFeatures == null) {
//return a empty FeatureCollection
FeatureCollection result = new FeatureCollection();
result.setCrs(crs);
result.setFeatures(new Feature[0]);
return result;
}
int size = jFeatures.size();
Feature[] features = new Feature[size];
for (int i=0;i<size;i++) {
features[i] = readFeature(jFeatures.getJSONObject(i));
}
FeatureCollection result = new FeatureCollection();
result.setCrs(crs);
result.setFeatures(features);
return result;
}
private static Feature readFeature(JSONObject node) {
JSONObject geoJ = node.getJSONObject("geometry");
Geometry geo = null;
if (geoJ != null) {
geo = readGeometry(geoJ, geoJ.getString("type"));
}
node.remove("geometry");
Feature result = JSON.toJavaObject(node, Feature.class);
result.setGeometry(geo);
return result;
}
private static Geometry readGeometry(JSONObject node, String type) {
if (GeoJsonTypes.TYPE_GEOMETRYCOLLECTION.equals(type)) {
JSONObject crsJson = node.getJSONObject("crs");
CRS crs = null;
if (crsJson != null) {
crs = JSON.toJavaObject(crsJson, CRS.class);
}
GeometryCollection result = new GeometryCollection(new Geometry[0]);
result.setCrs(crs);
JSONArray jGeos = node.getJSONArray("geometries");
if (jGeos != null) {
int size = jGeos.size();
Geometry[] geometries = new Geometry[size];
for (int i=0;i<size;i++) {
JSONObject jgeo = jGeos.getJSONObject(i);
geometries[i] = readGeometry(jgeo, jgeo.getString("type"));
}
result.setGeometries(geometries);
} else {
//return a empty GeometryCollection
result.setGeometries(new Geometry[0]);
}
return result;
}
Class clazz = getGeoJsonType(type);
Object obj = JSON.toJavaObject(node, clazz);
return ((Geometry) obj);
}
public static Class getGeoJsonType(String type) {
Class clazz = geoJsonTypeMap.get(type);
return clazz;
}
}
|
package com.ociweb.gl.api;
import java.util.concurrent.atomic.AtomicBoolean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.ociweb.gl.impl.BuilderImpl;
import com.ociweb.gl.impl.PubSubMethodListenerBase;
import com.ociweb.gl.impl.schema.IngressMessages;
import com.ociweb.gl.impl.schema.MessagePrivate;
import com.ociweb.gl.impl.schema.MessagePubSub;
import com.ociweb.gl.impl.schema.MessageSubscription;
import com.ociweb.gl.impl.schema.TrafficOrderSchema;
import com.ociweb.gl.impl.stage.PublishPrivateTopics;
import com.ociweb.pronghorn.network.ClientCoordinator;
import com.ociweb.pronghorn.network.config.HTTPContentType;
import com.ociweb.pronghorn.network.config.HTTPRevisionDefaults;
import com.ociweb.pronghorn.network.module.AbstractAppendablePayloadResponseStage;
import com.ociweb.pronghorn.network.schema.ClientHTTPRequestSchema;
import com.ociweb.pronghorn.network.schema.ServerResponseSchema;
import com.ociweb.pronghorn.pipe.ChannelReader;
import com.ociweb.pronghorn.pipe.DataInputBlobReader;
import com.ociweb.pronghorn.pipe.DataOutputBlobWriter;
import com.ociweb.pronghorn.pipe.FieldReferenceOffsetManager;
import com.ociweb.pronghorn.pipe.Pipe;
import com.ociweb.pronghorn.pipe.PipeConfig;
import com.ociweb.pronghorn.pipe.PipeConfigManager;
import com.ociweb.pronghorn.pipe.PipeWriter;
import com.ociweb.pronghorn.pipe.RawDataSchema;
import com.ociweb.pronghorn.stage.scheduling.GraphManager;
import com.ociweb.pronghorn.util.Appendables;
import com.ociweb.pronghorn.util.BloomFilter;
import com.ociweb.pronghorn.util.TrieParserReader;
import com.ociweb.pronghorn.util.field.MessageConsumer;
/**
* Represents a dedicated channel for communicating with a single device
* or resource on an IoT system.
*/
public class MsgCommandChannel<B extends BuilderImpl> {
private final static Logger logger = LoggerFactory.getLogger(MsgCommandChannel.class);
private boolean isInit = false;
private Pipe<TrafficOrderSchema> goPipe;
///////////////////////////All the known data pipes
private Pipe<MessagePubSub> messagePubSub;
private Pipe<ClientHTTPRequestSchema> httpRequest;
private Pipe<ServerResponseSchema>[] netResponse;
public TrieParserReader unScopedReader = null; //only build when needed in this instance.
private final byte[] track;
private Pipe<MessagePubSub>[] exclusivePubSub;
private static final byte[] RETURN_NEWLINE = "\r\n".getBytes();
private int lastResponseWriterFinished = 1;//starting in the "end" state
private String[] exclusiveTopics = new String[0];
protected AtomicBoolean aBool = new AtomicBoolean(false);
protected static final long MS_TO_NS = 1_000_000;
private Behavior listener;
//TODO: add GreenService class for getting API specific objects.
public static final int DYNAMIC_MESSAGING = 1<<0;
public static final int STATE_MACHINE = DYNAMIC_MESSAGING;//state machine is based on DYNAMIC_MESSAGING;
public static final int NET_REQUESTER = 1<<1;
public static final int NET_RESPONDER = 1<<2;
public static final int USE_DELAY = 1<<3;
public static final int ALL = DYNAMIC_MESSAGING | NET_REQUESTER | NET_RESPONDER;
protected final B builder;
public int maxHTTPContentLength;
protected Pipe<?>[] optionalOutputPipes;
public int initFeatures; //this can be modified up to the moment that we build the pipes.
private PublishPrivateTopics publishPrivateTopics;
protected PipeConfigManager pcm;
private final int parallelInstanceId;
public MsgCommandChannel(GraphManager gm, B hardware,
int parallelInstanceId,
PipeConfigManager pcm
) {
this(gm,hardware,ALL, parallelInstanceId, pcm);
}
public MsgCommandChannel(GraphManager gm, B builder,
int features,
int parallelInstanceId,
PipeConfigManager pcm
) {
this.initFeatures = features;//this is held so we can check at every method call that its configured right
this.builder = builder;
this.pcm = pcm;
this.parallelInstanceId = parallelInstanceId;
this.track = parallelInstanceId<0 ? null : trackNameBuilder(parallelInstanceId);
}
//common method for building topic suffix
static byte[] trackNameBuilder(int parallelInstanceId) {
return ('/'+Integer.toString(parallelInstanceId)).getBytes();
}
public boolean hasRoomFor(int messageCount) {
return null==goPipe || Pipe.hasRoomForWrite(goPipe,
FieldReferenceOffsetManager.maxFragmentSize(Pipe.from(goPipe))*messageCount);
}
public boolean hasRoomForHTTP(int messageCount) {
return Pipe.hasRoomForWrite(httpRequest,
FieldReferenceOffsetManager.maxFragmentSize(Pipe.from(httpRequest))*messageCount);
}
public void ensureDynamicMessaging() {
if (isInit) {
throw new UnsupportedOperationException("Too late, ensureDynamicMessaging method must be called in define behavior.");
}
this.initFeatures |= DYNAMIC_MESSAGING;
}
public void ensureDynamicMessaging(int queueLength, int maxMessageSize) {
if (isInit) {
throw new UnsupportedOperationException("Too late, ensureDynamicMessaging method must be called in define behavior.");
}
growCommandCountRoom(queueLength);
this.initFeatures |= DYNAMIC_MESSAGING;
pcm.ensureSize(MessagePubSub.class, queueLength, maxMessageSize);
//also ensure consumers have pipes which can consume this.
pcm.ensureSize(MessageSubscription.class, queueLength, maxMessageSize);
//IngressMessages Confirm that MQTT ingress is big enough as well
pcm.ensureSize(IngressMessages.class, queueLength, maxMessageSize);
}
public static boolean isTooSmall(int queueLength, int maxMessageSize, PipeConfig<?> config) {
return queueLength>config.minimumFragmentsOnPipe() || maxMessageSize>config.maxVarLenSize();
}
public void ensureHTTPClientRequesting() {
if (isInit) {
throw new UnsupportedOperationException("Too late, ensureHTTPClientRequesting method must be called in define behavior.");
}
this.initFeatures |= NET_REQUESTER;
}
public void ensureHTTPClientRequesting(int queueLength, int maxMessageSize) {
if (isInit) {
throw new UnsupportedOperationException("Too late, ensureHTTPClientRequesting method must be called in define behavior.");
}
growCommandCountRoom(queueLength);
this.initFeatures |= NET_REQUESTER;
pcm.ensureSize(ClientHTTPRequestSchema.class, queueLength, maxMessageSize);
}
public void ensureDelaySupport() {
if (isInit) {
throw new UnsupportedOperationException("Too late, ensureDelaySupport method must be called in define behavior.");
}
this.initFeatures |= USE_DELAY;
}
public void ensureHTTPServerResponse() {
if (isInit) {
throw new UnsupportedOperationException("Too late, ensureHTTPServerResponse method must be called in define behavior.");
}
this.initFeatures |= NET_RESPONDER;
}
public void ensureHTTPServerResponse(int queueLength, int maxMessageSize) {
if (isInit) {
throw new UnsupportedOperationException("Too late, ensureHTTPServerResponse method must be called in define behavior.");
}
growCommandCountRoom(queueLength);
this.initFeatures |= NET_RESPONDER;
pcm.ensureSize(ServerResponseSchema.class, queueLength, maxMessageSize);
}
protected void growCommandCountRoom(int count) {
if (isInit) {
throw new UnsupportedOperationException("Too late, growCommandCountRoom method must be called in define behavior.");
}
PipeConfig<TrafficOrderSchema> goConfig = this.pcm.getConfig(TrafficOrderSchema.class);
this.pcm.addConfig(count + goConfig.minimumFragmentsOnPipe(), 0, TrafficOrderSchema.class);
}
@SuppressWarnings("unchecked")
private void buildAllPipes() {
if (!isInit) {
isInit = true;
this.messagePubSub = ((this.initFeatures & DYNAMIC_MESSAGING) == 0) ? null : newPubSubPipe(pcm.getConfig(MessagePubSub.class), builder);
this.httpRequest = ((this.initFeatures & NET_REQUESTER) == 0) ? null : newNetRequestPipe(pcm.getConfig(ClientHTTPRequestSchema.class), builder);
//when looking at features that requires cops, eg go pipes we ignore
//the following since they do not use cops but are features;
int filteredFeatures = this.initFeatures;
if (0!=(NET_RESPONDER&filteredFeatures)) {
filteredFeatures ^= NET_RESPONDER;
}
int featuresCount = Integer.bitCount(filteredFeatures);
if (featuresCount>1 || featuresCount==USE_DELAY) {
this.goPipe = newGoPipe(pcm.getConfig(TrafficOrderSchema.class));
} else {
assert(null==goPipe);
}
//build pipes for sending out the REST server responses
Pipe<ServerResponseSchema>[] netResponse = null;
if ((this.initFeatures & NET_RESPONDER) != 0) {
//int parallelInstanceId = hardware.ac
if (-1 == parallelInstanceId) {
//we have only a single instance of this object so we must have 1 pipe for each parallel track
int p = builder.parallelTracks();
netResponse = ( Pipe<ServerResponseSchema>[])new Pipe[p];
while (--p>=0) {
netResponse[p] = builder.newNetResponsePipe(pcm.getConfig(ServerResponseSchema.class), p);
}
} else {
//we have multiple instances of this object so each only has 1 pipe
netResponse = ( Pipe<ServerResponseSchema>[])new Pipe[1];
netResponse[0] = builder.newNetResponsePipe(pcm.getConfig(ServerResponseSchema.class), parallelInstanceId);
}
}
this.netResponse = netResponse;
if (null != this.netResponse) {
int x = this.netResponse.length;
while(--x>=0) {
if (!Pipe.isInit(netResponse[x])) {
//hack for now.
netResponse[x].initBuffers();
}
}
}
int e = this.exclusiveTopics.length;
this.exclusivePubSub = (Pipe<MessagePubSub>[])new Pipe[e];
while (--e>=0) {
exclusivePubSub[e] = newPubSubPipe(pcm.getConfig(MessagePubSub.class), builder);
}
int temp = 0;
if (null!=netResponse && netResponse.length>0) {
int x = netResponse.length;
int min = Integer.MAX_VALUE;
while (--x>=0) {
min = Math.min(min, netResponse[x].maxVarLen);
}
temp= min;
}
this.maxHTTPContentLength = temp;
}
}
protected boolean goHasRoom() {
return null==goPipe || PipeWriter.hasRoomForWrite(goPipe);
}
public Pipe<?>[] getOutputPipes() {
//we wait till this last possible moment before building.
buildAllPipes();
int length = 0;
if (null != messagePubSub) { //Index needed plust i2c index needed.
length++;
}
if (null != httpRequest) {
length++;
}
if (null != netResponse) {
length+=netResponse.length;
}
boolean hasGoSpace = false;
if (length>0) {//last count for go pipe
length++;
hasGoSpace = true;
}
length += exclusivePubSub.length;
if (null!=optionalOutputPipes) {
length+=optionalOutputPipes.length;
}
if (null!=publishPrivateTopics) {
length+=publishPrivateTopics.count();
}
int idx = 0;
Pipe<?>[] results = new Pipe[length];
System.arraycopy(exclusivePubSub, 0, results, 0, exclusivePubSub.length);
idx+=exclusivePubSub.length;
if (null != messagePubSub) {
results[idx++] = messagePubSub;
}
if (null != httpRequest) {
results[idx++] = httpRequest;
}
if (null != netResponse) {
System.arraycopy(netResponse, 0, results, idx, netResponse.length);
idx+=netResponse.length;
}
if (null!=optionalOutputPipes) {
System.arraycopy(optionalOutputPipes, 0, results, idx, optionalOutputPipes.length);
idx+=optionalOutputPipes.length;
}
if (null!=publishPrivateTopics) {
publishPrivateTopics.copyPipes(results, idx);
idx+=publishPrivateTopics.count();
}
if (hasGoSpace) {//last pipe for go, may be null
results[idx++] = goPipe;
}
return results;
}
private static <B extends BuilderImpl> Pipe<MessagePubSub> newPubSubPipe(PipeConfig<MessagePubSub> config, B builder) {
//TODO: need to create these pipes with constants for the topics we can avoid the copy...
// this will add a new API where a constant can be used instead of a topic string...
// in many cases this change will double the throughput or do even better.
if (builder.isAllPrivateTopics()) {
return null;
} else {
return new Pipe<MessagePubSub>(config) {
@Override
protected DataOutputBlobWriter<MessagePubSub> createNewBlobWriter() {
return new PubSubWriter(this);
}
};
}
}
private static <B extends BuilderImpl> Pipe<ClientHTTPRequestSchema> newNetRequestPipe(PipeConfig<ClientHTTPRequestSchema> config, B builder) {
return new Pipe<ClientHTTPRequestSchema>(config) {
@Override
protected DataOutputBlobWriter<ClientHTTPRequestSchema> createNewBlobWriter() {
return new PayloadWriter<ClientHTTPRequestSchema>(this);
}
};
}
private Pipe<TrafficOrderSchema> newGoPipe(PipeConfig<TrafficOrderSchema> goPipeConfig) {
return new Pipe<TrafficOrderSchema>(goPipeConfig);
}
public static void setListener(MsgCommandChannel<?> c, Behavior listener) {
if (null != c.listener && c.listener!=listener) {
throw new UnsupportedOperationException("Bad Configuration, A CommandChannel can only be held and used by a single listener lambda/class");
}
c.listener = listener;
}
protected boolean enterBlockOk() {
return aBool.compareAndSet(false, true);
}
protected boolean exitBlockOk() {
return aBool.compareAndSet(true, false);
}
public final boolean shutdown() {
assert(enterBlockOk()) : "Concurrent usage error, ensure this never called concurrently";
try {
if (goHasRoom()) {
if (null!=goPipe) {
PipeWriter.publishEOF(this.goPipe);
} else {
//must find one of these outputs to shutdown
if (!sentEOF(messagePubSub)) {
if (!sentEOF(httpRequest)) {
if (!sentEOF(netResponse)) {
if (!sentEOFPrivate()) {
secondShutdownMsg();
}
}
}
}
}
return true;
} else {
return false;
}
} finally {
assert(exitBlockOk()) : "Concurrent usage error, ensure this never called concurrently";
}
}
//can be overridden to add shutdown done by another service.
protected void secondShutdownMsg() {
//if pubsub or request or response is supported any can be used for shutdown
logger.warn("Unable to shutdown, no supported services found...");
}
private boolean sentEOFPrivate() {
boolean ok = false;
if (null!=publishPrivateTopics) {
int c = publishPrivateTopics.count();
while (--c>=0) {
Pipe.publishEOF(publishPrivateTopics.getPipe(c));
ok = true;
}
}
return ok;
}
protected boolean sentEOF(Pipe<?> pipe) {
if (null!=pipe) {
PipeWriter.publishEOF(pipe);
return true;
} else {
return false;
}
}
protected boolean sentEOF(Pipe<?>[] pipes) {
if (null != pipes) {
int i = pipes.length;
while (--i>=0) {
if (null!=pipes[i]) {
PipeWriter.publishEOF(pipes[i]);
return true;
}
}
}
return false;
}
@Deprecated
public boolean block(long durationNanos) {
return delay(durationNanos);
}
@Deprecated
public boolean blockUntil(long msTime) {
return delayUntil(msTime);
}
/**
* Causes this channel to delay processing any actions until the specified
* amount of time has elapsed.
*
* @param durationNanos Nanos to delay
*
* @return True if blocking was successful, and false otherwise.
*/
public boolean delay(long durationNanos) {
assert(enterBlockOk()) : "Concurrent usage error, ensure this never called concurrently";
try {
if (goHasRoom()) {
MsgCommandChannel.publishBlockChannel(durationNanos, this);
return true;
} else {
return false;
}
} finally {
assert(exitBlockOk()) : "Concurrent usage error, ensure this never called concurrently";
}
}
/**
* Causes this channel to delay processing any actions
* until the specified UNIX time is reached.
*
* @return True if blocking was successful, and false otherwise.
*/
public boolean delayUntil(long msTime) {
assert(enterBlockOk()) : "Concurrent usage error, ensure this never called concurrently";
try {
if (goHasRoom()) {
MsgCommandChannel.publishBlockChannelUntil(msTime, this);
return true;
} else {
return false;
}
} finally {
assert(exitBlockOk()) : "Concurrent usage error, ensure this never called concurrently";
}
}
//TODO: update the httpRequest to use the low level API.
public boolean httpGet(ClientHostPortInstance session, CharSequence route) {
return httpGet(session,route,null);
}
public boolean httpGet(ClientHostPortInstance session, CharSequence route, HeaderWritable headers) {
int routeId = session.uniqueId;
assert(builder.getHTTPClientConfig() != null);
assert((this.initFeatures & NET_REQUESTER)!=0) : "must turn on NET_REQUESTER to use this method";
//get the cached connection ID so we need not deal with the host again
if (session.getConnectionId()<0) {
final long id = builder.getClientCoordinator().lookup(
ClientCoordinator.lookupHostId(session.host),
session.port,
session.sessionId);
if (id>=0) {
session.setConnectionId(id);
}
}
if ((null==goPipe || PipeWriter.hasRoomForWrite(goPipe))) {
if (session.getConnectionId()<0) {
if (PipeWriter.tryWriteFragment(httpRequest, ClientHTTPRequestSchema.MSG_HTTPGET_100)) {
int pipeId = builder.lookupHTTPClientPipe(routeId);
PipeWriter.writeInt(httpRequest, ClientHTTPRequestSchema.MSG_HTTPGET_100_FIELD_DESTINATION_11, pipeId);
PipeWriter.writeInt(httpRequest, ClientHTTPRequestSchema.MSG_HTTPGET_100_FIELD_SESSION_10, session.sessionId);
PipeWriter.writeInt(httpRequest, ClientHTTPRequestSchema.MSG_HTTPGET_100_FIELD_PORT_1, session.port);
PipeWriter.writeBytes(httpRequest, ClientHTTPRequestSchema.MSG_HTTPGET_100_FIELD_HOST_2, session.hostBytes);
PipeWriter.writeUTF8(httpRequest, ClientHTTPRequestSchema.MSG_HTTPGET_100_FIELD_PATH_3, route);
DataOutputBlobWriter<ClientHTTPRequestSchema> hw = Pipe.outputStream(httpRequest);
DataOutputBlobWriter.openField(hw);
if (null!=headers) {
headers.write(headerWriter.target(hw));
}
hw.closeHighLevelField(ClientHTTPRequestSchema.MSG_HTTPGET_100_FIELD_HEADERS_7);
PipeWriter.publishWrites(httpRequest);
publishGo(1, builder.netIndex(), this);
return true;
}
} else {
if (PipeWriter.tryWriteFragment(httpRequest, ClientHTTPRequestSchema.MSG_FASTHTTPGET_200)) {
int pipeId = builder.lookupHTTPClientPipe(routeId);
PipeWriter.writeInt(httpRequest, ClientHTTPRequestSchema.MSG_FASTHTTPGET_200_FIELD_DESTINATION_11, pipeId);
PipeWriter.writeInt(httpRequest, ClientHTTPRequestSchema.MSG_FASTHTTPGET_200_FIELD_SESSION_10, session.sessionId);
PipeWriter.writeInt(httpRequest, ClientHTTPRequestSchema.MSG_FASTHTTPGET_200_FIELD_PORT_1, session.port);
PipeWriter.writeBytes(httpRequest, ClientHTTPRequestSchema.MSG_FASTHTTPGET_200_FIELD_HOST_2, session.hostBytes);
PipeWriter.writeLong(httpRequest, ClientHTTPRequestSchema.MSG_FASTHTTPGET_200_FIELD_CONNECTIONID_20, session.getConnectionId());
PipeWriter.writeUTF8(httpRequest, ClientHTTPRequestSchema.MSG_FASTHTTPGET_200_FIELD_PATH_3, route);
DataOutputBlobWriter<ClientHTTPRequestSchema> hw = Pipe.outputStream(httpRequest);
DataOutputBlobWriter.openField(hw);
if (null!=headers) {
headers.write(headerWriter.target(hw));
}
hw.closeHighLevelField(ClientHTTPRequestSchema.MSG_FASTHTTPGET_200_FIELD_HEADERS_7);
PipeWriter.publishWrites(httpRequest);
publishGo(1, builder.netIndex(), this);
return true;
}
}
}
return false;
}
public boolean httpClose(ClientHostPortInstance session) {
assert(builder.getHTTPClientConfig() != null);
assert((this.initFeatures & NET_REQUESTER)!=0) : "must turn on NET_REQUESTER to use this method";
if ((null==goPipe || PipeWriter.hasRoomForWrite(goPipe))
&& PipeWriter.tryWriteFragment(httpRequest, ClientHTTPRequestSchema.MSG_CLOSE_104)) {
PipeWriter.writeInt(httpRequest, ClientHTTPRequestSchema.MSG_CLOSE_104_FIELD_SESSION_10, session.sessionId);
PipeWriter.writeInt(httpRequest, ClientHTTPRequestSchema.MSG_CLOSE_104_FIELD_PORT_1, session.port);
PipeWriter.writeBytes(httpRequest, ClientHTTPRequestSchema.MSG_CLOSE_104_FIELD_HOST_2, session.hostBytes);
PipeWriter.publishWrites(httpRequest);
publishGo(1, builder.netIndex(), this);
return true;
}
return false;
}
private final HeaderWriter headerWriter = new HeaderWriter();//used in each post call.
public boolean httpPost(ClientHostPortInstance session, CharSequence route, Writable payload) {
return httpPost(session, route, null, payload);
}
public boolean httpPost(ClientHostPortInstance session, CharSequence route, HeaderWritable headers, Writable payload) {
int routeId = session.uniqueId;
assert((this.initFeatures & NET_REQUESTER)!=0) : "must turn on NET_REQUESTER to use this method";
if ((null==goPipe || PipeWriter.hasRoomForWrite(goPipe))
&& PipeWriter.tryWriteFragment(httpRequest, ClientHTTPRequestSchema.MSG_HTTPPOST_101)) {
int pipeId = builder.lookupHTTPClientPipe(routeId);
//TODO: note many routes may all go to the same pipe so where is JSON extraction?
PipeWriter.writeInt(httpRequest, ClientHTTPRequestSchema.MSG_HTTPPOST_101_FIELD_DESTINATION_11, pipeId);
PipeWriter.writeInt(httpRequest, ClientHTTPRequestSchema.MSG_HTTPPOST_101_FIELD_SESSION_10, session.sessionId);
PipeWriter.writeInt(httpRequest, ClientHTTPRequestSchema.MSG_HTTPPOST_101_FIELD_PORT_1, session.port);
PipeWriter.writeBytes(httpRequest, ClientHTTPRequestSchema.MSG_HTTPPOST_101_FIELD_HOST_2, session.hostBytes);
PipeWriter.writeUTF8(httpRequest, ClientHTTPRequestSchema.MSG_HTTPPOST_101_FIELD_PATH_3, route);
DataOutputBlobWriter<ClientHTTPRequestSchema> hw = Pipe.outputStream(httpRequest);
DataOutputBlobWriter.openField(hw);
if (null!=headers) {
headers.write(headerWriter.target(hw));
}
hw.closeHighLevelField(ClientHTTPRequestSchema.MSG_HTTPPOST_101_FIELD_HEADERS_7);
DataOutputBlobWriter<ClientHTTPRequestSchema> pw = Pipe.outputStream(httpRequest);
DataOutputBlobWriter.openField(pw);
payload.write(pw);
pw.closeHighLevelField(ClientHTTPRequestSchema.MSG_HTTPPOST_101_FIELD_PAYLOAD_5);
PipeWriter.publishWrites(httpRequest);
publishGo(1, builder.netIndex(), this);
return true;
}
return false;
}
/**
* Subscribes the listener associated with this command channel to
* a topic.
*
* @param topic Topic to subscribe to.
*
* @return True if the topic was successfully subscribed to, and false
* otherwise.
*/
public boolean subscribe(CharSequence topic) {
assert((0 != (initFeatures & DYNAMIC_MESSAGING))) : "CommandChannel must be created with DYNAMIC_MESSAGING flag";
if (null==listener) {
throw new UnsupportedOperationException("Can not subscribe before startup. Call addSubscription when registering listener.");
}
return subscribe(topic, (PubSubMethodListenerBase)listener);
}
/**
* Subscribes a listener to a topic on this command channel.
*
* @param topic Topic to subscribe to.
* @param listener Listener to subscribe.
*
* @return True if the topic was successfully subscribed to, and false
* otherwise.
*/
public boolean subscribe(CharSequence topic, PubSubMethodListenerBase listener) {
assert((0 != (initFeatures & DYNAMIC_MESSAGING))) : "CommandChannel must be created with DYNAMIC_MESSAGING flag";
if ((null==goPipe || PipeWriter.hasRoomForWrite(goPipe))
&& PipeWriter.tryWriteFragment(messagePubSub, MessagePubSub.MSG_SUBSCRIBE_100)) {
PipeWriter.writeInt(messagePubSub, MessagePubSub.MSG_SUBSCRIBE_100_FIELD_SUBSCRIBERIDENTITYHASH_4, System.identityHashCode(listener));
//OLD -- PipeWriter.writeUTF8(messagePubSub, MessagePubSub.MSG_SUBSCRIBE_100_FIELD_TOPIC_1, topic);
DataOutputBlobWriter<MessagePubSub> output = PipeWriter.outputStream(messagePubSub);
output.openField();
output.append(topic);
publicTrackedTopicSuffix(this, output);
output.closeHighLevelField(MessagePubSub.MSG_SUBSCRIBE_100_FIELD_TOPIC_1);
PipeWriter.publishWrites(messagePubSub);
builder.releasePubSubTraffic(1, this);
return true;
}
return false;
}
/**
* Unsubscribes the listener associated with this command channel from
* a topic.
*
* @param topic Topic to unsubscribe from.
*
* @return True if the topic was successfully unsubscribed from, and false otherwise.
*/
public boolean unsubscribe(CharSequence topic) {
assert((0 != (initFeatures & DYNAMIC_MESSAGING))) : "CommandChannel must be created with DYNAMIC_MESSAGING flag";
return unsubscribe(topic, (PubSubMethodListenerBase)listener);
}
/**
* Unsubscribes a listener from a topic.
*
* @param topic Topic to unsubscribe from.
* @param listener Listener to unsubscribe.
*
* @return True if the topic was successfully unsubscribed from, and false otherwise.
*/
public boolean unsubscribe(CharSequence topic, PubSubMethodListenerBase listener) {
assert((0 != (initFeatures & DYNAMIC_MESSAGING))) : "CommandChannel must be created with DYNAMIC_MESSAGING flag";
if ((null==goPipe || PipeWriter.hasRoomForWrite(goPipe))
&& PipeWriter.tryWriteFragment(messagePubSub, MessagePubSub.MSG_UNSUBSCRIBE_101)) {
PipeWriter.writeInt(messagePubSub, MessagePubSub.MSG_SUBSCRIBE_100_FIELD_SUBSCRIBERIDENTITYHASH_4, System.identityHashCode(listener));
//OLD PipeWriter.writeUTF8(messagePubSub, MessagePubSub.MSG_UNSUBSCRIBE_101_FIELD_TOPIC_1, topic);
DataOutputBlobWriter<MessagePubSub> output = PipeWriter.outputStream(messagePubSub);
output.openField();
output.append(topic);
publicTrackedTopicSuffix(this, output);
output.closeHighLevelField(MessagePubSub.MSG_UNSUBSCRIBE_101_FIELD_TOPIC_1);
PipeWriter.publishWrites(messagePubSub);
builder.releasePubSubTraffic(1, this);
return true;
}
return false;
}
/**
* Changes the state of this command channel's state machine.
*
* @param state State to transition to.
*
* @return True if the state was successfully transitioned, and false otherwise.
*/
public <E extends Enum<E>> boolean changeStateTo(E state) {
assert((0 != (initFeatures & DYNAMIC_MESSAGING))) : "CommandChannel must be created with DYNAMIC_MESSAGING flag";
assert(builder.isValidState(state));
if (!builder.isValidState(state)) {
throw new UnsupportedOperationException("no match "+state.getClass());
}
if ((null==goPipe || PipeWriter.hasRoomForWrite(goPipe))
&& PipeWriter.tryWriteFragment(messagePubSub, MessagePubSub.MSG_CHANGESTATE_70)) {
PipeWriter.writeInt(messagePubSub, MessagePubSub.MSG_CHANGESTATE_70_FIELD_ORDINAL_7, state.ordinal());
PipeWriter.publishWrites(messagePubSub);
builder.releasePubSubTraffic(1, this);
return true;
}
return false;
}
public void presumePublishTopic(CharSequence topic, Writable writable) {
presumePublishTopic(topic, writable, WaitFor.All);
}
public void presumePublishTopic(CharSequence topic, Writable writable, WaitFor ap) {
assert((0 != (initFeatures & DYNAMIC_MESSAGING))) : "CommandChannel must be created with DYNAMIC_MESSAGING flag";
if (publishTopic(topic, writable, ap)) {
return;
} else {
logger.warn("unable to publish on topic {} must wait.",topic);
while (!publishTopic(topic, writable, ap)) {
Thread.yield();
}
}
}
public boolean publishTopic(CharSequence topic, Writable writable) {
return publishTopic(topic, writable, WaitFor.All);
}
/**
* Opens a topic on this channel for writing.
*
* @param topic Topic to open.
*
* @return {@link PayloadWriter} attached to the given topic.
*/
public boolean publishTopic(CharSequence topic, Writable writable, WaitFor ap) {
assert((0 != (initFeatures & DYNAMIC_MESSAGING))) : "CommandChannel must be created with DYNAMIC_MESSAGING flag";
assert(writable != null);
int token = null==publishPrivateTopics ? -1 : publishPrivateTopics.getToken(topic);
if (token>=0) {
return publishOnPrivateTopic(token, writable);
} else {
if ((null==goPipe || PipeWriter.hasRoomForWrite(goPipe)) &&
PipeWriter.tryWriteFragment(messagePubSub, MessagePubSub.MSG_PUBLISH_103)) {
PipeWriter.writeInt(messagePubSub, MessagePubSub.MSG_PUBLISH_103_FIELD_QOS_5, ap.policy());
//PipeWriter.writeUTF8(messagePubSub, MessagePubSub.MSG_PUBLISH_103_FIELD_TOPIC_1, topic);
DataOutputBlobWriter<MessagePubSub> output = PipeWriter.outputStream(messagePubSub);
output.openField();
output.append(topic);
publicTrackedTopicSuffix(this, output);
output.closeHighLevelField(MessagePubSub.MSG_PUBLISH_103_FIELD_TOPIC_1);
PubSubWriter pw = (PubSubWriter) Pipe.outputStream(messagePubSub);
DataOutputBlobWriter.openField(pw);
writable.write(pw);
DataOutputBlobWriter.closeHighLevelField(pw, MessagePubSub.MSG_PUBLISH_103_FIELD_PAYLOAD_3);
PipeWriter.publishWrites(messagePubSub);
publishGo(1,builder.pubSubIndex(), this);
return true;
} else {
return false;
}
}
}
public FailableWrite publishFailableTopic(CharSequence topic, FailableWritable writable) {
return publishFailableTopic(topic, writable, WaitFor.All);
}
public FailableWrite publishFailableTopic(CharSequence topic, FailableWritable writable, WaitFor ap) {
assert((0 != (initFeatures & DYNAMIC_MESSAGING))) : "CommandChannel must be created with DYNAMIC_MESSAGING flag";
assert(writable != null);
int token = null==publishPrivateTopics ? -1 : publishPrivateTopics.getToken(topic);
if (token>=0) {
return publishFailableOnPrivateTopic(token, writable);
} else {
if ((null==goPipe || PipeWriter.hasRoomForWrite(goPipe)) && PipeWriter.hasRoomForWrite(messagePubSub)) {
PubSubWriter pw = (PubSubWriter) Pipe.outputStream(messagePubSub);
DataOutputBlobWriter.openField(pw);
FailableWrite result = writable.write(pw);
if (result == FailableWrite.Cancel) {
messagePubSub.closeBlobFieldWrite();
}
else {
PipeWriter.presumeWriteFragment(messagePubSub, MessagePubSub.MSG_PUBLISH_103);
PipeWriter.writeInt(messagePubSub, MessagePubSub.MSG_PUBLISH_103_FIELD_QOS_5, ap.policy());
DataOutputBlobWriter<MessagePubSub> output = PipeWriter.outputStream(messagePubSub);
output.openField();
output.append(topic);
publicTrackedTopicSuffix(this, output);
output.closeHighLevelField(MessagePubSub.MSG_PUBLISH_103_FIELD_TOPIC_1);
//OLD PipeWriter.writeUTF8(messagePubSub, MessagePubSub.MSG_PUBLISH_103_FIELD_TOPIC_1, topic);
DataOutputBlobWriter.closeHighLevelField(pw, MessagePubSub.MSG_PUBLISH_103_FIELD_PAYLOAD_3);
PipeWriter.publishWrites(messagePubSub);
publishGo(1, builder.pubSubIndex(), this);
}
return result;
} else {
return FailableWrite.Retry;
}
}
}
public boolean publishTopic(CharSequence topic) {
return publishTopic(topic, WaitFor.All);
}
public boolean publishTopic(CharSequence topic, WaitFor ap) {
assert((0 != (initFeatures & DYNAMIC_MESSAGING))) : "CommandChannel must be created with DYNAMIC_MESSAGING flag";
int token = null==publishPrivateTopics ? -1 : publishPrivateTopics.getToken(topic);
if (token>=0) {
return publishOnPrivateTopic(token);
} else {
if (null==messagePubSub) {
if (builder.isAllPrivateTopics()) {
throw new RuntimeException("Discovered non private topic '"+topic+"' but exclusive use of private topics was set on.");
} else {
throw new RuntimeException("Enable DYNAMIC_MESSAGING for this CommandChannel before publishing.");
}
}
if ((null==goPipe || PipeWriter.hasRoomForWrite(goPipe)) &&
PipeWriter.tryWriteFragment(messagePubSub, MessagePubSub.MSG_PUBLISH_103)) {
PipeWriter.writeInt(messagePubSub, MessagePubSub.MSG_PUBLISH_103_FIELD_QOS_5, ap.policy());
DataOutputBlobWriter<MessagePubSub> output = PipeWriter.outputStream(messagePubSub);
output.openField();
output.append(topic);
publicTrackedTopicSuffix(this, output);
output.closeHighLevelField(MessagePubSub.MSG_PUBLISH_103_FIELD_TOPIC_1);
////OLD: PipeWriter.writeUTF8(messagePubSub, MessagePubSub.MSG_PUBLISH_103_FIELD_TOPIC_1, topic);
PipeWriter.writeSpecialBytesPosAndLen(messagePubSub, MessagePubSub.MSG_PUBLISH_103_FIELD_PAYLOAD_3, -1, 0);
PipeWriter.publishWrites(messagePubSub);
publishGo(1,builder.pubSubIndex(), this);
return true;
} else {
return false;
}
}
}
private static final void publicTrackedTopicSuffix(MsgCommandChannel cmd, DataOutputBlobWriter<MessagePubSub> output) {
if (null==cmd.track) { //most command channels are assumed to be un tracked
//nothing to do.
} else {
trackedChannelSuffix(cmd, output);
}
}
private static void trackedChannelSuffix(MsgCommandChannel cmd, DataOutputBlobWriter<MessagePubSub> output) {
if (BuilderImpl.hasNoUnscopedTopics()) {//normal case where topics are scoped
output.write(cmd.track);
} else {
unScopedCheckForTrack(cmd, output);
}
}
private static void unScopedCheckForTrack(MsgCommandChannel cmd, DataOutputBlobWriter<MessagePubSub> output) {
boolean addSuffix=false;
if (null!=cmd.unScopedReader) {
//only do this if 1. we are tracked & 2. there are unscoped topics
addSuffix = BuilderImpl.notUnscoped(cmd.unScopedReader, output);
} else {
cmd.unScopedReader = new TrieParserReader(0, true);
//only do this if 1. we are tracked & 2. there are unscoped topics
addSuffix = BuilderImpl.notUnscoped(cmd.unScopedReader, output);
}
if (addSuffix) {
output.write(cmd.track);
}
}
public boolean publishTopic(byte[] topic, Writable writable) {
assert((0 != (initFeatures & DYNAMIC_MESSAGING))) : "CommandChannel must be created with DYNAMIC_MESSAGING flag";
assert(writable != null);
int token = null==publishPrivateTopics ? -1 : publishPrivateTopics.getToken(topic, 0, topic.length);
if (token>=0) {
return publishOnPrivateTopic(token, writable);
} else {
//should not be called when DYNAMIC_MESSAGING is not on.
//this is a public topic
if ((null==goPipe || PipeWriter.hasRoomForWrite(goPipe)) &&
PipeWriter.tryWriteFragment(messagePubSub, MessagePubSub.MSG_PUBLISH_103)) {
DataOutputBlobWriter<MessagePubSub> output = PipeWriter.outputStream(messagePubSub);
output.openField();
output.write(topic);
publicTrackedTopicSuffix(this, output);
output.closeHighLevelField(MessagePubSub.MSG_PUBLISH_103_FIELD_TOPIC_1);
//OLD PipeWriter.writeBytes(messagePubSub, MessagePubSub.MSG_PUBLISH_103_FIELD_TOPIC_1, topic);
PubSubWriter writer = (PubSubWriter) Pipe.outputStream(messagePubSub);
writer.openField(MessagePubSub.MSG_PUBLISH_103_FIELD_PAYLOAD_3,this);
writable.write(writer);
writer.publish();
publishGo(1,builder.pubSubIndex(), this);
return true;
} else {
return false;
}
}
}
public boolean publishTopic(byte[] topic) {
assert((0 != (initFeatures & DYNAMIC_MESSAGING))) : "CommandChannel must be created with DYNAMIC_MESSAGING flag";
int token = null==publishPrivateTopics ? -1 : publishPrivateTopics.getToken(topic, 0, topic.length);
if (token>=0) {
return publishOnPrivateTopic(token);
} else {
//should not be called when DYNAMIC_MESSAGING is not on.
//this is a public topic
if ((null==goPipe || PipeWriter.hasRoomForWrite(goPipe)) &&
PipeWriter.tryWriteFragment(messagePubSub, MessagePubSub.MSG_PUBLISH_103)) {
DataOutputBlobWriter<MessagePubSub> output = PipeWriter.outputStream(messagePubSub);
output.openField();
output.write(topic);
publicTrackedTopicSuffix(this, output);
output.closeHighLevelField(MessagePubSub.MSG_PUBLISH_103_FIELD_TOPIC_1);
//OLD PipeWriter.writeBytes(messagePubSub, MessagePubSub.MSG_PUBLISH_103_FIELD_TOPIC_1, topic);
PipeWriter.writeSpecialBytesPosAndLen(messagePubSub, MessagePubSub.MSG_PUBLISH_103_FIELD_PAYLOAD_3, -1, 0);
PipeWriter.publishWrites(messagePubSub);
publishGo(1,builder.pubSubIndex(), this);
return true;
} else {
return false;
}
}
}
private boolean publishOnPrivateTopic(int token, Writable writable) {
//this is a private topic
Pipe<MessagePrivate> output = publishPrivateTopics.getPipe(token);
if (PipeWriter.tryWriteFragment(output, MessagePrivate.MSG_PUBLISH_1)) {
DataOutputBlobWriter<MessagePrivate> writer = PipeWriter.outputStream(output);
DataOutputBlobWriter.openField(writer);
writable.write(writer);
DataOutputBlobWriter.closeHighLevelField(writer, MessagePrivate.MSG_PUBLISH_1_FIELD_PAYLOAD_3);
PipeWriter.publishWrites(output);
return true;
} else {
logPrivateTopicTooShort(token,output);
return false;
}
}
private FailableWrite publishFailableOnPrivateTopic(int token, FailableWritable writable) {
//this is a private topic
Pipe<MessagePrivate> output = publishPrivateTopics.getPipe(token);
if (PipeWriter.hasRoomForWrite(output)) {
DataOutputBlobWriter<MessagePrivate> writer = PipeWriter.outputStream(output);
DataOutputBlobWriter.openField(writer);
FailableWrite result = writable.write(writer);
if (result == FailableWrite.Cancel) {
output.closeBlobFieldWrite();
}
else {
PipeWriter.presumeWriteFragment(output, MessagePrivate.MSG_PUBLISH_1);
DataOutputBlobWriter.closeHighLevelField(writer, MessagePrivate.MSG_PUBLISH_1_FIELD_PAYLOAD_3);
PipeWriter.publishWrites(output);
}
return result;
} else {
return FailableWrite.Retry;
}
}
private boolean publishOnPrivateTopic(int token) {
//this is a private topic
Pipe<MessagePrivate> output = publishPrivateTopics.getPipe(token);
if (PipeWriter.tryWriteFragment(output, MessagePrivate.MSG_PUBLISH_1)) {
PipeWriter.writeSpecialBytesPosAndLen(output, MessagePrivate.MSG_PUBLISH_1_FIELD_PAYLOAD_3, -1, 0);
PipeWriter.publishWrites(output);
return true;
} else {
logPrivateTopicTooShort(token, output);
return false;
}
}
private final BloomFilter topicsTooShort = new BloomFilter(10000, .00001); //32K
private void logPrivateTopicTooShort(int token, Pipe<?> p) {
String topic = publishPrivateTopics.getTopic(token);
if (!topicsTooShort.mayContain(topic)) {
logger.info("full pipe {}",p);
logger.info("the private topic '{}' has become backed up, it may be too short. When it was defined it should be made to be longer.", topic);
topicsTooShort.addValue(topic);
}
}
public void presumePublishTopic(TopicWritable topic, Writable writable) {
presumePublishTopic(topic,writable,WaitFor.All);
}
public void presumePublishTopic(TopicWritable topic, Writable writable, WaitFor ap) {
assert((0 != (initFeatures & DYNAMIC_MESSAGING))) : "CommandChannel must be created with DYNAMIC_MESSAGING flag";
if (publishTopic(topic, writable, ap)) {
return;
} else {
logger.warn("unable to publish on topic {} must wait.",topic);
while (!publishTopic(topic, writable, ap)) {
Thread.yield();
}
}
}
public boolean publishTopic(TopicWritable topic, Writable writable) {
return publishTopic(topic, writable, WaitFor.All);
}
public boolean publishTopic(TopicWritable topic, Writable writable, WaitFor ap) {
assert((0 != (initFeatures & DYNAMIC_MESSAGING))) : "CommandChannel must be created with DYNAMIC_MESSAGING flag";
assert(writable != null);
int token = tokenForPrivateTopic(topic);
if (token>=0) {
return publishOnPrivateTopic(token, writable);
} else {
if ((null==goPipe || PipeWriter.hasRoomForWrite(goPipe)) &&
PipeWriter.tryWriteFragment(messagePubSub, MessagePubSub.MSG_PUBLISH_103)) {
PipeWriter.writeInt(messagePubSub, MessagePubSub.MSG_PUBLISH_103_FIELD_QOS_5, ap.policy());
PubSubWriter pw = (PubSubWriter) Pipe.outputStream(messagePubSub);
DataOutputBlobWriter.openField(pw);
topic.write(pw);
publicTrackedTopicSuffix(this, pw);
DataOutputBlobWriter.closeHighLevelField(pw, MessagePubSub.MSG_PUBLISH_103_FIELD_TOPIC_1);
DataOutputBlobWriter.openField(pw);
writable.write(pw);
DataOutputBlobWriter.closeHighLevelField(pw, MessagePubSub.MSG_PUBLISH_103_FIELD_PAYLOAD_3);
PipeWriter.publishWrites(messagePubSub);
publishGo(1,builder.pubSubIndex(), this);
return true;
} else {
return false;
}
}
}
private final int maxDynamicTopicLength = 128;
private Pipe<RawDataSchema> tempTopicPipe;
public boolean publishTopic(TopicWritable topic) {
return publishTopic(topic, WaitFor.All);
}
public boolean publishTopic(TopicWritable topic, WaitFor ap) {
assert((0 != (initFeatures & DYNAMIC_MESSAGING))) : "CommandChannel must be created with DYNAMIC_MESSAGING flag";
int token = tokenForPrivateTopic(topic);
if (token>=0) {
return publishOnPrivateTopic(token);
} else {
if ((null==goPipe || PipeWriter.hasRoomForWrite(goPipe)) &&
PipeWriter.tryWriteFragment(messagePubSub, MessagePubSub.MSG_PUBLISH_103)) {
PipeWriter.writeInt(messagePubSub, MessagePubSub.MSG_PUBLISH_103_FIELD_QOS_5, ap.policy());
PubSubWriter pw = (PubSubWriter) Pipe.outputStream(messagePubSub);
DataOutputBlobWriter.openField(pw);
topic.write(pw);
publicTrackedTopicSuffix(this, pw);
DataOutputBlobWriter.closeHighLevelField(pw, MessagePubSub.MSG_PUBLISH_103_FIELD_TOPIC_1);
PipeWriter.writeSpecialBytesPosAndLen(messagePubSub, MessagePubSub.MSG_PUBLISH_103_FIELD_PAYLOAD_3, -1, 0);
PipeWriter.publishWrites(messagePubSub);
publishGo(1,builder.pubSubIndex(), this);
return true;
} else {
return false;
}
}
}
private int tokenForPrivateTopic(TopicWritable topic) {
if (null==publishPrivateTopics) {
return -1;
}
if (null==tempTopicPipe) {
tempTopicPipe = RawDataSchema.instance.newPipe(2, maxDynamicTopicLength);
tempTopicPipe.initBuffers();
}
int size = Pipe.addMsgIdx(tempTopicPipe, RawDataSchema.MSG_CHUNKEDSTREAM_1);
DataOutputBlobWriter<RawDataSchema> output = Pipe.openOutputStream(tempTopicPipe);
topic.write(output);
DataOutputBlobWriter.closeLowLevelField(output);
Pipe.confirmLowLevelWrite(tempTopicPipe, size);
Pipe.publishWrites(tempTopicPipe);
Pipe.takeMsgIdx(tempTopicPipe);
int token = publishPrivateTopics.getToken(tempTopicPipe);
Pipe.confirmLowLevelRead(tempTopicPipe, size);
Pipe.releaseReadLock(tempTopicPipe);
return token;
}
public void presumePublishStructuredTopic(CharSequence topic, PubSubStructuredWritable writable) {
assert((0 != (initFeatures & DYNAMIC_MESSAGING))) : "CommandChannel must be created with DYNAMIC_MESSAGING flag";
if (publishStructuredTopic(topic, writable)) {
return;
} else {
logger.warn("unable to publish on topic {} must wait.",topic);
while (!publishStructuredTopic(topic, writable)) {
Thread.yield();
}
}
}
//returns consumed boolean
public boolean copyStructuredTopic(CharSequence topic,
ChannelReader reader,
MessageConsumer consumer) {
return copyStructuredTopic(topic, reader, consumer, WaitFor.All);
}
//returns consumed boolean
public boolean copyStructuredTopic(CharSequence topic,
ChannelReader inputReader,
MessageConsumer consumer,
WaitFor ap) {
DataInputBlobReader<?> reader = (DataInputBlobReader<?>)inputReader;
assert((0 != (initFeatures & DYNAMIC_MESSAGING))) : "CommandChannel must be created with DYNAMIC_MESSAGING flag";
int pos = reader.absolutePosition();
if (consumer.process(reader)) {
if ((null==goPipe || PipeWriter.hasRoomForWrite(goPipe))
&& PipeWriter.tryWriteFragment(messagePubSub, MessagePubSub.MSG_PUBLISH_103) ) {
PipeWriter.writeInt(messagePubSub, MessagePubSub.MSG_PUBLISH_103_FIELD_QOS_5, ap.policy());
PipeWriter.writeUTF8(messagePubSub, MessagePubSub.MSG_PUBLISH_103_FIELD_TOPIC_1, topic);
PubSubWriter pw = (PubSubWriter) Pipe.outputStream(messagePubSub);
DataOutputBlobWriter.openField(pw);
reader.absolutePosition(pos);//restore position as unread
//direct copy from one to the next
reader.readInto(pw, reader.available());
DataOutputBlobWriter.closeHighLevelField(pw, MessagePubSub.MSG_PUBLISH_103_FIELD_PAYLOAD_3);
PipeWriter.publishWrites(messagePubSub);
publishGo(1,builder.pubSubIndex(), this);
return true;
} else {
reader.absolutePosition(pos);//restore position as unread
return false;//needed to consume but no place to go.
}
} else {
return true;
}
}
public boolean publishStructuredTopic(CharSequence topic, PubSubStructuredWritable writable) {
return publishStructuredTopic(topic, writable, WaitFor.All);
}
public boolean publishStructuredTopic(CharSequence topic, PubSubStructuredWritable writable, WaitFor ap) {
assert((0 != (initFeatures & DYNAMIC_MESSAGING))) : "CommandChannel must be created with DYNAMIC_MESSAGING flag";
assert(writable != null);
assert(null != messagePubSub);
if ((null==goPipe || PipeWriter.hasRoomForWrite(goPipe))
&& PipeWriter.tryWriteFragment(messagePubSub, MessagePubSub.MSG_PUBLISH_103)) {
PipeWriter.writeInt(messagePubSub, MessagePubSub.MSG_PUBLISH_103_FIELD_QOS_5, ap.policy());
PipeWriter.writeUTF8(messagePubSub, MessagePubSub.MSG_PUBLISH_103_FIELD_TOPIC_1, topic);
PubSubWriter pw = (PubSubWriter) Pipe.outputStream(messagePubSub);
DataOutputBlobWriter.openField(pw);
writable.write(pw);
DataOutputBlobWriter.closeHighLevelField(pw, MessagePubSub.MSG_PUBLISH_103_FIELD_PAYLOAD_3);
PipeWriter.publishWrites(messagePubSub);
publishGo(1,builder.pubSubIndex(), this);
return true;
} else {
return false;
}
}
public boolean publishHTTPResponse(HTTPFieldReader<?> reqeustReader, int statusCode) {
assert((0 != (initFeatures & NET_RESPONDER))) : "CommandChannel must be created with NET_RESPONDER flag";
//logger.info("Building response for connection {} sequence {} ",w.getConnectionId(),w.getSequenceCode());
return publishHTTPResponse(reqeustReader.getConnectionId(), reqeustReader.getSequenceCode(),
statusCode,false,null,Writable.NO_OP); //no type and no body so use null
}
public boolean publishHTTPResponse(HTTPFieldReader<?> reqeustReader,
int statusCode,
HTTPContentType contentType,
Writable writable) {
assert((0 != (initFeatures & NET_RESPONDER))) : "CommandChannel must be created with NET_RESPONDER flag";
return publishHTTPResponse(reqeustReader.getConnectionId(), reqeustReader.getSequenceCode(),
statusCode, false, contentType, writable);
}
public boolean publishHTTPResponse(HTTPFieldReader<?> reqeustReader,
int statusCode, boolean hasContinuation,
HTTPContentType contentType,
Writable writable) {
assert((0 != (initFeatures & NET_RESPONDER))) : "CommandChannel must be created with NET_RESPONDER flag";
return publishHTTPResponse(reqeustReader.getConnectionId(), reqeustReader.getSequenceCode(),
statusCode, hasContinuation, contentType, writable);
}
public boolean publishHTTPResponse(long connectionId, long sequenceCode, int statusCode) {
return publishHTTPResponse(connectionId, sequenceCode, statusCode, false, null, Writable.NO_OP);
}
//these fields are needed for holding the position data for the first block of two
//this is required so we can go back to fill in length after the second block
//length is known
private long block1PositionOfLen;
private int block1HeaderBlobPosition;
//this is not thread safe but works because command channels are only used by same thread
public boolean publishHTTPResponse(long connectionId, long sequenceCode,
int statusCode,
boolean hasContinuation,
HTTPContentType contentType,
Writable writable) {
assert(null!=writable);
assert((0 != (initFeatures & NET_RESPONDER))) : "CommandChannel must be created with NET_RESPONDER flag";
final int sequenceNo = 0xFFFFFFFF & (int)sequenceCode;
final int parallelIndex = 0xFFFFFFFF & (int)(sequenceCode>>32);
assert(1==lastResponseWriterFinished) : "Previous write was not ended can not start another.";
Pipe<ServerResponseSchema> pipe = netResponse.length>1 ? netResponse[parallelIndex] : netResponse[0];
//logger.trace("try new publishHTTPResponse");
if (!Pipe.hasRoomForWrite(pipe, 2*Pipe.sizeOf(pipe, ServerResponseSchema.MSG_TOCHANNEL_100))) {
return false;
}
//simple check to ensure we have room.
assert(Pipe.workingHeadPosition(pipe)<(Pipe.tailPosition(pipe)+ pipe.sizeOfSlabRing /* pipe.slabMask*/ )) : "Working position is now writing into published(unreleased) tail "+
Pipe.workingHeadPosition(pipe)+"<"+Pipe.tailPosition(pipe)+"+"+pipe.sizeOfSlabRing /*pipe.slabMask*/+" total "+((Pipe.tailPosition(pipe)+pipe.slabMask));
//message 1 which contains the headers
holdEmptyBlock(connectionId, sequenceNo, pipe);
//check again because we have taken 2 spots now
assert(Pipe.workingHeadPosition(pipe)<(Pipe.tailPosition(pipe)+ pipe.sizeOfSlabRing /* pipe.slabMask*/ )) : "Working position is now writing into published(unreleased) tail "+
Pipe.workingHeadPosition(pipe)+"<"+Pipe.tailPosition(pipe)+"+"+pipe.sizeOfSlabRing /*pipe.slabMask*/+" total "+((Pipe.tailPosition(pipe)+pipe.slabMask));
//begin message 2 which contains the body
Pipe.addMsgIdx(pipe, ServerResponseSchema.MSG_TOCHANNEL_100);
Pipe.addLongValue(connectionId, pipe);
Pipe.addIntValue(sequenceNo, pipe);
NetResponseWriter outputStream = (NetResponseWriter)Pipe.outputStream(pipe);
int context;
if (hasContinuation) {
context = 0;
lastResponseWriterFinished = 0;
} else {
context = HTTPFieldReader.END_OF_RESPONSE;
lastResponseWriterFinished = 1;
}
//NB: context passed in here is looked at to know if this is END_RESPONSE and if so
//then the length is added if not then the header will designate chunked.
outputStream.openField(statusCode, context, contentType);
writable.write(outputStream);
if (hasContinuation) {
// for chunking we must end this block
outputStream.write(RETURN_NEWLINE);
}
outputStream.publishWithHeader(block1HeaderBlobPosition, block1PositionOfLen); //closeLowLevelField and publish
return true;
}
public boolean publishHTTPResponse(long connectionId, long sequenceCode,
boolean hasContinuation,
CharSequence headers,
Writable writable) {
assert((0 != (initFeatures & NET_RESPONDER))) : "CommandChannel must be created with NET_RESPONDER flag";
final int sequenceNo = 0xFFFFFFFF & (int)sequenceCode;
final int parallelIndex = 0xFFFFFFFF & (int)(sequenceCode>>32);
assert(1==lastResponseWriterFinished) : "Previous write was not ended can not start another.";
Pipe<ServerResponseSchema> pipe = netResponse.length>1 ? netResponse[parallelIndex] : netResponse[0];
if (!Pipe.hasRoomForWrite(pipe)) {
return false;
}
//message 1 which contains the headers
holdEmptyBlock(connectionId, sequenceNo, pipe);
//begin message 2 which contains the body
Pipe.addMsgIdx(pipe, ServerResponseSchema.MSG_TOCHANNEL_100);
Pipe.addLongValue(connectionId, pipe);
Pipe.addIntValue(sequenceNo, pipe);
NetResponseWriter outputStream = (NetResponseWriter)Pipe.outputStream(pipe);
int context;
if (hasContinuation) {
context = 0;
lastResponseWriterFinished = 0;
} else {
context = HTTPFieldReader.END_OF_RESPONSE;
lastResponseWriterFinished = 1;
}
DataOutputBlobWriter.openField(outputStream);
writable.write(outputStream);
if (hasContinuation) {
// for chunking we must end this block
outputStream.write(RETURN_NEWLINE);
}
int len = NetResponseWriter.closeLowLevelField(outputStream); //end of writing the payload
Pipe.addIntValue(context, outputStream.getPipe()); //real context
Pipe.confirmLowLevelWrite(outputStream.getPipe());
////////////////////Write the header
DataOutputBlobWriter.openFieldAtPosition(outputStream, block1HeaderBlobPosition);
//HACK TODO: must formalize response building..
outputStream.write(HTTPRevisionDefaults.HTTP_1_1.getBytes());
outputStream.append(" 200 OK\r\n");
outputStream.append(headers);
outputStream.append("Content-Length: "+len+"\r\n");
outputStream.append("\r\n");
//outputStream.debugAsUTF8();
int propperLength = DataOutputBlobWriter.length(outputStream);
Pipe.validateVarLength(outputStream.getPipe(), propperLength);
Pipe.setIntValue(propperLength, outputStream.getPipe(), block1PositionOfLen); //go back and set the right length.
outputStream.getPipe().closeBlobFieldWrite();
//now publish both header and payload
Pipe.publishWrites(outputStream.getPipe());
return true;
}
private void holdEmptyBlock(long connectionId, final int sequenceNo, Pipe<ServerResponseSchema> pipe) {
Pipe.addMsgIdx(pipe, ServerResponseSchema.MSG_TOCHANNEL_100);
Pipe.addLongValue(connectionId, pipe);
Pipe.addIntValue(sequenceNo, pipe);
NetResponseWriter outputStream = (NetResponseWriter)Pipe.outputStream(pipe);
block1HeaderBlobPosition = Pipe.getWorkingBlobHeadPosition(pipe);
DataOutputBlobWriter.openFieldAtPosition(outputStream, block1HeaderBlobPosition); //no context, that will come in the second message
//for the var field we store this as meta then length
block1PositionOfLen = (1+Pipe.workingHeadPosition(pipe));
DataOutputBlobWriter.closeLowLevelMaxVarLenField(outputStream);
assert(pipe.maxVarLen == Pipe.slab(pipe)[((int)block1PositionOfLen) & Pipe.slabMask(pipe)]) : "expected max var field length";
Pipe.addIntValue(0, pipe); //no context, that will come in the second message
//the full blob size of this message is very large to ensure we have room later...
//this call allows for the following message to be written after this messages blob data
int consumed = Pipe.writeTrailingCountOfBytesConsumed(outputStream.getPipe());
assert(pipe.maxVarLen == consumed);
Pipe.confirmLowLevelWrite(pipe);
//Stores this publish until the next message is complete and published
Pipe.storeUnpublishedWrites(outputStream.getPipe());
//logger.info("new empty block at {} {} ",block1HeaderBlobPosition, block1PositionOfLen);
}
public boolean publishHTTPResponseContinuation(HTTPFieldReader<?> w,
boolean hasContinuation, Writable writable) {
return publishHTTPResponseContinuation(w.getConnectionId(),w.getSequenceCode(), hasContinuation, writable);
}
public boolean publishHTTPResponseContinuation(long connectionId, long sequenceCode,
boolean hasContinuation, Writable writable) {
assert((0 != (initFeatures & NET_RESPONDER))) : "CommandChannel must be created with NET_RESPONDER flag";
final int sequenceNo = 0xFFFFFFFF & (int)sequenceCode;
final int parallelIndex = 0xFFFFFFFF & (int)(sequenceCode>>32);
assert(0==lastResponseWriterFinished) : "Unable to find write in progress, nothing to continue with";
Pipe<ServerResponseSchema> pipe = netResponse.length>1 ? netResponse[parallelIndex] : netResponse[0];
//logger.trace("calling publishHTTPResponseContinuation");
if (!Pipe.hasRoomForWrite(pipe)) {
return false;
}
//message 1 which contains the chunk length
holdEmptyBlock(connectionId, sequenceNo, pipe);
//message 2 which contains the chunk
Pipe.addMsgIdx(pipe, ServerResponseSchema.MSG_TOCHANNEL_100);
Pipe.addLongValue(connectionId, pipe);
Pipe.addIntValue(sequenceNo, pipe);
NetResponseWriter outputStream = (NetResponseWriter)Pipe.outputStream(pipe);
outputStream.openField(hasContinuation? 0: HTTPFieldReader.END_OF_RESPONSE);
lastResponseWriterFinished = hasContinuation ? 0 : 1;
writable.write(outputStream);
//this is not the end of the data so we must close this block
outputStream.write(RETURN_NEWLINE);
if (1 == lastResponseWriterFinished) {
//this is the end of the data, we must close the block
//and add the zero trailer
//this adds 3, note the publishWithChunkPrefix also takes this into account
Appendables.appendHexDigitsRaw(outputStream, 0);
outputStream.write(AbstractAppendablePayloadResponseStage.RETURN_NEWLINE);
//TODO: add trailing headers here. (no request for this feature yet)
outputStream.write(AbstractAppendablePayloadResponseStage.RETURN_NEWLINE);
}
outputStream.publishWithChunkPrefix(block1HeaderBlobPosition, block1PositionOfLen);
return true;
}
public static void publishGo(int count, int pipeIdx, MsgCommandChannel<?> gcc) {
if (null != gcc.goPipe) { //no 'go' needed if pipe is null
assert(pipeIdx>=0);
TrafficOrderSchema.publishGo(gcc.goPipe, pipeIdx, count);
}
}
public static void publishBlockChannel(long durationNanos, MsgCommandChannel<?> gcc) {
if (null != gcc.goPipe) {
PipeWriter.presumeWriteFragment(gcc.goPipe, TrafficOrderSchema.MSG_BLOCKCHANNEL_22);
PipeWriter.writeLong(gcc.goPipe,TrafficOrderSchema.MSG_BLOCKCHANNEL_22_FIELD_DURATIONNANOS_13, durationNanos);
PipeWriter.publishWrites(gcc.goPipe);
} else {
logger.info("Unable to use block channel for ns without an additonal feature use or USE_DELAY can be added.");
}
}
public static void publishBlockChannelUntil(long timeMS, MsgCommandChannel<?> gcc) {
if (null != gcc.goPipe) {
PipeWriter.presumeWriteFragment(gcc.goPipe, TrafficOrderSchema.MSG_BLOCKCHANNELUNTIL_23);
PipeWriter.writeLong(gcc.goPipe,TrafficOrderSchema.MSG_BLOCKCHANNELUNTIL_23_FIELD_TIMEMS_14, timeMS);
PipeWriter.publishWrites(gcc.goPipe);
} else {
logger.info("Unable to use block channel for ns without an additonal feature or USE_DELAY can be added.");
}
}
public void setPrivateTopics(PublishPrivateTopics publishPrivateTopics) {
this.publishPrivateTopics = publishPrivateTopics;
}
public boolean isGoPipe(Pipe<TrafficOrderSchema> target) {
return (null==goPipe) || (target==goPipe);
}
}
|
package com.dmdirc.addons.lagdisplay;
import com.dmdirc.ClientModule.GlobalConfig;
import com.dmdirc.FrameContainer;
import com.dmdirc.ServerState;
import com.dmdirc.actions.ActionManager;
import com.dmdirc.actions.CoreActionType;
import com.dmdirc.addons.lagdisplay.LagDisplayModule.LagDisplaySettingsDomain;
import com.dmdirc.addons.ui_swing.MainFrame;
import com.dmdirc.addons.ui_swing.SelectionListener;
import com.dmdirc.addons.ui_swing.components.frames.TextFrame;
import com.dmdirc.addons.ui_swing.components.statusbar.SwingStatusBar;
import com.dmdirc.interfaces.ActionListener;
import com.dmdirc.interfaces.Connection;
import com.dmdirc.interfaces.actions.ActionType;
import com.dmdirc.interfaces.config.AggregateConfigProvider;
import com.dmdirc.interfaces.config.ConfigChangeListener;
import com.dmdirc.util.collections.RollingList;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.WeakHashMap;
import javax.inject.Inject;
import javax.inject.Provider;
import javax.inject.Singleton;
/**
* Manages the lifecycle of the lag display plugin.
*/
@Singleton
public class LagDisplayManager implements ActionListener, ConfigChangeListener, SelectionListener {
/** Frame to listen to selection events on. */
// TODO: Selection/focus management should be behind an interface
private final MainFrame mainFrame;
/** Status bar to add panels to. */
private final SwingStatusBar statusBar;
private final Provider<LagDisplayPanel> panelProvider;
/** The settings domain to use. */
private final String domain;
/** Config to read global settings from. */
private final AggregateConfigProvider globalConfig;
/** A cache of ping times. */
private final Map<Connection, String> pings = new WeakHashMap<>();
/** Ping history. */
private final Map<Connection, RollingList<Long>> history = new HashMap<>();
/** Whether or not to show a graph in the info popup. */
private boolean showGraph = true;
/** Whether or not to show labels on that graph. */
private boolean showLabels = true;
/** The length of history to keep per-server. */
private int historySize = 100;
/** The panel currently in use. Null before {@link #load()} or after {@link #unload()}. */
private LagDisplayPanel panel;
@Inject
public LagDisplayManager(
final MainFrame mainFrame,
final SwingStatusBar statusBar,
final Provider<LagDisplayPanel> panelProvider,
@LagDisplaySettingsDomain final String domain,
@GlobalConfig final AggregateConfigProvider globalConfig) {
this.mainFrame = mainFrame;
this.statusBar = statusBar;
this.panelProvider = panelProvider;
this.domain = domain;
this.globalConfig = globalConfig;
}
public void load() {
panel = panelProvider.get();
statusBar.addComponent(panel);
mainFrame.addSelectionListener(this);
globalConfig.addChangeListener(domain, this);
readConfig();
ActionManager.getActionManager().registerListener(this,
CoreActionType.SERVER_GOTPING, CoreActionType.SERVER_NOPING,
CoreActionType.SERVER_DISCONNECTED,
CoreActionType.SERVER_PINGSENT, CoreActionType.SERVER_NUMERIC);
}
public void unload() {
statusBar.removeComponent(panel);
mainFrame.removeSelectionListener(this);
globalConfig.removeListener(this);
ActionManager.getActionManager().unregisterListener(this);
panel = null;
}
/** Reads the plugin's global configuration settings. */
private void readConfig() {
showGraph = globalConfig.getOptionBool(domain, "graph");
showLabels = globalConfig.getOptionBool(domain, "labels");
historySize = globalConfig.getOptionInt(domain, "history");
}
/**
* Retrieves the history of the specified server. If there is no history, a new list is added to
* the history map and returned.
*
* @param connection The connection whose history is being requested
*
* @return The history for the specified server
*/
protected RollingList<Long> getHistory(final Connection connection) {
if (!history.containsKey(connection)) {
history.put(connection, new RollingList<Long>(historySize));
}
return history.get(connection);
}
/**
* Determines if the {@link ServerInfoDialog} should show a graph of the ping time for the
* current server.
*
* @return True if a graph should be shown, false otherwise
*/
public boolean shouldShowGraph() {
return showGraph;
}
/**
* Determines if the {@link PingHistoryPanel} should show labels on selected points.
*
* @return True if labels should be shown, false otherwise
*/
public boolean shouldShowLabels() {
return showLabels;
}
/** {@inheritDoc} */
@Override
public void selectionChanged(final TextFrame window) {
final FrameContainer source = window.getContainer();
if (source == null || source.getConnection() == null) {
panel.getComponent().setText("Unknown");
} else if (source.getConnection().getState() != ServerState.CONNECTED) {
panel.getComponent().setText("Not connected");
} else {
panel.getComponent().setText(getTime(source.getConnection()));
}
panel.refreshDialog();
}
/** {@inheritDoc} */
@Override
public void processEvent(final ActionType type, final StringBuffer format,
final Object... arguments) {
boolean useAlternate = false;
for (Object obj : arguments) {
if (obj instanceof FrameContainer
&& ((FrameContainer) obj).getConfigManager() != null) {
useAlternate = ((FrameContainer) obj).getConfigManager()
.getOptionBool(domain, "usealternate");
break;
}
}
final TextFrame activeFrame = mainFrame.getActiveFrame();
final FrameContainer active = activeFrame == null ? null
: activeFrame.getContainer();
final boolean isActive = active != null
&& arguments[0] instanceof Connection
&& ((Connection) arguments[0]).equals(active.getConnection());
if (!useAlternate && type.equals(CoreActionType.SERVER_GOTPING)) {
final String value = formatTime(arguments[1]);
getHistory(((Connection) arguments[0])).add((Long) arguments[1]);
pings.put(((Connection) arguments[0]), value);
if (isActive) {
panel.getComponent().setText(value);
}
panel.refreshDialog();
} else if (!useAlternate && type.equals(CoreActionType.SERVER_NOPING)) {
final String value = formatTime(arguments[1]) + "+";
pings.put(((Connection) arguments[0]), value);
if (isActive) {
panel.getComponent().setText(value);
}
panel.refreshDialog();
} else if (type.equals(CoreActionType.SERVER_DISCONNECTED)) {
if (isActive) {
panel.getComponent().setText("Not connected");
pings.remove(arguments[0]);
}
panel.refreshDialog();
} else if (useAlternate && type.equals(CoreActionType.SERVER_PINGSENT)) {
((Connection) arguments[0]).getParser().sendRawMessage("LAGCHECK_" + new Date().
getTime());
} else if (useAlternate && type.equals(CoreActionType.SERVER_NUMERIC)
&& ((Integer) arguments[1]) == 421
&& ((String[]) arguments[2])[3].startsWith("LAGCHECK_")) {
try {
final long sent = Long.parseLong(((String[]) arguments[2])[3].substring(9));
final Long duration = new Date().getTime() - sent;
final String value = formatTime(duration);
pings.put((Connection) arguments[0], value);
getHistory(((Connection) arguments[0])).add(duration);
if (isActive) {
panel.getComponent().setText(value);
}
} catch (NumberFormatException ex) {
pings.remove(arguments[0]);
}
if (format != null) {
format.delete(0, format.length());
}
panel.refreshDialog();
}
}
/**
* Retrieves the ping time for the specified connection.
*
* @param connection The connection whose ping time is being requested
*
* @return A String representation of the current lag, or "Unknown"
*/
public String getTime(final Connection connection) {
return pings.get(connection) == null ? "Unknown" : pings.get(connection);
}
/**
* Formats the specified time so it's a nice size to display in the label.
*
* @param object An uncast Long representing the time to be formatted
*
* @return Formatted time string
*/
protected String formatTime(final Object object) {
final Long time = (Long) object;
if (time >= 10000) {
return Math.round(time / 1000.0) + "s";
} else {
return time + "ms";
}
}
/** {@inheritDoc} */
@Override
public void configChanged(final String domain, final String key) {
readConfig();
}
}
|
package org.bsc;
import static org.bsc.commands.AddonUtils.getAttribute;
import static org.bsc.commands.AddonUtils.getManifest;
import static org.bsc.commands.AddonUtils.getOut;
import static org.bsc.commands.AddonUtils.putAttribute;
import java.util.jar.Manifest;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.bsc.commands.AbstractDynjsProjectCommand;
import org.bsc.commands.EvalStep;
import org.dynjs.runtime.DynJS;
import org.dynjs.runtime.GlobalObject;
import org.dynjs.runtime.GlobalObjectFactory;
import org.jboss.forge.addon.parser.java.facets.JavaSourceFacet;
import org.jboss.forge.addon.parser.xml.resources.XMLResource;
import org.jboss.forge.addon.projects.Project;
import org.jboss.forge.addon.resource.DirectoryResource;
import org.jboss.forge.addon.ui.context.UIBuilder;
import org.jboss.forge.addon.ui.context.UIContext;
import org.jboss.forge.addon.ui.context.UIExecutionContext;
import org.jboss.forge.addon.ui.context.UINavigationContext;
import org.jboss.forge.addon.ui.metadata.UICommandMetadata;
import org.jboss.forge.addon.ui.result.NavigationResult;
import org.jboss.forge.addon.ui.result.Result;
import org.jboss.forge.addon.ui.result.Results;
import org.jboss.forge.addon.ui.util.Categories;
import org.jboss.forge.addon.ui.util.Metadata;
import org.jboss.forge.addon.ui.wizard.UIWizard;
import org.jboss.forge.roaster.Roaster;
import org.jboss.forge.roaster.model.source.JavaClassSource;
import org.jboss.forge.roaster.model.source.MethodSource;
import org.xml.sax.helpers.XMLReaderFactory;
public class JQM4GWTAddPage extends AbstractDynjsProjectCommand implements UIWizard
{
@Override
public UICommandMetadata getMetadata(UIContext context)
{
return Metadata.forCommand(JQM4GWTAddPage.class)
.name("jqm4gwt-add-page")
.category(Categories.create("JQM4GWT"));
}
@Override
public void initializeUI(UIBuilder builder) throws Exception
{
}
@Override
public Result execute(UIExecutionContext context) throws Exception
{
return Results
.success("Command 'jqm4gwt-add-page' successfully executed!");
}
@Override
public NavigationResult next(UINavigationContext context) throws Exception
{
DynJS dynjs = getAttribute(context, DynJS.class.getName());
if (dynjs == null)
{
final Project project = super.getSelectedProject(context);
final GlobalObjectFactory factory = new GlobalObjectFactory()
{
@Override
public GlobalObject newGlobalObject(DynJS runtime)
{
return new GlobalObject(runtime)
{
{
defineReadOnlyGlobalProperty("self",
JQM4GWTAddPage.this, true);
defineReadOnlyGlobalProperty("project", project,
true);
}
};
}
};
dynjs = newDynJS(context, factory);
final Manifest mf = getManifest();
try
{
runnerFromClasspath(dynjs, "javasource.js", mf).evaluate();
}
catch (Exception e)
{
throw e;
}
putAttribute(context, DynJS.class.getName(), dynjs);
}
return Results.navigateTo(EvalStep.class);
}
public final JavaClassSource createJavaPage( UIExecutionContext context, Project project, String className ) {
final JavaSourceFacet jsf = project.getFacet(JavaSourceFacet.class);
final JavaClassSource jcs = Roaster.create( JavaClassSource.class );
jcs.setPublic()
.setPackage( jsf.getBasePackage().concat(".client") )
.setName( className )
.addInterface("JQMPageEvent.Handler")
.addField( String.format("public static final UiBinder BINDER = GWT.create(%s.UiBinder.class);", className))
.getOrigin()
.addField( String.format("public final static JQMPage INSTANCE = new %s().page;", className))
.getOrigin()
.addField( String.format("private final JQMPage page = %s.BINDER.createAndBindUi(this);", className))
.getOrigin()
.addMethod().setConstructor(true).setBody("page.addPageHandler(this);")
.getOrigin()
;
{
MethodSource<?> m = jcs.addMethod()
.setName("onInit")
.setReturnTypeVoid()
.setPublic()
.setBody("");
m.addParameter("com.sksamuel.jqm4gwt.JQMPageEvent", "event");
m.addAnnotation(Override.class);
}
{
MethodSource<?> m = jcs.addMethod()
.setName("onBeforeShow")
.setReturnTypeVoid()
.setPublic()
.setBody("");
m.addParameter("com.sksamuel.jqm4gwt.JQMPageEvent", "event");
m.addAnnotation(Override.class);
}
{
MethodSource<?> m = jcs.addMethod()
.setName("onBeforeHide")
.setReturnTypeVoid()
.setPublic()
.setBody("");
m.addParameter("com.sksamuel.jqm4gwt.JQMPageEvent", "event");
m.addAnnotation(Override.class);
}
{
MethodSource<?> m = jcs.addMethod()
.setName("onShow")
.setReturnTypeVoid()
.setPublic()
.setBody("");
m.addParameter("com.sksamuel.jqm4gwt.JQMPageEvent", "event");
m.addAnnotation(Override.class);
}
{
MethodSource<?> m = jcs.addMethod()
.setName("onHide")
.setReturnTypeVoid()
.setPublic()
.setBody("");
m.addParameter("com.sksamuel.jqm4gwt.JQMPageEvent", "event");
m.addAnnotation(Override.class);
}
jcs.addImport("com.sksamuel.jqm4gwt.JQMPage");
jcs.addImport("com.sksamuel.jqm4gwt.JQMPageEvent");
jcs.addNestedType(String.format("interface UiBinder extends com.google.gwt.uibinder.client.UiBinder<JQMPage, %s> { }", className));
return jcs;
}
/**
*
* @return
*/
public final void createUIBinder( UIExecutionContext context, Project project, String className ) throws Exception {
final JavaSourceFacet jsf = project.getFacet(JavaSourceFacet.class);
final DirectoryResource uibinderDir = jsf.getBasePackageDirectory().getChildDirectory("client");
if (!uibinderDir.exists()) {
if (!uibinderDir.mkdirs()) {
getOut(context).err().printf("ERROR CREATING FOLDER: [%s]\n", uibinderDir);
return;
}
}
final java.io.InputStream is = getClass().getClassLoader()
.getResourceAsStream("pageTemplate.xml");
java.io.File uibinderFile = new java.io.File( uibinderDir.getUnderlyingResourceObject(), String.format("%s.ui.xml", className));
FileUtils.copyInputStreamToFile(is, uibinderFile);
}
}
|
package com.ecyrd.jspwiki.attachment;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
import java.io.*;
import org.apache.log4j.Category;
import com.ecyrd.jspwiki.*;
import com.ecyrd.jspwiki.providers.WikiAttachmentProvider;
import com.ecyrd.jspwiki.providers.ProviderException;
// multipartrequest.jar imports:
import http.utils.multipartrequest.*;
/**
* This is a simple file upload servlet customized for JSPWiki. It receives
* a mime/multipart POST message, as sent by an Attachment page, stores it
* temporarily, figures out what WikiName to use to store it, checks for
* previously existing versions.
*
* <p>This servlet does not worry about authentication; we leave that to the
* container, or a previous servlet that chains to us.
*
* @author Erik Bunn
* @author Janne Jalkanen
*
* @since 1.9.45.
*/
public class AttachmentServlet
extends HttpServlet
{
private WikiEngine m_engine;
private Category log = Category.getInstance( AttachmentServlet.class );
public static final String HDR_VERSION = "version";
public static final String HDR_NAME = "page";
private String m_tmpDir;
/**
* Initializes the servlet from WikiEngine properties.
*/
public void init( ServletConfig config )
throws ServletException
{
super.init( config );
m_engine = WikiEngine.getInstance( config );
Properties props = m_engine.getWikiProperties();
m_tmpDir = System.getProperty( "java.io.tmpdir" );
log.debug( "UploadServlet initialized. Using " +
m_tmpDir + " for temporary storage." );
}
/**
* Serves a GET with two parameters: 'wikiname' specifying the wikiname
* of the attachment, 'version' specifying the version indicator.
*/
// FIXME: Messages would need to be localized somehow.
public void doGet( HttpServletRequest req, HttpServletResponse res )
throws IOException, ServletException
{
String page = m_engine.safeGetParameter( req, "page" );
String version = m_engine.safeGetParameter( req, HDR_VERSION );
String nextPage = m_engine.safeGetParameter( req, "nextpage" );
String msg = "An error occurred. Ouch.";
int ver = WikiProvider.LATEST_VERSION;
AttachmentManager mgr = m_engine.getAttachmentManager();
if( page == null )
{
msg = "Invalid attachment name.";
}
else
{
try
{
// System.out.println("Attempting to download att "+page+", version "+version);
if( version != null )
{
ver = Integer.parseInt( version );
}
Attachment att = mgr.getAttachmentInfo( page, ver );
if( att != null )
{
String mimetype = getServletConfig().getServletContext().getMimeType( att.getFileName().toLowerCase() );
if( mimetype == null )
{
mimetype = "application/binary";
}
res.setContentType( mimetype );
// We use 'inline' instead of 'attachment' so that user agents
// can try to automatically open the file.
res.setHeader( "Content-Disposition",
"inline; filename=" + att.getFileName() + ";" );
// If a size is provided by the provider, report it.
if( att.getSize() >= 0 )
res.setContentLength( (int)att.getSize() );
OutputStream out = res.getOutputStream();
InputStream in = mgr.getAttachmentStream( att );
int read = 0;
byte buffer[] = new byte[8192];
while( (read = in.read( buffer )) > -1 )
{
out.write( buffer, 0, read );
}
in.close();
out.close();
msg = "Attachment "+att.getFileName()+" sent to "+req.getRemoteUser()+" on "+req.getRemoteHost();
log.debug( msg );
if( nextPage != null ) res.sendRedirect( nextPage );
return;
}
else
{
msg = "Attachment '" + page + "', version " + ver +
" does not exist.";
}
}
catch( ProviderException pe )
{
msg = "Provider error: "+pe.getMessage();
}
catch( NumberFormatException nfe )
{
msg = "Invalid version number (" + version + ")";
}
catch( IOException ioe )
{
msg = "Error: " + ioe.getMessage();
}
}
log.info( msg );
if( nextPage != null ) res.sendRedirect( nextPage );
}
/**
* Grabs mime/multipart data and stores it into the temporary area.
* Uses other parameters to determine which name to store as.
*
* <p>The input to this servlet is generated by an HTML FORM with
* two parts. The first, named 'wikiname', is the WikiName identifier
* for the attachment. The second, named 'content', is the binary
* content of the file.
*
* <p>After handling, the request is forwarded to m_resultPage.
*/
public void doPost( HttpServletRequest req, HttpServletResponse res )
throws IOException, ServletException
{
String nextPage = upload( req );
log.debug( "Forwarding to " + nextPage );
res.sendRedirect( nextPage );
}
/**
* Uploads a specific mime multipart input set, intercepts exceptions.
*
* @return The page to which we should go next.
*/
// FIXME: Error reporting is non-existent - the user gets no feedback whatsoever.
protected String upload( HttpServletRequest req )
{
String msg = "";
String attName = "(unknown)";
String nextPage = "Error.jsp"; // If something bad happened.
try
{
MultipartRequest multi = new ServletMultipartRequest( req, m_tmpDir, Integer.MAX_VALUE );
nextPage = multi.getURLParameter( "nextpage" );
String wikipage = multi.getURLParameter( "page" );
String user = m_engine.getValidUserName( req );
// Go through all files being uploaded.
Enumeration files = multi.getFileParameterNames();
while( files.hasMoreElements() )
{
String part = (String) files.nextElement();
File f = multi.getFile( part );
AttachmentManager mgr = m_engine.getAttachmentManager();
InputStream in;
// Is a file to be uploaded.
String filename = multi.getFileSystemName( part );
if( filename == null || filename.trim().length() == 0 )
{
log.error("Empty file name given.");
return nextPage;
}
// Attempt to open the input stream
if( f != null )
{
in = new FileInputStream( f );
}
else
{
in = multi.getFileContents( part );
}
if( in == null )
{
log.error("File could not be opened.");
return nextPage;
}
// Check whether we already have this kind of a page.
// If the "page" parameter already defines an attachment
// name for an update, then we just use that file.
// Otherwise we create a new attachment, and use the
// filename given. Incidentally, this will also mean
// that if the user uploads a file with the exact
// same name than some other previous attachment,
// then that attachment gains a new version.
Attachment att = mgr.getAttachmentInfo( wikipage );
if( att == null )
{
att = new Attachment( wikipage, filename );
}
att.setAuthor( user );
m_engine.getAttachmentManager().storeAttachment( att, in );
log.info( "User " + user + " uploaded attachment to " + wikipage +
" called "+filename+", size " + multi.getFileSize(part) );
f.delete();
}
// Inform the JSP page of which file we are handling:
// req.setAttribute( ATTR_ATTACHMENT, wikiname );
}
catch( ProviderException e )
{
msg = "Upload failed because the provider failed: "+e.getMessage();
log.warn( msg + " (attachment: " + attName + ")", e );
}
catch( IOException e )
{
// Show the submit page again, but with a bit more
// intimidating output.
msg = "Upload failure: " + e.getMessage();
log.warn( msg + " (attachment: " + attName + ")", e );
}
return nextPage;
}
/**
* Produces debug output listing parameters and files.
*/
/*
private void debugContentList( MultipartRequest multi )
{
StringBuffer sb = new StringBuffer();
sb.append( "Upload information: parameters: [" );
Enumeration params = multi.getParameterNames();
while( params.hasMoreElements() )
{
String name = (String)params.nextElement();
String value = multi.getURLParameter( name );
sb.append( "[" + name + " = " + value + "]" );
}
sb.append( " files: [" );
Enumeration files = multi.getFileParameterNames();
while( files.hasMoreElements() )
{
String name = (String)files.nextElement();
String filename = multi.getFileSystemName( name );
String type = multi.getContentType( name );
File f = multi.getFile( name );
sb.append( "[name: " + name );
sb.append( " temp_file: " + filename );
sb.append( " type: " + type );
if (f != null)
{
sb.append( " abs: " + f.getPath() );
sb.append( " size: " + f.length() );
}
sb.append( "]" );
}
sb.append( "]" );
log.debug( sb.toString() );
}
*/
}
|
package com.podio.hudson;
import hudson.Extension;
import hudson.Launcher;
import hudson.model.BuildListener;
import hudson.model.Result;
import hudson.model.AbstractBuild;
import hudson.model.AbstractProject;
import hudson.model.Run;
import hudson.model.User;
import hudson.scm.ChangeLogSet;
import hudson.scm.ChangeLogSet.Entry;
import hudson.tasks.BuildStepDescriptor;
import hudson.tasks.BuildStepMonitor;
import hudson.tasks.Notifier;
import hudson.tasks.Publisher;
import hudson.tasks.Mailer;
import hudson.tasks.test.AbstractTestResultAction;
import hudson.util.FormValidation;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.joda.time.LocalDate;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.QueryParameter;
import org.kohsuke.stapler.StaplerRequest;
import com.podio.BaseAPI;
import com.podio.common.Reference;
import com.podio.common.ReferenceType;
import com.podio.contact.ContactAPI;
import com.podio.contact.ProfileField;
import com.podio.contact.ProfileType;
import com.podio.item.FieldValues;
import com.podio.item.ItemAPI;
import com.podio.item.ItemCreate;
import com.podio.item.ItemsResponse;
import com.podio.oauth.OAuthClientCredentials;
import com.podio.oauth.OAuthUsernameCredentials;
import com.podio.root.RootAPI;
import com.podio.root.SystemStatus;
import com.podio.space.SpaceAPI;
import com.podio.space.SpaceWithOrganization;
import com.podio.task.Task;
import com.podio.task.TaskAPI;
import com.podio.task.TaskCreate;
import com.podio.task.TaskStatus;
import com.podio.user.UserMini;
import com.sun.jersey.api.client.UniformInterfaceException;
public class PodioBuildNotifier extends Notifier {
private static final int FAILED_TESTS_FIELD_ID = 74282;
private static final int TOTAL_TESTS_FIELD_ID = 74281;
private static final int USERS_FIELD_ID = 74280;
private static final int URL_FIELD_ID = 74670;
private static final int RESULT_FIELD_ID = 74279;
private static final int BUILD_NUMBER_FIELD_ID = 74278;
private static final int DURATION_FIELD_ID = 74671;
private static final int APP_ID = 13658;
protected static final Logger LOGGER = Logger
.getLogger(PodioBuildNotifier.class.getName());
private final String username;
private final String password;
private final String clientId;
private final String clientSecret;
private final String spaceURL;
@DataBoundConstructor
public PodioBuildNotifier(String username, String password,
String clientId, String clientSecret, String spaceURL) {
this.username = username;
this.password = password;
this.clientId = clientId;
this.clientSecret = clientSecret;
this.spaceURL = spaceURL;
LOGGER.info(username);
}
public String getUsername() {
return username;
}
public String getPassword() {
return password;
}
public String getClientId() {
return clientId;
}
public String getClientSecret() {
return clientSecret;
}
public String getSpaceURL() {
return spaceURL;
}
public BuildStepMonitor getRequiredMonitorService() {
return BuildStepMonitor.BUILD;
}
private BaseAPI getBaseAPI() {
DescriptorImpl descriptor = (DescriptorImpl) getDescriptor();
return new BaseAPI(descriptor.hostname, descriptor.hostname,
descriptor.port, descriptor.ssl, false,
new OAuthClientCredentials(clientId, clientSecret),
new OAuthUsernameCredentials(username, password));
}
@Override
public boolean perform(AbstractBuild<?, ?> build, Launcher launcher,
BuildListener listener) throws InterruptedException, IOException {
LOGGER.info("Build complete");
BaseAPI baseAPI = getBaseAPI();
String result = StringUtils.capitalize(build.getResult().toString()
.toLowerCase());
result = result.replace('_', ' ');
SpaceWithOrganization space = getSpace(baseAPI);
String url = Mailer.descriptor().getUrl() + build.getParent().getUrl()
+ build.getNumber();
List<Integer> userIds = getUserIds(baseAPI, space.getId(), build);
Integer totalTestCases = null;
Integer failedTestCases = null;
AbstractTestResultAction testResult = build.getTestResultAction();
if (testResult != null) {
totalTestCases = testResult.getTotalCount();
failedTestCases = testResult.getFailCount();
}
int itemId = postBuild(baseAPI, build.getNumber(), result, url,
userIds, totalTestCases, failedTestCases,
build.getDurationString());
AbstractBuild previousBuild = build.getPreviousBuild();
boolean oldFailed = previousBuild != null
&& previousBuild.getResult() != Result.SUCCESS;
TaskAPI taskAPI = new TaskAPI(baseAPI);
if (oldFailed && build.getResult() == Result.SUCCESS) {
Run firstFailed = getFirstFailure(previousBuild);
Integer firstFailedItemId = getItemId(baseAPI,
firstFailed.getNumber());
if (firstFailedItemId != null) {
List<Task> tasks = taskAPI.getTasksWithReference(new Reference(
ReferenceType.ITEM, firstFailedItemId));
for (Task task : tasks) {
if (task.getStatus() == TaskStatus.ACTIVE) {
taskAPI.completeTask(task.getId());
}
}
}
} else if (!oldFailed && build.getResult() != Result.SUCCESS) {
for (Integer userId : userIds) {
taskAPI.createTaskWithReference(new TaskCreate(
"Fix broken build", false, new LocalDate(), userId),
new Reference(ReferenceType.ITEM, itemId));
}
}
return true;
}
private Run getFirstFailure(Run build) {
Run previousBuild = build.getPreviousBuild();
if (previousBuild != null) {
if (previousBuild.getResult() == Result.SUCCESS) {
return build;
}
return getFirstFailure(previousBuild);
} else {
return build;
}
}
private Integer getItemId(BaseAPI baseAPI, int buildNumber) {
ItemsResponse response = new ItemAPI(baseAPI).getItemsByExternalId(
APP_ID, Integer.toString(buildNumber));
if (response.getFiltered() != 1) {
return null;
}
return response.getItems().get(0).getId();
}
private int postBuild(BaseAPI baseAPI, int buildNumber, String result,
String url, List<Integer> userIds, Integer totalTestCases,
Integer failedTestCases, String duration) {
List<FieldValues> fields = new ArrayList<FieldValues>();
fields.add(new FieldValues(BUILD_NUMBER_FIELD_ID, "value", "Build "
+ buildNumber));
fields.add(new FieldValues(RESULT_FIELD_ID, "value", result));
fields.add(new FieldValues(URL_FIELD_ID, "value", url));
List<Map<String, Object>> subValues = new ArrayList<Map<String, Object>>();
for (Integer userId : userIds) {
subValues.add(Collections.<String, Object> singletonMap("value",
userId));
}
fields.add(new FieldValues(USERS_FIELD_ID, subValues));
if (totalTestCases != null) {
fields.add(new FieldValues(TOTAL_TESTS_FIELD_ID, "value",
totalTestCases));
}
if (failedTestCases != null) {
fields.add(new FieldValues(FAILED_TESTS_FIELD_ID, "value",
failedTestCases));
}
fields.add(new FieldValues(DURATION_FIELD_ID, "value", duration));
ItemCreate create = new ItemCreate(Integer.toString(buildNumber),
fields, Collections.<Integer> emptyList(),
Collections.<String> emptyList());
ItemAPI itemAPI = new ItemAPI(baseAPI);
int itemId = itemAPI.addItem(APP_ID, create, true).getItemId();
return itemId;
}
private SpaceWithOrganization getSpace(BaseAPI baseAPI) {
return new SpaceAPI(baseAPI).getByURL(spaceURL);
}
private List<Integer> getUserIds(BaseAPI baseAPI, int spaceId,
AbstractBuild<?, ?> build) {
List<Integer> userIds = new ArrayList<Integer>();
Set<User> culprits = build.getCulprits();
ChangeLogSet<? extends Entry> changeSet = build.getChangeSet();
if (culprits.size() > 0) {
for (User culprit : culprits) {
LOGGER.info("Looking for user " + culprit);
Integer userId = getUserId(baseAPI, spaceId, culprit);
LOGGER.info("Found " + userId);
if (userId != null) {
userIds.add(userId);
}
}
}
if (changeSet != null) {
for (Entry entry : changeSet) {
LOGGER.info("Looking for user " + entry.getAuthor());
Integer userId = getUserId(baseAPI, spaceId, entry.getAuthor());
LOGGER.info("Found " + userId);
if (userId != null) {
userIds.add(userId);
}
}
}
LOGGER.info(userIds.toString());
return userIds;
}
private Integer getUserId(BaseAPI baseAPI, int spaceId, User user) {
String mail = user.getProperty(Mailer.UserProperty.class).getAddress();
List<UserMini> contacts = new ContactAPI(baseAPI).getSpaceContacts(
spaceId, ProfileField.MAIL, mail, 1, null, ProfileType.MINI,
null);
if (contacts.isEmpty()) {
return null;
}
return contacts.get(0).getId();
}
@Extension
public static final class DescriptorImpl extends
BuildStepDescriptor<Publisher> {
private String hostname = "localhost";
private int port = 9090;
private boolean ssl = false;
public DescriptorImpl() {
super(PodioBuildNotifier.class);
load();
}
@Override
public String getDisplayName() {
return "Podio Build Poster";
}
@Override
public boolean configure(StaplerRequest req, JSONObject formData)
throws FormException {
req.bindParameters(this);
this.hostname = formData.getString("hostname");
this.port = formData.getInt("port");
this.ssl = formData.getBoolean("ssl");
save();
return super.configure(req, formData);
}
public FormValidation doValidateAuth(
@QueryParameter("username") final String username,
@QueryParameter("password") final String password,
@QueryParameter("clientId") final String clientId,
@QueryParameter("clientSecret") final String clientSecret,
@QueryParameter("spaceURL") final String spaceURL)
throws IOException, ServletException {
BaseAPI baseAPI = new BaseAPI(hostname, hostname, port, ssl, false,
new OAuthClientCredentials(clientId, clientSecret),
new OAuthUsernameCredentials(username, password));
try {
SpaceWithOrganization space = new SpaceAPI(baseAPI)
.getByURL(spaceURL);
return FormValidation.ok("Connection ok, using space "
+ space.getName() + " in organization "
+ space.getOrganization().getName());
} catch (UniformInterfaceException e) {
if (e.getResponse().getStatus() == 404) {
return FormValidation.error("No space found with the URL "
+ spaceURL);
} else {
return FormValidation.error("Invalid username or password");
}
} catch (Exception e) {
e.printStackTrace();
return FormValidation.error("Invalid username or password");
}
}
public FormValidation doValidateAPI(
@QueryParameter("hostname") final String hostname,
@QueryParameter("port") final String port,
@QueryParameter("ssl") final boolean ssl) throws IOException,
ServletException {
int portInt;
try {
portInt = Integer.parseInt(port);
} catch (NumberFormatException e) {
return FormValidation.error("Port must be an integer");
}
BaseAPI baseAPI = new BaseAPI(hostname, hostname, portInt, ssl,
false, null, null);
try {
SystemStatus status = new RootAPI(baseAPI).getStatus();
return FormValidation
.ok("Connection validated, running API version "
+ status.getVersion());
} catch (Exception e) {
e.printStackTrace();
return FormValidation.error("Invalid hostname, port or ssl");
}
}
@Override
public Publisher newInstance(StaplerRequest req, JSONObject formData)
throws FormException {
return super.newInstance(req, formData);
}
@Override
public boolean isApplicable(Class<? extends AbstractProject> jobType) {
return true;
}
public String getHostname() {
return hostname;
}
public void setHostname(String hostname) {
this.hostname = hostname;
}
public int getPort() {
return port;
}
public void setPort(int port) {
this.port = port;
}
public boolean isSsl() {
return ssl;
}
public void setSsl(boolean ssl) {
this.ssl = ssl;
}
}
}
|
package org.sagebionetworks.web.client.view;
import org.gwtbootstrap3.client.ui.Anchor;
import org.gwtbootstrap3.client.ui.Lead;
import org.sagebionetworks.web.client.GlobalApplicationState;
import org.sagebionetworks.web.client.widget.header.Header;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.History;
import com.google.gwt.user.client.ui.IsWidget;
import com.google.gwt.user.client.ui.SimplePanel;
import com.google.gwt.user.client.ui.Widget;
import com.google.inject.Inject;
public class ErrorViewImpl implements ErrorView {
@UiField
Anchor goBackLink;
@UiField
Lead message;
private Header headerWidget;
public interface Binder extends UiBinder<Widget, ErrorViewImpl> {}
public Widget widget;
@Inject
public ErrorViewImpl(Binder uiBinder,
Header headerWidget,
GlobalApplicationState globalAppState) {
widget = uiBinder.createAndBindUi(this);
this.headerWidget = headerWidget;
headerWidget.configure();
goBackLink.addClickHandler(event -> globalAppState.gotoLastPlace());
}
@Override
public void refreshHeader() {
headerWidget.configure();
headerWidget.refresh();
com.google.gwt.user.client.Window.scrollTo(0, 0); // scroll user to top of page
}
@Override
public Widget asWidget() {
return widget;
}
@Override
public void setErrorMessage(String error) {
message.setText(error);
}
}
|
package ca.uwaterloo.joos.symboltable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;
import org.hamcrest.Matchers;
import ca.uwaterloo.joos.Main;
import ca.uwaterloo.joos.ast.AST;
import ca.uwaterloo.joos.ast.decl.PackageDeclaration;
import ch.lambdaj.Lambda;
public class SymbolTable {
@SuppressWarnings("serial")
public static class SymbolTableException extends Exception {
public SymbolTableException(String string) {
super(string);
}
}
public static Logger logger = Main.getLogger(SymbolTable.class);
private Map<String, Scope> scopes = new HashMap<String, Scope>();
public SymbolTable() {
this.scopes = new HashMap<String, Scope>();
}
public PackageScope getPackageByDecl(PackageDeclaration packDecl) throws Exception {
// Get Package Name
String name = null;
if(packDecl.getPackageName() == null) {
name = "__default__";
} else {
name = packDecl.getPackageName().getName();
}
// Find the scope
Scope scope = this.scopes.get(name);
if (scope == null) {
scope = this.addPackage(name);
} else if (!(scope instanceof PackageScope)) {
throw new SymbolTableException("Expecting PackageScope but get " + scope.getClass().getName());
}
return (PackageScope) scope;
}
public PackageScope getPackage(String name) throws Exception {
// Get Package Name
if(name == null) {
name = "__default__";
}
// Find the scope
Scope scope = this.scopes.get(name);
if (!(scope instanceof PackageScope)) {
throw new SymbolTableException("Expecting PackageScope but get " + scope.getClass().getName());
}
return (PackageScope) scope;
}
public List<? extends Scope> getScopeByPrefix(String prefix, Class<?> scopeClass) {
return Lambda.select(
Lambda.select(this.scopes.values(), Matchers.instanceOf(scopeClass)),
Lambda.having(Lambda.on(Scope.class).getName(), Matchers.startsWith(prefix)));
}
public TypeScope getType(String name) throws Exception {
Scope scope = this.scopes.get(name + "{}");
if (!(scope instanceof TypeScope)) {
throw new SymbolTableException("Expecting TypeScope but get " + scope);
}
return (TypeScope) scope;
}
public BlockScope getBlock(String name) throws Exception {
Scope scope = this.scopes.get(name);
if (!(scope instanceof BlockScope)) {
throw new SymbolTableException("Expecting BlockScope but get " + scope);
}
return (BlockScope) scope;
}
public boolean containPackage(String name) {
Scope scope = this.scopes.get(name);
return scope != null && scope instanceof PackageScope;
}
public boolean containType(String name) {
Scope scope = this.scopes.get(name + "{}");
return scope != null && scope instanceof TypeScope;
}
public boolean containBlock(String name) {
Scope scope = this.scopes.get(name);
return scope != null && scope instanceof BlockScope;
}
public PackageScope addPackage(String packageName) throws Exception {
int i = 0;
String[] components = packageName.split("\\.");
String name;
// Check for prefix conflict
for (i = 0, name = ""; i < components.length; i++) {
if (i != 0)
name += ".";
name += components[i];
if (this.containType(name)) {
throw new SymbolTableException("Package declaration conflict with type prefix " + name);
}
}
PackageScope scope = new PackageScope(packageName);
this.scopes.put(packageName, scope);
return scope;
}
public TypeScope addType(String typeName, PackageScope packageScope) throws Exception {
// Check for prefix conflict
List<? extends Scope> packages = this.getScopeByPrefix(typeName + ".", PackageScope.class);
if (this.containPackage(typeName) || !packages.isEmpty()) {
throw new SymbolTableException("Type declaration conflict with package prefix " + typeName);
}
typeName += "{}";
TypeScope scope = new TypeScope(typeName, packageScope);
this.scopes.put(typeName, scope);
return scope;
}
public BlockScope addBlock(String blockName, Scope parent) throws Exception {
// Check for prefix conflict
if (this.scopes.containsKey(blockName)) {
throw new SymbolTableException("Duplicate Block Declaration: " + blockName);
}
BlockScope scope = new BlockScope(blockName, parent);
this.scopes.put(blockName, scope);
return scope;
}
public void build(List<AST> asts) throws Exception {
// logger.setLevel(Level.FINER);
for (AST ast : asts) {
ast.getRoot().accept(new TopDeclVisitor(this));
}
logger.info("Building Symbol Table Pass 1 Finished");
for (AST ast: asts){
ast.getRoot().accept(new ImportVisitor(this));
}
logger.info("Building Symbol Table Pass 2 Finished");
for (AST ast: asts){
ast.getRoot().accept(new DeepDeclVisitor(this));
}
logger.info("Building Symbol Table Pass 3 Finished");
}
public void listScopes() {
System.out.println("Listing Scopes");
List<String> keys = new ArrayList<String>(this.scopes.keySet());
Collections.sort(keys);
for (String key : keys) {
System.out.println(this.scopes.get(key).getName());
this.scopes.get(key).listSymbols();
}
}
}
|
package org.spongepowered.api.text.selector;
import com.flowpowered.math.vector.Vector3d;
import com.flowpowered.math.vector.Vector3i;
import org.spongepowered.api.entity.EntityType;
import org.spongepowered.api.entity.player.gamemode.GameMode;
/**
* Represents the list of default {@link ArgumentType}s available in Vanilla
* Minecraft.
*/
public final class ArgumentTypes {
private ArgumentTypes() {
}
/**
* The argument types representing the position of the selector.
*
* <p>In Vanilla, this is represented by the {@code x}, {@code y} and
* {@code z} selector keys.</p>
*/
public static final ArgumentType.Vector3<Vector3i, Integer> POSITION = null;
/**
* The argument types representing the radius of the selector.
*
* <p>In Vanilla, this is represented by the {@code r} (for minimum) and
* {@code rm} (for maximum) selector keys.</p>
*/
public static final ArgumentType.Limit<ArgumentType<Integer>> RADIUS = null;
/**
* The argument type filtering based on the {@link GameMode} of a player.
*
* <p>In Vanilla, this is represented by the {@code m} selector key.</p>
*/
public static final ArgumentType<GameMode> GAME_MODE = null;
/**
* The argument type limiting the number of results of a {@link Selector}.
* Negative values will reverse the order of targets - for example the
* farthest targets will be returned first.
*
* <p>The default count for the {@link SelectorTypes#RANDOM_PLAYER} and
* {@link SelectorTypes#NEAREST_PLAYER} is {@code 1}, therefore a higher
* number will increase the count instead of limiting it.</p>
*
* <p>In Vanilla, this is represented by the {@code c} selector key.</p>
*/
public static final ArgumentType<Integer> COUNT = null;
/**
* The argument types filtering based on the number of experience levels of
* the target.
*
* <p>In Vanilla, this is represented by the {@code l} (for maximum) and
* {@code lm} (for minimum) selector keys.</p>
*/
public static final ArgumentType.Limit<ArgumentType<Integer>> LEVEL = null;
// TODO: Scoreboard API
/**
* The argument type filtering based on the {@link String} of the target.
* Inverting this argument type will search for all targets not in the
* specified team instead.
*
* <p>In Vanilla, this is represented by the {@code team} selector key with
* the {@code !} prefix for inverted values.</p>
*/
public static final ArgumentType.Invertible<String> TEAM = null;
/**
* The argument type filtering based on the name of the target. Inverting
* this argument type will search for all targets without the specified name
* instead.
*
* <p>In Vanilla, this is represented by the {@code name} selector key with
* the {@code !} prefix for inverted values.</p>
*/
public static final ArgumentType.Invertible<String> NAME = null;
/**
* The argument type filtering targets which aren't in the specified volume.
*
* <p>In Vanilla, this is represented by the {@code dx}, {@code dy} and
* {@code dz} selector keys.</p>
*/
public static final ArgumentType.Vector3<Vector3i, Integer> DIMENSION = null;
/**
* The argument type filtering targets within a specific rotation range.
*
* <p>In Vanilla, the {@link Float}s will be floored to {@link Integer}s and
* the third float is completely ignored. It is represented by the
* {@code rx}/{@code ry} (for minimum) and {@code rxm}/{@code rym} selector
* keys.</p>
*/
public static final ArgumentType.Limit<ArgumentType.Vector3<Vector3d, Float>> ROTATION = null;
/**
* The argument type filtering targets based on the {@link EntityType}.
*
* <p>In Vanilla, this is represented by the {@code type} selector key.</p>
*/
public static final ArgumentType.Invertible<EntityType> ENTITY_TYPE = null;
// TODO: Scoreboard API
/**
* Creates a minimum and maximum {@link ArgumentType} filtering depending on
* the score of the specified objective.
*
* @param name The objective name to use
* @return The created argument type
*/
public static ArgumentType.Limit<ArgumentType<Integer>> score(String name) {
return Selectors.factory.createScoreArgumentType(name);
}
/**
* Creates a custom {@link ArgumentType} with the specified key.
*
* @param key The key to use for the argument
* @return The created argument type
*/
public static ArgumentType<String> create(String key) {
return Selectors.factory.createArgumentType(key);
}
/**
* Creates a custom {@link ArgumentType} with the specified key and value.
*
* @param key The key to use for the argument
* @param type The class of the argument's value type
* @param <T> The argument's value type
* @return The created argument type
*/
public static <T> ArgumentType<T> create(String key, Class<T> type) {
return Selectors.factory.createArgumentType(key, type);
}
/**
* Checks if this is a flowerpot.
*
* @return Whether this is a flowerpot
*/
public static boolean isFlowerPot() {
return false;
}
}
|
package com.spoon.backgroundfileupload;
import com.orm.SugarRecord;
import com.orm.dsl.Unique;
import com.orm.query.Condition;
import com.orm.query.Select;
import org.json.JSONObject;
import java.util.List;
public class PendingUpload extends SugarRecord {
String uploadId;
String data;
public PendingUpload() {}
public PendingUpload(JSONObject payload) {
try {
uploadId = payload.getString("id");
data = payload.toString();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void create(JSONObject payload) {
PendingUpload pendingUpload = new PendingUpload(payload);
pendingUpload.save();
return pendingUpload();
}
public static void remove(String uploadId) {
List<PendingUpload> results = Select.from(PendingUpload.class)
.where(Condition.prop("upload_id").eq(uploadId))
.list();
if (results.size() > 0)
results.get(0).delete();
}
public static List<PendingUpload> all() {
return PendingUpload.listAll(PendingUpload.class);
}
}
|
package org.fxmisc.flowless;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Optional;
import java.util.Queue;
import java.util.stream.Stream;
import javafx.application.Platform;
import javafx.beans.binding.Bindings;
import javafx.beans.binding.BooleanBinding;
import javafx.beans.binding.DoubleBinding;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.value.ObservableDoubleValue;
import javafx.collections.ListChangeListener;
import javafx.collections.ObservableList;
import javafx.geometry.Bounds;
import javafx.geometry.Orientation;
import javafx.scene.Node;
import javafx.scene.control.IndexRange;
import javafx.scene.control.ScrollBar;
import javafx.scene.input.ScrollEvent;
import javafx.scene.layout.Region;
import javafx.scene.shape.Rectangle;
public class VirtualFlow<T, C extends Node> extends Region {
// Children of a VirtualFlow are cells. All children are unmanaged.
// Children correspond to a sublist of items. Not all children are
// visible. Visible children form a continuous subrange of all children.
// Invisible children have CSS applied, but are not sized and positioned.
public static <T, C extends Node> VirtualFlow<T, C> createHorizontal(
ObservableList<T> items, CellFactory<T, C> cellFactory) {
return new VirtualFlow<>(items, cellFactory, new HorizontalFlowMetrics());
}
public static <T, C extends Node> VirtualFlow<T, C> createVertical(
ObservableList<T> items, CellFactory<T, C> cellFactory) {
return new VirtualFlow<>(items, cellFactory, new VerticalFlowMetrics());
}
private final ScrollBar hbar;
private final ScrollBar vbar;
private final VirtualFlowContent<T, C> content;
private VirtualFlow(ObservableList<T> items, CellFactory<T, C> cellFactory, Metrics metrics) {
this.content = new VirtualFlowContent<>(items, cellFactory, metrics);
// create scrollbars
hbar = new ScrollBar();
vbar = new ScrollBar();
vbar.setOrientation(Orientation.VERTICAL);
// scrollbar ranges
hbar.setMin(0);
vbar.setMin(0);
hbar.maxProperty().bind(metrics.widthEstimateProperty(content));
vbar.maxProperty().bind(metrics.heightEstimateProperty(content));
// scrollbar increments
setupUnitIncrement(hbar);
setupUnitIncrement(vbar);
hbar.blockIncrementProperty().bind(hbar.visibleAmountProperty());
vbar.blockIncrementProperty().bind(vbar.visibleAmountProperty());
// scrollbar positions
hbar.setValue(metrics.getHorizontalPosition(content));
vbar.setValue(metrics.getVerticalPosition(content));
metrics.horizontalPositionProperty(content).addListener(
obs -> hbar.setValue(metrics.getHorizontalPosition(content)));
metrics.verticalPositionProperty(content).addListener(
obs -> vbar.setValue(metrics.getVerticalPosition(content)));
// scroll content by scrollbars
hbar.valueProperty().addListener((obs, old, pos) ->
metrics.setHorizontalPosition(content, pos.doubleValue()));
vbar.valueProperty().addListener((obs, old, pos) ->
metrics.setVerticalPosition(content, pos.doubleValue()));
// scroll content by mouse scroll
this.addEventHandler(ScrollEvent.SCROLL, se -> {
double dx = se.getDeltaX();
double dy = se.getDeltaY();
metrics.scrollVertically(content, dy);
metrics.scrollHorizontally(content, dx);
se.consume();
});
// scrollbar visibility
DoubleBinding layoutWidth = Bindings.createDoubleBinding(
() -> getLayoutBounds().getWidth(),
layoutBoundsProperty());
DoubleBinding layoutHeight = Bindings.createDoubleBinding(
() -> getLayoutBounds().getHeight(),
layoutBoundsProperty());
BooleanBinding needsHBar0 = Bindings.greaterThan(
metrics.widthEstimateProperty(content),
layoutWidth);
BooleanBinding needsVBar0 = Bindings.greaterThan(
metrics.heightEstimateProperty(content),
layoutHeight);
BooleanBinding needsHBar = needsHBar0.or(needsVBar0.and(
Bindings.greaterThan(
Bindings.add(metrics.widthEstimateProperty(content), vbar.widthProperty()),
layoutWidth)));
BooleanBinding needsVBar = needsVBar0.or(needsHBar0.and(
Bindings.greaterThan(
Bindings.add(metrics.heightEstimateProperty(content), hbar.heightProperty()),
layoutHeight)));
hbar.visibleProperty().bind(needsHBar);
vbar.visibleProperty().bind(needsVBar);
// request layout later, because if currently in layout, the request is ignored
hbar.visibleProperty().addListener(obs -> Platform.runLater(() -> requestLayout()));
vbar.visibleProperty().addListener(obs -> Platform.runLater(() -> requestLayout()));
getChildren().addAll(content, hbar, vbar);
}
@Override
public Orientation getContentBias() {
return content.getContentBias();
}
@Override
public double computePrefWidth(double height) {
return content.prefWidth(height)
+ (vbar.isVisible() ? vbar.prefWidth(-1) : 0);
}
@Override
public double computePrefHeight(double width) {
return content.prefHeight(width)
+ (hbar.isVisible() ? hbar.prefHeight(-1) : 0);
}
@Override
public double computeMinWidth(double height) {
return content.minWidth(height)
+ (vbar.isVisible() ? vbar.minWidth(-1) : 0);
}
@Override
public double computeMinHeight(double width) {
return content.minHeight(width)
+ (hbar.isVisible() ? hbar.minHeight(-1) : 0);
}
@Override
public double computeMaxWidth(double height) {
return content.maxWidth(height)
+ (vbar.isVisible() ? vbar.maxWidth(-1) : 0);
}
@Override
public double computeMaxHeight(double width) {
return content.maxHeight(width)
+ (hbar.isVisible() ? hbar.maxHeight(-1) : 0);
}
@Override
protected void layoutChildren() {
double layoutWidth = getLayoutBounds().getWidth();
double layoutHeight = getLayoutBounds().getHeight();
boolean vbarVisible = vbar.isVisible();
boolean hbarVisible = hbar.isVisible();
double vbarWidth = vbarVisible ? vbar.prefWidth(-1) : 0;
double hbarHeight = hbarVisible ? hbar.prefHeight(-1) : 0;
double w = layoutWidth - vbarWidth;
double h = layoutHeight - hbarHeight;
content.resizeRelocate(0, 0, w, h);
hbar.setVisibleAmount(w);
vbar.setVisibleAmount(h);
if(vbarVisible) {
vbar.resizeRelocate(layoutWidth - vbarWidth, 0, vbarWidth, h);
}
if(hbarVisible) {
hbar.resizeRelocate(0, layoutHeight - hbarHeight, w, hbarHeight);
}
}
private static void setupUnitIncrement(ScrollBar bar) {
bar.unitIncrementProperty().bind(new DoubleBinding() {
{ bind(bar.maxProperty(), bar.visibleAmountProperty()); }
@Override
protected double computeValue() {
double max = bar.getMax();
double visible = bar.getVisibleAmount();
return max > visible
? 13 / (max - visible) * max
: 0;
}
});
}
}
class VirtualFlowContent<T, C extends Node> extends Region {
private final List<T> items;
private final List<C> cells;
private final CellFactory<T, C> cellFactory;
private final Metrics metrics;
private final BreadthTracker breadthTracker;
private final IntegerProperty prefCellCount = new SimpleIntegerProperty(20);
private final Queue<C> cellPool = new LinkedList<>();
private double visibleLength = 0; // total length of all visible cells
private int renderedFrom = 0; // index of the first item that has a cell
private Optional<IndexRange> hole = Optional.empty();
// offset of the content in breadth axis, <= 0
private double breadthOffset = 0;
private final DoubleBinding totalBreadthEstimate;
public ObservableDoubleValue totalBreadthEstimateProperty() {
return totalBreadthEstimate;
}
private final DoubleBinding totalLengthEstimate;
public ObservableDoubleValue totalLengthEstimateProperty() {
return totalLengthEstimate;
}
private final DoubleBinding breadthPositionEstimate;
public ObservableDoubleValue breadthPositionEstimateProperty() {
return breadthPositionEstimate;
}
private final DoubleBinding lengthOffsetEstimate;
private final DoubleBinding lengthPositionEstimate;
public ObservableDoubleValue lengthPositionEstimateProperty() {
return lengthPositionEstimate;
}
VirtualFlowContent(ObservableList<T> items, CellFactory<T, C> cellFactory, Metrics metrics) {
this.items = items;
this.cellFactory = cellFactory;
this.metrics = metrics;
this.breadthTracker = new BreadthTracker(items.size());
@SuppressWarnings("unchecked")
ObservableList<C> cells = (ObservableList<C>) getChildren();
this.cells = cells;
Rectangle clipRect = new Rectangle();
setClip(clipRect);
layoutBoundsProperty().addListener((obs, oldBounds, newBounds) -> {
clipRect.setWidth(newBounds.getWidth());
clipRect.setHeight(newBounds.getHeight());
layoutBoundsChanged(oldBounds, newBounds);
});
items.addListener((ListChangeListener<? super T>) ch -> {
while(ch.next()) {
int pos = ch.getFrom();
int removedSize;
int addedSize;
if(ch.wasPermutated()) {
addedSize = removedSize = ch.getTo() - pos;
} else {
removedSize = ch.getRemovedSize();
addedSize = ch.getAddedSize();
}
itemsReplaced(pos, removedSize, addedSize);
}
});
// set up bindings
totalBreadthEstimate = new DoubleBinding() {
@Override
protected double computeValue() {
return maxKnownBreadth();
}
};
totalLengthEstimate = new DoubleBinding() {
@Override
protected double computeValue() {
return hasVisibleCells()
? visibleLength / visibleCells().count() * items.size()
: 0;
}
};
breadthPositionEstimate = new DoubleBinding() {
@Override
protected double computeValue() {
if(items.isEmpty()) {
return 0;
}
double total = maxKnownBreadth();
if(total <= breadth()) {
return 0;
}
return breadthPixelsToPosition(-breadthOffset);
}
};
lengthOffsetEstimate = new DoubleBinding() {
@Override
protected double computeValue() {
if(items.isEmpty()) {
return 0;
}
double total = totalLengthEstimate.get();
if(total <= length()) {
return 0;
}
double avgLen = total / items.size();
double beforeVisible = firstVisibleRange().getStart() * avgLen;
return beforeVisible - visibleCellsMinY();
}
};
lengthPositionEstimate = new DoubleBinding() {
{ bind(lengthOffsetEstimate); }
@Override
protected double computeValue() {
return pixelsToPosition(lengthOffsetEstimate.get());
}
};
}
@Override
protected void layoutChildren() {
// do nothing
}
@Override
protected final double computePrefWidth(double height) {
switch(getContentBias()) {
case HORIZONTAL: // vertical flow
return computePrefBreadth();
case VERTICAL: // horizontal flow
return computePrefLength(height);
default:
throw new AssertionError("Unreachable code");
}
}
@Override
protected final double computePrefHeight(double width) {
switch(getContentBias()) {
case HORIZONTAL: // vertical flow
return computePrefLength(width);
case VERTICAL: // horizontal flow
return computePrefBreadth();
default:
throw new AssertionError("Unreachable code");
}
}
private double computePrefBreadth() {
// take maximum of all rendered cells,
// but first ensure there are at least 10 rendered cells
ensureRenderedCells(10);
return cells.stream()
.mapToDouble(metrics::prefBreadth)
.reduce(0, (a, b) -> Math.max(a, b));
}
private double computePrefLength(double breadth) {
int n = prefCellCount.get();
ensureRenderedCells(n);
return cells.stream().limit(n)
.mapToDouble(cell -> metrics.prefLength(cell, breadth))
.sum();
}
@Override
public final Orientation getContentBias() {
return metrics.getContentBias();
}
protected final void setLengthPosition(double pos) {
setLengthOffset(positionToPixels(pos));
}
protected final void setBreadthPosition(double pos) {
setBreadthOffset(breadthPositionToPixels(pos));
}
protected final void scrollLength(double deltaLength) {
setLengthOffset(lengthOffsetEstimate.get() - deltaLength);
}
protected final void scrollBreadth(double deltaBreadth) {
setBreadthOffset(breadthOffset - deltaBreadth);
}
private void ensureRenderedCells(int n) {
for(int i = cells.size(); i < n; ++i) {
if(hole.isPresent()) {
render(hole.get().getStart());
} else if(renderedFrom > 0) {
render(renderedFrom - 1);
} else if(renderedFrom + cells.size() < items.size()) {
render(renderedFrom + cells.size());
} else {
break;
}
}
}
private C renderInitial(int index) {
if(!cells.isEmpty()) {
throw new IllegalStateException("There are some rendered cells already");
}
renderedFrom = index;
visibleLength = 0;
return render(index, 0);
}
private C render(int index, int childInsertionPos) {
T item = items.get(index);
C cell = createCell(index, item);
cell.setVisible(false);
cells.add(childInsertionPos, cell);
cell.applyCss();
return cell;
}
private C render(int index) {
int renderedTo = renderedFrom + cells.size() + hole.map(IndexRange::getLength).orElse(0);
if(index < renderedFrom - 1) {
throw new IllegalArgumentException("Cannot render " + index + ". Rendered cells start at " + renderedFrom);
} else if(index == renderedFrom - 1) {
C cell = render(index, 0);
renderedFrom -= 1;
return cell;
} else if(index == renderedTo) {
return render(index, cells.size());
} else if(index > renderedTo) {
throw new IllegalArgumentException("Cannot render " + index + ". Rendered cells end at " + renderedTo);
} else if(hole.isPresent()) {
IndexRange hole = this.hole.get();
if(index < hole.getStart()) {
return cells.get(index - renderedFrom);
} else if(index >= hole.getEnd()) {
return cells.get(index - renderedFrom - hole.getLength());
} else if(index == hole.getStart()) {
C cell = render(index, index - renderedFrom);
this.hole = hole.getLength() == 1
? Optional.empty()
: Optional.of(new IndexRange(index + 1, hole.getEnd()));
return cell;
} else if(index == hole.getEnd() - 1) {
C cell = render(index, hole.getStart() - renderedFrom);
this.hole = Optional.of(new IndexRange(hole.getStart(), hole.getEnd() - 1));
return cell;
} else {
throw new IllegalArgumentException("Cannot render " + index + " inside hole " + hole);
}
} else {
return cells.get(index - renderedFrom);
}
}
private C createCell(int index, T item) {
C cell;
C cachedCell = getFromPool();
if(cachedCell != null) {
cell = cellFactory.createCell(index, item, cachedCell);
if(cell != cachedCell) {
cellFactory.disposeCell(cachedCell);
}
} else {
cell = cellFactory.createCell(index, item);
}
cell.setManaged(false);
return cell;
}
private C getFromPool() {
return cellPool.poll();
}
private void addToPool(C cell) {
if(cell.isVisible()) {
visibleLength -= metrics.length(cell);
}
cellFactory.resetCell(cell);
cellPool.add(cell);
}
private void cullFrom(int pos) {
if(hole.isPresent()) {
IndexRange hole = this.hole.get();
if(pos >= hole.getEnd()) {
dropCellsFrom(pos - hole.getLength() - renderedFrom);
} else if(pos > hole.getStart()) {
dropCellsFrom(hole.getStart() - renderedFrom);
this.hole = Optional.of(new IndexRange(hole.getStart(), pos));
} else {
dropCellsFrom(pos - renderedFrom);
this.hole = Optional.empty();
}
} else {
dropCellsFrom(pos - renderedFrom);
}
}
private void cullBefore(int pos) {
if(hole.isPresent()) {
IndexRange hole = this.hole.get();
if(pos <= hole.getStart()) {
dropCellsBefore(pos - renderedFrom);
} else if(pos < hole.getEnd()) {
dropCellsBefore(hole.getStart() - renderedFrom);
this.hole = Optional.of(new IndexRange(pos, hole.getEnd()));
} else {
dropCellsBefore(pos - hole.getLength() - renderedFrom);
this.hole = Optional.empty();
}
} else {
dropCellsBefore(pos - renderedFrom);
}
renderedFrom = pos;
}
private void dropCellsFrom(int cellIdx) {
dropCellRange(cellIdx, cells.size());
}
private void dropCellsBefore(int cellIdx) {
dropCellRange(0, cellIdx);
}
private void dropCellRange(int from, int to) {
List<C> toDrop = cells.subList(from, to);
toDrop.forEach(this::addToPool);
toDrop.clear();
}
private void layoutBoundsChanged(Bounds oldBounds, Bounds newBounds) {
double oldBreadth = metrics.breadth(oldBounds);
double newBreadth = metrics.breadth(newBounds);
double minBreadth = maxKnownBreadth();
double breadth = Math.max(minBreadth, newBreadth);
// adjust breadth of visible cells
if(oldBreadth != newBreadth) {
if(oldBreadth <= minBreadth && newBreadth <= minBreadth) {
// do nothing
} else {
resizeVisibleCells(breadth);
}
}
if(breadth + breadthOffset < newBreadth) { // empty space on the right
shiftVisibleCellsByBreadth(newBreadth - (breadth + breadthOffset));
}
// fill current screen
fillViewport(0);
totalBreadthEstimate.invalidate();
totalLengthEstimate.invalidate();
breadthPositionEstimate.invalidate();
lengthOffsetEstimate.invalidate();
}
private void itemsReplaced(int pos, int removedSize, int addedSize) {
if(hole.isPresent()) {
throw new IllegalStateException("change in items before hole was closed");
}
breadthTracker.itemsReplaced(pos, removedSize, addedSize);
if(pos >= renderedFrom + cells.size()) {
// does not affect any cells, do nothing
} else if(pos + removedSize <= renderedFrom) {
// change before rendered cells, just update indices
int delta = addedSize - removedSize;
renderedFrom += delta;
for(int i = 0; i < cells.size(); ++i) {
cellFactory.updateIndex(cells.get(i), renderedFrom + i);
}
} else if(pos > renderedFrom && pos + removedSize < renderedFrom + cells.size()) {
// change within rendered cells,
// at least one cell retained on both sides
dropCellRange(pos - renderedFrom, pos + removedSize - renderedFrom);
for(int i = pos + renderedFrom; i < cells.size(); ++i) {
cellFactory.updateIndex(cells.get(i), pos + addedSize + i);
}
if(addedSize > 0) {
// creating a hole in rendered cells
hole = Optional.of(new IndexRange(pos, pos + addedSize));
}
} else if(pos > renderedFrom) {
dropCellsFrom(pos - renderedFrom);
} else if(pos + removedSize >= renderedFrom + cells.size()) {
// all rendered items removed
dropCellsFrom(0);
renderedFrom = 0;
visibleLength = 0;
} else {
dropCellsBefore(pos + removedSize - renderedFrom);
renderedFrom = pos + addedSize;
for(int i = 0; i < cells.size(); ++i) {
cellFactory.updateIndex(cells.get(i), pos + i);
}
}
fillViewport(pos);
totalBreadthEstimate.invalidate();
totalLengthEstimate.invalidate();
breadthPositionEstimate.invalidate();
lengthOffsetEstimate.invalidate();
}
private void fillViewport(int ifEmptyStartWith) {
if(!hasVisibleCells()) {
if(hole.isPresent()) {
// There is a hole in rendered cells.
// Place its first item at the start of the viewport.
shrinkHoleFromLeft(0.0);
} else if(!cells.isEmpty()) {
// There are at least some rendered cells.
// Place the first one at 0.
placeAt(renderedFrom, cells.get(0), 0.0);
} else if(!items.isEmpty()) {
// use the hint
int idx = ifEmptyStartWith < 0 ? 0
: ifEmptyStartWith >= items.size() ? items.size() - 1
: ifEmptyStartWith;
placeInitialAtStart(idx);
} else {
return;
}
}
fillViewport();
}
private void fillViewport() {
if(!hasVisibleCells()) {
throw new IllegalStateException("need a visible cell to start from");
}
double breadth = Math.max(maxKnownBreadth(), breadth());
boolean repeat = true;
while(repeat) {
fillViewportOnce();
if(maxKnownBreadth() > breadth) { // broader cell encountered
breadth = maxKnownBreadth();
resizeVisibleCells(breadth);
} else {
repeat = false;
}
}
// cull, but first eliminate the hole
if(hole.isPresent()) {
IndexRange hole = this.hole.get();
if(hole.getStart() > renderedFrom) {
C cellBeforeHole = cells.get(hole.getStart() - 1 - renderedFrom);
if(!cellBeforeHole.isVisible() || metrics.maxY(cellBeforeHole) <= 0) {
cullBefore(hole.getEnd());
} else {
cullFrom(hole.getStart());
}
} else {
cullBefore(hole.getEnd());
}
}
cullBeforeViewport();
cullAfterViewport();
}
private void fillViewportOnce() {
// expand the visible range
IndexRange visibleRange = firstVisibleRange();
int firstVisible = visibleRange.getStart();
int lastVisible = visibleRange.getEnd() - 1;
// fill backward until 0 is covered
firstVisible = paveBackwardTo(0.0, firstVisible);
double minY = metrics.minY(getVisibleCell(firstVisible));
if(minY > 0) {
shiftVisibleCellsByLength(-minY);
minY = 0;
}
// fill forward until end of viewport is covered
double length = length();
lastVisible = paveForwardTo(length, lastVisible);
double maxY = metrics.maxY(getVisibleCell(lastVisible));
double leftToFill = length - maxY;
if(leftToFill > 0) {
firstVisible = paveBackwardTo(-leftToFill, firstVisible);
minY = metrics.minY(getVisibleCell(firstVisible));
double shift = Math.min(-minY, leftToFill);
shiftVisibleCellsByLength(shift);
}
}
private int paveForwardTo(double y, int startAfter) {
int i = startAfter;
C cell = getVisibleCell(i);
double maxY = metrics.maxY(cell);
while(maxY < y && i < items.size() - 1) {
cell = placeAt(++i, maxY);
maxY = metrics.maxY(cell);
}
return i;
}
private int paveBackwardTo(double y, int startBefore) {
int i = startBefore;
C cell = getVisibleCell(i);
double minY = metrics.minY(cell);
while(minY > y && i > 0) {
cell = placeEndAt(--i, minY);
minY = metrics.minY(cell);
}
return i;
}
private void cullBeforeViewport() {
if(hole.isPresent()) {
throw new IllegalStateException("unexpected hole");
}
// find first in the viewport
int i = 0;
for(; i < cells.size(); ++i) {
C cell = cells.get(i);
if(cell.isVisible() && metrics.maxY(cell) > 0) {
break;
}
}
cullBefore(renderedFrom + i);
}
private void cullAfterViewport() {
if(hole.isPresent()) {
throw new IllegalStateException("unexpected hole");
}
// find first after the viewport
int i = 0;
for(; i < cells.size(); ++i) {
C cell = cells.get(i);
if(!cell.isVisible() || metrics.minY(cell) >= length()) {
break;
}
}
cullFrom(renderedFrom + i);
}
private C getVisibleCell(int itemIdx) {
if(itemIdx < renderedFrom) {
throw new IllegalArgumentException("Item " + itemIdx + " is not visible");
} else if(hole.isPresent()) {
IndexRange hole = this.hole.get();
C cell;
if(itemIdx < hole.getStart()) {
cell = cells.get(itemIdx - renderedFrom);
} else if(itemIdx < hole.getEnd()) {
throw new IllegalArgumentException("Item " + itemIdx + " is not visible");
} else if(itemIdx < renderedFrom + hole.getLength() + cells.size()) {
cell = cells.get(itemIdx - hole.getLength() - renderedFrom);
} else {
throw new IllegalArgumentException("Item " + itemIdx + " is not visible");
}
if(cell.isVisible()) {
return cell;
} else {
throw new IllegalArgumentException("Item " + itemIdx + " is not visible");
}
} else if(itemIdx >= renderedFrom + cells.size()) {
throw new IllegalArgumentException("Item " + itemIdx + " is not visible");
} else {
C cell = cells.get(itemIdx - renderedFrom);
if(cell.isVisible()) {
return cell;
} else {
throw new IllegalArgumentException("Item " + itemIdx + " is not visible");
}
}
}
private boolean hasVisibleCells() {
return cells.stream().anyMatch(Node::isVisible);
}
private void shrinkHoleFromLeft(double placeAtY) {
int itemIdx = hole.get().getStart();
int cellIdx = itemIdx - renderedFrom;
C cell = render(itemIdx, cellIdx);
placeAt(itemIdx, cell, placeAtY);
hole = hole.get().getLength() == 1
? Optional.empty()
: Optional.of(new IndexRange(itemIdx + 1, hole.get().getEnd()));
}
private void placeAt(int itemIdx, C cell, double y) {
double minBreadth = metrics.minBreadth(cell);
breadthTracker.reportBreadth(itemIdx, minBreadth);
double breadth = Math.max(maxKnownBreadth(), breadth());
double length = metrics.prefLength(cell, breadth);
layoutCell(cell, y, breadth, length);
}
private void placeEndAt(int itemIdx, C cell, double endY) {
double minBreadth = metrics.minBreadth(cell);
breadthTracker.reportBreadth(itemIdx, minBreadth);
double breadth = Math.max(maxKnownBreadth(), breadth());
double length = metrics.prefLength(cell, breadth);
layoutCell(cell, endY - length, breadth, length);
}
private C placeAt(int itemIdx, double y) {
C cell = render(itemIdx);
placeAt(itemIdx, cell, y);
return cell;
}
private C placeEndAt(int itemIdx, double endY) {
C cell = render(itemIdx);
placeEndAt(itemIdx, cell, endY);
return cell;
}
private void placeInitialAt(int itemIdx, double y) {
C cell = renderInitial(itemIdx);
placeAt(itemIdx, cell, y);
}
private void placeInitialAtStart(int itemIdx) {
placeInitialAt(itemIdx, 0.0);
}
private void placeInitialAtEnd(int itemIdx) {
C cell = renderInitial(itemIdx);
double length = length();
placeAt(itemIdx, cell, length - metrics.length(cell));
}
private void layoutCell(C cell, double l0, double breadth, double length) {
if(cell.isVisible()) {
visibleLength -= metrics.length(cell);
} else {
cell.setVisible(true);
}
visibleLength += length;
metrics.resizeRelocate(cell, breadthOffset, l0, breadth, length);
}
private void shiftVisibleCellsByLength(double shift) {
visibleCells().forEach(cell -> {
metrics.relocate(cell, breadthOffset, metrics.minY(cell) + shift);
});
}
private void shiftVisibleCellsByBreadth(double shift) {
breadthOffset += shift;
visibleCells().forEach(cell -> {
metrics.relocate(cell, breadthOffset, metrics.minY(cell));
});
}
private void resizeVisibleCells(double breadth) {
if(hole.isPresent()) {
throw new IllegalStateException("unexpected hole in rendered cells");
}
double y = visibleCellsMinY();
for(C cell: cells) {
if(cell.isVisible()) {
double length = metrics.prefLength(cell, breadth);
layoutCell(cell, y, breadth, length);
y += length;
}
}
}
private Stream<C> visibleCells() {
return cells.stream().filter(Node::isVisible);
}
private double maxKnownBreadth() {
return breadthTracker.maxKnownBreadth();
}
private double length() {
return metrics.length(this);
}
private double breadth() {
return metrics.breadth(this);
}
private double visibleCellsMinY() {
return visibleCells().findFirst().map(metrics::minY).orElse(0.0);
}
private IndexRange firstVisibleRange() {
if(cells.isEmpty()) {
throw new IllegalStateException("no rendered cells");
}
if(hole.isPresent()) {
IndexRange rng = visibleRangeIn(0, hole.get().getStart() - renderedFrom);
if(rng != null) {
return new IndexRange(rng.getStart() + renderedFrom, rng.getEnd() + renderedFrom);
} else if((rng = visibleRangeIn(hole.get().getStart() - renderedFrom, cells.size())) != null) {
return new IndexRange(rng.getStart() + hole.get().getLength() + renderedFrom, rng.getEnd() + hole.get().getLength() + renderedFrom);
} else {
throw new IllegalStateException("no visible cells");
}
} else {
IndexRange rng = visibleRangeIn(0, cells.size());
if(rng != null) {
return new IndexRange(rng.getStart() + renderedFrom, rng.getEnd() + renderedFrom);
} else {
throw new IllegalStateException("no visible cells");
}
}
}
private IndexRange visibleRangeIn(int from, int to) {
int a;
for(a = from; a < to; ++a) {
if(cells.get(a).isVisible()) {
break;
}
}
if(a < to) {
int b;
for(b = a + 1; b < to; ++b) {
if(!cells.get(b).isVisible()) {
break;
}
}
return new IndexRange(a, b);
} else {
return null;
}
}
private void setLengthOffset(double pixels) {
double total = totalLengthEstimate.get();
double length = length();
double max = Math.max(total - length, 0);
double current = lengthOffsetEstimate.get();
if(pixels > max) pixels = max;
if(pixels < 0) pixels = 0;
double diff = pixels - current;
if(Math.abs(diff) < length) { // distance less than one screen
shiftVisibleCellsByLength(-diff);
fillViewport(0);
} else {
goToY(pixels);
}
totalBreadthEstimate.invalidate();
totalLengthEstimate.invalidate();
lengthOffsetEstimate.invalidate();
}
private void setBreadthOffset(double pixels) {
double total = totalBreadthEstimate.get();
double breadth = breadth();
double max = Math.max(total - breadth, 0);
double current = -breadthOffset;
if(pixels > max) pixels = max;
if(pixels < 0) pixels = 0;
if(pixels != current) {
shiftVisibleCellsByBreadth(current - pixels);
breadthPositionEstimate.invalidate();
}
}
private void goToY(double pixels) {
if(items.isEmpty()) {
return;
}
// guess the first visible cell and its offset in the viewport
double total = totalLengthEstimate.get();
double avgLen = total / items.size();
if(avgLen == 0) return;
int first = (int) Math.floor(pixels / avgLen);
double firstOffset = -(pixels % avgLen);
// remove all cells
cullFrom(renderedFrom);
if(first < items.size()) {
placeInitialAt(first, firstOffset);
fillViewport();
} else {
placeInitialAtEnd(items.size()-1);
fillViewport();
}
}
private double pixelsToPosition(double pixels) {
double total = totalLengthEstimate.get();
double length = length();
return total > length
? pixels / (total - length) * total
: 0;
}
private double positionToPixels(double pos) {
double total = totalLengthEstimate.get();
double length = length();
return total > 0 && total > length
? pos / total * (total - length())
: 0;
}
private double breadthPixelsToPosition(double pixels) {
double total = totalBreadthEstimate.get();
double breadth = breadth();
return total > breadth
? pixels / (total - breadth) * total
: 0;
}
private double breadthPositionToPixels(double pos) {
double total = totalBreadthEstimate.get();
double breadth = breadth();
return total > 0 && total > breadth
? pos / total * (total - breadth)
: 0;
}
}
final class BreadthTracker {
private final List<Double> breadths; // NaN means not known
private double maxKnownBreadth = 0; // NaN means needs recomputing
BreadthTracker(int initSize) {
breadths = new ArrayList<>(initSize);
for(int i = 0; i < initSize; ++i) {
breadths.add(Double.NaN);
}
}
void reportBreadth(int itemIdx, double breadth) {
breadths.set(itemIdx, breadth);
if(!Double.isNaN(maxKnownBreadth) && breadth > maxKnownBreadth) {
maxKnownBreadth = breadth;
}
}
void itemsReplaced(int pos, int removedSize, int addedSize) {
List<Double> remBreadths = breadths.subList(pos, pos + removedSize);
for(double b: remBreadths) {
if(b == maxKnownBreadth) {
maxKnownBreadth = Double.NaN;
break;
}
}
remBreadths.clear();
for(int i = 0; i < addedSize; ++i) {
remBreadths.add(Double.NaN);
}
}
double maxKnownBreadth() {
if(Double.isNaN(maxKnownBreadth)) {
maxKnownBreadth = breadths.stream()
.filter(x -> !Double.isNaN(x))
.mapToDouble(x -> x)
.reduce(0, (a, b) -> Math.max(a, b));
}
return maxKnownBreadth;
}
}
interface Metrics {
Orientation getContentBias();
double length(Bounds bounds);
double breadth(Bounds bounds);
double minY(Bounds bounds);
double maxY(Bounds bounds);
default double length(Node cell) { return length(cell.getLayoutBounds()); }
default double breadth(Node cell) { return breadth(cell.getLayoutBounds()); }
default double minY(Node cell) { return minY(cell.getBoundsInParent()); }
default double maxY(Node cell) { return maxY(cell.getBoundsInParent()); }
double minBreadth(Node cell);
double prefBreadth(Node cell);
double prefLength(Node cell, double breadth);
void resizeRelocate(Node cell, double b0, double l0, double breadth, double length);
void relocate(Node cell, double b0, double l0);
ObservableDoubleValue widthEstimateProperty(VirtualFlowContent<?, ?> content);
ObservableDoubleValue heightEstimateProperty(VirtualFlowContent<?, ?> content);
ObservableDoubleValue horizontalPositionProperty(VirtualFlowContent<?, ?> content);
ObservableDoubleValue verticalPositionProperty(VirtualFlowContent<?, ?> content);
void setHorizontalPosition(VirtualFlowContent<?, ?> content, double pos);
void setVerticalPosition(VirtualFlowContent<?, ?> content, double pos);
void scrollHorizontally(VirtualFlowContent<?, ?> content, double dx);
void scrollVertically(VirtualFlowContent<?, ?> content, double dy);
default double getHorizontalPosition(VirtualFlowContent<?, ?> content) {
return horizontalPositionProperty(content).get();
}
default double getVerticalPosition(VirtualFlowContent<?, ?> content) {
return verticalPositionProperty(content).get();
}
}
final class HorizontalFlowMetrics implements Metrics {
@Override
public Orientation getContentBias() {
return Orientation.VERTICAL;
}
@Override
public double minBreadth(Node cell) {
return cell.minHeight(-1);
}
@Override
public double prefBreadth(Node cell) {
return cell.prefHeight(-1);
}
@Override
public double prefLength(Node cell, double breadth) {
return cell.prefWidth(breadth);
}
@Override
public double breadth(Bounds bounds) {
return bounds.getHeight();
}
@Override
public double length(Bounds bounds) {
return bounds.getWidth();
}
@Override
public double maxY(Bounds bounds) {
return bounds.getMaxX();
}
@Override
public double minY(Bounds bounds) {
return bounds.getMinX();
}
@Override
public void resizeRelocate(
Node cell, double b0, double l0, double breadth, double length) {
cell.resizeRelocate(l0, b0, length, breadth);
}
@Override
public void relocate(Node cell, double b0, double l0) {
cell.relocate(l0, b0);
}
@Override
public ObservableDoubleValue widthEstimateProperty(
VirtualFlowContent<?, ?> content) {
return content.totalLengthEstimateProperty();
}
@Override
public ObservableDoubleValue heightEstimateProperty(
VirtualFlowContent<?, ?> content) {
return content.totalBreadthEstimateProperty();
}
@Override
public ObservableDoubleValue horizontalPositionProperty(
VirtualFlowContent<?, ?> content) {
return content.lengthPositionEstimateProperty();
}
@Override
public ObservableDoubleValue verticalPositionProperty(
VirtualFlowContent<?, ?> content) {
return content.breadthPositionEstimateProperty();
}
@Override
public void setHorizontalPosition(VirtualFlowContent<?, ?> content,
double pos) {
content.setLengthPosition(pos);
}
@Override
public void setVerticalPosition(VirtualFlowContent<?, ?> content, double pos) {
content.setBreadthPosition(pos);
}
@Override
public void scrollHorizontally(VirtualFlowContent<?, ?> content, double dx) {
content.scrollLength(dx);
}
@Override
public void scrollVertically(VirtualFlowContent<?, ?> content, double dy) {
content.scrollBreadth(dy);
}
}
final class VerticalFlowMetrics implements Metrics {
@Override
public Orientation getContentBias() {
return Orientation.HORIZONTAL;
}
@Override
public double minBreadth(Node cell) {
return cell.minWidth(-1);
}
@Override
public double prefBreadth(Node cell) {
return cell.prefWidth(-1);
}
@Override
public double prefLength(Node cell, double breadth) {
return cell.prefHeight(breadth);
}
@Override
public double breadth(Bounds bounds) {
return bounds.getWidth();
}
@Override
public double length(Bounds bounds) {
return bounds.getHeight();
}
@Override
public double maxY(Bounds bounds) {
return bounds.getMaxY();
}
@Override
public double minY(Bounds bounds) {
return bounds.getMinY();
}
@Override
public void resizeRelocate(
Node cell, double b0, double l0, double breadth, double length) {
cell.resizeRelocate(b0, l0, breadth, length);
}
@Override
public void relocate(Node cell, double b0, double l0) {
cell.relocate(b0, l0);
}
@Override
public ObservableDoubleValue widthEstimateProperty(
VirtualFlowContent<?, ?> content) {
return content.totalBreadthEstimateProperty();
}
@Override
public ObservableDoubleValue heightEstimateProperty(
VirtualFlowContent<?, ?> content) {
return content.totalLengthEstimateProperty();
}
@Override
public ObservableDoubleValue horizontalPositionProperty(
VirtualFlowContent<?, ?> content) {
return content.breadthPositionEstimateProperty();
}
@Override
public ObservableDoubleValue verticalPositionProperty(
VirtualFlowContent<?, ?> content) {
return content.lengthPositionEstimateProperty();
}
@Override
public void setHorizontalPosition(VirtualFlowContent<?, ?> content,
double pos) {
content.setBreadthPosition(pos);
}
@Override
public void setVerticalPosition(VirtualFlowContent<?, ?> content, double pos) {
content.setLengthPosition(pos);
}
@Override
public void scrollHorizontally(VirtualFlowContent<?, ?> content, double dx) {
content.scrollBreadth(dx);
}
@Override
public void scrollVertically(VirtualFlowContent<?, ?> content, double dy) {
content.scrollLength(dy);
}
}
|
package com.sandwell.JavaSimulation3D;
import java.util.ArrayList;
import com.jaamsim.Graphics.DisplayEntity;
import com.jaamsim.basicsim.Entity;
import com.jaamsim.datatypes.DoubleVector;
import com.jaamsim.input.IntegerInput;
import com.jaamsim.input.Keyword;
import com.jaamsim.input.Output;
import com.jaamsim.input.ValueInput;
import com.jaamsim.math.Vec3d;
import com.jaamsim.units.DimensionlessUnit;
import com.jaamsim.units.DistanceUnit;
import com.jaamsim.units.TimeUnit;
import com.sandwell.JavaSimulation.FileEntity;
public class Queue extends DisplayEntity {
@Keyword(description = "The amount of graphical space shown between DisplayEntity objects in the queue.",
example = "Queue1 Spacing { 1 m }")
private final ValueInput spacingInput;
@Keyword(description = "The number of queuing entities in each row.",
example = "Queue1 MaxPerLine { 4 }")
protected final IntegerInput maxPerLineInput; // maximum items per sub line-up of queue
protected ArrayList<DisplayEntity> itemList;
private ArrayList<Double> timeAddedList;
// Statistics
protected double timeOfLastUpdate; // time at which the statistics were last updated
protected double startOfStatisticsCollection; // time at which statistics collection was started
protected int minElements; // minimum observed number of entities in the queue
protected int maxElements; // maximum observed number of entities in the queue
protected double elementSeconds; // total time that entities have spent in the queue
protected double squaredElementSeconds; // total time for the square of the number of elements in the queue
protected int numberAdded; // number of entities that have been added to the queue
protected int numberRemoved; // number of entities that have been removed from the queue
protected DoubleVector queueLengthDist; // entry at position n is the total time the queue has had length n
protected ArrayList<QueueRecorder> recorderList;
{
this.setDefaultSize(new Vec3d(0.5, 0.5, 0.5));
spacingInput = new ValueInput("Spacing", "Key Inputs", 0.0d);
spacingInput.setUnitType(DistanceUnit.class);
spacingInput.setValidRange(0.0d, Double.POSITIVE_INFINITY);
this.addInput(spacingInput);
maxPerLineInput = new IntegerInput("MaxPerLine", "Key Inputs", Integer.MAX_VALUE);
maxPerLineInput.setValidRange( 1, Integer.MAX_VALUE);
this.addInput(maxPerLineInput);
}
public Queue() {
itemList = new ArrayList<>();
timeAddedList = new ArrayList<>();
queueLengthDist = new DoubleVector(10,10);
}
@Override
public void earlyInit() {
super.earlyInit();
// Clear the entries in the queue
itemList.clear();
timeAddedList.clear();
// Clear statistics
this.clearStatistics();
recorderList = new ArrayList<>();
for( QueueRecorder rec : Entity.getClonesOfIterator( QueueRecorder.class ) ) {
if( rec.getQueueList().contains( this ) ) {
recorderList.add( rec );
}
}
}
// QUEUE HANDLING METHODS
/**
* Inserts the specified element at the specified position in this Queue.
* Shifts the element currently at that position (if any) and any subsequent elements to the right (adds one to their indices).
*/
public void add( int i, DisplayEntity perf ) {
this.updateStatistics(); // update the queue length distribution
itemList.add( i, perf );
timeAddedList.add( i, this.getSimTime() );
this.updateStatistics(); // update the min and max queue length
numberAdded++;
for( QueueRecorder rec : recorderList ) {
rec.add( perf, this );
}
}
/**
* Add an entity to the end of the queue
*/
public void addLast( DisplayEntity perf ) {
this.add(itemList.size(), perf);
}
/**
* Removes the entity at the specified position in the queue
*/
public DisplayEntity remove(int i) {
if (i >= itemList.size() || i < 0)
error("Index: %d is beyond the end of the queue.", i);
this.updateStatistics(); // update the queue length distribution
DisplayEntity out = itemList.remove(i);
//double queueTime = this.getSimTime() - timeAddedList.remove(i);
timeAddedList.remove(i);
this.updateStatistics(); // update the min and max queue length
numberRemoved++;
for( QueueRecorder rec : recorderList ) {
rec.remove( out, this );
}
return out;
}
/**
* Removes the specified entity from the queue
*/
public void remove( DisplayEntity perf ) {
int i = itemList.indexOf(perf);
if( i >= 0 )
this.remove(i);
else
error("Entity:%s not found in queue.", perf);
}
/**
* Removes the first entity from the queue
*/
public DisplayEntity removeFirst() {
return this.remove(0);
}
/**
* Removes the last entity from the queue
*/
public DisplayEntity removeLast() {
return this.remove( itemList.size()-1 );
}
/**
* Number of entities in the queue
*/
public int getCount() {
return itemList.size();
}
/**
* Returns the number of seconds spent by the first object in the queue
*/
public double getQueueTime() {
return this.getSimTime() - timeAddedList.get(0);
}
/**
* Update the position of all entities in the queue. ASSUME that entities
* will line up according to the orientation of the queue.
*/
@Override
public void updateGraphics( double simTime ) {
Vec3d queueOrientation = getOrientation();
Vec3d qSize = this.getSize();
Vec3d tmp = new Vec3d();
double distanceX = 0.5d * qSize.x;
double distanceY = 0;
double maxWidth = 0;
// find widest vessel
if( itemList.size() > maxPerLineInput.getValue()){
for (int j = 0; j < itemList.size(); j++) {
maxWidth = Math.max(maxWidth, itemList.get(j).getSize().y);
}
}
// update item locations
for (int i = 0; i < itemList.size(); i++) {
// if new row is required, set reset distanceX and move distanceY up one row
if( i > 0 && i % maxPerLineInput.getValue() == 0 ){
distanceX = 0.5d * qSize.x;
distanceY += spacingInput.getValue() + maxWidth;
}
DisplayEntity item = itemList.get(i);
// Rotate each transporter about its center so it points to the right direction
item.setOrientation(queueOrientation);
Vec3d itemSize = item.getSize();
distanceX += spacingInput.getValue() + 0.5d * itemSize.x;
tmp.set3(-distanceX / qSize.x, distanceY/qSize.y, 0.0d);
// increment total distance
distanceX += 0.5d * itemSize.x;
// Set Position
Vec3d itemCenter = this.getGlobalPositionForAlignment(tmp);
item.setPositionForAlignment(new Vec3d(), itemCenter);
}
}
public ArrayList<DisplayEntity> getItemList() {
return itemList;
}
public double getPhysicalLength() {
double length;
length = 0.0;
for( int x = 0; x < itemList.size(); x++ ) {
DisplayEntity item = itemList.get( x );
length += item.getSize().x + spacingInput.getValue();
}
return length;
}
/**
* Returns the position for a new entity at the end of the queue.
*/
public Vec3d getEndVector3dFor(DisplayEntity perf) {
Vec3d qSize = this.getSize();
double distance = 0.5d * qSize.x;
for (int x = 0; x < itemList.size(); x++) {
DisplayEntity item = itemList.get(x);
distance += spacingInput.getValue() + item.getSize().x;
}
distance += spacingInput.getValue() + 0.5d * perf.getSize().x;
Vec3d tempAlign = new Vec3d(-distance / qSize.x, 0.0d, 0.0d);
return this.getPositionForAlignment(tempAlign);
}
// STATISTICS
/**
* Clear queue statistics
*/
@Override
public void clearStatistics() {
double simTime = this.getSimTime();
startOfStatisticsCollection = simTime;
timeOfLastUpdate = simTime;
minElements = itemList.size();
maxElements = itemList.size();
elementSeconds = 0.0;
squaredElementSeconds = 0.0;
numberAdded = 0;
numberRemoved = 0;
queueLengthDist.clear();
}
public void updateStatistics() {
int queueSize = itemList.size(); // present number of entities in the queue
minElements = Math.min(queueSize, minElements);
maxElements = Math.max(queueSize, maxElements);
// Add the necessary number of additional bins to the queue length distribution
int n = queueSize + 1 - queueLengthDist.size();
for( int i=0; i<n; i++ ) {
queueLengthDist.add(0.0);
}
double simTime = this.getSimTime();
double dt = simTime - timeOfLastUpdate;
if( dt > 0.0 ) {
elementSeconds += dt * queueSize;
squaredElementSeconds += dt * queueSize * queueSize;
queueLengthDist.addAt(dt,queueSize); // add dt to the entry at index queueSize
timeOfLastUpdate = simTime;
}
}
// OUTPUT METHODS
public void printUtilizationOn( FileEntity anOut ) {
if (isActive()) {
anOut.format( "%s\t", getName() );
anOut.format( "%d\t", this.getQueueLengthMinimum(0.0) );
anOut.format( "%d\t", this.getQueueLengthMaximum(0.0) );
anOut.format( "%.0f\t", this.getQueueLength(0.0) );
anOut.format( "\n" );
}
}
public void printUtilizationHeaderOn( FileEntity anOut ) {
anOut.format( "Name\t" );
anOut.format( "Min Elements\t" );
anOut.format( "Max Elements\t" );
anOut.format( "Present Elements\t" );
anOut.format( "\n" );
}
@Output(name = "NumberAdded",
description = "The number of entities that have been added to the queue.",
unitType = DimensionlessUnit.class,
reportable = true)
public Integer getNumberAdded(double simTime) {
return numberAdded;
}
@Output(name = "NumberRemoved",
description = "The number of entities that have been removed from the queue.",
unitType = DimensionlessUnit.class,
reportable = true)
public Integer getNumberRemoved(double simTime) {
return numberRemoved;
}
@Output(name = "QueueLength",
description = "The present number of entities in the queue.",
unitType = DimensionlessUnit.class)
public double getQueueLength(double simTime) {
return itemList.size();
}
@Output(name = "QueueLengthAverage",
description = "The average number of entities in the queue.",
unitType = DimensionlessUnit.class,
reportable = true)
public double getQueueLengthAverage(double simTime) {
double dt = simTime - timeOfLastUpdate;
int queueSize = itemList.size();
double totalTime = simTime - startOfStatisticsCollection;
if( totalTime > 0.0 ) {
return (elementSeconds + dt*queueSize)/totalTime;
}
return 0.0;
}
@Output(name = "QueueLengthStandardDeviation",
description = "The standard deviation of the number of entities in the queue.",
unitType = DimensionlessUnit.class,
reportable = true)
public double getQueueLengthStandardDeviation(double simTime) {
double dt = simTime - timeOfLastUpdate;
int queueSize = itemList.size();
double mean = this.getQueueLengthAverage(simTime);
double totalTime = simTime - startOfStatisticsCollection;
if( totalTime > 0.0 ) {
return Math.sqrt( (squaredElementSeconds + dt*queueSize*queueSize)/totalTime - mean*mean );
}
return 0.0;
}
@Output(name = "QueueLengthMinimum",
description = "The minimum number of entities in the queue.",
unitType = DimensionlessUnit.class,
reportable = true)
public Integer getQueueLengthMinimum(double simTime) {
return minElements;
}
@Output(name = "QueueLengthMaximum",
description = "The maximum number of entities in the queue.",
unitType = DimensionlessUnit.class,
reportable = true)
public Integer getQueueLengthMaximum(double simTime) {
// An entity that is added to an empty queue and removed immediately
// does not count as a non-zero queue length
if( maxElements == 1 && queueLengthDist.get(1) == 0.0 )
return 0;
return maxElements;
}
@Output(name = "QueueLengthDistribution",
description = "The fraction of time that the queue has length 0, 1, 2, etc.",
unitType = DimensionlessUnit.class,
reportable = true)
public DoubleVector getQueueLengthDistribution(double simTime) {
DoubleVector ret = new DoubleVector(queueLengthDist);
double dt = simTime - timeOfLastUpdate;
int queueSize = itemList.size();
double totalTime = simTime - startOfStatisticsCollection;
if( totalTime > 0.0 ) {
if( ret.size() == 0 )
ret.add(0.0);
ret.addAt(dt, queueSize); // adds dt to the entry at index queueSize
for( int i=0; i<ret.size(); i++ ) {
ret.set(i, ret.get(i)/totalTime);
}
}
else {
ret.clear();
}
return ret;
}
@Output(name = "AverageQueueTime",
description = "The average time each entity waits in the queue. Calculated as total queue time to date divided " +
"by the total number of entities added to the queue.",
unitType = TimeUnit.class,
reportable = true)
public double getAverageQueueTime(double simTime) {
if( numberAdded == 0 )
return 0.0;
double dt = simTime - timeOfLastUpdate;
int queueSize = itemList.size();
return (elementSeconds + dt*queueSize)/numberAdded;
}
}
|
package com.seadowg.loafers.collection;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Random;
public class List<T> {
private final java.util.List<T> values;
public List(T ... values) {
this.values = Arrays.asList(values);
}
public T chooseOne() {
int index = new Random().nextInt(values.size());
return values.get(index);
}
public T first() {
return values.get(0);
}
public T last() {
return values.get(values.size() - 1);
}
public T get(int index) {
return values.get(index);
}
public int length() {
return values.size();
}
public java.util.List<T> toJavaList() {
return new ArrayList<T>(values);
}
public List<T> add(List<T> appendList) {
java.util.List<T> javaList = toJavaList();
javaList.addAll(appendList.toJavaList());
return new List((T[]) javaList.toArray());
}
public boolean equals(Object object) {
if (object.getClass().isAssignableFrom(this.getClass())) {
List<T> otherList = (List<T>) object;
return toJavaList().equals(otherList.toJavaList());
} else {
return false;
}
}
}
|
package io.flutter.view;
import android.graphics.Rect;
import android.opengl.Matrix;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityNodeInfo;
import android.view.accessibility.AccessibilityNodeProvider;
import io.flutter.plugin.common.BasicMessageChannel;
import io.flutter.plugin.common.StandardMessageCodec;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
class AccessibilityBridge extends AccessibilityNodeProvider implements BasicMessageChannel.MessageHandler<Object> {
private static final String TAG = "FlutterView";
// Constants from higher API levels.
// TODO(goderbauer): Get these from Android Support Library when
private static final int ACTION_SHOW_ON_SCREEN = 16908342; // API level 23
private static final float SCROLL_EXTENT_FOR_INFINITY = 100000.0f;
private static final float SCROLL_POSITION_CAP_FOR_INFINITY = 70000.0f;
private Map<Integer, SemanticsObject> mObjects;
private final FlutterView mOwner;
private boolean mAccessibilityEnabled = false;
private SemanticsObject mA11yFocusedObject;
private SemanticsObject mInputFocusedObject;
private SemanticsObject mHoveredObject;
private final BasicMessageChannel<Object> mFlutterAccessibilityChannel;
enum Action {
TAP(1 << 0),
LONG_PRESS(1 << 1),
SCROLL_LEFT(1 << 2),
SCROLL_RIGHT(1 << 3),
SCROLL_UP(1 << 4),
SCROLL_DOWN(1 << 5),
INCREASE(1 << 6),
DECREASE(1 << 7),
SHOW_ON_SCREEN(1 << 8),
MOVE_CURSOR_FORWARD_BY_CHARACTER(1 << 9),
MOVE_CURSOR_BACKWARD_BY_CHARACTER(1 << 10),
SET_SELECTION(1 << 11),
COPY(1 << 12),
CUT(1 << 13),
PASTE(1 << 14),
DID_GAIN_ACCESSIBILITY_FOCUS(1 << 15),
DID_LOSE_ACCESSIBILITY_FOCUS(1 << 16);
Action(int value) {
this.value = value;
}
final int value;
}
enum Flag {
HAS_CHECKED_STATE(1 << 0),
IS_CHECKED(1 << 1),
IS_SELECTED(1 << 2),
IS_BUTTON(1 << 3),
IS_TEXT_FIELD(1 << 4),
IS_FOCUSED(1 << 5),
HAS_ENABLED_STATE(1 << 6),
IS_ENABLED(1 << 7),
IS_IN_MUTUALLY_EXCLUSIVE_GROUP(1 << 8),
IS_HEADER(1 << 9);
Flag(int value) {
this.value = value;
}
final int value;
}
AccessibilityBridge(FlutterView owner) {
assert owner != null;
mOwner = owner;
mObjects = new HashMap<Integer, SemanticsObject>();
mFlutterAccessibilityChannel = new BasicMessageChannel<>(owner, "flutter/accessibility",
StandardMessageCodec.INSTANCE);
}
void setAccessibilityEnabled(boolean accessibilityEnabled) {
mAccessibilityEnabled = accessibilityEnabled;
if (accessibilityEnabled) {
mFlutterAccessibilityChannel.setMessageHandler(this);
} else {
mFlutterAccessibilityChannel.setMessageHandler(null);
}
}
@Override
@SuppressWarnings("deprecation")
public AccessibilityNodeInfo createAccessibilityNodeInfo(int virtualViewId) {
if (virtualViewId == View.NO_ID) {
AccessibilityNodeInfo result = AccessibilityNodeInfo.obtain(mOwner);
mOwner.onInitializeAccessibilityNodeInfo(result);
if (mObjects.containsKey(0))
result.addChild(mOwner, 0);
return result;
}
SemanticsObject object = mObjects.get(virtualViewId);
if (object == null)
return null;
AccessibilityNodeInfo result = AccessibilityNodeInfo.obtain(mOwner, virtualViewId);
result.setPackageName(mOwner.getContext().getPackageName());
result.setClassName("android.view.View");
result.setSource(mOwner, virtualViewId);
result.setFocusable(object.isFocusable());
if (mInputFocusedObject != null)
result.setFocused(mInputFocusedObject.id == virtualViewId);
if (mA11yFocusedObject != null)
result.setAccessibilityFocused(mA11yFocusedObject.id == virtualViewId);
if (object.hasFlag(Flag.IS_TEXT_FIELD)) {
result.setClassName("android.widget.EditText");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
result.setEditable(true);
if (object.textSelectionBase != -1 && object.textSelectionExtent != -1) {
result.setTextSelection(object.textSelectionBase, object.textSelectionExtent);
}
}
// Cursor movements
int granularities = 0;
if (object.hasAction(Action.MOVE_CURSOR_FORWARD_BY_CHARACTER)) {
result.addAction(AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY);
granularities |= AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER;
}
if (object.hasAction(Action.MOVE_CURSOR_BACKWARD_BY_CHARACTER)) {
result.addAction(AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY);
granularities |= AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER;
}
result.setMovementGranularities(granularities);
}
if (object.hasAction(Action.SET_SELECTION)) {
result.addAction(AccessibilityNodeInfo.ACTION_SET_SELECTION);
}
if (object.hasAction(Action.COPY)) {
result.addAction(AccessibilityNodeInfo.ACTION_COPY);
}
if (object.hasAction(Action.CUT)) {
result.addAction(AccessibilityNodeInfo.ACTION_CUT);
}
if (object.hasAction(Action.PASTE)) {
result.addAction(AccessibilityNodeInfo.ACTION_PASTE);
}
if (object.hasFlag(Flag.IS_BUTTON)) {
result.setClassName("android.widget.Button");
}
if (object.parent != null) {
assert object.id > 0;
result.setParent(mOwner, object.parent.id);
} else {
assert object.id == 0;
result.setParent(mOwner);
}
Rect bounds = object.getGlobalRect();
if (object.parent != null) {
Rect parentBounds = object.parent.getGlobalRect();
Rect boundsInParent = new Rect(bounds);
boundsInParent.offset(-parentBounds.left, -parentBounds.top);
result.setBoundsInParent(boundsInParent);
} else {
result.setBoundsInParent(bounds);
}
result.setBoundsInScreen(bounds);
result.setVisibleToUser(true);
result.setEnabled(!object.hasFlag(Flag.HAS_ENABLED_STATE) ||
object.hasFlag(Flag.IS_ENABLED));
if (object.hasAction(Action.TAP)) {
result.addAction(AccessibilityNodeInfo.ACTION_CLICK);
result.setClickable(true);
}
if (object.hasAction(Action.LONG_PRESS)) {
result.addAction(AccessibilityNodeInfo.ACTION_LONG_CLICK);
result.setLongClickable(true);
}
if (object.hasAction(Action.SCROLL_LEFT) || object.hasAction(Action.SCROLL_UP)
|| object.hasAction(Action.SCROLL_RIGHT) || object.hasAction(Action.SCROLL_DOWN)) {
result.setScrollable(true);
// This tells Android's a11y to send scroll events when reaching the end of
// the visible viewport of a scrollable.
result.setClassName("android.widget.ScrollView");
// TODO(ianh): Once we're on SDK v23+, call addAction to
// expose AccessibilityAction.ACTION_SCROLL_LEFT, _RIGHT,
// _UP, and _DOWN when appropriate.
if (object.hasAction(Action.SCROLL_LEFT) || object.hasAction(Action.SCROLL_UP)) {
result.addAction(AccessibilityNodeInfo.ACTION_SCROLL_FORWARD);
}
if (object.hasAction(Action.SCROLL_RIGHT) || object.hasAction(Action.SCROLL_DOWN)) {
result.addAction(AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD);
}
}
if (object.hasAction(Action.INCREASE) || object.hasAction(Action.DECREASE)) {
result.setClassName("android.widget.SeekBar");
if (object.hasAction(Action.INCREASE)) {
result.addAction(AccessibilityNodeInfo.ACTION_SCROLL_FORWARD);
}
if (object.hasAction(Action.DECREASE)) {
result.addAction(AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD);
}
}
boolean hasCheckedState = object.hasFlag(Flag.HAS_CHECKED_STATE);
result.setCheckable(hasCheckedState);
if (hasCheckedState) {
result.setChecked(object.hasFlag(Flag.IS_CHECKED));
if (object.hasFlag(Flag.IS_IN_MUTUALLY_EXCLUSIVE_GROUP))
result.setClassName("android.widget.RadioButton");
else
result.setClassName("android.widget.CheckBox");
}
result.setSelected(object.hasFlag(Flag.IS_SELECTED));
result.setText(object.getValueLabelHint());
if (object.previousNodeId != -1)
result.setTraversalAfter(mOwner, object.previousNodeId);
// Accessibility Focus
if (mA11yFocusedObject != null && mA11yFocusedObject.id == virtualViewId) {
result.addAction(AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS);
} else {
result.addAction(AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS);
}
if (object.children != null) {
for (SemanticsObject child : object.children) {
result.addChild(mOwner, child.id);
}
}
return result;
}
@Override
public boolean performAction(int virtualViewId, int action, Bundle arguments) {
SemanticsObject object = mObjects.get(virtualViewId);
if (object == null) {
return false;
}
switch (action) {
case AccessibilityNodeInfo.ACTION_CLICK: {
mOwner.dispatchSemanticsAction(virtualViewId, Action.TAP);
return true;
}
case AccessibilityNodeInfo.ACTION_LONG_CLICK: {
mOwner.dispatchSemanticsAction(virtualViewId, Action.LONG_PRESS);
return true;
}
case AccessibilityNodeInfo.ACTION_SCROLL_FORWARD: {
if (object.hasAction(Action.SCROLL_UP)) {
mOwner.dispatchSemanticsAction(virtualViewId, Action.SCROLL_UP);
} else if (object.hasAction(Action.SCROLL_LEFT)) {
// TODO(ianh): bidi support using textDirection
mOwner.dispatchSemanticsAction(virtualViewId, Action.SCROLL_LEFT);
} else if (object.hasAction(Action.INCREASE)) {
object.value = object.increasedValue;
// Event causes Android to read out the updated value.
sendAccessibilityEvent(virtualViewId, AccessibilityEvent.TYPE_VIEW_SELECTED);
mOwner.dispatchSemanticsAction(virtualViewId, Action.INCREASE);
} else {
return false;
}
return true;
}
case AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD: {
if (object.hasAction(Action.SCROLL_DOWN)) {
mOwner.dispatchSemanticsAction(virtualViewId, Action.SCROLL_DOWN);
} else if (object.hasAction(Action.SCROLL_RIGHT)) {
// TODO(ianh): bidi support using textDirection
mOwner.dispatchSemanticsAction(virtualViewId, Action.SCROLL_RIGHT);
} else if (object.hasAction(Action.DECREASE)) {
object.value = object.decreasedValue;
// Event causes Android to read out the updated value.
sendAccessibilityEvent(virtualViewId, AccessibilityEvent.TYPE_VIEW_SELECTED);
mOwner.dispatchSemanticsAction(virtualViewId, Action.DECREASE);
} else {
return false;
}
return true;
}
case AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY: {
return performCursorMoveAction(object, virtualViewId, arguments, false);
}
case AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY: {
return performCursorMoveAction(object, virtualViewId, arguments, true);
}
case AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS: {
mOwner.dispatchSemanticsAction(virtualViewId, Action.DID_LOSE_ACCESSIBILITY_FOCUS);
sendAccessibilityEvent(virtualViewId, AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED);
mA11yFocusedObject = null;
return true;
}
case AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS: {
mOwner.dispatchSemanticsAction(virtualViewId, Action.DID_GAIN_ACCESSIBILITY_FOCUS);
sendAccessibilityEvent(virtualViewId, AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED);
if (mA11yFocusedObject == null) {
// When Android focuses a node, it doesn't invalidate the view.
// (It does when it sends ACTION_CLEAR_ACCESSIBILITY_FOCUS, so
// we only have to worry about this when the focused node is null.)
mOwner.invalidate();
}
mA11yFocusedObject = object;
if (object.hasAction(Action.INCREASE) || object.hasAction(Action.DECREASE)) {
// SeekBars only announce themselves after this event.
sendAccessibilityEvent(virtualViewId, AccessibilityEvent.TYPE_VIEW_SELECTED);
}
return true;
}
case ACTION_SHOW_ON_SCREEN: {
mOwner.dispatchSemanticsAction(virtualViewId, Action.SHOW_ON_SCREEN);
return true;
}
case AccessibilityNodeInfo.ACTION_SET_SELECTION: {
final Map<String, Integer> selection = new HashMap<String, Integer>();
final boolean hasSelection = arguments != null
&& arguments.containsKey(
AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_START_INT)
&& arguments.containsKey(
AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_END_INT);
if (hasSelection) {
selection.put("base", arguments.getInt(
AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_START_INT));
selection.put("extent", arguments.getInt(
AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_END_INT));
} else {
// Clear the selection
selection.put("base", object.textSelectionExtent);
selection.put("extent", object.textSelectionExtent);
}
mOwner.dispatchSemanticsAction(virtualViewId, Action.SET_SELECTION, selection);
return true;
}
case AccessibilityNodeInfo.ACTION_COPY: {
mOwner.dispatchSemanticsAction(virtualViewId, Action.COPY);
return true;
}
case AccessibilityNodeInfo.ACTION_CUT: {
mOwner.dispatchSemanticsAction(virtualViewId, Action.CUT);
return true;
}
case AccessibilityNodeInfo.ACTION_PASTE: {
mOwner.dispatchSemanticsAction(virtualViewId, Action.PASTE);
return true;
}
}
return false;
}
boolean performCursorMoveAction(SemanticsObject object, int virtualViewId, Bundle arguments, boolean forward) {
final int granularity = arguments.getInt(
AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT);
final boolean extendSelection = arguments.getBoolean(
AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN);
switch (granularity) {
case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER: {
if (forward && object.hasAction(Action.MOVE_CURSOR_FORWARD_BY_CHARACTER)) {
mOwner.dispatchSemanticsAction(virtualViewId, Action.MOVE_CURSOR_FORWARD_BY_CHARACTER, extendSelection);
return true;
}
if (!forward && object.hasAction(Action.MOVE_CURSOR_BACKWARD_BY_CHARACTER)) {
mOwner.dispatchSemanticsAction(virtualViewId, Action.MOVE_CURSOR_BACKWARD_BY_CHARACTER, extendSelection);
return true;
}
}
// TODO(goderbauer): support other granularities.
}
return false;
}
// TODO(ianh): implement findAccessibilityNodeInfosByText()
@Override
public AccessibilityNodeInfo findFocus(int focus) {
switch (focus) {
case AccessibilityNodeInfo.FOCUS_INPUT: {
if (mInputFocusedObject != null)
return createAccessibilityNodeInfo(mInputFocusedObject.id);
}
case AccessibilityNodeInfo.FOCUS_ACCESSIBILITY: {
if (mA11yFocusedObject != null)
return createAccessibilityNodeInfo(mA11yFocusedObject.id);
}
}
return null;
}
private SemanticsObject getRootObject() {
assert mObjects.containsKey(0);
return mObjects.get(0);
}
private SemanticsObject getOrCreateObject(int id) {
SemanticsObject object = mObjects.get(id);
if (object == null) {
object = new SemanticsObject();
object.id = id;
mObjects.put(id, object);
}
return object;
}
void handleTouchExplorationExit() {
if (mHoveredObject != null) {
sendAccessibilityEvent(mHoveredObject.id, AccessibilityEvent.TYPE_VIEW_HOVER_EXIT);
mHoveredObject = null;
}
}
void handleTouchExploration(float x, float y) {
if (mObjects.isEmpty()) {
return;
}
SemanticsObject newObject = getRootObject().hitTest(new float[]{ x, y, 0, 1 });
if (newObject != mHoveredObject) {
// sending ENTER before EXIT is how Android wants it
if (newObject != null) {
sendAccessibilityEvent(newObject.id, AccessibilityEvent.TYPE_VIEW_HOVER_ENTER);
}
if (mHoveredObject != null) {
sendAccessibilityEvent(mHoveredObject.id, AccessibilityEvent.TYPE_VIEW_HOVER_EXIT);
}
mHoveredObject = newObject;
}
}
void updateSemantics(ByteBuffer buffer, String[] strings) {
ArrayList<SemanticsObject> updated = new ArrayList<SemanticsObject>();
while (buffer.hasRemaining()) {
int id = buffer.getInt();
SemanticsObject object = getOrCreateObject(id);
boolean hadCheckedState = object.hasFlag(Flag.HAS_CHECKED_STATE);
boolean wasChecked = object.hasFlag(Flag.IS_CHECKED);
object.updateWith(buffer, strings);
if (object.hasFlag(Flag.IS_FOCUSED)) {
mInputFocusedObject = object;
}
if (object.hadPreviousConfig) {
updated.add(object);
}
}
Set<SemanticsObject> visitedObjects = new HashSet<SemanticsObject>();
SemanticsObject rootObject = getRootObject();
if (rootObject != null) {
final float[] identity = new float[16];
Matrix.setIdentityM(identity, 0);
rootObject.updateRecursively(identity, visitedObjects, false);
}
Iterator<Map.Entry<Integer, SemanticsObject>> it = mObjects.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<Integer, SemanticsObject> entry = it.next();
SemanticsObject object = entry.getValue();
if (!visitedObjects.contains(object)) {
willRemoveSemanticsObject(object);
it.remove();
}
}
// TODO(goderbauer): Send this event only once (!) for changed subtrees,
sendAccessibilityEvent(0, AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED);
for (SemanticsObject object : updated) {
if (object.didScroll()) {
AccessibilityEvent event =
obtainAccessibilityEvent(object.id, AccessibilityEvent.TYPE_VIEW_SCROLLED);
// Android doesn't support unbound scrolling. So we pretend there is a large
// bound (SCROLL_EXTENT_FOR_INFINITY), which you can never reach.
float position = object.scrollPosition;
float max = object.scrollExtentMax;
if (Float.isInfinite(object.scrollExtentMax)) {
max = SCROLL_EXTENT_FOR_INFINITY;
if (position > SCROLL_POSITION_CAP_FOR_INFINITY) {
position = SCROLL_POSITION_CAP_FOR_INFINITY;
}
}
if (Float.isInfinite(object.scrollExtentMin)) {
max += SCROLL_EXTENT_FOR_INFINITY;
if (position < -SCROLL_POSITION_CAP_FOR_INFINITY) {
position = -SCROLL_POSITION_CAP_FOR_INFINITY;
}
position += SCROLL_EXTENT_FOR_INFINITY;
} else {
max -= object.scrollExtentMin;
position -= object.scrollExtentMin;
}
if (object.hadAction(Action.SCROLL_UP) || object.hadAction(Action.SCROLL_DOWN)) {
event.setScrollY((int) position);
event.setMaxScrollY((int) max);
} else if (object.hadAction(Action.SCROLL_LEFT)
|| object.hadAction(Action.SCROLL_RIGHT)) {
event.setScrollX((int) position);
event.setMaxScrollX((int) max);
}
sendAccessibilityEvent(event);
}
if (mA11yFocusedObject != null && mA11yFocusedObject.id == object.id
&& object.hadFlag(Flag.HAS_CHECKED_STATE)
&& object.hasFlag(Flag.HAS_CHECKED_STATE)
&& object.hadFlag(Flag.IS_CHECKED) != object.hasFlag(Flag.IS_CHECKED)) {
// Simulate a click so TalkBack announces the change in checked state.
sendAccessibilityEvent(object.id, AccessibilityEvent.TYPE_VIEW_CLICKED);
}
if (mA11yFocusedObject != null && mA11yFocusedObject.id == object.id
&& !object.hadFlag(Flag.IS_SELECTED) && object.hasFlag(Flag.IS_SELECTED)) {
AccessibilityEvent event =
obtainAccessibilityEvent(object.id, AccessibilityEvent.TYPE_VIEW_SELECTED);
event.getText().add(object.label);
sendAccessibilityEvent(event);
}
if (mInputFocusedObject != null && mInputFocusedObject.id == object.id
&& object.hadFlag(Flag.IS_TEXT_FIELD)
&& object.hasFlag(Flag.IS_TEXT_FIELD)) {
String oldValue = object.previousValue != null ? object.previousValue : "";
String newValue = object.value != null ? object.value : "";
AccessibilityEvent event = createTextChangedEvent(object.id, oldValue, newValue);
if (event != null) {
sendAccessibilityEvent(event);
}
if (object.previousTextSelectionBase != object.textSelectionBase
|| object.previousTextSelectionExtent != object.textSelectionExtent) {
AccessibilityEvent selectionEvent = obtainAccessibilityEvent(
object.id, AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED);
selectionEvent.getText().add(newValue);
selectionEvent.setFromIndex(object.textSelectionBase);
selectionEvent.setToIndex(object.textSelectionExtent);
selectionEvent.setItemCount(newValue.length());
sendAccessibilityEvent(selectionEvent);
}
}
}
}
private AccessibilityEvent createTextChangedEvent(int id, String oldValue, String newValue) {
AccessibilityEvent e = obtainAccessibilityEvent(id, AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED);
e.setBeforeText(oldValue);
e.getText().add(newValue);
int i;
for (i = 0; i < oldValue.length() && i < newValue.length(); ++i) {
if (oldValue.charAt(i) != newValue.charAt(i)) {
break;
}
}
if (i >= oldValue.length() && i >= newValue.length()) {
return null; // Text did not change
}
int firstDifference = i;
e.setFromIndex(firstDifference);
int oldIndex = oldValue.length() - 1;
int newIndex = newValue.length() - 1;
while (oldIndex >= firstDifference && newIndex >= firstDifference) {
if (oldValue.charAt(oldIndex) != newValue.charAt(newIndex)) {
break;
}
--oldIndex;
--newIndex;
}
e.setRemovedCount(oldIndex - firstDifference + 1);
e.setAddedCount(newIndex - firstDifference + 1);
return e;
}
private AccessibilityEvent obtainAccessibilityEvent(int virtualViewId, int eventType) {
assert virtualViewId != 0;
AccessibilityEvent event = AccessibilityEvent.obtain(eventType);
event.setPackageName(mOwner.getContext().getPackageName());
event.setSource(mOwner, virtualViewId);
return event;
}
private void sendAccessibilityEvent(int virtualViewId, int eventType) {
if (!mAccessibilityEnabled) {
return;
}
if (virtualViewId == 0) {
mOwner.sendAccessibilityEvent(eventType);
} else {
sendAccessibilityEvent(obtainAccessibilityEvent(virtualViewId, eventType));
}
}
private void sendAccessibilityEvent(AccessibilityEvent event) {
if (!mAccessibilityEnabled) {
return;
}
mOwner.getParent().requestSendAccessibilityEvent(mOwner, event);
}
// Message Handler for [mFlutterAccessibilityChannel].
public void onMessage(Object message, BasicMessageChannel.Reply<Object> reply) {
@SuppressWarnings("unchecked")
final HashMap<String, Object> annotatedEvent = (HashMap<String, Object>)message;
final String type = (String)annotatedEvent.get("type");
@SuppressWarnings("unchecked")
final HashMap<String, Object> data = (HashMap<String, Object>)annotatedEvent.get("data");
switch (type) {
case "announce":
mOwner.announceForAccessibility((String) data.get("message"));
break;
default:
assert false;
}
}
private void willRemoveSemanticsObject(SemanticsObject object) {
assert mObjects.containsKey(object.id);
assert mObjects.get(object.id) == object;
object.parent = null;
if (mA11yFocusedObject == object) {
sendAccessibilityEvent(mA11yFocusedObject.id, AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED);
mA11yFocusedObject = null;
}
if (mInputFocusedObject == object) {
mInputFocusedObject = null;
}
if (mHoveredObject == object) {
mHoveredObject = null;
}
}
void reset() {
mObjects.clear();
if (mA11yFocusedObject != null)
sendAccessibilityEvent(mA11yFocusedObject.id, AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED);
mA11yFocusedObject = null;
mHoveredObject = null;
sendAccessibilityEvent(0, AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED);
}
private enum TextDirection {
UNKNOWN, LTR, RTL;
public static TextDirection fromInt(int value) {
switch (value) {
case 1:
return RTL;
case 2:
return LTR;
}
return UNKNOWN;
}
}
private class SemanticsObject {
SemanticsObject() { }
int id = -1;
int flags;
int actions;
int textSelectionBase;
int textSelectionExtent;
float scrollPosition;
float scrollExtentMax;
float scrollExtentMin;
String label;
String value;
String increasedValue;
String decreasedValue;
String hint;
TextDirection textDirection;
int previousNodeId;
boolean hadPreviousConfig = false;
int previousFlags;
int previousActions;
int previousTextSelectionBase;
int previousTextSelectionExtent;
float previousScrollPosition;
float previousScrollExtentMax;
float previousScrollExtentMin;
String previousValue;
private float left;
private float top;
private float right;
private float bottom;
private float[] transform;
SemanticsObject parent;
List<SemanticsObject> children; // In inverse hit test order (i.e. paint order).
private boolean inverseTransformDirty = true;
private float[] inverseTransform;
private boolean globalGeometryDirty = true;
private float[] globalTransform;
private Rect globalRect;
boolean hasAction(Action action) {
return (actions & action.value) != 0;
}
boolean hadAction(Action action) {
return (previousActions & action.value) != 0;
}
boolean hasFlag(Flag flag) {
return (flags & flag.value) != 0;
}
boolean hadFlag(Flag flag) {
assert hadPreviousConfig;
return (previousFlags & flag.value) != 0;
}
boolean didScroll() {
return !Float.isNaN(scrollPosition) && !Float.isNaN(previousScrollPosition)
&& previousScrollPosition != scrollPosition;
}
void log(String indent, boolean recursive) {
Log.i(TAG, indent + "SemanticsObject id=" + id + " label=" + label + " actions=" + actions + " flags=" + flags + "\n" +
indent + " +-- textDirection=" + textDirection + "\n"+
indent + " +-- previousNodeId=" + previousNodeId + "\n"+
indent + " +-- rect.ltrb=(" + left + ", " + top + ", " + right + ", " + bottom + ")\n" +
indent + " +-- transform=" + Arrays.toString(transform) + "\n");
if (children != null && recursive) {
String childIndent = indent + " ";
for (SemanticsObject child : children) {
child.log(childIndent, recursive);
}
}
}
void updateWith(ByteBuffer buffer, String[] strings) {
hadPreviousConfig = true;
previousValue = value;
previousFlags = flags;
previousActions = actions;
previousTextSelectionBase = textSelectionBase;
previousTextSelectionExtent = textSelectionExtent;
previousScrollPosition = scrollPosition;
previousScrollExtentMax = scrollExtentMax;
previousScrollExtentMin = scrollExtentMin;
flags = buffer.getInt();
actions = buffer.getInt();
textSelectionBase = buffer.getInt();
textSelectionExtent = buffer.getInt();
scrollPosition = buffer.getFloat();
scrollExtentMax = buffer.getFloat();
scrollExtentMin = buffer.getFloat();
int stringIndex = buffer.getInt();
label = stringIndex == -1 ? null : strings[stringIndex];
stringIndex = buffer.getInt();
value = stringIndex == -1 ? null : strings[stringIndex];
stringIndex = buffer.getInt();
increasedValue = stringIndex == -1 ? null : strings[stringIndex];
stringIndex = buffer.getInt();
decreasedValue = stringIndex == -1 ? null : strings[stringIndex];
stringIndex = buffer.getInt();
hint = stringIndex == -1 ? null : strings[stringIndex];
textDirection = TextDirection.fromInt(buffer.getInt());
previousNodeId = buffer.getInt();
left = buffer.getFloat();
top = buffer.getFloat();
right = buffer.getFloat();
bottom = buffer.getFloat();
if (transform == null)
transform = new float[16];
for (int i = 0; i < 16; ++i)
transform[i] = buffer.getFloat();
inverseTransformDirty = true;
globalGeometryDirty = true;
final int childCount = buffer.getInt();
if (childCount == 0) {
children = null;
} else {
if (children == null)
children = new ArrayList<SemanticsObject>(childCount);
else
children.clear();
for (int i = 0; i < childCount; ++i) {
SemanticsObject child = getOrCreateObject(buffer.getInt());
child.parent = this;
children.add(child);
}
}
}
private void ensureInverseTransform() {
if (!inverseTransformDirty)
return;
inverseTransformDirty = false;
if (inverseTransform == null)
inverseTransform = new float[16];
if (!Matrix.invertM(inverseTransform, 0, transform, 0))
Arrays.fill(inverseTransform, 0);
}
Rect getGlobalRect() {
assert !globalGeometryDirty;
return globalRect;
}
SemanticsObject hitTest(float[] point) {
final float w = point[3];
final float x = point[0] / w;
final float y = point[1] / w;
if (x < left || x >= right || y < top || y >= bottom)
return null;
if (children != null) {
final float[] transformedPoint = new float[4];
for (int i = children.size() - 1; i >= 0; i -= 1) {
final SemanticsObject child = children.get(i);
child.ensureInverseTransform();
Matrix.multiplyMV(transformedPoint, 0, child.inverseTransform, 0, point, 0);
final SemanticsObject result = child.hitTest(transformedPoint);
if (result != null) {
return result;
}
}
}
return this;
}
// TODO(goderbauer): This should be decided by the framework once we have more information
// about focusability there.
boolean isFocusable() {
int scrollableActions = Action.SCROLL_RIGHT.value | Action.SCROLL_LEFT.value
| Action.SCROLL_UP.value | Action.SCROLL_DOWN.value;
return (actions & ~scrollableActions) != 0
|| flags != 0
|| (label != null && !label.isEmpty())
|| (value != null && !value.isEmpty())
|| (hint != null && !hint.isEmpty());
}
void updateRecursively(float[] ancestorTransform, Set<SemanticsObject> visitedObjects, boolean forceUpdate) {
visitedObjects.add(this);
if (globalGeometryDirty)
forceUpdate = true;
if (forceUpdate) {
if (globalTransform == null)
globalTransform = new float[16];
Matrix.multiplyMM(globalTransform, 0, ancestorTransform, 0, transform, 0);
final float[] sample = new float[4];
sample[2] = 0;
sample[3] = 1;
final float[] point1 = new float[4];
final float[] point2 = new float[4];
final float[] point3 = new float[4];
final float[] point4 = new float[4];
sample[0] = left;
sample[1] = top;
transformPoint(point1, globalTransform, sample);
sample[0] = right;
sample[1] = top;
transformPoint(point2, globalTransform, sample);
sample[0] = right;
sample[1] = bottom;
transformPoint(point3, globalTransform, sample);
sample[0] = left;
sample[1] = bottom;
transformPoint(point4, globalTransform, sample);
if (globalRect == null)
globalRect = new Rect();
globalRect.set(
Math.round(min(point1[0], point2[0], point3[0], point4[0])),
Math.round(min(point1[1], point2[1], point3[1], point4[1])),
Math.round(max(point1[0], point2[0], point3[0], point4[0])),
Math.round(max(point1[1], point2[1], point3[1], point4[1]))
);
globalGeometryDirty = false;
}
assert globalTransform != null;
assert globalRect != null;
if (children != null) {
for (int i = 0; i < children.size(); ++i) {
children.get(i).updateRecursively(globalTransform, visitedObjects, forceUpdate);
}
}
}
private void transformPoint(float[] result, float[] transform, float[] point) {
Matrix.multiplyMV(result, 0, transform, 0, point, 0);
final float w = result[3];
result[0] /= w;
result[1] /= w;
result[2] /= w;
result[3] = 0;
}
private float min(float a, float b, float c, float d) {
return Math.min(a, Math.min(b, Math.min(c, d)));
}
private float max(float a, float b, float c, float d) {
return Math.max(a, Math.max(b, Math.max(c, d)));
}
private String getValueLabelHint() {
StringBuilder sb = new StringBuilder();
String[] array = { value, label, hint };
for (String word: array) {
if (word != null && word.length() > 0) {
if (sb.length() > 0)
sb.append(", ");
sb.append(word);
}
}
return sb.length() > 0 ? sb.toString() : null;
}
}
}
|
package com.axiastudio.zoefx.view;
import com.axiastudio.zoefx.controller.FXController;
import com.axiastudio.zoefx.db.Model;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.fxml.JavaFXBuilderFactory;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.layout.AnchorPane;
import java.io.IOException;
import java.net.URL;
public class ZoeSceneBuilder {
public static Scene build(String sUrl, Model model){
URL url = Application.class.getResource(sUrl);
FXMLLoader loader = new FXMLLoader();
loader.setLocation(url);
loader.setBuilderFactory(new JavaFXBuilderFactory());
Parent root=null;
try {
root = (Parent) loader.load(url.openStream());
} catch (IOException e) {
e.printStackTrace();
}
Scene scene = new Scene(root, 500, 375);
ZoeToolBar toolBar = new ZoeToolBar();
AnchorPane pane = (AnchorPane) root;
pane.getChildren().add(toolBar);
FXController controller = loader.getController();
//toolBar.setController(controller)
controller.setScene(scene);
controller.bindModel(model);
return scene;
}
}
|
package org.utplsql.api.outputBuffer;
import oracle.jdbc.OracleConnection;
import oracle.jdbc.OracleTypes;
import org.utplsql.api.Version;
import org.utplsql.api.exception.InvalidVersionException;
import org.utplsql.api.reporter.Reporter;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.SQLException;
public class OutputBufferProvider {
/** Returns an OutputBuffer compatible with the given databaseVersion
* If we are at 3.1.0 or greater, returns an OutputBuffer based upon the information whether the Reporter has Output or not
*
* @param databaseVersion
* @param reporter
* @param conn
* @return
* @throws SQLException
*/
public static OutputBuffer getCompatibleOutputBuffer(Version databaseVersion, Reporter reporter, Connection conn ) throws SQLException {
OracleConnection oraConn = conn.unwrap(OracleConnection.class);
try {
if (databaseVersion.isGreaterOrEqualThan(new Version("3.1.0"))) {
if ( hasOutput(reporter, oraConn) ) {
return new DefaultOutputBuffer(reporter);
}
else {
return new NonOutputBuffer(reporter);
}
}
}
catch ( InvalidVersionException ignored ) { }
// If we couldn't find an appropriate OutputBuffer, return the Pre310-Compatibility-Buffer
return new CompatibilityOutputBufferPre310(reporter);
}
private static boolean hasOutput( Reporter reporter, OracleConnection oraConn ) throws SQLException {
String reporterName = reporter.getTypeName();
if ( !reporterName.matches("^[a-zA-Z0-9_]+$"))
throw new IllegalArgumentException(String.format("Reporter-Name %s is not valid", reporterName));
String sql =
"declare " +
" l_result int;" +
"begin " +
" begin " +
" execute immediate '" +
" begin " +
" :x := case ' || dbms_assert.valid_sql_name( ? ) || '() is of (ut_output_reporter_base) when true then 1 else 0 end;" +
" end;'" +
" using out l_result;" +
" end;" +
" ? := l_result;" +
"end;";
try ( CallableStatement stmt = oraConn.prepareCall(sql)) {
stmt.setQueryTimeout(3);
stmt.setString(1, reporterName);
stmt.registerOutParameter(2, OracleTypes.INTEGER);
stmt.execute();
int result = stmt.getInt(2);
return result == 1;
}
}
private OutputBufferProvider() {
}
}
|
package com.st.configuration;
import java.net.URI;
import java.net.URISyntaxException;
import org.apache.commons.collections.CollectionUtils;
import org.apache.tomcat.jdbc.pool.DataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class DatabaseConfig {
private final static Logger logger = LoggerFactory.getLogger(DatabaseConfig.class);
private final static int USER_PASSWORD_PARAMS = 2;
@Bean
public DataSource postgresDataSource() {
String databaseUrl = System.getenv("DATABASE_URL");
logger.debug("Found environment variable DATABASE_URL with value: " + databaseUrl);
URI dbUri;
try {
dbUri = new URI(databaseUrl);
} catch (URISyntaxException e) {
logger.error("databaseUrl cannot be null");
return null;
}
// For travis, as DB has no password.
String username = dbUri.getUserInfo().split(":")[0];
String password = null;
if (USER_PASSWORD_PARAMS == CollectionUtils.size(dbUri.getUserInfo().split(":"))) {
password = dbUri.getUserInfo().split(":")[1];
}
String dbUrl = "jdbc:postgresql://" + dbUri.getHost() + ':' + dbUri.getPort() + dbUri.getPath();
logger.debug("Data base properties");
logger.debug("dbUrl: " + dbUrl);
logger.debug("username: " + username);
org.apache.tomcat.jdbc.pool.DataSource dataSource = new org.apache.tomcat.jdbc.pool.DataSource();
dataSource.setDriverClassName("org.postgresql.Driver");
dataSource.setUrl(dbUrl);
dataSource.setUsername(username);
dataSource.setPassword(password);
dataSource.setTestOnBorrow(true);
dataSource.setTestWhileIdle(true);
dataSource.setTestOnReturn(true);
dataSource.setValidationQuery("SELECT 1");
return dataSource;
}
}
|
package pl.java.scalatech.security;
import java.util.List;
import javax.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.jasypt.encryption.StringEncryptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.DependsOn;
import org.springframework.dao.DataAccessException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import com.google.common.collect.Lists;
import pl.java.scalatech.annotation.SecurityComponent;
import pl.java.scalatech.domain.Role;
import pl.java.scalatech.domain.User;
import pl.java.scalatech.repository.RoleRepository;
import pl.java.scalatech.repository.UserRepository;
@Slf4j
@SecurityComponent
@DependsOn("stringEncryptor")
public class UserServiceDetailsImpl implements UserDetailsService {
@Autowired
private UserRepository userRepository;
@Autowired
private PasswordEncoder passwordEncoder;
@Autowired
private RoleRepository roleRepository;
List<User> users = Lists.newArrayList();
@PostConstruct
public void init() {
log.info("+++ role : {} , user : {} userDetailsService postConstruct" + roleRepository.count(),
userRepository.count());
log.info("{}", passwordEncoder.encode("test"));
if (roleRepository.count() == 2) {
Role r_user = new Role("user", "user");
roleRepository.save(r_user);
Role a_user = new Role("admin", "admin");
roleRepository.save(a_user);
Role b_user = new Role("business", "buisness");
roleRepository.save(b_user);
log.info("+++ {}", roleRepository.findOne("user"));
}
log.info("+++ {}", roleRepository.findOne("user"));
if (userRepository.count() == 0) {
User one = User.builder().login("przodownik").password(passwordEncoder.encode("test")).activated(true).email("przodownik@tlen.pl")
.fistName("slawek").lastName("borowiec").logged(false).roles(Lists.newArrayList(roleRepository.findOne("user"))).build();
userRepository.save(one);
User two = User.builder().login("admin").password(passwordEncoder.encode("test")).activated(true).email("admin@tlen.pl").fistName("admin")
.lastName("borowiec").logged(false).roles(Lists.newArrayList(roleRepository.findOne("admin"))).build();
userRepository.save(two);
User three = User.builder().login("buisness").password(passwordEncoder.encode("test")).activated(true).email("business@tlen.pl")
.fistName("buisness").lastName("borowiec").logged(false).roles(Lists.newArrayList(roleRepository.findOne("business"))).build();
userRepository.save(three);
User four = User.builder().login("bak").password(passwordEncoder.encode("test")).activated(true).email("bak@tlen.pl").fistName("kalinka")
.lastName("borowiec").logged(false)
.roles(Lists.newArrayList(roleRepository.findOne("user"), roleRepository.findOne("admin"), roleRepository.findOne("business"))).build();
User fourLoaded = userRepository.save(four);
fourLoaded.getRoles().add(roleRepository.findOne("user"));
userRepository.save(fourLoaded);
}
log.info("+++ {} --> roles : {} ", userRepository.findUserByLogin("przodownik"),userRepository.findUserByLogin("przodownik").getAuthorities());
// log.info("+++ {}", userRepository.findUserByLoginOrEmail("przodownik"));
}
@Autowired
private StringEncryptor strongEncryptor;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException, DataAccessException {
User user = findUserByLoginOrMail(username);
if (user == null) { throw new UsernameNotFoundException("login.not.exists"); }
if (user.getAttemptLoginCount() >= 3) {
throw new UsernameNotFoundException("attempt.3x.login.error");
} else if (!user.isAccountNonLocked() || !user.isEnabled()) { throw new UsernameNotFoundException("user.block"); }
return user;
}
private User findUserByLoginOrMail(String loginOrMail) {
User user = null;
try {
// TODO dao problem
user = userRepository.findUserByLogin(loginOrMail);
} catch (Exception e) {
log.error("Login or mail not exists : {} , exception {}", loginOrMail, e);
}
return user;
}
}
|
package com.thindeck.cockpit.deck;
import com.jcabi.xml.XML;
import com.thindeck.api.Base;
import com.thindeck.api.Deck;
import com.thindeck.api.Decks;
import com.thindeck.cockpit.RqUser;
import java.io.IOException;
import java.security.SecureRandom;
import java.util.Arrays;
import java.util.Date;
import java.util.Random;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.takes.Request;
import org.takes.Response;
import org.takes.Take;
import org.takes.facets.flash.RsFlash;
import org.takes.facets.forward.RsForward;
import org.takes.rq.RqForm;
import org.xembly.Directive;
import org.xembly.Directives;
/**
* Post a command.
*
* @author Yegor Bugayenko (yegor@teamed.io)
* @version $Id$
* @since 0.5
* @checkstyle ClassDataAbstractionCouplingCheck (500 lines)
* @checkstyle MultipleStringLiteralsCheck (500 lines)
*/
public final class TkCommand implements Take {
/**
* Random.
*/
private static final Random RND = new SecureRandom();
/**
* Base.
*/
private final transient Base base;
/**
* Ctor.
* @param bse Base
*/
TkCommand(final Base bse) {
this.base = bse;
}
@Override
public Response act(final Request req) throws IOException {
final Decks decks = new RqUser(req, this.base).get().decks();
final String deck = new RqDeck(this.base, req).deck().name();
final String cmd = new RqForm.Smart(
new RqForm.Base(req)
).single("command");
final Deck.Smart smart = new Deck.Smart(decks.get(deck));
smart.update(TkCommand.answer(smart.xml(), cmd));
return new RsForward(new RsFlash("thanks!"));
}
/**
* Process command.
* @param deck XML deck
* @param cmd Command
* @return Directives
* @throws IOException If fails
*/
private static Iterable<Directive> answer(final XML deck, final String cmd)
throws IOException {
final Directives dirs = new Directives().xpath("/deck");
final String[] parts = cmd.trim().split("\\s+");
if ("domain".equals(parts[0])) {
dirs.append(
TkCommand.domain(
Arrays.copyOfRange(parts, 1, parts.length)
)
);
} else if ("repo".equals(parts[0])) {
dirs.append(
TkCommand.repo(
deck,
Arrays.copyOfRange(parts, 1, parts.length)
)
);
} else if ("container".equals(parts[0])) {
dirs.append(
TkCommand.container(
Arrays.copyOfRange(parts, 1, parts.length)
)
);
}
return dirs;
}
/**
* Domain command.
* @param args Arguments
* @return Directives
* @throws IOException If fails
*/
private static Iterable<Directive> domain(final String... args)
throws IOException {
if (args.length == 0) {
throw new RsForward(
new RsFlash(
"'domain' command supports 'add' and 'remove'"
)
);
}
final Directives dirs = new Directives();
if ("add".equals(args[0])) {
dirs.addIf("domains").add("domain").set(args[1]);
} else if ("remove".equals(args[0])) {
dirs.xpath(
String.format(
"/deck/domains/domain[.='%s']", args[1]
)
).remove();
} else {
throw new RsForward(
new RsFlash(
String.format(
"should be either 'add' or 'remove': '%s' is wrong",
args[0]
)
)
);
}
return dirs;
}
/**
* Repo command.
* @param deck XML deck
* @param args Arguments
* @return Directives
* @throws IOException If fails
*/
private static Iterable<Directive> repo(final XML deck,
final String... args) throws IOException {
if (args.length == 0) {
throw new RsForward(
new RsFlash(
"'repo' command supports 'put'"
)
);
}
final Directives dirs = new Directives();
if ("put".equals(args[0])) {
if (deck.nodes("/deck/images/image").size() > 2) {
throw new IllegalArgumentException(
"there are too many images as is, waste a few first"
);
}
final String today = DateFormatUtils.ISO_DATETIME_FORMAT.format(
new Date()
);
dirs.xpath("/deck").add("repo")
.attr("added", today)
.add("name")
.set(String.format("%08x", TkCommand.RND.nextInt())).up()
.add("uri").set(args[1]);
} else {
throw new IllegalArgumentException(
String.format(
"should be only 'put': '%s' is wrong",
args[0]
)
);
}
return dirs;
}
/**
* Container command.
* @param args Arguments
* @return Directives
* @throws IOException If fails
*/
private static Iterable<Directive> container(final String... args)
throws IOException {
if (args.length == 0) {
throw new RsForward(
new RsFlash(
"'container' command supports 'waste'"
)
);
}
final Directives dirs = new Directives();
if ("waste".equals(args[0])) {
final String today = DateFormatUtils.ISO_DATETIME_FORMAT.format(
new Date()
);
dirs.xpath(
String.format(
"/deck/containers/container[name='%s']",
args[1]
)
).attr("waste", today);
} else {
throw new IllegalArgumentException(
String.format(
"should be only 'waste': '%s' is wrong",
args[0]
)
);
}
return dirs;
}
}
|
package com.jcwhatever.bukkit.generic.utils;
import org.bukkit.entity.Entity;
import org.bukkit.inventory.ItemStack;
import java.lang.reflect.Array;
/**
* Array utilities.
*/
public final class ArrayUtils {
private ArrayUtils() {}
public static final boolean[] EMPTY_BOOLEAN_ARRAY = new boolean[0];
public static final byte[] EMPTY_BYTE_ARRAY = new byte[0];
public static final char[] EMPTY_CHAR_ARRAY = new char[0];
public static final short[] EMPTY_SHORT_ARRAY = new short[0];
public static final int[] EMPTY_INT_ARRAY = new int[0];
public static final long[] EMPTY_LONG_ARRAY = new long[0];
public static final float[] EMPTY_FLOAT_ARRAY = new float[0];
public static final double[] EMPTY_DOUBLE_ARRAY = new double[0];
public static final String[] EMPTY_STRING_ARRAY = new String[0];
public static final ItemStack[] EMPTY_ITEMSTACK_ARRAY = new ItemStack[0];
public static final Entity[] EMPTY_ENTITY_ARRAY = new Entity[0];
/**
* Copy the source array elements to the destination array starting from the
* beginning and ending when either the destination runs out of space or the
* source runs out of elements.
*
* @param source The source array.
* @param destination The destination array.
*
* @param <T> The array component type.
*
* @return The destination array.
*/
public static <T> T[] copyFromStart(T[] source, T[] destination) {
PreCon.notNull(source);
PreCon.notNull(destination);
int size = Math.min(source.length, destination.length);
System.arraycopy(source, 0, destination, 0, size);
return destination;
}
/**
* Copy the source array elements to the destination array starting from the
* beginning and ending when either the destination runs out of space or the
* source runs out of elements.
*
* @param source The source array.
* @param destination The destination array.
*
* @return The destination array.
*/
public static boolean[] copyFromStart(boolean[] source, boolean[] destination) {
PreCon.notNull(source);
PreCon.notNull(destination);
int size = Math.min(source.length, destination.length);
System.arraycopy(source, 0, destination, 0, size);
return destination;
}
/**
* Copy the source array elements to the destination array starting from the
* beginning and ending when either the destination runs out of space or the
* source runs out of elements.
*
* @param source The source array.
* @param destination The destination array.
*
* @return The destination array.
*/
public static byte[] copyFromStart(byte[] source, byte[] destination) {
PreCon.notNull(source);
PreCon.notNull(destination);
int size = Math.min(source.length, destination.length);
System.arraycopy(source, 0, destination, 0, size);
return destination;
}
/**
* Copy the source array elements to the destination array starting from the
* beginning and ending when either the destination runs out of space or the
* source runs out of elements.
*
* @param source The source array.
* @param destination The destination array.
*
* @return The destination array.
*/
public static char[] copyFromStart(char[] source, char[] destination) {
PreCon.notNull(source);
PreCon.notNull(destination);
int size = Math.min(source.length, destination.length);
System.arraycopy(source, 0, destination, 0, size);
return destination;
}
/**
* Copy the source array elements to the destination array starting from the
* beginning and ending when either the destination runs out of space or the
* source runs out of elements.
*
* @param source The source array.
* @param destination The destination array.
*
* @return The destination array.
*/
public static short[] copyFromStart(short[] source, short[] destination) {
PreCon.notNull(source);
PreCon.notNull(destination);
int size = Math.min(source.length, destination.length);
System.arraycopy(source, 0, destination, 0, size);
return destination;
}
/**
* Copy the source array elements to the destination array starting from the
* beginning and ending when either the destination runs out of space or the
* source runs out of elements.
*
* @param source The source array.
* @param destination The destination array.
*
* @return The destination array.
*/
public static int[] copyFromStart(int[] source, int[] destination) {
PreCon.notNull(source);
PreCon.notNull(destination);
int size = Math.min(source.length, destination.length);
System.arraycopy(source, 0, destination, 0, size);
return destination;
}
/**
* Copy the source array elements to the destination array starting from the
* beginning and ending when either the destination runs out of space or the
* source runs out of elements.
*
* @param source The source array.
* @param destination The destination array.
*
* @return The destination array.
*/
public static long[] copyFromStart(long[] source, long[] destination) {
PreCon.notNull(source);
PreCon.notNull(destination);
int size = Math.min(source.length, destination.length);
System.arraycopy(source, 0, destination, 0, size);
return destination;
}
/**
* Copy the source array elements to the destination array starting from the
* beginning and ending when either the destination runs out of space or the
* source runs out of elements.
*
* @param source The source array.
* @param destination The destination array.
*
* @return The destination array.
*/
public static float[] copyFromStart(float[] source, float[] destination) {
PreCon.notNull(source);
PreCon.notNull(destination);
int size = Math.min(source.length, destination.length);
System.arraycopy(source, 0, destination, 0, size);
return destination;
}
/**
* Copy the source array elements to the destination array starting from the
* beginning and ending when either the destination runs out of space or the
* source runs out of elements.
*
* @param source The source array.
* @param destination The destination array.
*
* @return The destination array.
*/
public static double[] copyFromStart(double[] source, double[] destination) {
PreCon.notNull(source);
PreCon.notNull(destination);
int size = Math.min(source.length, destination.length);
System.arraycopy(source, 0, destination, 0, size);
return destination;
}
/**
* Copy the source array elements to the destination array starting from the end
* and finishing when either the destination runs out of space or the source runs
* out of elements.
*
* @param source The source array.
* @param destination The destination array.
*
* @param <T> The array component type.
*
* @return The destination array.
*/
public static <T> T[] copyFromEnd(T[] source, T[] destination) {
PreCon.notNull(source);
PreCon.notNull(destination);
int delta = source.length - destination.length;
int sourceAdjust = delta < 0 ? 0 : delta;
int destAdjust = delta < 0 ? -delta : 0;
System.arraycopy(source, sourceAdjust, destination, destAdjust, destination.length - destAdjust);
return destination;
}
/**
* Copy the source array elements to the destination array starting from the end
* and finishing when either the destination runs out of space or the source runs
* out of elements.
*
* @param source The source array.
* @param destination The destination array.
*
* @return The destination array.
*/
public static boolean[] copyFromEnd(boolean[] source, boolean[] destination) {
PreCon.notNull(source);
PreCon.notNull(destination);
int delta = source.length - destination.length;
int sourceAdjust = delta < 0 ? 0 : delta;
int destAdjust = delta < 0 ? -delta : 0;
System.arraycopy(source, sourceAdjust, destination, destAdjust, destination.length - destAdjust);
return destination;
}
/**
* Copy the source array elements to the destination array starting from the end
* and finishing when either the destination runs out of space or the source runs
* out of elements.
*
* @param source The source array.
* @param destination The destination array.
*
* @return The destination array.
*/
public static byte[] copyFromEnd(byte[] source, byte[] destination) {
PreCon.notNull(source);
PreCon.notNull(destination);
int delta = source.length - destination.length;
int sourceAdjust = delta < 0 ? 0 : delta;
int destAdjust = delta < 0 ? -delta : 0;
System.arraycopy(source, sourceAdjust, destination, destAdjust, destination.length - destAdjust);
return destination;
}
/**
* Copy the source array elements to the destination array starting from the end
* and finishing when either the destination runs out of space or the source runs
* out of elements.
*
* @param source The source array.
* @param destination The destination array.
*
* @return The destination array.
*/
public static char[] copyFromEnd(char[] source, char[] destination) {
PreCon.notNull(source);
PreCon.notNull(destination);
int delta = source.length - destination.length;
int sourceAdjust = delta < 0 ? 0 : delta;
int destAdjust = delta < 0 ? -delta : 0;
System.arraycopy(source, sourceAdjust, destination, destAdjust, destination.length - destAdjust);
return destination;
}
/**
* Copy the source array elements to the destination array starting from the end
* and finishing when either the destination runs out of space or the source runs
* out of elements.
*
* @param source The source array.
* @param destination The destination array.
*
* @return The destination array.
*/
public static short[] copyFromEnd(short[] source, short[] destination) {
PreCon.notNull(source);
PreCon.notNull(destination);
int delta = source.length - destination.length;
int sourceAdjust = delta < 0 ? 0 : delta;
int destAdjust = delta < 0 ? -delta : 0;
System.arraycopy(source, sourceAdjust, destination, destAdjust, destination.length - destAdjust);
return destination;
}
/**
* Copy the source array elements to the destination array starting from the end
* and finishing when either the destination runs out of space or the source runs
* out of elements.
*
* @param source The source array.
* @param destination The destination array.
*
* @return The destination array.
*/
public static int[] copyFromEnd(int[] source, int[] destination) {
PreCon.notNull(source);
PreCon.notNull(destination);
int delta = source.length - destination.length;
int sourceAdjust = delta < 0 ? 0 : delta;
int destAdjust = delta < 0 ? -delta : 0;
System.arraycopy(source, sourceAdjust, destination, destAdjust, destination.length - destAdjust);
return destination;
}
/**
* Copy the source array elements to the destination array starting from the end
* and finishing when either the destination runs out of space or the source runs
* out of elements.
*
* @param source The source array.
* @param destination The destination array.
*
* @return The destination array.
*/
public static long[] copyFromEnd(long[] source, long[] destination) {
PreCon.notNull(source);
PreCon.notNull(destination);
int delta = source.length - destination.length;
int sourceAdjust = delta < 0 ? 0 : delta;
int destAdjust = delta < 0 ? -delta : 0;
System.arraycopy(source, sourceAdjust, destination, destAdjust, destination.length - destAdjust);
return destination;
}
/**
* Copy the source array elements to the destination array starting from the end
* and finishing when either the destination runs out of space or the source runs
* out of elements.
*
* @param source The source array.
* @param destination The destination array.
*
* @return The destination array.
*/
public static float[] copyFromEnd(float[] source, float[] destination) {
PreCon.notNull(source);
PreCon.notNull(destination);
int delta = source.length - destination.length;
int sourceAdjust = delta < 0 ? 0 : delta;
int destAdjust = delta < 0 ? -delta : 0;
System.arraycopy(source, sourceAdjust, destination, destAdjust, destination.length - destAdjust);
return destination;
}
/**
* Copy the source array elements to the destination array starting from the end
* and finishing when either the destination runs out of space or the source runs
* out of elements.
*
* @param source The source array.
* @param destination The destination array.
*
* @return The destination array.
*/
public static double[] copyFromEnd(double[] source, double[] destination) {
PreCon.notNull(source);
PreCon.notNull(destination);
int delta = source.length - destination.length;
int sourceAdjust = delta < 0 ? 0 : delta;
int destAdjust = delta < 0 ? -delta : 0;
System.arraycopy(source, sourceAdjust, destination, destAdjust, destination.length - destAdjust);
return destination;
}
/**
* Reduce the size of an array by trimming from the beginning and end of the array.
*
* @param startAmountToRemove The number of elements to remove from the start of the array.
* @param array The array to trim.
* @param endAmountToRemove The number of elements to remove from the end of the array.
*
* @param <T> The component type.
*
* @return A new trimmed array.
*/
public static <T> T[] reduce(int startAmountToRemove, T[] array, int endAmountToRemove) {
PreCon.positiveNumber(startAmountToRemove);
PreCon.notNull(array);
PreCon.positiveNumber(endAmountToRemove);
PreCon.isValid(startAmountToRemove + endAmountToRemove <= array.length,
"Amount to remove is larger than the array.");
@SuppressWarnings("unchecked")
Class<T> componentClass = (Class<T>) array.getClass().getComponentType();
int size = array.length - (startAmountToRemove + endAmountToRemove);
if (size == 0)
return newArray(componentClass, 0);
T[] newArray = newArray(componentClass, size);
System.arraycopy(array, startAmountToRemove - 1, newArray, 0, newArray.length);
return newArray;
}
/**
* Reduce the size of an array by trimming from the beginning and end of the array.
*
* @param startAmountToRemove The number of elements to remove from the start of the array.
* @param array The array to trim.
* @param endAmountToRemove The number of elements to remove from the end of the array.
*
* @return A new trimmed array.
*/
public static boolean[] reduce(int startAmountToRemove, boolean[] array, int endAmountToRemove) {
PreCon.positiveNumber(startAmountToRemove);
PreCon.notNull(array);
PreCon.positiveNumber(endAmountToRemove);
PreCon.isValid(startAmountToRemove + endAmountToRemove <= array.length,
"Amount to remove is larger than the array.");
int size = array.length - (startAmountToRemove + endAmountToRemove);
if (size == 0)
return EMPTY_BOOLEAN_ARRAY;
boolean[] newArray = new boolean[size];
System.arraycopy(array, startAmountToRemove - 1, newArray, 0, newArray.length);
return newArray;
}
/**
* Reduce the size of an array by trimming from the beginning and end of the array.
*
* @param startAmountToRemove The number of elements to remove from the start of the array.
* @param array The array to trim.
* @param endAmountToRemove The number of elements to remove from the end of the array.
*
* @return A new trimmed array.
*/
public static byte[] reduce(int startAmountToRemove, byte[] array, int endAmountToRemove) {
PreCon.positiveNumber(startAmountToRemove);
PreCon.notNull(array);
PreCon.positiveNumber(endAmountToRemove);
PreCon.isValid(startAmountToRemove + endAmountToRemove <= array.length,
"Amount to remove is larger than the array.");
int size = array.length - (startAmountToRemove + endAmountToRemove);
if (size == 0)
return EMPTY_BYTE_ARRAY;
byte[] newArray = new byte[size];
System.arraycopy(array, startAmountToRemove - 1, newArray, 0, newArray.length);
return newArray;
}
/**
* Reduce the size of an array by trimming from the beginning and end of the array.
*
* @param startAmountToRemove The number of elements to remove from the start of the array.
* @param array The array to trim.
* @param endAmountToRemove The number of elements to remove from the end of the array.
*
* @return A new trimmed array.
*/
public static char[] reduce(int startAmountToRemove, char[] array, int endAmountToRemove) {
PreCon.positiveNumber(startAmountToRemove);
PreCon.notNull(array);
PreCon.positiveNumber(endAmountToRemove);
PreCon.isValid(startAmountToRemove + endAmountToRemove <= array.length,
"Amount to remove is larger than the array.");
int size = array.length - (startAmountToRemove + endAmountToRemove);
if (size == 0)
return EMPTY_CHAR_ARRAY;
char[] newArray = new char[size];
System.arraycopy(array, startAmountToRemove - 1, newArray, 0, newArray.length);
return newArray;
}
/**
* Reduce the size of an array by trimming from the beginning and end of the array.
*
* @param startAmountToRemove The number of elements to remove from the start of the array.
* @param array The array to trim.
* @param endAmountToRemove The number of elements to remove from the end of the array.
*
* @return A new trimmed array.
*/
public static short[] reduce(int startAmountToRemove, short[] array, int endAmountToRemove) {
PreCon.positiveNumber(startAmountToRemove);
PreCon.notNull(array);
PreCon.positiveNumber(endAmountToRemove);
PreCon.isValid(startAmountToRemove + endAmountToRemove <= array.length,
"Amount to remove is larger than the array.");
int size = array.length - (startAmountToRemove + endAmountToRemove);
if (size == 0)
return EMPTY_SHORT_ARRAY;
short[] newArray = new short[size];
System.arraycopy(array, startAmountToRemove - 1, newArray, 0, newArray.length);
return newArray;
}
/**
* Reduce the size of an array by trimming from the beginning and end of the array.
*
* @param startAmountToRemove The number of elements to remove from the start of the array.
* @param array The array to trim.
* @param endAmountToRemove The number of elements to remove from the end of the array.
*
* @return A new trimmed array.
*/
public static int[] reduce(int startAmountToRemove, int[] array, int endAmountToRemove) {
PreCon.positiveNumber(startAmountToRemove);
PreCon.notNull(array);
PreCon.positiveNumber(endAmountToRemove);
PreCon.isValid(startAmountToRemove + endAmountToRemove <= array.length,
"Amount to remove is larger than the array.");
int size = array.length - (startAmountToRemove + endAmountToRemove);
if (size == 0)
return EMPTY_INT_ARRAY;
int[] newArray = new int[size];
System.arraycopy(array, startAmountToRemove - 1, newArray, 0, newArray.length);
return newArray;
}
/**
* Reduce the size of an array by trimming from the beginning and end of the array.
*
* @param startAmountToRemove The number of elements to remove from the start of the array.
* @param array The array to trim.
* @param endAmountToRemove The number of elements to remove from the end of the array.
*
* @return A new trimmed array.
*/
public static long[] reduce(int startAmountToRemove, long[] array, int endAmountToRemove) {
PreCon.positiveNumber(startAmountToRemove);
PreCon.notNull(array);
PreCon.positiveNumber(endAmountToRemove);
PreCon.isValid(startAmountToRemove + endAmountToRemove <= array.length,
"Amount to remove is larger than the array.");
int size = array.length - (startAmountToRemove + endAmountToRemove);
if (size == 0)
return EMPTY_LONG_ARRAY;
long[] newArray = new long[size];
System.arraycopy(array, startAmountToRemove - 1, newArray, 0, newArray.length);
return newArray;
}
/**
* Reduce the size of an array by trimming from the beginning and end of the array.
*
* @param startAmountToRemove The number of elements to remove from the start of the array.
* @param array The array to trim.
* @param endAmountToRemove The number of elements to remove from the end of the array.
*
* @return A new trimmed array.
*/
public static float[] reduce(int startAmountToRemove, float[] array, int endAmountToRemove) {
PreCon.positiveNumber(startAmountToRemove);
PreCon.notNull(array);
PreCon.positiveNumber(endAmountToRemove);
PreCon.isValid(startAmountToRemove + endAmountToRemove <= array.length,
"Amount to remove is larger than the array.");
int size = array.length - (startAmountToRemove + endAmountToRemove);
if (size == 0)
return EMPTY_FLOAT_ARRAY;
float[] newArray = new float[size];
System.arraycopy(array, startAmountToRemove - 1, newArray, 0, newArray.length);
return newArray;
}
/**
* Reduce the size of an array by trimming from the beginning and end of the array.
*
* @param startAmountToRemove The number of elements to remove from the start of the array.
* @param array The array to trim.
* @param endAmountToRemove The number of elements to remove from the end of the array.
*
* @return A new trimmed array.
*/
public static double[] reduce(int startAmountToRemove, double[] array, int endAmountToRemove) {
PreCon.positiveNumber(startAmountToRemove);
PreCon.notNull(array);
PreCon.positiveNumber(endAmountToRemove);
PreCon.isValid(startAmountToRemove + endAmountToRemove <= array.length,
"Amount to remove is larger than the array.");
int size = array.length - (startAmountToRemove + endAmountToRemove);
if (size == 0)
return EMPTY_DOUBLE_ARRAY;
double[] newArray = new double[size];
System.arraycopy(array, startAmountToRemove - 1, newArray, 0, newArray.length);
return newArray;
}
/**
* Reduce the size of an array by trimming from the beginning and end of the array.
*
* @param startAmountToRemove The number of elements to remove from the start of the array.
* @param array The array to trim.
* @param endAmountToRemove The number of elements to remove from the end of the array.
*
* @return A new trimmed array.
*/
public static String[] reduce(int startAmountToRemove, String[] array, int endAmountToRemove) {
PreCon.positiveNumber(startAmountToRemove);
PreCon.notNull(array);
PreCon.positiveNumber(endAmountToRemove);
PreCon.isValid(startAmountToRemove + endAmountToRemove <= array.length,
"Amount to remove is larger than the array.");
int size = array.length - (startAmountToRemove + endAmountToRemove);
if (size == 0)
return EMPTY_STRING_ARRAY;
String[] newArray = new String[size];
System.arraycopy(array, startAmountToRemove - 1, newArray, 0, newArray.length);
return newArray;
}
/**
* Reduce the size of an array by trimming from the beginning and end of the array.
*
* @param startAmountToRemove The number of elements to remove from the start of the array.
* @param array The array to trim.
* @param endAmountToRemove The number of elements to remove from the end of the array.
*
* @return A new trimmed array.
*/
public static ItemStack[] reduce(int startAmountToRemove, ItemStack[] array, int endAmountToRemove) {
PreCon.positiveNumber(startAmountToRemove);
PreCon.notNull(array);
PreCon.positiveNumber(endAmountToRemove);
PreCon.isValid(startAmountToRemove + endAmountToRemove <= array.length,
"Amount to remove is larger than the array.");
int size = array.length - (startAmountToRemove + endAmountToRemove);
if (size == 0)
return EMPTY_ITEMSTACK_ARRAY;
ItemStack[] newArray = new ItemStack[size];
System.arraycopy(array, startAmountToRemove - 1, newArray, 0, newArray.length);
return newArray;
}
/**
* Reduce the size of an array by trimming from the beginning and end of the array.
*
* @param startAmountToRemove The number of elements to remove from the start of the array.
* @param array The array to trim.
* @param endAmountToRemove The number of elements to remove from the end of the array.
*
* @return A new trimmed array.
*/
public static Entity[] reduce(int startAmountToRemove, Entity[] array, int endAmountToRemove) {
PreCon.positiveNumber(startAmountToRemove);
PreCon.notNull(array);
PreCon.positiveNumber(endAmountToRemove);
PreCon.isValid(startAmountToRemove + endAmountToRemove <= array.length,
"Amount to remove is larger than the array.");
int size = array.length - (startAmountToRemove + endAmountToRemove);
if (size == 0)
return EMPTY_ENTITY_ARRAY;
Entity[] newArray = new Entity[size];
System.arraycopy(array, startAmountToRemove - 1, newArray, 0, newArray.length);
return newArray;
}
/**
* Reduce the size of an array by trimming from the beginning of the array.
*
* @param amountToRemove The number of elements to remove.
* @param array The array to trim.
*
* @param <T> The component type.
*
* @return A new trimmed array.
*/
public static <T> T[] reduceStart(int amountToRemove, T[] array) {
PreCon.notNull(array);
PreCon.isValid(amountToRemove <= array.length, "Amount to remove is larger than the array.");
@SuppressWarnings("unchecked")
Class<T> componentClass = (Class<T>) array.getClass().getComponentType();
if (array.length == amountToRemove)
return newArray(componentClass, 0);
int size = array.length - amountToRemove;
T[] result = newArray(componentClass, size);
return copyFromEnd(array, result);
}
/**
* Reduce the size of an array by trimming from the beginning of the array.
*
* @param amountToRemove The number of elements to remove.
* @param array The array to trim.
*
* @return A new trimmed array.
*/
public static boolean[] reduceStart(int amountToRemove, boolean[] array) {
PreCon.notNull(array);
PreCon.isValid(amountToRemove <= array.length, "Amount to remove is larger than the array.");
if (array.length == amountToRemove)
return EMPTY_BOOLEAN_ARRAY;
int size = array.length - amountToRemove;
return copyFromEnd(array, new boolean[size]);
}
/**
* Reduce the size of an array by trimming from the beginning of the array.
*
* @param amountToRemove The number of elements to remove.
* @param array The array to trim.
*
* @return A new trimmed array.
*/
public static byte[] reduceStart(int amountToRemove, byte[] array) {
PreCon.notNull(array);
PreCon.isValid(amountToRemove <= array.length, "Amount to remove is larger than the array.");
if (array.length == amountToRemove)
return EMPTY_BYTE_ARRAY;
int size = array.length - amountToRemove;
return copyFromEnd(array, new byte[size]);
}
/**
* Reduce the size of an array by trimming from the beginning of the array.
*
* @param amountToRemove The number of elements to remove.
* @param array The array to trim.
*
* @return A new trimmed array.
*/
public static char[] reduceStart(int amountToRemove, char[] array) {
PreCon.notNull(array);
PreCon.isValid(amountToRemove <= array.length, "Amount to remove is larger than the array.");
if (array.length == amountToRemove)
return EMPTY_CHAR_ARRAY;
int size = array.length - amountToRemove;
return copyFromEnd(array, new char[size]);
}
/**
* Reduce the size of an array by trimming from the beginning of the array.
*
* @param amountToRemove The number of elements to remove.
* @param array The array to trim.
*
* @return A new trimmed array.
*/
public static short[] reduceStart(int amountToRemove, short[] array) {
PreCon.notNull(array);
PreCon.isValid(amountToRemove <= array.length, "Amount to remove is larger than the array.");
if (array.length == amountToRemove)
return EMPTY_SHORT_ARRAY;
int size = array.length - amountToRemove;
return copyFromEnd(array, new short[size]);
}
/**
* Reduce the size of an array by trimming from the beginning of the array.
*
* @param amountToRemove The number of elements to remove.
* @param array The array to trim.
*
* @return A new trimmed array.
*/
public static int[] reduceStart(int amountToRemove, int[] array) {
PreCon.notNull(array);
PreCon.isValid(amountToRemove <= array.length, "Amount to remove is larger than the array.");
if (array.length == amountToRemove)
return EMPTY_INT_ARRAY;
int size = array.length - amountToRemove;
return copyFromEnd(array, new int[size]);
}
/**
* Reduce the size of an array by trimming from the beginning of the array.
*
* @param amountToRemove The number of elements to remove.
* @param array The array to trim.
*
* @return A new trimmed array.
*/
public static long[] reduceStart(int amountToRemove, long[] array) {
PreCon.notNull(array);
PreCon.isValid(amountToRemove <= array.length, "Amount to remove is larger than the array.");
if (array.length == amountToRemove)
return EMPTY_LONG_ARRAY;
int size = array.length - amountToRemove;
return copyFromEnd(array, new long[size]);
}
/**
* Reduce the size of an array by trimming from the beginning of the array.
*
* @param amountToRemove The number of elements to remove.
* @param array The array to trim.
*
* @return A new trimmed array.
*/
public static float[] reduceStart(int amountToRemove, float[] array) {
PreCon.notNull(array);
PreCon.isValid(amountToRemove <= array.length, "Amount to remove is larger than the array.");
if (array.length == amountToRemove)
return EMPTY_FLOAT_ARRAY;
int size = array.length - amountToRemove;
return copyFromEnd(array, new float[size]);
}
/**
* Reduce the size of an array by trimming from the beginning of the array.
*
* @param amountToRemove The number of elements to remove.
* @param array The array to trim.
*
* @return A new trimmed array.
*/
public static double[] reduceStart(int amountToRemove, double[] array) {
PreCon.notNull(array);
PreCon.isValid(amountToRemove <= array.length, "Amount to remove is larger than the array.");
if (array.length == amountToRemove)
return EMPTY_DOUBLE_ARRAY;
int size = array.length - amountToRemove;
return copyFromEnd(array, new double[size]);
}
/**
* Reduce the size of an array by trimming from the beginning of the array.
*
* @param amountToRemove The number of elements to remove.
* @param array The array to trim.
*
* @return A new trimmed array.
*/
public static String[] reduceStart(int amountToRemove, String[] array) {
PreCon.notNull(array);
PreCon.isValid(amountToRemove <= array.length, "Amount to remove is larger than the array.");
if (array.length == amountToRemove)
return EMPTY_STRING_ARRAY;
int size = array.length - amountToRemove;
return copyFromEnd(array, new String[size]);
}
/**
* Reduce the size of an array by trimming from the beginning of the array.
*
* @param amountToRemove The number of elements to remove.
* @param array The array to trim.
*
* @return A new trimmed array.
*/
public static ItemStack[] reduceStart(int amountToRemove, ItemStack[] array) {
PreCon.notNull(array);
PreCon.isValid(amountToRemove <= array.length, "Amount to remove is larger than the array.");
if (array.length == amountToRemove)
return EMPTY_ITEMSTACK_ARRAY;
int size = array.length - amountToRemove;
return copyFromEnd(array, new ItemStack[size]);
}
/**
* Reduce the size of an array by trimming from the beginning of the array.
*
* @param amountToRemove The number of elements to remove.
* @param array The array to trim.
*
* @return A new trimmed array.
*/
public static Entity[] reduceStart(int amountToRemove, Entity[] array) {
PreCon.notNull(array);
PreCon.isValid(amountToRemove <= array.length, "Amount to remove is larger than the array.");
if (array.length == amountToRemove)
return EMPTY_ENTITY_ARRAY;
int size = array.length - amountToRemove;
return copyFromEnd(array, new Entity[size]);
}
/**
* Reduce the size of an array by trimming from the end of the array.
*
* @param array The array to trim.
* @param amountToRemove The number of elements to remove.
*
* @param <T> The array component type.
*
* @return A new trimmed array.
*/
public static <T> T[] reduceEnd(T[] array, int amountToRemove) {
PreCon.notNull(array);
PreCon.isValid(amountToRemove <= array.length, "Amount to remove is larger than the array.");
@SuppressWarnings("unchecked")
Class<T> componentClass = (Class<T>) array.getClass().getComponentType();
if (array.length == amountToRemove)
return newArray(componentClass, 0);
int size = array.length - amountToRemove;
T[] result = newArray(componentClass, size);
return copyFromStart(array, result);
}
/**
* Reduce the size of an array by trimming from the end of the array.
*
* @param array The array to trim.
* @param amountToRemove The number of elements to remove.
*
* @return A new trimmed array.
*/
public static boolean[] reduceEnd(boolean[] array, int amountToRemove) {
PreCon.notNull(array);
PreCon.isValid(amountToRemove <= array.length, "Amount to remove is larger than the array.");
if (array.length == amountToRemove)
return EMPTY_BOOLEAN_ARRAY;
int size = array.length - amountToRemove;
return copyFromStart(array, new boolean[size]);
}
/**
* Reduce the size of an array by trimming from the end of the array.
*
* @param array The array to trim.
* @param amountToRemove The number of elements to remove.
*
* @return A new trimmed array.
*/
public static byte[] reduceEnd(byte[] array, int amountToRemove) {
PreCon.notNull(array);
PreCon.isValid(amountToRemove <= array.length, "Amount to remove is larger than the array.");
if (array.length == amountToRemove)
return EMPTY_BYTE_ARRAY;
int size = array.length - amountToRemove;
return copyFromStart(array, new byte[size]);
}
/**
* Reduce the size of an array by trimming from the end of the array.
*
* @param array The array to trim.
* @param amountToRemove The number of elements to remove.
*
* @return A new trimmed array.
*/
public static char[] reduceEnd(char[] array, int amountToRemove) {
PreCon.notNull(array);
PreCon.isValid(amountToRemove <= array.length, "Amount to remove is larger than the array.");
if (array.length == amountToRemove)
return EMPTY_CHAR_ARRAY;
int size = array.length - amountToRemove;
return copyFromStart(array, new char[size]);
}
/**
* Reduce the size of an array by trimming from the end of the array.
*
* @param array The array to trim.
* @param amountToRemove The number of elements to remove.
*
* @return A new trimmed array.
*/
public static short[] reduceEnd(short[] array, int amountToRemove) {
PreCon.notNull(array);
PreCon.isValid(amountToRemove <= array.length, "Amount to remove is larger than the array.");
if (array.length == amountToRemove)
return EMPTY_SHORT_ARRAY;
int size = array.length - amountToRemove;
return copyFromStart(array, new short[size]);
}
/**
* Reduce the size of an array by trimming from the end of the array.
*
* @param array The array to trim.
* @param amountToRemove The number of elements to remove.
*
* @return A new trimmed array.
*/
public static int[] reduceEnd(int[] array, int amountToRemove) {
PreCon.notNull(array);
PreCon.isValid(amountToRemove <= array.length, "Amount to remove is larger than the array.");
if (array.length == amountToRemove)
return EMPTY_INT_ARRAY;
int size = array.length - amountToRemove;
return copyFromStart(array, new int[size]);
}
/**
* Reduce the size of an array by trimming from the end of the array.
*
* @param array The array to trim.
* @param amountToRemove The number of elements to remove.
*
* @return A new trimmed array.
*/
public static long[] reduceEnd(long[] array, int amountToRemove) {
PreCon.notNull(array);
PreCon.isValid(amountToRemove <= array.length, "Amount to remove is larger than the array.");
if (array.length == amountToRemove)
return EMPTY_LONG_ARRAY;
int size = array.length - amountToRemove;
return copyFromStart(array, new long[size]);
}
/**
* Reduce the size of an array by trimming from the end of the array.
*
* @param array The array to trim.
* @param amountToRemove The number of elements to remove.
*
* @return A new trimmed array.
*/
public static float[] reduceEnd(float[] array, int amountToRemove) {
PreCon.notNull(array);
PreCon.isValid(amountToRemove <= array.length, "Amount to remove is larger than the array.");
if (array.length == amountToRemove)
return EMPTY_FLOAT_ARRAY;
int size = array.length - amountToRemove;
return copyFromStart(array, new float[size]);
}
/**
* Reduce the size of an array by trimming from the end of the array.
*
* @param array The array to trim.
* @param amountToRemove The number of elements to remove.
*
* @return A new trimmed array.
*/
public static double[] reduceEnd(double[] array, int amountToRemove) {
PreCon.notNull(array);
PreCon.isValid(amountToRemove <= array.length, "Amount to remove is larger than the array.");
if (array.length == amountToRemove)
return EMPTY_DOUBLE_ARRAY;
int size = array.length - amountToRemove;
return copyFromStart(array, new double[size]);
}
/**
* Reduce the size of an array by trimming from the end of the array.
*
* @param array The array to trim.
* @param amountToRemove The number of elements to remove.
*
* @return A new trimmed array.
*/
public static String[] reduceEnd(String[] array, int amountToRemove) {
PreCon.notNull(array);
PreCon.isValid(amountToRemove <= array.length, "Amount to remove is larger than the array.");
if (array.length == amountToRemove)
return EMPTY_STRING_ARRAY;
int size = array.length - amountToRemove;
return copyFromStart(array, new String[size]);
}
/**
* Reduce the size of an array by trimming from the end of the array.
*
* @param array The array to trim.
* @param amountToRemove The number of elements to remove.
*
* @return A new trimmed array.
*/
public static ItemStack[] reduceEnd(ItemStack[] array, int amountToRemove) {
PreCon.notNull(array);
PreCon.isValid(amountToRemove <= array.length, "Amount to remove is larger than the array.");
if (array.length == amountToRemove)
return EMPTY_ITEMSTACK_ARRAY;
int size = array.length - amountToRemove;
return copyFromStart(array, new ItemStack[size]);
}
/**
* Reduce the size of an array by trimming from the end of the array.
*
* @param array The array to trim.
* @param amountToRemove The number of elements to remove.
*
* @return A new trimmed array.
*/
public static Entity[] reduceEnd(Entity[] array, int amountToRemove) {
PreCon.notNull(array);
PreCon.isValid(amountToRemove <= array.length, "Amount to remove is larger than the array.");
if (array.length == amountToRemove)
return EMPTY_ENTITY_ARRAY;
int size = array.length - amountToRemove;
return copyFromStart(array, new Entity[size]);
}
/**
* Convert a primitive wrapper array to a primitive array.
*
* @param array The array to convert.
*
* @return A new primitive array.
*/
public static boolean[] toPrimitive(Boolean[] array) {
PreCon.notNull(array);
if (array.length == 0)
return EMPTY_BOOLEAN_ARRAY;
boolean[] newArray = new boolean[array.length];
for (int i=0; i < array.length; i++) {
Boolean element = array[i];
newArray[i] = element == null ? false : element;
}
return newArray;
}
/**
* Convert a primitive wrapper array to a primitive array.
*
* @param array The array to convert.
*
* @return A new primitive array.
*/
public static byte[] toPrimitive(Byte[] array) {
PreCon.notNull(array);
if (array.length == 0)
return EMPTY_BYTE_ARRAY;
byte[] newArray = new byte[array.length];
for (int i=0; i < array.length; i++) {
Byte element = array[i];
newArray[i] = element == null ? 0 : element;
}
return newArray;
}
/**
* Convert a primitive wrapper array to a primitive array.
*
* @param array The array to convert.
*
* @return A new primitive array.
*/
public static char[] toPrimitive(Character[] array) {
PreCon.notNull(array);
if (array.length == 0)
return EMPTY_CHAR_ARRAY;
char[] newArray = new char[array.length];
for (int i=0; i < array.length; i++) {
Character element = array[i];
newArray[i] = element == null ? 0 : element;
}
return newArray;
}
/**
* Convert a primitive wrapper array to a primitive array.
*
* @param array The array to convert.
*
* @return A new primitive array.
*/
public static short[] toPrimitive(Short[] array) {
PreCon.notNull(array);
if (array.length == 0)
return EMPTY_SHORT_ARRAY;
short[] newArray = new short[array.length];
for (int i=0; i < array.length; i++) {
Short element = array[i];
newArray[i] = element == null ? 0 : element;
}
return newArray;
}
/**
* Convert a primitive wrapper array to a primitive array.
*
* @param array The array to convert.
*
* @return A new primitive array.
*/
public static int[] toPrimitive(Integer[] array) {
PreCon.notNull(array);
if (array.length == 0)
return EMPTY_INT_ARRAY;
int[] newArray = new int[array.length];
for (int i=0; i < array.length; i++) {
Integer element = array[i];
newArray[i] = element == null ? 0 : element;
}
return newArray;
}
/**
* Convert a primitive wrapper array to a primitive array.
*
* @param array The array to convert.
*
* @return A new primitive array.
*/
public static long[] toPrimitive(Long[] array) {
PreCon.notNull(array);
if (array.length == 0)
return EMPTY_LONG_ARRAY;
long[] newArray = new long[array.length];
for (int i=0; i < array.length; i++) {
Long element = array[i];
newArray[i] = element == null ? 0L : element;
}
return newArray;
}
/**
* Convert a primitive wrapper array to a primitive array.
*
* @param array The array to convert.
*
* @return A new primitive array.
*/
public static float[] toPrimitive(Float[] array) {
PreCon.notNull(array);
if (array.length == 0)
return EMPTY_FLOAT_ARRAY;
float[] newArray = new float[array.length];
for (int i=0; i < array.length; i++) {
Float element = array[i];
newArray[i] = element == null ? 0F : element;
}
return newArray;
}
/**
* Convert a primitive wrapper array to a primitive array.
*
* @param array The array to convert.
*
* @return A new primitive array.
*/
public static double[] toPrimitive(Double[] array) {
PreCon.notNull(array);
if (array.length == 0)
return EMPTY_DOUBLE_ARRAY;
double[] newArray = new double[array.length];
for (int i=0; i < array.length; i++) {
Double element = array[i];
newArray[i] = element == null ? 0 : element;
}
return newArray;
}
/**
* Convert a primitive array to a primitive wrapper array.
*
* @param array The array to convert.
*
* @return A new primitive wrapper array.
*/
public static Boolean[] toWrapper(boolean[] array) {
PreCon.notNull(array);
Boolean[] newArray = new Boolean[array.length];
for (int i=0; i < array.length; i++) {
newArray[i] = array[i];
}
return newArray;
}
/**
* Convert a primitive array to a primitive wrapper array.
*
* @param array The array to convert.
*
* @return A new primitive wrapper array.
*/
public static Byte[] toWrapper(byte[] array) {
PreCon.notNull(array);
Byte[] newArray = new Byte[array.length];
for (int i=0; i < array.length; i++) {
newArray[i] = array[i];
}
return newArray;
}
/**
* Convert a primitive array to a primitive wrapper array.
*
* @param array The array to convert.
*
* @return A new primitive wrapper array.
*/
public static Character[] toWrapper(char[] array) {
PreCon.notNull(array);
Character[] newArray = new Character[array.length];
for (int i=0; i < array.length; i++) {
newArray[i] = array[i];
}
return newArray;
}
/**
* Convert a primitive array to a primitive wrapper array.
*
* @param array The array to convert.
*
* @return A new primitive wrapper array.
*/
public static Short[] toWrapper(short[] array) {
PreCon.notNull(array);
Short[] newArray = new Short[array.length];
for (int i=0; i < array.length; i++) {
newArray[i] = array[i];
}
return newArray;
}
/**
* Convert a primitive array to a primitive wrapper array.
*
* @param array The array to convert.
*
* @return A new primitive wrapper array.
*/
public static Integer[] toWrapper(int[] array) {
PreCon.notNull(array);
Integer[] newArray = new Integer[array.length];
for (int i=0; i < array.length; i++) {
newArray[i] = array[i];
}
return newArray;
}
/**
* Convert a primitive array to a primitive wrapper array.
*
* @param array The array to convert.
*
* @return A new primitive wrapper array.
*/
public static Long[] toWrapper(long[] array) {
PreCon.notNull(array);
Long[] newArray = new Long[array.length];
for (int i=0; i < array.length; i++) {
newArray[i] = array[i];
}
return newArray;
}
/**
* Convert a primitive array to a primitive wrapper array.
*
* @param array The array to convert.
*
* @return A new primitive wrapper array.
*/
public static Float[] toWrapper(float[] array) {
PreCon.notNull(array);
Float[] newArray = new Float[array.length];
for (int i=0; i < array.length; i++) {
newArray[i] = array[i];
}
return newArray;
}
/**
* Convert a primitive array to a primitive wrapper array.
*
* @param array The array to convert.
*
* @return A new primitive wrapper array.
*/
public static Double[] toWrapper(double[] array) {
PreCon.notNull(array);
Double[] newArray = new Double[array.length];
for (int i=0; i < array.length; i++) {
newArray[i] = array[i];
}
return newArray;
}
/**
* Get the element at the specified index of the array
* or return the default value if the array is smaller
* than the specified index.
*
* @param array The array to get an element from.
* @param index The index of the element to get.
* @param defaultValue The default value if the array isn't large enough.
*
* @param <T> The array component type.
*
* @return The element at the specified index or the default value.
*/
public static <T> T get(T[] array, int index, T defaultValue) {
PreCon.notNull(array);
return (index - 1 > array.length)
? defaultValue
: array[index];
}
/**
* Get the element at the specified index of the array
* or return the default value if the array is smaller
* than the specified index.
*
* @param array The array to get an element from.
* @param index The index of the element to get.
* @param defaultValue The default value if the array isn't large enough.
*
* @return The element at the specified index or the default value.
*/
public static boolean get(boolean[] array, int index, boolean defaultValue) {
PreCon.notNull(array);
return (index - 1 > array.length)
? defaultValue
: array[index];
}
/**
* Get the element at the specified index of the array
* or return the default value if the array is smaller
* than the specified index.
*
* @param array The array to get an element from.
* @param index The index of the element to get.
* @param defaultValue The default value if the array isn't large enough.
*
* @return The element at the specified index or the default value.
*/
public static byte get(byte[] array, int index, byte defaultValue) {
PreCon.notNull(array);
return (index - 1 > array.length)
? defaultValue
: array[index];
}
/**
* Get the element at the specified index of the array
* or return the default value if the array is smaller
* than the specified index.
*
* @param array The array to get an element from.
* @param index The index of the element to get.
* @param defaultValue The default value if the array isn't large enough.
*
* @return The element at the specified index or the default value.
*/
public static short get(short[] array, int index, short defaultValue) {
PreCon.notNull(array);
return (index - 1 > array.length)
? defaultValue
: array[index];
}
/**
* Get the element at the specified index of the array
* or return the default value if the array is smaller
* than the specified index.
*
* @param array The array to get an element from.
* @param index The index of the element to get.
* @param defaultValue The default value if the array isn't large enough.
*
* @return The element at the specified index or the default value.
*/
public static char get(char[] array, int index, char defaultValue) {
PreCon.notNull(array);
return (index - 1 > array.length)
? defaultValue
: array[index];
}
/**
* Get the element at the specified index of the array
* or return the default value if the array is smaller
* than the specified index.
*
* @param array The array to get an element from.
* @param index The index of the element to get.
* @param defaultValue The default value if the array isn't large enough.
*
* @return The element at the specified index or the default value.
*/
public static int get(int[] array, int index, int defaultValue) {
PreCon.notNull(array);
return (index - 1 > array.length)
? defaultValue
: array[index];
}
/**
* Get the element at the specified index of the array
* or return the default value if the array is smaller
* than the specified index.
*
* @param array The array to get an element from.
* @param index The index of the element to get.
* @param defaultValue The default value if the array isn't large enough.
*
* @return The element at the specified index or the default value.
*/
public static long get(long[] array, int index, long defaultValue) {
PreCon.notNull(array);
return (index - 1 > array.length)
? defaultValue
: array[index];
}
/**
* Get the element at the specified index of the array
* or return the default value if the array is smaller
* than the specified index.
*
* @param array The array to get an element from.
* @param index The index of the element to get.
* @param defaultValue The default value if the array isn't large enough.
*
* @return The element at the specified index or the default value.
*/
public static float get(float[] array, int index, float defaultValue) {
PreCon.notNull(array);
return (index - 1 > array.length)
? defaultValue
: array[index];
}
/**
* Get the element at the specified index of the array
* or return the default value if the array is smaller
* than the specified index.
*
* @param array The array to get an element from.
* @param index The index of the element to get.
* @param defaultValue The default value if the array isn't large enough.
*
* @return The element at the specified index or the default value.
*/
public static double get(double[] array, int index, double defaultValue) {
PreCon.notNull(array);
return (index - 1 > array.length)
? defaultValue
: array[index];
}
/**
* Get the last element in an array.
*
* @param array The array.
*
* @param <T> The array component type.
*/
public static <T> T last(T[] array) {
PreCon.notNull(array);
PreCon.isValid(array.length > 0, "Array has no elements.");
return array[array.length - 1];
}
/**
* Get the last element in an array.
*
* @param array The array.
*
* @param <T> The array component type.
*/
public static <T> T last(T[] array, T empty) {
PreCon.notNull(array);
if (array.length == 0)
return empty;
return array[array.length - 1];
}
/**
* Get the last element in an array.
*
* @param array The array.
*/
public static boolean last(boolean[] array) {
PreCon.notNull(array);
PreCon.isValid(array.length > 0, "Array has no elements.");
return array[array.length - 1];
}
/**
* Get the last element in an array.
*
* @param array The array.
* @param empty The value to return if the array is empty.
*/
public static boolean last(boolean[] array, boolean empty) {
PreCon.notNull(array);
if (array.length == 0)
return empty;
return array[array.length - 1];
}
/**
* Get the last element in an array.
*
* @param array The array.
*/
public static byte last(byte[] array) {
PreCon.notNull(array);
PreCon.isValid(array.length > 0, "Array has no elements.");
return array[array.length - 1];
}
/**
* Get the last element in an array.
*
* @param array The array.
* @param empty The value to return if the array is empty.
*/
public static byte last(byte[] array, byte empty) {
PreCon.notNull(array);
if (array.length == 0)
return empty;
return array[array.length - 1];
}
/**
* Get the last element in an array.
*
* @param array The array.
*/
public static char last(char[] array) {
PreCon.notNull(array);
PreCon.isValid(array.length > 0, "Array has no elements.");
return array[array.length - 1];
}
/**
* Get the last element in an array.
*
* @param array The array.
* @param empty The value to return if the array is empty.
*/
public static char last(char[] array, char empty) {
PreCon.notNull(array);
if (array.length == 0)
return empty;
return array[array.length - 1];
}
/**
* Get the last element in an array.
*
* @param array The array.
*/
public static short last(short[] array) {
PreCon.notNull(array);
PreCon.isValid(array.length > 0, "Array has no elements.");
return array[array.length - 1];
}
/**
* Get the last element in an array.
*
* @param array The array.
* @param empty The value to return if the array is empty.
*/
public static short last(short[] array, short empty) {
PreCon.notNull(array);
if (array.length == 0)
return empty;
return array[array.length - 1];
}
/**
* Get the last element in an array.
*
* @param array The array.
*/
public static int last(int[] array) {
PreCon.notNull(array);
PreCon.isValid(array.length > 0, "Array has no elements.");
return array[array.length - 1];
}
/**
* Get the last element in an array.
*
* @param array The array.
* @param empty The value to return if the array is empty.
*/
public static int last(int[] array, int empty) {
PreCon.notNull(array);
if (array.length == 0)
return empty;
return array[array.length - 1];
}
/**
* Get the last element in an array.
*
* @param array The array.
*/
public static long last(long[] array) {
PreCon.notNull(array);
PreCon.isValid(array.length > 0, "Array has no elements.");
return array[array.length - 1];
}
/**
* Get the last element in an array.
*
* @param array The array.
* @param empty The value to return if the array is empty.
*/
public static long last(long[] array, long empty) {
PreCon.notNull(array);
if (array.length == 0)
return empty;
return array[array.length - 1];
}
/**
* Get the last element in an array.
*
* @param array The array.
*/
public static float last(float[] array) {
PreCon.notNull(array);
PreCon.isValid(array.length > 0, "Array has no elements.");
return array[array.length - 1];
}
/**
* Get the last element in an array.
*
* @param array The array.
* @param empty The value to return if the array is empty.
*/
public static float last(float[] array, float empty) {
PreCon.notNull(array);
if (array.length == 0)
return empty;
return array[array.length - 1];
}
/**
* Get the last element in an array.
*
* @param array The array.
*/
public static double last(double[] array) {
PreCon.notNull(array);
PreCon.isValid(array.length > 0, "Array has no elements.");
return array[array.length - 1];
}
/**
* Get the last element in an array.
*
* @param array The array.
* @param empty The value to return if the array is empty.
*/
public static double last(double[] array, double empty) {
PreCon.notNull(array);
if (array.length == 0)
return empty;
return array[array.length - 1];
}
private static <T> T[] newArray(Class<T> arrayClass, int size) {
@SuppressWarnings("unchecked")
T[] newArray = (T[])Array.newInstance(arrayClass, size);
return newArray;
}
}
|
package com.witchworks.common.tile;
import com.witchworks.api.helper.ItemNullHelper;
import com.witchworks.client.gui.container.ContainerOven;
import net.minecraft.entity.item.EntityItem;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.entity.player.InventoryPlayer;
import net.minecraft.init.Items;
import net.minecraft.inventory.Container;
import net.minecraft.inventory.ISidedInventory;
import net.minecraft.inventory.ItemStackHelper;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.tileentity.TileEntityLockable;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.ITickable;
import net.minecraft.util.text.TextComponentTranslation;
import net.minecraftforge.items.ItemStackHandler;
import java.util.List;
public class TileOven extends TileEntityLockable implements ITickable, ISidedInventory {
private static final int[] SLOT_TOP = new int[]{3, 4};
private static final int[] SLOT_BOTTOM = new int[]{0, 1, 2};
private List<ItemStack> itemStacks = ItemNullHelper.asList(5);
private String customName;
private EntityPlayerMP player;
private ItemStackHandler handler;
@Override
public int[] getSlotsForFace(EnumFacing side) {
return side == EnumFacing.UP ? SLOT_TOP : SLOT_BOTTOM;
}
@Override
public void setInventorySlotContents(int index, ItemStack stack) {
final boolean flag = !stack.isEmpty() && stack.isItemEqual(itemStacks.get(index)) && ItemStack.areItemStackTagsEqual(stack, itemStacks.get(index));
itemStacks.set(index, stack);
if (!stack.isEmpty() && stack.getCount() > this.getInventoryStackLimit()) {
stack.setCount(getInventoryStackLimit());
}
if (index == 0 && !flag) {
this.markDirty();
}
}
@Override
public boolean canInsertItem(int index, ItemStack itemStackIn, EnumFacing direction) {
return this.isItemValidForSlot(index, itemStackIn);
}
@Override
public boolean canExtractItem(int index, ItemStack stack, EnumFacing direction) {
{
if (direction == EnumFacing.DOWN && index == 1) {
Item item = stack.getItem();
if (item != Items.WATER_BUCKET && item != Items.BUCKET) {
return false;
}
}
return true;
}
}
@Override
public int getSizeInventory() {
return this.itemStacks.size();
}
@Override
public boolean isEmpty() {
return ItemNullHelper.isEmpty(itemStacks);
}
@Override
public ItemStack getStackInSlot(int index) {
return itemStacks.get(index);
}
@Override
public ItemStack decrStackSize(int index, int count) {
return ItemStackHelper.getAndSplit(itemStacks, index, count);
}
@Override
public ItemStack removeStackFromSlot(int index) {
return ItemStackHelper.getAndRemove(itemStacks, index);
}
@Override
public int getInventoryStackLimit() {
return 1;
}
@Override
public boolean isUsableByPlayer(EntityPlayer player) {
return true;
}
@Override
public void openInventory(EntityPlayer player) {
}
@Override
public void closeInventory(EntityPlayer player) {
}
public boolean isItemValidForSlot(int index, ItemStack stack) {
return true;
}
public void dropItems() {
for (int i = 0; i < 16; ++i) {
final ItemStack stack = itemStacks.get(i);
if (!world.isRemote && !stack.isEmpty()) {
final EntityItem item = new EntityItem(world, pos.getX() + 0.5D, pos.getY() + 0.5D, pos.getZ() + 0.5D, stack);
world.spawnEntity(item);
}
itemStacks.set(i, ItemStack.EMPTY);
}
}
@Override
public int getField(int id) {
return 0;
}
@Override
public void setField(int id, int value) {
}
@Override
public int getFieldCount() {
return 0;
}
@Override
public void clear() {
for (int i = 0; i < 16; ++i) {
this.itemStacks.set(i, ItemStack.EMPTY);
}
}
public void update() {
}
@Override
public Container createContainer(InventoryPlayer playerInventory, EntityPlayer playerIn) {
return new ContainerOven(playerInventory, this);
}
@Override
public String getGuiID() {
return "witchworks:oven";
}
public void setCustomInventoryName(String name) {
this.customName = name;
}
@Override
public String getName() {
return this.hasCustomName() ? this.customName : new TextComponentTranslation("container.oven").getFormattedText();
}
@Override
public boolean hasCustomName() {
return this.customName != null && !this.customName.isEmpty();
}
@Override
public void readFromNBT(NBTTagCompound compound) {
super.readFromNBT(compound);
final NBTTagList nbttaglist = compound.getTagList("Items", 10);
this.itemStacks = ItemNullHelper.asList(320);
for (int i = 0; i < nbttaglist.tagCount(); ++i) {
final NBTTagCompound nbttagcompound = nbttaglist.getCompoundTagAt(i);
final int j = nbttagcompound.getByte("Slot");
if (j >= 0 && j < 16) {
this.itemStacks.set(j, new ItemStack(nbttagcompound));
}
}
if (compound.hasKey("CustomName", 8)) {
this.customName = compound.getString("CustomName");
}
}
@Override
public NBTTagCompound writeToNBT(NBTTagCompound compound) {
super.writeToNBT(compound);
final NBTTagList nbttaglist = new NBTTagList();
for (int i = 0; i < 16; ++i) {
if (!itemStacks.get(i).isEmpty()) {
final NBTTagCompound nbttagcompound = new NBTTagCompound();
nbttagcompound.setByte("Slot", (byte) i);
itemStacks.get(i).writeToNBT(nbttagcompound);
nbttaglist.appendTag(nbttagcompound);
}
}
compound.setTag("Items", nbttaglist);
if (this.hasCustomName()) {
compound.setString("CustomName", this.customName);
}
return compound;
}
}
|
package com.provinggrounds.match3things.game;
/*
* Represents a game grid. Contains a rectangular grid of Block objects.
*/
public class Grid {
int width;
int height;
Block[][] gameGrid;
/*
* Width and height must always be provided to Grid - should not be constructed without initializing/passing in those values
*/
@SuppressWarnings("unused")
private Grid() {
}
Grid(int width, int height) {
this.width = width;
this.height = height;
createGameGrid();
}
/*
* Creates grid, allocates storage
*/
private void createGameGrid() {
gameGrid = new Block[width][height];
}
}
|
package com.weather_report.networking;
import com.weather_report.data.Pull;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public enum HttpManager implements Pull<String, String> {
GET {
@Override
public String retrieve(String... urlParams) throws IllegalStateException {
StringBuilder result = new StringBuilder();
StringBuilder urlToParse = new StringBuilder();
for (String path : urlParams) {
urlToParse.append(path).append("/");
}
try {
URL url = new URL(urlToParse.toString());
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5000);
conn.setReadTimeout(5000);
conn.setRequestMethod("GET");
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
result.append(line);
}
rd.close();
} catch (Exception e) {
System.err.println("Couldn't load Help, " + e.getMessage());
}
return result.toString();
}
},
POST {
@Override
public String retrieve(String... params) throws IllegalStateException {
// TODO: To be implemented.
return null;
}
}
}
|
package de.domisum.animulusapi.npc;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.craftbukkit.v1_9_R1.entity.CraftPlayer;
import org.bukkit.craftbukkit.v1_9_R1.inventory.CraftItemStack;
import org.bukkit.craftbukkit.v1_9_R1.util.CraftChatMessage;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import com.mojang.authlib.GameProfile;
import de.domisum.animulusapi.AnimulusAPI;
import de.domisum.auxiliumapi.util.bukkit.LocationUtil;
import de.domisum.auxiliumapi.util.bukkit.PacketUtil;
import de.domisum.auxiliumapi.util.java.ReflectionUtil;
import de.domisum.auxiliumapi.util.java.ThreadUtil;
import net.minecraft.server.v1_9_R1.DataWatcher;
import net.minecraft.server.v1_9_R1.DataWatcherObject;
import net.minecraft.server.v1_9_R1.DataWatcherRegistry;
import net.minecraft.server.v1_9_R1.Entity;
import net.minecraft.server.v1_9_R1.EnumItemSlot;
import net.minecraft.server.v1_9_R1.PacketPlayOutAnimation;
import net.minecraft.server.v1_9_R1.PacketPlayOutEntity.PacketPlayOutEntityLook;
import net.minecraft.server.v1_9_R1.PacketPlayOutEntity.PacketPlayOutRelEntityMoveLook;
import net.minecraft.server.v1_9_R1.PacketPlayOutEntityDestroy;
import net.minecraft.server.v1_9_R1.PacketPlayOutEntityEquipment;
import net.minecraft.server.v1_9_R1.PacketPlayOutEntityHeadRotation;
import net.minecraft.server.v1_9_R1.PacketPlayOutEntityMetadata;
import net.minecraft.server.v1_9_R1.PacketPlayOutEntityTeleport;
import net.minecraft.server.v1_9_R1.PacketPlayOutNamedEntitySpawn;
import net.minecraft.server.v1_9_R1.PacketPlayOutPlayerInfo;
import net.minecraft.server.v1_9_R1.PacketPlayOutPlayerInfo.EnumPlayerInfoAction;
import net.minecraft.server.v1_9_R1.PacketPlayOutPlayerInfo.PlayerInfoData;
import net.minecraft.server.v1_9_R1.WorldSettings.EnumGamemode;
public class StateNPC
{
// CONSTANTS
protected static final double VISIBILITY_RANGE = 60d;
protected static final long TABLIST_REMOVE_DELAY_MS = 5000;
protected static final long RELATIVE_MOVE_TELEPORT_INTERVAL = 40;
// STATUS
protected transient String id;
protected transient int entityId;
protected transient GameProfile gameProfile;
protected transient Location location;
protected transient ItemStack itemInHand = null;
protected transient ItemStack itemInOffHand = null;
protected transient ItemStack[] armor = new ItemStack[4]; // 0: boots, 1: leggings, 2: chestplate, 3: helmet
protected transient boolean onFire = false;
protected transient boolean crouched = false;
protected transient boolean sprinting = false;
protected transient boolean isEating = false; // TODO npc api | implement these
protected transient boolean isDrinking = false;
protected transient boolean isBlocking = false;
protected transient boolean isInvisible = false; // TODO npc api | does this work?
protected transient boolean isGlowing = false;
protected transient boolean isFlyingWithElytra = false;
protected transient byte numberOfArrowsInBody = 0;
// PLAYERS
protected transient Set<Player> visibleTo;
// TEMP
protected transient int moveTeleportCounter = 0;
// CONSTRUCTOR
protected StateNPC(GameProfile gameProfile, Location location)
{
this.gameProfile = gameProfile;
this.location = location;
initialize();
}
protected void initialize()
{
this.entityId = getUnusedEntityId();
this.visibleTo = new HashSet<Player>();
}
protected void terminate()
{
sendRemoveToPlayer(getPlayersVisibleToArray());
this.visibleTo.clear();
}
public void despawn()
{
AnimulusAPI.getNPCManager().removeNPC(this);
terminate();
}
// GETTERS
public String getId()
{
return this.id;
}
public int getEntityId()
{
return this.entityId;
}
public Location getLocation()
{
return this.location.clone();
}
public double getEyeHeight()
{
if(this.crouched)
return 1.54;
return 1.62;
}
public Location getEyeLocation()
{
return this.location.clone().add(0, getEyeHeight(), 0);
}
public ItemStack getItemInHand()
{
return this.itemInHand;
}
public boolean isOnFire()
{
return this.onFire;
}
public boolean isCrouched()
{
return this.crouched;
}
public boolean isSprinting()
{
return this.sprinting;
}
public boolean isGlowing()
{
return this.isGlowing;
}
protected DataWatcher getMetadata()
{
DataWatcher metadata = new DataWatcher(null);
// http://wiki.vg/Entities#Entity_Metadata_Format
// base information
byte metadataBaseInfo = 0;
if(this.onFire)
metadataBaseInfo |= 0x01;
if(this.crouched)
metadataBaseInfo |= 0x02;
if(this.sprinting)
metadataBaseInfo |= 0x08;
if(this.isEating || this.isDrinking || this.isBlocking)
metadataBaseInfo |= 0x10;
if(this.isInvisible)
metadataBaseInfo |= 0x20;
if(this.isGlowing)
metadataBaseInfo |= 0x40;
if(this.isFlyingWithElytra)
metadataBaseInfo |= 0x80;
metadata.register(new DataWatcherObject<Byte>(0, DataWatcherRegistry.a), metadataBaseInfo);
// arrows in body
metadata.register(new DataWatcherObject<Byte>(9, DataWatcherRegistry.a), this.numberOfArrowsInBody);
// !!! seems to have changed to 10 in v1.9/v1.10
// skin parts
byte skinParts = 0b01111111; // all parts displayed (first bit is unused)
metadata.register(new DataWatcherObject<Byte>(13, DataWatcherRegistry.a), skinParts);
return metadata;
}
public Set<Player> getPlayersVisibleTo()
{
return new HashSet<Player>(this.visibleTo);
}
public boolean isVisibleTo(Player player)
{
return this.visibleTo.contains(player);
}
public boolean isVisibleToSomebody()
{
return !this.visibleTo.isEmpty();
}
public Player[] getPlayersVisibleToArray()
{
return this.visibleTo.toArray(new Player[this.visibleTo.size()]);
}
// SETTERS
public void setId(String id)
{
this.id = id;
}
public void setItemInHand(ItemStack itemStack)
{
this.itemInHand = itemStack;
sendEntityEquipmentChange(EnumItemSlot.MAINHAND, itemStack, getPlayersVisibleToArray());
}
public void setItemInOffHand(ItemStack itemStack)
{
this.itemInOffHand = itemStack;
sendEntityEquipmentChange(EnumItemSlot.OFFHAND, itemStack, getPlayersVisibleToArray());
}
public void setArmor(int slot, ItemStack itemStack)
{
this.armor[slot] = itemStack;
sendEntityEquipmentChange(getArmorItemSlot(slot), itemStack, getPlayersVisibleToArray());
}
public void setOnFire(boolean onFire)
{
if(this.onFire == onFire)
return;
this.onFire = onFire;
sendEntityMetadata(getPlayersVisibleToArray());
}
public void setCrouched(boolean crouched)
{
if(this.crouched == crouched)
return;
if(isSprinting())
throw new IllegalStateException("Can't crouch while sprinting");
this.crouched = crouched;
sendEntityMetadata(getPlayersVisibleToArray());
}
public void setSprinting(boolean sprinting)
{
if(this.sprinting == sprinting)
return;
if(isCrouched())
throw new IllegalStateException("Can't sprint while crouching");
this.sprinting = sprinting;
sendEntityMetadata(getPlayersVisibleToArray());
}
public void setGlowing(boolean glowing)
{
if(this.isGlowing == glowing)
return;
this.isGlowing = glowing;
sendEntityMetadata(getPlayersVisibleToArray());
}
public void setNumberOfArrowsInBody(byte numberOfArrowsInBody)
{
if(this.numberOfArrowsInBody == numberOfArrowsInBody)
return;
this.numberOfArrowsInBody = numberOfArrowsInBody;
sendEntityMetadata(getPlayersVisibleToArray());
}
// PLAYERS
protected void updateVisibleForPlayers()
{
for(Player p : Bukkit.getOnlinePlayers())
updateVisibilityForPlayer(p);
}
protected void updateVisibilityForPlayer(Player player)
{
if(player.getLocation().distanceSquared(getLocation()) < (VISIBILITY_RANGE * VISIBILITY_RANGE))
{
if(!isVisibleTo(player))
becomeVisibleFor(player);
}
else
{
if(isVisibleTo(player))
becomeInvisibleFor(player, true);
}
}
public void becomeVisibleFor(Player player)
{
this.visibleTo.add(player);
sendToPlayer(player);
}
public void becomeInvisibleFor(Player player, boolean sendPackets)
{
this.visibleTo.remove(player);
if(sendPackets)
sendRemoveToPlayer(player);
}
// INTERACTION
public void playerLeftClick(Player player)
{
}
public void playerRightClick(Player player)
{
}
// ACTION
public void swingArm()
{
sendAnimation(0, getPlayersVisibleToArray());
}
public void swingOffhandArm()
{
sendAnimation(3, getPlayersVisibleToArray());
}
// MOVEMENT
public void moveToNearby(Location target)
{
if((this.moveTeleportCounter++ % RELATIVE_MOVE_TELEPORT_INTERVAL) == 0)
{
teleport(target);
return;
}
sendRelativeMoveLook(target, getPlayersVisibleToArray());
this.location = target;
sendHeadRotation(getPlayersVisibleToArray());
}
public void teleport(Location target)
{
this.location = target;
// this sends despawn packets if the npc is too far away now
updateVisibleForPlayers();
sendTeleport(getPlayersVisibleToArray());
sendLookHeadRotation(getPlayersVisibleToArray());
}
public void lookAt(Location lookAt)
{
this.location = LocationUtil.lookAt(this.location, lookAt);
sendLookHeadRotation(getPlayersVisibleToArray());
}
public boolean canStandAt(Location location)
{
if(location.getBlock().getType().isSolid())
return false;
if(location.clone().add(0, 1, 0).getBlock().getType().isSolid())
return false;
if(!location.clone().add(0, -1, 0).getBlock().getType().isSolid())
return false;
return true;
}
// TICKING
protected void tick(int tick)
{
}
// PACKETS
protected void sendToPlayer(Player... players)
{
sendPlayerInfo(players);
sendEntitySpawn(players);
sendHeadRotation(players);
sendEntityMetadata(players);
sendEntityEquipment(players);
sendPlayerInfoRemove(players);
}
protected void sendEntityEquipment(Player... players)
{
for(int slot = 0; slot < 4; slot++)
sendEntityEquipmentChange(getArmorItemSlot(slot), this.armor[slot], players);
sendEntityEquipmentChange(EnumItemSlot.MAINHAND, this.itemInHand, players);
sendEntityEquipmentChange(EnumItemSlot.OFFHAND, this.itemInOffHand, players);
}
protected void sendRemoveToPlayer(Player... players)
{
sendEntityDespawn(players);
}
// PLAYER INFO
protected PlayerInfoData getPlayerInfoData(PacketPlayOutPlayerInfo packetPlayOutPlayerInfo)
{
return packetPlayOutPlayerInfo.new PlayerInfoData(this.gameProfile, 0, EnumGamemode.NOT_SET,
CraftChatMessage.fromString("")[0]);
}
protected void sendPlayerInfo(Player... players)
{
PacketPlayOutPlayerInfo packet = new PacketPlayOutPlayerInfo();
ReflectionUtil.setDeclaredFieldValue(packet, "a", EnumPlayerInfoAction.ADD_PLAYER);
@SuppressWarnings("unchecked")
List<PlayerInfoData> b = (List<PlayerInfoData>) ReflectionUtil.getDeclaredFieldValue(packet, "b");
b.add(getPlayerInfoData(packet));
for(Player p : players)
((CraftPlayer) p).getHandle().playerConnection.sendPacket(packet);
}
protected void sendPlayerInfoRemove(Player... players)
{
PacketPlayOutPlayerInfo packet = new PacketPlayOutPlayerInfo();
ReflectionUtil.setDeclaredFieldValue(packet, "a", EnumPlayerInfoAction.REMOVE_PLAYER);
@SuppressWarnings("unchecked")
List<PlayerInfoData> b = (List<PlayerInfoData>) ReflectionUtil.getDeclaredFieldValue(packet, "b");
b.add(getPlayerInfoData(packet));
ThreadUtil.runDelayed(() ->
{
for(Player p : players)
((CraftPlayer) p).getHandle().playerConnection.sendPacket(packet);
}, TABLIST_REMOVE_DELAY_MS);
}
// ENTITY SPAWN
protected void sendEntitySpawn(Player... players)
{
PacketPlayOutNamedEntitySpawn packet = new PacketPlayOutNamedEntitySpawn();
ReflectionUtil.setDeclaredFieldValue(packet, "a", this.entityId);
ReflectionUtil.setDeclaredFieldValue(packet, "b", this.gameProfile.getId());
ReflectionUtil.setDeclaredFieldValue(packet, "c", this.location.getX());
ReflectionUtil.setDeclaredFieldValue(packet, "d", this.location.getY());
ReflectionUtil.setDeclaredFieldValue(packet, "e", this.location.getZ());
ReflectionUtil.setDeclaredFieldValue(packet, "f", PacketUtil.toPacketAngle(this.location.getYaw()));
ReflectionUtil.setDeclaredFieldValue(packet, "g", PacketUtil.toPacketAngle(this.location.getPitch()));
ReflectionUtil.setDeclaredFieldValue(packet, "h", getMetadata());
for(Player p : players)
((CraftPlayer) p).getHandle().playerConnection.sendPacket(packet);
}
// ENTITY DESPAWN
protected void sendEntityDespawn(Player... players)
{
PacketPlayOutEntityDestroy packet = new PacketPlayOutEntityDestroy();
ReflectionUtil.setDeclaredFieldValue(packet, "a", new int[] { this.entityId });
for(Player p : players)
((CraftPlayer) p).getHandle().playerConnection.sendPacket(packet);
}
// ENTITY CHANGE
protected void sendEntityEquipmentChange(EnumItemSlot slot, ItemStack itemStack, Player... players)
{
PacketPlayOutEntityEquipment packet = new PacketPlayOutEntityEquipment(this.entityId, slot,
CraftItemStack.asNMSCopy(itemStack));
for(Player p : players)
((CraftPlayer) p).getHandle().playerConnection.sendPacket(packet);
}
protected void sendEntityMetadata(Player... players)
{
// the boolean determines the metadata sent to the player;
// true = all metadata
// false = the dirty metadata
PacketPlayOutEntityMetadata packet = new PacketPlayOutEntityMetadata(this.entityId, getMetadata(), true);
for(Player p : players)
((CraftPlayer) p).getHandle().playerConnection.sendPacket(packet);
}
// MOVEMENT
protected void sendRelativeMoveLook(Location target, Player... players)
{
double dX = target.getX() - this.location.getX();
double dY = target.getY() - this.location.getY();
double dZ = target.getZ() - this.location.getZ();
// @formatter:off
PacketPlayOutRelEntityMoveLook packet = new PacketPlayOutRelEntityMoveLook(
this.entityId,
PacketUtil.toPacketDistance(dX),
PacketUtil.toPacketDistance(dY),
PacketUtil.toPacketDistance(dZ),
PacketUtil.toPacketAngle(target.getYaw()),
PacketUtil.toPacketAngle(target.getPitch()),
true);
// @formatter:on
for(Player p : players)
((CraftPlayer) p).getHandle().playerConnection.sendPacket(packet);
}
protected void sendTeleport(Player... players)
{
PacketPlayOutEntityTeleport packet = new PacketPlayOutEntityTeleport();
ReflectionUtil.setDeclaredFieldValue(packet, "a", this.entityId);
ReflectionUtil.setDeclaredFieldValue(packet, "b", this.location.getX());
ReflectionUtil.setDeclaredFieldValue(packet, "c", this.location.getY());
ReflectionUtil.setDeclaredFieldValue(packet, "d", this.location.getZ());
ReflectionUtil.setDeclaredFieldValue(packet, "e", PacketUtil.toPacketAngle(this.location.getYaw()));
ReflectionUtil.setDeclaredFieldValue(packet, "f", PacketUtil.toPacketAngle(this.location.getPitch()));
ReflectionUtil.setDeclaredFieldValue(packet, "g", true);
for(Player p : players)
((CraftPlayer) p).getHandle().playerConnection.sendPacket(packet);
}
protected void sendLookHeadRotation(Player... players)
{
sendLook(players);
sendHeadRotation(players);
}
protected void sendLook(Player... players)
{
PacketPlayOutEntityLook packet = new PacketPlayOutEntityLook(this.entityId,
PacketUtil.toPacketAngle(this.location.getYaw()), PacketUtil.toPacketAngle(this.location.getPitch()), true);
for(Player p : players)
((CraftPlayer) p).getHandle().playerConnection.sendPacket(packet);
}
protected void sendHeadRotation(Player... players)
{
PacketPlayOutEntityHeadRotation packet = new PacketPlayOutEntityHeadRotation();
ReflectionUtil.setDeclaredFieldValue(packet, "a", this.entityId);
ReflectionUtil.setDeclaredFieldValue(packet, "b", PacketUtil.toPacketAngle(this.location.getYaw()));
for(Player p : players)
((CraftPlayer) p).getHandle().playerConnection.sendPacket(packet);
}
// ACTION
protected void sendAnimation(int animationId, Player... players)
{
PacketPlayOutAnimation packet = new PacketPlayOutAnimation();
ReflectionUtil.setDeclaredFieldValue(packet, "a", this.entityId);
ReflectionUtil.setDeclaredFieldValue(packet, "b", animationId);
for(Player p : players)
((CraftPlayer) p).getHandle().playerConnection.sendPacket(packet);
}
// UTIL
protected static int getUnusedEntityId()
{
// the entityId of a new (net.minecraft.server.)Entity is set like this:
// this.id = (entityCount++);
// since the ++ is after the variable, the value of id is set to the current value of entityCount and
// entity count is increased by one for the next entity
// this means returning the entityCount as a new entityId is safe, if we increase the variable before returning
int entityCount = (int) ReflectionUtil.getDeclaredFieldValue(Entity.class, null, "entityCount");
ReflectionUtil.setDeclaredFieldValue(Entity.class, null, "entityCount", entityCount + 1);
return entityCount;
}
protected static EnumItemSlot getArmorItemSlot(int slot)
{
if(slot == 0)
return EnumItemSlot.FEET;
else if(slot == 1)
return EnumItemSlot.LEGS;
else if(slot == 2)
return EnumItemSlot.CHEST;
else if(slot == 3)
return EnumItemSlot.HEAD;
return null;
}
}
|
package de.gruphi.tdwtf_reader.db;
import java.io.File;
import java.time.LocalDate;
import java.util.Set;
import com.sleepycat.je.DatabaseException;
import com.sleepycat.je.Environment;
import com.sleepycat.je.EnvironmentConfig;
import com.sleepycat.persist.EntityStore;
import com.sleepycat.persist.PrimaryIndex;
import com.sleepycat.persist.StoreConfig;
import com.sleepycat.persist.model.AnnotationModel;
import com.sleepycat.persist.model.EntityModel;
import de.gruphi.tdwtf_reader.Constants;
import de.gruphi.tdwtf_reader.entities.Article;
import de.gruphi.tdwtf_reader.entities.MonthlyArticles;
public class DataStore implements AutoCloseable {
private File dbPath = new File("tdwtf-db");
private Environment env;
private EntityStore articleStore;
public DataStore() throws DatabaseException {
startup();
}
private void startup() throws DatabaseException {
// long start = System.currentTimeMillis();
EnvironmentConfig envcfg = new EnvironmentConfig();
envcfg.setAllowCreate(true);
envcfg.setReadOnly(false);
env = new Environment(dbPath, envcfg);
StoreConfig stcfg = new StoreConfig();
stcfg.setAllowCreate(true);
stcfg.setReadOnly(false);
EntityModel model = new AnnotationModel();
model.registerClass(LocalDateProxy.class);
model.registerClass(URLProxy.class);
stcfg.setModel(model);
articleStore = new EntityStore(env, "articlestore", stcfg);
// System.out.println("boottime:" + (System.currentTimeMillis() - start));
}
public void insertArticle(Article article) throws DatabaseException {
PrimaryIndex<String, MonthlyArticles> pIndex = articleStore.getPrimaryIndex(String.class,
MonthlyArticles.class);
LocalDate monthDate = article.getPublished().withDayOfMonth(1);
if (!pIndex.contains(monthDate.toString())) {
Constants.logger.info("Create monthly articles set: " + monthDate);
MonthlyArticles newEntity = new MonthlyArticles();
newEntity.setDate(monthDate);
pIndex.put(newEntity);
}
MonthlyArticles entity = pIndex.get(monthDate.toString());
Set<Article> articles = entity.getArticles();
articles.add(article);
pIndex.put(entity);
}
public void updateArticle(Article article) throws DatabaseException {
PrimaryIndex<String, MonthlyArticles> pIndex = articleStore.getPrimaryIndex(String.class,
MonthlyArticles.class);
MonthlyArticles entity = pIndex.get(article.getPublished().withDayOfMonth(1).toString());
Set<Article> articles = entity.getArticles();
articles.remove(article);
articles.add(article);
pIndex.put(entity);
}
public MonthlyArticles getArticles(int year, int month) throws DatabaseException {
return getArticles(LocalDate.of(year, month, 1));
}
public MonthlyArticles getArticles(LocalDate ld) throws DatabaseException {
return articleStore.getPrimaryIndex(String.class, MonthlyArticles.class).get(ld.toString());
}
private void shutdown() throws DatabaseException {
articleStore.close();
env.close();
}
@Override
public void close(){
shutdown();
}
}
|
package com.netto.server;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.log4j.Logger;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import com.netto.filter.InvokeMethodFilter;
import com.netto.server.bean.ServiceBean;
import com.netto.server.handler.NettyServerHandler;
import com.netto.server.handler.NettyServerHandler.NettoServiceBean;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
public class NettyServer implements InitializingBean, ApplicationContextAware {
private static Logger logger = Logger.getLogger(NettyServer.class);
private int port = 12345;
private Map<String, Object> refBeans;
private Map<String, NettoServiceBean> serviceBeans;
private List<InvokeMethodFilter> filters;
private ApplicationContext applicationContext;
public NettyServer() {
}
public NettyServer(int port) {
this.port = port;
}
public List<InvokeMethodFilter> getFilters() {
return filters;
}
public void setFilters(List<InvokeMethodFilter> filters) {
this.filters = filters;
}
public void setRefBeans(Map<String, Object> refBeans) {
this.refBeans = refBeans;
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
public void afterPropertiesSet() throws Exception {
this.serviceBeans = new HashMap<String, NettoServiceBean>();
if (this.refBeans == null) {
Map<String, ServiceBean> temps = this.applicationContext.getBeansOfType(ServiceBean.class);
for (String key : temps.keySet()) {
ServiceBean bean = temps.get(key);
NettoServiceBean factoryBean = new NettoServiceBean(bean,
this.applicationContext.getBean(bean.getRef()));
this.serviceBeans.put(bean.getRef(), factoryBean);
}
} else {
for (String key : this.refBeans.keySet()) {
ServiceBean bean = new ServiceBean();
bean.setRef(key);
NettoServiceBean factoryBean = new NettoServiceBean(bean, this.refBeans.get(key));
this.serviceBeans.put(key, factoryBean);
}
}
this.run();
}
private void run() throws Exception {
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
ServerBootstrap b = new ServerBootstrap();
b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
.option(ChannelOption.SO_BACKLOG, 1024).childHandler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline p = ch.pipeline();
p.addLast(new NettyServerHandler(serviceBeans, filters));
}
});
// Bind and start to accept incoming connections.
ChannelFuture f = b.bind(this.port).sync();
logger.info("server bind port:" + this.port);
// Wait until the server socket is closed.
f.channel().closeFuture().sync();
} finally {
// Shut down all event loops to terminate all threads.
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
}
|
package org.intermine.api.profile;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;
import org.apache.commons.collections.map.ListOrderedMap;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.intermine.api.bag.ClassKeysNotFoundException;
import org.intermine.api.bag.SharedBagManager;
import org.intermine.api.bag.UnknownBagTypeException;
import org.intermine.api.config.ClassKeyHelper;
import org.intermine.api.search.CreationEvent;
import org.intermine.api.search.DeletionEvent;
import org.intermine.api.search.SearchRepository;
import org.intermine.api.search.UserRepository;
import org.intermine.api.search.WebSearchable;
import org.intermine.api.tag.TagTypes;
import org.intermine.api.template.ApiTemplate;
import org.intermine.api.tracker.TrackerDelegate;
import org.intermine.api.util.NameUtil;
import org.intermine.metadata.FieldDescriptor;
import org.intermine.model.userprofile.Tag;
import org.intermine.model.userprofile.UserProfile;
import org.intermine.objectstore.ObjectStore;
import org.intermine.objectstore.ObjectStoreException;
import org.intermine.objectstore.ObjectStoreWriter;
import org.intermine.pathquery.PathQuery;
/**
* Class to represent a user of the webapp
*
* The profile is responsible for informing its search repository of all web-searchable objects
* created or deleted on its watch.
*
* @author Mark Woodbridge
* @author Thomas Riley
* @author Daniela Butano
*/
public class Profile
{
private static final Logger LOG = Logger.getLogger(Profile.class);
/** Empty typed map holding no saved queries - useful when creating profiles. **/
public static final Map<String, SavedQuery> NO_QUERIES = Collections.emptyMap();
/** Empty typed map holding no bags - useful when creating profiles. **/
public static final Map<String, InterMineBag> NO_BAGS = Collections.emptyMap();
/** Empty typed map holding no templates - useful when creating profiles. **/
public static final Map<String, ApiTemplate> NO_TEMPLATES = Collections.emptyMap();
protected ProfileManager manager;
protected String username;
protected Integer userId;
protected String password;
protected boolean isSuperUser;
protected Map<String, SavedQuery> savedQueries = new TreeMap<String, SavedQuery>();
protected Map<String, InterMineBag> savedBags
= Collections.synchronizedMap(new TreeMap<String, InterMineBag>());
protected Map<String, ApiTemplate> savedTemplates = new TreeMap<String, ApiTemplate>();
protected Map<String, InvalidBag> savedInvalidBags = new TreeMap<String, InvalidBag>();
// was ListOrderedMap() - but that is the same as a LinkedHashMap.
protected boolean savingDisabled;
private SearchRepository searchRepository;
private String token;
private Map<String, String> preferences;
@SuppressWarnings("unchecked")
protected Map<String, SavedQuery> queryHistory = new ListOrderedMap();
/**
* True if this account is purely local. False if it was created
* in reference to another authenticator, such as an OpenID provider.
*/
private final boolean isLocal;
/**
* Construct a Profile
* @param manager the manager for this profile
* @param username the username for this profile
* @param userId the id of this user
* @param password the password for this profile
* @param savedQueries the saved queries for this profile
* @param savedBags the saved bags for this profile
* @param savedTemplates the saved templates for this profile
* @param token the token to use as an API key
* @param isLocal true if the account is local
* @param isSuperUser true if the user is a super user
*/
public Profile(ProfileManager manager, String username, Integer userId, String password,
Map<String, SavedQuery> savedQueries, Map<String, InterMineBag> savedBags,
Map<String, ApiTemplate> savedTemplates, String token, boolean isLocal,
boolean isSuperUser) {
this.manager = manager;
this.username = username;
this.userId = userId;
this.password = password;
this.isLocal = isLocal;
this.isSuperUser = isSuperUser;
if (savedQueries != null) {
this.savedQueries.putAll(savedQueries);
}
if (savedBags != null) {
this.savedBags.putAll(savedBags);
}
if (savedTemplates != null) {
this.savedTemplates.putAll(savedTemplates);
}
searchRepository = new UserRepository(this);
this.token = token;
if (this.userId != null) {
// preferences backed by DB.
this.preferences = manager.getPreferences(this);
} else {
// preferences just stored in memory.
this.preferences = new HashMap<String, String>();
}
}
/**
* Construct a Profile
* @param manager the manager for this profile
* @param username the username for this profile
* @param userId the id of this user
* @param password the password for this profile
* @param savedQueries the saved queries for this profile
* @param savedBags the saved bags for this profile
* @param savedInvalidBags the saved bags which type doesn't match with the model
* @param savedTemplates the saved templates for this profile
* @param token The token to use as an API key
* @param isLocal true if the account is local
* @param isSuperUser the flag identifying the super user
*/
public Profile(ProfileManager manager, String username, Integer userId, String password,
Map<String, SavedQuery> savedQueries, Map<String, InterMineBag> savedBags,
Map<String, InterMineBag> savedInvalidBags,
Map<String, ApiTemplate> savedTemplates, String token, boolean isLocal,
boolean isSuperUser) {
this(manager, username, userId, password, savedQueries, savedBags, savedTemplates, token,
isLocal, isSuperUser);
for (Entry<String, InterMineBag> pair: savedInvalidBags.entrySet()) {
this.savedInvalidBags.put(pair.getKey(), pair.getValue().invalidate());
}
}
/**
* Construct a Profile
* @param manager the manager for this profile
* @param username the username for this profile
* @param userId the id of this user
* @param password the password for this profile
* @param savedQueries the saved queries for this profile
* @param bagset a bagset (=valid and invalid bags) for this profile
* @param savedTemplates the saved templates for this profile
* @param token The token to use as an API key
* @param isLocal true if the account is local
* @param isSuperUser the flag identifying the super user
*/
public Profile(ProfileManager manager, String username, Integer userId, String password,
Map<String, SavedQuery> savedQueries, BagSet bagset,
Map<String, ApiTemplate> savedTemplates, String token, boolean isLocal,
boolean isSuperUser) {
this(manager, username, userId, password, savedQueries, bagset.getBags(), savedTemplates,
token, isLocal, isSuperUser);
this.savedInvalidBags.putAll(bagset.getInvalidBags());
}
/**
* Construct a profile without an API key
* @param manager the manager for this profile
* @param username the username for this profile
* @param userId the id of this user
* @param password the password for this profile
* @param savedQueries the saved queries for this profile
* @param savedBags the saved bags for this profile
* @param savedTemplates the saved templates for this profile
* @param isLocal true if the account is local
* @param isSuperUser the flag identifying the super user
*/
public Profile(ProfileManager manager, String username, Integer userId, String password,
Map<String, SavedQuery> savedQueries, Map<String, InterMineBag> savedBags,
Map<String, ApiTemplate> savedTemplates, boolean isLocal, boolean isSuperUser) {
this(manager, username, userId, password, savedQueries, savedBags, savedTemplates,
null, isLocal, isSuperUser);
}
/**
* Return the ProfileManager that was passed to the constructor.
* @return the ProfileManager
*/
public ProfileManager getProfileManager() {
return manager;
}
/**
* Get the value of username
* @return the value of username
*/
public String getUsername() {
return username;
}
/**
* Get this user's preferred email address.
* @return This user's email address.
*/
public String getEmailAddress() {
if (prefers(UserPreferences.EMAIL)) {
return preferences.get(UserPreferences.EMAIL);
}
return getUsername();
}
/**
* Return a first part of the username before the "@" sign (used in metabolicMine)
* @author radek
*
* @return String
*/
public String getName() {
// AKA is my name for myself (not public).
if (prefers(UserPreferences.AKA)) {
return getPreferences().get(UserPreferences.AKA);
}
// ALIAS is public (and globally unique) name
if (prefers(UserPreferences.ALIAS)) {
return getPreferences().get(UserPreferences.ALIAS);
}
// Else try and work out something reasonable.
int atPos = username.indexOf("@");
if (atPos > 0) {
return username.substring(0, atPos);
} else {
return username;
}
}
/**
* Return true if and only if the user is logged is (and the Profile will be written to the
* userprofile).
* @return Return true if logged in
*/
public boolean isLoggedIn() {
return getUsername() != null;
}
/**
* Return true if and only if the user logged is superuser
* @return Return true if superuser
*/
public boolean isSuperuser() {
return isSuperUser;
}
/**
* Alias of isSuperUser() for jsp purposes.
* @return The same value as isSuperUser().
*/
public boolean getSuperuser() {
return isSuperuser();
}
/**
* Set the superuser flag and store it in userprofile database
* @param isSuperUser if true the profile is set as superuser
* @throws ObjectStoreException if an error occurs during storage of the object
*/
public void setSuperuser(boolean isSuperUser) throws ObjectStoreException {
ObjectStoreWriter uosw = manager.getProfileObjectStoreWriter();
UserProfile p = (UserProfile) uosw.getObjectStore().getObjectById(userId,
UserProfile.class);
p.setSuperuser(isSuperUser);
uosw.store(p);
this.isSuperUser = isSuperUser;
}
/**
* Get the value of userId
* @return an Integer
*/
public Integer getUserId() {
return userId;
}
/**
* Set the userId
*
* @param userId an Integer
*/
public void setUserId(Integer userId) {
Integer oldId = getUserId();
this.userId = userId;
if (this.userId != null && !this.userId.equals(oldId)) { // Need to update the preferences
Map<String, String> oldPrefs = preferences;
this.preferences = manager.getPreferences(this);
preferences.putAll(oldPrefs);
oldPrefs.clear(); // Delete them now that they are copied over.
}
}
/**
* Get the value of password
* @return the value of password
*/
public String getPassword() {
return password;
}
/**
* Disable saving until enableSaving() is called. This is called before many templates or
* queries need to be saved or deleted because each call to ProfileManager.saveProfile() is
* slow.
*/
public void disableSaving() {
savingDisabled = true;
}
/**
* Re-enable saving when saveTemplate(), deleteQuery() etc. are called. Also calls
* ProfileManager.saveProfile() to write this Profile to the database and rebuilds the
* template description index.
*/
public void enableSaving() {
savingDisabled = false;
if (manager != null) {
manager.saveProfile(this);
}
// Why were these calls here in the first place?
//reindex(TagTypes.TEMPLATE);
//reindex(TagTypes.BAG);
}
/**
* Get the users saved templates
* @return saved templates
*/
public synchronized Map<String, ApiTemplate> getSavedTemplates() {
return Collections.unmodifiableMap(savedTemplates);
}
/**
* Save a template
* @param name the template name
* @param template the template
* @throws BadTemplateException if the template name is invalid.
*/
public void saveTemplate(String name, ApiTemplate template) throws BadTemplateException {
if (!NameUtil.isValidName(template.getName())) {
throw new BadTemplateException("Invalid name.");
}
savedTemplates.put(name, template);
if (manager != null && !savingDisabled) {
manager.saveProfile(this);
}
searchRepository.receiveEvent(new CreationEvent(template));
}
/**
* get a template
* @param name the template
* @return template
*/
public ApiTemplate getTemplate(String name) {
return savedTemplates.get(name);
}
/**
* Delete a template and its tags, rename the template tracks adding the prefix "deleted_"
* to the previous name. If trackerDelegate is null, the template tracks are not renamed
* @param name the template name
* @param trackerDelegate used to rename the template tracks.
* @param deleteTracks true if we want to delete the tracks associated to the template.
* Actually the tracks have never been deleted but only renamed
*/
public void deleteTemplate(String name, TrackerDelegate trackerDelegate,
boolean deleteTracks) {
ApiTemplate template = savedTemplates.get(name);
if (template == null) {
LOG.warn("Attempt to delete non-existant template: " + name);
} else {
savedTemplates.remove(name);
if (manager != null) {
if (!savingDisabled) {
manager.saveProfile(this);
}
}
searchRepository.receiveEvent(new DeletionEvent(template));
TagManager tagManager = getTagManager();
tagManager.deleteObjectTags(name, TagTypes.TEMPLATE, username);
if (trackerDelegate != null && deleteTracks) {
trackerDelegate.updateTemplateName(name, "deleted_" + name);
}
}
}
/**
* Get the value of savedQueries
* @return the value of savedQueries
*/
public Map<String, SavedQuery> getSavedQueries() {
return Collections.unmodifiableMap(savedQueries);
}
/**
* Save or update a query.
*
* If a query with the given name exists in this profile, that query will be overwritten.
*
* @param name the query name
* @param query the query
*/
public void saveQuery(String name, SavedQuery query) {
savedQueries.put(name, query);
if (manager != null && !savingDisabled) {
manager.saveProfile(this);
}
}
/**
* Save the map of queries as given to the user's profile, avoiding all possible name
* collisions. This method will not overwrite any existing user data.
*
* @param toSave The queries to save.
* @return successes The queries as they were saved.
*/
public Map<String, String> saveQueries(Map<? extends String, ? extends PathQuery> toSave) {
Map<String, String> successes = new HashMap<String, String>();
Date now = new Date();
for (Entry<? extends String, ? extends PathQuery> pair: toSave.entrySet()) {
String name = pair.getKey();
int c = 1;
while (savedQueries.containsKey(name)) {
name = pair.getKey() + "_" + c++;
}
SavedQuery sq = new SavedQuery(name, now, pair.getValue());
savedQueries.put(name, sq);
successes.put(pair.getKey(), name);
}
try {
if (manager != null && !savingDisabled) {
manager.saveProfile(this);
}
} catch (Exception e) {
// revert all changes.
savedQueries.entrySet().removeAll(successes.keySet());
try {
manager.saveProfile(this);
} catch (Exception e2) {
// Ignore.
}
throw new RuntimeException("Could not save queries.", e);
}
return successes;
}
/**
* Delete a query
* @param name the query name
*/
public void deleteQuery(String name) {
savedQueries.remove(name);
if (manager != null && !savingDisabled) {
manager.saveProfile(this);
}
}
/**
* Get the session query history.
* @return map from query name to SavedQuery
*/
public Map<String, SavedQuery> getHistory() {
return Collections.unmodifiableMap(queryHistory);
}
/**
* Save a query to the query history.
* @param query the SavedQuery to save to the history
*/
public void saveHistory(SavedQuery query) {
queryHistory.put(query.getName(), query);
}
/**
* Remove an item from the query history.
* @param name the of the SavedQuery from the history
*/
public void deleteHistory(String name) {
queryHistory.remove(name);
}
/**
* Rename an item in the history.
* @param oldName the name of the old item
* @param newName the new name
*/
public void renameHistory(String oldName, String newName) {
SavedQuery q = queryHistory.get(oldName);
if (q == null) {
throw new IllegalArgumentException("No query named " + oldName);
}
if (StringUtils.isBlank(newName)) {
throw new IllegalArgumentException("new name must not be blank");
}
if (queryHistory.containsKey(newName)) {
throw new IllegalArgumentException("there is already a query named " + newName);
}
q = new SavedQuery(newName, q.getDateCreated(), q.getPathQuery());
@SuppressWarnings("unchecked")
// Rebuild history to preserve iteration order.
Map<String, SavedQuery> newHistory = new ListOrderedMap();
for (Entry<String, SavedQuery> oldEntry: queryHistory.entrySet()) {
if (oldName.equals(oldEntry.getKey())) {
newHistory.put(newName, q);
} else {
newHistory.put(oldEntry.getKey(), oldEntry.getValue());
}
}
queryHistory = newHistory;
}
/**
* Get the value of savedBags
* @return the value of savedBags
*/
public synchronized Map<String, InterMineBag> getSavedBags() {
return Collections.unmodifiableMap(savedBags);
}
/**
* @return the invalid bags for this profile.
*/
public synchronized Map<String, InvalidBag> getInvalidBags() {
return Collections.unmodifiableMap(this.savedInvalidBags);
}
/**
* Fix this bag by changing its type
* @param name the invalid bag name
* @param newType The new type of this list
* @throws UnknownBagTypeException If the new type is not in the current model.
* @throws ObjectStoreException If there is a problem saving state to the DB.
*/
public synchronized void fixInvalidBag(String name, String newType)
throws UnknownBagTypeException, ObjectStoreException {
InvalidBag invb = savedInvalidBags.get(name);
InterMineBag imb = invb.amendTo(newType);
savedInvalidBags.remove(name);
saveBag(name, imb);
}
/**
* Get all bags associated with this profile, both valid and invalid.
*
* @return a map from name to bag.
*/
public synchronized Map<String, StorableBag> getAllBags() {
Map<String, StorableBag> ret = new HashMap<String, StorableBag>();
ret.putAll(savedBags);
ret.putAll(savedInvalidBags);
return Collections.unmodifiableMap(ret);
}
/**
* Get the saved bags in a map of "status key" => map of lists
* @return the map from status to a map containing bag name and bag
*/
public Map<String, Map<String, InterMineBag>> getSavedBagsByStatus() {
Map<String, Map<String, InterMineBag>> result =
new LinkedHashMap<String, Map<String, InterMineBag>>();
// maintain order on the JSP page
result.put("NOT_CURRENT", new HashMap<String, InterMineBag>());
result.put("TO_UPGRADE", new HashMap<String, InterMineBag>());
result.put("CURRENT", new HashMap<String, InterMineBag>());
result.put("UPGRADING", new HashMap<String, InterMineBag>());
for (InterMineBag bag : savedBags.values()) {
String state = bag.getState();
// XXX: this can go pear shaped if new states are introduced
Map<String, InterMineBag> stateMap = result.get(state);
stateMap.put(bag.getName(), bag);
}
return result;
}
/**
* Get the value of savedBags current
* @return the value of savedBags
*/
public Map<String, InterMineBag> getCurrentSavedBags() {
Map<String, InterMineBag> clone = new HashMap<String, InterMineBag>();
clone.putAll(savedBags);
for (InterMineBag bag : savedBags.values()) {
if (!bag.isCurrent()) {
clone.remove(bag.getName());
}
}
return clone;
}
/**
* Stores a new bag in the profile. Note that bags are always present in the user profile
* database, so this just adds the bag to the in-memory list of this profile.
*
* @param bag the InterMineBag object
*/
public void saveBag(InterMineBag bag) {
if (bag == null) {
throw new IllegalArgumentException("bag may not be null");
}
saveBag(bag.getName(), bag);
}
/**
* Stores a new bag in the profile. Note that bags are always present in the user profile
* database, so this just adds the bag to the in-memory list of this profile.
*
* @param name the name of the bag
* @param bag the InterMineBag object
*/
public void saveBag(String name, InterMineBag bag) {
if (StringUtils.isBlank(name)) {
throw new RuntimeException("No name specified for the list to save.");
}
savedBags.put(name, bag);
searchRepository.receiveEvent(new CreationEvent(bag));
}
/**
* Create a bag and save it to the userprofile database.
*
* @param name the bag name
* @param type the bag type
* @param description the bag description
* @param classKeys the classKeys used to obtain the primary identifier field
* @return the new bag
* @throws UnknownBagTypeException if the bag type is wrong
* @throws ClassKeysNotFoundException if the classKeys is empty
* @throws ObjectStoreException if something goes wrong
*/
public InterMineBag createBag(String name, String type, String description,
Map<String, List<FieldDescriptor>> classKeys)
throws UnknownBagTypeException, ClassKeysNotFoundException, ObjectStoreException {
ObjectStore os = manager.getProductionObjectStore();
ObjectStoreWriter uosw = manager.getProfileObjectStoreWriter();
List<String> keyFieldNames = ClassKeyHelper.getKeyFieldNames(
classKeys, type);
InterMineBag bag = new InterMineBag(name, type, description, new Date(),
BagState.CURRENT, os, userId, uosw, keyFieldNames);
saveBag(name, bag);
return bag;
}
/**
* Delete a bag from the user account, if user is logged in also deletes from the userprofile
* database.
* If there is no such bag associated with the account, no action is performed.
* @param name the bag name
* @throws ObjectStoreException if problems deleting bag
*/
public void deleteBag(String name) throws ObjectStoreException {
if (!savedBags.containsKey(name) && !savedInvalidBags.containsKey(name)) {
throw new BagDoesNotExistException(name + " not found");
}
StorableBag bagToDelete;
if (savedBags.containsKey(name)) {
bagToDelete = savedBags.get(name);
savedBags.remove(name);
} else {
bagToDelete = savedInvalidBags.get(name);
savedInvalidBags.remove(name);
}
if (isLoggedIn()) {
getSharedBagManager().unshareBagWithAllUsers(bagToDelete);
bagToDelete.delete();
} else { //refresh the search repository
bagToDelete.delete();
}
TagManager tagManager = getTagManager();
tagManager.deleteObjectTags(name, TagTypes.BAG, username);
}
/**
* Update the type of bag.
* If there is no such bag associated with the account, no action is performed.
* @param name the bag name
* @param newType the type to set
* @throws UnknownBagTypeException if the bag type is wrong
* @throws ObjectStoreException if problems storing bag
*/
public void updateBagType(String name, String newType)
throws UnknownBagTypeException, ObjectStoreException {
if (!savedBags.containsKey(name) && !savedInvalidBags.containsKey(name)) {
throw new BagDoesNotExistException(name + " not found");
}
if (savedBags.containsKey(name)) {
InterMineBag bagToUpdate = savedBags.get(name);
if (isLoggedIn()) {
bagToUpdate.setType(newType);
}
} else {
InterMineBag recovered = savedInvalidBags.get(name).amendTo(newType);
savedInvalidBags.remove(name);
saveBag(recovered.getName(), recovered);
}
}
/**
* Rename an existing bag, throw exceptions when bag doesn't exist of if new name already
* exists. Moves tags from old bag to new bag.
* @param oldName the bag to rename
* @param newName new name for the bag
* @throws ObjectStoreException if problems storing
*/
public void renameBag(String oldName, String newName) throws ObjectStoreException {
if (!getAllBags().containsKey(oldName)) {
throw new BagDoesNotExistException("Attempting to rename " + oldName);
}
if (getAllBags().containsKey(newName)) {
throw new ProfileAlreadyExistsException("Attempting to rename a bag to a new name that"
+ " already exists: " + newName);
}
if (savedBags.containsKey(oldName)) {
InterMineBag bag = savedBags.get(oldName);
savedBags.remove(oldName);
bag.setName(newName);
saveBag(newName, bag);
} else {
InvalidBag bag = savedInvalidBags.get(oldName);
InvalidBag newBag = bag.rename(newName);
savedInvalidBags.remove(oldName);
savedInvalidBags.put(newName, newBag);
}
moveTagsToNewObject(oldName, newName, TagTypes.BAG);
}
/**
* Update an existing template, throw exceptions when template doesn't exist.
* Moves tags from old template to new template.
* @param oldName the template to rename
* @param template the new template
* @throws ObjectStoreException if problems storing
* @throws BadTemplateException if bad template
*/
public void updateTemplate(String oldName, ApiTemplate template)
throws ObjectStoreException, BadTemplateException {
if (oldName == null) {
throw new IllegalArgumentException("oldName may not be null");
}
ApiTemplate old = savedTemplates.get(oldName);
if (old == null) {
throw new IllegalArgumentException("Attempting to rename a template that doesn't"
+ " exist: " + oldName);
}
ApiTemplate oldTemplate = savedTemplates.remove(oldName);
try {
saveTemplate(template.getName(), template);
} catch (BadTemplateException bte) {
savedTemplates.put(oldName, oldTemplate);
throw bte;
}
if (!oldName.equals(template.getName())) {
searchRepository.receiveEvent(new DeletionEvent(old));
moveTagsToNewObject(oldName, template.getName(), TagTypes.TEMPLATE);
}
}
private void moveTagsToNewObject(String oldTaggedObj, String newTaggedObj, String type) {
TagManager tagManager = getTagManager();
List<Tag> tags = tagManager.getTags(null, oldTaggedObj, type, username);
for (Tag tag : tags) {
try {
tagManager.addTag(tag.getTagName(), newTaggedObj, type, this);
} catch (TagManager.TagNameException e) {
throw new IllegalStateException("Existing tag is illegal: " + tag.getTagName(), e);
} catch (TagManager.TagNamePermissionException e) {
throw new IllegalStateException("Object tagged with " + tag.getTagName(), e);
}
tagManager.deleteTag(tag);
}
}
private TagManager getTagManager() {
return new TagManagerFactory(manager).getTagManager();
}
private SharedBagManager getSharedBagManager() {
return SharedBagManager.getInstance(manager);
}
/**
* Return a WebSearchable Map for the given type.
* @param type the type (from TagTypes)
* @return the Map
*/
public Map<String, ? extends WebSearchable> getWebSearchablesByType(String type) {
if (type.equals(TagTypes.TEMPLATE)) {
return savedTemplates;
}
if (type.equals(TagTypes.BAG)) {
return getSavedBags();
}
throw new RuntimeException("unknown type: " + type);
}
/**
* Get the SearchRepository for this Profile.
* @return the SearchRepository for the user
*/
public SearchRepository getSearchRepository() {
return searchRepository;
}
/**
* @return the user's API key token.
*/
public String getApiKey() {
return token;
}
private String dayToken = null;
/**
* Get a token with at least an hour of validity, and up to 24 hours.
* @return A token for web-service use.
*/
public String getDayToken() {
if (dayToken == null || !manager.tokenHasMoreUses(dayToken)) {
dayToken = getProfileManager().generate24hrKey(this);
}
return dayToken;
}
/**
* Set the API token for this user, and save it in the backing DB.
* @param token The API token.
*/
public void setApiKey(String token) {
this.token = token;
if (manager != null && !savingDisabled) {
manager.saveProfile(this);
}
}
/**
* Returns true if this is a local account, and not, for
* example, an OpenID account.
* @return Whether or not this is a local account.
*/
public boolean isLocal() {
return this.isLocal;
}
/**
* Return a single use API key for this profile
* @return the single use key
*/
public String getSingleUseKey() {
if (isLoggedIn()) {
return manager.generateSingleUseKey(this);
} else {
return "";
}
}
/**
* Return the shared bags for the profile.
* @return a map from bag name to bag
*/
public Map<String, InterMineBag> getSharedBags() {
return getSharedBagManager().getSharedBags(this);
}
/**
* Update the user repository with the sharedbags
*/
public void updateUserRepositoryWithSharedBags() {
if (searchRepository instanceof UserRepository) {
((UserRepository) searchRepository).updateUserRepositoryWithSharedBags();
}
}
/**
* Get the object representing the preferences of this user.
*
* Changes to this user's preferences can be written directly into
* this object.
* @return A representation of the preferences of a user.
*/
public Map<String, String> getPreferences() {
return preferences;
}
/**
* Determine whether a user perfers a certain thing or not.
* @param preference The name of the preference.
* @return Whether this preference is set by this user.
*/
public boolean prefers(String preference) {
return preferences.containsKey(preference);
}
}
|
package com.jk.coolweather.activity;
import java.util.ArrayList;
import java.util.List;
import com.jk.coolweather.R;
import com.jk.coolweather.R.id;
import com.jk.coolweather.R.layout;
import com.jk.coolweather.R.menu;
import com.jk.coolweather.model.City;
import com.jk.coolweather.model.CoolWeatherDB;
import com.jk.coolweather.model.County;
import com.jk.coolweather.model.Province;
import com.jk.coolweather.util.HttpCallbackListener;
import com.jk.coolweather.util.HttpUtil;
import com.jk.coolweather.util.Utility;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class ChooseAreaActivity extends Activity {
public static final int LEVEL_PROVINCE = 0;
public static final int LEVEL_CITY = 1;
public static final int LEVEL_COUNTY = 2;
private ProgressDialog progressDialog;
private TextView titleText;
private ListView listView;
private ArrayAdapter<String> adapter;
private CoolWeatherDB coolWeatherDB;
private List<String> dataList = new ArrayList<String>();
private List<Province> provinceList;
private List<City> cityList;
private List<County> countyList;
private Province selectedProvince;
private City selectedCity;
private int currentLevel;
private boolean isFromWeatherActivity;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
isFromWeatherActivity=getIntent().getBooleanExtra("from_weather_activity", false);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
if (prefs.getBoolean("city_selected", false)&& !isFromWeatherActivity) {
Intent intent = new Intent(this, WeatherActivity.class);
startActivity(intent);
finish();
return;
}
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.choose_area);
listView = (ListView) findViewById(R.id.list_view);
titleText = (TextView) findViewById(R.id.title_text);
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, dataList);
listView.setAdapter(adapter);
coolWeatherDB = CoolWeatherDB.getInstance(this);
listView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int index, long arg3) {
// TODO Auto-generated method stub
if (currentLevel == LEVEL_PROVINCE) {
selectedProvince = provinceList.get(index);
queryCities();
} else if (currentLevel == LEVEL_CITY) {
selectedCity = cityList.get(index);
queryCounties();
} else if (currentLevel == LEVEL_COUNTY) {
String countyCode = countyList.get(index).getCountyCode();
Intent intent = new Intent(ChooseAreaActivity.this, WeatherActivity.class);
intent.putExtra("county_code", countyCode);
startActivity(intent);
finish();
}
}
});
queryProvinces();
}
private void queryProvinces() {
// TODO Auto-generated method stub
provinceList = coolWeatherDB.loadProvinces();
if (provinceList.size() > 0) {
dataList.clear();
for (Province province : provinceList) {
dataList.add(province.getProvinceName());
}
adapter.notifyDataSetChanged();
listView.setSelection(0);
titleText.setText("й");
currentLevel = LEVEL_PROVINCE;
} else {
queryFromServer(null, "province");
}
}
private void queryCities() {
cityList = coolWeatherDB.loadCities(selectedProvince.getId());
if (cityList.size() > 0) {
dataList.clear();
for (City city : cityList) {
dataList.add(city.getCityName());
}
adapter.notifyDataSetChanged();
listView.setSelection(0);
titleText.setText(selectedProvince.getProvinceName());
currentLevel = LEVEL_CITY;
} else {
queryFromServer(selectedProvince.getProvinceCode(), "city");
}
}
private void queryCounties() {
countyList = coolWeatherDB.loadCounties(selectedCity.getId());
if (countyList.size() > 0) {
dataList.clear();
for (County county : countyList) {
dataList.add(county.getCountyName());
}
adapter.notifyDataSetChanged();
listView.setSelection(0);
titleText.setText(selectedCity.getCityName());
currentLevel = LEVEL_COUNTY;
} else {
queryFromServer(selectedCity.getCityCode(), "county");
}
}
private void queryFromServer(final String code, final String type) {
String address;
if (!TextUtils.isEmpty(code)) {
address = "http:
} else {
address = "http:
}
showProgressDialog();
HttpUtil.sendHttpRequest(address, new HttpCallbackListener() {
@Override
public void onFinish(String response) {
boolean result = false;
if ("province".equals(type)) {
result = Utility.handleProvincesResponse(coolWeatherDB, response);
} else if ("city".equals(type)) {
result = Utility.handleCitiesResponse(coolWeatherDB, response, selectedProvince.getId());
} else if ("county".equals(type)) {
result = Utility.handleCountiesResponse(coolWeatherDB, response, selectedCity.getId());
}
if (result) {
runOnUiThread(new Runnable() {
@Override
public void run() {
closeProgressDialog();
if ("province".equals(type)) {
queryProvinces();
} else if ("city".equals(type)) {
queryCities();
} else if ("county".equals(type)) {
queryCounties();
}
}
});
}
}
@Override
public void onError(Exception e) {
runOnUiThread(new Runnable() {
@Override
public void run() {
closeProgressDialog();
Toast.makeText(ChooseAreaActivity.this, "ʧ", Toast.LENGTH_SHORT).show();
}
});
}
});
}
private void showProgressDialog() {
if (progressDialog == null) {
progressDialog = new ProgressDialog(this);
progressDialog.setMessage("ڼ...");
progressDialog.setCanceledOnTouchOutside(false);
}
progressDialog.show();
}
private void closeProgressDialog() {
if (progressDialog != null) {
progressDialog.dismiss();
}
}
@Override
public void onBackPressed() {
if (currentLevel == LEVEL_COUNTY) {
queryCities();
} else if (currentLevel == LEVEL_CITY) {
queryProvinces();
} else {
if(isFromWeatherActivity)
{
Intent intent=new Intent(this,WeatherActivity.class);
startActivity(intent);
}
finish();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.choose_area, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
|
package de.hbz.lobid.helper;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Stack;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.JsonNodeType;
/**
* Builds a map with json paths as keys with aggregated values, thus comparing
* to JsonNodes becomes easy. If a key ends with "Order" it is assumed that the
* values must be in the given order, so this tests also ordered lists.
* Successfully compared elements will be removed from the actual map, thus a
* successful comparison leads to an empty 'actual' map (see last line).
*
* @author Pascal Christoph (dr0i)
* @author Jan Schnasse
*
*/
@SuppressWarnings("javadoc")
public final class CompareJsonMaps {
final static Logger logger = LoggerFactory.getLogger(CompareJsonMaps.class);
Stack<String> stack = new Stack<>();
static final String JSON_LD_CONTEXT = "[@context";
private static boolean IGNORE_CONTEXT = true;
private static String filename1;
private static String filename2;
public static void main(String... args) {
if (args.length < 2)
CompareJsonMaps.logger.info(
"Usage: <filename1> <filename2> {<false> if @context should be taken into acount}");
filename1 = args[0];
filename2 = args[1];
CompareJsonMaps.logger
.info("\n" + filename1 + " may be referenced in the logs as 'actual'\n"
+ filename2 + " may be referenced as 'expected'");
if (args.length >= 3 && args[2].equals("false"))
IGNORE_CONTEXT = false;
try {
if (new CompareJsonMaps().writeFileAndTestJson(
new ObjectMapper().readValue(new File(args[0]), JsonNode.class),
new ObjectMapper().readValue(new File(args[1]), JsonNode.class)))
CompareJsonMaps.logger.info("OK. The content is equal.");
else
CompareJsonMaps.logger.info("Sadeness. The content differs.");
} catch (IOException e) {
e.printStackTrace();
}
}
public boolean writeFileAndTestJson(final JsonNode actual,
final JsonNode expected) {
// generated data to map
final HashMap<String, String> actualMap = new HashMap<>();
extractFlatMapFromJsonNode(actual, actualMap);
// expected data to map
final HashMap<String, String> expectedMap = new HashMap<>();
extractFlatMapFromJsonNode(expected, expectedMap);
CompareJsonMaps.logger.debug("\n
Iterator<String> it = actualMap.keySet().iterator();
removeContext(it);
it = expectedMap.keySet().iterator();
removeContext(it);
for (final Entry<String, String> e : expectedMap.entrySet()) {
CompareJsonMaps.logger.debug("Trying to remove " + e.getKey() + "...");
if (!actualMap.containsKey(e.getKey())) {
CompareJsonMaps.logger
.warn("At least this element is missing in actual: " + e.getKey());
return false;
}
if (e.getKey().endsWith("Order]")) {
handleOrderedValues(actualMap, e);
} else {
handleUnorderedValues(actualMap, e);
}
}
if (!actualMap.isEmpty()) {
CompareJsonMaps.logger
.warn("Fail - no Equality! These keys/values were NOT expected:");
actualMap.forEach((key, val) -> CompareJsonMaps.logger
.warn("KEY=" + key + " VALUE=" + val));
} else
CompareJsonMaps.logger.info("Succeeded - resources are equal");
return actualMap.size() == 0;
}
private static void removeContext(Iterator<String> it) {
while (it.hasNext()) {
String se = it.next();
if (IGNORE_CONTEXT && se.startsWith(JSON_LD_CONTEXT))
it.remove();
}
}
private static void handleUnorderedValues(
final HashMap<String, String> actualMap, final Entry<String, String> e) {
if (checkIfAllValuesAreContainedUnordered(actualMap.get(e.getKey()),
e.getValue())) {
actualMap.remove(e.getKey());
CompareJsonMaps.logger.debug("Removed " + e.getKey());
} else {
CompareJsonMaps.logger
.debug("Missing/wrong: " + e.getKey() + ", will fail");
}
}
private static void handleOrderedValues(
final HashMap<String, String> actualMap, final Entry<String, String> e) {
CompareJsonMaps.logger.debug("Test if proper order for: " + e.getKey());
if (actualMap.containsKey(e.getKey())) {
CompareJsonMaps.logger.trace("Existing as expected: " + e.getKey());
if (e.getValue().equals(actualMap.get(e.getKey()))) {
CompareJsonMaps.logger.trace(
"Equality:\n" + e.getValue() + "\n" + actualMap.get(e.getKey()));
actualMap.remove(e.getKey());
} else
CompareJsonMaps.logger.debug("...but not equal! Will fail");
} else {
CompareJsonMaps.logger.warn("Missing: " + e.getKey() + " , will fail");
}
}
/**
* Construct a map with json paths as keys with aggregated values form json
* nodes.
*
* @param jnode the JsonNode which should be transformed into a map
* @param map the map constructed out of the JsonNode
*/
public void extractFlatMapFromJsonNode(final JsonNode jnode,
final HashMap<String, String> map) {
if (jnode.getNodeType().equals(JsonNodeType.OBJECT)) {
final Iterator<Map.Entry<String, JsonNode>> it = jnode.fields();
while (it.hasNext()) {
final Map.Entry<String, JsonNode> entry = it.next();
stack.push(entry.getKey());
extractFlatMapFromJsonNode(entry.getValue(), map);
stack.pop();
}
} else if (jnode.isArray()) {
final Iterator<JsonNode> it = jnode.iterator();
while (it.hasNext()) {
extractFlatMapFromJsonNode(it.next(), map);
}
} else if (jnode.isValueNode()) {
String value = jnode.toString();
if (map.containsKey(stack.toString()))
value = map.get(stack.toString()).concat("," + jnode.toString());
map.put(stack.toString(), value);
CompareJsonMaps.logger
.trace("Stored this path as key into map:" + stack.toString(), value);
}
}
/*
* Values may be an unorderd set.
*/
private static boolean checkIfAllValuesAreContainedUnordered(
final String actual, final String expected) {
CompareJsonMaps.logger
.trace("\nActual value: " + actual + "\nExpected value: " + expected);
return valuesToList(actual).containsAll(valuesToList(expected));
}
private static List<String> valuesToList(final String values) {
return Arrays
.asList(values.substring(1, values.length() - 1).split("\",\""));
}
}
|
package org.flymine.sql.logging;
import org.flymine.sql.query.Query;
import java.io.Writer;
import java.io.IOException;
import java.util.Date;
/**
* Provides a logging facility for a Query
*
* @author Andrew Varley
*/
public class QueryLogger
{
protected static Object lock = new Object();
/**
* Allows a Query to be logged
*
* @param q a Query to be logged
* @param w the Writer on which to log the Query
* @throws IOException if unable to log correctly
*/
public static void log(Query q, Writer w) throws IOException {
synchronized (lock) {
w.write(new Date().toString() + "\t" + q.getSQLString());
}
}
}
|
package com.mcbans.firestar.mcbans.pluginInterface;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;
import net.h31ix.anticheat.api.AnticheatAPI;
import org.bukkit.ChatColor;
import org.bukkit.OfflinePlayer;
import org.bukkit.entity.Player;
import com.mcbans.firestar.mcbans.MCBans;
import com.mcbans.firestar.mcbans.events.PlayerBanEvent;
import com.mcbans.firestar.mcbans.events.PlayerBannedEvent;
import com.mcbans.firestar.mcbans.events.PlayerGlobalBanEvent;
import com.mcbans.firestar.mcbans.events.PlayerLocalBanEvent;
import com.mcbans.firestar.mcbans.events.PlayerTempBanEvent;
import com.mcbans.firestar.mcbans.events.PlayerUnbanEvent;
import com.mcbans.firestar.mcbans.events.PlayerUnbannedEvent;
import com.mcbans.firestar.mcbans.org.json.JSONException;
import com.mcbans.firestar.mcbans.org.json.JSONObject;
import com.mcbans.firestar.mcbans.request.JsonHandler;
import com.mcbans.firestar.mcbans.util.Util;
import fr.neatmonster.nocheatplus.checks.ViolationHistory;
import fr.neatmonster.nocheatplus.checks.ViolationHistory.ViolationLevel;
public class Ban implements Runnable {
private MCBans plugin;
private String playerName = null;
private String playerIP = null;
private String senderName = null;
private String reason = null;
private String action = null;
private String duration = null;
private String measure = null;
private boolean rollback = false;
private String badword = null;
private JSONObject actionData = null;
private HashMap<String, Integer> responses = new HashMap<String, Integer>();
private int action_id;
public Ban(MCBans plugin, String action, String playerName, String playerIP, String senderName, String reason, String duration,
String measure, JSONObject actionData, boolean rollback) {
this.plugin = plugin;
this.playerName = playerName;
this.playerIP = playerIP;
this.senderName = senderName;
this.reason = reason;
this.rollback = rollback;
this.duration = duration;
this.measure = measure;
this.action = action;
this.actionData = (actionData != null) ? actionData : new JSONObject();
responses.put("globalBan", 0);
responses.put("localBan", 1);
responses.put("tempBan", 2);
responses.put("unBan", 3);
}
public Ban(MCBans plugin, String action, String playerName, String playerIP, String senderName, String reason, String duration,
String measure) {
this (plugin, action, playerName, playerIP, senderName, reason, duration, measure, null, false);
}
/**
* @deprecated Use another constructor. This constructor will be removed on future release.
*/
@Deprecated
public Ban(MCBans plugin, String action, String playerName, String playerIP, String senderName, String reason, String duration,
String measure, JSONObject actionData, int rollback_dummy) {
this (plugin, action, playerName, playerIP, senderName, reason, duration, measure, actionData, true);
}
public void kickPlayer(String playerToKick, final String kickString) {
final Player target = plugin.getServer().getPlayer(playerToKick);
if (target != null) {
plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() {
@Override
public void run() {
target.kickPlayer(kickString);
}
}, 1L);
}
}
@Override
public void run() {
while (plugin.notSelectedServer) {
// waiting for server select
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
if (plugin.getConfigs().isDebug()) {
e.printStackTrace();
}
}
}
try {
if (responses.containsKey(action)) {
action_id = responses.get(action);
// Call BanEvent
if (action_id != 3){
PlayerBanEvent banEvent = new PlayerBanEvent(playerName, playerIP, senderName, reason, action_id, duration, measure);
plugin.getServer().getPluginManager().callEvent(banEvent);
if (banEvent.isCancelled()){
return;
}
senderName = banEvent.getSenderName();
reason = banEvent.getReason();
action_id = banEvent.getActionID();
duration = banEvent.getDuration();
measure = banEvent.getMeasure();
}
switch (action_id) {
case 0:
globalBan();
break;
case 1:
localBan();
break;
case 2:
tempBan();
break;
case 3:
unBan();
break;
}
} else {
plugin.log("Error, caught invalid action! Another plugin using mcbans improperly?");
}
} catch (NullPointerException e) {
if (plugin.getConfigs().isDebug()) {
e.printStackTrace();
}
}
}
public void unBan() {
// Call PlayerUnbanEvent
PlayerUnbanEvent unBanEvent = new PlayerUnbanEvent(playerName, senderName);
plugin.getServer().getPluginManager().callEvent(unBanEvent);
if (unBanEvent.isCancelled()){
return;
}
senderName = unBanEvent.getSenderName();
JsonHandler webHandle = new JsonHandler(plugin);
HashMap<String, String> url_items = new HashMap<String, String>();
url_items.put("player", playerName);
url_items.put("admin", senderName);
url_items.put("exec", "unBan");
HashMap<String, String> response = webHandle.mainRequest(url_items);
try {
if (response.containsKey("error")){
Util.message(senderName, ChatColor.DARK_RED + "Error: " + response.get("error"));
return;
}
if (!response.containsKey("result")) {
Util.message(senderName, ChatColor.DARK_RED + plugin.language.getFormat("unBanMessageError", playerName, senderName));
return;
}
if (response.get("result").equals("y")) {
OfflinePlayer d = plugin.getServer().getOfflinePlayer(playerName);
if (d.isBanned()) {
d.setBanned(false);
}
plugin.log(senderName + " unbanned " + playerName + "!");
Util.message(senderName, ChatColor.GREEN + plugin.language.getFormat("unBanMessageSuccess", playerName, senderName));
plugin.getServer().getPluginManager().callEvent(new PlayerUnbannedEvent(playerName, senderName));
return;
} else if (response.get("result").equals("e")) {
Util.message(senderName, ChatColor.DARK_RED + plugin.language.getFormat("unBanMessageError", playerName, senderName));
} else if (response.get("result").equals("s")) {
Util.message(senderName, ChatColor.DARK_RED + plugin.language.getFormat("unBanMessageGroup", playerName, senderName));
} else if (response.get("result").equals("n")) {
Util.message(senderName, ChatColor.DARK_RED + plugin.language.getFormat("unBanMessageNot", playerName, senderName));
}
plugin.log(senderName + " tried to unban " + playerName + "!");
} catch (NullPointerException e) {
if (plugin.getConfigs().isDebug()) {
e.printStackTrace();
}
}
}
public void localBan() {
// Call PlayerLocalBanEvent
PlayerLocalBanEvent lBanEvent = new PlayerLocalBanEvent(playerName, playerIP, senderName, reason);
plugin.getServer().getPluginManager().callEvent(lBanEvent);
if (lBanEvent.isCancelled()){
return;
}
senderName = lBanEvent.getSenderName();
reason = lBanEvent.getReason();
JsonHandler webHandle = new JsonHandler(plugin);
HashMap<String, String> url_items = new HashMap<String, String>();
url_items.put("player", playerName);
url_items.put("playerip", playerIP);
url_items.put("reason", reason);
url_items.put("admin", senderName);
if (rollback) {
plugin.getRbHandler().rollback(senderName, playerName);
}
if (actionData != null) {
url_items.put("actionData", actionData.toString());
}
url_items.put("exec", "localBan");
HashMap<String, String> response = webHandle.mainRequest(url_items);
try {
if (response.containsKey("error")){
Util.message(senderName, ChatColor.DARK_RED + "Error: " + response.get("error"));
return;
}
if (!response.containsKey("result")) {
Util.message(senderName, ChatColor.DARK_RED + " MCBans down, adding local ban, unban with /pardon");
OfflinePlayer d = plugin.getServer().getOfflinePlayer(playerName);
if (!d.isBanned()) {
d.setBanned(true);
}
this.kickPlayer(playerName, plugin.language.getFormat("localBanMessagePlayer", playerName, senderName, reason, playerIP));
// MCBans.broadcastPlayer( PlayerAdmin, ChatColor.DARK_RED +
// MCBans.Language.getFormat( "localBanMessageError",
// PlayerName, PlayerAdmin, Reason, PlayerIP ) );
return;
}
if (response.get("result").equals("y")) {
plugin.log(playerName + " has been banned with a local type ban [" + reason + "] [" + senderName + "]!");
this.kickPlayer(playerName, plugin.language.getFormat("localBanMessagePlayer", playerName, senderName, reason, playerIP));
Util.broadcastMessage(ChatColor.GREEN + plugin.language.getFormat("localBanMessageSuccess", playerName, senderName, reason, playerIP));
plugin.getServer().getPluginManager().callEvent(new PlayerBannedEvent(playerName, playerIP, senderName, reason, action_id, duration, measure));
return;
} else if (response.get("result").equals("e")) {
Util.message(senderName,
ChatColor.DARK_RED + plugin.language.getFormat("localBanMessageError", playerName, senderName, reason, playerIP));
} else if (response.get("result").equals("s")) {
Util.message(senderName,
ChatColor.DARK_RED + plugin.language.getFormat("localBanMessageGroup", playerName, senderName, reason, playerIP));
} else if (response.get("result").equals("a")) {
Util.message(senderName,
ChatColor.DARK_RED + plugin.language.getFormat("localBanMessageAlready", playerName, senderName, reason, playerIP));
}
plugin.log(senderName + " has tried to ban " + playerName + " with a local type ban [" + reason + "]!");
} catch (NullPointerException e) {
Util.message(senderName, ChatColor.DARK_RED + " MCBans down, adding local ban, unban with /pardon");
OfflinePlayer d = plugin.getServer().getOfflinePlayer(playerName);
if (!d.isBanned()) {
d.setBanned(true);
}
this.kickPlayer(playerName, plugin.language.getFormat("localBanMessagePlayer", playerName, senderName, reason, playerIP));
if (plugin.getConfigs().isDebug()) {
e.printStackTrace();
}
}
}
public void globalBan() {
// Call PlayerGlobalBanEvent
PlayerGlobalBanEvent gBanEvent = new PlayerGlobalBanEvent(playerName, playerIP, senderName, reason);
plugin.getServer().getPluginManager().callEvent(gBanEvent);
if (gBanEvent.isCancelled()){
return;
}
senderName = gBanEvent.getSenderName();
reason = gBanEvent.getReason();
JsonHandler webHandle = new JsonHandler(plugin);
HashMap<String, String> url_items = new HashMap<String, String>();
url_items.put("player", playerName);
url_items.put("playerip", playerIP);
url_items.put("reason", reason);
url_items.put("admin", senderName);
// Put proof
try{
for (Map.Entry<String, JSONObject> proof : getProof().entrySet()){
actionData.put(proof.getKey(), proof.getValue());
}
}catch (JSONException ex){
if (plugin.getConfigs().isDebug()) {
ex.printStackTrace();
}
}
if (rollback) {
plugin.getRbHandler().rollback(senderName, playerName);
}
if (actionData.length() > 0) {
url_items.put("actionData", actionData.toString());
}
url_items.put("exec", "globalBan");
HashMap<String, String> response = webHandle.mainRequest(url_items);
try {
if (response.containsKey("error")){
Util.message(senderName, ChatColor.DARK_RED + "Error: " + response.get("error"));
return;
}
if (!response.containsKey("result")) {
Util.message(senderName, ChatColor.DARK_RED + " MCBans down, adding local ban, unban with /pardon");
OfflinePlayer d = plugin.getServer().getOfflinePlayer(playerName);
if (!d.isBanned()) {
d.setBanned(true);
}
this.kickPlayer(playerName, plugin.language.getFormat("localBanMessagePlayer", playerName, senderName, reason, playerIP));
// MCBans.broadcastPlayer( PlayerAdmin, ChatColor.DARK_RED +
// MCBans.Language.getFormat( "globalBanMessageError",
// PlayerName, PlayerAdmin, Reason, PlayerIP ) );
return;
}
if (response.get("result").equals("y")) {
plugin.log(playerName + " has been banned with a global type ban [" + reason + "] [" + senderName + "]!");
this.kickPlayer(playerName, plugin.language.getFormat("globalBanMessagePlayer", playerName, senderName, reason, playerIP));
Util.broadcastMessage(ChatColor.GREEN + plugin.language.getFormat("globalBanMessageSuccess", playerName, senderName, reason, playerIP));
plugin.getServer().getPluginManager().callEvent(new PlayerBannedEvent(playerName, playerIP, senderName, reason, action_id, duration, measure));
return;
} else if (response.get("result").equals("e")) {
Util.message(senderName,
ChatColor.DARK_RED + plugin.language.getFormat("globalBanMessageError", playerName, senderName, reason, playerIP));
} else if (response.get("result").equals("w")) {
badword = response.get("word");
Util.message(senderName,
ChatColor.DARK_RED + plugin.language.getFormat("globalBanMessageWarning", playerName, senderName, reason, playerIP, badword));
} else if (response.get("result").equals("s")) {
Util.message(senderName,
ChatColor.DARK_RED + plugin.language.getFormat("globalBanMessageGroup", playerName, senderName, reason, playerIP));
} else if (response.get("result").equals("a")) {
Util.message(senderName,
ChatColor.DARK_RED + plugin.language.getFormat("globalBanMessageAlready", playerName, senderName, reason, playerIP));
}
plugin.log(senderName + " has tried to ban " + playerName + " with a global type ban [" + reason + "]!");
} catch (NullPointerException e) {
Util.message(senderName, ChatColor.DARK_RED + " MCBans down, adding local ban, unban with /pardon");
OfflinePlayer d = plugin.getServer().getOfflinePlayer(playerName);
if (!d.isBanned()) {
d.setBanned(true);
}
this.kickPlayer(playerName, plugin.language.getFormat("localBanMessagePlayer", playerName, senderName, reason, playerIP));
if (plugin.getConfigs().isDebug()) {
e.printStackTrace();
}
}
}
public void tempBan() {
// Call PlayerTempBanEvent
PlayerTempBanEvent tBanEvent = new PlayerTempBanEvent(playerName, playerIP, senderName, reason, duration, measure);
plugin.getServer().getPluginManager().callEvent(tBanEvent);
if (tBanEvent.isCancelled()){
return;
}
senderName = tBanEvent.getSenderName();
reason = tBanEvent.getReason();
duration = tBanEvent.getDuration();
measure = tBanEvent.getMeasure();
JsonHandler webHandle = new JsonHandler(plugin);
HashMap<String, String> url_items = new HashMap<String, String>();
url_items.put("player", playerName);
url_items.put("playerip", playerIP);
url_items.put("reason", reason);
url_items.put("admin", senderName);
url_items.put("duration", duration);
url_items.put("measure", measure);
if (plugin.getConfigs().isEnableRollbackTempBan()) {
plugin.getRbHandler().rollback(senderName, playerName);
}
if (actionData != null) {
url_items.put("actionData", actionData.toString());
}
url_items.put("exec", "tempBan");
HashMap<String, String> response = webHandle.mainRequest(url_items);
try {
if (response.containsKey("error")){
Util.message(senderName, ChatColor.DARK_RED + "Error: " + response.get("error"));
return;
}
if (!response.containsKey("result")) {
Util.message(senderName, ChatColor.DARK_RED + " MCBans down, adding local ban, unban with /pardon");
OfflinePlayer d = plugin.getServer().getOfflinePlayer(playerName);
if (!d.isBanned()) {
d.setBanned(true);
}
this.kickPlayer(playerName, plugin.language.getFormat("localBanMessagePlayer", playerName, senderName, reason, playerIP));
// MCBans.broadcastPlayer( PlayerAdmin, ChatColor.DARK_RED +
// MCBans.Language.getFormat( "tempBanMessageError", PlayerName,
// PlayerAdmin, Reason, PlayerIP ) );
return;
}
if (response.get("result").equals("y")) {
plugin.log(playerName + " has been banned with a temp type ban [" + reason + "] [" + senderName + "]!");
this.kickPlayer(playerName, plugin.language.getFormat("tempBanMessagePlayer", playerName, senderName, reason, playerIP));
Util.broadcastMessage(ChatColor.GREEN + plugin.language.getFormat("tempBanMessageSuccess", playerName, senderName, reason, playerIP));
plugin.getServer().getPluginManager().callEvent(new PlayerBannedEvent(playerName, playerIP, senderName, reason, action_id, duration, measure));
return;
} else if (response.get("result").equals("e")) {
Util.message(senderName,
ChatColor.DARK_RED + plugin.language.getFormat("tempBanMessageError", playerName, senderName, reason, playerIP));
} else if (response.get("result").equals("s")) {
Util.message(senderName,
ChatColor.DARK_RED + plugin.language.getFormat("tempBanMessageGroup", playerName, senderName, reason, playerIP));
} else if (response.get("result").equals("a")) {
Util.message(senderName,
ChatColor.DARK_RED + plugin.language.getFormat("tempBanMessageAlready", playerName, senderName, reason, playerIP));
}
plugin.log(senderName + " has tried to ban " + playerName + " with a temp type ban [" + reason + "]!");
} catch (NullPointerException e) {
Util.message(senderName, ChatColor.DARK_RED + " MCBans down, adding local ban, unban with /pardon");
OfflinePlayer d = plugin.getServer().getOfflinePlayer(playerName);
if (!d.isBanned()) {
d.setBanned(true);
}
this.kickPlayer(playerName, plugin.language.getFormat("localBanMessagePlayer", playerName, senderName, reason, playerIP));
if (plugin.getConfigs().isDebug()) {
e.printStackTrace();
}
}
}
private Map<String, JSONObject> getProof() throws JSONException{
HashMap<String, JSONObject> ret = new HashMap<String, JSONObject>();
/* Hacked client */
// No catch PatternSyntaxException. This exception thrown when compiling invalid regex.
// In this case, regex is constant string. Next line is wrong if throw this. So should output full exception message.
Pattern regex = Pattern.compile("(fly|hack|nodus|glitch|exploit|NC|cheat|nuker|x-ray|xray)");
boolean foundMatch = regex.matcher(reason).find();
if (foundMatch) {
Player p = plugin.getServer().getPlayerExact(playerName);
if (p != null) playerName = p.getName();
// NoCheatPlus
if (plugin.isEnabledNCP()) {
ViolationHistory history = ViolationHistory.getHistory(playerName, false);
if (history != null){
// found player history
final ViolationLevel[] violations = history.getViolationLevels();
JSONObject tmp = new JSONObject();
for (ViolationLevel vl : violations){
tmp.put(vl.check, String.valueOf(Math.round(vl.sumVL)));
}
ret.put("nocheatplus", tmp);
//ActionData.put("nocheatplus", tmp); // don't put directly
}
}
// AntiCheat
if (plugin.isEnabledAC() && p.getPlayer() != null) {
JSONObject tmp = new JSONObject();
final int level = AnticheatAPI.getLevel(p);
final boolean xray = AnticheatAPI.isXrayer(p);
// TODO: Detail proof. Refer AntiCheat CommandHandler:
if (level > 0) tmp.put("hack level", String.valueOf(level));
if (xray) tmp.put("detected x-ray", "true");
if (tmp.length() > 0) ret.put("anticheat", tmp);
}
}
return ret;
}
}
|
/**
* <p>The hll package contains a very compact implementation of Phillipe Flajolet's
* HLL sketch but with significantly improved error behavior. If the ONLY use case for sketching is
* counting uniques and merging, the HLL sketch is the highest performing in terms of accuracy for
* space consumed. For large counts, this HLL version will be 16 to 32 times smaller for the same
* accuracy than the Theta Sketches.</p>
*
* <p>However, large data with many dimensions and dimension coordinates are often highly skewed
* creating a "long-tailed" or power-law distribution of unique values per sketch.
* In this case a majority of sketches tend to have only a few entries. It is this long tail of
* the distribution of sketch sizes that will dominate the overall storage cost for all of the
* sketches. In this case the size advantage of the HLL will be significantly reduced down to a
* factor of two to four compared to Theta Sketches. This behavior is strictly a function of the
* distribution of the input data so it is advisable to understand and measure this phenomenon with
* your own data.</p>
*
* <p>The HLL sketch is not recommended if you anticipate the need of performing set intersection
* or difference operations with reasonable accuracy,
* or if you anticipate the need to merge sketches that were constructed with different
* values of <i>k</i> or <i>Nominal Entries</i>.</p>
*
* <p>HLL sketches do not retain any of the hash values of the associated unique identifiers,
* so if there is any anticipation of a future need to leverage associations with these
* retained hash values, Theta Sketches would be a better choice.</p>
*
* <p>HLL sketches cannot be intermixed or merged in any way with Theta Sketches.
* </p>
*
* @author Kevin Lang
* @author Lee Rhodes
* @author Alex Saydakov
*/
package com.yahoo.sketches.hll;
|
package org.intermine.web.logic;
/**
* Container for ServletContext and Session attribute names used by the webapp
*
* @author Kim Rutherford
* @author Thomas Riley
*/
public interface Constants
{
/**
* ServletContext attribute used to store web.properties
*/
String WEB_PROPERTIES = "WEB_PROPERTIES";
/**
* ServletContext attribute, List of category names.
*/
String CATEGORIES = "CATEGORIES";
/**
* ServletContext attribute, autocompletion.
*/
String AUTO_COMPLETER = "AUTO_COMPLETER";
/**
* ServletContext attribute, Map from unqualified type name to list of subclass names.
*/
String SUBCLASSES = "SUBCLASSES";
/**
* Session attribute, name of tab selected on MyMine page.
*/
String MYMINE_PAGE = "MYMINE_PAGE"; // serializes
/**
* ServletContext attribute used to store the WebConfig object for the Model.
*/
String WEBCONFIG = "WEBCONFIG";
/**
* Session attribute used to store the user's Profile
*/
String PROFILE = "PROFILE"; // serialized as 'username'
/**
* Session attribute used to store the current query
*/
String QUERY = "QUERY";
/**
* Session attribute used to store the status new template
*/
String NEW_TEMPLATE = "NEW_TEMPLATE";
/**
* Session attribute used to store the status editing template
*/
String EDITING_TEMPLATE = "EDITING_TEMPLATE";
/**
* Session attribute used to store the previous template name
*/
String PREV_TEMPLATE_NAME = "PREV_TEMPLATE_NAME";
/**
* Servlet context attribute - map from aspect set name to Aspect object.
*/
String ASPECTS = "ASPECTS";
/**
* Session attribute equals Boolean.TRUE when logged in user is superuser.
*/
String IS_SUPERUSER = "IS_SUPERUSER";
/**
* Session attribute that temporarily holds a Vector of messages that will be displayed by the
* errorMessages.jsp on the next page viewed by the user and then removed (allows message
* after redirect).
*/
String MESSAGES = "MESSAGES";
/**
* Session attribute that temporarily holds a Vector of errors that will be displayed by the
* errorMessages.jsp on the next page viewed by the user and then removed (allows errors
* after redirect).
*/
String ERRORS = "ERRORS";
/**
* Session attribute that temporarily holds messages from the Portal
*/
String PORTAL_MSG = "PORTAL_MSG";
/**
* Session attribute that holds message when a lookup constraint has been used
*/
String LOOKUP_MSG = "LOOKUP_MSG";
/**
* The name of the property to look up to find the maximum size of an inline table.
*/
String INLINE_TABLE_SIZE = "inline.table.size";
/**
* Session attribut containing the default operator name, either 'and' or 'or'.
*/
String DEFAULT_OPERATOR = "DEFAULT_OPERATOR";
/**
* Period of time to wait for client to poll a running query before cancelling the query.
*/
int QUERY_TIMEOUT_SECONDS = 20;
/**
* Refresh period specified on query poll page.
*/
int POLL_REFRESH_SECONDS = 2;
/**
* The session attribute that holds the DisplayObjectCache object for the session.
*/
String DISPLAY_OBJECT_CACHE = "DISPLAY_OBJECT_CACHE";
/**
* Session attribute that holds cache of table identifiers to PagedTable objects.
*/
String TABLE_MAP = "TABLE_MAP";
/**
* Session attribute that holds a map from class name to map from field name to Boolean.TRUE.
*/
String EMPTY_FIELD_MAP = "EMPTY_FIELD_MAP";
/**
* Session attribute. A Map from query id to QueryMonitor.
*/
String RUNNING_QUERIES = "RUNNING_QUERIES";
/**
* Servlet attribute. Map from class name to Set of leaf class descriptors.
*/
String LEAF_DESCRIPTORS_MAP = "LEAF_DESCRIPTORS_MAP";
/**
* Servlet attribute. Map from MultiKey(experiment, gene) id to temp file name.
*/
String GRAPH_CACHE = "GRAPH_CACHE";
/**
* Servlet attribute. The global webapp cache - a InterMineCache object.
*/
String GLOBAL_CACHE = "GLOBAL_CACHE";
/**
* Maximum size a bag should have if the user is not logged in (to save memory)
*/
int MAX_NOT_LOGGED_BAG_SIZE = 500;
/**
* Servlet attribute. Contains the SearchRepository for global/public WebSearchable objects.
*/
String GLOBAL_SEARCH_REPOSITORY = "GLOBAL_SEARCH_REPOSITORY";
/**
* Default size of table implemented by PagedTable.
*/
int DEFAULT_TABLE_SIZE = 25;
/**
* Session attribute used to store the size of table with results.
*/
String RESULTS_TABLE_SIZE = "RESULTS_TABLE_SIZE";
/**
* Session attribute used to store WebState object.
*/
String WEB_STATE = "WEB_STATE";
/**
* Current version of the InterMine WebService.
* This constant must changed every time the API changes, either by addition
* or deletion of features.
*/
int WEB_SERVICE_VERSION = 4;
/**
* Key for a Map from class name to Boolean.TRUE for all classes in the model that do not have
* any class keys.
*/
String KEYLESS_CLASSES_MAP = "KEYLESS_CLASSES_MAP";
/**
* Key for the InterMine API object
*/
String INTERMINE_API = "INTERMINE_API";
String INITIALISER_KEY_ERROR = "INITIALISER_KEY_ERROR";
}
|
package de.henninglanghorst.functional;
import de.henninglanghorst.functional.model.Person;
import de.henninglanghorst.functional.util.Either;
import org.h2.jdbcx.JdbcConnectionPool;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.sql.Date;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.List;
import static de.henninglanghorst.functional.sql.DatabaseOperations.*;
import static java.util.Arrays.asList;
/**
* Example program.
*
* @author Henning Langhorst
*/
public class Main {
private static final Logger LOGGER = LoggerFactory.getLogger(Main.class);
public static void main(String[] args) {
final JdbcConnectionPool cp = JdbcConnectionPool.create("jdbc:h2:~/testdb", "sa", "");
doInDatabase(cp::getConnection, databaseUpdate(statement("drop table Person")))
.handleResult(objects -> LOGGER.info("Success " + objects), Main::logError);
doInDatabase(
cp::getConnection,
withinTransaction(
databaseUpdate(
statement("create table Person (id integer primary key, firstName varchar2, lastName varchar2, birthday date)"))))
.handleResult(objects -> LOGGER.info("Success " + objects), Main::logError);
doInDatabase(cp::getConnection, multipleDatabaseUpdates(
asList(
statement(
"insert into Person values (?, ?, ?, ?);",
1, "Carl", "Carlsson", Date.valueOf("1972-04-02")),
statement("insert into Person values (?, ?, ?, ?);",
2, "Lenny", "Leonard", Date.valueOf("1981-04-02")))
)
).handleResult(
objects -> LOGGER.info("Inserted rows: " + Arrays.toString(objects)),
Main::logError);
final Either<List<Person>, SQLException> result = doInDatabase(
cp::getConnection,
databaseQuery(
statement("select * from Person where id = ?", 1),
resultSet -> new Person(
resultSet.getInt("id"),
resultSet.getString("firstName"),
resultSet.getString("lastName"),
resultSet.getDate("birthday").toLocalDate())));
LOGGER.info("DB Result: " + result.left());
}
private static void logError(final SQLException e) {
LOGGER.error("Error during database operation", e);
}
}
|
package com.mick88.dittimetable.timetable;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import android.content.Context;
import com.mick88.dittimetable.AppSettings;
import com.mick88.dittimetable.list.EventAdapter.EventItem;
import com.mick88.dittimetable.list.MultiEvent;
import com.mick88.dittimetable.list.Space;
/**
* ontains list of classes in a day
*
*/
public class TimetableDay implements Serializable
{
private static final long serialVersionUID = 1L;
// final String name;
final int id;
final String logTag = "TimetableDay";
private List<TimetableEvent> events = new ArrayList<TimetableEvent>();
public TimetableDay(int id)
{
this.id = id;
}
public void clearEvents()
{
synchronized (events)
{
events.clear();
}
}
public void sortEvents()
{
synchronized (events)
{
Collections.sort(events);
}
}
public void addClass(TimetableEvent c)
{
synchronized (events)
{
events.add(c);
}
}
public String getName()
{
return Timetable.DAY_NAMES[id];
}
public CharSequence getShortName()
{
return getName().subSequence(0, 3);
}
public int getNumEvents(int hour, Set<String> hiddenGroups, int week)
{
int n=0;
for (TimetableEvent event : events) if (event.getStartHour() == hour && event.isInWeek(week))
{
if (event.isGroup(hiddenGroups)) n++;
}
return n;
}
public List<TimetableEvent> getClasses()
{
return events;
}
/**
* Get Set of lectures at this time
* @return
*/
public Set<TimetableEvent> getCurrentEvents()
{
Set<TimetableEvent> result = new HashSet<TimetableEvent>();
if (isToday())
{
int hour = Calendar.getInstance().get(Calendar.HOUR_OF_DAY);
for (TimetableEvent event : events)
if (event.isEventOn(hour)) result.add(event);
}
return result;
}
/**
* Gets string representing hours from first to last event on this day
* @param appSettings
* @return
*/
public CharSequence getHoursRange(AppSettings appSettings)
{
List<TimetableEvent> events = getEvents(appSettings);
if (events.isEmpty()) return null;
CharSequence start = events.get(0).getStartTime(),
end = events.get(events.size()-1).getEndTime();
return new StringBuilder(start).append(" - ").append(end);
}
@Deprecated
public int parseHtmlEvent(Timetable timetable, Element element, Context context, boolean allowCache)
{
int n=0;
TimetableEvent c = new TimetableEvent(element, timetable, context, allowCache, id);
if (c.isValid() /*&& c.isGroup(timetable.getHiddenGroups())*/)
{
addClass(c);
n++;
}
return n;
}
public boolean parseGridRow(Timetable timetable, Elements gridCols, Context context, boolean allowCache)
{
TimetableEvent event = new TimetableEvent(this.id, gridCols);
if (event.isValid())
{
addClass(event);
return true;
}
else
return false;
}
@Override
public String toString()
{
if (events.isEmpty()) return new String();
StringBuilder builder = new StringBuilder(getName());
for (TimetableEvent c : events)
{
builder.append('\n');
builder.append(c.toString());
}
return builder.toString();
}
public String toString(Set<String> hiddenGroups, int week)
{
if (events.isEmpty()) return new String();
int n=0;
StringBuilder builder = new StringBuilder(getName());
for (TimetableEvent event : events) if (event.isInWeek(week) && event.isGroup(hiddenGroups))
{
builder.append('\n');
builder.append(event.toString());
n++;
}
if (n == 0) return new String();
else return builder.toString();
}
private final String EXPORT_DAY_SEPARATOR = "\n";
public CharSequence export()
{
StringBuilder builder = new StringBuilder();
for (TimetableEvent event : events)
{
builder.append(event.export()).append(EXPORT_DAY_SEPARATOR);
}
return builder;
}
public int importFromString(String string, Timetable timetable)
{
int n=0;
String [] events = string.split(EXPORT_DAY_SEPARATOR);
for (String eventString : events)
{
TimetableEvent event = new TimetableEvent(eventString, timetable, id);
if (event.isValid() /*&& event.isGroup(timetable.hiddenGroups)*/)
{
n++;
addClass(event);
}
}
return n;
}
public boolean isToday()
{
return Timetable.getTodayId(false) == this.id;
// return Timetable.getToday(false) == this;
}
public List<TimetableEvent> getEvents(AppSettings settings)
{
List<TimetableEvent> events = new ArrayList<TimetableEvent>();
int currentWeek = Timetable.getCurrentWeek(),
showWeek = settings.getOnlyCurrentWeek()?currentWeek : 0;
for (TimetableEvent event : this.events)
if (event.isGroup(settings.getHiddenGroups()) && event.isInWeek(showWeek))
{
events.add(event);
}
return events;
}
public List<EventItem> getTimetableEntries(AppSettings settings)
{
List<EventItem> entries = new ArrayList<EventItem>(events.size());
int lastEndHour=0;
TimetableEvent lastEvent=null;
int currentWeek = Timetable.getCurrentWeek(),
showWeek = settings.getOnlyCurrentWeek()?currentWeek : 0;
List<TimetableEvent> sameHourEvents = new ArrayList<TimetableEvent>();
synchronized (events)
{
for (TimetableEvent event : events)
if (event.isGroup(settings.getHiddenGroups()) && event.isInWeek(showWeek))
{
if (lastEvent != null)
{
// add space if there was a time off between the events
if (lastEndHour < event.getStartHour())
{
entries.add(new Space(event.getStartHour() - lastEndHour, lastEndHour));
}
}
int numEvents = getNumEvents(event.getStartHour(), settings.getHiddenGroups(), showWeek);
boolean singleEvent = (numEvents == 1);
if (singleEvent)
{
entries.add(event);
}
else
{
if (sameHourEvents.isEmpty()) entries.add(new MultiEvent(sameHourEvents));
else if (sameHourEvents.get(0).getStartHour() != event.getStartHour())
{
sameHourEvents = new ArrayList<TimetableEvent>();
entries.add(new MultiEvent(sameHourEvents));
}
sameHourEvents.add(event);
}
lastEvent = event;
lastEndHour = event.getEndHour();
}
}
return entries;
}
public void downloadAdditionalInfo(Context context, Timetable timetable)
{
synchronized (events)
{
for (TimetableEvent event : events) if (event.isComplete() == false)
{
if (timetable.isDisposed()) break;
event.downloadAdditionalInfo(context, timetable);
}
}
}
@Override
public int hashCode()
{
return id;
}
@Override
public boolean equals(Object o)
{
if (o instanceof TimetableDay)
{
return ((TimetableDay) o).id == id;
}
else return super.equals(o);
}
}
|
package org.slc.sli.api.service;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
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.ListIterator;
import java.util.Map;
import java.util.Set;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.slc.sli.api.client.constants.EntityNames;
import org.slc.sli.api.config.EntityDefinition;
import org.slc.sli.api.representation.EntityBody;
import org.slc.sli.api.security.CallingApplicationInfoProvider;
import org.slc.sli.api.security.SLIPrincipal;
import org.slc.sli.api.security.context.ContextResolverStore;
import org.slc.sli.api.security.context.resolver.AllowAllEntityContextResolver;
import org.slc.sli.api.security.context.resolver.EdOrgContextResolver;
import org.slc.sli.api.security.context.resolver.EntityContextResolver;
import org.slc.sli.api.security.schema.SchemaDataProvider;
import org.slc.sli.api.util.SecurityUtil;
import org.slc.sli.dal.convert.IdConverter;
import org.slc.sli.domain.Entity;
import org.slc.sli.domain.NeutralCriteria;
import org.slc.sli.domain.NeutralQuery;
import org.slc.sli.domain.QueryParseException;
import org.slc.sli.domain.Repository;
import org.slc.sli.domain.enums.Right;
/**
* Implementation of EntityService that can be used for most entities.
*
* <p/>
* It is very important this bean prototype scope, since one service is needed per
* entity/association.
*/
@Scope("prototype")
@Component("basicService")
public class BasicService implements EntityService {
private static final String ADMIN_SPHERE = "Admin";
private static final String PUBLIC_SPHERE = "Public";
private static final int MAX_RESULT_SIZE = 9999;
private static final String CUSTOM_ENTITY_COLLECTION = "custom_entities";
private static final String CUSTOM_ENTITY_CLIENT_ID = "clientId";
private static final String CUSTOM_ENTITY_ENTITY_ID = "entityId";
private static final String METADATA = "metaData";
private static final String collectionsExcluded = "tenant, userSession, realm, userAccount, roles, application, applicationAuthorization";
private static final Set<String> NOT_BY_TENANT = new HashSet<String>();
static {
String[] collections = collectionsExcluded.split(",");
for (String collection : collections) {
NOT_BY_TENANT.add(collection.trim());
}
}
private String collectionName;
private List<Treatment> treatments;
private EntityDefinition defn;
private Right readRight;
private Right writeRight; // this is possibly the worst named variable ever
@Autowired
private Repository<Entity> repo;
@Autowired
private ContextResolverStore contextResolverStore;
@Autowired
private SchemaDataProvider provider;
@Autowired
private IdConverter idConverter;
@Autowired
private CallingApplicationInfoProvider clientInfo;
@Autowired
private EdOrgContextResolver edOrgContextResolver;
public BasicService(String collectionName, List<Treatment> treatments, Right readRight, Right writeRight) {
this.collectionName = collectionName;
this.treatments = treatments;
this.readRight = readRight;
this.writeRight = writeRight;
}
public BasicService(String collectionName, List<Treatment> treatments) {
this(collectionName, treatments, Right.READ_GENERAL, Right.WRITE_GENERAL);
}
@Override
public long count(NeutralQuery neutralQuery) {
checkRights(readRight);
checkFieldAccess(neutralQuery);
NeutralCriteria securityCriteria = findAccessible(defn.getType());
List<String> allowed = (List<String>) securityCriteria.getValue();
if (allowed.isEmpty() && readRight != Right.ANONYMOUS_ACCESS) {
return 0;
}
Set<String> ids = new HashSet<String>();
List<NeutralCriteria> criterias = neutralQuery.getCriteria();
for (NeutralCriteria criteria : criterias) {
if (criteria.getKey().equals("_id")) {
@SuppressWarnings("unchecked")
List<String> idList = (List<String>) criteria.getValue();
ids.addAll(idList);
}
}
NeutralQuery localNeutralQuery = new NeutralQuery(neutralQuery);
if (securityCriteria.getKey().equals("_id")) {
if (allowed.size() >= 0 && readRight != Right.ANONYMOUS_ACCESS) {
if (!ids.isEmpty()) {
ids.retainAll(new HashSet<String>(allowed)); // retain only those IDs that area
// allowed
//update the security criteria
securityCriteria = new NeutralCriteria("_id", NeutralCriteria.CRITERIA_IN, new ArrayList<String>(ids));
}
}
}
if (allowed.size() > 0) {
//add the security criteria
localNeutralQuery.addCriteria(securityCriteria);
}
this.addDefaultQueryParams(localNeutralQuery, collectionName);
return repo.count(collectionName, localNeutralQuery);
}
/**
* Retrieves an entity from the data store with certain fields added/removed.
*
* @param neutralQuery all parameters to be included in query
* @return the body of the entity
*/
@Override
public Iterable<String> listIds(NeutralQuery neutralQuery) {
checkRights(readRight);
checkFieldAccess(neutralQuery);
NeutralCriteria securityCriteria = findAccessible(defn.getType());
List<String> allowed = (List<String>) securityCriteria.getValue();
if (allowed.isEmpty()) {
return Collections.emptyList();
}
// super list logic --> only true when using DefaultEntityContextResolver
List<String> results = new ArrayList<String>();
//not a super list so add the criteria
//not sure if this ever happen
if (allowed.size() > 0) {
//add the security criteria
neutralQuery.addCriteria(securityCriteria);
}
this.addDefaultQueryParams(neutralQuery, collectionName);
Iterable<Entity> entities = repo.findAll(collectionName, neutralQuery);
for (Entity entity : entities) {
results.add(entity.getEntityId());
}
return results;
}
@Override
public String create(EntityBody content) {
// DE260 - Logging of possibly sensitive data
// LOG.debug("Creating a new entity in collection {} with content {}", new Object[] {
// collectionName, content });
// if service does not allow anonymous write access, check user rights
if (writeRight != Right.ANONYMOUS_ACCESS) {
checkRights(determineWriteAccess(content, ""));
}
checkReferences(content);
return repo.create(defn.getType(), sanitizeEntityBody(content), createMetadata(), collectionName).getEntityId();
}
@Override
public void delete(String id) {
// DE260 - Logging of possibly sensitive data
// LOG.debug("Deleting {} in {}", new String[] { id, collectionName });
checkAccess(writeRight, id);
try {
cascadeDelete(id);
} catch (RuntimeException re) {
debug(re.toString());
}
if (!repo.delete(collectionName, id)) {
info("Could not find {}", id);
throw new EntityNotFoundException(id);
}
deleteAttachedCustomEntities(id);
}
@Override
public boolean update(String id, EntityBody content) {
debug("Updating {} in {}", id, collectionName);
if (writeRight != Right.ANONYMOUS_ACCESS) {
checkAccess(determineWriteAccess(content, ""), id);
}
NeutralQuery query = new NeutralQuery();
query.addCriteria(new NeutralCriteria("_id", "=", id));
this.addDefaultQueryParams(query, collectionName);
Entity entity = repo.findOne(collectionName, query);
//Entity entity = repo.findById(collectionName, id);
if (entity == null) {
info("Could not find {}", id);
throw new EntityNotFoundException(id);
}
EntityBody sanitized = sanitizeEntityBody(content);
if (entity.getBody().equals(sanitized)) {
info("No change detected to {}", id);
return false;
}
info("new body is {}", sanitized);
entity.getBody().clear();
entity.getBody().putAll(sanitized);
repo.update(collectionName, entity);
return true;
}
@Override
public EntityBody get(String id) {
checkAccess(readRight, id);
// change to accommodate tenantId:
// findById does not support NeutralQuery and therefore cannot be used any more
// Entity entity = getRepo().findById(collectionName, id);
NeutralQuery neutralQuery = new NeutralQuery();
neutralQuery.addCriteria(new NeutralCriteria("_id", "=", id));
this.addDefaultQueryParams(neutralQuery, collectionName);
Entity entity = getRepo().findOne(collectionName, neutralQuery);
if (entity == null) {
info("Could not find {}", id);
throw new EntityNotFoundException(id);
}
return makeEntityBody(entity);
}
@Override
public EntityBody get(String id, NeutralQuery neutralQuery) {
checkAccess(readRight, id);
checkFieldAccess(neutralQuery);
if (neutralQuery == null) {
neutralQuery = new NeutralQuery();
}
neutralQuery.addCriteria(new NeutralCriteria("_id", "=", id));
this.addDefaultQueryParams(neutralQuery, collectionName);
Entity entity = repo.findOne(collectionName, neutralQuery);
if (entity == null) {
throw new EntityNotFoundException(id);
}
return makeEntityBody(entity);
}
/**
* The purpose of this method is to add the default parameters to a neutral query. At inception,
* this method
* add the Tenant ID to a neutral query.
*
* @param query
* The query returned is the same as the query passed.
* @return
* The modified neutral query
*/
protected NeutralQuery addDefaultQueryParams(NeutralQuery query, String collectionName) {
if (query == null) {
query = new NeutralQuery();
}
// Add tenant ID
if (!NOT_BY_TENANT.contains(collectionName)) {
SLIPrincipal principal = (SLIPrincipal) SecurityContextHolder.getContext().getAuthentication()
.getPrincipal();
if(principal == null || principal.getTenantId() == null) {
debug("A user is attempting to access collection: " + collectionName + "with null tenantId." );
return query;
}
// make sure a criterion for tenantId has not already been added to this query
boolean addCrit = true;
List<NeutralCriteria> criteria = query.getCriteria();
if (criteria != null) {
ListIterator<NeutralCriteria> li = criteria.listIterator();
while (li.hasNext()) {
if ("metaData.tenantId".equalsIgnoreCase(li.next().getKey())) {
addCrit = false;
break;
}
}
}
// add the tenant ID if it's not already there
if (addCrit) {
query.addCriteria(new NeutralCriteria("metaData.tenantId", "=", principal.getTenantId(), false));
}
}
return query;
}
private Iterable<EntityBody> noEntitiesFound(NeutralQuery neutralQuery) {
//this.addDefaultQueryParams(neutralQuery, collectionName);
if (makeEntityList(repo.findAll(collectionName, neutralQuery)).isEmpty()) {
return new ArrayList<EntityBody>();
} else {
throw new AccessDeniedException("Access to resource denied.");
}
}
private List<Entity> makeEntityList(Iterable<Entity> items) {
List<Entity> myList = new ArrayList<Entity>();
for (Entity item : items) {
myList.add(item);
}
return myList;
}
@Override
public Iterable<EntityBody> get(Iterable<String> ids) {
NeutralQuery neutralQuery = new NeutralQuery();
neutralQuery.setOffset(0);
neutralQuery.setLimit(MAX_RESULT_SIZE);
this.addDefaultQueryParams(neutralQuery, collectionName);
return get(ids, neutralQuery);
}
@Override
public Iterable<EntityBody> get(Iterable<String> ids, NeutralQuery neutralQuery) {
if (!ids.iterator().hasNext()) {
return Collections.emptyList();
}
checkRights(readRight);
checkFieldAccess(neutralQuery);
NeutralCriteria securityCriteria = findAccessible(defn.getType());
List<String> allowed = (List<String>) securityCriteria.getValue();
List<String> idList = new ArrayList<String>();
for (String id : ids) {
idList.add(id);
}
if (!idList.isEmpty()) {
if (neutralQuery == null) {
neutralQuery = new NeutralQuery();
neutralQuery.setOffset(0);
neutralQuery.setLimit(MAX_RESULT_SIZE);
}
if (allowed.size() > 0) {
//add the security criteria
neutralQuery.addCriteria(securityCriteria);
}
//add the ids requested
neutralQuery.addCriteria(new NeutralCriteria("_id", "in", idList));
this.addDefaultQueryParams(neutralQuery, collectionName);
Iterable<Entity> entities = repo.findAll(collectionName, neutralQuery);
List<EntityBody> results = new ArrayList<EntityBody>();
for (Entity e : entities) {
results.add(makeEntityBody(e));
}
return results;
}
return Collections.emptyList();
}
@Override
public Iterable<EntityBody> list(NeutralQuery neutralQuery) {
checkRights(readRight);
checkFieldAccess(neutralQuery);
NeutralCriteria securityCriteria = findAccessible(defn.getType());
List<String> allowed = (List<String>) securityCriteria.getValue();
NeutralQuery localNeutralQuery = new NeutralQuery(neutralQuery);
if (readRight == Right.ANONYMOUS_ACCESS) {
debug("super list logic --> {} service allows anonymous access", collectionName);
} else if (allowed.isEmpty()) {
return Collections.emptyList();
} else if (allowed.size() < 0) {
debug("super list logic --> only true when using DefaultEntityContextResolver");
} else {
if (securityCriteria.getKey().equals("_id")) {
Set<String> ids = new HashSet<String>();
List<NeutralCriteria> criterias = neutralQuery.getCriteria();
for (NeutralCriteria criteria : criterias) {
if (criteria.getKey().equals("_id")) {
@SuppressWarnings("unchecked")
List<String> idList = (List<String>) criteria.getValue();
ids.addAll(idList);
}
}
if (!ids.isEmpty()) {
Set<String> allowedSet = new HashSet<String>(allowed);
ids.retainAll(allowedSet);
//update the security criteria to only include the needed ids
securityCriteria = new NeutralCriteria("_id", NeutralCriteria.CRITERIA_IN, new ArrayList<String>(ids));
}
}
}
if (allowed.size() > 0) {
//add the security criteria
localNeutralQuery.addCriteria(securityCriteria);
}
List<EntityBody> results = new ArrayList<EntityBody>();
this.addDefaultQueryParams(localNeutralQuery, collectionName);
Collection<Entity> entities = (Collection<Entity>) repo.findAll(collectionName, localNeutralQuery);
for (Entity entity : entities) {
results.add(makeEntityBody(entity));
}
if (results.isEmpty()) {
return noEntitiesFound(neutralQuery);
}
return results;
}
@Override
public boolean exists(String id) {
checkRights(readRight);
boolean exists = false;
NeutralQuery query = new NeutralQuery();
query.addCriteria(new NeutralCriteria("_id", "=", id));
this.addDefaultQueryParams(query, collectionName);
if (repo.findAll(collectionName, query) != null) {
exists = true;
}
return exists;
}
/**
* TODO: refactor clientId, entityId out of body into root of mongo document
* TODO: entity collection should be per application
*/
@Override
public EntityBody getCustom(String id) {
checkAccess(readRight, id);
String clientId = getClientId();
debug("Reading custom entity: entity={}, entityId={}, clientId={}", new String[] {
getEntityDefinition().getType(), id, clientId });
NeutralQuery query = new NeutralQuery();
query.addCriteria(new NeutralCriteria("metaData." + CUSTOM_ENTITY_CLIENT_ID, "=", clientId, false));
query.addCriteria(new NeutralCriteria("metaData." + CUSTOM_ENTITY_ENTITY_ID, "=", id, false));
this.addDefaultQueryParams(query, collectionName);
Entity entity = getRepo().findOne(CUSTOM_ENTITY_COLLECTION, query);
if (entity != null) {
EntityBody clonedBody = new EntityBody(entity.getBody());
return clonedBody;
} else {
return null;
}
}
/**
* TODO: refactor clientId, entityId out of body into root of mongo document
* TODO: entity collection should be per application
*/
@Override
public void deleteCustom(String id) {
checkAccess(writeRight, id);
String clientId = getClientId();
NeutralQuery query = new NeutralQuery();
query.addCriteria(new NeutralCriteria("metaData." + CUSTOM_ENTITY_CLIENT_ID, "=", clientId, false));
query.addCriteria(new NeutralCriteria("metaData." + CUSTOM_ENTITY_ENTITY_ID, "=", id, false));
this.addDefaultQueryParams(query, collectionName);
Entity entity = getRepo().findOne(CUSTOM_ENTITY_COLLECTION, query);
if (entity == null) {
throw new EntityNotFoundException(id);
}
boolean deleted = getRepo().delete(CUSTOM_ENTITY_COLLECTION, entity.getEntityId());
debug("Deleting custom entity: entity={}, entityId={}, clientId={}, deleted?={}", new String[] {
getEntityDefinition().getType(), id, clientId, String.valueOf(deleted) });
}
/**
* TODO: refactor clientId, entityId out of body into root of mongo document
* TODO: entity collection should be per application
*/
@Override
public void createOrUpdateCustom(String id, EntityBody customEntity) {
checkAccess(writeRight, id);
String clientId = getClientId();
NeutralQuery query = new NeutralQuery();
query.addCriteria(new NeutralCriteria("metaData." + CUSTOM_ENTITY_CLIENT_ID, "=", clientId, false));
query.addCriteria(new NeutralCriteria("metaData." + CUSTOM_ENTITY_ENTITY_ID, "=", id, false));
this.addDefaultQueryParams(query, collectionName);
Entity entity = getRepo().findOne(CUSTOM_ENTITY_COLLECTION, query);
if (entity != null && entity.getBody().equals(customEntity)) {
debug("No change detected to custom entity, ignoring update: entity={}, entityId={}, clientId={}",
new String[]{ getEntityDefinition().getType(), id, clientId });
return;
}
EntityBody clonedEntity = new EntityBody(customEntity);
if (entity != null) {
debug("Overwriting existing custom entity: entity={}, entityId={}, clientId={}", new String[]{
getEntityDefinition().getType(), id, clientId });
entity.getBody().clear();
entity.getBody().putAll(clonedEntity);
getRepo().update(CUSTOM_ENTITY_COLLECTION, entity);
} else {
debug("Creating new custom entity: entity={}, entityId={}, clientId={}", new String[]{
getEntityDefinition().getType(), id, clientId });
EntityBody metaData = new EntityBody();
Map<String, Object> metadata = new HashMap<String, Object>();
SLIPrincipal principal = (SLIPrincipal) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
metaData.put(CUSTOM_ENTITY_CLIENT_ID, clientId);
metaData.put(CUSTOM_ENTITY_ENTITY_ID, id);
metaData.put("tenantId", principal.getTenantId());
getRepo().create(CUSTOM_ENTITY_COLLECTION, clonedEntity, metaData, CUSTOM_ENTITY_COLLECTION);
}
}
//DE719 -- Need to fix this method
private void checkReferences(EntityBody eb) {
for (Map.Entry<String, Object> entry : eb.entrySet()) {
String fieldName = entry.getKey();
Object value = entry.getValue();
if (value == null) {
continue;
}
String fieldPath = fieldName;
String entityType = provider.getReferencingEntity(defn.getType(), fieldPath);
if (entityType != null) {
debug("Field {} is referencing {}", fieldPath, entityType);
SLIPrincipal principal = (SLIPrincipal) SecurityContextHolder.getContext().getAuthentication()
.getPrincipal();
EntityContextResolver resolver = contextResolverStore.findResolver(principal.getEntity().getType(),
entityType);
List<String> accessible = resolver.findAccessible(principal.getEntity());
if (!principal.getEntity().getType().equals(EntityNames.STAFF)) {
if (value instanceof List) {
List<String> valuesList = (List<String>) value;
for (String cur : valuesList) {
NeutralQuery neutralQuery = new NeutralQuery();
neutralQuery.addCriteria(new NeutralCriteria("_id", "=", cur));
// this.addDefaultQueryParams(neutralQuery, entityType);
Entity entity = getRepo().findOne(entityType, neutralQuery);
if (!accessible.contains(cur) && entity != null) {
debug("{} in {} is not accessible", value, entityType);
throw new AccessDeniedException(
"Cannot create an association to an entity you don't have access to");
}
}
} else {
NeutralQuery neutralQuery = new NeutralQuery();
neutralQuery.addCriteria(new NeutralCriteria("_id", "=", (String) value));
// this.addDefaultQueryParams(neutralQuery, entityType);
Entity entity = getRepo().findOne(entityType, neutralQuery);
if (value != null && !accessible.contains(value) && entity != null) {
debug("{} in {} is not accessible", value, entityType);
throw new AccessDeniedException(
"Cannot create an association to an entity you don't have access to");
}
}
} else {
//need to refactor this again when we have time
//working on a P1 on the due date is not the time to do it
if (value instanceof List) {
List<String> valuesList = (List<String>) value;
for (String cur : valuesList) {
NeutralQuery neutralQuery = new NeutralQuery();
neutralQuery.addCriteria(new NeutralCriteria("_id", "=", cur));
// this.addDefaultQueryParams(neutralQuery, entityType);
Entity entity = getRepo().findOne(entityType, neutralQuery);
if (!isEntityAllowed(cur, entityType, entityType) && entity != null) {
debug("{} in {} is not accessible", value, entityType);
throw new AccessDeniedException(
"Cannot create an association to an entity you don't have access to");
}
}
} else {
NeutralQuery neutralQuery = new NeutralQuery();
neutralQuery.addCriteria(new NeutralCriteria("_id", "=", (String) value));
// this.addDefaultQueryParams(neutralQuery, entityType);
Entity entity = getRepo().findOne(entityType, neutralQuery);
if (!isEntityAllowed((String) value, entityType, entityType) && entity != null) {
debug("{} in {} is not accessible", value, entityType);
throw new AccessDeniedException(
"Cannot create an association to an entity you don't have access to");
}
}
}
}
}
}
private String getClientId() {
String clientId = clientInfo.getClientId();
if (clientId == null) {
throw new AccessDeniedException("No Application Id");
}
return clientId;
}
/**
* given an entity, make the entity body to expose
*
* @param entity
* @return
*/
private EntityBody makeEntityBody(Entity entity) {
EntityBody toReturn = new EntityBody(entity.getBody());
for (Treatment treatment : treatments) {
toReturn = treatment.toExposed(toReturn, defn, entity);
}
if (readRight != Right.ANONYMOUS_ACCESS) {
// Blank out fields inaccessible to the user
filterFields(toReturn);
}
return toReturn;
}
/**
* given an entity body that was exposed, return the version with the treatments reversed
*
* @param content
* @return
*/
private EntityBody sanitizeEntityBody(EntityBody content) {
EntityBody sanitized = new EntityBody(content);
for (Treatment treatment : treatments) {
sanitized = treatment.toStored(sanitized, defn);
}
return sanitized;
}
/**
* Deletes any object with a reference to the given sourceId. Assumes that the sourceId
* still exists so that authorization/context can be checked.
*
* @param sourceId ID that was deleted, where anything else with that ID should also be deleted
*/
private void cascadeDelete(String sourceId) {
// loop for every EntityDefinition that references the deleted entity's type
for (EntityDefinition referencingEntity : defn.getReferencingEntities()) {
// loop for every reference field that COULD reference the deleted ID
for (String referenceField : referencingEntity.getReferenceFieldNames(defn.getStoredCollectionName())) {
EntityService referencingEntityService = referencingEntity.getService();
NeutralQuery neutralQuery = new NeutralQuery();
neutralQuery.addCriteria(new NeutralCriteria(referenceField + "=" + sourceId));
this.addDefaultQueryParams(neutralQuery, collectionName);
try {
// list all entities that have the deleted entity's ID in their reference field
for (EntityBody entityBody : referencingEntityService.list(neutralQuery)) {
String idToBeDeleted = (String) entityBody.get("id");
// delete that entity as well
referencingEntityService.delete(idToBeDeleted);
// delete custom entities attached to this entity
deleteAttachedCustomEntities(idToBeDeleted);
}
} catch (AccessDeniedException ade) {
debug("No {} have {}={}", new Object[]{ referencingEntity.getResourceName(), referenceField,
sourceId });
}
}
}
}
private void deleteAttachedCustomEntities(String sourceId) {
NeutralQuery query = new NeutralQuery();
query.addCriteria(new NeutralCriteria("metaData." + CUSTOM_ENTITY_ENTITY_ID, "=", sourceId, false));
this.addDefaultQueryParams(query, collectionName);
Iterable<String> ids = getRepo().findAllIds(CUSTOM_ENTITY_COLLECTION, query);
for (String id : ids) {
getRepo().delete(CUSTOM_ENTITY_COLLECTION, id);
}
}
/**
* Checks that Actor has the appropriate Rights and linkage to access given entity
* Also checks for existence of the given entity
*
* @param right needed Right for action
* @param entityId id of the entity to access
* @throws EntityNotFoundException if requested entity doesn't exist
* @throws AccessDeniedException if actor doesn't have association path to given entity
*/
private void checkAccess(Right right, String entityId) {
// Check that user has the needed right
checkRights(right);
// Check that target entity actually exists
if (repo.findById(collectionName, entityId) == null) {
warn("Could not find {}", entityId);
throw new EntityNotFoundException(entityId);
}
if (right != Right.ANONYMOUS_ACCESS) {
// Check that target entity is accessible to the actor
if (entityId != null && !isEntityAllowed(entityId, collectionName, defn.getType())) {
throw new AccessDeniedException("No association between the user and target entity");
}
}
}
/**
* Checks to see if the entity id is allowed by security
* @param entityId The id to check
* @return
*/
//DE719 - Need to check this one
private boolean isEntityAllowed(String entityId, String collectionName, String toType) {
NeutralCriteria securityCriteria = findAccessible(toType);
List<String> allowed = (List<String>) securityCriteria.getValue();
if (securityCriteria.getKey().equals("_id")) {
return allowed.contains(entityId);
} else {
NeutralQuery query = new NeutralQuery();
//account for super list
if (allowed.size() > 0) {
query.addCriteria(securityCriteria);
}
query.addCriteria(new NeutralCriteria("_id", NeutralCriteria.CRITERIA_IN, Arrays.asList(entityId)));
this.addDefaultQueryParams(query, collectionName);
Entity entity = repo.findOne(collectionName, query);
return (entity != null);
}
}
private void checkRights(Right neededRight) {
// anonymous access is always granted
if (neededRight == Right.ANONYMOUS_ACCESS) {
return;
}
if (ADMIN_SPHERE.equals(provider.getDataSphere(defn.getType()))) {
neededRight = Right.ADMIN_ACCESS;
}
if (PUBLIC_SPHERE.equals(provider.getDataSphere(defn.getType()))) {
if (Right.READ_GENERAL.equals(neededRight)) {
neededRight = Right.READ_PUBLIC;
}
}
Collection<GrantedAuthority> auths = getAuths();
if (auths.contains(Right.FULL_ACCESS)) {
debug("User has full access");
} else if (auths.contains(neededRight)) {
debug("User has needed right: {}", neededRight);
} else {
throw new AccessDeniedException("Insufficient Privileges");
}
}
private Collection<GrantedAuthority> getAuths() {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if (readRight != Right.ANONYMOUS_ACCESS) {
SecurityUtil.ensureAuthenticated();
}
return auth.getAuthorities();
}
private NeutralCriteria findAccessible(String toType) {
String securityField = "_id";
SLIPrincipal principal = (SLIPrincipal) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
if (principal == null) {
throw new AccessDeniedException("Principal cannot be found");
}
Entity entity = principal.getEntity();
String type = entity != null ? entity.getType() : null; // null for super admins because
// they don't contain mongo
// entries
if (isPublic()) {
return new NeutralCriteria(securityField, NeutralCriteria.CRITERIA_IN, AllowAllEntityContextResolver.SUPER_LIST);
}
EntityContextResolver resolver = contextResolverStore.findResolver(type, toType);
List<String> allowed = resolver.findAccessible(principal.getEntity());
if (type != null && type.equals(EntityNames.STAFF) &&
!((toType.equals(EntityNames.SCHOOL)) || (toType.equals(EntityNames.EDUCATION_ORGANIZATION)))) {
securityField = "metaData.edOrgs";
}
NeutralCriteria securityCriteria = new NeutralCriteria(securityField, NeutralCriteria.CRITERIA_IN, allowed, false);
return securityCriteria;
}
private boolean isPublic() {
if (getAuths().contains(Right.FULL_ACCESS)) {
return getAuths().contains(Right.FULL_ACCESS);
} else {
return (defn.getType().equals(EntityNames.LEARNINGOBJECTIVE) || defn.getType().equals(
EntityNames.LEARNINGSTANDARD));
}
}
/**
* Removes fields user isn't entitled to see
*
* @param eb
*/
@SuppressWarnings("unchecked")
private void filterFields(Map<String, Object> eb) {
filterFields(eb, "");
complexFilter(eb);
}
private void complexFilter(Map<String, Object> eb) {
Collection<GrantedAuthority> auths = SecurityContextHolder.getContext().getAuthentication().getAuthorities();
if (!auths.contains(Right.READ_RESTRICTED) && defn.getType().equals(EntityNames.STAFF)) {
final String work = "Work";
final String telephoneNumberType = "telephoneNumberType";
final String emailAddressType = "emailAddressType";
final String telephone = "telephone";
final String electronicMail = "electronicMail";
List<Map<String, Object>> telephones = (List<Map<String, Object>>) eb.get(telephone);
if (telephones != null) {
for (Iterator<Map<String, Object>> it = telephones.iterator(); it.hasNext(); ) {
if (!work.equals(it.next().get(telephoneNumberType))) {
it.remove();
}
}
}
List<Map<String, Object>> emails = (List<Map<String, Object>>) eb.get(electronicMail);
if (emails != null) {
for (Iterator<Map<String, Object>> it = emails.iterator(); it.hasNext(); ) {
if (!work.equals(it.next().get(emailAddressType))) {
it.remove();
}
}
}
}
}
/**
* Removes fields user isn't entitled to see
*
* @param eb
*/
@SuppressWarnings("unchecked")
private void filterFields(Map<String, Object> eb, String prefix) {
Collection<GrantedAuthority> auths = SecurityContextHolder.getContext().getAuthentication().getAuthorities();
if (!auths.contains(Right.FULL_ACCESS)) {
List<String> toRemove = new LinkedList<String>();
for (Map.Entry<String, Object> entry : eb.entrySet()) {
String fieldName = entry.getKey();
Object value = entry.getValue();
String fieldPath = prefix + fieldName;
Right neededRight = getNeededRight(fieldPath);
debug("Field {} requires {}", fieldPath, neededRight);
SLIPrincipal principal = (SLIPrincipal) SecurityContextHolder.getContext().getAuthentication()
.getPrincipal();
if (!auths.contains(neededRight) && !principal.getEntity().getEntityId().equals(eb.get("id"))) {
toRemove.add(fieldName);
} else if (value instanceof Map) {
filterFields((Map<String, Object>) value, prefix + "." + fieldName + ".");
}
}
for (String fieldName : toRemove) {
eb.remove(fieldName);
}
}
}
/**
* Returns the needed right for a field by examining the schema
*
* @param fieldPath The field name
* @return
*/
protected Right getNeededRight(String fieldPath) {
Right neededRight = provider.getRequiredReadLevel(defn.getType(), fieldPath);
if (ADMIN_SPHERE.equals(provider.getDataSphere(defn.getType()))) {
neededRight = Right.ADMIN_ACCESS;
}
if (PUBLIC_SPHERE.equals(provider.getDataSphere(defn.getType()))) {
if (Right.READ_GENERAL.equals(neededRight)) {
neededRight = Right.READ_PUBLIC;
}
}
return neededRight;
}
/**
* Checks query params for access restrictions
*
* @param query The query to check
*/
protected void checkFieldAccess(NeutralQuery query) {
if (query != null) {
// get the authorities
Collection<GrantedAuthority> auths = SecurityContextHolder.getContext().getAuthentication()
.getAuthorities();
if (!auths.contains(Right.FULL_ACCESS) && !auths.contains(Right.ANONYMOUS_ACCESS)) {
for (NeutralCriteria criteria : query.getCriteria()) {
// get the needed right for the field
Right neededRight = getNeededRight(criteria.getKey());
if (!auths.contains(neededRight)) {
throw new QueryParseException("Cannot search on restricted field", criteria.getKey());
}
}
}
}
}
/**
* Figures out if writing to restricted fields
*
* @param eb data currently being passed in
* @return WRITE_RESTRICTED if restricted fields are being written, WRITE_GENERAL otherwise
*/
@SuppressWarnings("unchecked")
private Right determineWriteAccess(Map<String, Object> eb, String prefix) {
Right toReturn = Right.WRITE_GENERAL;
if (ADMIN_SPHERE.equals(provider.getDataSphere(defn.getType()))) {
toReturn = Right.ADMIN_ACCESS;
} else {
for (Map.Entry<String, Object> entry : eb.entrySet()) {
String fieldName = entry.getKey();
Object value = entry.getValue();
if (value instanceof Map) {
filterFields((Map<String, Object>) value, prefix + "." + fieldName + ".");
} else {
String fieldPath = prefix + fieldName;
Right neededRight = provider.getRequiredReadLevel(defn.getType(), fieldPath);
debug("Field {} requires {}", fieldPath, neededRight);
if (neededRight == Right.WRITE_RESTRICTED) {
toReturn = Right.WRITE_RESTRICTED;
break;
}
}
}
}
return toReturn;
}
/**
* Creates the metaData HashMap to be added to the entity created in mongo.
*
* @return Map containing important metadata for the created entity.
*/
private Map<String, Object> createMetadata() {
Map<String, Object> metadata = new HashMap<String, Object>();
SLIPrincipal principal = (SLIPrincipal) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
String createdBy = principal.getEntity().getEntityId();
if (createdBy != null && createdBy.equals("-133")) {
createdBy = principal.getExternalId();
}
metadata.put("isOrphaned", "true");
metadata.put("createdBy", createdBy);
metadata.put("tenantId", principal.getTenantId());
//add the edorgs for staff
createEdOrgMetaDataForStaff(principal, metadata);
return metadata;
}
/**
* Add the list of ed orgs a principal entity can see
* Needed for staff security
* @param principal
* @param metaData
*/
//DE-719 - need to check this one
private void createEdOrgMetaDataForStaff(SLIPrincipal principal, Map<String, Object> metaData) {
//get all the edorgs this principal can see
List<String> edOrgIds = edOrgContextResolver.findAccessible(principal.getEntity());
if (!edOrgIds.isEmpty()) {
debug("Updating metadData with edOrg ids");
metaData.put("edOrgs", edOrgIds);
}
}
/**
* Set the entity definition for this service.
* There is a circular dependency between BasicService and EntityDefinition, so they both can't
* have it be a constructor arg.
*/
public void setDefn(EntityDefinition defn) {
this.defn = defn;
}
@Override
public EntityDefinition getEntityDefinition() {
return defn;
}
protected String getCollectionName() {
return collectionName;
}
protected List<Treatment> getTreatments() {
return treatments;
}
protected Repository<Entity> getRepo() {
return repo;
}
protected void setClientInfo(CallingApplicationInfoProvider clientInfo) {
this.clientInfo = clientInfo;
}
}
|
package com.thaiopensource.relaxng.impl;
import com.thaiopensource.xml.util.Name;
import com.thaiopensource.relaxng.match.Matcher;
import com.thaiopensource.util.Equal;
import java.util.Vector;
import java.util.Hashtable;
import org.relaxng.datatype.ValidationContext;
public class PatternMatcher implements Cloneable, Matcher {
static private class Shared {
private final Pattern start;
private final ValidatorPatternBuilder builder;
private Hashtable recoverPatternTable;
Shared(Pattern start, ValidatorPatternBuilder builder) {
this.start = start;
this.builder = builder;
}
Pattern findElement(Name name) {
if (recoverPatternTable == null)
recoverPatternTable = new Hashtable();
Pattern p = (Pattern)recoverPatternTable.get(name);
if (p == null) {
p = FindElementFunction.findElement(builder, name, start);
recoverPatternTable.put(name, p);
}
return p;
}
PatternMemo fixAfter(PatternMemo p) {
return builder.getPatternMemo(p.getPattern().applyForPattern(new ApplyAfterFunction(builder) {
Pattern apply(Pattern p) {
return builder.makeEmpty();
}
}));
}
}
private PatternMemo memo;
private boolean textTyped;
private boolean hadError;
private boolean ignoreNextEndTag;
private String errorMessage;
private final Shared shared;
PatternMatcher(Pattern start, ValidatorPatternBuilder builder) {
shared = new Shared(start, builder);
memo = builder.getPatternMemo(start);
}
public boolean equals(Object obj) {
PatternMatcher other = (PatternMatcher)obj;
if (other == null)
return false;
return (memo == other.memo
&& hadError == other.hadError
&& Equal.equal(errorMessage, other.errorMessage)
&& ignoreNextEndTag == other.ignoreNextEndTag
&& textTyped == other.textTyped);
}
public int hashCode() {
return memo.hashCode();
}
public Object clone() {
try {
return super.clone();
}
catch (CloneNotSupportedException e) {
throw new Error("unexpected CloneNotSupportedException");
}
}
public Matcher copy() {
return (Matcher)clone();
}
public boolean matchStartDocument() {
if (memo.isNotAllowed())
return error("schema_allows_nothing");
return true;
}
public boolean matchStartTagOpen(Name name) {
if (setMemo(memo.startTagOpenDeriv(name)))
return true;
PatternMemo next = memo.startTagOpenRecoverDeriv(name);
if (!next.isNotAllowed()) {
memo = next;
return error("required_elements_missing");
}
ValidatorPatternBuilder builder = shared.builder;
next = builder.getPatternMemo(builder.makeAfter(shared.findElement(name), memo.getPattern()));
memo = next;
return error(next.isNotAllowed() ? "unknown_element" : "out_of_context_element", name);
}
public boolean matchAttributeName(Name name) {
if (setMemo(memo.startAttributeDeriv(name)))
return true;
ignoreNextEndTag = true;
return error("impossible_attribute_ignored", name);
}
public boolean matchAttributeValue(String value, ValidationContext vc) {
if (ignoreNextEndTag) {
ignoreNextEndTag = false;
return true;
}
if (setMemo(memo.dataDeriv(value, vc)))
return true;
memo = memo.recoverAfter();
return error("bad_attribute_value_no_name"); // XXX add to catalog
}
public boolean matchStartTagClose() {
boolean ret;
if (setMemo(memo.endAttributes()))
ret = true;
else {
memo = memo.ignoreMissingAttributes();
// XXX should specify which attributes
ret = error("required_attributes_missing");
}
textTyped = memo.getPattern().getContentType() == Pattern.DATA_CONTENT_TYPE;
return ret;
}
public boolean matchText(String string, ValidationContext vc, boolean nextTagIsEndTag) {
if (textTyped && nextTagIsEndTag) {
ignoreNextEndTag = true;
return setDataDeriv(string, vc);
}
else {
if (DataDerivFunction.isBlank(string))
return true;
return matchUntypedText();
}
}
public boolean matchUntypedText() {
if (setMemo(memo.mixedTextDeriv()))
return true;
return error("text_not_allowed");
}
public boolean isTextTyped() {
return textTyped;
}
private boolean setDataDeriv(String string, ValidationContext vc) {
textTyped = false;
if (!setMemo(memo.textOnly())) {
memo = memo.recoverAfter();
return error("only_text_not_allowed");
}
if (setMemo(memo.dataDeriv(string, vc))) {
ignoreNextEndTag = true;
return true;
}
PatternMemo next = memo.recoverAfter();
boolean ret = true;
if (!memo.isNotAllowed()) {
if (!next.isNotAllowed()
|| shared.fixAfter(memo).dataDeriv(string, vc).isNotAllowed())
ret = error("string_not_allowed");
}
memo = next;
return ret;
}
public boolean matchEndTag(ValidationContext vc) {
// The tricky thing here is that the derivative that we compute may be notAllowed simply because the parent
// is notAllowed; we don't want to give an error in this case.
if (ignoreNextEndTag) {
ignoreNextEndTag = false;
return true;
}
if (textTyped)
return setDataDeriv("", vc);
textTyped = false;
if (setMemo(memo.endTagDeriv()))
return true;
PatternMemo next = memo.recoverAfter();
if (memo.isNotAllowed()) {
if (!next.isNotAllowed()
|| shared.fixAfter(memo).endTagDeriv().isNotAllowed()) {
memo = next;
return error("unfinished_element");
}
}
memo = next;
return true;
}
public String getErrorMessage() {
return errorMessage;
}
public boolean isValidSoFar() {
return !hadError;
}
// members are of type Name
public Vector possibleStartTags() {
// XXX
return null;
}
public Vector possibleAttributes() {
// XXX
return null;
}
private boolean setMemo(PatternMemo m) {
if (m.isNotAllowed())
return false;
else {
memo = m;
return true;
}
}
private boolean error(String key) {
if (hadError && memo.isNotAllowed())
return true;
hadError = true;
errorMessage = SchemaBuilderImpl.localizer.message(key);
return false;
}
private boolean error(String key, Name arg) {
return error(key, NameFormatter.format(arg));
}
private boolean error(String key, String arg) {
if (hadError && memo.isNotAllowed())
return true;
hadError = true;
errorMessage = SchemaBuilderImpl.localizer.message(key, arg);
return false;
}
}
|
package com.sonar.it.scanner.msbuild;
import com.sonar.orchestrator.Orchestrator;
import com.sonar.orchestrator.build.BuildResult;
import com.sonar.orchestrator.build.ScannerForMSBuild;
import com.sonar.orchestrator.config.Configuration;
import com.sonar.orchestrator.locator.FileLocation;
import com.sonar.orchestrator.util.Command;
import com.sonar.orchestrator.util.CommandExecutor;
import com.sonar.orchestrator.util.StreamConsumer;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.annotation.CheckForNull;
import org.apache.commons.io.FileUtils;
import org.junit.rules.TemporaryFolder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static org.assertj.core.api.Assertions.assertThat;
public class TestUtils {
private final static Logger LOG = LoggerFactory.getLogger(ScannerMSBuildTest.class);
@CheckForNull
public static String getScannerVersion() {
Configuration configuration = Orchestrator.builderEnv().build().getConfiguration();
return configuration.getString("scannerForMSBuild.version");
}
public static ScannerForMSBuild newScanner(Path projectDir) {
String scannerVersion = getScannerVersion();
if (scannerVersion != null) {
LOG.info("Using Scanner for MSBuild " + scannerVersion);
return ScannerForMSBuild.create(projectDir.toFile())
.setScannerVersion(scannerVersion);
} else {
// run locally
LOG.info("Using Scanner for MSBuild from the local build");
Path scannerZip = Paths.get("../DeploymentArtifacts/BuildAgentPayload/Release/SonarQube.Scanner.MSBuild.zip");
return ScannerForMSBuild.create(projectDir.toFile())
.setScannerLocation(FileLocation.of(scannerZip.toFile()));
}
}
public static Path getCustomRoslynPlugin() {
Path customPluginDir = Paths.get("").resolve("analyzers");
DirectoryStream.Filter<Path> jarFilter = file -> Files.isRegularFile(file) && file.toString().endsWith(".jar");
List<Path> jars = new ArrayList<>();
try {
Files.newDirectoryStream(customPluginDir, jarFilter).forEach(jars::add);
} catch (IOException e) {
throw new IllegalStateException(e);
}
if (jars.isEmpty()) {
throw new IllegalStateException("No jars found in " + customPluginDir.toString());
} else if (jars.size() > 1) {
throw new IllegalStateException("Several jars found in " + customPluginDir.toString());
}
return jars.get(0);
}
public static Path projectDir(TemporaryFolder temp, String projectName) throws IOException {
Path projectDir = Paths.get("projects").resolve(projectName);
FileUtils.deleteDirectory(new File(temp.getRoot(), projectName));
Path tmpProjectDir = Paths.get(temp.newFolder(projectName).getCanonicalPath());
FileUtils.copyDirectory(projectDir.toFile(), tmpProjectDir.toFile());
return tmpProjectDir;
}
public static void runMSBuildWithBuildWrapper(Orchestrator orch, Path projectDir, File buildWrapperPath, File outDir,
String... arguments) {
Path msBuildPath = getMsBuildPath(orch);
int r = CommandExecutor.create().execute(Command.create(buildWrapperPath.toString())
.addArgument("--out-dir")
.addArgument(outDir.toString())
.addArgument(msBuildPath.toString())
.addArguments(arguments)
.setDirectory(projectDir.toFile()), 60 * 1000);
assertThat(r).isEqualTo(0);
}
public static void runMSBuild(Orchestrator orch, Path projectDir, String... arguments) {
BuildResult r = runMSBuildQuietly(orch, projectDir, arguments);
assertThat(r.isSuccess()).isTrue();
}
private static BuildResult runMSBuildQuietly(Orchestrator orch, Path projectDir, String... arguments) {
Path msBuildPath = getMsBuildPath(orch);
BuildResult result = new BuildResult();
StreamConsumer.Pipe writer = new StreamConsumer.Pipe(result.getLogsWriter());
int status = CommandExecutor.create().execute(Command.create(msBuildPath.toString())
.addArguments(arguments)
.setDirectory(projectDir.toFile()), writer, 60 * 1000);
result.addStatus(status);
return result;
}
private static Path getMsBuildPath(Orchestrator orch) {
String msBuildPathStr = orch.getConfiguration().getString("msbuild.path",
orch.getConfiguration().getString("MSBUILD_PATH", "C:\\Program Files (x86)\\Microsoft Visual "
+ "Studio\\2017\\Enterprise\\MSBuild\\15.0\\Bin\\MSBuild.exe"));
Path msBuildPath = Paths.get(msBuildPathStr).toAbsolutePath();
if (!Files.exists(msBuildPath)) {
throw new IllegalStateException("Unable to find MSBuild at " + msBuildPath.toString()
+ ". Please configure property 'msbuild.path' or 'MSBUILD_PATH'.");
}
return msBuildPath;
}
}
|
package com.worizon.jsonrpc.annotations;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.PARAMETER})
public @interface RemoteProcName {
String value();
}
|
package commandParsing.turtleCommandParsing;
import java.util.Iterator;
import java.util.List;
import java.util.Queue;
import workspaceState.Location;
import workspaceState.Turtle;
import workspaceState.WorkspaceState;
import commandParsing.CommandParser;
import commandParsing.drawableObectGenerationInterfaces.TurtleGenerator;
import commandParsing.exceptions.RunTimeDivideByZeroException;
import commandParsing.exceptions.SLOGOException;
import drawableobject.DrawableObject;
public class MakeTurtle extends CommandParser implements TurtleGenerator {
public MakeTurtle(WorkspaceState someWorkspace) {
super(someWorkspace);
}
@Override
public double parse(Iterator<String> commandString, Queue<DrawableObject> objectQueue)
throws SLOGOException {
Turtle newTurtle = new Turtle();
workspace.turtles.addTurtle(newTurtle);
objectQueue.add(generateDrawableObjectRepresentingTurtle(newTurtle));
return 0;
}
}
|
package edu.uib.info310.search;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import edu.uib.info310.transformation.XslTransformer;
@Component
public class LastFMSearch {
private static final String similarArtistRequest = "http://ws.audioscrobbler.com/2.0/?method=artist.getsimilar&artist=";
private static final String artistEvents = "http://ws.audioscrobbler.com/2.0/?method=artist.getevents&artist=";
private static final String artistCorrection = "http://ws.audioscrobbler.com/2.0/?method=artist.getcorrection&artist=";
private static final String apiKey = "&api_key=a7123248beb0bbcb90a2e3a9ced3bee9";
private static final Logger LOGGER = LoggerFactory.getLogger(LastFMSearch.class);
private InputStream artistCorrection(String search_string) throws ArtistNotFoundException {
InputStream in = null;
try{
URL lastFMRequest = new URL(artistCorrection + search_string + apiKey);
LOGGER.debug("LastFM correction request URL: " + lastFMRequest.toExternalForm());
URLConnection lastFMConnection = lastFMRequest.openConnection();
in = lastFMConnection.getInputStream();
} catch(IOException ioexc){
throw new ArtistNotFoundException("No correction found");
}
return in;
}
private Document docBuilder(String artist) throws ArtistNotFoundException {
DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
domFactory.setNamespaceAware(true);
Document doc = null;
String safe_search = "";
DocumentBuilder builder = null;
try {
builder = domFactory.newDocumentBuilder();
safe_search = URLEncoder.encode(artist, "UTF-8");
} catch (Exception e) {/*ignore*/}
try {
doc = builder.parse(artistCorrection(safe_search));
} catch (Exception a) {
throw new ArtistNotFoundException ("Doc couldn't be built");
}
LOGGER.debug("DOM object with " + artist + " as corrected by LastFM.");
return doc;
}
public String correctArtist(String artist) throws ArtistNotFoundException {
try{
Document correction = docBuilder(artist);
NodeList nameList = correction.getElementsByTagName("name");
Node nameNode = nameList.item(0);
Element element = (Element) nameNode;
NodeList name = element.getChildNodes();
LOGGER.debug("Get node value of correct artist: " + (name.item(0)).getNodeValue());
return (name.item(0)).getNodeValue();
}
catch (NullPointerException e) {
return artist;
}
}
public InputStream getArtistEvents (String artist) throws Exception {
String safeArtist = makeWebSafeString(artist);
URL lastFMRequest = new URL(artistEvents + safeArtist + apiKey);
URLConnection lastFMConnection = lastFMRequest.openConnection();
return lastFMConnection.getInputStream();
}
public InputStream getSimilarArtist(String artist) throws Exception {
String safeArtist = makeWebSafeString(artist);
URL lastFMRequest = new URL(similarArtistRequest + safeArtist + apiKey);
LOGGER.debug("LastFM request URL: " + lastFMRequest.toExternalForm());
URLConnection lastFMConnection = lastFMRequest.openConnection();
return lastFMConnection.getInputStream();
}
public static void main(String[] args) throws Exception {
File xsl = new File("src/main/resources/XSL/SimilarArtistLastFM.xsl");
LastFMSearch search = new LastFMSearch();
XslTransformer transform = new XslTransformer();
transform.setXml(search.getSimilarArtist("Iron & Wine"));
transform.setXsl(xsl);
File file = new File("log/rdf-artist.xml");
FileOutputStream fileOutputStream = new FileOutputStream(file);
transform.transform().writeTo(fileOutputStream);
// System.out.println(transform.transform());
System.out.println(search.correctArtist("ryksopp"));
}
public String makeWebSafeString(String unsafe){
try {
return URLEncoder.encode(unsafe, "UTF-8");
} catch (UnsupportedEncodingException e) {
return unsafe;
}
}
}
|
package edu.uib.info310.search;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import javax.xml.transform.TransformerException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Component;
import com.hp.hpl.jena.query.Query;
import com.hp.hpl.jena.query.QueryExecution;
import com.hp.hpl.jena.query.QueryExecutionFactory;
import com.hp.hpl.jena.query.QueryFactory;
import com.hp.hpl.jena.query.QuerySolution;
import com.hp.hpl.jena.query.ResultSet;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.sparql.engine.http.QueryEngineHTTP;
import edu.uib.info310.model.Artist;
import edu.uib.info310.model.Event;
import edu.uib.info310.model.Record;
import edu.uib.info310.model.Track;
import edu.uib.info310.model.factory.ModelFactory;
import edu.uib.info310.model.factory.ModelFactoryImpl;
import edu.uib.info310.model.imp.RecordImp;
import edu.uib.info310.model.mock.MockRecord;
import edu.uib.info310.search.builder.OntologyBuilder;
@Component
public class SearcherImpl implements Searcher {
private static final Logger LOGGER = LoggerFactory.getLogger(SearcherImpl.class);
@Autowired
private OntologyBuilder builder;
@Autowired
private ModelFactory modelFactory;
@Autowired
private DiscogSearch discog;
private Model model;
private Artist artist;
private Record record;
public Artist searchArtist(String search_string) throws ArtistNotFoundException {
this.artist = modelFactory.createArtist();
this.model = builder.createArtistOntology(search_string);
LOGGER.debug("Size of infered model: " + model.size());
setArtistIdAndName();
setSimilarArtist();
setArtistEvents();
setArtistDiscography();
setArtistInfo();
return this.artist;
}
public List<Record> searchRecords(String albumName) {
List<Record> records= new LinkedList<Record>();
String safe_search = "";
try {
safe_search = URLEncoder.encode(albumName, "UTF-8");
} catch (UnsupportedEncodingException e) {/*ignore*/}
String prefix =
"PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns
"PREFIX dc: <http://purl.org/dc/elements/1.1/>" +
"PREFIX foaf: <http://xmlns.com/foaf/0.1/>" +
"PREFIX mo: <http://purl.org/ontology/mo/>" +
"PREFIX xsd: <http://www.w3.org/2001/XMLSchema
"PREFIX dc: <http://purl.org/dc/terms/>" +
"PREFIX rdfs:<http://www.w3.org/2000/01/rdf-schema
String albums = "SELECT ?artistName ?albumName ?year "+
" WHERE { ?record dc:title \""+ safe_search + "\" ;" +
"rdf:type mo:Record ;" +
"foaf:maker ?artist ;" +
"mo:discogs ?discogs ;" +
"dc:issued ?year ;" +
"dc:title ?albumName." +
"?artist foaf:name ?artistName}" +
"ORDER BY ?year";
Query query = QueryFactory.create(prefix + albums);
QueryEngineHTTP queryExecution = QueryExecutionFactory.createServiceRequest("http://api.kasabi.com/dataset/discogs/apis/sparql", query);
queryExecution.addParam("apikey", "fe29b8c58180640f6db16b9cd3bce37c872c2036");
ResultSet recordResults = queryExecution.execSelect();
while(recordResults.hasNext()){
List<Artist> artists = new LinkedList<Artist>();
Record record = modelFactory.createRecord();
QuerySolution querySol = recordResults.next();
record.setName(querySol.get("albumName").toString());
Artist artist = modelFactory.createArtist();
artist.setName(querySol.get("artistName").toString());
artists.add(artist);
record.setArtist(artists);
// Date date = this.makeDate(querySol.get("year").toString());
record.setYear(querySol.get("year").toString().substring(0,4));
// recordResult.setDiscogId(querySol.get("discogs").toString());
if(!records.contains(record)){
records.add(record);
}
}
return records;
}
private void setArtistIdAndName() {
String getIdStr = "PREFIX rdf:<http://www.w3.org/1999/02/22-rdf-syntax-ns
QueryExecution execution = QueryExecutionFactory.create(getIdStr, model);
ResultSet similarResults = execution.execSelect();
if(similarResults.hasNext()){
QuerySolution solution = similarResults.next();
this.artist.setId(solution.get("id").toString());
this.artist.setName(solution.get("name").toString());
}
LOGGER.debug("Artist id set to: " + this.artist.getId() + ", Artist name set to: " + this.artist.getName());
}
private void setArtistDiscography() {
List<Record> discog = new LinkedList<Record>();
Map<String,Record> uniqueRecord = new HashMap<String, Record>();
String getDiscographyStr = "PREFIX foaf: <http://xmlns.com/foaf/0.1/> " +
"PREFIX mo: <http://purl.org/ontology/mo/> " +
"PREFIX xsd: <http://www.w3.org/2001/XMLSchema
"PREFIX dc: <http://purl.org/dc/terms/> " +
"PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns
"SELECT DISTINCT " +
" ?artistId ?albumId ?release ?title ?image ?year ?labelId ?labelName ?track ?artist "+
" WHERE { " +
"?artistId foaf:made ?albumId. " +
"?albumId dc:title ?title." +
"OPTIONAL {?albumId mo:publisher ?labelId. } "+
"OPTIONAL {?albumId dc:issued ?year. }" +
"OPTIONAL {?albumId foaf:depiction ?image. }" +
"}";
LOGGER.debug("Search for albums for artist with name: " + this.artist.getName() + ", with query:" + getDiscographyStr);
QueryExecution execution = QueryExecutionFactory.create(getDiscographyStr, model);
ResultSet albums = execution.execSelect();
LOGGER.debug("Found records? " + albums.hasNext());
while(albums.hasNext()){
Record recordResult = modelFactory.createRecord();
QuerySolution queryAlbum = albums.next();
recordResult.setId(queryAlbum.get("albumId").toString());
recordResult.setName(queryAlbum.get("title").toString());
if(queryAlbum.get("image") != null) {
recordResult.setImage(queryAlbum.get("image").toString());
}
if(queryAlbum.get("year") != null) {
SimpleDateFormat format = new SimpleDateFormat("yyyy",Locale.US);
recordResult.setYear(format.format(makeDate(queryAlbum.get("year").toString())));
}
if(recordResult.getImage() != null){
uniqueRecord.put(recordResult.getName(), recordResult);
}
}
for(Record record : uniqueRecord.values()){
discog.add(record);
}
this.artist.setDiscography(discog);
LOGGER.debug("Found "+ artist.getDiscography().size() +" artist records");
}
private void setSimilarArtist() {
List<Artist> similar = new LinkedList<Artist>();
String similarStr = "PREFIX rdf:<http://www.w3.org/1999/02/22-rdf-syntax-ns
"PREFIX mo:<http://purl.org/ontology/mo/> " +
"PREFIX foaf:<http://xmlns.com/foaf/0.1/> " +
"SELECT ?name ?id ?image " +
" WHERE { <" + this.artist.getId() + "> mo:similar-to ?id . " +
"?id foaf:name ?name; " +
" mo:image ?image } ";
QueryExecution execution = QueryExecutionFactory.create(similarStr, model);
ResultSet similarResults = execution.execSelect();
while(similarResults.hasNext()){
Artist similarArtist = modelFactory.createArtist();
QuerySolution queryArtist = similarResults.next();
similarArtist.setName(queryArtist.get("name").toString());
similarArtist.setId(queryArtist.get("id").toString());
similarArtist.setImage(queryArtist.get("image").toString());
similar.add(similarArtist);
}
artist.setSimilar(similar);
LOGGER.debug("Found " + this.artist.getSimilar().size() +" similar artists");
}
private void setArtistEvents(){
List<Event> events = new LinkedList<Event>();
String getArtistEventsStr = " PREFIX foaf:<http://xmlns.com/foaf/0.1/> PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns
"SELECT ?venueId ?venueName ?date ?lng ?lat ?location ?preformance " +
" WHERE {?preformance foaf:hasAgent <" + this.artist.getId() + ">; event:place ?venueId; event:time ?date. ?venueId v:organisation-name ?venueName; geo:lat ?lat; geo:long ?lng; v:locality ?location}";
QueryExecution execution = QueryExecutionFactory.create(getArtistEventsStr, model);
ResultSet eventResults = execution.execSelect();
while(eventResults.hasNext()){
Event event = modelFactory.createEvent();
QuerySolution queryEvent = eventResults.next();
event.setId(queryEvent.get("venueId").toString());
event.setVenue(queryEvent.get("venueName").toString());
event.setLat(queryEvent.get("lat").toString());
event.setLng(queryEvent.get("lng").toString());
String dateString = queryEvent.get("date").toString();
Date date = new Date();
SimpleDateFormat stf = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss",Locale.US);
try {
date = stf.parse(dateString);
} catch (ParseException e) {
LOGGER.error("Couldnt parse date");
}
event.setDate(date);
event.setLocation(queryEvent.get("location").toString());
event.setWebsite(queryEvent.get("preformance").toString());
events.add(event);
}
this.artist.setEvents(events);
LOGGER.debug("Found "+ artist.getEvents().size() +" artist events");
}
private void setArtistInfo() {
String id = "<" + artist.getId() + ">";
LOGGER.debug("Artisturi " + artist.getName());
String getArtistInfoStr = "PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns
"PREFIX foaf: <http://xmlns.com/foaf/0.1/> " +
"PREFIX mo: <http://purl.org/ontology/mo/> " +
"PREFIX dbpedia: <http://dbpedia.org/property/> " +
"PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema
"PREFIX owl: <http://www.w3.org/2002/07/owl
"PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema
"PREFIX dbont: <http://dbpedia.org/ontology/> " +
"SELECT DISTINCT * WHERE {" +
"OPTIONAL { "+ id +" mo:fanpage ?sFanpage. BIND(str(?sFanpage) AS ?fanpage)} " +
"OPTIONAL { "+ id +" mo:imdb ?imdb. }" +
"OPTIONAL { "+ id +" foaf:name ?name. }" +
"OPTIONAL { "+ id +" mo:myspace ?myspace. } " +
"OPTIONAL { "+ id +" mo:homepage ?homepage. } " +
"OPTIONAL { "+ id +" rdfs:comment ?sShortDesc. BIND(str(?sShortDesc) AS ?shortDesc)} " +
"OPTIONAL { "+ id +" mo:image ?image}" +
"OPTIONAL { "+ id +" mo:biography ?sBio. BIND(str(?sBio) AS ?bio) } " +
"OPTIONAL { "+ id +" dbont:birthname ?birthname} " +
"OPTIONAL { "+ id +" dbont:hometown ?hometown. } " +
"OPTIONAL { "+ id +" mo:origin ?sOrigin. BIND(str(?sOrigin) AS ?origin)} " +
"OPTIONAL { "+ id +" mo:activity_start ?start. } " +
"OPTIONAL { "+ id +" mo:activity_end ?end. } " +
"OPTIONAL { "+ id +" dbont:birthDate ?birthdate. } " +
"OPTIONAL { "+ id +" dbont:deathDate ?deathdate. } " +
"OPTIONAL { "+ id +" mo:wikipedia ?wikipedia. } " +
"OPTIONAL { "+ id +" foaf:page ?bbcpage. }" +
"OPTIONAL { "+ id +" dbont:bandMember ?memberOf. ?memberOf rdfs:label ?sName1. BIND(str(?sName1) AS ?name1)}" +
"OPTIONAL { "+ id +" dbont:formerBandMember ?pastMemberOf. ?pastMemberOf rdfs:label ?sName2. BIND(str(?sName2) AS ?name2) }" +
"OPTIONAL { "+ id +" dbpedia:currentMembers ?currentMembers. ?currentMembers rdfs:label ?sName3. BIND(str(?sName3) AS ?name3) }" +
"OPTIONAL { "+ id +" dbpedia:pastMembers ?pastMembers. ?pastMembers rdfs:label ?sName4. BIND(str(?sName4) AS ?name4) }}" ;
QueryExecution ex = QueryExecutionFactory.create(getArtistInfoStr, model);
ResultSet results = ex.execSelect();
HashMap<String,Object> metaMap = new HashMap<String,Object>();
List<String> fanpages = new LinkedList<String>();
List<String> bands = new LinkedList<String>();
List<String> formerBands = new LinkedList<String>();
List<String> currentMembers = new LinkedList<String>();
List<String> pastMembers = new LinkedList<String>();
while(results.hasNext()) {
// TODO: optimize (e.g storing in variables instead of performing query.get several times?)
QuerySolution query = results.next();
if(query.get("name") != null){
LOGGER.debug("Artistname " + query.get("name").toString());
}
if(query.get("image") != null){
artist.setImage(query.get("image").toString());
}
if(query.get("fanpage") != null){
String fanpage = "<a href=\"" + query.get("fanpage").toString() + "\">" + query.get("fanpage").toString() + "</a>";
if(!fanpages.contains(fanpage)) {
fanpages.add(fanpage);
}
}
if(query.get("memberOf") != null){
String test2 = query.get("name1").toString();
String test = null;
try {
test = URLEncoder.encode(test2, "UTF-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String memberOf = "<a href=\"artist?q=" + test + "\">" + test2 + "</a>";
if(!bands.contains(memberOf)) {
bands.add(memberOf);
}
}
if(query.get("pastMemberOf") != null){
String test2 = query.get("name2").toString();
String test = null;
try {
test = URLEncoder.encode(test2, "UTF-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String pastMemberOf = "<a href=\"artist?q=" + test + "\">" + test2 + "</a>";
if(!formerBands.contains(pastMemberOf)) {
formerBands.add(pastMemberOf);
}
}
if(query.get("currentMembers") != null){
String test2 = query.get("name3").toString();
String test = null;
try {
test = URLEncoder.encode(test2, "UTF-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String currentMember = "<a href=\"artist?q=" + test + "\">" + test2 + "</a>";
if(!currentMembers.contains(currentMember)) {
currentMembers.add(currentMember);
}
}
if(query.get("pastMembers") != null){
String test2 = query.get("name4").toString();
String test = null;
try {
test = URLEncoder.encode(test2, "UTF-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String pastMember = "<a href=\"artist?q=" + test + "\">" + test2 + "</a>";
if(!pastMembers.contains(pastMember)) {
pastMembers.add(pastMember);
}
}
if(query.get("bio") != null) {
artist.setBio(query.get("bio").toString());
}
if(query.get("wikipedia") != null) {
metaMap.put("Wikipedia", ("<a href=\"" + query.get("wikipedia").toString() + "\">" + query.get("wikipedia").toString() + "</a>"));
}
if(query.get("bbcpage") != null) {
metaMap.put("BBC Music", ("<a href=\"" + query.get("bbcpage").toString() + "\">" + query.get("bbcpage").toString() + "</a>"));
}
if(query.get("birthdate") != null) {
SimpleDateFormat format = new SimpleDateFormat("EEE dd. MMM yyyy",Locale.US);
metaMap.put("Born", (format.format(makeDate(query.get("birthdate").toString()))));
}
if(query.get("homepage") != null) {
metaMap.put("Homepage", ("<a href=\"" + query.get("homepage").toString() + "\">" + query.get("homepage").toString() + "</a>"));
}
if(query.get("imdb") != null) {
metaMap.put("IMDB", ("<a href=\"" + query.get("imdb").toString() + "\">" + query.get("imdb").toString() + "</a>"));
}
if(query.get("myspace") != null) {
metaMap.put("MySpace", ("<a href=\"" + query.get("myspace").toString() + "\">" + query.get("myspace").toString() + "</a>"));
}
if(query.get("shortDesc") != null) {
artist.setShortDescription(query.get("shortDesc").toString());
}
if(query.get("birthname") != null) {
metaMap.put("Name", (query.get("birthname").toString()));
}
if(query.get("deathdate") != null) {
SimpleDateFormat format = new SimpleDateFormat("EEE dd. MMM yyyy",Locale.US);
metaMap.put("Died", (format.format(makeDate(query.get("deathdate").toString()))));
}
if(query.get("origin") != null) {
metaMap.put("From", (query.get("origin").toString()));
}
if(query.get("hometown") != null) {
metaMap.put("Living", (query.get("hometown").toString()));
}
if(query.get("start") != null) {
SimpleDateFormat format = new SimpleDateFormat("yyyy",Locale.US);
String activityStart = format.format(makeDate(query.get("start").toString()));
if(query.get("end") != null) {
activityStart += "-" + format.format(makeDate(query.get("end").toString()));
}
metaMap.put("Active",activityStart);
}
}
if(!fanpages.isEmpty()) {
metaMap.put("Fanpages", fanpages.toString());
}
if(!bands.isEmpty()) {
metaMap.put("Bandmembers", bands);
}
if(!formerBands.isEmpty()) {
metaMap.put("Former bandmembers", formerBands);
}
if(!currentMembers.isEmpty()) {
metaMap.put("Member of", currentMembers);
}
if(!pastMembers.isEmpty()) {
metaMap.put("Past member of", pastMembers);
}
artist.setMeta(metaMap);
LOGGER.debug("Found " + artist.getMeta().size() + " fun facts.");
}
public Event searchEvent(String search_string) {
// TODO Auto-generated method stub
return null;
}
public Record searchRecord(String record_name, String artist_name) throws MasterNotFoundException {
this.record = modelFactory.createRecord();
String release = discog.getRecordReleaseId(record_name, artist_name);
this.model = builder.createRecordOntology(release, record_name, artist_name);
try {
setRecordInfo(release);
} catch (MasterNotFoundException e) {
e.printStackTrace();
} catch (TransformerException e) {
e.printStackTrace();
}
return record;
}
public Track searchTrack(String search_string) {
// TODO Auto-generated method stub
return null;
}
public void setRecordInfo(String search_string) throws MasterNotFoundException, TransformerException{
String release = "<http://api.discogs.com/release/" + search_string + ">";
LOGGER.debug("This is the search_string "+ release);
String albumStr = "PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns
"PREFIX foaf: <http://xmlns.com/foaf/0.1/> " +
"PREFIX mo: <http://purl.org/ontology/mo/> " +
"PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema
"PREFIX dc: <http://purl.org/dc/terms/> " +
"PREFIX time: <http://www.w3.org/2006/time
"SELECT DISTINCT * WHERE { " + release + " foaf:name ?name;" +
"rdfs:comment ?comment;" +
"foaf:hasAgent ?artist;" +
"mo:genre ?genre;" +
"mo:catalogue_number ?catalogueNumber;" +
"mo:label ?publisher ;" +
"mo:image ?image ;" +
"dc:issued ?year." +
"?trackid foaf:name ?trackName;" +
"mo:track_number ?trackNumber;" +
"mo:preview ?preview; " +
"time:duration ?trackDuration." +
"}";
QueryExecution execution = QueryExecutionFactory.create(albumStr, model);
ResultSet albumResults = execution.execSelect();
HashMap<String,String> genre = new HashMap<String,String>();
HashMap<String,Object> meta = new HashMap<String,Object>();
HashMap<String, Track> tracks = new HashMap<String, Track>();
HashMap<String, Artist> artists = new HashMap<String, Artist>();
while(albumResults.hasNext()){
QuerySolution queryAlbum = albumResults.next();
// LOGGER.debug(queryAlbum.get("label").toString());
// LOGGER.debug(queryAlbum.get("comment").toString());
// LOGGER.debug(queryAlbum.get("genre").toString());
// LOGGER.debug(queryAlbum.get("year").toString());
record.setId(release);
record.setName(queryAlbum.get("name").toString());
record.setImage(queryAlbum.get("image").toString());
Track track = modelFactory.createTrack();
track.setName(queryAlbum.get("trackName").toString());
track.setTrackNr(queryAlbum.get("trackNumber").toString());
track.setPreview(queryAlbum.get("preview").toString());
if(queryAlbum.get("trackDuration") != null) {
track.setLength(queryAlbum.get("trackDuration").toString());
}
tracks.put(queryAlbum.get("trackNumber").toString(), track);
Artist artist = modelFactory.createArtist();
artist.setName(queryAlbum.get("artist").toString());
artists.put(queryAlbum.get("artist").toString(), artist);
genre.put(queryAlbum.get("genre").toString(),queryAlbum.get("genre").toString());
meta.put("Released", queryAlbum.get("year").toString());
if(queryAlbum.get("catalogueNumber").toString() != "none") {
meta.put("Catalogue Number", queryAlbum.get("catalogueNumber").toString());
}
meta.put("Label", queryAlbum.get("publisher").toString());
record.setYear(queryAlbum.get("year").toString());
record.setDescription(queryAlbum.get("comment").toString());
}
record.setGenres(genre);
record.setTracks(new LinkedList<Track>(tracks.values()));
record.setArtist(new LinkedList<Artist>(artists.values()));
record.setMeta(meta);
}
public static void main(String[] args) throws MasterNotFoundException {
ApplicationContext context = new ClassPathXmlApplicationContext("main-context.xml");
// System.out.println(context);
Searcher searcher = (Searcher) context.getBean("searcherImpl");
//// searcher.searchArtist("Guns N Roses");
// Map<String, Record> records = searcher.searchRecords("Thriller");
// for(Record record:records.values()){
// System.out.println(record.getName()+", " + record.getDiscogId()+ ", " + record.getArtist().get(0).getName());
// Searcher searcher = new SearcherImpl();
searcher.searchRecord("Rated R","Rihanna");
}
private Date makeDate(String dateString){
Date date = new Date();
SimpleDateFormat stf = new SimpleDateFormat("yyyy-mm-dd",Locale.US);
try {
date = stf.parse(dateString);
} catch (ParseException e) {
LOGGER.error("Couldnt parse date");
}
return date;
}
}
|
package eu.agilejava.snoop;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.core.Response;
/**
*
* @author Ivar Grimstad (ivar.grimstad@gmail.com)
*/
@Path("world")
public class WorldResource {
@GET
public Response greet() {
return Response.ok("World").build();
}
}
|
package edu.virginia.psyc.pi.domain;
import java.util.ArrayList;
import java.util.List;
public class Session {
/** This is an ordered enumeration, and is used that way.
* Changing the order here will impact the order in which
* sessions occur in the interface and in their progression.
*/
public enum NAME {ELIGIBLE, PRE, SESSION1, SESSION2, SESSION3, SESSION4, SESSION5, SESSION6, SESSION7, SESSION8, POST, COMPLETE}
public enum STATE {COMPLETE,CURRENT,INCOMPLETE}
private NAME name;
private boolean complete;
private boolean current;
private List<Task> tasks;
public static List<Session> defaultList() {
return createListView(NAME.values()[0], 0);
}
/**
* Generates a list of sessions suitable for display, based on the current session, and index of the
* current task within that Session.
* @return
*/
public static List<Session> createListView(NAME currentName, int taskIndex) {
List<Session> list = new ArrayList<Session>();
boolean completed = true;
boolean current = false;
Session session;
for(Session.NAME name : Session.NAME.values()) {
if(name == currentName) {
completed = false;
current = true;
}
if(!name.equals(NAME.ELIGIBLE) && !name.equals(NAME.COMPLETE)) {
session = new Session(name, completed, current);
session.setTasks(getTasks(name, taskIndex));
list.add(session);
}
current = false; // only one can be current.
}
return list;
}
/**
* In the future we should refactor this, so that we load the sessions from a
* configuration file, or from the database. But neither of these directions
* seems clean to me, as they will naturally depend on certain code and paths
* existing. So here is how sessions and tasks are defined, until requirements,
* or common sense dictate a more complex solution.
* @param name The Name of a given session.
* @return
*/
public static List<Task> getTasks(NAME name, int taskIndex) {
List<Task> tasks = new ArrayList<Task>();
switch(name) {
case PRE:
tasks.add(new Task("DASS21_AS", "Status Questionnaire", Task.TYPE.questions));
tasks.add(new Task("credibility", "Credibility Assessment", Task.TYPE.questions));
tasks.add(new Task("MH", "Mental Health History", Task.TYPE.questions));
tasks.add(new Task("SA", "State Anxiety", Task.TYPE.questions));
tasks.add(new Task("QOL", "Quality of Life Scale", Task.TYPE.questions));
tasks.add(new Task("DASS21_DS", "Symptom Measures", Task.TYPE.questions));
break;
case SESSION1:
tasks.add(new Task("AIP", "Imagery Prime", Task.TYPE.questions));
tasks.add(new Task("FirstSessionComplete", "First Session", Task.TYPE.playerScript));
tasks.add(new Task("DASS21_AS", "Status Questionnaire", Task.TYPE.questions));
break;
case SESSION2:
tasks.add(new Task("SecondSessionComplete", "Second Session", Task.TYPE.playerScript));
tasks.add(new Task("DASS21_AS", "Status Questionnaire", Task.TYPE.questions));
break;
case SESSION3:
tasks.add(new Task("AIP", "Imagery Prime", Task.TYPE.questions));
tasks.add(new Task("ThirdSessionComplete", "Third Session", Task.TYPE.playerScript));
tasks.add(new Task("DASS21_AS", "Status Questionnaire", Task.TYPE.questions));
tasks.add(new Task("SAPo", "State Anxiety", Task.TYPE.questions));
break;
case SESSION4:
tasks.add(new Task("FourthSessionComplete", "Fourth Session", Task.TYPE.playerScript));
tasks.add(new Task("DASS21_AS", "Status Questionnaire", Task.TYPE.questions));
tasks.add(new Task("QOL", "Quality of Life Scale", Task.TYPE.questions));
tasks.add(new Task("DASS21_DS", "Symptom Measures", Task.TYPE.questions));
break;
case SESSION5:
tasks.add(new Task("FirstSessionComplete", "First Session", Task.TYPE.playerScript));
tasks.add(new Task("DASS21_AS", "Status Questionnaire", Task.TYPE.questions));
break;
case SESSION6:
tasks.add(new Task("AIP", "Imagery Prime", Task.TYPE.questions));
tasks.add(new Task("SecondSessionComplete", "Second Session", Task.TYPE.playerScript));
tasks.add(new Task("DASS21_AS", "Status Questionnaire", Task.TYPE.questions));
tasks.add(new Task("SAPo", "State Anxiety", Task.TYPE.questions));
break;
case SESSION7:
tasks.add(new Task("DASS21_AS", "Status Questionnaire", Task.TYPE.questions));
tasks.add(new Task("ThirdSessionComplete", "Third Session", Task.TYPE.playerScript));
break;
case SESSION8:
tasks.add(new Task("AIP", "Imagery Prime", Task.TYPE.questions));
tasks.add(new Task("FourthSessionComplete", "Fourth Session", Task.TYPE.playerScript));
tasks.add(new Task("DASS21_AS", "Status Questionnaire", Task.TYPE.questions));
tasks.add(new Task("SAPo", "State Anxiety", Task.TYPE.questions));
tasks.add(new Task("QOL", "Quality of Life Scale", Task.TYPE.questions));
tasks.add(new Task("DASS21_DS", "Symptom Measures", Task.TYPE.questions));
break;
case POST:
tasks.add(new Task("MUE", "User Experience", Task.TYPE.questions));
tasks.add(new Task("DASS21_AS", "Status Questionnaire", Task.TYPE.questions));
tasks.add(new Task("SAPo", "State Anxiety", Task.TYPE.questions));
tasks.add(new Task("QOL", "Quality of Life Scale", Task.TYPE.questions));
tasks.add(new Task("DASS21_DS", "Symptom Measures", Task.TYPE.questions));
}
setTaskStates(tasks, taskIndex);
return tasks;
}
/**
* This method churns through the list of tasks, setting the "current" and "complete" flags based on the
* current task index.
*/
private static void setTaskStates(List<Task> tasks, int taskIndex) {
int index = 0;
for(Task t : tasks) {
t.setCurrent(taskIndex == index);
t.setComplete(taskIndex > index);
index ++;
}
}
/**
* Given a session name, returns the next session name.
*/
public static NAME nextSession(NAME last) {
boolean nextOne = false;
for(Session.NAME name : Session.NAME.values()) {
if(nextOne) return name;
if(name == last) nextOne = true;
}
return null;
}
/** State is one of the STATE enumerations defined at the head of this class.
* @return Current State of this Session (incomplete / current / complete).
*/
public STATE getState() {
if(current) return STATE.CURRENT;
else if(complete) return STATE.COMPLETE;
else return STATE.INCOMPLETE;
}
public Task getCurrentTask() {
for(Task t : tasks) {
if (t.isCurrent()) return t;
}
return null;
}
/**
* Returns the index of the current task in the list of tasks in this session.
* This is a 0-based index.
* @return
*/
public int getCurrentTaskIndex() {
int counter = 0;
for(Task t : tasks) {
if (t.isCurrent()) return counter;
counter ++;
}
return 0;
}
public Session() {}
public Session(NAME name, boolean complete, boolean current) {
this.name = name;
this.complete = complete;
this.current = current;
}
public boolean isComplete() {
return complete;
}
public void setComplete(boolean complete) {
this.complete = complete;
}
public boolean isCurrent() {
return current;
}
public void setCurrent(boolean current) {
this.current = current;
}
public NAME getName() {
return name;
}
public void setName(NAME name) {
this.name = name;
}
public List<Task> getTasks() {
return tasks;
}
public void setTasks(List<Task> tasks) {
this.tasks = tasks;
}
}
|
package com.intellij.java.psi;
import com.intellij.lang.java.JavaLanguage;
import com.intellij.openapi.application.WriteAction;
import com.intellij.openapi.application.ex.PathManagerEx;
import com.intellij.openapi.project.DumbServiceImpl;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.util.io.IoTestUtil;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.pom.java.LanguageLevel;
import com.intellij.psi.*;
import com.intellij.psi.impl.compiled.*;
import com.intellij.psi.impl.source.tree.java.ClassElement;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.psi.search.searches.DirectClassInheritorsSearch;
import com.intellij.psi.util.PsiUtil;
import com.intellij.testFramework.LeakHunter;
import com.intellij.testFramework.LightIdeaTestCase;
import com.intellij.util.ref.GCWatcher;
import java.io.File;
import java.io.IOException;
import java.util.Collection;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
public class ClsPsiTest extends LightIdeaTestCase {
private static final String TEST_DATA_PATH = "/psi/cls/repo";
private PsiClass myObjectClass;
private GlobalSearchScope myScope;
@Override
protected void setUp() throws Exception {
super.setUp();
myScope = GlobalSearchScope.moduleWithDependenciesAndLibrariesScope(getModule());
myObjectClass = getJavaFacade().findClass(CommonClassNames.JAVA_LANG_OBJECT, myScope);
assertNotNull(myObjectClass);
}
@Override
protected void tearDown() throws Exception {
myScope = null;
myObjectClass = null;
super.tearDown();
}
public void testClassFileUpdate() throws IOException {
File testFile = IoTestUtil.createTestFile("TestClass.class");
File file1 = new File(PathManagerEx.getTestDataPath() + TEST_DATA_PATH + "/1_TestClass.class");
FileUtil.copy(file1, testFile);
VirtualFile vFile = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(testFile);
vFile.refresh(false, false);
assertEquals(FileUtil.loadFileBytes(file1).length, vFile.contentsToByteArray().length);
assertNotNull(testFile.getPath(), vFile);
PsiFile file = PsiManager.getInstance(getProject()).findFile(vFile);
assertNotNull(file);
PsiClass aClass = ((PsiJavaFile)file).getClasses()[0];
assertTrue(aClass.isValid());
assertEquals(2, aClass.getFields().length);
assertEquals("field11", aClass.getFields()[0].getName());
assertEquals("field12", aClass.getFields()[1].getName());
assertEquals(2, aClass.getMethods().length);
assertEquals("TestClass", aClass.getMethods()[0].getName());
assertEquals("method1", aClass.getMethods()[1].getName());
File file2 = new File(PathManagerEx.getTestDataPath() + TEST_DATA_PATH + "/2_TestClass.class");
FileUtil.copy(file2, testFile);
assertTrue(testFile.setLastModified(System.currentTimeMillis() + 5000));
vFile.refresh(false, false);
aClass = ((PsiJavaFile)file).getClasses()[0];
assertTrue(aClass.isValid());
assertEquals(1, aClass.getFields().length);
assertEquals("field2", aClass.getFields()[0].getName());
assertEquals(2, aClass.getMethods().length);
assertEquals("TestClass", aClass.getMethods()[0].getName());
assertEquals("method2", aClass.getMethods()[1].getName());
}
public void testFile() {
PsiJavaFile file = getFile("MyClass");
assertTrue(file.isValid());
assertEquals("pack", file.getPackageName());
assertEquals(1, file.getClasses().length);
file = getFile("MyEnum");
assertEquals(LanguageLevel.JDK_1_5, file.getLanguageLevel());
}
public void testClassBasics() {
PsiJavaFile file = getFile("MyClass");
PsiClass aClass = file.getClasses()[0];
assertTrue(aClass.isValid());
assertEquals(file, aClass.getParent());
assertEquals(file, aClass.getContainingFile());
assertEquals("MyClass", aClass.getName());
assertEquals("pack.MyClass", aClass.getQualifiedName());
assertFalse(aClass.isInterface());
assertFalse(aClass.isDeprecated());
}
public void testViewProviderHasJavaLanguage() {
PsiJavaFile file = getFile("MyClass");
assertEquals(JavaLanguage.INSTANCE, file.getLanguage());
assertEquals(JavaLanguage.INSTANCE, file.getViewProvider().getBaseLanguage());
}
public void testClassMembers() {
PsiClass aClass = getFile("MyClass").getClasses()[0];
PsiClass[] inners = aClass.getInnerClasses();
assertEquals(1, inners.length);
assertEquals(aClass, inners[0].getParent());
PsiField[] fields = aClass.getFields();
assertEquals(2, fields.length);
assertEquals(aClass, fields[0].getParent());
PsiMethod[] methods = aClass.getMethods();
assertEquals(3, methods.length);
assertEquals(aClass, methods[0].getParent());
assertNotNull(aClass.findFieldByName("field1", false));
}
public void testModifierList() {
PsiClass aClass = getFile("MyClass").getClasses()[0];
PsiModifierList modifierList = aClass.getModifierList();
assertNotNull(modifierList);
assertTrue(modifierList.hasModifierProperty(PsiModifier.PUBLIC));
assertFalse(modifierList.hasModifierProperty(PsiModifier.STATIC));
assertEquals(modifierList.getParent(), aClass);
PsiField field = aClass.getFields()[0];
modifierList = field.getModifierList();
assertNotNull(modifierList);
assertTrue(modifierList.hasModifierProperty(PsiModifier.PACKAGE_LOCAL));
assertEquals(modifierList.getParent(), field);
PsiMethod method = aClass.getMethods()[0];
modifierList = method.getModifierList();
assertNotNull(modifierList);
assertTrue(modifierList.hasModifierProperty(PsiModifier.PACKAGE_LOCAL));
assertEquals(modifierList.getParent(), method);
}
public void testField() {
PsiClass aClass = getFile("MyClass").getClasses()[0];
PsiField field1 = aClass.getFields()[0], field2 = aClass.getFields()[1];
assertEquals("field1", field1.getName());
PsiType type1 = field1.getType();
assertEquals(PsiType.INT, type1);
assertEquals("int", type1.getPresentableText());
assertTrue(type1 instanceof PsiPrimitiveType);
PsiType type2 = field2.getType();
assertTrue(type2.equalsToText("java.lang.Object[]"));
assertEquals("Object[]", type2.getPresentableText());
assertFalse(type2 instanceof PsiPrimitiveType);
assertTrue(type2 instanceof PsiArrayType);
PsiType componentType = ((PsiArrayType)type2).getComponentType();
assertTrue(componentType.equalsToText(CommonClassNames.JAVA_LANG_OBJECT));
assertEquals(CommonClassNames.JAVA_LANG_OBJECT_SHORT, componentType.getPresentableText());
assertFalse(componentType instanceof PsiPrimitiveType);
assertFalse(componentType instanceof PsiArrayType);
PsiLiteralExpression initializer = (PsiLiteralExpression)field1.getInitializer();
assertNotNull(initializer);
assertEquals("123", initializer.getText());
assertEquals(123, initializer.getValue());
assertEquals(PsiType.INT, initializer.getType());
assertFalse(field2.hasInitializer());
assertNull(field2.getInitializer());
}
public void testMethod() {
PsiClass aClass = getFile("MyClass").getClasses()[0];
assertEquals("method1", aClass.getMethods()[0].getName());
PsiMethod method1 = aClass.getMethods()[0];
PsiTypeElement type1 = method1.getReturnTypeElement();
assertNotNull(type1);
assertEquals(method1, type1.getParent());
assertEquals("void", type1.getText());
assertTrue(type1.getType() instanceof PsiPrimitiveType);
assertFalse(method1.isConstructor());
PsiMethod method3 = aClass.getMethods()[2];
assertNull(method3.getReturnType());
assertTrue(method3.isConstructor());
}
public void testTypeReference() {
PsiClass aClass = getFile("MyClass").getClasses()[0];
PsiType type1 = aClass.getFields()[0].getType();
assertNull(PsiUtil.resolveClassInType(type1));
PsiType type2 = aClass.getFields()[1].getType();
PsiType componentType = ((PsiArrayType)type2).getComponentType();
assertTrue(componentType instanceof PsiClassType);
assertTrue(componentType.equalsToText(CommonClassNames.JAVA_LANG_OBJECT));
assertEquals(CommonClassNames.JAVA_LANG_OBJECT_SHORT, componentType.getPresentableText());
PsiElement target = PsiUtil.resolveClassInType(type2);
assertEquals(myObjectClass, target);
}
public void testReferenceLists() {
PsiClass aClass = getFile("MyClass").getClasses()[0];
PsiReferenceList extList = aClass.getExtendsList();
assertNotNull(extList);
PsiClassType[] refs = extList.getReferencedTypes();
assertEquals(1, refs.length);
assertEquals("ArrayList", refs[0].getPresentableText());
assertEquals("java.util.ArrayList", refs[0].getCanonicalText());
PsiReferenceList implList = aClass.getImplementsList();
assertNotNull(implList);
PsiClassType[] implRefs = implList.getReferencedTypes();
assertEquals(1, implRefs.length);
assertEquals("Cloneable", implRefs[0].getPresentableText());
assertEquals("java.lang.Cloneable", implRefs[0].getCanonicalText());
PsiReferenceList throwsList = aClass.getMethods()[0].getThrowsList();
PsiClassType[] throwsRefs = throwsList.getReferencedTypes();
assertEquals(2, throwsRefs.length);
assertEquals("Exception", throwsRefs[0].getPresentableText());
assertEquals("java.lang.Exception", throwsRefs[0].getCanonicalText());
assertEquals("IOException", throwsRefs[1].getPresentableText());
assertEquals("java.io.IOException", throwsRefs[1].getCanonicalText());
}
public void testParameters() {
PsiClass aClass = getFile("MyClass").getClasses()[0];
PsiParameter[] parameters = aClass.getMethods()[0].getParameterList().getParameters();
assertEquals(2, parameters.length);
PsiType type1 = parameters[0].getType();
assertEquals("int[]", type1.getPresentableText());
assertTrue(type1.equalsToText("int[]"));
assertTrue(type1 instanceof PsiArrayType);
assertNull(PsiUtil.resolveClassInType(type1));
PsiType type2 = parameters[1].getType();
assertEquals("Object", type2.getPresentableText());
assertTrue(type2.equalsToText(CommonClassNames.JAVA_LANG_OBJECT));
assertFalse(type2 instanceof PsiArrayType);
assertFalse(type2 instanceof PsiPrimitiveType);
PsiClass target2 = PsiUtil.resolveClassInType(type2);
assertEquals(myObjectClass, target2);
assertNotNull(parameters[0].getModifierList());
assertNotNull(parameters[1].getModifierList());
Runnable checkNames = () -> {
assertTrue(((ClsParameterImpl)parameters[0]).isAutoGeneratedName());
assertTrue(((ClsParameterImpl)parameters[1]).isAutoGeneratedName());
assertEquals("ints", parameters[0].getName());
assertEquals("o", parameters[1].getName());
};
DumbServiceImpl.getInstance(getProject()).runInDumbMode(checkNames);
checkNames.run();
}
public void testModifiers() {
PsiClass aClass = getFile().getClasses()[0];
assertEquals("private transient", aClass.getFields()[0].getModifierList().getText());
assertEquals("private volatile", aClass.getFields()[1].getModifierList().getText());
assertEquals("public", aClass.getMethods()[0].getModifierList().getText());
assertEquals("private", aClass.getMethods()[1].getModifierList().getText());
assertEquals("private synchronized", aClass.getMethods()[2].getModifierList().getText());
}
public void testEnum() {
PsiClass aClass = getFile("MyEnum").getClasses()[0];
assertTrue(aClass.isEnum());
PsiField[] fields = aClass.getFields();
PsiClassType type = getJavaFacade().getElementFactory().createType(aClass);
assertEnumConstant(fields[0], "RED", type);
assertEnumConstant(fields[1], "GREEN", type);
assertEnumConstant(fields[2], "BLUE", type);
}
private static void assertEnumConstant(PsiField field, String name, PsiClassType type) {
assertEquals(name, field.getName());
assertTrue(field instanceof PsiEnumConstant);
assertEquals(type, field.getType());
}
public void testSyntheticEnumMethodsWhereApplicable() {
PsiClass aClass = getJavaFacade().findClass(TimeUnit.class.getName());
assertTrue(aClass.isEnum());
assertSize(1, aClass.findMethodsByName("valueOf", false));
assertSize(1, aClass.findMethodsByName("values", false));
Collection<PsiClass> constants = DirectClassInheritorsSearch.search(aClass).findAll();
assertSize(7, constants);
for (PsiClass constant : constants) {
assertSize(0, constant.findMethodsByName("valueOf", false));
assertSize(0, constant.findMethodsByName("values", false));
}
}
public void testAnnotations() {
PsiClass aClass = getFile("Annotated").getClasses()[0];
PsiModifierList modifierList = aClass.getModifierList();
assertNotNull(modifierList);
PsiAnnotation[] annotations = modifierList.getAnnotations();
assertEquals(1, annotations.length);
assertEquals("@pack.Annotation", annotations[0].getText());
PsiMethod method = aClass.getMethods()[1];
annotations = method.getModifierList().getAnnotations();
assertEquals(1, annotations.length);
assertEquals("@pack.Annotation", annotations[0].getText());
PsiParameter[] params = method.getParameterList().getParameters();
assertEquals(1, params.length);
modifierList = params[0].getModifierList();
assertNotNull(modifierList);
annotations = modifierList.getAnnotations();
assertEquals(1, annotations.length);
assertEquals("@pack.Annotation", annotations[0].getText());
modifierList = aClass.getFields()[0].getModifierList();
assertNotNull(modifierList);
annotations = modifierList.getAnnotations();
assertEquals(1, annotations.length);
assertEquals("@pack.Annotation", annotations[0].getText());
}
public void testAnnotationMethods() {
PsiMethod[] methods = getFile("Annotation").getClasses()[0].getMethods();
assertNotNull(((PsiAnnotationMethod)methods[0]).getDefaultValue());
methods = getFile("Annotation2").getClasses()[0].getMethods();
for (PsiMethod method : methods) {
assertTrue(String.valueOf(method), method instanceof PsiAnnotationMethod);
try {
PsiAnnotationMemberValue defaultValue = ((PsiAnnotationMethod)method).getDefaultValue();
assertTrue(String.valueOf(defaultValue), defaultValue instanceof PsiBinaryExpression);
PsiPrimitiveType type = method.getName().startsWith("f") ? PsiType.FLOAT : PsiType.DOUBLE;
assertEquals(type, ((PsiBinaryExpression)defaultValue).getType());
}
catch (Exception e) {
String valueText = ((ClsMethodImpl)method).getStub().getDefaultValueText();
fail("Unable to compute default value of method " + method + " from text '" + valueText + "': " + e.getMessage());
}
}
}
public void testKeywordAnnotatedClass() {
PsiModifierList modList = getFile("../KeywordAnnotatedClass").getClasses()[0].getModifierList();
assertNotNull(modList);
assertEquals("@pkg.native", modList.getAnnotations()[0].getText());
}
public void testGenerics() {
PsiClass aClass = getJavaFacade().findClass(CommonClassNames.JAVA_UTIL_HASH_MAP, myScope);
assertNotNull(aClass);
PsiTypeParameter[] parameters = aClass.getTypeParameters();
assertEquals(2, parameters.length);
assertEquals("K", parameters[0].getName());
assertEquals("V", parameters[1].getName());
PsiClassType extType = aClass.getExtendsListTypes()[0];
assertEquals("java.util.AbstractMap<K,V>", extType.getCanonicalText());
PsiType returnType = aClass.findMethodsByName("entrySet", false)[0].getReturnType();
assertNotNull(returnType);
assertEquals("java.util.Set<java.util.Map.Entry<K,V>>", returnType.getCanonicalText());
PsiType paramType = aClass.findMethodsByName("putAll", false)[0].getParameterList().getParameters()[0].getType();
assertNotNull(paramType);
assertEquals("java.util.Map<? extends K,? extends V>", paramType.getCanonicalText());
assertNotNull(((PsiClassType)paramType).resolveGenerics().getElement());
}
public void testFqnCorrectness() {
PsiClass aClass = getFile("$Weird$Name").getClasses()[0].getInnerClasses()[0];
assertEquals("pack.$Weird$Name.Inner", aClass.getQualifiedName());
}
public void testFieldConstantValue() {
PsiClass dbl = getJavaFacade().findClass(Double.class.getName(), myScope);
assertNotNull(dbl);
PsiField dnn = dbl.findFieldByName("NaN", false);
assertNotNull(dnn);
assertEquals(Double.NaN, dnn.computeConstantValue());
PsiClass cls = getFile("../../mirror/pkg/Primitives").getClasses()[0];
PsiField lng = cls.findFieldByName("LONG", false);
assertNotNull(lng);
assertEquals(42L, lng.computeConstantValue());
}
public void testAnnotationsOnTypes() {
PsiClass cls = getFile("../../mirror/pkg/TypeAnnotations").getClasses()[0];
PsiField f1 = cls.findFieldByName("f1", false);
assertNotNull(f1);
assertEquals("java.lang.@pkg.TypeAnnotations.TA(\"field type\") String", f1.getType().getCanonicalText(true));
PsiField f2 = cls.findFieldByName("f2", false);
assertNotNull(f2);
assertEquals("java.lang.@pkg.TypeAnnotations.MixA(\"field and type\") String", f2.getType().getCanonicalText(true));
PsiMethod m1 = cls.findMethodsByName("m1", false)[0];
assertEquals("@pkg.TypeAnnotations.TA(\"return type\") int", Objects.requireNonNull(m1.getReturnType()).getCanonicalText(true));
PsiParameter p1 = cls.findMethodsByName("m2", false)[0].getParameterList().getParameters()[0];
assertEquals("@pkg.TypeAnnotations.TA(\"parameter\") int", p1.getType().getCanonicalText(true));
}
public void testModuleInfo() {
PsiJavaFile file = getFile("../../stubBuilder/module-info");
assertEquals(LanguageLevel.JDK_1_9, file.getLanguageLevel());
assertEquals("", file.getPackageName());
PsiJavaModule module = file.getModuleDeclaration();
assertNotNull(module);
assertEquals("M.N", module.getName());
assertNull(file.getPackageStatement());
assertEquals(0, file.getClasses().length);
}
private PsiJavaFile getFile() {
return getFile(getTestName(false));
}
private PsiJavaFile getFile(String name) {
String path = PathManagerEx.getTestDataPath() + TEST_DATA_PATH + "/pack/" + name + ".class";
VirtualFile file = LocalFileSystem.getInstance().refreshAndFindFileByPath(path);
assertNotNull(path, file);
PsiFile clsFile = PsiManager.getInstance(getProject()).findFile(file);
assertTrue(String.valueOf(clsFile), clsFile instanceof ClsFileImpl);
return (PsiJavaFile)clsFile;
}
public void testClsPsiDoesNotHoldStrongReferencesToMirrorAST() {
PsiClass dbl = getJavaFacade().findClass(Double.class.getName(), myScope);
assertNotNull(dbl);
assertEquals(dbl, ((ClsClassImpl)dbl).getMirror().getUserData(ClsElementImpl.COMPILED_ELEMENT));
GCWatcher.tracking(((ClsClassImpl)dbl).getMirror()).ensureCollected();
LeakHunter.checkLeak(dbl, ClassElement.class, element -> element.getPsi().getUserData(ClsElementImpl.COMPILED_ELEMENT) == dbl);
}
public void testMirrorBecomesInvalidTogetherWithCls() throws IOException {
File testFile = IoTestUtil.createTestFile("TestClass.class");
File file1 = new File(PathManagerEx.getTestDataPath() + TEST_DATA_PATH + "/1_TestClass.class");
FileUtil.copy(file1, testFile);
VirtualFile copyVFile = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(testFile);
ClsFileImpl clsFile = (ClsFileImpl)PsiManager.getInstance(getProject()).findFile(copyVFile);
PsiElement mirror = clsFile.getMirror();
assertTrue(clsFile.isValid());
assertTrue(mirror.isValid());
WriteAction.run(() -> copyVFile.delete(this));
assertFalse(clsFile.isValid());
assertFalse(mirror.isValid());
assertTrue(PsiInvalidElementAccessException.findOutInvalidationReason(mirror)
.contains(PsiInvalidElementAccessException.findOutInvalidationReason(clsFile)));
}
}
|
package javaslang.collection;
import javaslang.Tuple2;
import javaslang.Tuple3;
import javaslang.Value;
import javaslang.control.Option;
import java.math.BigInteger;
import java.util.Comparator;
import java.util.NoSuchElementException;
import java.util.Objects;
import java.util.function.BiFunction;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
/**
* An interface for inherently recursive, multi-valued data structures. The order of elements is determined by
* {@link Iterable#iterator()}, which may vary each time it is called.
*
* <p>
* Basic operations:
*
* <ul>
* <li>{@link #contains(Object)}</li>
* <li>{@link #containsAll(Iterable)}</li>
* <li>{@link #head()}</li>
* <li>{@link #headOption()}</li>
* <li>{@link #init()}</li>
* <li>{@link #initOption()}</li>
* <li>{@link #isEmpty()}</li>
* <li>{@link #last()}</li>
* <li>{@link #lastOption()}</li>
* <li>{@link #length()}</li>
* <li>{@link #size()}</li>
* <li>{@link #tail()}</li>
* <li>{@link #tailOption()}</li>
* </ul>
*
* Iteration:
*
* <ul>
* <li>{@link #grouped(int)}</li>
* <li>{@link #iterator()}</li>
* <li>{@link #sliding(int)}</li>
* <li>{@link #sliding(int, int)}</li>
* </ul>
*
* Numeric operations:
*
* <ul>
* <li>{@link #average()}</li>
* <li>{@link #max()}</li>
* <li>{@link #maxBy(Comparator)}</li>
* <li>{@link #maxBy(Function)}</li>
* <li>{@link #min()}</li>
* <li>{@link #minBy(Comparator)}</li>
* <li>{@link #minBy(Function)}</li>
* <li>{@link #product()}</li>
* <li>{@link #sum()}</li>
* </ul>
*
* Reduction/Folding:
*
* <ul>
* <li>{@link #count(Predicate)}</li>
* <li>{@link #fold(Object, BiFunction)}</li>
* <li>{@link #foldLeft(Object, BiFunction)}</li>
* <li>{@link #foldRight(Object, BiFunction)}</li>
* <li>{@link #mkString()}</li>
* <li>{@link #mkString(CharSequence)}</li>
* <li>{@link #mkString(CharSequence, CharSequence, CharSequence)}</li>
* <li>{@link #reduce(BiFunction)}</li>
* <li>{@link #reduceOption(BiFunction)}</li>
* <li>{@link #reduceLeft(BiFunction)}</li>
* <li>{@link #reduceLeftOption(BiFunction)}</li>
* <li>{@link #reduceRight(BiFunction)}</li>
* <li>{@link #reduceRightOption(BiFunction)}</li>
* </ul>
*
* Selection:
*
* <ul>
* <li>{@link #drop(int)}</li>
* <li>{@link #dropRight(int)}</li>
* <li>{@link #dropUntil(Predicate)}</li>
* <li>{@link #dropWhile(Predicate)}</li>
* <li>{@link #filter(Predicate)}</li>
* <li>{@link #find(Predicate)}</li>
* <li>{@link #findLast(Predicate)}</li>
* <li>{@link #groupBy(Function)}</li>
* <li>{@link #partition(Predicate)}</li>
* <li>{@link #retainAll(Iterable)}</li>
* <li>{@link #take(int)}</li>
* <li>{@link #takeRight(int)}</li>
* <li>{@link #takeUntil(Predicate)}</li>
* <li>{@link #takeWhile(Predicate)}</li>
* </ul>
*
* Tests:
*
* <ul>
* <li>{@link #existsUnique(Predicate)}</li>
* <li>{@link #hasDefiniteSize()}</li>
* <li>{@link #isTraversableAgain()}</li>
* </ul>
*
* Transformation:
*
* <ul>
* <li>{@link #distinct()}</li>
* <li>{@link #distinctBy(Comparator)}</li>
* <li>{@link #distinctBy(Function)}</li>
* <li>{@link #flatMap(Function)}</li>
* <li>{@link #map(Function)}</li>
* <li>{@link #replace(Object, Object)}</li>
* <li>{@link #replaceAll(Object, Object)}</li>
* <li>{@link #scan(Object, BiFunction)}</li>
* <li>{@link #scanLeft(Object, BiFunction)}</li>
* <li>{@link #scanRight(Object, BiFunction)}</li>
* <li>{@link #span(Predicate)}</li>
* <li>{@link #unzip(Function)}</li>
* <li>{@link #unzip3(Function)}</li>
* <li>{@link #zip(Iterable)}</li>
* <li>{@link #zipAll(Iterable, Object, Object)}</li>
* <li>{@link #zipWithIndex()}</li>
* </ul>
*
* @param <T> Component type
* @author Daniel Dietrich and others
* @since 1.1.0
*/
public interface Traversable<T> extends Foldable<T>, Value<T> {
/**
* Narrows a widened {@code Traversable<? extends T>} to {@code Traversable<T>}
* by performing a type safe-cast. This is eligible because immutable/read-only
* collections are covariant.
*
* @param traversable An {@code Traversable}.
* @param <T> Component type of the {@code Traversable}.
* @return the given {@code traversable} instance as narrowed type {@code Traversable<T>}.
*/
@SuppressWarnings("unchecked")
static <T> Traversable<T> narrow(Traversable<? extends T> traversable) {
return (Traversable<T>) traversable;
}
/**
* Calculates the average of this elements. Returns {@code None} if this is empty, otherwise {@code Some(average)}.
* Supported component types are {@code Byte}, {@code Double}, {@code Float}, {@code Integer}, {@code Long},
* {@code Short}, {@code BigInteger} and {@code BigDecimal}.
* <p>
* Examples:
* <pre>
* <code>
* List.empty().average() // = None
* List.of(1, 2, 3).average() // = Some(2.0)
* List.of(0.1, 0.2, 0.3).average() // = Some(0.2)
* List.of("apple", "pear").average() // throws
* </code>
* </pre>
*
* @return {@code Some(average)} or {@code None}, if there are no elements
* @throws UnsupportedOperationException if this elements are not numeric
*/
@SuppressWarnings("unchecked")
default Option<Double> average() {
if (isEmpty()) {
return Option.none();
} else {
final Traversable<?> objects = isTraversableAgain() ? this : toStream();
final Object o = objects.head();
if (o instanceof Number) {
final Traversable<Number> numbers = (Traversable<Number>) objects;
final double d;
if (o instanceof Integer || o instanceof Long || o instanceof Byte || o instanceof BigInteger || o instanceof Short) {
d = numbers.toJavaStream()
.mapToLong(Number::longValue)
.average()
.getAsDouble();
} else {
d = numbers.toJavaStream()
.mapToDouble(Number::doubleValue)
.average()
.getAsDouble();
}
return Option.some(d);
} else {
throw new UnsupportedOperationException("not numeric");
}
}
}
/**
* Tests if this Traversable contains all given elements.
* <p>
* The result is equivalent to
* {@code elements.isEmpty() ? true : contains(elements.head()) && containsAll(elements.tail())} but implemented
* without recursion.
*
* @param elements A List of values of type T.
* @return true, if this List contains all given elements, false otherwise.
* @throws NullPointerException if {@code elements} is null
*/
default boolean containsAll(Iterable<? extends T> elements) {
HashSet<T> uniqueElements = HashSet.ofAll(elements);
return toSet().intersect(uniqueElements).size() == uniqueElements.size();
}
/**
* Counts the elements which satisfy the given predicate.
*
* @param predicate A predicate
* @return A number {@code >= 0}
* @throws NullPointerException if {@code predicate} is null.
*/
default int count(Predicate<? super T> predicate) {
Objects.requireNonNull(predicate, "predicate is null");
return foldLeft(0, (i, t) -> predicate.test(t) ? i + 1 : i);
}
/**
* Returns a new version of this which contains no duplicates. Elements are compared using {@code equals}.
*
* @return a new {@code Traversable} containing this elements without duplicates
*/
Traversable<T> distinct();
/**
* Returns a new version of this which contains no duplicates. Elements are compared using the given
* {@code comparator}.
*
* @param comparator A comparator
* @return a new {@code Traversable} containing this elements without duplicates
* @throws NullPointerException if {@code comparator} is null.
*/
Traversable<T> distinctBy(Comparator<? super T> comparator);
/**
* Returns a new version of this which contains no duplicates. Elements mapped to keys which are compared using
* {@code equals}.
* <p>
* The elements of the result are determined in the order of their occurrence - first match wins.
*
* @param keyExtractor A key extractor
* @param <U> key type
* @return a new {@code Traversable} containing this elements without duplicates
* @throws NullPointerException if {@code keyExtractor} is null
*/
<U> Traversable<T> distinctBy(Function<? super T, ? extends U> keyExtractor);
/**
* Drops the first n elements of this or all elements, if this length < n.
*
* @param n The number of elements to drop.
* @return a new instance consisting of all elements of this except the first n ones, or else the empty instance,
* if this has less than n elements.
*/
Traversable<T> drop(int n);
/**
* Drops the last n elements of this or all elements, if this length < n.
*
* @param n The number of elements to drop.
* @return a new instance consisting of all elements of this except the last n ones, or else the empty instance,
* if this has less than n elements.
*/
Traversable<T> dropRight(int n);
/**
* Drops elements until the predicate holds for the current element.
* <p>
* Note: This is essentially the same as {@code dropWhile(predicate.negate())}. It is intended to be used with
* method references, which cannot be negated directly.
*
* @param predicate A condition tested subsequently for this elements.
* @return a new instance consisting of all elements starting from the first one which does satisfy the given
* predicate.
* @throws NullPointerException if {@code predicate} is null
*/
Traversable<T> dropUntil(Predicate<? super T> predicate);
/**
* Drops elements while the predicate holds for the current element.
*
* @param predicate A condition tested subsequently for this elements starting with the first.
* @return a new instance consisting of all elements starting from the first one which does not satisfy the
* given predicate.
* @throws NullPointerException if {@code predicate} is null
*/
Traversable<T> dropWhile(Predicate<? super T> predicate);
/**
* Checks, if a unique elements exists such that the predicate holds.
*
* @param predicate A Predicate
* @return true, if predicate holds for a unique element, false otherwise
* @throws NullPointerException if {@code predicate} is null
*/
default boolean existsUnique(Predicate<? super T> predicate) {
Objects.requireNonNull(predicate, "predicate is null");
boolean exists = false;
for (T t : this) {
if (predicate.test(t)) {
if (exists) {
return false;
} else {
exists = true;
}
}
}
return exists;
}
/**
* Returns a new traversable consisting of all elements which satisfy the given predicate.
*
* @param predicate A predicate
* @return a new traversable
* @throws NullPointerException if {@code predicate} is null
*/
Traversable<T> filter(Predicate<? super T> predicate);
/**
* Returns the first element of this which satisfies the given predicate.
*
* @param predicate A predicate.
* @return Some(element) or None, where element may be null (i.e. {@code List.of(null).find(e -> e == null)}).
* @throws NullPointerException if {@code predicate} is null
*/
default Option<T> find(Predicate<? super T> predicate) {
Objects.requireNonNull(predicate, "predicate is null");
for (T a : this) {
if (predicate.test(a)) {
return Option.some(a); // may be Some(null)
}
}
return Option.none();
}
/**
* Returns the last element of this which satisfies the given predicate.
* <p>
* Same as {@code reverse().find(predicate)}.
*
* @param predicate A predicate.
* @return Some(element) or None, where element may be null (i.e. {@code List.of(null).find(e -> e == null)}).
* @throws NullPointerException if {@code predicate} is null
*/
default Option<T> findLast(Predicate<? super T> predicate) {
Objects.requireNonNull(predicate, "predicate is null");
return iterator().findLast(predicate);
}
/**
* FlatMaps this Traversable.
*
* @param mapper A mapper
* @param <U> The resulting component type.
* @return A new Traversable instance.
*/
<U> Traversable<U> flatMap(Function<? super T, ? extends Iterable<? extends U>> mapper);
/**
* Accumulates the elements of this Traversable by successively calling the given function {@code f} from the left,
* starting with a value {@code zero} of type B.
* <p>
* Example: Reverse and map a Traversable in one pass
* <pre><code>
* List.of("a", "b", "c").foldLeft(List.empty(), (xs, x) -> xs.prepend(x.toUpperCase()))
* // = List("C", "B", "A")
* </code></pre>
*
* @param zero Value to start the accumulation with.
* @param f The accumulator function.
* @param <U> Result type of the accumulator.
* @return an accumulated version of this.
* @throws NullPointerException if {@code f} is null
*/
@Override
default <U> U foldLeft(U zero, BiFunction<? super U, ? super T, ? extends U> f) {
Objects.requireNonNull(f, "f is null");
U xs = zero;
for (T x : this) {
xs = f.apply(xs, x);
}
return xs;
}
/**
* Accumulates the elements of this Traversable by successively calling the given function {@code f} from the right,
* starting with a value {@code zero} of type B.
* <p>
* Example: {@code List.of("a", "b", "c").foldRight("", (x, xs) -> x + xs) = "abc"}
*
* @param zero Value to start the accumulation with.
* @param f The accumulator function.
* @param <U> Result type of the accumulator.
* @return an accumulated version of this.
* @throws NullPointerException if {@code f} is null
*/
@Override
<U> U foldRight(U zero, BiFunction<? super T, ? super U, ? extends U> f);
@Override
default T get() {
return iterator().next();
}
/**
* Returns the only element of a Traversable as {@code Option}.
*
* @return {@code Some(element)} or {@code None} if the Traversable does not contain a single element.
*/
default Option<T> singleOption() {
final Iterator<T> it = iterator();
if (!it.hasNext()) {
return Option.none();
}
final T first = it.next();
if (it.hasNext()) {
return Option.none();
} else {
return Option.some(first);
}
}
/**
* if the Traversable contains a single element, return it,
* otherwise throws.
*
* @return the single element from the Traversable
* @throws NoSuchElementException if the Traversable does not contain a single element.
*/
default T single() {
return singleOption().getOrElseThrow(() -> new NoSuchElementException("Does not contain a single value"));
}
/**
* Groups this elements by classifying the elements.
*
* @param classifier A function which classifies elements into classes
* @param <C> classified class type
* @return A Map containing the grouped elements
* @throws NullPointerException if {@code classifier} is null.
*/
<C> Map<C, ? extends Traversable<T>> groupBy(Function<? super T, ? extends C> classifier);
Iterator<? extends Traversable<T>> grouped(int size);
/**
* Checks if this Traversable is known to have a finite size.
* <p>
* This method should be implemented by classes only, i.e. not by interfaces.
*
* @return true, if this Traversable is known to hafe a finite size, false otherwise.
*/
boolean hasDefiniteSize();
/**
* Returns the first element of a non-empty Traversable.
*
* @return The first element of this Traversable.
* @throws NoSuchElementException if this is empty
*/
T head();
/**
* Returns the first element of a non-empty Traversable as {@code Option}.
*
* @return {@code Some(element)} or {@code None} if this is empty.
*/
default Option<T> headOption() {
return isEmpty() ? Option.none() : Option.some(head());
}
/**
* Dual of {@linkplain #tail()}, returning all elements except the last.
*
* @return a new instance containing all elements except the last.
* @throws UnsupportedOperationException if this is empty
*/
Traversable<T> init();
/**
* Dual of {@linkplain #tailOption()}, returning all elements except the last as {@code Option}.
*
* @return {@code Some(traversable)} or {@code None} if this is empty.
*/
default Option<? extends Traversable<T>> initOption() {
return isEmpty() ? Option.none() : Option.some(init());
}
/**
* Checks if this Traversable is empty.
*
* @return true, if this Traversable contains no elements, false otherwise.
*/
@Override
default boolean isEmpty() {
return length() == 0;
}
/**
* Each of Javaslang's collections may contain more than one element.
*
* @return {@code false}
*/
@Override
default boolean isSingleValued() {
return false;
}
/**
* Checks if this Traversable can be repeatedly traversed.
* <p>
* This method should be implemented by classes only, i.e. not by interfaces.
*
* @return true, if this Traversable is known to be traversable repeatedly, false otherwise.
*/
boolean isTraversableAgain();
/**
* An iterator by means of head() and tail(). Subclasses may want to override this method.
*
* @return A new Iterator of this Traversable elements.
*/
@Override
default Iterator<T> iterator() {
final Traversable<T> that = this;
return new AbstractIterator<T>() {
Traversable<T> traversable = that;
@Override
public boolean hasNext() {
return !traversable.isEmpty();
}
@Override
public T getNext() {
final T result = traversable.head();
traversable = traversable.tail();
return result;
}
};
}
/**
* Dual of {@linkplain #head()}, returning the last element.
*
* @return the last element.
* @throws NoSuchElementException is this is empty
*/
default T last() {
if (isEmpty()) {
throw new NoSuchElementException("last of empty Traversable");
} else {
final Iterator<T> it = iterator();
T result = null;
while (it.hasNext()) {
result = it.next();
}
return result;
}
}
/**
* Dual of {@linkplain #headOption()}, returning the last element as {@code Opiton}.
*
* @return {@code Some(element)} or {@code None} if this is empty.
*/
default Option<T> lastOption() {
return isEmpty() ? Option.none() : Option.some(last());
}
/**
* Computes the number of elements of this Traversable.
* <p>
* Same as {@link #size()}.
*
* @return the number of elements
*/
int length();
/**
* Maps the elements of this {@code Traversable} to elements of a new type preserving their order, if any.
*
* @param mapper A mapper.
* @param <U> Component type of the target Traversable
* @return a mapped Traversable
* @throws NullPointerException if {@code mapper} is null
*/
@Override
<U> Traversable<U> map(Function<? super T, ? extends U> mapper);
/**
* Calculates the maximum of this elements according to the underlying element {@code Comparator} if exists,
* or the natural order of elements.
*
* @return {@code Some(maximum)} of this elements or {@code None} if this is empty or no {@code Comparator} is applicable
*/
@SuppressWarnings("unchecked")
default Option<T> max() {
final Traversable<T> ts = isTraversableAgain() ? this : toStream();
if (isEmpty() || !(ts.head() instanceof Comparable)) {
return Option.none();
} else {
return ts.maxBy((o1, o2) -> ((Comparable<T>) o1).compareTo(o2));
}
}
/**
* Calculates the maximum of this elements using a specific comparator.
*
* @param comparator A non-null element comparator
* @return {@code Some(maximum)} of this elements or {@code None} if this is empty
* @throws NullPointerException if {@code comparator} is null
*/
default Option<T> maxBy(Comparator<? super T> comparator) {
Objects.requireNonNull(comparator, "comparator is null");
if (isEmpty()) {
return Option.none();
} else {
final T value = reduce((t1, t2) -> comparator.compare(t1, t2) >= 0 ? t1 : t2);
return Option.some(value);
}
}
/**
* Calculates the maximum of this elements within the co-domain of a specific function.
*
* @param f A function that maps this elements to comparable elements
* @param <U> The type where elements are compared
* @return The element of type T which is the maximum within U
* @throws NullPointerException if {@code f} is null.
*/
default <U extends Comparable<? super U>> Option<T> maxBy(Function<? super T, ? extends U> f) {
Objects.requireNonNull(f, "f is null");
if (isEmpty()) {
return Option.none();
} else {
final Iterator<T> iter = iterator();
T tm = iter.next();
U um = f.apply(tm);
while (iter.hasNext()) {
final T t = iter.next();
final U u = f.apply(t);
if (u.compareTo(um) > 0) {
um = u;
tm = t;
}
}
return Option.some(tm);
}
}
/**
* Calculates the minimum of this elements according to the underlying element {@code Comparator} if exists,
* or the natural order of elements.
*
* @return {@code Some(minimum)} of this elements or {@code None} if this is empty or no {@code Comparator} is applicable
*/
@SuppressWarnings("unchecked")
default Option<T> min() {
final Traversable<T> ts = isTraversableAgain() ? this : toStream();
if (isEmpty() || !(ts.head() instanceof Comparable)) {
return Option.none();
} else {
return ts.minBy((o1, o2) -> ((Comparable<T>) o1).compareTo(o2));
}
}
/**
* Calculates the minimum of this elements using a specific comparator.
*
* @param comparator A non-null element comparator
* @return {@code Some(minimum)} of this elements or {@code None} if this is empty
* @throws NullPointerException if {@code comparator} is null
*/
default Option<T> minBy(Comparator<? super T> comparator) {
Objects.requireNonNull(comparator, "comparator is null");
if (isEmpty()) {
return Option.none();
} else {
final T value = reduce((t1, t2) -> comparator.compare(t1, t2) <= 0 ? t1 : t2);
return Option.some(value);
}
}
/**
* Calculates the minimum of this elements within the co-domain of a specific function.
*
* @param f A function that maps this elements to comparable elements
* @param <U> The type where elements are compared
* @return The element of type T which is the minimum within U
* @throws NullPointerException if {@code f} is null.
*/
default <U extends Comparable<? super U>> Option<T> minBy(Function<? super T, ? extends U> f) {
Objects.requireNonNull(f, "f is null");
if (isEmpty()) {
return Option.none();
} else {
final Iterator<T> iter = iterator();
T tm = iter.next();
U um = f.apply(tm);
while (iter.hasNext()) {
final T t = iter.next();
final U u = f.apply(t);
if (u.compareTo(um) < 0) {
um = u;
tm = t;
}
}
return Option.some(tm);
}
}
/**
* Joins the elements of this by concatenating their string representations.
* <p>
* This has the same effect as calling {@code mkString("", "", "")}.
*
* @return a new String
*/
default String mkString() {
return mkString("", "", "");
}
/**
* Joins the string representations of this elements using a specific delimiter.
* <p>
* This has the same effect as calling {@code mkString(delimiter, "", "")}.
*
* @param delimiter A delimiter string put between string representations of elements of this
* @return A new String
*/
default String mkString(CharSequence delimiter) {
return mkString("", delimiter, "");
}
/**
* Joins the string representations of this elements using a specific delimiter, prefix and suffix.
* <p>
* Example: {@code List.of("a", "b", "c").mkString(", ", "Chars(", ")") = "Chars(a, b, c)"}
*
* @param prefix prefix of the resulting string
* @param delimiter A delimiter string put between string representations of elements of this
* @param suffix suffix of the resulting string
* @return a new String
*/
default String mkString(CharSequence prefix, CharSequence delimiter, CharSequence suffix) {
final StringBuilder builder = new StringBuilder(prefix);
iterator().map(String::valueOf).intersperse(String.valueOf(delimiter)).forEach(builder::append);
return builder.append(suffix).toString();
}
/**
* Joins the elements of this by concatenating their string representations.
* <p>
* This has the same effect as calling {@code mkCharSeq("", "", "")}.
*
* @return a new {@link CharSeq}
*/
default CharSeq mkCharSeq() {
return mkCharSeq("", "", "");
}
/**
* Joins the string representations of this elements using a specific delimiter.
* <p>
* This has the same effect as calling {@code mkCharSeq(delimiter, "", "")}.
*
* @param delimiter A delimiter string put between string representations of elements of this
* @return A new {@link CharSeq}
*/
default CharSeq mkCharSeq(CharSequence delimiter) {
return mkCharSeq("", delimiter, "");
}
/**
* Joins the string representations of this elements using a specific delimiter, prefix and suffix.
* <p>
* Example: {@code List.of("a", "b", "c").mkCharSeq(", ", "Chars(", ")") = CharSeq.of("Chars(a, b, c))"}
*
* @param prefix prefix of the resulting {@link CharSeq}
* @param delimiter A delimiter string put between string representations of elements of this
* @param suffix suffix of the resulting {@link CharSeq}
* @return a new {@link CharSeq}
*/
default CharSeq mkCharSeq(CharSequence prefix, CharSequence delimiter, CharSequence suffix) {
return CharSeq.of(mkString(prefix, delimiter, suffix));
}
/**
* Checks, this {@code Traversable} is not empty.
* <p>
* The call is equivalent to {@code !isEmpty()}.
*
* @return true, if an underlying value is present, false otherwise.
*/
default boolean nonEmpty() {
return !isEmpty();
}
/**
* Creates a partition of this {@code Traversable} by splitting this elements in two in distinct tarversables
* according to a predicate.
*
* @param predicate A predicate which classifies an element if it is in the first or the second traversable.
* @return A disjoint union of two traversables. The first {@code Traversable} contains all elements that satisfy the given {@code predicate}, the second {@code Traversable} contains all elements that don't. The original order of elements is preserved.
* @throws NullPointerException if predicate is null
*/
Tuple2<? extends Traversable<T>, ? extends Traversable<T>> partition(Predicate<? super T> predicate);
@Override
Traversable<T> peek(Consumer<? super T> action);
/**
* Calculates the product of this elements. Supported component types are {@code Byte}, {@code Double}, {@code Float},
* {@code Integer}, {@code Long}, {@code Short}, {@code BigInteger} and {@code BigDecimal}.
* <p>
* Examples:
* <pre>
* <code>
* List.empty().product() // = 1
* List.of(1, 2, 3).product() // = 6L
* List.of(0.1, 0.2, 0.3).product() // = 0.006
* List.of("apple", "pear").product() // throws
* </code>
* </pre>
*
* @return a {@code Number} representing the sum of this elements
* @throws UnsupportedOperationException if this elements are not numeric
*/
@SuppressWarnings("unchecked")
default Number product() {
if (isEmpty()) {
return 1;
} else {
final Iterator<?> iter = iterator();
final Object o = iter.next();
if (o instanceof Number) {
final Number head = (Number) o;
final Iterator<Number> numbers = (Iterator<Number>) iter;
if (head instanceof Integer || head instanceof Long || head instanceof Byte || head instanceof BigInteger || head instanceof Short) {
return numbers.toJavaStream().mapToLong(Number::longValue).reduce(head.longValue(), (l1, l2) -> l1 * l2);
} else {
return numbers.toJavaStream().mapToDouble(Number::doubleValue).reduce(head.doubleValue(), (d1, d2) -> d1 * d2);
}
} else {
throw new UnsupportedOperationException("not numeric");
}
}
}
/**
* Accumulates the elements of this Traversable by successively calling the given operation {@code op} from the left.
*
* @param op A BiFunction of type T
* @return the reduced value.
* @throws NoSuchElementException if this is empty
* @throws NullPointerException if {@code op} is null
*/
@Override
default T reduceLeft(BiFunction<? super T, ? super T, ? extends T> op) {
Objects.requireNonNull(op, "op is null");
if (isEmpty()) {
throw new NoSuchElementException("reduceLeft on Nil");
} else {
return tail().foldLeft(head(), op);
}
}
/**
* Shortcut for {@code isEmpty() ? Option.none() : Option.some(reduceLeft(op))}.
*
* @param op A BiFunction of type T
* @return a reduced value
* @throws NullPointerException if {@code op} is null
*/
@Override
default Option<T> reduceLeftOption(BiFunction<? super T, ? super T, ? extends T> op) {
Objects.requireNonNull(op, "op is null");
return isEmpty() ? Option.none() : Option.some(reduceLeft(op));
}
/**
* Accumulates the elements of this Traversable by successively calling the given operation {@code op} from the right.
*
* @param op An operation of type T
* @return the reduced value.
* @throws NoSuchElementException if this is empty
* @throws NullPointerException if {@code op} is null
*/
@Override
default T reduceRight(BiFunction<? super T, ? super T, ? extends T> op) {
Objects.requireNonNull(op, "op is null");
if (isEmpty()) {
throw new NoSuchElementException("reduceRight on empty");
} else {
return iterator().reduceRight(op);
}
}
/**
* Shortcut for {@code isEmpty() ? Option.none() : Option.some(reduceRight(op))}.
*
* @param op An operation of type T
* @return a reduced value
* @throws NullPointerException if {@code op} is null
*/
@Override
default Option<T> reduceRightOption(BiFunction<? super T, ? super T, ? extends T> op) {
Objects.requireNonNull(op, "op is null");
return isEmpty() ? Option.none() : Option.some(reduceRight(op));
}
/**
* Replaces the first occurrence (if exists) of the given currentElement with newElement.
*
* @param currentElement An element to be substituted.
* @param newElement A replacement for currentElement.
* @return a Traversable containing all elements of this where the first occurrence of currentElement is replaced with newELement.
*/
Traversable<T> replace(T currentElement, T newElement);
/**
* Replaces all occurrences of the given currentElement with newElement.
*
* @param currentElement An element to be substituted.
* @param newElement A replacement for currentElement.
* @return a Traversable containing all elements of this where all occurrences of currentElement are replaced with newELement.
*/
Traversable<T> replaceAll(T currentElement, T newElement);
/**
* Keeps all occurrences of the given elements from this.
*
* @param elements Elements to be kept.
* @return a Traversable containing all occurrences of the given elements.
* @throws NullPointerException if {@code elements} is null
*/
Traversable<T> retainAll(Iterable<? extends T> elements);
/**
* Computes a prefix scan of the elements of the collection.
*
* Note: The neutral element z may be applied more than once.
*
* @param zero neutral element for the operator op
* @param operation the associative operator for the scan
* @return a new traversable collection containing the prefix scan of the elements in this traversable collection
* @throws NullPointerException if {@code operation} is null.
*/
Traversable<T> scan(T zero, BiFunction<? super T, ? super T, ? extends T> operation);
/**
* Produces a collection containing cumulative results of applying the
* operator going left to right.
*
* Note: will not terminate for infinite-sized collections.
*
* Note: might return different results for different runs, unless the
* underlying collection type is ordered.
*
* @param <U> the type of the elements in the resulting collection
* @param zero the initial value
* @param operation the binary operator applied to the intermediate result and the element
* @return collection with intermediate results
* @throws NullPointerException if {@code operation} is null.
*/
<U> Traversable<U> scanLeft(U zero, BiFunction<? super U, ? super T, ? extends U> operation);
/**
* Produces a collection containing cumulative results of applying the
* operator going right to left. The head of the collection is the last
* cumulative result.
*
* Note: will not terminate for infinite-sized collections.
*
* Note: might return different results for different runs, unless the
* underlying collection type is ordered.
*
* @param <U> the type of the elements in the resulting collection
* @param zero the initial value
* @param operation the binary operator applied to the intermediate result and the element
* @return collection with intermediate results
* @throws NullPointerException if {@code operation} is null.
*/
<U> Traversable<U> scanRight(U zero, BiFunction<? super T, ? super U, ? extends U> operation);
/**
* Computes the number of elements of this Traversable.
* <p>
* Same as {@link #length()}.
*
* @return the number of elements
*/
default int size() {
return length();
}
Iterator<? extends Traversable<T>> sliding(int size);
Iterator<? extends Traversable<T>> sliding(int size, int step);
/**
* Returns a tuple where the first element is the longest prefix of elements that satisfy the given
* {@code predicate} and the second element is the remainder.
*
* @param predicate A predicate.
* @return a Tuple containing the longest prefix of elements that satisfy p and the remainder.
* @throws NullPointerException if {@code predicate} is null
*/
Tuple2<? extends Traversable<T>, ? extends Traversable<T>> span(Predicate<? super T> predicate);
/**
* Calculates the sum of this elements. Supported component types are {@code Byte}, {@code Double}, {@code Float},
* {@code Integer}, {@code Long}, {@code Short}, {@code BigInteger} and {@code BigDecimal}.
* <p>
* Examples:
* <pre>
* <code>
* List.empty().sum() // = 0
* List.of(1, 2, 3).sum() // = 6L
* List.of(0.1, 0.2, 0.3).sum() // = 0.6
* List.of("apple", "pear").sum() // throws
* </code>
* </pre>
*
* @return a {@code Number} representing the sum of this elements
* @throws UnsupportedOperationException if this elements are not numeric
*/
@SuppressWarnings("unchecked")
default Number sum() {
if (isEmpty()) {
return 0;
} else {
final Iterator<?> iter = iterator();
final Object o = iter.next();
if (o instanceof Number) {
final Number head = (Number) o;
final Iterator<Number> numbers = (Iterator<Number>) iter;
if (head instanceof Integer || head instanceof Long || head instanceof Byte || head instanceof BigInteger || head instanceof Short) {
return numbers.foldLeft(head.longValue(), (n1, n2) -> n1 + n2.longValue());
} else {
return numbers.foldLeft(head.doubleValue(), (n1, n2) -> n1 + n2.doubleValue());
}
} else {
throw new UnsupportedOperationException("not numeric");
}
}
}
/**
* Drops the first element of a non-empty Traversable.
*
* @return A new instance of Traversable containing all elements except the first.
* @throws UnsupportedOperationException if this is empty
*/
Traversable<T> tail();
/**
* Drops the first element of a non-empty Traversable and returns an {@code Option}.
*
* @return {@code Some(traversable)} or {@code None} if this is empty.
*/
Option<? extends Traversable<T>> tailOption();
/**
* Takes the first n elements of this or all elements, if this length < n.
* <p>
* The result is equivalent to {@code sublist(0, max(0, min(length(), n)))} but does not throw if {@code n < 0} or
* {@code n > length()}.
* <p>
* In the case of {@code n < 0} the empty instance is returned, in the case of {@code n > length()} this is returned.
*
* @param n The number of elements to take.
* @return A new instance consisting the first n elements of this or all elements, if this has less than n elements.
*/
Traversable<T> take(int n);
/**
* Takes the last n elements of this or all elements, if this length < n.
* <p>
* The result is equivalent to {@code sublist(max(0, min(length(), length() - n)), n)}, i.e. takeRight will not
* throw if {@code n < 0} or {@code n > length()}.
* <p>
* In the case of {@code n < 0} the empty instance is returned, in the case of {@code n > length()} this is returned.
*
* @param n The number of elements to take.
* @return A new instance consisting the first n elements of this or all elements, if this has less than n elements.
*/
Traversable<T> takeRight(int n);
/**
* Takes elements until the predicate holds for the current element.
* <p>
* Note: This is essentially the same as {@code takeWhile(predicate.negate())}. It is intended to be used with
* method references, which cannot be negated directly.
*
* @param predicate A condition tested subsequently for this elements.
* @return a new instance consisting of all elements until the first which does satisfy the given predicate.
* @throws NullPointerException if {@code predicate} is null
*/
Traversable<T> takeUntil(Predicate<? super T> predicate);
/**
* Takes elements while the predicate holds for the current element.
*
* @param predicate A condition tested subsequently for the contained elements.
* @return a new instance consisting of all elements until the first which does not satisfy the given predicate.
* @throws NullPointerException if {@code predicate} is null
*/
Traversable<T> takeWhile(Predicate<? super T> predicate);
/**
* Unzips this elements by mapping this elements to pairs which are subsequently split into two distinct
* sets.
*
* @param unzipper a function which converts elements of this to pairs
* @param <T1> 1st element type of a pair returned by unzipper
* @param <T2> 2nd element type of a pair returned by unzipper
* @return A pair of set containing elements split by unzipper
* @throws NullPointerException if {@code unzipper} is null
*/
<T1, T2> Tuple2<? extends Traversable<T1>, ? extends Traversable<T2>> unzip(
Function<? super T, Tuple2<? extends T1, ? extends T2>> unzipper);
/**
* Unzips this elements by mapping this elements to triples which are subsequently split into three distinct
* sets.
*
* @param unzipper a function which converts elements of this to pairs
* @param <T1> 1st element type of a triplet returned by unzipper
* @param <T2> 2nd element type of a triplet returned by unzipper
* @param <T3> 3rd element type of a triplet returned by unzipper
* @return A triplet of set containing elements split by unzipper
* @throws NullPointerException if {@code unzipper} is null
*/
<T1, T2, T3> Tuple3<? extends Traversable<T1>, ? extends Traversable<T2>, ? extends Traversable<T3>> unzip3(
Function<? super T, Tuple3<? extends T1, ? extends T2, ? extends T3>> unzipper);
/**
* Returns a traversable formed from this traversable and another Iterable collection by combining
* corresponding elements in pairs. If one of the two iterables is longer than the other, its remaining elements
* are ignored.
* <p>
* The length of the returned traversable is the minimum of the lengths of this traversable and {@code that}
* iterable.
*
* @param <U> The type of the second half of the returned pairs.
* @param that The Iterable providing the second half of each result pair.
* @return a new traversable containing pairs consisting of corresponding elements of this traversable and {@code that} iterable.
* @throws NullPointerException if {@code that} is null
*/
<U> Traversable<Tuple2<T, U>> zip(Iterable<? extends U> that);
/**
* Returns a traversable formed from this traversable and another Iterable collection by mapping elements.
* If one of the two iterables is longer than the other, its remaining elements are ignored.
* <p>
* The length of the returned traversable is the minimum of the lengths of this traversable and {@code that}
* iterable.
*
* @param <U> The type of the second parameter of the mapper.
* @param <R> The type of the mapped elements.
* @param that The Iterable providing the second parameter of the mapper.
* @param mapper a mapper.
* @return a new traversable containing mapped elements of this traversable and {@code that} iterable.
* @throws NullPointerException if {@code that} or {@code mapper} is null
*/
<U, R> Traversable<R> zipWith(Iterable<? extends U> that, BiFunction<? super T, ? super U, ? extends R> mapper);
/**
* Returns a traversable formed from this traversable and another Iterable by combining corresponding elements in
* pairs. If one of the two collections is shorter than the other, placeholder elements are used to extend the
* shorter collection to the length of the longer.
* <p>
* The length of the returned traversable is the maximum of the lengths of this traversable and {@code that}
* iterable.
* <p>
* Special case: if this traversable is shorter than that elements, and that elements contains duplicates, the
* resulting traversable may be shorter than the maximum of the lengths of this and that because a traversable
* contains an element at most once.
* <p>
* If this Traversable is shorter than that, thisElem values are used to fill the result.
* If that is shorter than this Traversable, thatElem values are used to fill the result.
*
* @param <U> The type of the second half of the returned pairs.
* @param that The Iterable providing the second half of each result pair.
* @param thisElem The element to be used to fill up the result if this traversable is shorter than that.
* @param thatElem The element to be used to fill up the result if that is shorter than this traversable.
* @return A new traversable containing pairs consisting of corresponding elements of this traversable and that.
* @throws NullPointerException if {@code that} is null
*/
<U> Traversable<Tuple2<T, U>> zipAll(Iterable<? extends U> that, T thisElem, U thatElem);
/**
* Zips this traversable with its indices.
*
* @return A new traversable containing all elements of this traversable paired with their index, starting with 0.
*/
Traversable<Tuple2<T, Integer>> zipWithIndex();
/**
* Returns a traversable formed from this traversable and another Iterable collection by mapping elements.
* If one of the two iterables is longer than the other, its remaining elements are ignored.
* <p>
* The length of the returned traversable is the minimum of the lengths of this traversable and {@code that}
* iterable.
*
* @param <U> The type of the mapped elements.
* @param mapper a mapper.
* @return a new traversable containing mapped elements of this traversable and {@code that} iterable.
* @throws NullPointerException if {@code mapper} is null
*/
<U> Traversable<U> zipWithIndex(BiFunction<? super T, ? super Integer, ? extends U> mapper);
}
|
package com.chiorichan.framework;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import com.chiorichan.Loader;
import com.chiorichan.http.PersistentSession;
import com.sun.jersey.core.util.Base64;
public class HttpUtilsWrapper extends WebUtils
{
PersistentSession sess;
public HttpUtilsWrapper(PersistentSession _sess)
{
sess = _sess;
}
protected String findPackagePath( String pack )
{
try
{
Site site = sess.getSite();
return findPackagePathWithException( pack, site );
}
catch ( FileNotFoundException e )
{
try
{
Site site = Loader.getSiteManager().getSiteById( "framework" );
return findPackagePathWithException( pack, site );
}
catch ( FileNotFoundException e1 )
{
Loader.getLogger().warning( e1.getMessage() );
return "";
}
}
}
public String readPackage( String pack ) throws IOException
{
return readPackage( pack, sess.getSite() );
}
public String evalPackage( String pack ) throws IOException, CodeParsingException
{
Evaling eval = sess.getEvaling();
return evalPackage( eval, pack, sess.getSite() );
}
public String evalFile( File file ) throws IOException, CodeParsingException
{
return evalFile( file.getAbsolutePath() );
}
public String evalFile( String absoluteFile ) throws IOException, CodeParsingException
{
Evaling eval = sess.getEvaling();
return evalFile( eval, absoluteFile );
}
public String evalGroovy( String source ) throws IOException, CodeParsingException
{
return evalGroovy( source, "" );
}
public String evalGroovy( String source, String filePath ) throws IOException, CodeParsingException
{
Evaling eval = sess.getEvaling();
return evalGroovy( eval, source, filePath );
}
public byte[] readUrl( String url ) throws IOException
{
return readUrl( url, null, null );
}
public byte[] readUrl( String surl, String user, String pass ) throws IOException
{
ByteArrayOutputStream out = new ByteArrayOutputStream();
URL url = new URL( surl );
URLConnection uc = url.openConnection();
if ( user != null || pass != null )
{
String userpass = user + ":" + pass;
String basicAuth = "Basic " + new String( new Base64().encode( userpass.getBytes() ) );
uc.setRequestProperty( "Authorization", basicAuth );
}
InputStream is = uc.getInputStream();
byte[] byteChunk = new byte[4096];
int n;
while ( ( n = is.read( byteChunk ) ) > 0 )
{
out.write( byteChunk, 0, n );
}
is.close();
return out.toByteArray();
}
}
|
package cz.cuni.lf1.lge.ThunderSTORM;
import ij.IJ;
import java.net.URL;
import java.net.URLConnection;
import java.util.Iterator;
import java.util.ServiceConfigurationError;
import java.util.ServiceLoader;
import java.util.Vector;
/**
* A class for loading modules at runtime.
*/
public class ModuleLoader {
/**
* Loads implementations of sublcasses of IModule interface. It uses the
* imagej plugin classloader, so it looks for implementations in the imagej
* plugin directory. For the module to be loaded, you must place a jar with
* an implementation of one of the subclasses of IModule. The jar must
* contain, in the folder META-INF/services, a file named after the full
* name of the implemented interface (for example
* cz.cuni.lf1.lge.ThunderSTORM.detectors.IDetector) and the content of the
* file is full names of the classes implementing the interface. Each on a
* separate line. The file must be in UTF-8 (without BOM!) See
* {@link ServiceLoader} for more details.
*
* <br/>
* The implementation must provide a no-arguments constructor so the module
* can be instantiated.
*
* If there is an error while loading a module, the error is logged and the
* method attempts to continue loading other modules. Exception is thrown
* only when no modules are succesfully loaded.
*
* @return a vector of instances of the specified class (instantiated by the
* no-args constructor)
* @throws RuntimeException if no modules were loaded.
*/
public static <T extends IModuleUI> Vector<T> getUIModules(Class<T> c) {
//workaround a bug when service loading does not work after refreshing menus in ImageJ
boolean oldUseCaching = setUseCaching(false);
Vector<T> retval = new Vector<T>();
try {
ServiceLoader loader = ServiceLoader.load(c, IJ.getClassLoader());
for(Iterator<T> it = loader.iterator(); it.hasNext();) {
//when something goes wrong while loading modules, log the error and try to continue
try {
retval.add(it.next());
} catch(ServiceConfigurationError e) {
IJ.handleException(e);
}
}
} catch(Throwable e) {
IJ.handleException(e);
} finally {
setUseCaching(oldUseCaching);
}
if(retval.isEmpty()) {
//throw exception only when no modules are succesfully loaded
throw new RuntimeException("No modules of type " + c.getSimpleName() + " loaded.");
}
return retval;
}
public static <T extends IModule> Vector<T> getModules(Class<T> c) {
//workaround a bug when service loading does not work after refreshing menus in ImageJ
boolean oldUseCaching = setUseCaching(false);
Vector<T> retval = new Vector<T>();
try {
ServiceLoader loader = ServiceLoader.load(c, IJ.getClassLoader());
for(Iterator<T> it = loader.iterator(); it.hasNext();) {
//when something goes wrong while loading modules, log the error and try to continue
try {
retval.add(it.next());
} catch(ServiceConfigurationError e) {
IJ.handleException(e);
}
}
} catch(Throwable e) {
IJ.handleException(e);
} finally {
setUseCaching(oldUseCaching);
}
if(retval.isEmpty()) {
//throw exception only when no modules are succesfully loaded
throw new RuntimeException("No modules of type " + c.getSimpleName() + " loaded.");
}
return retval;
}
/**
* Enables or disables caching for URLConnection.
*
* @return the value of useCaching before this call
*/
private static boolean setUseCaching(boolean useCache) {
try {
URLConnection URLConnection = new URL("http://localhost/").openConnection();
boolean oldValue = URLConnection.getDefaultUseCaches();
URLConnection.setDefaultUseCaches(false);
return oldValue;
} catch(Exception ex) {
return true;
}
}
}
|
package fr.minuskube.inv.content;
import fr.minuskube.inv.ClickableItem;
import java.util.Arrays;
public interface Pagination {
ClickableItem[] getPageItems();
int getPage();
Pagination page(int page);
boolean isFirst();
boolean isLast();
Pagination first();
Pagination previous();
Pagination next();
Pagination last();
Pagination addToIterator(SlotIterator iterator);
Pagination setItems(ClickableItem... items);
Pagination setItemsPerPage(int itemsPerPage);
class Impl implements Pagination {
private int currentPage;
private ClickableItem[] items = new ClickableItem[0];
private int itemsPerPage = 5;
@Override
public ClickableItem[] getPageItems() {
return Arrays.copyOfRange(items,
currentPage * itemsPerPage,
(currentPage + 1) * itemsPerPage);
}
@Override
public int getPage() {
return this.currentPage;
}
@Override
public Pagination page(int page) {
this.currentPage = page;
return this;
}
@Override
public boolean isFirst() {
return this.currentPage == 0;
}
@Override
public boolean isLast() {
int pageCount = (int) Math.ceil((double) this.items.length / this.itemsPerPage);
return this.currentPage == pageCount - 1;
}
@Override
public Pagination first() {
this.currentPage = 0;
return this;
}
@Override
public Pagination previous() {
if(!isFirst())
this.currentPage
return this;
}
@Override
public Pagination next() {
if(!isLast())
this.currentPage++;
return this;
}
@Override
public Pagination last() {
this.currentPage = this.items.length / this.itemsPerPage;
return this;
}
@Override
public Pagination addToIterator(SlotIterator iterator) {
for(ClickableItem item : getPageItems()) {
iterator.next().set(item);
if(iterator.ended())
break;
}
return this;
}
@Override
public Pagination setItems(ClickableItem... items) {
this.items = items;
return this;
}
@Override
public Pagination setItemsPerPage(int itemsPerPage) {
this.itemsPerPage = itemsPerPage;
return this;
}
}
}
|
package org.spine3.server.entity;
import com.google.protobuf.Descriptors;
import com.google.protobuf.Message;
import com.google.protobuf.Timestamp;
import org.spine3.base.Identifiers;
import org.spine3.protobuf.Messages;
import org.spine3.server.entity.status.EntityStatus;
import javax.annotation.CheckReturnValue;
import javax.annotation.Nullable;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import static com.google.common.base.Preconditions.checkNotNull;
import static org.spine3.protobuf.Timestamps.getCurrentTime;
import static org.spine3.server.reflect.Classes.getGenericParameterType;
/**
* A server-side object with an identity.
*
* <p>An entity identifier can be of one of the following types:
* <ul>
* <li>String
* <li>Long
* <li>Integer
* <li>A class implementing {@link Message}
* </ul>
*
* <p>Consider using {@code Message}-based IDs if you want to have typed IDs in your code, and/or
* if you need to have IDs with some structure inside. Examples of such structural IDs are:
* <ul>
* <li>EAN value used in bar codes
* <li>ISBN
* <li>Phone number
* <li>email address as a couple of local-part and domain
* </ul>
*
*
* <p>A state of an entity is defined as a protobuf message and basic versioning attributes.
* The entity keeps only its latest state and meta information associated with this state.
*
* @param <I> the type of the entity ID
* @param <S> the type of the entity state
* @author Alexander Yevsyikov
* @author Alexander Litus
*/
public abstract class Entity<I, S extends Message> {
/** The index of the declaration of the generic parameter type {@code I} in this class. */
private static final int ID_CLASS_GENERIC_INDEX = 0;
/** The index of the declaration of the generic parameter type {@code S} in this class. */
public static final int STATE_CLASS_GENERIC_INDEX = 1;
private final I id;
@Nullable
private S state;
@Nullable
private Timestamp whenModified;
private int version;
private EntityStatus status = EntityStatus.getDefaultInstance();
protected Entity(I id) {
checkNotNull(id);
Identifiers.checkSupported(id.getClass());
this.id = id;
}
/**
* Sets the object into the default state.
*
* <p>Results of this method call are:
* <ul>
* <li>The state object is set to the value produced by {@link #getDefaultState()}.
* <li>The version number is set to zero.
* <li>The {@link #whenModified} field is set to the system time of the call.
* <li>The {@link #status} field is set to the default instance.
* </ul>
*
* <p>This method cannot be called from within {@code Entity} constructor because
* the call to {@link #getDefaultState()} relies on completed initialization
* of the instance.
*/
void init() {
setState(getDefaultState(), 0, getCurrentTime());
this.status = EntityStatus.getDefaultInstance();
}
/**
* Obtains the ID of the entity.
*/
@CheckReturnValue
public I getId() {
return id;
}
static <E extends Entity<I, ?>, I> Constructor<E> getConstructor(Class<E> entityClass, Class<I> idClass) {
try {
final Constructor<E> result = entityClass.getDeclaredConstructor(idClass);
result.setAccessible(true);
return result;
} catch (NoSuchMethodException ignored) {
throw noSuchConstructor(entityClass.getName(), idClass.getName());
}
}
private static IllegalStateException noSuchConstructor(String entityClass, String idClass) {
final String errMsg = String.format("%s class must declare a constructor with a single %s ID parameter.",
entityClass, idClass);
return new IllegalStateException(new NoSuchMethodException(errMsg));
}
/**
* Creates new entity and sets it to the default state.
*
* @param constructor the constructor to use
* @param id the ID of the entity
* @param <I> the type of entity IDs
* @param <E> the type of the entity
* @return new entity
*/
static <I, E extends Entity<I, ?>> E createEntity(Constructor<E> constructor, I id) {
try {
final E result = constructor.newInstance(id);
result.init();
return result;
} catch (InvocationTargetException | InstantiationException | IllegalAccessException e) {
throw new IllegalStateException(e);
}
}
/**
* Obtains the default entity state.
*
* @return an empty instance of the state class
*/
@CheckReturnValue
protected S getDefaultState() {
final Class<? extends Entity> entityClass = getClass();
final DefaultStateRegistry registry = DefaultStateRegistry.getInstance();
if (!registry.contains(entityClass)) {
final S state = createDefaultState();
registry.put(entityClass, state);
}
@SuppressWarnings("unchecked") // cast is safe because this type of messages is saved to the map
final S defaultState = (S) registry.get(entityClass);
return defaultState;
}
private S createDefaultState() {
final Class<S> stateClass = getStateClass();
final S result = Messages.newInstance(stateClass);
return result;
}
/**
* Obtains the entity state.
*
* @return the current state object or the value produced by {@link #getDefaultState()}
* if the state wasn't set
*/
@CheckReturnValue
public S getState() {
final S result = state == null
? getDefaultState()
: state;
return result;
}
@SuppressWarnings({"NoopMethodInAbstractClass", "UnusedParameters"})
// Have this no-op method to prevent enforcing implementation in all sub-classes.
protected void validate(S state) throws IllegalStateException {
// Do nothing by default.
}
/**
* Validates and sets the state.
*
* @param state the state object to set
* @param version the entity version to set
* @param whenLastModified the time of the last modification to set
* @see #validate(S)
*/
protected void setState(S state, int version, Timestamp whenLastModified) {
validate(state);
this.state = checkNotNull(state);
setVersion(version, whenLastModified);
}
/**
* Sets status for the entity.
*/
void setStatus(EntityStatus status) {
this.status = status;
}
/**
* Sets version information of the entity.
*
* @param version the version number of the entity
* @param whenLastModified the time of the last modification of the entity
*/
protected void setVersion(int version, Timestamp whenLastModified) {
this.version = version;
this.whenModified = checkNotNull(whenLastModified);
}
/**
* Updates the state incrementing the version number and recording time of the modification.
*
* @param newState a new state to set
*/
protected void incrementState(S newState) {
setState(newState, incrementVersion(), getCurrentTime());
}
/**
* Obtains the version number of the entity.
*
* @return the version number or zero if the entity was not modified
*/
public int getVersion() {
return version;
}
/**
* Advances the current version by one and records the time of the modification.
*
* @return new version number
*/
protected int incrementVersion() {
++version;
whenModified = getCurrentTime();
return version;
}
/**
* Obtains the timestamp of the last modification.
*
* @return the timestamp instance or the value produced by
* {@link Timestamp#getDefaultInstance()} if the state wasn't set
* @see #setState(Message, int, Timestamp)
*/
@CheckReturnValue
public Timestamp whenModified() {
final Timestamp result = whenModified == null
? Timestamp.getDefaultInstance()
: whenModified;
return result;
}
/**
* Obtains the entity status.
*/
protected EntityStatus getStatus() {
final EntityStatus result = this.status == null
? EntityStatus.getDefaultInstance()
: this.status;
return result;
}
/**
* Tests whether the entity is marked as archived.
*
* @return {@code true} if the entity is archived, {@code false} otherwise
*/
protected boolean isArchived() {
return getStatus().getArchived();
}
/**
* Sets {@code archived} status flag to the passed value.
*/
protected void setArchived(boolean archived) {
this.status = getStatus().toBuilder()
.setArchived(archived)
.build();
}
/**
* Tests whether the entity is marked as deleted.
*
* @return {@code true} if the entity is deleted, {@code false} otherwise
*/
protected boolean isDeleted() {
return getStatus().getDeleted();
}
/**
* Sets {@code deleted} status flag to the passed value.
*/
protected void setDeleted(boolean deleted) {
this.status = getStatus().toBuilder()
.setDeleted(deleted)
.build();
}
/**
* Retrieves the ID class of the entities of the given class using reflection.
*
* @param entityClass the entity class to inspect
* @param <I> the entity ID type
* @return the entity ID class
*/
public static <I> Class<I> getIdClass(Class<? extends Entity<I, ?>> entityClass) {
checkNotNull(entityClass);
final Class<I> idClass = getGenericParameterType(entityClass, ID_CLASS_GENERIC_INDEX);
return idClass;
}
/**
* Obtains the class of the entity state.
*/
protected Class<S> getStateClass() {
final Class<? extends Entity> clazz = getClass();
return getStateClass(clazz);
}
/**
* Retrieves the state class of the passed entity class.
*
* @param entityClass the entity class to inspect
* @param <S> the entity state type
* @return the entity state class
*/
public static <S extends Message> Class<S> getStateClass(Class<? extends Entity> entityClass) {
final Class<S> result = getGenericParameterType(entityClass, STATE_CLASS_GENERIC_INDEX);
return result;
}
/**
* Returns the short name of the ID type.
*
* @return
* <ul>
* <li>Short Protobuf type name if the value is {@link Message}.
* <li>Simple class name of the value, otherwise.
* </ul>
*/
public String getShortIdTypeName() {
if (id instanceof Message) {
//noinspection TypeMayBeWeakened
final Message message = (Message) id;
final Descriptors.Descriptor descriptor = message.getDescriptorForType();
final String result = descriptor.getName();
return result;
} else {
final String result = id.getClass().getSimpleName();
return result;
}
}
@Override
@SuppressWarnings("ConstantConditions" /* It is required to check for null. */)
public boolean equals(Object anotherObj) {
if (this == anotherObj) {
return true;
}
if (anotherObj == null ||
getClass() != anotherObj.getClass()) {
return false;
}
@SuppressWarnings("unchecked") // parameter must have the same generics
final Entity<I, S> another = (Entity<I, S>) anotherObj;
if (!getId().equals(another.getId())) {
return false;
}
if (!getState().equals(another.getState())) {
return false;
}
if (getVersion() != another.getVersion()) {
return false;
}
if (!getStatus().equals(another.getStatus())) {
return false;
}
final boolean result = whenModified().equals(another.whenModified());
return result;
}
@Override
public int hashCode() {
int result = getId().hashCode();
result = 31 * result + getState().hashCode();
result = 31 * result + whenModified().hashCode();
result = 31 * result + getVersion();
result = 31 * result + getStatus().hashCode();
return result;
}
}
|
package guru.haun.hackery.items;
import java.util.Iterator;
import java.util.List;
import guru.haun.hackery.ExploitUtils;
import guru.haun.hackery.exploits.IExploit;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLiving;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Items;
import net.minecraft.item.EnumAction;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.world.World;
public class ExploitItem extends Item {
private static IExploit getExploit(ItemStack is) {
return ExploitUtils.getExploitById(is.getItemDamage());
}
public ExploitItem() {
setHasSubtypes(true);
setMaxDamage(0);
setMaxStackSize(1);
setTextureName("hackery:Exploit");
}
public void getSubItems(Item item, CreativeTabs tab, List list){
List<IExploit> ex = ExploitUtils.getAllExploits();
Iterator<IExploit> it = ex.iterator();
while(it.hasNext()){
list.add(new ItemStack(this,1,it.next().getId()));
}
}
public boolean hitEntity(ItemStack is, EntityLivingBase attacker, EntityLivingBase defender){
return false;
}
public EnumAction getItemUseAction(ItemStack is){
IExploit ex = ExploitUtils.getExploitById(is.getItemDamage());
if(ex.isRanged()){
return EnumAction.bow;
}else{
if(ex.canTargetSelf())
return EnumAction.eat;
}
return EnumAction.none;
}
public boolean onItemUseFirst(ItemStack stack, EntityPlayer player, World w, int x, int y, int z, int side, float hitX, float hitY, float hitZ){
return false;
}
public boolean onLeftClickEntity(ItemStack stack, EntityPlayer player, Entity target){
IExploit ex = this.getExploit(stack);
if(ex.canTargetOthers()){
if(target instanceof EntityPlayer)
ex.targetUser((EntityPlayer)target);
else if(ex.canTargetMobs() && target instanceof EntityLiving)
ex.targetMob(target);
return true;
}
return false;
}
public boolean onItemUse(ItemStack stack, EntityPlayer player, World w, int x, int y, int z, int side, float hitX, float hitY, float hitZ){
IExploit ex = this.getExploit(stack);
if(ex.canTargetOthers() && ex.isRanged()){
return true;
}else if(ex.canTargetSelf()){
ex.targetUser(player);
return true;
}
return false;
}
public ItemStack onItemRightClick(ItemStack is, World world, EntityPlayer player){
IExploit ex = this.getExploit(is);
if(ex.canTargetOthers() && ex.isRanged()) {
super.onItemRightClick(is, world, player);
}else if(ex.canTargetSelf()){
ex.targetUser(player);
return is;
}
return is;
}
public String getUnlocalizedName(ItemStack is) {
return getExploit(is).getUnlocalizedName();
}
}
|
package info.danidiaz.util;
import java.util.Collection;
import java.util.Deque;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.NoSuchElementException;
/**
* <p>An implementation of a doubly linked list.<p>
*
* <p>Some methods which the standard interfaces designate as optional have not
* been implemented and throw {@link UnsupportedOperationException}. In
* particular random-access methods, which are bound to be inefficient for
* linked lists.</p>
*
* <p>Also not implemented are methods like {@link subList} that are out of
* scope for the exercise.</p>
*
* <p>Intermediate insertions and deletions can be done using the {@link
* ForwardIterator} returned by {@link listIterator()}.
*
* <p>Use {@link descendingIterator()} to get an iterator that goes backwards
* from the end of the list. The {@link forward()} method changes direction.</p>
*
* <p>The iterator implementation contains most of the logic.</p>
*
*/
public final class DoublyLinkedList<E> implements List<E>, Deque<E>
{
private Node<E> first;
private Node<E> last;
private int size;
public DoublyLinkedList() {
super();
}
@Override
public void addFirst(E e) {
listIterator().add(e);
}
@Override
public void addLast(E e) {
listIteratorAtEnd().add(e);
}
@Override
public E element() {
return getFirst();
}
@Override
public E getFirst() {
if (isEmpty()) {
throw new NoSuchElementException();
}
return first.getValue();
}
@Override
public E getLast() {
if (isEmpty()) {
throw new NoSuchElementException();
}
return last.getValue();
}
@Override
public boolean offer(E e) {
return offerLast(e);
}
@Override
public boolean offerFirst(E e) {
addFirst(e);
return true;
}
@Override
public boolean offerLast(E e) {
addLast(e);
return true;
}
@Override
public E peek() {
return peekFirst();
}
@Override
public E peekFirst() {
if (isEmpty()) {
return null;
}
return first.getValue();
}
@Override
public E peekLast() {
if (isEmpty()) {
return null;
}
return last.getValue();
}
@Override
public E poll() {
return pollFirst();
}
@Override
public E pollFirst() {
final ForwardIterator iter = listIterator();
if (iter.hasNext()) {
E result = iter.next();
iter.remove();
return result;
}
return null;
}
@Override
public E pollLast() {
final ForwardIterator iter = listIteratorAtEnd();
if (iter.hasPrevious()) {
E result = iter.previous();
iter.remove();
return result;
}
return null;
}
@Override
public E pop() {
return removeFirst();
}
@Override
public void push(E e) {
addFirst(e);
}
@Override
public E remove() {
return removeFirst();
}
@Override
public E removeFirst() {
final ForwardIterator iter = listIterator();
if (iter.hasNext()) {
E result = iter.next();
iter.remove();
return result;
}
throw new NoSuchElementException();
}
@Override
public E removeLast() {
final ForwardIterator iter = listIteratorAtEnd();
if (iter.hasPrevious()) {
E result = iter.previous();
iter.remove();
return result;
}
throw new NoSuchElementException();
}
@Override
public boolean remove(Object o) {
return removeFirstOccurrence(o);
}
@Override
public boolean removeFirstOccurrence(Object o) {
ListIterator<E> iter = iterOf(o);
if (iter!=null) {
iter.remove();
return true;
}
return false;
}
@Override
public boolean removeLastOccurrence(Object o) {
ListIterator<E> iter = iterLastOf(o);
if (iter!=null) {
iter.remove();
return true;
}
return false;
}
@Override
public boolean add(E e) {
addLast(e);
return true;
}
@Override
public boolean addAll(Collection<? extends E> c) {
for (E e:c) {
addLast(e);
}
return true;
}
@Override
public boolean isEmpty() {
return size == 0;
}
@Override
public void clear() {
first = null;
last = null;
size = 0;
}
@Override
public boolean contains(Object o) {
return indexOf(o) != -1;
}
@Override
public boolean containsAll(Collection<?> c) {
for (Object o:c) {
if (!contains(o)) {
return false;
}
}
return true;
}
@Override
public E get(int index) {
if (index >= 0 && index < size()) {
Iterator<E> iter = listIterator(index);
return iter.next();
}
throw new IndexOutOfBoundsException();
}
/**
* Variant of {@link indexOf} which returns an iterator.
* @param o Element to search for.
* @return null if the element isn't present, otherwise an iterator that has
* just passed the element.
*/
public ForwardIterator iterOf(Object o) {
ForwardIterator iter = listIterator();
if (o == null) {
while (iter.hasNext()) {
E element = iter.next();
if (element == null) {
return iter;
}
}
} else {
while (iter.hasNext()) {
E element = iter.next();
if (o.equals(element)) {
return iter;
}
}
}
return null;
}
@Override
public int indexOf(Object o) {
ListIterator<E> iter = iterOf(o);
return iter==null? -1 : iter.previousIndex();
}
@Override
public Iterator<E> iterator() {
return listIterator();
}
/**
* Variant of {@link lastIndexOf} which returns an iterator.
* @param o Element to search for.
* @return null if the element isn't present, otherwise an iterator that has
* just passed the element while going backwards.
*/
public ForwardIterator iterLastOf(Object o) {
ForwardIterator iter = listIteratorAtEnd();
if (o == null) {
while (iter.hasPrevious()) {
E element = iter.previous();
if (element == null) {
return iter;
}
}
} else {
while (iter.hasPrevious()) {
E element = iter.previous();
if (element != null && element.equals(o)) {
return iter;
}
}
}
return null;
}
@Override
public int lastIndexOf(Object o) {
ListIterator<E> iter = iterLastOf(o);
return iter==null? -1 : iter.nextIndex();
}
@Override
public ForwardIterator listIterator() {
return new ForwardIterator(0,null,first);
}
@Override
public DescendingIterator descendingIterator() {
return new ForwardIterator(size,last,null).descending();
}
public ForwardIterator listIteratorAtEnd() {
return descendingIterator().forward();
}
@Override
public ForwardIterator listIterator(int index) {
final ForwardIterator iter = listIterator();
for (int i=0;i<index;i++) {
if (i < index-1 && !iter.hasNext()) {
throw new IndexOutOfBoundsException();
}
iter.next();
}
return iter;
}
@Override
public Object[] toArray() {
Object [] result = new Object[size()];
ListIterator<E> iter = listIterator();
while (iter.hasNext()) {
final int index = iter.nextIndex();
final E element = iter.next();
result[index] = element;
}
return result;
}
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append('[');
Iterator<E> iter = iterator();
while (iter.hasNext()) {
E e = iter.next();
if (e==null) {
builder.append("null");
} else {
builder.append(e.toString());
}
if (iter.hasNext()) {
builder.append(',');
}
}
builder.append(']');
return builder.toString();
}
/**
* This method has O(1) complexity, because the size is cached.
*/
@Override
public int size() {
return size;
}
/** Unsupported.
* @throws UnsupportedOperationException always
*/
@Override
public E remove(int index) {
throw new UnsupportedOperationException();
}
/** Unsupported.
* @throws UnsupportedOperationException always
*/
@Override
public boolean removeAll(Collection<?> c) {
throw new UnsupportedOperationException();
}
/** Unsupported.
* @throws UnsupportedOperationException always
*/
@Override
public boolean retainAll(Collection<?> c) {
throw new UnsupportedOperationException();
}
/** Unsupported.
* @throws UnsupportedOperationException always
*/
@Override
public E set(int index, E element) {
throw new UnsupportedOperationException();
}
/** Unsupported.
* @throws UnsupportedOperationException always
*/
@Override
public List<E> subList(int fromIndex, int toIndex) {
throw new UnsupportedOperationException();
}
/** Unsupported.
* @throws UnsupportedOperationException always
*/
@Override
public void add(int index, E element) {
throw new UnsupportedOperationException();
}
/** Unsupported.
* @throws UnsupportedOperationException always
*/
@Override
public boolean addAll(int index, Collection<? extends E> c) {
throw new UnsupportedOperationException();
}
/** Unsupported.
* @throws UnsupportedOperationException always
*/
@Override
public <T> T[] toArray(T[] a) {
throw new UnsupportedOperationException();
}
private final static class Node<E> {
private E value;
private Node<E> previous;
private Node<E> next;
public Node(E value, Node<E> previous,Node<E> next) {
super();
this.value = value;
this.previous = previous;
this.next = next;
}
public Node<E> getPrevious() {
return previous;
}
public void setPrevious(Node<E> previous) {
this.previous = previous;
}
public Node<E> getNext() {
return next;
}
public void setNext(Node<E> next) {
this.next = next;
}
public E getValue() {
return value;
}
public void setValue(E e) {
value = e;
}
// Useful for debugging.
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append(String.format("{ val = %s",getValue()));
if (getPrevious()!=null) {
builder.append(String.format(", previous = %s ",getPrevious().getValue()));
}
if (getNext()!=null) {
builder.append(String.format(", next = %s ",getNext().getValue()));
}
builder.append(" }");
return builder.toString();
}
}
public final class ForwardIterator implements ListIterator<E> {
// Index of the element that would be returned by a subsequent call to
// next().
private int index;
private Node<E> iterPrevious;
private Node<E> iterNext;
// See https://docs.oracle.com/javase/7/docs/api/java/util/ListIterator.html#remove()
// for an explanation of the necessity of keeping track of the last movement.
private Node<E> lastMovement = null;
public ForwardIterator(int index, Node<E> iterPrevious, Node<E> iterNext) {
super();
this.index = index;
this.iterPrevious = iterPrevious;
this.iterNext = iterNext;
}
@Override
public void add(E arg0) {
index++;
final Node<E> newNode = new Node<>(arg0,iterPrevious,iterNext);
if (iterPrevious==null) {
first = newNode;
} else {
iterPrevious.setNext(newNode);
}
if (iterNext==null) {
last = newNode;
} else {
iterNext.setPrevious(newNode);
}
iterPrevious = newNode;
lastMovement = null;
size++;
}
@Override
public boolean hasNext() {
return iterNext != null;
}
@Override
public boolean hasPrevious() {
return iterPrevious != null;
}
@Override
public E next() {
if (iterNext == null) {
throw new NoSuchElementException();
}
index++;
final E result = iterNext.getValue();
lastMovement = iterNext;
iterPrevious = iterNext;
iterNext = iterNext.getNext();
return result;
}
@Override
public E previous() {
if (iterPrevious == null) {
throw new NoSuchElementException();
}
index
final E result = iterPrevious.getValue();
lastMovement = iterPrevious;
iterNext = iterPrevious;
iterPrevious = iterPrevious.getPrevious();
return result;
}
@Override
public int nextIndex() {
return index;
}
@Override
public int previousIndex() {
return index-1;
}
@Override
public void remove() {
if (lastMovement == null) {
throw new IllegalStateException();
}
if (lastMovement == iterPrevious) { // last movement was forwards
index
iterPrevious = iterPrevious.getPrevious();
if (iterPrevious == null) { // removal put us an the beginning
first = iterNext;
} else {
iterPrevious.setNext(iterNext);
}
if (iterNext == null) { // we were at end of list
last = iterPrevious;
} else {
iterNext.setPrevious(iterPrevious);
}
} else if (lastMovement == iterNext) { // last movement was backwards
iterNext = iterNext.getNext();
if (iterNext == null) { // removal put us at the end
last = iterPrevious;
} else {
iterNext.setPrevious(iterPrevious);
}
if (iterPrevious == null) { // we were at the beginning of list
first = iterNext;
} else {
iterPrevious.setNext(iterNext);
}
}
lastMovement = null;
size
}
@Override
public void set(E e) {
if (lastMovement == null) {
throw new IllegalStateException();
}
lastMovement.setValue(e);
}
public DescendingIterator descending() {
return new DescendingIterator(this);
}
}
public final class DescendingIterator implements Iterator<E> {
private ForwardIterator iter;
public DescendingIterator(DoublyLinkedList<E>.ForwardIterator iter) {
super();
this.iter = iter;
}
@Override
public boolean hasNext() {
return iter.hasPrevious();
}
@Override
public E next() {
return iter.previous();
}
@Override
public void remove() {
iter.remove();
}
public ForwardIterator forward() {
return iter;
}
}
}
|
package com.intellij.openapi.vcs.changes.ui;
import com.intellij.ide.DeleteProvider;
import com.intellij.ide.dnd.*;
import com.intellij.ide.util.DeleteHandler;
import com.intellij.ide.util.treeView.TreeState;
import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.actionSystem.ex.DataConstantsEx;
import com.intellij.openapi.fileEditor.OpenFileDescriptor;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.vcs.FilePath;
import com.intellij.openapi.vcs.VcsBundle;
import com.intellij.openapi.vcs.changes.*;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiDirectory;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiManager;
import com.intellij.ui.PopupHandler;
import com.intellij.ui.SmartExpander;
import com.intellij.ui.TreeSpeedSearch;
import com.intellij.ui.TreeUtils;
import com.intellij.ui.awt.RelativePoint;
import com.intellij.ui.awt.RelativeRectangle;
import com.intellij.util.EditSourceOnDoubleClickHandler;
import com.intellij.util.containers.Convertor;
import com.intellij.util.ui.Tree;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import javax.swing.table.TableCellRenderer;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeCellRenderer;
import javax.swing.tree.TreePath;
import javax.swing.tree.TreeSelectionModel;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* @author max
*/
public class ChangesListView extends Tree implements DataProvider, DeleteProvider, AdvancedDnDSource {
private ChangesListView.DropTarget myDropTarget;
private DnDManager myDndManager;
private ChangeListOwner myDragOwner;
private final Project myProject;
private TreeState myTreeState;
private boolean myShowFlatten = false;
@NonNls public static final String UNVERSIONED_FILES_KEY = "ChangeListView.UnversionedFiles";
@NonNls public static final String MISSING_FILES_KEY = "ChangeListView.MissingFiles";
public ChangesListView(final Project project) {
myProject = project;
getModel().setRoot(new ChangesBrowserNode(TreeModelBuilder.ROOT_NODE_VALUE));
setShowsRootHandles(true);
setRootVisible(false);
new TreeSpeedSearch(this, new NodeToTextConvertor());
SmartExpander.installOn(this);
}
public DefaultTreeModel getModel() {
return (DefaultTreeModel)super.getModel();
}
public static FilePath safeCastToFilePath(Object o) {
if (o instanceof FilePath) return (FilePath)o;
return null;
}
public synchronized void addMouseListener(MouseListener l) {
super.addMouseListener(l); //To change body of overridden methods use File | Settings | File Templates.
}
public static String getRelativePath(FilePath parent, FilePath child) {
if (parent == null) return child.getPath().replace('/', File.separatorChar);
return child.getPath().substring(parent.getPath().length() + 1).replace('/', File.separatorChar);
}
public void installDndSupport(ChangeListOwner owner) {
myDragOwner = owner;
myDropTarget = new DropTarget();
myDndManager = DnDManager.getInstance(myProject);
myDndManager.registerSource(this);
myDndManager.registerTarget(myDropTarget, this);
}
public void dispose() {
if (myDropTarget != null) {
myDndManager.unregisterSource(this);
myDndManager.unregisterTarget(myDropTarget, this);
myDropTarget = null;
myDndManager = null;
myDragOwner = null;
}
}
private void storeState() {
myTreeState = TreeState.createOn(this, (ChangesBrowserNode)getModel().getRoot());
}
private void restoreState() {
myTreeState.applyTo(this, (ChangesBrowserNode)getModel().getRoot());
}
public boolean isShowFlatten() {
return myShowFlatten;
}
public void setShowFlatten(final boolean showFlatten) {
myShowFlatten = showFlatten;
}
public void updateModel(List<LocalChangeList> changeLists, List<VirtualFile> unversionedFiles, final List<File> locallyDeletedFiles) {
storeState();
TreeModelBuilder builder = new TreeModelBuilder(myProject, isShowFlatten());
final DefaultTreeModel model = builder.buildModel(changeLists, unversionedFiles, locallyDeletedFiles);
setModel(model);
setCellRenderer(new ChangeBrowserNodeRenderer(myProject, isShowFlatten()));
expandPath(new TreePath(((ChangesBrowserNode)model.getRoot()).getPath()));
restoreState();
}
@Nullable
public Object getData(String dataId) {
if (DataConstants.CHANGES.equals(dataId)) {
return getSelectedChanges();
}
else if (DataConstants.CHANGE_LISTS.equals(dataId)) {
return getSelectedChangeLists();
}
else if (DataConstants.VIRTUAL_FILE_ARRAY.equals(dataId)) {
return getSelectedFiles();
}
else if (DataConstants.NAVIGATABLE.equals(dataId)) {
final VirtualFile[] files = getSelectedFiles();
if (files.length == 1) {
return new OpenFileDescriptor(myProject, files[0], 0);
}
}
else if (DataConstants.NAVIGATABLE_ARRAY.equals(dataId)) {
return ChangesUtil.getNavigatableArray(myProject, getSelectedFiles());
}
else if (DataConstantsEx.DELETE_ELEMENT_PROVIDER.equals(dataId)) {
return this;
}
else if (UNVERSIONED_FILES_KEY.equals(dataId)) {
return getSelectedUnversionedFiles();
}
else if (MISSING_FILES_KEY.equals(dataId)) {
return getSelectedMissingFiles();
}
return null;
}
private List<VirtualFile> getSelectedUnversionedFiles() {
List<VirtualFile> files = new ArrayList<VirtualFile>();
final TreePath[] paths = getSelectionPaths();
if (paths != null) {
for (TreePath path : paths) {
ChangesBrowserNode node = (ChangesBrowserNode)path.getLastPathComponent();
files.addAll(node.getAllFilesUnder());
}
}
return files;
}
private List<File> getSelectedMissingFiles() {
List<File> files = new ArrayList<File>();
final TreePath[] paths = getSelectionPaths();
if (paths != null) {
for (TreePath path : paths) {
ChangesBrowserNode node = (ChangesBrowserNode)path.getLastPathComponent();
files.addAll(node.getAllIOFilesUnder());
}
}
return files;
}
private VirtualFile[] getSelectedFiles() {
final Change[] changes = getSelectedChanges();
ArrayList<VirtualFile> files = new ArrayList<VirtualFile>();
for (Change change : changes) {
final ContentRevision afterRevision = change.getAfterRevision();
if (afterRevision != null) {
final VirtualFile file = afterRevision.getFile().getVirtualFile();
if (file != null && file.isValid()) {
files.add(file);
}
}
}
files.addAll(getSelectedUnversionedFiles());
return files.toArray(new VirtualFile[files.size()]);
}
public void deleteElement(DataContext dataContext) {
PsiElement[] elements = getPsiElements(dataContext);
DeleteHandler.deletePsiElement(elements, myProject);
}
public boolean canDeleteElement(DataContext dataContext) {
PsiElement[] elements = getPsiElements(dataContext);
return DeleteHandler.shouldEnableDeleteAction(elements);
}
private PsiElement[] getPsiElements(final DataContext dataContext) {
List<PsiElement> elements = new ArrayList<PsiElement>();
final PsiManager manager = PsiManager.getInstance(myProject);
List<VirtualFile> files = (List<VirtualFile>)dataContext.getData(UNVERSIONED_FILES_KEY);
if (files == null) return PsiElement.EMPTY_ARRAY;
for (VirtualFile file : files) {
if (file.isDirectory()) {
final PsiDirectory psiDir = manager.findDirectory(file);
if (psiDir != null) {
elements.add(psiDir);
}
}
else {
final PsiFile psiFile = manager.findFile(file);
if (psiFile != null) {
elements.add(psiFile);
}
}
}
return elements.toArray(new PsiElement[elements.size()]);
}
@NotNull
private Change[] getSelectedChanges() {
Set<Change> changes = new HashSet<Change>();
for (ChangeList list : getSelectedChangeLists()) {
changes.addAll(list.getChanges());
}
final TreePath[] paths = getSelectionPaths();
if (paths == null) return new Change[0];
for (TreePath path : paths) {
ChangesBrowserNode node = (ChangesBrowserNode)path.getLastPathComponent();
changes.addAll(node.getAllChangesUnder());
}
return changes.toArray(new Change[changes.size()]);
}
@NotNull
private ChangeList[] getSelectedChangeLists() {
Set<ChangeList> lists = new HashSet<ChangeList>();
final TreePath[] paths = getSelectionPaths();
if (paths == null) return new ChangeList[0];
for (TreePath path : paths) {
ChangesBrowserNode node = (ChangesBrowserNode)path.getLastPathComponent();
final Object userObject = node.getUserObject();
if (userObject instanceof ChangeList) {
lists.add((ChangeList)userObject);
}
}
return lists.toArray(new ChangeList[lists.size()]);
}
public void setMenuActions(final ActionGroup menuGroup) {
PopupHandler.installPopupHandler(this, menuGroup, ActionPlaces.CHANGES_VIEW, ActionManager.getInstance());
EditSourceOnDoubleClickHandler.install(this);
}
@SuppressWarnings({"UtilityClassWithoutPrivateConstructor"})
private static class DragImageFactory {
private static void drawSelection(JTable table, int column, Graphics g, final int width) {
int y = 0;
final int[] rows = table.getSelectedRows();
final int height = table.getRowHeight();
for (int row : rows) {
final TableCellRenderer renderer = table.getCellRenderer(row, column);
final Component component = renderer.getTableCellRendererComponent(table, table.getValueAt(row, column), false, false, row, column);
g.translate(0, y);
component.setBounds(0, 0, width, height);
boolean wasOpaque = false;
if (component instanceof JComponent) {
final JComponent j = (JComponent)component;
if (j.isOpaque()) wasOpaque = true;
j.setOpaque(false);
}
component.paint(g);
if (wasOpaque) {
((JComponent)component).setOpaque(true);
}
y += height;
g.translate(0, -y);
}
}
private static void drawSelection(JTree tree, Graphics g, final int width) {
int y = 0;
final int[] rows = tree.getSelectionRows();
final int height = tree.getRowHeight();
for (int row : rows) {
final TreeCellRenderer renderer = tree.getCellRenderer();
final Object value = tree.getPathForRow(row).getLastPathComponent();
if (value == null) continue;
final Component component = renderer.getTreeCellRendererComponent(tree, value, false, false, false, row, false);
if (component.getFont() == null) {
component.setFont(tree.getFont());
}
g.translate(0, y);
component.setBounds(0, 0, width, height);
boolean wasOpaque = false;
if (component instanceof JComponent) {
final JComponent j = (JComponent)component;
if (j.isOpaque()) wasOpaque = true;
j.setOpaque(false);
}
component.paint(g);
if (wasOpaque) {
((JComponent)component).setOpaque(true);
}
y += height;
g.translate(0, -y);
}
}
public static Image createImage(final JTable table, int column) {
final int height = Math.max(20, Math.min(100, table.getSelectedRowCount() * table.getRowHeight()));
final int width = table.getColumnModel().getColumn(column).getWidth();
final BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2 = (Graphics2D)image.getGraphics();
g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.7f));
drawSelection(table, column, g2, width);
return image;
}
public static Image createImage(final JTree tree) {
final TreeSelectionModel model = tree.getSelectionModel();
final TreePath[] paths = model.getSelectionPaths();
int count = 0;
final List<ChangesBrowserNode> nodes = new ArrayList<ChangesBrowserNode>();
for (final TreePath path : paths) {
final ChangesBrowserNode node = (ChangesBrowserNode)path.getLastPathComponent();
if (!node.isLeaf()) {
nodes.add(node);
count += node.getCount();
}
}
for (TreePath path : paths) {
final ChangesBrowserNode element = (ChangesBrowserNode)path.getLastPathComponent();
boolean child = false;
for (final ChangesBrowserNode node : nodes) {
if (node.isNodeChild(element)) {
child = true;
break;
}
}
if (!child) {
if (element.isLeaf()) count++;
} else if (!element.isLeaf()) {
count -= element.getCount();
}
}
final JLabel label = new JLabel(VcsBundle.message("changes.view.dnd.label", count));
label.setOpaque(true);
label.setForeground(tree.getForeground());
label.setBackground(tree.getBackground());
label.setFont(tree.getFont());
label.setSize(label.getPreferredSize());
final BufferedImage image = new BufferedImage(label.getWidth(), label.getHeight(), BufferedImage.TYPE_INT_ARGB);
Graphics2D g2 = (Graphics2D)image.getGraphics();
g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.7f));
label.paint(g2);
g2.dispose();
return image;
}
}
private static class ChangeListDragBean {
private ChangesListView myView;
private Change[] myChanges;
private List<VirtualFile> myUnversionedFiles;
private LocalChangeList myDropList = null;
public ChangeListDragBean(final ChangesListView view, final Change[] changes, final List<VirtualFile> unversionedFiles) {
myView = view;
myChanges = changes;
myUnversionedFiles = unversionedFiles;
}
public ChangesListView getView() {
return myView;
}
public Change[] getChanges() {
return myChanges;
}
public List<VirtualFile> getUnversionedFiles() {
return myUnversionedFiles;
}
public void setTargetList(final LocalChangeList dropList) {
myDropList = dropList;
}
public LocalChangeList getDropList() {
return myDropList;
}
}
public class DropTarget implements DnDTarget {
public boolean update(DnDEvent aEvent) {
aEvent.hideHighlighter();
aEvent.setDropPossible(false, "");
Object attached = aEvent.getAttachedObject();
if (!(attached instanceof ChangeListDragBean)) return false;
final ChangeListDragBean dragBean = (ChangeListDragBean)attached;
if (dragBean.getView() != ChangesListView.this) return false;
if (dragBean.getChanges().length == 0 && dragBean.getUnversionedFiles().size() == 0) return false;
dragBean.setTargetList(null);
RelativePoint dropPoint = aEvent.getRelativePoint();
Point onTree = dropPoint.getPoint(ChangesListView.this);
final TreePath dropPath = getPathForLocation(onTree.x, onTree.y);
if (dropPath == null) return false;
Object object;
ChangesBrowserNode dropNode = (ChangesBrowserNode)dropPath.getLastPathComponent();
do {
if (dropNode == null || dropNode.isRoot()) return false;
object = dropNode.getUserObject();
if (object instanceof ChangeList) break;
dropNode = (ChangesBrowserNode)dropNode.getParent();
}
while (true);
LocalChangeList dropList = (LocalChangeList)object;
final Change[] changes = dragBean.getChanges();
for (Change change : dropList.getChanges()) {
for (Change incomingChange : changes) {
if (change == incomingChange) return false;
}
}
final Rectangle tableCellRect = getPathBounds(new TreePath(dropNode.getPath()));
aEvent.setHighlighting(new RelativeRectangle(ChangesListView.this, tableCellRect), DnDEvent.DropTargetHighlightingType.RECTANGLE);
aEvent.setDropPossible(true, null);
dragBean.setTargetList(dropList);
return false;
}
public void drop(DnDEvent aEvent) {
Object attached = aEvent.getAttachedObject();
if (!(attached instanceof ChangeListDragBean)) return;
final ChangeListDragBean dragBean = (ChangeListDragBean)attached;
final LocalChangeList dropList = dragBean.getDropList();
if (dropList != null) {
myDragOwner.moveChangesTo(dropList, dragBean.getChanges());
final List<VirtualFile> unversionedFiles = dragBean.getUnversionedFiles();
if (unversionedFiles != null) {
myDragOwner.addUnversionedFiles(dropList, unversionedFiles);
}
}
}
public void cleanUpOnLeave() {
}
public void updateDraggedImage(Image image, Point dropPoint, Point imageOffset) {
}
}
private static class NodeToTextConvertor implements Convertor<TreePath, String> {
public String convert(final TreePath path) {
ChangesBrowserNode node = (ChangesBrowserNode)path.getLastPathComponent();
final Object object = node.getUserObject();
if (object instanceof ChangeList) {
final ChangeList list = ((ChangeList)object);
return list.getName();
}
else if (object instanceof Change) {
final Change change = (Change)object;
final FilePath filePath = ChangesUtil.getFilePath(change);
return filePath.getName();
}
else if (object instanceof VirtualFile) {
final VirtualFile file = (VirtualFile)object;
return file.getName();
}
else if (object instanceof FilePath) {
final FilePath filePath = (FilePath)object;
return filePath.getName();
}
else if (object instanceof Module) {
final Module module = (Module)object;
return module.getName();
}
return node.toString();
}
}
public boolean canStartDragging(DnDAction action, Point dragOrigin) {
return action == DnDAction.MOVE && (getSelectedChanges().length > 0 || getSelectedUnversionedFiles().size() > 0);
}
public DnDDragStartBean startDragging(DnDAction action, Point dragOrigin) {
return new DnDDragStartBean(new ChangeListDragBean(this, getSelectedChanges(), getSelectedUnversionedFiles()));
}
@Nullable
public Pair<Image, Point> createDraggedImage(DnDAction action, Point dragOrigin) {
final Image image = DragImageFactory.createImage(this);
return new Pair<Image, Point>(image, new Point(-image.getWidth(null), -image.getHeight(null)));
}
public void dragDropEnd() {
}
public void dropActionChanged(final int gestureModifiers) {
}
@NotNull
public JComponent getComponent() {
return this;
}
public void processMouseEvent(final MouseEvent e) {
if (MouseEvent.MOUSE_RELEASED == e.getID() && !isSelectionEmpty() && !e.isShiftDown() && !e.isPopupTrigger()) {
if (isOverSelection(e.getPoint())) {
clearSelection();
final TreePath path = getPathForLocation(e.getPoint().x, e.getPoint().y);
if (path != null) {
setSelectionPath(path);
e.consume();
}
}
}
super.processMouseEvent(e);
}
public boolean isOverSelection(final Point point) {
return TreeUtils.isOverSelection(this, point);
}
}
|
package com.intellij.openapi.vcs.changes.ui;
import com.intellij.ide.util.PropertiesComponent;
import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.keymap.KeymapManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.EmptyRunnable;
import com.intellij.openapi.util.IconLoader;
import com.intellij.openapi.util.SystemInfo;
import com.intellij.openapi.vcs.FilePath;
import com.intellij.openapi.vcs.FileStatus;
import com.intellij.openapi.vcs.FileStatusManager;
import com.intellij.openapi.vcs.VcsBundle;
import com.intellij.openapi.vcs.changes.Change;
import com.intellij.openapi.vcs.changes.ChangesUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.ui.ColoredListCellRenderer;
import com.intellij.ui.ListSpeedSearch;
import com.intellij.ui.PopupHandler;
import com.intellij.ui.SimpleTextAttributes;
import com.intellij.ui.treeStructure.actions.CollapseAllAction;
import com.intellij.ui.treeStructure.actions.ExpandAllAction;
import com.intellij.util.Icons;
import com.intellij.util.ui.Tree;
import com.intellij.util.ui.tree.TreeUtil;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeCellRenderer;
import javax.swing.tree.TreePath;
import java.awt.*;
import java.awt.event.*;
import java.io.File;
import java.util.*;
import java.util.List;
/**
* @author max
*/
public abstract class ChangesTreeList<T> extends JPanel {
private Tree myTree;
private JList myList;
private Project myProject;
private final boolean myShowCheckboxes;
private final boolean myHighlightProblems;
private boolean myShowFlatten;
private Collection<T> myIncludedChanges;
private Runnable myDoubleClickHandler = EmptyRunnable.getInstance();
@NonNls private static final String TREE_CARD = "Tree";
@NonNls private static final String LIST_CARD = "List";
@NonNls private static final String ROOT = "root";
private CardLayout myCards;
@NonNls private final static String FLATTEN_OPTION_KEY = "ChangesBrowser.SHOW_FLATTEN";
public ChangesTreeList(final Project project, Collection<T> initiallyIncluded, final boolean showCheckboxes,
final boolean highlightProblems) {
myProject = project;
myShowCheckboxes = showCheckboxes;
myHighlightProblems = highlightProblems;
myIncludedChanges = new HashSet<T>(initiallyIncluded);
myCards = new CardLayout();
setLayout(myCards);
final int checkboxWidth = new JCheckBox().getPreferredSize().width;
myTree = new Tree(ChangesBrowserNode.create(myProject, ROOT)) {
public Dimension getPreferredScrollableViewportSize() {
Dimension size = super.getPreferredScrollableViewportSize();
size = new Dimension(size.width + 10, size.height);
return size;
}
protected void processMouseEvent(MouseEvent e) {
if (e.getID() == MouseEvent.MOUSE_PRESSED) {
int row = myTree.getRowForLocation(e.getX(), e.getY());
if (row >= 0) {
final Rectangle baseRect = myTree.getRowBounds(row);
baseRect.setSize(checkboxWidth, baseRect.height);
if (baseRect.contains(e.getPoint())) {
myTree.setSelectionRow(row);
toggleSelection();
}
}
}
super.processMouseEvent(e);
}
public int getToggleClickCount() {
return -1;
}
};
myTree.setRootVisible(false);
myTree.setShowsRootHandles(true);
myTree.setCellRenderer(new MyTreeCellRenderer());
myList = new JList(new DefaultListModel());
myList.setVisibleRowCount(10);
add(new JScrollPane(myList), LIST_CARD);
add(new JScrollPane(myTree), TREE_CARD);
new ListSpeedSearch(myList) {
protected String getElementText(Object element) {
if (element instanceof Change) {
return ChangesUtil.getFilePath((Change)element).getName();
}
return super.getElementText(element);
}
};
myList.setCellRenderer(new MyListCellRenderer());
new MyToggleSelectionAction().registerCustomShortcutSet(new CustomShortcutSet(KeyStroke.getKeyStroke(KeyEvent.VK_SPACE, 0)), this);
registerKeyboardAction(new ActionListener() {
public void actionPerformed(ActionEvent e) {
includeSelection();
}
}, KeyStroke.getKeyStroke(KeyEvent.VK_INSERT, 0), JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
registerKeyboardAction(new ActionListener() {
public void actionPerformed(ActionEvent e) {
excludeSelection();
}
}, KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0), JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
myList.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
final int idx = myList.locationToIndex(e.getPoint());
if (idx >= 0) {
final Rectangle baseRect = myList.getCellBounds(idx, idx);
baseRect.setSize(checkboxWidth, baseRect.height);
if (baseRect.contains(e.getPoint())) {
toggleSelection();
e.consume();
}
else if (e.getClickCount() == 2) {
myDoubleClickHandler.run();
e.consume();
}
}
}
});
myTree.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
final int row = myTree.getRowForLocation(e.getPoint().x, e.getPoint().y);
if (row >= 0) {
final Rectangle baseRect = myTree.getRowBounds(row);
baseRect.setSize(checkboxWidth, baseRect.height);
if (!baseRect.contains(e.getPoint()) && e.getClickCount() == 2) {
myDoubleClickHandler.run();
e.consume();
}
}
}
});
setShowFlatten(PropertiesComponent.getInstance(myProject).isTrueValue(FLATTEN_OPTION_KEY));
}
public void setDoubleClickHandler(final Runnable doubleClickHandler) {
myDoubleClickHandler = doubleClickHandler;
}
public void installPopupHandler(ActionGroup group) {
PopupHandler.installUnknownPopupHandler(myList, group, ActionManager.getInstance());
PopupHandler.installUnknownPopupHandler(myTree, group, ActionManager.getInstance());
}
public Dimension getPreferredSize() {
return new Dimension(400, 400);
}
public boolean isShowFlatten() {
return myShowFlatten;
}
public void setShowFlatten(final boolean showFlatten) {
myShowFlatten = showFlatten;
myCards.show(this, myShowFlatten ? LIST_CARD : TREE_CARD);
if (myList.hasFocus() || myTree.hasFocus()) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
requestFocus();
}
});
}
}
public void requestFocus() {
if (myShowFlatten) {
myList.requestFocus();
}
else {
myTree.requestFocus();
}
}
public void setChangesToDisplay(final List<T> changes) {
final DefaultListModel listModel = (DefaultListModel)myList.getModel();
final List<T> sortedChanges = new ArrayList<T>(changes);
Collections.sort(sortedChanges, new Comparator<T>() {
public int compare(final T o1, final T o2) {
return TreeModelBuilder.getPathForObject(o1).getName().compareToIgnoreCase(TreeModelBuilder.getPathForObject(o1).getName());
}
});
listModel.removeAllElements();
for (T change : sortedChanges) {
listModel.addElement(change);
}
final DefaultTreeModel model = buildTreeModel(changes);
myTree.setModel(model);
SwingUtilities.invokeLater(new Runnable() {
public void run() {
TreeUtil.expandAll(myTree);
if (myIncludedChanges.size() > 0) {
int listSelection = 0;
int count = 0;
for (T change : changes) {
if (myIncludedChanges.contains(change)) {
listSelection = count;
break;
}
count ++;
}
ChangesBrowserNode root = (ChangesBrowserNode)model.getRoot();
Enumeration enumeration = root.depthFirstEnumeration();
while (enumeration.hasMoreElements()) {
ChangesBrowserNode node = (ChangesBrowserNode)enumeration.nextElement();
final NodeState state = getNodeStatus(node);
if (node != root && state == NodeState.CLEAR) {
myTree.collapsePath(new TreePath(node.getPath()));
}
}
enumeration = root.depthFirstEnumeration();
int scrollRow = 0;
while (enumeration.hasMoreElements()) {
ChangesBrowserNode node = (ChangesBrowserNode)enumeration.nextElement();
final NodeState state = getNodeStatus(node);
if (state == NodeState.FULL && node.isLeaf()) {
scrollRow = myTree.getRowForPath(new TreePath(node.getPath()));
break;
}
}
if (changes.size() > 0) {
myList.setSelectedIndex(listSelection);
myList.ensureIndexIsVisible(listSelection);
myTree.setSelectionRow(scrollRow);
TreeUtil.showRowCentered(myTree, scrollRow, false);
}
}
}
});
}
protected abstract DefaultTreeModel buildTreeModel(final List<T> changes);
@SuppressWarnings({"SuspiciousMethodCalls"})
private void toggleSelection() {
boolean hasExcluded = false;
for (T value : getSelectedChanges()) {
if (!myIncludedChanges.contains(value)) {
hasExcluded = true;
}
}
if (hasExcluded) {
includeSelection();
}
else {
excludeSelection();
}
repaint();
}
private void includeSelection() {
for (T change : getSelectedChanges()) {
myIncludedChanges.add(change);
}
repaint();
}
@SuppressWarnings({"SuspiciousMethodCalls"})
private void excludeSelection() {
for (T change : getSelectedChanges()) {
myIncludedChanges.remove(change);
}
repaint();
}
@NotNull
public List<T> getSelectedChanges() {
if (myShowFlatten) {
final Object[] o = myList.getSelectedValues();
final List<T> changes = new ArrayList<T>();
for (Object anO : o) {
changes.add((T)anO);
}
return changes;
}
else {
List<T> changes = new ArrayList<T>();
final TreePath[] paths = myTree.getSelectionPaths();
if (paths != null) {
for (TreePath path : paths) {
ChangesBrowserNode node = (ChangesBrowserNode)path.getLastPathComponent();
changes.addAll(getSelectedObjects(node));
}
}
return changes;
}
}
protected abstract List<T> getSelectedObjects(final ChangesBrowserNode node);
@Nullable
public T getLeadSelection() {
if (myShowFlatten) {
final int index = myList.getLeadSelectionIndex();
ListModel listModel = myList.getModel();
if (index < 0 || index >= listModel.getSize()) return null;
//noinspection unchecked
return (T)listModel.getElementAt(index);
}
else {
final TreePath path = myTree.getSelectionPath();
if (path == null) return null;
final List<T> changes = getSelectedObjects(((ChangesBrowserNode)path.getLastPathComponent()));
return changes.size() > 0 ? changes.get(0) : null;
}
}
public void includeChange(final T change) {
myIncludedChanges.add(change);
myTree.repaint();
myList.repaint();
}
public void excludeChange(final T change) {
myIncludedChanges.remove(change);
myTree.repaint();
myList.repaint();
}
public boolean isIncluded(final T change) {
return myIncludedChanges.contains(change);
}
public Collection<T> getIncludedChanges() {
return myIncludedChanges;
}
public AnAction[] getTreeActions() {
final ToggleShowDirectoriesAction directoriesAction = new ToggleShowDirectoriesAction();
final ExpandAllAction expandAllAction = new ExpandAllAction(myTree) {
public void update(AnActionEvent e) {
e.getPresentation().setVisible(!myShowFlatten);
}
};
final CollapseAllAction collapseAllAction = new CollapseAllAction(myTree) {
public void update(AnActionEvent e) {
e.getPresentation().setVisible(!myShowFlatten);
}
};
final SelectAllAction selectAllAction = new SelectAllAction();
final AnAction[] actions = new AnAction[]{directoriesAction, expandAllAction, collapseAllAction, selectAllAction};
directoriesAction.registerCustomShortcutSet(
new CustomShortcutSet(KeyStroke.getKeyStroke(KeyEvent.VK_P, SystemInfo.isMac ? KeyEvent.META_DOWN_MASK : KeyEvent.CTRL_DOWN_MASK)),
this);
expandAllAction.registerCustomShortcutSet(
new CustomShortcutSet(KeymapManager.getInstance().getActiveKeymap().getShortcuts(IdeActions.ACTION_EXPAND_ALL)),
myTree);
collapseAllAction.registerCustomShortcutSet(
new CustomShortcutSet(KeymapManager.getInstance().getActiveKeymap().getShortcuts(IdeActions.ACTION_COLLAPSE_ALL)),
myTree);
selectAllAction.registerCustomShortcutSet(
new CustomShortcutSet(KeyStroke.getKeyStroke(KeyEvent.VK_A, SystemInfo.isMac ? KeyEvent.META_DOWN_MASK : KeyEvent.CTRL_DOWN_MASK)),
this);
return actions;
}
private class MyTreeCellRenderer extends JPanel implements TreeCellRenderer {
private final ChangesBrowserNodeRenderer myTextRenderer;
private final JCheckBox myCheckBox;
public MyTreeCellRenderer() {
super(new BorderLayout());
myCheckBox = new JCheckBox();
myTextRenderer = new ChangesBrowserNodeRenderer(myProject, false, myHighlightProblems);
myCheckBox.setBackground(null);
setBackground(null);
if (myShowCheckboxes) {
add(myCheckBox, BorderLayout.WEST);
}
add(myTextRenderer, BorderLayout.CENTER);
}
public Component getTreeCellRendererComponent(JTree tree,
Object value,
boolean selected,
boolean expanded,
boolean leaf,
int row,
boolean hasFocus) {
myTextRenderer.getTreeCellRendererComponent(tree, value, selected, expanded, leaf, row, hasFocus);
if (myShowCheckboxes) {
ChangesBrowserNode node = (ChangesBrowserNode)value;
NodeState state = getNodeStatus(node);
myCheckBox.setSelected(state != NodeState.CLEAR);
myCheckBox.setEnabled(state != NodeState.PARTIAL);
revalidate();
return this;
}
else {
return myTextRenderer;
}
}
}
private static enum NodeState {
FULL, CLEAR, PARTIAL
}
private NodeState getNodeStatus(ChangesBrowserNode node) {
boolean hasIncluded = false;
boolean hasExcluded = false;
for (T change : getSelectedObjects(node)) {
if (myIncludedChanges.contains(change)) {
hasIncluded = true;
}
else {
hasExcluded = true;
}
}
if (hasIncluded && hasExcluded) return NodeState.PARTIAL;
if (hasIncluded) return NodeState.FULL;
return NodeState.CLEAR;
}
private class MyListCellRenderer extends JPanel implements ListCellRenderer {
private final ColoredListCellRenderer myTextRenderer;
public final JCheckBox myCheckbox;
public MyListCellRenderer() {
super(new BorderLayout());
myCheckbox = new JCheckBox();
myTextRenderer = new ColoredListCellRenderer() {
protected void customizeCellRenderer(JList list, Object value, int index, boolean selected, boolean hasFocus) {
final FilePath path = TreeModelBuilder.getPathForObject(value);
setIcon(path.getFileType().getIcon());
final FileStatus fileStatus;
if (value instanceof Change) {
fileStatus = ((Change) value).getFileStatus();
}
else {
final VirtualFile virtualFile = path.getVirtualFile();
if (virtualFile != null) {
fileStatus = FileStatusManager.getInstance(myProject).getStatus(virtualFile);
}
else {
fileStatus = FileStatus.NOT_CHANGED;
}
}
append(path.getName(), new SimpleTextAttributes(SimpleTextAttributes.STYLE_PLAIN, fileStatus.getColor(), null));
final File parentFile = path.getIOFile().getParentFile();
if (parentFile != null) {
append(" (" + parentFile.getPath() + ")", SimpleTextAttributes.GRAYED_ATTRIBUTES);
}
}
};
myCheckbox.setBackground(null);
setBackground(null);
if (myShowCheckboxes) {
add(myCheckbox, BorderLayout.WEST);
}
add(myTextRenderer, BorderLayout.CENTER);
}
public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
myTextRenderer.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
if (myShowCheckboxes) {
myCheckbox.setSelected(myIncludedChanges.contains(value));
return this;
}
else {
return myTextRenderer;
}
}
}
private class MyToggleSelectionAction extends AnAction {
public void actionPerformed(AnActionEvent e) {
toggleSelection();
}
}
public class ToggleShowDirectoriesAction extends ToggleAction {
public ToggleShowDirectoriesAction() {
super(VcsBundle.message("changes.action.show.directories.text"),
VcsBundle.message("changes.action.show.directories.description"),
Icons.DIRECTORY_CLOSED_ICON);
}
public boolean isSelected(AnActionEvent e) {
return !PropertiesComponent.getInstance(myProject).isTrueValue(FLATTEN_OPTION_KEY);
}
public void setSelected(AnActionEvent e, boolean state) {
PropertiesComponent.getInstance(myProject).setValue(FLATTEN_OPTION_KEY, String.valueOf(!state));
setShowFlatten(!state);
}
}
private class SelectAllAction extends AnAction {
private SelectAllAction() {
super("Select All", "Select all items", IconLoader.getIcon("/actions/selectall.png"));
}
public void actionPerformed(final AnActionEvent e) {
if (myShowFlatten) {
final int count = myList.getModel().getSize();
if (count > 0) {
myList.setSelectionInterval(0, count-1);
}
}
else {
final int count = myTree.getRowCount();
if (count > 0) {
myTree.setSelectionInterval(0, count-1);
}
}
}
}
}
|
package io.metacake.core.process;
import io.metacake.core.common.MilliTimer;
import io.metacake.core.input.Action;
import io.metacake.core.input.InputSystem;
import io.metacake.core.output.OutputSystem;
/**
* This class run is the main execution loop of the game
*
* @author florence
* @author rpless
*/
public class GameRunner {
InputSystem inputSystem;
OutputSystem outputSystem;
private boolean isRunning = false;
public GameRunner(InputSystem inputSystem, OutputSystem outputSystem) {
this.inputSystem = inputSystem;
this.outputSystem = outputSystem;
}
/**
* Execute the main game loop in the current thread. This method returns after #stop has been called.
* <p>The game loop will attempt to put {@code interval} milliseconds between the start of each game loop.
* This WILL fail if the GameState#tick takes more than {@code interval} milliseconds to run</p>
* <p>When #stop is called the function will terminate after the current state finishes its tick cycle</p>
* @param state the initial state of the game
* @param interval the number of milliseconds requested to be between the start of each loop.
*/
public void mainLoop(GameState state, long interval) {
isRunning = true;
MilliTimer timer = new MilliTimer(interval);
// TODO: excpetion handling
while (isRunning) {
outputSystem.addToRenderQueue(state);
updateTriggers(state);
updateRecognizers(state);
state = state.tick();
timer.block();
}
}
/**
* Tell the main game loop to stop. If the main game loop is not running, this has no effect.
*/
public void stop(){
isRunning = false;
}
/**
* If the state requests the the input system gets new action triggers, give them.
* @param s The current state
*/
private void updateTriggers(GameState s){
if(s.shouldReplaceActionTriggers()) {
inputSystem.setActionTriggers(s.getNewActionTriggers());
}
}
/**
* handle the clearing actions and passing those actions to the state recognizers.
* @param s the current state
*/
private void updateRecognizers(GameState s){
if(s.shouldClearActions()){
inputSystem.clearActions();
} else {
// CONCERN: This might be two slow. maybe we need to redesign action->recognizer bindings.
for (Action a : inputSystem.getAndCleanActions()) {
for(ActionRecognizer r : s.getRecognizers()) {
r.actionOccurred(a);
}
}
}
}
}
|
package com.jbooktrader.platform.preferences;
public enum JBTPreferences {
// TWS connection
Host("Host", "localhost"),
Port("Port", "7496"),
ClientID("Client ID", "0"),
AccountType("Account type", "Universal"),
AdvisorAccount("Advisor account", ""),
// Reporting
ReportRenderer("Report renderer", "com.jbooktrader.platform.report.HTMLReportRenderer"),
ReportRecycling("Report recycling", "Append"),
// Remote monitoring
EmailMonitoring("Monitoring", "disabled"),
HeartBeatInterval("Heartbeat Interval", "60"),
SMTPSHost("SMTPS Host", "smtp.gmail.com"),
EmailLogin("Email Login", "me@gmail.com"),
EmailPassword("Email Password", ""),
From("From", "me@gmail.com"),
To("To", "me@anyprovider.com"),
EmailSubject("Email Subject", "[JBT Remote Notification]"),
// Web Access
WebAccess("Web access", "disabled"),
WebAccessPort("Web access port", "1234"),
WebAccessUser("Web access user", "admin"),
WebAccessPassword("Web access password", "admin"),
// Back tester
BackTesterFileName("backTester.dataFileName", ""),
// Optimizer
OptimizerFileName("optimizer.dataFileName", ""),
OptimizerMinTrades("optimizer.minTrades", "50"),
OptimizerSelectBy("optimizer.selectBy", ""),
OptimizerMethod("optimizer.method", ""),
// Main window
MainWindowWidth("mainwindow.width", "-1"),
MainWindowHeight("mainwindow.height", "-1"),
MainWindowX("mainwindow.x", "-1"),
MainWindowY("mainwindow.y", "-1"),
// Performance chart
PerformanceChartWidth("performance.chart.width", "-1"),
PerformanceChartHeight("performance.chart.height", "-1"),
PerformanceChartX("performance.chart.x", "-1"),
PerformanceChartY("performance.chart.y", "-1"),
PerformanceChartState("performance.chart.state", "-1"),
// Optimization Map
OptimizationMapWidth("optimization.map.width", "-1"),
OptimizationMapHeight("optimization.map.height", "-1"),
OptimizationMapX("optimization.map.x", "-1"),
OptimizationMapY("optimization.map.y", "-1");
private final String name, defaultValue;
JBTPreferences(String name, String defaultValue) {
this.name = name;
this.defaultValue = defaultValue;
}
public String getDefault() {
return defaultValue;
}
public String getName() {
return name;
}
}
|
package it.unito.geosummly.io;
import it.unito.geosummly.BoundingBox;
import it.unito.geosummly.io.templates.VenueTemplate;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.TimeZone;
import com.google.gson.stream.JsonWriter;
public class GeoJSONWriter implements IGeoWriter{
@Override
public void writeStream(
BoundingBox bbox,
HashMap<Integer, String> labels,
HashMap<Integer, ArrayList<ArrayList<Double>>> cells,
HashMap<Integer, ArrayList<ArrayList<String>>> venues,
double eps,
String output,
Calendar cal) {
try {
//Get the current date. Example: 2014-03-19T17:10:57.616Z
SimpleDateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd'T'H:mm:ss.SSS'Z'");
dateFormat.setLenient(false); //now month index starts from 1
dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); //set UTC time zone
String date=dateFormat.format(cal.getTime());
//Create GeoJSON
File dir=new File(output); //create the output directory if it doesn't exist
dir.mkdirs();
OutputStream os= new FileOutputStream(new File(dir.getPath().concat("/clustering-output-eps").concat(eps+"").concat(".geojson")));
ArrayList<Integer> keys=new ArrayList<Integer>(labels.keySet()); //keys of clusters
String name; //cluster label
int key; //cluster key
ArrayList<ArrayList<Double>> cellsOfCluster; //cells informations (cell_id, cell_lat, cell_lng) of a cluster
ArrayList<ArrayList<String>> venuesOfCell; //all venues of a cell
JsonWriter writer = new JsonWriter(new OutputStreamWriter(os, "UTF-8"));
writer.setIndent(" ");
writer.beginObject();
writer.name("type").value("FeatureCollection");
writer.name("features");
writer.beginArray();
//iterate for each cluster
for(Integer i: keys) {
name=labels.get(i);
key=i;
cellsOfCluster=new ArrayList<ArrayList<Double>>(cells.get(i));
ArrayList<VenueTemplate> vo_array=new ArrayList<VenueTemplate>();
writer.beginObject();
writer.name("type").value("Feature");
writer.name("id").value(key);
writer.name("geometry");
writer.beginObject();
writer.name("type").value("MultiPoint");
writer.name("coordinates");
writer.beginArray();
//iterate for each cell of the cluster
for(ArrayList<Double> cl: cellsOfCluster) {
DecimalFormat df=new DecimalFormat("
String s1=df.format(cl.get(1)).replaceAll(",", ".");
String s2=df.format(cl.get(2)).replaceAll(",", ".");
writer.beginArray();
writer.value(Double.parseDouble(s1));
writer.value(Double.parseDouble(s2));
writer.endArray();
//put venue informations to the list
if(venues.containsKey(cl.get(0).intValue())) {
venuesOfCell=new ArrayList<ArrayList<String>>(venues.get(cl.get(0).intValue()));
}
else
venuesOfCell=new ArrayList<ArrayList<String>>();
//iterate for each venue of the cell
for(ArrayList<String> r: venuesOfCell) {
Long timestamp=Long.parseLong(r.get(0));
Integer bH=Integer.parseInt(r.get(1));
Double vLat=Double.parseDouble(df.format(Double.parseDouble(r.get(3))).replaceAll(",", "."));
Double vLng=Double.parseDouble(df.format(Double.parseDouble(r.get(4))).replaceAll(",", "."));
Double fLat=Double.parseDouble(df.format(Double.parseDouble(r.get(5))).replaceAll(",", "."));
Double fLng=Double.parseDouble(df.format(Double.parseDouble(r.get(6))).replaceAll(",", "."));
//create a VenueObject with the venue informations
VenueTemplate vo=new VenueTemplate(timestamp, bH, r.get(2), vLat, vLng, fLat, fLng, r.get(7));
vo_array.add(vo);
}
}
writer.endArray();
writer.endObject();
writer.name("properties");
writer.beginObject();
writer.name("clusterId").value(key+1);
writer.name("name").value(name);
writer.name("venues");
writer.beginArray();
//write down all the VenueObjects of the cluster
for(VenueTemplate obj: vo_array) {
writer.beginObject();
writer.name("timestamp").value(obj.getTimestamp());
if(obj.getBeen_here()>0)
writer.name("beenHere").value(obj.getBeen_here());
writer.name("id").value(obj.getId());
writer.name("venueLatitude").value(obj.getVenue_latitude());
writer.name("venueLongitude").value(obj.getVenue_longitude());
writer.name("centroidLatitude").value(obj.getFocal_latitude());
writer.name("centroidLongitude").value(obj.getFocal_longitude());
writer.name("category").value(obj.getCategory());
writer.endObject();
}
writer.endArray();
writer.endObject();
writer.endObject();
}
writer.endArray();
writer.name("properties");
writer.beginObject();
writer.name("name").value("geosummly");
writer.name("bbox");
writer.beginObject();
writer.name("north").value(bbox.getNorth());
writer.name("east").value(bbox.getEast());
writer.name("south").value(bbox.getSouth());
writer.name("west").value(bbox.getWest());
writer.endObject();
writer.name("date").value(date);
writer.name("eps").value(eps);
writer.endObject();
writer.endObject();
writer.close();
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public void writerAfterOptimization(BoundingBox bbox, ArrayList<ArrayList<ArrayList<Double>>> cells,
ArrayList<ArrayList<VenueTemplate>> venues,
ArrayList<String[]> labels,
double eps, String date, String output) {
try {
//Create GeoJSON
File dir=new File(output); //create the output directory if it doesn't exist
dir.mkdirs();
OutputStream os= new FileOutputStream(new File(dir.getPath().concat("/opt-clustering-output-eps").concat(eps+"").concat(".geojson")));
String name=""; //cluster label
int key; //cluster key
ArrayList<ArrayList<Double>> cellsOfCluster; //cells informations (cell_lat, cell_lng) of a cluster
JsonWriter writer = new JsonWriter(new OutputStreamWriter(os, "UTF-8"));
writer.setIndent(" ");
writer.beginObject();
writer.name("type").value("FeatureCollection");
writer.name("features");
writer.beginArray();
//iterate for each cluster
for(int i=0;i<cells.size();i++) {
name="";
for(String s: labels.get(i))
name=name.concat(s).concat(",");
name=name.substring(0, name.length()-1); //delete last comma
key=i;
cellsOfCluster=new ArrayList<ArrayList<Double>>(cells.get(i)); //get the cells of the ith cluster
writer.beginObject();
writer.name("type").value("Feature");
writer.name("id").value(key);
writer.name("geometry");
writer.beginObject();
writer.name("type").value("MultiPoint");
writer.name("coordinates");
writer.beginArray();
//iterate for each cell of the cluster
for(ArrayList<Double> cl: cellsOfCluster) {
writer.beginArray();
writer.value(cl.get(0));
writer.value(cl.get(1));
writer.endArray();
}
writer.endArray();
writer.endObject();
writer.name("properties");
writer.beginObject();
writer.name("clusterId").value(key+1);
writer.name("name").value(name);
writer.name("venues");
writer.beginArray();
//write down all the VenueObjects of the cluster
for(VenueTemplate obj: venues.get(i)) {
writer.beginObject();
writer.name("timestamp").value(obj.getTimestamp());
if(obj.getBeen_here()>0)
writer.name("beenHere").value(obj.getBeen_here());
writer.name("id").value(obj.getId());
writer.name("venueLatitude").value(obj.getVenue_latitude());
writer.name("venueLongitude").value(obj.getVenue_longitude());
writer.name("centroidLatitude").value(obj.getFocal_latitude());
writer.name("centroidLongitude").value(obj.getFocal_longitude());
writer.name("category").value(obj.getCategory());
writer.endObject();
}
writer.endArray();
writer.endObject();
writer.endObject();
}
writer.endArray();
writer.name("properties");
writer.beginObject();
writer.name("name").value("geosummly");
writer.name("bbox");
writer.beginObject();
writer.name("north").value(bbox.getNorth());
writer.name("east").value(bbox.getEast());
writer.name("south").value(bbox.getSouth());
writer.name("west").value(bbox.getWest());
writer.endObject();
writer.name("date").value(date);
writer.name("eps").value(eps);
writer.endObject();
writer.endObject();
writer.close();
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
|
package mcjty.enigma.snapshot;
import mcjty.enigma.parser.StringPointer;
import net.minecraft.block.Block;
import net.minecraft.block.state.IBlockState;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import net.minecraft.world.chunk.Chunk;
import net.minecraftforge.fml.common.registry.ForgeRegistries;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.Pair;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class SnapshotTools {
private static class Loc {
private int x = 0;
private int y = 0;
private int z = 0;
public int getX() {
return x;
}
public int getY() {
return y;
}
public int getZ() {
return z;
}
public void inc() {
z++;
if (z > 15) {
z = 0;
x++;
if (x > 15) {
x = 0;
y++;
}
}
}
}
public static void restoreChunkSnapshot(World world, Chunk curchunk, String input) {
List<IBlockState> differentBlocks = new ArrayList<>();
BufferedReader reader = new BufferedReader(new StringReader(input));
int cnt = 0;
try {
String line = reader.readLine();
while (line != null && line.startsWith(":")) {
String[] split = StringUtils.split(line.substring(1), "@");
Block block = ForgeRegistries.BLOCKS.getValue(new ResourceLocation(split[0]));
int meta = Integer.parseInt(split[1]);
differentBlocks.add(block.getStateFromMeta(meta));
line = reader.readLine();
}
if (line != null) {
Loc loc = new Loc();
StringPointer s = new StringPointer(line);
s.inc();
while (s.hasMore()) {
int count = uncompress(s);
int index = uncompress(s);
IBlockState state = differentBlocks.get(index);
for (int i = 0 ; i < count ; i++) {
int x = curchunk.getPos().chunkXPos * 16 + loc.getX();
int y = loc.getY();
int z = curchunk.getPos().chunkZPos * 16 + loc.getZ();
loc.inc();
BlockPos p = new BlockPos(x, y, z);
IBlockState curstate = curchunk.getBlockState(p);
if (!curstate.equals(state)) {
world.setBlockState(p, state, 3);
cnt++;
}
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("cnt = " + cnt);
}
public static String makeChunkSnapshot(World world, Chunk curchunk) {
Map<Pair<String,Integer>, Integer> differentBlocks = new HashMap<>();
StringBuffer output = new StringBuffer();
int maxindex = 0;
Pair<String, Integer> prev = null;
int cnt = 0;
for (int y = 0 ; y < world.getHeight() ; y++) {
for (int x = 0 ; x < 16 ; x++) {
for (int z = 0 ; z < 16 ; z++) {
IBlockState curstate = curchunk.getBlockState(x, y, z);
String n = curstate.getBlock().getRegistryName().toString();
int meta = curstate.getBlock().getMetaFromState(curstate);
Pair<String, Integer> p = Pair.of(n, meta);
int blockindex;
if (!differentBlocks.containsKey(p)) {
blockindex = maxindex;
differentBlocks.put(p, blockindex);
maxindex++;
}
if (p.equals(prev)) {
cnt++;
} else {
if (cnt > 0) {
compress(cnt, output);
compress(differentBlocks.get(prev), output);
}
cnt = 1;
prev = p;
}
}
}
}
if (cnt > 0) {
compress(cnt, output);
compress(differentBlocks.get(prev), output);
}
System.out.println("differentBlocks = " + differentBlocks.size());
System.out.println("bytes = " + output.length());
System.out.println("output = " + output);
Map<Integer, Pair<String, Integer>> reverseBlockMap = new HashMap<>();
for (Map.Entry<Pair<String, Integer>, Integer> entry : differentBlocks.entrySet()) {
reverseBlockMap.put(entry.getValue(), entry.getKey());
}
StringBuffer fullOut = new StringBuffer();
for (int i = 0 ; i < maxindex ; i++) {
String name = reverseBlockMap.get(i).getKey();
Integer meta = reverseBlockMap.get(i).getValue();
fullOut.append(":").append(name).append("@").append(meta).append('\n');
}
fullOut.append(output);
return fullOut.toString();
}
private static void compress(int i, StringBuffer buf) {
if (i < 10) {
buf.append((char) ('0' + i));
} else if (i < 10+26) {
buf.append((char) ('A' + i - 10));
} else if (i < 10+26+26) {
buf.append((char) ('a' + i - 10 - 26));
} else {
buf.append('.');
compress(i / (10+26+26), buf);
compress(i % (10+26+26), buf);
}
}
private static int uncompress(StringPointer s) {
char c = s.current();
s.inc();
if (c >= '0' && c <= '9') {
return c-'0';
} else if (c >= 'A' && c <= 'Z') {
return c-'A'+10;
} else if (c >= 'a' && c <= 'z') {
return c-'a'+10+26;
} else if (c == '.') {
if (!s.hasMore()) {
throw new RuntimeException("Impossible!");
}
int j1 = uncompress(s);
int j2 = uncompress(s);
return (j1 * (10+26+26)) + j2;
} else {
throw new RuntimeException("Impossible!");
}
}
public static void main(String[] args) {
StringBuffer compressed = new StringBuffer();
compress(1, compressed);
compress(2, compressed);
compress(3, compressed);
compress(100, compressed);
compress(500, compressed);
compress(1, compressed);
StringPointer p = new StringPointer(compressed.toString());
p.inc();
while (p.hasMore()) {
int i = uncompress(p);
System.out.println("i = " + i);
}
}
}
|
package net.glowstone.util;
import java.util.ArrayList;
import java.util.List;
import org.bukkit.Achievement;
import org.bukkit.Material;
import org.bukkit.NamespacedKey;
import org.bukkit.Statistic;
import org.bukkit.UnsafeValues;
import org.bukkit.advancement.Advancement;
import org.bukkit.inventory.ItemStack;
import org.bukkit.util.StringUtil;
/**
* Implementation of Bukkit's internal-use UnsafeValues.
*
* <p>In CraftBukkit, this uses Mojang identifiers, but here we just stick to Bukkit's.
*
* <p>The implementation may be a bit sketchy but this isn't a problem since the behavior of this
* class isn't strictly specified.
*/
@Deprecated
public final class GlowUnsafeValues implements UnsafeValues {
@Override
public Material getMaterialFromInternalName(String name) {
try {
return Material.valueOf(name);
} catch (IllegalArgumentException ex) {
return null;
}
}
@Override
public List<String> tabCompleteInternalMaterialName(String token, List<String> completions) {
List<String> materialNames = new ArrayList<>(Material.values().length);
for (Material mat : Material.values()) {
materialNames.add(mat.name().toLowerCase());
}
return StringUtil.copyPartialMatches(token, materialNames, completions);
}
@Override
public ItemStack modifyItemStack(ItemStack stack, String arguments) {
return stack;
}
@Override
public Statistic getStatisticFromInternalName(String name) {
try {
return Statistic.valueOf(name);
} catch (IllegalArgumentException ex) {
return null;
}
}
@Override
public Achievement getAchievementFromInternalName(String name) {
try {
return Achievement.valueOf(name);
} catch (IllegalArgumentException ex) {
return null;
}
}
@Override
public List<String> tabCompleteInternalStatisticOrAchievementName(
String token, List<String> completions) {
Statistic[] stats = Statistic.values();
Achievement[] achievements = Achievement.values();
List<String> names = new ArrayList<>(stats.length + achievements.length);
for (Statistic stat : stats) {
names.add(stat.name());
}
for (Achievement achievement : achievements) {
names.add(achievement.name());
}
return StringUtil.copyPartialMatches(token, names, completions);
}
@Override
public Advancement loadAdvancement(NamespacedKey key, String advancement) {
return null;
}
@Override
public boolean removeAdvancement(NamespacedKey key) {
return false;
}
}
|
package net.ihiroky.niotty;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
/**
* A skeletal implementation of {@link Pipeline}.
*
* @param <S> the type of a stage
* @param <L> the type of the TaskLoop which executes the stages by default
*/
public abstract class AbstractPipeline<S, L extends TaskLoop> implements Pipeline<S> {
private final String name_;
private final AbstractTransport<L> transport_;
private final PipelineElement<Object, Object> head_;
private final Tail<S> tail_;
private final PipelineElementExecutorPool defaultPipelineElementExecutorPool_;
private Logger logger_ = LoggerFactory.getLogger(AbstractPipeline.class);
static final NullPipelineElementExecutorPool NULL_POOL = new NullPipelineElementExecutorPool();
static final PipelineElement<Object, Object> TERMINAL = new NullPipelineElement();
private static final int INPUT_TYPE = 0;
private static final int OUTPUT_TYPE = 1;
protected AbstractPipeline(
String name, AbstractTransport<L> transport, TaskLoopGroup<? extends TaskLoop> taskLoopGroup) {
transport_ = transport;
DefaultPipelineElementExecutorPool<L> pool = new DefaultPipelineElementExecutorPool<>(this, taskLoopGroup);
Tail<S> tail = createTail(pool);
tail.setNext(TERMINAL);
PipelineElement<Object, Object> head = new NullPipelineElement();
head.setNext(tail);
name_ = name;
head_ = head;
tail_ = tail;
defaultPipelineElementExecutorPool_ = pool;
}
@Override
public Pipeline<S> add(StageKey key, S stage) {
return add(key, stage, defaultPipelineElementExecutorPool_);
}
@Override
public Pipeline<S> add(StageKey key, S stage, PipelineElementExecutorPool pool) {
Objects.requireNonNull(key, "key");
Objects.requireNonNull(stage, "stage");
if (key.equals(IO_STAGE)) {
throw new IllegalArgumentException(IO_STAGE + " must not be added.");
}
synchronized (head_) {
if (head_.next() == tail_) {
PipelineElement<Object, Object> newContext = createContext(key, stage, pool);
head_.setNext(newContext);
newContext.setNext(tail_);
return this;
} else {
for (PipelineElementIterator i = new PipelineElementIterator(head_); i.hasNext();) {
PipelineElement<Object, Object> context = i.next();
if (context.key().equals(key)) {
throw new IllegalArgumentException("key " + key + " already exists.");
}
if (context.next() == tail_) {
PipelineElement<Object, Object> newContext = createContext(key, stage, pool);
newContext.setNext(tail_);
context.setNext(newContext);
break;
}
}
}
}
return this;
}
@Override
public Pipeline<S> addBefore(StageKey baseKey, StageKey key, S stage) {
return addBefore(baseKey, key, stage, defaultPipelineElementExecutorPool_);
}
@Override
public Pipeline<S> addBefore(StageKey baseKey, StageKey key, S stage, PipelineElementExecutorPool pool) {
Objects.requireNonNull(baseKey, "baseKey");
Objects.requireNonNull(key, "key");
Objects.requireNonNull(stage, "stage");
if (key.equals(IO_STAGE)) {
throw new IllegalArgumentException(IO_STAGE + " must not be added.");
}
synchronized (head_) {
PipelineElement<Object, Object> prev = null;
PipelineElement<Object, Object> target = null;
for (PipelineElementIterator i = new PipelineElementIterator(head_); i.hasNext();) {
PipelineElement<Object, Object> context = i.next();
StageKey ikey = context.key();
if (ikey.equals(key)) {
throw new IllegalArgumentException("key " + key + " already exists.");
}
if (ikey.equals(baseKey)) {
prev = i.prev();
target = context;
}
}
if (target != null) {
PipelineElement<Object, Object> newContext = createContext(key, stage, pool);
newContext.setNext(target);
prev.setNext(newContext);
return this;
}
}
throw new NoSuchElementException("baseKey " + baseKey + " is not found.");
}
@Override
public Pipeline<S> addAfter(StageKey baseKey, StageKey key, S stage) {
return addAfter(baseKey, key, stage, defaultPipelineElementExecutorPool_);
}
@Override
public Pipeline<S> addAfter(StageKey baseKey, StageKey key, S stage, PipelineElementExecutorPool pool) {
Objects.requireNonNull(baseKey, "baseKey");
Objects.requireNonNull(key, "key");
Objects.requireNonNull(stage, "stage");
if (baseKey.equals(IO_STAGE)) {
throw new IllegalArgumentException(IO_STAGE + " must be the tail of this pipeline.");
}
if (key.equals(IO_STAGE)) {
throw new IllegalArgumentException(IO_STAGE + " must not be added.");
}
synchronized (head_) {
PipelineElement<Object, Object> target = null;
for (PipelineElementIterator i = new PipelineElementIterator(head_); i.hasNext();) {
PipelineElement<Object, Object> context = i.next();
StageKey ikey = context.key();
if (ikey.equals(key)) {
throw new IllegalArgumentException("key " + key + " already exists.");
}
if (ikey.equals(baseKey)) {
target = context;
}
}
if (target != null) {
PipelineElement<Object, Object> next = target.next();
PipelineElement<Object, Object> newContext = createContext(key, stage, pool);
newContext.setNext(next);
target.setNext(newContext);
return this;
}
}
throw new NoSuchElementException("baseKey " + baseKey + " is not found.");
}
@Override
public Pipeline<S> remove(StageKey key) {
Objects.requireNonNull(key, "key");
if (key.equals(IO_STAGE)) {
throw new IllegalArgumentException(IO_STAGE + " must not be removed.");
}
synchronized (head_) {
for (PipelineElementIterator i = new PipelineElementIterator(head_); i.hasNext();) {
PipelineElement<Object, Object> context = i.next();
if (context.key().equals(key)) {
PipelineElement<Object, Object> prev = i.prev();
prev.setNext(context.next());
context.close();
return this;
}
}
}
throw new NoSuchElementException("key " + key + " is not found.");
}
@Override
public Pipeline<S> replace(StageKey oldKey, StageKey newKey, S newStage) {
return replace(oldKey, newKey, newStage, defaultPipelineElementExecutorPool_);
}
@Override
public Pipeline<S> replace(StageKey oldKey, StageKey newKey, S newStage, PipelineElementExecutorPool pool) {
Objects.requireNonNull(oldKey, "oldKey");
Objects.requireNonNull(newKey, "newKey");
Objects.requireNonNull(newStage, "newStage");
if (oldKey.equals(IO_STAGE)) {
throw new IllegalArgumentException(IO_STAGE + " must not be removed.");
}
if (newKey.equals(IO_STAGE)) {
throw new IllegalArgumentException(IO_STAGE + " must not be added.");
}
synchronized (head_) {
PipelineElement<Object, Object> prev = null;
PipelineElement<Object, Object> target = null;
for (PipelineElementIterator i = new PipelineElementIterator(head_); i.hasNext();) {
PipelineElement<Object, Object> context = i.next();
StageKey ikey = context.key();
if (ikey.equals(newKey)) {
throw new IllegalArgumentException("newKey " + newKey + " already exists.");
}
if (ikey.equals(oldKey)) {
prev = i.prev();
target = context;
}
}
if (target != null) {
PipelineElement<Object, Object> next = target.next();
PipelineElement<Object, Object> newContext = createContext(newKey, newStage, pool);
newContext.setNext(next);
prev.setNext(newContext);
target.close();
return this;
}
}
throw new NoSuchElementException("oldKey " + oldKey + " is not found.");
}
protected abstract PipelineElement<Object, Object> createContext(
StageKey key, S stage, PipelineElementExecutorPool pool);
protected abstract Tail<S> createTail(PipelineElementExecutorPool defaultPool);
void setTailStage(S stage) {
Objects.requireNonNull(stage, "stage");
logger_.debug("[setTailStage] {}", stage);
tail_.setStage(stage);
}
public void close() {
for (PipelineElement<Object, Object> ctx = head_; ctx != TERMINAL; ctx = ctx.next()) {
ctx.close();
}
}
public void verifyStageType() {
// TODO review if a dedicated flag instead of log level should be used.
if (!logger_.isWarnEnabled()) {
return;
}
int counter = 0;
Class<?> prevOutputClass = null;
Class<?> prevStageClass = null;
for (PipelineElementIterator i = new PipelineElementIterator(head_); i.hasNext();) {
PipelineElement e = i.next();
Object stage = e.stage();
if (stage == null) {
if (e instanceof Tail) {
logger_.debug("[verifyStageType] The tail stage: {}", stage);
} else {
logger_.debug("[verifyStageType] The stage of {} is null.", e);
}
continue;
}
Class<?> stageClass = stage.getClass();
for (Type type : stageClass.getGenericInterfaces()) {
Type[] actualTypeArguments = stageTypeParameters(type);
if (actualTypeArguments == null) {
continue;
}
logger_.debug("[verifyStageType] {}:{} - I:{}, O:{}",
name_, counter, actualTypeArguments[INPUT_TYPE], actualTypeArguments[OUTPUT_TYPE]);
checkIfStageTypeIsValid(stageClass, actualTypeArguments[INPUT_TYPE], prevStageClass, prevOutputClass);
// Update previous stage and output type.
if (actualTypeArguments[OUTPUT_TYPE] instanceof Class) {
prevOutputClass = (Class<?>) actualTypeArguments[OUTPUT_TYPE];
prevStageClass = stageClass;
} else {
logger_.debug(
"[verifyStageType] output type {} of {} is not an instance of Class.",
actualTypeArguments[OUTPUT_TYPE], stageClass);
prevOutputClass = null;
prevStageClass = null;
}
counter++;
break;
}
}
}
/**
* Returns type parameters of a specified {@code type} if the {@code type} is {@link net.ihiroky.niotty.LoadStage}
* or {@link net.ihiroky.niotty.StoreStage}. Otherwise, returns null.
*
* @param type a type of the stage generic interface
* @return type parameters or null
*/
private Type[] stageTypeParameters(Type type) {
if (!(type instanceof ParameterizedType)) {
return null;
}
ParameterizedType parameterizedType = (ParameterizedType) type;
Type rawType = parameterizedType.getRawType();
if (!(rawType instanceof Class)) {
return null;
}
Class<?> rawTypeClass = (Class<?>) rawType;
if (!(rawTypeClass.equals(LoadStage.class) || rawTypeClass.equals(StoreStage.class))) {
return null;
}
return parameterizedType.getActualTypeArguments();
}
/**
* Check if the input type of the stage is assignable from the previous output type of the previous stage.
* That is, the stage is called by the previous stage without ClassCastException.
*
* @param stageClass class of the stage
* @param inputType input type of the stage
* @param prevStageClass class of the previous stage
* @param prevOutputClass output type of the previous stage
* @throws java.lang.RuntimeException the previous stage can't call the stage because of type mismatch.
*/
private void checkIfStageTypeIsValid(
Class<?> stageClass, Type inputType, Class<?> prevStageClass, Class<?> prevOutputClass) {
if (inputType instanceof Class) {
Class<?> inputClass = (Class<?>) inputType;
if (prevOutputClass != null) {
if (inputClass.isAssignableFrom(prevOutputClass)) {
logger_.debug("[checkIfStageTypeIsValid] OK from [{}] to [{}]", prevStageClass, stageClass);
} else {
logger_.warn("Input type [{}] of [{}] is not assignable from output type [{}] of [{}].",
inputClass, stageClass, prevOutputClass, prevStageClass);
}
}
} else {
logger_.debug(
"[checkIfStageTypeIsValid] input type {} of {} is not an instance of Class. Skip assignment check.",
inputType, stageClass);
}
}
public void execute(final Object input) {
final PipelineElement<Object, Object> next = head_.next();
next.taskLoop().execute(new Task() {
@Override
public long execute(TimeUnit timeUnit) throws Exception {
next.fire(input);
return DONE;
}
});
}
public void execute(final Object input, final TransportParameter parameter) {
final PipelineElement<Object, Object> next = head_.next();
next.taskLoop().execute(new Task() {
@Override
public long execute(TimeUnit timeUnit) throws Exception {
next.fire(input, parameter);
return DONE;
}
});
}
public void execute(final TransportStateEvent event) {
final PipelineElement<?, ?> next = head_.next();
next.taskLoop().execute(new Task() {
@Override
public long execute(TimeUnit timeUnit) throws Exception {
next.fire(event);
next.proceed(event);
return DONE;
}
});
}
@Override
public String name() {
return name_;
}
AbstractTransport<L> transport() {
return transport_;
}
protected PipelineElement<Object, Object> search(StageKey key) {
for (PipelineElementIterator i = new PipelineElementIterator(head_); i.hasNext();) {
PipelineElement<Object, Object> context = i.next();
if (context.key() == key) {
return context;
}
}
return null;
}
protected Iterator<PipelineElement<Object, Object>> iterator() {
return new PipelineElementIterator(head_);
}
private static class NullPipelineElement extends PipelineElement<Object, Object> {
protected NullPipelineElement() {
super(null, null, NULL_POOL);
}
@Override
protected Object stage() {
return this;
}
@Override
protected void fire(Object input) {
}
@Override
protected void fire(Object input, TransportParameter parameter) {
}
@Override
protected void fire(TransportStateEvent event) {
}
@Override
public TransportParameter transportParameter() {
return DefaultTransportParameter.NO_PARAMETER;
}
}
private static class NullPipelineElementExecutorPool implements PipelineElementExecutorPool {
static final TaskFuture NULL_FUTURE = new TaskFuture(-1L, new Task() {
@Override
public long execute(TimeUnit timeUnit) throws Exception {
return DONE;
}
});
static final TaskLoop NULL_TASK_LOOP = new TaskLoop() {
@Override
protected void onOpen() {
}
@Override
protected void onClose() {
}
@Override
protected void poll(long timeout, TimeUnit timeUnit) throws Exception {
}
@Override
protected void wakeUp() {
}
@Override
public void offer(Task task) {
}
@Override
public TaskFuture schedule(Task task, long timeout, TimeUnit timeUnit) {
return NULL_FUTURE;
}
@Override
public void execute(Task task) {
}
};
@Override
public TaskLoop assign(TaskSelection context) {
return NULL_TASK_LOOP;
}
@Override
public void close() {
}
}
/**
* Iterates {@code PipelineElement} chain from head context.
*/
private static class PipelineElementIterator implements Iterator<PipelineElement<Object, Object>> {
private PipelineElement<Object, Object> context_;
private final PipelineElement<Object, Object> terminal_;
private PipelineElement<Object, Object> prev_;
PipelineElementIterator(PipelineElement<Object, Object> head) {
this(head, TERMINAL);
}
PipelineElementIterator(PipelineElement<Object, Object> head, PipelineElement<Object, Object> terminal) {
context_ = head;
terminal_ = terminal;
prev_ = null;
}
@Override
public boolean hasNext() {
return context_.next() != terminal_;
}
@Override
public PipelineElement<Object, Object> next() {
prev_ = context_;
context_ = context_.next();
if (context_ == terminal_) {
throw new NoSuchElementException();
}
return context_;
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
public PipelineElement<Object, Object> prev() {
return prev_;
}
}
static abstract class Tail<S> extends PipelineElement<Object, Object> {
protected Tail(AbstractPipeline<?, ?> pipeline, StageKey key, PipelineElementExecutorPool pool) {
super(pipeline, key, pool);
}
abstract void setStage(S stage);
}
}
|
package net.imagej.ops.image;
import net.imagej.ImgPlus;
import net.imagej.ops.AbstractNamespace;
import net.imagej.ops.Namespace;
import net.imagej.ops.OpMethod;
import net.imagej.ops.Ops;
import net.imagej.ops.image.cooccurrenceMatrix.MatrixOrientation;
import net.imagej.ops.special.computer.UnaryComputerOp;
import net.imglib2.Interval;
import net.imglib2.IterableInterval;
import net.imglib2.RandomAccessible;
import net.imglib2.RandomAccessibleInterval;
import net.imglib2.histogram.Histogram1d;
import net.imglib2.img.Img;
import net.imglib2.interpolation.InterpolatorFactory;
import net.imglib2.type.Type;
import net.imglib2.type.numeric.RealType;
import net.imglib2.type.numeric.real.DoubleType;
import org.scijava.plugin.Plugin;
/**
* The image namespace contains operations relating to images.
*
* @author Curtis Rueden
*/
@Plugin(type = Namespace.class)
public class ImageNamespace extends AbstractNamespace {
// -- ascii --
/** Executes the "ascii" operation on the given arguments. */
@OpMethod(op = Ops.Image.ASCII.class)
public Object ascii(final Object... args) {
return ops().run(Ops.Image.ASCII.class, args);
}
/** Executes the "ascii" operation on the given arguments. */
@OpMethod(op = net.imagej.ops.image.ascii.DefaultASCII.class)
public <T extends RealType<T>> String ascii(final IterableInterval<T> image) {
final String result = (String) ops().run(
net.imagej.ops.Ops.Image.ASCII.class, image);
return result;
}
/** Executes the "ascii" operation on the given arguments. */
@OpMethod(op = net.imagej.ops.image.ascii.DefaultASCII.class)
public <T extends RealType<T>> String ascii(final IterableInterval<T> image,
final T min)
{
final String result = (String) ops().run(
net.imagej.ops.Ops.Image.ASCII.class, image, min);
return result;
}
/** Executes the "ascii" operation on the given arguments. */
@OpMethod(op = net.imagej.ops.image.ascii.DefaultASCII.class)
public <T extends RealType<T>> String ascii(final IterableInterval<T> image,
final T min, final T max)
{
final String result = (String) ops().run(
net.imagej.ops.Ops.Image.ASCII.class, image, min, max);
return result;
}
// -- cooccurrence matrix --
@OpMethod(ops = {
net.imagej.ops.image.cooccurrenceMatrix.CooccurrenceMatrix3D.class,
net.imagej.ops.image.cooccurrenceMatrix.CooccurrenceMatrix2D.class })
public <T extends RealType<T>> double[][] cooccurrenceMatrix(
final IterableInterval<T> in, final int nrGreyLevels,
final int distance, final MatrixOrientation orientation) {
final double[][] result = (double[][]) ops().run(
Ops.Image.CooccurrenceMatrix.class, in, nrGreyLevels, distance,
orientation);
return result;
}
// -- crop --
/** Executes the "crop" operation on the given arguments. */
@OpMethod(op = Ops.Image.Crop.class)
public Object crop(final Object... args) {
return ops().run(Ops.Image.Crop.class, args);
}
/** Executes the "crop" operation on the given arguments. */
@OpMethod(op = net.imagej.ops.image.crop.CropImgPlus.class)
public <T extends Type<T>> ImgPlus<T> crop(final ImgPlus<T> in,
final Interval interval) {
@SuppressWarnings("unchecked")
final ImgPlus<T> result = (ImgPlus<T>) ops().run(
net.imagej.ops.Ops.Image.Crop.class, in, interval);
return result;
}
/** Executes the "crop" operation on the given arguments. */
@OpMethod(op = net.imagej.ops.image.crop.CropImgPlus.class)
public <T extends Type<T>> ImgPlus<T> crop(final ImgPlus<T> in,
final Interval interval, final boolean dropSingleDimensions) {
@SuppressWarnings("unchecked")
final ImgPlus<T> result = (ImgPlus<T>) ops().run(
net.imagej.ops.Ops.Image.Crop.class, in, interval,
dropSingleDimensions);
return result;
}
/** Executes the "crop" operation on the given arguments. */
@OpMethod(op = net.imagej.ops.image.crop.CropRAI.class)
public <T> RandomAccessibleInterval<T> crop(
final RandomAccessibleInterval<T> in, final Interval interval) {
@SuppressWarnings("unchecked")
final RandomAccessibleInterval<T> result = (RandomAccessibleInterval<T>) ops()
.run(net.imagej.ops.Ops.Image.Crop.class, in, interval);
return result;
}
/** Executes the "crop" operation on the given arguments. */
@OpMethod(op = net.imagej.ops.image.crop.CropRAI.class)
public <T> RandomAccessibleInterval<T> crop(
final RandomAccessibleInterval<T> in, final Interval interval,
final boolean dropSingleDimensions) {
@SuppressWarnings("unchecked")
final RandomAccessibleInterval<T> result = (RandomAccessibleInterval<T>) ops()
.run(net.imagej.ops.Ops.Image.Crop.class, in, interval,
dropSingleDimensions);
return result;
}
// -- equation --
/** Executes the "equation" operation on the given arguments. */
@OpMethod(op = Ops.Image.Equation.class)
public Object equation(final Object... args) {
return ops().run(Ops.Image.Equation.class, args);
}
/** Executes the "equation" operation on the given arguments. */
@OpMethod(op = net.imagej.ops.image.equation.DefaultEquation.class)
public <T extends RealType<T>> IterableInterval<T> equation(final String in) {
@SuppressWarnings("unchecked")
final IterableInterval<T> result = (IterableInterval<T>) ops().run(
net.imagej.ops.Ops.Image.Equation.class, in);
return result;
}
/** Executes the "equation" operation on the given arguments. */
@OpMethod(op = net.imagej.ops.image.equation.DefaultEquation.class)
public <T extends RealType<T>> IterableInterval<T> equation(
final IterableInterval<T> out, final String in) {
@SuppressWarnings("unchecked")
final IterableInterval<T> result = (IterableInterval<T>) ops().run(
net.imagej.ops.Ops.Image.Equation.class, out, in);
return result;
}
// -- fill --
/** Executes the "fill" operation on the given arguments. */
@OpMethod(op = net.imagej.ops.Ops.Image.Fill.class)
public Object fill(final Object... args) {
return ops().run(Ops.Image.Fill.class, args);
}
/** Executes the "fill" operation on the given arguments. */
@OpMethod(op = net.imagej.ops.image.fill.DefaultFill.class)
public <T extends Type<T>> Iterable<T> fill(final Iterable<T> out,
final T in)
{
@SuppressWarnings("unchecked")
final Iterable<T> result = (Iterable<T>) ops().run(
net.imagej.ops.Ops.Image.Fill.class, out, in);
return result;
}
// -- histogram --
/** Executes the "histogram" operation on the given arguments. */
@OpMethod(op = Ops.Image.Histogram.class)
public Object histogram(final Object... args) {
return ops().run(Ops.Image.Histogram.class, args);
}
/** Executes the "histogram" operation on the given arguments. */
@OpMethod(op = net.imagej.ops.image.histogram.HistogramCreate.class)
public <T extends RealType<T>> Histogram1d<T> histogram(final Iterable<T> in) {
@SuppressWarnings("unchecked")
final Histogram1d<T> result = (Histogram1d<T>) ops().run(
net.imagej.ops.Ops.Image.Histogram.class, in);
return result;
}
/** Executes the "histogram" operation on the given arguments. */
@OpMethod(op = net.imagej.ops.image.histogram.HistogramCreate.class)
public <T extends RealType<T>> Histogram1d<T> histogram(
final Iterable<T> in, final int numBins) {
@SuppressWarnings("unchecked")
final Histogram1d<T> result = (Histogram1d<T>) ops().run(
net.imagej.ops.Ops.Image.Histogram.class, in,
numBins);
return result;
}
//-- integral --
@SuppressWarnings({ "unchecked", "rawtypes" })
@OpMethod(op = net.imagej.ops.image.integral.DefaultIntegralImg.class)
public <T extends RealType<T>> RandomAccessibleInterval<RealType> integral(
final RandomAccessibleInterval<T> in, final int order)
{
final RandomAccessibleInterval<RealType> result =
(RandomAccessibleInterval) ops().run(Ops.Image.Integral.class, in, order);
return result;
}
@SuppressWarnings({ "unchecked", "rawtypes" })
@OpMethod(ops = { net.imagej.ops.image.integral.DefaultIntegralImg.class,
net.imagej.ops.image.integral.WrappedIntegralImg.class })
public <T extends RealType<T>> RandomAccessibleInterval<RealType> integral(
final RandomAccessibleInterval<T> in)
{
final RandomAccessibleInterval<RealType> result =
(RandomAccessibleInterval) ops().run(Ops.Image.Integral.class, in);
return result;
}
@SuppressWarnings({ "unchecked", "rawtypes" })
@OpMethod(op = net.imagej.ops.image.integral.DefaultIntegralImg.class)
public <T extends RealType<T>> RandomAccessibleInterval<RealType> integral(
final RandomAccessibleInterval<RealType> out,
final RandomAccessibleInterval<T> in, final int order)
{
final RandomAccessibleInterval<RealType> result =
(RandomAccessibleInterval) ops().run(
net.imagej.ops.image.integral.DefaultIntegralImg.class, out, in, order);
return result;
}
@SuppressWarnings({ "unchecked", "rawtypes" })
@OpMethod(op = net.imagej.ops.image.integral.DefaultIntegralImg.class)
public <T extends RealType<T>> RandomAccessibleInterval<RealType> integral(
final RandomAccessibleInterval<RealType> out,
final RandomAccessibleInterval<T> in)
{
final RandomAccessibleInterval<RealType> result =
(RandomAccessibleInterval) ops().run(
net.imagej.ops.image.integral.DefaultIntegralImg.class, out, in);
return result;
}
// -- invert --
/** Executes the "invert" operation on the given arguments. */
@OpMethod(op = Ops.Image.Invert.class)
public Object invert(final Object... args) {
return ops().run(Ops.Image.Invert.class, args);
}
/** Executes the "invert" operation on the given arguments. */
@OpMethod(op = net.imagej.ops.image.invert.InvertII.class)
public <I extends RealType<I>, O extends RealType<O>> IterableInterval<O> invert(
final IterableInterval<O> out, final IterableInterval<I> in) {
@SuppressWarnings("unchecked")
final IterableInterval<O> result = (IterableInterval<O>) ops().run(
net.imagej.ops.Ops.Image.Invert.class, out,
in);
return result;
}
// -- normalize --
/** Executes the "normalize" operation on the given arguments. */
@OpMethod(op = Ops.Image.Normalize.class)
public Object normalize(final Object... args) {
return ops().run(Ops.Image.Normalize.class, args);
}
@OpMethod(op = net.imagej.ops.image.normalize.NormalizeIIComputer.class)
public
<T extends RealType<T>> IterableInterval<T> normalize(
final IterableInterval<T> out, final IterableInterval<T> in)
{
@SuppressWarnings("unchecked")
final IterableInterval<T> result =
(IterableInterval<T>) ops()
.run(net.imagej.ops.Ops.Image.Normalize.class,
out, in);
return result;
}
@OpMethod(op = net.imagej.ops.image.normalize.NormalizeIIComputer.class)
public
<T extends RealType<T>> IterableInterval<T> normalize(
final IterableInterval<T> out, final IterableInterval<T> in,
final T sourceMin)
{
@SuppressWarnings("unchecked")
final IterableInterval<T> result =
(IterableInterval<T>) ops().run(
net.imagej.ops.Ops.Image.Normalize.class, out,
in, sourceMin);
return result;
}
@OpMethod(op = net.imagej.ops.image.normalize.NormalizeIIComputer.class)
public
<T extends RealType<T>> IterableInterval<T> normalize(
final IterableInterval<T> out, final IterableInterval<T> in,
final T sourceMin, final T sourceMax)
{
@SuppressWarnings("unchecked")
final IterableInterval<T> result =
(IterableInterval<T>) ops().run(
net.imagej.ops.Ops.Image.Normalize.class, out,
in, sourceMin, sourceMax);
return result;
}
@OpMethod(op = net.imagej.ops.image.normalize.NormalizeIIComputer.class)
public
<T extends RealType<T>> IterableInterval<T> normalize(
final IterableInterval<T> out, final IterableInterval<T> in,
final T sourceMin, final T sourceMax, final T targetMin)
{
@SuppressWarnings("unchecked")
final IterableInterval<T> result =
(IterableInterval<T>) ops().run(
net.imagej.ops.Ops.Image.Normalize.class, out,
in, sourceMin, sourceMax, targetMin);
return result;
}
@OpMethod(op = net.imagej.ops.image.normalize.NormalizeIIComputer.class)
public
<T extends RealType<T>>
IterableInterval<T>
normalize(final IterableInterval<T> out, final IterableInterval<T> in,
final T sourceMin, final T sourceMax, final T targetMin, final T targetMax)
{
@SuppressWarnings("unchecked")
final IterableInterval<T> result =
(IterableInterval<T>) ops().run(
net.imagej.ops.Ops.Image.Normalize.class, out,
in, sourceMin, sourceMax, targetMin, targetMax);
return result;
}
@OpMethod(
op = net.imagej.ops.image.normalize.NormalizeIIFunction.class)
public
<T extends RealType<T>> IterableInterval<T> normalize(
final IterableInterval<T> in)
{
@SuppressWarnings("unchecked")
final IterableInterval<T> result =
(IterableInterval<T>) ops().run(
net.imagej.ops.Ops.Image.Normalize.class,
in);
return result;
}
@OpMethod(
op = net.imagej.ops.image.normalize.NormalizeIIFunction.class)
public
<T extends RealType<T>> IterableInterval<T> normalize(
final IterableInterval<T> in, final T sourceMin)
{
@SuppressWarnings("unchecked")
final IterableInterval<T> result =
(IterableInterval<T>) ops().run(
net.imagej.ops.Ops.Image.Normalize.class,
in, sourceMin);
return result;
}
@OpMethod(
op = net.imagej.ops.image.normalize.NormalizeIIFunction.class)
public
<T extends RealType<T>> IterableInterval<T> normalize(
final IterableInterval<T> in, final T sourceMin, final T sourceMax)
{
@SuppressWarnings("unchecked")
final IterableInterval<T> result =
(IterableInterval<T>) ops().run(
net.imagej.ops.Ops.Image.Normalize.class,
in, sourceMin, sourceMax);
return result;
}
@OpMethod(
op = net.imagej.ops.image.normalize.NormalizeIIFunction.class)
public
<T extends RealType<T>> IterableInterval<T> normalize(
final IterableInterval<T> in, final T sourceMin, final T sourceMax,
final T targetMin)
{
@SuppressWarnings("unchecked")
final IterableInterval<T> result =
(IterableInterval<T>) ops().run(
net.imagej.ops.Ops.Image.Normalize.class,
in, sourceMin, sourceMax, targetMin);
return result;
}
@OpMethod(
op = net.imagej.ops.image.normalize.NormalizeIIFunction.class)
public
<T extends RealType<T>> IterableInterval<T> normalize(
final IterableInterval<T> in, final T sourceMin, final T sourceMax,
final T targetMin, final T targetMax)
{
@SuppressWarnings("unchecked")
final IterableInterval<T> result =
(IterableInterval<T>) ops().run(
net.imagej.ops.Ops.Image.Normalize.class,
in, sourceMin, sourceMax, targetMin, targetMax);
return result;
}
@OpMethod(
op = net.imagej.ops.image.normalize.NormalizeIIFunction.class)
public
<T extends RealType<T>> IterableInterval<T> normalize(
final IterableInterval<T> in, final T sourceMin, final T sourceMax,
final T targetMin, final T targetMax, final boolean isLazy)
{
@SuppressWarnings("unchecked")
final IterableInterval<T> result =
(IterableInterval<T>) ops().run(
net.imagej.ops.Ops.Image.Normalize.class,
in, sourceMin, sourceMax, targetMin, targetMax, isLazy);
return result;
}
// -- project --
/** Executes the "project" operation on the given arguments. */
@OpMethod(op = Ops.Image.Project.class)
public Object project(final Object... args) {
return ops().run(Ops.Image.Project.class, args);
}
/** Executes the "project" operation on the given arguments. */
@OpMethod(ops = {
net.imagej.ops.image.project.DefaultProjectParallel.class,
net.imagej.ops.image.project.ProjectRAIToII.class })
public <T, V> IterableInterval<V> project(final IterableInterval<V> out,
final RandomAccessibleInterval<T> in,
final UnaryComputerOp<Iterable<T>, V> method, final int dim) {
@SuppressWarnings("unchecked")
final IterableInterval<V> result = (IterableInterval<V>) ops().run(
net.imagej.ops.Ops.Image.Project.class, out, in, method, dim);
return result;
}
// -- scale --
/** Executes the "scale" operation on the given arguments. */
@OpMethod(op = Ops.Image.Scale.class)
public Object scale(final Object... args) {
return ops().run(Ops.Image.Scale.class, args);
}
/** Executes the "scale" operation on the given arguments. */
@OpMethod(op = net.imagej.ops.image.scale.ScaleImg.class)
public <T extends RealType<T>> Img<T> scale(final Img<T> in,
final double[] scaleFactors,
final InterpolatorFactory<T, RandomAccessible<T>> interpolator) {
@SuppressWarnings("unchecked")
final Img<T> result = (Img<T>) ops().run(
net.imagej.ops.Ops.Image.Scale.class, in, scaleFactors,
interpolator);
return result;
}
@Override
public String getName() {
return "image";
}
}
|
package net.qbar.common.block;
import net.minecraft.block.material.Material;
public class BlockKeypunch extends BlockMachineBase
{
public BlockKeypunch()
{
super("keypunch", Material.IRON);
}
}
|
package net.sf.jabref.pdfimport;
import java.io.File;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
import net.sf.jabref.Globals;
import net.sf.jabref.gui.BasePanel;
import net.sf.jabref.gui.BasePanelMode;
import net.sf.jabref.gui.EntryTypeDialog;
import net.sf.jabref.gui.JabRefFrame;
import net.sf.jabref.gui.entryeditor.EntryEditor;
import net.sf.jabref.gui.externalfiles.DroppedFileHandler;
import net.sf.jabref.gui.externalfiletype.ExternalFileTypes;
import net.sf.jabref.gui.filelist.FileListEntry;
import net.sf.jabref.gui.filelist.FileListTableModel;
import net.sf.jabref.gui.maintable.MainTable;
import net.sf.jabref.gui.undo.UndoableInsertEntry;
import net.sf.jabref.logic.bibtexkeypattern.BibtexKeyPatternUtil;
import net.sf.jabref.logic.importer.ParserResult;
import net.sf.jabref.logic.importer.fileformat.PdfContentImporter;
import net.sf.jabref.logic.importer.fileformat.PdfXmpImporter;
import net.sf.jabref.logic.l10n.Localization;
import net.sf.jabref.logic.util.UpdateField;
import net.sf.jabref.logic.util.io.FileUtil;
import net.sf.jabref.logic.xmp.XMPUtil;
import net.sf.jabref.model.database.KeyCollisionException;
import net.sf.jabref.model.entry.BibEntry;
import net.sf.jabref.model.entry.EntryType;
import net.sf.jabref.model.entry.FieldName;
import net.sf.jabref.preferences.JabRefPreferences;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public class PdfImporter {
private final JabRefFrame frame;
private final BasePanel panel;
private final MainTable entryTable;
private final int dropRow;
private static final Log LOGGER = LogFactory.getLog(PdfImporter.class);
/**
* Creates the PdfImporter
*
* @param frame the JabRef frame
* @param panel the panel to use
* @param entryTable the entry table to work on
* @param dropRow the row the entry is dropped to. May be -1 to indicate that no row is selected.
*/
public PdfImporter(JabRefFrame frame, BasePanel panel, MainTable entryTable, int dropRow) {
this.frame = frame;
this.panel = panel;
this.entryTable = entryTable;
this.dropRow = dropRow;
}
public class ImportPdfFilesResult {
private final List<String> noPdfFiles;
private final List<BibEntry> entries;
public ImportPdfFilesResult(List<String> noPdfFiles, List<BibEntry> entries) {
this.noPdfFiles = noPdfFiles;
this.entries = entries;
}
public List<String> getNoPdfFiles() {
return noPdfFiles;
}
public List<BibEntry> getEntries() {
return entries;
}
}
/**
*
* Imports the PDF files given by fileNames
*
* @param fileNames states the names of the files to import
* @return list of successful created BibTeX entries and list of non-PDF files
*/
public ImportPdfFilesResult importPdfFiles(List<String> fileNames) {
// sort fileNames in PDFfiles to import and other files
// PDFfiles: variable files
// other files: variable noPdfFiles
List<String> files = new ArrayList<>(fileNames);
List<String> noPdfFiles = new ArrayList<>();
for (String file : files) {
if (!PdfFileFilter.accept(file)) {
noPdfFiles.add(file);
}
}
files.removeAll(noPdfFiles);
// files and noPdfFiles correctly sorted
// import the files
List<BibEntry> entries = importPdfFilesInternal(files);
return new ImportPdfFilesResult(noPdfFiles, entries);
}
/**
* @param fileNames - PDF files to import
* @return true if the import succeeded, false otherwise
*/
private List<BibEntry> importPdfFilesInternal(List<String> fileNames) {
if (panel == null) {
return Collections.emptyList();
}
ImportDialog importDialog = null;
boolean doNotShowAgain = false;
boolean neverShow = Globals.prefs.getBoolean(JabRefPreferences.IMPORT_ALWAYSUSE);
int globalChoice = Globals.prefs.getInt(JabRefPreferences.IMPORT_DEFAULT_PDF_IMPORT_STYLE);
List<BibEntry> res = new ArrayList<>();
for (String fileName : fileNames) {
if (!neverShow && !doNotShowAgain) {
importDialog = new ImportDialog(dropRow >= 0, fileName);
if (!XMPUtil.hasMetadata(Paths.get(fileName), Globals.prefs.getXMPPreferences())) {
importDialog.disableXMPChoice();
}
importDialog.setLocationRelativeTo(frame);
importDialog.showDialog();
doNotShowAgain = importDialog.isDoNotShowAgain();
}
if (neverShow || (importDialog.getResult() == JOptionPane.OK_OPTION)) {
int choice = neverShow ? globalChoice : importDialog.getChoice();
switch (choice) {
case ImportDialog.XMP:
doXMPImport(fileName, res);
break;
case ImportDialog.CONTENT:
doContentImport(fileName, res);
break;
case ImportDialog.NOMETA:
createNewBlankEntry(fileName).ifPresent(res::add);
break;
case ImportDialog.ONLYATTACH:
DroppedFileHandler dfh = new DroppedFileHandler(frame, panel);
dfh.linkPdfToEntry(fileName, entryTable, dropRow);
break;
default:
break;
}
}
}
return res;
}
private void doXMPImport(String fileName, List<BibEntry> res) {
List<BibEntry> localRes = new ArrayList<>();
PdfXmpImporter importer = new PdfXmpImporter(Globals.prefs.getXMPPreferences());
Path filePath = Paths.get(fileName);
ParserResult result = importer.importDatabase(filePath, Globals.prefs.getDefaultEncoding());
if (result.hasWarnings()) {
frame.showMessage(result.getErrorMessage());
}
localRes.addAll(result.getDatabase().getEntries());
BibEntry entry;
if (localRes.isEmpty()) {
// import failed -> generate default entry
LOGGER.info("Import failed");
createNewBlankEntry(fileName).ifPresent(res::add);
return;
}
// only one entry is imported
entry = localRes.get(0);
// insert entry to database and link file
panel.getDatabase().insertEntry(entry);
panel.markBaseChanged();
FileListTableModel tm = new FileListTableModel();
File toLink = new File(fileName);
// Get a list of file directories:
List<String> dirsS = panel.getBibDatabaseContext()
.getFileDirectories(Globals.prefs.getFileDirectoryPreferences());
tm.addEntry(0, new FileListEntry(toLink.getName(), FileUtil.shortenFileName(toLink, dirsS).getPath(),
ExternalFileTypes.getInstance().getExternalFileTypeByName("PDF")));
entry.setField(FieldName.FILE, tm.getStringRepresentation());
res.add(entry);
}
private Optional<BibEntry> createNewBlankEntry(String fileName) {
Optional<BibEntry> newEntry = createNewEntry();
newEntry.ifPresent(bibEntry -> {
DroppedFileHandler dfh = new DroppedFileHandler(frame, panel);
dfh.linkPdfToEntry(fileName, bibEntry);
});
return newEntry;
}
private void doContentImport(String fileName, List<BibEntry> res) {
PdfContentImporter contentImporter = new PdfContentImporter(
Globals.prefs.getImportFormatPreferences());
Path filePath = Paths.get(fileName);
ParserResult result = contentImporter.importDatabase(filePath, Globals.prefs.getDefaultEncoding());
if (result.hasWarnings()) {
frame.showMessage(result.getErrorMessage());
}
if (!result.getDatabase().hasEntries()) {
// import failed -> generate default entry
createNewBlankEntry(fileName).ifPresent(res::add);
return;
}
// only one entry is imported
BibEntry entry = result.getDatabase().getEntries().get(0);
// insert entry to database and link file
panel.getDatabase().insertEntry(entry);
panel.markBaseChanged();
BibtexKeyPatternUtil.makeAndSetLabel(panel.getBibDatabaseContext().getMetaData()
.getCiteKeyPattern(Globals.prefs.getBibtexKeyPatternPreferences().getKeyPattern()), panel.getDatabase(), entry,
Globals.prefs.getBibtexKeyPatternPreferences());
DroppedFileHandler dfh = new DroppedFileHandler(frame, panel);
dfh.linkPdfToEntry(fileName, entry);
SwingUtilities.invokeLater(() -> panel.highlightEntry(entry));
if (Globals.prefs.getBoolean(JabRefPreferences.AUTO_OPEN_FORM)) {
EntryEditor editor = panel.getEntryEditor(entry);
panel.showEntryEditor(editor);
}
res.add(entry);
}
private Optional<BibEntry> createNewEntry() {
// Find out what type is desired
EntryTypeDialog etd = new EntryTypeDialog(frame);
// We want to center the dialog, to make it look nicer.
etd.setLocationRelativeTo(frame);
etd.setVisible(true);
EntryType type = etd.getChoice();
if (type != null) { // Only if the dialog was not canceled.
final BibEntry bibEntry = new BibEntry(type.getName());
try {
panel.getDatabase().insertEntry(bibEntry);
// Set owner/timestamp if options are enabled:
List<BibEntry> list = new ArrayList<>();
list.add(bibEntry);
UpdateField.setAutomaticFields(list, true, true, Globals.prefs.getUpdateFieldPreferences());
// Create an UndoableInsertEntry object.
panel.getUndoManager().addEdit(new UndoableInsertEntry(panel.getDatabase(), bibEntry, panel));
panel.output(Localization.lang("Added new") + " '" + type.getName().toLowerCase() + "' "
+ Localization.lang("entry") + ".");
// We are going to select the new entry. Before that, make sure that we are in
// show-entry mode. If we aren't already in that mode, enter the WILL_SHOW_EDITOR
// mode which makes sure the selection will trigger display of the entry editor
// and adjustment of the splitter.
if (panel.getMode() != BasePanelMode.SHOWING_EDITOR) {
panel.setMode(BasePanelMode.WILL_SHOW_EDITOR);
}
SwingUtilities.invokeLater(() -> panel.showEntry(bibEntry));
// The database just changed.
panel.markBaseChanged();
return Optional.of(bibEntry);
} catch (KeyCollisionException ex) {
LOGGER.info("Key collision occurred", ex);
}
}
return Optional.empty();
}
}
|
package org.opencms.ade.contenteditor.client;
import com.alkacon.acacia.client.EditorBase;
import com.alkacon.acacia.client.I_WidgetFactory;
import com.alkacon.acacia.client.widgets.I_EditWidget;
import com.alkacon.acacia.client.widgets.StringWidget;
import com.alkacon.acacia.client.widgets.TinyMCEWidget;
import com.alkacon.acacia.shared.ContentDefinition;
import com.alkacon.vie.shared.I_Entity;
import org.opencms.ade.contenteditor.shared.rpc.I_CmsContentServiceAsync;
import org.opencms.gwt.client.rpc.CmsRpcAction;
import java.util.HashMap;
import java.util.Map;
import com.google.gwt.user.client.Command;
/**
* The content editor base.<p>
*/
public class CmsEditorBase extends EditorBase {
/**
* Constructor.<p>
*
* @param service the content service
*/
public CmsEditorBase(I_CmsContentServiceAsync service) {
super(service);
Map<String, I_WidgetFactory> widgetFactories = new HashMap<String, I_WidgetFactory>();
widgetFactories.put("org.opencms.widgets.CmsInputWidget", new I_WidgetFactory() {
public I_EditWidget createWidget(String configuration) {
I_EditWidget widget = new StringWidget();
widget.setConfiguration(configuration);
return widget;
}
});
widgetFactories.put("org.opencms.widgets.CmsHtmlWidget", new I_WidgetFactory() {
public I_EditWidget createWidget(String configuration) {
I_EditWidget widget = new TinyMCEWidget(null);
widget.setConfiguration(configuration);
return widget;
}
});
getWidgetService().setWidgetFactories(widgetFactories);
}
/**
* Loads the content definition for the given entity and executes the callback on success.<p>
*
* @param entityId the entity id
* @param locale the content locale
* @param callback the callback
*/
@Override
public void loadContentDefinition(final String entityId, final String locale, final Command callback) {
CmsRpcAction<ContentDefinition> action = new CmsRpcAction<ContentDefinition>() {
@Override
public void execute() {
start(0, true);
getService().loadContentDefinition(entityId, locale, this);
}
@Override
protected void onResponse(ContentDefinition result) {
registerContentDefinition(result);
callback.execute();
stop(false);
}
};
action.execute();
}
/**
* Saves the given entity.<p>
*
* @param entity the entity
* @param locale the content locale
* @param clearOnSuccess <code>true</code> to clear all entities from VIE on success
* @param callback the callback executed on success
*/
@Override
public void saveEntity(
final I_Entity entity,
final String locale,
final boolean clearOnSuccess,
final Command callback) {
CmsRpcAction<Void> action = new CmsRpcAction<Void>() {
@Override
public void execute() {
start(0, true);
getService().saveEntity(com.alkacon.acacia.shared.Entity.serializeEntity(entity), locale, this);
}
@Override
protected void onResponse(Void result) {
callback.execute();
if (clearOnSuccess) {
clearVie();
}
stop(true);
}
};
action.execute();
}
}
|
package net.shadowfacts.foodies.item;
import cpw.mods.fml.common.registry.GameRegistry;
/**
* Helper class for registering items.
* @author shadowfacts
*/
public class FItems {
// Foods
public static Food toast;
public static Food tomato;
public static Food beefPattie;
public static Food hamburger;
public static Food cheese;
public static Food cheeseburger;
public static Food lettuce;
public static Food deluxeCheeseburger;
public static void preInit() {
// Create Items
toast = new Food(3, 0.3f).setUnlocalizedName("foodToast").setTextureName("foodToast");
tomato = new Food(1, 0.1f).setUnlocalizedName("fruitTomato").setTextureName("fruitTomato");
beefPattie = new Food(3, 0.6f).setUnlocalizedName("foodBeefPattie").setTextureName("foodBeefPattie");
hamburger = new Food(5, 0.7f).setUnlocalizedName("foodHamburger").setTextureName("foodHamburger");
cheese = new Food(2, 0.3f).setUnlocalizedName("foodCheese").setTextureName("foodCheese");
cheeseburger = new Food(10, 0.8f).setUnlocalizedName("foodCheeseburger").setTextureName("foodCheeseburger");
lettuce = new Food(1, 0.1f).setUnlocalizedName("vegeLettuce").setTextureName("vegeLettuce");
deluxeCheeseburger = new Food(15, 1.0f).setUnlocalizedName("foodDeluxeCheeseburger").setTextureName("foodDeluxeCheeseburger");
// Register items
GameRegistry.registerItem(toast, "foodToast");
GameRegistry.registerItem(tomato, "fruitTomato");
GameRegistry.registerItem(beefPattie, "foodBeefPattie");
GameRegistry.registerItem(hamburger, "foodHamburger");
GameRegistry.registerItem(cheese, "foodCheese");
GameRegistry.registerItem(cheeseburger, "foodCheeseburger");
GameRegistry.registerItem(lettuce, "vegeLettuce");
GameRegistry.registerItem(deluxeCheeseburger, "foodDeluxeCheeseburger");
}
public static void load() {
}
public static void postInit() {
}
}
|
package org.opencms.gwt.client.ui.input.form;
import org.opencms.gwt.client.Messages;
import org.opencms.gwt.client.ui.CmsPopup;
import org.opencms.gwt.client.ui.CmsPushButton;
import org.opencms.gwt.client.ui.input.I_CmsFormField;
import java.util.Map;
import com.google.gwt.core.client.Scheduler;
import com.google.gwt.core.client.Scheduler.ScheduledCommand;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.logical.shared.CloseEvent;
import com.google.gwt.event.logical.shared.CloseHandler;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.Event;
import com.google.gwt.user.client.Event.NativePreviewEvent;
import com.google.gwt.user.client.Event.NativePreviewHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.PopupPanel;
/**
* A dialog containing a form.<p>
*
* @since 8.0.0
*/
public class CmsFormDialog extends CmsPopup {
/** The maximum dialog width. */
public static final int MAX_DIALOG_WIDTH = 930;
/** The dialog width. */
public static final int STANDARD_DIALOG_WIDTH = 700;
/** The widget containing the form fields. */
protected CmsForm m_form;
/** The form handler for this dialog. */
protected I_CmsFormHandler m_formHandler;
/** The OK button of this dialog. */
private CmsPushButton m_okButton;
/** The event preview handler registration. */
private HandlerRegistration m_previewHandlerRegistration;
/**
* Constructs a new form dialog with a given title.<p>
*
* @param title the title of the form dialog
* @param form the form to use
*/
public CmsFormDialog(String title, CmsForm form) {
this(title, form, -1);
}
/**
* Constructs a new form dialog with a given title.<p>
*
* @param title the title of the form dialog
* @param form the form to use
* @param dialogWidth the dialog width
*/
public CmsFormDialog(String title, CmsForm form, int dialogWidth) {
super(title);
setGlassEnabled(true);
setAutoHideEnabled(false);
setModal(true);
// check the available width for this dialog
int windowWidth = Window.getClientWidth();
if (dialogWidth > 0) {
// reduce the dialog width if necessary
if ((windowWidth - 50) < dialogWidth) {
dialogWidth = windowWidth - 50;
}
} else {
dialogWidth = (windowWidth - 100) > STANDARD_DIALOG_WIDTH ? windowWidth - 100 : STANDARD_DIALOG_WIDTH;
dialogWidth = dialogWidth > MAX_DIALOG_WIDTH ? MAX_DIALOG_WIDTH : dialogWidth;
}
setWidth(dialogWidth);
addButton(createCancelButton());
m_okButton = createOkButton();
addButton(m_okButton);
m_form = form;
addCloseHandler(new CloseHandler<PopupPanel>() {
public void onClose(CloseEvent<PopupPanel> event) {
removePreviewHandler();
}
});
}
/**
* @see org.opencms.gwt.client.ui.CmsPopup#center()
*/
@Override
public void center() {
initContent();
registerPreviewHandler();
super.center();
notifyWidgetsOfOpen();
}
/**
* Gets the form of this dialog.<p>
*
* @return the form of this dialog
*/
public CmsForm getForm() {
return m_form;
}
/**
* Returns the 'OK' button.<p>
*
* @return the 'OK' button
*/
public CmsPushButton getOkButton() {
return m_okButton;
}
/**
* Sets the form handler for this form dialog.<p>
*
* @param formHandler the new form handler
*/
public void setFormHandler(I_CmsFormHandler formHandler) {
m_form.setFormHandler(formHandler);
}
/**
* Enables/disables the OK button.<p>
*
* @param enabled if true, enables the OK button, else disables it
*/
public void setOkButtonEnabled(final boolean enabled) {
Scheduler.get().scheduleDeferred(new ScheduledCommand() {
/**
* @see com.google.gwt.core.client.Scheduler.ScheduledCommand#execute()
*/
public void execute() {
// The event handling of GWT gets confused if we don't execute this as a scheduled command
getOkButton().setDown(false);
getOkButton().setEnabled(enabled);
}
});
}
/**
* @see org.opencms.gwt.client.ui.CmsPopup#show()
*/
@Override
public void show() {
initContent();
registerPreviewHandler();
super.show();
notifyWidgetsOfOpen();
}
/**
* Initializes the form content.<p>
*/
protected void initContent() {
setMainContent(m_form.getWidget());
}
/**
* Called when the cancel button is clicked.
*/
protected void onClickCancel() {
hide();
}
/**
* The method which should be called when the user clicks on the OK button of the dialog.<p>
*/
protected void onClickOk() {
m_form.validateAndSubmit();
}
/**
* Registers the 'Enter' and 'Esc' shortcut action handler.<p>
*/
protected void registerPreviewHandler() {
NativePreviewHandler eventPreviewHandler = new NativePreviewHandler() {
public void onPreviewNativeEvent(NativePreviewEvent event) {
Event nativeEvent = Event.as(event.getNativeEvent());
if (DOM.eventGetType(nativeEvent) == Event.ONKEYDOWN) {
int keyCode = nativeEvent.getKeyCode();
if (keyCode == KeyCodes.KEY_ESCAPE) {
onClickCancel();
} else if (keyCode == KeyCodes.KEY_ENTER) {
onClickOk();
}
}
}
};
m_previewHandlerRegistration = Event.addNativePreviewHandler(eventPreviewHandler);
}
/**
* Removes the 'Enter' and 'Esc' shortcut action handler.<p>
*/
protected void removePreviewHandler() {
if (m_previewHandlerRegistration != null) {
m_previewHandlerRegistration.removeHandler();
m_previewHandlerRegistration = null;
}
}
/**
* Creates the cancel button.<p>
*
* @return the cancel button
*/
private CmsPushButton createCancelButton() {
addDialogClose(null);
CmsPushButton button = new CmsPushButton();
button.setText(Messages.get().key(Messages.GUI_CANCEL_0));
button.setUseMinWidth(true);
button.addClickHandler(new ClickHandler() {
/**
* @see com.google.gwt.event.dom.client.ClickHandler#onClick(com.google.gwt.event.dom.client.ClickEvent)
*/
public void onClick(ClickEvent event) {
onClickCancel();
}
});
return button;
}
/**
* Creates the OK button.<p>
*
* @return the OK button
*/
private CmsPushButton createOkButton() {
CmsPushButton button = new CmsPushButton();
button.setText(Messages.get().key(Messages.GUI_OK_0));
button.setUseMinWidth(true);
button.addClickHandler(new ClickHandler() {
/**
* @see com.google.gwt.event.dom.client.ClickHandler#onClick(com.google.gwt.event.dom.client.ClickEvent)
*/
public void onClick(ClickEvent event) {
onClickOk();
}
});
return button;
}
/**
* Tells all widgets that the dialog has been opened.<p>
*/
private void notifyWidgetsOfOpen() {
for (Map.Entry<String, I_CmsFormField> fieldEntry : m_form.getFields().entrySet()) {
fieldEntry.getValue().getWidget().setAutoHideParent(this);
}
}
}
|
package net.spy.memcached.ops;
public enum OperationType {
/*
* only Ascii Operation have WRITE or READ, ETC OperationType
* Binary Operation has only UNDEFIED OperationType
* because Arcus Client don't use Binary Operation.
*/
/*
* StoreOperationImpl (add / replace / set / asyncSetBulk)
* ConcatenationOperationImpl (append / prepend)
* MutatorOperationImpl (asyncIncr / asyncDecr)
* DeleteOperationImpl (delete)
* CASOperationImpl (asyncCAS, cas)
* CollectionCreateOperationImpl (asyncBopCreate / asyncLopCreate / asyncSopCreate)
* CollectionStoreOperationImpl (asyncBopInsert / asyncLopInsert / asyncSopInsert)
* CollectionDeleteOperationImpl (asynBopDelete / asyncLopDelete / asyncSopDelete)
* CollectionGetOperationImpl (asyncBopGet / asyncLopGet / asyncSopGet) is WRITE, when withDelete is true.
* ExtendedBTreeGetOperationImpl (asyncBopGet) is WRITE, when withDelete is true
* CollectionBulkStoreOperationImpl (asyncBopInsertBulk / asyncLopInsertBulk / asyncSopInsertBulk)
* CollectionPipedStoreOperationImpl (asyncBopPipedInsertBulk / asyncLopPipedInsertBulk / asyncSopPipedInsertBulk)
* CollectionPipedUpdateOperationImpl (asyncBopPipedUpdateBulk)
* CollectionUpsertOperationImpl (asyncBopUpsert)
* CollectionUpdateOperationImpl (asyncBopUpdate)
* CollectionMutateOperationImpl (asyncBopIncr / asyncBopDecr)
* BtreeStoreAndGetOpeartionImpl (asynBopInsertAndGetTrimmed)
* FlushOperationImpl / FlushByPrefixOperationImpl (flush)
* SetAttrOperationImpl (asyncSetAttr)
*/
WRITE,
/*
* GetOperationImpl (asyncGet / asyncGetBulk)
* GetsOperationImpl (asyncGets)
* CollectionGetOperationImpl (asynBopGet / asyncLopGet / asyncSopGet) is READ, when withDelete is false.
* ExtendedBTreeGetOperationImpl (asyncBopGet) is READ, when withDelete is false.
* CollectionExistOperationImpl (asyncSopExist)
* CollectionPipedExistOperationImpl (asyncSopPipedExistBulk)
* CollectionCountOperationImpl (asyncBopGetItemCount)
* BTreeGetBulkOperationImpl (asyncBopGetBulk)
* BTreeSortMergeGetOperationImpl (asyncBopSortMergeGet)
* BTreeFindPositionOperationImpl (asyncBopFindPosition)
* BTreeGetByPositionOperationImpl (asyncBopGetByPosition)
* BTreeFindPositionWithGetOperationImpl (asyncBopFindPositionWithGet)
* GetAttrOperationImpl (asyncGetAttr)
*/
READ,
/*
* StatsOperationImpl (getStats)
* VersionOperationImpl (getVersions)
*/
ETC,
/*
* When the type of an operation is undefined,
* it has the operation type of UNDEFINED.
*/
UNDEFINED
}
/* Operation Hierarchy (only ascii type)
* BaseOperationImple.java-Abstract
Operation.java-Interface
OperationImpl.java-extends[BaseOperationImpl]-implements[Operation]
BaseGetOpImpl.java-Abstract-extends[OperationImpl]
BaseStoreOperationImpl.java-Abstract-extends[OperationImpl]
FlushOperation.java-Interface-extends[Operation]
FlushByPrefixOperationImpl.java-extends[OperationImpl]-implements[FlushOperation]
FlushOperationImpl.java-extends[OperationImpl]-implements[FlushOperation]
KeyedOperation.java-Interface-extends[Operation]
BTreeFindPositionOperation.java-Interface-extends[KeyedOperation]
BTreeFindPositionOperationImpl.java-extends[OperationImpl]-implements[BTreeFindPositionOperation]
BTreeFindPositionWithGetOperation.java-Interface-extends[KeyedOperation]
BTreeFindPositionWithGetOperationImpl.java-extends[OperationImpl]-implements[KeyedOpeartion]
BTreeGetBulkOperation.java-Interface-extends[KeyedOperation]
BTreeGetBulkOperationImpl.java-extends[OpeartionImpl]-implements[KeyedOpeartion]
BTreeGetByPositionOperation.java-Interface-extends[KeyedOperation]
BTreeGetByPositionOperationImpl.java-extends[OperationImpl]-implements[KeyedOpeartion]
BTreeSortMergeGetOperation.java-Interface-extends[KeyedOpeartion]
BTreeSortMergeGetOperationImpl.java-extends[OperationImpl]-implements[BtreeSortMergeGetOperation]
BTreeStoreAndGetOperation.java-Interface-extends[KeyedOperation]
BTreeStoreAndGetOperationImpl.java-extends[OperationImpl]-implements[BtreeStoreAndGetOperation]
CASOperation.java-Interface-extends[KeyedOperation]
CASOperationImpl.java-extends[OpeartionImpl]-implements[CASOperation]
CollectionBulkStoreOperation.java-Interface-extends[KeyedOperation]
CollectionBulkStoreOperationImpl.java-extends[OpeartionImpl]-implements[CollectionBulkStoreOperation]
CollectionCountOperation.java-Interface-extends[KeyedOperation]
CollectionCountOperationImpl.java-extends[OperationImpl]-implements[CollectionCountOperation]
CollectionCreateOperation.java-Interface-extends[KeyedOperation]
CollectionCreateOperationImpl.java-extends[OperationImpl]-implements[CollectionCreateOperation]
CollectionDeleteOperation.java-Interface-extends[KeyedOperation]
CollectionDeleteOperationImpl.java-extends[OperationImpl]-implements[CollectionDeleteOperation]
CollectionExistOperation.java-Interface-extends[KeyedOperation]
CollectionExistOperationImpl.java-extends[OperationImpl]-implements[CollectionExistOperation]
CollectionGetOperation.java-Interface-extends[KeyedOperation]
CollectionGetOperationImpl.java-extends[OperationImpl]-implements[CollectionGetOperation]
ExtendedBTreeGetOperationImpl.java-extends[OperationImpl]-implements[CollectionGetOperation]
CollectionMutateOperation.java-Interface-extends[KeyedOperation]
CollectionMutateOperationImpl.java-extends[OperationImpl]-implements[CollectionMutateOperation]
CollectionPipedExistOperation.java-Interface-extends[KeyedOperation]
CollectionPipedExistOperationImpl.java-extends[OperationImpl]-implements[CollectionPipedExist]
CollectionPipedStoreOperation.java-Interface-extends[KeyedOperation]
CollectionPipedStoreOperationImpl.java-extends[OperationImpl]-implements[CollectionPipedStore]
CollectionPipedUpdateOperation.java-Interface-extends[KeyedOperation]
CollectionPipedUpdateOperationImpl.java-extends[OperationImpl]-implements[CollectionPipedUpdateOperation]
CollectionStoreOperation.java-Interface-extends[KeyedOperation]
CollectionStoreOperationImpl.java-extends[OperationImpl]-implements[CollectionStoreOperation]
CollectionUpsertOperationImpl.java-extends[OpeartionImpl]-implements[CollectionStoreOperation]
CollectionUpdateOperation.java-Interface-extends[KeyedOperation]
CollectionUpdateOperationImpl.java-extends[OperationImpl]-implements[OperationUpdateOperation]
CollectionUpsertOperation.java-Interface-extends[KeyedOperation]
ConcatenationOperation.java-Interface-extends[KeyedOperation]
ConcatenationOperationImpl.java-extends[BaseStoreOperationImpl]-implements[ConcatenationOperation]
DeleteOperation.java-Interface-extends[KeyedOperation]
DeleteOperationImpl.java-extends[OperationImpl]-implements[DeleteOperation]
ExtendedBTreeGetOperation.java-Interface-extends[KeyedOperation]
GetAttrOperation.java-Interface-extends[KeyedOperation]
GetAttrOperationImpl.java-extends[OperationImpl]-implements[GetAttrOperation]
OptimizedGetImpl.java-extends[GetOperationImpl]
GetOperation.java-Interface-extends[KeyedOperation]
GetOperationImpl.java-extends[BaseGetOpImpl]-implements[GetOperation]
GetsOperation.java-Interface-extends[KeyedOperation]
GetsOperationImpl.java-extends[BaseGetOpImpl]-implements[GetsOperation]
MutatorOperation.java-Interface-extends[KeyedOperation]
MutatorOperationImpl.java-extends[OperationImpl]-implements[MutatorOperation]
SetAttrOperation.java-Interface-extends[KeyedOperation]
SetAttrOperationImpl.java-extends[OperationImpl]-implements[SetAttrOperation]
StoreOperation.java-Interface-extends[KeyedOperation]
StoreOperationImpl.java-extends[BaseStoreOperationImpl]-implements[StoreOperation]
StatsOperation.java-Interface-extends[Operation]
StatsOperationImpl.java-extends[OperationImpl]-implements[StatsOperation]
NoopOperation.java-Interface-extends[Operation]
VersionOperation.java-Interface-extends[Operation]
VersionOperationImpl.java-extends[OperationImpl]-implements[VersionOperation]-implements[NoopOperation]
*/
|
package chat.client.gui;
import chat.client.agent.ChatClientAgent;
import jade.android.AndroidHelper;
import jade.android.MicroRuntimeService;
import jade.android.MicroRuntimeServiceBinder;
import jade.android.RuntimeCallback;
import jade.core.MicroRuntime;
import jade.core.Profile;
import jade.util.Logger;
import jade.util.leap.Properties;
import jade.wrapper.AgentController;
import jade.wrapper.ControllerException;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
/**
* This activity implement the main interface.
*
* @author Michele Izzo - Telecomitalia
*/
public class MainActivity extends Activity {
private Logger logger = Logger.getMyLogger(this.getClass().getName());
private MicroRuntimeServiceBinder microRuntimeServiceBinder;
private ServiceConnection serviceConnection;
static final int CHAT_REQUEST = 0;
static final int SETTINGS_REQUEST = 1;
private MyReceiver myReceiver;
private MyHandler myHandler;
private TextView infoTextView;
private String nickname;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
myReceiver = new MyReceiver();
IntentFilter killFilter = new IntentFilter();
killFilter.addAction("jade.demo.chat.KILL");
registerReceiver(myReceiver, killFilter);
IntentFilter showChatFilter = new IntentFilter();
showChatFilter.addAction("jade.demo.chat.SHOW_CHAT");
registerReceiver(myReceiver, showChatFilter);
myHandler = new MyHandler();
setContentView(R.layout.main);
Button button = (Button) findViewById(R.id.button_chat);
button.setOnClickListener(buttonChatListener);
infoTextView = (TextView) findViewById(R.id.infoTextView);
infoTextView.setText("");
}
@Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(myReceiver);
logger.info("Destroy activity!");
}
private static boolean checkName(String name) {
if (name == null || name.trim().equals("")) {
return false;
}
// FIXME: should also check that name is composed
// of letters and digits only
return true;
}
private OnClickListener buttonChatListener = new OnClickListener() {
public void onClick(View v) {
final EditText nameField = (EditText) findViewById(R.id.edit_nickname);
nickname = nameField.getText().toString();
if (!checkName(nickname)) {
logger.info("Invalid nickname!");
myHandler.postError(getString(R.string.msg_nickname_not_valid));
} else {
try {
SharedPreferences settings = getSharedPreferences(
"jadeChatPrefsFile", 0);
String host = settings.getString("defaultHost", "");
String port = settings.getString("defaultPort", "");
infoTextView.setText(getString(R.string.msg_connecting_to)
+ " " + host + ":" + port + "...");
startChat(nickname, host, port, agentStartupCallback);
} catch (Exception ex) {
logger.severe("Unexpected exception creating chat agent!");
infoTextView.setText(getString(R.string.msg_unexpected));
}
}
}
};
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main_menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_settings:
Intent showSettings = new Intent(MainActivity.this,
SettingsActivity.class);
MainActivity.this.startActivityForResult(showSettings,
SETTINGS_REQUEST);
return true;
case R.id.menu_exit:
finish();
default:
return super.onOptionsItemSelected(item);
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CHAT_REQUEST) {
if (resultCode == RESULT_CANCELED) {
// The chat activity was closed.
infoTextView.setText("");
logger.info("Stopping Jade...");
microRuntimeServiceBinder
.stopAgentContainer(new RuntimeCallback<Void>() {
@Override
public void onSuccess(Void thisIsNull) {
}
@Override
public void onFailure(Throwable throwable) {
logger.severe("Failed to stop the "
+ ChatClientAgent.class.getName()
+ "...");
agentStartupCallback.onFailure(throwable);
}
});
}
}
}
private RuntimeCallback<AgentController> agentStartupCallback = new RuntimeCallback<AgentController>() {
@Override
public void onSuccess(AgentController agent) {
}
@Override
public void onFailure(Throwable throwable) {
logger.info("Nickname already in use!");
myHandler.postError(getString(R.string.msg_nickname_in_use));
}
};
public void ShowDialog(String message) {
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setMessage(message).setCancelable(false)
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
private class MyReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
logger.info("Received intent " + action);
if (action.equalsIgnoreCase("jade.demo.chat.KILL")) {
finish();
}
if (action.equalsIgnoreCase("jade.demo.chat.SHOW_CHAT")) {
Intent showChat = new Intent(MainActivity.this,
ChatActivity.class);
showChat.putExtra("nickname", nickname);
MainActivity.this
.startActivityForResult(showChat, CHAT_REQUEST);
}
}
}
private class MyHandler extends Handler {
@Override
public void handleMessage(Message msg) {
Bundle bundle = msg.getData();
if (bundle.containsKey("error")) {
infoTextView.setText("");
String message = bundle.getString("error");
ShowDialog(message);
}
}
public void postError(String error) {
Message msg = obtainMessage();
Bundle b = new Bundle();
b.putString("error", error);
msg.setData(b);
sendMessage(msg);
}
}
public void startChat(final String nickname, final String host,
final String port,
final RuntimeCallback<AgentController> agentStartupCallback) {
final Properties profile = new Properties();
profile.setProperty(Profile.MAIN_HOST, host);
profile.setProperty(Profile.MAIN_PORT, port);
profile.setProperty(Profile.MAIN, Boolean.FALSE.toString());
profile.setProperty(Profile.JVM, Profile.ANDROID);
if (AndroidHelper.isEmulator()) {
// Emulator: this is needed to work with emulated devices
profile.setProperty(Profile.LOCAL_HOST, AndroidHelper.LOOPBACK);
} else {
profile.setProperty(Profile.LOCAL_HOST,
AndroidHelper.getLocalIPAddress());
}
// Emulator: this is not really needed on a real device
profile.setProperty(Profile.LOCAL_PORT, "2000");
if (microRuntimeServiceBinder == null) {
serviceConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className,
IBinder service) {
microRuntimeServiceBinder = (MicroRuntimeServiceBinder) service;
logger.info("Gateway successfully bound to MicroRuntimeService");
startContainer(nickname, profile, agentStartupCallback);
};
public void onServiceDisconnected(ComponentName className) {
microRuntimeServiceBinder = null;
logger.info("Gateway unbound from MicroRuntimeService");
}
};
logger.info("Binding Gateway to MicroRuntimeService...");
bindService(new Intent(getApplicationContext(),
MicroRuntimeService.class), serviceConnection,
Context.BIND_AUTO_CREATE);
} else {
logger.info("MicroRumtimeGateway already binded to service");
startContainer(nickname, profile, agentStartupCallback);
}
}
private void startContainer(final String nickname, Properties profile,
final RuntimeCallback<AgentController> agentStartupCallback) {
if (!MicroRuntime.isRunning()) {
microRuntimeServiceBinder.startAgentContainer(profile,
new RuntimeCallback<Void>() {
@Override
public void onSuccess(Void thisIsNull) {
logger.info("Successfully start of the container...");
startAgent(nickname, agentStartupCallback);
}
@Override
public void onFailure(Throwable throwable) {
logger.severe("Failed to start the container...");
}
});
} else {
startAgent(nickname, agentStartupCallback);
}
}
private void startAgent(final String nickname,
final RuntimeCallback<AgentController> agentStartupCallback) {
microRuntimeServiceBinder.startAgent(nickname,
ChatClientAgent.class.getName(),
new Object[] { getApplicationContext() },
new RuntimeCallback<Void>() {
@Override
public void onSuccess(Void thisIsNull) {
logger.info("Successfully start of the "
+ ChatClientAgent.class.getName() + "...");
try {
agentStartupCallback.onSuccess(MicroRuntime
.getAgent(nickname));
} catch (ControllerException e) {
// Should never happen
agentStartupCallback.onFailure(e);
}
}
@Override
public void onFailure(Throwable throwable) {
logger.severe("Failed to start the "
+ ChatClientAgent.class.getName() + "...");
agentStartupCallback.onFailure(throwable);
}
});
}
}
|
package net.zero918nobita.Xemime.entity;
import net.zero918nobita.Xemime.NodeType;
import net.zero918nobita.Xemime.Recognizable;
import net.zero918nobita.Xemime.ast.FatalException;
import net.zero918nobita.Xemime.ast.Node;
/**
*
* @author Kodai Matsumoto
*/
public class Str extends Node implements Recognizable {
private final String value;
public Str(int location, String str) {
super(location);
value = str;
}
public Str(String str) {
this(0, str);
}
@Override
public NodeType recognize() {
return NodeType.STR;
}
@Override
public String toString() {
return value;
}
@Override
public boolean equals(Object obj) {
return (obj instanceof Str) && (this.value.equals(obj.toString()));
}
/**
*
* @param line
* @param obj
* @return
* @throws FatalException
*/
@Override
public Str add(int line, Node obj) throws FatalException {
if (obj instanceof Str) {
return new Str(0, this.value + ((Str) obj).value);
} else {
throw new FatalException(line, 128);
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.