answer
stringlengths 17
10.2M
|
|---|
package br.jus.trf2.apolo.signer;
import java.io.ByteArrayInputStream;
import java.sql.Blob;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Types;
import com.crivano.swaggerservlet.SwaggerServlet;
import com.crivano.swaggerservlet.SwaggerUtils;
import br.jus.trf2.assijus.system.api.IAssijusSystem.DocIdPdfGetRequest;
import br.jus.trf2.assijus.system.api.IAssijusSystem.DocIdPdfGetResponse;
import br.jus.trf2.assijus.system.api.IAssijusSystem.IDocIdPdfGet;
public class DocIdPdfGet implements IDocIdPdfGet {
@Override
public void run(DocIdPdfGetRequest req, DocIdPdfGetResponse resp)
throws Exception {
String status = null;
String error = null;
final boolean fForcePKCS7 = true;
Id id = new Id(req.id);
byte[] pdf = null;
// Chama a procedure que recupera os dados do PDF
Connection conn = null;
CallableStatement cstmt = null;
Exception exception = null;
try {
conn = Utils.getConnection();
cstmt = conn.prepareCall(Utils.getSQL("pdfinfo"));
// 2=TRF)
cstmt.setInt(1, id.codsecao);
cstmt.setLong(2, id.coddoc);
cstmt.setTimestamp(3, id.dthrmov);
// CPF
cstmt.setString(4, id.cpf);
cstmt.setInt(5, fForcePKCS7 ? 1 : 0);
// SHA1
cstmt.registerOutParameter(6, Types.VARCHAR);
// SHA256
cstmt.registerOutParameter(7, Types.VARCHAR);
cstmt.registerOutParameter(8, Types.NUMERIC);
cstmt.registerOutParameter(9, Types.TIMESTAMP);
// PDF uncompressed
cstmt.registerOutParameter(10, Types.BLOB);
// Status
cstmt.registerOutParameter(11, Types.VARCHAR);
// Error
cstmt.registerOutParameter(12, Types.VARCHAR);
cstmt.execute();
// for diferente de null
Blob blob = cstmt.getBlob(10);
if (blob != null)
pdf = blob.getBytes(1, (int) blob.length());
status = cstmt.getString(11);
error = cstmt.getString(12);
} catch (Exception ex) {
exception = ex;
pdf = null;
} finally {
if (cstmt != null)
cstmt.close();
if (conn != null)
conn.close();
}
if (pdf == null
&& Utils.getProperty("pdfservice.url", null) != null) {
byte[] docCompressed = null;
// Get documents from Oracle
conn = null;
PreparedStatement pstmt = null;
ResultSet rset = null;
try {
conn = Utils.getConnection();
pstmt = conn.prepareStatement(Utils.getSQL("doc"));
pstmt.setInt(1, id.codsecao);
pstmt.setLong(2, id.coddoc);
pstmt.setTimestamp(3, id.dthrmov);
rset = pstmt.executeQuery();
if (rset.next()) {
Blob blob = rset.getBlob("TXTWORD");
docCompressed = blob.getBytes(1L, (int) blob.length());
} else {
throw new Exception("Nenhum DOC encontrado.");
}
if (rset.next())
throw new Exception("Mais de um DOC encontrado.");
} finally {
if (rset != null)
rset.close();
if (pstmt != null)
pstmt.close();
if (conn != null)
conn.close();
}
if (docCompressed == null)
throw new Exception("Não foi possível localizar o DOC.");
// Decompress
byte[] doc = Utils.decompress(docCompressed);
if (doc == null)
throw new Exception("Não foi possível descomprimir o DOC.");
// Convert
pdf = Utils.convertDocToPdf(doc);
// pdf = Utils.convertDocToPdfUnoConv(doc);
if (pdf == null)
throw new Exception("Não foi possível converter para PDF.");
}
if (pdf == null && exception != null)
throw exception;
// Produce responses
resp.inputstream = new ByteArrayInputStream(pdf);
SwaggerServlet.getHttpServletResponse().addHeader("Doc-Secret", getSecret(id));
}
public static String getSecret(Id id) throws Exception {
// Get documents from Oracle
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rset = null;
try {
conn = Utils.getConnection();
pstmt = conn.prepareStatement(Utils.getSQL("secret"));
pstmt.setInt(1, id.codsecao);
pstmt.setLong(2, id.coddoc);
pstmt.setTimestamp(3, id.dthrmov);
rset = pstmt.executeQuery();
if (rset.next()) {
return rset.getString("secret");
} else {
throw new Exception("Nenhum DOC encontrado.");
}
} finally {
if (rset != null)
rset.close();
if (pstmt != null)
pstmt.close();
if (conn != null)
conn.close();
}
}
@Override
public String getContext() {
return "visualizar documento";
}
}
|
package com.acme.apis;
import com.acme.apis.models.Contact;
import com.ibm.mfp.adapter.api.OAuthSecurity;
import io.swagger.annotations.*;
import java.util.*;
import java.util.logging.Logger;
import javax.ws.rs.*;
import javax.ws.rs.core.*;
import com.ibm.mfp.adapter.api.ConfigurationAPI;
@Api(value = "Contact list adapter")
@Path("/")
public class ContactListApiResource {
// Define logger (Standard java.util.Logger)
static Logger logger = Logger.getLogger(ContactListApiResource.class.getName());
// Inject the MFP configuration API:
@Context
ConfigurationAPI configApi;
static Map<String, Contact> contactMap = new HashMap<String, Contact>();
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Success", response = Contact[].class)
})
@ApiOperation(value = "Returns A list of all the contacts")
@GET
@Produces(MediaType.APPLICATION_JSON)
@OAuthSecurity(enabled = false)
public Collection<Contact> getAllContacts() {
return contactMap.values();
}
@ApiOperation(value = "Add contact")
@ApiResponses(value = {
@ApiResponse(code = 201, message = "Created", responseHeaders = {
@ResponseHeader(name = "Location", description = "Location (URL) of the created contact")
}),
@ApiResponse(code = 406, message = "Contact (name) already exist")
})
@POST
@Consumes(MediaType.APPLICATION_JSON)
public Response addContact(Contact contact, @Context UriInfo uriInfo) {
if (contactMap.containsKey(contact.name)) {
return Response.status(401).entity("Contact named: " + contact.name + " already exist").build();
}
contactMap.put(contact.name, contact);
UriBuilder builder = uriInfo.getAbsolutePathBuilder();
builder.path(contact.name);
return Response.created(builder.build()).build();
}
@ApiOperation(value = "Update contact")
@ApiResponses(value = {
@ApiResponse(code = 201, message = "Updated successfully"),
@ApiResponse(code = 404, message = "Contact not found")
})
@PUT
@Consumes(MediaType.APPLICATION_JSON)
public Response updateContact(Contact contact) {
if (contactMap.containsKey(contact.name)) {
contactMap.put(contact.name, contact);
} else {
throw new NotFoundException(contact.name);
}
return Response.ok().build();
}
@ApiOperation(value = "Get contact")
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Success", response = Contact.class),
@ApiResponse(code = 404, message = "Contact not found")
})
@GET
@Path("{name}")
@Produces(MediaType.APPLICATION_JSON)
public Contact getContact(@PathParam("name") String name) {
Contact contact = contactMap.get(name);
if (contact == null) {
throw new NotFoundException(name);
}
return contact;
}
@ApiOperation(value = "Delete contact")
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Success"),
@ApiResponse(code = 404, message = "Contact not found")
})
@DELETE
@Path("{name}")
public Response deleteContact(@PathParam("name") String name) {
Contact contact = contactMap.remove(name);
if (contact == null) {
throw new NotFoundException(name);
}
return Response.ok().build();
}
}
|
package com.acme.apis;
import com.acme.apis.models.Contact;
import io.swagger.annotations.*;
import java.util.*;
import java.util.logging.Logger;
import javax.ws.rs.*;
import javax.ws.rs.core.*;
import com.ibm.mfp.adapter.api.ConfigurationAPI;
@Api(value = "Contact list adapter")
@Path("/")
public class ContactListApiResource {
// Define logger (Standard java.util.Logger)
static Logger logger = Logger.getLogger(ContactListApiResource.class.getName());
// Inject the MFP configuration API:
@Context
ConfigurationAPI configApi;
static Map<String, Contact> contactMap = new HashMap<String, Contact>();
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Success", response = Contact[].class)
})
@ApiOperation(value = "Returns A list of all the contacts")
@GET
@Produces(MediaType.APPLICATION_JSON)
public Collection<Contact> getAllContacts() {
return contactMap.values();
}
@ApiOperation(value = "Add contact")
@ApiResponses(value = {
@ApiResponse(code = 201, message = "Created", responseHeaders = {
@ResponseHeader(name = "Location", description = "Location (URL) of the created contact")
}),
@ApiResponse(code = 406, message = "Contact (name) already exist")
})
@POST
@Consumes(MediaType.APPLICATION_JSON)
public Response addContact(Contact contact, @Context UriInfo uriInfo) {
if (contactMap.containsKey(contact.name)) {
return Response.status(409).entity("Contact named: " + contact.name + " already exist").build();
}
contactMap.put(contact.name, contact);
UriBuilder builder = uriInfo.getAbsolutePathBuilder();
builder.path(contact.name);
return Response.created(builder.build()).build();
}
@ApiOperation(value = "Update contact")
@ApiResponses(value = {
@ApiResponse(code = 201, message = "Updated successfully"),
@ApiResponse(code = 404, message = "Contact not found")
})
@PUT
@Consumes(MediaType.APPLICATION_JSON)
public Response updateContact(Contact contact) {
if (contactMap.containsKey(contact.name)) {
contactMap.put(contact.name, contact);
} else {
throw new NotFoundException(contact.name);
}
return Response.ok().build();
}
@ApiOperation(value = "Get contact")ix
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Success", response = Contact.class),
@ApiResponse(code = 404, message = "Contact not found")
})
@GET
@Path("{name}")
@Produces(MediaType.APPLICATION_JSON)
public Contact getContact(@PathParam("name") String name) {
Contact contact = contactMap.get(name);
if (contact == null) {
throw new NotFoundException(name);
}
return contact;
}
@ApiOperation(value = "Delete contact")
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Success"),
@ApiResponse(code = 404, message = "Contact not found")
})
@DELETE
@Path("{name}")
public Response deleteContact(@PathParam("name") String name) {
Contact contact = contactMap.remove(name);
if (contact == null) {
throw new NotFoundException(name);
}
return Response.ok().build();
}
}
|
package jlibs.xml.sax;
import jlibs.core.lang.StringUtil;
import jlibs.xml.sax.helpers.MyNamespaceSupport;
import jlibs.xml.xsl.TransformerUtil;
import org.xml.sax.*;
import org.xml.sax.helpers.AttributesImpl;
import org.xml.sax.helpers.NamespaceSupport;
import javax.xml.namespace.QName;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Result;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.sax.TransformerHandler;
import javax.xml.transform.stream.StreamResult;
import java.io.IOException;
import java.io.StringReader;
import java.util.Enumeration;
import java.util.Stack;
/**
* This class is used to write xml documents
*
* @author Santhosh Kumar T
*/
public class XMLDocument{
private SAXDelegate xml;
public XMLDocument(SAXDelegate xml){
this.xml = xml;
}
public XMLDocument(Result result, boolean omitXMLDeclaration, int indentAmount, String encoding) throws TransformerConfigurationException{
TransformerHandler handler = TransformerUtil.newTransformerHandler(null, omitXMLDeclaration, indentAmount, encoding);
handler.setResult(result);
xml = new SAXDelegate(handler);
}
public XMLDocument startDocument() throws SAXException{
nsSupport.reset();
attrs.clear();
elemStack.clear();
elem = null;
nsSupport.pushContext();
xml.startDocument();
mark();
return this;
}
public XMLDocument endDocument() throws SAXException{
release(0);
xml.endDocument();
return this;
}
private MyNamespaceSupport nsSupport = new MyNamespaceSupport();
private boolean needsNewContext = true;
public void suggestPrefix(String prefix, String uri){
nsSupport.suggestPrefix(prefix, uri);
}
public String declarePrefix(String uri){
String prefix = nsSupport.findPrefix(uri);
if(prefix==null){
if(needsNewContext){
nsSupport.pushContext();
needsNewContext = false;
}
prefix = nsSupport.declarePrefix(uri);
}
return prefix;
}
public boolean declarePrefix(String prefix, String uri){
if(needsNewContext){
nsSupport.pushContext();
needsNewContext = false;
}
return nsSupport.declarePrefix(prefix, uri);
}
private QName declareQName(String uri, String localPart){
return new QName(uri, localPart, declarePrefix(uri));
}
public String toQName(String uri, String localPart){
String prefix = declarePrefix(uri);
return prefix.length()==0 ? localPart : prefix+':'+localPart;
}
private void startPrefixMapping(NamespaceSupport nsSupport) throws SAXException{
Enumeration enumer = nsSupport.getDeclaredPrefixes();
while(enumer.hasMoreElements()){
String prefix = (String) enumer.nextElement();
xml.startPrefixMapping(prefix, nsSupport.getURI(prefix));
}
}
private void endPrefixMapping(NamespaceSupport nsSupport) throws SAXException{
Enumeration enumer = nsSupport.getDeclaredPrefixes();
while(enumer.hasMoreElements())
xml.endPrefixMapping((String)enumer.nextElement());
}
private Stack<QName> elemStack = new Stack<QName>();
private QName elem;
private int marks = -1;
public int mark() throws SAXException{
finishStartElement();
elemStack.push(null);
return ++marks;
}
public int release() throws SAXException{
if(marks==-1 || elemStack.empty())
throw new SAXException("no mark found to be released");
endElements();
if(elemStack.peek()!=null)
throw new SAXException("expected </"+toString(elemStack.peek())+'>');
elemStack.pop();
return --marks;
}
public void release(int mark) throws SAXException{
while(marks>=mark)
release();
}
private String toString(QName qname){
return qname.getPrefix().length()==0 ? qname.getLocalPart() : qname.getPrefix()+':'+qname.getLocalPart();
}
private void finishStartElement() throws SAXException{
if(elem!=null){
startPrefixMapping(nsSupport);
if(needsNewContext)
nsSupport.pushContext();
else
needsNewContext = true;
elemStack.push(elem);
xml.startElement(elem.getNamespaceURI(), elem.getLocalPart(), toString(elem), attrs);
elem = null;
attrs.clear();
}
}
public XMLDocument startElement(String name) throws SAXException{
return startElement("", name);
}
public XMLDocument startElement(String uri, String name) throws SAXException{
finishStartElement();
elem = declareQName(uri, name);
return this;
}
public XMLDocument addElement(String name, String text, boolean cdata) throws SAXException{
return addElement("", name, text, cdata);
}
public XMLDocument addElement(String uri, String name, String text, boolean cdata) throws SAXException{
if(text!=null){
startElement(uri, name);
if(cdata)
addCDATA(text);
else
addText(text);
endElement();
}
return this;
}
public XMLDocument addElement(String name, String text) throws SAXException{
return addElement("", name, text, false);
}
public XMLDocument addElement(String uri, String name, String text) throws SAXException{
return addElement(uri, name, text, false);
}
public XMLDocument addCDATAElement(String name, String text) throws SAXException{
return addElement("", name, text, true);
}
public XMLDocument addCDATAElement(String uri, String name, String text) throws SAXException{
return addElement(uri, name, text, true);
}
private AttributesImpl attrs = new AttributesImpl();
public XMLDocument addAttribute(String name, String value) throws SAXException{
return addAttribute("", name, value);
}
public XMLDocument addAttribute(String uri, String name, String value) throws SAXException{
if(elem==null)
throw new SAXException("no start element found to associate this attribute");
if(value!=null)
attrs.addAttribute(uri, name, toQName(uri, name), "CDATA", value);
return this;
}
public XMLDocument addText(String text) throws SAXException{
if(!StringUtil.isEmpty(text)){
finishStartElement();
xml.characters(text.toCharArray(), 0, text.length());
}
return this;
}
public XMLDocument addCDATA(String text) throws SAXException{
if(!StringUtil.isEmpty(text)){
finishStartElement();
xml.startCDATA();
xml.characters(text.toCharArray(), 0, text.length());
xml.endCDATA();
}
return this;
}
private QName findEndElement() throws SAXException{
finishStartElement();
if(elemStack.empty() || elemStack.peek()==null)
throw new SAXException("can't find matching start element");
return elemStack.pop();
}
private XMLDocument endElement(QName qname) throws SAXException{
xml.endElement(qname.getNamespaceURI(), qname.getLocalPart(), toString(qname));
endPrefixMapping(nsSupport);
nsSupport.popContext();
needsNewContext = true;
return this;
}
public XMLDocument endElement(String uri, String name) throws SAXException{
QName qname = findEndElement();
if(!qname.getNamespaceURI().equals(uri) || !qname.getLocalPart().equals(name))
throw new SAXException("expected </"+toString(qname)+'>');
return endElement(qname);
}
public XMLDocument endElement(String name) throws SAXException{
return endElement("", name);
}
public XMLDocument endElement() throws SAXException{
return endElement(findEndElement());
}
public XMLDocument endElements(String uri, String name) throws SAXException{
QName qname = findEndElement();
while(true){
endElement(qname);
if(qname.getNamespaceURI().equals(uri) && qname.getLocalPart().equals(name))
break;
}
return this;
}
public XMLDocument endElements(String name) throws SAXException{
return endElements("", name);
}
public XMLDocument endElements() throws SAXException{
finishStartElement();
while(!elemStack.empty() && elemStack.peek()!=null)
endElement();
return this;
}
@SuppressWarnings({"ThrowableInstanceNeverThrown"})
public void warning(String msg, Exception ex) throws SAXException{
xml.warning(new SAXParseException(msg, null, ex));
}
@SuppressWarnings({"ThrowableInstanceNeverThrown"})
public void error(String msg, Exception ex) throws SAXException{
xml.error(new SAXParseException(msg, null, ex));
}
@SuppressWarnings({"ThrowableInstanceNeverThrown"})
public void fatalError(String msg, Exception ex) throws SAXException{
SAXParseException saxException = new SAXParseException(msg, null, ex);
xml.fatalError(saxException);
throw saxException;
}
public XMLDocument addXML(String xmlString, boolean excludeRoot) throws SAXException{
if(!StringUtil.isWhitespace(xmlString))
addXML(new InputSource(new StringReader(xmlString)), excludeRoot);
return this;
}
public XMLDocument addXML(InputSource is, boolean excludeRoot) throws SAXException{
finishStartElement();
try{
SAXDelegate delegate;
if(excludeRoot){
delegate = new SAXDelegate(xml){
private int depth = 0;
private NamespaceSupport nsSupport = new NamespaceSupport();
@Override public void startDocument(){}
@Override public void endDocument(){}
@Override public void setDocumentLocator(Locator locator){}
@Override
public void characters(char[] ch, int start, int length) throws SAXException{
if(depth!=1)
super.characters(ch, start, length);
}
@Override
public void ignorableWhitespace(char[] ch, int start, int length) throws SAXException{
if(depth!=1)
super.ignorableWhitespace(ch, start, length);
}
@Override
public void startPrefixMapping(String prefix, String uri) throws SAXException{
if(depth==0)
nsSupport.declarePrefix(prefix, uri);
else
super.startPrefixMapping(prefix, uri);
}
@Override
public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException{
depth++;
if(depth>1){
if(depth==2)
XMLDocument.this.startPrefixMapping(nsSupport);
super.startElement(uri, localName, qName, atts);
}
}
@Override
public void endElement(String uri, String localName, String qName) throws SAXException{
if(depth>1){
super.endElement(uri, localName, qName);
if(depth==2)
XMLDocument.this.endPrefixMapping(nsSupport);
}
depth
}
@Override
public void endPrefixMapping(String prefix) throws SAXException{
if(depth>0)
super.endPrefixMapping(prefix);
}
};
}else{
delegate = new SAXDelegate(xml){
@Override public void startDocument(){}
@Override public void endDocument(){}
@Override public void setDocumentLocator(Locator locator){}
};
}
XMLReader reader = SAXUtil.newSAXParser(true, false, false).getXMLReader();
SAXUtil.setHandler(reader, delegate);
reader.parse(is);
}catch(ParserConfigurationException ex){
throw new SAXException(ex);
}catch(IOException ex){
throw new SAXException(ex);
}
return this;
}
public XMLDocument addProcessingInstruction(String target, String data) throws SAXException{
xml.processingInstruction(target, data);
return this;
}
public XMLDocument addComment(String text) throws SAXException{
if(!StringUtil.isEmpty(text)){
finishStartElement();
xml.comment(text.toCharArray(), 0, text.length());
}
return this;
}
public XMLDocument add(SAXProducer saxProducer) throws SAXException{
return add(saxProducer, (QName)null);
}
public XMLDocument add(SAXProducer saxProducer, String name) throws SAXException{
return add(saxProducer, "", name);
}
public XMLDocument add(SAXProducer saxProducer, String uri, String name) throws SAXException{
return add(saxProducer, new QName(uri, name));
}
public XMLDocument add(SAXProducer saxProducer, QName qname) throws SAXException{
if(saxProducer!=null){
mark();
saxProducer.serializeTo(qname, this);
endElements();
release();
}
return this;
}
public XMLDocument addPublicDTD(String name, String publicId, String systemID) throws SAXException{
xml.startDTD(name, publicId, systemID);
xml.endDTD();
return this;
}
public XMLDocument addSystemDTD(String name, String systemId) throws SAXException{
xml.startDTD(name, null, systemId);
xml.endDTD();
return this;
}
public static void main(String[] args) throws Exception{
String google = "http://google.com";
String yahoo = "http://yahoo.com";
XMLDocument xml = new XMLDocument(new StreamResult(System.out), false, 4, null);
xml.startDocument();{
xml.addProcessingInstruction("san", "test='1.2'");
xml.declarePrefix("google", google);
xml.declarePrefix("yahoo", yahoo);
xml.declarePrefix("http://msn.com");
xml.startElement(google, "hello");{
xml.addAttribute("name", "value");
xml.addElement("xyz", "helloworld");
xml.addElement(google, "hai", "test");
xml.addXML(new InputSource("xml/xsds/note.xsd"), true);
xml.addComment("this is comment");
xml.addCDATA("this is sample cdata");
}
}
xml.endDocument();
}
}
|
package com.asana.resources.gen;
import com.asana.Client;
import com.asana.resources.Resource;
import com.asana.models.Project;
import com.asana.requests.ItemRequest;
import com.asana.requests.CollectionRequest;
public class ProjectsBase extends Resource
{
/**
* @param client Parent client instance
*/
public ProjectsBase(Client client)
{
super(client);
}
/**
* Creates a new project in a workspace or team.
*
* Every project is required to be created in a specific workspace or
* organization, and this cannot be changed once set. Note that you can use
* the `workspace` parameter regardless of whether or not it is an
* organization.
*
* If the workspace for your project _is_ an organization, you must also
* supply a `team` to share the project with.
*
* Returns the full record of the newly created project.
*
* @return Request object
*/
public ItemRequest<Project> create()
{
return new ItemRequest<Project>(this, Project.class, "/projects", "POST");
}
/**
* If the workspace for your project _is_ an organization, you must also
* supply a `team` to share the project with.
*
* Returns the full record of the newly created project.
*
* @param workspace The workspace or organization to create the project in.
* @return Request object
*/
public ItemRequest<Project> createInWorkspace(String workspace)
{
String path = String.format("/workspaces/%s/projects", workspace);
return new ItemRequest<Project>(this, Project.class, path, "POST");
}
/**
* Creates a project shared with the given team.
*
* Returns the full record of the newly created project.
*
* @param team The team to create the project in.
* @return Request object
*/
public ItemRequest<Project> createInTeam(String team)
{
String path = String.format("/teams/%s/projects", team);
return new ItemRequest<Project>(this, Project.class, path, "POST");
}
/**
* Returns the complete project record for a single project.
*
* @param project The project to get.
* @return Request object
*/
public ItemRequest<Project> findById(String project)
{
String path = String.format("/projects/%s", project);
return new ItemRequest<Project>(this, Project.class, path, "GET");
}
/**
* A specific, existing project can be updated by making a PUT request on the
* URL for that project. Only the fields provided in the `data` block will be
* updated; any unspecified fields will remain unchanged.
*
* When using this method, it is best to specify only those fields you wish
* to change, or else you may overwrite changes made by another user since
* you last retrieved the task.
*
* Returns the complete updated project record.
*
* @param project The project to update.
* @return Request object
*/
public ItemRequest<Project> update(String project)
{
String path = String.format("/projects/%s", project);
return new ItemRequest<Project>(this, Project.class, path, "PUT");
}
/**
* A specific, existing project can be deleted by making a DELETE request
* on the URL for that project.
*
* Returns an empty data record.
*
* @param project The project to delete.
* @return Request object
*/
public ItemRequest<Project> delete(String project)
{
String path = String.format("/projects/%s", project);
return new ItemRequest<Project>(this, Project.class, path, "DELETE");
}
/**
* Returns the compact project records for some filtered set of projects.
* Use one or more of the parameters provided to filter the projects returned.
*
* @return Request object
*/
public CollectionRequest<Project> findAll()
{
return new CollectionRequest<Project>(this, Project.class, "/projects", "GET");
}
/**
* Returns the compact project records for all projects in the workspace.
*
* @param workspace The workspace or organization to find projects in.
* @return Request object
*/
public CollectionRequest<Project> findByWorkspace(String workspace)
{
String path = String.format("/workspaces/%s/projects", workspace);
return new CollectionRequest<Project>(this, Project.class, path, "GET");
}
/**
* Returns the compact project records for all projects in the team.
*
* @param team The team to find projects in.
* @return Request object
*/
public CollectionRequest<Project> findByTeam(String team)
{
String path = String.format("/teams/%s/projects", team);
return new CollectionRequest<Project>(this, Project.class, path, "GET");
}
/**
* Returns compact records for all sections in the specified project.
*
* @param project The project to get sections from.
* @return Request object
*/
public CollectionRequest<Project> sections(String project)
{
String path = String.format("/projects/%s/sections", project);
return new CollectionRequest<Project>(this, Project.class, path, "GET");
}
/**
* Returns the compact task records for all tasks within the given project,
* ordered by their priority within the project. Tasks can exist in more than one project at a time.
*
* @param project The project in which to search for tasks.
* @return Request object
*/
public CollectionRequest<Project> tasks(String project)
{
String path = String.format("/projects/%s/tasks", project);
return new CollectionRequest<Project>(this, Project.class, path, "GET");
}
}
|
package com.binatechnologies.varsim;
import org.apache.log4j.Logger;
import org.kohsuke.args4j.CmdLineException;
import org.kohsuke.args4j.CmdLineParser;
import org.kohsuke.args4j.Option;
import java.util.HashMap;
import java.util.Map;
/**
* @author johnmu
*/
class Stats_record {
public static final int SV_LIM = 50; // >= this val is an SV
int[] bin_counts; // the last bin is for anything larger
int total_count;
int sv_total_count;
int[] bin_breaks = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 19, 29, 39, 49, 99,
199, 399, 799, 1599, 3199, 6399, 12799, 25599, 51199, 102399, 500000, 1000000};
int num_bins;
Stats_record() {
num_bins = bin_breaks.length + 1;
bin_counts = new int[num_bins];
total_count = 0;
sv_total_count = 0;
}
/**
* Increments the bin that val belongs in
*
* @param val value to be added
*/
public void add(int val) {
total_count++;
if (val >= SV_LIM) sv_total_count++;
for (int i = 0; i < bin_breaks.length; i++) {
if (val <= bin_breaks[i]) {
bin_counts[i]++;
return;
}
}
bin_counts[num_bins - 1]++;
}
public int getTotal_count() {
return total_count;
}
public int getsvTotal_count() {
return sv_total_count;
}
public String toString() {
return toString(bin_breaks[bin_breaks.length - 1] + 1);
}
public String toString(int max_len) {
StringBuilder sb = new StringBuilder();
sb.append("Total: " + getTotal_count() + "\n");
sb.append("Total (>=" + SV_LIM + "): " + getsvTotal_count() + "\n");
sb.append("[");
sb.append(1);
sb.append(",");
sb.append(bin_breaks[0]);
sb.append("]");
sb.append(':');
sb.append(bin_counts[0]);
sb.append('\n');
for (int i = 1; i < bin_breaks.length; i++) {
if (bin_breaks[i] > max_len) {
break;
}
sb.append("[");
sb.append(bin_breaks[i - 1] + 1);
sb.append(",");
sb.append(bin_breaks[i]);
sb.append("]");
sb.append(':');
sb.append(bin_counts[i]);
sb.append('\n');
}
if (bin_breaks[bin_breaks.length - 1] < max_len) {
sb.append("[");
sb.append(bin_breaks[bin_breaks.length - 1] + 1);
sb.append(",");
sb.append("inf");
sb.append("]");
sb.append(':');
sb.append(bin_counts[num_bins - 1]);
sb.append('\n');
}
return sb.toString();
}
}
class Type_record<T extends Enum> {
HashMap<T, Stats_record> data;
Type_record() {
data = new HashMap<T, Stats_record>();
}
/**
* Increments the bin (of type) that val belongs in
*
* @param type type of bin
* @param val value to be incremented
*/
public void add(T type, int val) {
if (data.containsKey(type)) {
Stats_record rec = data.get(type);
rec.add(val);
} else {
Stats_record rec = new Stats_record();
rec.add(val);
data.put(type, rec);
}
}
public int getTotal_nonref() {
int total = 0;
for (Map.Entry<T, Stats_record> entry : data.entrySet()) {
total += entry.getValue().getTotal_count();
}
return total;
}
public String toString() {
StringBuilder sb = new StringBuilder();
for (Map.Entry<T, Stats_record> entry : data.entrySet()) {
sb.append(entry.getKey().name() + "\n");
sb.append("Total: " + entry.getValue().getTotal_count() + "\n");
sb.append("Total (>="+ Stats_record.SV_LIM +"): " + entry.getValue().getsvTotal_count() + "\n");
sb.append('\n');
if (entry.getKey() == Variant.Type.SNP) {
sb.append(entry.getValue().toString(1));
} else {
sb.append(entry.getValue());
}
}
return sb.toString();
}
}
/**
* Stores the data for each haplotype separately
*/
class Parent_record {
// 0 = paternal, 1 = maternal
public final static int PATERNAL = 0;
public final static int MATERNAL = 1;
Type_record<Variant.Type>[] data;
Type_record<Variant.OverallType> overall_data;
int total_count;
Parent_record() {
data = new Type_record[2];
data[PATERNAL] = new Type_record();
data[MATERNAL] = new Type_record();
overall_data = new Type_record<Variant.OverallType>();
total_count = 0;
}
public void add(Variant var, BedFile bed_file) {
int paternal_allele = var.paternal();
int maternal_allele = var.maternal();
boolean added = false;
if (bed_file == null
|| bed_file.contains(var.getChr_name(), var.get_interval(paternal_allele))) {
data[PATERNAL].add(var.getType(paternal_allele), var.max_len(paternal_allele));
added = true;
}
if (bed_file == null
|| bed_file.contains(var.getChr_name(), var.get_interval(maternal_allele))) {
data[MATERNAL].add(var.getType(maternal_allele), var.max_len(maternal_allele));
added = true;
}
if (bed_file == null
|| bed_file.contains(var.getChr_name(), var.get_geno_interval())) {
overall_data.add(var.getType(), var.max_len());
added = true;
}
if (added) {
total_count++;
}
}
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("Total count: ");
sb.append(total_count);
sb.append("\n");
sb.append("Paternal\n");
sb.append("Total: ");
sb.append(data[PATERNAL].getTotal_nonref());
sb.append("\n");
sb.append(data[PATERNAL]);
sb.append("\n");
sb.append("Maternal\n");
sb.append("Total: ");
sb.append(data[MATERNAL].getTotal_nonref());
sb.append("\n");
sb.append(data[MATERNAL]);
sb.append("\n");
sb.append("Overall\n");
sb.append("Total: ");
sb.append(overall_data.getTotal_nonref());
sb.append("\n");
sb.append(overall_data);
sb.append("\n");
return sb.toString();
}
}
public class VCFstats {
String VERSION = "VarSim " + getClass().getPackage().getImplementationVersion();
private final static Logger log = Logger.getLogger(VCFstats.class.getName());
BedFile bed_file;
@Option(name = "-bed", usage = "BED file to restrict the analysis [Optional]", metaVar = "BED_file")
String bed_filename = null;
@Option(name = "-vcf", usage = "VCF file to analyse [Required]", metaVar = "VCF_file", required = true)
String vcf_filename;
/**
* @param args command line parameters
*/
public static void main(String[] args) {
VCFstats runner = new VCFstats();
runner.run(args);
}
private void run(String[] args) {
String usage = "Compute the distribution of variants in a VCF file\n"
+ "Assume that there is only one sample in the VCF file\n";
CmdLineParser cmd_parser = new CmdLineParser(this);
// if you have a wider console, you could increase the value;
// here 80 is also the default
cmd_parser.setUsageWidth(80);
try {
cmd_parser.parseArgument(args);
} catch (CmdLineException e) {
System.err.println(VERSION);
System.err.println(e.getMessage());
System.err.println("java -jar vcfstats.jar [options...]");
// print the list of available options
cmd_parser.printUsage(System.err);
System.err.println(usage);
return;
}
bed_file = null;
if (bed_filename != null) {
log.info("Reading BED file...");
bed_file = new BedFile(bed_filename);
}
Parent_record data = new Parent_record();
VCFparser parser = new VCFparser(vcf_filename, null, false);
while (parser.hasMoreInput()) {
Variant var = parser.parseLine();
if (var == null) {
continue;
}
if (var.maternal() == 0 && var.paternal() == 0) {
continue;
}
data.add(var, bed_file);
}
System.out.println(data);
}
}
|
package com.bwfcwalshy.flarebot;
import com.google.gson.JsonIOException;
import com.google.gson.JsonSyntaxException;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import sx.blah.discord.api.internal.json.objects.EmbedObject;
import sx.blah.discord.handle.obj.IChannel;
import sx.blah.discord.handle.obj.IMessage;
import sx.blah.discord.handle.obj.IUser;
import sx.blah.discord.util.*;
import java.awt.*;
import java.io.*;
import java.nio.charset.Charset;
import java.lang.Throwable;
public class MessageUtils {
private static String[] defaults = {
"6debd47ed13483642cf09e832ed0bc1b",
"322c936a8c8be1b803cd94861bdfa868",
"dd4dbc0016779df1378e7812eabaa04d",
"0e291f67c9274a1abdddeb3fd919cbaa",
"1cbd08c76f8af6dddce02c5138971129"
};
public static final String DEBUG_CHANNEL = "226786557862871040";
public static IMessage sendMessage(CharSequence message, IChannel channel) {
RequestBuffer.RequestFuture<IMessage> future = RequestBuffer.request(() -> {
try {
return channel.sendMessage(message.toString().substring(0, Math.min(message.length(), 1999)));
} catch (DiscordException | MissingPermissionsException e) {
FlareBot.LOGGER.error("Something went wrong!", e);
}
return null;
});
return future.get();
}
public static void sendPM(IUser user, CharSequence message) {
RequestBuffer.request(() -> {
try {
return user.getOrCreatePMChannel().sendMessage(message.toString().substring(0, Math.min(message.length(), 1999)));
} catch (MissingPermissionsException | DiscordException e) {
FlareBot.LOGGER.error("Uh oh!", e);
}
return null;
}).get();
}
public static void sendPM(IUser user, EmbedObject message) {
RequestBuffer.request(() -> {
try {
return new MessageBuilder(FlareBot.getInstance().getClient()).withEmbed(message)
.withChannel(user.getOrCreatePMChannel()).withContent("\u200B").send();
} catch (MissingPermissionsException | DiscordException e) {
FlareBot.LOGGER.error("Uh oh!", e);
}
return null;
}).get();
}
public static IMessage sendException(String s, Throwable e, IChannel channel) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
e.printStackTrace(pw);
String trace = sw.toString();
pw.close();
return sendErrorMessage(getEmbed().withDesc(s + "\n**Stack trace**: " + hastebin(trace)), channel);
}
public static String hastebin(String trace) {
try {
HttpPost req = new HttpPost("https://hastebin.com/documents");
req.addHeader("Content-Type", "text/plain");
req.addHeader("User-Agent", "Mozilla/5.0 FlareBot");
StringEntity ent = new StringEntity(trace);
req.setEntity(ent);
HttpResponse response = FlareBot.HTPP_CLIENT.execute(req);
if (response.getStatusLine().getStatusCode() != 200) {
FlareBot.LOGGER.error("HasteBin API did not respond with a correct code! Code was: {}! Response: {}", response.getStatusLine().getStatusCode(),
IOUtils.toString(response.getEntity().getContent(), Charset.defaultCharset()));
return null;
}
return "https://hastebin.com/" + FlareBot.GSON.fromJson(new InputStreamReader(response.getEntity().getContent()), HastebinResponse.class).key;
} catch (JsonSyntaxException | JsonIOException | IOException e) {
FlareBot.LOGGER.error("Could not make POST request to hastebin!", e);
return null;
}
}
public static void editMessage(IMessage message, String content) {
RequestBuffer.request(() -> {
try {
return message.edit(content);
} catch (MissingPermissionsException | DiscordException e1) {
FlareBot.LOGGER.error("Could not edit own message!", e1);
}
return message;
}).get();
}
public static IMessage sendFile(IChannel channel, String s, String fileContent, String filename) {
ByteArrayInputStream stream = new ByteArrayInputStream(fileContent.getBytes());
return RequestBuffer.request(() -> {
try {
return channel.sendFile(s, false, stream, filename);
} catch (MissingPermissionsException e1) {
FlareBot.LOGGER.error("Could not send stack trace!", e1);
return null;
} catch (DiscordException e1) {
return sendFile(channel, s, fileContent, filename);
}
}).get();
}
public static EmbedBuilder getEmbed() {
return new EmbedBuilder()
.withAuthorIcon(getAvatar(FlareBot.getInstance().getClient().getOurUser()))
.withAuthorUrl("https://github.com/FlareBot/FlareBot")
.withAuthorName(getTag(FlareBot.getInstance().getClient().getOurUser()));
}
public static String getTag(IUser user) {
return user.getName() + '#' + user.getDiscriminator();
}
public static EmbedBuilder getEmbed(IUser user) {
return getEmbed().withFooterIcon(getAvatar(user))
.withFooterText("Requested by @" + getTag(user));
}
public static String getAvatar(IUser user) {
return user.getAvatar() != null ? user.getAvatarURL() : getDefaultAvatar(user);
}
public static String getDefaultAvatar(IUser user) {
int discrim = Integer.parseInt(user.getDiscriminator());
discrim %= defaults.length;
return "https://discordapp.com/assets/" + defaults[discrim] + ".png";
}
public static IMessage sendMessage(EmbedObject embedObject, IChannel channel) {
RequestBuffer.RequestFuture<IMessage> future = RequestBuffer.request(() -> {
try {
return new MessageBuilder(FlareBot.getInstance().getClient()).withEmbed(embedObject)
.withChannel(channel).withContent("\u200B").send();
} catch (Throwable e) {
FlareBot.LOGGER.error("Something went wrong!", e);
}
return null;
});
return future.get();
}
public static IMessage sendErrorMessage(EmbedBuilder builder, IChannel channel) {
RequestBuffer.RequestFuture<IMessage> future = RequestBuffer.request(() -> {
try {
return new MessageBuilder(FlareBot.getInstance().getClient()).withEmbed(builder.withColor(Color.red).build()).withChannel(channel).withContent("\u200B").send();
} catch (Throwable e) {
FlareBot.LOGGER.error("Something went wrong!", e);
}
return null;
});
return future.get();
}
public static IMessage sendErrorMessage(String message, IChannel channel) {
RequestBuffer.RequestFuture<IMessage> future = RequestBuffer.request(() -> {
try {
return new MessageBuilder(FlareBot.getInstance().getClient()).withEmbed(MessageUtils.getEmbed()
.withColor(Color.red).withDesc(message).build()).withChannel(channel).withContent("\u200B").send();
} catch (Throwable e) {
FlareBot.LOGGER.error("Something went wrong!", e);
}
return null;
});
return future.get();
}
public static void editMessage(EmbedObject embed, IMessage message) {
editMessage(message.getContent(), embed, message);
}
public static void editMessage(String s, EmbedObject embed, IMessage message) {
RequestBuffer.request(() -> {
try {
if(message != null)
message.edit(s, embed);
} catch (MissingPermissionsException | DiscordException e) {
FlareBot.LOGGER.error("Could not edit own message + embed!", e);
}
});
}
private static class HastebinResponse {
public String key;
}
}
|
package org.jetel.util;
import java.nio.CharBuffer;
import sun.text.Normalizer;
/**
* Helper class with some useful methods regarding string/text manipulation
*
* @author dpavlis
* @since July 25, 2002
* @revision $Revision$
*/
public class StringUtils {
// quoting characters
public final static char QUOTE_CHAR='\'';
public final static char DOUBLE_QUOTE_CHAR='"';
/**
* Converts control characters into textual representation<br>
* Note: This code handles only \n, \r ,\t ,\f, \b special chars
*
* @param controlString string containing control characters
* @return string where control characters are replaced by their
* text representation (i.e.\n -> "\n" )
* @since July 25, 2002
*/
public static String specCharToString(String controlString) {
StringBuffer copy = new StringBuffer();
char character;
for (int i = 0; i < controlString.length(); i++) {
character = controlString.charAt(i);
switch (character) {
case '\n':
copy.append("\\n");
break;
case '\t':
copy.append("\\t");
break;
case '\r':
copy.append("\\r");
break;
case '\b':
copy.append("\\b");
break;
case '\f':
copy.append("\\f");
break;
default:
copy.append(character);
}
}
return copy.toString();
}
/**
* Converts textual representation of control characters into control
* characters<br>
* Note: This code handles only \n, \r , \t , \f, \" ,\', \\ special chars
*
* @param controlString Description of the Parameter
* @return String with control characters
* @since July 25, 2002
*/
public static String stringToSpecChar(String controlString) {
if(controlString == null) {
return null;
}
StringBuffer copy = new StringBuffer();
char character;
boolean isBackslash = false;
for (int i = 0; i < controlString.length(); i++) {
character = controlString.charAt(i);
if (isBackslash) {
switch (character) {
case '\\':
copy.append('\\');
break;
case 'n':
copy.append('\n');
break;
case 't':
copy.append('\t');
break;
case 'r':
copy.append('\r');
break;
case '"':
copy.append('"');
break;
case '\'':
copy.append('\'');
break;
case 'f':
copy.append('\f');
break;
case 'b':
copy.append('\b');
break;
default:
copy.append('\\');
copy.append(character);
break;
}
isBackslash = false;
} else {
if (character == '\\') {
isBackslash = true;
} else {
copy.append(character);
}
}
}
return copy.toString();
}
/**
* Formats string from specified messages and their lengths.<br>
* Negative (<0) length means justify to the left, positive (>0) to the right<br>
* If message is longer than specified size, it is trimmed; if shorter, it is padded with blanks.
*
* @param messages array of objects with toString() implemented methods
* @param sizes array of desired lengths (+-) for every message specified
* @return Formatted string
*/
public static String formatString(Object[] messages, int[] sizes) {
int formatSize;
String message;
StringBuffer strBuff = new StringBuffer(100);
for (int i = 0; i < messages.length; i++) {
message = messages[i].toString();
// left or right justified ?
if (sizes[i] < 0) {
formatSize = sizes[i] * (-1);
fillString(strBuff, message, 0, formatSize);
} else {
formatSize = sizes[i];
if (message.length() < formatSize) {
fillBlank(strBuff, formatSize - message.length());
fillString(strBuff, message, 0, message.length());
} else {
fillString(strBuff, message, 0, formatSize);
}
}
}
return strBuff.toString();
}
/**
* Description of the Method
*
* @param strBuf Description of the Parameter
* @param source Description of the Parameter
* @param start Description of the Parameter
* @param length Description of the Parameter
*/
private static void fillString(StringBuffer strBuff, String source, int start, int length) {
int srcLength = source.length();
for (int i = start; i < start + length; i++) {
if (i < srcLength) {
strBuff.append(source.charAt(i));
} else {
strBuff.append(' ');
}
}
}
/**
* Description of the Method
*
* @param strBuf Description of the Parameter
* @param length Description of the Parameter
*/
private static void fillBlank(StringBuffer strBuff, int length) {
for (int i = 0; i < length; i++) {
strBuff.append(' ');
}
}
/**
* Returns True, if the character sequence contains only valid identifier chars.<br>
* [A-Za-z0-9_]
* @param seq Description of the Parameter
* @return The validObjectName value
*/
public static boolean isValidObjectName(CharSequence seq) {
if(seq == null) return false;
for (int i = 0; i < seq.length(); i++) {
if (!Character.isUnicodeIdentifierPart(seq.charAt(i))) {
return false;
}
}
return true;
}
/**
* Returns true if the passed-in character is quote ['] or double
* quote ["].
*
* @param character
* @return true if character equals to ['] or ["]
*/
public static final boolean isQuoteChar(char character){
return character==QUOTE_CHAR || character==DOUBLE_QUOTE_CHAR;
}
/**
* Returns true of passed-in string is quoted - i.e.
* the first character is quote character and the
* last character is equal to the first one.
*
* @param str
* @return true if the string is quoted
*/
public static final boolean isQuoted(CharSequence str){
return isQuoteChar(str.charAt(0)) && str.charAt(0)==str.charAt(str.length()-1);
}
/**
* Modifies buffer scope so that the string quotes are ignored,
* in case quotes are not present doesn't do anything.
* @param buf
* @return
*/
public static CharBuffer unquote(CharBuffer buf) {
if (StringUtils.isQuoted(buf)) {
buf.position(buf.position() + 1);
buf.limit(buf.limit() - 1);
}
return buf;
}
/**
* Modifies string so that the string quotes are ignored,
* in case quotes are not present doesn't do anything.
* @param str
* @return
*/
public static String unquote(String str) {
if (StringUtils.isQuoted(str)) {
str = str.substring(1,str.length()-1);
}
return str;
}
/**
* Modifies buffer scope so that the leading whitespace is ignored.
* @param buf
* @return
*/
public static CharBuffer trimLeading(CharBuffer buf) {
int pos = buf.position();
int lim = buf.limit();
while (pos < lim && Character.isWhitespace(buf.get(pos))) {
pos++;
}
buf.position(pos);
return buf;
}
/**
* Modifies buffer scope so that the trailing whitespace is ignored.
* @param buf
* @return
*/
public static CharBuffer trimTrailing(CharBuffer buf) {
int pos = buf.position();
int lim = buf.limit();
while (pos < lim && Character.isWhitespace(buf.get(lim - 1))) {
lim
}
buf.limit(lim);
return buf;
}
/**
* Modifies buffer scope so that the leading and trailing whitespace is ignored.
* @param buf
* @return
*/
public static CharBuffer trim(CharBuffer buf) {
trimLeading(buf);
trimTrailing(buf);
return buf;
}
/**
* This method removes from the string characters which are not letters nor digits
*
* @param str - input String
* @param takeAlpha - if true method leaves letters
* @param takeNumeric - if true method leaves digits
* @return String where are only letters and (or) digits from input String
*/
public static String getOnlyAlphaNumericChars(String str,boolean takeAlpha,boolean takeNumeric){
if (!takeAlpha && !takeNumeric){
return str;
}
int counter=0;
int length=str.length();
char[] chars=str.toCharArray();
char[] result=new char[length];
char character;
for (int j=0;j<length;j++){
character=chars[j];
if ( (Character.isLetter(character) && takeAlpha) ||
(Character.isDigit(character) && takeNumeric) ){
result[counter++]=chars[j];
}
}
return new String(result,0,counter);
}
/**
* This method removed from string blank space
*
* @param str - input String
* @return input string without blank space
*/
public static String removeBlankSpace(String str){
int length=str.length();
int counter = 0;
char[] chars=str.toCharArray();
char[] result = new char[length];
for (int j=0;j<length;j++){
if (!Character.isWhitespace(chars[j])) {
result[counter++] = chars[j];
}
}
return new String(result,0,counter);
}
/**
* Test whether parameter consists of space characters
* only
* @param data
* @return true if parameter contains space characters only
*/
public static boolean isBlank(CharBuffer data){
data.mark();
for(int i=0;i<data.length();i++){
if (!Character.isSpaceChar(data.get())){
data.reset();
return false;
}
}
data.reset();
return true;
}
/**
* Test whether parameter consists of space characters
* only
* @param data
* @return true if parameter contains space characters only
*/
public static boolean isBlank(CharSequence data){
for(int i=0;i<data.length();i++){
if (!Character.isSpaceChar(data.charAt(i))){
return false;
}
}
return true;
}
/**
* This method replaces diacritic chars by theirs equivalence without diacritic.
* It works only for chars for which decomposition is defined
*
* @param str
* @return string in which diacritic chars are replaced by theirs equivalences without diacritic
*/
public static String removeDiacritic(String str){
return Normalizer.decompose(str, false, 0).replaceAll("\\p{InCombiningDiacriticalMarks}+", "");
}
/**
* This method concates string array to one string. Parts are delimited by given char
*
* @param strings - input array of strings
* @param delimiter
* @return
*/
public static String stringArraytoString(String[] strings,char delimiter){
int length = strings.length;
if (length==0) {
return null;
}
StringBuffer result = new StringBuffer();
for (int i=0;i<length;i++){
result.append(strings[i]);
if (i<length-1) {
result.append(delimiter);
}
}
return result.toString();
}
public static String stringArraytoString(String[] strings){
return stringArraytoString(strings,' ');
}
public static boolean isEmpty(String s) {
return s == null || s.length() == 0;
}
/**
* This method appends passed-in CharSequence to the end of
* passed-in StringBuffer;<br>
* It returns reference to buffer object to allow cascading
* of these operations.
* @param buff buffer to which append sequence of characters
* @param seq characters sequence to append
* @return reference to passed-in buffer
*/
public static final StringBuffer strBuffAppend(StringBuffer buff,CharSequence seq){
int seqLen=seq.length();
buff.ensureCapacity(buff.length()+seqLen);
buff.append(seq);
return buff;
}
/**
* This method appends passed-in CharSequence to the end of
* passed-in StringBuffer;<br>
* It returns reference to buffer object to allow cascading
* of these operations.
* @param buff buffer to which append sequence of characters
* @param seq characters sequence to append
* @return reference to passed-in buffer
*/
public static final StringBuilder strBuffAppend(StringBuilder buff,CharSequence seq){
int seqLen=seq.length();
buff.ensureCapacity(buff.length()+seqLen);
buff.append(seq);
return buff;
}
/**
* This method finds index of string from string array
*
* @param str String to find
* @param array String array for searching
* @return index or found String or -1 if String was not found
*/
public static int findString(String str,String[] array){
for (int i=0;i<array.length;i++){
if (str.equals(array[i])) return i;
}
return -1;
}
}
/*
* End class StringUtils
*/
|
package com.clementscode.mmi.swing;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.KeyEvent;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import javax.swing.Action;
import javax.swing.JComponent;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.KeyStroke;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.AnnotationIntrospector;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.xc.JaxbAnnotationIntrospector;
import com.clementscode.mmi.MainGui;
import com.clementscode.mmi.res.CategoryItem;
import com.clementscode.mmi.res.Session;
import com.clementscode.mmi.res.SessionConfig;
public class CrudFrame extends JFrame {
private static final long serialVersionUID = -5629208181141679241L;
public static final String DELETE_CATEGORY_ITEM = "DELETE_CATEGORY_ITEM";
public static final String ADD_CATEGORY_ITEM = "ADD_CATEGORY_ITEM";
private JPanel topPanel;
private JTextField tfName;
private JTextArea tfDescription;
private JTextField tfShuffleCount;
private JTextField tfDelayForPrompt;
private JTextField tfDelayForAnswer;
private JPanel mainPanel;
private JPanel diyTable;
private JScrollPane scrollPane;
private GuiForCategoryItem firstCategoryItem;
private List<GuiForCategoryItem> lstGuiForCategoryItems;
protected ObjectMapper mapper;
public static void main(String[] args) {
try {
new CrudFrame();
} catch (Exception bland) {
bland.printStackTrace();
}
}
public CrudFrame() {
super("Cread Read Update Delete utility....");
mapper = new ObjectMapper();
AnnotationIntrospector introspector = new JaxbAnnotationIntrospector();
mapper.getDeserializationConfig().withAnnotationIntrospector(
introspector);
mapper.getSerializationConfig()
.withAnnotationIntrospector(introspector);
lstGuiForCategoryItems = new ArrayList<GuiForCategoryItem>();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainPanel = new JPanel();
mainPanel.setLayout(new BorderLayout());
topPanel = new JPanel();
getContentPane().add(mainPanel);
mainPanel.add(topPanel, BorderLayout.NORTH);
topPanel.setLayout(new BorderLayout());
tfName = new JTextField(60);
topPanel.add(new LabelAndField("Name: ", tfName), BorderLayout.NORTH);
tfDescription = new JTextArea(5, 60);
topPanel.add(new LabelAndField("Description:", tfDescription),
BorderLayout.CENTER);
tfShuffleCount = new JTextField("1");
JPanel gridPanel = new JPanel();
gridPanel.setLayout(new GridLayout(0, 1));
gridPanel.add(new LabelAndField("Shuffle Count: ", tfShuffleCount));
tfDelayForPrompt = new JTextField(5);
tfDelayForAnswer = new JTextField(5);
gridPanel
.add(new LabelAndField("Delay for prompt: ", tfDelayForPrompt));
gridPanel.add(new LabelAndField("Delay for Answer:", tfDelayForAnswer));
topPanel.add(gridPanel, BorderLayout.SOUTH);
scrollPane = createDiyTableScrollPane();
Dimension ps = scrollPane.getPreferredSize();
ps.setSize(ps.getWidth(), ps.getHeight() * 2);
scrollPane.setPreferredSize(ps);
mainPanel.add(scrollPane, BorderLayout.SOUTH);
setupMenus();
pack();
setVisible(true);
}
private void setupMenus() {
// TODO: Different portable strings
// TODO: fill in the mediator stuff!
MediatorListener mediator = new MediatorForCrud(this);
Action openAction = new ActionRecorder(
Messages.getString("Gui.Open"), null, //$NON-NLS-1$
Messages.getString("Gui.OpenDescription"), //$NON-NLS-1$
new Integer(KeyEvent.VK_L), KeyStroke
.getKeyStroke("control F2"),
Mediator.OPEN, mediator);
Action saveAction = new ActionRecorder("Save", null,
"Save the session.", new Integer(KeyEvent.VK_L), KeyStroke
.getKeyStroke("control F2"), Mediator.SAVE, mediator);
Action saveAsAction = new ActionRecorder("Save As...", null,
"Choose the file to Save the session.", new Integer(
KeyEvent.VK_L), KeyStroke.getKeyStroke("control F2"),
Mediator.SAVE_AS, mediator);
Action quitAction = new ActionRecorder(
Messages.getString("Gui.Quit"), null, //$NON-NLS-1$
Messages.getString("Gui.QuitDescriptino"), new Integer(
KeyEvent.VK_L),
KeyStroke.getKeyStroke("control F2"),
//$NON-NLS-1$
Mediator.QUIT, mediator);
// Create the menu bar.
JMenuBar menuBar = new JMenuBar();
// Build the first menu.
JMenu menu = new JMenu(Messages.getString("Gui.File")); //$NON-NLS-1$
menu.setMnemonic(KeyEvent.VK_A);
menuBar.add(menu);
// a group of JMenuItems
JMenuItem menuItem = new JMenuItem(openAction);
menu.add(menuItem);
menuItem = new JMenuItem(saveAction);
menu.add(menuItem);
menuItem = new JMenuItem(saveAsAction);
menu.add(menuItem);
menuItem = new JMenuItem(quitAction);
menuItem.setMnemonic(KeyEvent.VK_B);
menu.add(menuItem);
menuBar.add(menu);
this.setJMenuBar(menuBar);
}
private JScrollPane createDiyTableScrollPane() {
diyTable = new JPanel();
diyTable.setLayout(new GridLayout(0, 1)); // one column
for (int i = 0; i < 1; ++i) {
// JButton b = new JButton("Test " + i);
// b.addActionListener(this);
// diyTable.add(b);
firstCategoryItem = new GuiForCategoryItem(this);
diyTable.add(firstCategoryItem);
lstGuiForCategoryItems.add(firstCategoryItem);
}
// scrollPane = new JScrollPane(diyTable,
// JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
// JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
JScrollPane sp = new JScrollPane(diyTable,
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
return sp;
}
public void openSessionFile() {
File file;
// TODO: Remove hard coded directory.
// TODO: Get application to remember the last place we opened this...
JFileChooser chooser = new JFileChooser(new File(
"/Users/mgpayne/MMI/src/test/resources"));
int returnVal = chooser.showOpenDialog(this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
file = chooser.getSelectedFile();
try {
readSessionFile(file);
} catch (Exception e) {
JOptionPane.showMessageDialog(this, String.format(
"Problem reading %s exception was %s", file, e));
e.printStackTrace();
}
}
}
private void readSessionFile(File file) throws Exception {
Properties props = new Properties();
// Do it this way and no relative path huha is needed.
InputStream in = this.getClass().getClassLoader().getResourceAsStream(
MainGui.propFile);
props.load(new InputStreamReader(in));
String[] sndExts = props.getProperty(MainGui.sndKey).split(",");
SessionConfig config = mapper.readValue(new FileInputStream(file),
SessionConfig.class);
Session session = new Session(config, sndExts);
String sessionPath = file.getParent();
populateGui(session, sessionPath);
}
protected void writeSessionConfig(SessionConfig config, File file)
throws JsonGenerationException, JsonMappingException, IOException {
writeSessionConfig(config, new FileOutputStream(file));
}
protected void writeSessionConfig(SessionConfig config, OutputStream out)
throws JsonGenerationException, JsonMappingException, IOException {
mapper.writeValue(out, config);
}
private void populateGui(Session session, String sessionPath) {
tfName.setText(session.getName());
tfDescription.setText(session.getDescription());
tfDelayForAnswer.setText("" + session.getTimeDelayAnswer());
tfDelayForPrompt.setText("" + session.getTimeDelayPrompt());
CategoryItem[] items = session.getItems();
for (CategoryItem categoryItem : items) {
// System.out.println("sessionPath=" + sessionPath);
// System.out.println("categoryItem=" + categoryItem);
if (!firstCategoryItem.isSet()) {
firstCategoryItem.setSet(true);
firstCategoryItem.populate(categoryItem);
} else {
final GuiForCategoryItem g4ci = new GuiForCategoryItem(this);
g4ci.populate(categoryItem);
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
lstGuiForCategoryItems.add(g4ci);
diyTable.add(g4ci);
}
});
}
}// foreach categoryItem
refreshGui();
}
void refreshGui() {
// diyTable.revalidate();
// scrollPane.revalidate();
((JComponent) scrollPane.getParent()).revalidate();
pack();
}
public JPanel getDiyTable() {
return diyTable;
}
public void setDiyTable(JPanel diyTable) {
this.diyTable = diyTable;
}
public List<GuiForCategoryItem> getLstGuiForCategoryItems() {
return lstGuiForCategoryItems;
}
public void setLstGuiForCategoryItems(
List<GuiForCategoryItem> lstGuiForCategoryItems) {
this.lstGuiForCategoryItems = lstGuiForCategoryItems;
}
}
|
package org.jetel.util;
import java.nio.CharBuffer;
import sun.text.Normalizer;
/**
* Helper class with some useful methods regarding string/text manipulation
*
* @author dpavlis
* @since July 25, 2002
* @revision $Revision$
*/
public class StringUtils {
// quoting characters
public final static char QUOTE_CHAR='\'';
public final static char DOUBLE_QUOTE_CHAR='"';
/**
* Converts control characters into textual representation<br>
* Note: This code handles only \n, \r ,\t ,\f, \b special chars
*
* @param controlString string containing control characters
* @return string where control characters are replaced by their
* text representation (i.e.\n -> "\n" )
* @since July 25, 2002
*/
public static String specCharToString(String controlString) {
StringBuffer copy = new StringBuffer();
char character;
for (int i = 0; i < controlString.length(); i++) {
character = controlString.charAt(i);
switch (character) {
case '\n':
copy.append("\\n");
break;
case '\t':
copy.append("\\t");
break;
case '\r':
copy.append("\\r");
break;
case '\b':
copy.append("\\b");
break;
case '\f':
copy.append("\\f");
break;
default:
copy.append(character);
}
}
return copy.toString();
}
/**
* Converts textual representation of control characters into control
* characters<br>
* Note: This code handles only \n, \r , \t , \f, \" ,\', \\ special chars
*
* @param controlString Description of the Parameter
* @return String with control characters
* @since July 25, 2002
*/
public static String stringToSpecChar(String controlString) {
if(controlString == null) {
return null;
}
StringBuffer copy = new StringBuffer();
char character;
boolean isBackslash = false;
for (int i = 0; i < controlString.length(); i++) {
character = controlString.charAt(i);
if (isBackslash) {
switch (character) {
case '\\':
copy.append('\\');
break;
case 'n':
copy.append('\n');
break;
case 't':
copy.append('\t');
break;
case 'r':
copy.append('\r');
break;
case '"':
copy.append('"');
break;
case '\'':
copy.append('\'');
break;
case 'f':
copy.append('\f');
break;
case 'b':
copy.append('\b');
break;
default:
copy.append('\\');
copy.append(character);
break;
}
isBackslash = false;
} else {
if (character == '\\') {
isBackslash = true;
} else {
copy.append(character);
}
}
}
return copy.toString();
}
/**
* Formats string from specified messages and their lengths.<br>
* Negative (<0) length means justify to the left, positive (>0) to the right<br>
* If message is longer than specified size, it is trimmed; if shorter, it is padded with blanks.
*
* @param messages array of objects with toString() implemented methods
* @param sizes array of desired lengths (+-) for every message specified
* @return Formatted string
*/
public static String formatString(Object[] messages, int[] sizes) {
int formatSize;
String message;
StringBuffer strBuff = new StringBuffer(100);
for (int i = 0; i < messages.length; i++) {
message = messages[i].toString();
// left or right justified ?
if (sizes[i] < 0) {
formatSize = sizes[i] * (-1);
fillString(strBuff, message, 0, formatSize);
} else {
formatSize = sizes[i];
if (message.length() < formatSize) {
fillBlank(strBuff, formatSize - message.length());
fillString(strBuff, message, 0, message.length());
} else {
fillString(strBuff, message, 0, formatSize);
}
}
}
return strBuff.toString();
}
/**
* Description of the Method
*
* @param strBuf Description of the Parameter
* @param source Description of the Parameter
* @param start Description of the Parameter
* @param length Description of the Parameter
*/
private static void fillString(StringBuffer strBuff, String source, int start, int length) {
int srcLength = source.length();
for (int i = start; i < start + length; i++) {
if (i < srcLength) {
strBuff.append(source.charAt(i));
} else {
strBuff.append(' ');
}
}
}
/**
* Description of the Method
*
* @param strBuf Description of the Parameter
* @param length Description of the Parameter
*/
private static void fillBlank(StringBuffer strBuff, int length) {
for (int i = 0; i < length; i++) {
strBuff.append(' ');
}
}
/**
* Returns True, if the character sequence contains only valid identifier chars.<br>
* [A-Za-z0-9_]
* @param seq Description of the Parameter
* @return The validObjectName value
*/
public static boolean isValidObjectName(CharSequence seq) {
if(seq == null) return false;
for (int i = 0; i < seq.length(); i++) {
if (!Character.isUnicodeIdentifierPart(seq.charAt(i))) {
return false;
}
}
return true;
}
/**
* Returns true if the passed-in character is quote ['] or double
* quote ["].
*
* @param character
* @return true if character equals to ['] or ["]
*/
public static final boolean isQuoteChar(char character){
return character==QUOTE_CHAR || character==DOUBLE_QUOTE_CHAR;
}
/**
* Returns true of passed-in string is quoted - i.e.
* the first character is quote character and the
* last character is equal to the first one.
*
* @param str
* @return true if the string is quoted
*/
public static final boolean isQuoted(CharSequence str){
return isQuoteChar(str.charAt(0)) && str.charAt(0)==str.charAt(str.length()-1);
}
/**
* Modifies buffer scope so that the string quotes are ignored,
* in case quotes are not present doesn't do anything.
* @param buf
* @return
*/
public static CharBuffer unquote(CharBuffer buf) {
if (StringUtils.isQuoted(buf)) {
buf.position(buf.position() + 1);
buf.limit(buf.limit() - 1);
}
return buf;
}
/**
* Modifies string so that the string quotes are ignored,
* in case quotes are not present doesn't do anything.
* @param str
* @return
*/
public static String unquote(String str) {
if (StringUtils.isQuoted(str)) {
str = str.substring(1,str.length()-1);
}
return str;
}
/**
* Modifies buffer scope so that the leading whitespace is ignored.
* @param buf
* @return
*/
public static CharBuffer trimLeading(CharBuffer buf) {
int pos = buf.position();
int lim = buf.limit();
while (pos < lim && Character.isWhitespace(buf.get(pos))) {
pos++;
}
buf.position(pos);
return buf;
}
/**
* Modifies buffer scope so that the trailing whitespace is ignored.
* @param buf
* @return
*/
public static CharBuffer trimTrailing(CharBuffer buf) {
int pos = buf.position();
int lim = buf.limit();
while (pos < lim && Character.isWhitespace(buf.get(lim - 1))) {
lim
}
buf.limit(lim);
return buf;
}
/**
* Modifies buffer scope so that the leading and trailing whitespace is ignored.
* @param buf
* @return
*/
public static CharBuffer trim(CharBuffer buf) {
trimLeading(buf);
trimTrailing(buf);
return buf;
}
/**
* This method removes from the string characters which are not letters nor digits
*
* @param str - input String
* @param takeAlpha - if true method leaves letters
* @param takeNumeric - if true method leaves digits
* @return String where are only letters and (or) digits from input String
*/
public static String getOnlyAlphaNumericChars(String str,boolean takeAlpha,boolean takeNumeric){
if (!takeAlpha && !takeNumeric){
return str;
}
int counter=0;
int length=str.length();
char[] chars=str.toCharArray();
char[] result=new char[length];
char character;
for (int j=0;j<length;j++){
character=chars[j];
if ( (Character.isLetter(character) && takeAlpha) ||
(Character.isDigit(character) && takeNumeric) ){
result[counter++]=chars[j];
}
}
return new String(result,0,counter);
}
/**
* This method removed from string blank space
*
* @param str - input String
* @return input string without blank space
*/
public static String removeBlankSpace(String str){
int length=str.length();
int counter = 0;
char[] chars=str.toCharArray();
char[] result = new char[length];
for (int j=0;j<length;j++){
if (!Character.isWhitespace(chars[j])) {
result[counter++] = chars[j];
}
}
return new String(result,0,counter);
}
/**
* Test whether parameter consists of space characters
* only
* @param data
* @return true if parameter contains space characters only
*/
public static boolean isBlank(CharBuffer data){
data.mark();
for(int i=0;i<data.length();i++){
if (!Character.isSpaceChar(data.get())){
data.reset();
return false;
}
}
data.reset();
return true;
}
/**
* Test whether parameter consists of space characters
* only
* @param data
* @return true if parameter contains space characters only
*/
public static boolean isBlank(CharSequence data){
for(int i=0;i<data.length();i++){
if (!Character.isSpaceChar(data.charAt(i))){
return false;
}
}
return true;
}
/**
* This method replaces diacritic chars by theirs equivalence without diacritic.
* It works only for chars for which decomposition is defined
*
* @param str
* @return string in which diacritic chars are replaced by theirs equivalences without diacritic
*/
public static String removeDiacritic(String str){
return Normalizer.decompose(str, false, 0).replaceAll("\\p{InCombiningDiacriticalMarks}+", "");
}
/**
* This method concates string array to one string. Parts are delimited by given char
*
* @param strings - input array of strings
* @param delimiter
* @return
*/
public static String stringArraytoString(String[] strings,char delimiter){
int length = strings.length;
if (length==0) {
return null;
}
StringBuffer result = new StringBuffer();
for (int i=0;i<length;i++){
result.append(strings[i]);
if (i<length-1) {
result.append(delimiter);
}
}
return result.toString();
}
public static String stringArraytoString(String[] strings){
return stringArraytoString(strings,' ');
}
public static boolean isEmpty(String s) {
return s == null || s.length() == 0;
}
/**
* This method appends passed-in CharSequence to the end of
* passed-in StringBuffer;<br>
* It returns reference to buffer object to allow cascading
* of these operations.
* @param buff buffer to which append sequence of characters
* @param seq characters sequence to append
* @return reference to passed-in buffer
*/
public static final StringBuffer strBuffAppend(StringBuffer buff,CharSequence seq){
int seqLen=seq.length();
buff.ensureCapacity(buff.length()+seqLen);
buff.append(seq);
return buff;
}
/**
* This method appends passed-in CharSequence to the end of
* passed-in StringBuffer;<br>
* It returns reference to buffer object to allow cascading
* of these operations.
* @param buff buffer to which append sequence of characters
* @param seq characters sequence to append
* @return reference to passed-in buffer
*/
public static final StringBuilder strBuffAppend(StringBuilder buff,CharSequence seq){
int seqLen=seq.length();
buff.ensureCapacity(buff.length()+seqLen);
buff.append(seq);
return buff;
}
/**
* This method finds index of string from string array
*
* @param str String to find
* @param array String array for searching
* @return index or found String or -1 if String was not found
*/
public static int findString(String str,String[] array){
for (int i=0;i<array.length;i++){
if (str.equals(array[i])) return i;
}
return -1;
}
/**
* This method finds index of string from string array
*
* @param str String to find
* @param array String array for searching
* @return index or found String or -1 if String was not found
*/
public static int findStringIgnoreCase(String str,String[] array){
for (int i=0;i<array.length;i++){
if (str.equalsIgnoreCase(array[i])) return i;
}
return -1;
}
/**
* This method finds index of first charater, which can't be part of identifier
*
* @param str String for searching
* @param fromIndex
* @return index of first character after identifier name
*/
public static int findIdentifierEnd(CharSequence str, int fromIndex){
int index = fromIndex;
while (index < str.length() && Character.isUnicodeIdentifierPart(str.charAt(index))){
index++;
}
return index;
}
/**
* This method finds index of first charater, which can be part of identifier
*
* @param str String for searching
* @param fromIndex
* @return index of first character, which can be in identifier name
*/
public static int findIdentifierBegining(CharSequence str, int fromIndex){
int index = fromIndex;
while (index < str.length() && !Character.isUnicodeIdentifierPart(str.charAt(index))){
index++;
}
return index;
}
/**
* This method finds maximal lenth from set of Strings
*
* @param strings
* @return length of longest string
*/
public static int getMaxLength(String...strings){
int length = 0;
for (int i=0;i<strings.length;i++){
if (strings[i] != null && strings[i].length() > length){
length = strings[i].length();
}
}
return length;
}
}
/*
* End class StringUtils
*/
|
package org.jetel.graph;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Future;
import junit.framework.Test;
import junit.framework.TestSuite;
import org.apache.commons.io.filefilter.AbstractFileFilter;
import org.apache.commons.io.filefilter.IOFileFilter;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jetel.graph.runtime.EngineInitializer;
import org.jetel.graph.runtime.GraphRuntimeContext;
import org.jetel.main.runGraph;
import org.jetel.test.CloverTestCase;
import org.jetel.util.file.FileUtils;
import org.jetel.util.string.StringUtils;
public class ResetTest extends CloverTestCase {
private final static String SCENARIOS_RELATIVE_PATH = "../cloveretl.test.scenarios/";
private final static String[] EXAMPLE_PATH = {
"../cloveretl.examples/SimpleExamples/",
"../cloveretl.examples/AdvancedExamples/",
"../cloveretl.examples/CTL1FunctionsTutorial/",
"../cloveretl.examples/CTL2FunctionsTutorial/",
"../cloveretl.examples/DataProfiling/",
"../cloveretl.examples/DataSampling/",
"../cloveretl.examples/ExtExamples/",
"../cloveretl.examples.community/RealWorldExamples/",
"../cloveretl.examples.community/WebSiteExamples/",
"../cloveretl.examples/BasicExamples/",
"../cloveretl.test.scenarios/",
"../cloveretl.examples.commercial/CommercialExamples/",
"../cloveretl.examples.commercial/DataQualityExamples/"
//"../cloveretl.examples/CompanyTransactionsTutorial/" // runs too long
};
private final static String[] NEEDS_SCENARIOS_CONNECTION = {
"graphRevenues.grf",
"graphDBExecuteMsSql.grf",
"graphDBExecuteMySql.grf",
"graphDBExecuteOracle.grf",
"graphDBExecutePostgre.grf",
"graphDBExecuteSybase.grf",
"graphInfobrightDataWriterRemote.grf",
"graphLdapReaderWriter.grf"
};
private final static String[] NEEDS_SCENARIOS_LIB = {
"graphDBExecuteOracle.grf",
"graphDBExecuteSybase.grf",
"graphLdapReaderWriter.grf"
};
private final static Map<String, List<String>> CLASSPATHS = new HashMap<String, List<String>>();
static {
CLASSPATHS.put("rpc-literal-service-test.grf", Collections.singletonList("lib/rpc-literal-test.jar"));
}
private final static String GRAPHS_DIR = "graph";
private final static String TRANS_DIR = "trans";
private final static String[] OUT_DIRS = {"data-out/", "data-tmp/", "seq/"};
private final String basePath;
private final File graphFile;
private final boolean batchMode;
private boolean cleanUp = true;
private static Log logger = LogFactory.getLog(ResetTest.class);
public static Test suite() {
final TestSuite suite = new TestSuite();
for (int i = 0; i < EXAMPLE_PATH.length; i++) {
logger.info("Testing graphs in " + EXAMPLE_PATH[i]);
final File graphsDir = new File(EXAMPLE_PATH[i], GRAPHS_DIR);
if(!graphsDir.exists()){
throw new IllegalStateException("Graphs directory " + graphsDir.getAbsolutePath() +" not found");
}
IOFileFilter fileFilter = new AbstractFileFilter() {
@Override
public boolean accept(File file) {
return file.getName().endsWith(".grf")
&& !file.getName().startsWith("TPCH")// ok, performance tests - last very long
&& !file.getName().startsWith("Subgraph") // need server
&& !file.getName().startsWith("clusterDictionary") // cluster tests
&& !file.getName().contains("Performance")// ok, performance tests - last very long
&& !file.getName().equals("graphJoinData.grf") // ok, uses class file that is not created
&& !file.getName().equals("graphJoinHash.grf") // ok, uses class file that is not created
&& !file.getName().equals("graphOrdersReformat.grf") // ok, uses class file that is not created
&& !file.getName().equals("graphDataGeneratorExt.grf") // ok, uses class file that is not created
&& !file.getName().equals("graphApproximativeJoin.grf") // ok, uses class file that is not created
&& !file.getName().equals("graphDBJoin.grf") // ok, uses class file that is not created
&& !file.getName().equals("conversionNum2num.grf") // ok, should fail
&& !file.getName().equals("outPortWriting.grf") // ok, should fail
&& !file.getName().equals("graphDb2Load.grf") // ok, can only work with db2 client
&& !file.getName().equals("graphMsSqlDataWriter.grf") // ok, can only work with MsSql client
&& !file.getName().equals("graphMysqlDataWriter.grf") // ok, can only work with MySql client
&& !file.getName().equals("graphOracleDataWriter.grf") // ok, can only work with Oracle client
&& !file.getName().equals("graphPostgreSqlDataWriter.grf") // ok, can only work with postgre client
&& !file.getName().equals("graphInformixDataWriter.grf") // ok, can only work with informix server
&& !file.getName().equals("graphInfobrightDataWriter.grf") // ok, can only work with infobright server
&& !file.getName().equals("graphSystemExecuteWin.grf") // ok, graph for Windows
&& !file.getName().equals("graphLdapReader_Uninett.grf") // ok, invalid server
&& !file.getName().equals("graphSequenceChecker.grf") // ok, is to fail
&& !file.getName().equals("FixedData.grf") // ok, is to fail
&& !file.getName().equals("xpathReaderStates.grf") // ok, is to fail
&& !file.getName().equals("graphDataPolicy.grf") // ok, is to fail
&& !file.getName().equals("conversionDecimal2integer.grf") // ok, is to fail
&& !file.getName().equals("conversionDecimal2long.grf") // ok, is to fail
&& !file.getName().equals("conversionDouble2integer.grf") // ok, is to fail
&& !file.getName().equals("conversionDouble2long.grf") // ok, is to fail
&& !file.getName().equals("conversionLong2integer.grf") // ok, is to fail
&& !file.getName().equals("nativeSortTestGraph.grf") // ok, invalid paths
&& !file.getName().equals("mountainsInformix.grf") // see issue 2550
&& !file.getName().equals("SystemExecuteWin_EchoFromFile.grf") // graph for windows
&& !file.getName().equals("XLSEncryptedFail.grf") // ok, is to fail
&& !file.getName().equals("XLSXEncryptedFail.grf") // ok, is to fail
&& !file.getName().equals("XLSInvalidFile.grf") // ok, is to fail
&& !file.getName().equals("XLSReaderOrderMappingFail.grf") // ok, is to fail
&& !file.getName().equals("XLSXReaderOrderMappingFail.grf") // ok, is to fail
&& !file.getName().equals("XLSWildcardStrict.grf") // ok, is to fail
&& !file.getName().equals("XLSXWildcardStrict.grf") // ok, is to fail
&& !file.getName().equals("XLSWildcardControlled1.grf") // ok, is to fail
&& !file.getName().equals("XLSXWildcardControlled1.grf") // ok, is to fail
&& !file.getName().equals("XLSWildcardControlled7.grf") // ok, is to fail
&& !file.getName().equals("XLSXWildcardControlled7.grf") // ok, is to fail
&& !file.getName().equals("SSWRITER_MultilineInsertIntoTemplate.grf") // uses graph parameter definition from after-commit.ts
&& !file.getName().equals("SSWRITER_FormatInMetadata.grf") // uses graph parameter definition from after-commit.ts
&& !file.getName().equals("WSC_NamespaceBindingsDefined.grf") // ok, is to fail
&& !file.getName().equals("FailingGraph.grf") // ok, is to fail
&& !file.getName().equals("RunGraph_FailWhenUnderlyingGraphFails.grf") // probably should fail, recheck after added to after-commit.ts
&& !file.getName().equals("DataIntersection_order_check_A.grf") // ok, is to fail
&& !file.getName().equals("DataIntersection_order_check_B.grf") // ok, is to fail
&& !file.getName().equals("UDR_Logging_SFTP_CL1469.grf") // ok, is to fail
&& !file.getName().startsWith("AddressDoctor") //wrong path to db file, try to fix when AD installed on jenkins machines
&& !file.getName().equals("EmailReader_Local.grf") // remove after CL-2167 solved
&& !file.getName().equals("EmailReader_Server.grf") // remove after CLD-3437 solved (or mail.javlin.eu has valid certificate)
&& !file.getName().equals("EmailValidation.grf") // runs too long
&& !file.getName().equals("EmailFilterGreylistingExample.grf") // runs too long
&& !file.getName().equals("EmailFilterSimpleExample.grf") // runs too long
&& !file.getName().equals("graphEmailFilterTestSmtp.grf") // runs too long
&& !file.getName().contains("firebird") // remove after CL-2170 solved
&& !file.getName().startsWith("ListOfRecords_Functions_02_") // remove after CL-2173 solved
&& !file.getName().equals("UDR_FileURL_OneZipMultipleFilesUnspecified.grf") // remove after CL-2174 solved
&& !file.getName().equals("UDR_FileURL_OneZipOneFileUnspecified.grf") // remove after CL-2174 solved
&& !file.getName().startsWith("MapOfRecords_Functions_01_Compiled_") // remove after CL-2175 solved
&& !file.getName().startsWith("MapOfRecords_Functions_01_Interpreted_") // remove after CL-2176 solved
&& !file.getName().equals("manyRecords.grf") // remove after CL-1292 implemented
&& !file.getName().equals("packedDecimal.grf") // remove after CL-1811 solved
&& !file.getName().equals("SimpleZipWrite.grf") // used by ArchiveFlushTest.java, doesn't make sense to run it separately
&& !file.getName().equals("XMLExtract_TKLK_003_Back.grf") // needs output from XMLWriter_LKTW_003.grf
&& !file.getName().equals("XMLWriter-CL-2404-CNO_OTF_ITSS.grf") // runs too long
&& !file.getName().equals("WebAccessLog.grf") // runs too long
&& !file.getName().equals("graphXLSReadWrite.grf") // runs too long
&& !file.getName().equals("JoiningAggregating.grf") // runs too long
&& !file.getName().equals("UDW_sortedInput_manyFiles.grf") // runs too long
&& !file.getName().equals("dataWriting.grf") // runs too long
&& !file.getName().equals("FSClosingTest-longRunning.grf") // runs too long
&& !file.getName().equals("CDW_sortedInput_manyFiles_CLO-5060.grf") // runs too long
&& !file.getName().equals("CreditCards.grf") // runs too long
&& !file.getName().equals("SQLDataParser_precision_CL2187.grf") // ok, is to fail
&& !file.getName().equals("incrementalReadingDB_explicitMapping.grf") // remove after CL-2239 solved
&& !file.getName().equals("HTTPConnector_get_bodyparams.grf") // ok, is to fail
&& !file.getName().equals("HTTPConnector_get_error_unknownhost.grf") // ok, is to fail
&& !file.getName().equals("HTTPConnector_get_error_unknownprotocol.grf") // ok, is to fail
&& !file.getName().equals("HTTPConnector_get_inputfield.grf") // ok, is to fail
&& !file.getName().equals("HTTPConnector_get_inputfileURL.grf") // ok, is to fail
&& !file.getName().equals("HTTPConnector_get_requestcontent.grf") // ok, is to fail
&& !file.getName().equals("HTTPConnector_post_error_unknownhost.grf") // ok, is to fail
&& !file.getName().equals("HTTPConnector_post_error_unknownprotocol.grf") // ok, is to fail
&& !file.getName().equals("HTTPConnector_inputmapping_null_values.grf") // ok, is to fail
&& !file.getName().equals("HttpConnector_errHandlingNoRedir.grf") // ok, is to fail
&& !file.getName().equals("HTTPConnector_retry_CLO-1251.grf") // runs too long
&& !file.getName().equals("HTTPConnector_timeout_CLO-1251.grf") // runs too long
&& !file.getName().equals("XMLExtract_fileURL_not_xml.grf") // ok, is to fail
&& !file.getName().equals("XMLExtract_charset_invalid.grf") // ok, is to fail
&& !file.getName().equals("XMLExtract_mappingURL_missing.grf") // ok, is to fail
&& !file.getName().equals("XMLExtract_fileURL_not_exists.grf") // ok, is to fail
&& !file.getName().equals("XMLExtract_charset_not_default_fail.grf") // ok, is to fail
&& !file.getName().equals("RunGraph_differentOutputMetadataFail.grf") // ok, is to fail
&& !file.getName().equals("LUTPersistent_wrong_metadata.grf") // ok, is to fail
&& !file.getName().equals("UDW_nonExistingDir_fail_CL-2478.grf") // ok, is to fail
&& !file.getName().equals("CTL_lookup_put_fail.grf") // ok, is to fail
&& !file.getName().equals("SystemExecute_printBatchFile.grf") // ok, is to fail
&& !file.getName().equals("JoinMergeIssue_FailWhenMasterUnsorted.grf") // ok, is to fail
&& !file.getName().equals("UDW_remoteZipPartitioning_fail_CL-2564.grf") // ok, is to fail
&& !file.getName().equals("checkConfigTest.grf") // ok, is to fail
&& !file.getName().equals("DebuggingGraph.grf") // ok, is to fail
&& !file.getName().equals("graphDebuggingGraph.grf") // ok, is to fail
&& !file.getName().equals("CLO-404-recordCountsInErrorMessage.grf") // ok, is to fail
&& !file.getName().equals("TreeReader_CLO-4699.grf") // ok, is to fail
&& !file.getName().matches("Locale_.*_default.grf") // server only
&& !file.getName().equals("CompanyChecks.grf") // an example that needs embedded derby
&& !file.getName().equals("DatabaseAccess.grf") // an example that needs embedded derby
&& !file.getName().equals("graphDatabaseAccess.grf") // an example that needs embedded derby
&& !file.getName().equals("Twitter.grf") // an example that needs credentials
&& !file.getName().equals("XMLReader_no_output_port.grf") // ok, is to fail
&& !file.getName().startsWith("Proxy_") // allowed to run only on virt-cyan as proxy tests
&& !file.getName().equals("SandboxOperationHandlerTest.grf") // runs only on server
&& !file.getName().equals("DenormalizerWithoutInputFile.grf") // probably subgraph not supposed to be executed separately
&& !file.getName().equals("SimpleSequence_longValue.grf") // needs the sequence to be reset on start
&& !file.getName().equals("BeanWriterReader_employees.grf") // remove after CL-2474 solved
&& !file.getName().equals("GraphParameters_secure.grf") // server test
&& !file.getName().equals("GraphParameters_secureOverriden.grf") // server test
&& !file.getName().equals("GraphParameters_secureOverriden_subgraph.grf") // subgraph of server test
&& !file.getName().equals("SSR_CloseOnError.grf") // subgraph of server test
&& !file.getName().equals("TypedProperties_CLO-1997.grf") // server test
&& !file.getName().equals("EmptySubGraph.grf") // server test
&& !file.getName().equals("ParallelReader_HDFS.grf") // cluster test
&& !file.getName().equals("SubgraphsReuse.grf") // contains subgraphs
&& !file.getName().startsWith("Issues") // contains subgraphs
&& !file.getName().equals("SubgraphsSimplifyingGraph.grf") // contains subgraphs
&& !file.getName().equals("GEOCoding.grf") // contains subgraphs
&& !file.getName().equals("RandomDataGenerator.grf") // contains subgraphs
&& !file.getName().equals("graphHTTPConnector.grf") // external service is unstable
&& !file.getName().equals("CLO-2214_pre_post_execute_race_condition.grf") // ok, is to fail
&& !file.getName().equals("EmptyGraph.grf") // ok, is to fail
&& !file.getName().equals("informix.grf") // remove after CLO-2793 solved
&& !file.getName().equals("EmailReader_BadDataFormatException.grf") // ok, is to fail
&& !file.getName().equals("PhaseOrderCheck.grf") // ok, is to fail
&& !file.getName().equals("JoinApproximative_invalid_join_key_CLO-4748.grf") // ok, is to fail
&& !file.getName().equals("ExtSort_missing_sort_key_CLO-4741.grf") // ok, is to fail
&& !file.getName().equals("Transformations_invalid_language.grf") // ok, is to fail
&& !file.getName().equals("graphCloverData.grf") // remove after CLO-4360 fixed
&& !file.getName().equals("MetadataWriting.grf") // server test
&& !file.getName().equals("WSC_ThrowException.grf") // negative test
&& !file.getName().startsWith("DBInputTable_query_error_logging_") // negative tests
&& !file.getName().startsWith("DBExecute_query_error_logging_") // negative tests
&& !file.getName().equals("EclipseClasspathParsing_CLO-6013.grf") // server test
&& !file.getName().equals("CDR_corruptFile_CLO-5329.grf") // negative test
&& !file.getName().equals("CDR_metadataPropagation_CLO-2850.grf") // negative test
&& !file.getName().equals("CDW_append_CLO-5217.grf") // negative test
&& !file.getName().equals("CDW_autofilling_CLO-6311.grf") // server test
&& !file.getName().equals("CTL_getComponentProperty_dynamicParam_fail_CLO-3838.grf") // negative test
&& !file.getName().equals("CTL_isSubgraphInputPortConnected_1_negative.grf") // negative test
&& !file.getName().equals("CTL_isSubgraphInputPortConnected_2_negative.grf") // negative test
&& !file.getName().equals("CTL_isSubgraphOutputPortConnected_1_negative.grf") // negative test
&& !file.getName().equals("CTL_isSubgraphOutputPortConnected_2_negative.grf") // negative test
&& !file.getName().equals("CTL_raiseError_CLO-4084.grf") // negative test
&& !file.getName().equals("CoDR_missingFields_CLO-2838.grf") // negative test
&& !file.getName().equals("CoDR_parsingError_CLO-5703.grf") // negative test
&& !file.getName().equals("CoDR_prematureFinish_CLO-5610.grf") // negative test
&& !file.getName().equals("CoDR_tooManyFields_CLO-2838.grf") // negative test
&& !file.getName().equals("CopyFiles_emptyUrl_CLO-5114.grf") // negative test
&& !file.getName().equals("CopyFiles_maskPassword_CLO-6064.grf") // negative test
&& !file.getName().equals("CopyFiles_unsupported_protocols_checkConfig_CLO-4491.grf") // negative test
&& !file.getName().equals("CopyFiles_nativePath_Windows.grf") // windows test
&& !file.getName().equals("CreateFiles_createDir_fail.grf") // negative test
&& !file.getName().equals("CreateFiles_emptyUrl_CLO-5114.grf") // negative test
&& !file.getName().equals("CreateFiles_unsupported_protocols_checkConfig_CLO-4491.grf") // negative test
&& !file.getName().equals("DBExecute_external_sql_resolve_CLO-3641.grf") // negative test
&& !file.getName().equals("DBJoin_checkConfig_CLO-4826.grf") // negative test
&& !file.getName().equals("DeleteFiles_emptyUrl_CLO-5114.grf") // negative test
&& !file.getName().equals("DeleteFiles_unsupported_protocols_checkConfig_CLO-4491.grf") // negative test
&& !file.getName().startsWith("Denormalizer_incompleteGroupAllowed_fail") // negative test
&& !file.getName().equals("Divider_fail.grf") // negative test
&& !file.getName().startsWith("EOF_as_delimiter_onRecord_fail_") // negative test
&& !file.getName().equals("KeyValuesToRecord_WrongSortOrder.grf") // negative test
&& !file.getName().equals("ListFiles_emptyUrl_CLO-5114.grf") // negative test
&& !file.getName().equals("ListFiles_unsupported_protocols_checkConfig_CLO-4491.grf") // negative test
&& !file.getName().equals("LoopInGraph3.grf") // negative test
&& !file.getName().startsWith("LoopWithSubgraph_") // negative and server tests
&& !file.getName().equals("MoveFiles_emptyUrl_CLO-5114.grf") // negative test
&& !file.getName().equals("MoveFiles_unsupported_protocols_checkConfig_CLO-4491.grf") // negative test
&& !file.getName().equals("NonExistingSandbox.grf") // negative test
&& !file.getName().equals("NotNullableFieldWithDefaultValueInNullValues_CLO-4569.grf") // negative test
&& !file.getName().equals("ParameterDynamicValue_circular_reference_fail.grf") // negative test
&& !file.getName().equals("Pivot_CLO-4726_nameMissing.grf") // negative test
&& !file.getName().equals("Pivot_CLO-4726_valueMissing.grf") // negative test
&& !file.getName().equals("Pivot_NPE_CLO-4739.grf") // negative test
&& !file.getName().equals("ProfilerProbe_metadata_mismatch_active.grf") // negative test
&& !file.getName().equals("ProfilerProbe_no_output_port_no_persist.grf") // negative test
&& !file.getName().startsWith("RedundantPort_CLO-6774") // negative test
&& !file.getName().equals("RunGraph_recursion_detection_CLO-4586.grf") // negative test
&& !file.getName().equals("SFTP_missingPrivateKey_CLO-5770.grf") // negative test
&& !file.getName().equals("Tableau-TerminateIfTableExists.grf") // negative test
&& !file.getName().startsWith("Tableau-Unsupported") // negative test
&& !file.getName().equals("UDR_fixedLengthMetadata_errorReporting_CLO-3955.grf") // negative test
&& !file.getName().equals("UDR_invalidDataPolicy.grf") // negative test
&& !file.getName().equals("UDR_unmappable_characters_CharByteDataParser_fail.grf") // negative test
&& !file.getName().equals("UDR_unmappable_characters_CharByteDataParser_skip_fail.grf") // negative test
&& !file.getName().equals("UDR_unmappable_characters_DataParser_fail.grf") // negative test
&& !file.getName().equals("UDR_unmappable_characters_DataParser_skip_fail.grf") // negative test
&& !file.getName().equals("UDR_unmappable_characters_SimpleDataParser_fail.grf") // negative test
&& !file.getName().equals("WildcardsInDirPath.grf") // negative test
&& !file.getName().equals("dataGenerator.grf") // negative test
&& !file.getName().equals("BuiltInGraphParameters_parent.grf") // server test
&& !file.getName().startsWith("CTL_getSubgraphInputPortsCount_") // server test
&& !file.getName().startsWith("CTL_getSubgraphOutputPortsCount_") // server test
&& !file.getName().equals("CTL_isSubgraphInputPortConnected_1.grf") // server test
&& !file.getName().equals("CTL_isSubgraphInputPortConnected_2.grf") // server test
&& !file.getName().equals("CTL_isSubgraphOutputPortConnected_1.grf") // server test
&& !file.getName().equals("CTL_isSubgraphOutputPortConnected_2.grf") // server test
&& !file.getName().startsWith("ConditionalExecution_0") // server test
&& !file.getName().equals("Denormalizer_groupBySize_earlyRecordRelease.grf") // server test
&& !file.getName().equals("DisableAsTrash_metadata_propagation_CLO-6749.grf") // server test
&& !file.getName().equals("ExecuteProfilerJob_executionLabel.grf") // server test
&& !file.getName().equals("MetadataPropagation_CLO-6057.grf") // server test
&& !file.getName().equals("MoreFilesMatchPattern.grf") // server test
&& !file.getName().equals("NoFileMatchesPattern.grf") // server test
&& !file.getName().equals("OneFileMatchesPattern.grf") // server test
&& !file.getName().startsWith("OptionalPorts_0") // server test
&& !file.getName().equals("ParameterDynamicValue_dictionary_use.grf") // server test
&& !file.getName().equals("ParameterDynamicValue_disable_component.grf") // server test
&& !file.getName().equals("ParameterDynamicValue_override_dynamic_value_from_parent.grf") // server test
&& !file.getName().equals("ParameterDynamicValue_subgraph_simple_usage.grf") // server test
&& !file.getName().equals("ParameterEmptyValue_secure_CLO-4615.grf") // server test
&& !file.getName().equals("ProfilerProbe_no_output_port.grf") // server test
&& !file.getName().equals("ProfilerProbe_persisting_results.grf") // server test
&& !file.getName().equals("SimpleSequence_concurrent.grf") // server test
&& !file.getName().equals("UDW_escapeSequences_CLO-5660.grf") // server test
&& !file.getName().equals("SetJobOutput_dictionary_CLO-3007.grf") // server test
&& !file.getName().equals("ValidationDefaultLanguageSettings.grf") // server test
&& !file.getName().equals("DB_rollback_CLO-4878.grf") // server test
&& !file.getName().equals("ValidationTransformLifeCycle.grf") // have to be run only once
&& !file.getName().equals("Tableau-ThreadSafe.grf"); // disabled test
}
};
IOFileFilter dirFilter = new AbstractFileFilter() {
@Override
public boolean accept(File file) {
return file.isDirectory()
&& !file.getName().equals("bigRecords") // runs too long
&& !file.getName().equals("cluster") // cluster tests
&& !file.getName().equals("S3")
&& !file.getName().equals("email")
&& !file.getName().equals("performance")
&& !file.getName().equals("dataPolicy") // negative tests
&& !file.getName().equals("metadataPropagation") // mostly server tests
&& !file.getName().equals("ExecuteGraph") // jobflows
&& !file.getName().equals("RecordToKeyValues") // CLO-7086: temporarily removed tests
&& !file.getName().equals("KeyValuesToRecord") // CLO-7086: temporarily removed tests
&& !file.getName().equals("DB2DataWriter") // can only work with db2 client
&& !file.getName().equals("windows"); // wokna only tests
}
};
Collection<File> filesCollection = org.apache.commons.io.FileUtils.listFiles(graphsDir, fileFilter, dirFilter);
File[] graphFiles = filesCollection.toArray(new File[0]);
Arrays.sort(graphFiles);
for(int j = 0; j < graphFiles.length; j++){
suite.addTest(new ResetTest(EXAMPLE_PATH[i], graphFiles[j], false, false));
suite.addTest(new ResetTest(EXAMPLE_PATH[i], graphFiles[j], true, j == graphFiles.length - 1 ? true : false));
}
}
return suite;
}
@Override
protected void setUp() throws Exception {
super.setUp();
initEngine();
}
protected static String getTestName(String basePath, File graphFile, boolean batchMode) {
final StringBuilder ret = new StringBuilder();
final String n = graphFile.getName();
int lastDot = n.lastIndexOf('.');
if (lastDot == -1) {
ret.append(n);
} else {
ret.append(n.substring(0, lastDot));
}
if (batchMode) {
ret.append("-batch");
} else {
ret.append("-nobatch");
}
return ret.toString();
}
protected ResetTest(String basePath, File graphFile, boolean batchMode, boolean cleanup) {
super(getTestName(basePath, graphFile, batchMode));
this.basePath = basePath;
this.graphFile = graphFile;
this.batchMode = batchMode;
this.cleanUp = cleanup;
}
@Override
protected void runTest() throws Throwable {
final String baseAbsolutePath = new File(basePath).getAbsolutePath().replace('\\', '/');
logger.info("Project dir: " + baseAbsolutePath);
logger.info("Analyzing graph " + graphFile.getPath());
logger.info("Batch mode: " + batchMode);
final GraphRuntimeContext runtimeContext = new GraphRuntimeContext();
runtimeContext.setUseJMX(false);
runtimeContext.setContextURL(FileUtils.getFileURL(FileUtils.appendSlash(baseAbsolutePath))); // context URL should be absolute
runtimeContext.setJobUrl(FileUtils.getFileURL(runtimeContext.getContextURL(), graphFile.getPath()).toString());
// absolute path in PROJECT parameter is required for graphs using Derby database
runtimeContext.addAdditionalProperty("PROJECT", baseAbsolutePath);
if (StringUtils.findString(graphFile.getName(), NEEDS_SCENARIOS_CONNECTION) != -1) {
final String connDir = new File(SCENARIOS_RELATIVE_PATH + "conn").getAbsolutePath();
runtimeContext.addAdditionalProperty("CONN_DIR", connDir);
logger.info("CONN_DIR set to " + connDir);
}
if (StringUtils.findString(graphFile.getName(), NEEDS_SCENARIOS_LIB) != -1) {// set LIB_DIR to jdbc drivers directory
final String libDir = new File(SCENARIOS_RELATIVE_PATH + "lib").getAbsolutePath();
runtimeContext.addAdditionalProperty("LIB_DIR", libDir);
logger.info("LIB_DIR set to " + libDir);
}
// for scenarios graphs, add the TRANS dir to the classpath
if (basePath.contains("cloveretl.test.scenarios")) {
List<URL> classpath = new ArrayList<URL>();
classpath.add(FileUtils.getFileURL(FileUtils.appendSlash(baseAbsolutePath) + TRANS_DIR + "/"));
if (CLASSPATHS.containsKey(graphFile.getName())) {
for (String path : CLASSPATHS.get(graphFile.getName())) {
classpath.add(FileUtils.getFileURL(runtimeContext.getContextURL(), path));
}
}
runtimeContext.setRuntimeClassPath(classpath.toArray(new URL[classpath.size()]));
runtimeContext.setCompileClassPath(runtimeContext.getRuntimeClassPath());
}
runtimeContext.setBatchMode(batchMode);
final TransformationGraph graph = TransformationGraphXMLReaderWriter.loadGraph(new FileInputStream(graphFile), runtimeContext);
try {
graph.setDebugMode(false);
EngineInitializer.initGraph(graph);
for (int i = 0; i < 3; i++) {
final Future<Result> futureResult = runGraph.executeGraph(graph, runtimeContext);
Result result = Result.N_A;
result = futureResult.get();
switch (result) {
case FINISHED_OK:
// everything O.K.
logger.info("Execution of graph successful !");
break;
case ABORTED:
// execution was ABORTED !!
logger.info("Execution of graph failed !");
fail("Execution of graph failed !");
break;
default:
logger.info("Execution of graph failed !");
fail("Execution of graph failed !");
}
}
} catch (Throwable e) {
throw new IllegalStateException("Error executing graph " + graphFile, e);
} finally {
if (cleanUp) {
cleanupData();
}
logger.info("Transformation graph is freeing.\n");
graph.free();
}
}
private void cleanupData() {
for (String outDir : OUT_DIRS) {
File outDirFile = new File(basePath, outDir);
File[] file = outDirFile.listFiles(new FileFilter() {
@Override
public boolean accept(File f) {
return f.isFile();
}
});
for (int i = 0; i < file.length; i++) {
final boolean drt = file[i].delete();
if (drt) {
logger.info("Cleanup: deleted file " + file[i].getAbsolutePath());
} else {
logger.info("Cleanup: error delete file " + file[i].getAbsolutePath());
}
}
}
}
}
|
package com.facebook.litho;
import javax.annotation.Nullable;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.graphics.Rect;
import android.support.annotation.AttrRes;
import android.support.annotation.ColorInt;
import android.support.annotation.DimenRes;
import android.support.annotation.Dimension;
import android.support.annotation.DrawableRes;
import android.support.annotation.Px;
import android.support.annotation.StringRes;
import android.support.v4.view.ViewCompat;
import android.text.TextUtils;
import android.util.SparseArray;
import com.facebook.R;
import com.facebook.litho.config.ComponentsConfiguration;
import com.facebook.litho.reference.ColorDrawableReference;
import com.facebook.litho.reference.Reference;
import com.facebook.litho.reference.ResourceDrawableReference;
import com.facebook.infer.annotation.ThreadConfined;
import com.facebook.yoga.YogaAlign;
import com.facebook.yoga.YogaBaselineFunction;
import com.facebook.yoga.YogaFlexDirection;
import com.facebook.yoga.YogaJustify;
import com.facebook.yoga.YogaDirection;
import com.facebook.yoga.YogaPositionType;
import com.facebook.yoga.YogaWrap;
import com.facebook.yoga.YogaEdge;
import com.facebook.yoga.YogaConstants;
import com.facebook.yoga.YogaMeasureFunction;
import com.facebook.yoga.YogaNode;
import com.facebook.yoga.YogaNodeAPI;
import com.facebook.yoga.YogaOverflow;
import com.facebook.yoga.Spacing;
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;
import static android.os.Build.VERSION_CODES.JELLY_BEAN_MR1;
import static android.support.annotation.Dimension.DP;
import static com.facebook.litho.ComponentContext.NULL_LAYOUT;
import static com.facebook.yoga.YogaEdge.ALL;
import static com.facebook.yoga.YogaEdge.BOTTOM;
import static com.facebook.yoga.YogaEdge.END;
import static com.facebook.yoga.YogaEdge.HORIZONTAL;
import static com.facebook.yoga.YogaEdge.LEFT;
import static com.facebook.yoga.YogaEdge.RIGHT;
import static com.facebook.yoga.YogaEdge.START;
import static com.facebook.yoga.YogaEdge.TOP;
import static com.facebook.yoga.YogaEdge.VERTICAL;
/**
* Internal class representing both a {@link ComponentLayout} and a
* {@link com.facebook.litho.ComponentLayout.ContainerBuilder}.
*/
@ThreadConfined(ThreadConfined.ANY)
class InternalNode implements ComponentLayout, ComponentLayout.ContainerBuilder {
// Used to check whether or not the framework can use style IDs for
// paddingStart/paddingEnd due to a bug in some Android devices.
private static final boolean SUPPORTS_RTL = (SDK_INT >= JELLY_BEAN_MR1);
// When this flag is set, layoutDirection style was explicitly set on this node.
private static final long PFLAG_LAYOUT_DIRECTION_IS_SET = 1L << 0;
// When this flag is set, alignSelf was explicitly set on this node.
private static final long PFLAG_ALIGN_SELF_IS_SET = 1L << 1;
// When this flag is set, position type was explicitly set on this node.
private static final long PFLAG_POSITION_TYPE_IS_SET = 1L << 2;
// When this flag is set, flex was explicitly set on this node.
private static final long PFLAG_FLEX_IS_SET = 1L << 3;
// When this flag is set, flex grow was explicitly set on this node.
private static final long PFLAG_FLEX_GROW_IS_SET = 1L << 4;
// When this flag is set, flex shrink was explicitly set on this node.
private static final long PFLAG_FLEX_SHRINK_IS_SET = 1L << 5;
// When this flag is set, flex basis was explicitly set on this node.
private static final long PFLAG_FLEX_BASIS_IS_SET = 1L << 6;
// When this flag is set, importantForAccessibility was explicitly set on this node.
private static final long PFLAG_IMPORTANT_FOR_ACCESSIBILITY_IS_SET = 1L << 7;
// When this flag is set, duplicateParentState was explicitly set on this node.
private static final long PFLAG_DUPLICATE_PARENT_STATE_IS_SET = 1L << 8;
// When this flag is set, margin was explicitly set on this node.
private static final long PFLAG_MARGIN_IS_SET = 1L << 9;
// When this flag is set, padding was explicitly set on this node.
private static final long PFLAG_PADDING_IS_SET = 1L << 10;
// When this flag is set, position was explicitly set on this node.
private static final long PFLAG_POSITION_IS_SET = 1L << 11;
// When this flag is set, width was explicitly set on this node.
private static final long PFLAG_WIDTH_IS_SET = 1L << 12;
// When this flag is set, minWidth was explicitly set on this node.
private static final long PFLAG_MIN_WIDTH_IS_SET = 1L << 13;
// When this flag is set, maxWidth was explicitly set on this node.
private static final long PFLAG_MAX_WIDTH_IS_SET = 1L << 14;
// When this flag is set, height was explicitly set on this node.
private static final long PFLAG_HEIGHT_IS_SET = 1L << 15;
// When this flag is set, minHeight was explicitly set on this node.
private static final long PFLAG_MIN_HEIGHT_IS_SET = 1L << 16;
// When this flag is set, maxHeight was explicitly set on this node.
private static final long PFLAG_MAX_HEIGHT_IS_SET = 1L << 17;
// When this flag is set, background was explicitly set on this node.
private static final long PFLAG_BACKGROUND_IS_SET = 1L << 18;
// When this flag is set, foreground was explicitly set on this node.
private static final long PFLAG_FOREGROUND_IS_SET = 1L << 19;
// When this flag is set, visibleHandler was explicitly set on this node.
private static final long PFLAG_VISIBLE_HANDLER_IS_SET = 1L << 20;
// When this flag is set, focusedHandler was explicitly set on this node.
private static final long PFLAG_FOCUSED_HANDLER_IS_SET = 1L << 21;
// When this flag is set, fullImpressionHandler was explicitly set on this node.
private static final long PFLAG_FULL_IMPRESSION_HANDLER_IS_SET = 1L << 22;
// When this flag is set, invisibleHandler was explicitly set on this node.
private static final long PFLAG_INVISIBLE_HANDLER_IS_SET = 1L << 23;
// When this flag is set, touch expansion was explicitly set on this node.
private static final long PFLAG_TOUCH_EXPANSION_IS_SET = 1L << 24;
// When this flag is set, border width was explicitly set on this node.
private static final long PFLAG_BORDER_WIDTH_IS_SET = 1L << 25;
// When this flag is set, aspectRatio was explicitly set on this node.
private static final long PFLAG_ASPECT_RATIO_IS_SET = 1L << 26;
// When this flag is set, transitionKey was explicitly set on this node.
private static final long PFLAG_TRANSITION_KEY_IS_SET = 1L << 27;
// When this flag is set, border color was explicitly set on this node.
private static final long PFLAG_BORDER_COLOR_IS_SET = 1L << 28;
private final ResourceResolver mResourceResolver = new ResourceResolver();
YogaNodeAPI mYogaNode;
private ComponentContext mComponentContext;
private Resources mResources;
private Component mComponent;
private int mImportantForAccessibility = ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_AUTO;
private boolean mDuplicateParentState;
private boolean mIsNestedTreeHolder;
private InternalNode mNestedTree;
private InternalNode mNestedTreeHolder;
private long mPrivateFlags;
private Reference<? extends Drawable> mBackground;
private Reference<? extends Drawable> mForeground;
private int mBorderColor = Color.TRANSPARENT;
private NodeInfo mNodeInfo;
private boolean mForceViewWrapping;
private String mTransitionKey;
private EventHandler mVisibleHandler;
private EventHandler mFocusedHandler;
private EventHandler mFullImpressionHandler;
private EventHandler mInvisibleHandler;
private String mTestKey;
private Spacing mTouchExpansion;
private Spacing mNestedTreePadding;
private Spacing mNestedTreeBorderWidth;
private boolean[] mIsPaddingPercent;
private float mResolvedTouchExpansionLeft = YogaConstants.UNDEFINED;
private float mResolvedTouchExpansionRight = YogaConstants.UNDEFINED;
private float mResolvedX = YogaConstants.UNDEFINED;
private float mResolvedY = YogaConstants.UNDEFINED;
private float mResolvedWidth = YogaConstants.UNDEFINED;
private float mResolvedHeight = YogaConstants.UNDEFINED;
private int mLastWidthSpec = DiffNode.UNSPECIFIED;
private int mLastHeightSpec = DiffNode.UNSPECIFIED;
private float mLastMeasuredWidth = DiffNode.UNSPECIFIED;
private float mLastMeasuredHeight = DiffNode.UNSPECIFIED;
private DiffNode mDiffNode;
private boolean mCachedMeasuresValid;
private TreeProps mPendingTreeProps;
void init(YogaNodeAPI yogaNode, ComponentContext componentContext, Resources resources) {
yogaNode.setData(this);
yogaNode.setOverflow(YogaOverflow.HIDDEN);
yogaNode.setMeasureFunction(null);
// YogaNode is the only version of YogaNodeAPI with this support;
if (yogaNode instanceof YogaNode) {
yogaNode.setBaselineFunction(null);
}
mYogaNode = yogaNode;
mComponentContext = componentContext;
mResources = resources;
mResourceResolver.init(
mComponentContext,
componentContext.getResourceCache());
}
@Px
@Override
public int getX() {
if (YogaConstants.isUndefined(mResolvedX)) {
mResolvedX = mYogaNode.getLayoutX();
}
return (int) mResolvedX;
}
@Px
@Override
public int getY() {
if (YogaConstants.isUndefined(mResolvedY)) {
mResolvedY = mYogaNode.getLayoutY();
}
return (int) mResolvedY;
}
@Px
@Override
public int getWidth() {
if (YogaConstants.isUndefined(mResolvedWidth)) {
mResolvedWidth = mYogaNode.getLayoutWidth();
}
return (int) mResolvedWidth;
}
@Px
@Override
public int getHeight() {
if (YogaConstants.isUndefined(mResolvedHeight)) {
mResolvedHeight = mYogaNode.getLayoutHeight();
}
return (int) mResolvedHeight;
}
@Px
@Override
public int getPaddingLeft() {
return FastMath.round(mYogaNode.getLayoutPadding(LEFT));
}
@Px
@Override
public int getPaddingTop() {
return FastMath.round(mYogaNode.getLayoutPadding(TOP));
}
@Px
@Override
public int getPaddingRight() {
return FastMath.round(mYogaNode.getLayoutPadding(RIGHT));
}
@Px
@Override
public int getPaddingBottom() {
return FastMath.round(mYogaNode.getLayoutPadding(BOTTOM));
}
public Reference<? extends Drawable> getBackground() {
return mBackground;
}
public Reference<? extends Drawable> getForeground() {
return mForeground;
}
public void setCachedMeasuresValid(boolean valid) {
mCachedMeasuresValid = valid;
}
public int getLastWidthSpec() {
return mLastWidthSpec;
}
public void setLastWidthSpec(int widthSpec) {
mLastWidthSpec = widthSpec;
}
public int getLastHeightSpec() {
return mLastHeightSpec;
}
public void setLastHeightSpec(int heightSpec) {
mLastHeightSpec = heightSpec;
}
public boolean hasVisibilityHandlers() {
return mVisibleHandler != null
|| mFocusedHandler != null
|| mFullImpressionHandler != null
|| mInvisibleHandler != null;
}
/**
* The last value the measure funcion associated with this node {@link Component} returned
* for the width. This is used together with {@link InternalNode#getLastWidthSpec()}
* to implement measure caching.
*/
float getLastMeasuredWidth() {
return mLastMeasuredWidth;
}
/**
* Sets the last value the measure funcion associated with this node {@link Component} returned
* for the width.
*/
void setLastMeasuredWidth(float lastMeasuredWidth) {
mLastMeasuredWidth = lastMeasuredWidth;
}
/**
* The last value the measure funcion associated with this node {@link Component} returned
* for the height. This is used together with {@link InternalNode#getLastHeightSpec()}
* to implement measure caching.
*/
float getLastMeasuredHeight() {
return mLastMeasuredHeight;
}
/**
* Sets the last value the measure funcion associated with this node {@link Component} returned
* for the height.
*/
void setLastMeasuredHeight(float lastMeasuredHeight) {
mLastMeasuredHeight = lastMeasuredHeight;
}
DiffNode getDiffNode() {
return mDiffNode;
}
boolean areCachedMeasuresValid() {
return mCachedMeasuresValid;
}
void setDiffNode(DiffNode diffNode) {
mDiffNode = diffNode;
}
/**
* Mark this node as a nested tree root holder.
*/
void markIsNestedTreeHolder(TreeProps currentTreeProps) {
mIsNestedTreeHolder = true;
mPendingTreeProps = TreeProps.copy(currentTreeProps);
}
/**
* @return Whether this node is holding a nested tree or not. The decision was made during
* tree creation {@link ComponentLifecycle#createLayout(ComponentContext, Component, boolean)}.
*/
boolean isNestedTreeHolder() {
return mIsNestedTreeHolder;
}
@Override
public YogaDirection getResolvedLayoutDirection() {
return mYogaNode.getLayoutDirection();
}
@Override
public InternalNode layoutDirection(YogaDirection direction) {
mPrivateFlags |= PFLAG_LAYOUT_DIRECTION_IS_SET;
mYogaNode.setDirection(direction);
return this;
}
@Override
public InternalNode flexDirection(YogaFlexDirection direction) {
mYogaNode.setFlexDirection(direction);
return this;
}
@Override
public InternalNode wrap(YogaWrap wrap) {
mYogaNode.setWrap(wrap);
return this;
}
@Override
public InternalNode justifyContent(YogaJustify justifyContent) {
mYogaNode.setJustifyContent(justifyContent);
return this;
}
@Override
public InternalNode alignItems(YogaAlign alignItems) {
mYogaNode.setAlignItems(alignItems);
return this;
}
@Override
public InternalNode alignContent(YogaAlign alignContent) {
mYogaNode.setAlignContent(alignContent);
return this;
}
@Override
public InternalNode alignSelf(YogaAlign alignSelf) {
mPrivateFlags |= PFLAG_ALIGN_SELF_IS_SET;
mYogaNode.setAlignSelf(alignSelf);
return this;
}
@Override
public InternalNode positionType(YogaPositionType positionType) {
mPrivateFlags |= PFLAG_POSITION_TYPE_IS_SET;
mYogaNode.setPositionType(positionType);
return this;
}
@Override
public InternalNode flex(float flex) {
mPrivateFlags |= PFLAG_FLEX_IS_SET;
mYogaNode.setFlex(flex);
return this;
}
@Override
public InternalNode flexGrow(float flexGrow) {
mPrivateFlags |= PFLAG_FLEX_GROW_IS_SET;
mYogaNode.setFlexGrow(flexGrow);
return this;
}
@Override
public InternalNode flexShrink(float flexShrink) {
mPrivateFlags |= PFLAG_FLEX_SHRINK_IS_SET;
mYogaNode.setFlexShrink(flexShrink);
return this;
}
@Override
public InternalNode flexBasisPx(@Px int flexBasis) {
mPrivateFlags |= PFLAG_FLEX_BASIS_IS_SET;
mYogaNode.setFlexBasis(flexBasis);
return this;
}
@Override
public InternalNode flexBasisPercent(float percent) {
mPrivateFlags |= PFLAG_FLEX_BASIS_IS_SET;
mYogaNode.setFlexBasisPercent(percent);
return this;
}
@Override
public InternalNode flexBasisAttr(@AttrRes int resId, @DimenRes int defaultResId) {
return flexBasisPx(mResourceResolver.resolveDimenOffsetAttr(resId, defaultResId));
}
@Override
public InternalNode flexBasisAttr(@AttrRes int resId) {
return flexBasisAttr(resId, 0);
}
@Override
public InternalNode flexBasisRes(@DimenRes int resId) {
return flexBasisPx(mResourceResolver.resolveDimenOffsetRes(resId));
}
@Override
public InternalNode flexBasisDip(@Dimension(unit = DP) int flexBasis) {
return flexBasisPx(mResourceResolver.dipsToPixels(flexBasis));
}
@Override
public InternalNode importantForAccessibility(int importantForAccessibility) {
mPrivateFlags |= PFLAG_IMPORTANT_FOR_ACCESSIBILITY_IS_SET;
mImportantForAccessibility = importantForAccessibility;
return this;
}
@Override
public InternalNode duplicateParentState(boolean duplicateParentState) {
mPrivateFlags |= PFLAG_DUPLICATE_PARENT_STATE_IS_SET;
mDuplicateParentState = duplicateParentState;
return this;
}
@Override
public InternalNode marginPx(YogaEdge edge, @Px int margin) {
mPrivateFlags |= PFLAG_MARGIN_IS_SET;
mYogaNode.setMargin(edge, margin);
return this;
}
@Override
public InternalNode marginPercent(YogaEdge edge, float percent) {
mPrivateFlags |= PFLAG_MARGIN_IS_SET;
mYogaNode.setMarginPercent(edge, percent);
return this;
}
@Override
public InternalNode marginAuto(YogaEdge edge) {
mPrivateFlags |= PFLAG_MARGIN_IS_SET;
mYogaNode.setMarginAuto(edge);
return this;
}
@Override
public InternalNode marginAttr(
YogaEdge edge,
@AttrRes int resId,
@DimenRes int defaultResId) {
return marginPx(edge, mResourceResolver.resolveDimenOffsetAttr(resId, defaultResId));
}
@Override
public InternalNode marginAttr(
YogaEdge edge,
@AttrRes int resId) {
return marginAttr(edge, resId, 0);
}
@Override
public InternalNode marginRes(YogaEdge edge, @DimenRes int resId) {
return marginPx(edge, mResourceResolver.resolveDimenOffsetRes(resId));
}
@Override
public InternalNode marginDip(YogaEdge edge, @Dimension(unit = DP) int margin) {
return marginPx(edge, mResourceResolver.dipsToPixels(margin));
}
@Override
public InternalNode paddingPx(YogaEdge edge, @Px int padding) {
mPrivateFlags |= PFLAG_PADDING_IS_SET;
if (mIsNestedTreeHolder) {
if (mNestedTreePadding == null) {
mNestedTreePadding = ComponentsPools.acquireSpacing();
}
mNestedTreePadding.set(edge.intValue(), padding);
setIsPaddingPercent(edge, false);
} else {
mYogaNode.setPadding(edge, padding);
}
return this;
}
@Override
public InternalNode paddingPercent(YogaEdge edge, float percent) {
mPrivateFlags |= PFLAG_PADDING_IS_SET;
if (mIsNestedTreeHolder) {
if (mNestedTreePadding == null) {
mNestedTreePadding = ComponentsPools.acquireSpacing();
}
mNestedTreePadding.set(edge.intValue(), percent);
setIsPaddingPercent(edge, true);
} else {
mYogaNode.setPaddingPercent(edge, percent);
}
return this;
}
@Override
public InternalNode paddingAttr(
YogaEdge edge,
@AttrRes int resId,
@DimenRes int defaultResId) {
return paddingPx(edge, mResourceResolver.resolveDimenOffsetAttr(resId, defaultResId));
}
@Override
public InternalNode paddingAttr(
YogaEdge edge,
@AttrRes int resId) {
return paddingAttr(edge, resId, 0);
}
@Override
public InternalNode paddingRes(YogaEdge edge, @DimenRes int resId) {
return paddingPx(edge, mResourceResolver.resolveDimenOffsetRes(resId));
}
@Override
public InternalNode paddingDip(YogaEdge edge, @Dimension(unit = DP) int padding) {
return paddingPx(edge, mResourceResolver.dipsToPixels(padding));
}
@Override
public InternalNode borderWidthPx(YogaEdge edge, @Px int borderWidth) {
mPrivateFlags |= PFLAG_BORDER_WIDTH_IS_SET;
if (mIsNestedTreeHolder) {
if (mNestedTreeBorderWidth == null) {
mNestedTreeBorderWidth = ComponentsPools.acquireSpacing();
}
mNestedTreeBorderWidth.set(edge.intValue(), borderWidth);
} else {
mYogaNode.setBorder(edge, borderWidth);
}
return this;
}
@Override
public InternalNode borderWidthAttr(
YogaEdge edge,
@AttrRes int resId,
@DimenRes int defaultResId) {
return borderWidthPx(edge, mResourceResolver.resolveDimenOffsetAttr(resId, defaultResId));
}
@Override
public InternalNode borderWidthAttr(
YogaEdge edge,
@AttrRes int resId) {
return borderWidthAttr(edge, resId, 0);
}
@Override
public InternalNode borderWidthRes(YogaEdge edge, @DimenRes int resId) {
return borderWidthPx(edge, mResourceResolver.resolveDimenOffsetRes(resId));
}
@Override
public InternalNode borderWidthDip(
YogaEdge edge,
@Dimension(unit = DP) int borderWidth) {
return borderWidthPx(edge, mResourceResolver.dipsToPixels(borderWidth));
}
@Override
public Builder borderColor(@ColorInt int borderColor) {
mPrivateFlags |= PFLAG_BORDER_COLOR_IS_SET;
mBorderColor = borderColor;
return this;
}
@Override
public InternalNode positionPx(YogaEdge edge, @Px int position) {
mPrivateFlags |= PFLAG_POSITION_IS_SET;
mYogaNode.setPosition(edge, position);
return this;
}
@Override
public InternalNode positionPercent(YogaEdge edge, float percent) {
mPrivateFlags |= PFLAG_POSITION_IS_SET;
mYogaNode.setPositionPercent(edge, percent);
return this;
}
@Override
public InternalNode positionAttr(
YogaEdge edge,
@AttrRes int resId,
@DimenRes int defaultResId) {
return positionPx(edge, mResourceResolver.resolveDimenOffsetAttr(resId, defaultResId));
}
@Override
public InternalNode positionAttr(YogaEdge edge, @AttrRes int resId) {
return positionAttr(edge, resId, 0);
}
@Override
public InternalNode positionRes(YogaEdge edge, @DimenRes int resId) {
return positionPx(edge, mResourceResolver.resolveDimenOffsetRes(resId));
}
@Override
public InternalNode positionDip(
YogaEdge edge,
@Dimension(unit = DP) int position) {
return positionPx(edge, mResourceResolver.dipsToPixels(position));
}
@Override
public InternalNode widthPx(@Px int width) {
mPrivateFlags |= PFLAG_WIDTH_IS_SET;
mYogaNode.setWidth(width);
return this;
}
@Override
public InternalNode widthPercent(float percent) {
mPrivateFlags |= PFLAG_WIDTH_IS_SET;
mYogaNode.setWidthPercent(percent);
return this;
}
@Override
public InternalNode widthRes(@DimenRes int resId) {
return widthPx(mResourceResolver.resolveDimenSizeRes(resId));
}
@Override
public InternalNode widthAttr(@AttrRes int resId, @DimenRes int defaultResId) {
return widthPx(mResourceResolver.resolveDimenSizeAttr(resId, defaultResId));
}
@Override
public InternalNode widthAttr(@AttrRes int resId) {
return widthAttr(resId, 0);
}
@Override
public InternalNode widthDip(@Dimension(unit = DP) int width) {
return widthPx(mResourceResolver.dipsToPixels(width));
}
@Override
public InternalNode minWidthPx(@Px int minWidth) {
mPrivateFlags |= PFLAG_MIN_WIDTH_IS_SET;
mYogaNode.setMinWidth(minWidth);
return this;
}
@Override
public InternalNode minWidthPercent(float percent) {
mPrivateFlags |= PFLAG_MIN_WIDTH_IS_SET;
mYogaNode.setMinWidthPercent(percent);
return this;
}
@Override
public InternalNode minWidthAttr(@AttrRes int resId, @DimenRes int defaultResId) {
return minWidthPx(mResourceResolver.resolveDimenSizeAttr(resId, defaultResId));
}
@Override
public InternalNode minWidthAttr(@AttrRes int resId) {
return minWidthAttr(resId, 0);
}
@Override
public InternalNode minWidthRes(@DimenRes int resId) {
return minWidthPx(mResourceResolver.resolveDimenSizeRes(resId));
}
@Override
public InternalNode minWidthDip(@Dimension(unit = DP) int minWidth) {
return minWidthPx(mResourceResolver.dipsToPixels(minWidth));
}
@Override
public InternalNode maxWidthPx(@Px int maxWidth) {
mPrivateFlags |= PFLAG_MAX_WIDTH_IS_SET;
mYogaNode.setMaxWidth(maxWidth);
return this;
}
@Override
public InternalNode maxWidthPercent(float percent) {
mPrivateFlags |= PFLAG_MAX_WIDTH_IS_SET;
mYogaNode.setMaxWidthPercent(percent);
return this;
}
@Override
public InternalNode maxWidthAttr(@AttrRes int resId, @DimenRes int defaultResId) {
return maxWidthPx(mResourceResolver.resolveDimenSizeAttr(resId, defaultResId));
}
@Override
public InternalNode maxWidthAttr(@AttrRes int resId) {
return maxWidthAttr(resId, 0);
}
@Override
public InternalNode maxWidthRes(@DimenRes int resId) {
return maxWidthPx(mResourceResolver.resolveDimenSizeRes(resId));
}
@Override
public InternalNode maxWidthDip(@Dimension(unit = DP) int maxWidth) {
return maxWidthPx(mResourceResolver.dipsToPixels(maxWidth));
}
@Override
public InternalNode heightPx(@Px int height) {
mPrivateFlags |= PFLAG_HEIGHT_IS_SET;
mYogaNode.setHeight(height);
return this;
}
@Override
public InternalNode heightPercent(float percent) {
mPrivateFlags |= PFLAG_HEIGHT_IS_SET;
mYogaNode.setHeightPercent(percent);
return this;
}
@Override
public InternalNode heightRes(@DimenRes int resId) {
return heightPx(mResourceResolver.resolveDimenSizeRes(resId));
}
@Override
public InternalNode heightAttr(@AttrRes int resId, @DimenRes int defaultResId) {
return heightPx(mResourceResolver.resolveDimenSizeAttr(resId, defaultResId));
}
@Override
public InternalNode heightAttr(@AttrRes int resId) {
return heightAttr(resId, 0);
}
@Override
public InternalNode heightDip(@Dimension(unit = DP) int height) {
return heightPx(mResourceResolver.dipsToPixels(height));
}
@Override
public InternalNode minHeightPx(@Px int minHeight) {
mPrivateFlags |= PFLAG_MIN_HEIGHT_IS_SET;
mYogaNode.setMinHeight(minHeight);
return this;
}
@Override
public InternalNode minHeightPercent(float percent) {
mPrivateFlags |= PFLAG_MIN_HEIGHT_IS_SET;
mYogaNode.setMinHeightPercent(percent);
return this;
}
@Override
public InternalNode minHeightAttr(@AttrRes int resId, @DimenRes int defaultResId) {
return minHeightPx(mResourceResolver.resolveDimenSizeAttr(resId, defaultResId));
}
@Override
public InternalNode minHeightAttr(@AttrRes int resId) {
return minHeightAttr(resId, 0);
}
@Override
public InternalNode minHeightRes(@DimenRes int resId) {
return minHeightPx(mResourceResolver.resolveDimenSizeRes(resId));
}
@Override
public InternalNode minHeightDip(@Dimension(unit = DP) int minHeight) {
return minHeightPx(mResourceResolver.dipsToPixels(minHeight));
}
@Override
public InternalNode maxHeightPx(@Px int maxHeight) {
mPrivateFlags |= PFLAG_MAX_HEIGHT_IS_SET;
mYogaNode.setMaxHeight(maxHeight);
return this;
}
@Override
public InternalNode maxHeightPercent(float percent) {
mPrivateFlags |= PFLAG_MAX_HEIGHT_IS_SET;
mYogaNode.setMaxHeightPercent(percent);
return this;
}
@Override
public InternalNode maxHeightAttr(@AttrRes int resId, @DimenRes int defaultResId) {
return maxHeightPx(mResourceResolver.resolveDimenSizeAttr(resId, defaultResId));
}
@Override
public InternalNode maxHeightAttr(@AttrRes int resId) {
return maxHeightAttr(resId, 0);
}
@Override
public InternalNode maxHeightRes(@DimenRes int resId) {
return maxHeightPx(mResourceResolver.resolveDimenSizeRes(resId));
}
@Override
public InternalNode maxHeightDip(@Dimension(unit = DP) int maxHeight) {
return maxHeightPx(mResourceResolver.dipsToPixels(maxHeight));
}
@Override
public InternalNode aspectRatio(float aspectRatio) {
mPrivateFlags |= PFLAG_ASPECT_RATIO_IS_SET;
if (mYogaNode instanceof YogaNode) {
((YogaNode) mYogaNode).setAspectRatio(aspectRatio);
return this;
} else {
throw new IllegalStateException("Aspect ration requires using YogaNode not YogaNodeDEPRECATED");
}
}
private boolean shouldApplyTouchExpansion() {
return mTouchExpansion != null && mNodeInfo != null && mNodeInfo.hasTouchEventHandlers();
}
boolean hasTouchExpansion() {
return ((mPrivateFlags & PFLAG_TOUCH_EXPANSION_IS_SET) != 0L);
}
Spacing getTouchExpansion() {
return mTouchExpansion;
}
int getTouchExpansionLeft() {
if (!shouldApplyTouchExpansion()) {
return 0;
}
if (YogaConstants.isUndefined(mResolvedTouchExpansionLeft)) {
mResolvedTouchExpansionLeft = resolveHorizontalSpacing(mTouchExpansion, Spacing.LEFT);
}
return FastMath.round(mResolvedTouchExpansionLeft);
}
int getTouchExpansionTop() {
if (!shouldApplyTouchExpansion()) {
return 0;
}
return FastMath.round(mTouchExpansion.get(Spacing.TOP));
}
int getTouchExpansionRight() {
if (!shouldApplyTouchExpansion()) {
return 0;
}
if (YogaConstants.isUndefined(mResolvedTouchExpansionRight)) {
mResolvedTouchExpansionRight = resolveHorizontalSpacing(mTouchExpansion, Spacing.RIGHT);
}
return FastMath.round(mResolvedTouchExpansionRight);
}
int getTouchExpansionBottom() {
if (!shouldApplyTouchExpansion()) {
return 0;
}
return FastMath.round(mTouchExpansion.get(Spacing.BOTTOM));
}
@Override
public InternalNode touchExpansionPx(YogaEdge edge, @Px int touchExpansion) {
if (mTouchExpansion == null) {
mTouchExpansion = ComponentsPools.acquireSpacing();
}
mPrivateFlags |= PFLAG_TOUCH_EXPANSION_IS_SET;
mTouchExpansion.set(edge.intValue(), touchExpansion);
return this;
}
@Override
public InternalNode touchExpansionAttr(
YogaEdge edge,
@AttrRes int resId,
@DimenRes int defaultResId) {
return touchExpansionPx(
edge,
mResourceResolver.resolveDimenOffsetAttr(resId, defaultResId));
}
@Override
public InternalNode touchExpansionAttr(
YogaEdge edge,
@AttrRes int resId) {
return touchExpansionAttr(edge, resId, 0);
}
@Override
public InternalNode touchExpansionRes(YogaEdge edge, @DimenRes int resId) {
return touchExpansionPx(edge, mResourceResolver.resolveDimenOffsetRes(resId));
}
@Override
public InternalNode touchExpansionDip(
YogaEdge edge,
@Dimension(unit = DP) int touchExpansion) {
return touchExpansionPx(edge, mResourceResolver.dipsToPixels(touchExpansion));
}
@Override
public InternalNode child(ComponentLayout child) {
if (child != null && child != NULL_LAYOUT) {
|
package com.facebook.litho;
import javax.annotation.Nullable;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.graphics.Rect;
import android.support.annotation.AttrRes;
import android.support.annotation.ColorInt;
import android.support.annotation.DimenRes;
import android.support.annotation.Dimension;
import android.support.annotation.DrawableRes;
import android.support.annotation.Px;
import android.support.annotation.StringRes;
import android.support.v4.view.ViewCompat;
import android.text.TextUtils;
import android.util.SparseArray;
import com.facebook.R;
import com.facebook.litho.config.ComponentsConfiguration;
import com.facebook.litho.reference.ColorDrawableReference;
import com.facebook.litho.reference.Reference;
import com.facebook.litho.reference.ResourceDrawableReference;
import com.facebook.infer.annotation.ThreadConfined;
import com.facebook.yoga.YogaAlign;
import com.facebook.yoga.YogaBaselineFunction;
import com.facebook.yoga.YogaFlexDirection;
import com.facebook.yoga.YogaJustify;
import com.facebook.yoga.YogaDirection;
import com.facebook.yoga.YogaPositionType;
import com.facebook.yoga.YogaWrap;
import com.facebook.yoga.YogaEdge;
import com.facebook.yoga.YogaConstants;
import com.facebook.yoga.YogaMeasureFunction;
import com.facebook.yoga.YogaNode;
import com.facebook.yoga.YogaNodeAPI;
import com.facebook.yoga.YogaOverflow;
import com.facebook.yoga.Spacing;
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;
import static android.os.Build.VERSION_CODES.JELLY_BEAN_MR1;
import static android.support.annotation.Dimension.DP;
import static com.facebook.litho.ComponentContext.NULL_LAYOUT;
import static com.facebook.yoga.YogaEdge.ALL;
import static com.facebook.yoga.YogaEdge.BOTTOM;
import static com.facebook.yoga.YogaEdge.END;
import static com.facebook.yoga.YogaEdge.HORIZONTAL;
import static com.facebook.yoga.YogaEdge.LEFT;
import static com.facebook.yoga.YogaEdge.RIGHT;
import static com.facebook.yoga.YogaEdge.START;
import static com.facebook.yoga.YogaEdge.TOP;
import static com.facebook.yoga.YogaEdge.VERTICAL;
/**
* Internal class representing both a {@link ComponentLayout} and a
* {@link com.facebook.litho.ComponentLayout.ContainerBuilder}.
*/
@ThreadConfined(ThreadConfined.ANY)
class InternalNode implements ComponentLayout, ComponentLayout.ContainerBuilder {
// Used to check whether or not the framework can use style IDs for
// paddingStart/paddingEnd due to a bug in some Android devices.
private static final boolean SUPPORTS_RTL = (SDK_INT >= JELLY_BEAN_MR1);
// When this flag is set, layoutDirection style was explicitly set on this node.
private static final long PFLAG_LAYOUT_DIRECTION_IS_SET = 1L << 0;
// When this flag is set, alignSelf was explicitly set on this node.
private static final long PFLAG_ALIGN_SELF_IS_SET = 1L << 1;
// When this flag is set, position type was explicitly set on this node.
private static final long PFLAG_POSITION_TYPE_IS_SET = 1L << 2;
// When this flag is set, flex was explicitly set on this node.
private static final long PFLAG_FLEX_IS_SET = 1L << 3;
// When this flag is set, flex grow was explicitly set on this node.
private static final long PFLAG_FLEX_GROW_IS_SET = 1L << 4;
// When this flag is set, flex shrink was explicitly set on this node.
private static final long PFLAG_FLEX_SHRINK_IS_SET = 1L << 5;
// When this flag is set, flex basis was explicitly set on this node.
private static final long PFLAG_FLEX_BASIS_IS_SET = 1L << 6;
// When this flag is set, importantForAccessibility was explicitly set on this node.
private static final long PFLAG_IMPORTANT_FOR_ACCESSIBILITY_IS_SET = 1L << 7;
// When this flag is set, duplicateParentState was explicitly set on this node.
private static final long PFLAG_DUPLICATE_PARENT_STATE_IS_SET = 1L << 8;
// When this flag is set, margin was explicitly set on this node.
private static final long PFLAG_MARGIN_IS_SET = 1L << 9;
// When this flag is set, padding was explicitly set on this node.
private static final long PFLAG_PADDING_IS_SET = 1L << 10;
// When this flag is set, position was explicitly set on this node.
private static final long PFLAG_POSITION_IS_SET = 1L << 11;
// When this flag is set, width was explicitly set on this node.
private static final long PFLAG_WIDTH_IS_SET = 1L << 12;
// When this flag is set, minWidth was explicitly set on this node.
private static final long PFLAG_MIN_WIDTH_IS_SET = 1L << 13;
// When this flag is set, maxWidth was explicitly set on this node.
private static final long PFLAG_MAX_WIDTH_IS_SET = 1L << 14;
// When this flag is set, height was explicitly set on this node.
private static final long PFLAG_HEIGHT_IS_SET = 1L << 15;
// When this flag is set, minHeight was explicitly set on this node.
private static final long PFLAG_MIN_HEIGHT_IS_SET = 1L << 16;
// When this flag is set, maxHeight was explicitly set on this node.
private static final long PFLAG_MAX_HEIGHT_IS_SET = 1L << 17;
// When this flag is set, background was explicitly set on this node.
private static final long PFLAG_BACKGROUND_IS_SET = 1L << 18;
// When this flag is set, foreground was explicitly set on this node.
private static final long PFLAG_FOREGROUND_IS_SET = 1L << 19;
// When this flag is set, visibleHandler was explicitly set on this node.
private static final long PFLAG_VISIBLE_HANDLER_IS_SET = 1L << 20;
// When this flag is set, focusedHandler was explicitly set on this node.
private static final long PFLAG_FOCUSED_HANDLER_IS_SET = 1L << 21;
// When this flag is set, fullImpressionHandler was explicitly set on this node.
private static final long PFLAG_FULL_IMPRESSION_HANDLER_IS_SET = 1L << 22;
// When this flag is set, invisibleHandler was explicitly set on this node.
private static final long PFLAG_INVISIBLE_HANDLER_IS_SET = 1L << 23;
// When this flag is set, touch expansion was explicitly set on this node.
private static final long PFLAG_TOUCH_EXPANSION_IS_SET = 1L << 24;
// When this flag is set, border width was explicitly set on this node.
private static final long PFLAG_BORDER_WIDTH_IS_SET = 1L << 25;
// When this flag is set, aspectRatio was explicitly set on this node.
private static final long PFLAG_ASPECT_RATIO_IS_SET = 1L << 26;
// When this flag is set, transitionKey was explicitly set on this node.
private static final long PFLAG_TRANSITION_KEY_IS_SET = 1L << 27;
// When this flag is set, border color was explicitly set on this node.
private static final long PFLAG_BORDER_COLOR_IS_SET = 1L << 28;
private final ResourceResolver mResourceResolver = new ResourceResolver();
YogaNodeAPI mYogaNode;
private ComponentContext mComponentContext;
private Resources mResources;
private Component mComponent;
private int mImportantForAccessibility = ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_AUTO;
private boolean mDuplicateParentState;
private boolean mIsNestedTreeHolder;
private InternalNode mNestedTree;
private InternalNode mNestedTreeHolder;
private long mPrivateFlags;
private Reference<? extends Drawable> mBackground;
private Reference<? extends Drawable> mForeground;
private int mBorderColor = Color.TRANSPARENT;
private NodeInfo mNodeInfo;
private boolean mForceViewWrapping;
private String mTransitionKey;
private EventHandler mVisibleHandler;
private EventHandler mFocusedHandler;
private EventHandler mFullImpressionHandler;
private EventHandler mInvisibleHandler;
private String mTestKey;
private Spacing mTouchExpansion;
private Spacing mNestedTreePadding;
private Spacing mNestedTreeBorderWidth;
private boolean[] mIsPaddingPercent;
private float mResolvedTouchExpansionLeft = YogaConstants.UNDEFINED;
private float mResolvedTouchExpansionRight = YogaConstants.UNDEFINED;
private float mResolvedX = YogaConstants.UNDEFINED;
private float mResolvedY = YogaConstants.UNDEFINED;
private float mResolvedWidth = YogaConstants.UNDEFINED;
private float mResolvedHeight = YogaConstants.UNDEFINED;
private int mLastWidthSpec = DiffNode.UNSPECIFIED;
private int mLastHeightSpec = DiffNode.UNSPECIFIED;
private float mLastMeasuredWidth = DiffNode.UNSPECIFIED;
private float mLastMeasuredHeight = DiffNode.UNSPECIFIED;
private DiffNode mDiffNode;
private boolean mCachedMeasuresValid;
private TreeProps mPendingTreeProps;
void init(YogaNodeAPI yogaNode, ComponentContext componentContext, Resources resources) {
yogaNode.setData(this);
yogaNode.setOverflow(YogaOverflow.HIDDEN);
yogaNode.setMeasureFunction(null);
// YogaNode is the only version of YogaNodeAPI with this support;
if (yogaNode instanceof YogaNode) {
yogaNode.setBaselineFunction(null);
}
mYogaNode = yogaNode;
mComponentContext = componentContext;
mResources = resources;
mResourceResolver.init(
mComponentContext,
componentContext.getResourceCache());
}
@Px
@Override
public int getX() {
if (YogaConstants.isUndefined(mResolvedX)) {
mResolvedX = mYogaNode.getLayoutX();
}
return (int) mResolvedX;
}
@Px
@Override
public int getY() {
if (YogaConstants.isUndefined(mResolvedY)) {
mResolvedY = mYogaNode.getLayoutY();
}
return (int) mResolvedY;
}
@Px
@Override
public int getWidth() {
if (YogaConstants.isUndefined(mResolvedWidth)) {
mResolvedWidth = mYogaNode.getLayoutWidth();
}
return (int) mResolvedWidth;
}
@Px
@Override
public int getHeight() {
if (YogaConstants.isUndefined(mResolvedHeight)) {
mResolvedHeight = mYogaNode.getLayoutHeight();
}
return (int) mResolvedHeight;
}
@Px
@Override
public int getPaddingLeft() {
return FastMath.round(mYogaNode.getLayoutPadding(LEFT));
}
@Px
@Override
public int getPaddingTop() {
return FastMath.round(mYogaNode.getLayoutPadding(TOP));
}
@Px
@Override
public int getPaddingRight() {
return FastMath.round(mYogaNode.getLayoutPadding(RIGHT));
}
@Px
@Override
public int getPaddingBottom() {
return FastMath.round(mYogaNode.getLayoutPadding(BOTTOM));
}
public Reference<? extends Drawable> getBackground() {
return mBackground;
}
public Reference<? extends Drawable> getForeground() {
return mForeground;
}
public void setCachedMeasuresValid(boolean valid) {
mCachedMeasuresValid = valid;
}
public int getLastWidthSpec() {
return mLastWidthSpec;
}
public void setLastWidthSpec(int widthSpec) {
mLastWidthSpec = widthSpec;
}
public int getLastHeightSpec() {
return mLastHeightSpec;
}
public void setLastHeightSpec(int heightSpec) {
mLastHeightSpec = heightSpec;
}
public boolean hasVisibilityHandlers() {
return mVisibleHandler != null
|| mFocusedHandler != null
|| mFullImpressionHandler != null
|| mInvisibleHandler != null;
}
/**
* The last value the measure funcion associated with this node {@link Component} returned
* for the width. This is used together with {@link InternalNode#getLastWidthSpec()}
* to implement measure caching.
*/
float getLastMeasuredWidth() {
return mLastMeasuredWidth;
}
/**
* Sets the last value the measure funcion associated with this node {@link Component} returned
* for the width.
*/
void setLastMeasuredWidth(float lastMeasuredWidth) {
mLastMeasuredWidth = lastMeasuredWidth;
}
/**
* The last value the measure funcion associated with this node {@link Component} returned
* for the height. This is used together with {@link InternalNode#getLastHeightSpec()}
* to implement measure caching.
*/
float getLastMeasuredHeight() {
return mLastMeasuredHeight;
}
/**
* Sets the last value the measure funcion associated with this node {@link Component} returned
* for the height.
*/
void setLastMeasuredHeight(float lastMeasuredHeight) {
mLastMeasuredHeight = lastMeasuredHeight;
}
DiffNode getDiffNode() {
return mDiffNode;
}
boolean areCachedMeasuresValid() {
return mCachedMeasuresValid;
}
void setDiffNode(DiffNode diffNode) {
mDiffNode = diffNode;
}
/**
* Mark this node as a nested tree root holder.
*/
void markIsNestedTreeHolder(TreeProps currentTreeProps) {
mIsNestedTreeHolder = true;
mPendingTreeProps = TreeProps.copy(currentTreeProps);
}
/**
* @return Whether this node is holding a nested tree or not. The decision was made during
* tree creation {@link ComponentLifecycle#createLayout(ComponentContext, Component, boolean)}.
*/
boolean isNestedTreeHolder() {
return mIsNestedTreeHolder;
}
@Override
public YogaDirection getResolvedLayoutDirection() {
return mYogaNode.getLayoutDirection();
}
@Override
public InternalNode layoutDirection(YogaDirection direction) {
mPrivateFlags |= PFLAG_LAYOUT_DIRECTION_IS_SET;
mYogaNode.setDirection(direction);
return this;
}
@Override
public InternalNode flexDirection(YogaFlexDirection direction) {
mYogaNode.setFlexDirection(direction);
return this;
}
@Override
public InternalNode wrap(YogaWrap wrap) {
mYogaNode.setWrap(wrap);
return this;
}
@Override
public InternalNode justifyContent(YogaJustify justifyContent) {
mYogaNode.setJustifyContent(justifyContent);
return this;
}
@Override
public InternalNode alignItems(YogaAlign alignItems) {
mYogaNode.setAlignItems(alignItems);
return this;
}
@Override
public InternalNode alignContent(YogaAlign alignContent) {
mYogaNode.setAlignContent(alignContent);
return this;
}
@Override
public InternalNode alignSelf(YogaAlign alignSelf) {
mPrivateFlags |= PFLAG_ALIGN_SELF_IS_SET;
mYogaNode.setAlignSelf(alignSelf);
return this;
}
@Override
public InternalNode positionType(YogaPositionType positionType) {
mPrivateFlags |= PFLAG_POSITION_TYPE_IS_SET;
mYogaNode.setPositionType(positionType);
return this;
}
@Override
public InternalNode flex(float flex) {
mPrivateFlags |= PFLAG_FLEX_IS_SET;
mYogaNode.setFlex(flex);
return this;
}
@Override
public InternalNode flexGrow(float flexGrow) {
mPrivateFlags |= PFLAG_FLEX_GROW_IS_SET;
mYogaNode.setFlexGrow(flexGrow);
return this;
}
@Override
public InternalNode flexShrink(float flexShrink) {
mPrivateFlags |= PFLAG_FLEX_SHRINK_IS_SET;
mYogaNode.setFlexShrink(flexShrink);
return this;
}
@Override
public InternalNode flexBasisPx(@Px int flexBasis) {
mPrivateFlags |= PFLAG_FLEX_BASIS_IS_SET;
mYogaNode.setFlexBasis(flexBasis);
return this;
}
@Override
public InternalNode flexBasisPercent(float percent) {
mPrivateFlags |= PFLAG_FLEX_BASIS_IS_SET;
mYogaNode.setFlexBasisPercent(percent);
return this;
}
@Override
public InternalNode flexBasisAttr(@AttrRes int resId, @DimenRes int defaultResId) {
return flexBasisPx(mResourceResolver.resolveDimenOffsetAttr(resId, defaultResId));
}
@Override
public InternalNode flexBasisAttr(@AttrRes int resId) {
return flexBasisAttr(resId, 0);
}
@Override
public InternalNode flexBasisRes(@DimenRes int resId) {
return flexBasisPx(mResourceResolver.resolveDimenOffsetRes(resId));
}
@Override
public InternalNode flexBasisDip(@Dimension(unit = DP) int flexBasis) {
return flexBasisPx(mResourceResolver.dipsToPixels(flexBasis));
}
@Override
public InternalNode importantForAccessibility(int importantForAccessibility) {
mPrivateFlags |= PFLAG_IMPORTANT_FOR_ACCESSIBILITY_IS_SET;
mImportantForAccessibility = importantForAccessibility;
return this;
}
@Override
public InternalNode duplicateParentState(boolean duplicateParentState) {
mPrivateFlags |= PFLAG_DUPLICATE_PARENT_STATE_IS_SET;
mDuplicateParentState = duplicateParentState;
return this;
}
@Override
public InternalNode marginPx(YogaEdge edge, @Px int margin) {
mPrivateFlags |= PFLAG_MARGIN_IS_SET;
mYogaNode.setMargin(edge, margin);
return this;
}
@Override
public InternalNode marginPercent(YogaEdge edge, float percent) {
mPrivateFlags |= PFLAG_MARGIN_IS_SET;
mYogaNode.setMarginPercent(edge, percent);
return this;
}
@Override
public InternalNode marginAuto(YogaEdge edge) {
mPrivateFlags |= PFLAG_MARGIN_IS_SET;
mYogaNode.setMarginAuto(edge);
return this;
}
@Override
public InternalNode marginAttr(
YogaEdge edge,
@AttrRes int resId,
@DimenRes int defaultResId) {
return marginPx(edge, mResourceResolver.resolveDimenOffsetAttr(resId, defaultResId));
}
@Override
public InternalNode marginAttr(
YogaEdge edge,
@AttrRes int resId) {
return marginAttr(edge, resId, 0);
}
@Override
public InternalNode marginRes(YogaEdge edge, @DimenRes int resId) {
return marginPx(edge, mResourceResolver.resolveDimenOffsetRes(resId));
}
@Override
public InternalNode marginDip(YogaEdge edge, @Dimension(unit = DP) int margin) {
return marginPx(edge, mResourceResolver.dipsToPixels(margin));
}
@Override
public InternalNode paddingPx(YogaEdge edge, @Px int padding) {
mPrivateFlags |= PFLAG_PADDING_IS_SET;
if (mIsNestedTreeHolder) {
if (mNestedTreePadding == null) {
mNestedTreePadding = ComponentsPools.acquireSpacing();
}
mNestedTreePadding.set(edge.intValue(), padding);
setIsPaddingPercent(edge, false);
} else {
mYogaNode.setPadding(edge, padding);
}
return this;
}
@Override
public InternalNode paddingPercent(YogaEdge edge, float percent) {
mPrivateFlags |= PFLAG_PADDING_IS_SET;
if (mIsNestedTreeHolder) {
if (mNestedTreePadding == null) {
mNestedTreePadding = ComponentsPools.acquireSpacing();
}
mNestedTreePadding.set(edge.intValue(), percent);
setIsPaddingPercent(edge, true);
} else {
mYogaNode.setPaddingPercent(edge, percent);
}
return this;
}
@Override
public InternalNode paddingAttr(
YogaEdge edge,
@AttrRes int resId,
@DimenRes int defaultResId) {
return paddingPx(edge, mResourceResolver.resolveDimenOffsetAttr(resId, defaultResId));
}
@Override
public InternalNode paddingAttr(
YogaEdge edge,
@AttrRes int resId) {
return paddingAttr(edge, resId, 0);
}
@Override
public InternalNode paddingRes(YogaEdge edge, @DimenRes int resId) {
return paddingPx(edge, mResourceResolver.resolveDimenOffsetRes(resId));
}
@Override
public InternalNode paddingDip(YogaEdge edge, @Dimension(unit = DP) int padding) {
return paddingPx(edge, mResourceResolver.dipsToPixels(padding));
}
@Override
public InternalNode borderWidthPx(YogaEdge edge, @Px int borderWidth) {
mPrivateFlags |= PFLAG_BORDER_WIDTH_IS_SET;
if (mIsNestedTreeHolder) {
if (mNestedTreeBorderWidth == null) {
mNestedTreeBorderWidth = ComponentsPools.acquireSpacing();
}
mNestedTreeBorderWidth.set(edge.intValue(), borderWidth);
} else {
mYogaNode.setBorder(edge, borderWidth);
}
return this;
}
@Override
public InternalNode borderWidthAttr(
YogaEdge edge,
@AttrRes int resId,
@DimenRes int defaultResId) {
return borderWidthPx(edge, mResourceResolver.resolveDimenOffsetAttr(resId, defaultResId));
}
@Override
public InternalNode borderWidthAttr(
YogaEdge edge,
@AttrRes int resId) {
return borderWidthAttr(edge, resId, 0);
}
@Override
public InternalNode borderWidthRes(YogaEdge edge, @DimenRes int resId) {
return borderWidthPx(edge, mResourceResolver.resolveDimenOffsetRes(resId));
}
@Override
public InternalNode borderWidthDip(
YogaEdge edge,
@Dimension(unit = DP) int borderWidth) {
return borderWidthPx(edge, mResourceResolver.dipsToPixels(borderWidth));
}
@Override
public Builder borderColor(@ColorInt int borderColor) {
mPrivateFlags |= PFLAG_BORDER_COLOR_IS_SET;
mBorderColor = borderColor;
return this;
}
@Override
public InternalNode positionPx(YogaEdge edge, @Px int position) {
mPrivateFlags |= PFLAG_POSITION_IS_SET;
mYogaNode.setPosition(edge, position);
return this;
}
@Override
public InternalNode positionPercent(YogaEdge edge, float percent) {
mPrivateFlags |= PFLAG_POSITION_IS_SET;
mYogaNode.setPositionPercent(edge, percent);
return this;
}
@Override
public InternalNode positionAttr(
YogaEdge edge,
@AttrRes int resId,
@DimenRes int defaultResId) {
return positionPx(edge, mResourceResolver.resolveDimenOffsetAttr(resId, defaultResId));
}
@Override
public InternalNode positionAttr(YogaEdge edge, @AttrRes int resId) {
return positionAttr(edge, resId, 0);
}
@Override
public InternalNode positionRes(YogaEdge edge, @DimenRes int resId) {
return positionPx(edge, mResourceResolver.resolveDimenOffsetRes(resId));
}
@Override
public InternalNode positionDip(
YogaEdge edge,
@Dimension(unit = DP) int position) {
return positionPx(edge, mResourceResolver.dipsToPixels(position));
}
@Override
public InternalNode widthPx(@Px int width) {
mPrivateFlags |= PFLAG_WIDTH_IS_SET;
mYogaNode.setWidth(width);
return this;
}
@Override
public InternalNode widthPercent(float percent) {
mPrivateFlags |= PFLAG_WIDTH_IS_SET;
mYogaNode.setWidthPercent(percent);
return this;
}
@Override
public InternalNode widthRes(@DimenRes int resId) {
return widthPx(mResourceResolver.resolveDimenSizeRes(resId));
}
@Override
public InternalNode widthAttr(@AttrRes int resId, @DimenRes int defaultResId) {
return widthPx(mResourceResolver.resolveDimenSizeAttr(resId, defaultResId));
}
@Override
public InternalNode widthAttr(@AttrRes int resId) {
return widthAttr(resId, 0);
}
@Override
public InternalNode widthDip(@Dimension(unit = DP) int width) {
return widthPx(mResourceResolver.dipsToPixels(width));
}
@Override
public InternalNode minWidthPx(@Px int minWidth) {
mPrivateFlags |= PFLAG_MIN_WIDTH_IS_SET;
mYogaNode.setMinWidth(minWidth);
return this;
}
@Override
public InternalNode minWidthPercent(float percent) {
mPrivateFlags |= PFLAG_MIN_WIDTH_IS_SET;
mYogaNode.setMinWidthPercent(percent);
return this;
}
@Override
public InternalNode minWidthAttr(@AttrRes int resId, @DimenRes int defaultResId) {
return minWidthPx(mResourceResolver.resolveDimenSizeAttr(resId, defaultResId));
}
@Override
public InternalNode minWidthAttr(@AttrRes int resId) {
return minWidthAttr(resId, 0);
}
@Override
public InternalNode minWidthRes(@DimenRes int resId) {
return minWidthPx(mResourceResolver.resolveDimenSizeRes(resId));
}
@Override
public InternalNode minWidthDip(@Dimension(unit = DP) int minWidth) {
return minWidthPx(mResourceResolver.dipsToPixels(minWidth));
}
@Override
public InternalNode maxWidthPx(@Px int maxWidth) {
mPrivateFlags |= PFLAG_MAX_WIDTH_IS_SET;
mYogaNode.setMaxWidth(maxWidth);
return this;
}
@Override
public InternalNode maxWidthPercent(float percent) {
mPrivateFlags |= PFLAG_MAX_WIDTH_IS_SET;
mYogaNode.setMaxWidthPercent(percent);
return this;
}
@Override
public InternalNode maxWidthAttr(@AttrRes int resId, @DimenRes int defaultResId) {
return maxWidthPx(mResourceResolver.resolveDimenSizeAttr(resId, defaultResId));
}
@Override
public InternalNode maxWidthAttr(@AttrRes int resId) {
return maxWidthAttr(resId, 0);
}
@Override
public InternalNode maxWidthRes(@DimenRes int resId) {
return maxWidthPx(mResourceResolver.resolveDimenSizeRes(resId));
}
@Override
public InternalNode maxWidthDip(@Dimension(unit = DP) int maxWidth) {
return maxWidthPx(mResourceResolver.dipsToPixels(maxWidth));
}
@Override
public InternalNode heightPx(@Px int height) {
mPrivateFlags |= PFLAG_HEIGHT_IS_SET;
mYogaNode.setHeight(height);
return this;
}
@Override
public InternalNode heightPercent(float percent) {
mPrivateFlags |= PFLAG_HEIGHT_IS_SET;
mYogaNode.setHeightPercent(percent);
return this;
}
@Override
public InternalNode heightRes(@DimenRes int resId) {
return heightPx(mResourceResolver.resolveDimenSizeRes(resId));
}
@Override
public InternalNode heightAttr(@AttrRes int resId, @DimenRes int defaultResId) {
return heightPx(mResourceResolver.resolveDimenSizeAttr(resId, defaultResId));
}
@Override
public InternalNode heightAttr(@AttrRes int resId) {
return heightAttr(resId, 0);
}
@Override
public InternalNode heightDip(@Dimension(unit = DP) int height) {
return heightPx(mResourceResolver.dipsToPixels(height));
}
@Override
public InternalNode minHeightPx(@Px int minHeight) {
mPrivateFlags |= PFLAG_MIN_HEIGHT_IS_SET;
mYogaNode.setMinHeight(minHeight);
return this;
}
@Override
public InternalNode minHeightPercent(float percent) {
mPrivateFlags |= PFLAG_MIN_HEIGHT_IS_SET;
mYogaNode.setMinHeightPercent(percent);
return this;
}
@Override
public InternalNode minHeightAttr(@AttrRes int resId, @DimenRes int defaultResId) {
return minHeightPx(mResourceResolver.resolveDimenSizeAttr(resId, defaultResId));
}
@Override
public InternalNode minHeightAttr(@AttrRes int resId) {
return minHeightAttr(resId, 0);
}
@Override
public InternalNode minHeightRes(@DimenRes int resId) {
return minHeightPx(mResourceResolver.resolveDimenSizeRes(resId));
}
@Override
public InternalNode minHeightDip(@Dimension(unit = DP) int minHeight) {
return minHeightPx(mResourceResolver.dipsToPixels(minHeight));
}
@Override
public InternalNode maxHeightPx(@Px int maxHeight) {
mPrivateFlags |= PFLAG_MAX_HEIGHT_IS_SET;
mYogaNode.setMaxHeight(maxHeight);
return this;
}
@Override
public InternalNode maxHeightPercent(float percent) {
mPrivateFlags |= PFLAG_MAX_HEIGHT_IS_SET;
mYogaNode.setMaxHeightPercent(percent);
return this;
}
@Override
public InternalNode maxHeightAttr(@AttrRes int resId, @DimenRes int defaultResId) {
return maxHeightPx(mResourceResolver.resolveDimenSizeAttr(resId, defaultResId));
}
@Override
public InternalNode maxHeightAttr(@AttrRes int resId) {
return maxHeightAttr(resId, 0);
}
@Override
public InternalNode maxHeightRes(@DimenRes int resId) {
return maxHeightPx(mResourceResolver.resolveDimenSizeRes(resId));
}
@Override
public InternalNode maxHeightDip(@Dimension(unit = DP) int maxHeight) {
return maxHeightPx(mResourceResolver.dipsToPixels(maxHeight));
}
@Override
public InternalNode aspectRatio(float aspectRatio) {
mPrivateFlags |= PFLAG_ASPECT_RATIO_IS_SET;
if (mYogaNode instanceof YogaNode) {
((YogaNode) mYogaNode).setAspectRatio(aspectRatio);
return this;
} else {
throw new IllegalStateException("Aspect ration requires using YogaNode not YogaNodeDEPRECATED");
}
}
private boolean shouldApplyTouchExpansion() {
return mTouchExpansion != null && mNodeInfo != null && mNodeInfo.hasTouchEventHandlers();
}
boolean hasTouchExpansion() {
return ((mPrivateFlags & PFLAG_TOUCH_EXPANSION_IS_SET) != 0L);
}
Spacing getTouchExpansion() {
return mTouchExpansion;
}
int getTouchExpansionLeft() {
if (!shouldApplyTouchExpansion()) {
return 0;
}
if (YogaConstants.isUndefined(mResolvedTouchExpansionLeft)) {
mResolvedTouchExpansionLeft = resolveHorizontalSpacing(mTouchExpansion, Spacing.LEFT);
}
return FastMath.round(mResolvedTouchExpansionLeft);
}
int getTouchExpansionTop() {
if (!shouldApplyTouchExpansion()) {
return 0;
}
return FastMath.round(mTouchExpansion.get(Spacing.TOP));
}
int getTouchExpansionRight() {
if (!shouldApplyTouchExpansion()) {
return 0;
}
if (YogaConstants.isUndefined(mResolvedTouchExpansionRight)) {
mResolvedTouchExpansionRight = resolveHorizontalSpacing(mTouchExpansion, Spacing.RIGHT);
}
return FastMath.round(mResolvedTouchExpansionRight);
}
int getTouchExpansionBottom() {
if (!shouldApplyTouchExpansion()) {
return 0;
}
return FastMath.round(mTouchExpansion.get(Spacing.BOTTOM));
}
@Override
public InternalNode touchExpansionPx(YogaEdge edge, @Px int touchExpansion) {
if (mTouchExpansion == null) {
mTouchExpansion = ComponentsPools.acquireSpacing();
}
mPrivateFlags |= PFLAG_TOUCH_EXPANSION_IS_SET;
mTouchExpansion.set(edge.intValue(), touchExpansion);
return this;
}
@Override
public InternalNode touchExpansionAttr(
YogaEdge edge,
@AttrRes int resId,
@DimenRes int defaultResId) {
return touchExpansionPx(
edge,
mResourceResolver.resolveDimenOffsetAttr(resId, defaultResId));
}
@Override
public InternalNode touchExpansionAttr(
YogaEdge edge,
@AttrRes int resId) {
return touchExpansionAttr(edge, resId, 0);
}
@Override
public InternalNode touchExpansionRes(YogaEdge edge, @DimenRes int resId) {
return touchExpansionPx(edge, mResourceResolver.resolveDimenOffsetRes(resId));
}
@Override
public InternalNode touchExpansionDip(
YogaEdge edge,
@Dimension(unit = DP) int touchExpansion) {
return touchExpansionPx(edge, mResourceResolver.dipsToPixels(touchExpansion));
}
@Override
public InternalNode child(ComponentLayout child) {
if (child != null && child != NULL_LAYOUT) {
addChildAt((InternalNode) child, mYogaNode.getChildCount());
}
return this;
}
@Override
public InternalNode child(ComponentLayout.Builder child) {
if (child != null && child != NULL_LAYOUT) {
child(child.build());
}
return this;
}
@Override
public InternalNode child(Component<?> child) {
if (child != null) {
child(Layout.create(mComponentContext, child).flexShrink(0).flexShrink(0).flexShrink(0));
}
return this;
}
@Override
public InternalNode child(Component.Builder<?> child) {
if (child != null) {
child(child.build());
}
return this;
}
@Override
public InternalNode background(Reference<? extends Drawable> background) {
mPrivateFlags |= PFLAG_BACKGROUND_IS_SET;
mBackground = background;
setPaddingFromDrawableReference(background);
return this;
}
@Override
public InternalNode background(Reference.Builder<? extends Drawable> builder) {
return background(builder.build());
}
@Override
public InternalNode backgroundAttr(@AttrRes int resId, @DrawableRes int defaultResId) {
return backgroundRes(mResourceResolver.resolveResIdAttr(resId, defaultResId));
}
@Override
public InternalNode backgroundAttr(@AttrRes int resId) {
return backgroundAttr(resId, 0);
}
@Override
public InternalNode backgroundRes(@DrawableRes int resId) {
if (resId == 0) {
return background((Reference<Drawable>) null);
}
return background(
ResourceDrawableReference.create(mComponentContext)
.resId(resId)
.build());
}
@Override
public InternalNode backgroundColor(@ColorInt int backgroundColor) {
return background(
ColorDrawableReference.create(mComponentContext)
.color(backgroundColor)
.build());
}
@Override
public InternalNode foreground(Reference<? extends Drawable> foreground) {
mPrivateFlags |= PFLAG_FOREGROUND_IS_SET;
mForeground = foreground;
return this;
}
@Override
public InternalNode foreground(Reference.Builder<? extends Drawable> builder) {
return foreground(builder.build());
}
@Override
public InternalNode foregroundAttr(@AttrRes int resId, @DrawableRes int defaultResId) {
return foregroundRes(mResourceResolver.resolveResIdAttr(resId, defaultResId));
}
@Override
public InternalNode foregroundAttr(@AttrRes int resId) {
return foregroundAttr(resId, 0);
}
@Override
public InternalNode foregroundRes(@DrawableRes int resId) {
if (resId == 0) {
return foreground((Reference<Drawable>) null);
}
return foreground(
ResourceDrawableReference.create(mComponentContext)
.resId(resId)
.build());
}
@Override
public InternalNode foregroundColor(@ColorInt int foregroundColor) {
return foreground(
ColorDrawableReference.create(mComponentContext)
.color(foregroundColor)
.build());
}
@Override
public InternalNode wrapInView() {
mForceViewWrapping = true;
return this;
}
boolean isForceViewWrapping() {
return mForceViewWrapping;
}
@Override
public InternalNode clickHandler(EventHandler clickHandler) {
getOrCreateNodeInfo().setClickHandler(clickHandler);
return this;
}
@Override
public InternalNode longClickHandler(EventHandler longClickHandler) {
getOrCreateNodeInfo().setLongClickHandler(longClickHandler);
return this;
}
@Override
public InternalNode touchHandler(EventHandler touchHandler) {
getOrCreateNodeInfo().setTouchHandler(touchHandler);
return this;
}
@Override
public ContainerBuilder focusable(boolean isFocusable) {
getOrCreateNodeInfo().setFocusable(isFocusable);
return this;
}
@Override
public InternalNode visibleHandler(EventHandler visibleHandler) {
mPrivateFlags |= PFLAG_VISIBLE_HANDLER_IS_SET;
mVisibleHandler = visibleHandler;
return this;
}
EventHandler getVisibleHandler() {
return mVisibleHandler;
}
@Override
public InternalNode focusedHandler(EventHandler focusedHandler) {
mPrivateFlags |= PFLAG_FOCUSED_HANDLER_IS_SET;
mFocusedHandler = focusedHandler;
return this;
}
EventHandler getFocusedHandler() {
return mFocusedHandler;
}
@Override
public InternalNode fullImpressionHandler(EventHandler fullImpressionHandler) {
mPrivateFlags |= PFLAG_FULL_IMPRESSION_HANDLER_IS_SET;
mFullImpressionHandler = fullImpressionHandler;
return this;
}
EventHandler getFullImpressionHandler() {
return mFullImpressionHandler;
}
@Override
public InternalNode invisibleHandler(EventHandler invisibleHandler) {
mPrivateFlags |= PFLAG_INVISIBLE_HANDLER_IS_SET;
mInvisibleHandler = invisibleHandler;
return this;
}
EventHandler getInvisibleHandler() {
return mInvisibleHandler;
}
@Override
public InternalNode contentDescription(CharSequence contentDescription) {
getOrCreateNodeInfo().setContentDescription(contentDescription);
return this;
}
@Override
public InternalNode contentDescription(@StringRes int stringId) {
return contentDescription(mResources.getString(stringId));
}
@Override
public InternalNode contentDescription(@StringRes int stringId, Object... formatArgs) {
return contentDescription(mResources.getString(stringId, formatArgs));
}
@Override
public InternalNode viewTag(Object viewTag) {
getOrCreateNodeInfo().setViewTag(viewTag);
return this;
}
@Override
public InternalNode viewTags(SparseArray<Object> viewTags) {
getOrCreateNodeInfo().setViewTags(viewTags);
return this;
}
@Override
public InternalNode testKey(String testKey) {
mTestKey = testKey;
return this;
}
@Override
public InternalNode dispatchPopulateAccessibilityEventHandler(
EventHandler<DispatchPopulateAccessibilityEventEvent>
dispatchPopulateAccessibilityEventHandler) {
getOrCreateNodeInfo().setDispatchPopulateAccessibilityEventHandler(
dispatchPopulateAccessibilityEventHandler);
return this;
}
@Override
public InternalNode onInitializeAccessibilityEventHandler(
EventHandler<OnInitializeAccessibilityEventEvent> onInitializeAccessibilityEventHandler) {
getOrCreateNodeInfo().setOnInitializeAccessibilityEventHandler(
onInitializeAccessibilityEventHandler);
return this;
}
@Override
public InternalNode onInitializeAccessibilityNodeInfoHandler(
EventHandler<OnInitializeAccessibilityNodeInfoEvent>
onInitializeAccessibilityNodeInfoHandler) {
getOrCreateNodeInfo().setOnInitializeAccessibilityNodeInfoHandler(
onInitializeAccessibilityNodeInfoHandler);
return this;
}
@Override
public InternalNode onPopulateAccessibilityEventHandler(
EventHandler<OnPopulateAccessibilityEventEvent> onPopulateAccessibilityEventHandler) {
getOrCreateNodeInfo().setOnPopulateAccessibilityEventHandler(
onPopulateAccessibilityEventHandler);
return this;
}
@Override
public InternalNode onRequestSendAccessibilityEventHandler(
EventHandler<OnRequestSendAccessibilityEventEvent> onRequestSendAccessibilityEventHandler) {
getOrCreateNodeInfo().setOnRequestSendAccessibilityEventHandler(
onRequestSendAccessibilityEventHandler);
return this;
}
@Override
public InternalNode performAccessibilityActionHandler(
EventHandler<PerformAccessibilityActionEvent> performAccessibilityActionHandler) {
getOrCreateNodeInfo().setPerformAccessibilityActionHandler(performAccessibilityActionHandler);
return this;
}
@Override
public InternalNode sendAccessibilityEventHandler(
EventHandler<SendAccessibilityEventEvent> sendAccessibilityEventHandler) {
getOrCreateNodeInfo().setSendAccessibilityEventHandler(sendAccessibilityEventHandler);
return this;
}
@Override
public InternalNode sendAccessibilityEventUncheckedHandler(
EventHandler<SendAccessibilityEventUncheckedEvent> sendAccessibilityEventUncheckedHandler) {
getOrCreateNodeInfo().setSendAccessibilityEventUncheckedHandler(
sendAccessibilityEventUncheckedHandler);
return this;
}
@Override
public ContainerBuilder transitionKey(String key) {
if (SDK_INT >= ICE_CREAM_SANDWICH) {
mPrivateFlags |= PFLAG_TRANSITION_KEY_IS_SET;
mTransitionKey = key;
wrapInView();
}
return this;
}
String getTransitionKey() {
return mTransitionKey;
}
/**
* A unique identifier which may be set for retrieving a component and its bounds when testing.
*/
String getTestKey() {
return mTestKey;
}
void setMeasureFunction(YogaMeasureFunction measureFunction) {
mYogaNode.setMeasureFunction(measureFunction);
}
void setBaselineFunction(YogaBaselineFunction baselineFunction) {
// YogaNode is the only version of YogaNodeAPI with this support;
if (mYogaNode instanceof YogaNode) {
mYogaNode.setBaselineFunction(baselineFunction);
}
}
boolean hasNewLayout() {
return mYogaNode.hasNewLayout();
}
void markLayoutSeen() {
mYogaNode.markLayoutSeen();
}
float getStyleWidth() {
return mYogaNode.getWidth().value;
}
float getMinWidth() {
return mYogaNode.getMinWidth().value;
}
float getMaxWidth() {
return mYogaNode.getMaxWidth().value;
}
float getStyleHeight() {
return mYogaNode.getHeight().value;
}
float getMinHeight() {
return mYogaNode.getMinHeight().value;
}
float getMaxHeight() {
return mYogaNode.getMaxHeight().value;
}
void calculateLayout(float width, float height) {
final ComponentTree tree = mComponentContext == null
? null
: mComponentContext.getComponentTree();
final ComponentsStethoManager stethoManager = tree == null ? null : tree.getStethoManager();
if (stethoManager != null) {
applyOverridesRecursive(stethoManager, this);
}
mYogaNode.calculateLayout(width, height);
}
private static void applyOverridesRecursive(
ComponentsStethoManager stethoManager,
InternalNode node) {
stethoManager.applyOverrides(node);
for (int i = 0, count = node.getChildCount(); i < count; i++) {
applyOverridesRecursive(stethoManager, node.getChildAt(i));
}
if (node.hasNestedTree()) {
applyOverridesRecursive(stethoManager, node.getNestedTree());
}
}
void calculateLayout() {
calculateLayout(YogaConstants.UNDEFINED, YogaConstants.UNDEFINED);
}
int getChildCount() {
return mYogaNode.getChildCount();
}
com.facebook.yoga.YogaDirection getStyleDirection() {
return mYogaNode.getStyleDirection();
}
InternalNode getChildAt(int index) {
if (mYogaNode.getChildAt(index) == null) {
return null;
}
return (InternalNode) mYogaNode.getChildAt(index).getData();
}
int getChildIndex(InternalNode child) {
for (int i = 0, count = mYogaNode.getChildCount(); i < count; i++) {
if (mYogaNode.getChildAt(i) == child.mYogaNode) {
return i;
}
}
return -1;
}
InternalNode getParent() {
if (mYogaNode == null || mYogaNode.getParent() == null) {
return null;
}
return (InternalNode) mYogaNode.getParent().getData();
}
void addChildAt(InternalNode child, int index) {
mYogaNode.addChildAt(child.mYogaNode, index);
}
InternalNode removeChildAt(int index) {
return (InternalNode) mYogaNode.removeChildAt(index).getData();
}
@Override
public ComponentLayout build() {
return this;
}
private float resolveHorizontalSpacing(Spacing spacing, int index) {
final boolean isRtl =
(mYogaNode.getLayoutDirection() == YogaDirection.RTL);
final int resolvedIndex;
switch (index) {
case Spacing.LEFT:
resolvedIndex = (isRtl ? Spacing.END : Spacing.START);
break;
case Spacing.RIGHT:
resolvedIndex = (isRtl ? Spacing.START : Spacing.END);
break;
default:
throw new IllegalArgumentException("Not an horizontal padding index: " + index);
}
float result = spacing.getRaw(resolvedIndex);
if (YogaConstants.isUndefined(result)) {
result = spacing.get(index);
}
return result;
}
ComponentContext getContext() {
return mComponentContext;
}
Component getComponent() {
return mComponent;
}
int getBorderColor() {
return mBorderColor;
}
boolean shouldDrawBorders() {
return mBorderColor != Color.TRANSPARENT
&& (mYogaNode.getLayoutBorder(LEFT) != 0
|| mYogaNode.getLayoutBorder(TOP) != 0
|| mYogaNode.getLayoutBorder(RIGHT) != 0
|| mYogaNode.getLayoutBorder(BOTTOM) != 0);
}
void setComponent(Component component) {
mComponent = component;
}
boolean hasNestedTree() {
return mNestedTree != null;
}
@Nullable InternalNode getNestedTree() {
return mNestedTree;
}
InternalNode getNestedTreeHolder() {
return mNestedTreeHolder;
}
/**
* Set the nested tree before measuring it in order to transfer over important information
* such as layout direction needed during measurement.
*/
void setNestedTree(InternalNode nestedTree) {
nestedTree.mNestedTreeHolder = this;
mNestedTree = nestedTree;
}
NodeInfo getNodeInfo() {
return mNodeInfo;
}
void copyInto(InternalNode node) {
if (mNodeInfo != null) {
if (node.mNodeInfo == null) {
node.mNodeInfo = mNodeInfo.acquireRef();
} else {
node.mNodeInfo.updateWith(mNodeInfo);
}
}
if ((node.mPrivateFlags & PFLAG_LAYOUT_DIRECTION_IS_SET) == 0L
|| node.getResolvedLayoutDirection() == YogaDirection.INHERIT) {
node.layoutDirection(getResolvedLayoutDirection());
}
if ((node.mPrivateFlags & PFLAG_IMPORTANT_FOR_ACCESSIBILITY_IS_SET) == 0L
|| node.mImportantForAccessibility == ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_AUTO) {
node.mImportantForAccessibility = mImportantForAccessibility;
}
if ((mPrivateFlags & PFLAG_DUPLICATE_PARENT_STATE_IS_SET) != 0L) {
node.mDuplicateParentState = mDuplicateParentState;
}
if ((mPrivateFlags & PFLAG_BACKGROUND_IS_SET) != 0L) {
node.mBackground = mBackground;
}
if ((mPrivateFlags & PFLAG_FOREGROUND_IS_SET) != 0L) {
node.mForeground = mForeground;
}
if (mForceViewWrapping) {
node.mForceViewWrapping = true;
}
if ((mPrivateFlags & PFLAG_VISIBLE_HANDLER_IS_SET) != 0L) {
node.mVisibleHandler = mVisibleHandler;
}
if ((mPrivateFlags & PFLAG_FOCUSED_HANDLER_IS_SET) != 0L) {
node.mFocusedHandler = mFocusedHandler;
}
if ((mPrivateFlags & PFLAG_FULL_IMPRESSION_HANDLER_IS_SET) != 0L) {
node.mFullImpressionHandler = mFullImpressionHandler;
}
if ((mPrivateFlags & PFLAG_INVISIBLE_HANDLER_IS_SET) != 0L) {
node.mInvisibleHandler = mInvisibleHandler;
}
|
package com.fluentinterface.utils;
import com.fluentinterface.builder.Builder;
import java.util.HashMap;
import java.util.Map;
/**
* Utility builder to create a map with a fluent API. Because this builder implements the <pre>{@code Builder<>}</pre> interface, it can
* be used directly in other builders as parameters, without the need to call `build()`.
* <p>
* Direct usage:
* <pre>{@code
* mappingof("key", 2).and("other", 3).build();
* }</pre>
* <p>
* Usage within other builders:
* <pre>{@code
* class Person {
* public Map<String, Integer> details;
* }
*
* interface PersonBuilder extends Builder<Person> {
* PersonBuilder withDetails(MapBuilder<String, Integer> details);
* }
*
* aPerson().withDetails(mappingOf("playerNumber", 1929).and("attribute", 12993))
* }</pre>
*
* @param <K> type for the map's keys
* @param <V> type for the map's values
*/
public class MapBuilder<K, V> implements Builder<Map<K, V>> {
private Map<K, V> built = new HashMap<>();
private MapBuilder() {}
@Override
public Map<K, V> build(Object... ignored) {
return built;
}
public MapBuilder<K, V> and(K key, V value) {
built.put(key, value);
return this;
}
public MapBuilder<K, V> with(K key, V value) {
built.put(key, value);
return this;
}
private MapBuilder(K initialKey, V initialValue) {
built.put(initialKey, initialValue);
}
public static <K, V> MapBuilder<K, V> mappingOf(K key, V value) {
return new MapBuilder<>(key, value);
}
public static <K, V> MapBuilder<K, V> mapOf(K key, V value) {
return mappingOf(key, value);
}
public static <K, V> MapBuilder<K, V> mapOf(K k1, V v1, K k2, V v2) {
return mappingOf(k1, v1).and(k2, v2);
}
public static <K, V> MapBuilder<K, V> mapOf(K k1, V v1, K k2, V v2, K k3, V v3) {
return mappingOf(k1, v1).and(k2, v2).and(k3, v3);
}
public static <K, V> MapBuilder<K, V> mapOf(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4) {
return mappingOf(k1, v1).and(k2, v2).and(k3, v3).and(k4, v4);
}
public static <K, V> MapBuilder<K, V> mapOf(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5) {
return mappingOf(k1, v1).and(k2, v2).and(k3, v3).and(k4, v4).and(k5, v5);
}
public static MapBuilder<Object, Object> map() {
return new MapBuilder<>();
}
}
|
package com.github.leonardocouto;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.GZIPInputStream;
import org.apache.commons.compress.archivers.ArchiveInputStream;
import org.apache.commons.compress.archivers.ArchiveStreamFactory;
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;
import org.apache.commons.compress.utils.IOUtils;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.descriptor.PluginDescriptor;
import org.apache.maven.plugin.logging.Log;
import org.apache.maven.plugins.annotations.LifecyclePhase;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
/**
* Install node if this version is not already installed.
* Also execute global npm installs (if not already installed)
*/
@Mojo(name = "install", defaultPhase = LifecyclePhase.NONE)
public class InstallMojo extends AbstractMojo {
@Parameter(property = "npm", defaultValue = "")
private String[] npm;
@Parameter(property = "target", defaultValue = "${basedir}/gen")
private File target;
@Parameter(property = "binary-group", defaultValue = "com.github.leonardo-couto")
private String binaryGroup;
@Parameter(property = "binary-artifact", defaultValue = "nodejs-binaries")
private String binaryArtifact;
@Parameter(defaultValue = "${plugin}", readonly = true)
private PluginDescriptor plugin;
@Override
public void execute() throws MojoExecutionException {
Artifact binaryArtifact = this.binaryArtifact();
String version = binaryArtifact.getVersion();
if (!this.alreadyInstalled(version)) {
this.install(binaryArtifact);
}
List<String> packages = this.nodePackages(version);
for (String pkg : this.npm) {
if (!packages.contains(pkg)) {
this.installPackage(pkg, version);
}
}
}
private void installPackage(String pkg, String nodeVersion) throws MojoExecutionException {
getLog().warn("installing npm package " + pkg + " ...");
String npmPath = this.npmPath(nodeVersion);
String install = npmPath + " install -g " + pkg;
Runtime run = Runtime.getRuntime();
try {
Process process = run.exec(install);
this.logInputStream(process.getErrorStream());
this.logInputStream(process.getInputStream());
} catch (IOException e) {
throw new MojoExecutionException("Error installing node package " + pkg, e);
}
}
private List<String> nodePackages(String version) {
String template = "%s/%s/lib/node_modules";
String path = String.format(template, this.target.getPath(), installationDirectoryName(version));
File nodeModules = new File(path);
List<String> packages = new ArrayList<>();
for (File f : nodeModules.listFiles()) {
packages.add(f.getName());
}
return packages;
}
private void install(Artifact binaryArtifact) throws MojoExecutionException {
getLog().warn("installing node.js on " + this.target.getPath() + " ...");
this.target.mkdirs();
File file = binaryArtifact.getFile();
this.unarchive(file, this.target);
File nodeDirectory = this.renameExtracted(binaryArtifact.getVersion());
this.createLink(nodeDirectory);
}
private File renameExtracted(String version) throws MojoExecutionException {
String path = this.target.getPath();
for (File f : this.target.listFiles()) {
if (Files.isDirectory(f.toPath()) && (f.getName().startsWith("node-v"))) {
File newName = new File(path, this.installationDirectoryName(version));
if (!f.renameTo(newName)) {
throw new MojoExecutionException("Could not rename directory");
}
return newName;
}
}
throw new MojoExecutionException("directory not found");
}
private boolean alreadyInstalled(String version) throws MojoExecutionException {
if (!this.target.exists()) return false;
if (this.target.isFile()) {
String error = String.format("target '%s' is a file", this.target.toString());
throw new MojoExecutionException(error);
}
for (File f : this.target.listFiles()) {
if (Files.isDirectory(f.toPath())) {
String name = f.getName();
if (this.installationDirectoryName(version).equals(name)) {
return true;
}
}
}
return false;
}
private Artifact binaryArtifact() {
String key = this.binaryGroup + ":" + this.binaryArtifact;
return this.plugin.getArtifactMap().get(key);
}
private String npmPath(String version) {
return this.baseExecutablePath(version) + "/npm";
}
private String baseExecutablePath(String version) {
String template = "%s/%s/bin/";
return String.format(template, this.target.getPath(), this.installationDirectoryName(version));
}
private String installationDirectoryName(String version) {
return "node-v" + version;
}
private void createLink(File nodeDirectory) throws MojoExecutionException {
try {
File nodeLink = new File(this.target.getPath(), "node");
this.deleteLink(nodeLink);
Files.createSymbolicLink(nodeLink.toPath(), nodeDirectory.toPath());
} catch (IOException e) {
throw new MojoExecutionException("Error creating symlink", e);
}
}
private void deleteLink(File nodeLink) throws MojoExecutionException {
if (nodeLink.exists()) {
if (!nodeLink.delete()) {
throw new MojoExecutionException("Could not delete " + nodeLink.getPath());
}
}
}
private void logInputStream(InputStream input) throws IOException {
Log logger = getLog();
InputStreamReader reader = new InputStreamReader(input);
BufferedReader br = new BufferedReader(reader);
String line = br.readLine();
while (line != null) {
logger.warn(line);
line = br.readLine();
}
br.close();
}
private void unarchive(File input, File output) throws MojoExecutionException {
try {
GZIPInputStream tar = new GZIPInputStream(new FileInputStream(input));
ArchiveInputStream ais = (new ArchiveStreamFactory()).createArchiveInputStream("tar", tar);
final TarArchiveInputStream files = (TarArchiveInputStream) ais;
TarArchiveEntry entry = (TarArchiveEntry) files.getNextEntry();
while (entry != null) {
final File outputFile = new File(output, entry.getName());
if (entry.isDirectory()) {
outputFile.mkdirs();
} else if (entry.isSymbolicLink()) {
File target = new File(entry.getLinkName());
Files.createSymbolicLink(outputFile.toPath(), target.toPath());
} else {
boolean executable = (entry.getMode() % 2) == 1;
final OutputStream fout = new FileOutputStream(outputFile);
IOUtils.copy(files, fout);
fout.close();
outputFile.setExecutable(executable);
}
entry = (TarArchiveEntry) files.getNextEntry();
}
} catch (Exception e) {
throw new MojoExecutionException("Error extracting node binary tar.gz", e);
}
}
}
|
package com.github.lunatrius.stackie;
import com.github.lunatrius.core.version.VersionChecker;
import com.github.lunatrius.stackie.handler.ConfigurationHandler;
import com.github.lunatrius.stackie.proxy.CommonProxy;
import com.github.lunatrius.stackie.reference.Names;
import com.github.lunatrius.stackie.reference.Reference;
import cpw.mods.fml.common.Mod;
import cpw.mods.fml.common.Mod.EventHandler;
import cpw.mods.fml.common.SidedProxy;
import cpw.mods.fml.common.event.FMLInitializationEvent;
import cpw.mods.fml.common.event.FMLPostInitializationEvent;
import cpw.mods.fml.common.event.FMLPreInitializationEvent;
import cpw.mods.fml.common.event.FMLServerStartingEvent;
import cpw.mods.fml.common.event.FMLServerStoppingEvent;
import cpw.mods.fml.common.network.NetworkCheckHandler;
import cpw.mods.fml.common.registry.GameData;
import cpw.mods.fml.relauncher.Side;
import net.minecraft.item.Item;
import net.minecraft.util.MathHelper;
import java.util.Map;
@Mod(modid = Reference.MODID, name = Reference.NAME, version = Reference.VERSION, guiFactory = Reference.GUI_FACTORY)
public class Stackie {
@SidedProxy(serverSide = Reference.PROXY_SERVER, clientSide = Reference.PROXY_CLIENT)
public static CommonProxy proxy;
@NetworkCheckHandler
public boolean checkModList(Map<String, String> versions, Side side) {
return true;
}
@EventHandler
public void preInit(FMLPreInitializationEvent event) {
Reference.logger = event.getModLog();
ConfigurationHandler.init(event.getSuggestedConfigurationFile());
proxy.setConfigEntryClasses();
VersionChecker.registerMod(event.getModMetadata(), Reference.FORGE);
}
@EventHandler
public void init(FMLInitializationEvent event) {
proxy.registerEvents();
}
@EventHandler
public void postInit(FMLPostInitializationEvent event) {
for (String info : ConfigurationHandler.stackSizes) {
String[] parts = info.split(Names.Config.STACK_SIZE_DELIMITER);
if (parts.length == 2) {
try {
String uniqueName = parts[0];
int stackSize = MathHelper.clamp_int(Integer.parseInt(parts[1], 10), 1, 64);
Item item = GameData.getItemRegistry().getObject(uniqueName);
if (item != null) {
item.setMaxStackSize(stackSize);
}
} catch (Exception e) {
Reference.logger.error("Invalid format?", e);
}
}
}
}
@EventHandler
public void serverStarting(FMLServerStartingEvent event) {
proxy.serverStarting(event);
}
@EventHandler
public void serverStopping(FMLServerStoppingEvent event) {
proxy.serverStopping(event);
}
}
|
package com.indeed.imhotep.sql;
import com.google.common.base.Function;
import com.google.common.base.Predicate;
import com.google.common.base.Strings;
import com.google.common.base.Throwables;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import com.indeed.imhotep.metadata.FieldType;
import com.indeed.util.serialization.LongStringifier;
import com.indeed.util.serialization.Stringifier;
import com.indeed.flamdex.lucene.LuceneQueryTranslator;
import com.indeed.imhotep.client.ImhotepClient;
import com.indeed.imhotep.ez.DynamicMetric;
import com.indeed.imhotep.ez.EZImhotepSession;
import com.indeed.imhotep.ez.Field;
import com.indeed.imhotep.iql.Condition;
import com.indeed.imhotep.iql.DistinctGrouping;
import com.indeed.imhotep.iql.FieldGrouping;
import com.indeed.imhotep.iql.FieldInGrouping;
import com.indeed.imhotep.iql.Grouping;
import com.indeed.imhotep.iql.IQLQuery;
import com.indeed.imhotep.iql.IntInCondition;
import com.indeed.imhotep.iql.MetricCondition;
import com.indeed.imhotep.iql.PercentileGrouping;
import com.indeed.imhotep.iql.QueryCondition;
import com.indeed.imhotep.iql.SampleCondition;
import com.indeed.imhotep.iql.StatRangeGrouping;
import com.indeed.imhotep.iql.StatRangeGrouping2D;
import com.indeed.imhotep.iql.StringInCondition;
import com.indeed.imhotep.iql.StringPredicateCondition;
import com.indeed.imhotep.metadata.DatasetMetadata;
import com.indeed.imhotep.metadata.FieldMetadata;
import com.indeed.imhotep.sql.ast.Expression;
import com.indeed.imhotep.sql.ast.FunctionExpression;
import com.indeed.imhotep.sql.ast.NameExpression;
import com.indeed.imhotep.sql.ast.NumberExpression;
import com.indeed.imhotep.sql.ast.Op;
import com.indeed.imhotep.sql.ast.StringExpression;
import com.indeed.imhotep.sql.ast.TupleExpression;
import com.indeed.imhotep.sql.ast2.FromClause;
import com.indeed.imhotep.sql.ast2.SelectStatement;
import com.indeed.imhotep.sql.parser.ExpressionParser;
import com.indeed.imhotep.sql.parser.PeriodParser;
import com.indeed.imhotep.web.ImhotepMetadataCache;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.KeywordAnalyzer;
import org.apache.lucene.analysis.PerFieldAnalyzerWrapper;
import org.apache.lucene.analysis.WhitespaceAnalyzer;
import org.apache.lucene.queryParser.ParseException;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.Query;
import org.joda.time.DateTime;
import org.joda.time.DurationFieldType;
import org.joda.time.Period;
import org.joda.time.PeriodType;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import javax.annotation.Nonnull;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static com.indeed.imhotep.ez.Stats.Stat;
import static com.indeed.imhotep.ez.EZImhotepSession.*;
/**
* @author jplaisance
*/
public final class IQLTranslator {
private static final Logger log = Logger.getLogger(IQLTranslator.class);
public static IQLQuery translate(SelectStatement parse, ImhotepClient client, String username, ImhotepMetadataCache metadata) {
if(log.isTraceEnabled()) {
log.trace(parse.toHashKeyString());
}
final FromClause fromClause = parse.from;
final String dataset = fromClause.getDataset();
final DatasetMetadata datasetMetadata = metadata.getDataset(dataset);
final Set<String> keywordAnalyzerWhitelist = metadata.getKeywordAnalyzerWhitelist(dataset);
final List<Stat> stats = Lists.newArrayList();
final List<Expression> projections = Lists.newArrayList(parse.select.getProjections());
final DistinctGrouping distinctGrouping = getDistinctGrouping(projections, datasetMetadata);
final PercentileGrouping percentileGrouping = getPercentileGrouping(projections, datasetMetadata, EZImhotepSession.counts());
if (distinctGrouping != null && percentileGrouping != null) {
throw new IllegalArgumentException("Cannot use distinct and percentile in the same query");
}
final StatMatcher statMatcher = new StatMatcher(datasetMetadata, keywordAnalyzerWhitelist);
for (Expression expression : projections) {
stats.add(expression.match(statMatcher));
}
final List<Condition> conditions;
if (parse.where != null) {
conditions = parse.where.getExpression().match(new ConditionMatcher(datasetMetadata, keywordAnalyzerWhitelist));
} else {
conditions = Collections.emptyList();
}
final List<Grouping> groupings = Lists.newArrayList();
final GroupByMatcher groupByMatcher = new GroupByMatcher(datasetMetadata, keywordAnalyzerWhitelist, fromClause.getStart(), fromClause.getEnd());
if (parse.groupBy != null) {
for (Expression groupBy : parse.groupBy.groupings) {
groupings.add(groupBy.match(groupByMatcher));
}
}
ensureBucketsComeFirst(groupings);
if(distinctGrouping != null) {
ensureDistinctSelectDoesntMatchGroupings(groupings, distinctGrouping);
groupings.add(distinctGrouping); // distinct has to come last
} else if (percentileGrouping != null) {
groupings.add(percentileGrouping);
}
handleMultitermIn(conditions, groupings);
optimizeGroupings(groupings);
return new IQLQuery(client, stats, fromClause.getDataset(), fromClause.getStart(), fromClause.getEnd(),
conditions, groupings, parse.limit, username, metadata);
}
private static void ensureDistinctSelectDoesntMatchGroupings(List<Grouping> groupings, DistinctGrouping distinctGrouping) {
for(Field distinctField : distinctGrouping.getFields()) {
for(Grouping grouping: groupings) {
if(grouping instanceof FieldGrouping && ((FieldGrouping) grouping).getField().equals(distinctField) ||
grouping instanceof FieldInGrouping && ((FieldInGrouping) grouping).getField().equals(distinctField)) {
throw new IllegalArgumentException("Please remove distinct(" + distinctField.getFieldName() +
") from the SELECT clause as it is always going to be 1 due to it being one of the GROUP BY groups");
}
}
}
}
private static void optimizeGroupings(List<Grouping> groupings) {
// if we have only one grouping we can safely disable exploding which allows us to stream the result
if(groupings.size() == 1 && groupings.get(0) instanceof FieldGrouping) {
FieldGrouping fieldGrouping = (FieldGrouping) groupings.get(0);
if(fieldGrouping.getTopK() == 0 && !fieldGrouping.isNoExplode()) {
groupings.set(0, new FieldGrouping(fieldGrouping.getField(), true));
}
}
}
private static void ensureBucketsComeFirst(List<Grouping> groupings) {
boolean inBucketing = true;
for(Grouping grouping : groupings) {
boolean bucketGrouping = grouping instanceof StatRangeGrouping || grouping instanceof StatRangeGrouping2D;
if(bucketGrouping && !inBucketing) {
throw new UnsupportedOperationException("Bucketing groupings (e.g. time or bucket()) have to come before all other non-bucketing groupings. " +
"'group by time, country' is supported but 'group by country, time' is not.");
} else if(!bucketGrouping) {
inBucketing = false;
}
}
}
/**
* Handles converting queries of the form WHERE field IN (term1, term2, ...) GROUP BY field
* to queries like: GROUP BY field IN (term1, term2, ...) .
* This properly handles the case where filtered and grouped by field has multiple terms per doc (e.g. grp, rcv).
* Modified the passed in lists.
*/
static void handleMultitermIn(List<Condition> conditions, List<Grouping> groupings) {
for(int i = 0; i < conditions.size(); i++) {
Condition condition = conditions.get(i);
if(! (condition instanceof StringInCondition)) {
continue;
}
StringInCondition inCondition = (StringInCondition) condition;
if(inCondition.isEquality()) {
continue; // when we have a single value filter (e.g. grp:smartphone), assume that MultitermIn is not intended
}
if(inCondition.isNegation()) {
continue; // negations shouldn't be rewritten
}
Field.StringField field = inCondition.getStringField();
// see if this field is also used in GROUP BY
for(int j = 0; j < groupings.size(); j++) {
Grouping grouping = groupings.get(j);
if(!(grouping instanceof FieldGrouping)) {
continue;
}
FieldGrouping fieldGrouping = (FieldGrouping) grouping;
if(!field.equals(fieldGrouping.getField())) {
continue;
}
// got a match. convert this grouping to a FieldInGrouping and remove the condition
FieldInGrouping fieldInGrouping = new FieldInGrouping(field, Lists.newArrayList(inCondition.getValues()));
conditions.remove(i);
i--; // have to redo the current index as indexes were shifted
groupings.set(j, fieldInGrouping);
}
}
}
static DistinctGrouping getDistinctGrouping(List<Expression> projections, DatasetMetadata datasetMetadata) {
DistinctGrouping distinctGrouping = null;
int projectionNumber = 0;
for(Iterator<Expression> projectionsIter = projections.iterator(); projectionsIter.hasNext(); projectionNumber++) {
Expression projection = projectionsIter.next();
if(!(projection instanceof FunctionExpression)) {
continue;
}
FunctionExpression functionProjection = (FunctionExpression) projection;
if (!functionProjection.function.equals("distinct")) {
continue;
}
if(functionProjection.args.size() != 1) {
throw new IllegalArgumentException("distinct() takes a field name as an argument and returns distinct count of terms for the field");
}
String fieldName = getStr(functionProjection.args.get(0));
final Field field = getField(fieldName, datasetMetadata);
projectionsIter.remove();
if(distinctGrouping == null) {
distinctGrouping = new DistinctGrouping();
}
distinctGrouping.addField(field, projectionNumber);
}
return distinctGrouping;
}
static PercentileGrouping getPercentileGrouping(List<Expression> projections, DatasetMetadata datasetMetadata, Stat countStat) {
PercentileGrouping percentileGrouping = null;
int projectionNumber = 0;
for(Iterator<Expression> projectionsIter = projections.iterator(); projectionsIter.hasNext(); projectionNumber++) {
Expression projection = projectionsIter.next();
if(!(projection instanceof FunctionExpression)) {
continue;
}
FunctionExpression functionProjection = (FunctionExpression) projection;
if (!functionProjection.function.equals("percentile")) {
continue;
}
if(functionProjection.args.size() != 2) {
throw new IllegalArgumentException(
"percentile() takes a field name and a percentile and returns that percentile, e.g. percentile(tottime, 50)"
);
}
String fieldName = getStr(functionProjection.args.get(0));
final Field field = getField(fieldName, datasetMetadata);
projectionsIter.remove();
final double percentile = parseInt(functionProjection.args.get(1));
if (percentile < 0 || percentile > 100) {
throw new IllegalArgumentException("percentile must be between 0 and 100");
}
if(percentileGrouping == null) {
percentileGrouping = new PercentileGrouping(countStat);
}
percentileGrouping.addPercentileQuery(field, percentile, projectionNumber);
}
return percentileGrouping;
}
@Nonnull
private static Field getField(String name, DatasetMetadata datasetMetadata) {
final FieldMetadata fieldMetadata = datasetMetadata.getField(name);
if(fieldMetadata == null) {
throw new IllegalArgumentException("Unknown field: " + name);
}
return fieldMetadata.isIntImhotepField() ? Field.intField(name) : Field.stringField(name);
}
private static class StatMatcher extends Expression.Matcher<Stat> {
private final DatasetMetadata datasetMetadata;
private final Map<String, Function<List<Expression>, Stat>> statLookup;
private Stat[] getStats(final List<Expression> input) {
List<Stat> stats = Lists.newArrayList();
for(Expression statString : input) {
stats.add(statString.match(StatMatcher.this));
}
return stats.toArray(new Stat[stats.size()]);
}
private StatMatcher(final DatasetMetadata datasetMetadata, final Set<String> keywordAnalyzerWhitelist) {
this.datasetMetadata = datasetMetadata;
final ImmutableMap.Builder<String, Function<List<Expression>, Stat>> builder = ImmutableMap.builder();
builder.put("count", new Function<List<Expression>, Stat>() {
public Stat apply(final List<Expression> input) {
return counts();
}
});
builder.put("cached", new Function<List<Expression>, Stat>() {
public Stat apply(final List<Expression> input) {
if (input.size() != 1) {
throw new UnsupportedOperationException();
}
return cached(input.get(0).match(StatMatcher.this));
}
});
builder.put("abs", new Function<List<Expression>, Stat>() {
public Stat apply(final List<Expression> input) {
if (input.size() != 1) {
throw new UnsupportedOperationException();
}
return abs(input.get(0).match(StatMatcher.this));
}
});
builder.put("min", new Function<List<Expression>, Stat>() {
public Stat apply(final List<Expression> input) {
if (input.size() < 2) {
throw new UnsupportedOperationException("min() requires at least 2 arguments");
}
return min(getStats(input));
}
});
builder.put("mulshr", new Function<List<Expression>, Stat>() {
public Stat apply(final List<Expression> input) {
if (input.size() != 3) {
throw new UnsupportedOperationException("mulshr requires 3 arguments: shift, stat1, stat2");
}
if(!(input.get(0) instanceof NumberExpression)) {
throw new IllegalArgumentException("First argument of mulshr() has to be an integer. ");
}
final String shiftStr = getStr(input.get(0));
final int shift = Integer.parseInt(shiftStr);
final Stat stat1 = input.get(1).match(StatMatcher.this);
final Stat stat2 = input.get(2).match(StatMatcher.this);
return multiplyShiftRight(shift, stat1, stat2);
}
});
builder.put("shldiv", new Function<List<Expression>, Stat>() {
public Stat apply(final List<Expression> input) {
if (input.size() != 3) {
throw new UnsupportedOperationException("shldiv requires 3 arguments: shift, stat1, stat2");
}
if(!(input.get(0) instanceof NumberExpression)) {
throw new IllegalArgumentException("First argument of shldiv() has to be an integer. ");
}
final String shiftStr = getStr(input.get(0));
final int shift = Integer.parseInt(shiftStr);
final Stat stat1 = input.get(1).match(StatMatcher.this);
final Stat stat2 = input.get(2).match(StatMatcher.this);
return shiftLeftDivide(shift, stat1, stat2);
}
});
builder.put("max", new Function<List<Expression>, Stat>() {
public Stat apply(final List<Expression> input) {
if (input.size() < 2) {
throw new UnsupportedOperationException("max() requires at least 2 arguments");
}
return max(getStats(input));
}
});
builder.put("exp", new Function<List<Expression>, Stat>() {
public Stat apply(final List<Expression> input) {
int scaleFactor = 1;
if(input.size() == 2) {
scaleFactor = parseInt(input.get(1));
} else if (input.size() != 1) {
throw new UnsupportedOperationException("exp() requires 1 or 2 arguments. " +
"e.g. exp(ojc, 1) where ojc is a metric and 1 is a scaling factor that the terms " +
"get divided by before exponentiation and multiplied by after exponentiation. " +
"Scaling factor defaults to 1.");
}
return exp(input.get(0).match(StatMatcher.this), scaleFactor);
}
});
builder.put("dynamic", new Function<List<Expression>, Stat>() {
public Stat apply(final List<Expression> input) {
if (input.size() != 1) {
throw new UnsupportedOperationException();
}
return dynamic(new DynamicMetric(getName(input.get(0))));
}
});
builder.put("hasstr", new Function<List<Expression>, Stat>() {
public Stat apply(final List<Expression> input) {
String field = null;
String value = null;
if (input.size() == 1) {
final String param = getStr(input.get(0));
final String[] parts = param.split(":");
if(parts.length == 2) {
field = parts[0];
value = parts[1];
} else if(parts.length == 1 && param.trim().endsWith(":")) {
field = parts[0];
value = "";
}
} else if(input.size() == 2) {
field = getStr(input.get(0));
value = getStr(input.get(1));
}
if(Strings.isNullOrEmpty(field) || value == null) {
throw new IllegalArgumentException("incorrect usage in hasstr(). Examples: hasstr(rcv,jsv) or hasstr(\"rcv:jsv\")");
}
return hasString(field, value);
}
});
builder.put("hasint", new Function<List<Expression>, Stat>() {
public Stat apply(final List<Expression> input) {
final String usageExamples = "Examples: hasint(clicked,1) or hasint(\"clicked:1\")";
String field = null;
long value = 0;
if (input.size() == 1) {
final String param = getStr(input.get(0));
final String[] parts = param.split(":");
if(parts.length == 2) {
field = parts[0];
try {
value = Long.parseLong(parts[1]);
} catch (NumberFormatException ignored) {
throw new IllegalArgumentException("Value in hasint() has to be an integer. " + usageExamples);
}
}
} else if(input.size() == 2) {
field = getStr(input.get(0));
if(!(input.get(1) instanceof NumberExpression)) {
throw new IllegalArgumentException("Second argument of hasint() has to be an integer. " + usageExamples);
}
value = parseInt(input.get(1));
}
if(Strings.isNullOrEmpty(field)) {
throw new IllegalArgumentException("incorrect usage in hasint(). " + usageExamples);
}
return hasInt(field, value);
}
});
builder.put("floatscale", new Function<List<Expression>, Stat>() {
public Stat apply(final List<Expression> input) {
if (input.size() == 3) {
return floatScale(getName(input.get(0)), parseInt(input.get(1)), parseInt(input.get(2)));
} else if (input.size() == 2) {
return floatScale(getName(input.get(0)), parseInt(input.get(1)), 0);
} else if(input.size() == 1) {
return floatScale(getName(input.get(0)), 1, 0);
} else {
throw new UnsupportedOperationException();
}
}
});
builder.put("lucene", new Function<List<Expression>, Stat>() {
public Stat apply(final List<Expression> input) {
if (input.size() != 1) {
throw new UnsupportedOperationException("lucene() requires a string argument containing the lucene query to try on each document");
}
final String luceneQuery = getStr(input.get(0));
final com.indeed.flamdex.query.Query flamdexQuery = parseLuceneQuery(luceneQuery, datasetMetadata, keywordAnalyzerWhitelist);
return lucene(flamdexQuery);
}
});
statLookup = builder.build();
}
protected Stat binaryExpression(final Expression left, final Op op, final Expression right) {
switch (op) {
case PLUS:
return add(left.match(this), right.match(this));
case MINUS:
return sub(left.match(this), right.match(this));
case MUL:
return mult(left.match(this), right.match(this));
case DIV:
return div(left.match(this), right.match(this));
case MOD:
return mod(left.match(this), right.match(this));
case LESS:
return less(left.match(this), right.match(this));
case LESS_EQ:
return lessEq(left.match(this), right.match(this));
case EQ:
if(left instanceof NameExpression) {
// probably a has[str/int] operation
final String fieldName = ((NameExpression) left).name;
final FieldMetadata field = datasetMetadata.getField(fieldName);
if(field == null) {
throw new IllegalArgumentException("Field not found: " + fieldName);
}
final FieldType fieldMetadataType = field.getType();
if(field.isIntImhotepField() && right instanceof NumberExpression) {
long value = parseInt(right);
return hasInt(fieldName, value);
} else if(fieldMetadataType == FieldType.Integer && right instanceof NumberExpression ||
fieldMetadataType == FieldType.String && (right instanceof NameExpression ||
right instanceof StringExpression || right instanceof NumberExpression)) {
return hasString(fieldName, getStr(right));
}
// if it got here, it's not a has[str/int] operation
}
// try to compare as metrics
return isEqual(left.match(this), right.match(this));
case NOT_EQ:
if(left instanceof NameExpression) {
final Stat equalsStat = binaryExpression(left, Op.EQ, right);
// TODO: only return if equalsStat is a HasIntStat or a HasStringStat
return sub(counts(), equalsStat);
}
// try to compare as metrics
return isNotEqual(left.match(this), right.match(this));
case GREATER:
return greater(left.match(this), right.match(this));
case GREATER_EQ:
return greaterEq(left.match(this), right.match(this));
case AGG_DIV:
{
if(right instanceof NumberExpression) {
throw new UnsupportedOperationException("Aggregate division (/) by a number is not yet supported. To divide each document's value, use '\\' e.g. 'tottime\\1000'");
}
return aggDiv(left.match(this), right.match(this));
}
default:
throw new UnsupportedOperationException();
}
}
protected Stat functionExpression(final String name, final List<Expression> args) {
final Function<List<Expression>, Stat> function = statLookup.get(name);
if (function == null) {
throw new IllegalArgumentException("Unknown stat function: " + name);
}
return function.apply(args);
}
protected Stat nameExpression(final String name) {
if(!datasetMetadata.hasField(name)) {
throw new IllegalArgumentException("Unknown field name in a stat: " + name);
}
return intField(name);
}
protected Stat numberExpression(final String value) {
return constant(Long.parseLong(value));
}
}
private static final class ConditionMatcher extends Expression.Matcher<List<Condition>> {
private final Map<String, Function<List<Expression>, Condition>> functionLookup;
private final DatasetMetadata datasetMetadata;
private final Set<String> keywordAnalyzerWhitelist;
private final StatMatcher statMatcher;
private boolean negation; // keeps track of whether we are inside a negated branch of expression
private ConditionMatcher(final DatasetMetadata datasetMetadata, final Set<String> keywordAnalyzerWhitelist) {
this.datasetMetadata = datasetMetadata;
this.keywordAnalyzerWhitelist = keywordAnalyzerWhitelist;
statMatcher = new StatMatcher(datasetMetadata, keywordAnalyzerWhitelist);
final ImmutableMap.Builder<String, Function<List<Expression>, Condition>> builder = ImmutableMap.builder();
Function<List<Expression>, Condition> luceneQueryHandler = new Function<List<Expression>, Condition>() {
public Condition apply(final List<Expression> input) {
if (input.size() != 1) throw new IllegalArgumentException("lucene query function takes exactly one string parameter");
final String queryString = getStr(input.get(0));
final com.indeed.flamdex.query.Query luceneQuery = parseLuceneQuery(queryString, datasetMetadata, keywordAnalyzerWhitelist);
return new QueryCondition(luceneQuery, negation);
}
};
builder.put("lucene", luceneQueryHandler);
// TODO: remove
builder.put("query", luceneQueryHandler);
// TODO: remove. can relax parsing of function params when it's done
builder.put("between", new Function<List<Expression>, Condition>() {
public Condition apply(final List<Expression> input) {
if (input.size() != 3) throw new IllegalArgumentException("between requires 3 arguments: stat, min, max. " + input.size() + " provided");
final Stat stat = input.get(0).match(statMatcher);
final long min = parseLong(input.get(1));
final long max = parseLong(input.get(2));
return new MetricCondition(stat, min, max, negation);
}
});
builder.put("sample", new Function<List<Expression>, Condition>() {
public Condition apply(final List<Expression> input) {
if (input.size() < 2 || input.size() > 4) throw new IllegalArgumentException("sample() requires 2 to 4 arguments: fieldName, samplingRatioNumerator, [samplingRatioDenominator=100], [randomSeed]. " + input.size() + " provided");
final Expression arg0 = input.get(0);
if(!(arg0 instanceof NameExpression)) {
throw new UnsupportedOperationException("sample() first argument has to be a field name. Instead given: " + String.valueOf(arg0));
}
final NameExpression nameExpression = (NameExpression) arg0;
final String fieldName = nameExpression.name;
final Field field = getField(fieldName, datasetMetadata);
final int numerator = Math.max(0, parseInt(input.get(1)));
final int denominator = Math.max(1, Math.max(numerator, input.size() >= 3 ? parseInt(input.get(2)) : 100));
final String salt;
if(input.size() >= 4) {
final String userSalt = Strings.nullToEmpty(getStr(input.get(3)));
salt = userSalt.substring(0, Math.min(userSalt.length(), 32)); // limit salt length to 32 char just in case
} else {
// generate a new salt
salt = String.valueOf(System.nanoTime() % Integer.MAX_VALUE);
}
return new SampleCondition(field, (double) numerator / denominator, salt, negation);
// we can also do it through a predicate condition but that requires FTGS instead of a regroup
}
});
functionLookup = builder.build();
}
@Override
protected List<Condition> binaryExpression(final Expression left, final Op op, final Expression right) {
boolean usingNegation = negation; // local copy so that it can be modified independently
switch (op) {
case NOT_IN:
usingNegation = !usingNegation;
// fall through to IN
case IN:
{
final NameExpression name = (NameExpression) left;
final TupleExpression values = (TupleExpression) right;
if (datasetMetadata.hasStringField(name.name)) {
// TODO how do we handle tokenized fields here?
final String[] strings = new String[values.expressions.size()];
int index = 0;
for (Expression expression : values.expressions) {
strings[index++] = getStr(expression);
}
Arrays.sort(strings); // looks like terms being sorted is a pre-requisite of stringOrRegroup()
return Lists.<Condition>newArrayList(new StringInCondition(Field.stringField(name.name), usingNegation, false, strings));
} else if (datasetMetadata.hasIntField(name.name)) {
final long[] ints = new long[values.expressions.size()];
int index = 0;
for (Expression expression : values.expressions) {
if(!(expression instanceof NumberExpression)) {
throw new IllegalArgumentException("A non integer value specified for an integer field: " + name.name);
}
ints[index++] = parseLong(expression);
}
Arrays.sort(ints); // looks like terms being sorted is a pre-requisite of intOrRegroup()
return Lists.<Condition>newArrayList(new IntInCondition(Field.intField(name.name), usingNegation, ints));
} else {
throw new IllegalArgumentException("Unknown field: " + name.name);
}
}
case NOT_EQ:
usingNegation = !usingNegation;
// fall through to EQ
case EQ:
if(left instanceof NameExpression) {
final NameExpression name = (NameExpression) left;
if(datasetMetadata.hasField(name.name)) {
return handleFieldComparison(name, right, usingNegation);
}
}
return handleMetricComparison(left, right, usingNegation);
case REGEX_NOT_EQ:
usingNegation = !usingNegation;
// fall through to REGEX_EQ
case REGEX_EQ:
if(!(left instanceof NameExpression)) {
throw new UnsupportedOperationException("Regexp compare only works on field names. Instead given: " + String.valueOf(left));
}
final NameExpression nameExpression = (NameExpression) left;
final String fieldName = nameExpression.name;
if (!datasetMetadata.hasStringField(fieldName)) {
throw new IllegalArgumentException("Unknown field: " + fieldName);
}
String regexp = getStr(right);
final Pattern pattern = Pattern.compile(regexp);
return Collections.<Condition>singletonList(new StringPredicateCondition(Field.stringField(fieldName), new Predicate<String>() {
@Override
public boolean apply(String input) {
return pattern.matcher(input).matches();
}
},
usingNegation));
case AND:
final List<Condition> ret = Lists.newArrayList();
ret.addAll(left.match(this));
ret.addAll(right.match(this));
return ret;
case LESS:
case LESS_EQ:
case GREATER:
case GREATER_EQ:
if (!(right instanceof NumberExpression)) throw new IllegalArgumentException("Comparison values have to be numbers. Given: " + right.toString());
final Stat stat = left.match(statMatcher);
long value = parseLong(right); // constant we are comparing against
if(op == Op.LESS) {
value -= 1;
} else if(op == Op.GREATER) {
value += 1;
}
final long min;
final long max;
if(op == Op.LESS || op == Op.LESS_EQ) {
min = Long.MIN_VALUE;
max = value;
} else { // GREATER / GREATER_EQ
min = value;
max = Long.MAX_VALUE;
}
return Collections.<Condition>singletonList(new MetricCondition(stat, min, max, negation));
default:
throw new UnsupportedOperationException();
}
}
private List<Condition> handleMetricComparison(Expression left, Expression right, boolean usingNegation) {
final Stat stat;
try {
stat = left.match(statMatcher);
} catch (Exception e) {
throw new IllegalArgumentException("Left side of comparison is not a known field or metric: " + left.toString());
}
if (!(right instanceof NumberExpression)) throw new IllegalArgumentException("Metric comparison values have to be numbers");
final long value = parseLong(right); // constant we are comparing against
return Collections.<Condition>singletonList(new MetricCondition(stat, value, value, usingNegation));
}
private List<Condition> handleFieldComparison(NameExpression name, Expression right, boolean usingNegation) {
if (datasetMetadata.hasStringField(name.name)) {
final String value = getStr(right);
final boolean isTokenized = !datasetMetadata.isImhotepDataset() && (keywordAnalyzerWhitelist == null || !keywordAnalyzerWhitelist.contains(name.name));
if(isTokenized && right instanceof StringExpression) {
// special handling for tokenized fields and multi-word queries e.g. jobsearch:q
String[] words = value.split("\\s+");
if(words.length > 1) {
List<Condition> conditions = Lists.newArrayList();
for(String word : words) {
conditions.add(new StringInCondition(Field.stringField(name.name), usingNegation, true, word));
}
return Lists.newArrayList(conditions);
} // else fall through to the normal case
}
final String[] strings = new String[] { value };
return Lists.<Condition>newArrayList(new StringInCondition(Field.stringField(name.name), usingNegation, true, strings));
} else if (datasetMetadata.hasIntField(name.name)) {
final long[] ints = new long[1];
if(!(right instanceof NumberExpression)) {
throw new IllegalArgumentException(name.name + " is an integer field and has to be compared to an integer. Instead was given: " + right.toString());
}
ints[0] = parseLong(right);
return Lists.<Condition>newArrayList(new IntInCondition(Field.intField(name.name), usingNegation, ints));
} else {
throw new IllegalArgumentException("Unknown field: " + name.name);
}
}
@Override
protected List<Condition> unaryExpression(Op op, Expression operand) {
if(op.equals(Op.NEG)) {
negation = !negation;
List<Condition> result = operand.match(this);
negation = !negation;
return result;
}
throw new UnsupportedOperationException();
}
@Override
protected List<Condition> functionExpression(final String name, final List<Expression> args) {
final Function<List<Expression>, Condition> function = functionLookup.get(name);
if (function == null) {
throw new IllegalArgumentException();
}
return Collections.singletonList(function.apply(args));
}
}
private static com.indeed.flamdex.query.Query parseLuceneQuery(String queryString, DatasetMetadata datasetMetadata, Set<String> keywordAnalyzerWhitelist) {
// Pick a lucene query analyzer based on whether it is for a lucene or flamdex dataset
// and what is in the keywordAnalyzerWhitelist for the dataset
final Analyzer analyzer;
if(datasetMetadata.isImhotepDataset()) {
analyzer = new KeywordAnalyzer();
} else if (!keywordAnalyzerWhitelist.isEmpty()) {
final KeywordAnalyzer kwAnalyzer = new KeywordAnalyzer();
if(keywordAnalyzerWhitelist.contains("*")) {
analyzer = kwAnalyzer;
} else {
final WhitespaceAnalyzer whitespaceAnalyzer = new WhitespaceAnalyzer();
final PerFieldAnalyzerWrapper perFieldAnalyzer = new PerFieldAnalyzerWrapper(whitespaceAnalyzer);
for (String field : keywordAnalyzerWhitelist) {
perFieldAnalyzer.addAnalyzer(field, kwAnalyzer);
}
analyzer = perFieldAnalyzer;
}
} else {
analyzer = new WhitespaceAnalyzer();
}
final QueryParser queryParser = new QueryParser("foo", analyzer);
queryParser.setDefaultOperator(QueryParser.Operator.AND);
final Query query;
try {
query = queryParser.parse(queryString);
} catch (ParseException e) {
throw Throwables.propagate(e);
}
return LuceneQueryTranslator.rewrite(query, datasetMetadata.getIntImhotepFieldSet());
}
private static final class GroupByMatcher extends Expression.Matcher<Grouping> {
private static final int MAX_RECOMMENDED_BUCKETS = 1000;
private final Map<String, Function<List<Expression>, Grouping>> functionLookup;
private final DatasetMetadata datasetMetadata;
private final DateTime start;
private final DateTime end;
private final StatMatcher statMatcher;
private GroupByMatcher(final DatasetMetadata datasetMetadata, final Set<String> keywordAnalyzerWhitelist, final DateTime start, final DateTime end) {
statMatcher = new StatMatcher(datasetMetadata, keywordAnalyzerWhitelist);
this.datasetMetadata = datasetMetadata;
this.start = start;
this.end = end;
final ImmutableMap.Builder<String, Function<List<Expression>, Grouping>> builder = ImmutableMap.builder();
builder.put("topterms", new Function<List<Expression>, Grouping>() {
public Grouping apply(final List<Expression> input) {
if (input.size() < 2 || input.size() > 4) {
throw new IllegalArgumentException("topterms() takes 2 to 4 arguments. " + input.size() + " given");
}
final String fieldName = getName(input.get(0));
final int topK = parseInt(input.get(1));
final Stat stat;
if (input.size() >= 3) {
stat = input.get(2).match(statMatcher);
} else {
stat = counts();
}
final boolean bottom;
if(input.size() >= 4) {
String ascDesc = getStr(input.get(3));
bottom = ascDesc.equals("bottom");
} else {
bottom = false;
}
final Field field = getField(fieldName, datasetMetadata);
return new FieldGrouping(field, topK, stat, bottom);
}
});
Function<List<Expression>, Grouping> bucketHandler =
new Function<List<Expression>, Grouping>() {
public Grouping apply(final List<Expression> input) {
if (input.size() == 4) {
final long min = parseLong(input.get(1));
final long max = parseLong(input.get(2));
final long interval = parseTimeBucketInterval(getStr(input.get(3)), false, 0, 0);
return new StatRangeGrouping(input.get(0).match(statMatcher), min, max, interval, new LongStringifier());
} else if (input.size() == 8) {
final Stat xStat = input.get(0).match(statMatcher);
final long xMin = parseLong(input.get(1));
final long xMax = parseLong(input.get(2));
final long xInterval = parseTimeBucketInterval(getStr(input.get(3)), false, 0, 0);
final Stat yStat = input.get(4).match(statMatcher);
final long yMin = parseLong(input.get(5));
final long yMax = parseLong(input.get(6));
final long yInterval = parseTimeBucketInterval(getStr(input.get(7)), false, 0, 0);
return new StatRangeGrouping2D(xStat, xMin, xMax, xInterval, yStat, yMin, yMax, yInterval);
} else {
throw new IllegalArgumentException("Bucketing function takes 1 or 2 groups of following arguments: stat, min, max, bucket_size");
}
}
};
builder.put("bucket", bucketHandler);
builder.put("buckets", bucketHandler);
Function<List<Expression>, Grouping> timeHandler = new Function<List<Expression>, Grouping>() {
public Grouping apply(final List<Expression> input) {
if (input.size() > 3) {
throw new IllegalArgumentException("time function takes up to 3 args");
}
final String bucket = input.size() > 0 ? getStr(input.get(0)) : null;
final String format = input.size() > 1 ? getStr(input.get(1)) : null;
final Expression timeField = input.size() > 2 ? input.get(2) : null;
return timeBuckets(bucket, format, timeField);
}
};
builder.put("timebuckets", timeHandler);
builder.put("time", timeHandler);
functionLookup = builder.build();
}
private Grouping timeBuckets(String bucket, String format, Expression timeField) {
final int min = (int) (start.getMillis()/1000);
final int max = (int) (end.getMillis()/1000);
final long interval = parseTimeBucketInterval(bucket, true, min, max);
final DateTimeFormatter dateTimeFormatter;
if (format != null) {
dateTimeFormatter = DateTimeFormat.forPattern(format);
} else {
dateTimeFormatter = DateTimeFormat.forPattern("YYYY-MM-dd HH:mm:ss");
}
final Stringifier<Long> stringifier = new Stringifier<Long>() {
public String toString(final Long integer) {
return new DateTime(integer*1000).toString(dateTimeFormatter);
}
public Long fromString(final String str) {
return (new DateTime(str).getMillis()/1000);
}
};
final Stat stat;
if (timeField != null) {
stat = timeField.match(statMatcher);
} else {
// TODO: time field inference?
stat = intField(datasetMetadata.getTimeFieldName());
}
return new StatRangeGrouping(stat, min, max, interval, stringifier);
}
private long parseTimeBucketInterval(String bucketSizeStr, boolean isTime, int min, int max) {
if(Strings.isNullOrEmpty(bucketSizeStr)) {
bucketSizeStr = inferTimeBucketSize();
}
long bucketSize;
if(StringUtils.isNumeric(bucketSizeStr)) {
// given a pure number
bucketSize = Long.parseLong(bucketSizeStr);
if(isTime) {
// no suffix specified for a time bucket size.
// assume hours instead of seconds to avoid overflows due to unintended second buckets
bucketSize *= SECONDS_IN_HOUR;
}
} else if(bucketSizeStr.charAt(bucketSizeStr.length()-1) == 'b' && min > 0 && max > 0) {
// given the number of buckets instead of the bucket size. so compute the bucket size ourselves
int bucketCount = Integer.parseInt(bucketSizeStr.substring(0, bucketSizeStr.length() - 1));
return (long)Math.ceil((max-min) / (double)bucketCount); // bucket size rounded up
} else {
Period period = PeriodParser.parseString(bucketSizeStr);
if(period == null) {
throw new IllegalArgumentException("Bucket size argument couldn't be parsed: " + bucketSizeStr);
}
if(period.getMonths() > 0 || period.getYears() > 0) {
throw new IllegalArgumentException("Months and years are not supported as bucket sizes because they vary in length. " +
"Please convert to a fixed period (e.g days, weeks) or request an absolute number of buckets (e.g. 5b)");
}
bucketSize = period.toStandardSeconds().getSeconds();
}
// validate time period bucketing is compatible with the given time range
if(isTime) {
int xMin = (int)(start.getMillis() / 1000);
int xMax = (int)(end.getMillis() / 1000);
long timePeriod = xMax - xMin;
if (timePeriod % bucketSize != 0) {
StringBuilder exceptionBuilder = new StringBuilder("You requested a time period (");
appendTimePeriod(timePeriod, exceptionBuilder);
exceptionBuilder.append(") not evenly divisible by the bucket size (");
appendTimePeriod(bucketSize, exceptionBuilder);
exceptionBuilder.append("). To correct, increase the time range by ");
appendTimePeriod(bucketSize - timePeriod%bucketSize, exceptionBuilder);
exceptionBuilder.append(" or reduce the time range by ");
appendTimePeriod(timePeriod%bucketSize, exceptionBuilder);
throw new IllegalArgumentException(exceptionBuilder.toString());
}
}
return bucketSize;
}
private static int appendTimePeriod(long timePeriod, StringBuilder builder) {
final int timePeriodUnits;
if (timePeriod % SECONDS_IN_WEEK == 0) {
// duration is in days
builder.append(timePeriod / SECONDS_IN_WEEK);
builder.append(" weeks");
timePeriodUnits = SECONDS_IN_WEEK;
} else if (timePeriod % SECONDS_IN_DAY == 0) {
// duration is in days
builder.append(timePeriod / SECONDS_IN_DAY);
builder.append(" days");
timePeriodUnits = SECONDS_IN_DAY;
} else if (timePeriod % SECONDS_IN_HOUR == 0) {
// duration is in hours
builder.append(timePeriod / SECONDS_IN_HOUR);
builder.append(" hours");
timePeriodUnits = SECONDS_IN_HOUR;
} else if (timePeriod % SECONDS_IN_MINUTE == 0) {
// duration is in minutes
builder.append(timePeriod / SECONDS_IN_MINUTE);
builder.append(" minutes");
timePeriodUnits = SECONDS_IN_MINUTE;
} else {
// duration is seconds
builder.append(timePeriod);
builder.append(" seconds");
timePeriodUnits = 1;
}
return timePeriodUnits;
}
private static final int SECONDS_IN_MINUTE = 60;
private static final int SECONDS_IN_HOUR = SECONDS_IN_MINUTE * 60;
private static final int SECONDS_IN_DAY = SECONDS_IN_HOUR * 24;
private static final int SECONDS_IN_WEEK = SECONDS_IN_DAY * 7;
protected Grouping functionExpression(final String name, final List<Expression> args) {
final Function<List<Expression>, Grouping> function = functionLookup.get(name);
if (function == null) {
throw new IllegalArgumentException("Unknown function in group by: " + name);
}
return function.apply(args);
}
protected Grouping nameExpression(final String name) {
if("time".equals(name)) { // time buckets special case
return timeBuckets(null, null, null);
} // else // normal simple field grouping
final Field field = getField(name, datasetMetadata);
return new FieldGrouping(field);
}
@Override
protected Grouping bracketsExpression(final String field, final String content) {
return topTerms(field, content);
}
@Override
protected Grouping binaryExpression(final Expression left, final Op op, final Expression right) {
switch (op) {
case IN:
{
final NameExpression name = (NameExpression) left;
final TupleExpression values = (TupleExpression) right;
List<String> terms = Lists.newArrayListWithCapacity(values.expressions.size());
for (Expression expression : values.expressions) {
terms.add(getStr(expression));
}
final Field field = getField(name.name, datasetMetadata);
return new FieldInGrouping(field, terms);
}
default:
throw new UnsupportedOperationException();
}
}
private String inferTimeBucketSize() {
Period period = new Period(start, end,
PeriodType.forFields(new DurationFieldType[]{DurationFieldType.weeks(), DurationFieldType.days(),
DurationFieldType.hours(), DurationFieldType.minutes(), DurationFieldType.seconds()})
);
// try various sizes from smallest to largest until we find one that gives us number of buckets no more than we want
for(int i = 0; i <= 4; i++) {
int buckets;
String value;
switch (i) {
case 4: {
buckets = period.toStandardWeeks().getWeeks();
value = "1w";
break;
}
case 3: {
buckets = period.toStandardDays().getDays();
value = "1d";
break;
}
case 2: {
buckets = period.toStandardHours().getHours();
value = "1h";
break;
}
case 1: {
buckets = period.toStandardMinutes().getMinutes();
value = "1m";
break;
}
case 0: {
buckets = period.toStandardSeconds().getSeconds();
value = "1s";
break;
}
default: {
throw new RuntimeException("Shouldn't happen");
}
}
if(buckets < MAX_RECOMMENDED_BUCKETS) {
return value;
}
}
// we should never get here but just in case
return "1w";
}
private final String syntaxExamples =
"Syntax examples:" +
"\nTop terms: country[top 5 by sjc]" +
"\nBucketing: buckets(oji, 0, 10, 1)";
private Grouping topTerms(String fieldName, String arg) {
if(arg == null || arg.trim().isEmpty()) {
// treat as a request to get all terms but not explode
final Field field = getField(fieldName, datasetMetadata);
return new FieldGrouping(field, true);
}
Pattern topTermsPattern = Pattern.compile("\\s*(?:(top|bottom)\\s+)?(\\d+)\\s*(?:\\s*(?:by|,)\\s*(.+))?\\s*");
Matcher matcher = topTermsPattern.matcher(arg);
if(!matcher.matches()) {
throw new IllegalArgumentException("'group by' part treated as top terms couldn't be parsed: " +
fieldName + "[" + arg + "].\n" + syntaxExamples);
}
final int topK = Integer.parseInt(matcher.group(2));
final Stat stat;
String statStr = matcher.group(3);
if (!Strings.isNullOrEmpty(statStr)) {
try {
Expression statExpression = ExpressionParser.parseExpression(statStr);
stat = statExpression.match(statMatcher);
} catch (Exception e) {
throw new IllegalArgumentException("Couldn't parse the stat expression for top terms: " + statStr +
"\n" + syntaxExamples, e);
}
} else {
stat = counts();
}
final boolean bottom = "bottom".equals(matcher.group(1));
final Field field = getField(fieldName, datasetMetadata);
return new FieldGrouping(field, topK, stat, bottom);
}
}
private static int parseInt(Expression expression) {
return Integer.parseInt(((NumberExpression)expression).number);
}
private static long parseLong(Expression expression) {
return Long.parseLong(((NumberExpression) expression).number);
}
private static final Expression.Matcher<String> GET_STR = new Expression.Matcher<String>() {
protected String numberExpression(final String value) {
return value;
}
protected String stringExpression(final String value) {
return value;
}
protected String nameExpression(final String value) {
return value;
}
};
private static String getStr(Expression expression) {
return expression.match(GET_STR);
}
private static String getName(Expression expression) {
return ((NameExpression)expression).name;
}
}
|
//Namespace
package com.katujo.web.utils;
//Java imports
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;
//Google imports
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
/**
* Helps in database communication.
* @author Johan Hertz
*
*/
public class DatabaseManager
{
//This map holds the data sources
private final static Map<String, DataSource> dataSources = new ConcurrentHashMap<String, DataSource>();
//The default data source look up that is used when calling methods without the data source specified
private final String defaultLookup;
/**
* Create the object <b>without</b> a default data source look up set.
*
*/
public DatabaseManager()
{
this.defaultLookup = null;
}
/**
* Create the object with the default data source look up set.
* @param defaultDataSource
*/
public DatabaseManager(String defaultDataSource)
{
this.defaultLookup = defaultDataSource;
}
/**
* Get the default data source.
* @return
* @throws Exception
*/
protected DataSource getDataSource() throws Exception
{
return getDataSource(defaultLookup);
}
/**
* Get the data source using the JNDI name.
* <p>
* On Tomcat this should be java:comp/env/DATA_SOURCE_NAME
* </p>
* @param name
* @return
* @throws Exception
*/
protected DataSource getDataSource(String lookup) throws Exception
{
//Try to get the data source
try
{
//Get the data source from the map
DataSource source = dataSources.get(lookup);
//Create and add the data source if not set
if(source == null)
{
//Get the context objects
Context initCtx = new InitialContext();
source = (DataSource) initCtx.lookup(lookup);
//Add the source to the data sources
dataSources.put(lookup, source);
}
//Return the source
return source;
}
//Failed
catch(Exception ex)
{
throw new Exception("Failed to get the data source with lookup " + lookup, ex);
}
}
/**
* Get a connection from the default data source.
* <p>
* This connection must be explicitly closed by the caller.
* </p>
* @return
* @throws Exception
*/
public Connection getConnection() throws Exception
{
//Try to get a connection
try {return getDataSource(defaultLookup).getConnection();}
//Failed
catch(Exception ex)
{
throw new Exception("Failed to get a connection", ex);
}
}
/**
* Get a connection from the named data source.
* <p>
* This connection must be explicitly closed by the caller.
* </p>
* @param name
* @return
* @throws Exception
*/
public Connection getConnection(String name) throws Exception
{
//Try to get a connection
try {return getDataSource(name).getConnection();}
//Failed
catch(Exception ex)
{
throw new Exception("Failed to get a connection", ex);
}
}
/**
* Load a JSON object from the database using the SQL.
* <p>
* If no result matched the query null will be returned.
* </p>
* @param sql
* @return
* @throws Exception
*/
protected JsonObject getObject(String sql) throws Exception
{
return getObject(sql, new Object[]{});
}
/**
* Load a JSON object from the database using the SQL and the parameter.
* <p>
* If no result matched the query null will be returned.
* </p>
* @param sql
* @param parameter
* @return
* @throws Exception
*/
protected JsonObject getObject(String sql, Object parameter) throws Exception
{
return getObject(sql, new Object[]{parameter});
}
/**
* Load a JSON object from the database using the SQL and the parameters.
* <p>
* If no result matched the query null will be returned.
* </p>
* @param sql
* @param parameters
* @return
* @throws Exception
*/
protected JsonObject getObject(String sql, Object[] parameters) throws Exception
{
//Fields
Connection connection = null;
PreparedStatement statement = null;
ResultSet result = null;
//Try to read data
try
{
//Get a connection
connection = getConnection();
//Create the statement
statement = connection.prepareStatement(sql);
//Set the parameters if set
if(parameters != null)
for(int i=0; i<parameters.length; i++)
statement.setObject(i+1, parameters[i]);
//Run the statement
result = statement.executeQuery();
//Move the result set
boolean found = result.next();
//No result found
if(!found) return null;
//Read and return the result
return JsonUtils.createJsonObject(result);
}
//Failed
catch(Exception ex)
{
throw new Exception("Failed to get JSON object from database result set", ex);
}
//Clean up
finally
{
try {result.close();} catch(Throwable t) {}
try {statement.close();} catch(Throwable t) {}
try {connection.close();} catch(Throwable t) {}
}
}
/**
* Load a JSON array of JSON objects from the database using the SQL.
* @param sql
* @return
* @throws Exception
*/
protected JsonArray getArray(String sql) throws Exception
{
return getArray(sql, new Object[]{});
}
/**
* Load a JSON array of JSON objects from the database using SQL and the parameter.
* @param sql
* @param parameter
* @return
* @throws Exception
*/
protected JsonArray getArray(String sql, Object parameter) throws Exception
{
return getArray(sql, new Object[]{parameter});
}
/**
* Load a JSON array of JSON objects from the database using the SQL and the parameters.
* @param sql
* @param parameters
* @return
* @throws Exception
*/
protected JsonArray getArray(String sql, Object[] parameters) throws Exception
{
//Fields
Connection connection = null;
PreparedStatement statement = null;
ResultSet result = null;
//Try to read data
try
{
//Get a connection
connection = getConnection();
//Create the statement
statement = connection.prepareStatement(sql);
//Set the parameters if set
if(parameters != null)
for(int i=0; i<parameters.length; i++)
statement.setObject(i+1, parameters[i]);
//Run the statement
result = statement.executeQuery();
//Create the array and return it
return JsonUtils.createJsonArray(result);
}
//Failed
catch(Exception ex)
{
throw new Exception("Failed to get JSON array from database result set", ex);
}
//Clean up
finally
{
try {result.close();} catch(Throwable t) {}
try {statement.close();} catch(Throwable t) {}
try {connection.close();} catch(Throwable t) {}
}
}
/**
* Execute the SQL with the parameter.
* @param sql
* @param parameter
* @throws Exception
*/
protected void execute(String sql, Object parameter) throws Exception
{
this.execute(sql, new Object[]{parameter});
}
/**
* Execute the SQL with the parameters.
* @param sql
* @param parameters
* @throws Exception
*/
protected void execute(String sql, Object[] parameters) throws Exception
{
//Fields
Connection connection = null;
//Try to execute the SQL
try
{
//Get a connection
connection = getConnection();
//Execute the SQL using the connection
execute(connection, sql, parameters);
}
//Failed
catch(Exception ex)
{
throw ex;
}
//Clean up
finally
{
try{connection.close();} catch(Throwable t){}
}
}
/**
* Execute the SQL with the parameters on the connection.
* @param connection
* @param sql
* @param parameters
* @throws Exception
*/
protected void execute(Connection connection, String sql, Object[] parameters) throws Exception
{
//Fields
PreparedStatement statement = null;
//Try to execute the SQL
try
{
//Create the statement
statement = connection.prepareStatement(sql);
//Set the parameters if set
if(parameters != null)
for(int i=0; i<parameters.length; i++)
statement.setObject(i+1, parameters[i]);
//Execute the statement
statement.execute();
}
//Failed
catch(Exception ex)
{
throw new Exception("Failed to execute the SQL", ex);
}
//Clean up
finally
{
try {statement.close();} catch(Throwable t) {}
}
}
}
|
package com.klarna.hiverunner;
import com.klarna.hiverunner.config.HiveRunnerConfig;
import org.apache.commons.lang.time.StopWatch;
import org.junit.rules.TestRule;
import org.junit.runner.Description;
import org.junit.runners.model.Statement;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ThrowOnTimeout extends Statement {
private static final Logger LOGGER = LoggerFactory.getLogger(ThrowOnTimeout.class);
private final Statement originalStatement;
private final HiveRunnerConfig config;
private Object target;
private Throwable statementException;
private boolean finished = false;
public ThrowOnTimeout(Statement originalStatement, HiveRunnerConfig config, Object target) {
this.originalStatement = originalStatement;
this.config = config;
this.target = target;
}
@Override
public void evaluate() throws Throwable {
final StopWatch stopWatch = new StopWatch();
if (config.isTimeoutEnabled()) {
LOGGER.warn("Starting timeout monitoring ({}s) of test case {}.", config.getTimeoutSeconds(), target);
}
Thread statementThread = new Thread(new Runnable() {
@Override
public void run() {
try {
stopWatch.start();
originalStatement.evaluate();
finished = true;
} catch (InterruptedException e) {
// Ignore the InterruptedException
LOGGER.debug(e.getMessage(), e);
} catch (Throwable e) {
synchronized (target) {
statementException = e;
}
}
}
});
statementThread.start();
statementThread.join(config.getTimeoutSeconds() * 1000);
synchronized (target) {
if (statementException != null) {
throw statementException;
} else if (!finished) {
if (config.isTimeoutEnabled()) {
statementThread.interrupt();
throw new TimeoutException(
String.format("test timed out after %d seconds", config.getTimeoutSeconds()));
} else {
LOGGER.warn(
"Test ran for {} seconds. Timeout disabled. See class {} for configuration options.",
stopWatch.getTime() / 1000, HiveRunnerConfig.class.getName());
statementThread.join();
if (statementException != null) {
throw statementException;
}
}
}
}
}
public static TestRule create(final HiveRunnerConfig config, final Object target) {
return new TestRule() {
@Override
public Statement apply(Statement base, Description description) {
return new ThrowOnTimeout(base, config, target);
}
};
}
}
|
package com.redoutevant.gitproj;
/**
*
* @author Tiago Pinto 10:00
*/
public class ValidarLogin {
private String username;
private int active;
public int getActive() {
return active;
}
public void setActive(int act) {
this.active = act;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public static void main(String[] args){
}
}
|
package com.sixtyfour.compression;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Locale;
import com.sixtyfour.Assembler;
import com.sixtyfour.Loader;
import com.sixtyfour.config.CompilerConfig;
import com.sixtyfour.system.FileWriter;
import com.sixtyfour.system.Program;
import com.sixtyfour.system.ProgramPart;
/**
* A simple compressor that can compress and uncompress byte[]-arrays based on a
* simple and most likely inefficient sliding window pattern matching algorithm
* that I came up with while being half asleep. It uses a pattern based
* approach, no huffman encoding. That's why it's less efficient but should
* decompress rather quickly.
*
* @author EgonOlsen
*
*/
public class Compressor {
private static final boolean FAST = true;
private static final int MAX_WINDOW_SIZE_1 = 32;
private static final int MAX_WINDOW_SIZE_2 = 128;
private static final int MIN_WINDOW_SIZE = 12;
private static final int CHUNK_SIZE = 32768;
public static void main(String[] args) throws Exception {
testCompressor("E:\\src\\workspace2018\\Adventure\\build\\++xam.prg",
"C:\\Users\\EgonOlsen\\Desktop\\++xam_c.prg");
testCompressor("E:\\src\\workspace2018\\Adventure\\build\\++brotquest.prg",
"C:\\Users\\EgonOlsen\\Desktop\\++brotquest_c.prg");
testCompressor("E:\\src\\workspace2018\\basicv2\\compiled\\++affine.prg",
"C:\\Users\\EgonOlsen\\Desktop\\++affine_c.prg");
testCompressor("E:\\src\\workspace2018\\basicv2\\compiled\\+xtris2.prg",
"C:\\Users\\EgonOlsen\\Desktop\\++xtris2_c.prg");
testCompressor("E:\\src\\workspace2018\\basicv2\\compiled\\+19 - StarDuel.prg",
"C:\\Users\\EgonOlsen\\Desktop\\++StarDuel_c.prg");
}
private static void testCompressor(String fileName, String resultFile) throws Exception {
byte[] bytes = loadProgram(fileName);
Program prg = compressAndLinkNative(bytes);
if (prg != null) {
FileWriter.writeAsPrg(prg, resultFile, false);
}
}
public static int[] convert(byte[] bytes) {
int[] res = new int[bytes.length];
for (int i = 0; i < bytes.length; i++) {
res[i] = bytes[i] & 0xff;
}
return res;
}
public static byte[] compress(byte[] dump, int windowSize) {
long time = System.currentTimeMillis();
int minSize = MIN_WINDOW_SIZE;
int len = dump.length;
if (len > 65536) {
throw new RuntimeException("This compressor can't compress anything larger than 64KB!");
}
byte[] window = new byte[windowSize];
fillWindow(dump, window, 0);
List<Part> parts = findMatches(dump, windowSize, minSize, len, window, FAST);
byte[] bos = compress(parts, dump);
if (bos.length >= len) {
log("No further compression possible!");
return null;
}
log("Binary compressed from " + len + " to " + bos.length + " bytes in " + (System.currentTimeMillis() - time)
+ "ms");
DecimalFormatSymbols symbols = new DecimalFormatSymbols(Locale.ENGLISH);
DecimalFormat decFor = new DecimalFormat("###.##", symbols);
log("Bytes saved: " + (len - bos.length));
log("Compression ratio: 1:" + decFor.format(((float) len / bos.length)));
return bos;
}
/**
* Decompresses the compressed data
*
* @param bytes
* @return
*/
public static byte[] decompress(byte[] bytes) {
long time = System.currentTimeMillis();
int clen = bytes.length;
int data = readLowHigh(bytes, 0);
int compLen = readLowHigh(bytes, 2);
int ucLen = readLowHigh(bytes, 4);
int headerOffset = 6;
int dataPos = headerOffset;
byte[] res = new byte[65536];
int pos = 0;
for (int i = data; i < clen;) {
int start = readLowHigh(bytes, i);
int target = 0;
i += 2;
do {
int len = bytes[i] & 0xFF;
i++;
target = 0;
if (len != 0) {
target = readLowHigh(bytes, i);
int copyLen = target - pos;
if (copyLen > 0) {
System.arraycopy(bytes, dataPos, res, pos, copyLen);
dataPos += copyLen;
pos = target;
}
System.arraycopy(res, start, res, target, len);
pos += len;
i += 2;
} else {
i++;
}
} while (target > 0);
}
if (dataPos < data) {
int len = data - dataPos;
System.arraycopy(bytes, dataPos, res, pos, len);
pos += len;
}
if (pos != ucLen) {
throw new RuntimeException("Failed to decompress, size mismatch: " + pos + "/" + ucLen);
}
log("Decompressed from " + compLen + " to " + ucLen + " bytes in " + (System.currentTimeMillis() - time)
+ "ms!");
return Arrays.copyOf(res, pos);
}
/**
* Decompresses the compressed data but unlike decompress(), it does that in one
* block of 64K memory just like the real machine would have to do it.
*
* @param bytes the compressed data
* @return the uncompressed data
*/
public static byte[] decompressInMemory(byte[] bytes) {
long time = System.currentTimeMillis();
int data = readLowHigh(bytes, 0);
int compLen = readLowHigh(bytes, 2);
int ucLen = readLowHigh(bytes, 4);
int memStart = 2049;
int memEnd = 53248;
int headerOffset = 6;
int byteCount = 0;
int totalLen = compLen - headerOffset;
try {
byte[] res = new byte[65536];
// Copy into memory just like it would be located on a real machine...
System.arraycopy(bytes, headerOffset, res, memStart, totalLen);
// Copy compressed data to the end of memory...
int dataPos = memEnd - totalLen;
data -= headerOffset;
int compPos = dataPos + data;
System.arraycopy(res, memStart, res, dataPos, totalLen);
int pos = memStart;
for (int i = compPos; i < memEnd;) {
int start = readLowHigh(res, i) + memStart;
int target = 0;
i += 2;
do {
int len = res[i] & 0xFF;
i++;
target = 0;
if (len != 0) {
target = readLowHigh(res, i) + memStart;
int copyLen = target - pos;
if (copyLen != 0) {
// Copy uncompressed data back down into memory...
byteCount += moveData(res, dataPos, pos, copyLen);
dataPos += copyLen;
pos = target;
}
byteCount += moveData(res, start, target, len);
pos += len;
i += 2;
} else {
i++;
}
} while (target != 0);
}
int left = compPos - dataPos;
if (left > 0) {
byteCount += moveData(res, dataPos, pos, left);
pos += left;
}
int newLen = pos - memStart;
if (newLen != ucLen) {
return null;
}
log("Decompressed from " + compLen + " to " + ucLen + " bytes in " + (System.currentTimeMillis() - time)
+ "ms! (" + byteCount + " bytes moved)");
return Arrays.copyOfRange(res, memStart, memStart + ucLen);
} catch (ArrayIndexOutOfBoundsException e) {
return null;
}
}
public static Program compressAndLinkNative(byte[] bytes) {
log("Trying to find best compression settings...");
byte[] compressedBytes = compress(bytes, MAX_WINDOW_SIZE_1);
byte[] compressedBytes2 = compress(bytes, MAX_WINDOW_SIZE_2);
if (compressedBytes == null) {
compressedBytes = compressedBytes2;
}
if (compressedBytes == null) {
return null;
}
if (compressedBytes2.length < compressedBytes.length) {
compressedBytes = compressedBytes2;
log("Setting 2 used!");
} else {
log("Setting 1 used!");
}
byte[] uncompressed = decompressInMemory(compressedBytes);
if (uncompressed == null || !Arrays.equals(uncompressed, bytes)) {
log("Uncompressed data and data table overlap, no compression performed!");
return null;
}
Program prg = compileHeader();
ProgramPart first = prg.getParts().get(0);
ProgramPart pp = new ProgramPart();
pp.setBytes(convert(compressedBytes));
pp.setAddress(first.getEndAddress());
pp.setEndAddress(pp.getAddress() + pp.getBytes().length);
prg.addPart(pp);
int size = pp.getEndAddress() - first.getAddress();
if (size >= bytes.length) {
log("No further compression possible!");
return null;
}
return prg;
}
public static byte[] loadProgram(String fileName) {
log("Compressing " + fileName);
byte[] bytes = Loader.loadBlob(fileName);
// Remove the prg header in this case...
bytes = Arrays.copyOfRange(bytes, 2, bytes.length);
return bytes;
}
private static Program compileHeader() {
log("Assembling decompressor...");
Assembler assy = new Assembler(
Loader.loadProgram(Compressor.class.getResourceAsStream("/compressor/decruncher.asm")));
assy.compile(new CompilerConfig());
ProgramPart prg = assy.getProgram().getParts().get(0);
log("Assembling decompression header...");
String[] headerCode = Loader.loadProgram(Compressor.class.getResourceAsStream("/compressor/header.asm"));
List<String> code = new ArrayList<>(Arrays.asList(headerCode));
List<String> res = new ArrayList<>();
for (int i = 0; i < code.size(); i++) {
String line = code.get(i);
if (line.contains("{code}")) {
int[] bytes = prg.getBytes();
int cnt = 0;
String nl = ".byte";
for (int p = 0; p < bytes.length; p++) {
nl += " $" + Integer.toHexString(bytes[p] & 0xff);
cnt++;
if (cnt == 16) {
res.add(nl);
nl = ".byte";
cnt = 0;
}
}
if (nl.length() > 5) {
res.add(nl);
}
} else {
res.add(line);
}
}
// res.forEach(p -> System.out.println(p));
assy = new Assembler(res.toArray(new String[res.size()]));
assy.compile(new CompilerConfig());
return assy.getProgram();
}
private static int moveData(byte[] res, int dataPos, int pos, int dataLen) {
System.arraycopy(res, dataPos, res, pos, dataLen);
return dataLen;
}
private static byte[] compress(List<Part> parts, byte[] dump) {
ByteArrayOutputStream footer = new ByteArrayOutputStream();
ByteArrayOutputStream data = new ByteArrayOutputStream();
int pos = 0;
int lastStart = -1;
for (Part part : parts) {
int start = part.sourceAddress;
int target = part.targetAddress;
if (target > pos) {
data.write(dump, pos, target - pos);
pos = target;
}
pos += part.size;
if (start != lastStart) {
if (lastStart != -1) {
writeEndFlag(footer);
}
writeLowHigh(footer, start);
}
lastStart = start;
footer.write(part.size);
writeLowHigh(footer, part.targetAddress);
}
data.write(dump, pos, dump.length - pos);
writeEndFlag(footer);
ByteArrayOutputStream res = new ByteArrayOutputStream();
int dataLen = data.size() + 6;
writeLowHigh(res, dataLen);
writeLowHigh(res, dataLen + footer.size());
writeLowHigh(res, dump.length);
try {
res.write(data.toByteArray());
res.write(footer.toByteArray());
} catch (IOException e) {
}
return res.toByteArray();
}
private static void writeEndFlag(ByteArrayOutputStream header) {
header.write(0);
header.write(0);
}
private static int readLowHigh(byte[] bytes, int pos) {
return (bytes[pos] & 0xFF) + ((bytes[pos + 1] & 0xFF) << 8);
}
private static void writeLowHigh(ByteArrayOutputStream header, int start) {
header.write((start & 0xFF));
header.write((start >> 8));
}
/**
* This is O(n*n) and therefore quite inefficient...anyway, it will do for
* now...
*
* @param dump
* @param windowSize
* @param minSize
* @param len
* @param windowPos
* @param window
* @param fastMode Less compression, but a lot faster.
* @return
*/
private static List<Part> findMatches(byte[] dump, int windowSize, int minSize, int len, byte[] window,
boolean fastMode) {
int curSize = windowSize;
int largest = 0;
int windowPos = 0;
List<Part> parts = new ArrayList<>();
byte[] covered = new byte[len];
int chunkSize = CHUNK_SIZE;
for (int lenPart = Math.min(len, chunkSize); lenPart <= len; lenPart += chunkSize) {
do {
for (int i = windowPos + curSize; i < lenPart - curSize; i++) {
if (covered[i] > 0) {
continue;
}
boolean match = true;
for (int p = 0; p < curSize; p++) {
if (covered[i + p] != 0) {
match = false;
break;
}
if (dump[i + p] != window[p]) {
match = false;
if (p > largest) {
largest = p;
}
break;
}
}
if (match) {
for (int h = i; h < i + curSize; h++) {
covered[h] = 1;
}
Part part = new Part(windowPos, i, curSize);
parts.add(part);
i += curSize - 1;
}
}
if (largest >= minSize) {
curSize = largest;
largest = 0;
} else {
if (fastMode) {
windowPos += Math.max(largest, 1);
if (windowPos + windowSize >= lenPart) {
windowPos -= (windowPos + windowSize - lenPart);
}
} else {
windowPos++;
}
curSize = windowSize;
largest = 0;
fillWindow(dump, window, windowPos);
}
} while (windowPos + curSize < lenPart);
windowPos = lenPart - curSize;
}
Collections.sort(parts, new Comparator<Part>() {
@Override
public int compare(Part p1, Part p2) {
return p1.targetAddress - p2.targetAddress;
}
});
// parts.forEach(p -> System.out.println(p));
// log("Iterations taken: " + cnt);
return parts;
}
private static void fillWindow(byte[] dump, byte[] window, int pos) {
System.arraycopy(dump, pos, window, 0, window.length);
}
private static void log(String txt) {
System.out.println(txt);
}
private static class Part {
Part(int source, int target, int size) {
this.sourceAddress = source;
this.targetAddress = target;
this.size = size;
}
int sourceAddress;
int targetAddress;
int size;
@Override
public String toString() {
return "block@ " + sourceAddress + "/" + targetAddress + "/" + size;
}
}
}
|
package com.vtence.molecule.http;
public interface HeaderNames {
static final String ACCEPT_ENCODING = "Accept-Encoding";
static final String ACCEPT_LANGUAGE = "Accept-Language";
static final String ALLOW = "Allow";
static final String CACHE_CONTROL = "Cache-Control";
static final String CONTENT_ENCODING = "Content-Encoding";
static final String CONTENT_LANGUAGE = "Content-Language";
static final String CONTENT_LENGTH = "Content-Length";
static final String CONTENT_TYPE = "Content-Type";
static final String DATE = "Date";
static final String ETAG = "ETag";
static final String IF_MODIFIED_SINCE = "If-Modified-Since";
static final String IF_NONE_MATCH = "If-None-Match";
static final String LAST_MODIFIED = "Last-Modified";
static final String LOCATION = "Location";
static final String SERVER = "Server";
static final String TRANSFER_ENCODING = "Transfer-Encoding";
}
|
package com.yiji.falcon.agent.web;
/*
* :
* guqiu@yiji.com 2016-07-26 13:45
*/
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
/**
* @author guqiu@yiji.com
*/
public class HttpServer extends Thread{
private final Logger logger = LoggerFactory.getLogger(this.getClass());
private static final String SHUTDOWN_COMMAND = "/__SHUTDOWN__";
private boolean shutdown = false;
/**
* 0 :
* 1 :
* -1 :
*/
public static int status = 0;
private int port;
private ServerSocket serverSocket;
public HttpServer(int port) {
this.port = port;
}
@Override
public void run() {
try {
startServer();
} catch (IOException e) {
logger.error("web",e);
status = 0;
System.exit(0);
}
}
public void startServer() throws IOException {
serverSocket = new ServerSocket(port, 10, InetAddress.getLocalHost());
logger.info("Web:http://{}:{}",serverSocket.getInetAddress().getHostName(),serverSocket.getLocalPort());
status = 1;
while (!shutdown) {
Socket socket;
InputStream input;
OutputStream output;
try {
socket = serverSocket.accept();
input = socket.getInputStream();
output = socket.getOutputStream();
Request request = new Request(input);
request.parse();
Response response = new Response(output);
response.setRequest(request);
shutdown = SHUTDOWN_COMMAND.equals(request.getUri());
if(shutdown){
status = -1;
response.send("Shutdown OK");
}else{
response.doRequest();
}
socket.close();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
try {
close();
} catch (IOException e) {
logger.error("web",e);
}
}
private void close() throws IOException {
if(serverSocket != null && !serverSocket.isClosed()){
serverSocket.close();
status = 0;
logger.info("Web ");
}
}
}
|
package cz.jcu.prf.uai.javamugs.logic;
import sun.reflect.generics.reflectiveObjects.NotImplementedException;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
public class Buffer {
private Queue<Chord> chordQueue;
private List<Double> pressTimes;
private int tolerance;
/**
* Creates Buffer with set difficulty
*
* @param difficulty 1-3 - tolerance of hits and misses
*/
public Buffer(byte difficulty) {
chordQueue = new LinkedList<Chord>();
pressTimes = new ArrayList<Double>();
switch (difficulty) {
case 1:
this.tolerance = 150;
break;
case 2:
this.tolerance = 100;
break;
case 3:
this.tolerance = 50;
break;
}
}
/**
* Adds chord to queue and time to list.
*
* @param chord Chord to add to buffer
* @param pressTime time to when the chord should be pressed
*/
public void addToBuffer(Chord chord, double pressTime) {
if(!chord.isEmpty()) {
chordQueue.add(chord);
pressTimes.add(pressTime);
}
}
/**
* Checks if time exists in list and dequeue Chords from queue if so.
*
* @param pressedKeys Chord of pressed keys from
* @param pressTime Time of the press
* @return Pair of hits and misses, never null
*/
public BufferReport check(Chord pressedKeys, double pressTime) {
double minTime = pressTime - tolerance;
double maxTime = pressTime + tolerance;
int hits = 0;
int misses = 0;
double chordTime = -1;
int chordTimeIndex = -1;
for (int i = 0; i < pressTimes.size(); i++) { // get expected chord time
double time = pressTimes.get(i);
if (time > minTime && time < maxTime) {
chordTime = time;
chordTimeIndex = i;
break;
}
}
Chord expectedChord;
if (chordTime > 0) { // get expected chord
expectedChord = chordQueue.peek();
} else {
expectedChord = new Chord(false, false, false, false, false);
}
for (int i = 0; i < 5; i++) {
if (pressedKeys.getChords()[i] && !expectedChord.getChords()[i] // key pressed, nothing expected
|| !pressedKeys.getChords()[i] && expectedChord.getChords()[i]) { // nothing pressed, key press expected
misses++;
}
if (pressedKeys.getChords()[i] && expectedChord.getChords()[i]) {
hits++;
}
}
if(hits > 0) {
chordQueue.poll();
pressTimes.remove(chordTimeIndex);
} else {
// delete by time
for (int i = 0; i < pressTimes.size(); i++) {
if(pressTimes.get(i) < chordTime - tolerance) {
pressTimes.remove(i);
i
chordQueue.poll();
misses++;
}
}
}
return new BufferReport(hits, misses, expectedChord);
}
/**
* @return size of Chord queue
*/
public int getChordCount() {
return chordQueue.size();
}
/**
* @return size of times list
*/
public int getTimesCount() {
return pressTimes.size();
}
}
|
package de.dakror.arise.server;
import de.dakror.arise.net.Server;
import de.dakror.arise.net.User;
import de.dakror.arise.net.packet.Packet02Disconnect;
import de.dakror.arise.net.packet.Packet02Disconnect.Cause;
/**
* @author Dakror
*/
public class ServerUpdater extends Thread
{
boolean running;
long lastCheck;
public ServerUpdater()
{
running = true;
start();
}
@Override
public void run()
{
try
{
while (running)
{
DBManager.updateBuildingTimers();
DBManager.updateBuildingStage();
if (System.currentTimeMillis() - lastCheck >= 60000)
{
DBManager.updateCityResources();
DBManager.dispatchCityResources();
kickInactiveUsers();
// DakrorBin.checkForUpdates();
lastCheck = System.currentTimeMillis();
}
System.gc();
Thread.sleep(1000);
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
public void kickInactiveUsers() throws Exception
{
long hourInMs = 1000 * 60 * 60;
for (User u : Server.currentServer.clients)
{
if (System.currentTimeMillis() - u.getLastInteraction() > hourInMs)
{
Server.currentServer.sendPacket(new Packet02Disconnect(0, Cause.KICK), u);
Server.out("Kicked user: #" + u.getId() + " (" + Cause.KICK + ")");
Server.currentServer.clients.remove(u);
}
}
}
}
|
package de.dhbw.humbuch.model;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import de.dhbw.humbuch.model.entity.Grade;
import de.dhbw.humbuch.model.entity.ProfileType;
import de.dhbw.humbuch.model.entity.Student;
public class StudentHandler {
public static String getFullNameOfStudent(Student student){
return student.getFirstname() + " " + student.getLastname();
}
}
|
package ee.shy.cli.command;
import ee.shy.cli.Command;
import ee.shy.cli.SuperCommand;
import java.io.IOException;
import java.util.Map;
public class CompletionCommand implements Command {
private final Command rootCommand;
public CompletionCommand(Command rootCommand) {
this.rootCommand = rootCommand;
}
@Override
public void execute(String[] args) throws IOException {
Command command = rootCommand;
for (int i = 0; i <= args.length; i++) { // loop for one extra time for supercommands without arguments
if (command instanceof SuperCommand) {
Map<String, Command> subCommands = ((SuperCommand) command).getSubCommands();
Command subCommand;
if ((i < args.length - 1) // complete subcommand even if fully typed (don't nest yet)
&& ((subCommand = subCommands.get(args[i])) != null)) {
command = subCommand;
}
else {
System.out.println(String.join(" ", subCommands.keySet()));
break;
}
}
else if (command instanceof HelpCommand) {
command = ((HelpCommand) command).getRootCommand(); // changed command point without parsing extra argument
i--; // step back for that extra argument
}
}
}
@Override
public String getHelp() {
return null;
}
}
|
package gavel.base.sanction;
import static gavel.impl.sanction.Sanctions.getStructureName;
import gavel.api.common.LogicalFormula;
import gavel.api.common.Status;
import gavel.api.sanction.Sanction;
import gavel.api.sanction.SanctionCategory;
import gavel.impl.common.DefaultStatus;
import lombok.AccessLevel;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.Setter;
/**
* @author igorcadelima
*
*/
@Data
@AllArgsConstructor(access = AccessLevel.PROTECTED)
public abstract class AbstractSanction implements Sanction {
private final String id;
@Setter(AccessLevel.NONE)
private Status status = DefaultStatus.ENABLED;
private final LogicalFormula condition;
private final SanctionCategory category;
private final LogicalFormula content;
@Override
public boolean enable() {
if (status == DefaultStatus.DISABLED) {
status = DefaultStatus.ENABLED;
return true;
}
return false;
}
@Override
public boolean disable() {
if (status == DefaultStatus.ENABLED) {
status = DefaultStatus.DISABLED;
return true;
}
return false;
}
@Override
public String toString() {
return new StringBuilder(getStructureName() + '(').append("id(" + id + "),")
.append("status(" + status + "),")
.append("condition(" + condition + "),")
.append("category(" + category + "),")
.append("content(" + content + "))")
.toString();
}
}
|
package hdm.pk070.jscheme.eval;
import hdm.pk070.jscheme.error.SchemeError;
import hdm.pk070.jscheme.obj.SchemeObject;
import hdm.pk070.jscheme.obj.builtin.function.SchemeBuiltinFunction;
import hdm.pk070.jscheme.obj.builtin.simple.SchemeCons;
import hdm.pk070.jscheme.obj.builtin.simple.SchemeNil;
import hdm.pk070.jscheme.obj.builtin.simple.SchemeSymbol;
import hdm.pk070.jscheme.obj.builtin.syntax.SchemeBuiltinSyntax;
import hdm.pk070.jscheme.reader.SchemeReader;
import hdm.pk070.jscheme.stack.SchemeCallStack;
import hdm.pk070.jscheme.table.environment.Environment;
import hdm.pk070.jscheme.table.environment.entry.EnvironmentEntry;
/**
* A class for evaluating all kinds of Scheme lists.
*
* @author patrick.kleindienst
*/
class ListEvaluator extends AbstractEvaluator<SchemeCons> {
static ListEvaluator getInstance() {
return new ListEvaluator();
}
private ListEvaluator() {
}
/**
* Takes an arbitrary list expression from the {@link SchemeReader} as well as an {@link Environment} and passes
* it along to a specified evaluation class depending on what kind of expression it has been given. For this, it
* has to evaluate the function slot, which is accessible as the CAR of the list expression.
*
* @param expression
* The list expression to evaluate
* @param environment
* The evaluation context
* @return A {@link SchemeObject} as a list evaluation result
* @throws SchemeError
*/
@Override
public SchemeObject doEval(SchemeCons expression, Environment<SchemeSymbol, EnvironmentEntry> environment) throws
SchemeError {
// Extract function slot (car of expression)
SchemeObject functionSlot = expression.getCar();
// Evaluate function slot
SchemeObject evaluatedFunctionSlot = SchemeEval.getInstance().eval(functionSlot, environment);
// Extract arg list (cdr of expression)
SchemeObject argumentList = expression.getCdr();
// Check if function slot is built-in function
if (evaluatedFunctionSlot.subtypeOf(SchemeBuiltinFunction.class)) {
return evaluateBuiltinFunction(((SchemeBuiltinFunction) evaluatedFunctionSlot), argumentList, environment);
// Check if function slot is built-in syntax (e.g. define)
} else if (evaluatedFunctionSlot.subtypeOf(SchemeBuiltinSyntax.class)) {
return evaluateBuiltinSyntax(((SchemeBuiltinSyntax) evaluatedFunctionSlot), argumentList, environment);
}
// Reaching this section means we don't have a valid function slot -> throw SchemeError
throw new SchemeError(String.format("application: not a procedure [expected: procedure that can be applied to" +
" arguments, given: %s]", functionSlot));
}
private SchemeObject evaluateBuiltinSyntax(SchemeBuiltinSyntax builtinSyntax, SchemeObject argumentList,
Environment<SchemeSymbol, EnvironmentEntry> environment) {
return builtinSyntax.apply(argumentList, environment);
}
/**
* Gets passed a {@link SchemeBuiltinFunction} and evaluates it in the context of the {@link Environment}
* argument.
*
* @param builtinFunction
* The pre-defined function to call
* @param argumentList
* The argument list for the function call
* @param environment
* The {@link Environment} the function body gets evaluated in
* @return A {@link SchemeObject} as a result of the function call
* @throws SchemeError
*/
private SchemeObject evaluateBuiltinFunction(SchemeBuiltinFunction builtinFunction, SchemeObject argumentList,
Environment<SchemeSymbol, EnvironmentEntry> environment) throws
SchemeError {
SchemeObject restArguments;
restArguments = argumentList;
int argumentCount = 0;
// as long as end of argumentList is not reached ...
while (!restArguments.typeOf(SchemeNil.class)) {
SchemeObject currentArgument = ((SchemeCons) restArguments).getCar();
SchemeObject evaluatedArgument = SchemeEval.getInstance().eval(currentArgument, environment);
restArguments = ((SchemeCons) restArguments).getCdr();
// push evaluated arg to stack
SchemeCallStack.instance().push(evaluatedArgument);
// increment arg counter
argumentCount++;
}
// call built-in function
return builtinFunction.call(argumentCount);
}
}
|
package hudson.plugins.dry;
import hudson.model.AbstractBuild;
import hudson.plugins.analysis.core.BuildResult;
import hudson.plugins.analysis.core.ParserResult;
import hudson.plugins.analysis.core.ResultAction;
/**
* Represents the aggregated results of the DRY analysis in m2 jobs.
*
* @author Ulli Hafner
*/
public class DryReporterResult extends DryResult {
private static final long serialVersionUID = -2812927497499345424L;
/**
* Creates a new instance of {@link DryReporterResult}.
*
* @param build
* the current build as owner of this action
* @param defaultEncoding
* the default encoding to be used when reading and parsing files
* @param result
* the parsed result with all annotations
*/
public DryReporterResult(final AbstractBuild<?, ?> build, final String defaultEncoding,
final ParserResult result) {
super(build, defaultEncoding, result);
}
@Override
protected Class<? extends ResultAction<? extends BuildResult>> getResultActionType() {
return DryMavenResultAction.class;
}
}
|
package io.sigpipe.sing.adapters;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.GZIPInputStream;
import io.sigpipe.sing.dataset.feature.FeatureType;
import io.sigpipe.sing.graph.FeatureHierarchy;
import io.sigpipe.sing.graph.Sketch;
import io.sigpipe.sing.serialization.SerializationInputStream;
import io.sigpipe.sing.util.Geohash;
import io.sigpipe.sing.util.PerformanceTimer;
import io.sigpipe.sing.util.TestConfiguration;
public class MergeSketch {
public static void main(String[] args) throws Exception {
SketchProcessor sp = new SketchProcessor();
List<GeoHashIndexedRecord> records1 = createRecords(args[0]);
List<GeoHashIndexedRecord> records2 = createRecords(args[1]);
PerformanceTimer pt = new PerformanceTimer("time");
System.out.println("Building sketch...");
pt.start();
for (GeoHashIndexedRecord record : records1) {
sp.process(record);
}
pt.stopAndPrint();
System.out.println(sp.getGraphMetrics());
System.out.println("Splitting...");
pt.start();
byte[] region = sp.split("z");
pt.stopAndPrint();
System.out.println(sp.getGraphMetrics());
System.out.println("Building new sketch");
SketchProcessor miniSp = new SketchProcessor();
miniSp.merge(null, region);
System.out.println(miniSp.getGraphMetrics());
for (GeoHashIndexedRecord record : records2) {
miniSp.process(record);
}
byte[] entireRegion = miniSp.split("");
System.out.println("Merging...");
pt.start();
sp.merge(null, entireRegion);
pt.stopAndPrint();
System.out.println(sp.getGraphMetrics());
byte[] big = sp.split("9");
sp.merge(null, big);
System.out.println(sp.getGraphMetrics());
sp.split("9");
sp.split("d");
sp.split("c");
sp.split("f");
sp.split("b");
sp.split("8");
System.out.println(sp.getGraphMetrics());
Runtime runtime = Runtime.getRuntime();
System.gc();
System.gc();
System.out.println();
System.out.println("max=" + runtime.maxMemory());
System.out.println("total=" + runtime.totalMemory());
System.out.println("free=" + runtime.freeMemory());
System.out.println("used=" + (runtime.totalMemory() - runtime.freeMemory()));
sp.split("");
System.out.println(sp.getGraphMetrics());
}
public static List<GeoHashIndexedRecord> createRecords(String fileName)
throws Exception {
System.out.println("Reading metadata blob: " + fileName);
FileInputStream fIn = new FileInputStream(fileName);
BufferedInputStream bIn = new BufferedInputStream(fIn);
SerializationInputStream in = new SerializationInputStream(bIn);
int num = in.readInt();
System.out.println("Records: " + num);
List<GeoHashIndexedRecord> records = new ArrayList<>(num);
for (int i = 0; i < num; ++i) {
float lat = in.readFloat();
float lon = in.readFloat();
byte[] payload = in.readField();
GeoHashIndexedRecord rec = new GeoHashIndexedRecord(
payload, Geohash.encode(lat, lon, 4));
records.add(rec);
if (i % 5000 == 0) {
System.out.print('.');
}
}
System.out.println();
in.close();
return records;
}
}
|
package io.sigpipe.sing.query;
import java.io.IOException;
import java.util.Iterator;
import io.sigpipe.sing.graph.Vertex;
import io.sigpipe.sing.serialization.SerializationOutputStream;
public class PartitionQuery extends RelationalQuery {
@Override
public void serializeResults(
Vertex vertex, SerializationOutputStream out)
throws IOException {
serializeAndDeleteResults(vertex, out);
}
/**
* @return true if the Vertex this method was called on can be deleted;
* Vertices are deletable if the query matched it, AND all of its children.
*/
private boolean serializeAndDeleteResults(
Vertex vertex, SerializationOutputStream out)
throws IOException {
if (pruned.contains(vertex)) {
/* A pruned (non-matching) vertex cannot be deleted */
return false;
}
vertex.getLabel().serialize(out);
out.writeBoolean(vertex.hasData());
if (vertex.hasData() == true) {
vertex.getData().serialize(out);
}
/* How many neighbors are still valid after the pruning process? */
int validNeighbors = 0;
for (Vertex v : vertex.getAllNeighbors()) {
if (pruned.contains(v) == false) {
validNeighbors++;
}
}
out.writeInt(validNeighbors);
boolean deletable = true;
if (validNeighbors != vertex.numNeighbors()) {
/* If some of this vertex's children didn't match the query, it
* cannot be deleted */
deletable = false;
}
Iterator<Vertex> it = vertex.getAllNeighbors().iterator();
while (it.hasNext()) {
Vertex v = it.next();
if (pruned.contains(v) == false) {
if (serializeAndDeleteResults(v, out) == true) {
if (this.metrics != null) {
this.metrics.removeVertex();
if (v.hasData()) {
this.metrics.removeLeaf();
}
}
it.remove();
} else {
deletable = false;
}
}
}
return deletable;
}
}
|
package io.spacedog.services;
import java.util.Arrays;
import java.util.Optional;
import java.util.stream.StreamSupport;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.TextNode;
public class SchemaValidator {
private static enum JsonType {
OBJECT, ARRAY, BOOLEAN, STRING, NUMBER
}
public static JsonNode validate(String type, JsonNode schema) throws InvalidSchemaException {
JsonNode rootObject = checkField(schema, type, true, JsonType.OBJECT).get();
checkIfInvalidField(schema, false, type);
String rootType = checkField(rootObject, "_type", false, JsonType.STRING).orElse(TextNode.valueOf("object"))
.asText();
// if (rootType.equals("stash")) {
// checkStashProperty(type, rootObject);
// } else
if (rootType.equals("object")) {
checkField(rootObject, "_id", false, JsonType.STRING);
Optional<JsonNode> opt = checkField(rootObject, "_acl", false, JsonType.OBJECT);
if (opt.isPresent()) {
checkAcl(type, opt.get());
}
checkIfInvalidField(rootObject, true, "_acl", "_id", "_type");
checkObjectProperties(type, rootObject);
} else
throw InvalidSchemaException.invalidSchemaType(type, rootType);
return schema;
}
private static void checkAcl(String type, JsonNode json) throws InvalidSchemaException {
// TODO implement this
}
private static void checkObjectProperties(String propertyName, JsonNode json) {
Iterable<String> fieldNames = () -> json.fieldNames();
StreamSupport.stream(fieldNames.spliterator(), false).filter(name -> name.charAt(0) != '_').findFirst()
.orElseThrow(() -> InvalidSchemaException.noProperty(propertyName));
StreamSupport.stream(fieldNames.spliterator(), false).filter(name -> name.charAt(0) != '_')
.forEach(name -> checkProperty(name, json.get(name)));
}
private static void checkObjectProperty(String propertyName, JsonNode json) throws InvalidSchemaException {
checkField(json, "_type", false, JsonType.STRING, TextNode.valueOf("object"));
checkField(json, "_required", false, JsonType.BOOLEAN);
checkField(json, "_array", false, JsonType.BOOLEAN);
checkIfInvalidField(json, true, "_type", "_required", "_array");
checkObjectProperties(propertyName, json);
}
private static void checkProperty(String propertyName, JsonNode jsonObject) throws InvalidSchemaException {
if (!jsonObject.isObject())
throw new InvalidSchemaException(
String.format("invalid value [%s] for object property [%s]", jsonObject, propertyName));
Optional<JsonNode> optType = checkField(jsonObject, "_type", false, JsonType.STRING);
String type = optType.isPresent() ? optType.get().asText() : "object";
if (type.equals("text"))
checkTextProperty(propertyName, jsonObject);
else if (type.equals("string"))
checkSimpleProperty(jsonObject, propertyName, type);
else if (type.equals("date"))
checkSimpleProperty(jsonObject, propertyName, type);
else if (type.equals("time"))
checkSimpleProperty(jsonObject, propertyName, type);
else if (type.equals("timestamp"))
checkSimpleProperty(jsonObject, propertyName, type);
else if (type.equals("integer"))
checkSimpleProperty(jsonObject, propertyName, type);
else if (type.equals("long"))
checkSimpleProperty(jsonObject, propertyName, type);
else if (type.equals("float"))
checkSimpleProperty(jsonObject, propertyName, type);
else if (type.equals("double"))
checkSimpleProperty(jsonObject, propertyName, type);
else if (type.equals("boolean"))
checkSimpleProperty(jsonObject, propertyName, type);
else if (type.equals("object"))
checkObjectProperty(propertyName, jsonObject);
else if (type.equals("enum"))
checkEnumProperty(propertyName, jsonObject);
else if (type.equals("geopoint"))
checkSimpleProperty(jsonObject, propertyName, type);
else if (type.equals("stash"))
checkStashProperty(propertyName, jsonObject);
else
throw new InvalidSchemaException("Invalid field type: " + type);
}
private static void checkSimpleProperty(JsonNode json, String propertyName, String propertyType)
throws InvalidSchemaException {
checkField(json, "_required", false, JsonType.BOOLEAN);
checkField(json, "_array", false, JsonType.BOOLEAN);
checkIfInvalidField(json, false, "_type", "_required", "_array");
}
private static void checkStashProperty(String type, JsonNode json) {
checkField(json, "_required", false, JsonType.BOOLEAN);
checkIfInvalidField(json, false, "_type", "_required");
}
private static void checkEnumProperty(String propertyName, JsonNode json) throws InvalidSchemaException {
checkField(json, "_required", false, JsonType.BOOLEAN);
checkField(json, "_array", false, JsonType.BOOLEAN);
checkIfInvalidField(json, false, "_type", "_required", "_array");
}
private static void checkTextProperty(String propertyName, JsonNode json) throws InvalidSchemaException {
checkIfInvalidField(json, false, "_type", "_required", "_language", "_array");
checkField(json, "_required", false, JsonType.BOOLEAN);
checkField(json, "_language", false, JsonType.STRING);
checkField(json, "_array", false, JsonType.BOOLEAN);
}
private static void checkIfInvalidField(JsonNode json, boolean checkSettingsOnly, String... validFieldNames) {
Iterable<String> fieldNames = () -> json.fieldNames();
StreamSupport.stream(fieldNames.spliterator(), false)
.filter(name -> checkSettingsOnly ? name.charAt(0) == ('_') : true).filter(name -> {
for (String validName : validFieldNames) {
if (name.equals(validName))
return false;
}
return true;
}).findFirst().ifPresent(name -> {
throw InvalidSchemaException.invalidField(name, validFieldNames);
});
}
private static void checkField(JsonNode jsonObject, String fieldName, boolean required, JsonType fieldType,
JsonNode anticipatedFieldValue) throws InvalidSchemaException {
checkField(jsonObject, fieldName, required, fieldType)
.ifPresent(fieldValue -> {
if (!fieldValue.equals(anticipatedFieldValue))
throw InvalidSchemaException.invalidFieldValue(fieldName, fieldValue, anticipatedFieldValue);
});
}
private static Optional<JsonNode> checkField(JsonNode jsonObject, String fieldName, boolean required,
JsonType fieldType) throws InvalidSchemaException {
JsonNode fieldValue = jsonObject.get(fieldName);
if (fieldValue == null)
if (required)
throw new InvalidSchemaException("This schema field is required: " + fieldName);
else
return Optional.empty();
if ((fieldValue.isObject() && fieldType == JsonType.OBJECT)
|| (fieldValue.isTextual() && fieldType == JsonType.STRING)
|| (fieldValue.isArray() && fieldType == JsonType.ARRAY)
|| (fieldValue.isBoolean() && fieldType == JsonType.BOOLEAN)
|| (fieldValue.isNumber() && fieldType == JsonType.NUMBER))
return Optional.of(fieldValue);
throw new InvalidSchemaException(String.format("Invalid type [%s] for schema field [%s]. Must be [%s]",
getJsonType(fieldValue), fieldName, fieldType));
}
private static String getJsonType(JsonNode value) {
return value.isTextual() ? "string"
: value.isObject() ? "object"
: value.isNumber() ? "number"
: value.isArray() ? "array" : value.isBoolean() ? "boolean" : "null";
}
public static class InvalidSchemaException extends RuntimeException {
private static final long serialVersionUID = 6335047694807220133L;
public InvalidSchemaException(String message) {
super(message);
}
public static InvalidSchemaException invalidField(String fieldName, String... expectedFiedNames) {
return new InvalidSchemaException(String.format("invalid field [%s]: expected fields are %s", fieldName,
Arrays.toString(expectedFiedNames)));
}
public static InvalidSchemaException invalidSchemaType(String schemaName, String type) {
return new InvalidSchemaException(String.format("invalid schema type [%s]", type));
}
public static InvalidSchemaException invalidFieldValue(String fieldName, JsonNode fieldValue,
JsonNode anticipatedFieldValue) {
return new InvalidSchemaException(String.format("schema field [%s] equal to [%s] should be equal to [%s]",
fieldName, fieldValue, anticipatedFieldValue));
}
public static InvalidSchemaException noProperty(String propertyName) {
return new InvalidSchemaException(
String.format("property [%s] of type [object] has no properties", propertyName));
}
}
}
|
package kalang.compiler;
import java.lang.reflect.Modifier;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Nullable;
import kalang.AstNotFoundException;
import kalang.antlr.KalangParser;
import kalang.antlr.KalangParser.MethodDeclContext;
import kalang.antlr.KalangParserBaseVisitor;
import kalang.ast.AnnotationNode;
import kalang.ast.AssignExpr;
import kalang.ast.AssignableExpr;
import kalang.ast.BlockStmt;
import kalang.ast.ClassNode;
import kalang.ast.ClassReference;
import kalang.ast.ExprNode;
import kalang.ast.ExprStmt;
import kalang.ast.FieldNode;
import kalang.ast.MethodNode;
import kalang.ast.ObjectFieldExpr;
import kalang.ast.ParameterExpr;
import kalang.ast.ParameterNode;
import kalang.ast.StaticFieldExpr;
import kalang.ast.ThisExpr;
import kalang.core.GenericType;
import kalang.core.MethodDescriptor;
import kalang.core.ModifierConstant;
import kalang.core.NullableKind;
import kalang.core.ObjectType;
import kalang.core.Type;
import kalang.core.Types;
import kalang.exception.Exceptions;
import kalang.util.AstUtil;
import kalang.util.ClassTypeUtil;
import kalang.util.MethodUtil;
import kalang.util.ModifierUtil;
import org.antlr.v4.runtime.ParserRuleContext;
import org.antlr.v4.runtime.Token;
/**
*
* @author Kason Yang
*/
public class ClassNodeMetaBuilder extends KalangParserBaseVisitor<Object> {
AstBuilder astBuilder;
private final ClassNodeBuilder classNodeBuilder;
private ClassNode thisClazz;
private Map<MethodNode,KalangParser.StatContext[]> methodStatsContexts = new HashMap();
private Map<MethodNode,MethodDeclContext> methodContexts = new HashMap();
private MethodNode method;
private final CompilationUnit compilationUnit;
private DiagnosisReporter diagnosisReporter;
public ClassNodeMetaBuilder(CompilationUnit compilationUnit, AstBuilder astBuilder, ClassNodeBuilder classNodeBuilder) {
this.compilationUnit = compilationUnit;
this.astBuilder = astBuilder;
this.classNodeBuilder = classNodeBuilder;
this.diagnosisReporter = new DiagnosisReporter(this.compilationUnit);
}
public void build(ClassNode cn,boolean inScriptMode) {
this.thisClazz = cn;
astBuilder.thisClazz = cn;
ParserRuleContext ctx = classNodeBuilder.getClassNodeDefContext(cn);
if(ctx!=null) visit(ctx);
for (ClassNode c : cn.classes) {
build(c,false);
}
}
@Override
public Object visitClassDef(KalangParser.ClassDefContext ctx) {
thisClazz.annotations.addAll(astBuilder.getAnnotations(ctx.annotation()));
thisClazz.modifier = astBuilder.parseModifier(ctx.varModifier());
List<Token> gnrTypes = ctx.genericTypes;
if (gnrTypes != null && !gnrTypes.isEmpty()) {
for (Token g : gnrTypes) {
//TODO suport generic type bounds in syntax
GenericType gt = new GenericType(g.getText(), Types.getRootType(), null, NullableKind.NONNULL);
thisClazz.declareGenericType(gt);
}
}
ObjectType superType = null;
if (ctx.parentClass != null) {
ObjectType parentClass = astBuilder.parseClassType(ctx.parentClass);
if (parentClass != null) {
superType = parentClass;
}
} else {
superType = Types.getRootType();
}
if (Modifier.isInterface(thisClazz.modifier)) {
//TODO update syntax to support:interface extends T1,T2...
thisClazz.addInterface(superType);
} else {
thisClazz.setSuperType(superType);
}
if (ctx.interfaces != null && ctx.interfaces.size() > 0) {
for (KalangParser.ClassTypeContext itf : ctx.interfaces) {
ObjectType itfClz = astBuilder.parseClassType(itf);
if (itfClz != null) {
thisClazz.addInterface(itfClz);
}
}
}
if (this.isDeclaringNonStaticInnerClass()) {
ClassNode parentClass = thisClazz.enclosingClass;
if (parentClass == null) {
throw Exceptions.unexceptedValue(parentClass);
}
thisClazz.createField(Types.getClassType(parentClass), "this$0", Modifier.PRIVATE | ModifierConstant.SYNTHETIC);
}
visit(ctx.classBody());
if (!ModifierUtil.isInterface(thisClazz.modifier)
&& !AstUtil.containsConstructor(thisClazz)
&& !AstUtil.createEmptyConstructor(thisClazz)) {
this.diagnosisReporter.report(Diagnosis.Kind.ERROR
, "failed to create constructor with no parameters", ctx
);
}
MethodNode[] methods = thisClazz.getDeclaredMethodNodes();
for (int i = 0; i < methods.length; i++) {
MethodNode node = methods[i];
BlockStmt body = node.getBody();
if (body != null) {
if (AstUtil.isConstructor(node)) {//constructor
if (this.isDeclaringNonStaticInnerClass()) {
ClassNode enclosingClass = thisClazz.enclosingClass;
if (enclosingClass == null) {
throw Exceptions.unexceptedValue(enclosingClass);
}
ParameterNode outerInstanceParam = node.createParameter(0, Types.getClassType(enclosingClass), "this$0");
ExprNode parentFieldExpr = astBuilder.getObjectFieldExpr(
new ThisExpr(Types.getClassType(thisClazz)), "this$0", ParserRuleContext.EMPTY
);
if (parentFieldExpr == null) {
throw Exceptions.unexceptedValue(parentFieldExpr);
}
body.statements.add(1, new ExprStmt(new AssignExpr((AssignableExpr) parentFieldExpr, new ParameterExpr(outerInstanceParam))));
}
}
}
}
for (FieldNode fieldNode : thisClazz.getFields()) {
int mdf = fieldNode.modifier;
if (!AstUtil.hasGetter(thisClazz, fieldNode)) {
AstUtil.createGetter(thisClazz, fieldNode, mdf);
}
if (!AstUtil.hasSetter(thisClazz, fieldNode)) {
AstUtil.createSetter(thisClazz, fieldNode, mdf);
}
fieldNode.modifier = ModifierUtil.setPrivate(mdf);
}
return null;
}
private boolean isNonStaticInnerClass(ClassNode clazz) {
return clazz.enclosingClass != null && !Modifier.isStatic(clazz.modifier);
}
private boolean isDeclaringNonStaticInnerClass() {
return isNonStaticInnerClass(thisClazz);
}
@Override
public Object visitMethodDecl(KalangParser.MethodDeclContext ctx) {
String name;
Type type;
boolean isOverriding = ctx.OVERRIDE() != null;
if (ctx.prefix != null && ctx.prefix.getText().equals("constructor")) {
type = Types.VOID_TYPE;
name = "<init>";
} else {
if (ctx.type() == null) {
type = Types.VOID_TYPE;
} else {
type = astBuilder.parseType(ctx.returnType);
}
name = ctx.name.getText();
}
List<KalangParser.TypeContext> paramTypesCtx = ctx.paramTypes;
int modifier = astBuilder.parseModifier(ctx.varModifier());
Type[] paramTypes;
String[] paramNames;
if (paramTypesCtx != null) {
int paramSize = paramTypesCtx.size();
paramTypes = new Type[paramSize];
paramNames = new String[paramSize];
for(int i=0;i<paramSize;i++){
KalangParser.TypeContext t = paramTypesCtx.get(i);
paramTypes[i] = astBuilder.parseType(t);
paramNames[i] = ctx.paramIds.get(i).getText();
}
}else{
paramTypes = new Type[0];
paramNames = new String[0];
}
//check method duplicated before generate java stub
String mStr = MethodUtil.getDeclarationKey(name,paramTypes);
boolean existed = Arrays.asList(thisClazz.getDeclaredMethodNodes()).stream().anyMatch((m)->{
return MethodUtil.getDeclarationKey(m).equals(mStr);
});
if (existed) {
//TODO should remove the duplicated method
diagnosisReporter.report(Diagnosis.Kind.ERROR,"declare method duplicately:"+mStr, ctx);
return null;
}
KalangParser.BlockStmtContext blockStmt = ctx.blockStmt();
if(blockStmt==null){
if(ModifierUtil.isInterface(thisClazz.modifier)){
modifier |= Modifier.ABSTRACT;
}else if(!Modifier.isAbstract(modifier)){
diagnosisReporter.report(Diagnosis.Kind.ERROR, "method body required", ctx);
}else if(!Modifier.isAbstract(thisClazz.modifier)){
diagnosisReporter.report(Diagnosis.Kind.ERROR, "declare abstract method in non-abstract class", ctx);
}
}
method = thisClazz.createMethodNode(type,name,modifier);
for(int i=0;i<paramTypes.length;i++){
method.createParameter(paramTypes[i], paramNames[i]);
}
for(AnnotationNode a:astBuilder.getAnnotations(ctx.annotation())) method.addAnnotation(a);
ObjectType superType = thisClazz.getSuperType();
if(superType==null){//the superType of interface may be null
superType = Types.getRootType();
}
MethodDescriptor overriddenMd = ClassTypeUtil.getMethodDescriptor(superType, mStr, thisClazz, true,true);
if(overriddenMd==null){
overriddenMd = ClassTypeUtil.getMethodDescriptor(thisClazz.getInterfaces(), mStr, thisClazz, true,true);
}
if(isOverriding && overriddenMd==null){
diagnosisReporter.report(Diagnosis.Kind.ERROR,"method does not override or implement a method from a supertype", ctx);
}
if(!isOverriding && overriddenMd!=null){
diagnosisReporter.report(Diagnosis.Kind.ERROR,"method overrides or implements a method from a supertype", ctx);
}
this.methodContexts.put(method, ctx);
KalangParser.BlockStmtContext bstm = ctx.blockStmt();
if(bstm!=null){
List<KalangParser.StatContext> stats = bstm.stat();
if(stats!=null) this.methodStatsContexts.put(method, stats.toArray(new KalangParser.StatContext[stats.size()]));
}
if (ctx.exceptionTypes != null) {
for (Token et : ctx.exceptionTypes) {
ObjectType exType = astBuilder.requireClassType(et);
if(exType!=null){
method.addExceptionType(exType);
}
}
}
astBuilder.mapAst(method, ctx);
MethodNode m = method;
method=null;
return m;
}
@Nullable
public KalangParser.StatContext[] getStatContexts(MethodNode mn){
return this.methodStatsContexts.get(mn);
}
@Override
public Object visitClassBody(KalangParser.ClassBodyContext ctx) {
for(KalangParser.FieldDeclContext f:ctx.fieldDecl()){
visit(f);
}
for(KalangParser.MethodDeclContext m:ctx.methodDecl()){
visit(m);
}
return null;
}
@Override
public Void visitFieldDecl(KalangParser.FieldDeclContext ctx) {
int fieldModifier = astBuilder.parseModifier(ctx.varModifier());
for(KalangParser.VarDeclContext vd:ctx.varDecl()){
ExprNode initExpr;
if(vd.expression()!=null){
initExpr = astBuilder.visitExpression(vd.expression());
}else{
initExpr = null;
}
AstBuilder.VarInfo varInfo = astBuilder.varDecl(vd,initExpr==null
?Types.getRootType()
:initExpr.getType()
);
varInfo.modifier |= fieldModifier;
FieldNode fieldNode = thisClazz.createField(varInfo.type, varInfo.name,varInfo.modifier);
//TODO simplify it
if(initExpr!=null){
if(AstUtil.isStatic(fieldNode.modifier)){
thisClazz.staticInitStmts.add(new ExprStmt(new AssignExpr(new StaticFieldExpr(new ClassReference(thisClazz), fieldNode), initExpr)));
}else{
thisClazz.initStmts.add(new ExprStmt(
new AssignExpr(
new ObjectFieldExpr(
new ThisExpr(Types.getClassType(thisClazz)), fieldNode
)
, initExpr
)
)
);
}
}
}
return null;
}
@Override
public Object visitScriptDef(KalangParser.ScriptDefContext ctx) {
//FIXME fix filename
//thisClazz.fileName = this.compilationUnit.getSource().getFileName();
thisClazz.setSuperType(this.getScriptType());
List<MethodDeclContext> mds = ctx.methodDecl();
if(mds!=null){
for(MethodDeclContext m:mds){
visit(m);
}
}
MethodNode mm = thisClazz.createMethodNode(Types.VOID_TYPE,"execute",Modifier.PUBLIC);
mm.addExceptionType(Types.getExceptionClassType());
method = mm;
List<KalangParser.StatContext> stats = ctx.stat();
if(stats!=null){
this.methodStatsContexts.put(mm, stats.toArray(new KalangParser.StatContext[stats.size()]));
}
AstUtil.createEmptyConstructor(thisClazz);
return null;
}
public MethodDeclContext getMethodDeclContext(MethodNode mn){
return this.methodContexts.get(mn);
}
private ObjectType getScriptType(){
CompileContext context = this.compilationUnit.getCompileContext();
Configuration conf = context.getConfiguration();
AstLoader astLoader = context.getAstLoader();
String baseClass = this.classNodeBuilder.getOptionScript();
if(baseClass==null){
baseClass = conf.getScriptBaseClass();
}
try {
return Types.getClassType(astLoader.loadAst(baseClass));
} catch (AstNotFoundException ex) {
throw Exceptions.missingRuntimeClass(baseClass);
}
}
}
|
package mltk.predictor.tree.ensemble.brt;
import java.io.BufferedReader;
import java.io.PrintWriter;
import mltk.core.Instance;
import mltk.predictor.ProbabilisticClassifier;
import mltk.predictor.Regressor;
import mltk.predictor.tree.ensemble.BoostedDTables;
import mltk.util.MathUtils;
import mltk.util.StatUtils;
import mltk.util.VectorUtils;
/**
* Class for boosted decision tables (BDTs).
*
* <p>
* Reference:<br>
* Y. Lou and M. Obukhov. BDT: Boosting Decision Tables for High Accuracy and Scoring Efficiency. In <i>Proceedings of the
* 23rd ACM SIGKDD International Conference on Knowledge Discovery and Data Mining (KDD)</i>, Halifax, Nova Scotia, Canada, 2017.
* </p>
*
* @author Yin Lou
*
*/
public class BDT implements ProbabilisticClassifier, Regressor {
protected BoostedDTables[] tables;
/**
* Constructs a BDT from a BRT object.
*
* @param brt the BRT object.
* @return a BDT object.
*/
public static BDT constructBDT(BRT brt) {
int k = brt.trees.length;
BDT bdt = new BDT();
bdt.tables = new BoostedDTables[k];
for (int i = 0; i < bdt.tables.length; i++) {
bdt.tables[i] = new BoostedDTables(brt.trees[i]);
}
return bdt;
}
/**
* Constructor.
*/
public BDT() {
}
/**
* Constructor.
*
* @param k the number of classes.
*/
public BDT(int k) {
tables = new BoostedDTables[k];
for (int i = 0; i < tables.length; i++) {
tables[i] = new BoostedDTables();
}
}
/**
* Returns the table list for class k.
*
* @param k the class k.
* @return the table list for class k.
*/
public BoostedDTables getDecisionTreeList(int k) {
return tables[k];
}
@Override
public int classify(Instance instance) {
double[] prob = predictProbabilities(instance);
return StatUtils.indexOfMax(prob);
}
@Override
public void read(BufferedReader in) throws Exception {
int k = Integer.parseInt(in.readLine().split(": ")[1]);
tables = new BoostedDTables[k];
for (int i = 0; i < tables.length; i++) {
in.readLine();
tables[i] = new BoostedDTables();
tables[i].read(in);
in.readLine();
}
}
@Override
public void write(PrintWriter out) throws Exception {
out.printf("[Predictor: %s]\n", this.getClass().getCanonicalName());
out.println("K: " + tables.length);
for (BoostedDTables dtList : tables) {
dtList.write(out);
out.println();
}
}
@Override
public double regress(Instance instance) {
return tables[0].regress(instance);
}
@Override
public double[] predictProbabilities(Instance instance) {
if (tables.length == 1) {
double[] prob = new double[2];
double pred = regress(instance);
prob[1] = MathUtils.sigmoid(pred);
prob[0] = 1 - prob[1];
return prob;
} else {
double[] prob = new double[tables.length];
double[] pred = new double[tables.length];
for (int i = 0; i < tables.length; i++) {
pred[i] = tables[i].regress(instance);
}
double max = StatUtils.max(pred);
double sum = 0;
for (int i = 0; i < prob.length; i++) {
prob[i] = Math.exp(pred[i] - max);
sum += prob[i];
}
VectorUtils.divide(prob, sum);
return prob;
}
}
@Override
public BDT copy() {
BDT copy = new BDT(tables.length);
for (int i = 0; i < tables.length; i++) {
copy.tables[i] = tables[i].copy();
}
return copy;
}
}
|
package net.etalia.client.services;
import static org.springframework.web.bind.annotation.RequestMethod.GET;
import static org.springframework.web.bind.annotation.RequestMethod.POST;
import java.util.List;
import java.util.Map;
import net.etalia.client.domain.AdvertisedPaginationList;
import net.etalia.client.domain.Article;
import net.etalia.client.domain.PaginationList;
import net.etalia.client.domain.Publication;
import net.etalia.client.domain.SearchCriteria;
import net.etalia.client.domain.StampArticle;
import net.etalia.client.domain.Tag;
import net.etalia.client.domain.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public interface SearchApi {
@RequestMapping(method=GET, value="/publication/last")
public @ResponseBody PaginationList<Publication> getLastPublications(
@RequestParam(value="offset", required=false) Integer start,
@RequestParam(value="count", required=false) Integer count);
@RequestMapping(method=POST, value="/publication/images")
public @ResponseBody Map<String,String> getPublicationsImages(@RequestBody List<String> ids);
@RequestMapping(value="/suggestions/publication")
public @ResponseBody PaginationList<Publication> publicationSuggest(
@RequestParam("q") String q,
@RequestParam(value="ownerId", required=false) String ownerId,
@RequestParam(value="offset", required=false) Integer offset,
@RequestParam(value="count", required=false) Integer count);
@RequestMapping(value="/search/article", method=POST)
public @ResponseBody AdvertisedPaginationList<Article> searchArticles(
@RequestBody SearchCriteria criteria,
@RequestParam(value="offset", required=false) Integer offset,
@RequestParam(value="count", required=false) Integer count,
@RequestParam(value="advertising", required=false) Integer advertising,
@RequestParam(value="advertisingWidth", required=false) Integer advertisingWidth,
@RequestHeader(value="x-adu", required=false) String userTgt);
@RequestMapping(value="/search/inpage/{pid}", method=GET)
public @ResponseBody AdvertisedPaginationList<Article> searchArticlesByPage(
@PathVariable("pid") String pageId,
@RequestParam(value="offset", required=false) Integer offset,
@RequestParam(value="count", required=false) Integer count,
@RequestParam(value="advertising", required=false) Integer advertising,
@RequestParam(value="advertisingWidth", required=false) Integer advertisingWidth,
@RequestHeader(value="x-adu", required=false) String userTgt);
@RequestMapping(value="/article/{aid}/similar")
public @ResponseBody PaginationList<Article> searchSimilarArticles(
@PathVariable(value="aid") String article,
@RequestParam(value="count", required=false) Integer count);
@RequestMapping(value="/suggestions/stamp")
public @ResponseBody PaginationList<StampArticle> stampSuggest(
@RequestParam("q") String q,
@RequestParam(value="offset", required=false) Integer offset,
@RequestParam(value="count", required=false) Integer count);
@RequestMapping(value="/suggestions/tags")
public @ResponseBody PaginationList<Tag> tagSuggest(
@RequestParam("q") String q,
@RequestParam(value="offset", required=false) Integer offset,
@RequestParam(value="count", required=false) Integer count);
@RequestMapping(value="/suggestions/user")
public @ResponseBody PaginationList<User> userSuggest(
@RequestParam("q") String q,
@RequestParam(value="offset", required=false) Integer offset,
@RequestParam(value="count", required=false) Integer count);
}
|
package net.krinsoft.chat.targets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import net.krinsoft.chat.PlayerManager;
import net.krinsoft.chat.api.Target;
import net.krinsoft.chat.util.Replacer;
import net.krinsoft.chat.util.Replacer.Handler;
import org.bukkit.ChatColor;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;
import com.herocraftonline.dev.heroes.Heroes;
import com.herocraftonline.dev.heroes.persistence.Hero;
/**
*
* @author krinsdeath
*/
@SuppressWarnings("javadoc")
public class ChatPlayer implements Target {
private static class NodeGrabber implements Replacer.Handler {
final String node;
NodeGrabber(final String node) {
this.node = node;
}
@Override
public String getValue(final Object... scope) {
return ((ConfigurationSection) scope[1]).getString(node);
}
}
public enum Type {
GLOBAL("global"),
NORMAL("normal"),
WHISPER_RECEIVE("whisper_receive"),
WHISPER_SEND("whisper_send");
private String type;
private Type(final String type) {
this.type = type;
}
public String getName() {
return this.type;
}
}
private final static Replacer[] replacers;
private final static Replacer[] replacers_whisper;
static {
final Handler AFK = new NodeGrabber("afk");
final Handler GROUP = new NodeGrabber("group");
final Handler HEROES =
new Replacer.Handler() {
@Override
public String getValue(final Object... scope) {
final ChatPlayer chatPlayer = (ChatPlayer) scope[0];
final PlayerManager manager = chatPlayer.manager;
final Plugin tmp = manager.getPlugin().getServer().getPluginManager().getPlugin("Heroes");
if (tmp != null) {
try {
final Heroes heroes = (Heroes) tmp;
final Player player = manager.getPlugin().getServer().getPlayer(chatPlayer.getName());
final Hero hero = heroes.getHeroManager().getHero(player);
final String hero_name = hero.getHeroClass().getName();
return hero_name;
} catch (final Exception e) {
manager.getPlugin().warn("An error occurred while parsing a Hero class: " + e.getLocalizedMessage());
}
}
return "";
}
};
final Handler PREFIX = new NodeGrabber("prefix");
final Handler SUFFIX = new NodeGrabber("suffix");
final Handler SELF =
new Replacer.Handler() {
@Override
public String getValue(final Object... scope) {
return ((ChatPlayer) scope[0]).getName();
}
};
final Handler SELF_DISPLAY =
new Replacer.Handler() {
@Override
public String getValue(final Object... scope) {
final Player player = ((ChatPlayer) scope[0]).getPlayer();
if (player != null) return player.getDisplayName();
return "";
}
};
final Handler TARGET =
new Replacer.Handler() {
@Override
public String getValue(final Object... scope) {
final Target target = ((ChatPlayer) scope[0]).target;
if (target != null) {
if (target instanceof Channel) return ((Channel)target).getColoredName();
return target.getName();
}
return "";
}
};
final Handler TARGET_DISPLAY =
new Replacer.Handler() {
@Override
public String getValue(final Object... scope) {
final Player p = ((ChatPlayer) scope[0]).getPlayer();
if (p != null) return p.getDisplayName();
return "";
}
};
final Handler WORLD =
new Replacer.Handler() {
@Override
public String getValue(final Object... scope) {
final ChatPlayer chatPlayer = (ChatPlayer) scope[0];
return chatPlayer.manager.getPlugin().getWorldManager().getAlias(chatPlayer.world);
}
};
final Handler MESSAGE =
new Replacer.Handler() {
@Override
public String getValue(final Object... scope) {
return (String) scope[2];
}
};
replacers = new Replacer[] {
new Replacer("%afk", AFK, false),
new Replacer("%group", GROUP, false),
new Replacer("%g", GROUP, true),
new Replacer("%hero", HEROES, false),
new Replacer("%h", HEROES, true),
new Replacer("%prefix", PREFIX, false),
new Replacer("%p", PREFIX, true),
new Replacer("%name", SELF, false),
new Replacer("%n", SELF, true),
new Replacer("%display", SELF_DISPLAY, false),
new Replacer("%dn", SELF_DISPLAY, true),
new Replacer("%suffix", SUFFIX, false),
new Replacer("%s", SUFFIX, false),
new Replacer("%target", TARGET, false),
new Replacer("%t", TARGET, true),
new Replacer("%channel", TARGET, false),
new Replacer("%c", TARGET, true),
new Replacer("%disp_target", TARGET_DISPLAY, false),
new Replacer("%dt", TARGET_DISPLAY, true),
new Replacer("%message", MESSAGE, false),
new Replacer("%m", MESSAGE, true),
new Replacer("%world", WORLD, false),
new Replacer("%w", WORLD, true)};
Arrays.sort(replacers);
final Handler WHISPER_TARGET =
new Replacer.Handler() {
@Override
public String getValue(final Object... scope) {
return ((ChatPlayer) scope[0]).reply.getName();
}
};
replacers_whisper = new Replacer[] {
new Replacer("%afk", AFK, false),
new Replacer("%group", GROUP, false),
new Replacer("%g", GROUP, true),
new Replacer("%hero", HEROES, false),
new Replacer("%h", HEROES, true),
new Replacer("%prefix", PREFIX, false),
new Replacer("%p", PREFIX, true),
new Replacer("%name", SELF, false),
new Replacer("%n", SELF, true),
new Replacer("%display", SELF_DISPLAY, false),
new Replacer("%dn", SELF_DISPLAY, true),
new Replacer("%suffix", SUFFIX, false),
new Replacer("%s", SUFFIX, false),
// Begin whisper specific
new Replacer("%target", WHISPER_TARGET, false),
new Replacer("%t", WHISPER_TARGET, true),
new Replacer("%channel", WHISPER_TARGET, false),
new Replacer("%c", WHISPER_TARGET, true),
// End whisper specific
new Replacer("%message", MESSAGE, false),
new Replacer("%m", MESSAGE, true),
new Replacer("%disp_target", TARGET_DISPLAY, false),
new Replacer("%dt", TARGET_DISPLAY, true),
new Replacer("%world", WORLD, false),
new Replacer("%w", WORLD, true)};
Arrays.sort(replacers_whisper);
}
private boolean afk; // whether the player is afk or not
private String afk_message;
private final Set<String> auto_join = new HashSet<String>();
private boolean colorful;
private String group; // the player's group
private final PlayerManager manager;
private boolean muted;
private final String name;
private Target reply;
private Target target;
private String world; // the player's current world
public ChatPlayer(final PlayerManager man, final Player p) {
long time = System.nanoTime();
manager = man;
name = p.getName();
world = p.getWorld().getName();
colorful = p.hasPermission("chatsuite.colorize");
List<String> joins;
if (manager.getConfig().getConfigurationSection(name) != null) {
joins = manager.getConfig().getStringList(name + ".auto_join");
} else {
joins = manager.getConfig().getStringList("default_channels");
}
auto_join.addAll(joins);
if (manager.getConfig().get(name) != null) {
final String t = manager.getConfig().getString(getName() + ".target");
if (t != null) {
target = manager.getPlugin().getTarget(t);
}
}
if (target == null) {
target = manager.getPlugin().getChannelManager().getGlobalChannel();
}
getGroup();
muted = manager.getConfig().getBoolean(getName() + ".muted", false);
if (muted) {
p.sendMessage(ChatColor.RED + "You are muted.");
}
String nick = manager.getConfig().getString(getName() + ".nickname");
if (nick != null) {
p.setDisplayName(nick);
p.sendMessage(ChatColor.GREEN + "Your nickname is: " + ChatColor.WHITE + nick);
}
time = System.nanoTime() - time;
manager.getPlugin().debug("Player '" + name + "' registered in group '" + group + "' and " + (muted ? "" : "not ") + "muted took " + (time / 1000000L) + "ms. (" + time + "ns)");
}
public boolean colorfulChat() {
return colorful;
}
public Set<String> getAutoJoinChannels() {
return auto_join;
}
public String getAutoJoinChannelString() {
final StringBuilder ajoin = new StringBuilder();
for (final String ch : auto_join) {
ajoin.append(ChatColor.AQUA).append(ch).append(ChatColor.WHITE).append(", ");
}
return ajoin.toString().substring(0, ajoin.toString().length()-2);
}
public String getFormattedMessage() {
String format = manager.getPlugin().getChannelManager().getConfig().getString("channels." + getTarget().getName() + ".format");
if (format == null) {
format = manager.getPlugin().getConfig().getString("groups." + group + ".format.message");
if (format == null) {
format = manager.getPlugin().getConfig().getString("format.message");
if (format == null) {
format = "[%t] %p %n&F: %m";
}
}
}
format = parse(format, "%2$s", false);
return format;
}
public String getFormattedWhisperFrom(final Target target, final String message) {
String format = manager.getPlugin().getConfig().getString("groups." + ((ChatPlayer)target).getGroup() + ".format.from");
if (format == null) {
format = manager.getPlugin().getConfig().getString("format.from");
if (format == null) {
format = "&7[From] %t>>&F: %m";
}
}
format = parse(format, message, true);
return format;
}
public String getFormattedWhisperTo(final Target target, final String message) {
String format = manager.getPlugin().getConfig().getString("groups." + ((ChatPlayer)target).getGroup() + ".format.to");
if (format == null) {
format = manager.getPlugin().getConfig().getString("format.to");
if (format == null) {
format = "&7[To] %t>>&F: %m";
}
}
format = parse(format, message, true);
return format;
}
public String getGroup() {
long time = System.nanoTime();
final Player p = getPlayer();
if (p == null)
return manager.getPlugin().getDefaultGroup();
int weight = 0;
for (final String key : manager.getPlugin().getGroups()) {
final int i = manager.getPlugin().getGroupNode(key).getInt("weight");
if ((p.hasPermission("chatsuite.groups." + key) || p.hasPermission("group." + key)) && i > weight) {
weight = i;
group = key;
}
}
if (group == null) {
group = p.isOp() ? manager.getPlugin().getOpGroup() : manager.getPlugin().getDefaultGroup();
}
time = System.nanoTime() - time;
manager.getPlugin().debug(name + ": Determined '" + group + "' in " + (time / 1000000L) + "ms. (" + time + "ns)");
return group;
}
@Override
public String getName() {
return name;
}
public Player getPlayer() {
return manager.getPlugin().getServer().getPlayer(name);
}
public Target getTarget() {
return target;
}
@Override
public boolean isMuted() {
return muted;
}
public void join(final Channel c) {
if (!auto_join.contains(c.getName())) {
sendMessage(c.getColoredName() + " added to Auto-Join list.");
}
auto_join.add(c.getName());
}
public String parse(String format, final String message, final boolean isWhisper) {
final ConfigurationSection node = manager.getPlugin().getGroupNode(group);
format = Replacer.makeReplacements(format, isWhisper ? replacers_whisper : replacers, this, node, message);
format = ChatColor.translateAlternateColorCodes('&', format);
return format;
}
public void part(final Channel c) {
if (auto_join.contains(c.getName())) {
sendMessage(c.getColoredName() + " removed from Auto-Join list.");
}
auto_join.remove(c.getName());
}
@Override
public void persist() {
final String t = (target instanceof Channel ? "c:" + target.getName() : "p:" + target.getName());
manager.getConfig().set(getName() + ".target", t);
final List<String> joins = new ArrayList<String>();
joins.addAll(auto_join);
manager.getConfig().set(getName() + ".auto_join", joins);
manager.getConfig().set(getName() + ".muted", muted);
manager.getConfig().set(getName() + ".nickname", getPlayer().getDisplayName());
}
public void reply(final String message) {
if (reply == null) { return; }
whisperTo(reply, message);
((ChatPlayer)reply).whisperFrom(this, message);
}
@Override
public void sendMessage(final String message) {
final Player p = getPlayer();
if (p != null) { p.sendMessage(message); }
}
public void setColorfulChat(final boolean val) {
colorful = val;
}
public void setTarget(final Target t) {
setTarget(t, false);
}
public void setTarget(final Target t, final boolean silent) {
target = t;
if (!silent) {
target = t;
final Player p = getPlayer();
if (p != null) { p.sendMessage("[ChatSuite] Your target is now: " + target.getName()); }
}
}
public void setWorld(final String w) {
getGroup();
world = w;
}
public void toggleAfk(final String message) {
this.afk_message = message;
this.afk = !this.afk;
}
@Override
public void toggleMute() {
muted = !muted;
if (muted) {
sendMessage(ChatColor.RED + "You have been muted.");
} else {
sendMessage(ChatColor.GREEN + "You have been unmuted.");
}
}
public void whisperFrom(final Target from, final String message) {
reply = from;
final String format = getFormattedWhisperFrom(from, message);
sendMessage(format);
}
public void whisperTo(final Target to, final String message) {
reply = to;
final String format = getFormattedWhisperTo(to, message);
sendMessage(format);
if (to instanceof ChatPlayer && ((ChatPlayer)to).afk) {
sendMessage(to.getName() + " is afk: " + ((ChatPlayer)to).afk_message);
}
}
}
|
package net.ucanaccess.jdbc;
import java.io.File;
import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.DriverPropertyInfo;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import java.sql.SQLWarning;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.StringTokenizer;
import com.healthmarketscience.jackcess.Database.FileFormat;
import net.ucanaccess.converters.LoadJet;
import net.ucanaccess.converters.SQLConverter;
import net.ucanaccess.jdbc.UcanaccessSQLException.ExceptionMessages;
import net.ucanaccess.util.Logger;
import net.ucanaccess.util.Logger.Messages;
public final class UcanaccessDriver implements Driver {
public static final String URL_PREFIX = "jdbc:ucanaccess:
static {
try {
DriverManager.registerDriver(new UcanaccessDriver());
Class.forName("org.hsqldb.jdbc.JDBCDriver");
} catch (ClassNotFoundException e) {
Logger.logMessage(Messages.HSQLDB_DRIVER_NOT_FOUND);
throw new RuntimeException(e.getMessage());
} catch (SQLException e) {
throw new RuntimeException(e.getMessage());
}
}
public boolean acceptsURL(String url) throws SQLException {
return (url.startsWith(URL_PREFIX) && url.length() > URL_PREFIX
.length());
}
public Connection connect(String url, Properties pr) throws SQLException {
// ok wimp
if (!this.acceptsURL(url)) {
return null;
}
readProperties(pr, url);
String fileMdbPath = url.indexOf(";") > 0 ? url.substring(URL_PREFIX
.length(), url.indexOf(";")) : url.substring(URL_PREFIX
.length());
File mdb = new File(fileMdbPath);
DBReferenceSingleton as = DBReferenceSingleton.getInstance();
synchronized (UcanaccessDriver.class) {
try {
Session session = new Session();
boolean alreadyLoaded = as.loaded(mdb);
FileFormat ff = null;
if (pr.containsKey("newdatabaseversion")) {
if (!mdb.exists()) {
ff = FileFormat.valueOf(pr.getProperty(
"newdatabaseversion").toUpperCase());
}
}
boolean useCustomOpener=pr.containsKey("jackcessopener");
JackcessOpenerInterface jko=useCustomOpener?
newJackcessOpenerInstance(pr.getProperty("jackcessopener")):
new DefaultJackcessOpener();
DBReference ref = alreadyLoaded ? as.getReference(mdb) : as
.loadReference(mdb, ff, jko,pr.getProperty("password"));
if (!alreadyLoaded) {
if( (useCustomOpener||
(pr.containsKey("encrypt")&&"true".equalsIgnoreCase(pr.getProperty("encrypt")))
)
&&
( (pr.containsKey("memory")&&!"true".equalsIgnoreCase(pr.getProperty("memory")))||
pr.containsKey("keepmirror")
)
){
ref.setEncryptHSQLDB(true);
}
if (pr.containsKey("memory")) {
ref.setInMemory("true".equalsIgnoreCase(pr
.getProperty("memory")));
}
if(pr.containsKey("keepmirror")){
ref.setInMemory(false);
if(ref.isEncryptHSQLDB()){
Logger.logWarning(Messages.KEEP_MIRROR_AND_OTHERS);
}else{
File dbMirror=new File(pr.getProperty("keepmirror"));
ref.setToKeepHsql(dbMirror);
}
}
if (pr.containsKey("showschema")) {
ref.setShowSchema("true".equalsIgnoreCase(pr
.getProperty("showschema")));
}
if (pr.containsKey("inactivitytimeout")) {
int millis=60000*Integer.parseInt(pr.getProperty("inactivitytimeout"));
ref.setInactivityTimeout(millis);
}
if (pr.containsKey("singleconnection")) {
ref.setSingleConnection("true".equalsIgnoreCase(pr
.getProperty("singleconnection")));
}
if (pr.containsKey("lockmdb")) {
ref.setLockMdb("true".equalsIgnoreCase(pr
.getProperty("lockmdb")));
}
if(pr.containsKey("remap")){
ref.setExternalResourcesMapping(toMap(pr.getProperty("remap")));
}
if (pr.containsKey("supportsaccesslike")) {
SQLConverter.setSupportsAccessLike("true"
.equalsIgnoreCase(pr.getProperty("supportsaccesslike")));
}
}
String pwd = ref.getDbIO().getDatabasePassword();
if (pwd != null&&!pr.containsKey("jackcessopener")) {
if (!pwd.equals(pr.get("password")))
throw new UcanaccessSQLException(
ExceptionMessages.NOT_A_VALID_PASSWORD);
session.setPassword(pwd);
}
String user = pr.getProperty("user");
if (user != null) {
session.setUser(user);
}
if (pr.containsKey("ignorecase")) {
session.setIgnoreCase("true".equalsIgnoreCase(pr
.getProperty("ignorecase")));
}
SQLWarning sqlw=null;
if (!alreadyLoaded) {
boolean toBeLoaded=!ref.loadedFromKeptMirror(session);
LoadJet la= new LoadJet(ref.getHSQLDBConnection(session), ref
.getDbIO());
Logger.turnOffJackcessLog();
if (pr.containsKey("sysschema")) {
la.setSysSchema("true".equalsIgnoreCase(pr
.getProperty("sysschema")));
}
if(toBeLoaded)
la.loadDB();
as.put(mdb.getAbsolutePath(), ref);
sqlw=la.getLoadingWarnings();
}
UcanaccessConnection uc= new UcanaccessConnection(as.getReference(mdb), pr,
session);
uc.addWarnings(sqlw);
uc.setUrl(url);
return uc;
} catch (Exception e) {
throw new UcanaccessSQLException(e);
}
}
}
private Map<String,String> toMap(String property) {
HashMap<String,String> hm=new HashMap<String,String> ();
StringTokenizer st=new StringTokenizer(property,"&");
while(st.hasMoreTokens()){
String entry=st.nextToken();
if(entry.indexOf("|")<0)continue;
hm.put(entry.substring(0,entry.indexOf('|')).toLowerCase(), entry.substring(entry.indexOf('|')+1));
}
return hm;
}
public int getMajorVersion() {
return 0;
}
public int getMinorVersion() {
return 0;
}
public java.util.logging.Logger getParentLogger()
throws SQLFeatureNotSupportedException {
throw new SQLFeatureNotSupportedException();
}
public DriverPropertyInfo[] getPropertyInfo(String url, Properties arg1)
throws SQLException {
return new DriverPropertyInfo[0];
}
public boolean jdbcCompliant() {
return true;
}
private JackcessOpenerInterface newJackcessOpenerInstance(String className) throws InstantiationException, IllegalAccessException, ClassNotFoundException, UcanaccessSQLException{
Object newInstance=Class.forName(className).newInstance();
if(!(newInstance instanceof JackcessOpenerInterface))
throw new UcanaccessSQLException(ExceptionMessages.INVALID_JACKCESS_OPENER);
return (JackcessOpenerInterface)newInstance;
}
private void readProperties(Properties pr, String url) {
Properties nb=new Properties();
for( Entry<Object, Object> entry:pr.entrySet()){
String key=(String)entry.getKey();
if(key!=null){
nb.put(key.toLowerCase(), entry.getValue());
}
}
pr.clear();
pr.putAll(nb);
StringTokenizer st = new StringTokenizer(url, ";");
while (st.hasMoreTokens()) {
String entry = st.nextToken();
int sep;
if ((sep = entry.indexOf("=")) > 0 && entry.length() > sep) {
pr.put(entry.substring(0, sep).toLowerCase(), entry.substring(
sep + 1, entry.length()));
}
}
}
}
|
package net.viktorc.pp4j;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.lang.Thread.UncaughtExceptionHandler;
import java.util.ArrayList;
import java.util.List;
import java.util.Queue;
import java.util.concurrent.CancellationException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.LinkedTransferQueue;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.Semaphore;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.ReentrantLock;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.commons.pool2.PooledObject;
import org.apache.commons.pool2.PooledObjectFactory;
import org.apache.commons.pool2.impl.DefaultPooledObject;
import org.apache.commons.pool2.impl.GenericObjectPool;
/**
* An implementation of the {@link net.viktorc.pp4j.ProcessPool} interface for maintaining and managing a pool of pre-started
* processes. The processes are executed in instances of an own {@link net.viktorc.pp4j.ProcessExecutor} implementation. Each executor is
* assigned an instance of an implementation of the {@link net.viktorc.pp4j.ProcessManager} interface using an implementation of the
* {@link net.viktorc.pp4j.ProcessManagerFactory} interface. The pool accepts submissions in the form of {@link net.viktorc.pp4j.Submission}
* implementations which are executed on any one of the available active process executors maintained by the pool. While executing a submission,
* the executor cannot accept further submissions. The submissions are queued and executed as soon as there is an available executor. The size
* of the pool is always kept between the minimum pool size and the maximum pool size (both inclusive). The reserve size specifies the minimum
* number of processes that should always be available (there are no guarantees that there actually will be this many available executors at
* any given time).
*
* @author Viktor Csomor
*
*/
public class StandardProcessPool implements ProcessPool {
/**
* If a process cannot be started or an exception occurs which would make it impossible to retrieve the actual
* return code of the process.
*/
public static final int UNEXPECTED_TERMINATION_RESULT_CODE = -1;
/**
* The number of milliseconds after which idle process executor instances and the process executor threads are evicted if
* {@link #keepAliveTime} is non-positive.
*/
private static final long DEFAULT_EVICT_TIME = 60L*1000;
private final ProcessManagerFactory procManagerFactory;
private final int minPoolSize;
private final int maxPoolSize;
private final int reserveSize;
private final long keepAliveTime;
private final boolean verbose;
private final boolean doTime;
private final ExecutorService procExecThreadPool;
private final ExecutorService auxThreadPool;
private final Queue<StandardProcessExecutor> activeExecutors;
private final StandardProcessExecutorPool executorPool;
private final LinkedBlockingDeque<InternalSubmission> submissions;
private final AtomicInteger numOfExecutingSubmissions;
private final CountDownLatch prestartLatch;
private final Object mainLock;
private final Logger logger;
private volatile boolean close;
public StandardProcessPool(ProcessManagerFactory procManagerFactory, int minPoolSize, int maxPoolSize, int reserveSize,
long keepAliveTime, boolean verbose) throws InterruptedException {
if (procManagerFactory == null)
throw new IllegalArgumentException("The process manager factory cannot be null.");
if (minPoolSize < 0)
throw new IllegalArgumentException("The minimum pool size has to be greater than 0.");
if (maxPoolSize < 1 || maxPoolSize < minPoolSize)
throw new IllegalArgumentException("The maximum pool size has to be at least 1 and at least as great as the " +
"minimum pool size.");
if (reserveSize < 0 || reserveSize > maxPoolSize)
throw new IllegalArgumentException("The reserve has to be at least 0 and less than the maximum pool size.");
this.procManagerFactory = procManagerFactory;
this.minPoolSize = minPoolSize;
this.maxPoolSize = maxPoolSize;
this.reserveSize = reserveSize;
this.keepAliveTime = Math.max(0, keepAliveTime);
this.verbose = verbose;
int actualMinSize = Math.max(minPoolSize, reserveSize);
doTime = keepAliveTime > 0;
procExecThreadPool = new ProcessExecutorThreadPool();
/* If keepAliveTime is positive, one process requires 4 auxiliary threads (std_out listener, err_out listener,
* submission handler, timer); if it is not, only 3 are required. */
auxThreadPool = new ThreadPoolExecutor(doTime ? 4*actualMinSize : 3*actualMinSize, Integer.MAX_VALUE,
doTime ? keepAliveTime : DEFAULT_EVICT_TIME, TimeUnit.MILLISECONDS, new SynchronousQueue<>(),
new CustomizedThreadFactory("auxThreadPool"));
activeExecutors = new LinkedBlockingQueue<>();
executorPool = new StandardProcessExecutorPool();
submissions = new LinkedBlockingDeque<>();
numOfExecutingSubmissions = new AtomicInteger(0);
prestartLatch = new CountDownLatch(actualMinSize);
mainLock = new Object();
logger = Logger.getAnonymousLogger();
for (int i = 0; i < actualMinSize && !close; i++) {
synchronized (mainLock) {
startNewProcess(null);
}
}
// Wait for the processes in the initial pool to start up.
prestartLatch.await();
}
/**
* Returns the <code>ProcessManagerFactory</code> assigned to the pool.
*
* @return The process manager factory of the process pool.
*/
public ProcessManagerFactory getProcessManagerFactory() {
return procManagerFactory;
}
/**
* Returns the maximum allowed number of processes to hold in the pool.
*
* @return The maximum size of the process pool.
*/
public int getMaxSize() {
return maxPoolSize;
}
/**
* Returns the minimum number of processes to hold in the pool.
*
* @return The minimum size of the process pool.
*/
public int getMinSize() {
return minPoolSize;
}
/**
* Returns the minimum number of available processes to keep in the pool.
*
* @return The number of available processes to keep in the pool.
*/
public int getReserveSize() {
return reserveSize;
}
/**
* Returns the number of milliseconds after which idle processes should be terminated. If it is 0 or less,
* the processes are never terminated due to a timeout.
*
* @return The number of milliseconds after which idle processes should be terminated.
*/
public long getKeepAliveTime() {
return keepAliveTime;
}
/**
* Returns whether events relating to the management of the processes held by the pool are logged to the
* console.
*
* @return Whether the pool is verbose.
*/
public boolean isVerbose() {
return verbose;
}
/**
* Returns the number of running processes currently held in the pool.
*
* @return The number of running processes.
*/
public int getNumOfProcesses() {
return activeExecutors.size();
}
/**
* Returns the number of submissions currently being executed in the pool.
*
* @return The number of submissions currently being executed in the pool.
*/
public int getNumOfExecutingSubmissions() {
return numOfExecutingSubmissions.get();
}
/**
* Returns the number of submissions queued and waiting for execution.
*
* @return The number of queued submissions.
*/
public int getNumOfQueuedSubmissions() {
return submissions.size();
}
/**
* Returns the number of active, queued, and currently executing processes as string.
*
* @return A string of statistics concerning the size of the process pool.
*/
private String getPoolStats() {
return "Active processes: " + activeExecutors.size() + "; submitted commands: " +
(numOfExecutingSubmissions.get() + submissions.size());
}
/**
* Returns whether a new process {@link net.viktorc.pp4j.StandardProcessExecutor} instance should be started.
*
* @return Whether the process pool should be extended.
*/
private boolean doExtendPool() {
return !close && (activeExecutors.size() < minPoolSize || (activeExecutors.size() < Math.min(maxPoolSize,
numOfExecutingSubmissions.get() + submissions.size() + reserveSize)));
}
/**
* Starts a new process by executing the provided {@link net.viktorc.pp4j.StandardProcessExecutor}. If it is null, it borrows an
* instance from the pool.
*
* @param executor An optional {@link net.viktorc.pp4j.StandardProcessExecutor} instance to re-start in case one is available.
* @return Whether the process was successfully started.
*/
private boolean startNewProcess(StandardProcessExecutor executor) {
if (executor == null) {
try {
executor = executorPool.borrowObject();
} catch (Exception e) {
return false;
}
}
procExecThreadPool.execute(executor);
activeExecutors.add(executor);
if (verbose)
logger.info("Process executor " + executor + " started." + System.lineSeparator() +
getPoolStats());
return true;
}
@Override
public Future<Long> submit(Submission submission) {
if (close)
throw new IllegalStateException("The pool has already been shut down.");
if (submission == null)
throw new IllegalArgumentException("The submission cannot be null or empty.");
InternalSubmission internalSubmission = new InternalSubmission(submission);
submissions.addLast(internalSubmission);
synchronized (mainLock) {
if (doExtendPool())
startNewProcess(null);
}
if (verbose)
logger.info("Submission " + submission + " received." + System.lineSeparator() + getPoolStats());
// Return a Future holding the total execution time including the submission delay.
return new InternalSubmissionFuture(internalSubmission);
}
@Override
public synchronized void shutdown() {
synchronized (mainLock) {
if (close)
throw new IllegalStateException("The pool has already been shut down.");
if (verbose)
logger.info("Initiating shutdown...");
close = true;
while (prestartLatch.getCount() != 0)
prestartLatch.countDown();
if (verbose)
logger.info("Shutting down process executors...");
for (StandardProcessExecutor executor : activeExecutors) {
if (!executor.stop(true)) {
// This should never happen.
logger.log(Level.SEVERE, "Process executor " + executor + " could not be stopped.");
}
}
if (verbose)
logger.info("Shutting down thread pools...");
procExecThreadPool.shutdown();
auxThreadPool.shutdown();
executorPool.close();
if (verbose)
logger.info("Process pool shut down.");
}
}
/**
* An implementation of the {@link net.viktorc.pp4j.InternalSubmission} interface to keep track of the number of commands
* being executed at a time and to establish a mechanism for cancelling submitted commands via the {@link java.util.concurrent.Future}
* returned by the {@link net.viktorc.pp4j.StandardProcessPool#submit(Submission)} method.
*
* @author Viktor Csomor
*
*/
private class InternalSubmission implements Submission {
final Submission origSubmission;
final long receivedTime;
final Object lock;
Thread thread;
Exception exception;
volatile long submittedTime;
volatile long processedTime;
volatile boolean processed;
volatile boolean cancel;
InternalSubmission(Submission originalSubmission) {
if (originalSubmission == null)
throw new IllegalArgumentException("The submission cannot be null.");
this.origSubmission = originalSubmission;
receivedTime = System.nanoTime();
lock = new Object();
}
/**
* Sets the thread that is executing the submission.
*
* @param t The thread that executes the submission.
*/
void setThread(Thread t) {
synchronized (lock) {
thread = t;
}
}
/**
* Sets the exception thrown during the execution of the submission if there was any.
*
* @param e The exception thrown during the execution of the submission.
*/
void setException(Exception e) {
synchronized (lock) {
exception = e;
lock.notifyAll();
}
}
@Override
public List<Command> getCommands() {
return origSubmission.getCommands();
}
@Override
public boolean doTerminateProcessAfterwards() {
return origSubmission.doTerminateProcessAfterwards();
}
@Override
public boolean isCancelled() {
return origSubmission.isCancelled() || cancel || close;
}
@Override
public void onStartedProcessing() {
submittedTime = System.nanoTime();
origSubmission.onStartedProcessing();
}
@Override
public void onFinishedProcessing() {
origSubmission.onFinishedProcessing();
processedTime = System.nanoTime();
synchronized (lock) {
processed = true;
lock.notifyAll();
}
}
@Override
public String toString() {
return origSubmission.toString();
}
}
/**
* An implementation of {@link java.util.concurrent.Future} that returns the time it took to process the
* submission.
*
* @author Viktor Csomor
*
*/
private class InternalSubmissionFuture implements Future<Long> {
final InternalSubmission submission;
/**
* Constructs a {@link java.util.concurrent.Future} for the specified submission.
*
* @param submission The submission to get a {@link java.util.concurrent.Future} for.
*/
InternalSubmissionFuture(InternalSubmission submission) {
this.submission = submission;
}
@Override
public boolean cancel(boolean mayInterruptIfRunning) {
synchronized (submission.lock) {
if (mayInterruptIfRunning && submission.thread != null)
submission.thread.interrupt();
submission.cancel = true;
submission.lock.notifyAll();
return true;
}
}
@Override
public Long get() throws InterruptedException, ExecutionException, CancellationException {
synchronized (submission.lock) {
while (!submission.processed && !submission.isCancelled() && submission.exception == null)
submission.lock.wait();
if (submission.isCancelled())
throw new CancellationException();
if (submission.exception != null)
throw new ExecutionException(submission.exception);
return (long) Math.round(((double) (submission.processedTime - submission.receivedTime))/1000000);
}
}
@Override
public Long get(long timeout, TimeUnit unit)
throws InterruptedException, ExecutionException, TimeoutException, CancellationException {
synchronized (submission.lock) {
long timeoutNs = unit.toNanos(timeout);
long start = System.nanoTime();
while (!submission.processed && !submission.isCancelled() && submission.exception == null &&
timeoutNs > 0) {
submission.lock.wait(timeoutNs/1000000, (int) (timeoutNs%1000000));
timeoutNs -= (System.nanoTime() - start);
}
if (submission.isCancelled())
throw new CancellationException();
if (submission.exception != null)
throw new ExecutionException(submission.exception);
if (timeoutNs <= 0)
throw new TimeoutException();
return timeoutNs <= 0 ? null : (long) Math.round(((double) (submission.processedTime -
submission.receivedTime))/1000000);
}
}
@Override
public boolean isCancelled() {
return submission.isCancelled();
}
@Override
public boolean isDone() {
return submission.processed;
}
}
/**
* An implementation of the {@link net.viktorc.pp4j.ProcessExecutor} interface for starting, managing, and interacting with a process. The
* life cycle of the associated process is the same as that of the {@link #run()} method of the instance. The process is not started until
* this method is called and the method does not terminate until the process does.
*
* @author Viktor Csomor
*
*/
private class StandardProcessExecutor implements ProcessExecutor, Runnable {
final ProcessManager manager;
final KeepAliveTimer timer;
final Semaphore termSemaphore;
final ReentrantLock subLock;
final Object runLock;
final Object stopLock;
final Object execLock;
final Object helperLock;
Process process;
BufferedReader stdOutReader;
BufferedReader errOutReader;
BufferedWriter stdInWriter;
Thread subThread;
Command command;
boolean commandProcessed;
boolean startedUp;
volatile boolean running;
volatile boolean stop;
/**
* Constructs an executor for the specified process using two threads to listen to the out streams of the process, one for listening
* to the submission queue, and one thread for ensuring that the process is terminated once it times out if <code>keepAliveTime
* </code> is greater than 0.
*/
StandardProcessExecutor() {
timer = doTime ? new KeepAliveTimer() : null;
this.manager = procManagerFactory.newProcessManager();
termSemaphore = new Semaphore(0);
subLock = new ReentrantLock();
runLock = new Object();
stopLock = new Object();
execLock = new Object();
helperLock = new Object();
}
/**
* Starts listening to an out stream of the process using the specified reader.
*
* @param reader The buffered reader to use to listen to the steam.
* @param standard Whether it is the standard out or the error out stream of the process.
*/
void startListeningToProcess(BufferedReader reader, boolean standard) {
try {
String line;
while ((line = reader.readLine()) != null) {
line = line.trim();
if (line.isEmpty())
continue;
synchronized (execLock) {
if (startedUp) {
commandProcessed = command == null || command.onNewOutput(line, standard);
if (commandProcessed)
execLock.notifyAll();
} else {
startedUp = manager.isStartedUp(line, standard);
if (startedUp)
execLock.notifyAll();
}
}
}
} catch (IOException e) {
throw new ProcessException(e);
} finally {
termSemaphore.release();
}
}
/**
* Starts waiting on the blocking queue of submissions executing available ones one at a time.
*/
void startHandlingSubmissions() {
synchronized (helperLock) {
subThread = Thread.currentThread();
}
try {
while (running && !stop) {
InternalSubmission submission = null;
try {
/* Wait until the startup phase is over and the mainLock is available to avoid retrieving a submission only to find that it cannot
* be executed and thus has to be put back into the queue. */
subLock.lock();
subLock.unlock();
// Wait for an available submission.
submission = submissions.takeFirst();
submission.setThread(subThread);
/* It can happen of course that in the mean time, the mainLock has been stolen (for terminating the process) or that the process
* is already terminated, and thus the execute method fails. In this case, the submission is put back into the queue. */
if (execute(submission)) {
if (verbose)
logger.info(String.format("Submission %s processed; delay: %.3f; execution time: %.3f.", submission,
(float) ((double) (submission.submittedTime - submission.receivedTime)/1000000000),
(float) ((double) (submission.processedTime - submission.submittedTime)/1000000000)));
submission = null;
}
} catch (InterruptedException e) {
// Next round (unless the process is stopped).
continue;
} catch (Exception e) {
// Signal the exception to the future and do not put the submission back into the queue.
if (submission != null) {
submission.setException(e);
submission = null;
}
} finally {
// If the execute method failed and there was no exception thrown, put the submission back into the queue at the front.
if (submission != null) {
submission.setThread(null);
submissions.addFirst(submission);
}
}
}
} finally {
synchronized (helperLock) {
subThread = null;
}
termSemaphore.release();
}
}
/**
* It prompts the currently running process, if there is one, to terminate. Once the process has been successfully terminated,
* subsequent calls are ignored and return true unless the process is started again.
*
* @param forcibly Whether the process should be killed forcibly or using the {@link net.viktorc.pp4j.ProcessManager#terminate(ProcessExecutor)}
* method of the {@link net.viktorc.pp4j.ProcessManager} instance assigned to the executor. The latter might be ineffective if the
* process is currently executing a command or has not started up.
* @return Whether the process was successfully terminated.
*/
boolean stop(boolean forcibly) {
synchronized (stopLock) {
if (stop)
return true;
synchronized (execLock) {
boolean success = true;
if (running) {
if (!forcibly)
success = manager.terminate(this);
else {
synchronized (helperLock) {
if (process != null)
process.destroy();
}
}
}
if (success) {
stop = true;
execLock.notifyAll();
}
return success;
}
}
}
@Override
public boolean execute(Submission submission) throws IOException, InterruptedException {
if (running && !stop && subLock.tryLock()) {
numOfExecutingSubmissions.incrementAndGet();
boolean success = false;
synchronized (execLock) {
try {
if (!running || stop)
return success;
if (doTime)
timer.stop();
if (stop)
return success;
submission.onStartedProcessing();
List<Command> commands = submission.getCommands();
List<Command> processedCommands = commands.size() > 1 ? new ArrayList<>(commands.size() - 1) : null;
for (int i = 0; i < commands.size() && !submission.isCancelled() && running && !stop; i++) {
command = commands.get(i);
if (i != 0 && !command.doExecute(new ArrayList<>(processedCommands)))
continue;
commandProcessed = !command.generatesOutput();
stdInWriter.write(command.getInstruction());
stdInWriter.newLine();
stdInWriter.flush();
while (running && !stop && !commandProcessed)
execLock.wait();
if (!commandProcessed)
return success;
if (i < commands.size() - 1)
processedCommands.add(command);
command = null;
}
if (running && !stop) {
if (submission.doTerminateProcessAfterwards()) {
if (!stop(false))
stop(true);
} else if (doTime)
timer.start();
}
success = true;
return success;
} finally {
try {
if (success)
submission.onFinishedProcessing();
} finally {
command = null;
numOfExecutingSubmissions.decrementAndGet();
subLock.unlock();
}
}
}
}
return false;
}
@Override
public void run() {
synchronized (runLock) {
running = true;
termSemaphore.drainPermits();
int rc = UNEXPECTED_TERMINATION_RESULT_CODE;
long lifeTime = 0;
try {
subLock.lock();
try {
// Start the process
synchronized (execLock) {
if (stop)
return;
command = null;
synchronized (helperLock) {
process = manager.start();
}
lifeTime = System.currentTimeMillis();
stdOutReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
errOutReader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
stdInWriter = new BufferedWriter(new OutputStreamWriter(process.getOutputStream()));
startedUp = manager.startsUpInstantly();
auxThreadPool.submit(() -> startListeningToProcess(stdOutReader, true));
auxThreadPool.submit(() -> startListeningToProcess(errOutReader, false));
while (!startedUp) {
execLock.wait();
if (stop)
return;
}
manager.onStartup(this);
prestartLatch.countDown();
if (stop)
return;
auxThreadPool.submit(this::startHandlingSubmissions);
if (doTime) {
auxThreadPool.submit(timer);
timer.start();
}
}
} catch (Exception e) {
termSemaphore.release(doTime ? 4 : 3);
throw e;
} finally {
subLock.unlock();
}
rc = process.waitFor();
} catch (Exception e) {
throw new ProcessException(e);
} finally {
// Try to clean up and close all the resources.
if (doTime)
timer.stop();
synchronized (helperLock) {
if (process != null) {
if (process.isAlive()) {
process.destroy();
try {
process.waitFor();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
process = null;
}
}
lifeTime = lifeTime == 0 ? 0 : System.currentTimeMillis() - lifeTime;
if (verbose)
logger.info(String.format("Process runtime in executor %s: %.3f", this, ((float) lifeTime)/1000));
subLock.lock();
try {
synchronized (execLock) {
running = false;
execLock.notifyAll();
}
synchronized (helperLock) {
if (subThread != null)
subThread.interrupt();
}
// Make sure that the timer sees the new value of 'running'.
if (doTime)
timer.stop();
} finally {
subLock.unlock();
}
try {
termSemaphore.acquire(doTime ? 4 : 3);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
if (stdOutReader != null) {
try {
stdOutReader.close();
} catch (IOException e) {
// Ignore it.
}
}
if (errOutReader != null) {
try {
errOutReader.close();
} catch (IOException e) {
// Ignore it.
}
}
if (stdInWriter != null) {
try {
stdInWriter.close();
} catch (IOException e) {
// Ignore it.
}
}
try {
manager.onTermination(rc, lifeTime);
} finally {
stop = false;
}
}
}
}
/**
* A simple timer that stops the process after <code>keepAliveTime</code> milliseconds unless the process is inactive
* or the timer is cancelled. It also enables the timer to be restarted using the same thread.
*
* @author Viktor Csomor
*
*/
private class KeepAliveTimer implements Runnable {
boolean go;
/**
* Restarts the timer.
*/
synchronized void start() {
go = true;
notifyAll();
}
/**
* Stops the timer.
*/
synchronized void stop() {
go = false;
notifyAll();
}
@Override
public synchronized void run() {
try {
while (running && !stop) {
while (!go) {
wait();
if (!running || stop)
return;
}
long waitTime = keepAliveTime;
while (go && waitTime > 0) {
long start = System.currentTimeMillis();
wait(waitTime);
if (!running || stop)
return;
waitTime -= (System.currentTimeMillis() - start);
}
if (go && subLock.tryLock()) {
try {
if (!StandardProcessExecutor.this.stop(false))
StandardProcessExecutor.this.stop(true);
} finally {
subLock.unlock();
}
}
}
} catch (InterruptedException e) {
// Just let the thread terminate.
} catch (Exception e) {
throw new ProcessException(e);
} finally {
go = false;
termSemaphore.release();
}
}
}
}
/**
* A sub-class of {@link org.apache.commons.pool2.impl.GenericObjectPool} for the pooling of {@link net.viktorc.pp4j.StandardProcessExecutor}
* instances.
*
* @author Viktor Csomor
*
*/
private class StandardProcessExecutorPool extends GenericObjectPool<StandardProcessExecutor> {
/**
* Constructs an object pool instance to facilitate the reuse of {@link net.viktorc.pp4j.StandardProcessExecutor} instances. The pool
* does not block if there are no available objects, it accommodates <code>maxPoolSize</code> objects, and if there are more than
* <code>Math.max(minPoolSize, reserveSize)</code> idle objects in the pool, excess idle objects are eligible for eviction after
* <code>keepAliveTime</code> milliseconds, or if it is non-positive, after <code>DEFAULT_EVICT_TIME</code> milliseconds. The eviction
* thread runs at the above specified intervals and performs at most <code>maxPoolSize - minPoolSize</code> evictions per run.
*/
StandardProcessExecutorPool() {
super(new PooledObjectFactory<StandardProcessExecutor>() {
@Override
public PooledObject<StandardProcessExecutor> makeObject() throws Exception {
return new DefaultPooledObject<StandardProcessExecutor>(new StandardProcessExecutor());
}
@Override
public void activateObject(PooledObject<StandardProcessExecutor> p) {
// No-operation.
}
@Override
public boolean validateObject(PooledObject<StandardProcessExecutor> p) {
return true;
}
@Override
public void passivateObject(PooledObject<StandardProcessExecutor> p) {
// No-operation
}
@Override
public void destroyObject(PooledObject<StandardProcessExecutor> p) {
// No-operation.
}
});
setBlockWhenExhausted(false);
setMaxTotal(maxPoolSize);
setMaxIdle(Math.max(minPoolSize, reserveSize));
long evictTime = doTime ? keepAliveTime : DEFAULT_EVICT_TIME;
setTimeBetweenEvictionRunsMillis(evictTime);
setSoftMinEvictableIdleTimeMillis(evictTime);
setNumTestsPerEvictionRun(maxPoolSize - minPoolSize);
}
}
/**
* An implementation the {@link java.util.concurrent.ThreadFactory} interface that provides more descriptive thread names and
* extends the {@link java.lang.Thread.UncaughtExceptionHandler} of the created threads by logging the uncaught exceptions if
* the enclosing {@link net.viktorc.pp4j.StandardProcessPool} instance is verbose. It also attempts to shut down the
* enclosing pool if a {@link net.viktorc.pp4j.ProcessException} is thrown in one of the threads it created.
*
* @author Viktor Csomor
*
*/
private class CustomizedThreadFactory implements ThreadFactory {
final String poolName;
final ThreadFactory defaultFactory;
/**
* Constructs an instance according to the specified parameters.
*
* @param poolName The name of the thread pool. It will be prepended to the name of the created threads.
*/
CustomizedThreadFactory(String poolName) {
this.poolName = poolName;
defaultFactory = Executors.defaultThreadFactory();
}
@Override
public Thread newThread(Runnable r) {
Thread t = defaultFactory.newThread(r);
t.setName(t.getName().replaceFirst("pool-[0-9]+", poolName));
t.setUncaughtExceptionHandler(new UncaughtExceptionHandler() {
@Override
public void uncaughtException(Thread t, Throwable e) {
// Log the exception whether verbose or not.
logger.log(Level.SEVERE, e.getMessage(), e);
StandardProcessPool.this.shutdown();
}
});
return t;
}
}
private class ProcessExecutorThreadPool extends ThreadPoolExecutor {
/**
* Constructs thread pool for the execution of {@link net.viktorc.pp4j.StandardProcessExecutor} instances. If there are more than
* <code>Math.max(minPoolSize, reserveSize)</code> idle threads in the pool, excess threads are evicted after <code>keepAliveTime
* </code> milliseconds, or if it is non-positive, after <code>DEFAULT_EVICT_TIME</code> milliseconds.
*/
ProcessExecutorThreadPool() {
super(Math.max(minPoolSize, reserveSize), maxPoolSize, doTime ? keepAliveTime : DEFAULT_EVICT_TIME,
TimeUnit.MILLISECONDS, new LinkedTransferQueue<Runnable>() {
private static final long serialVersionUID = 1L;
@Override
public boolean offer(Runnable r) {
/* If there is at least one thread waiting on the queue, delegate the task immediately; else decline it and force
* the pool to create a new thread for running the task. */
return tryTransfer(r);
}
}, new CustomizedThreadFactory("procExecThreadPool"),
new RejectedExecutionHandler() {
@Override
public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
try {
/* If there are no threads waiting on the queue (all of them are busy executing) and the maximum pool size has
* been reached, when the queue declines the offer, the pool will not create any more threads but call this
* handler instead. This handler 'forces' the declined task on the queue, ensuring that it is not rejected. */
executor.getQueue().put(r);
} catch (InterruptedException e) {
// Should not happen.
Thread.currentThread().interrupt();
}
}
});
}
@Override
protected void afterExecute(Runnable r, Throwable t) {
super.afterExecute(r, t);
StandardProcessExecutor executor = (StandardProcessExecutor) r;
activeExecutors.remove(executor);
if (verbose)
logger.info("Process executor " + executor + " stopped." + System.lineSeparator() +
getPoolStats());
synchronized (mainLock) {
if (doExtendPool())
startNewProcess(executor);
else
executorPool.returnObject(executor);
}
}
}
}
|
package nom.bdezonia.zorbage.misc;
import java.util.ArrayList;
import java.util.List;
import nom.bdezonia.zorbage.algebra.Algebra;
import nom.bdezonia.zorbage.algebra.G;
import nom.bdezonia.zorbage.data.DimensionedDataSource;
import nom.bdezonia.zorbage.tuple.Tuple2;
import nom.bdezonia.zorbage.type.bool.BooleanMember;
import nom.bdezonia.zorbage.type.character.FixedStringMember;
import nom.bdezonia.zorbage.type.character.StringMember;
import nom.bdezonia.zorbage.type.float16.complex.ComplexFloat16CartesianTensorProductMember;
import nom.bdezonia.zorbage.type.float16.complex.ComplexFloat16MatrixMember;
import nom.bdezonia.zorbage.type.float16.complex.ComplexFloat16Member;
import nom.bdezonia.zorbage.type.float16.complex.ComplexFloat16VectorMember;
import nom.bdezonia.zorbage.type.float16.octonion.OctonionFloat16CartesianTensorProductMember;
import nom.bdezonia.zorbage.type.float16.octonion.OctonionFloat16MatrixMember;
import nom.bdezonia.zorbage.type.float16.octonion.OctonionFloat16Member;
import nom.bdezonia.zorbage.type.float16.octonion.OctonionFloat16RModuleMember;
import nom.bdezonia.zorbage.type.float16.quaternion.QuaternionFloat16CartesianTensorProductMember;
import nom.bdezonia.zorbage.type.float16.quaternion.QuaternionFloat16MatrixMember;
import nom.bdezonia.zorbage.type.float16.quaternion.QuaternionFloat16Member;
import nom.bdezonia.zorbage.type.float16.quaternion.QuaternionFloat16RModuleMember;
import nom.bdezonia.zorbage.type.float16.real.Float16CartesianTensorProductMember;
import nom.bdezonia.zorbage.type.float16.real.Float16MatrixMember;
import nom.bdezonia.zorbage.type.float16.real.Float16Member;
import nom.bdezonia.zorbage.type.float16.real.Float16VectorMember;
import nom.bdezonia.zorbage.type.float32.complex.ComplexFloat32CartesianTensorProductMember;
import nom.bdezonia.zorbage.type.float32.complex.ComplexFloat32MatrixMember;
import nom.bdezonia.zorbage.type.float32.complex.ComplexFloat32Member;
import nom.bdezonia.zorbage.type.float32.complex.ComplexFloat32VectorMember;
import nom.bdezonia.zorbage.type.float32.octonion.OctonionFloat32CartesianTensorProductMember;
import nom.bdezonia.zorbage.type.float32.octonion.OctonionFloat32MatrixMember;
import nom.bdezonia.zorbage.type.float32.octonion.OctonionFloat32Member;
import nom.bdezonia.zorbage.type.float32.octonion.OctonionFloat32RModuleMember;
import nom.bdezonia.zorbage.type.float32.quaternion.QuaternionFloat32CartesianTensorProductMember;
import nom.bdezonia.zorbage.type.float32.quaternion.QuaternionFloat32MatrixMember;
import nom.bdezonia.zorbage.type.float32.quaternion.QuaternionFloat32Member;
import nom.bdezonia.zorbage.type.float32.quaternion.QuaternionFloat32RModuleMember;
import nom.bdezonia.zorbage.type.float32.real.Float32CartesianTensorProductMember;
import nom.bdezonia.zorbage.type.float32.real.Float32MatrixMember;
import nom.bdezonia.zorbage.type.float32.real.Float32Member;
import nom.bdezonia.zorbage.type.float32.real.Float32VectorMember;
import nom.bdezonia.zorbage.type.float64.complex.ComplexFloat64CartesianTensorProductMember;
import nom.bdezonia.zorbage.type.float64.complex.ComplexFloat64MatrixMember;
import nom.bdezonia.zorbage.type.float64.complex.ComplexFloat64Member;
import nom.bdezonia.zorbage.type.float64.complex.ComplexFloat64VectorMember;
import nom.bdezonia.zorbage.type.float64.octonion.OctonionFloat64CartesianTensorProductMember;
import nom.bdezonia.zorbage.type.float64.octonion.OctonionFloat64MatrixMember;
import nom.bdezonia.zorbage.type.float64.octonion.OctonionFloat64Member;
import nom.bdezonia.zorbage.type.float64.octonion.OctonionFloat64RModuleMember;
import nom.bdezonia.zorbage.type.float64.quaternion.QuaternionFloat64CartesianTensorProductMember;
import nom.bdezonia.zorbage.type.float64.quaternion.QuaternionFloat64MatrixMember;
import nom.bdezonia.zorbage.type.float64.quaternion.QuaternionFloat64Member;
import nom.bdezonia.zorbage.type.float64.quaternion.QuaternionFloat64RModuleMember;
import nom.bdezonia.zorbage.type.float64.real.Float64CartesianTensorProductMember;
import nom.bdezonia.zorbage.type.float64.real.Float64MatrixMember;
import nom.bdezonia.zorbage.type.float64.real.Float64Member;
import nom.bdezonia.zorbage.type.float64.real.Float64VectorMember;
import nom.bdezonia.zorbage.type.highprec.complex.ComplexHighPrecisionCartesianTensorProductMember;
import nom.bdezonia.zorbage.type.highprec.complex.ComplexHighPrecisionMatrixMember;
import nom.bdezonia.zorbage.type.highprec.complex.ComplexHighPrecisionMember;
import nom.bdezonia.zorbage.type.highprec.complex.ComplexHighPrecisionVectorMember;
import nom.bdezonia.zorbage.type.highprec.octonion.OctonionHighPrecisionCartesianTensorProductMember;
import nom.bdezonia.zorbage.type.highprec.octonion.OctonionHighPrecisionMatrixMember;
import nom.bdezonia.zorbage.type.highprec.octonion.OctonionHighPrecisionMember;
import nom.bdezonia.zorbage.type.highprec.octonion.OctonionHighPrecisionRModuleMember;
import nom.bdezonia.zorbage.type.highprec.quaternion.QuaternionHighPrecisionCartesianTensorProductMember;
import nom.bdezonia.zorbage.type.highprec.quaternion.QuaternionHighPrecisionMatrixMember;
import nom.bdezonia.zorbage.type.highprec.quaternion.QuaternionHighPrecisionMember;
import nom.bdezonia.zorbage.type.highprec.quaternion.QuaternionHighPrecisionRModuleMember;
import nom.bdezonia.zorbage.type.highprec.real.HighPrecisionCartesianTensorProductMember;
import nom.bdezonia.zorbage.type.highprec.real.HighPrecisionMatrixMember;
import nom.bdezonia.zorbage.type.highprec.real.HighPrecisionMember;
import nom.bdezonia.zorbage.type.highprec.real.HighPrecisionVectorMember;
import nom.bdezonia.zorbage.type.int1.SignedInt1Member;
import nom.bdezonia.zorbage.type.int1.UnsignedInt1Member;
import nom.bdezonia.zorbage.type.int10.SignedInt10Member;
import nom.bdezonia.zorbage.type.int10.UnsignedInt10Member;
import nom.bdezonia.zorbage.type.int11.SignedInt11Member;
import nom.bdezonia.zorbage.type.int11.UnsignedInt11Member;
import nom.bdezonia.zorbage.type.int12.SignedInt12Member;
import nom.bdezonia.zorbage.type.int12.UnsignedInt12Member;
import nom.bdezonia.zorbage.type.int128.SignedInt128Member;
import nom.bdezonia.zorbage.type.int128.UnsignedInt128Member;
import nom.bdezonia.zorbage.type.int13.SignedInt13Member;
import nom.bdezonia.zorbage.type.int13.UnsignedInt13Member;
import nom.bdezonia.zorbage.type.int14.SignedInt14Member;
import nom.bdezonia.zorbage.type.int14.UnsignedInt14Member;
import nom.bdezonia.zorbage.type.int15.SignedInt15Member;
import nom.bdezonia.zorbage.type.int15.UnsignedInt15Member;
import nom.bdezonia.zorbage.type.int16.SignedInt16Member;
import nom.bdezonia.zorbage.type.int16.UnsignedInt16Member;
import nom.bdezonia.zorbage.type.int2.SignedInt2Member;
import nom.bdezonia.zorbage.type.int2.UnsignedInt2Member;
import nom.bdezonia.zorbage.type.int3.SignedInt3Member;
import nom.bdezonia.zorbage.type.int3.UnsignedInt3Member;
import nom.bdezonia.zorbage.type.int32.SignedInt32Member;
import nom.bdezonia.zorbage.type.int32.UnsignedInt32Member;
import nom.bdezonia.zorbage.type.int4.SignedInt4Member;
import nom.bdezonia.zorbage.type.int4.UnsignedInt4Member;
import nom.bdezonia.zorbage.type.int5.SignedInt5Member;
import nom.bdezonia.zorbage.type.int5.UnsignedInt5Member;
import nom.bdezonia.zorbage.type.int6.SignedInt6Member;
import nom.bdezonia.zorbage.type.int6.UnsignedInt6Member;
import nom.bdezonia.zorbage.type.int64.SignedInt64Member;
import nom.bdezonia.zorbage.type.int64.UnsignedInt64Member;
import nom.bdezonia.zorbage.type.int7.SignedInt7Member;
import nom.bdezonia.zorbage.type.int7.UnsignedInt7Member;
import nom.bdezonia.zorbage.type.int8.SignedInt8Member;
import nom.bdezonia.zorbage.type.int8.UnsignedInt8Member;
import nom.bdezonia.zorbage.type.int9.SignedInt9Member;
import nom.bdezonia.zorbage.type.int9.UnsignedInt9Member;
import nom.bdezonia.zorbage.type.point.Point;
import nom.bdezonia.zorbage.type.rational.RationalMember;
import nom.bdezonia.zorbage.type.rgb.ArgbMember;
import nom.bdezonia.zorbage.type.rgb.RgbMember;
import nom.bdezonia.zorbage.type.unbounded.UnboundedIntMember;
/**
* @author Barry DeZonia
*/
public class DataBundle {
public List<DimensionedDataSource<ArgbMember>> argbs = new ArrayList<>();
public List<DimensionedDataSource<BooleanMember>> bools = new ArrayList<>();
public List<DimensionedDataSource<ComplexFloat64Member>> cdbls = new ArrayList<>();
public List<DimensionedDataSource<ComplexFloat64VectorMember>> cdbl_vecs = new ArrayList<>();
public List<DimensionedDataSource<ComplexFloat64MatrixMember>> cdbl_mats = new ArrayList<>();
public List<DimensionedDataSource<ComplexFloat64CartesianTensorProductMember>> cdbl_tens = new ArrayList<>();
public List<DimensionedDataSource<ComplexFloat32Member>> cflts = new ArrayList<>();
public List<DimensionedDataSource<ComplexFloat32VectorMember>> cflt_vecs = new ArrayList<>();
public List<DimensionedDataSource<ComplexFloat32MatrixMember>> cflt_mats = new ArrayList<>();
public List<DimensionedDataSource<ComplexFloat32CartesianTensorProductMember>> cflt_tens = new ArrayList<>();
public List<DimensionedDataSource<ComplexFloat16Member>> chlfs = new ArrayList<>();
public List<DimensionedDataSource<ComplexFloat16VectorMember>> chlf_vecs = new ArrayList<>();
public List<DimensionedDataSource<ComplexFloat16MatrixMember>> chlf_mats = new ArrayList<>();
public List<DimensionedDataSource<ComplexFloat16CartesianTensorProductMember>> chlf_tens = new ArrayList<>();
public List<DimensionedDataSource<ComplexHighPrecisionMember>> chps = new ArrayList<>();
public List<DimensionedDataSource<ComplexHighPrecisionVectorMember>> chp_vecs = new ArrayList<>();
public List<DimensionedDataSource<ComplexHighPrecisionMatrixMember>> chp_mats = new ArrayList<>();
public List<DimensionedDataSource<ComplexHighPrecisionCartesianTensorProductMember>> chp_tens = new ArrayList<>();
public List<DimensionedDataSource<Float64Member>> dbls = new ArrayList<>();
public List<DimensionedDataSource<Float64VectorMember>> dbl_vecs = new ArrayList<>();
public List<DimensionedDataSource<Float64MatrixMember>> dbl_mats = new ArrayList<>();
public List<DimensionedDataSource<Float64CartesianTensorProductMember>> dbl_tens = new ArrayList<>();
public List<DimensionedDataSource<Float32Member>> flts = new ArrayList<>();
public List<DimensionedDataSource<Float32VectorMember>> flt_vecs = new ArrayList<>();
public List<DimensionedDataSource<Float32MatrixMember>> flt_mats = new ArrayList<>();
public List<DimensionedDataSource<Float32CartesianTensorProductMember>> flt_tens = new ArrayList<>();
public List<DimensionedDataSource<FixedStringMember>> fstrs = new ArrayList<>();
public List<DimensionedDataSource<StringMember>> strs = new ArrayList<>();
public List<DimensionedDataSource<Float16Member>> hlfs = new ArrayList<>();
public List<DimensionedDataSource<Float16VectorMember>> hlf_vecs = new ArrayList<>();
public List<DimensionedDataSource<Float16MatrixMember>> hlf_mats = new ArrayList<>();
public List<DimensionedDataSource<Float16CartesianTensorProductMember>> hlf_tens = new ArrayList<>();
public List<DimensionedDataSource<HighPrecisionMember>> hps = new ArrayList<>();
public List<DimensionedDataSource<HighPrecisionVectorMember>> hp_vecs = new ArrayList<>();
public List<DimensionedDataSource<HighPrecisionMatrixMember>> hp_mats = new ArrayList<>();
public List<DimensionedDataSource<HighPrecisionCartesianTensorProductMember>> hp_tens = new ArrayList<>();
public List<DimensionedDataSource<SignedInt1Member>> int1s = new ArrayList<>();
public List<DimensionedDataSource<SignedInt2Member>> int2s = new ArrayList<>();
public List<DimensionedDataSource<SignedInt3Member>> int3s = new ArrayList<>();
public List<DimensionedDataSource<SignedInt4Member>> int4s = new ArrayList<>();
public List<DimensionedDataSource<SignedInt5Member>> int5s = new ArrayList<>();
public List<DimensionedDataSource<SignedInt6Member>> int6s = new ArrayList<>();
public List<DimensionedDataSource<SignedInt7Member>> int7s = new ArrayList<>();
public List<DimensionedDataSource<SignedInt8Member>> int8s = new ArrayList<>();
public List<DimensionedDataSource<SignedInt9Member>> int9s = new ArrayList<>();
public List<DimensionedDataSource<SignedInt10Member>> int10s = new ArrayList<>();
public List<DimensionedDataSource<SignedInt11Member>> int11s = new ArrayList<>();
public List<DimensionedDataSource<SignedInt12Member>> int12s = new ArrayList<>();
public List<DimensionedDataSource<SignedInt13Member>> int13s = new ArrayList<>();
public List<DimensionedDataSource<SignedInt14Member>> int14s = new ArrayList<>();
public List<DimensionedDataSource<SignedInt15Member>> int15s = new ArrayList<>();
public List<DimensionedDataSource<SignedInt16Member>> int16s = new ArrayList<>();
public List<DimensionedDataSource<SignedInt32Member>> int32s = new ArrayList<>();
public List<DimensionedDataSource<SignedInt64Member>> int64s = new ArrayList<>();
public List<DimensionedDataSource<SignedInt128Member>> int128s = new ArrayList<>();
public List<DimensionedDataSource<OctonionFloat64Member>> odbls = new ArrayList<>();
public List<DimensionedDataSource<OctonionFloat64RModuleMember>> odbl_rmods = new ArrayList<>();
public List<DimensionedDataSource<OctonionFloat64MatrixMember>> odbl_mats = new ArrayList<>();
public List<DimensionedDataSource<OctonionFloat64CartesianTensorProductMember>> odbl_tens = new ArrayList<>();
public List<DimensionedDataSource<OctonionFloat32Member>> oflts = new ArrayList<>();
public List<DimensionedDataSource<OctonionFloat32RModuleMember>> oflt_rmods = new ArrayList<>();
public List<DimensionedDataSource<OctonionFloat32MatrixMember>> oflt_mats = new ArrayList<>();
public List<DimensionedDataSource<OctonionFloat32CartesianTensorProductMember>> oflt_tens = new ArrayList<>();
public List<DimensionedDataSource<OctonionFloat16Member>> ohlfs = new ArrayList<>();
public List<DimensionedDataSource<OctonionFloat16RModuleMember>> ohlf_rmods = new ArrayList<>();
public List<DimensionedDataSource<OctonionFloat16MatrixMember>> ohlf_mats = new ArrayList<>();
public List<DimensionedDataSource<OctonionFloat16CartesianTensorProductMember>> ohlf_tens = new ArrayList<>();
public List<DimensionedDataSource<OctonionHighPrecisionMember>> ohps = new ArrayList<>();
public List<DimensionedDataSource<OctonionHighPrecisionRModuleMember>> ohp_rmods = new ArrayList<>();
public List<DimensionedDataSource<OctonionHighPrecisionMatrixMember>> ohp_mats = new ArrayList<>();
public List<DimensionedDataSource<OctonionHighPrecisionCartesianTensorProductMember>> ohp_tens = new ArrayList<>();
public List<DimensionedDataSource<Point>> points = new ArrayList<>();
public List<DimensionedDataSource<QuaternionFloat64Member>> qdbls = new ArrayList<>();
public List<DimensionedDataSource<QuaternionFloat64RModuleMember>> qdbl_rmods = new ArrayList<>();
public List<DimensionedDataSource<QuaternionFloat64MatrixMember>> qdbl_mats = new ArrayList<>();
public List<DimensionedDataSource<QuaternionFloat64CartesianTensorProductMember>> qdbl_tens = new ArrayList<>();
public List<DimensionedDataSource<QuaternionFloat32Member>> qflts = new ArrayList<>();
public List<DimensionedDataSource<QuaternionFloat32RModuleMember>> qflt_rmods = new ArrayList<>();
public List<DimensionedDataSource<QuaternionFloat32MatrixMember>> qflt_mats = new ArrayList<>();
public List<DimensionedDataSource<QuaternionFloat32CartesianTensorProductMember>> qflt_tens = new ArrayList<>();
public List<DimensionedDataSource<QuaternionFloat16Member>> qhlfs = new ArrayList<>();
public List<DimensionedDataSource<QuaternionFloat16RModuleMember>> qhlf_rmods = new ArrayList<>();
public List<DimensionedDataSource<QuaternionFloat16MatrixMember>> qhlf_mats = new ArrayList<>();
public List<DimensionedDataSource<QuaternionFloat16CartesianTensorProductMember>> qhlf_tens = new ArrayList<>();
public List<DimensionedDataSource<QuaternionHighPrecisionMember>> qhps = new ArrayList<>();
public List<DimensionedDataSource<QuaternionHighPrecisionRModuleMember>> qhp_rmods = new ArrayList<>();
public List<DimensionedDataSource<QuaternionHighPrecisionMatrixMember>> qhp_mats = new ArrayList<>();
public List<DimensionedDataSource<QuaternionHighPrecisionCartesianTensorProductMember>> qhp_tens = new ArrayList<>();
public List<DimensionedDataSource<RationalMember>> rationals = new ArrayList<>();
public List<DimensionedDataSource<RgbMember>> rgbs = new ArrayList<>();
public List<DimensionedDataSource<UnsignedInt1Member>> uint1s = new ArrayList<>();
public List<DimensionedDataSource<UnsignedInt2Member>> uint2s = new ArrayList<>();
public List<DimensionedDataSource<UnsignedInt3Member>> uint3s = new ArrayList<>();
public List<DimensionedDataSource<UnsignedInt4Member>> uint4s = new ArrayList<>();
public List<DimensionedDataSource<UnsignedInt5Member>> uint5s = new ArrayList<>();
public List<DimensionedDataSource<UnsignedInt6Member>> uint6s = new ArrayList<>();
public List<DimensionedDataSource<UnsignedInt7Member>> uint7s = new ArrayList<>();
public List<DimensionedDataSource<UnsignedInt8Member>> uint8s = new ArrayList<>();
public List<DimensionedDataSource<UnsignedInt9Member>> uint9s = new ArrayList<>();
public List<DimensionedDataSource<UnsignedInt10Member>> uint10s = new ArrayList<>();
public List<DimensionedDataSource<UnsignedInt11Member>> uint11s = new ArrayList<>();
public List<DimensionedDataSource<UnsignedInt12Member>> uint12s = new ArrayList<>();
public List<DimensionedDataSource<UnsignedInt13Member>> uint13s = new ArrayList<>();
public List<DimensionedDataSource<UnsignedInt14Member>> uint14s = new ArrayList<>();
public List<DimensionedDataSource<UnsignedInt15Member>> uint15s = new ArrayList<>();
public List<DimensionedDataSource<UnsignedInt16Member>> uint16s = new ArrayList<>();
public List<DimensionedDataSource<UnsignedInt32Member>> uint32s = new ArrayList<>();
public List<DimensionedDataSource<UnsignedInt64Member>> uint64s = new ArrayList<>();
public List<DimensionedDataSource<UnsignedInt128Member>> uint128s = new ArrayList<>();
public List<DimensionedDataSource<UnboundedIntMember>> unbounds = new ArrayList<>();
public void mergeArgb(DimensionedDataSource<ArgbMember> ds) {
if (ds != null)
argbs.add(ds);
}
public void mergeBool(DimensionedDataSource<BooleanMember> ds) {
if (ds != null)
bools.add(ds);
}
public void mergeComplexFlt64(DimensionedDataSource<ComplexFloat64Member> ds) {
if (ds != null)
cdbls.add(ds);
}
public void mergeComplexFlt64Vec(DimensionedDataSource<ComplexFloat64VectorMember> ds) {
if (ds != null)
cdbl_vecs.add(ds);
}
public void mergeComplexFlt64Mat(DimensionedDataSource<ComplexFloat64MatrixMember> ds) {
if (ds != null)
cdbl_mats.add(ds);
}
public void mergeComplexFlt64Tens(DimensionedDataSource<ComplexFloat64CartesianTensorProductMember> ds) {
if (ds != null)
cdbl_tens.add(ds);
}
public void mergeComplexFlt32(DimensionedDataSource<ComplexFloat32Member> ds) {
if (ds != null)
cflts.add(ds);
}
public void mergeComplexFlt32Vec(DimensionedDataSource<ComplexFloat32VectorMember> ds) {
if (ds != null)
cflt_vecs.add(ds);
}
public void mergeComplexFlt32Mat(DimensionedDataSource<ComplexFloat32MatrixMember> ds) {
if (ds != null)
cflt_mats.add(ds);
}
public void mergeComplexFlt32Tens(DimensionedDataSource<ComplexFloat32CartesianTensorProductMember> ds) {
if (ds != null)
cflt_tens.add(ds);
}
public void mergeComplexFlt16(DimensionedDataSource<ComplexFloat16Member> ds) {
if (ds != null)
chlfs.add(ds);
}
public void mergeComplexFlt16Vec(DimensionedDataSource<ComplexFloat16VectorMember> ds) {
if (ds != null)
chlf_vecs.add(ds);
}
public void mergeComplexFlt16Mat(DimensionedDataSource<ComplexFloat16MatrixMember> ds) {
if (ds != null)
chlf_mats.add(ds);
}
public void mergeComplexFlt16Tens(DimensionedDataSource<ComplexFloat16CartesianTensorProductMember> ds) {
if (ds != null)
chlf_tens.add(ds);
}
public void mergeComplexHP(DimensionedDataSource<ComplexHighPrecisionMember> ds) {
if (ds != null)
chps.add(ds);
}
public void mergeComplexHPVec(DimensionedDataSource<ComplexHighPrecisionVectorMember> ds) {
if (ds != null)
chp_vecs.add(ds);
}
public void mergeComplexHPMat(DimensionedDataSource<ComplexHighPrecisionMatrixMember> ds) {
if (ds != null)
chp_mats.add(ds);
}
public void mergeComplexHPTens(DimensionedDataSource<ComplexHighPrecisionCartesianTensorProductMember> ds) {
if (ds != null)
chp_tens.add(ds);
}
public void mergeFlt64(DimensionedDataSource<Float64Member> ds) {
if (ds != null)
dbls.add(ds);
}
public void mergeFlt64Vec(DimensionedDataSource<Float64VectorMember> ds) {
if (ds != null)
dbl_vecs.add(ds);
}
public void mergeFlt64Mat(DimensionedDataSource<Float64MatrixMember> ds) {
if (ds != null)
dbl_mats.add(ds);
}
public void mergeFlt64Tens(DimensionedDataSource<Float64CartesianTensorProductMember> ds) {
if (ds != null)
dbl_tens.add(ds);
}
public void mergeFlt32(DimensionedDataSource<Float32Member> ds) {
if (ds != null)
flts.add(ds);
}
public void mergeFlt32Vec(DimensionedDataSource<Float32VectorMember> ds) {
if (ds != null)
flt_vecs.add(ds);
}
public void mergeFlt32Mat(DimensionedDataSource<Float32MatrixMember> ds) {
if (ds != null)
flt_mats.add(ds);
}
public void mergeFlt32Tens(DimensionedDataSource<Float32CartesianTensorProductMember> ds) {
if (ds != null)
flt_tens.add(ds);
}
public void mergeFixedString(DimensionedDataSource<FixedStringMember> ds) {
if (ds != null)
fstrs.add(ds);
}
public void mergeString(DimensionedDataSource<StringMember> ds) {
if (ds != null)
strs.add(ds);
}
public void mergeFlt16(DimensionedDataSource<Float16Member> ds) {
if (ds != null)
hlfs.add(ds);
}
public void mergeFlt16Vec(DimensionedDataSource<Float16VectorMember> ds) {
if (ds != null)
hlf_vecs.add(ds);
}
public void mergeFlt16Mat(DimensionedDataSource<Float16MatrixMember> ds) {
if (ds != null)
hlf_mats.add(ds);
}
public void mergeFlt16Tens(DimensionedDataSource<Float16CartesianTensorProductMember> ds) {
if (ds != null)
hlf_tens.add(ds);
}
public void mergeHP(DimensionedDataSource<HighPrecisionMember> ds) {
if (ds != null)
hps.add(ds);
}
public void mergeHPVec(DimensionedDataSource<HighPrecisionVectorMember> ds) {
if (ds != null)
hp_vecs.add(ds);
}
public void mergeHPMat(DimensionedDataSource<HighPrecisionMatrixMember> ds) {
if (ds != null)
hp_mats.add(ds);
}
public void mergeHPTens(DimensionedDataSource<HighPrecisionCartesianTensorProductMember> ds) {
if (ds != null)
hp_tens.add(ds);
}
public void mergeInt1(DimensionedDataSource<SignedInt1Member> ds) {
if (ds != null)
int1s.add(ds);
}
public void mergeInt2(DimensionedDataSource<SignedInt2Member> ds) {
if (ds != null)
int2s.add(ds);
}
public void mergeInt3(DimensionedDataSource<SignedInt3Member> ds) {
if (ds != null)
int3s.add(ds);
}
public void mergeInt4(DimensionedDataSource<SignedInt4Member> ds) {
if (ds != null)
int4s.add(ds);
}
public void mergeInt5(DimensionedDataSource<SignedInt5Member> ds) {
if (ds != null)
int5s.add(ds);
}
public void mergeInt6(DimensionedDataSource<SignedInt6Member> ds) {
if (ds != null)
int6s.add(ds);
}
public void mergeInt7(DimensionedDataSource<SignedInt7Member> ds) {
if (ds != null)
int7s.add(ds);
}
public void mergeInt8(DimensionedDataSource<SignedInt8Member> ds) {
if (ds != null)
int8s.add(ds);
}
public void mergeInt9(DimensionedDataSource<SignedInt9Member> ds) {
if (ds != null)
int9s.add(ds);
}
public void mergeInt10(DimensionedDataSource<SignedInt10Member> ds) {
if (ds != null)
int10s.add(ds);
}
public void mergeInt11(DimensionedDataSource<SignedInt11Member> ds) {
if (ds != null)
int11s.add(ds);
}
public void mergeInt12(DimensionedDataSource<SignedInt12Member> ds) {
if (ds != null)
int12s.add(ds);
}
public void mergeInt13(DimensionedDataSource<SignedInt13Member> ds) {
if (ds != null)
int13s.add(ds);
}
public void mergeInt14(DimensionedDataSource<SignedInt14Member> ds) {
if (ds != null)
int14s.add(ds);
}
public void mergeInt15(DimensionedDataSource<SignedInt15Member> ds) {
if (ds != null)
int15s.add(ds);
}
public void mergeInt16(DimensionedDataSource<SignedInt16Member> ds) {
if (ds != null)
int16s.add(ds);
}
public void mergeInt32(DimensionedDataSource<SignedInt32Member> ds) {
if (ds != null)
int32s.add(ds);
}
public void mergeInt64(DimensionedDataSource<SignedInt64Member> ds) {
if (ds != null)
int64s.add(ds);
}
public void mergeInt128(DimensionedDataSource<SignedInt128Member> ds) {
if (ds != null)
int128s.add(ds);
}
public void mergeOct64(DimensionedDataSource<OctonionFloat64Member> ds) {
if (ds != null)
odbls.add(ds);
}
public void mergeOct64RMod(DimensionedDataSource<OctonionFloat64RModuleMember> ds) {
if (ds != null)
odbl_rmods.add(ds);
}
public void mergeOct64Mat(DimensionedDataSource<OctonionFloat64MatrixMember> ds) {
if (ds != null)
odbl_mats.add(ds);
}
public void mergeOct64Tens(DimensionedDataSource<OctonionFloat64CartesianTensorProductMember> ds) {
if (ds != null)
odbl_tens.add(ds);
}
public void mergeOct32(DimensionedDataSource<OctonionFloat32Member> ds) {
if (ds != null)
oflts.add(ds);
}
public void mergeOct32RMod(DimensionedDataSource<OctonionFloat32RModuleMember> ds) {
if (ds != null)
oflt_rmods.add(ds);
}
public void mergeOct32Mat(DimensionedDataSource<OctonionFloat32MatrixMember> ds) {
if (ds != null)
oflt_mats.add(ds);
}
public void mergeOct32Tens(DimensionedDataSource<OctonionFloat32CartesianTensorProductMember> ds) {
if (ds != null)
oflt_tens.add(ds);
}
public void mergeOct16(DimensionedDataSource<OctonionFloat16Member> ds) {
if (ds != null)
ohlfs.add(ds);
}
public void mergeOct16RMod(DimensionedDataSource<OctonionFloat16RModuleMember> ds) {
if (ds != null)
ohlf_rmods.add(ds);
}
public void mergeOct16Mat(DimensionedDataSource<OctonionFloat16MatrixMember> ds) {
if (ds != null)
ohlf_mats.add(ds);
}
public void mergeOct16Tens(DimensionedDataSource<OctonionFloat16CartesianTensorProductMember> ds) {
if (ds != null)
ohlf_tens.add(ds);
}
public void mergeOctHP(DimensionedDataSource<OctonionHighPrecisionMember> ds) {
if (ds != null)
ohps.add(ds);
}
public void mergeOctHPRMod(DimensionedDataSource<OctonionHighPrecisionRModuleMember> ds) {
if (ds != null)
ohp_rmods.add(ds);
}
public void mergeOctHPMat(DimensionedDataSource<OctonionHighPrecisionMatrixMember> ds) {
if (ds != null)
ohp_mats.add(ds);
}
public void mergeOctHPTens(DimensionedDataSource<OctonionHighPrecisionCartesianTensorProductMember> ds) {
if (ds != null)
ohp_tens.add(ds);
}
public void mergePoint(DimensionedDataSource<Point> ds) {
if (ds != null)
points.add(ds);
}
public void mergeQuat64(DimensionedDataSource<QuaternionFloat64Member> ds) {
if (ds != null)
qdbls.add(ds);
}
public void mergeQuat64RMod(DimensionedDataSource<QuaternionFloat64RModuleMember> ds) {
if (ds != null)
qdbl_rmods.add(ds);
}
public void mergeQuat64Mat(DimensionedDataSource<QuaternionFloat64MatrixMember> ds) {
if (ds != null)
qdbl_mats.add(ds);
}
public void mergeQuat64Tens(DimensionedDataSource<QuaternionFloat64CartesianTensorProductMember> ds) {
if (ds != null)
qdbl_tens.add(ds);
}
public void mergeQuat32(DimensionedDataSource<QuaternionFloat32Member> ds) {
if (ds != null)
qflts.add(ds);
}
public void mergeQuat32RMod(DimensionedDataSource<QuaternionFloat32RModuleMember> ds) {
if (ds != null)
qflt_rmods.add(ds);
}
public void mergeQuat32Mat(DimensionedDataSource<QuaternionFloat32MatrixMember> ds) {
if (ds != null)
qflt_mats.add(ds);
}
public void mergeQuat32Tens(DimensionedDataSource<QuaternionFloat32CartesianTensorProductMember> ds) {
if (ds != null)
qflt_tens.add(ds);
}
public void mergeQuat16(DimensionedDataSource<QuaternionFloat16Member> ds) {
if (ds != null)
qhlfs.add(ds);
}
public void mergeQuat16RMod(DimensionedDataSource<QuaternionFloat16RModuleMember> ds) {
if (ds != null)
qhlf_rmods.add(ds);
}
public void mergeQuat16Mat(DimensionedDataSource<QuaternionFloat16MatrixMember> ds) {
if (ds != null)
qhlf_mats.add(ds);
}
public void mergeQuat16Tens(DimensionedDataSource<QuaternionFloat16CartesianTensorProductMember> ds) {
if (ds != null)
qhlf_tens.add(ds);
}
public void mergeQuatHP(DimensionedDataSource<QuaternionHighPrecisionMember> ds) {
if (ds != null)
qhps.add(ds);
}
public void mergeQuatHPRMod(DimensionedDataSource<QuaternionHighPrecisionRModuleMember> ds) {
if (ds != null)
qhp_rmods.add(ds);
}
public void mergeQuatHPMat(DimensionedDataSource<QuaternionHighPrecisionMatrixMember> ds) {
if (ds != null)
qhp_mats.add(ds);
}
public void mergeQuatHPTens(DimensionedDataSource<QuaternionHighPrecisionCartesianTensorProductMember> ds) {
if (ds != null)
qhp_tens.add(ds);
}
public void mergeRational(DimensionedDataSource<RationalMember> ds) {
if (ds != null)
rationals.add(ds);
}
public void mergeRgb(DimensionedDataSource<RgbMember> ds) {
if (ds != null)
rgbs.add(ds);
}
public void mergeUInt1(DimensionedDataSource<UnsignedInt1Member> ds) {
if (ds != null)
uint1s.add(ds);
}
public void mergeUInt2(DimensionedDataSource<UnsignedInt2Member> ds) {
if (ds != null)
uint2s.add(ds);
}
public void mergeUInt3(DimensionedDataSource<UnsignedInt3Member> ds) {
if (ds != null)
uint3s.add(ds);
}
public void mergeUInt4(DimensionedDataSource<UnsignedInt4Member> ds) {
if (ds != null)
uint4s.add(ds);
}
public void mergeUInt5(DimensionedDataSource<UnsignedInt5Member> ds) {
if (ds != null)
uint5s.add(ds);
}
public void mergeUInt6(DimensionedDataSource<UnsignedInt6Member> ds) {
if (ds != null)
uint6s.add(ds);
}
public void mergeUInt7(DimensionedDataSource<UnsignedInt7Member> ds) {
if (ds != null)
uint7s.add(ds);
}
public void mergeUInt8(DimensionedDataSource<UnsignedInt8Member> ds) {
if (ds != null)
uint8s.add(ds);
}
public void mergeUInt9(DimensionedDataSource<UnsignedInt9Member> ds) {
if (ds != null)
uint9s.add(ds);
}
public void mergeUInt10(DimensionedDataSource<UnsignedInt10Member> ds) {
if (ds != null)
uint10s.add(ds);
}
public void mergeUInt11(DimensionedDataSource<UnsignedInt11Member> ds) {
if (ds != null)
uint11s.add(ds);
}
public void mergeUInt12(DimensionedDataSource<UnsignedInt12Member> ds) {
if (ds != null)
uint12s.add(ds);
}
public void mergeUInt13(DimensionedDataSource<UnsignedInt13Member> ds) {
if (ds != null)
uint13s.add(ds);
}
public void mergeUInt14(DimensionedDataSource<UnsignedInt14Member> ds) {
if (ds != null)
uint14s.add(ds);
}
public void mergeUInt15(DimensionedDataSource<UnsignedInt15Member> ds) {
if (ds != null)
uint15s.add(ds);
}
public void mergeUInt16(DimensionedDataSource<UnsignedInt16Member> ds) {
if (ds != null)
uint16s.add(ds);
}
public void mergeUInt32(DimensionedDataSource<UnsignedInt32Member> ds) {
if (ds != null)
uint32s.add(ds);
}
public void mergeUInt64(DimensionedDataSource<UnsignedInt64Member> ds) {
if (ds != null)
uint64s.add(ds);
}
public void mergeUInt128(DimensionedDataSource<UnsignedInt128Member> ds) {
if (ds != null)
uint128s.add(ds);
}
public void mergeBigInt(DimensionedDataSource<UnboundedIntMember> ds) {
if (ds != null)
unbounds.add(ds);
}
public void mergeComplexFloat16(DimensionedDataSource<ComplexFloat16Member> ds) {
if (ds != null)
chlfs.add(ds);
}
public void mergeComplexFloat32(DimensionedDataSource<ComplexFloat32Member> ds) {
if (ds != null)
cflts.add(ds);
}
public void mergeComplexFloat64(DimensionedDataSource<ComplexFloat64Member> ds) {
if (ds != null)
cdbls.add(ds);
}
public void mergeComplexHighPrec(DimensionedDataSource<ComplexHighPrecisionMember> ds) {
if (ds != null)
chps.add(ds);
}
public void mergeQuaternionFloat16(DimensionedDataSource<QuaternionFloat16Member> ds) {
if (ds != null)
qhlfs.add(ds);
}
public void mergeQuaternionFloat32(DimensionedDataSource<QuaternionFloat32Member> ds) {
if (ds != null)
qflts.add(ds);
}
public void mergeQuaternionFloat64(DimensionedDataSource<QuaternionFloat64Member> ds) {
if (ds != null)
qdbls.add(ds);
}
public void mergeQuaternionHighPrec(DimensionedDataSource<QuaternionHighPrecisionMember> ds) {
if (ds != null)
qhps.add(ds);
}
public void mergeOctonionFloat16(DimensionedDataSource<OctonionFloat16Member> ds) {
if (ds != null)
ohlfs.add(ds);
}
public void mergeOctonionFloat32(DimensionedDataSource<OctonionFloat32Member> ds) {
if (ds != null)
oflts.add(ds);
}
public void mergeOctonionFloat64(DimensionedDataSource<OctonionFloat64Member> ds) {
if (ds != null)
odbls.add(ds);
}
public void mergeOctonionHighPrec(DimensionedDataSource<OctonionHighPrecisionMember> ds) {
if (ds != null)
ohps.add(ds);
}
public void mergeAll(DataBundle other) {
if (this == other) return;
argbs.addAll(other.argbs);
bools.addAll(other.bools);
cdbls.addAll(other.cdbls);
cdbl_vecs.addAll(other.cdbl_vecs);
cdbl_mats.addAll(other.cdbl_mats);
cdbl_tens.addAll(other.cdbl_tens);
cflts.addAll(other.cflts);
cflt_vecs.addAll(other.cflt_vecs);
cflt_mats.addAll(other.cflt_mats);
cflt_tens.addAll(other.cflt_tens);
chlfs.addAll(other.chlfs);
chlf_vecs.addAll(other.chlf_vecs);
chlf_mats.addAll(other.chlf_mats);
chlf_tens.addAll(other.chlf_tens);
chps.addAll(other.chps);
chp_vecs.addAll(other.chp_vecs);
chp_mats.addAll(other.chp_mats);
chp_tens.addAll(other.chp_tens);
dbls.addAll(other.dbls);
dbl_vecs.addAll(other.dbl_vecs);
dbl_mats.addAll(other.dbl_mats);
dbl_tens.addAll(other.dbl_tens);
flts.addAll(other.flts);
flt_vecs.addAll(other.flt_vecs);
flt_mats.addAll(other.flt_mats);
flt_tens.addAll(other.flt_tens);
fstrs.addAll(other.fstrs);
hlfs.addAll(other.hlfs);
hlf_vecs.addAll(other.hlf_vecs);
hlf_mats.addAll(other.hlf_mats);
hlf_tens.addAll(other.hlf_tens);
hps.addAll(other.hps);
hp_vecs.addAll(other.hp_vecs);
hp_mats.addAll(other.hp_mats);
hp_tens.addAll(other.hp_tens);
int1s.addAll(other.int1s);
int2s.addAll(other.int2s);
int3s.addAll(other.int3s);
int4s.addAll(other.int4s);
int5s.addAll(other.int5s);
int6s.addAll(other.int6s);
int7s.addAll(other.int7s);
int8s.addAll(other.int8s);
int9s.addAll(other.int9s);
int10s.addAll(other.int10s);
int11s.addAll(other.int11s);
int12s.addAll(other.int12s);
int13s.addAll(other.int13s);
int14s.addAll(other.int14s);
int15s.addAll(other.int15s);
int16s.addAll(other.int16s);
int32s.addAll(other.int32s);
int64s.addAll(other.int64s);
int128s.addAll(other.int128s);
odbls.addAll(other.odbls);
odbl_rmods.addAll(other.odbl_rmods);
odbl_mats.addAll(other.odbl_mats);
odbl_tens.addAll(other.odbl_tens);
oflts.addAll(other.oflts);
oflt_rmods.addAll(other.oflt_rmods);
oflt_mats.addAll(other.oflt_mats);
oflt_tens.addAll(other.oflt_tens);
ohlfs.addAll(other.ohlfs);
ohlf_rmods.addAll(other.ohlf_rmods);
ohlf_mats.addAll(other.ohlf_mats);
ohlf_tens.addAll(other.ohlf_tens);
ohps.addAll(other.ohps);
ohp_rmods.addAll(other.ohp_rmods);
ohp_mats.addAll(other.ohp_mats);
ohp_tens.addAll(other.ohp_tens);
points.addAll(other.points);
qdbls.addAll(other.qdbls);
qdbl_rmods.addAll(other.qdbl_rmods);
qdbl_mats.addAll(other.qdbl_mats);
qdbl_tens.addAll(other.qdbl_tens);
qflts.addAll(other.qflts);
qflt_rmods.addAll(other.qflt_rmods);
qflt_mats.addAll(other.qflt_mats);
qflt_tens.addAll(other.qflt_tens);
qhlfs.addAll(other.qhlfs);
qhlf_rmods.addAll(other.qhlf_rmods);
qhlf_mats.addAll(other.qhlf_mats);
qhlf_tens.addAll(other.qhlf_tens);
qhps.addAll(other.qhps);
qhp_rmods.addAll(other.qhp_rmods);
qhp_mats.addAll(other.qhp_mats);
qhp_tens.addAll(other.qhp_tens);
rationals.addAll(other.rationals);
rgbs.addAll(other.rgbs);
uint1s.addAll(other.uint1s);
uint2s.addAll(other.uint2s);
uint3s.addAll(other.uint3s);
uint4s.addAll(other.uint4s);
uint5s.addAll(other.uint5s);
uint6s.addAll(other.uint6s);
uint7s.addAll(other.uint7s);
uint8s.addAll(other.uint8s);
uint9s.addAll(other.uint9s);
uint10s.addAll(other.uint10s);
uint11s.addAll(other.uint11s);
uint12s.addAll(other.uint12s);
uint13s.addAll(other.uint13s);
uint14s.addAll(other.uint14s);
uint15s.addAll(other.uint15s);
uint16s.addAll(other.uint16s);
uint32s.addAll(other.uint32s);
uint64s.addAll(other.uint64s);
uint128s.addAll(other.uint128s);
unbounds.addAll(other.unbounds);
}
@SuppressWarnings("unchecked")
public <T extends Algebra<T,U>, U>
List<Tuple2<T,DimensionedDataSource<U>>> bundle()
{
ArrayList<Tuple2<T,DimensionedDataSource<U>>> fullList = new ArrayList<>();
for (DimensionedDataSource<?> ds : this.argbs) {
Tuple2<T, DimensionedDataSource<U>> tuple =
new Tuple2<T, DimensionedDataSource<U>>((T)G.ARGB, (DimensionedDataSource<U>)ds);
fullList.add(tuple);
}
for (DimensionedDataSource<?> ds : this.bools) {
Tuple2<T, DimensionedDataSource<U>> tuple =
new Tuple2<T, DimensionedDataSource<U>>((T)G.BOOL, (DimensionedDataSource<U>)ds);
fullList.add(tuple);
}
for (DimensionedDataSource<?> ds : this.cdbls) {
Tuple2<T, DimensionedDataSource<U>> tuple =
new Tuple2<T, DimensionedDataSource<U>>((T)G.CDBL, (DimensionedDataSource<U>)ds);
fullList.add(tuple);
}
for (DimensionedDataSource<?> ds : this.cdbl_vecs) {
Tuple2<T, DimensionedDataSource<U>> tuple =
new Tuple2<T, DimensionedDataSource<U>>((T)G.CDBL_VEC, (DimensionedDataSource<U>)ds);
fullList.add(tuple);
}
for (DimensionedDataSource<?> ds : this.cdbl_mats) {
Tuple2<T, DimensionedDataSource<U>> tuple =
new Tuple2<T, DimensionedDataSource<U>>((T)G.CDBL_MAT, (DimensionedDataSource<U>)ds);
fullList.add(tuple);
}
for (DimensionedDataSource<?> ds : this.cdbl_tens) {
Tuple2<T, DimensionedDataSource<U>> tuple =
new Tuple2<T, DimensionedDataSource<U>>((T)G.CDBL_TEN, (DimensionedDataSource<U>)ds);
fullList.add(tuple);
}
for (DimensionedDataSource<?> ds : this.cflts) {
Tuple2<T, DimensionedDataSource<U>> tuple =
new Tuple2<T, DimensionedDataSource<U>>((T)G.CFLT, (DimensionedDataSource<U>)ds);
fullList.add(tuple);
}
for (DimensionedDataSource<?> ds : this.cflt_vecs) {
Tuple2<T, DimensionedDataSource<U>> tuple =
new Tuple2<T, DimensionedDataSource<U>>((T)G.CFLT_VEC, (DimensionedDataSource<U>)ds);
fullList.add(tuple);
}
for (DimensionedDataSource<?> ds : this.cflt_mats) {
Tuple2<T, DimensionedDataSource<U>> tuple =
new Tuple2<T, DimensionedDataSource<U>>((T)G.CFLT_MAT, (DimensionedDataSource<U>)ds);
fullList.add(tuple);
}
for (DimensionedDataSource<?> ds : this.cflt_tens) {
Tuple2<T, DimensionedDataSource<U>> tuple =
new Tuple2<T, DimensionedDataSource<U>>((T)G.CFLT_TEN, (DimensionedDataSource<U>)ds);
fullList.add(tuple);
}
for (DimensionedDataSource<?> ds : this.chlfs) {
Tuple2<T, DimensionedDataSource<U>> tuple =
new Tuple2<T, DimensionedDataSource<U>>((T)G.CHLF, (DimensionedDataSource<U>)ds);
fullList.add(tuple);
}
for (DimensionedDataSource<?> ds : this.chlf_vecs) {
Tuple2<T, DimensionedDataSource<U>> tuple =
new Tuple2<T, DimensionedDataSource<U>>((T)G.CHLF_VEC, (DimensionedDataSource<U>)ds);
fullList.add(tuple);
}
for (DimensionedDataSource<?> ds : this.chlf_mats) {
Tuple2<T, DimensionedDataSource<U>> tuple =
new Tuple2<T, DimensionedDataSource<U>>((T)G.CHLF_MAT, (DimensionedDataSource<U>)ds);
fullList.add(tuple);
}
for (DimensionedDataSource<?> ds : this.chlf_tens) {
Tuple2<T, DimensionedDataSource<U>> tuple =
new Tuple2<T, DimensionedDataSource<U>>((T)G.CHLF_TEN, (DimensionedDataSource<U>)ds);
fullList.add(tuple);
}
for (DimensionedDataSource<?> ds : this.chps) {
Tuple2<T, DimensionedDataSource<U>> tuple =
new Tuple2<T, DimensionedDataSource<U>>((T)G.CHP, (DimensionedDataSource<U>)ds);
fullList.add(tuple);
}
for (DimensionedDataSource<?> ds : this.chp_vecs) {
Tuple2<T, DimensionedDataSource<U>> tuple =
new Tuple2<T, DimensionedDataSource<U>>((T)G.CHP_VEC, (DimensionedDataSource<U>)ds);
fullList.add(tuple);
}
for (DimensionedDataSource<?> ds : this.chp_mats) {
Tuple2<T, DimensionedDataSource<U>> tuple =
new Tuple2<T, DimensionedDataSource<U>>((T)G.CHP_MAT, (DimensionedDataSource<U>)ds);
fullList.add(tuple);
}
for (DimensionedDataSource<?> ds : this.chp_tens) {
Tuple2<T, DimensionedDataSource<U>> tuple =
new Tuple2<T, DimensionedDataSource<U>>((T)G.CHP_TEN, (DimensionedDataSource<U>)ds);
fullList.add(tuple);
}
for (DimensionedDataSource<?> ds : this.dbls) {
Tuple2<T, DimensionedDataSource<U>> tuple =
new Tuple2<T, DimensionedDataSource<U>>((T)G.DBL, (DimensionedDataSource<U>)ds);
fullList.add(tuple);
}
for (DimensionedDataSource<?> ds : this.dbl_vecs) {
Tuple2<T, DimensionedDataSource<U>> tuple =
new Tuple2<T, DimensionedDataSource<U>>((T)G.DBL_VEC, (DimensionedDataSource<U>)ds);
fullList.add(tuple);
}
for (DimensionedDataSource<?> ds : this.dbl_mats) {
Tuple2<T, DimensionedDataSource<U>> tuple =
new Tuple2<T, DimensionedDataSource<U>>((T)G.DBL_MAT, (DimensionedDataSource<U>)ds);
fullList.add(tuple);
}
for (DimensionedDataSource<?> ds : this.dbl_tens) {
Tuple2<T, DimensionedDataSource<U>> tuple =
new Tuple2<T, DimensionedDataSource<U>>((T)G.DBL_TEN, (DimensionedDataSource<U>)ds);
fullList.add(tuple);
}
for (DimensionedDataSource<?> ds : this.flts) {
Tuple2<T, DimensionedDataSource<U>> tuple =
new Tuple2<T, DimensionedDataSource<U>>((T)G.FLT, (DimensionedDataSource<U>)ds);
fullList.add(tuple);
}
for (DimensionedDataSource<?> ds : this.flt_vecs) {
Tuple2<T, DimensionedDataSource<U>> tuple =
new Tuple2<T, DimensionedDataSource<U>>((T)G.FLT_VEC, (DimensionedDataSource<U>)ds);
fullList.add(tuple);
}
for (DimensionedDataSource<?> ds : this.flt_mats) {
Tuple2<T, DimensionedDataSource<U>> tuple =
new Tuple2<T, DimensionedDataSource<U>>((T)G.FLT_MAT, (DimensionedDataSource<U>)ds);
fullList.add(tuple);
}
for (DimensionedDataSource<?> ds : this.flt_tens) {
Tuple2<T, DimensionedDataSource<U>> tuple =
new Tuple2<T, DimensionedDataSource<U>>((T)G.FLT_TEN, (DimensionedDataSource<U>)ds);
fullList.add(tuple);
}
for (DimensionedDataSource<?> ds : this.fstrs) {
Tuple2<T, DimensionedDataSource<U>> tuple =
new Tuple2<T, DimensionedDataSource<U>>((T)G.FSTRING, (DimensionedDataSource<U>)ds);
fullList.add(tuple);
}
for (DimensionedDataSource<?> ds : this.strs) {
Tuple2<T, DimensionedDataSource<U>> tuple =
new Tuple2<T, DimensionedDataSource<U>>((T)G.STRING, (DimensionedDataSource<U>)ds);
fullList.add(tuple);
}
for (DimensionedDataSource<?> ds : this.hlfs) {
Tuple2<T, DimensionedDataSource<U>> tuple =
new Tuple2<T, DimensionedDataSource<U>>((T)G.HLF, (DimensionedDataSource<U>)ds);
fullList.add(tuple);
}
for (DimensionedDataSource<?> ds : this.hlf_vecs) {
Tuple2<T, DimensionedDataSource<U>> tuple =
new Tuple2<T, DimensionedDataSource<U>>((T)G.HLF_VEC, (DimensionedDataSource<U>)ds);
fullList.add(tuple);
}
for (DimensionedDataSource<?> ds : this.hlf_mats) {
Tuple2<T, DimensionedDataSource<U>> tuple =
new Tuple2<T, DimensionedDataSource<U>>((T)G.HLF_MAT, (DimensionedDataSource<U>)ds);
fullList.add(tuple);
}
for (DimensionedDataSource<?> ds : this.hlf_tens) {
Tuple2<T, DimensionedDataSource<U>> tuple =
new Tuple2<T, DimensionedDataSource<U>>((T)G.HLF_TEN, (DimensionedDataSource<U>)ds);
fullList.add(tuple);
}
for (DimensionedDataSource<?> ds : this.hps) {
Tuple2<T, DimensionedDataSource<U>> tuple =
new Tuple2<T, DimensionedDataSource<U>>((T)G.HP, (DimensionedDataSource<U>)ds);
fullList.add(tuple);
}
for (DimensionedDataSource<?> ds : this.hp_vecs) {
Tuple2<T, DimensionedDataSource<U>> tuple =
new Tuple2<T, DimensionedDataSource<U>>((T)G.HP_VEC, (DimensionedDataSource<U>)ds);
fullList.add(tuple);
}
for (DimensionedDataSource<?> ds : this.hp_mats) {
Tuple2<T, DimensionedDataSource<U>> tuple =
new Tuple2<T, DimensionedDataSource<U>>((T)G.HP_MAT, (DimensionedDataSource<U>)ds);
fullList.add(tuple);
}
for (DimensionedDataSource<?> ds : this.hp_tens) {
Tuple2<T, DimensionedDataSource<U>> tuple =
new Tuple2<T, DimensionedDataSource<U>>((T)G.HP_TEN, (DimensionedDataSource<U>)ds);
fullList.add(tuple);
}
for (DimensionedDataSource<?> ds : this.int1s) {
Tuple2<T, DimensionedDataSource<U>> tuple =
new Tuple2<T, DimensionedDataSource<U>>((T)G.INT1, (DimensionedDataSource<U>)ds);
fullList.add(tuple);
}
for (DimensionedDataSource<?> ds : this.int2s) {
Tuple2<T, DimensionedDataSource<U>> tuple =
new Tuple2<T, DimensionedDataSource<U>>((T)G.INT2, (DimensionedDataSource<U>)ds);
fullList.add(tuple);
}
for (DimensionedDataSource<?> ds : this.int3s) {
Tuple2<T, DimensionedDataSource<U>> tuple =
new Tuple2<T, DimensionedDataSource<U>>((T)G.INT3, (DimensionedDataSource<U>)ds);
fullList.add(tuple);
}
for (DimensionedDataSource<?> ds : this.int4s) {
Tuple2<T, DimensionedDataSource<U>> tuple =
new Tuple2<T, DimensionedDataSource<U>>((T)G.INT4, (DimensionedDataSource<U>)ds);
fullList.add(tuple);
}
for (DimensionedDataSource<?> ds : this.int5s) {
Tuple2<T, DimensionedDataSource<U>> tuple =
new Tuple2<T, DimensionedDataSource<U>>((T)G.INT5, (DimensionedDataSource<U>)ds);
fullList.add(tuple);
}
for (DimensionedDataSource<?> ds : this.int6s) {
Tuple2<T, DimensionedDataSource<U>> tuple =
new Tuple2<T, DimensionedDataSource<U>>((T)G.INT6, (DimensionedDataSource<U>)ds);
fullList.add(tuple);
}
for (DimensionedDataSource<?> ds : this.int7s) {
Tuple2<T, DimensionedDataSource<U>> tuple =
new Tuple2<T, DimensionedDataSource<U>>((T)G.INT7, (DimensionedDataSource<U>)ds);
fullList.add(tuple);
}
for (DimensionedDataSource<?> ds : this.int8s) {
Tuple2<T, DimensionedDataSource<U>> tuple =
new Tuple2<T, DimensionedDataSource<U>>((T)G.INT8, (DimensionedDataSource<U>)ds);
fullList.add(tuple);
}
for (DimensionedDataSource<?> ds : this.int9s) {
Tuple2<T, DimensionedDataSource<U>> tuple =
new Tuple2<T, DimensionedDataSource<U>>((T)G.INT9, (DimensionedDataSource<U>)ds);
fullList.add(tuple);
}
for (DimensionedDataSource<?> ds : this.int10s) {
Tuple2<T, DimensionedDataSource<U>> tuple =
new Tuple2<T, DimensionedDataSource<U>>((T)G.INT10, (DimensionedDataSource<U>)ds);
fullList.add(tuple);
}
for (DimensionedDataSource<?> ds : this.int11s) {
Tuple2<T, DimensionedDataSource<U>> tuple =
new Tuple2<T, DimensionedDataSource<U>>((T)G.INT11, (DimensionedDataSource<U>)ds);
fullList.add(tuple);
}
for (DimensionedDataSource<?> ds : this.int12s) {
Tuple2<T, DimensionedDataSource<U>> tuple =
new Tuple2<T, DimensionedDataSource<U>>((T)G.INT12, (DimensionedDataSource<U>)ds);
fullList.add(tuple);
}
for (DimensionedDataSource<?> ds : this.int13s) {
Tuple2<T, DimensionedDataSource<U>> tuple =
new Tuple2<T, DimensionedDataSource<U>>((T)G.INT13, (DimensionedDataSource<U>)ds);
fullList.add(tuple);
}
for (DimensionedDataSource<?> ds : this.int14s) {
Tuple2<T, DimensionedDataSource<U>> tuple =
new Tuple2<T, DimensionedDataSource<U>>((T)G.INT14, (DimensionedDataSource<U>)ds);
fullList.add(tuple);
}
for (DimensionedDataSource<?> ds : this.int15s) {
Tuple2<T, DimensionedDataSource<U>> tuple =
new Tuple2<T, DimensionedDataSource<U>>((T)G.INT15, (DimensionedDataSource<U>)ds);
fullList.add(tuple);
}
for (DimensionedDataSource<?> ds : this.int16s) {
Tuple2<T, DimensionedDataSource<U>> tuple =
new Tuple2<T, DimensionedDataSource<U>>((T)G.INT16, (DimensionedDataSource<U>)ds);
fullList.add(tuple);
}
for (DimensionedDataSource<?> ds : this.int32s) {
Tuple2<T, DimensionedDataSource<U>> tuple =
new Tuple2<T, DimensionedDataSource<U>>((T)G.INT32, (DimensionedDataSource<U>)ds);
fullList.add(tuple);
}
for (DimensionedDataSource<?> ds : this.int64s) {
Tuple2<T, DimensionedDataSource<U>> tuple =
new Tuple2<T, DimensionedDataSource<U>>((T)G.INT64, (DimensionedDataSource<U>)ds);
fullList.add(tuple);
}
for (DimensionedDataSource<?> ds : this.int128s) {
Tuple2<T, DimensionedDataSource<U>> tuple =
new Tuple2<T, DimensionedDataSource<U>>((T)G.INT128, (DimensionedDataSource<U>)ds);
fullList.add(tuple);
}
for (DimensionedDataSource<?> ds : this.odbls) {
Tuple2<T, DimensionedDataSource<U>> tuple =
new Tuple2<T, DimensionedDataSource<U>>((T)G.ODBL, (DimensionedDataSource<U>)ds);
fullList.add(tuple);
}
for (DimensionedDataSource<?> ds : this.odbl_rmods) {
Tuple2<T, DimensionedDataSource<U>> tuple =
new Tuple2<T, DimensionedDataSource<U>>((T)G.ODBL_RMOD, (DimensionedDataSource<U>)ds);
fullList.add(tuple);
}
for (DimensionedDataSource<?> ds : this.odbl_mats) {
Tuple2<T, DimensionedDataSource<U>> tuple =
new Tuple2<T, DimensionedDataSource<U>>((T)G.ODBL_MAT, (DimensionedDataSource<U>)ds);
fullList.add(tuple);
}
for (DimensionedDataSource<?> ds : this.odbl_tens) {
Tuple2<T, DimensionedDataSource<U>> tuple =
new Tuple2<T, DimensionedDataSource<U>>((T)G.ODBL_TEN, (DimensionedDataSource<U>)ds);
fullList.add(tuple);
}
for (DimensionedDataSource<?> ds : this.oflts) {
Tuple2<T, DimensionedDataSource<U>> tuple =
new Tuple2<T, DimensionedDataSource<U>>((T)G.OFLT, (DimensionedDataSource<U>)ds);
fullList.add(tuple);
}
for (DimensionedDataSource<?> ds : this.oflt_rmods) {
Tuple2<T, DimensionedDataSource<U>> tuple =
new Tuple2<T, DimensionedDataSource<U>>((T)G.OFLT_RMOD, (DimensionedDataSource<U>)ds);
fullList.add(tuple);
}
for (DimensionedDataSource<?> ds : this.oflt_mats) {
Tuple2<T, DimensionedDataSource<U>> tuple =
new Tuple2<T, DimensionedDataSource<U>>((T)G.OFLT_MAT, (DimensionedDataSource<U>)ds);
fullList.add(tuple);
}
for (DimensionedDataSource<?> ds : this.oflt_tens) {
Tuple2<T, DimensionedDataSource<U>> tuple =
new Tuple2<T, DimensionedDataSource<U>>((T)G.OFLT_TEN, (DimensionedDataSource<U>)ds);
fullList.add(tuple);
}
for (DimensionedDataSource<?> ds : this.ohlfs) {
Tuple2<T, DimensionedDataSource<U>> tuple =
new Tuple2<T, DimensionedDataSource<U>>((T)G.OHLF, (DimensionedDataSource<U>)ds);
fullList.add(tuple);
}
for (DimensionedDataSource<?> ds : this.ohlf_rmods) {
Tuple2<T, DimensionedDataSource<U>> tuple =
new Tuple2<T, DimensionedDataSource<U>>((T)G.OHLF_RMOD, (DimensionedDataSource<U>)ds);
fullList.add(tuple);
}
for (DimensionedDataSource<?> ds : this.ohlf_mats) {
Tuple2<T, DimensionedDataSource<U>> tuple =
new Tuple2<T, DimensionedDataSource<U>>((T)G.OHLF_MAT, (DimensionedDataSource<U>)ds);
fullList.add(tuple);
}
for (DimensionedDataSource<?> ds : this.ohlf_tens) {
Tuple2<T, DimensionedDataSource<U>> tuple =
new Tuple2<T, DimensionedDataSource<U>>((T)G.OHLF_TEN, (DimensionedDataSource<U>)ds);
fullList.add(tuple);
}
for (DimensionedDataSource<?> ds : this.ohps) {
Tuple2<T, DimensionedDataSource<U>> tuple =
new Tuple2<T, DimensionedDataSource<U>>((T)G.OHP, (DimensionedDataSource<U>)ds);
fullList.add(tuple);
}
for (DimensionedDataSource<?> ds : this.ohp_rmods) {
Tuple2<T, DimensionedDataSource<U>> tuple =
new Tuple2<T, DimensionedDataSource<U>>((T)G.OHP_RMOD, (DimensionedDataSource<U>)ds);
fullList.add(tuple);
}
for (DimensionedDataSource<?> ds : this.ohp_mats) {
Tuple2<T, DimensionedDataSource<U>> tuple =
new Tuple2<T, DimensionedDataSource<U>>((T)G.OHP_MAT, (DimensionedDataSource<U>)ds);
fullList.add(tuple);
}
for (DimensionedDataSource<?> ds : this.ohp_tens) {
Tuple2<T, DimensionedDataSource<U>> tuple =
new Tuple2<T, DimensionedDataSource<U>>((T)G.OHP_TEN, (DimensionedDataSource<U>)ds);
fullList.add(tuple);
}
for (DimensionedDataSource<?> ds : this.points) {
Tuple2<T, DimensionedDataSource<U>> tuple =
new Tuple2<T, DimensionedDataSource<U>>((T)G.POINT, (DimensionedDataSource<U>)ds);
fullList.add(tuple);
}
for (DimensionedDataSource<?> ds : this.qdbls) {
Tuple2<T, DimensionedDataSource<U>> tuple =
new Tuple2<T, DimensionedDataSource<U>>((T)G.QDBL, (DimensionedDataSource<U>)ds);
fullList.add(tuple);
}
for (DimensionedDataSource<?> ds : this.qdbl_rmods) {
Tuple2<T, DimensionedDataSource<U>> tuple =
new Tuple2<T, DimensionedDataSource<U>>((T)G.QDBL_RMOD, (DimensionedDataSource<U>)ds);
fullList.add(tuple);
}
for (DimensionedDataSource<?> ds : this.qdbl_mats) {
Tuple2<T, DimensionedDataSource<U>> tuple =
new Tuple2<T, DimensionedDataSource<U>>((T)G.QDBL_MAT, (DimensionedDataSource<U>)ds);
fullList.add(tuple);
}
for (DimensionedDataSource<?> ds : this.qdbl_tens) {
Tuple2<T, DimensionedDataSource<U>> tuple =
new Tuple2<T, DimensionedDataSource<U>>((T)G.QDBL_TEN, (DimensionedDataSource<U>)ds);
fullList.add(tuple);
}
for (DimensionedDataSource<?> ds : this.qflts) {
Tuple2<T, DimensionedDataSource<U>> tuple =
new Tuple2<T, DimensionedDataSource<U>>((T)G.QFLT, (DimensionedDataSource<U>)ds);
fullList.add(tuple);
}
for (DimensionedDataSource<?> ds : this.qflt_rmods) {
Tuple2<T, DimensionedDataSource<U>> tuple =
new Tuple2<T, DimensionedDataSource<U>>((T)G.QFLT_RMOD, (DimensionedDataSource<U>)ds);
fullList.add(tuple);
}
for (DimensionedDataSource<?> ds : this.qflt_mats) {
Tuple2<T, DimensionedDataSource<U>> tuple =
new Tuple2<T, DimensionedDataSource<U>>((T)G.QFLT_MAT, (DimensionedDataSource<U>)ds);
fullList.add(tuple);
}
for (DimensionedDataSource<?> ds : this.qflt_tens) {
Tuple2<T, DimensionedDataSource<U>> tuple =
new Tuple2<T, DimensionedDataSource<U>>((T)G.QFLT_TEN, (DimensionedDataSource<U>)ds);
fullList.add(tuple);
}
for (DimensionedDataSource<?> ds : this.qhlfs) {
Tuple2<T, DimensionedDataSource<U>> tuple =
new Tuple2<T, DimensionedDataSource<U>>((T)G.QHLF, (DimensionedDataSource<U>)ds);
fullList.add(tuple);
}
for (DimensionedDataSource<?> ds : this.qhlf_rmods) {
Tuple2<T, DimensionedDataSource<U>> tuple =
new Tuple2<T, DimensionedDataSource<U>>((T)G.QHLF_RMOD, (DimensionedDataSource<U>)ds);
fullList.add(tuple);
}
for (DimensionedDataSource<?> ds : this.qhlf_mats) {
Tuple2<T, DimensionedDataSource<U>> tuple =
new Tuple2<T, DimensionedDataSource<U>>((T)G.QHLF_MAT, (DimensionedDataSource<U>)ds);
fullList.add(tuple);
}
for (DimensionedDataSource<?> ds : this.qhlf_tens) {
Tuple2<T, DimensionedDataSource<U>> tuple =
new Tuple2<T, DimensionedDataSource<U>>((T)G.QHLF_TEN, (DimensionedDataSource<U>)ds);
fullList.add(tuple);
}
for (DimensionedDataSource<?> ds : this.qhps) {
Tuple2<T, DimensionedDataSource<U>> tuple =
new Tuple2<T, DimensionedDataSource<U>>((T)G.QHP, (DimensionedDataSource<U>)ds);
fullList.add(tuple);
}
for (DimensionedDataSource<?> ds : this.qhp_rmods) {
Tuple2<T, DimensionedDataSource<U>> tuple =
new Tuple2<T, DimensionedDataSource<U>>((T)G.QHP_RMOD, (DimensionedDataSource<U>)ds);
fullList.add(tuple);
}
for (DimensionedDataSource<?> ds : this.qhp_mats) {
Tuple2<T, DimensionedDataSource<U>> tuple =
new Tuple2<T, DimensionedDataSource<U>>((T)G.QHP_MAT, (DimensionedDataSource<U>)ds);
fullList.add(tuple);
}
for (DimensionedDataSource<?> ds : this.qhp_tens) {
Tuple2<T, DimensionedDataSource<U>> tuple =
new Tuple2<T, DimensionedDataSource<U>>((T)G.QHP_TEN, (DimensionedDataSource<U>)ds);
fullList.add(tuple);
}
for (DimensionedDataSource<?> ds : this.rationals) {
Tuple2<T, DimensionedDataSource<U>> tuple =
new Tuple2<T, DimensionedDataSource<U>>((T)G.RAT, (DimensionedDataSource<U>)ds);
fullList.add(tuple);
}
for (DimensionedDataSource<?> ds : this.rgbs) {
Tuple2<T, DimensionedDataSource<U>> tuple =
new Tuple2<T, DimensionedDataSource<U>>((T)G.RGB, (DimensionedDataSource<U>)ds);
fullList.add(tuple);
}
for (DimensionedDataSource<?> ds : this.uint1s) {
Tuple2<T, DimensionedDataSource<U>> tuple =
new Tuple2<T, DimensionedDataSource<U>>((T)G.UINT1, (DimensionedDataSource<U>)ds);
fullList.add(tuple);
}
for (DimensionedDataSource<?> ds : this.uint2s) {
Tuple2<T, DimensionedDataSource<U>> tuple =
new Tuple2<T, DimensionedDataSource<U>>((T)G.UINT2, (DimensionedDataSource<U>)ds);
fullList.add(tuple);
}
for (DimensionedDataSource<?> ds : this.uint3s) {
Tuple2<T, DimensionedDataSource<U>> tuple =
new Tuple2<T, DimensionedDataSource<U>>((T)G.UINT3, (DimensionedDataSource<U>)ds);
fullList.add(tuple);
}
for (DimensionedDataSource<?> ds : this.uint4s) {
Tuple2<T, DimensionedDataSource<U>> tuple =
new Tuple2<T, DimensionedDataSource<U>>((T)G.UINT4, (DimensionedDataSource<U>)ds);
fullList.add(tuple);
}
for (DimensionedDataSource<?> ds : this.uint5s) {
Tuple2<T, DimensionedDataSource<U>> tuple =
new Tuple2<T, DimensionedDataSource<U>>((T)G.UINT5, (DimensionedDataSource<U>)ds);
fullList.add(tuple);
}
for (DimensionedDataSource<?> ds : this.uint6s) {
Tuple2<T, DimensionedDataSource<U>> tuple =
new Tuple2<T, DimensionedDataSource<U>>((T)G.UINT6, (DimensionedDataSource<U>)ds);
fullList.add(tuple);
}
for (DimensionedDataSource<?> ds : this.uint7s) {
Tuple2<T, DimensionedDataSource<U>> tuple =
new Tuple2<T, DimensionedDataSource<U>>((T)G.UINT7, (DimensionedDataSource<U>)ds);
fullList.add(tuple);
}
for (DimensionedDataSource<?> ds : this.uint8s) {
Tuple2<T, DimensionedDataSource<U>> tuple =
new Tuple2<T, DimensionedDataSource<U>>((T)G.UINT8, (DimensionedDataSource<U>)ds);
fullList.add(tuple);
}
for (DimensionedDataSource<?> ds : this.uint9s) {
Tuple2<T, DimensionedDataSource<U>> tuple =
new Tuple2<T, DimensionedDataSource<U>>((T)G.UINT9, (DimensionedDataSource<U>)ds);
fullList.add(tuple);
}
for (DimensionedDataSource<?> ds : this.uint10s) {
Tuple2<T, DimensionedDataSource<U>> tuple =
new Tuple2<T, DimensionedDataSource<U>>((T)G.UINT10, (DimensionedDataSource<U>)ds);
fullList.add(tuple);
}
for (DimensionedDataSource<?> ds : this.uint11s) {
Tuple2<T, DimensionedDataSource<U>> tuple =
new Tuple2<T, DimensionedDataSource<U>>((T)G.UINT11, (DimensionedDataSource<U>)ds);
fullList.add(tuple);
}
for (DimensionedDataSource<?> ds : this.uint12s) {
Tuple2<T, DimensionedDataSource<U>> tuple =
new Tuple2<T, DimensionedDataSource<U>>((T)G.UINT12, (DimensionedDataSource<U>)ds);
fullList.add(tuple);
}
for (DimensionedDataSource<?> ds : this.uint13s) {
Tuple2<T, DimensionedDataSource<U>> tuple =
new Tuple2<T, DimensionedDataSource<U>>((T)G.UINT13, (DimensionedDataSource<U>)ds);
fullList.add(tuple);
}
for (DimensionedDataSource<?> ds : this.uint14s) {
Tuple2<T, DimensionedDataSource<U>> tuple =
new Tuple2<T, DimensionedDataSource<U>>((T)G.UINT14, (DimensionedDataSource<U>)ds);
fullList.add(tuple);
}
for (DimensionedDataSource<?> ds : this.uint15s) {
Tuple2<T, DimensionedDataSource<U>> tuple =
new Tuple2<T, DimensionedDataSource<U>>((T)G.UINT15, (DimensionedDataSource<U>)ds);
fullList.add(tuple);
}
for (DimensionedDataSource<?> ds : this.uint16s) {
Tuple2<T, DimensionedDataSource<U>> tuple =
new Tuple2<T, DimensionedDataSource<U>>((T)G.UINT16, (DimensionedDataSource<U>)ds);
fullList.add(tuple);
}
for (DimensionedDataSource<?> ds : this.uint32s) {
Tuple2<T, DimensionedDataSource<U>> tuple =
new Tuple2<T, DimensionedDataSource<U>>((T)G.UINT32, (DimensionedDataSource<U>)ds);
fullList.add(tuple);
}
for (DimensionedDataSource<?> ds : this.uint64s) {
Tuple2<T, DimensionedDataSource<U>> tuple =
new Tuple2<T, DimensionedDataSource<U>>((T)G.UINT64, (DimensionedDataSource<U>)ds);
fullList.add(tuple);
}
for (DimensionedDataSource<?> ds : this.uint128s) {
Tuple2<T, DimensionedDataSource<U>> tuple =
new Tuple2<T, DimensionedDataSource<U>>((T)G.UINT128, (DimensionedDataSource<U>)ds);
fullList.add(tuple);
}
for (DimensionedDataSource<?> ds : this.unbounds) {
Tuple2<T, DimensionedDataSource<U>> tuple =
new Tuple2<T, DimensionedDataSource<U>>((T)G.UNBOUND, (DimensionedDataSource<U>)ds);
fullList.add(tuple);
}
return fullList;
}
}
|
package nuclibook.entity_utils;
import com.j256.ormlite.support.ConnectionSource;
import nuclibook.constants.P;
import nuclibook.models.CannotHashPasswordException;
import nuclibook.models.Staff;
import nuclibook.server.SqlServerConnection;
import spark.Response;
import spark.Session;
public class SecurityUtils {
private SecurityUtils() {
// prevent instantiation
}
private static void setUser(Session session, Staff user) {
session.attribute("user", user);
}
private static Staff getUser(Session session) {
return session.attribute("user");
}
public static Staff attemptLogin(Session session, String username, String password) {
// set up server connection
ConnectionSource conn = SqlServerConnection.acquireConnection();
if (conn != null) {
try {
// search for user
Staff staff = StaffUtils.getStaffByUsername(username);
if (staff != null) {
// check their password
if (staff.checkPassword(password)) {
// correct login!
setUser(session, staff);
return staff;
}
}
} catch (CannotHashPasswordException e) {
// fail
}
}
return null;
}
public static boolean checkLoggedIn(Session session) {
return getUser(session) != null;
}
public static void destroyLogin(Session session) {
setUser(session, null);
}
public static Staff getCurrentUser(Session session) {
return getUser(session);
}
public static boolean requirePermission(Session session, P p, Response response) {
if (getUser(session) == null || !getUser(session).hasPermission(p)) {
try {
response.redirect("/access-denied");
} catch (IllegalStateException e) {
// already redirecting
}
return false;
}
return true;
}
public static String validateNewPassword(Staff staff, String password) throws CannotHashPasswordException {
if (password.length() < 6) {
return "Password must be at least 6 characters long.";
} else if (staff.isInLastPasswords(password)) {
return "Password must not be the same as the last few passwords.";
}
return null;
}
}
|
package nuclibook.server;
import com.j256.ormlite.jdbc.JdbcConnectionSource;
import com.j256.ormlite.support.ConnectionSource;
import com.j256.ormlite.table.TableUtils;
import nuclibook.constants.C;
import nuclibook.models.*;
import java.sql.SQLException;
/**
* This singleton class initialises and manages the SQL connection
*/
public class SqlServerConnection {
/**
* Private constructor to enforce the singleton pattern
*/
private SqlServerConnection() {
}
private static ConnectionSource connection = null;
/**
* Acquires the single instance of the SQL connection.
* @return The SQL connection source
*/
public static ConnectionSource acquireConnection() {
return acquireConnection(C.MYSQL_URI, C.MYSQL_USERNAME, C.MYSQL_PASSWORD);
}
/**
* Acquires or creates the single instance of the SQL connection
* @param uri The DB URI
* @param username The DB username
* @param password The DB password
* @return The SQL connection source
*/
public static ConnectionSource acquireConnection(String uri, String username, String password) {
if (connection == null) {
try {
connection = new JdbcConnectionSource(uri);
((JdbcConnectionSource) connection).setUsername(username);
((JdbcConnectionSource) connection).setPassword(password);
initDB(connection);
} catch (Exception e) {
e.printStackTrace();
}
}
return connection;
}
/**
* Creates all tables (if needed)
* @param connection The connection source, linked to the DB to be used.
*/
public static void initDB(ConnectionSource connection) {
try {
TableUtils.createTableIfNotExists(connection, ActionLog.class);
TableUtils.createTableIfNotExists(connection, ActionLogEvent.class);
TableUtils.createTableIfNotExists(connection, Booking.class);
TableUtils.createTableIfNotExists(connection, BookingPatternSection.class);
TableUtils.createTableIfNotExists(connection, BookingSection.class);
TableUtils.createTableIfNotExists(connection, BookingStaff.class);
TableUtils.createTableIfNotExists(connection, Camera.class);
TableUtils.createTableIfNotExists(connection, CameraType.class);
TableUtils.createTableIfNotExists(connection, GenericEvent.class);
TableUtils.createTableIfNotExists(connection, Patient.class);
TableUtils.createTableIfNotExists(connection, PatientQuestion.class);
TableUtils.createTableIfNotExists(connection, Permission.class);
TableUtils.createTableIfNotExists(connection, Staff.class);
TableUtils.createTableIfNotExists(connection, StaffAbsence.class);
TableUtils.createTableIfNotExists(connection, StaffAvailability.class);
TableUtils.createTableIfNotExists(connection, StaffRole.class);
TableUtils.createTableIfNotExists(connection, StaffRolePermission.class);
TableUtils.createTableIfNotExists(connection, Therapy.class);
TableUtils.createTableIfNotExists(connection, TherapyCameraType.class);
TableUtils.createTableIfNotExists(connection, Tracer.class);
TableUtils.createTableIfNotExists(connection, TracerOrder.class);
} catch (SQLException e) {
// TODO deal with exception
e.printStackTrace();
}
}
}
|
package openmods.tileentity;
import com.google.common.collect.Sets;
import java.util.Set;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.math.BlockPos;
import openmods.network.rpc.IRpcTarget;
import openmods.network.rpc.RpcCallDispatcher;
import openmods.network.rpc.targets.SyncRpcTarget;
import openmods.network.senders.IPacketSender;
import openmods.reflection.TypeUtils;
import openmods.sync.ISyncListener;
import openmods.sync.ISyncMapProvider;
import openmods.sync.ISyncableObject;
import openmods.sync.SyncMap;
import openmods.sync.SyncMapTile;
import openmods.sync.SyncObjectScanner;
import openmods.sync.drops.DropTagSerializer;
public abstract class SyncedTileEntity extends OpenTileEntity implements ISyncMapProvider {
protected SyncMapTile<SyncedTileEntity> syncMap;
private DropTagSerializer tagSerializer;
public SyncedTileEntity() {
syncMap = new SyncMapTile<SyncedTileEntity>(this);
createSyncedFields();
SyncObjectScanner.INSTANCE.registerAllFields(syncMap, this);
syncMap.addSyncListener(new ISyncListener() {
@Override
public void onSync(Set<ISyncableObject> changes) {
markUpdated();
}
});
}
protected DropTagSerializer getDropSerializer() {
if (tagSerializer == null) tagSerializer = new DropTagSerializer();
return tagSerializer;
}
protected ISyncListener createRenderUpdateListener() {
return new ISyncListener() {
@Override
public void onSync(Set<ISyncableObject> changes) {
markBlockForRenderUpdate(getPos());
}
};
}
protected ISyncListener createRenderUpdateListener(final ISyncableObject target) {
return new ISyncListener() {
@Override
public void onSync(Set<ISyncableObject> changes) {
if (changes.contains(target)) markBlockForRenderUpdate(getPos());
}
};
}
protected ISyncListener createRenderUpdateListener(final Set<ISyncableObject> targets) {
return new ISyncListener() {
@Override
public void onSync(Set<ISyncableObject> changes) {
if (!Sets.intersection(changes, targets).isEmpty()) markBlockForRenderUpdate(getPos());
}
};
}
protected void markBlockForRenderUpdate(BlockPos pos) {
worldObj.markBlockRangeForRenderUpdate(pos, pos);
}
protected abstract void createSyncedFields();
public void addSyncedObject(String name, ISyncableObject obj) {
syncMap.put(name, obj);
}
public void sync() {
syncMap.sync();
}
@Override
public SyncMap<SyncedTileEntity> getSyncMap() {
return syncMap;
}
// TODO verify if initial NBT send is enough
@Override
public NBTTagCompound writeToNBT(NBTTagCompound tag) {
super.writeToNBT(tag);
syncMap.writeToNBT(tag);
return tag;
}
@Override
public void readFromNBT(NBTTagCompound tag) {
super.readFromNBT(tag);
syncMap.readFromNBT(tag);
}
public <T> T createRpcProxy(ISyncableObject object, Class<? extends T> mainIntf, Class<?>... extraIntf) {
TypeUtils.isInstance(object, mainIntf, extraIntf);
IRpcTarget target = new SyncRpcTarget.SyncTileEntityRpcTarget(this, object);
final IPacketSender sender = RpcCallDispatcher.INSTANCE.senders.client;
return RpcCallDispatcher.INSTANCE.createProxy(target, sender, mainIntf, extraIntf);
}
}
|
package org.aeonbits.owner;
import org.aeonbits.owner.event.ReloadEvent;
import org.aeonbits.owner.event.ReloadListener;
import org.aeonbits.owner.event.RollbackException;
import org.aeonbits.owner.event.TransactionalPropertyChangeListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.io.Reader;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock.ReadLock;
import java.util.concurrent.locks.ReentrantReadWriteLock.WriteLock;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import static java.util.Collections.synchronizedList;
import static org.aeonbits.owner.Config.LoadType.FIRST;
import static org.aeonbits.owner.PropertiesMapper.defaults;
import static org.aeonbits.owner.Util.asString;
import static org.aeonbits.owner.Util.ignore;
import static org.aeonbits.owner.Util.reverse;
import static org.aeonbits.owner.Util.unsupported;
/**
* Loads properties and manages access to properties handling concurrency.
*
* @author Luigi R. Viggiano
*/
class PropertiesManager implements Reloadable, Accessible, Mutable {
private final Class<? extends Config> clazz;
private final Map<?, ?>[] imports;
private final Properties properties;
private final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
private final ReadLock readLock = lock.readLock();
private final WriteLock writeLock = lock.writeLock();
private final LoadType loadType;
private final List<URL> urls;
private final ConfigURLFactory urlFactory;
private HotReloadLogic hotReloadLogic = null;
private volatile boolean loading = false;
private final List<ReloadListener> reloadListeners = synchronizedList(new LinkedList<ReloadListener>());
private Object proxy;
private final LoadersManager loaders;
private List<PropertyChangeListener> propertyChangeListeners =
synchronizedList(new LinkedList<PropertyChangeListener>());
@Retention(RUNTIME)
@Target(METHOD)
@interface Delegate {
}
PropertiesManager(Class<? extends Config> clazz, Properties properties, ScheduledExecutorService scheduler,
VariablesExpander expander, LoadersManager loaders, Map<?, ?>... imports) {
this.clazz = clazz;
this.properties = properties;
this.loaders = loaders;
this.imports = imports;
urlFactory = new ConfigURLFactory(clazz.getClassLoader(), expander);
urls = toURLs(clazz.getAnnotation(Sources.class));
LoadPolicy loadPolicy = clazz.getAnnotation(LoadPolicy.class);
loadType = (loadPolicy != null) ? loadPolicy.value() : FIRST;
setupHotReload(clazz, scheduler);
}
private List<URL> toURLs(Sources sources) {
String[] specs = specs(sources);
ArrayList<URL> result = new ArrayList<URL>();
for (String spec : specs) {
try {
URL url = urlFactory.newURL(spec);
if (url != null)
result.add(url);
} catch (MalformedURLException e) {
throw unsupported(e, "Can't convert '%s' to a valid URL", spec);
}
}
return result;
}
private String[] specs(Sources sources) {
if (sources != null) return sources.value();
return defaultSpecs();
}
private String[] defaultSpecs() {
String prefix = urlFactory.toClasspathURLSpec(clazz.getName());
return new String[] {prefix + ".properties", prefix + ".xml"};
}
private void setupHotReload(Class<? extends Config> clazz, ScheduledExecutorService scheduler) {
HotReload hotReload = clazz.getAnnotation(HotReload.class);
if (hotReload != null) {
hotReloadLogic = new HotReloadLogic(hotReload, urls, this);
if (hotReloadLogic.isAsync())
scheduler.scheduleAtFixedRate(new Runnable() {
public void run() {
hotReloadLogic.checkAndReload();
}
}, hotReload.value(), hotReload.value(), hotReload.unit());
}
}
Properties load() {
writeLock.lock();
try {
loading = true;
defaults(properties, clazz);
Properties loadedFromFile = doLoad();
merge(properties, loadedFromFile);
merge(properties, reverse(imports));
return properties;
} finally {
loading = false;
writeLock.unlock();
}
}
@Delegate
public void reload() {
writeLock.lock();
try {
performClear();
load();
fireReloadEvent();
} finally {
writeLock.unlock();
}
}
private void fireReloadEvent() {
for (ReloadListener listener : reloadListeners)
listener.reloadPerformed(new ReloadEvent(proxy));
}
@Delegate
public void addReloadListener(ReloadListener listener) {
reloadListeners.add(listener);
}
@Delegate
public void removeReloadListener(ReloadListener listener) {
reloadListeners.remove(listener);
}
@Delegate
public void addPropertyChangeListener(PropertyChangeListener listener) {
propertyChangeListeners.add(listener);
}
public void removePropertyChangeListener(PropertyChangeListener listener) {
propertyChangeListeners.remove(listener);
}
Properties doLoad() {
return loadType.load(urls, loaders);
}
private static void merge(Properties results, Map<?, ?>... inputs) {
for (Map<?, ?> input : inputs)
results.putAll(input);
}
@Delegate
public String getProperty(String key) {
readLock.lock();
try {
return properties.getProperty(key);
} finally {
readLock.unlock();
}
}
void syncReloadCheck() {
if (hotReloadLogic != null && hotReloadLogic.isSync())
hotReloadLogic.checkAndReload();
}
@Delegate
public String getProperty(String key, String defaultValue) {
readLock.lock();
try {
return properties.getProperty(key, defaultValue);
} finally {
readLock.unlock();
}
}
@Delegate
public void storeToXML(OutputStream os, String comment) throws IOException {
readLock.lock();
try {
properties.storeToXML(os, comment);
} finally {
readLock.unlock();
}
}
@Delegate
public Set<String> propertyNames() {
readLock.lock();
try {
LinkedHashSet<String> result = new LinkedHashSet<String>();
for (Enumeration<?> propertyNames = properties.propertyNames(); propertyNames.hasMoreElements(); )
result.add((String) propertyNames.nextElement());
return result;
} finally {
readLock.unlock();
}
}
@Delegate
public void list(PrintStream out) {
readLock.lock();
try {
properties.list(out);
} finally {
readLock.unlock();
}
}
@Delegate
public void list(PrintWriter out) {
readLock.lock();
try {
properties.list(out);
} finally {
readLock.unlock();
}
}
@Delegate
public void store(OutputStream out, String comments) throws IOException {
readLock.lock();
try {
properties.store(out, comments);
} finally {
readLock.unlock();
}
}
@Delegate
public String setProperty(String key, String value) {
writeLock.lock();
try {
PropertyChangeEvent event = createPropertyChangeEvent(key, value);
try {
fireBeforePropertyChange(event);
if (value == null) return removeProperty(key);
String result = asString(properties.setProperty(key, value));
firePropertyChange(event);
return result;
} catch (RollbackException e) {
return properties.getProperty(key);
}
} finally {
writeLock.unlock();
}
}
private void firePropertyChange(PropertyChangeEvent event) {
for (PropertyChangeListener listener : propertyChangeListeners)
listener.propertyChange(event);
}
private void fireBeforePropertyChange(PropertyChangeEvent event) throws RollbackException {
for (PropertyChangeListener listener : propertyChangeListeners)
if (listener instanceof TransactionalPropertyChangeListener)
((TransactionalPropertyChangeListener) listener).beforePropertyChange(event);
}
private PropertyChangeEvent createPropertyChangeEvent(String propertyName, String newValue) {
String oldValue = properties.getProperty(propertyName);
return new PropertyChangeEvent(proxy, propertyName, oldValue, newValue);
}
@Delegate
public String removeProperty(String key) {
writeLock.lock();
try {
PropertyChangeEvent event = createPropertyChangeEvent(key, null);
try {
fireBeforePropertyChange(event);
String result = asString(properties.remove(key));
firePropertyChange(event);
return result;
} catch (RollbackException e) {
return properties.getProperty(key);
}
} finally {
writeLock.unlock();
}
}
@Delegate
public void clear() {
writeLock.lock();
try {
Set<Object> keys = properties.keySet();
List<PropertyChangeEvent> events = new ArrayList<PropertyChangeEvent>();
for (Object key : keys) {
PropertyChangeEvent event = createPropertyChangeEvent((String) key, null);
fireBeforePropertyChange(event);
events.add(event);
}
performClear();
for (PropertyChangeEvent event : events)
firePropertyChange(event);
} catch (RollbackException e) {
ignore();
} finally {
writeLock.unlock();
}
}
private void performClear() {
properties.clear();
}
@Delegate
public void load(InputStream inStream) throws IOException {
writeLock.lock();
try {
properties.load(inStream);
} finally {
writeLock.unlock();
}
}
@Delegate
public void load(Reader reader) throws IOException {
writeLock.lock();
try {
properties.load(reader);
} finally {
writeLock.unlock();
}
}
public void setProxy(Object proxy) {
if (this.proxy == null)
this.proxy = proxy;
}
@Delegate
@Override
public String toString() {
readLock.lock();
try {
return properties.toString();
} finally {
readLock.unlock();
}
}
boolean isLoading() {
return loading;
}
}
|
package org.animotron.manipulator;
import org.animotron.graph.index.Order;
import org.animotron.graph.index.State;
import org.animotron.io.PipedInput;
import org.animotron.marker.AbstractMarker;
import org.animotron.marker.Marker;
import org.animotron.statement.Statement;
import org.animotron.statement.Statements;
import org.animotron.statement.operator.AN;
import org.animotron.statement.operator.Prepare;
import org.animotron.statement.operator.REF;
import org.animotron.statement.operator.THE;
import org.animotron.statement.relation.USE;
import org.neo4j.graphdb.Node;
import org.neo4j.graphdb.Relationship;
import org.neo4j.graphdb.index.IndexHits;
import java.io.IOException;
import static org.neo4j.graphdb.Direction.*;
/**
* @author <a href="mailto:gazdovsky@gmail.com">Evgeny Gazdovsky</a>
*
*/
public class Preparator extends StatementManipulator {
public static Preparator _ = new Preparator();
private Preparator() {};
public PipedInput<QCAVector> execute(final Controller controller, final Node op) throws IOException {
for (Relationship r : op.getRelationships(INCOMING)) {
if (r.isType(AN._) || r.isType(USE._) || r.isType(REF._)) {
//XXX: rewrite super.execute(r);
}
}
//System.out.println("Preparator "+op);
IndexHits<Relationship> hits = Order.queryDown(op);
try {
for (Relationship r : hits) {
Statement s = Statements.relationshipType(r);
if (s instanceof AN) {
try {
Relationship ref = r.getEndNode().getSingleRelationship(REF._, OUTGOING);
String name = (String) THE._.reference(ref);
if (name != null) {
s = Statements.name(name);
if (canGo(s)) {
super.execute(controller, new QCAVector(r), onQuestion(s, r), true);
}
}
} catch (Exception e) {
//XXX: log
//e.printStackTrace();
}
} else if (canGo(s)) {
super.execute(controller, new QCAVector(r), onQuestion(s, r), false);
}
}
} finally {
hits.close();
}
return null;
}
@Override
public boolean canGo(Statement statement) {
return statement instanceof Prepare;
}
@Override
public OnQuestion onQuestion(Statement statement, Relationship op) {
return ((Prepare) statement).onPrepareQuestion();
}
@Override
public Marker marker() {
return PrepareMarker._;
}
private static class PrepareMarker extends AbstractMarker {
private static final Marker _ = new PrepareMarker();
private PrepareMarker() {super(State.PREPARE);}
@Override
public Manipulator manipulator() {
return Preparator._;
}
}
}
|
package org.basex.gui.dialog;
import static org.basex.core.Text.*;
import static org.basex.util.Token.*;
import java.awt.BorderLayout;
import java.awt.Component;
import javax.swing.AbstractButton;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.border.EmptyBorder;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeCellRenderer;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreePath;
import javax.swing.tree.TreeSelectionModel;
import org.basex.core.Text;
import org.basex.core.cmd.Delete;
import org.basex.core.cmd.Rename;
import org.basex.data.Data;
import org.basex.gui.GUI;
import org.basex.gui.GUICommand;
import org.basex.gui.GUIConstants.Fill;
import org.basex.gui.layout.BaseXBack;
import org.basex.gui.layout.BaseXButton;
import org.basex.gui.layout.BaseXLayout;
import org.basex.gui.layout.BaseXPopup;
import org.basex.gui.layout.BaseXTextField;
import org.basex.gui.layout.BaseXTree;
import org.basex.gui.layout.TreeFolder;
import org.basex.gui.layout.TreeLeaf;
import org.basex.gui.layout.TreeNode;
import org.basex.gui.layout.TreeRootFolder;
public class DialogResources extends BaseXBack {
/** Resource tree. */
final BaseXTree tree;
/** Search text field. */
final BaseXTextField filterText;
/** Database/root node. */
final TreeFolder root;
/** Dialog reference. */
final DialogProps dialog;
/** Filter button. */
private final BaseXButton filter;
/** Clear button. */
private final BaseXButton clear;
/**
* Constructor.
* @param d dialog reference
*/
public DialogResources(final DialogProps d) {
setLayout(new BorderLayout(0, 5));
dialog = d;
// init tree - additional root node necessary to bypass
// the egg/chicken dilemma
final DefaultMutableTreeNode rootNode = new DefaultMutableTreeNode();
tree = new BaseXTree(rootNode, d);
tree.setBorder(new EmptyBorder(4, 4, 4, 4));
tree.setRootVisible(false);
tree.getSelectionModel().setSelectionMode(
TreeSelectionModel.SINGLE_TREE_SELECTION);
final ImageIcon xml = BaseXLayout.icon("file_xml");
final ImageIcon raw = BaseXLayout.icon("file_raw");
tree.setCellRenderer(new TreeNodeRenderer(xml, raw));
tree.addTreeSelectionListener(new TreeSelectionListener() {
@Override
public void valueChanged(final TreeSelectionEvent e) {
TreeNode n = (TreeNode) e.getPath().getLastPathComponent();
String filt = n.equals(root) ? "" : n.path();
String trgt = filt + '/';
if(n.isLeaf()) {
n = (TreeNode) n.getParent();
trgt = (n == null || n.equals(root) ? "" : n.path()) + '/';
} else {
filt = trgt;
}
filterText.setText(filt);
dialog.add.target.setText(trgt);
}
});
// add default children to tree
final Data data = d.gui.context.data();
root = new TreeRootFolder(token(data.meta.name), token("/"), tree, data);
((DefaultTreeModel) tree.getModel()).insertNodeInto(root, rootNode, 0);
tree.expandPath(new TreePath(root.getPath()));
filter = new BaseXButton(BUTTONFILTER, d);
clear = new BaseXButton(BUTTONCLEAR, d);
// popup menu for node interaction
new BaseXPopup(tree, d.gui, new DeleteCmd(), new RenameCmd());
// button panel
final BaseXBack buttons = new BaseXBack(Fill.NONE);
buttons.add(filter);
buttons.add(clear);
final BaseXBack btn = new BaseXBack(Fill.NONE).layout(new BorderLayout());
btn.add(buttons, BorderLayout.EAST);
filterText = new BaseXTextField("", d.gui);
BaseXLayout.setWidth(filterText, 220);
// left panel
final BaseXBack panel = new BaseXBack(new BorderLayout());
panel.add(filterText, BorderLayout.CENTER);
panel.add(btn, BorderLayout.SOUTH);
add(new JScrollPane(tree), BorderLayout.CENTER);
add(panel, BorderLayout.SOUTH);
}
/**
* Returns the current tree node selection.
* @return selected node
*/
TreeNode selection() {
final TreePath t = tree.getSelectionPath();
return t == null ? null : (TreeNode) t.getLastPathComponent();
}
/**
* Searches the tree for nodes that match the given search text.
*/
void filter() {
final byte[] path = TreeNode.preparePath(token(filterText.getText()));
if(eq(path, SLASH)) {
refreshFolder(root);
return;
}
final Data data = dialog.gui.context.data();
// clear tree to append filtered nodes
root.removeAllChildren();
// check if there's a directory
// create a folder if there's either a raw or document folder
if(data.resources.isDir(path)) {
root.add(new TreeFolder(TreeFolder.name(path),
TreeFolder.path(path), tree, data));
}
// now add the actual files (if there are any)
final byte[] name = TreeFolder.name(path);
final byte[] sub = TreeFolder.path(path);
final TreeLeaf[] leaves = TreeFolder.leaves(
new TreeFolder(TreeFolder.name(sub), TreeFolder.path(sub), tree, data));
for(final TreeLeaf l : leaves) {
if(name.length == 0 || eq(l.name, name)) root.add(l);
}
((DefaultTreeModel) tree.getModel()).nodeStructureChanged(root);
}
/**
* Refreshes the given folder node. Removes all its children and reloads
* it afterwards.
* @param n folder
*/
void refreshFolder(final TreeFolder n) {
if(n == null) return;
n.removeChildren();
final TreePath path = new TreePath(n.getPath());
tree.collapsePath(path);
tree.expandPath(path);
}
/**
* Reacts on user input.
* @param comp the action component
*/
void action(final Object comp) {
if(comp == filter) {
filter();
} else if(comp != null) {
if(comp == clear) {
filterText.requestFocus();
refreshFolder(root);
}
}
}
/**
* Expands the tree after a node with the given path has been inserted.
* Due to lazy evaluation of the tree inserted documents/files are only
* added to the tree after the parent folder has been reloaded.
* @param p path of new node
*/
public void refreshNewFolder(final String p) {
final byte[][] pathComp = split(token(p), '/');
TreeNode n = root;
for(final byte[] c : pathComp) {
// make sure folder is reloaded
if(n instanceof TreeFolder)
((TreeFolder) n).reload();
// find next child to continue with
for(int i = 0; i < n.getChildCount(); i++) {
final TreeNode ch = (TreeNode) n.getChildAt(i);
if(eq(ch.name, c)) {
// continue with the child if path component matches
n = ch;
break;
}
}
}
refreshFolder(n instanceof TreeFolder ? (TreeFolder) n :
(TreeFolder) n.getParent());
}
private static final class TreeNodeRenderer extends DefaultTreeCellRenderer {
/** Icon for xml files. */
private final Icon xmlIcon;
/** Icon for raw files. */
private final Icon rawIcon;
/**
* Constructor.
* @param xml xml icon
* @param raw raw icon
*/
TreeNodeRenderer(final Icon xml, final Icon raw) {
xmlIcon = xml;
rawIcon = raw;
}
@Override
public Component getTreeCellRendererComponent(final JTree tree,
final Object val, final boolean sel, final boolean exp,
final boolean leaf, final int row, final boolean focus) {
super.getTreeCellRendererComponent(tree, val, sel, exp, leaf, row, focus);
if(leaf) setIcon(((TreeLeaf) val).raw ? rawIcon : xmlIcon);
return this;
}
}
/** GUI commands for popup menu. */
abstract class BaseCmd implements GUICommand {
@Override
public boolean checked() {
return false;
}
@Override
public String help() {
return null;
}
@Override
public String key() {
return null;
}
}
/** Delete command. */
final class DeleteCmd extends BaseCmd {
@Override
public void execute(final GUI g) {
final TreeNode n = selection();
if(n == null || !Dialog.confirm(dialog.gui, Text.DELETECONF)) return;
final Thread post = new Thread() {
@Override
public void run() {
refreshNewFolder(n.path());
}
};
DialogProgress.execute(dialog, "", post, new Delete(n.path()));
}
@Override
public String label() {
return BUTTONDELETE + DOTS;
}
@Override
public void refresh(final GUI gui, final AbstractButton button) {
final TreeNode n = selection();
button.setEnabled(n != null && !n.equals(root));
}
}
/** Rename command. */
final class RenameCmd extends BaseCmd {
@Override
public void execute(final GUI g) {
final TreeNode n = selection();
if(n == null) return;
final DialogInput d = new DialogInput(
n.path(), RENAMETITLE, dialog.gui, 0);
if(!d.ok()) return;
final Thread post = new Thread() {
@Override
public void run() {
refreshNewFolder(n.path());
}
};
DialogProgress.execute(dialog, "", post, new Rename(n.path(), d.input()));
}
@Override
public String label() {
return BUTTONRENAME;
}
@Override
public void refresh(final GUI gui, final AbstractButton button) {
final TreeNode n = selection();
button.setEnabled(n != null && !n.equals(root));
}
}
}
|
package org.g_node.micro.commons;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
import java.util.Locale;
/**
* Main service class for dealing with files.
*
* @author Michael Sonntag (sonntag@bio.lmu.de)
*/
public final class FileService {
/**
* Method for validating that a file actually exists.
* @param checkFile Path and filename of the provided file.
* @return True if the file exists, false otherwise.
*/
public static boolean checkFile(final String checkFile) {
return Files.exists(Paths.get(checkFile))
&& Files.exists(Paths.get(checkFile).toAbsolutePath());
}
/**
* Method for validating that the provided file is of a supported file extension.
* @param checkFile Filename of the provided file.
* @param fileExtensions List containing all supported file extensions.
* @return True if the file ends with a supported file extension, false otherwise.
*/
public static boolean checkFileExtension(final String checkFile, final List<String> fileExtensions) {
boolean correctFileType = false;
final int i = checkFile.lastIndexOf('.');
if (i > 0) {
final String checkExtension = checkFile.substring(i + 1);
correctFileType = fileExtensions.contains(checkExtension.toUpperCase(Locale.ENGLISH));
}
return correctFileType;
}
/**
* Method for validating that the provided file is of a supported file extension.
* @param checkFile Filename of the provided file.
* @param fileExtension String containing the supported file extension.
* @return True if the file ends with the supported file extension, false otherwise.
*/
public static boolean checkFileExtension(final String checkFile, final String fileExtension) {
boolean correctFileType = false;
final int i = checkFile.lastIndexOf('.');
if (i > 0) {
final String checkExtension = checkFile.substring(i + 1);
correctFileType = fileExtension.equals(checkExtension.toUpperCase(Locale.ENGLISH));
}
return correctFileType;
}
}
|
package org.geometrycommands;
import com.vividsolutions.jts.geom.Geometry;
import com.vividsolutions.jts.io.WKBReader;
import com.vividsolutions.jts.io.WKTReader;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.Writer;
/**
* The base class Command that deals with at least one Geometry
* @param <T> A GeometryOptions or subclass
* @author Jared Erickson
*/
public abstract class GeometryCommand<T extends GeometryOptions> implements Command<T> {
/**
* The WKTReader
*/
private final WKTReader wktReader = new WKTReader();
/**
* Execute the Command against at least one input Geometry
* @param options The GeometryOptions
* @param reader The java.io.Reader
* @param writer The java.io.Writer
* @throws Exception if an error occurs
*/
@Override
public void execute(T options, Reader reader, Writer writer) throws Exception {
// Get Geometry from the GeometryOption
Geometry geometry;
if (options.getGeometry() != null && options.getGeometry().trim().length() > 0) {
geometry = readGeometry(options.getGeometry(), options);
} else {
// Or Read it from the Reader
BufferedReader inputStreamReader = new BufferedReader(reader);
String str;
StringBuilder builder = new StringBuilder();
while ((str = inputStreamReader.readLine()) != null) {
builder.append(str);
}
String text = builder.toString();
geometry = readGeometry(text, options);
}
// Process the Geometry
processGeometry(geometry, options, reader, writer);
}
/**
* Read a Geometry.
* @param geometry A Geometry encoded as a String
* @param options The GeometryOptions
* @return The Geometry
* @throws Exception if an error occurs
*/
protected Geometry readGeometry(String geometry, T options) throws Exception {
return wktReader.read(geometry);
}
/**
* Write a Geometry
* @param geometry A Geometry
* @param options The GeometryOptions
* @return The Geometry encoded as a String
* @throws Exception if an error occurs
*/
protected String writeGeometry(Geometry geometry, T options) throws Exception {
return geometry.toText();
}
/**
* Process the input Geometry
* @param geometry The input Geometry
* @param options The GeometryOptions
* @param reader The java.io.Reader
* @param writer The java.io.Writer
* @throws Exception if an error occurs
*/
protected abstract void processGeometry(Geometry geometry, T options, Reader reader, Writer writer) throws Exception;
/**
* Get the Command's name
* @return The Command's name
*/
@Override
public abstract String getName();
/**
* Get a new GeometryOptions
* @return A new GeometryOptions
*/
@Override
public abstract T getOptions();
}
|
package org.geoserver.shell;
import it.geosolutions.geoserver.rest.HTTPUtils;
import it.geosolutions.geoserver.rest.decoder.utils.JDOMBuilder;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.shell.core.CommandMarker;
import org.springframework.shell.core.annotation.CliCommand;
import org.springframework.shell.core.annotation.CliOption;
import org.springframework.shell.support.util.OsUtils;
import org.springframework.stereotype.Component;
import java.io.StringReader;
@Component
public class SettingsCommands implements CommandMarker {
@Autowired
private Geoserver geoserver;
@CliCommand(value = "settings list", help = "List settings.")
public String list() throws Exception {
String url = geoserver.getUrl() + "/rest/settings.xml";
String TAB = " ";
String xml = HTTPUtils.get(url, geoserver.getUser(), geoserver.getPassword());
StringBuilder builder = new StringBuilder();
Element root = JDOMBuilder.buildElement(xml);
Element settings = root.getChild("settings");
builder.append("Settings").append(OsUtils.LINE_SEPARATOR);
builder.append(TAB).append("Charset: ").append(settings.getChildText("charset")).append(OsUtils.LINE_SEPARATOR);
builder.append(TAB).append("Number of Decimals: ").append(settings.getChildText("numDecimals")).append(OsUtils.LINE_SEPARATOR);
builder.append(TAB).append("Online Resource: ").append(settings.getChildText("onlineResource")).append(OsUtils.LINE_SEPARATOR);
builder.append(TAB).append("Verbose: ").append(settings.getChildText("verbose")).append(OsUtils.LINE_SEPARATOR);
builder.append(TAB).append("Verbose Exceptions: ").append(settings.getChildText("verboseExceptions")).append(OsUtils.LINE_SEPARATOR);
builder.append(OsUtils.LINE_SEPARATOR);
Element contact = settings.getChild("contact");
builder.append("Contact").append(OsUtils.LINE_SEPARATOR);
builder.append(TAB).append("City: ").append(contact.getChildText("addressCity")).append(OsUtils.LINE_SEPARATOR);
builder.append(TAB).append("Country: ").append(contact.getChildText("addressCountry")).append(OsUtils.LINE_SEPARATOR);
builder.append(TAB).append("Type: ").append(contact.getChildText("addressType")).append(OsUtils.LINE_SEPARATOR);
builder.append(TAB).append("Email: ").append(contact.getChildText("contactEmail")).append(OsUtils.LINE_SEPARATOR);
builder.append(TAB).append("Organization: ").append(contact.getChildText("contactOrganization")).append(OsUtils.LINE_SEPARATOR);
builder.append(TAB).append("Name: ").append(contact.getChildText("contactPerson")).append(OsUtils.LINE_SEPARATOR);
builder.append(TAB).append("Position: ").append(contact.getChildText("contactPosition")).append(OsUtils.LINE_SEPARATOR);
builder.append(OsUtils.LINE_SEPARATOR);
Element jai = root.getChild("jai");
builder.append("Java Advanced Imaging (JAI)").append(OsUtils.LINE_SEPARATOR);
builder.append(TAB).append("Allow Interpolation: ").append(jai.getChildText("allowInterpolation")).append(OsUtils.LINE_SEPARATOR);
builder.append(TAB).append("Recycling: ").append(jai.getChildText("recycling")).append(OsUtils.LINE_SEPARATOR);
builder.append(TAB).append("Allow Interpolation: ").append(jai.getChildText("allowInterpolation")).append(OsUtils.LINE_SEPARATOR);
builder.append(TAB).append("Tile Threads: ").append(jai.getChildText("tilePriority")).append(OsUtils.LINE_SEPARATOR);
builder.append(TAB).append("Memory Capacity: ").append(jai.getChildText("memoryCapacity")).append(OsUtils.LINE_SEPARATOR);
builder.append(TAB).append("Memory Threshold: ").append(jai.getChildText("memoryThreshold")).append(OsUtils.LINE_SEPARATOR);
builder.append(TAB).append("Image IO Cache: ").append(jai.getChildText("imageIOCache")).append(OsUtils.LINE_SEPARATOR);
builder.append(TAB).append("Png Acceleration: ").append(jai.getChildText("pngAcceleration")).append(OsUtils.LINE_SEPARATOR);
builder.append(TAB).append("Jpeg Acceleration: ").append(jai.getChildText("jpegAcceleration")).append(OsUtils.LINE_SEPARATOR);
builder.append(TAB).append("Allow Native Mosaic: ").append(jai.getChildText("allowNativeMosaic")).append(OsUtils.LINE_SEPARATOR);
builder.append(OsUtils.LINE_SEPARATOR);
Element coverageAccess = root.getChild("coverageAccess");
builder.append("Coverage Access").append(OsUtils.LINE_SEPARATOR);
builder.append(TAB).append("maxPoolSize: ").append(coverageAccess.getChildText("maxPoolSize")).append(OsUtils.LINE_SEPARATOR);
builder.append(TAB).append("corePoolSize: ").append(coverageAccess.getChildText("corePoolSize")).append(OsUtils.LINE_SEPARATOR);
builder.append(TAB).append("keepAliveTime: ").append(coverageAccess.getChildText("keepAliveTime")).append(OsUtils.LINE_SEPARATOR);
builder.append(TAB).append("queueType: ").append(coverageAccess.getChildText("queueType")).append(OsUtils.LINE_SEPARATOR);
builder.append(TAB).append("imageIOCacheThreshold: ").append(coverageAccess.getChildText("imageIOCacheThreshold")).append(OsUtils.LINE_SEPARATOR);
builder.append(OsUtils.LINE_SEPARATOR);
builder.append("Other").append(OsUtils.LINE_SEPARATOR);
builder.append(TAB).append("Update Sequence: ").append(root.getChildText("updateSequence")).append(OsUtils.LINE_SEPARATOR);
builder.append(TAB).append("Feature Type Cache Size: ").append(root.getChildText("featureTypeCacheSize")).append(OsUtils.LINE_SEPARATOR);
builder.append(TAB).append("Global Services: ").append(root.getChildText("globalServices")).append(OsUtils.LINE_SEPARATOR);
builder.append(TAB).append("XML Post Request Log Buffer Size: ").append(root.getChildText("xmlPostRequestLogBufferSize")).append(OsUtils.LINE_SEPARATOR);
return builder.toString();
}
@CliCommand(value = "settings modify", help = "Modify settings.")
public boolean modify(
// Settings
@CliOption(key = "charset", mandatory = false, help = "The charset") String charset,
@CliOption(key = "numdecimals", mandatory = false, help = "The number of decimals") String numberOfDecimals,
@CliOption(key = "onlineresource", mandatory = false, help = "The oneline resource url") String onlineResource,
@CliOption(key = "verbose", mandatory = false, help = "The verbose flag (true | false)") String verbose,
@CliOption(key = "verboseexceptions", mandatory = false, help = "The verbose exceptions flag (true | false)") String verboseExceptions,
// Global
@CliOption(key = "updatesequence", mandatory = false, help = "The update sequence") String updateSequence,
@CliOption(key = "featuretyepcachesize", mandatory = false, help = "The feature type cache size") String featureTypeCacheSize,
@CliOption(key = "globalservices", mandatory = false, help = "The global service flag (true | false)") String globalServices,
@CliOption(key = "xmlpostrequestlogbuffersize", mandatory = false, help = "The xml post request log buffer size") String xmlPostRequestLogBufferSize,
// JAI
@CliOption(key = "allowinterpolation", mandatory = false, help = "The JAI flag to allow interpolation or not") String allowInterpolation,
@CliOption(key = "recycling", mandatory = false, help = "The JAI flag to allow recycling") String recycling,
@CliOption(key = "tilepriority", mandatory = false, help = "The JAI tile priority") String tilePriority,
@CliOption(key = "tilethreads", mandatory = false, help = "The JAI tile threads") String tileThreads,
@CliOption(key = "memorycapacity", mandatory = false, help = "The JAI memory capacity") String memoryCapacity,
@CliOption(key = "memorythreshold", mandatory = false, help = "The JAI memory threshold") String memoryThreshold,
@CliOption(key = "imageiocache", mandatory = false, help = "The JAI flag to allow image IO cache") String imageIOCache,
@CliOption(key = "pngacceleration", mandatory = false, help = "The JAI flag to allow PNG acceleration") String pngAcceleration,
@CliOption(key = "jpegacceleration", mandatory = false, help = "The JAI flag to allow JPEG acceleration") String jpegAcceleration,
@CliOption(key = "allownativemosaic", mandatory = false, help = "The JAI flag to allow native mosaic") String allowNativeMosaic,
// Coverage Access
@CliOption(key = "maxpoolsize", mandatory = false, help = "The coverage access parameter to set the max pool size") String maxPoolSize,
@CliOption(key = "corepoolsize", mandatory = false, help = "The coverage access parameter to set the core pool size") String corePoolSize,
@CliOption(key = "keepalivetime", mandatory = false, help = "The coverage access parameter to set the keep alive time") String keepAliveTime,
@CliOption(key = "queuetype", mandatory = false, help = "The coverage access parameter to set the queue type") String queueType,
@CliOption(key = "imageiocachethreshold", mandatory = false, help = "The coverage access parameter to set the image io cache threshold") String imageIOCacheThreshold,
// Contact
@CliOption(key = "person", mandatory = false, help = "The contact's name") String person,
@CliOption(key = "position", mandatory = false, help = "The contact's position") String position,
@CliOption(key = "email", mandatory = false, help = "The contact's email") String email,
@CliOption(key = "organization", mandatory = false, help = "The contact's organization") String organization,
@CliOption(key = "city", mandatory = false, help = "The contact's city") String city,
@CliOption(key = "country", mandatory = false, help = "The contact's country") String country,
@CliOption(key = "addresstype", mandatory = false, help = "The contact's address type") String addressType
) throws Exception {
String url = geoserver.getUrl() + "/rest/settings.xml";
String xml = HTTPUtils.get(url, geoserver.getUser(), geoserver.getPassword());
Element element = JDOMBuilder.buildElement(xml);
// Settings
Element settingsElement = element.getChild("settings");
if (charset != null) {
JDOMUtil.getOrAdd(settingsElement, "charset").setText(charset);
}
if (numberOfDecimals != null) {
JDOMUtil.getOrAdd(settingsElement, "numDecimals").setText(numberOfDecimals);
}
if (onlineResource != null) {
JDOMUtil.getOrAdd(settingsElement, "onlineResource").setText(onlineResource);
}
if (verbose != null) {
JDOMUtil.getOrAdd(settingsElement, "verbose").setText(verbose);
}
if (verboseExceptions != null) {
JDOMUtil.getOrAdd(settingsElement, "verboseExceptions").setText(verboseExceptions);
}
// Contacts
Element contactElement = settingsElement.getChild("contact");
if (person != null) {
JDOMUtil.getOrAdd(contactElement,"contactPerson").setText(person);
}
if (position != null) {
JDOMUtil.getOrAdd(contactElement,"contactPosition").setText(position);
}
if (email != null) {
JDOMUtil.getOrAdd(contactElement,"contactEmail").setText(email);
}
if (organization != null) {
JDOMUtil.getOrAdd(contactElement,"contactOrganization").setText(organization);
}
if (city != null) {
JDOMUtil.getOrAdd(contactElement,"addressCity").setText(city);
}
if (country != null) {
JDOMUtil.getOrAdd(contactElement,"addressCountry").setText(country);
}
if (addressType != null) {
JDOMUtil.getOrAdd(contactElement,"addressType").setText(addressType);
}
// JAI
Element jaiElement = element.getChild("jai");
if (allowInterpolation != null) {
JDOMUtil.getOrAdd(jaiElement,"allowInterpolation").setText(allowInterpolation);
}
if (recycling != null) {
JDOMUtil.getOrAdd(jaiElement,"recycling").setText(recycling);
}
if (tilePriority != null) {
JDOMUtil.getOrAdd(jaiElement,"tilePriority").setText(tilePriority);
}
if (tileThreads != null) {
JDOMUtil.getOrAdd(jaiElement,"tileThreads").setText(tileThreads);
}
if (memoryCapacity != null) {
JDOMUtil.getOrAdd(jaiElement,"memoryCapacity").setText(memoryCapacity);
}
if (memoryThreshold != null) {
JDOMUtil.getOrAdd(jaiElement,"memoryThreshold").setText(memoryThreshold);
}
if (imageIOCache != null) {
JDOMUtil.getOrAdd(jaiElement,"imageIOCache").setText(imageIOCache);
}
if (pngAcceleration != null) {
JDOMUtil.getOrAdd(jaiElement,"pngAcceleration").setText(pngAcceleration);
}
if (jpegAcceleration != null) {
JDOMUtil.getOrAdd(jaiElement,"jpegAcceleration").setText(jpegAcceleration);
}
if (allowNativeMosaic != null) {
JDOMUtil.getOrAdd(jaiElement,"allowNativeMosaic").setText(allowNativeMosaic);
}
// Coverage Access
Element coverageAccessElement = element.getChild("coverageAccess");
if (maxPoolSize != null) {
JDOMUtil.getOrAdd(coverageAccessElement,"maxPoolSize").setText(maxPoolSize);
}
if (corePoolSize != null) {
JDOMUtil.getOrAdd(coverageAccessElement,"corePoolSize").setText(corePoolSize);
}
if (keepAliveTime != null) {
JDOMUtil.getOrAdd(coverageAccessElement,"keepAliveTime").setText(keepAliveTime);
}
if (queueType != null) {
JDOMUtil.getOrAdd(coverageAccessElement,"queueType").setText(queueType);
}
if (imageIOCacheThreshold != null) {
JDOMUtil.getOrAdd(coverageAccessElement,"imageIOCacheThreshold").setText(imageIOCacheThreshold);
}
// Global
if (updateSequence != null) {
JDOMUtil.getOrAdd(element,"updateSequence").setText(updateSequence);
}
if (featureTypeCacheSize != null) {
JDOMUtil.getOrAdd(element,"featureTypeCacheSize").setText(featureTypeCacheSize);
}
if (globalServices != null) {
JDOMUtil.getOrAdd(element,"globalServices").setText(globalServices);
}
if (xmlPostRequestLogBufferSize != null) {
JDOMUtil.getOrAdd(element,"xmlPostRequestLogBufferSize").setText(xmlPostRequestLogBufferSize);
}
String content = new XMLOutputter(Format.getPrettyFormat()).outputString(element);
String response = HTTPUtils.putXml(url, content, geoserver.getUser(), geoserver.getPassword());
return response != null;
}
@CliCommand(value = "settings contact list", help = "List contact settings.")
public String listContact() throws Exception {
String TAB = " ";
String xml = HTTPUtils.get(geoserver.getUrl() + "/rest/settings/contact.xml", geoserver.getUser(), geoserver.getPassword());
StringBuilder builder = new StringBuilder();
Element element = JDOMBuilder.buildElement(xml);
builder.append("City: ").append(element.getChildText("addressCity")).append(OsUtils.LINE_SEPARATOR);
builder.append("Country: ").append(element.getChildText("addressCountry")).append(OsUtils.LINE_SEPARATOR);
builder.append("Type: ").append(element.getChildText("addressType")).append(OsUtils.LINE_SEPARATOR);
builder.append("Email: ").append(element.getChildText("contactEmail")).append(OsUtils.LINE_SEPARATOR);
builder.append("Organization: ").append(element.getChildText("contactOrganization")).append(OsUtils.LINE_SEPARATOR);
builder.append("Name: ").append(element.getChildText("contactPerson")).append(OsUtils.LINE_SEPARATOR);
builder.append("Position: ").append(element.getChildText("contactPosition")).append(OsUtils.LINE_SEPARATOR);
return builder.toString();
}
@CliCommand(value = "settings contact modify", help = "Modify contact settings.")
public boolean modifyContact(
@CliOption(key = "person", mandatory = false, help = "The contact's name") String person,
@CliOption(key = "position", mandatory = false, help = "The contact's position") String position,
@CliOption(key = "email", mandatory = false, help = "The contact's email") String email,
@CliOption(key = "organization", mandatory = false, help = "The contact's organization") String organization,
@CliOption(key = "city", mandatory = false, help = "The contact's city") String city,
@CliOption(key = "country", mandatory = false, help = "The contact's country") String country,
@CliOption(key = "addresstype", mandatory = false, help = "The contact's address type") String addressType
) throws Exception {
String url = geoserver.getUrl() + "/rest/settings/contact.xml";
Element element = new Element("contact");
if (person != null) {
element.addContent(new Element("contactPerson").setText(person));
}
if (position != null) {
element.addContent(new Element("contactPosition").setText(position));
}
if (email != null) {
element.addContent(new Element("contactEmail").setText(email));
}
if (organization != null) {
element.addContent(new Element("contactOrganization").setText(organization));
}
if (city != null) {
element.addContent(new Element("addressCity").setText(city));
}
if (country != null) {
element.addContent(new Element("addressCountry").setText(country));
}
if (addressType != null) {
element.addContent(new Element("addressType").setText(addressType));
}
String content = new XMLOutputter(Format.getPrettyFormat()).outputString(element);
String response = HTTPUtils.putXml(url, content, geoserver.getUser(), geoserver.getPassword());
return response != null;
}
@CliCommand(value = "settings local list", help = "List settings.")
public String listLocal(
@CliOption(key = "workspace", mandatory = true, help = "The workspace") String workspace
) throws Exception {
String url = geoserver.getUrl() + "/rest/workspaces/" + URLUtil.encode(workspace) + "/settings.xml";
String TAB = " ";
String xml = HTTPUtils.get(url, geoserver.getUser(), geoserver.getPassword());
StringBuilder builder = new StringBuilder();
Element settings = JDOMBuilder.buildElement(xml);
if (settings.getChild("workspace") != null) {
// Settings
builder.append("Settings").append(OsUtils.LINE_SEPARATOR);
builder.append(TAB).append("Charset: ").append(settings.getChildText("charset")).append(OsUtils.LINE_SEPARATOR);
builder.append(TAB).append("Number of Decimals: ").append(settings.getChildText("numDecimals")).append(OsUtils.LINE_SEPARATOR);
builder.append(TAB).append("Online Resource: ").append(settings.getChildText("onlineResource")).append(OsUtils.LINE_SEPARATOR);
builder.append(TAB).append("Verbose: ").append(settings.getChildText("verbose")).append(OsUtils.LINE_SEPARATOR);
builder.append(TAB).append("Verbose Exceptions: ").append(settings.getChildText("verboseExceptions")).append(OsUtils.LINE_SEPARATOR);
// Contact
Element contact = settings.getChild("contact");
if (contact != null) {
builder.append(OsUtils.LINE_SEPARATOR);
builder.append("Contact").append(OsUtils.LINE_SEPARATOR);
builder.append(TAB).append("City: ").append(contact.getChildText("addressCity")).append(OsUtils.LINE_SEPARATOR);
builder.append(TAB).append("Country: ").append(contact.getChildText("addressCountry")).append(OsUtils.LINE_SEPARATOR);
builder.append(TAB).append("Type: ").append(contact.getChildText("addressType")).append(OsUtils.LINE_SEPARATOR);
builder.append(TAB).append("Email: ").append(contact.getChildText("contactEmail")).append(OsUtils.LINE_SEPARATOR);
builder.append(TAB).append("Organization: ").append(contact.getChildText("contactOrganization")).append(OsUtils.LINE_SEPARATOR);
builder.append(TAB).append("Name: ").append(contact.getChildText("contactPerson")).append(OsUtils.LINE_SEPARATOR);
builder.append(TAB).append("Position: ").append(contact.getChildText("contactPosition")).append(OsUtils.LINE_SEPARATOR);
}
}
return builder.toString();
}
@CliCommand(value = "settings local create", help = "Create local settings.")
public boolean createLocal(
// Workspace
@CliOption(key = "workspace", mandatory = true, help = "The workspace") String workspace,
// Settings
@CliOption(key = "charset", mandatory = false, help = "The charset") String charset,
@CliOption(key = "numdecimals", mandatory = false, help = "The number of decimals") String numberOfDecimals,
@CliOption(key = "verbose", mandatory = false, help = "The verbose flag (true | false)") String verbose,
@CliOption(key = "verboseexceptions", mandatory = false, help = "The verbose exceptions flag (true | false)") String verboseExceptions,
// Contact
@CliOption(key = "person", mandatory = false, help = "The contact's name") String person,
@CliOption(key = "position", mandatory = false, help = "The contact's position") String position,
@CliOption(key = "email", mandatory = false, help = "The contact's email") String email,
@CliOption(key = "organization", mandatory = false, help = "The contact's organization") String organization,
@CliOption(key = "city", mandatory = false, help = "The contact's city") String city,
@CliOption(key = "country", mandatory = false, help = "The contact's country") String country,
@CliOption(key = "addresstype", mandatory = false, help = "The contact's address type") String addressType
) throws Exception {
String url = geoserver.getUrl() + "/rest/workspaces/" + URLUtil.encode(workspace) + "/settings.xml";
Element settingsElement = JDOMBuilder.buildElement(HTTPUtils.get(url, geoserver.getUser(), geoserver.getPassword()));
settingsElement.addContent(new Element("workspace").addContent(new Element("name").setText(workspace)));
// Settings
if (charset != null) {
JDOMUtil.getOrAdd(settingsElement, "charset").setText(charset);
}
if (numberOfDecimals != null) {
JDOMUtil.getOrAdd(settingsElement, "numDecimals").setText(numberOfDecimals);
}
if (verbose != null) {
JDOMUtil.getOrAdd(settingsElement, "verbose").setText(verbose);
}
if (verboseExceptions != null) {
JDOMUtil.getOrAdd(settingsElement, "verboseExceptions").setText(verboseExceptions);
}
// Contact
Element contactElement = JDOMUtil.getOrAdd(settingsElement,"contact");
if (person != null) {
JDOMUtil.getOrAdd(contactElement, "contactPerson").setText(person);
}
if (position != null) {
JDOMUtil.getOrAdd(contactElement, "contactPosition").setText(position);
}
if (email != null) {
JDOMUtil.getOrAdd(contactElement, "contactEmail").setText(email);
}
if (organization != null) {
JDOMUtil.getOrAdd(contactElement, "contactOrganization").setText(organization);
}
if (city != null) {
JDOMUtil.getOrAdd(contactElement, "addressCity").setText(city);
}
if (country != null) {
JDOMUtil.getOrAdd(contactElement, "addressCountry").setText(country);
}
if (addressType != null) {
JDOMUtil.getOrAdd(contactElement, "addressType").setText(addressType);
}
String xml = new XMLOutputter(Format.getPrettyFormat()).outputString(settingsElement);
String response = HTTPUtils.putXml(url, xml, geoserver.getUser(), geoserver.getPassword());
System.out.println(url);
System.out.println(xml);
System.out.println(response);
return response != null;
}
@CliCommand(value = "settings local modify", help = "Modify local settings.")
public boolean modifyLocal(
// Workspace
@CliOption(key = "workspace", mandatory = true, help = "The workspace") String workspace,
// Settings
@CliOption(key = "charset", mandatory = false, help = "The charset") String charset,
@CliOption(key = "numdecimals", mandatory = false, help = "The number of decimals") String numberOfDecimals,
@CliOption(key = "verbose", mandatory = false, help = "The verbose flag (true | false)") String verbose,
@CliOption(key = "verboseexceptions", mandatory = false, help = "The verbose exceptions flag (true | false)") String verboseExceptions,
// Contact
@CliOption(key = "person", mandatory = false, help = "The contact's name") String person,
@CliOption(key = "position", mandatory = false, help = "The contact's position") String position,
@CliOption(key = "email", mandatory = false, help = "The contact's email") String email,
@CliOption(key = "organization", mandatory = false, help = "The contact's organization") String organization,
@CliOption(key = "city", mandatory = false, help = "The contact's city") String city,
@CliOption(key = "country", mandatory = false, help = "The contact's country") String country,
@CliOption(key = "addresstype", mandatory = false, help = "The contact's address type") String addressType
) throws Exception {
String url = geoserver.getUrl() + "/rest/workspaces/" + URLUtil.encode(workspace) + "/settings.xml";
Element settingsElement = JDOMBuilder.buildElement(HTTPUtils.get(url, geoserver.getUser(), geoserver.getPassword()));
// Settings
if (charset != null) {
JDOMUtil.getOrAdd(settingsElement, "charset").setText(charset);
}
if (numberOfDecimals != null) {
JDOMUtil.getOrAdd(settingsElement, "numDecimals").setText(numberOfDecimals);
}
if (verbose != null) {
JDOMUtil.getOrAdd(settingsElement, "verbose").setText(verbose);
}
if (verboseExceptions != null) {
JDOMUtil.getOrAdd(settingsElement, "verboseExceptions").setText(verboseExceptions);
}
// Contact
Element contactElement = JDOMUtil.getOrAdd(settingsElement,"contact");
if (person != null) {
JDOMUtil.getOrAdd(contactElement, "contactPerson").setText(person);
}
if (position != null) {
JDOMUtil.getOrAdd(contactElement, "contactPosition").setText(position);
}
if (email != null) {
JDOMUtil.getOrAdd(contactElement, "contactEmail").setText(email);
}
if (organization != null) {
JDOMUtil.getOrAdd(contactElement, "contactOrganization").setText(organization);
}
if (city != null) {
JDOMUtil.getOrAdd(contactElement, "addressCity").setText(city);
}
if (country != null) {
JDOMUtil.getOrAdd(contactElement, "addressCountry").setText(country);
}
if (addressType != null) {
JDOMUtil.getOrAdd(contactElement, "addressType").setText(addressType);
}
String xml = new XMLOutputter(Format.getPrettyFormat()).outputString(settingsElement);
String response = HTTPUtils.putXml(url, xml, geoserver.getUser(), geoserver.getPassword());
System.out.println(url);
System.out.println(xml);
System.out.println(response);
return response != null;
}
@CliCommand(value = "settings local delete", help = "Delete local settings.")
public boolean deleteLocal(
@CliOption(key = "workspace", mandatory = true, help = "The workspace") String workspace
) throws Exception {
String url = geoserver.getUrl() + "/rest/workspaces/" + URLUtil.encode(workspace) + "/settings.xml";
return HTTPUtils.delete(url, geoserver.getUser(), geoserver.getPassword());
}
}
|
package org.jboss.vfs.spi;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.FileNotFoundException;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import org.jboss.vfs.VirtualFile;
import org.jboss.vfs.VirtualFileAssembly;
/**
* FileSystem used to mount an Assembly into the VFS.
*
* @author <a href="baileyje@gmail.com">John Bailey</a>
*/
public class AssemblyFileSystem implements FileSystem {
private final VirtualFileAssembly assembly;
public AssemblyFileSystem(VirtualFileAssembly assembly) {
this.assembly = assembly;
}
/** {@inheritDoc} */
public File getFile(VirtualFile mountPoint, VirtualFile target) throws IOException {
return getExistingFile(mountPoint, target).getPhysicalFile();
}
/** {@inheritDoc} */
public boolean delete(VirtualFile mountPoint, VirtualFile target) {
VirtualFile assemblyFile = assembly.getFile(mountPoint, target);
return assemblyFile != null && assemblyFile.delete();
}
/** {@inheritDoc} */
public boolean exists(VirtualFile mountPoint, VirtualFile target) {
VirtualFile assemblyFile = assembly.getFile(mountPoint, target);
return assemblyFile != null && assemblyFile.exists();
}
/** {@inheritDoc} */
public List<String> getDirectoryEntries(VirtualFile mountPoint, VirtualFile target) {
VirtualFile assemblyFile = assembly.getFile(mountPoint, target);
if (assemblyFile == null) {
return Collections.<String>emptyList();
}
List<String> directoryEntries = new LinkedList<String>();
for (VirtualFile child : assemblyFile.getChildren()) {
directoryEntries.add(child.getName());
}
return directoryEntries;
}
/** {@inheritDoc} */
public long getLastModified(VirtualFile mountPoint, VirtualFile target) {
VirtualFile assemblyFile = assembly.getFile(mountPoint, target);
return assemblyFile == null ? 0L : assemblyFile.getLastModified();
}
/** {@inheritDoc} */
public long getSize(VirtualFile mountPoint, VirtualFile target) {
VirtualFile assemblyFile = assembly.getFile(mountPoint, target);
return assemblyFile == null ? 0L : assemblyFile.getSize();
}
/** {@inheritDoc} */
public boolean isDirectory(VirtualFile mountPoint, VirtualFile target) {
VirtualFile assemblyFile = assembly.getFile(mountPoint, target);
return assemblyFile != null && assemblyFile.isDirectory();
}
/** {@inheritDoc} */
public boolean isReadOnly() {
return false;
}
/** {@inheritDoc} */
public InputStream openInputStream(VirtualFile mountPoint, VirtualFile target) throws IOException {
return getExistingFile(mountPoint, target).openStream();
}
/** {@inheritDoc} */
public void close() throws IOException {
assembly.close();
}
private VirtualFile getExistingFile(final VirtualFile mountPoint, final VirtualFile target) throws FileNotFoundException {
VirtualFile assemblyFile = assembly.getFile(mountPoint, target);
if (assemblyFile == null) {
throw new FileNotFoundException(target.getPathName());
}
return assemblyFile;
}
}
|
package org.jenkinsci.plugins.p4;
import com.cloudbees.plugins.credentials.CredentialsMatchers;
import com.cloudbees.plugins.credentials.CredentialsProvider;
import com.cloudbees.plugins.credentials.domains.DomainRequirement;
import com.perforce.p4java.exception.P4JavaException;
import com.perforce.p4java.impl.generic.core.Label;
import hudson.AbortException;
import hudson.EnvVars;
import hudson.Extension;
import hudson.FilePath;
import hudson.Launcher;
import hudson.Plugin;
import hudson.matrix.MatrixBuild;
import hudson.matrix.MatrixConfiguration;
import hudson.matrix.MatrixExecutionStrategy;
import hudson.matrix.MatrixProject;
import hudson.model.*;
import hudson.scm.ChangeLogParser;
import hudson.scm.PollingResult;
import hudson.scm.RepositoryBrowser;
import hudson.scm.SCM;
import hudson.scm.SCMDescriptor;
import hudson.scm.SCMRevisionState;
import hudson.security.ACL;
import hudson.util.FormValidation;
import hudson.util.ListBoxModel;
import hudson.util.LogTaskListener;
import jenkins.model.Jenkins;
import net.sf.json.JSONException;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.jenkinsci.plugins.multiplescms.MultiSCM;
import org.jenkinsci.plugins.p4.browsers.P4Browser;
import org.jenkinsci.plugins.p4.browsers.SwarmBrowser;
import org.jenkinsci.plugins.p4.changes.P4ChangeEntry;
import org.jenkinsci.plugins.p4.changes.P4ChangeParser;
import org.jenkinsci.plugins.p4.changes.P4ChangeSet;
import org.jenkinsci.plugins.p4.changes.P4Revision;
import org.jenkinsci.plugins.p4.client.ConnectionHelper;
import org.jenkinsci.plugins.p4.credentials.P4BaseCredentials;
import org.jenkinsci.plugins.p4.credentials.P4CredentialsImpl;
import org.jenkinsci.plugins.p4.filters.Filter;
import org.jenkinsci.plugins.p4.filters.FilterPerChangeImpl;
import org.jenkinsci.plugins.p4.matrix.MatrixOptions;
import org.jenkinsci.plugins.p4.populate.Populate;
import org.jenkinsci.plugins.p4.review.ReviewProp;
import org.jenkinsci.plugins.p4.tagging.TagAction;
import org.jenkinsci.plugins.p4.tasks.CheckoutTask;
import org.jenkinsci.plugins.p4.tasks.PollTask;
import org.jenkinsci.plugins.p4.tasks.RemoveClientTask;
import org.jenkinsci.plugins.p4.workspace.ManualWorkspaceImpl;
import org.jenkinsci.plugins.p4.workspace.SpecWorkspaceImpl;
import org.jenkinsci.plugins.p4.workspace.StaticWorkspaceImpl;
import org.jenkinsci.plugins.p4.workspace.StreamWorkspaceImpl;
import org.jenkinsci.plugins.p4.workspace.TemplateWorkspaceImpl;
import org.jenkinsci.plugins.p4.workspace.Workspace;
import org.kohsuke.stapler.*;
import javax.annotation.CheckForNull;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
public class PerforceScm extends SCM {
private static Logger logger = Logger.getLogger(PerforceScm.class.getName());
private final String credential;
private final Workspace workspace;
private final List<Filter> filter;
private final Populate populate;
private final P4Browser browser;
private transient List<P4Revision> incrementalChanges;
private transient P4Revision parentChange;
/**
* JENKINS-37442: We need to store the changelog file name for the build so
* that we can expose it to the build environment
*/
private transient String changelogFilename = null;
public String getCredential() {
return credential;
}
public Workspace getWorkspace() {
return workspace;
}
public List<Filter> getFilter() {
return filter;
}
public Populate getPopulate() {
return populate;
}
@Override
public P4Browser getBrowser() {
return browser;
}
public List<P4Revision> getIncrementalChanges() {
return incrementalChanges;
}
/**
* Helper function for converting an SCM object into a
* PerforceScm object when appropriate.
*
* @param scm the SCM object
* @return a PerforceScm instance or null
*/
public static PerforceScm convertToPerforceScm(SCM scm) {
PerforceScm perforceScm = null;
if (scm instanceof PerforceScm) {
perforceScm = (PerforceScm) scm;
} else {
Jenkins jenkins = Jenkins.getInstance();
if (jenkins != null) {
Plugin multiSCMPlugin = jenkins.getPlugin("multiple-scms");
if (multiSCMPlugin != null) {
if (scm instanceof MultiSCM) {
MultiSCM multiSCM = (MultiSCM) scm;
for (SCM configuredSCM : multiSCM.getConfiguredSCMs()) {
if (configuredSCM instanceof PerforceScm) {
perforceScm = (PerforceScm) configuredSCM;
break;
}
}
}
}
}
}
return perforceScm;
}
/**
* Create a constructor that takes non-transient fields, and add the
* annotation @DataBoundConstructor to it. Using the annotation helps the
* Stapler class to find which constructor that should be used when
* automatically copying values from a web form to a class.
*
* @param credential Credential ID
* @param workspace Workspace connection details
* @param filter Polling filters
* @param populate Populate options
* @param browser Browser options
*/
@DataBoundConstructor
public PerforceScm(String credential, Workspace workspace, List<Filter> filter, Populate populate,
P4Browser browser) {
this.credential = credential;
this.workspace = workspace;
this.filter = filter;
this.populate = populate;
this.browser = browser;
}
public PerforceScm(String credential, Workspace workspace, Populate populate) {
this.credential = credential;
this.workspace = workspace;
this.filter = null;
this.populate = populate;
this.browser = null;
}
@Override
public String getKey() {
String delim = "-";
StringBuffer key = new StringBuffer("p4");
// add Credential
key.append(delim);
key.append(credential);
// add Mapping/Stream
key.append(delim);
if (workspace instanceof ManualWorkspaceImpl) {
ManualWorkspaceImpl ws = (ManualWorkspaceImpl) workspace;
key.append(ws.getSpec().getView());
key.append(ws.getSpec().getStreamName());
}
if (workspace instanceof StreamWorkspaceImpl) {
StreamWorkspaceImpl ws = (StreamWorkspaceImpl) workspace;
key.append(ws.getStreamName());
}
if (workspace instanceof SpecWorkspaceImpl) {
SpecWorkspaceImpl ws = (SpecWorkspaceImpl) workspace;
key.append(ws.getSpecPath());
}
if (workspace instanceof StaticWorkspaceImpl) {
StaticWorkspaceImpl ws = (StaticWorkspaceImpl) workspace;
key.append(ws.getName());
}
if (workspace instanceof TemplateWorkspaceImpl) {
TemplateWorkspaceImpl ws = (TemplateWorkspaceImpl) workspace;
key.append(ws.getTemplateName());
}
return key.toString();
}
@Override
public RepositoryBrowser<?> guessBrowser() {
String scmCredential = getCredential();
if (scmCredential == null) {
logger.fine("No credential for perforce");
return null;
}
StaplerRequest req = Stapler.getCurrentRequest();
if (req == null) {
logger.fine("Unable to retrieve job from request");
return null;
}
Job job = req.findAncestorObject(Job.class);
if (req == null) {
logger.fine("Unable to retrieve job");
return null;
}
try {
ConnectionHelper connection = new ConnectionHelper(job, scmCredential, null);
String swarm = connection.getSwarm();
URL url = new URL(swarm);
return new SwarmBrowser(url);
} catch (MalformedURLException e) {
logger.info("Unable to guess repository browser.");
return null;
} catch (P4JavaException e) {
logger.info("Unable to access Perforce Property.");
return null;
}
}
/**
* Calculate the state of the workspace of the given build. The returned
* object is then fed into compareRemoteRevisionWith as the baseline
* SCMRevisionState to determine if the build is necessary, and is added to
* the build as an Action for later retrieval.
*/
@Override
public SCMRevisionState calcRevisionsFromBuild(Run<?, ?> run, FilePath buildWorkspace, Launcher launcher,
TaskListener listener) throws IOException, InterruptedException {
// A baseline is not required... but a baseline object is, so we'll
// return the NONE object.
return SCMRevisionState.NONE;
}
/**
* This method does the actual polling and returns a PollingResult. The
* change attribute of the PollingResult the significance of the changes
* detected by this poll.
*/
@Override
public PollingResult compareRemoteRevisionWith(Job<?, ?> job, Launcher launcher, FilePath buildWorkspace,
TaskListener listener, SCMRevisionState baseline) throws IOException, InterruptedException {
PollingResult state = PollingResult.NO_CHANGES;
Node node = workspaceToNode(buildWorkspace);
// Delay polling if build is in progress
if (job.isBuilding()) {
listener.getLogger().println("Build in progress, polling delayed.");
return PollingResult.NO_CHANGES;
}
Jenkins j = Jenkins.getInstance();
if (j == null) {
listener.getLogger().println("Warning Jenkins instance is null.");
return PollingResult.NO_CHANGES;
}
// Get last run and build workspace
Run<?, ?> lastRun = job.getLastBuild();
buildWorkspace = j.getRootPath();
if (job instanceof MatrixProject) {
if (isBuildParent(job)) {
// Poll PARENT only
EnvVars envVars = job.getEnvironment(node, listener);
state = pollWorkspace(envVars, listener, buildWorkspace, lastRun);
} else {
// Poll CHILDREN only
MatrixProject matrixProj = (MatrixProject) job;
Collection<MatrixConfiguration> configs = matrixProj.getActiveConfigurations();
for (MatrixConfiguration config : configs) {
EnvVars envVars = config.getEnvironment(node, listener);
state = pollWorkspace(envVars, listener, buildWorkspace, lastRun);
// exit early if changes found
if (state == PollingResult.BUILD_NOW) {
return PollingResult.BUILD_NOW;
}
}
}
} else {
EnvVars envVars = job.getEnvironment(node, listener);
state = pollWorkspace(envVars, listener, buildWorkspace, lastRun);
}
return state;
}
/**
* Construct workspace from environment and then look for changes.
*
* @param envVars
* @param listener
* @throws InterruptedException
* @throws IOException
*/
private PollingResult pollWorkspace(EnvVars envVars, TaskListener listener, FilePath buildWorkspace, Run<?, ?> lastRun)
throws InterruptedException, IOException {
PrintStream log = listener.getLogger();
// set NODE_NAME to Node or default "master" if not set
Node node = workspaceToNode(buildWorkspace);
String nodeName = node.getNodeName();
nodeName = (nodeName.isEmpty()) ? "master" : nodeName;
envVars.put("NODE_NAME", envVars.get("NODE_NAME", nodeName));
Workspace ws = (Workspace) workspace.clone();
String root = buildWorkspace.getRemote();
if (root.contains("@")) {
root = root.replace("@", "%40");
}
ws.setRootPath(root);
ws.setExpand(envVars);
// don't call setRootPath() here, polling is often on the master
// Set EXPANDED client
String client = ws.getFullName();
String syncID = ws.getSyncID();
log.println("P4: Polling on: " + nodeName + " with:" + client);
// Set EXPANDED pinned label/change
String pin = populate.getPin();
if (pin != null && !pin.isEmpty()) {
pin = ws.getExpand().format(pin, false);
ws.getExpand().set(ReviewProp.LABEL.toString(), pin);
}
// Calculate last change, build if null (JENKINS-40356)
P4Revision last = TagAction.getLastChange(lastRun, listener, syncID);
if (last == null) {
return PollingResult.BUILD_NOW;
}
// Create task
PollTask task = new PollTask(filter, last);
task.setCredential(credential, lastRun);
task.setWorkspace(ws);
task.setListener(listener);
task.setLimit(pin);
// Execute remote task
incrementalChanges = buildWorkspace.act(task);
// Report changes
if (!incrementalChanges.isEmpty()) {
return PollingResult.BUILD_NOW;
}
return PollingResult.NO_CHANGES;
}
/**
* The checkout method is expected to check out modified files into the
* project workspace. In Perforce terms a 'p4 sync' on the project's
* workspace. Authorisation
*/
@Override
public void checkout(Run<?, ?> run, Launcher launcher, FilePath buildWorkspace, TaskListener listener,
File changelogFile, SCMRevisionState baseline) throws IOException, InterruptedException {
PrintStream log = listener.getLogger();
boolean success = true;
// Create task
CheckoutTask task = new CheckoutTask(populate);
task.setListener(listener);
task.setCredential(credential, run);
// Get workspace used for the Task
Workspace ws = task.setEnvironment(run, workspace, buildWorkspace);
// Set the Workspace and initialise
task.setWorkspace(ws);
task.initialise();
// Override build change if polling per change, MUST clear after use.
if (isIncremental()) {
task.setIncrementalChanges(incrementalChanges);
}
incrementalChanges = new ArrayList<P4Revision>();
// Add tagging action to build, enabling label support.
TagAction tag = new TagAction(run, credential);
tag.setWorkspace(ws);
tag.setBuildChange(task.getSyncChange());
run.addAction(tag);
// Invoke build.
String node = ws.getExpand().get("NODE_NAME");
Job<?, ?> job = run.getParent();
if (run instanceof MatrixBuild) {
parentChange = task.getSyncChange();
if (isBuildParent(job)) {
log.println("Building Parent on Node: " + node);
success &= buildWorkspace.act(task);
} else {
listener.getLogger().println("Skipping Parent build...");
success = true;
}
} else {
if (job instanceof MatrixProject) {
if (parentChange != null) {
log.println("Using parent change: " + parentChange);
task.setBuildChange(parentChange);
}
log.println("Building Child on Node: " + node);
} else {
log.println("Building on Node: " + node);
}
success &= buildWorkspace.act(task);
}
// Only write change log if build succeeded and changeLogFile has been
// set.
if (success) {
if (changelogFile != null) {
// Calculate changes prior to build (based on last build)
listener.getLogger().println("P4 Task: saving built changes.");
List<P4ChangeEntry> changes = calculateChanges(run, task);
P4ChangeSet.store(changelogFile, changes);
listener.getLogger().println("... done\n");
// JENKINS-37442: Make the log file name available
changelogFilename = changelogFile.getAbsolutePath();
} else {
listener.getLogger().println("P4 Task: changeLogFile not set. Not saving built changes.");
}
} else {
String msg = "P4: Build failed";
logger.warning(msg);
throw new AbortException(msg);
}
}
// Get Matrix Execution options
private MatrixExecutionStrategy getMatrixExecutionStrategy(Job<?, ?> job) {
if (job instanceof MatrixProject) {
MatrixProject matrixProj = (MatrixProject) job;
return matrixProj.getExecutionStrategy();
}
return null;
}
boolean isBuildParent(Job<?, ?> job) {
MatrixExecutionStrategy matrix = getMatrixExecutionStrategy(job);
if (matrix instanceof MatrixOptions) {
return ((MatrixOptions) matrix).isBuildParent();
} else {
// if user hasn't configured "Perforce: Matrix Options" execution
// strategy, default to false
return false;
}
}
private List<P4ChangeEntry> calculateChanges(Run<?, ?> run, CheckoutTask task) {
List<P4ChangeEntry> list = new ArrayList<P4ChangeEntry>();
// Look for all changes since the last build
Run<?, ?> lastBuild = run.getPreviousSuccessfulBuild();
String syncID = task.getSyncID();
P4Revision lastChange = TagAction.getLastChange(lastBuild, task.getListener(), syncID);
if (lastChange != null) {
List<P4ChangeEntry> changes;
changes = task.getChangesFull(lastChange);
for (P4ChangeEntry c : changes) {
list.add(c);
}
}
// if empty, look for shelves in current build. The latest change
// will not get listed as 'p4 changes n,n' will return no change
if (list.isEmpty()) {
P4Revision lastRevision = task.getBuildChange();
if (lastRevision != null) {
List<P4ChangeEntry> changes;
changes = task.getChangesFull(lastRevision);
for (P4ChangeEntry c : changes) {
list.add(c);
}
}
}
// still empty! No previous build, so add current
if ((lastBuild == null) && list.isEmpty()) {
list.add(task.getCurrentChange());
}
return list;
}
@Override
public void buildEnvVars(AbstractBuild<?, ?> build, Map<String, String> env) {
super.buildEnvVars(build, env);
TagAction tagAction = build.getAction(TagAction.class);
if (tagAction != null) {
// Set P4_CHANGELIST value
String change = getChangeNumber(tagAction, build);
if (change != null) {
env.put("P4_CHANGELIST", change);
}
// Set P4_CLIENT workspace value
String client = tagAction.getClient();
if (client != null) {
env.put("P4_CLIENT", client);
}
// Set P4_PORT connection
String port = tagAction.getPort();
if (port != null) {
env.put("P4_PORT", port);
}
// Set P4_USER connection
String user = tagAction.getUser();
if (user != null) {
env.put("P4_USER", user);
}
// Set P4_TICKET connection
Jenkins j = Jenkins.getInstance();
if (j != null) {
@SuppressWarnings("unchecked")
Descriptor<SCM> scm = j.getDescriptor(PerforceScm.class);
DescriptorImpl p4scm = (DescriptorImpl) scm;
String ticket = tagAction.getTicket();
if (ticket != null && !p4scm.isHideTicket()) {
env.put("P4_TICKET", ticket);
}
}
// JENKINS-37442: Make the log file name available
env.put("HUDSON_CHANGELOG_FILE", StringUtils.defaultIfBlank(changelogFilename, "Not-set"));
}
}
private String getChangeNumber(TagAction tagAction, Run<?, ?> run) {
P4Revision buildChange = tagAction.getBuildChange();
if (!buildChange.isLabel()) {
// its a change, so return...
return buildChange.toString();
}
try {
// it is really a change number, so add change...
int change = Integer.parseInt(buildChange.toString());
return String.valueOf(change);
} catch (NumberFormatException n) {
// not a change number
}
ConnectionHelper p4 = new ConnectionHelper(run.getParent(), credential, null);
String name = buildChange.toString();
try {
Label label = p4.getLabel(name);
String spec = label.getRevisionSpec();
if (spec != null && !spec.isEmpty()) {
if (spec.startsWith("@")) {
spec = spec.substring(1);
}
return spec;
} else {
// a label, but no RevisionSpec
return name;
}
} catch (Exception e) {
// not a label
}
try {
String counter = p4.getCounter(name);
if (!"0".equals(counter)) {
try {
// if a change number, add change...
int change = Integer.parseInt(counter);
return String.valueOf(change);
} catch (NumberFormatException n) {
// no change number in counter
}
}
} catch (Exception e) {
// not a counter
}
p4.disconnect();
return name;
}
/**
* The checkout method should, besides checking out the modified files,
* write a changelog.xml file that contains the changes for a certain build.
* The changelog.xml file is specific for each SCM implementation, and the
* createChangeLogParser returns a parser that can parse the file and return
* a ChangeLogSet.
*/
@Override
public ChangeLogParser createChangeLogParser() {
return new P4ChangeParser();
}
/**
* Called before a workspace is deleted on the given node, to provide SCM an
* opportunity to perform clean up.
*/
@Override
public boolean processWorkspaceBeforeDeletion(Job<?, ?> job, FilePath buildWorkspace, Node node)
throws IOException, InterruptedException {
logger.info("processWorkspaceBeforeDeletion");
Run<?, ?> run = job.getLastBuild();
if (run == null) {
logger.warning("P4: No previous builds found");
return false;
}
// exit early if client workspace is undefined
LogTaskListener listener = new LogTaskListener(logger, Level.INFO);
EnvVars envVars = run.getEnvironment(listener);
String client = envVars.get("P4_CLIENT");
if (client == null || client.isEmpty()) {
logger.warning("P4: Unable to read P4_CLIENT");
return false;
}
// exit early if client workspace does not exist
ConnectionHelper connection = new ConnectionHelper(job, credential, null);
try {
if (!connection.isClient(client)) {
logger.warning("P4: client not found:" + client);
return false;
}
} catch (Exception e) {
logger.warning("P4: Not able to get connection");
return false;
}
// Setup Cleanup Task
RemoveClientTask task = new RemoveClientTask(client);
task.setListener(listener);
task.setCredential(credential, job);
// Set workspace used for the Task
Workspace ws = task.setEnvironment(run, workspace, buildWorkspace);
task.setWorkspace(ws);
boolean clean = buildWorkspace.act(task);
logger.info("clean: " + clean);
return clean;
}
@Override
public DescriptorImpl getDescriptor() {
return (DescriptorImpl) super.getDescriptor();
}
/**
* The relationship of Descriptor and SCM (the describable) is akin to class
* and object. What this means is that the descriptor is used to create
* instances of the describable. Usually the Descriptor is an internal class
* in the SCM class named DescriptorImpl. The Descriptor should also contain
* the global configuration options as fields, just like the SCM class
* contains the configurations options for a job.
*
* @author pallen
*/
@Extension
public static class DescriptorImpl extends SCMDescriptor<PerforceScm> {
private boolean autoSave;
private String credential;
private String clientName;
private String depotPath;
private boolean deleteClient;
private boolean deleteFiles;
private boolean hideTicket;
private int maxFiles;
private int maxChanges;
public boolean isAutoSave() {
return autoSave;
}
public String getCredential() {
return credential;
}
public String getClientName() {
return clientName;
}
public String getDepotPath() {
return depotPath;
}
public boolean isDeleteClient() {
return deleteClient;
}
public boolean isDeleteFiles() {
return deleteFiles;
}
public boolean isHideTicket() {
return hideTicket;
}
public int getMaxFiles() {
return maxFiles;
}
public int getMaxChanges() {
return maxChanges;
}
/**
* public no-argument constructor
*/
public DescriptorImpl() {
super(PerforceScm.class, P4Browser.class);
load();
}
/**
* Returns the name of the SCM, this is the name that will show up next
* to CVS and Subversion when configuring a job.
*/
@Override
public String getDisplayName() {
return "Perforce Software";
}
@Override
public boolean isApplicable(Job project) {
return true;
}
@Override
public SCM newInstance(StaplerRequest req, JSONObject formData) throws FormException {
PerforceScm scm = (PerforceScm) super.newInstance(req, formData);
return scm;
}
/**
* The configure method is invoked when the global configuration page is
* submitted. In the method the data in the web form should be copied to
* the Descriptor's fields. To persist the fields to the global
* configuration XML file, the save() method must be called. Data is
* defined in the global.jelly page.
*/
@Override
public boolean configure(StaplerRequest req, JSONObject json) throws FormException {
try {
autoSave = json.getBoolean("autoSave");
credential = json.getString("credential");
clientName = json.getString("clientName");
depotPath = json.getString("depotPath");
} catch (JSONException e) {
logger.info("Unable to read Auto Version configuration.");
autoSave = false;
}
try {
deleteClient = json.getBoolean("deleteClient");
deleteFiles = json.getBoolean("deleteFiles");
} catch (JSONException e) {
logger.info("Unable to read client cleanup configuration.");
deleteClient = false;
deleteFiles = false;
}
try {
hideTicket = json.getBoolean("hideTicket");
} catch (JSONException e) {
logger.info("Unable to read TICKET security configuration.");
hideTicket = false;
}
try {
maxFiles = json.getInt("maxFiles");
maxChanges = json.getInt("maxChanges");
} catch (JSONException e) {
logger.info("Unable to read Max limits in configuration.");
maxFiles = 50;
maxChanges = 10;
}
save();
return true;
}
/**
* Credentials list, a Jelly config method for a build job.
*
* @return A list of Perforce credential items to populate the jelly
* Select list.
*/
public ListBoxModel doFillCredentialItems(@AncestorInPath Item project, @QueryParameter String credential) {
return P4CredentialsImpl.doFillCredentialItems(project, credential);
}
public FormValidation doCheckCredential(@AncestorInPath Item project, @QueryParameter String value) {
return P4CredentialsImpl.doCheckCredential(project, value);
}
}
/**
* This methods determines if the SCM plugin can be used for polling
*/
@Override
public boolean supportsPolling() {
return true;
}
/**
* This method should return true if the SCM requires a workspace for
* polling. Perforce however can report submitted, pending and shelved
* changes without needing a workspace
*/
@Override
public boolean requiresWorkspaceForPolling() {
return false;
}
/**
* Helper: find the Remote/Local Computer used for build
*
* @param workspace
*/
private static Computer workspaceToComputer(FilePath workspace) {
Jenkins jenkins = Jenkins.getInstance();
if (workspace != null && workspace.isRemote()) {
for (Computer computer : jenkins.getComputers()) {
if (computer.getChannel() == workspace.getChannel()) {
return computer;
}
}
}
return null;
}
/**
* Helper: find the Node for slave build or return current instance.
*
* @param workspace
*/
private static Node workspaceToNode(FilePath workspace) {
Computer computer = workspaceToComputer(workspace);
if (computer != null) {
return computer.getNode();
}
Jenkins jenkins = Jenkins.getInstance();
return jenkins;
}
/**
* Incremental polling filter is set
*
* @return true if set
*/
private boolean isIncremental() {
if (filter != null) {
for (Filter f : filter) {
if (f instanceof FilterPerChangeImpl) {
if (((FilterPerChangeImpl) f).isPerChange()) {
return true;
}
}
}
}
return false;
}
}
|
package org.jenkinsci.remoting;
import hudson.remoting.Callable;
import java.util.Collection;
/**
* Used by {@link Callable}-like objects to designate the intended recipient of the callable,
* to help verify callables are running in JVMs that it is intended to run.
*
* <p>
* This interface is defined separately from {@link Callable} so that other callable-like interfaces
* can reuse this.
*
* @author Kohsuke Kawaguchi
* @see RoleChecker
* @since TODO
*/
public interface RoleSensitive {
void checkRoles(RoleChecker checker) throws SecurityException;
}
|
package org.jtrfp.trcl.core;
import org.jtrfp.trcl.mem.MemoryWindow;
public class TextureTOCWindow extends MemoryWindow {
public static final int WIDTH_IN_SUBTEXTURES=19;
//19^2 * 4 = 1444 bytes
public final IntArrayVariable subtextureAddrsVec4 = new IntArrayVariable(361);
public final ByteArrayVariable filler0 = new ByteArrayVariable(12);//12 bytes to quantize to next VEC4
//Offset 1456B, 91VEC4
public final IntVariable width = new IntVariable();
public final IntVariable height = new IntVariable();
public final IntVariable startTile = new IntVariable();
//Tally: 1468B
public final ByteArrayVariable unused = new ByteArrayVariable(68);//68B
public TextureTOCWindow(TR tr){
this.init(tr, "TextureTOCWindow");
}//end constructor
}//end TextureTOCWindow
|
package org.mitre.synthea.export;
import static org.mitre.synthea.export.ExportHelper.dateFromTimestamp;
import static org.mitre.synthea.export.ExportHelper.iso8601Timestamp;
import com.google.gson.JsonObject;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.sis.geometry.DirectPosition2D;
import org.mitre.synthea.engine.Event;
import org.mitre.synthea.helpers.FactTable;
import org.mitre.synthea.helpers.Utilities;
import org.mitre.synthea.modules.Immunizations;
import org.mitre.synthea.world.agents.Person;
import org.mitre.synthea.world.agents.Provider;
import org.mitre.synthea.world.concepts.Costs;
import org.mitre.synthea.world.concepts.HealthRecord;
import org.mitre.synthea.world.concepts.HealthRecord.CarePlan;
import org.mitre.synthea.world.concepts.HealthRecord.Code;
import org.mitre.synthea.world.concepts.HealthRecord.Encounter;
import org.mitre.synthea.world.concepts.HealthRecord.EncounterType;
import org.mitre.synthea.world.concepts.HealthRecord.Entry;
import org.mitre.synthea.world.concepts.HealthRecord.ImagingStudy;
import org.mitre.synthea.world.concepts.HealthRecord.Immunization;
import org.mitre.synthea.world.concepts.HealthRecord.Medication;
import org.mitre.synthea.world.concepts.HealthRecord.Observation;
import org.mitre.synthea.world.concepts.HealthRecord.Procedure;
import org.mitre.synthea.world.geography.Location;
public class CDWExporter {
/**
* Table key sequence generators.
*/
private Map<FileWriter,AtomicInteger> sids;
private FactTable maritalStatus = new FactTable();
private FactTable sta3n = new FactTable();
private FactTable location = new FactTable();
// private FactTable appointmentStatus = new FactTable();
// private FactTable appointmentType = new FactTable();
private FactTable immunizationName = new FactTable();
private FactTable localDrug = new FactTable();
private FactTable nationalDrug = new FactTable();
private FactTable dosageForm = new FactTable();
private FactTable pharmacyOrderableItem = new FactTable();
/**
* Writers for patient data.
*/
private FileWriter lookuppatient;
private FileWriter spatient;
private FileWriter spatientaddress;
private FileWriter spatientphone;
private FileWriter patientrace;
private FileWriter patientethnicity;
/**
* Writers for encounter data.
*/
private FileWriter consult;
private FileWriter visit;
private FileWriter appointment;
private FileWriter inpatient;
/**
* Writers for immunization data.
*/
private FileWriter immunization;
/**
* Writers for allergy data.
*/
private FileWriter allergy;
private FileWriter allergycomment;
/**
* Writers for condition data.
*/
private FileWriter problemlist;
private FileWriter vdiagnosis;
/**
* Writers for medications data.
*/
private FileWriter rxoutpatient;
/**
* System-dependent string for a line break. (\n on Mac, *nix, \r\n on Windows)
*/
private static final String NEWLINE = System.lineSeparator();
/**
* Constructor for the CDWExporter -
* initialize the required files and associated writers.
*/
private CDWExporter() {
sids = new HashMap<FileWriter,AtomicInteger>();
try {
File output = Exporter.getOutputFolder("cdw", null);
output.mkdirs();
Path outputDirectory = output.toPath();
// Patient Data
lookuppatient = openFileWriter(outputDirectory, "lookuppatient.csv");
spatient = openFileWriter(outputDirectory, "spatient.csv");
spatientaddress = openFileWriter(outputDirectory, "spatientaddress.csv");
spatientphone = openFileWriter(outputDirectory, "spatientphone.csv");
patientrace = openFileWriter(outputDirectory, "patientrace.csv");
patientethnicity = openFileWriter(outputDirectory, "patientethnicity.csv");
// Encounter Data
consult = openFileWriter(outputDirectory, "consult.csv");
visit = openFileWriter(outputDirectory, "visit.csv");
appointment = openFileWriter(outputDirectory, "appointment.csv");
inpatient = openFileWriter(outputDirectory, "inpatient.csv");
// Immunization Data
immunization = openFileWriter(outputDirectory, "immunization.csv");
// Allergy Data
allergy = openFileWriter(outputDirectory, "allergy.csv");
allergycomment = openFileWriter(outputDirectory, "allergycomment.csv");
// Condition Data
problemlist = openFileWriter(outputDirectory, "problemlist.csv");
vdiagnosis = openFileWriter(outputDirectory, "vdiagnosis.csv");
// Medications Data
rxoutpatient = openFileWriter(outputDirectory, "rxoutpatient.csv");
writeCSVHeaders();
} catch (IOException e) {
// wrap the exception in a runtime exception.
// the singleton pattern below doesn't work if the constructor can throw
// and if these do throw ioexceptions there's nothing we can do anyway
throw new RuntimeException(e);
}
}
private FileWriter openFileWriter(Path outputDirectory, String filename) throws IOException {
File file = outputDirectory.resolve(filename).toFile();
return new FileWriter(file);
}
/**
* Write the headers to each of the CSV files.
* @throws IOException if any IO error occurs
*/
private void writeCSVHeaders() throws IOException {
// Fact Tables
maritalStatus.setHeader("MaritalStatusSID,MaritalStatusCode");
sta3n.setHeader("Sta3n,Sta3nName,TimeZone");
location.setHeader("LocationSID,LocationName");
immunizationName.setHeader("ImmunizationNameSID,ImmunizationName,CVXCode,MaxInSeries");
localDrug.setHeader("LocalDrugSID,LocalDrugIEN,Sta3n,LocalDrugNameWithDose,"
+ "NationalDrugSID,NationalDrugNameWithDose");
nationalDrug.setHeader("NationalDrugSID,DrugNameWithDose,DosageFormSID,"
+ "InactivationDate,VUID");
dosageForm.setHeader("DosageFormSID,DosageFormIEN,DosageForm");
pharmacyOrderableItem.setHeader("PharmacyOrderableItemSID,PharmacyOrderableItem,SupplyFlag");
// Patient Tables
lookuppatient.write("PatientSID,Sta3n,PatientIEN,PatientICN,PatientFullCN,"
+ "PatientName,TestPatient");
lookuppatient.write(NEWLINE);
spatient.write("PatientSID,PatientName,PatientLastName,PatientFirstName,PatientSSN,Age,"
+ "BirthDateTime,DeceasedFlag,DeathDateTime,Gender,SelfIdentifiedGender,Religion,"
+ "MaritalStatus,MaritalStatusSID,PatientEnteredDateTime");
spatient.write(NEWLINE);
spatientaddress.write("SPatientAddressSID,PatientSID,AddressType,NameOfContact,"
+ "RelationshipToPatient,StreetAddress1,StreetAddress2,StreetAddress3,"
+ "City,State,Zip,Country,GISMatchScore,GISStreetSide,"
+ "GISPatientAddressLongitude,GISPatientAddressLatitude,GISFIPSCode");
spatientaddress.write(NEWLINE);
spatientphone.write("SPatientPhoneSID,PatientSID,PatientContactType,NameOfContact,"
+ "RelationshipToPatient,PhoneNumber,WorkPhoneNumber,EmailAddress");
spatientphone.write(NEWLINE);
patientrace.write("PatientRaceSID,PatientSID,Race");
patientrace.write(NEWLINE);
patientethnicity.write("PatientEthnicitySID,PatientSID,Ethnicity");
patientethnicity.write(NEWLINE);
// Encounter Tables
consult.write("ConsultSID,ToRequestServiceSID");
consult.write(NEWLINE);
visit.write("VisitSID,VisitDateTime,CreatedByStaffSID,LocationSID,PatientSID");
visit.write(NEWLINE);
appointment.write("AppointmentSID,Sta3n,PatientSID,AppointmentDateTime,AppointmentMadeDate,"
+ "AppointmentTypeSID,AppointmentStatus,VisitSID,LocationSID,PurposeOfVisit,"
+ "SchedulingRequestType,FollowUpVisitFlag,LengthOfAppointment,ConsultSID,"
+ "CheckInDateTime,CheckOutDateTime");
appointment.write(NEWLINE);
inpatient.write("InpatientSID,PatientSID,AdmitDateTime");
inpatient.write(NEWLINE);
// Immunization Table
immunization.write("ImmunizationSID,ImmunizationIEN,Sta3n,PatientSID,ImmunizationNameSID,"
+ "Series,Reaction,VisitDateTime,ImmunizationDateTime,OrderingStaffSID,ImmunizingStaffSID,"
+ "VisitSID,ImmunizationComments,ImmunizationRemarks");
immunization.write(NEWLINE);
// Allergy Tables
allergy.write("AllergySID,AllergyIEN,Sta3n,PatientSID,AllergyType,AllergicReactant,"
+ "LocalDrugSID,DrugNameWithoutDoseSID,DrugClassSID,ReactantSID,DrugIngredientSID,"
+ "OriginationDateTime,OriginatingStaffSID,ObservedHistorical,Mechanism,VerifiedFlag,"
+ "VerificatiionDateTime,VerifyingStaffSID,EnteredInErrorFlag");
allergy.write(NEWLINE);
allergycomment.write("AllergyCommentSID,AllergyIEN,Sta3n,PatientSID,OriginationDateTime,"
+ "EnteringStaffSID,AllergyComment");
allergycomment.write(NEWLINE);
// Condition Tables
problemlist.write("ProblemListSID,Sta3n,ICD9SID,ICD10SID,PatientSID,ProviderNarrativeSID,"
+ "EnteredDateTime,OnsetDateTime,ProblemListCondition,RecordingProviderSID,"
+ "ResolvedDateTime,SNOMEDCTConceptCode");
problemlist.write(NEWLINE);
vdiagnosis.write("VDiagnosisSID,Sta3n,ICD9SID,ICD10SID,PatientSID,VisitSID,"
+ "VisitDateTime,VDiagnosisDateTime,ProviderNarrativeSID,ProblemListSID,"
+ "OrderingProviderSID,EncounterProviderSID");
vdiagnosis.write(NEWLINE);
// Medications Tables
rxoutpatient.write("RxOutpatSID,Sta3n,RxNumber,IssueDate,CancelDate,FinishingDateTime,"
+ "PatientSID,ProviderSID,EnteredByStaffSID,LocalDrugSID,NationalDrugSID,"
+ "PharmacyOrderableItemSID,MaxRefills,RxStatus,OrderedQuantity");
rxoutpatient.write(NEWLINE);
}
private static class SingletonHolder {
/**
* Singleton instance of the CDWExporter.
*/
private static final CDWExporter instance = new CDWExporter();
}
/**
* Get the current instance of the CDWExporter.
* @return the current instance of the CDWExporter.
*/
public static CDWExporter getInstance() {
return SingletonHolder.instance;
}
/**
* Add a single Person's health record info to the CSV records.
* @param person Person to write record data for
* @param time Time the simulation ended
* @throws IOException if any IO error occurs
*/
public void export(Person person, long time) throws IOException {
// TODO Ignore civilians, only consider the veteran population.
// if (!person.attributes.containsKey("veteran")) {
// return;
int primarySta3n = -1;
Provider provider = person.getAmbulatoryProvider(time);
if (provider != null) {
String state = Location.getStateName(provider.state);
String tz = Location.getTimezoneByState(state);
primarySta3n = sta3n.addFact(provider.id, clean(provider.name) + "," + tz);
}
int personID = patient(person, primarySta3n, time);
for (Encounter encounter : person.record.encounters) {
int encounterID = encounter(personID, person, encounter);
for (HealthRecord.Entry condition : encounter.conditions) {
condition(personID, encounterID, encounter, condition);
}
for (HealthRecord.Entry allergy : encounter.allergies) {
allergy(personID, person, encounterID, encounter, allergy);
}
for (Observation observation : encounter.observations) {
observation(personID, encounterID, observation);
}
for (Procedure procedure : encounter.procedures) {
procedure(personID, encounterID, procedure);
}
for (Medication medication : encounter.medications) {
medication(personID, encounterID, encounter, medication);
}
for (Immunization immunization : encounter.immunizations) {
immunization(personID, person, encounterID, encounter, immunization);
}
for (CarePlan careplan : encounter.careplans) {
careplan(personID, encounterID, careplan);
}
for (ImagingStudy imagingStudy : encounter.imagingStudies) {
imagingStudy(personID, encounterID, imagingStudy);
}
}
// Patient Data
lookuppatient.flush();
spatient.flush();
spatientaddress.flush();
spatientphone.flush();
patientrace.flush();
patientethnicity.flush();
// Encounter Data
consult.flush();
visit.flush();
appointment.flush();
inpatient.flush();
// Immunization Data
immunization.flush();
// Allergy Data
allergy.flush();
allergycomment.flush();
// Condition Data
problemlist.flush();
vdiagnosis.flush();
}
/**
* Fact Tables should only be written after all patients have completed export.
*/
public void writeFactTables() {
try {
File output = Exporter.getOutputFolder("cdw", null);
output.mkdirs();
Path outputDirectory = output.toPath();
maritalStatus.write(openFileWriter(outputDirectory,"maritalstatus.csv"));
sta3n.write(openFileWriter(outputDirectory,"sta3n.csv"));
location.write(openFileWriter(outputDirectory,"location.csv"));
immunizationName.write(openFileWriter(outputDirectory,"immunizationname.csv"));
localDrug.write(openFileWriter(outputDirectory,"localdrug.csv"));
nationalDrug.write(openFileWriter(outputDirectory,"nationaldrug.csv"));
dosageForm.write(openFileWriter(outputDirectory,"dosageform.csv"));
pharmacyOrderableItem.write(openFileWriter(outputDirectory,"pharmacyorderableitem.csv"));
} catch (IOException e) {
// wrap the exception in a runtime exception.
// the singleton pattern below doesn't work if the constructor can throw
// and if these do throw ioexceptions there's nothing we can do anyway
throw new RuntimeException(e);
}
}
/**
* Record a Patient.
*
* @param person Person to write data for
* @param sta3n The primary station ID for this patient
* @param time Time the simulation ended, to calculate age/deceased status
* @return the patient's ID, to be referenced as a "foreign key" if necessary
* @throws IOException if any IO error occurs
*/
private int patient(Person person, int sta3n, long time) throws IOException {
// Generate full name and ID
StringBuilder s = new StringBuilder();
if (person.attributes.containsKey(Person.NAME_PREFIX)) {
s.append(person.attributes.get(Person.NAME_PREFIX)).append(' ');
}
s.append(person.attributes.get(Person.FIRST_NAME)).append(' ');
s.append(person.attributes.get(Person.LAST_NAME));
if (person.attributes.containsKey(Person.NAME_SUFFIX)) {
s.append(' ').append(person.attributes.get(Person.NAME_SUFFIX));
}
String patientName = s.toString();
int personID = getNextKey(spatient);
// lookuppatient.write("PatientSID,Sta3n,PatientIEN,PatientICN,PatientFullCN,"
// + "PatientName,TestPatient");
s.setLength(0);
s.append(personID).append(',');
s.append(sta3n).append(',');
s.append(personID).append(',');
s.append(personID).append(',');
s.append(personID).append(',');
s.append(patientName).append(",1");
s.append(NEWLINE);
write(s.toString(), lookuppatient);
// spatient.write("PatientSID,PatientName,PatientLastName,PatientFirstName,PatientSSN,Age,"
// + "BirthDateTime,DeceasedFlag,DeathDateTime,Gender,SelfIdentifiedGender,Religion,"
// + "MaritalStatus,MaritalStatusSID,PatientEnteredDateTime");
s.setLength(0);
s.append(personID).append(',');
s.append(patientName);
s.append(',').append(clean((String) person.attributes.getOrDefault(Person.LAST_NAME, "")));
s.append(',').append(clean((String) person.attributes.getOrDefault(Person.FIRST_NAME, "")));
s.append(',').append(clean((String) person.attributes.getOrDefault(Person.IDENTIFIER_SSN, "")));
boolean alive = person.alive(time);
int age = 0;
if (alive) {
age = person.ageInYears(time);
} else {
age = person.ageInYears(person.events.event(Event.DEATH).time);
}
s.append(',').append(age);
s.append(',').append(iso8601Timestamp((long) person.attributes.get(Person.BIRTHDATE)));
if (alive) {
s.append(',').append('N').append(',');
} else {
s.append(',').append('Y');
s.append(',').append(iso8601Timestamp(person.events.event(Event.DEATH).time));
}
if (person.attributes.get(Person.GENDER).equals("M")) {
s.append(",M,Male");
} else {
s.append(",F,Female");
}
s.append(",None"); // Religion
// Currently there are no divorces or widows
String marital = ((String) person.attributes.get(Person.MARITAL_STATUS));
if (marital != null) {
if (marital.equals("M")) {
s.append(",Married");
} else {
marital = "N";
s.append(",Never Married");
}
} else {
marital = "U";
s.append(",Unknown");
}
s.append(',').append(maritalStatus.addFact(marital, marital));
// TODO Need an enlistment date or date they became a veteran.
s.append(',').append(iso8601Timestamp(time - Utilities.convertTime("years", 10)));
s.append(NEWLINE);
write(s.toString(), spatient);
// spatientaddress.write("SPatientAddressSID,PatientSID,AddressType,NameOfContact,"
// + "RelationshipToPatient,StreetAddress1,StreetAddress2,StreetAddress3,"
// + "City,State,Zip,Country,GISMatchScore,GISStreetSide,"
// + "GISPatientAddressLongitude,GISPatientAddressLatitude,GISFIPSCode");
s.setLength(0);
s.append(getNextKey(spatientaddress)).append(',');
s.append(personID).append(',');
s.append("Legal Residence").append(',');
s.append(person.attributes.get(Person.FIRST_NAME)).append(' ');
s.append(person.attributes.get(Person.LAST_NAME)).append(',');
s.append("Self").append(',');
s.append(person.attributes.get(Person.ADDRESS)).append(",,,");
s.append(person.attributes.get(Person.CITY)).append(',');
s.append(person.attributes.get(Person.STATE)).append(',');
s.append(person.attributes.get(Person.ZIP)).append(",USA,,,");
DirectPosition2D coord = (DirectPosition2D) person.attributes.get(Person.COORDINATE);
if (coord != null) {
s.append(coord.x).append(',').append(coord.y).append(',');
} else {
s.append(",,");
}
s.append(NEWLINE);
write(s.toString(), spatientaddress);
//spatientphone.write("SPatientPhoneSID,PatientSID,PatientContactType,NameOfContact,"
// + "RelationshipToPatient,PhoneNumber,WorkPhoneNumber,EmailAddress");
s.setLength(0);
s.append(getNextKey(spatientphone)).append(',');
s.append(personID).append(',');
s.append("Patient Cell Phone").append(',');
s.append(person.attributes.get(Person.FIRST_NAME)).append(' ');
s.append(person.attributes.get(Person.LAST_NAME)).append(',');
s.append("Self").append(',');
s.append(person.attributes.get(Person.TELECOM)).append(",,");
s.append(NEWLINE);
write(s.toString(), spatientphone);
if (person.random.nextBoolean()) {
// Add an email address
s.setLength(0);
s.append(getNextKey(spatientphone)).append(',');
s.append(personID).append(',');
s.append("Patient Email").append(',');
s.append(person.attributes.get(Person.FIRST_NAME)).append(' ');
s.append(person.attributes.get(Person.LAST_NAME)).append(',');
s.append("Self").append(',');
s.append(",,");
s.append(person.attributes.get(Person.FIRST_NAME)).append('.');
s.append(person.attributes.get(Person.LAST_NAME)).append("@email.example");
s.append(NEWLINE);
write(s.toString(), spatientphone);
}
//patientrace.write("PatientRaceSID,PatientSID,Race");
String race = (String) person.attributes.get(Person.RACE);
if (race.equals("white")) {
race = "WHITE NOT OF HISP ORIG";
} else if (race.equals("hispanic")) {
race = "WHITE";
} else if (race.equals("black")) {
race = "BLACK OR AFRICAN AMERICAN";
} else if (race.equals("asian")) {
race = "ASIAN";
} else if (race.equals("native")) {
if (person.attributes.get(Person.STATE).equals("Hawaii")) {
race = "NATIVE HAWAIIAN OR OTHER PACIFIC ISLANDER";
} else {
race = "AMERICAN INDIAN OR ALASKA NATIVE";
}
} else { // race.equals("other")
race = "ASIAN";
}
s.setLength(0);
s.append(getNextKey(patientrace)).append(',');
s.append(personID).append(',');
s.append(race);
s.append(NEWLINE);
write(s.toString(), patientrace);
//patientethnicity.write("PatientEthnicitySID,PatientSID,Ethnicity");
s.setLength(0);
s.append(getNextKey(patientethnicity)).append(',');
s.append(personID).append(',');
race = (String) person.attributes.get(Person.RACE);
if (race.equals("hispanic")) {
s.append("HISPANIC OR LATINO");
} else {
s.append("NOT HISPANIC OR LATINO");
}
s.append(NEWLINE);
write(s.toString(), patientethnicity);
return personID;
}
/**
* Write a single Encounter line to encounters.csv.
*
* @param personID The ID of the person that had this encounter
* @param person The person attending the encounter
* @param encounter The encounter itself
* @return The encounter ID, to be referenced as a "foreign key" if necessary
* @throws IOException if any IO error occurs
*/
private int encounter(int personID, Person person, Encounter encounter) throws IOException {
StringBuilder s = new StringBuilder();
// consult.write("ConsultSID,ToRequestServiceSID");
int consultSid = getNextKey(consult);
s.append(consultSid).append(',').append(consultSid).append(NEWLINE);
write(s.toString(), consult);
// visit.write("VisitSID,VisitDateTime,CreatedByStaffSID,LocationSID,PatientSID");
int visitSid = getNextKey(visit);
s.setLength(0);
s.append(visitSid).append(',');
s.append(iso8601Timestamp(encounter.start)).append(',');
s.append(','); // CreatedByStaffID == null
Integer locationSid = null;
if (encounter.provider != null) {
locationSid = location.addFact(encounter.provider.id, clean(encounter.provider.name));
s.append(locationSid).append(',');
} else {
s.append(',');
}
s.append(personID);
s.append(NEWLINE);
write(s.toString(), visit);
// appointment.write("AppointmentSID,Sta3n,PatientSID,AppointmentDateTime,AppointmentMadeDate,"
// + "AppointmentTypeSID,AppointmentStatus,VisitSID,LocationSID,PurposeOfVisit,"
// + "SchedulingRequestType,FollowUpVisitFlag,LengthOfAppointment,ConsultSID,"
// + "CheckInDateTime,CheckOutDateTime");
s.setLength(0);
s.append(getNextKey(appointment)).append(',');
if (encounter.provider != null) {
String state = Location.getStateName(encounter.provider.state);
String tz = Location.getTimezoneByState(state);
s.append(sta3n.addFact(encounter.provider.id, clean(encounter.provider.name) + "," + tz));
}
s.append(',');
s.append(personID).append(',');
s.append(iso8601Timestamp(encounter.start)).append(',');
s.append(iso8601Timestamp(encounter.start)).append(',');
s.append(",,"); // skip: AppointmentTypeSID, AppointmentStatus
s.append(visitSid).append(',');
if (locationSid != null) {
s.append(locationSid).append(',');
} else {
s.append(",");
}
s.append("3,"); // 3:SCHEDULED VISIT
s.append(person.rand(new String[] {"N", "C", "P", "W", "M", "A", "O"})).append(',');
s.append(person.randInt(1)).append(',');
s.append((encounter.stop - encounter.start) / (60 * 1000)).append(',');
s.append(consultSid).append(',');
s.append(iso8601Timestamp(encounter.start)).append(',');
s.append(iso8601Timestamp(encounter.stop)).append(NEWLINE);
write(s.toString(), appointment);
if (encounter.type.equalsIgnoreCase(EncounterType.INPATIENT.toString())) {
// inpatient.write("InpatientSID,PatientSID,AdmitDateTime");
s.setLength(0);
s.append(getNextKey(inpatient)).append(',');
s.append(personID).append(',');
s.append(iso8601Timestamp(encounter.start)).append(NEWLINE);
write(s.toString(), inpatient);
}
return visitSid;
}
/**
* Write a single Condition to conditions.csv.
*
* @param personID ID of the person that has the condition.
* @param encounterID ID of the encounter where the condition was diagnosed
* @param encounter The encounter
* @param condition The condition itself
* @throws IOException if any IO error occurs
*/
private void condition(int personID, int encounterID, Encounter encounter,
Entry condition) throws IOException {
StringBuilder s = new StringBuilder();
Integer sta3nValue = null;
if (encounter.provider != null) {
String state = Location.getStateName(encounter.provider.state);
String tz = Location.getTimezoneByState(state);
sta3nValue = sta3n.addFact(encounter.provider.id, clean(encounter.provider.name) + "," + tz);
}
// problemlist.write("ProblemListSID,Sta3n,ICD9SID,ICD10SID,PatientSID,ProviderNarrativeSID,"
// + "EnteredDateTime,OnsetDateTime,ProblemListCondition,RecordingProviderSID,"
// + "ResolvedDateTime,SNOMEDCTConceptCode");
int problemListSid = getNextKey(problemlist);
s.append(problemListSid).append(',');
if (sta3nValue != null) {
s.append(sta3nValue);
}
s.append(',');
s.append(",,"); // skip icd 9 and icd 10
s.append(personID).append(',');
s.append(','); // provider narrative -- history of present illness
s.append(iso8601Timestamp(encounter.start)).append(',');
s.append(iso8601Timestamp(condition.start)).append(',');
s.append("P,");
s.append("-1,");
if (condition.stop != 0L) {
s.append(iso8601Timestamp(condition.stop));
}
s.append(',');
s.append(condition.codes.get(0).code);
s.append(NEWLINE);
write(s.toString(), problemlist);
// vdiagnosis.write("VDiagnosisSID,Sta3n,ICD9SID,ICD10SID,PatientSID,VisitSID,"
// + "VisitDateTime,VDiagnosisDateTime,ProviderNarrativeSID,ProblemListSID,"
// + "OrderingProviderSID,EncounterProviderSID");
s.setLength(0);
s.append(getNextKey(vdiagnosis));
s.append(',');
if (sta3nValue != null) {
s.append(sta3nValue);
}
s.append(',');
s.append(",,"); // skip icd 9 and icd 10
s.append(personID).append(',');
s.append(encounterID).append(',');
s.append(iso8601Timestamp(encounter.start)).append(',');
s.append(iso8601Timestamp(condition.start)).append(',');
s.append(','); // provider narrative -- history of present illness
s.append(problemListSid).append(',');
s.append("-1,");
s.append("-1");
s.append(NEWLINE);
write(s.toString(), vdiagnosis);
}
/**
* Write a single Allergy to allergies.csv.
*
* @param personID ID of the person that has the allergy.
* @param person The person
* @param encounterID ID of the encounter where the allergy was diagnosed
* @param encounter The encounter
* @param allergyEntry The allergy itself
* @throws IOException if any IO error occurs
*/
private void allergy(int personID, Person person, int encounterID, Encounter encounter,
Entry allergyEntry) throws IOException {
StringBuilder s = new StringBuilder();
Integer sta3nValue = null;
if (encounter.provider != null) {
String state = Location.getStateName(encounter.provider.state);
String tz = Location.getTimezoneByState(state);
sta3nValue = sta3n.addFact(encounter.provider.id, clean(encounter.provider.name) + "," + tz);
}
Code code = allergyEntry.codes.get(0);
boolean food = code.display.matches(".*(nut|peanut|milk|dairy|eggs|shellfish|wheat).*");
// allergy.write("AllergySID,AllergyIEN,Sta3n,PatientSID,AllergyType,AllergicReactant,"
// + "LocalDrugSID,DrugNameWithoutDoseSID,DrugClassSID,ReactantSID,DrugIngredientSID,"
// + "OriginationDateTime,OriginatingStaffSID,ObservedHistorical,Mechanism,VerifiedFlag,"
// + "VerificatiionDateTime,VerifyingStaffSID,EnteredInErrorFlag");
int allergySID = getNextKey(allergy);
s.append(allergySID).append(',');
s.append(allergySID).append(',');
if (encounter.provider != null) {
s.append(sta3nValue);
}
s.append(',');
s.append(personID).append(',');
if (food) {
s.append('F').append(','); // F: Food allergy
} else {
s.append('O').append(','); // O: Other
}
s.append(','); // AllergicReactant
s.append(','); // LocalDrugSID
s.append(','); // DrugNameWithoutDoseSID
s.append(','); // DrugClassSID
s.append(','); // ReactantSID
s.append(','); // DrugIngredientSID
s.append(iso8601Timestamp(allergyEntry.start)).append(',');
s.append("-1,");
s.append(person.rand(new String[] {"o", "h"})).append(',');
s.append("A,");
s.append("1,"); // Verified
s.append(iso8601Timestamp(allergyEntry.start)).append(',');
s.append("-1,");
s.append(',');
s.append(NEWLINE);
write(s.toString(), allergy);
// allergycomment.write("AllergyCommentSID,AllergyIEN,Sta3n,PatientSID,OriginationDateTime,"
// + "EnteringStaffSID,AllergyComment");
s.setLength(0);
int allergyCommentSid = getNextKey(allergycomment);
s.append(allergyCommentSid).append(',');
s.append(allergyCommentSid).append(',');
if (encounter.provider != null) {
s.append(sta3nValue);
}
s.append(',');
s.append(personID).append(',');
s.append(iso8601Timestamp(allergyEntry.start)).append(',');
s.append("-1,");
s.append(clean(code.display));
s.append(NEWLINE);
write(s.toString(), allergycomment);
}
/**
* Write a single Observation to observations.csv.
*
* @param personID ID of the person to whom the observation applies.
* @param encounterID ID of the encounter where the observation was taken
* @param observation The observation itself
* @throws IOException if any IO error occurs
*/
private void observation(int personID, int encounterID,
Observation observation) throws IOException {
if (observation.value == null) {
if (observation.observations != null && !observation.observations.isEmpty()) {
// just loop through the child observations
for (Observation subObs : observation.observations) {
observation(personID, encounterID, subObs);
}
}
// no value so nothing more to report here
return;
}
// DATE,PATIENT,ENCOUNTER,CODE,DESCRIPTION,VALUE,UNITS
StringBuilder s = new StringBuilder();
s.append(dateFromTimestamp(observation.start)).append(',');
s.append(personID).append(',');
s.append(encounterID).append(',');
Code coding = observation.codes.get(0);
s.append(coding.code).append(',');
s.append(clean(coding.display)).append(',');
String value = ExportHelper.getObservationValue(observation);
String type = ExportHelper.getObservationType(observation);
s.append(value).append(',');
s.append(observation.unit).append(',');
s.append(type);
s.append(NEWLINE);
//write(s.toString(), observations);
}
/**
* Write a single Procedure to procedures.csv.
*
* @param personID ID of the person on whom the procedure was performed.
* @param encounterID ID of the encounter where the procedure was performed
* @param procedure The procedure itself
* @throws IOException if any IO error occurs
*/
private void procedure(int personID, int encounterID,
Procedure procedure) throws IOException {
// DATE,PATIENT,ENCOUNTER,CODE,DESCRIPTION,COST,REASONCODE,REASONDESCRIPTION
StringBuilder s = new StringBuilder();
s.append(dateFromTimestamp(procedure.start)).append(',');
s.append(personID).append(',');
s.append(encounterID).append(',');
Code coding = procedure.codes.get(0);
s.append(coding.code).append(',');
s.append(clean(coding.display)).append(',');
s.append(String.format("%.2f", Costs.calculateCost(procedure, true))).append(',');
if (procedure.reasons.isEmpty()) {
s.append(','); // reason code & desc
} else {
Code reason = procedure.reasons.get(0);
s.append(reason.code).append(',');
s.append(clean(reason.display));
}
s.append(NEWLINE);
//write(s.toString(), procedures);
}
/**
* Write a single Medication to medications.csv.
*
* @param personID ID of the person prescribed the medication.
* @param encounterID ID of the encounter where the medication was prescribed
* @param encounter The encounter
* @param medication The medication itself
* @throws IOException if any IO error occurs
*/
private void medication(int personID, int encounterID, Encounter encounter,
Medication medication) throws IOException {
StringBuilder s = new StringBuilder();
Integer sta3nValue = null;
if (encounter.provider != null) {
String state = Location.getStateName(encounter.provider.state);
String tz = Location.getTimezoneByState(state);
sta3nValue = sta3n.addFact(encounter.provider.id, clean(encounter.provider.name) + "," + tz);
}
Code code = medication.codes.get(0);
// pharmacyOrderableItem ("PharmacyOrderableItemSID,PharmacyOrderableItem,SupplyFlag");
int pharmSID = pharmacyOrderableItem.addFact(code.code, clean(code.display) + ",1");
// dosageForm.setHeader("DosageFormSID,DosageFormIEN,DosageForm");
Integer dosageSID = null;
if (medication.prescriptionDetails != null
&& medication.prescriptionDetails.has("dosage")) {
JsonObject dosage = medication.prescriptionDetails.get("dosage").getAsJsonObject();
s.setLength(0);
s.append(dosage.get("amount").getAsInt());
s.append(" dose(s) ");
s.append(dosage.get("frequency").getAsInt());
s.append(" time(s) per ");
s.append(dosage.get("period").getAsInt());
s.append(" ");
s.append(dosage.get("unit").getAsString());
dosageSID = dosageForm.addFact(code.code, pharmSID + "," + s.toString());
}
// nationalDrug.setHeader("NationalDrugSID,DrugNameWithDose,DosageFormSID,"
// + "InactivationDate,VUID");
s.setLength(0);
s.append(clean(code.display));
s.append(',');
if (dosageSID != null) {
s.append(dosageSID);
}
s.append(",,");
s.append(code.code);
int ndrugSID = nationalDrug.addFact(code.code, s.toString());
// localDrug.setHeader("LocalDrugSID,LocalDrugIEN,Sta3n,LocalDrugNameWithDose,"
// + "NationalDrugSID,NationalDrugNameWithDose");
s.setLength(0);
s.append(ndrugSID).append(',');
if (sta3nValue != null) {
s.append(sta3nValue);
}
s.append(',');
s.append(clean(code.display)).append(',');
s.append(ndrugSID).append(',');
s.append(clean(code.display));
int ldrugSID = localDrug.addFact(code.code, s.toString());
// rxoutpatient.write("RxOutpatSID,Sta3n,RxNumber,IssueDate,CancelDate,FinishingDateTime,"
// + "PatientSID,ProviderSID,EnteredByStaffSID,LocalDrugSID,NationalDrugSID,"
// + "PharmacyOrderableItemSID,MaxRefills,RxStatus,OrderedQuantity");
s.setLength(0);
int rxNum = getNextKey(rxoutpatient);
s.append(rxNum).append(',');
if (sta3nValue != null) {
s.append(sta3nValue);
}
s.append(',');
s.append(rxNum).append(',');
s.append(iso8601Timestamp(medication.start)).append(',');
if (medication.stop != 0L) {
s.append(iso8601Timestamp(medication.stop));
}
s.append(',');
if (medication.prescriptionDetails != null
&& medication.prescriptionDetails.has("duration")) {
JsonObject duration = medication.prescriptionDetails.get("duration").getAsJsonObject();
long time = Utilities.convertTime(
duration.get("unit").getAsString(), duration.get("quantity").getAsLong());
s.append(iso8601Timestamp(medication.start + time));
}
s.append(',');
s.append(personID).append(',');
s.append("-1,"); // Provider
s.append("-1,"); // Entered by staff
s.append(ldrugSID).append(',');
s.append(ndrugSID).append(',');
s.append(pharmSID).append(',');
if (medication.prescriptionDetails != null
&& medication.prescriptionDetails.has("refills")) {
s.append(medication.prescriptionDetails.get("refills").getAsInt());
}
s.append(',');
if (medication.stop == 0L) {
s.append("0,"); // Active
} else {
s.append("10,"); // Done
}
s.append(NEWLINE);
write(s.toString(), rxoutpatient);
}
/**
* Write a single Immunization to immunizations.csv.
*
* @param personID ID of the person on whom the immunization was performed.
* @param person The person
* @param encounterID ID of the encounter where the immunization was performed
* @param encounter The encounter itself
* @param immunization The immunization itself
* @throws IOException if any IO error occurs
*/
private void immunization(int personID, Person person, int encounterID, Encounter encounter,
Immunization immunizationEntry) throws IOException {
StringBuilder s = new StringBuilder();
// immunization.write("ImmunizationSID,ImmunizationIEN,Sta3n,PatientSID,ImmunizationNameSID,"
// + "Series,Reaction,VisitDateTime,ImmunizationDateTime,OrderingStaffSID,ImmunizingStaffSID,"
// + "VisitSID,ImmunizationComments,ImmunizationRemarks");
int immunizationSid = getNextKey(immunization);
s.append(immunizationSid).append(',');
s.append(immunizationSid).append(','); // ImmunizationIEN
if (encounter.provider != null) {
String state = Location.getStateName(encounter.provider.state);
String tz = Location.getTimezoneByState(state);
s.append(sta3n.addFact(encounter.provider.id, clean(encounter.provider.name) + "," + tz));
}
s.append(',');
s.append(personID).append(',');
Code cvx = immunizationEntry.codes.get(0);
int maxInSeries = Immunizations.getMaximumDoses(cvx.code);
s.append(
immunizationName.addFact(
cvx.code, clean(cvx.display) + "," + cvx.code + "," + maxInSeries));
int series = immunizationEntry.series;
if (series == maxInSeries) {
s.append(",C,");
} else {
s.append(",B,");
}
s.append(person.randInt(12)).append(','); // Reaction
s.append(iso8601Timestamp(immunizationEntry.start)).append(',');
s.append(iso8601Timestamp(immunizationEntry.start)).append(',');
s.append("-1,-1,");
s.append(encounterID).append(',');
// Comment
s.append("Dose #" + series + " of " + maxInSeries + " of "
+ clean(cvx.display) + " vaccine administered.,");
// Remark
s.append("Dose #" + series + " of " + maxInSeries + " of "
+ clean(cvx.display) + " vaccine administered.");
s.append(NEWLINE);
write(s.toString(), immunization);
}
/**
* Write a single CarePlan to careplans.csv.
*
* @param personID ID of the person prescribed the careplan.
* @param encounterID ID of the encounter where the careplan was prescribed
* @param careplan The careplan itself
* @throws IOException if any IO error occurs
*/
private String careplan(int personID, int encounterID,
CarePlan careplan) throws IOException {
// ID,START,STOP,PATIENT,ENCOUNTER,CODE,DESCRIPTION,REASONCODE,REASONDESCRIPTION
StringBuilder s = new StringBuilder();
String careplanID = UUID.randomUUID().toString();
s.append(careplanID).append(',');
s.append(dateFromTimestamp(careplan.start)).append(',');
if (careplan.stop != 0L) {
s.append(dateFromTimestamp(careplan.stop));
}
s.append(',');
s.append(personID).append(',');
s.append(encounterID).append(',');
Code coding = careplan.codes.get(0);
s.append(coding.code).append(',');
s.append(coding.display).append(',');
if (careplan.reasons.isEmpty()) {
s.append(','); // reason code & desc
} else {
Code reason = careplan.reasons.get(0);
s.append(reason.code).append(',');
s.append(clean(reason.display));
}
s.append(NEWLINE);
//write(s.toString(), careplans);
return careplanID;
}
/**
* Write a single ImagingStudy to imaging_studies.csv.
*
* @param personID ID of the person the ImagingStudy was taken of.
* @param encounterID ID of the encounter where the ImagingStudy was performed
* @param imagingStudy The ImagingStudy itself
* @throws IOException if any IO error occurs
*/
private String imagingStudy(int personID, int encounterID,
ImagingStudy imagingStudy) throws IOException {
// ID,DATE,PATIENT,ENCOUNTER,BODYSITE_CODE,BODYSITE_DESCRIPTION,
// MODALITY_CODE,MODALITY_DESCRIPTION,SOP_CODE,SOP_DESCRIPTION
StringBuilder s = new StringBuilder();
String studyID = UUID.randomUUID().toString();
s.append(studyID).append(',');
s.append(dateFromTimestamp(imagingStudy.start)).append(',');
s.append(personID).append(',');
s.append(encounterID).append(',');
ImagingStudy.Series series1 = imagingStudy.series.get(0);
ImagingStudy.Instance instance1 = series1.instances.get(0);
Code bodySite = series1.bodySite;
Code modality = series1.modality;
Code sopClass = instance1.sopClass;
s.append(bodySite.code).append(',');
s.append(bodySite.display).append(',');
s.append(modality.code).append(',');
s.append(modality.display).append(',');
s.append(sopClass.code).append(',');
s.append(sopClass.display);
s.append(NEWLINE);
//write(s.toString(), imagingStudies);
return studyID;
}
private int getNextKey(FileWriter table) {
synchronized (sids) {
return sids.computeIfAbsent(table, k -> new AtomicInteger(1)).getAndIncrement();
}
}
/**
* Replaces commas and line breaks in the source string with a single space.
* Null is replaced with the empty string.
*/
private static String clean(String src) {
if (src == null) {
return "";
} else {
return src.replaceAll("\\r\\n|\\r|\\n|,", " ").trim();
}
}
/**
* Helper method to write a line to a File.
* Extracted to a separate method here to make it a little easier to replace implementations.
*
* @param line The line to write
* @param writer The place to write it
* @throws IOException if an I/O error occurs
*/
private static void write(String line, FileWriter writer) throws IOException {
synchronized (writer) {
writer.write(line);
writer.flush();
}
}
}
|
package org.mvel.math;
import org.mvel.CompileException;
import org.mvel.ConversionException;
import org.mvel.DataTypes;
import org.mvel.Operator;
import org.mvel.util.ParseTools;
import static org.mvel.util.ParseTools.resolveType;
import static org.mvel.util.PropertyTools.isNumber;
import static java.lang.String.valueOf;
import java.math.BigDecimal;
import java.math.BigInteger;
/**
* @author Christopher Brock
*/
public class JDK14CompatabilityMath implements MathProcessor {
public static final int ROUND_MODE = BigDecimal.ROUND_CEILING;
public static final int SCALE = 128;
public Object doOperation(Object val1, int operation, Object val2) {
int type1 = val1 == null ? DataTypes.NULL : resolveType(val1.getClass());
int type2 = val2 == null ? DataTypes.NULL : resolveType(val2.getClass());
if (type1 == DataTypes.BIG_DECIMAL) {
if (type2 == DataTypes.BIG_DECIMAL) {
return doBigDecimalArithmetic((BigDecimal) val1, operation, (BigDecimal) val2);
}
else if (type2 > 99) {
return doBigDecimalArithmetic((BigDecimal) val1, operation, getBigDecimalFromType(val2, type2));
}
else {
return _doOperations(type1, val1, operation, type2, val2);
}
}
else if (type2 == DataTypes.BIG_DECIMAL && (type1 > 99 || (type1 == DataTypes.STRING && isNumber(val1)))) {
return doBigDecimalArithmetic(getBigDecimalFromType(val1, type1), operation, (BigDecimal) val2);
}
else {
return _doOperations(type1, val1, operation, type2, val2);
}
}
private static Object doBigDecimalArithmetic(BigDecimal val1, int operation, BigDecimal val2) {
switch (operation) {
case Operator.ADD:
return val1.add(val2);
case Operator.DIV:
return val1.divide(val2, SCALE, ROUND_MODE);
case Operator.SUB:
return val1.subtract(val2);
case Operator.MULT:
return val1.multiply(val2);
case Operator.POWER:
return Math.pow(val1.doubleValue(), val2.doubleValue());
case Operator.MOD:
return val1.doubleValue() % val2.doubleValue();
case Operator.GTHAN:
return val1.compareTo(val2) == 1;
case Operator.GETHAN:
return val1.compareTo(val2) >= 0;
case Operator.LTHAN:
return val1.compareTo(val2) == -1;
case Operator.LETHAN:
return val1.compareTo(val2) <= 0;
case Operator.EQUAL:
return val1.compareTo(val2) == 0;
case Operator.NEQUAL:
return val1.compareTo(val2) != 0;
}
return null;
}
private static Object _doOperations(int type1, Object val1, int operation, int type2, Object val2) {
if (operation < 10 || operation == Operator.EQUAL || operation == Operator.NEQUAL) {
if (type1 > 99 && type1 == type2) {
return doOperationsSameType(type1, val1, operation, val2);
}
else if ((type1 > 99 && (type2 > 99)) || (isNumber(val1) && isNumber(val2))) {
return doBigDecimalArithmetic(getBigDecimalFromType(val1, type1), operation, getBigDecimalFromType(val2, type2));
}
}
return doOperationNonNumeric(val1, operation, val2);
}
private static Object doOperationNonNumeric(Object val1, int operation, Object val2) {
switch (operation) {
case Operator.ADD:
return valueOf(val1) + valueOf(val2);
case Operator.EQUAL:
return safeEquals(val2, val1);
case Operator.NEQUAL:
return safeNotEquals(val2, val1);
case Operator.SUB:
case Operator.DIV:
case Operator.MULT:
case Operator.MOD:
case Operator.GTHAN:
case Operator.GETHAN:
case Operator.LTHAN:
case Operator.LETHAN:
throw new CompileException("could not perform numeric operation on non-numeric types: left-type="
+ (val1 != null ? val1.getClass().getName() : "null") + "; right-type=" + (val2 != null ? val2.getClass().getName() : "null"));
}
throw new CompileException("unable to perform operation");
}
private static Boolean safeEquals(Object val1, Object val2) {
if (val1 != null) {
return val1.equals(val2);
}
else if (val2 != null) {
return val2.equals(val1);
}
else {
return val1 == val2;
}
}
private static Boolean safeNotEquals(Object val1, Object val2) {
if (val1 != null) {
return !val1.equals(val2);
}
else return val2 != null && !val2.equals(val1);
}
private static Object doOperationsSameType(int type1, Object val1, int operation, Object val2) {
switch (type1) {
case DataTypes.INTEGER:
case DataTypes.W_INTEGER:
switch (operation) {
case Operator.ADD:
return ((Integer) val1) + ((Integer) val2);
case Operator.SUB:
return ((Integer) val1) - ((Integer) val2);
case Operator.DIV:
return new BigDecimal((Integer) val1).divide(new BigDecimal((Integer) val2), SCALE, ROUND_MODE);
case Operator.MULT:
return ((Integer) val1) * ((Integer) val2);
case Operator.POWER:
double d = Math.pow((Integer) val1, (Integer) val2);
if (d > Integer.MAX_VALUE) return d;
else return (int) d;
case Operator.MOD:
return ((Integer) val1) % ((Integer) val2);
case Operator.GTHAN:
return ((Integer) val1) > ((Integer) val2);
case Operator.GETHAN:
return ((Integer) val1) >= ((Integer) val2);
case Operator.LTHAN:
return ((Integer) val1) < ((Integer) val2);
case Operator.LETHAN:
return ((Integer) val1) <= ((Integer) val2);
case Operator.EQUAL:
return ((Integer) val1).intValue() == ((Integer) val2).intValue();
case Operator.NEQUAL:
return ((Integer) val1).intValue() != ((Integer) val2).intValue();
}
case DataTypes.SHORT:
case DataTypes.W_SHORT:
switch (operation) {
case Operator.ADD:
return ((Short) val1) + ((Short) val2);
case Operator.SUB:
return ((Short) val1) - ((Short) val2);
case Operator.DIV:
return new BigDecimal((Short) val1).divide(new BigDecimal((Short) val2), SCALE, ROUND_MODE);
case Operator.MULT:
return ((Short) val1) * ((Short) val2);
case Operator.POWER:
double d = Math.pow((Short) val1, (Short) val2);
if (d > Short.MAX_VALUE) return d;
else return (short) d;
case Operator.MOD:
return ((Short) val1) % ((Short) val2);
case Operator.GTHAN:
return ((Short) val1) > ((Short) val2);
case Operator.GETHAN:
return ((Short) val1) >= ((Short) val2);
case Operator.LTHAN:
return ((Short) val1) < ((Short) val2);
case Operator.LETHAN:
return ((Short) val1) <= ((Short) val2);
case Operator.EQUAL:
return ((Short) val1).shortValue() == ((Short) val2).shortValue();
case Operator.NEQUAL:
return ((Short) val1).shortValue() != ((Short) val2).shortValue();
}
case DataTypes.LONG:
case DataTypes.W_LONG:
switch (operation) {
case Operator.ADD:
return ((Long) val1) + ((Long) val2);
case Operator.SUB:
return ((Long) val1) - ((Long) val2);
case Operator.DIV:
return new BigDecimal((Long) val1).divide(new BigDecimal((Long) val2), SCALE, ROUND_MODE);
case Operator.MULT:
return ((Long) val1) * ((Long) val2);
case Operator.POWER:
double d = Math.pow((Long) val1, (Long) val2);
if (d > Long.MAX_VALUE) return d;
else return (long) d;
case Operator.MOD:
return ((Long) val1) % ((Long) val2);
case Operator.GTHAN:
return ((Long) val1) > ((Long) val2);
case Operator.GETHAN:
return ((Long) val1) >= ((Long) val2);
case Operator.LTHAN:
return ((Long) val1) < ((Long) val2);
case Operator.LETHAN:
return ((Long) val1) <= ((Long) val2);
case Operator.EQUAL:
return ((Long) val1).longValue() == ((Long) val2).longValue();
case Operator.NEQUAL:
return ((Long) val1).longValue() != ((Long) val2).longValue();
}
case DataTypes.DOUBLE:
case DataTypes.W_DOUBLE:
switch (operation) {
case Operator.ADD:
return ((Double) val1) + ((Double) val2);
case Operator.SUB:
return ((Double) val1) - ((Double) val2);
case Operator.DIV:
return new BigDecimal((Double) val1).divide(new BigDecimal((Double) val2), SCALE, ROUND_MODE);
case Operator.MULT:
return ((Double) val1) * ((Double) val2);
case Operator.POWER:
return Math.pow((Double) val1, (Double) val2);
case Operator.MOD:
return ((Double) val1) % ((Double) val2);
case Operator.GTHAN:
return ((Double) val1) > ((Double) val2);
case Operator.GETHAN:
return ((Double) val1) >= ((Double) val2);
case Operator.LTHAN:
return ((Double) val1) < ((Double) val2);
case Operator.LETHAN:
return ((Double) val1) <= ((Double) val2);
case Operator.EQUAL:
return ((Double) val1).doubleValue() == ((Double) val2).doubleValue();
case Operator.NEQUAL:
return ((Double) val1).doubleValue() != ((Double) val2).doubleValue();
}
case DataTypes.FLOAT:
case DataTypes.W_FLOAT:
switch (operation) {
case Operator.ADD:
return ((Float) val1) + ((Float) val2);
case Operator.SUB:
return ((Float) val1) - ((Float) val2);
case Operator.DIV:
return new BigDecimal((Float) val1).divide(new BigDecimal((Float) val2), SCALE, ROUND_MODE);
case Operator.MULT:
return ((Float) val1) * ((Float) val2);
case Operator.POWER:
Math.pow( (Float) val1, (Float) val2 );
case Operator.MOD:
return ((Float) val1) % ((Float) val2);
case Operator.GTHAN:
return ((Float) val1) > ((Float) val2);
case Operator.GETHAN:
return ((Float) val1) >= ((Float) val2);
case Operator.LTHAN:
return ((Float) val1) < ((Float) val2);
case Operator.LETHAN:
return ((Float) val1) <= ((Float) val2);
case Operator.EQUAL:
return ((Float) val1).floatValue() == ((Float) val2).floatValue();
case Operator.NEQUAL:
return ((Float) val1).floatValue() != ((Float) val2).floatValue();
}
case DataTypes.BIG_INTEGER:
switch (operation) {
case Operator.ADD:
return ((BigInteger) val1).add(((BigInteger) val2));
case Operator.SUB:
return ((BigInteger) val1).subtract(((BigInteger) val2));
case Operator.DIV:
return ((BigInteger) val1).divide(((BigInteger) val2));
case Operator.MULT:
return ((BigInteger) val1).multiply(((BigInteger) val2));
case Operator.POWER:
return ((BigInteger) val1).pow(((BigInteger) val2).intValue());
case Operator.MOD:
return ((BigInteger) val1).remainder(((BigInteger) val2));
case Operator.GTHAN:
return ((BigInteger) val1).compareTo(((BigInteger) val2)) == 1;
case Operator.GETHAN:
return ((BigInteger) val1).compareTo(((BigInteger) val2)) >= 0;
case Operator.LTHAN:
return ((BigInteger) val1).compareTo(((BigInteger) val2)) == -1;
case Operator.LETHAN:
return ((BigInteger) val1).compareTo(((BigInteger) val2)) <= 0;
case Operator.EQUAL:
return ((BigInteger) val1).compareTo(((BigInteger) val2)) == 0;
case Operator.NEQUAL:
return ((BigInteger) val1).compareTo(((BigInteger) val2)) != 0;
}
default:
switch (operation) {
case Operator.EQUAL:
return safeEquals(val2, val1);
case Operator.NEQUAL:
return safeNotEquals(val2, val1);
case Operator.ADD:
return valueOf(val1) + valueOf(val2);
}
}
return null;
}
public static BigDecimal getBigDecimalFromType(Object in, int type) {
if (in == null)
return new BigDecimal(0);
switch (type) {
case DataTypes.BIG_DECIMAL:
return (BigDecimal) in;
case DataTypes.BIG_INTEGER:
return new BigDecimal((BigInteger) in);
case DataTypes.W_INTEGER:
return BigDecimal.valueOf((Integer) in);
case DataTypes.W_LONG:
return BigDecimal.valueOf((Long) in);
case DataTypes.STRING:
return new BigDecimal((String) in);
case DataTypes.W_FLOAT:
return new BigDecimal((Float) in);
case DataTypes.W_DOUBLE:
return new BigDecimal((Double) in);
case DataTypes.W_SHORT:
return BigDecimal.valueOf((Short) in);
}
throw new ConversionException("cannot convert <" + in + "> to a numeric type");
}
}
|
package org.openforis.ceo.env;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import spark.servlet.SparkFilter;
public class CeoSparkFilter extends SparkFilter {
// Read context parameters from webapp/WEB-INF/web.xml
public void init(FilterConfig filterConfig) throws ServletException {
var context = filterConfig.getServletContext();
CeoConfig.documentRoot = context.getInitParameter("documentRoot");
CeoConfig.databaseType = context.getInitParameter("databaseType");
CeoConfig.baseUrl = context.getInitParameter("baseUrl");
CeoConfig.smtpUser = context.getInitParameter("smtpUser");
CeoConfig.smtpServer = context.getInitParameter("smtpServer");
CeoConfig.smtpPort = context.getInitParameter("smtpPort");
CeoConfig.smtpPassword = context.getInitParameter("smtpPassword");
CeoConfig.smtpRecipientLimit = context.getInitParameter("smtpRecipientLimit");
CeoConfig.mailingListInterval = context.getInitParameter("mailingListInterval");
super.init(filterConfig);
}
}
|
package org.orbeon.oxf.xforms.function;
import org.orbeon.dom.QName;
import org.orbeon.oxf.common.OXFException;
import org.orbeon.oxf.xforms.XFormsContainingDocument;
import org.orbeon.oxf.xforms.event.XFormsEvent;
import org.orbeon.oxf.xml.dom4j.Dom4jUtils;
import org.orbeon.saxon.expr.*;
import org.orbeon.saxon.om.EmptyIterator;
import org.orbeon.saxon.om.NamespaceResolver;
import org.orbeon.saxon.om.SequenceIterator;
import org.orbeon.saxon.trans.XPathException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
/**
* 2.4 Accessing Context Information for Events
*
* This is the event() function which returns "context specific information" for an event.
*/
public class Event extends XFormsFunction {
private Map<String, String> namespaceMappings;
@Override
public SequenceIterator iterate(XPathContext xpathContext) throws XPathException {
// Get parameter name
final Expression instanceIdExpression = argument[0];
final String attributeName = instanceIdExpression.evaluateAsString(xpathContext).toString();
// Get the current event
// TODO: getContainingDocument(xpathContext) can be null in tests
final XFormsContainingDocument doc = getContainingDocument(xpathContext);
if (doc == null) {
return EmptyIterator.getInstance();
} else {
final XFormsEvent event = doc.getCurrentEvent();
if (event == null) {
return EmptyIterator.getInstance();
} else {
return getEventAttribute(event, attributeName);
}
}
}
@Override
public int getIntrinsicDependencies() {
// So that Saxon doesn't try to evaluate us at compile-time
return StaticProperty.DEPENDS_ON_RUNTIME_ENVIRONMENT;
}
private SequenceIterator getEventAttribute(XFormsEvent event, String attributeName) {
// As an extension, we allow a QName
// NOTE: Here the idea is to find the namespaces in scope. We assume that the expression occurs on an XForms
// element. There are other ways of obtaining the namespaces, for example we could extract them from the static
// state.
// final Element element = getContextStack(xpathContext).getCurrentBindingContext().getControlElement();
// final Map namespaceMappings = containingDocument(xpathContext).getStaticState().getNamespaceMappings(element);
final QName attributeQName = Dom4jUtils.extractTextValueQName(namespaceMappings, attributeName, true);
// Simply ask the event for the attribute
return event.getAttribute(Dom4jUtils.qNameToExplodedQName(attributeQName));
}
// The following copies StaticContext namespace information
@Override
public void checkArguments(ExpressionVisitor visitor) throws XPathException {
// See also Saxon Evaluate.java
if (namespaceMappings == null) { // only do this once
final StaticContext env = visitor.getStaticContext();
super.checkArguments(visitor);
namespaceMappings = new HashMap<String, String>();
final NamespaceResolver namespaceResolver = env.getNamespaceResolver();
for (Iterator iterator = namespaceResolver.iteratePrefixes(); iterator.hasNext();) {
final String prefix = (String) iterator.next();
if (!"".equals(prefix)) {
final String uri = namespaceResolver.getURIForPrefix(prefix, true);
namespaceMappings.put(prefix, uri);
}
}
}
}
}
|
package org.petapico.nanopub.indexer;
import java.io.IOException;
import java.io.InputStream;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.zip.GZIPInputStream;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClientBuilder;
import org.nanopub.MultiNanopubRdfHandler;
import org.nanopub.Nanopub;
import org.nanopub.NanopubUtils;
import org.nanopub.MultiNanopubRdfHandler.NanopubHandler;
import org.nanopub.extra.server.GetNanopub;
import org.nanopub.extra.server.NanopubServerUtils;
import org.nanopub.extra.server.ServerInfo;
import org.nanopub.extra.server.ServerIterator;
import org.openrdf.model.Resource;
import org.openrdf.model.Statement;
import org.openrdf.model.URI;
import org.openrdf.model.Value;
import org.openrdf.rio.RDFFormat;
import org.openrdf.rio.RDFHandlerException;
public class Indexer {
public static final int SECTION_HEAD = 1;
public static final int SECTION_ASSERTION = 2;
public static final int SECTION_PROVENANCE = 3;
public static final int SECTION_PUBINFO = 4;
NanopubDatabase db = null;
public static List<Nanopub> nanopubs; //used by the callback function of the MultiNanopubRdfHandler class -> can we do this better?
public static void main(String[] args) {
args = new String[3];
args[0] = "root";
args[1] = "admin";
args[2] = "true";
if (args.length < 2){
System.out.printf("Invalid arguments expected: dbusername, dbpassword\n");
System.exit(1);
}
while (true){
try {
Indexer indexer = new Indexer(args[0], args[1]);
indexer.run();
}
catch (Exception E){
System.out.println("Run error");
System.out.println(E.getMessage());
}
// sleep ?
}
}
public Indexer(String dbusername, String dbpassword) throws ClassNotFoundException, SQLException {
db = new NanopubDatabase(dbusername, dbpassword);
}
public void run() throws IOException, RDFHandlerException, Exception {
ServerIterator serverIterator = new ServerIterator();
while (serverIterator.hasNext()) {
ServerInfo si = serverIterator.next();
String serverName = si.getPublicUrl();
System.out.println("==========");
System.out.println("Server: " + serverName + "\n");
//retrieve server information (from server)
int peerPageSize = si.getPageSize(); //nanopubs per page
long peerNanopubNo = si.getNextNanopubNo(); //number of np's stored on the server
long peerJid = si.getJournalId(); //journal identifier of the server
System.out.printf("Info:\n %d peerpagesize\n %d peernanopubno\n %d peerjid\n\n", peerPageSize, peerNanopubNo, peerJid);
//retrieve stored server information (from database)
long dbNanopubNo = db.getNextNanopubNo(serverName); //number of np's stored according to db
long dbJid = db.getJournalId(serverName); //journal identifier according to db
System.out.printf("Db:\n %d dbnanopubno\n %d dbjid\n", dbNanopubNo, dbJid);
System.out.println("==========\n");
//Start from the beginning
if (dbJid != peerJid) {
dbNanopubNo = 0;
db.updateJournalId(serverName, peerJid);
}
long currentNanopub = dbNanopubNo;
System.out.printf("Starting from: %d\n", currentNanopub);
long start = System.currentTimeMillis();
try {
while (currentNanopub < peerNanopubNo){
int addedNanopubs = 0;
int page = (int) (currentNanopub / peerPageSize) + 1; // compute the starting page
System.out.printf("comp: %d-%d < %d\n", peerNanopubNo, currentNanopub, peerPageSize);
if ((peerNanopubNo - currentNanopub) < peerPageSize) {
System.out.println("last bits");
List<String> nanopubsOnPage = NanopubServerUtils.loadNanopubUriList(si, page);
for (String artifactCode : nanopubsOnPage) {
Nanopub np = GetNanopub.get(artifactCode);
int insertStatus = db.npInserted(artifactCode);
if (insertStatus == -1){ // not inserted
insertNpInDatabase(np, artifactCode, false);
}
else if (insertStatus == 0){ // started but not finished
insertNpInDatabase(np, artifactCode, true);
}
addedNanopubs ++;
}
}
else {
addedNanopubs = insertNanopubsFromPage(page, serverName); // add all nanopubs from page
}
currentNanopub += addedNanopubs;
if (addedNanopubs < peerPageSize && currentNanopub < peerNanopubNo) {
System.out.println("ERROR not enough nanopubs found on page: " + page);
break;
}
System.out.printf("page: %d (%d/%d)\n",page, currentNanopub, peerNanopubNo);
}
}
catch (Exception E){
System.out.println( "ERROR" );
System.out.println(E.getMessage());
}
finally {
System.out.println( "Updating database ") ;
db.updateNextNanopubNo(serverName, currentNanopub);
}
long end = System.currentTimeMillis();
System.out.printf("performance estimate: %d hours\n", ((end-start))/(1000 * 60 * 24));
}
}
public int insertNanopubsFromPage(int page, String server) throws Exception{
int coveredNanopubs = 0;
getNanopubPackage(page, server); // fills the nanopub list
if (nanopubs.size() == 0) {
System.out.println("ERROR no nanopubs found on page " + page);
return 0;
}
for (Nanopub np : nanopubs) {
String artifactCode = np.getUri().toString();
int insertStatus = db.npInserted(artifactCode);
if (insertStatus == -1){ // not inserted
insertNpInDatabase(np, artifactCode, false);
}
else if (insertStatus == 0){ // started but not finished
//System.out.printf("ignore insert: %s\n", artifactCode);
insertNpInDatabase(np, artifactCode, true);
}
coveredNanopubs ++;
}
return coveredNanopubs;
}
public int insertNpInDatabase(Nanopub np, String artifactCode, boolean ignore) throws IOException, SQLException{
int totalURIs = 0;
if (!ignore){
db.insertNp(artifactCode);
}
//totalURIs += insertStatementsInDB(np.getHead(), artifactCode, stmt, SECTION_HEAD);
totalURIs += insertStatementsInDB(np.getAssertion(), artifactCode, SECTION_ASSERTION, ignore);
totalURIs += insertStatementsInDB(np.getProvenance(), artifactCode, SECTION_PROVENANCE, ignore);
totalURIs += insertStatementsInDB(np.getPubinfo(), artifactCode, SECTION_PUBINFO, ignore);
db.updateNpFinished(artifactCode);
return totalURIs;
}
public int insertStatementsInDB(Set<Statement> statements, String artifactCode, int sectionID, boolean ignore) throws IOException, SQLException{
Set<String> URIlist = new HashSet<String>();
for (Statement statement : statements){
Value object = statement.getObject();
URI predicate = statement.getPredicate();
Resource subject = statement.getSubject();
if (object instanceof URI){
String objectStr = object.stringValue();
URIlist.add(objectStr);
}
if (subject instanceof URI){
String subjectStr = subject.stringValue();
URIlist.add(subjectStr);
}
String predicateStr = predicate.toString();
URIlist.add(predicateStr);
}
PreparedStatement stmt;
if (ignore){
stmt = db.getInsertIgnoreStmt();
}
else {
stmt = db.getInsertStmt();
}
stmt.setString(2, artifactCode);
stmt.setInt(3, sectionID);
//insert URIlist in database
for (String uri : URIlist){
stmt.setString(1, uri);
stmt.executeUpdate();
}
return URIlist.size();
}
public void getNanopubPackage(int page, String server) throws Exception{
nanopubs = new ArrayList<Nanopub>();
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(5 * 1000).build();
HttpClient c = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig).build();
String nanopubPackage = server + "package.gz?page=" + page;
HttpGet get = new HttpGet(nanopubPackage);
get.setHeader("Accept", "application/x-gzip");
HttpResponse resp = c.execute(get);
InputStream in = null;
try {
if (wasSuccessful(resp)) {
in = new GZIPInputStream(resp.getEntity().getContent());
} else {
System.out.println("Failed. Trying uncompressed package...");
// This is for compability with older versions; to be removed at some point...
get = new HttpGet(server + "package.gz?page=" + page);
get.setHeader("Accept", "application/trig");
resp = c.execute(get);
if (!wasSuccessful(resp)) {
System.out.println("HTTP request failed: " + resp.getStatusLine().getReasonPhrase());
throw new RuntimeException(resp.getStatusLine().getReasonPhrase());
}
in = resp.getEntity().getContent();
}
MultiNanopubRdfHandler.process(RDFFormat.TRIG, in, new NanopubHandler() {
@Override
public void handleNanopub(Nanopub np) {
try {
Indexer.nanopubs.add(np);
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
});
} finally {
if (in != null){
in.close();
}
}
}
private boolean wasSuccessful(HttpResponse resp) {
int c = resp.getStatusLine().getStatusCode();
return c >= 200 && c < 300;
}
}
|
package org.scijava.convert;
import org.scijava.Priority;
import org.scijava.plugin.Plugin;
import org.scijava.util.ClassUtils;
import org.scijava.util.ConversionUtils;
import org.scijava.util.GenericUtils;
/**
* Minimal {@link Converter} implementation to do direct casting.
*
* @author Mark Hiner hinerm at gmail.com
*/
@Plugin(type = Converter.class, priority = Priority.FIRST_PRIORITY)
public class CastingConverter extends AbstractConverter<Object, Object> {
@SuppressWarnings("deprecation")
@Override
public boolean canConvert(final Object src, final Class<?> dest) {
return ClassUtils.canCast(src, dest);
}
@Override
public boolean canConvert(final Class<?> src, final Class<?> dest) {
// OK if the existing object can be casted
if (ConversionUtils.canCast(src, dest))
return true;
return false;
}
@SuppressWarnings("unchecked")
@Override
public <T> T convert(final Object src, final Class<T> dest) {
// NB: Regardless of whether the destination type is an array or
// collection, we still want to cast directly if doing so is possible.
// But note that in general, this check does not detect cases of
// incompatible generic parameter types. If this limitation becomes a
// problem in the future we can extend the logic here to provide
// additional signatures of canCast which operate on Types in general
// rather than only Classes. However, the logic could become complex
// very quickly in various subclassing cases, generic parameters
// resolved vs. propagated, etc.
final Class<?> c = GenericUtils.getClass(dest);
return (T) ConversionUtils.cast(src, c);
}
@Override
public Class<Object> getOutputType() {
return Object.class;
}
@Override
public Class<Object> getInputType() {
return Object.class;
}
}
|
package org.scijava.convert;
import java.lang.reflect.Array;
import java.lang.reflect.Constructor;
import java.lang.reflect.Modifier;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.scijava.plugin.Plugin;
import org.scijava.util.ArrayUtils;
import org.scijava.util.ClassUtils;
import org.scijava.util.ConversionUtils;
import org.scijava.util.GenericUtils;
/**
* Default {@link Converter} implementation. Provides useful conversion
* functionality for many common conversion cases.
*
* @author Mark Hiner
*/
@Plugin(type = Converter.class)
public class DefaultConverter extends AbstractConverter<Object, Object> {
// -- ConversionHandler methods --
@Override
public Object convert(final Object src, final Type dest) {
// NB: Regardless of whether the destination type is an array or collection,
// we still want to cast directly if doing so is possible. But note that in
// general, this check does not detect cases of incompatible generic
// parameter types. If this limitation becomes a problem in the future we
// can extend the logic here to provide additional signatures of canCast
// which operate on Types in general rather than only Classes. However, the
// logic could become complex very quickly in various subclassing cases,
// generic parameters resolved vs. propagated, etc.
final Class<?> c = GenericUtils.getClass(dest);
if (c != null && ConversionUtils.canCast(src, c)) return ConversionUtils
.cast(src, c);
// Handle array types, including generic array types.
if (isArray(dest)) {
return convertToArray(src, GenericUtils.getComponentClass(dest));
}
// Handle parameterized collection types.
if (dest instanceof ParameterizedType && isCollection(dest)) {
return convertToCollection(src, (ParameterizedType) dest);
}
// This wasn't a collection or array, so convert it as a single element.
return convert(src, GenericUtils.getClass(dest));
}
@Override
public <T> T convert(final Object src, final Class<T> dest) {
if (dest == null) return null;
if (src == null) return ConversionUtils.getNullValue(dest);
// ensure type is well-behaved, rather than a primitive type
final Class<T> saneDest = ConversionUtils.getNonprimitiveType(dest);
// cast the existing object, if possible
if (ConversionUtils.canCast(src, saneDest)) return ConversionUtils.cast(
src, saneDest);
// Handle array types
if (isArray(dest)) {
@SuppressWarnings("unchecked")
T array = (T) convertToArray(src, GenericUtils.getComponentClass(dest));
return array;
}
// special case for conversion from number to number
if (src instanceof Number) {
final Number number = (Number) src;
if (saneDest == Byte.class) {
final Byte result = number.byteValue();
@SuppressWarnings("unchecked")
final T typedResult = (T) result;
return typedResult;
}
if (saneDest == Double.class) {
final Double result = number.doubleValue();
@SuppressWarnings("unchecked")
final T typedResult = (T) result;
return typedResult;
}
if (saneDest == Float.class) {
final Float result = number.floatValue();
@SuppressWarnings("unchecked")
final T typedResult = (T) result;
return typedResult;
}
if (saneDest == Integer.class) {
final Integer result = number.intValue();
@SuppressWarnings("unchecked")
final T typedResult = (T) result;
return typedResult;
}
if (saneDest == Long.class) {
final Long result = number.longValue();
@SuppressWarnings("unchecked")
final T typedResult = (T) result;
return typedResult;
}
if (saneDest == Short.class) {
final Short result = number.shortValue();
@SuppressWarnings("unchecked")
final T typedResult = (T) result;
return typedResult;
}
}
// special cases for strings
if (src instanceof String) {
// source type is String
final String s = (String) src;
if (s.isEmpty()) {
// return null for empty strings
return ConversionUtils.getNullValue(dest);
}
// use first character when converting to Character
if (saneDest == Character.class) {
final Character c = new Character(s.charAt(0));
@SuppressWarnings("unchecked")
final T result = (T) c;
return result;
}
// special case for conversion to enum
if (dest.isEnum()) {
final T result = ConversionUtils.convertToEnum(s, dest);
if (result != null) return result;
}
}
if (saneDest == String.class) {
// destination type is String; use Object.toString() method
final String sValue = src.toString();
@SuppressWarnings("unchecked")
final T result = (T) sValue;
return result;
}
// wrap the original object with one of the new type, using a constructor
try {
final Constructor<?> ctor = getConstructor(saneDest, src.getClass());
if (ctor == null) return null;
@SuppressWarnings("unchecked")
final T instance = (T) ctor.newInstance(src);
return instance;
}
catch (final Exception exc) {
// TODO: Best not to catch blanket Exceptions here.
// no known way to convert
return null;
}
}
@Override
public Class<Object> getOutputType() {
return Object.class;
}
@Override
public Class<Object> getInputType() {
return Object.class;
}
// -- Helper methods --
private Constructor<?> getConstructor(final Class<?> type,
final Class<?> argType)
{
for (final Constructor<?> ctor : type.getConstructors()) {
final Class<?>[] params = ctor.getParameterTypes();
if (params.length == 1 && ConversionUtils.canCast(argType, params[0])) {
return ctor;
}
}
return null;
}
private boolean isArray(final Type type) {
return GenericUtils.getComponentClass(type) != null;
}
private boolean isCollection(final Type type) {
return ConversionUtils.canCast(GenericUtils.getClass(type),
Collection.class);
}
private Object
convertToArray(final Object value, final Class<?> componentType)
{
// First we make sure the value is a collection. This provides the simplest
// interface for iterating over all the elements. We use SciJava's
// PrimitiveArray collection implementations internally, so that this
// conversion is always wrapping by reference, for performance.
final Collection<?> items = ArrayUtils.toCollection(value);
final Object array = Array.newInstance(componentType, items.size());
// Populate the array by converting each item in the value collection
// to the component type.
int index = 0;
for (final Object item : items) {
Array.set(array, index++, convert(item, componentType));
}
return array;
}
private Object convertToCollection(final Object value,
final ParameterizedType pType)
{
final Collection<Object> collection =
createCollection(GenericUtils.getClass(pType));
if (collection == null) return null;
// Populate the collection.
final Collection<?> items = ArrayUtils.toCollection(value);
// TODO: The following can fail; e.g. "Foo extends ArrayList<String>"
final Type collectionType = pType.getActualTypeArguments()[0];
for (final Object item : items) {
collection.add(convert(item, collectionType));
}
return collection;
}
private Collection<Object> createCollection(final Class<?> type) {
// If we were given an interface or abstract class, and not a concrete
// class, we attempt to make default implementations.
if (type.isInterface() || Modifier.isAbstract(type.getModifiers())) {
// We don't have a concrete class. If it's a set or a list, we use
// the typical default implementation. Otherwise we won't convert.
if (ConversionUtils.canCast(type, List.class)) return new ArrayList<Object>();
if (ConversionUtils.canCast(type, Set.class)) return new HashSet<Object>();
return null;
}
// Got a concrete type. Instantiate it.
try {
@SuppressWarnings("unchecked")
final Collection<Object> c = (Collection<Object>) type.newInstance();
return c;
}
catch (final InstantiationException exc) {
return null;
}
catch (final IllegalAccessException exc) {
return null;
}
}
// -- Deprecated API --
@Override
@Deprecated
public boolean canConvert(final Class<?> src, final Type dest) {
// Handle array types, including generic array types.
if (isArray(dest)) return true;
// Handle parameterized collection types.
if (dest instanceof ParameterizedType && isCollection(dest)) {
return createCollection(GenericUtils.getClass(dest)) != null;
}
return super.canConvert(src, dest);
}
@Override
@Deprecated
public boolean canConvert(final Class<?> src, final Class<?> dest) {
if (src == null || dest == null) return true;
// ensure type is well-behaved, rather than a primitive type
final Class<?> saneDest = ConversionUtils.getNonprimitiveType(dest);
// OK if the existing object can be casted
if (ConversionUtils.canCast(src, saneDest)) return true;
// OK for numerical conversions
if (ConversionUtils.canCast(ConversionUtils.getNonprimitiveType(src),
Number.class) &&
(ClassUtils.isByte(dest) || ClassUtils.isDouble(dest) ||
ClassUtils.isFloat(dest) || ClassUtils.isInteger(dest) ||
ClassUtils.isLong(dest) || ClassUtils.isShort(dest)))
{
return true;
}
// OK if string
if (saneDest == String.class) return true;
if (ConversionUtils.canCast(src, String.class)) {
// OK if source type is string and destination type is character
// (in this case, the first character of the string would be used)
if (saneDest == Character.class) return true;
// OK if source type is string and destination type is an enum
if (dest.isEnum()) return true;
}
// OK if appropriate wrapper constructor exists
try {
return getConstructor(saneDest, src) != null;
}
catch (final Exception exc) {
// TODO: Best not to catch blanket Exceptions here.
// no known way to convert
return false;
}
}
}
|
package org.tqdev.visarray;
import static org.lwjgl.opengl.GL11.*;
import java.awt.Font;
import java.io.FileOutputStream;
import java.net.URL;
import java.nio.FloatBuffer;
import java.util.ArrayList;
import java.util.List;
import org.lwjgl.BufferUtils;
import org.lwjgl.input.Mouse;
import org.lwjgl.util.vector.Matrix4f;
import org.lwjgl.util.vector.Vector2f;
import org.lwjgl.util.vector.Vector3f;
import org.newdawn.slick.UnicodeFont;
import org.newdawn.slick.font.effects.ColorEffect;
import org.tqdev.visarray.XMLParse.Cloud;
import org.tqdev.visarray.XMLParse.Mesh;
import org.tqdev.visarray.XMLParse.Model;
import org.tqdev.visarray.opengl.Viewport;
import de.schlichtherle.truezip.file.TArchiveDetector;
import de.schlichtherle.truezip.file.TConfig;
import de.schlichtherle.truezip.file.TFile;
import de.schlichtherle.truezip.fs.archive.zip.JarDriver;
import de.schlichtherle.truezip.io.Streams;
import de.schlichtherle.truezip.socket.sl.IOPoolLocator;
/**
*
* @author James Sweet
*/
public class DHARMAApplication implements VisApplication {
private double mFrameEnd = 0.0f, mFrameTime = 0.0f;
private Viewport mViewport = new Viewport();
private UnicodeFont font = new UnicodeFont(new Font("Times New Roman", Font.BOLD, 18));
// Rendering
private Processor ProcessData;
private Vector3f Background = new Vector3f( 0.0f, 0.0f, 0.0f );
// Camera
private float Radius = 0.0f;
private float Zoom = 0.0f;
private Vector2f Rotation = new Vector2f();
public void appletInit( List<String> parameters ) {
TConfig.get().setArchiveDetector( new TArchiveDetector( "dhz", new JarDriver(IOPoolLocator.SINGLETON)));
List<String> requested = Parameters();
for (int i = 0; i < requested.size(); i++) {
String param = requested.get(i);
System.out.println( "Parameter: " + param + " = " + parameters.get(i) );
}
try{
if( parameters.size() == 0 ){
System.err.println( "No arguments passed. Exiting." );
System.exit(1);
}else{
if( !parameters.get(0).isEmpty() ){
ProcessData = new Processor( parameters.get(0) );
}
if( !parameters.get(1).isEmpty() ){
String[] part = parameters.get(1).trim().split( "\\s+", 3 );
Background.x = Float.parseFloat( part[0] );
Background.y = Float.parseFloat( part[1] );
Background.z = Float.parseFloat( part[2] );
}
}
}catch( Exception e ){
System.err.println( "Error: " + e );
}
init();
}
public void applicationInit(String[] arguments) {
TConfig.get().setArchiveDetector( new TArchiveDetector( "dhz", new JarDriver(IOPoolLocator.SINGLETON)));
try{
if( arguments.length == 0 ){
System.err.println( "No arguments passed. Exiting." );
System.exit(1);
}else{
if( !arguments[0].isEmpty() ){
ProcessData = new Processor( arguments[0] );
}
}
}catch( Exception e ){
System.err.println( "Error: " + e );
}
init();
}
public void destroy(){
try {
ProcessData.join();
} catch (InterruptedException e) {
System.err.println( e );
}
}
private void init(){
try{
font.addAsciiGlyphs();
font.getEffects().add(new ColorEffect(java.awt.Color.white));
font.loadGlyphs();
}catch( Exception e ){
System.err.println( "Error Loading Font: " + e );
}
glShadeModel(GL_SMOOTH);
glEnable(GL_LIGHTING);
glEnable(GL_COLOR_MATERIAL);
FloatBuffer ambient = BufferUtils.createFloatBuffer(4);
ambient.put( 0.5f );
ambient.put( 0.5f );
ambient.put( 0.5f );
ambient.put( 1.0f );
ambient.rewind();
glLightModel(GL_LIGHT_MODEL_AMBIENT, ambient );
glClearColor( Background.x, Background.y, Background.z, 0.0f);
glClearDepth(1.0f);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
}
public void resize(final int width, final int height) {
glViewport(0, 0, width, height);
mViewport.size(width, height);
}
public void render() {
mFrameTime = System.currentTimeMillis() - mFrameEnd;
if( !ProcessData.isAlive() && !ProcessData.isProcessed() ) ProcessData.start();
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
processInput();
render3d();
render2d();
mFrameEnd = System.currentTimeMillis();
}
private void processInput(){
if (Mouse.isButtonDown(0)) {
int xDiff = Mouse.getDX();
int yDiff = Mouse.getDY();
// Dragged
if( xDiff != 0 || yDiff != 0 ){
Rotation.x += 0.01 * xDiff;
Rotation.y += 0.01 * yDiff;
}
}
if (Mouse.isButtonDown(1)) {
Rotation.x = 0.0f;
Rotation.y = 0.0f;
Zoom = 0.0f;
}
int wDiff = Mouse.getDWheel();
if( wDiff != 0 ){
Zoom += 0.01 * wDiff;
mViewport.clip(0.1f, Zoom-Radius );
}
}
private void render3d() {
mViewport.perspective();
glPushMatrix();
{
if( ProcessData.isProcessed() ){
List<Model> models = ProcessData.Parser().Models;
if( Math.abs( Radius ) < 0.00001f ){
Radius = (2*models.get(0).Radius);
mViewport.clip(0.1f, Zoom-Radius );
}
Matrix4f transform = new Matrix4f();
transform.translate( new Vector3f( 0.0f, 0.0f, Zoom-Radius ) );
transform.rotate(Rotation.x, new Vector3f( 0.0f, 1.0f, 0.0f ) );
transform.rotate(Rotation.y, new Vector3f( -1.0f, 0.0f, 0.0f ) );
FloatBuffer matrix = BufferUtils.createFloatBuffer(16);
transform.store(matrix);
matrix.rewind();
glMultMatrix( matrix );
for( Model m: models ){
glRotatef( 270.0f, 1.0f, 0.0f, 0.0f );
glTranslatef(-m.Center.x, -m.Center.y, -m.Center.z);
for( Mesh mesh: m.Meshes ){
mesh.Draw();
}
glDisable( GL_LIGHTING );
{
for( Cloud cloud: m.Clouds ){
cloud.Draw();
}
}
glEnable( GL_LIGHTING );
}
}
}
glPopMatrix();
}
private void render2d() {
mViewport.orthographic();
glEnable( GL_TEXTURE_2D );
{
if( !ProcessData.isDownloaded() ){
String string = "Downloading Model";
font.drawString((mViewport.width() / 2)-(font.getWidth(string)/2), (mViewport.height() / 2)-(font.getHeight(string)/2), string);
}
if( !ProcessData.isProcessed() ){
String string = "Processing Model";
font.drawString((mViewport.width() / 2)-(font.getWidth(string)/2), (mViewport.height() / 2)-(font.getHeight(string)/2), string);
}
String renderer = String.format("Renderer: %.0fms %.0ffps", CalcAverageTick( mFrameTime ), 1000 / CalcAverageTick( mFrameTime ));
font.drawString(mViewport.width() - font.getWidth(renderer), mViewport.height() - font.getHeight(renderer), renderer);
}
glDisable( GL_TEXTURE_2D );
}
int tickindex = 0;
double ticksum = 0;
double ticklist[] = new double[100];
private double CalcAverageTick(double newtick) {
ticksum -= ticklist[tickindex];
ticksum += newtick;
ticklist[tickindex] = newtick;
if (++tickindex == 100) {
tickindex = 0;
}
/* return average */
return ( ticksum / 100.0f);
}
public List<String> Parameters() {
List<String> retVal = new ArrayList<String>();
retVal.add( "url" );
retVal.add( "background" );
return retVal;
}
public class Processor extends Thread{
private final String From;
private boolean Downloaded, Processed;
private XMLParse Parser;
public Processor( String address ){
From = address;
Downloaded = false;
Parser = new XMLParse();
this.setPriority(Thread.MIN_PRIORITY);
}
synchronized public boolean isDownloaded(){
return Downloaded;
}
synchronized public boolean isProcessed(){
return Processed;
}
public XMLParse Parser(){
return Parser;
}
public void run() {
String To = System.getProperty("java.io.tmpdir") + From.substring( From.lastIndexOf("/") + 1 );
System.out.println("Downloading: " + From + " to " + To );
try{
Streams.copy(new URL(From).openConnection().getInputStream(), new FileOutputStream(To));
}catch( Exception e ){
System.err.println( "Download Error: " + e );
}
System.out.println("Downloaded: " + From );
Downloaded = true;
try {
TFile list[] = new TFile( To ).listFiles();
for (int i = 0; i < list.length; i++) {
if (list[i].getName().contains(".xml")) {
try{
Parser.Parse(list[i]);
}catch( Exception ex ){
System.out.println( "Process Error: " + ex );
}
}
}
Processed = true;
} catch (Exception exception) {
System.out.println( "Thread Error: " + exception );
}
}
}
}
|
package org.vaadin.viritin.fields;
import org.vaadin.viritin.fluency.ui.FluentCustomField;
import org.vaadin.viritin.label.RichText;
import org.vaadin.viritin.v7.fields.CaptionGenerator;
import com.vaadin.ui.Component;
import com.vaadin.ui.CustomField;
import com.vaadin.ui.Label;
/**
* A field which represents the value always in a label, so it is not editable.
* <p>
* The use case is a non editable value in a form, e.g. an id.
* <p>
* The creation of the label text can be controlled via a
* {@link org.vaadin.viritin.v7.fields.CaptionGenerator}.
*
* @author Daniel Nordhoff-Vergien
*
* @param <T> the type of the entity
*/
public class LabelField<T> extends CustomField<T>
implements FluentCustomField<LabelField<T>, T> {
private static final long serialVersionUID = -3079451926367430515L;
private T value;
@Override
protected void doSetValue(T value) {
this.value = value;
updateLabel();
}
@Override
public T getValue() {
return value;
}
private static class ToStringCaptionGenerator<T> implements
CaptionGenerator<T> {
private static final long serialVersionUID = 1149675718238329960L;
@Override
public String getCaption(T option) {
if (option == null) {
return "";
} else {
return option.toString();
}
}
}
public LabelField(String caption) {
super();
setCaption(caption);
}
private CaptionGenerator<T> captionGenerator = new ToStringCaptionGenerator<>();
private Label label = new RichText();
public LabelField() {
}
@Override
protected Component initContent() {
updateLabel();
return label;
}
protected void updateLabel() {
String caption;
if (captionGenerator != null) {
caption = captionGenerator.getCaption(getValue());
} else {
caption = getValue().toString();
}
label.setValue(caption);
}
/**
* Sets the CaptionGenerator for creating the label value.
*
* @param captionGenerator the caption generator used to format the
* displayed property
*/
public void setCaptionGenerator(CaptionGenerator<T> captionGenerator) {
this.captionGenerator = captionGenerator;
updateLabel();
}
public void setLabel(Label label) {
this.label = label;
}
public Label getLabel() {
return label;
}
}
|
package pixlepix.auracascade.block;
import cpw.mods.fml.common.Loader;
import cpw.mods.fml.common.ModAPIManager;
import cpw.mods.fml.common.event.FMLInterModComms;
import cpw.mods.fml.common.network.NetworkRegistry;
import net.minecraft.block.Block;
import net.minecraft.block.ITileEntityProvider;
import net.minecraft.block.material.Material;
import net.minecraft.client.renderer.texture.IIconRegister;
import net.minecraft.entity.Entity;
import net.minecraft.entity.item.EntityItem;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Blocks;
import net.minecraft.init.Items;
import net.minecraft.inventory.IInventory;
import net.minecraft.item.ItemBlock;
import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.ChatComponentText;
import net.minecraft.util.IIcon;
import net.minecraft.world.World;
import net.minecraftforge.common.util.ForgeDirection;
import pixlepix.auracascade.AuraCascade;
import pixlepix.auracascade.block.tile.*;
import pixlepix.auracascade.data.AuraQuantity;
import pixlepix.auracascade.data.CoordTuple;
import pixlepix.auracascade.data.EnumAura;
import pixlepix.auracascade.data.IToolTip;
import pixlepix.auracascade.item.ItemAuraCrystal;
import pixlepix.auracascade.main.Config;
import pixlepix.auracascade.main.EnumColor;
import pixlepix.auracascade.network.PacketBurst;
import pixlepix.auracascade.registry.BlockRegistry;
import pixlepix.auracascade.registry.CraftingBenchRecipe;
import pixlepix.auracascade.registry.ITTinkererBlock;
import pixlepix.auracascade.registry.ThaumicTinkererRecipe;
import java.util.ArrayList;
import java.util.List;
public class AuraBlock extends Block implements IToolTip, ITTinkererBlock, ITileEntityProvider {
public static String name = "auraNode";
//"" is default
//"pump" is AuraTilePump\
//"black" is AuraTileBlack etc
String type;
private IIcon topIcon;
private IIcon sideIcon;
private IIcon botIcon;
public AuraBlock(String type) {
super(Material.glass);
this.type = type;
if (!type.equals("craftingCenter")) {
setBlockBounds(.25F, .25F, .25F, .75F, .75F, .75F);
}
setLightOpacity(0);
setHardness(2F);
}
public AuraBlock() {
this("");
setHardness(2F);
}
public static AuraBlock getBlockFromName(String name) {
List<Block> blockList = BlockRegistry.getBlockFromClass(AuraBlock.class);
for (Block b : blockList) {
if (((AuraBlock) b).type.equals(name)) {
return (AuraBlock) b;
}
}
return null;
}
public static ItemStack getAuraNodeItemstack() {
List<Block> blockList = BlockRegistry.getBlockFromClass(AuraBlock.class);
for (Block b : blockList) {
if (((AuraBlock) b).type.equals("")) {
return new ItemStack(b);
}
}
AuraCascade.log.warn("Failed to find aura node itemstack. Something has gone horribly wrong");
return null;
}
public static ItemStack getAuraNodePumpItemstack() {
List<Block> blockList = BlockRegistry.getBlockFromClass(AuraBlock.class);
for (Block b : blockList) {
if (((AuraBlock) b).type.equals("pump")) {
return new ItemStack(b);
}
}
AuraCascade.log.warn("Failed to find aura node pump itemstack. Something has gone horribly wrong");
return null;
}
//Prevents being moved by RIM
public static boolean _Immovable() {
return true;
}
@Override
public String getHarvestTool(int metadata) {
return "pickaxe";
}
@Override
public boolean isOpaqueCube() {
return false;
}
@Override
public boolean hasComparatorInputOverride() {
return true;
}
@Override
public int getComparatorInputOverride(World world, int x, int y, int z, int meta) {
TileEntity tileEntity = world.getTileEntity(x, y, z);
if (tileEntity instanceof AuraTile) {
int aura = ((AuraTile) tileEntity).storage.getTotalAura();
return (int) Math.floor(Math.log10(aura));
} else {
return super.getComparatorInputOverride(world, x, y, z, meta);
}
}
@Override
public boolean onBlockActivated(World world, int x, int y, int z, EntityPlayer player, int meta, float hitX, float hitY, float hitZ) {
if (!world.isRemote && world.getTileEntity(x, y, z) instanceof AuraTile) {
if (world.getTileEntity(x, y, z) instanceof AuraTileCapacitor && player.isSneaking()) {
AuraTileCapacitor capacitor = (AuraTileCapacitor) world.getTileEntity(x, y, z);
capacitor.storageValueIndex = (capacitor.storageValueIndex + 1) % capacitor.storageValues.length;
player.addChatComponentMessage(new ChatComponentText("Max Storage: " + capacitor.storageValues[capacitor.storageValueIndex]));
world.markBlockForUpdate(x, y, z);
} else if (world.getTileEntity(x, y, z) instanceof AuraTilePedestal && !player.isSneaking()) {
AuraTilePedestal pedestal = (AuraTilePedestal) world.getTileEntity(x, y, z);
//Remove current itemstack from pedestal
if (pedestal.itemStack != null) {
EntityItem item = new EntityItem(world, player.posX, player.posY, player.posZ, pedestal.itemStack);
world.spawnEntityInWorld(item);
}
pedestal.itemStack = player.inventory.getCurrentItem() != null ? player.inventory.decrStackSize(player.inventory.currentItem, 1) : null;
world.markBlockForUpdate(x, y, z);
world.notifyBlockChange(x, y, z, this);
return true;
} else if (world.getTileEntity(x, y, z) instanceof AuraTile && player.inventory.getCurrentItem() == null) {
player.addChatComponentMessage(new ChatComponentText("Aura:"));
for (EnumAura aura : EnumAura.values()) {
if (((AuraTile) world.getTileEntity(x, y, z)).storage.get(aura) != 0) {
player.addChatComponentMessage(new ChatComponentText(aura.name + " Aura: " + ((AuraTile) world.getTileEntity(x, y, z)).storage.get(aura)));
}
}
if (world.getTileEntity(x, y, z) instanceof AuraTilePumpBase) {
player.addChatComponentMessage(new ChatComponentText("Power: " + ((AuraTilePumpBase) world.getTileEntity(x, y, z)).pumpPower));
}
}
} else if (!world.isRemote && world.getTileEntity(x, y, z) instanceof CraftingCenterTile && player.inventory.getCurrentItem() == null) {
CraftingCenterTile tile = (CraftingCenterTile) world.getTileEntity(x, y, z);
if (tile.getRecipe() != null) {
player.addChatComponentMessage(new ChatComponentText(EnumColor.DARK_BLUE + "Making: " + tile.getRecipe().result.getDisplayName()));
for (ForgeDirection direction : CraftingCenterTile.pedestalRelativeLocations) {
AuraTilePedestal pedestal = (AuraTilePedestal) new CoordTuple(x, y, z).add(direction).getTile(world);
if (tile.getRecipe() != null && tile.getRecipe().getAuraFromItem(pedestal.itemStack) != null) {
player.addChatComponentMessage(new ChatComponentText("" + EnumColor.AQUA + pedestal.powerReceived + "/" + tile.getRecipe().getAuraFromItem(pedestal.itemStack).getNum() + " (" + tile.getRecipe().getAuraFromItem(pedestal.itemStack).getType().name + ")"));
} else {
AuraCascade.log.warn("Invalid recipe when checking crafting center");
}
}
} else {
player.addChatComponentMessage(new ChatComponentText("No Recipe Selected"));
}
}
return false;
}
@Override
public void onEntityCollidedWithBlock(World world, int x, int y, int z, Entity entity) {
super.onEntityCollidedWithBlock(world, x, y, z, entity);
TileEntity te = world.getTileEntity(x, y, z);
if (entity instanceof EntityItem && !world.isRemote) {
ItemStack stack = ((EntityItem) entity).getEntityItem();
if (stack.getItem() instanceof ItemAuraCrystal) {
if (te instanceof AuraTile) {
((AuraTile) te).storage.add(new AuraQuantity(EnumAura.values()[stack.getItemDamage()], 1000 * stack.stackSize));
world.markBlockForUpdate(x, y, z);
world.notifyBlockChange(x, y, z, this);
AuraCascade.proxy.networkWrapper.sendToAllAround(new PacketBurst(1, entity.posX, entity.posY, entity.posZ), new NetworkRegistry.TargetPoint(world.provider.dimensionId, x, y, z, 32));
entity.setDead();
}
}
}
if (!world.isRemote && te instanceof AuraTilePumpProjectile) {
((AuraTilePumpProjectile) te).onEntityCollidedWithBlock(entity);
}
}
@Override
public void registerBlockIcons(IIconRegister iconRegister) {
if(type.contains("Alt")){
topIcon = iconRegister.registerIcon("aura:" + type.replace("Alt", "") + "Node_Top");
sideIcon = iconRegister.registerIcon("aura:" + type.replace("Alt", "") + "Node_Side_Alt");
botIcon = iconRegister.registerIcon("aura:" + type.replace("Alt", "") + "Node_Bottom");
}else {
sideIcon = iconRegister.registerIcon("aura:" + type + "Node_Side");
botIcon = iconRegister.registerIcon("aura:" + type + "Node_Bottom");
topIcon = iconRegister.registerIcon("aura:" + type + "Node_Top");
}
}
@Override
public IIcon getIcon(int side, int meta) {
switch (side) {
case 0:
return botIcon;
case 1:
return topIcon;
default:
return sideIcon;
}
}
@Override
public void breakBlock(World world, int x, int y, int z, Block block, int p_149749_6_) {
TileEntity te = world.getTileEntity(x, y, z);
if (te instanceof IInventory) {
IInventory inv = (IInventory) te;
for (int i = 0; i < inv.getSizeInventory(); i++) {
if (inv.getStackInSlot(i) != null) {
float f = 0.7F;
double d0 = (double) (world.rand.nextFloat() * f) + (double) (1.0F - f) * 0.5D;
double d1 = (double) (world.rand.nextFloat() * f) + (double) (1.0F - f) * 0.5D;
double d2 = (double) (world.rand.nextFloat() * f) + (double) (1.0F - f) * 0.5D;
EntityItem entityitem = new EntityItem(world, (double) x + d0, (double) y + d1, (double) z + d2, inv.getStackInSlot(i));
entityitem.delayBeforeCanPickup = 10;
world.spawnEntityInWorld(entityitem);
}
}
}
}
@Override
public ThaumicTinkererRecipe getRecipeItem() {
// TODO Auto-generated method stub
if (type.equals("pump")) {
return new CraftingBenchRecipe(new ItemStack(this), "ILI", "INI", "ILI", 'I', new ItemStack(Items.iron_ingot), 'L', new ItemStack(Items.dye, 1, 4), 'N', getAuraNodeItemstack());
}
if (type.equals("black")) {
return new CraftingBenchRecipe(new ItemStack(this), "ILI", "INI", "ILI", 'I', new ItemStack(Items.iron_ingot), 'L', new ItemStack(Items.dye), 'N', getAuraNodeItemstack());
}
if (type.equals("conserve")) {
return new CraftingBenchRecipe(new ItemStack(this), "ILI", "INI", "HHH", 'I', new ItemStack(Items.iron_ingot), 'L', new ItemStack(Items.redstone), 'N', getAuraNodeItemstack(), 'H', new ItemStack(Items.gold_ingot));
}
if (type.equals("capacitor")) {
return new CraftingBenchRecipe(new ItemStack(this), "III", " N ", "III", 'I', new ItemStack(Items.iron_ingot), 'N', getAuraNodeItemstack());
}
if (type.equals("craftingPedestal")) {
return new CraftingBenchRecipe(new ItemStack(this), "GRR", "GNR", "GRR", 'G', new ItemStack(Items.gold_ingot), 'R', new ItemStack(Items.redstone), 'N', getAuraNodeItemstack());
}
if (type.equals("craftingCenter")) {
return new CraftingBenchRecipe(new ItemStack(this), "GGG", "RDR", "RRR", 'G', new ItemStack(Items.gold_ingot), 'R', new ItemStack(Items.redstone), 'D', new ItemStack(Items.diamond));
}
if (type.equals("orange")) {
return new CraftingBenchRecipe(new ItemStack(this), "ILI", "INI", "ILI", 'I', new ItemStack(Items.iron_ingot), 'L', new ItemStack(Items.dye, 1, 14), 'N', getAuraNodeItemstack());
}
if (type.equals("pumpProjectile")) {
return new CraftingBenchRecipe(new ItemStack(this), "XXX", "IPI", "GIG", 'X', new ItemStack(Items.arrow), 'I', new ItemStack(Items.iron_ingot), 'G', new ItemStack(Items.gold_ingot), 'P', getAuraNodePumpItemstack());
}
if (type.equals("pumpFall")) {
return new CraftingBenchRecipe(new ItemStack(this), "XXX", "IPI", "GIG", 'X', new ItemStack(Items.water_bucket), 'I', new ItemStack(Items.iron_ingot), 'G', new ItemStack(Items.gold_ingot), 'P', getAuraNodePumpItemstack());
}
if (type.equals("pumpLight")) {
return new CraftingBenchRecipe(new ItemStack(this), "XXX", "IPI", "GIG", 'X', new ItemStack(Blocks.glowstone), 'I', new ItemStack(Items.iron_ingot), 'G', new ItemStack(Items.gold_ingot), 'P', getAuraNodePumpItemstack());
}
if (type.equals("pumpRedstone")) {
return new CraftingBenchRecipe(new ItemStack(this), "XXX", "IPI", "GIG", 'X', new ItemStack(Blocks.redstone_block), 'I', new ItemStack(Items.iron_ingot), 'G', new ItemStack(Items.gold_ingot), 'P', getAuraNodePumpItemstack());
}
if(type.equals("pumpAlt")){
return new CraftingBenchRecipe(new ItemStack(this), " E ", "EPE", " E ", 'P', new ItemStack(getBlockFromName("pump")));
}
if(type.equals("pumpRedstoneAlt")){
return new CraftingBenchRecipe(new ItemStack(this), " E ", "EPE", " E ", 'P', new ItemStack(getBlockFromName("pumpRedstone")));
}
if(type.equals("pumpLightAlt")){
return new CraftingBenchRecipe(new ItemStack(this), " E ", "EPE", " E ", 'P', new ItemStack(getBlockFromName("pumpLight")));
}
if(type.equals("pumpFallAlt")){
return new CraftingBenchRecipe(new ItemStack(this), " E ", "EPE", " E ", 'P', new ItemStack(getBlockFromName("pumpFall")));
}
if(type.equals("pumpProjectileAlt")){
return new CraftingBenchRecipe(new ItemStack(this), " E ", "EPE", " E ", 'P', new ItemStack(getBlockFromName("pumpProjectile")));
}
if (type.equals("flux")) {
return new CraftingBenchRecipe(new ItemStack(this), "III", "RNR", "III", 'R', new ItemStack(Items.redstone), 'I', new ItemStack(Items.gold_ingot), 'N', getAuraNodeItemstack());
}
return new CraftingBenchRecipe(new ItemStack(this), "PPP", "PRP", "PPP", 'P', new ItemStack(Blocks.glass_pane), 'R', new ItemStack(Blocks.redstone_block));
}
@Override
public ArrayList<Object> getSpecialParameters() {
// TODO Auto-generated method stub
ArrayList result = new ArrayList<Object>();
result.add("pump");
result.add("black");
result.add("conserve");
result.add("capacitor");
result.add("craftingCenter");
result.add("craftingPedestal");
result.add("orange");
result.add("pumpAlt");
result.add("pumpProjectile");
result.add("pumpFall");
result.add("pumpLight");
result.add("pumpRedstone");
result.add("pumpProjectileAlt");
result.add("pumpFallAlt");
result.add("pumpLightAlt");
result.add("pumpRedstoneAlt");
if (ModAPIManager.INSTANCE.hasAPI("CoFHAPI|energy")) {
result.add("flux");
}
return result;
}
@Override
public String getBlockName() {
// TODO Auto-generated method stub
return name + type;
}
@Override
public boolean shouldRegister() {
// TODO Auto-generated method stub
return true;
}
@Override
public boolean shouldDisplayInTab() {
// TODO Auto-generated method stub
return true;
}
@Override
public Class<? extends ItemBlock> getItemBlock() {
// TODO Auto-generated method stub
return null;
}
@Override
public Class<? extends TileEntity> getTileEntity() {
if (type.equals("pump")) {
return AuraTilePump.class;
}
if (type.equals("black")) {
return AuraTileBlack.class;
}
if (type.equals("conserve")) {
return AuraTileConserve.class;
}
if (type.equals("capacitor")) {
return AuraTileCapacitor.class;
}
if (type.equals("craftingPedestal")) {
return AuraTilePedestal.class;
}
if (type.equals("craftingCenter")) {
return CraftingCenterTile.class;
}
if (type.equals("flux")) {
return AuraTileRF.class;
}
if (type.equals("orange")) {
return AuraTileOrange.class;
}
if (type.equals("pumpProjectile")) {
return AuraTilePumpProjectile.class;
}
if (type.equals("pumpFall")) {
return AuraTilePumpFall.class;
}
if (type.equals("pumpLight")) {
return AuraTilePumpLight.class;
}
if (type.equals("pumpRedstone")) {
return AuraTilePumpRedstone.class;
}
if (type.equals("pumpAlt")) {
return AuraTilePumpAlt.class;
}
if (type.equals("pumpProjectileAlt")) {
return AuraTilePumpProjectileAlt.class;
}
if (type.equals("pumpFallAlt")) {
return AuraTilePumpFallAlt.class;
}
if (type.equals("pumpLightAlt")) {
return AuraTilePumpLightAlt.class;
}
if (type.equals("pumpRedstoneAlt")) {
return AuraTilePumpRedstoneAlt.class;
}
return AuraTile.class;
}
@Override
public TileEntity createNewTileEntity(World world, int meta) {
try {
return getTileEntity().newInstance();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
return null;
}
@Override
public int damageDropped(int meta) {
return meta;
}
@Override
public List<String> getTooltipData(World world, EntityPlayer player, int x, int y, int z) {
List<String> result = new ArrayList<String>();
TileEntity tileEntity = world.getTileEntity(x, y, z);
if (tileEntity instanceof AuraTile) {
if (tileEntity instanceof AuraTileCapacitor) {
AuraTileCapacitor capacitor = (AuraTileCapacitor) tileEntity;
result.add("Max Storage: " + capacitor.storageValues[capacitor.storageValueIndex]);
}
if (((AuraTile) tileEntity).storage.getTotalAura() > 0) {
result.add("Aura Stored: ");
for (EnumAura aura : EnumAura.values()) {
if (((AuraTile) tileEntity).storage.get(aura) != 0) {
result.add(" " + aura.name + " Aura: " + ((AuraTile) tileEntity).storage.get(aura));
}
}
} else {
result.add("No Aura");
}
if (tileEntity instanceof AuraTileCapacitor) {
if (((AuraTileCapacitor) tileEntity).ticksDisabled > 0) {
result.add("Time until functional: " + ((AuraTileCapacitor) tileEntity).ticksDisabled / 20);
}
}
if (tileEntity instanceof AuraTilePumpBase) {
result.add("Time left: " + ((AuraTilePumpBase) tileEntity).pumpPower + " seconds");
result.add("Power: " + ((AuraTilePumpBase) tileEntity).pumpSpeed + " power per second");
if(((AuraTilePumpBase) tileEntity).isAlternator()){
AuraTilePumpBase altPump = (AuraTilePumpBase) tileEntity;
int power = (int) (altPump.pumpSpeed * altPump.getAlternatingFactor());
result.add("Phase Power: " + power);
}
}
if (ModAPIManager.INSTANCE.hasAPI("CoFHAPI|energy")) {
if(tileEntity instanceof AuraTileRF){
AuraTileRF auraTileRF = (AuraTileRF) tileEntity;
result.add("RF/t Output: " + auraTileRF.lastPower * Config.powerFactor);
}
}
} else if (tileEntity instanceof CraftingCenterTile) {
CraftingCenterTile tile = (CraftingCenterTile) tileEntity;
if (tile.getRecipe() != null) {
result.add("Making: " + tile.getRecipe().result.getDisplayName());
for (ForgeDirection direction : CraftingCenterTile.pedestalRelativeLocations) {
AuraTilePedestal pedestal = (AuraTilePedestal) new CoordTuple(x, y, z).add(direction).getTile(world);
if (tile.getRecipe() != null && tile.getRecipe().getAuraFromItem(pedestal.itemStack) != null) {
result.add(" " + pedestal.powerReceived + "/" + tile.getRecipe().getAuraFromItem(pedestal.itemStack).getNum() + " (" + tile.getRecipe().getAuraFromItem(pedestal.itemStack).getType().name + ")");
} else {
AuraCascade.log.warn("Invalid recipe when checking crafting center");
}
}
} else {
result.add("No Valid Recipe Selected");
}
}
return result;
}
}
|
package pl.mkrystek.mkbot.task.impl;
import static pl.mkrystek.mkbot.task.TaskExecutionEngine.COMMAND_HELP_BODY;
import pl.mkrystek.mkbot.message.SkypeMessage;
import pl.mkrystek.mkbot.task.ReplyTask;
public class HelpTask extends ReplyTask {
private static final String TASK_NAME = "help";
public HelpTask() {
super(TASK_NAME);
}
@Override
public String performAction(SkypeMessage skypeMessage) {
return "Help requested! Sample bot usage: \"!MKBot <commandName> <body>\"\n" +
"If you want to know more about particular command, type \"!MKBot <commandName> " + COMMAND_HELP_BODY + "\"";
}
}
|
package pl.pw.edu.mini.dos.node.ndb;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import pl.pw.edu.mini.dos.Helper;
import java.math.BigDecimal;
import java.sql.Blob;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;
import java.util.function.Consumer;
/**
* Contains common method used by DBmanager and ImDBmanager.
*/
public class DBhelper {
private static final Logger logger = LoggerFactory.getLogger(DBhelper.class);
public static Consumer[] getSetDataFunctions(final PreparedStatement st, List<String> columnsTypes) {
logger.debug("Get get functions for colums: " + Helper.collectionToString(columnsTypes));
Consumer[] functions = new Consumer[columnsTypes.size()];
for (int i = 0; i < columnsTypes.size(); i++) {
String type = columnsTypes.get(i);
final int col = i + 1;
switch (type) {
case "INTEGER":
case "INT":
case "TINYINT":
case "SMALLINT":
case "MEDIUMINT":
case "BIGINT":
case "INT2":
case "INT8":
functions[i] = x -> {
try {
st.setLong(col, Long.parseLong(x.toString()));
} catch (SQLException e) {
logger.error("Col: " + col + ", Value: " + x + " E: " + e.getMessage());
}
};
break;
case "TEXT":
case "CHARACTER":
case "VARCHAR":
case "CLOB":
functions[i] = x -> {
try {
st.setString(col, x.toString());
} catch (SQLException e) {
logger.error("Col: " + col + ", Value: " + x + " E: " + e.getMessage());
}
};
break;
case "BLOB":
functions[i] = x -> {
try {
st.setBlob(col, (Blob) x);
} catch (SQLException e) {
logger.error("Col: " + col + ", Value: " + x + " E: " + e.getMessage());
}
};
break;
case "REAL":
case "DOUBLE":
case "FLOAT ":
functions[i] = x -> {
try {
st.setDouble(col, Double.parseDouble(x.toString()));
} catch (SQLException e) {
logger.error("Col: " + col + ", Value: " + x + " E: " + e.getMessage());
}
};
break;
case "NUMERIC":
case "DECIMAL":
case "BOOLEAN":
case "DATE":
case "DATETIME ":
functions[i] = x -> {
try {
st.setBigDecimal(col, (BigDecimal) x);
} catch (SQLException e) {
logger.error("Col: " + col + ", Value: " + x + " E: " + e.getMessage());
logger.error(e.getMessage());
}
};
break;
}
}
return functions;
}
}
|
package se.kth.hopsworks.rest;
import java.util.LinkedList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.security.RolesAllowed;
import javax.ejb.EJB;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.enterprise.context.RequestScoped;
import javax.servlet.http.HttpServletRequest;
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.Context;
import javax.ws.rs.core.GenericEntity;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.SecurityContext;
import org.elasticsearch.action.ActionFuture;
import org.elasticsearch.action.admin.indices.cache.clear.ClearIndicesCacheRequest;
import org.elasticsearch.action.admin.indices.exists.indices.IndicesExistsRequestBuilder;
import org.elasticsearch.action.admin.indices.exists.indices.IndicesExistsResponse;
import org.elasticsearch.action.admin.indices.exists.types.TypesExistsRequest;
import org.elasticsearch.action.admin.indices.exists.types.TypesExistsResponse;
import org.elasticsearch.action.admin.indices.open.OpenIndexRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.AdminClient;
import org.elasticsearch.client.Client;
import org.elasticsearch.client.IndicesAdminClient;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.ImmutableSettings;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.index.query.QueryBuilder;
import static org.elasticsearch.index.query.QueryBuilders.boolQuery;
import static org.elasticsearch.index.query.QueryBuilders.hasParentQuery;
import static org.elasticsearch.index.query.QueryBuilders.matchPhraseQuery;
import static org.elasticsearch.index.query.QueryBuilders.matchQuery;
import static org.elasticsearch.index.query.QueryBuilders.prefixQuery;
import static org.elasticsearch.index.query.QueryBuilders.termsQuery;
import org.elasticsearch.search.SearchHit;
import se.kth.bbc.lims.Constants;
import se.kth.hopsworks.controller.ResponseMessages;
import se.kth.hopsworks.filters.AllowedRoles;
/**
*
* @author vangelis
*/
@Path("/elastic")
@RolesAllowed({"SYS_ADMIN", "BBC_USER"})
@Produces(MediaType.APPLICATION_JSON)
@RequestScoped
@TransactionAttribute(TransactionAttributeType.NEVER)
public class ElasticService {
private final static Logger logger = Logger.getLogger(ElasticService.class.
getName());
@EJB
private NoCacheResponse noCacheResponse;
/**
* Searches for content composed of projects and datasets. Hits two elastic
* indices: 'project' and 'dataset'
* <p/>
* @param searchTerm
* @param sc
* @param req
* @return
* @throws AppException
*/
@GET
@Path("globalsearch/{searchTerm}")
@Produces(MediaType.APPLICATION_JSON)
@AllowedRoles(roles = {AllowedRoles.DATA_SCIENTIST, AllowedRoles.DATA_OWNER})
public Response globalSearch(
@PathParam("searchTerm") String searchTerm,
@Context SecurityContext sc,
@Context HttpServletRequest req) throws AppException {
if (searchTerm == null) {
throw new AppException(Response.Status.BAD_REQUEST.getStatusCode(),
"Incomplete request!");
}
//some necessary client settings
final Settings settings = ImmutableSettings.settingsBuilder()
.put("client.transport.sniff", true) //being able to inspect other nodes
.put("cluster.name", "hopsworks")
.build();
//initialize the client
Client client
= new TransportClient(settings)
.addTransportAddress(new InetSocketTransportAddress("193.10.66.125",
9300));
//check if the indices are up and running
if (!this.indexExists(client, Constants.META_PROJECT_INDEX) || !this.
indexExists(client, Constants.META_DATASET_INDEX)) {
logger.log(Level.FINE, ResponseMessages.ELASTIC_INDEX_NOT_FOUND);
throw new AppException(Response.Status.INTERNAL_SERVER_ERROR.
getStatusCode(), ResponseMessages.ELASTIC_INDEX_NOT_FOUND);
}
//TODO. ADD SEARCHABLE FIELD IN PROJECTS (DB)
/*
* If projects contain a searchable field then the client can hit both
* indices (projects, datasets) with a single query. Right now the single
* query fails because of the lack of a searchable field in the projects.
* ADDED MANUALLY A SEARCHABLE FIELD IN THE RIVER. MAKES A PROJECT
* SEARCHABLE BY DEFAULT. NEEDS REFACTORING
*/
//hit the indices - execute the queries
SearchResponse response
= client.prepareSearch(Constants.META_PROJECT_INDEX,
Constants.META_DATASET_INDEX).
setTypes(Constants.META_PROJECT_PARENT_TYPE,
Constants.META_DATASET_PARENT_TYPE)
.setQuery(this.matchProjectsDatasetsQuery(searchTerm))
//.setQuery(this.getDatasetComboQuery(searchTerm))
.addHighlightedField("name")
.execute().actionGet();
if (response.status().getStatus() == 200) {
//logger.log(Level.INFO, "Matched number of documents: {0}", response.
//getHits().
//totalHits());
//construct the response
List<ElasticHit> elasticHits = new LinkedList<>();
if (response.getHits().getHits().length > 0) {
SearchHit[] hits = response.getHits().getHits();
for (SearchHit hit : hits) {
elasticHits.add(new ElasticHit(hit));
}
}
this.clientShutdown(client);
GenericEntity<List<ElasticHit>> searchResults
= new GenericEntity<List<ElasticHit>>(elasticHits) {
};
return noCacheResponse.getNoCacheResponseBuilder(Response.Status.OK).
entity(searchResults).build();
}
//something went wrong so throw an exception
this.clientShutdown(client);
throw new AppException(Response.Status.INTERNAL_SERVER_ERROR.
getStatusCode(), ResponseMessages.ELASTIC_SERVER_NOT_FOUND);
}
/**
* Searches for content inside a specific project. Hits 'project' index
* <p/>
* @param projectName
* @param searchTerm
* @param sc
* @param req
* @return
* @throws AppException
*/
@GET
@Path("projectsearch/{projectName}/{searchTerm}")
@Produces(MediaType.APPLICATION_JSON)
@AllowedRoles(roles = {AllowedRoles.DATA_SCIENTIST, AllowedRoles.DATA_OWNER})
public Response projectSearch(
@PathParam("projectName") String projectName,
@PathParam("searchTerm") String searchTerm,
@Context SecurityContext sc,
@Context HttpServletRequest req) throws AppException {
if (projectName == null || searchTerm == null) {
throw new AppException(Response.Status.BAD_REQUEST.getStatusCode(),
"Incomplete request!");
}
final Settings settings = ImmutableSettings.settingsBuilder()
.put("client.transport.sniff", true) //being able to retrieve other nodes
.put("cluster.name", "hopsworks").build();
Client client
= new TransportClient(settings)
.addTransportAddress(new InetSocketTransportAddress("193.10.66.125",
9300));
//check if the indices are up and running
if (!this.indexExists(client, Constants.META_PROJECT_INDEX)) {
throw new AppException(Response.Status.INTERNAL_SERVER_ERROR.
getStatusCode(), ResponseMessages.ELASTIC_INDEX_NOT_FOUND);
} else if (!this.typeExists(client, Constants.META_PROJECT_INDEX,
Constants.META_PROJECT_CHILD_TYPE)) {
throw new AppException(Response.Status.INTERNAL_SERVER_ERROR.
getStatusCode(), ResponseMessages.ELASTIC_TYPE_NOT_FOUND);
}
//hit the indices - execute the queries
SearchResponse response
= client.prepareSearch(Constants.META_PROJECT_INDEX)
.setTypes(Constants.META_PROJECT_CHILD_TYPE)
.setQuery(this.matchChildQuery(projectName,
Constants.META_PROJECT_PARENT_TYPE, searchTerm))
.addHighlightedField("name")
.execute().actionGet();
if (response.status().getStatus() == 200) {
//logger.log(Level.INFO, "Matched number of documents: {0}", response.
//getHits().
//totalHits());
//construct the response
List<ElasticHit> elasticHits = new LinkedList<>();
if (response.getHits().getHits().length > 0) {
SearchHit[] hits = response.getHits().getHits();
for (SearchHit hit : hits) {
elasticHits.add(new ElasticHit(hit));
}
}
this.clientShutdown(client);
GenericEntity<List<ElasticHit>> searchResults
= new GenericEntity<List<ElasticHit>>(elasticHits) {
};
return noCacheResponse.getNoCacheResponseBuilder(Response.Status.OK).
entity(searchResults).build();
}
this.clientShutdown(client);
throw new AppException(Response.Status.INTERNAL_SERVER_ERROR.
getStatusCode(), ResponseMessages.ELASTIC_SERVER_NOT_FOUND);
}
/**
* Searches for content inside a specific dataset. Hits 'dataset' index
* <p/>
* @param datasetName
* @param searchTerm
* @param sc
* @param req
* @return
* @throws AppException
*/
@GET
@Path("datasetsearch/{datasetName}/{searchTerm}")
@Produces(MediaType.APPLICATION_JSON)
@AllowedRoles(roles = {AllowedRoles.DATA_SCIENTIST, AllowedRoles.DATA_OWNER})
public Response datasetSearch(
@PathParam("datasetName") String datasetName,
@PathParam("searchTerm") String searchTerm,
@Context SecurityContext sc,
@Context HttpServletRequest req) throws AppException {
if (datasetName == null || searchTerm == null) {
throw new AppException(Response.Status.BAD_REQUEST.getStatusCode(),
"Incomplete request!");
}
final Settings settings = ImmutableSettings.settingsBuilder()
.put("client.transport.sniff", true) //being able to retrieve other nodes
.put("cluster.name", "hopsworks").build();
Client client
= new TransportClient(settings)
.addTransportAddress(new InetSocketTransportAddress("193.10.66.125",
9300));
//check if the indices are up and running
if (!this.indexExists(client, Constants.META_DATASET_INDEX)) {
throw new AppException(Response.Status.INTERNAL_SERVER_ERROR.
getStatusCode(), ResponseMessages.ELASTIC_INDEX_NOT_FOUND);
} else if (!this.typeExists(client, Constants.META_DATASET_INDEX,
Constants.META_DATASET_CHILD_TYPE)) {
throw new AppException(Response.Status.INTERNAL_SERVER_ERROR.
getStatusCode(), ResponseMessages.ELASTIC_TYPE_NOT_FOUND);
}
//hit the indices - execute the queries
SearchResponse response
= client.prepareSearch(Constants.META_DATASET_INDEX)
.setTypes(Constants.META_DATASET_CHILD_TYPE)
.setQuery(this.matchChildQuery(datasetName,
Constants.META_DATASET_PARENT_TYPE, searchTerm))
.addHighlightedField("name")
.execute().actionGet();
if (response.status().getStatus() == 200) {
//logger.log(Level.INFO, "Matched number of documents: {0}", response.
//getHits().
//totalHits());
//construct the response
List<ElasticHit> elasticHits = new LinkedList<>();
if (response.getHits().getHits().length > 0) {
SearchHit[] hits = response.getHits().getHits();
for (SearchHit hit : hits) {
elasticHits.add(new ElasticHit(hit));
}
}
this.clientShutdown(client);
GenericEntity<List<ElasticHit>> searchResults
= new GenericEntity<List<ElasticHit>>(elasticHits) {
};
return noCacheResponse.getNoCacheResponseBuilder(Response.Status.OK).
entity(searchResults).build();
}
this.clientShutdown(client);
throw new AppException(Response.Status.INTERNAL_SERVER_ERROR.
getStatusCode(), ResponseMessages.ELASTIC_SERVER_NOT_FOUND);
}
/**
* Gathers the query filters applied on projects and datasets. Projects and
* datasets are parent documents
* <p/>
* @param searchTerm
* @return
*/
private QueryBuilder matchProjectsDatasetsQuery(String searchTerm) {
//first part is the base condition
QueryBuilder firstPart = this.getParentBasePart();
QueryBuilder secondPart = this.getDescMetaPart(searchTerm);
/*
* The following boolean query is being applied in the parent documents
* (operation && searchable) && (name || description || metadata)
*/
QueryBuilder query = boolQuery()
.must(firstPart)
.must(secondPart);
return query;
}
/**
* Creates the base condition every matched document has to satisfy. It has to
* be an added document (operation = 0) and it has to be searchable
* (searchable = 1)
* <p/>
* @return
*/
private QueryBuilder getParentBasePart() {
//build the project base condition queries
QueryBuilder operationMatch = matchQuery(
Constants.META_INODE_OPERATION_FIELD,
Constants.META_INODE_OPERATION_ADD);
//match searchable
QueryBuilder searchableMatch = matchQuery(
Constants.META_INODE_SEARCHABLE_FIELD, 1);
QueryBuilder baseCondition = boolQuery()
.must(operationMatch)
.must(searchableMatch);
return baseCondition;
}
/**
* Creates the main query condition. Applies filters on the texts describing a
* document i.e. on the description and metadata fields
* <p/>
* @param searchTerm
* @return
*/
private QueryBuilder getDescMetaPart(String searchTerm) {
//apply a prefix filter on the name field
QueryBuilder namePart = this.getNameQuery(searchTerm);
//apply several text filters on the description and metadata fields
QueryBuilder descMetaPart = this.getDescMetaQuery(searchTerm);
QueryBuilder textCondition = boolQuery()
.should(namePart)
.should(descMetaPart);
return textCondition;
}
/**
* Creates the query that is applied on the name field.
* <p/>
* @param searchTerm
* @return
*/
private QueryBuilder getNameQuery(String searchTerm) {
//prefix name match
QueryBuilder namePrefixMatch = prefixQuery(Constants.META_NAME_FIELD,
searchTerm);
QueryBuilder namePhraseMatch = matchPhraseQuery(Constants.META_NAME_FIELD,
searchTerm);
QueryBuilder nameQuery = boolQuery()
.should(namePrefixMatch)
.should(namePhraseMatch);
return nameQuery;
}
/**
* Creates the query that is applied on the text fields of a document. Hits
* the description and metadata fields
* <p/>
* @param searchTerm
* @return
*/
private QueryBuilder getDescMetaQuery(String searchTerm) {
//do a prefix query on the description field in case the user starts writing
//a full sentence
QueryBuilder descriptionPrefixMatch = prefixQuery(
Constants.META_DESCRIPTION_FIELD, searchTerm);
//a phrase query to match the dataset description
QueryBuilder descriptionMatch = termsQuery(
Constants.META_DESCRIPTION_FIELD, searchTerm);
//add a phrase match query to enable results to popup while typing phrases
QueryBuilder descriptionPhraseMatch = matchPhraseQuery(
Constants.META_DESCRIPTION_FIELD, searchTerm);
//add a fuzzy search on description field
//QueryBuilder descriptionFuzzyQuery = fuzzyQuery(
// Constants.META_DESCRIPTION_FIELD, searchTerm);
//do a prefix query on the metadata first in case the user starts typing a
//full sentence
QueryBuilder metadataPrefixMatch = prefixQuery(Constants.META_DATA_FIELD,
searchTerm);
//apply phrase filter on user metadata
QueryBuilder metadataMatch = termsQuery(
Constants.META_DATA_FIELD, searchTerm);
//add a phrase match query to enable results to popup while typing phrases
QueryBuilder metadataPhraseMatch = matchPhraseQuery(
Constants.META_DATA_FIELD, searchTerm);
//add a fuzzy search on metadata field
//QueryBuilder metadataFuzzyQuery = fuzzyQuery(Constants.META_DATA_FIELD,
// searchTerm);
QueryBuilder datasetsQuery = boolQuery()
.should(descriptionPrefixMatch)
.should(descriptionMatch)
.should(descriptionPhraseMatch)
.should(metadataPrefixMatch)
.should(metadataMatch)
.should(metadataPhraseMatch);
return datasetsQuery;
}
/**
* Gathers the query filters applied on common files and folders. Common files
* and folders are child documents
* <p/>
* @param searchTerm
* @return
*/
private QueryBuilder matchChildQuery(String parentName,
String parentType, String searchTerm) {
//get the base conditions query
QueryBuilder childBase = this.getChildBasePart(parentName, parentType);
//get the text conditions query
QueryBuilder childRest = this.getDescMetaPart(searchTerm);
/*
* The following boolean query is being applied in the child documents
* (hasParent && operation && searchable) && (name || description ||
* metadata)
*/
QueryBuilder union = boolQuery()
.must(childBase)
.must(childRest);
return union;
}
/**
* Creates the base condition every matched document has to satisfy. It has to
* have a specific parent type (hasParent), it must be an added document
* (operation = 0) and it has to be searchable (searchable = 1)
* <p/>
* @return
*/
private QueryBuilder getChildBasePart(String parentName, String parentType) {
//TODO: ADD SEARCHABLE FIELD IN CHILD DOCUMENTS. 1 BY DEFAULT BY THE INDEXING SCRIPTS
QueryBuilder hasParentPart = hasParentQuery(
parentType,
matchQuery(Constants.META_NAME_FIELD, parentName));
//build the base conditions query for the child documents
QueryBuilder operationMatch = matchQuery(
Constants.META_INODE_OPERATION_FIELD,
Constants.META_INODE_OPERATION_ADD);
//match searchable
QueryBuilder searchableMatch = matchQuery(
Constants.META_INODE_SEARCHABLE_FIELD, 1);
QueryBuilder baseCondition = boolQuery()
.must(hasParentPart)
.must(operationMatch);
//.must(searchableMatch);
return baseCondition;
}
/**
* Checks if a given index exists in elastic
* <p/>
* @param client
* @param indexName
* @return
*/
private boolean indexExists(Client client, String indexName) {
AdminClient admin = client.admin();
IndicesAdminClient indices = admin.indices();
IndicesExistsRequestBuilder indicesExistsRequestBuilder = indices.
prepareExists(indexName);
IndicesExistsResponse response = indicesExistsRequestBuilder
.execute()
.actionGet();
return response.isExists();
}
/**
* Checks if a given data type exists. It is a given that the index exists
* <p/>
* @param client
* @param typeName
* @return
*/
private boolean typeExists(Client client, String indexName, String typeName) {
AdminClient admin = client.admin();
IndicesAdminClient indices = admin.indices();
ActionFuture<TypesExistsResponse> action = indices.typesExists(
new TypesExistsRequest(
new String[]{indexName}, typeName));
TypesExistsResponse response = action.actionGet();
return response.isExists();
}
/**
* Shuts down the client and clears the cache
* <p/>
* @param client
*/
private void clientShutdown(Client client) {
client.admin().indices().clearCache(new ClearIndicesCacheRequest(
Constants.META_PROJECT_INDEX, Constants.META_DATASET_INDEX));
client.close();
}
/**
* Boots up a previously closed index
*/
private void bootIndices(Client client) {
client.admin().indices().open(new OpenIndexRequest(
Constants.META_PROJECT_INDEX, Constants.META_DATASET_INDEX));
}
}
|
package seedu.jimi.logic.commands;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import seedu.jimi.commons.exceptions.IllegalValueException;
import seedu.jimi.model.datetime.DateTime;
import seedu.jimi.model.event.Event;
import seedu.jimi.model.tag.Tag;
import seedu.jimi.model.tag.UniqueTagList;
import seedu.jimi.model.task.DeadlineTask;
import seedu.jimi.model.task.FloatingTask;
import seedu.jimi.model.task.Name;
import seedu.jimi.model.task.ReadOnlyTask;
import seedu.jimi.model.task.UniqueTaskList;
/**
* Adds a task to the Jimi.
*/
public class AddCommand extends Command {
public static final String COMMAND_WORD = "add";
public static final String MESSAGE_USAGE =
COMMAND_WORD + ": Adds a task or event to Jimi with one optional tag.\n"
+ "\n"
+ "To add a task:\n"
+ "Parameters: \"TASK_DETAILS\" [due DATE_TIME] [t/TAG]\n"
+ "Example: " + COMMAND_WORD + " \"do dishes\" t/important\n"
+ "\n"
+ "To add an event:\n"
+ "Parameters: \"TASK_DETAILS\" on START_DATE_TIME [to END_DATE_TIME] [t/TAG]\n"
+ "Example: " + COMMAND_WORD + " \"linkin park concert\" on sunday 2pm t/fun\n"
+ "\n"
+ "> Tip: Typing `a` or `ad` instead of `add` works too.";
public static final String MESSAGE_SUCCESS = "New task added: %1$s";
public static final String MESSAGE_DUPLICATE_TASK = "This task already exists in Jimi";
private final ReadOnlyTask toAdd;
public AddCommand() {
toAdd = null;
}
public AddCommand(String name, List<Date> dates, Set<String> tags) throws IllegalValueException {
final Set<Tag> tagSet = new HashSet<>();
for (String tagName : tags) {
tagSet.add(new Tag(tagName));
}
if (dates.size() == 0) {
this.toAdd = new FloatingTask(new Name(name), new UniqueTagList(tagSet));
} else {
this.toAdd = new DeadlineTask(new Name(name), new DateTime(dates.get(0)), new UniqueTagList(tagSet));
}
}
public AddCommand(String name, List<Date> startDateTime, List<Date> endDateTime, Set<String> tags)
throws IllegalValueException {
final Set<Tag> tagSet = new HashSet<>();
for (String tagName : tags) {
tagSet.add(new Tag(tagName));
}
// events do not always have an end date
DateTime endDateTimeToAdd = endDateTime.isEmpty() ? null : new DateTime(endDateTime.get(0));
this.toAdd = new Event(
new Name(name),
new DateTime(startDateTime.get(0)),
endDateTimeToAdd,
new UniqueTagList(tagSet)
);
}
@Override
public CommandResult execute() {
assert model != null;
try {
if(toAdd instanceof Event) {
model.addEvent(toAdd);
} else if(toAdd instanceof DeadlineTask) {
model.addDeadlineTask(toAdd);
} else {
model.addTask(toAdd);
}
return new CommandResult(String.format(MESSAGE_SUCCESS, toAdd));
} catch (UniqueTaskList.DuplicateTaskException e) {
return new CommandResult(MESSAGE_DUPLICATE_TASK);
}
}
@Override
public boolean isValidCommandWord(String commandWord) {
for (int i = 1; i <= COMMAND_WORD.length(); i++) {
if (commandWord.equals(COMMAND_WORD.substring(0, i))) {
return true;
}
}
return false;
}
}
|
package sk.mrtn.library.client.ticker;
import com.google.gwt.logging.client.LogConfiguration;
import com.google.gwt.user.client.Timer;
import jsinterop.annotations.JsFunction;
import jsinterop.annotations.JsMethod;
import jsinterop.annotations.JsPackage;
import sk.mrtn.library.client.utils.stats.Stats;
import javax.annotation.Nullable;
import javax.inject.Inject;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Ticker implements ITicker {
private final ITick tick;
private Stats stats;
private StatsTimer statsTimer;
private static class StatsTimer extends Timer {
private Stats stats;
public StatsTimer(final Stats stats) {
this.stats = stats;
}
@Override
public void run() {
this.stats.update();
}
}
@FunctionalInterface
@JsFunction
interface ITick {
void call();
}
protected static Logger LOG;
static {
if (LogConfiguration.loggingIsEnabled()) {
LOG = Logger.getLogger(Ticker.class.getSimpleName());
LOG.setLevel(Level.ALL);
}
}
private State state;
/**
* field is package protected so {@link sk.mrtn.library.client.ticker.TickableRegistration}
* can access method
*/
List<TickableRegistration> tickables;
private Date tickerStart;
private double currentTick;
private double previousTick;
private double deltaTick;
private Date tickerPauseStart;
private double tickerPausedMS;
private Integer requestId;
private boolean tickRequested;
private boolean ticking;
@Inject
protected Ticker(){
reset();
this.tickables = new ArrayList<>();
this.tick = new ITick() {
@Override
public void call() {
onTick();
}
};
}
@Override
public void setStats(final Stats stats) {
this.stats = stats;
if (this.stats != null) {
this.statsTimer = new StatsTimer(stats);
this.statsTimer.scheduleRepeating(1000);
this.stats.update();
}
}
@Override
public ITickableRegistration addTickable(ITickable tickable) {
if (!this.ticking) {
this.currentTick = getCurrentTick();
this.previousTick = this.currentTick;
}
TickableRegistration tickableRegistration = new TickableRegistration(this, tickable);
this.tickables.add(tickableRegistration);
requestAnimationFrame();
return tickableRegistration;
}
@Override
public State getState() {
return this.state;
}
@Override
public void pause() {
if (this.state == State.PAUSED) {
return;
}
this.state = State.PAUSED;
this.tickerPauseStart = new Date();
if (this.requestId != null) {
cancelAnimationFrame(this.requestId);
this.requestId = null;
}
this.previousTick = this.currentTick;
updateDeltaTick();
}
@Override
public void start() {
switch (state) {
case STOPPED:
reset();
break;
case PAUSED:
this.tickerPausedMS += new Date().getTime() - this.tickerPauseStart.getTime();
break;
case RUNNING:
return;
}
this.state = State.RUNNING;
this.currentTick = getCurrentTick();
this.previousTick = this.currentTick;
updateDeltaTick();
if (!this.ticking) {
this.tickRequested = false;
this.requestId = requestAnimationFrame(this.tick);
}
onTick();
}
@Override
public void stop() {
if (this.state == State.STOPPED) {
return;
}
this.state = State.STOPPED;
if (this.requestId != null) {
cancelAnimationFrame(this.requestId);
this.requestId = null;
}
reset();
updateDeltaTick();
}
@Override
public double getElapsedMS() {
return getCurrentTick() - this.tickerPausedMS;
}
@Override
public double getDeltaTick() {
return this.deltaTick;
}
private void reset() {
this.state = State.STOPPED;
this.tickerStart = new Date();
this.currentTick = getCurrentTick();
this.previousTick = this.currentTick;
this.tickerPausedMS = 0;
}
/**
* method is package protected so {@link sk.mrtn.library.client.ticker.TickableRegistration}
* can access method
*/
void requestAnimationFrame() {
if (this.state != State.RUNNING) {
return;
}
if (this.ticking) {
return;
}
this.ticking = true;
this.tickRequested = false;
this.requestId = requestAnimationFrame(this.tick);
}
private void onTick() {
new Timer() {
@Override
public void run() {
doTick();
}
}.schedule(0);
}
private void doTick() {
if (this.state == State.RUNNING) {
if (this.stats != null) {
this.stats.begin();
}
this.currentTick = getCurrentTick();
updateDeltaTick();
for (TickableRegistration tickableRegistration : new ArrayList<>(this.tickables)) {
ITickable tickable = tickableRegistration.getTickable();
tickable.update(this);
this.tickRequested = this.tickRequested || tickable.shouldTick();
}
this.previousTick = this.currentTick;
if (this.stats != null) {
this.stats.end();
}
if (shouldTick()) {
this.tickRequested = false;
this.requestId = requestAnimationFrame(this.tick);
} else {
updateDeltaTick();
this.ticking = false;
}
}
}
@Override
public void requestTick() {
onTick();
}
private boolean shouldTick() {
return this.tickRequested && this.state == State.RUNNING;
}
private double getCurrentTick() {
final long now = new Date().getTime() - this.tickerStart.getTime();
return now;
}
public void updateDeltaTick() {
this.deltaTick = this.currentTick - this.previousTick;
}
@JsMethod(namespace = JsPackage.GLOBAL)
private static native int requestAnimationFrame(Object object);
@JsMethod(namespace = JsPackage.GLOBAL)
private static native void cancelAnimationFrame(int id);
}
|
package studentcapture.submission;
import studentcapture.model.Grade;
import javax.validation.constraints.NotNull;
import java.sql.Timestamp;
import java.util.Map;
public class Submission {
@NotNull
private Integer assignmentID;
@NotNull
private Integer studentID;
private Boolean studentPublishConsent = false;
private Timestamp submissionDate;
private Grade grade;
private Boolean publishStudentSubmission = false;
private String courseID;
private String courseCode;
private String feedback;
private Boolean publishFeedback;
private Status subStatus;
private String firstName;
private String lastName;
private String status;
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
//A submission must have one of these statuses
public enum Status {
ANSWER("Answer"),
NOANSWER("NoAnswer"),
BLANK("Blank");
Status(String status) {
}
}
public Submission(int studentID, int assignmentID) {
this.studentID = studentID;
this.assignmentID = assignmentID;
}
public Submission() {
}
/**
* Constructor that parses map of database elements.
*
* @param map map retrieved from database
* @author tfy12hsm
*/
public Submission(Map<String, Object> map) {
// These three variables (assignmentID, studentID, submissionDate) cannot be null.
assignmentID = (Integer) map.get("AssignmentId");
studentID = (Integer) map.get("StudentId");
submissionDate = (Timestamp) map.get("SubmissionDate");
try {
firstName = (String) map.get("FirstName"); // Upper/lower-case doesn't matter
} catch (NullPointerException e) {
firstName = null;
}
try {
lastName = (String) map.get("LastName");
} catch (NullPointerException e) {
lastName = null;
}
try {
studentPublishConsent = (Boolean) map.get("StudentPublishConsent");
} catch (NullPointerException e) {
studentPublishConsent = null;
}
try {
status = (String) map.get("Status");
} catch (NullPointerException e) {
status = null;
}
try {
publishStudentSubmission = (Boolean) map.get("PublishStudentSubmission");
} catch (NullPointerException e) {
publishStudentSubmission = null;
}
}
public String getCourseID() {
return courseID;
}
public void setCourseID(String courseID) {
this.courseID = courseID;
}
public void setGrade(Grade grade) {
this.grade = grade;
}
public Grade getGrade() {
return grade;
}
public void studentAllowsPublication(boolean studentPublishConsent) {
this.studentPublishConsent = studentPublishConsent;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public Timestamp getSubmissionDate() {
return submissionDate;
}
public void setSubmissionDate(Timestamp submissionDate) {
this.submissionDate = submissionDate;
}
public int getStudentID() {
return studentID;
}
public void setStudentID(int studentID) {
this.studentID = studentID;
}
public int getAssignmentID() {
return assignmentID;
}
public void setAssignmentID(int assignmentID) {
this.assignmentID = assignmentID;
}
public boolean getStudentPublishConsent() {
return studentPublishConsent;
}
public void setStudentPublishConsent(boolean studentPublishConsent) {
this.studentPublishConsent = studentPublishConsent;
}
public String getCourseCode() {
return courseCode;
}
public void setCourseCode(String courseCode) {
this.courseCode = courseCode;
}
public String getFeedback() {
return feedback;
}
public void setFeedback(String feedback) {
this.feedback = feedback;
}
public Status getSubStatus() {
return subStatus;
}
public void setSubStatus(Status subStatus) {
this.subStatus = subStatus;
}
public void setPublishStudentSubmission(Boolean publishStudentSubmission) {
this.publishStudentSubmission = publishStudentSubmission;
}
public Boolean getPublishStudentSubmission() {
return publishStudentSubmission;
}
public Boolean getPublishFeedback() {
return publishFeedback;
}
public void setPublishFeedback(Boolean publishFeedback) {
this.publishFeedback = publishFeedback;
}
@Override
public String toString() {
return "Submission{" +
"\n\tassignmentID=" + assignmentID +
", \n\tstudentID=" + studentID +
", \n\tstudentPublishConsent=" + studentPublishConsent +
", \n\tsubmissionDate=" + submissionDate +
", \n\tgrade=" + grade +
", \n\tteacherID=" + grade.getTeacherID() +
", \n\tpublishStudentSubmission=" + publishStudentSubmission +
", \n\tcourseID='" + courseID + '\'' +
", \n\tcourseCode='" + courseCode + '\'' +
", \n\tfeedback='" + feedback + '\'' +
", \n\tsubStatus=" + subStatus +
", \n\tfirstName='" + firstName + '\'' +
", \n\tlastName='" + lastName + '\'' +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Submission that = (Submission) o;
if (assignmentID != null ? !assignmentID.equals(that.assignmentID) : that.assignmentID != null) return false;
if (studentID != null ? !studentID.equals(that.studentID) : that.studentID != null) return false;
if (studentPublishConsent != null ? !studentPublishConsent.equals(that.studentPublishConsent) : that.studentPublishConsent != null)
return false;
if (submissionDate != null ? !submissionDate.equals(that.submissionDate) : that.submissionDate != null)
return false;
if (grade.getGrade() != null ? !grade.getGrade().equals(that.grade.getGrade()) : that.grade.getGrade() != null) return false;
if (grade.getTeacherID() != null ? !grade.getTeacherID().equals(that.grade.getTeacherID()) : that.grade.getTeacherID() != null) return false;
if (publishStudentSubmission != null ? !publishStudentSubmission.equals(that.publishStudentSubmission) : that.publishStudentSubmission != null)
return false;
if (courseID != null ? !courseID.equals(that.courseID) : that.courseID != null) return false;
if (courseCode != null ? !courseCode.equals(that.courseCode) : that.courseCode != null) return false;
if (feedback != null ? !feedback.equals(that.feedback) : that.feedback != null) return false;
if (publishFeedback != null ? !publishFeedback.equals(that.publishFeedback) : that.publishFeedback != null)
return false;
if (subStatus != that.subStatus) return false;
if (firstName != null ? !firstName.equals(that.firstName) : that.firstName != null) return false;
if (lastName != null ? !lastName.equals(that.lastName) : that.lastName != null) return false;
return status != null ? status.equals(that.status) : that.status == null;
}
}
|
package uk.ac.edukapp.servlets;
import uk.ac.edukapp.model.*;
import uk.ac.edukapp.renderer.WookieServerConfiguration;
import uk.ac.edukapp.repository.SolrConnector;
import java.io.File;
import java.io.IOException;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.multipart.*;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* Servlet implementation class RegisterServlet
*/
public class UploadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private Log log;
private static final File FILE_UPLOAD_TEMP_DIRECTORY = new File(
System.getProperty("java.io.tmpdir"));
private int intMaxFileUploadSize = 25 * 1024 * 1024;// 25 mb is more than
// enough
/**
* @see HttpServlet#HttpServlet()
*/
public UploadServlet() {
super();
log = LogFactory.getLog(UploadServlet.class);
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
if (ServletFileUpload.isMultipartContent(request)) {// file attached
// =>widget invoke
// wookie/widgets
// rest service
DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
// Set factory constraints
diskFileItemFactory.setSizeThreshold(intMaxFileUploadSize);
diskFileItemFactory.setRepository(FILE_UPLOAD_TEMP_DIRECTORY);
// Create a new file upload handler
ServletFileUpload servletFileUpload = new ServletFileUpload(
diskFileItemFactory);
try {
// Get the multipart items as a list
List<FileItem> listFileItems = (List<FileItem>) servletFileUpload.parseRequest(request);
// Iterate the multipart items list
for (FileItem fileItemCurrent : listFileItems) {
// If the current item is a form field, then create a string
// part
if (!fileItemCurrent.isFormField()) {
// The item is a file upload, so we create a FilePart
FilePart filePart = new FilePart(
fileItemCurrent.getFieldName(),
new ByteArrayPartSource( fileItemCurrent.getName(),fileItemCurrent.get())
);
if (!uploadW3CWidget(filePart)){
doForward(request, response, "/upload.jsp?error=3");
}
}
}
} catch (HttpException hte) {
log.error("Fatal protocol violation: " + hte.getMessage());
hte.printStackTrace();
doForward(request, response, "/upload.jsp?error=4");
} catch (IOException ioe) {
log.error("Fatal transport error: " + ioe.getMessage());
ioe.printStackTrace();
doForward(request, response, "/upload.jsp?error=5");
} catch (FileUploadException fue) {
fue.printStackTrace();
doForward(request, response, "/upload.jsp?error=6");
} catch (Exception e) {
e.printStackTrace();
doForward(request, response, "/upload.jsp?error=9");
}
} else {
// get parameters
String uploadurl = null;
String gadgetName = null;
uploadurl = request.getParameter("uploadurl");
gadgetName = request.getParameter("gadget-name");
EntityManagerFactory factory = Persistence
.createEntityManagerFactory("edukapp");
EntityManager em = factory.createEntityManager();
Widgetprofile gadget = null;
try {
em.getTransaction().begin();
gadget = new Widgetprofile();
gadget.setName(gadgetName);
byte one = 1;
gadget.setW3cOrOs(one);
gadget.setWidId(uploadurl);
em.persist(gadget);
log.info("Gadget created with id:" + gadget.getId());
} catch (Exception e) {
e.printStackTrace();
// em.getTransaction().rollback();
doForward(request, response, "/upload.jsp?error=1");
}
em.getTransaction().commit();
em.close();
factory.close();
if (gadget != null) {
doForward(request, response, "/widget.jsp?id=" + gadget.getId());
} else {
doForward(request, response, "/upload.jsp?error=1");
}
}
}
private void doForward(HttpServletRequest request,
HttpServletResponse response, String jsp) throws ServletException,
IOException {
/*
* if we redirect using the dispatcher then the url in address bar does
* not update
*/
// RequestDispatcher dispatcher = getServletContext()
// .getRequestDispatcher(jsp);
// dispatcher.forward(request, response);
response.sendRedirect(jsp);
}
/**
* Upload a Widget to Wookie
* @param filePart
* @return true if the widget was successfully uploaded
* @throws HttpException
* @throws IOException
*/
private boolean uploadW3CWidget(FilePart filePart) throws HttpException, IOException{
HttpClient client = new HttpClient();
WookieServerConfiguration wookie = WookieServerConfiguration.getInstance();
client.getState().setCredentials(wookie.getAuthScope(), wookie.getCredentials());
PostMethod postMethod = new PostMethod(wookie.getWookieServerLocation()+"/widgets");
Part[] parts = {filePart};
postMethod.setRequestEntity(new MultipartRequestEntity(parts, postMethod.getParams()));
int status = client.executeMethod(postMethod);
if (status == 200 || status == 201){
// update the index
SolrConnector.getInstance().index();
return true;
}
return false;
}
}
|
package net.somethingdreadful.MAL;
import java.util.ArrayList;
import java.util.Calendar;
import net.somethingdreadful.MAL.NavigationItems.NavItem;
import net.somethingdreadful.MAL.api.MALApi;
import net.somethingdreadful.MAL.api.MALApi.ListType;
import net.somethingdreadful.MAL.api.response.Anime;
import net.somethingdreadful.MAL.api.response.Manga;
import net.somethingdreadful.MAL.sql.MALSqlHelper;
import net.somethingdreadful.MAL.tasks.AnimeNetworkTask;
import net.somethingdreadful.MAL.tasks.AnimeNetworkTaskFinishedListener;
import net.somethingdreadful.MAL.tasks.MangaNetworkTask;
import net.somethingdreadful.MAL.tasks.MangaNetworkTaskFinishedListener;
import net.somethingdreadful.MAL.tasks.TaskJob;
import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.NotificationCompat;
import android.support.v4.view.GravityCompat;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.ViewFlipper;
import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockDialogFragment;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.sherlock.navigationdrawer.compat.SherlockActionBarDrawerToggle;
import de.keyboardsurfer.android.widget.crouton.Crouton;
import de.keyboardsurfer.android.widget.crouton.Style;
public class Home extends BaseActionBarSearchView
implements ActionBar.TabListener, ItemGridFragment.IItemGridFragment,
LogoutConfirmationDialogFragment.LogoutConfirmationDialogListener {
/**
* The {@link android.support.v4.view.PagerAdapter} that will provide fragments for each of the
* sections. We use a {@link android.support.v4.app.FragmentPagerAdapter} derivative, which will
* keep every loaded fragment in memory. If this becomes too memory intensive, it may be best
* to switch to a {@link android.support.v4.app.FragmentStatePagerAdapter}.
*/
HomeSectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {@link ViewPager} that will host the section contents.
*/
ViewPager mViewPager;
Context context;
PrefManager mPrefManager;
public MALManager mManager;
private boolean init = false;
ItemGridFragment af;
ItemGridFragment mf;
public boolean instanceExists;
boolean networkAvailable;
BroadcastReceiver networkReceiver;
MenuItem searchItem;
int AutoSync = 0; //run or not to run.
private DrawerLayout mDrawerLayout;
private ListView listView;
private SherlockActionBarDrawerToggle mDrawerToggle;
private ActionBarHelper mActionBar;
View mActiveView;
View mPreviousView;
boolean myList = true; //tracks if the user is on 'My List' or not
private NavigationItemAdapter mNavigationItemAdapter;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = getApplicationContext();
mPrefManager = new PrefManager(context);
init = mPrefManager.getInit();
//The following is state handling code
instanceExists = savedInstanceState != null && savedInstanceState.getBoolean("instanceExists", false);
networkAvailable = savedInstanceState == null || savedInstanceState.getBoolean("networkAvailable", true);
if (savedInstanceState != null) {
AutoSync = savedInstanceState.getInt("AutoSync");
}
if (init) {
setContentView(R.layout.activity_home);
// Creates the adapter to return the Animu and Mango fragments
mSectionsPagerAdapter = new HomeSectionsPagerAdapter(getSupportFragmentManager());
mDrawerLayout= (DrawerLayout)findViewById(R.id.drawer_layout);
mDrawerLayout.setDrawerListener(new DemoDrawerListener());
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
listView = (ListView)findViewById(R.id.left_drawer);
NavigationItems mNavigationContent = new NavigationItems();
mNavigationItemAdapter = new NavigationItemAdapter(this,
R.layout.item_navigation, mNavigationContent.ITEMS);
listView.setAdapter(mNavigationItemAdapter);
listView.setOnItemClickListener(new DrawerItemClickListener());
listView.setCacheColorHint(0);
listView.setScrollingCacheEnabled(false);
listView.setScrollContainer(false);
listView.setFastScrollEnabled(true);
listView.setSmoothScrollbarEnabled(true);
mActionBar = createActionBarHelper();
mActionBar.init();
mDrawerToggle = new SherlockActionBarDrawerToggle(this, mDrawerLayout, R.drawable.ic_drawer_light, R.string.drawer_open, R.string.drawer_close);
mDrawerToggle.syncState();
mManager = new MALManager(context);
// Set up the action bar.
final ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
mViewPager.setPageMargin(32);
// When swiping between different sections, select the corresponding
// tab.
// We can also use ActionBar.Tab#select() to do this if we have a
// reference to the
// Tab.
mViewPager
.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
@Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
});
// Add tabs for the anime and manga lists
for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
// Create a tab with text corresponding to the page title
// defined by the adapter.
// Also specify this Activity object, which implements the
// TabListener interface, as the
// listener for when this tab is selected.
actionBar.addTab(actionBar.newTab()
.setText(mSectionsPagerAdapter.getPageTitle(i))
.setTabListener(this));
}
networkReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
checkNetworkAndDisplayCrouton();
}
};
} else { //If the app hasn't been configured, take us to the first run screen to sign in.
Intent firstRunInit = new Intent(this, FirstTimeInit.class);
firstRunInit.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(firstRunInit);
finish();
}
NfcHelper.disableBeam(this);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getSupportMenuInflater().inflate(R.menu.activity_home, menu);
searchItem = menu.findItem(R.id.action_search);
super.onCreateOptionsMenu(menu);
return true;
}
@Override
public MALApi.ListType getCurrentListType() {
String listName = getSupportActionBar().getSelectedTab().getText().toString();
return MALApi.getListTypeByString(listName);
}
public boolean isConnectedWifi() {
ConnectivityManager connManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo Wifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if (Wifi.isConnected()&& mPrefManager.getonly_wifiEnabled() ) {
return true;
} else {
return false;
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
switch (item.getItemId()) {
case R.id.menu_settings:
startActivity(new Intent(this, Settings.class));
break;
case R.id.menu_logout:
showLogoutDialog();
break;
case R.id.menu_about:
startActivity(new Intent(this, AboutActivity.class));
break;
case R.id.listType_all:
if (af != null && mf != null) {
af.getRecords(TaskJob.GETLIST, context, 0);
mf.getRecords(TaskJob.GETLIST, context, 0);
supportInvalidateOptionsMenu();
}
break;
case R.id.listType_inprogress:
if (af != null && mf != null) {
af.getRecords(TaskJob.GETLIST, context, 1);
mf.getRecords(TaskJob.GETLIST, context, 1);
supportInvalidateOptionsMenu();
}
break;
case R.id.listType_completed:
if (af != null && mf != null) {
af.getRecords(TaskJob.GETLIST, context, 2);
mf.getRecords(TaskJob.GETLIST, context, 2);
supportInvalidateOptionsMenu();
}
break;
case R.id.listType_onhold:
if (af != null && mf != null) {
af.getRecords(TaskJob.GETLIST, context, 3);
mf.getRecords(TaskJob.GETLIST, context, 3);
supportInvalidateOptionsMenu();
}
break;
case R.id.listType_dropped:
if (af != null && mf != null) {
af.getRecords(TaskJob.GETLIST, context, 4);
mf.getRecords(TaskJob.GETLIST, context, 4);
supportInvalidateOptionsMenu();
}
break;
case R.id.listType_planned:
if (af != null && mf != null) {
af.getRecords(TaskJob.GETLIST, context, 5);
mf.getRecords(TaskJob.GETLIST, Home.this.context, 5);
supportInvalidateOptionsMenu();
}
break;
case R.id.forceSync:
if (af != null && mf != null) {
af.getRecords(TaskJob.FORCESYNC, context, af.currentList);
mf.getRecords(TaskJob.FORCESYNC, context, mf.currentList);
syncNotify();
}
break;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onResume() {
super.onResume();
checkNetworkAndDisplayCrouton();
if (instanceExists && af.getMode() == TaskJob.GETLIST) {
af.getRecords(TaskJob.GETLIST, context, af.currentList);
mf.getRecords(TaskJob.GETLIST, context, mf.currentList);
}
registerReceiver(networkReceiver, new IntentFilter("android.net.conn.CONNECTIVITY_CHANGE"));
if (mSearchView != null) {
mSearchView.clearFocus();
mSearchView.setFocusable(false);
mSearchView.setQuery("", false);
searchItem.collapseActionView();
}
}
@Override
public void onPause() {
super.onPause();
instanceExists = true;
unregisterReceiver(networkReceiver);
}
@Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
@Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
// When the given tab is selected, switch to the corresponding page in the ViewPager.
mViewPager.setCurrentItem(tab.getPosition());
}
@Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
@Override
public void fragmentReady() {
//Interface implementation for knowing when the dynamically created fragment is finished loading
//We use instantiateItem to return the fragment. Since the fragment IS instantiated, the method returns it.
af = (net.somethingdreadful.MAL.ItemGridFragment) mSectionsPagerAdapter.instantiateItem(mViewPager, 0);
mf = (net.somethingdreadful.MAL.ItemGridFragment) mSectionsPagerAdapter.instantiateItem(mViewPager, 1);
af.setRecordType(ListType.ANIME);
mf.setRecordType(ListType.MANGA);
//auto-sync stuff
if (mPrefManager.getsync_time_last() == 0 && AutoSync == 0 && networkAvailable == true){
mPrefManager.setsync_time_last(1);
mPrefManager.commitChanges();
synctask();
} else if (mPrefManager.getsynchronisationEnabled() && AutoSync == 0 && networkAvailable == true){
Calendar localCalendar = Calendar.getInstance();
int Time_now = localCalendar.get(Calendar.DAY_OF_YEAR)*24*60; //will reset on new year ;)
Time_now = Time_now + localCalendar.get(Calendar.HOUR_OF_DAY)*60;
Time_now = Time_now + localCalendar.get(Calendar.MINUTE);
int last_sync = mPrefManager.getsync_time_last();
if (last_sync >= Time_now && last_sync <= (Time_now + mPrefManager.getsync_time())){
//no sync needed (This is inside the time range)
}else{
if (mPrefManager.getonly_wifiEnabled() == false){
synctask();
mPrefManager.setsync_time_last(Time_now + mPrefManager.getsync_time());
}else if (mPrefManager.getonly_wifiEnabled() && isConnectedWifi()){ //connected to Wi-Fi and sync only on Wi-Fi checked.
synctask();
mPrefManager.setsync_time_last(Time_now + mPrefManager.getsync_time());
}
}
mPrefManager.commitChanges();
}
}
public void synctask(){
af.getRecords(TaskJob.FORCESYNC, context, af.currentList);
mf.getRecords(TaskJob.FORCESYNC, context, mf.currentList);
syncNotify();
AutoSync = 1;
}
@Override
public void onSaveInstanceState(Bundle state) {
//This is telling out future selves that we already have some things and not to do them
state.putBoolean("instanceExists", true);
state.putBoolean("networkAvailable", networkAvailable);
state.putInt("AutoSync", AutoSync);
super.onSaveInstanceState(state);
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
MenuItem item = menu.findItem(R.id.menu_listType);
if(!myList){//if not on my list then disable menu items like listType, etc
item.setEnabled(false);
item.setVisible(false);
}
else{
item.setEnabled(true);
item.setVisible(true);
}
if (af != null) {
//All this is handling the ticks in the switch list menu
switch (af.currentList) {
case 0:
menu.findItem(R.id.listType_all).setChecked(true);
break;
case 1:
menu.findItem(R.id.listType_inprogress).setChecked(true);
break;
case 2:
menu.findItem(R.id.listType_completed).setChecked(true);
break;
case 3:
menu.findItem(R.id.listType_onhold).setChecked(true);
break;
case 4:
menu.findItem(R.id.listType_dropped).setChecked(true);
break;
case 5:
menu.findItem(R.id.listType_planned).setChecked(true);
}
}
if (networkAvailable) {
if (myList){
menu.findItem(R.id.forceSync).setVisible(true);
}else{
menu.findItem(R.id.forceSync).setVisible(false);
}
menu.findItem(R.id.action_search).setVisible(true);
}
else {
menu.findItem(R.id.forceSync).setVisible(false);
menu.findItem(R.id.action_search).setVisible(false);
AutoSync = 1;
}
return true;
}
@SuppressLint("NewApi")
@Override
public void onLogoutConfirmed() {
mPrefManager.setInit(false);
mPrefManager.setUser("");
mPrefManager.setPass("");
mPrefManager.commitChanges();
context.deleteDatabase(MALSqlHelper.getHelper(context).getDatabaseName());
startActivity(new Intent(this, Home.class).addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
finish();
}
private void syncNotify() {
Crouton.makeText(this, R.string.crouton_info_SyncMessage, Style.INFO).show();
Intent notificationIntent = new Intent(context, Home.class);
PendingIntent contentIntent = PendingIntent.getActivity(context, 1, notificationIntent, PendingIntent.FLAG_CANCEL_CURRENT);
NotificationManager nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
Notification syncNotification = new NotificationCompat.Builder(context).setOngoing(true)
.setContentIntent(contentIntent)
.setSmallIcon(R.drawable.icon)
.setContentTitle(getString(R.string.app_name))
.setContentText(getString(R.string.crouton_info_SyncMessage))
.getNotification();
nm.notify(R.id.notification_sync, syncNotification);
myList = true;
supportInvalidateOptionsMenu();
}
private void showLogoutDialog() {
FragmentManager fm = getSupportFragmentManager();
LogoutConfirmationDialogFragment lcdf = new LogoutConfirmationDialogFragment();
if (Build.VERSION.SDK_INT >= 11) {
lcdf.setStyle(SherlockDialogFragment.STYLE_NORMAL, android.R.style.Theme_Holo_Dialog);
} else {
lcdf.setStyle(SherlockDialogFragment.STYLE_NORMAL, 0);
}
lcdf.show(fm, "fragment_LogoutConfirmationDialog");
}
public void checkNetworkAndDisplayCrouton() {
if (!MALApi.isNetworkAvailable(context) && networkAvailable == true) {
Crouton.makeText(this, R.string.crouton_error_noConnectivityOnRun, Style.ALERT).show();
af = (net.somethingdreadful.MAL.ItemGridFragment) mSectionsPagerAdapter.instantiateItem(mViewPager, 0);
mf = (net.somethingdreadful.MAL.ItemGridFragment) mSectionsPagerAdapter.instantiateItem(mViewPager, 1);
if (af.getMode() != null) {
af.setMode(null);
mf.setMode(null);
af.getRecords(TaskJob.GETLIST, context, af.currentList);
mf.getRecords(TaskJob.GETLIST, context, mf.currentList);
}
} else if (MALApi.isNetworkAvailable(context) && networkAvailable == false) {
Crouton.makeText(this, R.string.crouton_info_connectionRestored, Style.INFO).show();
synctask();
}
if (!MALApi.isNetworkAvailable(context)) {
networkAvailable = false;
} else {
networkAvailable = true;
}
supportInvalidateOptionsMenu();
}
/*private classes for nav drawer*/
private ActionBarHelper createActionBarHelper() {
return new ActionBarHelper();
}
public class DrawerItemClickListener implements ListView.OnItemClickListener {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
/* do stuff when drawer item is clicked here */
af.scrollToTop();
mf.scrollToTop();
if (!networkAvailable && position > 2) {
position = 1;
Crouton.makeText(Home.this, R.string.crouton_error_noConnectivity, Style.ALERT).show();
}
myList = (position == 1);
switch (position){
case 0:
Intent Profile = new Intent(context, net.somethingdreadful.MAL.ProfileActivity.class);
Profile.putExtra("username", mPrefManager.getUser());
startActivity(Profile);
break;
case 1:
af.getRecords(TaskJob.GETLIST, Home.this.context, af.currentList);
mf.getRecords(TaskJob.GETLIST, Home.this.context, mf.currentList);
break;
case 2:
Intent Friends = new Intent(context, net.somethingdreadful.MAL.FriendsActivity.class);
startActivity(Friends);
break;
case 3:
af.getRecords(TaskJob.GETTOPRATED, Home.this.context);
mf.getRecords(TaskJob.GETTOPRATED, Home.this.context);
af.scrollListener.resetPageNumber();
mf.scrollListener.resetPageNumber();
break;
case 4:
af.getRecords(TaskJob.GETMOSTPOPULAR, Home.this.context);
mf.getRecords(TaskJob.GETMOSTPOPULAR, Home.this.context);
af.scrollListener.resetPageNumber();
mf.scrollListener.resetPageNumber();
break;
case 5:
af.getRecords(TaskJob.GETJUSTADDED, Home.this.context);
mf.getRecords(TaskJob.GETJUSTADDED, Home.this.context);
af.scrollListener.resetPageNumber();
mf.scrollListener.resetPageNumber();
break;
case 6:
af.getRecords(TaskJob.GETUPCOMING, Home.this.context);
mf.getRecords(TaskJob.GETUPCOMING, Home.this.context);
af.scrollListener.resetPageNumber();
mf.scrollListener.resetPageNumber();
break;
}
Home.this.supportInvalidateOptionsMenu();
//This part is for figuring out which item in the nav drawer is selected and highlighting it with colors
mPreviousView = mActiveView;
if (mPreviousView != null)
mPreviousView.setBackgroundColor(Color.parseColor("#333333")); //dark color
mActiveView = view;
mActiveView.setBackgroundColor(Color.parseColor("#38B2E1")); //blue color
mDrawerLayout.closeDrawer(listView);
}
}
private class DemoDrawerListener implements DrawerLayout.DrawerListener {
@Override
public void onDrawerOpened(View drawerView) {
mDrawerToggle.onDrawerOpened(drawerView);
mActionBar.onDrawerOpened();
}
@Override
public void onDrawerClosed(View drawerView) {
mDrawerToggle.onDrawerClosed(drawerView);
mActionBar.onDrawerClosed();
}
@Override
public void onDrawerSlide(View drawerView, float slideOffset) {
mDrawerToggle.onDrawerSlide(drawerView, slideOffset);
}
@Override
public void onDrawerStateChanged(int newState) {
mDrawerToggle.onDrawerStateChanged(newState);
}
}
private class ActionBarHelper {
private final ActionBar mActionBar;
private CharSequence mDrawerTitle;
private CharSequence mTitle;
private ActionBarHelper() {
mActionBar = getSupportActionBar();
}
public void init() {
mActionBar.setDisplayHomeAsUpEnabled(true);
mActionBar.setHomeButtonEnabled(true);
mTitle = mDrawerTitle = getTitle();
}
/**
* When the drawer is closed we restore the action bar state reflecting
* the specific contents in view.
*/
public void onDrawerClosed() {
mActionBar.setTitle(mTitle);
}
/**
* When the drawer is open we set the action bar to a generic title. The
* action bar should only contain data relevant at the top level of the
* nav hierarchy represented by the drawer, as the rest of your content
* will be dimmed down and non-interactive.
*/
public void onDrawerOpened() {
mActionBar.setTitle(mDrawerTitle);
}
}
private class NavigationItemAdapter extends ArrayAdapter<NavItem> {
private ArrayList<NavItem> items;
public NavigationItemAdapter(Context context, int textViewResourceId,
ArrayList<NavItem> objects) {
super(context, textViewResourceId, objects);
this.items = objects;
}
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = getLayoutInflater();
v = vi.inflate(R.layout.item_navigation, null);
}
NavItem item = items.get(position);
if (item != null) {
ImageView mIcon = (ImageView) v
.findViewById(R.id.nav_item_icon);
TextView mTitle = (TextView) v.findViewById(R.id.nav_item_text);
if (mIcon != null) {
mIcon.setImageResource(item.icon);
} else {
Log.d("LISTITEM", "Null");
}
if (mTitle != null) {
mTitle.setText(item.title);
} else {
Log.d("LISTITEM", "Null");
}
}
return v;
}
}
}
|
package com.raizlabs.baseutils;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import android.util.Log;
public class IOUtils {
/**
* Utility method for pulling plain text from an InputStream object
* @param in InputStream object retrieved from an HttpResponse
* @return String contents of stream
*/
public static String readStream(InputStream in)
{
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder sb = new StringBuilder();
String line = null;
try
{
while((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
}
catch(Exception ex) { }
finally
{
safeClose(in);
safeClose(reader);
}
return sb.toString();
}
/**
* Reads the given input stream into a byte array. Note that this is done
* entirely in memory, so the input should not be very large.
* @param input The stream to read.
* @return The byte array containing all the data from the input stream or
* null if there was a problem.
*/
public static byte[] readStreamBytes(InputStream input) {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
if (copyStream(input, outputStream)) {
return outputStream.toByteArray();
}
return null;
}
/**
* Feeds the entire input stream into the output stream.
* @param input The stream to copy from.
* @param output The stream to copy into.
* @return True if the copy succeeded, false if it failed.
*/
public static boolean copyStream(InputStream input, OutputStream output) {
return copyStream(input, output, 4096);
}
/**
* Feeds the entire input stream into the output stream.
* @param input The stream to copy from.
* @param output The stream to copy into.
* @param bufferSize The size of the buffer to use.
* @return True if the copy succeeded, false if it failed.
*/
public static boolean copyStream(InputStream input, OutputStream output, int bufferSize) {
byte[] buffer = new byte[bufferSize];
try {
int bytesRead;
while ((bytesRead = input.read(buffer)) != -1) {
output.write(buffer, 0, bytesRead);
}
return true;
} catch (IOException e) {
Log.w(IOUtils.class.getSimpleName(), "Error copying stream", e);
return false;
}
}
/**
* Safely closes the given {@link Closeable} without throwing
* any exceptions due to null pointers or {@link IOException}s.
* @param closeable The {@link Closeable} to close.
*/
public static void safeClose(Closeable closeable)
{
if(closeable != null)
{
try
{
closeable.close();
}
catch (IOException e) { }
}
}
/**
* Creates an {@link InputStream} from the data in the given string.
* @param str The string to set as the contents of the stream.
* @return The created {@link InputStream}
*/
public static InputStream getInputStream(String str) {
return new ByteArrayInputStream(str.getBytes());
}
/**
* Deletes the file or directory at the given path using the rm shell
* command.
* @param path Path to the file to delete.
* @param recursive True to do the delete recursively, else false.
* @return True if the file existed and was deleted, or false if it didn't
* exist.
* @throws IOException if the shell execution fails.
*/
public static boolean deleteViaShell(String path, boolean recursive)
throws IOException {
File file = new File(path);
if (file.exists()) {
String deleleteCommand = (recursive ? "rm -r " : "rm ") + path;
Runtime runtime = Runtime.getRuntime();
runtime.exec(deleleteCommand);
return true;
}
return false;
}
/**
* Deletes the file or directory at the given path using the rm shell
* command.
* @param file The {@link File} to delete.
* @param recursive True to do the delete recursively, else false.
* @return True if the file existed and was deleted, or false if it didn't
* exist.
* @throws IOException if the shell execution fails.
*/
public static boolean deleteViaShell(File file, boolean recursive)
throws IOException {
if (file.exists()) {
String deleleteCommand = (recursive ? "rm -r " : "rm ")
+ file.getAbsolutePath();
Runtime runtime = Runtime.getRuntime();
runtime.exec(deleleteCommand);
return true;
}
return false;
}
}
|
package io.branch.referral;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.util.Log;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
/**
* <p>A class that uses the helper pattern to provide regularly referenced static values and
* logging capabilities used in various other parts of the SDK, and that are related to globally set
* preference values.</p>
*/
public class PrefHelper {
/**
* {@link Boolean} value that enables/disables Branch developer external debug mode.
*/
private static boolean BNC_Dev_Debug = false;
/**
* {@link Boolean} value that enables/disables Branch logging.
*/
private static boolean BNC_Logging = false;
/**
* {@link Boolean} value that determines whether external App Listing is enabled or not.
*
* @see {@link Branch#scheduleListOfApps()}
* @see {@link SystemObserver#getListOfApps()}
*/
private static boolean BNC_App_Listing = false;
/**
* A {@link String} value used where no string value is available.
*/
public static final String NO_STRING_VALUE = "bnc_no_value";
// We should keep this non-zero to give the connection time to recover after a failure
private static final int INTERVAL_RETRY = 1000;
/**
* Number of times to reattempt connection to the Branch server before giving up and throwing an
* exception.
*/
private static final int MAX_RETRIES = 3; // Default retry count is 3
private static final int TIMEOUT = 5500; // Default timeout id 5.5 sec
private static final String SHARED_PREF_FILE = "branch_referral_shared_pref";
private static final String KEY_BRANCH_KEY = "bnc_branch_key";
private static final String KEY_APP_VERSION = "bnc_app_version";
private static final String KEY_DEVICE_FINGERPRINT_ID = "bnc_device_fingerprint_id";
private static final String KEY_SESSION_ID = "bnc_session_id";
private static final String KEY_IDENTITY_ID = "bnc_identity_id";
private static final String KEY_IDENTITY = "bnc_identity";
private static final String KEY_LINK_CLICK_ID = "bnc_link_click_id";
private static final String KEY_LINK_CLICK_IDENTIFIER = "bnc_link_click_identifier";
private static final String KEY_GOOGLE_SEARCH_INSTALL_IDENTIFIER = "bnc_google_search_install_identifier";
private static final String KEY_GOOGLE_PLAY_INSTALL_REFERRER_EXTRA = "bnc_google_play_install_referrer_extras";
private static final String KEY_IS_TRIGGERED_BY_FB_APP_LINK = "bnc_triggered_by_fb_app_link";
private static final String KEY_APP_LINK = "bnc_app_link";
private static final String KEY_PUSH_IDENTIFIER = "bnc_push_identifier";
private static final String KEY_SESSION_PARAMS = "bnc_session_params";
private static final String KEY_INSTALL_PARAMS = "bnc_install_params";
private static final String KEY_USER_URL = "bnc_user_url";
private static final String KEY_IS_REFERRABLE = "bnc_is_referrable";
private static final String KEY_BUCKETS = "bnc_buckets";
private static final String KEY_CREDIT_BASE = "bnc_credit_base_";
private static final String KEY_ACTIONS = "bnc_actions";
private static final String KEY_TOTAL_BASE = "bnc_total_base_";
private static final String KEY_UNIQUE_BASE = "bnc_balance_base_";
private static final String KEY_RETRY_COUNT = "bnc_retry_count";
private static final String KEY_RETRY_INTERVAL = "bnc_retry_interval";
private static final String KEY_TIMEOUT = "bnc_timeout";
private static final String KEY_LAST_READ_SYSTEM = "bnc_system_read_date";
private static final String KEY_EXTERNAL_INTENT_URI = "bnc_external_intent_uri";
private static final String KEY_EXTERNAL_INTENT_EXTRA = "bnc_external_intent_extra";
private static final String KEY_BRANCH_VIEW_NUM_OF_USE = "bnc_branch_view_use";
private static final String KEY_BRANCH_ANALYTICAL_DATA = "bnc_branch_analytical_data";
private static final String KEY_LAST_STRONG_MATCH_TIME = "bnc_branch_strong_match_time";
private static final String KEY_INSTALL_REFERRER = "bnc_install_referrer";
private static final String KEY_IS_FULL_APP_CONVERSION = "bnc_is_full_app_conversion";
private static String Branch_Key = null;
/**
* Internal static variable of own type {@link PrefHelper}. This variable holds the single
* instance used when the class is instantiated via the Singleton pattern.
*/
private static PrefHelper prefHelper_;
/**
* A single variable that holds a reference to the application's {@link SharedPreferences}
* object for use whenever {@link SharedPreferences} values are read or written via this helper
* class.
*/
private SharedPreferences appSharedPrefs_;
/**
* A single variable that holds a reference to an {@link Editor} object that is used by the
* helper class whenever the preferences for the application are changed.
*/
private Editor prefsEditor_;
/**
* Arbitrary key values added to all requests.
*/
private JSONObject requestMetadata;
/**
* Reference of application {@link Context}, normally the base context of the application.
*/
private Context context_;
/**
* Branch Content discovery data
*/
private static JSONObject savedAnalyticsData_;
/**
* <p>Empty, but required constructor for the {@link PrefHelper} {@link SharedPreferences}
* helper class.</p>
*/
public PrefHelper() {
}
/**
* <p>Constructor with context passed from calling {@link Activity}.</p>
*
* @param context A reference to the {@link Context} that the application is operating
* within. This is normally the base context of the application.
*/
private PrefHelper(Context context) {
this.appSharedPrefs_ = context.getSharedPreferences(SHARED_PREF_FILE,
Context.MODE_PRIVATE);
this.prefsEditor_ = this.appSharedPrefs_.edit();
this.context_ = context;
this.requestMetadata = new JSONObject();
}
/**
* <p>Singleton method to return the pre-initialised, or newly initialise and return, a singleton
* object of the type {@link PrefHelper}.</p>
*
* @param context The {@link Context} within which the object should be instantiated; this
* parameter is passed to the private {@link #PrefHelper(Context)}
* constructor method.
* @return A {@link PrefHelper} object instance.
*/
public static PrefHelper getInstance(Context context) {
if (prefHelper_ == null) {
prefHelper_ = new PrefHelper(context);
}
return prefHelper_;
}
/**
* <p>Returns the base URL to use for all calls to the Branch API as a {@link String}.</p>
*
* @return A {@link String} variable containing the hard-coded base URL that the Branch
* API uses.
*/
public String getAPIBaseUrl() {
return "https://api.branch.io/";
}
/**
* <p>Sets the duration in milliseconds to override the timeout value for calls to the Branch API.</p>
*
* @param timeout The {@link Integer} value of the timeout setting in milliseconds.
*/
public void setTimeout(int timeout) {
setInteger(KEY_TIMEOUT, timeout);
}
/**
* <p>Returns the currently set timeout value for calls to the Branch API. This will be the default
* SDK setting unless it has been overridden manually between Branch object instantiation and
* this call.</p>
*
* @return An {@link Integer} value containing the currently set timeout value in
* milliseconds.
*/
public int getTimeout() {
return getInteger(KEY_TIMEOUT, TIMEOUT);
}
/**
* <p>Sets the value specifying the number of times that a Branch API call has been re-attempted.</p>
*
* <p>This overrides the default retry value.</p>
*
* @param retry An {@link Integer} value specifying the value to be specified in preferences
* that determines the number of times that a Branch API call has been re-
* attempted.
*/
public void setRetryCount(int retry) {
setInteger(KEY_RETRY_COUNT, retry);
}
/**
* <p>Gets the current count of the number of times that a Branch API call has been re-attempted.</p>
*
* @return An {@link Integer} value containing the current count of the number of times
* that a Branch API call has been attempted.
*/
public int getRetryCount() {
return getInteger(KEY_RETRY_COUNT, MAX_RETRIES);
}
/**
* <p>Sets the amount of time in milliseconds to wait before re-attempting a timed-out request
* to the Branch API.</p>
*
* @param retryInt An {@link Integer} value specifying the number of milliseconds to wait
* before re-attempting a timed-out request.
*/
public void setRetryInterval(int retryInt) {
setInteger(KEY_RETRY_INTERVAL, retryInt);
}
/**
* <p>Gets the amount of time in milliseconds to wait before re-attempting a timed-out request
* to the Branch API.</p>
*
* @return An {@link Integer} value containing the currently set retry interval in
* milliseconds.
*/
public int getRetryInterval() {
return getInteger(KEY_RETRY_INTERVAL, INTERVAL_RETRY);
}
/**
* <p>Sets the value of {@link #KEY_APP_VERSION} in preferences.</p>
*
* @param version A {@link String} value containing the current app version.
*/
public void setAppVersion(String version) {
setString(KEY_APP_VERSION, version);
}
/**
* <p>Returns the current value of {@link #KEY_APP_VERSION} as stored in preferences.</p>
*
* @return A {@link String} value containing the current app version.
*/
public String getAppVersion() {
return getString(KEY_APP_VERSION);
}
/**
* Set the given Branch Key to preference. Clears the preference data if the key is a new key.
*
* @param key A {@link String} representing Branch Key.
* @return A {@link Boolean} which is true if the key set is a new key. On Setting a new key need to clear all preference items.
*/
public boolean setBranchKey(String key) {
Branch_Key = key;
String currentBranchKey = getString(KEY_BRANCH_KEY);
if (key == null || currentBranchKey == null || !currentBranchKey.equals(key)) {
clearPrefOnBranchKeyChange();
setString(KEY_BRANCH_KEY, key);
return true;
}
return false;
}
public String getBranchKey() {
if (Branch_Key == null) {
Branch_Key = getString(KEY_BRANCH_KEY);
}
return Branch_Key;
}
public String readBranchKey(boolean isLive) {
String branchKey = null;
String metaDataKey = isLive ? "io.branch.sdk.BranchKey" : "io.branch.sdk.BranchKey.test";
if (!isLive) {
setExternDebug();
}
try {
final ApplicationInfo ai = context_.getPackageManager().getApplicationInfo(context_.getPackageName(), PackageManager.GET_META_DATA);
if (ai.metaData != null) {
branchKey = ai.metaData.getString(metaDataKey);
if (branchKey == null && !isLive) {
branchKey = ai.metaData.getString("io.branch.sdk.BranchKey");
}
}
} catch (final PackageManager.NameNotFoundException ignore) {
}
// If Branch key is not specified in the manifest check String resource
if (TextUtils.isEmpty(branchKey)) {
try {
Resources resources = context_.getResources();
branchKey = resources.getString(resources.getIdentifier(metaDataKey, "string", context_.getPackageName()));
} catch (Exception ignore) {
}
}
if (branchKey == null) {
branchKey = NO_STRING_VALUE;
}
return branchKey;
}
/**
* <p>Sets the {@link android.os.Build#FINGERPRINT} value of the current OS build, on the current device,
* as a {@link String} in preferences.</p>
*
* @param device_fingerprint_id A {@link String} that uniquely identifies this build.
*/
public void setDeviceFingerPrintID(String device_fingerprint_id) {
setString(KEY_DEVICE_FINGERPRINT_ID, device_fingerprint_id);
}
/**
* <p>Gets the {@link android.os.Build#FINGERPRINT} value of the current OS build, on the current device,
* as a {@link String} from preferences.</p>
*
* @return A {@link String} that uniquely identifies this build.
*/
public String getDeviceFingerPrintID() {
return getString(KEY_DEVICE_FINGERPRINT_ID);
}
/**
* <p>Sets the ID of the {@link #KEY_SESSION_ID} {@link String} value in preferences.</p>
*
* @param session_id A {@link String} value containing the session ID as returned by the
* Branch API upon successful initialisation.
*/
public void setSessionID(String session_id) {
setString(KEY_SESSION_ID, session_id);
}
/**
* <p>Gets the ID of the {@link #KEY_SESSION_ID} {@link String} value from preferences.</p>
*
* @return A {@link String} value containing the session ID as returned by the Branch
* API upon successful initialisation.
*/
public String getSessionID() {
return getString(KEY_SESSION_ID);
}
/**
* <p>Sets the {@link #KEY_IDENTITY_ID} {@link String} value that has been set via the Branch API.</p>
*
* <p>This is used to identify a specific <b>user ID</b> and link that to a current session. Useful both
* for analytics and debugging purposes.</p>
*
* <p><b>Note: </b> Not to be confused with {@link #setIdentity(String)} - the name of the user</p>
*
* @param identity_id A {@link String} value containing the currently configured identity
* within preferences.
*/
public void setIdentityID(String identity_id) {
setString(KEY_IDENTITY_ID, identity_id);
}
/**
* <p>Gets the {@link #KEY_IDENTITY_ID} {@link String} value that has been set via the Branch API.</p>
*
* @return A {@link String} value containing the currently configured user id within
* preferences.
*/
public String getIdentityID() {
return getString(KEY_IDENTITY_ID);
}
/**
* <p>Sets the {@link #KEY_IDENTITY} {@link String} value that has been set via the Branch API.</p>
*
* <p>This is used to identify a specific <b>user identity</b> and link that to a current session. Useful both
* for analytics and debugging purposes.</p>
*
* <p><b>Note: </b> Not to be confused with {@link #setIdentityID(String)} - the UID reference of the user</p>
*
* @param identity A {@link String} value containing the currently configured identity
* within preferences.
*/
public void setIdentity(String identity) {
setString(KEY_IDENTITY, identity);
}
/**
* <p>Gets the {@link #KEY_IDENTITY} {@link String} value that has been set via the Branch API.</p>
*
* <p>This is used to identify a specific <b>user identity</b> and link that to a current session. Useful both
* for analytics and debugging purposes.</p>
*
* @return A {@link String} value containing the username assigned to the currentuser ID.
*/
public String getIdentity() {
return getString(KEY_IDENTITY);
}
/**
* <p>Sets the {@link #KEY_LINK_CLICK_ID} {@link String} value that has been set via the Branch API.</p>
*
* @param link_click_id A {@link String} value containing the identifier of the
* associated link.
*/
public void setLinkClickID(String link_click_id) {
setString(KEY_LINK_CLICK_ID, link_click_id);
}
/**
* <p>Gets the {@link #KEY_LINK_CLICK_ID} {@link String} value that has been set via the Branch API.</p>
*
* @return A {@link String} value containing the identifier of the associated link.
*/
public String getLinkClickID() {
return getString(KEY_LINK_CLICK_ID);
}
/**
* Set the value to specify if the current init is triggered by an FB app link
*
* @param isAppLinkTriggered {@link Boolean} with value for triggered by an FB app link state
*/
public void setIsAppLinkTriggeredInit(Boolean isAppLinkTriggered) {
setBool(KEY_IS_TRIGGERED_BY_FB_APP_LINK, isAppLinkTriggered);
}
/**
* Specifies the value to specify if the current init is triggered by an FB app link
*
* @return {@link Boolean} with value true if the init is triggered by an FB app link
*/
public boolean getIsAppLinkTriggeredInit() {
return getBool(KEY_IS_TRIGGERED_BY_FB_APP_LINK);
}
/**
* <p>Sets the {@link #KEY_EXTERNAL_INTENT_URI} with value with given intent URI String.</p>
*
* @param uri A {@link String} value containing intent URI to set
*/
public void setExternalIntentUri(String uri) {
setString(KEY_EXTERNAL_INTENT_URI, uri);
}
/**
* <p>Gets the {@link #KEY_EXTERNAL_INTENT_URI} {@link String} value that has been set via the Branch API.</p>
*
* @return A {@link String} value containing external URI set.
*/
public String getExternalIntentUri() {
return getString(KEY_EXTERNAL_INTENT_URI);
}
/**
* <p>Sets the {@link #KEY_EXTERNAL_INTENT_EXTRA} with value with given intent extras in string format.</p>
*
* @param extras A {@link String} value containing intent URI extra to set
*/
public void setExternalIntentExtra(String extras) {
setString(KEY_EXTERNAL_INTENT_EXTRA, extras);
}
/**
* <p>Gets the {@link #KEY_EXTERNAL_INTENT_EXTRA} {@link String} value that has been set via the Branch API.</p>
*
* @return A {@link String} value containing external intent extra set.
*/
public String getExternalIntentExtra() {
return getString(KEY_EXTERNAL_INTENT_EXTRA);
}
/**
* <p>Sets the KEY_LINK_CLICK_IDENTIFIER {@link String} value that has been set via the Branch API.</p>
*
* @param identifier A {@link String} value containing the identifier of the associated
* link.
*/
public void setLinkClickIdentifier(String identifier) {
setString(KEY_LINK_CLICK_IDENTIFIER, identifier);
}
/**
* <p>Gets the KEY_LINK_CLICK_IDENTIFIER {@link String} value that has been set via the Branch API.</p>
*
* @return A {@link String} value containing the identifier of the associated link.
*/
public String getLinkClickIdentifier() {
return getString(KEY_LINK_CLICK_IDENTIFIER);
}
/**
* Sets the Google install referrer identifier to the pref
*
* @param identifier Google install referrer identifier
*/
public void setGoogleSearchInstallIdentifier(String identifier) {
setString(KEY_GOOGLE_SEARCH_INSTALL_IDENTIFIER, identifier);
}
/**
* Gets the google install referrer identifier
*
* @return {@link String} google install referrer identifier
*/
public String getGoogleSearchInstallIdentifier() {
return getString(KEY_GOOGLE_SEARCH_INSTALL_IDENTIFIER);
}
/**
* Sets the Google play install referrer string
*
* @param referrer Google play install referrer string
*/
public void setGooglePlayReferrer(String referrer) {
setString(KEY_GOOGLE_PLAY_INSTALL_REFERRER_EXTRA, referrer);
}
/**
* Gets the google play install referrer string
*
* @return {@link String} Google play install referrer string
*/
public String getGooglePlayReferrer() {
return getString(KEY_GOOGLE_PLAY_INSTALL_REFERRER_EXTRA);
}
/**
* <p> Set the KEY_APP_LINK {@link String} values that has been started the application. </p>
*
* @param appLinkUrl The App link which started this application
*/
public void setAppLink(String appLinkUrl) {
setString(KEY_APP_LINK, appLinkUrl);
}
/**
* <p> Get the App link which statrted the application.</p>
*
* @return A {@link String} value of App link url
*/
public String getAppLink() {
return getString(KEY_APP_LINK);
}
/**
* Set the value for the full app conversion state. If set true indicate that this session is
* initiated by a full app conversion flow
*
* @param isFullAppConversion {@link Boolean} with value for full app conversion state
*/
public void setIsFullAppConversion(boolean isFullAppConversion) {
setBool(KEY_IS_FULL_APP_CONVERSION, isFullAppConversion);
}
/**
* Get the value for the full app conversion state.
*
* @return {@code true} if the session is initiated by a full app conversion flow
*/
public boolean isFullAppConversion() {
return getBool(KEY_IS_FULL_APP_CONVERSION);
}
/**
* <p> Set the KEY_PUSH_IDENTIFIER {@link String} values that has been started the application. </p>
*
* @param pushIdentifier The Branch url with the push notification which started the app.
*/
public void setPushIdentifier(String pushIdentifier) {
setString(KEY_PUSH_IDENTIFIER, pushIdentifier);
}
/**
* <p> Get the branch url in push payload which started the application.</p>
*
* @return A {@link String} value of push identifier
*/
public String getPushIdentifier() {
return getString(KEY_PUSH_IDENTIFIER);
}
/**
* <p>Gets the session parameters as currently set in preferences.</p>
*
* <p>Parameters are stored in JSON format, and must be parsed prior to access.</p>
*
* @return A {@link String} value containing the JSON-encoded structure of parameters for
* the current session.
*/
public String getSessionParams() {
return getString(KEY_SESSION_PARAMS);
}
/**
* <p>Sets the session parameters as currently set in preferences.</p>
*
* @param params A {@link String} value containing the JSON-encoded structure of
* parameters for the current session.
*/
public void setSessionParams(String params) {
setString(KEY_SESSION_PARAMS, params);
}
/**
* <p>Gets the session parameters as originally set at time of app installation, in preferences.</p>
*
* @return A {@link String} value containing the JSON-encoded structure of parameters as
* they were at the time of installation.
*/
public String getInstallParams() {
return getString(KEY_INSTALL_PARAMS);
}
/**
* <p>Sets the session parameters as originally set at time of app installation, in preferences.</p>
*
* @param params A {@link String} value containing the JSON-encoded structure of
* parameters as they should be at the time of installation.
*/
public void setInstallParams(String params) {
setString(KEY_INSTALL_PARAMS, params);
}
public void setInstallReferrerParams(String params) {
setString(KEY_INSTALL_REFERRER, params);
}
public String getInstallReferrerParams() {
return getString(KEY_INSTALL_REFERRER);
}
/**
* <p>Sets the user URL from preferences.</p>
*
* @param user_url A {@link String} value containing the current user URL.
*/
public void setUserURL(String user_url) {
setString(KEY_USER_URL, user_url);
}
/**
* <p>Sets the user URL from preferences.</p>
*
* @return A {@link String} value containing the current user URL.
*/
public String getUserURL() {
return getString(KEY_USER_URL);
}
/**
* <p>Gets the {@link Integer} value of the preference setting {@link #KEY_IS_REFERRABLE}, which
* indicates whether or not the current session should be considered referrable.</p>
*
* @return A {@link Integer} value indicating whether or not the session should be
* considered referrable.
*/
public int getIsReferrable() {
return getInteger(KEY_IS_REFERRABLE);
}
/**
* <p>Sets the {@link #KEY_IS_REFERRABLE} value in preferences to 1, or <i>true</i> if parsed as a {@link Boolean}.
* This value is used by the {@link Branch} object.</p>
* <ul>
* <li>Sets {@link #KEY_IS_REFERRABLE} to 1 - <i>true</i> - This session <b><u>is</u></b> referrable.</li>
* </ul>
*/
public void setIsReferrable() {
setInteger(KEY_IS_REFERRABLE, 1);
}
/**
* <p>Sets the {@link #KEY_IS_REFERRABLE} value in preferences to 0, or <i>false</i> if parsed as a {@link Boolean}.
* This value is used by the {@link Branch} object.</p>
*
* <ul>
* <li>Sets {@link #KEY_IS_REFERRABLE} to 0 - <i>false</i> - This session <b><u>is not</u></b> referrable.</li>
* </ul>
*/
public void clearIsReferrable() {
setInteger(KEY_IS_REFERRABLE, 0);
}
/**
* <p>Resets the time that the system was last read. This is used to calculate how "stale" the
* values are that are in use in preferences.</p>
*/
public void clearSystemReadStatus() {
Calendar c = Calendar.getInstance();
setLong(KEY_LAST_READ_SYSTEM, c.getTimeInMillis() / 1000);
}
/**
* <p>Resets the user-related values that have been stored in preferences. This will cause a
* sync to occur whenever a method reads any of the values and finds the value to be 0 or unset.</p>
*/
public void clearUserValues() {
ArrayList<String> buckets = getBuckets();
for (String bucket : buckets) {
setCreditCount(bucket, 0);
}
setBuckets(new ArrayList<String>());
ArrayList<String> actions = getActions();
for (String action : actions) {
setActionTotalCount(action, 0);
setActionUniqueCount(action, 0);
}
setActions(new ArrayList<String>());
}
// REWARD TRACKING CALLS
private ArrayList<String> getBuckets() {
String bucketList = getString(KEY_BUCKETS);
if (bucketList.equals(NO_STRING_VALUE)) {
return new ArrayList<>();
} else {
return deserializeString(bucketList);
}
}
private void setBuckets(ArrayList<String> buckets) {
if (buckets.size() == 0) {
setString(KEY_BUCKETS, NO_STRING_VALUE);
} else {
setString(KEY_BUCKETS, serializeArrayList(buckets));
}
}
/**
* <p>Sets the credit count for the default bucket to the specified {@link Integer}, in preferences.</p>
*
* <p><b>Note:</b> This does not set the actual value of the bucket itself on the Branch server,
* but only the cached value as stored in preferences for the current app. The age of that value
* should be checked before being considered accurate; read {@link #KEY_LAST_READ_SYSTEM} to see
* when the last system sync occurred.
* </p>
*
* @param count A {@link Integer} value that the default bucket credit count will be set to.
*/
public void setCreditCount(int count) {
setCreditCount(Defines.Jsonkey.DefaultBucket.getKey(), count);
}
/**
* <p>Sets the credit count for the default bucket to the specified {@link Integer}, in preferences.</p>
*
* <p><b>Note:</b> This does not set the actual value of the bucket itself on the Branch server,
* but only the cached value as stored in preferences for the current app. The age of that value
* should be checked before being considered accurate; read {@link #KEY_LAST_READ_SYSTEM} to see
* when the last system sync occurred.
* </p>
*
* @param bucket A {@link String} value containing the value of the bucket being referenced.
* @param count A {@link Integer} value that the default bucket credit count will be set to.
*/
public void setCreditCount(String bucket, int count) {
ArrayList<String> buckets = getBuckets();
if (!buckets.contains(bucket)) {
buckets.add(bucket);
setBuckets(buckets);
}
setInteger(KEY_CREDIT_BASE + bucket, count);
}
/**
* <p>Get the current cached credit count for the default bucket, as currently stored in
* preferences for the current app.</p>
*
* @return A {@link Integer} value specifying the current number of credits in the bucket, as
* currently stored in preferences.
*/
public int getCreditCount() {
return getCreditCount(Defines.Jsonkey.DefaultBucket.getKey());
}
/**
* <p>Get the current cached credit count for the default bucket, as currently stored in
* preferences for the current app.</p>
*
* @param bucket A {@link String} value containing the value of the bucket being referenced.
* @return A {@link Integer} value specifying the current number of credits in the bucket, as
* currently stored in preferences.
*/
public int getCreditCount(String bucket) {
return getInteger(KEY_CREDIT_BASE + bucket);
}
// EVENT REFERRAL INSTALL CALLS
private ArrayList<String> getActions() {
String actionList = getString(KEY_ACTIONS);
if (actionList.equals(NO_STRING_VALUE)) {
return new ArrayList<>();
} else {
return deserializeString(actionList);
}
}
private void setActions(ArrayList<String> actions) {
if (actions.size() == 0) {
setString(KEY_ACTIONS, NO_STRING_VALUE);
} else {
setString(KEY_ACTIONS, serializeArrayList(actions));
}
}
/**
* <p>Sets the count of total number of times that the specified action has been carried out
* during the current session, as defined in preferences.</p>
*
* @param action - A {@link String} value containing the name of the action to return the
* count for.
* @param count - An {@link Integer} value containing the total number of times that the
* specified action has been carried out during the current session.
*/
public void setActionTotalCount(String action, int count) {
ArrayList<String> actions = getActions();
if (!actions.contains(action)) {
actions.add(action);
setActions(actions);
}
setInteger(KEY_TOTAL_BASE + action, count);
}
/**
* <p>Sets the count of the unique number of times that the specified action has been carried
* out during the current session, as defined in preferences.</p>
*
* @param action A {@link String} value containing the name of the action to return the
* count for.
* @param count An {@link Integer} value containing the total number of times that the
* specified action has been carried out during the current session.
*/
public void setActionUniqueCount(String action, int count) {
setInteger(KEY_UNIQUE_BASE + action, count);
}
/**
* <p>Gets the count of total number of times that the specified action has been carried
* out during the current session, as defined in preferences.</p>
*
* @param action A {@link String} value containing the name of the action to return the
* count for.
* @return An {@link Integer} value containing the total number of times that the
* specified action has been carried out during the current session.
*/
public int getActionTotalCount(String action) {
return getInteger(KEY_TOTAL_BASE + action);
}
/**
* <p>Gets the count of the unique number of times that the specified action has been carried
* out during the current session, as defined in preferences.</p>
*
* @param action A {@link String} value containing the name of the action to return the
* count for.
* @return An {@link Integer} value containing the total number of times that the
* specified action has been carried out during the current session.
*/
public int getActionUniqueCount(String action) {
return getInteger(KEY_UNIQUE_BASE + action);
}
// ALL GENERIC CALLS
private String serializeArrayList(ArrayList<String> strings) {
String retString = "";
for (String value : strings) {
retString = retString + value + ",";
}
retString = retString.substring(0, retString.length() - 1);
return retString;
}
private ArrayList<String> deserializeString(String list) {
ArrayList<String> strings = new ArrayList<>();
String[] stringArr = list.split(",");
Collections.addAll(strings, stringArr);
return strings;
}
/**
* <p>A basic method that returns an integer value from a specified preferences Key.</p>
*
* @param key A {@link String} value containing the key to reference.
* @return An {@link Integer} value of the specified key as stored in preferences.
*/
public int getInteger(String key) {
return getInteger(key, 0);
}
/**
* <p>A basic method that returns an {@link Integer} value from a specified preferences Key, with a
* default value supplied in case the value is null.</p>
*
* @param key A {@link String} value containing the key to reference.
* @param defaultValue An {@link Integer} specifying the value to use if the preferences value
* is null.
* @return An {@link Integer} value containing the value of the specified key, or the supplied
* default value if null.
*/
public int getInteger(String key, int defaultValue) {
return prefHelper_.appSharedPrefs_.getInt(key, defaultValue);
}
/**
* <p>A basic method that returns a {@link Long} value from a specified preferences Key.</p>
*
* @param key A {@link String} value containing the key to reference.
* @return A {@link Long} value of the specified key as stored in preferences.
*/
public long getLong(String key) {
return prefHelper_.appSharedPrefs_.getLong(key, 0);
}
/**
* <p>A basic method that returns a {@link Float} value from a specified preferences Key.</p>
*
* @param key A {@link String} value containing the key to reference.
* @return A {@link Float} value of the specified key as stored in preferences.
*/
public float getFloat(String key) {
return prefHelper_.appSharedPrefs_.getFloat(key, 0);
}
/**
* <p>A basic method that returns a {@link String} value from a specified preferences Key.</p>
*
* @param key A {@link String} value containing the key to reference.
* @return A {@link String} value of the specified key as stored in preferences.
*/
public String getString(String key) {
return prefHelper_.appSharedPrefs_.getString(key, NO_STRING_VALUE);
}
/**
* <p>A basic method that returns a {@link Boolean} value from a specified preferences Key.</p>
*
* @param key A {@link String} value containing the key to reference.
* @return An {@link Boolean} value of the specified key as stored in preferences.
*/
public boolean getBool(String key) {
return prefHelper_.appSharedPrefs_.getBoolean(key, false);
}
/**
* <p>Sets the value of the {@link String} key value supplied in preferences.</p>
*
* @param key A {@link String} value containing the key to reference.
* @param value An {@link Integer} value to set the preference record to.
*/
public void setInteger(String key, int value) {
prefHelper_.prefsEditor_.putInt(key, value);
prefHelper_.prefsEditor_.apply();
}
/**
* <p>Sets the value of the {@link String} key value supplied in preferences.</p>
*
* @param key A {@link String} value containing the key to reference.
* @param value A {@link Long} value to set the preference record to.
*/
public void setLong(String key, long value) {
prefHelper_.prefsEditor_.putLong(key, value);
prefHelper_.prefsEditor_.apply();
}
/**
* <p>Sets the value of the {@link String} key value supplied in preferences.</p>
*
* @param key A {@link String} value containing the key to reference.
* @param value A {@link Float} value to set the preference record to.
*/
public void setFloat(String key, float value) {
prefHelper_.prefsEditor_.putFloat(key, value);
prefHelper_.prefsEditor_.apply();
}
/**
* <p>Sets the value of the {@link String} key value supplied in preferences.</p>
*
* @param key A {@link String} value containing the key to reference.
* @param value A {@link String} value to set the preference record to.
*/
public void setString(String key, String value) {
prefHelper_.prefsEditor_.putString(key, value);
prefHelper_.prefsEditor_.apply();
}
/**
* <p>Sets the value of the {@link String} key value supplied in preferences.</p>
*
* @param key A {@link String} value containing the key to reference.
* @param value A {@link Boolean} value to set the preference record to.
*/
public void setBool(String key, Boolean value) {
prefHelper_.prefsEditor_.putBoolean(key, value);
prefHelper_.prefsEditor_.apply();
}
public void updateBranchViewUsageCount(String branchViewId) {
String key = KEY_BRANCH_VIEW_NUM_OF_USE + "_" + branchViewId;
int currentUsage = getBranchViewUsageCount(branchViewId) + 1;
setInteger(key, currentUsage);
}
public int getBranchViewUsageCount(String branchViewId) {
String key = KEY_BRANCH_VIEW_NUM_OF_USE + "_" + branchViewId;
return getInteger(key, 0);
}
public JSONObject getBranchAnalyticsData() {
JSONObject analyticsDataObject;
if (savedAnalyticsData_ != null) {
analyticsDataObject = savedAnalyticsData_;
} else {
String savedAnalyticsData = getString(KEY_BRANCH_ANALYTICAL_DATA);
analyticsDataObject = new JSONObject();
if (!TextUtils.isEmpty(savedAnalyticsData) && !savedAnalyticsData.equals(NO_STRING_VALUE)) {
try {
analyticsDataObject = new JSONObject(savedAnalyticsData);
} catch (JSONException ignore) {
}
}
}
return analyticsDataObject;
}
public void clearBranchAnalyticsData() {
savedAnalyticsData_ = null;
setString(KEY_BRANCH_ANALYTICAL_DATA, "");
}
public void saveBranchAnalyticsData(JSONObject analyticsData) {
String sessionID = getSessionID();
if (!sessionID.equals(NO_STRING_VALUE)) {
if (savedAnalyticsData_ == null) {
savedAnalyticsData_ = getBranchAnalyticsData();
}
try {
JSONArray viewDataArray;
if (savedAnalyticsData_.has(sessionID)) {
viewDataArray = savedAnalyticsData_.getJSONArray(sessionID);
} else {
viewDataArray = new JSONArray();
savedAnalyticsData_.put(sessionID, viewDataArray);
}
viewDataArray.put(analyticsData);
setString(KEY_BRANCH_ANALYTICAL_DATA, savedAnalyticsData_.toString());
} catch (JSONException ignore) {
}
}
}
/**
* Saves the last strong match epoch time stamp
*
* @param strongMatchCheckTime epoch time stamp for last strong match
*/
public void saveLastStrongMatchTime(long strongMatchCheckTime) {
setLong(KEY_LAST_STRONG_MATCH_TIME, strongMatchCheckTime);
}
/**
* Get the last strong match check epoch time
*
* @return {@link Long} with last strong match epoch timestamp
*/
public long getLastStrongMatchTime() {
return getLong(KEY_LAST_STRONG_MATCH_TIME);
}
/**
* <p>Clears all the Branch referral shared preferences related to the current key.
* Should be called before setting an new Branch-Key. </p>
*/
private void clearPrefOnBranchKeyChange() {
// If stored key isn't the same as the current key, we need to clean up
// Note: Link Click Identifier is not cleared because of the potential for that to mess up a deep link
String linkClickID = getLinkClickID();
String linkClickIdentifier = getLinkClickIdentifier();
String appLink = getAppLink();
String pushIdentifier = getPushIdentifier();
prefsEditor_.clear();
setLinkClickID(linkClickID);
setLinkClickIdentifier(linkClickIdentifier);
setAppLink(appLink);
setPushIdentifier(pushIdentifier);
prefHelper_.prefsEditor_.apply();
}
/**
* <p>Switches external debugging on.</p>
*/
public void setExternDebug() {
BNC_Dev_Debug = true;
}
/**
* <p>Gets the value of the debug status {@link Boolean} value.</p>
*
* @return A {@link Boolean} value indicating the current state of external debugging.
*/
public boolean getExternDebug() {
return BNC_Dev_Debug;
}
/**
* <p>Toggles debugging on/off.</p>
*/
public void setLogging(final boolean logging) {
BNC_Logging = logging;
}
/**
* <p>Sets the {@link Boolean} value that is checked prior to the listing of external apps to
* <i>false</i>.</p>
*
* @deprecated App listing is disabled by default.
*/
public void disableExternAppListing() {
BNC_App_Listing = false;
}
/**
* <p>This let Branch to collect the external apps data.
* Please note that this will let Branch collect information about other apps installed on the device for analytics purpose
* </p>
*/
public void enableExternAppListing() {
BNC_App_Listing = true;
}
/**
* <p>Sets the {@link Boolean} value that is checked prior to the listing of external apps.</p>
*
* @return A {@link Boolean} value containing the current value of the
* {@link #BNC_App_Listing} boolean.
*/
public boolean getExternAppListing() {
return BNC_App_Listing;
}
public void setRequestMetadata(@NonNull String key, @NonNull String value) {
if (key == null) {
return;
}
if (this.requestMetadata.has(key) && value == null) {
this.requestMetadata.remove(key);
}
try {
this.requestMetadata.put(key, value);
} catch (JSONException e) {
// no-op
}
}
public JSONObject getRequestMetadata() {
return this.requestMetadata;
}
/**
* <p>Creates a <b>Log</b> message in the debugger. If debugging is disabled, this will fail silently.</p>
*
* @param tag A {@link String} value specifying the logging tag to use for the message.
* @param message A {@link String} value containing the logging message to record.
*/
public void log(final String tag, final String message) {
if (BNC_Dev_Debug || BNC_Logging) {
Log.i(tag, message);
}
}
/**
* <p>Creates a <b>Debug</b> message in the debugger. If debugging is disabled, this will fail silently.</p>
*
* @param tag A {@link String} value specifying the logging tag to use for the message.
* @param message A {@link String} value containing the debug message to record.
*/
public static void Debug(String tag, String message) {
if (prefHelper_ != null) {
prefHelper_.log(tag, message);
} else {
if (BNC_Dev_Debug || BNC_Logging) {
Log.i(tag, message);
}
}
}
}
|
package mumart.micromod.replay;
import java.io.*;
import javax.sound.sampled.*;
/*
Module player class.
Provides module loading, oversampling and simpler buffering.
*/
public class Player {
private static final int OVERSAMPLE = 2;
private Replay replay;
private boolean loop;
private int sampling_rate, duration, sample_pos;
private int filt_l, filt_r, mix_pos, mix_len;
private int[] mix_buffer;
/* Initialise a Player to play the specified music module. */
public Player( byte[] module_data, int sampling_rate, boolean loop ) {
this.sampling_rate = sampling_rate;
this.loop = loop;
replay = init_replay( module_data, sampling_rate * OVERSAMPLE );
duration = replay.calculate_song_duration() / OVERSAMPLE;
mix_buffer = new int[ replay.get_mix_buffer_length() ];
}
/* Get version information from the playback engine.*/
public String get_version() {
return replay.get_version();
}
/* Get the song and instrument names, or null if idx is out of range. */
public String get_string( int idx ) {
return replay.get_string( idx );
}
/* Get the song duration in samples at the current sampling rate. */
public int get_song_duration() {
return duration;
}
/* Set playback to begin at the specified pattern position. */
public void set_sequence_pos( int pos ) {
loop = true;
mix_pos = mix_len = sample_pos = 0;
replay.set_sequence_pos( pos );
}
/*
Seek to approximately the specified sample position.
The actual position reached is returned.
*/
public int seek( int sample_pos ) {
mix_pos = mix_len = 0;
return sample_pos = replay.seek( sample_pos * OVERSAMPLE ) / OVERSAMPLE;
}
/*
Get up to the specified number of stereo samples of audio into
the specified buffer. Returns false if the song has finished.
*/
public boolean get_audio( short[] output, int offset, int count ) {
int[] mix_buf = mix_buffer;
while( count > 0 ) {
if( mix_pos >= mix_len ) {
// More audio required from Replay.
mix_pos = 0;
if( !loop ) {
sample_pos += mix_len;
if( sample_pos >= duration ) {
mix_len = 0;
// Song finished, zero rest of output buffer.
int end = offset + count * 2;
while( offset < end ) output[ offset++ ] = 0;
return false;
}
}
mix_len = downsample( mix_buf, replay.get_audio( mix_buf ) );
}
// Calculate maximum number of samples to copy.
int len = mix_len - mix_pos;
if( len > count ) len = count;
// Clip and copy samples to output.
int end = offset + len * 2;
int mix_idx = mix_pos * 2;
while( offset < end ) {
int sam = mix_buf[ mix_idx++ ];
if( sam > 32767 ) sam = 32767;
if( sam < -32768 ) sam = -32768;
output[ offset++ ] = ( short ) sam;
}
mix_pos += len;
count -= len;
}
return ( sample_pos + mix_pos ) < duration;
}
/*
2:1 downsampling with simple but effective anti-aliasing.
Count is the number of stereo samples to process, and must be even.
*/
private int downsample( int[] buf, int count ) {
int fl = filt_l, fr = filt_r;
int in_idx = 0, out_idx = 0;
while( out_idx < count ) {
int out_l = fl + ( buf[ in_idx++ ] >> 1 );
int out_r = fr + ( buf[ in_idx++ ] >> 1 );
fl = buf[ in_idx++ ] >> 2;
fr = buf[ in_idx++ ] >> 2;
buf[ out_idx++ ] = out_l + fl;
buf[ out_idx++ ] = out_r + fr;
}
filt_l = fl;
filt_r = fr;
return count >> 1;
}
private Replay init_replay( byte[] module_data, int sampling_rate ) {
try {
// Try loading as an XM.
mumart.micromod.xm.Module module = new mumart.micromod.xm.Module( module_data );
// XMs generally sound better with interpolation, Mods and S3Ms generally without.
return new mumart.micromod.xm.IBXM( module, sampling_rate, true );
} catch( IllegalArgumentException e ) {}
try {
// Not an XM, try as an S3M.
mumart.micromod.s3m.Module module = new mumart.micromod.s3m.Module( module_data );
return new mumart.micromod.s3m.Micros3m( module, sampling_rate, false );
} catch( IllegalArgumentException e ) {}
// Must be a MOD ...
mumart.micromod.mod.Module module = new mumart.micromod.mod.Module( module_data );
return new mumart.micromod.mod.Micromod( module, sampling_rate, false );
}
}
|
package com.sandwell.JavaSimulation3D;
import com.sandwell.JavaSimulation.BooleanInput;
import com.sandwell.JavaSimulation.DoubleInput;
import com.sandwell.JavaSimulation.DoubleListInput;
import com.sandwell.JavaSimulation.DoubleVector;
import com.sandwell.JavaSimulation.Entity;
import com.sandwell.JavaSimulation.EntityInput;
import com.sandwell.JavaSimulation.EntityListInput;
import com.sandwell.JavaSimulation.ErrorException;
import com.sandwell.JavaSimulation.Input;
import com.sandwell.JavaSimulation.InputErrorException;
import com.sandwell.JavaSimulation.ObjectType;
import com.sandwell.JavaSimulation.Simulation;
import com.sandwell.JavaSimulation.StringVector;
import com.sandwell.JavaSimulation.Vector;
import com.sandwell.JavaSimulation.Vector3dInput;
import com.sandwell.JavaSimulation3D.util.Cube;
import com.sandwell.JavaSimulation3D.util.PointWithSize;
import com.sandwell.JavaSimulation3D.util.Shape;
import javax.media.j3d.Node;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Enumeration;
import javax.media.j3d.Appearance;
import javax.media.j3d.BoundingSphere;
import javax.media.j3d.BranchGroup;
import javax.media.j3d.DistanceLOD;
import javax.media.j3d.LineArray;
import javax.media.j3d.OrderedGroup;
import javax.media.j3d.Shape3D;
import javax.media.j3d.Switch;
import javax.media.j3d.Transform3D;
import javax.media.j3d.TransformGroup;
import javax.swing.JFrame;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import javax.vecmath.Point3d;
import javax.vecmath.Point3f;
import javax.vecmath.Vector3d;
/**
* Encapsulates the methods and data needed to display a simulation object in the 3D environment.
* Extends the basic functionality of entity in order to have access to the basic system
* components like the eventManager.
*
* <h3>Visual Heirarchy</h3>
*
* GraphicsSimulation.rootLocale (Locale)<br>
* -stores regionBranchGroups in the Vector: regionModels<br>
* -this vector corrects the J3D memory leak when the visual universe has no viewers<br>
*<br>
* Region.branchGroup (BranchGroup from DisplayEntity)<br>
*<br>
* Region.rootTransform (TransformGroup from DisplayEntity)<br>
*<br>
* Region.scaleTransform (TransformGroup from DisplayEntity)<br>
*<br>
* DisplayEntity.branchGroup (BranchGroup)<br>
* ** allows detach, pick reporting<br>
* - provides the container to add and remove from a region<br>
* - the basis for selecting an object from the visual display<br>
*<br>
* DisplayEntity.rootTransform (TransformGroup)<br>
* ** allows writing and extending children, changing transforms<br>
* - provides the basis for local transformations of position and orientation<br>
* - host for visual utilities bounds, name and axis<br>
*<br>
* DisplayEntity.scaleTransform (TransformGroup)<br>
* ** allows changing transforms<br>
* - provides the basis for local transformation of scaling<br>
* - used to scale model, but not visual utilities like bounds and axis<br>
*<br>
* DisplayEntity.displayModel (BranchGroup)<br>
* ** allows detach, reading, writing, extending children<br>
* - provides the container for user models to be added to the visual universe<br>
* - capabilities to allow manipulation of the model's components<br>
*<br>
* Shape3D, BranchGroup, SharedGroup, Shape2D (Rectangle, Circle, Label, ...) (Node)<br>
* - model for the DisplayEntity comprised of components of Shape3Ds<br>
* - may be loaded from a geometry file<br>
*
*
*
* <h3>DisplayEntity Structure</h3>
*
* DisplayEntity is defined to be compatible with Audition DisplayPerformers, as such origin and extent
* are provided. Since the display of objects using Java3D is not bound to 2 dimensions nor a fixed
* range of pixels, some changes are required.<br>
*<br>
* - extent does not provides physical visual bounds of the DisplayEntity, rather it is a convenience used
* to determine where the logical dimensions of the object. It has no effect on visual display<br>
*<br>
* - origin represents the bottom left (in 2D space) of the DisplayEntity. It is calculate from the
* more fundamental center and is related by the extent value. Origin can still be used for positioning
* but rather center should be used for future compatibility.<br>
*<br>
* - center represents the position of the object in 3D space. This is the default positioning mechanism
* for DisplayEntities. Setting the origin will be translated into setting the center. The center represents
* the position on the Region of the local origin for the displayModel.<br>
*/
public class DisplayEntity extends Entity {
private static final ArrayList<DisplayEntity> allInstances;
// simulation properties
/** Graphic Simulation object this model is running under **/
protected static GraphicSimulation simulation;
// J3D graphics properties
private final BranchGroup branchGroup; // connects to the region
private final TransformGroup rootTransform; // provides universal transformations for the DisplayEntity's entire model
private final TransformGroup scaleTransform; // provides scaling for display models
private final OrderedGroup displayNode; // container for DisplayEntity's specific model
protected boolean modelNeedsRender = true; // indicates if the model needs rebuilding
private boolean needsRender = true;
private final Vector3dInput positionInput;
private final Vector3dInput sizeInput;
private final Vector3dInput orientationInput;
private final Vector3dInput alignmentInput;
private final EntityInput<Region> regionInput;
private final DoubleInput mouseNodesExtentInput;
private final Vector3d position = new Vector3d();
private final Vector3d size = new Vector3d(1.0d, 1.0d, 1.0d);
private final Vector3d orient = new Vector3d();
private final Vector3d align = new Vector3d();
private final Vector3d scale = new Vector3d(1.0d, 1.0d, 1.0d);
protected Region currentRegion;
private BranchGroup currentGrp = null;
private BranchGroup nextGrp = null;
private DoubleListInput levelOfDetail;
private final EntityListInput<DisplayModel> displayModelList; // DisplayModel from the input
protected final ArrayList<DisplayModelBG> displayModels; // DisplayModel which represents this DisplayEntity
private final EntityInput<DisplayEntity> relativeEntity;
private final BooleanInput show;
private final BooleanInput active;
private final BooleanInput movable;
private boolean animated = false;
// continuous motion properties
/** a Vector of Vector3d with coordinates for points along the track to be traversed */
protected Vector displayTrack;
/** the distance of the entity along the track in screen units */
protected double displayDistanceAlongTrack;
/** Distance in screen units of each portion in the track */
protected DoubleVector displayTrackDistanceList;
/** Angle in radians for each portion in the track */
protected Vector displayTrackOrientationList;
/** Total distance in screen units of the track */
protected double displayTrackTotalDistance;
/** the display speed of the entity in screen units per hour for continuous motion */
protected double displaySpeedAlongTrack;
/** the time at which the entity was last moved */
private double timeOfLastMovement;
// resize and rotate listener
private boolean showResize = false;
private BranchGroup rotateSizeBounds; // holds the extent outline
private LineArray resizeLine; // line up to the rotating corner
// setup a default appearance for the default displayModel
private static Appearance axisLineAppearance;
// vector of mouseNodes
private ArrayList<MouseNode> mouseNodes;
protected double mouseNodesSize;
protected BooleanInput showToolTip; // true => show the tooltip on the screen for the DisplayEntity
protected boolean graphicsSetup = false;
static {
axisLineAppearance = new Appearance();
axisLineAppearance.setLineAttributes( new javax.media.j3d.LineAttributes( 2, javax.media.j3d.LineAttributes.PATTERN_SOLID, false ) );
axisLineAppearance.setColoringAttributes(Shape.getColorWithName("mint"));
allInstances = new ArrayList<DisplayEntity>(100);
}
{
positionInput = new Vector3dInput("Position", "Graphics", new Vector3d());
positionInput.setUnits("m");
this.addInput(positionInput, true);
alignmentInput = new Vector3dInput("Alignment", "Graphics", new Vector3d());
this.addInput(alignmentInput, true);
sizeInput = new Vector3dInput("Size", "Graphics", new Vector3d(1.0d,1.0d,1.0d));
sizeInput.setUnits("m");
this.addInput(sizeInput, true);
orientationInput = new Vector3dInput("Orientation", "Graphics", new Vector3d());
orientationInput.setUnits("rad");
this.addInput(orientationInput, true);
regionInput = new EntityInput<Region>(Region.class, "Region", "Graphics", simulation.getDefaultRegion());
this.addInput(regionInput, true);
showToolTip = new BooleanInput("ToolTip", "Graphics", true);
this.addInput(showToolTip, true);
mouseNodesExtentInput = new DoubleInput("MouseNodesExtent", "Graphics", 0.05d);
mouseNodesExtentInput.setUnits("m");
this.addInput(mouseNodesExtentInput, true);
relativeEntity = new EntityInput<DisplayEntity>(DisplayEntity.class, "RelativeEntity", "Graphics", null);
this.addInput(relativeEntity, true);
displayModelList = new EntityListInput<DisplayModel>( DisplayModel.class, "DisplayModel", "Graphics", null);
this.addInput(displayModelList, true);
displayModelList.setUnique(false);
levelOfDetail = new DoubleListInput("LevelOfDetail", "Graphics", null);
levelOfDetail.setValidRange( 0.0d, Double.POSITIVE_INFINITY );
this.addInput(levelOfDetail, true);
show = new BooleanInput("Show", "Graphics", true);
this.addInput(show, true);
active = new BooleanInput("Active", "Graphics", true);
this.addInput(active, true);
movable = new BooleanInput("Movable", "Graphics", true);
this.addInput(movable, true);
}
/**
* Constructor: initializing the DisplayEntity's graphics
*/
public DisplayEntity() {
super();
currentRegion = simulation.getDefaultRegion();
allInstances.add(this);
// Create a branchgroup and make it detachable.
branchGroup = new BranchGroup();
branchGroup.setCapability( BranchGroup.ALLOW_DETACH );
branchGroup.setCapability( BranchGroup.ENABLE_PICK_REPORTING );
// Hold a reference to the DisplayEntity in the topmost branchgroup to
// speed up picking lookups
branchGroup.setUserData(this);
// Initialize the root transform to be the identity
rootTransform = new TransformGroup();
rootTransform.setCapability( TransformGroup.ALLOW_TRANSFORM_WRITE );
rootTransform.setCapability( TransformGroup.ALLOW_CHILDREN_WRITE );
rootTransform.setCapability( TransformGroup.ALLOW_CHILDREN_EXTEND );
rootTransform.setCapability( TransformGroup.ALLOW_CHILDREN_READ );
branchGroup.addChild( rootTransform );
// Initialize the root transform to be the identity
scaleTransform = new TransformGroup();
scaleTransform.setCapability( TransformGroup.ALLOW_TRANSFORM_WRITE );
scaleTransform.setCapability( TransformGroup.ALLOW_CHILDREN_WRITE );
scaleTransform.setCapability( TransformGroup.ALLOW_CHILDREN_EXTEND );
rootTransform.addChild( scaleTransform );
displayTrack = new Vector( 1, 1 );
displayDistanceAlongTrack = 0.0;
displayTrackDistanceList = new DoubleVector( 1, 1 );
displayTrackOrientationList = new Vector( 1, 1 ); // Vector of Vector3d
displayTrackTotalDistance = 0.0;
displaySpeedAlongTrack = 0.0;
timeOfLastMovement = 0.0;
// create a placeholder of the model
displayNode = new OrderedGroup();
displayNode.setCapability( BranchGroup.ALLOW_CHILDREN_WRITE );
displayNode.setCapability( BranchGroup.ALLOW_CHILDREN_EXTEND );
displayNode.setCapability( BranchGroup.ALLOW_CHILDREN_READ );
scaleTransform.addChild( displayNode );
mouseNodes = new ArrayList<MouseNode>();
setMouseNodesSize(0.050);
displayModels = new ArrayList<DisplayModelBG>();
DisplayModel dm = this.getDefaultDisplayModel();
if(dm != null) {
ArrayList<DisplayModel> defList = new ArrayList<DisplayModel>();
defList.add(dm);
displayModelList.setDefaultValue(defList);
}
if( currentRegion != null )
this.enterRegion();
}
public static ArrayList<? extends DisplayEntity> getAll() {
return allInstances;
}
/**
* Sets the Graphic Simulation object for the entity.
* @param newSimulation - states the new simulation the entity is controled by
*/
public static void setSimulation( GraphicSimulation newSimulation ) {
simulation = newSimulation;
}
public Region getCurrentRegion() {
return currentRegion;
}
/**
* Removes the entity from its current region and assigns a new region
* @param newRegion - the region the entity will be assigned to
*/
public void setRegion( Region newRegion ) {
exitRegion();
currentRegion = newRegion;
}
/**
* Visually adds the entity to its currently assigned region
*/
public void enterRegion() {
synchronized (position) {
nextGrp = currentRegion.getEntGroup();
needsRender = true;
}
}
/**
* Removes the entity from its current region and visually adds the entity to the specified region.
* @param newRegion - the region the entity will be assigned to
*/
public void enterRegion( Region newRegion ) {
setRegion( newRegion );
enterRegion();
}
/**
* Visually removes the entity from its region. The current region for the entity is maintained.
*/
public void exitRegion() {
synchronized (position) {
nextGrp = null;
needsRender = true;
}
}
private void duplicate() {
ObjectType type = ObjectType.getFor(this.getClass());
if(type == null)
return;
// Unique name
int i = 1;
String name = String.format("Copy_of_%s", getInputName());
while (Simulation.getNamedEntity(name) != null) {
name = String.format("Copy%d_of_%s", i, getInputName());
i++;
}
DisplayEntity copiedEntity = (DisplayEntity)InputAgent.defineEntity(
type.getJavaClass(), name, true);
// Match all the inputs
for(Input<?> each: this.getEditableInputs() ){
String val = each.getValueString();
if (val.isEmpty())
continue;
Input<?> copiedInput = copiedEntity.getInput(each.getKeyword());
InputAgent.processEntity_Keyword_Value(copiedEntity, copiedInput, val);
}
Vector3d pos = copiedEntity.getPosition();
Vector3d offset = copiedEntity.getSize();
offset.scale(0.5);
offset.setZ(0);
pos.add(offset);
copiedEntity.setPosition(pos);
copiedEntity.initializeGraphics();
copiedEntity.enterRegion();
FrameBox.setSelectedEntity(copiedEntity);
}
private void addLabel() {
ObjectType type = ObjectType.getFor(TextLabel.class);
if(type == null)
return;
// Unique name
int i = 1;
String name = String.format("Label_for_%s", getInputName());
while (Simulation.getNamedEntity(name) != null) {
name = String.format("Label%d_of_%s", i, getInputName());
i++;
}
TextLabel label = (TextLabel)InputAgent.defineEntity(
type.getJavaClass(), name, true);
InputAgent.processEntity_Keyword_Value(label, "RelativeEntity", this.getInputName() );
InputAgent.processEntity_Keyword_Value(label, "Position", "1.0, -1.0, 0.0" );
InputAgent.processEntity_Keyword_Value(label, "Region", currentRegion.getInputName() );
InputAgent.processEntity_Keyword_Value(label, "Text", this.getName());
label.initializeGraphics();
label.enterRegion();
FrameBox.setSelectedEntity(label);
}
/**
* Destroys the branchGroup hierarchy for the entity
*/
public void kill() {
super.kill();
for (MouseNode each : mouseNodes) {
each.kill();
}
allInstances.remove(this);
exitRegion();
GraphicsUpdateBehavior.detachBG(branchGroup);
nextGrp = null;
currentGrp = null;
if(OrbitBehavior.selectedEntity == this)
OrbitBehavior.selectedEntity = null;
currentRegion = null;
displayTrack = null;
displayDistanceAlongTrack = 0.0;
displayTrackDistanceList = null;
displayTrackOrientationList = null;
displayTrackTotalDistance = 0.0;
displaySpeedAlongTrack = 0.0;
}
public void render(double time) {
synchronized (position) {
if (animated)
this.animate(time);
if (!needsRender && relativeEntity.getValue() == null)
return;
if (currentGrp != nextGrp) {
branchGroup.detach();
currentGrp = null;
if (show.getValue() && nextGrp != null) {
currentGrp = nextGrp;
currentGrp.addChild(branchGroup);
}
}
Transform3D temp = new Transform3D();
temp.setEuler(orient);
Vector3d offset = new Vector3d(size.x * align.x, size.y * align.y, size.z * align.z);
temp.transform(offset);
offset.sub(position, offset);
offset.add(getOffsetToRelativeEntity());
temp.setTranslation(offset);
rootTransform.setTransform(temp);
temp.setIdentity();
temp.setScale(scale);
scaleTransform.setTransform(temp);
if( !graphicsSetup ) {
this.setupGraphics();
graphicsSetup = true;
return;
}
if (showResize) {
if( mouseNodes.size() > 0 ) {
nodesOn();
}
else {
if (rotateSizeBounds == null)
makeResizeBounds();
updateResizeBounds(size.x, size.y, size.z);
}
}
else {
if( mouseNodes.size() > 0 ) {
nodesOff();
}
else {
if (rotateSizeBounds != null) {
rootTransform.removeChild(rotateSizeBounds);
rotateSizeBounds = null;
}
}
}
for (DisplayModelBG each : displayModels) {
each.setModelSize(size);
}
needsRender = false;
}
}
private void calculateEulerRotation(Vector3d val, Vector3d euler) {
double sinx = Math.sin(euler.x);
double siny = Math.sin(euler.y);
double sinz = Math.sin(euler.z);
double cosx = Math.cos(euler.x);
double cosy = Math.cos(euler.y);
double cosz = Math.cos(euler.z);
// Calculate a 3x3 rotation matrix
double m00 = cosy * cosz;
double m01 = -(cosx * sinz) + (sinx * siny * cosz);
double m02 = (sinx * sinz) + (cosx * siny * cosz);
double m10 = cosy * sinz;
double m11 = (cosx * cosz) + (sinx * siny * sinz);
double m12 = -(sinx * cosz) + (cosx * siny * sinz);
double m20 = -siny;
double m21 = sinx * cosy;
double m22 = cosx * cosy;
double x = m00 * val.x + m01 * val.y + m02 * val.z;
double y = m10 * val.x + m11 * val.y + m12 * val.z;
double z = m20 * val.x + m21 * val.y + m22 * val.z;
val.set(x, y, z);
}
public Vector3d getPositionForAlignment(Vector3d alignment) {
Vector3d temp = new Vector3d(alignment);
synchronized (position) {
temp.sub(align);
temp.x *= size.x;
temp.y *= size.y;
temp.z *= size.z;
calculateEulerRotation(temp, orient);
temp.add(position);
}
return temp;
}
public Vector3d getOrientation() {
synchronized (position) {
return new Vector3d(orient);
}
}
public void setOrientation(Vector3d orientation) {
synchronized (position) {
orient.set(orientation);
needsRender = true;
}
}
public void setAngle(double theta) {
this.setOrientation(new Vector3d(0.0, 0.0, theta * Math.PI / 180.0));
}
/** Translates the object to a new position, the same distance from centerOfOrigin,
* but at angle theta radians
* counterclockwise
* @param centerOfOrigin
* @param Theta
*/
public void polarTranslationAroundPointByAngle( Vector3d centerOfOrigin, double Theta ) {
Vector3d centerOfEntityRotated = new Vector3d();
Vector3d centerOfEntity = this.getPositionForAlignment(new Vector3d());
centerOfEntityRotated.x = centerOfOrigin.x + Math.cos( Theta ) * ( centerOfEntity.x - centerOfOrigin.x ) - Math.sin( Theta ) * ( centerOfEntity.y - centerOfOrigin.y );
centerOfEntityRotated.y = centerOfOrigin.y + Math.cos( Theta ) * ( centerOfEntity.y - centerOfOrigin.y ) + Math.sin( Theta ) * ( centerOfEntity.x - centerOfOrigin.x );
centerOfEntityRotated.z = centerOfOrigin.z;
this.setPosition(centerOfEntityRotated);
this.setAlignment(new Vector3d());
}
/** Get the position of the DisplayEntity if it Rotates (counterclockwise) around the centerOfOrigin by
* Theta radians assuming the object centers at pos
*
* @param centerOfOrigin
* @param Theta
* @param pos
*/
public Vector3d getCoordinatesForRotationAroundPointByAngleForPosition( Vector3d centerOfOrigin, double Theta, Vector3d pos ) {
Vector3d centerOfEntityRotated = new Vector3d();
centerOfEntityRotated.x = centerOfOrigin.x + Math.cos( Theta ) * ( pos.x - centerOfOrigin.x ) - Math.sin( Theta ) * ( pos.y - centerOfOrigin.y );
centerOfEntityRotated.y = centerOfOrigin.y + Math.cos( Theta ) * ( pos.y - centerOfOrigin.y ) + Math.sin( Theta ) * ( pos.x - centerOfOrigin.x );
centerOfEntityRotated.z = centerOfOrigin.z;
return centerOfEntityRotated;
}
public Vector getDisplayTrack() {
return displayTrack;
}
public DoubleVector getDisplayTrackDistanceList() {
return displayTrackDistanceList;
}
public Vector getDisplayTrackOrientationList() {
return displayTrackOrientationList;
}
/**
* Method to set the display track of the entity
* @param track - the DisplayEntity's new track
*/
public void setDisplayTrack( Vector track ) {
displayTrack = track;
}
/**
* Method to set the display track distances of the entity
* @param distances - the DisplayEntity's new track distances
*/
public void setDisplayTrackDistanceList( DoubleVector distances ) {
displayTrackDistanceList = distances;
displayTrackTotalDistance = distances.sum();
}
/**
* Method to set the display track orientations of the entity
* @param distances - the DisplayEntity's new track orientations
*/
public void setDisplayTrackOrientationList( Vector orientations ) {
displayTrackOrientationList = orientations;
}
/**
* Method to set the display distance along track of the entity
* @param d - the DisplayEntity's new display distance along track
*/
public void setDisplayDistanceAlongTrack( double d ) {
// this.trace( "setDisplayDistanceAlongTrack( "+d+" )" );
displayDistanceAlongTrack = d;
}
/**
* Method to set the display distance along track of the entity
* @param d - the DisplayEntity's new display distance along track
*/
public void setDisplayTrackTotalDistance( double d ) {
// this.trace( "setDisplayTrackTotalDistance( "+d+" )" );
displayTrackTotalDistance = d;
}
/**
* Method to set the display speed of the entity
* @param s - the DisplayEntity's new display speed
*/
public void setDisplaySpeedAlongTrack( double s ) {
// If the display speed is the same, do nothing
if( s == displaySpeedAlongTrack ) {
return;
}
// Was the object previously moving?
if( displaySpeedAlongTrack > 0 ) {
// Determine the time since the last movement for the entity
double dt = getCurrentTime() - timeOfLastMovement;
// Update the displayDistanceAlongTrack
displayDistanceAlongTrack += ( displaySpeedAlongTrack * dt );
}
displaySpeedAlongTrack = s;
timeOfLastMovement = getCurrentTime();
if (s == 0.0)
animated = false;
else
animated = true;
}
/**
* Returns the display distance for the DisplayEntity
* @return double - display distance for the DisplayEntity
**/
public double getDisplayDistanceAlongTrack() {
return displayDistanceAlongTrack;
}
public double getDisplayTrackTotalDistance() {
return displayTrackTotalDistance;
}
public void setSize(Vector3d size) {
synchronized (position) {
this.size.set(size);
needsRender = true;
}
this.setScale(size.x, size.y, size.z);
}
public Vector3d getPosition() {
synchronized (position) {
return new Vector3d(position);
}
}
DisplayEntity getRelativeEntity() {
return relativeEntity.getValue();
}
private Vector3d getOffsetToRelativeEntity() {
Vector3d offset = new Vector3d();
DisplayEntity entity = this.getRelativeEntity();
if(entity != null && entity != this) {
offset.add( entity.getPosition() );
}
return offset;
}
/*
* Returns the center relative to the origin
*/
public Vector3d getAbsoluteCenter() {
Vector3d cent = this.getPositionForAlignment(new Vector3d());
cent.add(getOffsetToRelativeEntity());
return cent;
}
public Vector3d getAbsolutePositionForAlignment(Vector3d alignment) {
Vector3d extent = this.getSize();
alignment.x *= extent.x;
alignment.y *= extent.y;
alignment.z *= extent.z;
calculateEulerRotation(alignment, orient);
alignment.add(this.getAbsoluteCenter());
return alignment;
}
/**
* Returns the extent for the DisplayEntity
* @return Vector3d - width, height and depth of the bounds for the DisplayEntity
*/
public Vector3d getSize() {
synchronized (position) {
return new Vector3d(size);
}
}
public void setScale( double x, double y, double z ) {
synchronized (position) {
scale.set( x, y, z );
needsRender = true;
}
}
public Vector3d getScale() {
synchronized (position) {
return new Vector3d(scale);
}
}
public Vector3d getAlignment() {
synchronized (position) {
return new Vector3d(align);
}
}
public void setAlignment(Vector3d align) {
synchronized (position) {
this.align.set(align);
needsRender = true;
}
}
public void setPosition(Vector3d pos) {
synchronized (position) {
position.set(pos);
needsRender = true;
}
}
BranchGroup getBranchGroup() {
return branchGroup;
}
/**
Returns a vector of strings describing the DisplayEntity.
Override to add details
@return Vector - tab delimited strings describing the DisplayEntity
**/
public Vector getInfo() {
Vector info = super.getInfo();
if( getCurrentRegion() != null )
info.addElement( "Region" + "\t" + getCurrentRegion().getName() );
else
info.addElement( "Region\t<no region>" );
return info;
}
private void updateResizeBounds(double x, double y, double z) {
((PointWithSize)rotateSizeBounds.getChild(0)).setCenter(-x, 0.0, 0.0);
((PointWithSize)rotateSizeBounds.getChild(1)).setCenter(-x/2, y/2, 0.0);
((PointWithSize)rotateSizeBounds.getChild(2)).setCenter(x/2, y/2, 0.0);
((PointWithSize)rotateSizeBounds.getChild(3)).setCenter(-x/2, -y/2, 0.0);
((PointWithSize)rotateSizeBounds.getChild(4)).setCenter( x/2, -y/2, 0.0);
((PointWithSize)rotateSizeBounds.getChild(5)).setCenter(0.0, y/2, 0.0);
((PointWithSize)rotateSizeBounds.getChild(6)).setCenter( x/2, 0.0, 0.0);
((PointWithSize)rotateSizeBounds.getChild(7)).setCenter(-x/2, 0.0, 0.0);
((PointWithSize)rotateSizeBounds.getChild(8)).setCenter(0.0, -y/2, 0.0);
resizeLine.setCoordinate(1, new Point3d(-x, 0.0d, 0.0d));
((Cube)rotateSizeBounds.getChild(10)).setSize(x, y, z);
}
private void makeResizeBounds() {
rotateSizeBounds = new BranchGroup();
rotateSizeBounds.setCapability(BranchGroup.ALLOW_DETACH);
resizeLine = new LineArray(2, LineArray.COORDINATES);
resizeLine.setCapability(LineArray.ALLOW_COORDINATE_WRITE);
resizeLine.setCoordinate(0, new Point3d(0.0, 0.0, 0.0));
resizeLine.setCoordinate(1, new Point3d(1.0, 0.0, 0.0));
// circle handles
boolean state = true;
for (int i = 0; i < 9; i++) {
// square handles
if(i > 4)
state = false;
PointWithSize temp = new PointWithSize(9.0f, state, "pixels" );
temp.setColor(Shape.getColorWithName("LightBlue"));
rotateSizeBounds.addChild(temp);
}
rotateSizeBounds.addChild(new Shape3D(resizeLine, axisLineAppearance));
Cube boundsModel = new Cube(Cube.SHAPE_OUTLINE, "boundsModel");
boundsModel.setColor(Shape.getColorWithName("mint"));
rotateSizeBounds.addChild(boundsModel);
rotateSizeBounds.compile();
rootTransform.addChild(rotateSizeBounds);
}
public void setResizeBounds( boolean bool ) {
synchronized (position) {
showResize = bool;
needsRender = true;
}
}
/**
* Accessor method to obtain the display model for the DisplayEntity
* created: Feb 21, 2003 by JM
* To change the model for the DisplayEntity, obtain the refence to the model using this method
* then, add desired graphics to this Group.
* @return the BranchGroup for the DisplayEntity that the display model can be added to.
*/
public OrderedGroup getModel() {
return displayNode;
}
/**
* Adds a shape to the shapelist and to the DisplayEntity Java3D hierarchy.
* Takes into account the desired layer for the added shape.
*
* @param shape the shape to add.
*/
public void addShape( Shape shape ) {
synchronized (getModel()) {
// Make sure we don't get added twice, try to remove it first in case
getModel().removeChild(shape);
getModel().addChild(shape);
}
}
/**
* Adds a mouseNode at the given position
* Empty in DisplayEntity -- must be overloaded for entities which can have mouseNodes such as RouteSegment and Path
* @param posn
*/
public void addMouseNodeAt( Vector3d posn ) {
}
/**
* Remove a shape from the shapelist and the java3d model. Return if the
* shape is not on the list.
*
* @param shape the shape to be removed.
*/
public void removeShape( Shape shape ) {
synchronized (getModel()) {
getModel().removeChild(shape);
}
}
/** removes a components from the displayModel, clearing the graphics **/
public void clearModel() {
synchronized (position) {
// remove all of the submodels from the model
getModel().removeAllChildren();
if(displayModels.size() != 0){
DoubleVector distances;
distances = new DoubleVector(0);
if(levelOfDetail.getValue() != null){
distances = levelOfDetail.getValue();
}
// LOD is defined
if(distances.size() > 0){
Enumeration<?> children = rootTransform.getAllChildren();
while(children.hasMoreElements()){
Node child = (Node) children.nextElement();
if(child.getName() != null && child.getName().equalsIgnoreCase("lodTransformGroup")) {
rootTransform.removeChild(child);
for(DisplayModelBG each: displayModels){
each.removeAllChildren();
}
}
}
}
// One display model
else{
rootTransform.removeChild(displayModels.get(0));
displayModels.get(0).removeAllChildren();
}
displayModels.clear();
}
}
}
void addScaledBG(BranchGroup node) {
synchronized (scaleTransform) {
scaleTransform.addChild(node);
}
}
void removeScaledBG(BranchGroup node) {
synchronized (scaleTransform) {
scaleTransform.removeChild(node);
}
}
/**
* Allows overridding to add menu items for user menus
* @param menu - the Popup menu to add items to
* @param xLoc - the x location of the mouse when the mouse event occurred
* @param yLoc - the y location of the mouse when the mouse event occurred
**/
public void addMenuItems( JPopupMenu menu, final int xLoc, final int yLoc ) {
JMenuItem input = new JMenuItem("Input Editor");
input.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
EditBox.getInstance().setVisible(true);
EditBox.getInstance().setExtendedState(JFrame.NORMAL);
FrameBox.setSelectedEntity(DisplayEntity.this);
}
});
menu.add(input);
JMenuItem prop = new JMenuItem("Property Viewer");
prop.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
PropertyBox.getInstance().setVisible(true);
PropertyBox.getInstance().setExtendedState(JFrame.NORMAL);
FrameBox.setSelectedEntity(DisplayEntity.this);
}
});
menu.add(prop);
JMenuItem output = new JMenuItem("Output Viewer");
output.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
InfoBox.getInstance().setVisible(true);
InfoBox.getInstance().setExtendedState(JFrame.NORMAL);
FrameBox.setSelectedEntity(DisplayEntity.this);
}
});
menu.add(output);
if (!this.testFlag(Entity.FLAG_GENERATED)) {
JMenuItem copy = new JMenuItem( "Copy" );
copy.addActionListener( new ActionListener() {
public void actionPerformed( ActionEvent event ) {
duplicate();
}
} );
// Only if this object is selected
if(OrbitBehavior.selectedEntity == this)
menu.add( copy );
}
JMenuItem delete = new JMenuItem( "Delete" );
delete.addActionListener( new ActionListener() {
public void actionPerformed( ActionEvent event ) {
DisplayEntity.this.kill();
FrameBox.setSelectedEntity(null);
}
} );
// Only if this object is selected
if(OrbitBehavior.selectedEntity == this)
menu.add( delete );
JMenuItem displayModel = new JMenuItem( "Change Graphics" );
displayModel.addActionListener( new ActionListener() {
public void actionPerformed( ActionEvent event ) {
// More than one DisplayModel(LOD) or No DisplayModel
if(displayModels.size() > 1 || displayModelList.getValue() == null)
return;
GraphicBox graphicBox = GraphicBox.getInstance( DisplayEntity.this, xLoc, yLoc );
graphicBox.setVisible( true );
}
} );
menu.add( displayModel );
JMenuItem addLabel = new JMenuItem( "Add Label" );
addLabel.addActionListener( new ActionListener() {
public void actionPerformed( ActionEvent event ) {
DisplayEntity.this.addLabel();
}
} );
menu.add( addLabel );
}
public void readData_ForKeyword(StringVector data, String keyword, boolean syntaxOnly, boolean isCfgInput)
throws InputErrorException {
if( "Label".equalsIgnoreCase( keyword ) ) {
InputAgent.logWarning("The keyword Label no longer has any effect");
return;
}
if( "LABELBOTTOMLEFT".equalsIgnoreCase( keyword ) ) {
InputAgent.logWarning("The keyword LABELBOTTOMLEFT no longer has any effect");
return;
}
if( "TextHeight".equalsIgnoreCase( keyword ) ) {
InputAgent.logWarning("The keyword TextHeight no longer has any effect");
return;
}
if( "FontName".equalsIgnoreCase( keyword ) ) {
InputAgent.logWarning("The keyword FontName no longer has any effect");
return;
}
if( "FontStyle".equalsIgnoreCase( keyword ) ) {
InputAgent.logWarning("The keyword FontStyle no longer has any effect");
return;
}
if ("FontColour".equalsIgnoreCase(keyword) ||
"FontColor".equalsIgnoreCase( keyword ) ) {
InputAgent.logWarning("The keyword FontColour no longer has any effect");
return;
}
if( "Angle".equalsIgnoreCase( keyword ) ) {
InputAgent.logWarning("The keyword Angle no longer has any effect");
return;
}
super.readData_ForKeyword( data, keyword, syntaxOnly, isCfgInput );
}
/**
* Return the orientation for the specified distance along the display track
*/
public Vector3d getDisplayTrackOrientationForDistance( double distance ) {
// If there is no orientation, return no orientation
if( displayTrackOrientationList.size() == 0 ) {
return ( new Vector3d( 0.0, 0.0, 0.0 ) );
}
// If there is only one orientation, return it
if( displayTrackOrientationList.size() == 1 ) {
return (Vector3d)displayTrackOrientationList.get( 0 );
}
distance = Math.max( distance, 0.0 );
distance = Math.min( distance, displayTrackTotalDistance );
// Determine the line for the position
double totalLength = 0.0;
for( int i = 0; i < displayTrackDistanceList.size(); i++ ) {
totalLength += displayTrackDistanceList.get( i );
if( distance <= totalLength ) {
return (Vector3d)displayTrackOrientationList.get( i );
}
}
throw new ErrorException( "Could not find orientation for obect " + this.getName() );
}
/**
* Return the screen coordinates for the specified distance along the display track
*/
public Vector3d getDisplayTrackCoordinatesForDistance( double distance ) {
double ratio;
Vector3d p1 = (Vector3d)displayTrack.get( 0 );
Vector3d p2 = (Vector3d)displayTrack.lastElement();
// Are the inputs valid for calculation?
//if( distance - displayTrackTotalDistance > 0.2 ) {
// throw new ErrorException( this.getName() + " Specified distance must be less than or equal to the track distance. " + distance + " / " + displayTrackTotalDistance );
if( distance < -0.2 ) {
throw new ErrorException( " The specified distance must be positive. " );
}
// Find the ratio of the track length to the specified distance
if( displayTrackTotalDistance == 0.0 ) {
ratio = 1.0;
}
else {
distance = Math.max( distance, 0.0 );
distance = Math.min( distance, displayTrackTotalDistance );
ratio = (distance / displayTrackTotalDistance);
}
// Are there bends in the segment?
if( displayTrack.size() > 2 ) {
// Determine the line for the position and the fraction of the way through the line
double totalLength = 0.0;
double distanceInLine;
for( int i = 0; i < displayTrackDistanceList.size(); i++ ) {
distanceInLine = distance - totalLength;
totalLength += displayTrackDistanceList.get( i );
if( distance <= totalLength ) {
p1 = (Vector3d)displayTrack.get( i );
p2 = (Vector3d)displayTrack.get( i + 1 );
if( displayTrackDistanceList.get( i ) > 0 ) {
ratio = distanceInLine / displayTrackDistanceList.get( i );
}
else {
ratio = 0.0;
}
break;
}
}
}
// Calculate the resulting point
Vector3d vec = new Vector3d();
vec.sub(p2, p1);
vec.scale(ratio);
vec.add(p1);
return vec;
}
private void animate(double t) {
//this.trace( "updateMovementAtTime( " + t + " )" );
// Determine the display speed
double s = this.displaySpeedAlongTrack;
if( s == 0.0 ) {
return;
}
//this.trace( "Display Speed Along Track (SCREEN UNITS/h)= "+s );
// Determine the time since the last movement for the entity
double dt = t - timeOfLastMovement;
if( dt <= 0.0 ) {
return;
}
//this.trace( "Time of last movement = "+ this.getTimeOfLastMovement() );
//this.trace( "Time For this update (dt) = "+dt );
// Find the display distance moved since the last update
double distance = this.getDisplayDistanceAlongTrack() + ( dt * s );
//this.trace( "distance travelled during this update (SCREEN UNITS) = "+distance );
this.setDisplayDistanceAlongTrack( distance );
// Set the new location
Vector3d loc = this.getDisplayTrackCoordinatesForDistance( distance );
this.setPosition(loc);
this.setAlignment(new Vector3d());
timeOfLastMovement = t;
this.setOrientation(this.getDisplayTrackOrientationForDistance(distance));
}
/**
* Move the DisplayEntity to the given destination over the given time.
* If a non-empty path is specified, then the DisplayEntity will follow the path.
* Otherwise, it will follow a straight line to the destination.
*/
public void moveToPosition_FollowingVectors3d_DuringTime_WithChangingOrientation( Vector3d destination, Vector path, double t, boolean orientationChanges ) {
// Create a list of all the points to be followed
Vector pts = new Vector();
pts.addElement(this.getPosition());
pts.addAllLast( path );
pts.addElement( destination );
// Store the new track and track distances
Vector newDisplayTrack = new Vector( 1, 1 );
DoubleVector newDisplayTrackDistanceList = new DoubleVector( 1, 1 );
Vector newDisplayTrackOrientationList = new Vector( 1, 1 );
double dx, dy, dz;
Vector3d p1, p2;
Vector3d prevPt, nextPt;
// Add the present location to the display track
newDisplayTrack.addElement(this.getPosition());
for( int i = 0; i < (pts.size() - 1); i++ ) {
prevPt = (Vector3d)newDisplayTrack.get( i );
// Determine the offset to the next point
p1 = (Vector3d)pts.get( i );
p2 = (Vector3d)pts.get( i + 1 );
dx = p2.x - p1.x;
dy = p2.y - p1.y;
dz = p2.z - p1.z;
// Add the next point to the display track
nextPt = new Vector3d( prevPt.x + dx, prevPt.y + dy, prevPt.z + dz );
newDisplayTrack.addElement( nextPt );
// Add the next distance to the display track distances
Vector3d vec = new Vector3d();
vec.sub( nextPt, prevPt );
double distance = vec.length();
newDisplayTrackDistanceList.add(distance);
if( orientationChanges ) {
newDisplayTrackOrientationList.addElement( new Vector3d( 0.0, -1.0 * Math.atan2( dz, Math.hypot( dx, dy ) ), Math.atan2( dy, dx ) ) );
}
else {
newDisplayTrackOrientationList.addElement(this.getOrientation());
}
}
// Set the new track and distances
this.setDisplayTrack( newDisplayTrack );
this.setDisplayTrackDistanceList( newDisplayTrackDistanceList );
displayTrackTotalDistance = newDisplayTrackDistanceList.sum();
this.setDisplayTrackOrientationList( newDisplayTrackOrientationList );
// Set the distance along track
displayDistanceAlongTrack = 0.0;
// Set the display speed to the destination (in Java screen units per hour)
this.setDisplaySpeedAlongTrack( displayTrackTotalDistance / t );
// Give this event slightly higher priority in case the entity exits region after the wait.
// We want to resume this method first so that we can set the origin of the entity on its present region before it exits region.
scheduleWait( t, 4 );
this.setDisplaySpeedAlongTrack( 0.0 );
this.setPosition(destination);
}
/**
* Move the DisplayEntity to the given destination over the given time.
* If a non-empty path is specified, then the DisplayEntity will follow the path and the given orientations.
* Otherwise, it will follow a straight line to the destination.
*/
public void moveToPosition_FollowingVectors3d_DuringTime_WithOrientations( Vector3d destination, Vector path, double t, DoubleVector orientations ) {
// Create a list of all the points to be followed
Vector pts = new Vector();
pts.addElement( this.getPositionForAlignment(new Vector3d()) );
pts.addAllLast( path );
pts.addElement( destination );
// Store the new track and track distances
Vector newDisplayTrack = new Vector( 1, 1 );
DoubleVector newDisplayTrackDistanceList = new DoubleVector( 1, 1 );
Vector newDisplayTrackOrientationList = new Vector( 1, 1 );
double dx, dy;
Vector3d p1, p2;
Vector3d prevPt, nextPt;
// Add the present location to the display track
newDisplayTrack.addElement(this.getPositionForAlignment(new Vector3d()));
for( int i = 0; i < (pts.size() - 1); i++ ) {
prevPt = (Vector3d)newDisplayTrack.get( i );
// Determine the offset to the next point
p1 = (Vector3d)pts.get( i );
p2 = (Vector3d)pts.get( i + 1 );
dx = p2.x - p1.x;
dy = p2.y - p1.y;
// Add the next point to the display track
nextPt = new Vector3d( prevPt.x + dx, prevPt.y + dy, 0.0 );
newDisplayTrack.addElement( nextPt );
// Add the next distance to the display track distances
Vector3d vec = new Vector3d();
vec.sub( nextPt, prevPt );
double distance = vec.length();
newDisplayTrackDistanceList.add(distance);
if( i == 0 ) {
newDisplayTrackOrientationList.addElement( new Vector3d( 0, 0, orientations.get( 0 ) * Math.PI / 180.0 ) );
}
else {
if( i == pts.size() - 2 ) {
newDisplayTrackOrientationList.addElement( new Vector3d( 0, 0, orientations.lastElement() * Math.PI / 180.0 ) );
}
else {
newDisplayTrackOrientationList.addElement( new Vector3d( 0, 0, orientations.get( i-1 ) * Math.PI / 180.0 ) );
}
}
}
// Set the new track and distances
this.setDisplayTrack( newDisplayTrack );
this.setDisplayTrackDistanceList( newDisplayTrackDistanceList );
displayTrackTotalDistance = newDisplayTrackDistanceList.sum();
this.setDisplayTrackOrientationList( newDisplayTrackOrientationList );
// Set the distance along track
displayDistanceAlongTrack = 0.0;
// Set the display speed to the destination (in Java screen units per hour)
this.setDisplaySpeedAlongTrack( displayTrackTotalDistance / t );
// Give this event slightly higher priority in case the entity exits region after the wait.
// We want to resume this method first so that we can set the origin of the entity on its present region before it exits region.
scheduleWait( t, 4 );
this.setDisplaySpeedAlongTrack( 0.0 );
this.setPosition(destination);
this.setAlignment(new Vector3d());
}
public void updateGraphics() {}
public void initializeGraphics() {}
public void setupGraphics() {
// No DisplayModel
if(displayModelList.getValue() == null)
return;
clearModel();
synchronized (position) {
if(this.getDisplayModelList().getValue() != null){
for(DisplayModel each: this.getDisplayModelList().getValue()){
DisplayModelBG dm = each.getDisplayModel();
dm.setModelSize(size);
displayModels.add(dm);
}
}
DoubleVector distances;
distances = new DoubleVector(0);
if(this.getLevelOfDetail() != null){
distances = this.getLevelOfDetail();
}
// LOD is defined
if(distances.size() > 0){
Switch targetSwitch;
DistanceLOD dLOD;
float[] dists= new float[distances.size()];
for(int i = 0; i < distances.size(); i++){
dists[i] = (float)distances.get(i);
}
targetSwitch = new Switch();
targetSwitch.setCapability(Switch.ALLOW_SWITCH_WRITE);
dLOD = new DistanceLOD(dists, new Point3f());
BranchGroup lodBranchGroup = new BranchGroup();
lodBranchGroup.setName("lodBranchGroup");
// TODO: The bounding box should be big enough to include the camera. Otherwise, the model could not be seen
BoundingSphere bounds = new BoundingSphere(new Point3d(0,0,0), Double.POSITIVE_INFINITY);
for(DisplayModelBG each: displayModels){
targetSwitch.addChild(each);
}
dLOD.addSwitch(targetSwitch);
dLOD.setSchedulingBounds(bounds);
lodBranchGroup.addChild(dLOD);
lodBranchGroup.addChild(targetSwitch);
rootTransform.addChild(lodBranchGroup);
}
// One display model
else if (displayModels.size() > 0){
rootTransform.addChild(displayModels.get(0));
}
}
// Moving DisplayEntity with label (i.e. Truck and Train) is creating new DisplayEntity for its label when
// enterRegion(). This causes the ConcurrentModificationException to the caller of this method if it
// iterates through DisplayModel.getAll(). This is the place for the DisplayEntity to enterRegion though
if(this.getClass() == DisplayEntity.class){
enterRegion();
}
synchronized (position) {
needsRender = true;
}
}
public DisplayModel getDefaultDisplayModel(){
return DisplayModel.getDefaultDisplayModelForClass(this.getClass());
}
public EntityListInput<DisplayModel> getDisplayModelList() {
return displayModelList;
}
public DoubleVector getLevelOfDetail() {
return levelOfDetail.getValue();
}
/** Callback method so that the UI can inform a DisplayEntity it is about to be dragged by the user.<br>
* Called by the user interface to allow the DisplayEntity to setup properties or UI before it is moved
* in the user interface.
**/
public void preDrag() {}
/** Callback method so that the UI can inform a DisplayEntity that dragged by the user is complete.<br>
* Called by the user interface to allow the DisplayEntity to setup properties or UI after it has been moved
* in the user interface.
**/
public void postDrag() {}
public void dragged(Vector3d distance) {
Vector3d newPos = this.getPosition();
newPos.add(distance);
this.setPosition(newPos);
// update mouseNode positions
for( int i = 0; i < this.getMouseNodes().size(); i++ ) {
MouseNode node = this.getMouseNodes().get(i);
Vector3d nodePos = node.getPosition();
nodePos.add(distance);
node.setPosition(nodePos);
node.enterRegion( this.getCurrentRegion() );
}
// inform simulation and editBox of new positions
this.updateInputPosition();
}
/**
* Inform simulation and editBox of new positions.
* This method works for any DisplayEntity that uses the keyword "Center".
* Any DisplayEntity that does not use the keyword "Center" must overwrite this method.
*/
public void updateInputPosition() {
Vector3d vec = this.getPosition();
InputAgent.processEntity_Keyword_Value(this, positionInput, String.format( "%.3f %.3f %.3f %s", vec.x, vec.y, vec.z, positionInput.getUnits() ));
FrameBox.valueUpdate();
}
/**
* Inform simulation and editBox of new size.
* This method works for any DisplayEntity that sets size via the keyword "Extent".
* Any DisplayEntity that does not set size via the keyword "Extent" must overwrite this method.
*/
public void updateInputSize() {
Vector3d vec = this.getSize();
InputAgent.processEntity_Keyword_Value(this, sizeInput, String.format( "%.3f %.3f %.3f %s", vec.x, vec.y, vec.z, sizeInput.getUnits() ));
FrameBox.valueUpdate();
}
/**
* Inform simulation and editBox of new angle.
* This method works for any DisplayEntity that sets angle via the keyword "Orientation".
* Any DisplayEntity that does not set angle via the keyword "Orientation" must overwrite this method.
*/
public void updateInputOrientation() {
Vector3d vec = this.getOrientation();
InputAgent.processEntity_Keyword_Value(this, orientationInput, String.format( "%.3f %.3f %.3f %s", vec.x, vec.y, vec.z, orientationInput.getUnits() ));
FrameBox.valueUpdate();
}
public void updateInputAlignment() {
Vector3d vec = this.getAlignment();
InputAgent.processEntity_Keyword_Value(this, alignmentInput, String.format( "%.3f %.3f %.3f", vec.x, vec.y, vec.z ));
FrameBox.valueUpdate();
}
public ArrayList<MouseNode> getMouseNodes() {
return mouseNodes;
}
public void killMouseNodes() {
for( int i = this.getMouseNodes().size() - 1; i >= 0; i
MouseNode node = this.getMouseNodes().get( i );
this.getMouseNodes().remove( node );
node.kill();
}
}
public double getMouseNodesSize() {
return mouseNodesSize;
}
public void setMouseNodesSize( double size ) {
mouseNodesSize = size;
Vector3d nodeSize = new Vector3d(size, size, size);
for (MouseNode each : this.getMouseNodes()) {
each.setSize(nodeSize);
}
}
public void nodesOn() {
for (MouseNode each : mouseNodes) {
each.enterRegion(currentRegion);
}
}
public void nodesOff() {
for (MouseNode each : mouseNodes) {
each.exitRegion();
}
}
public boolean isActive() {
return active.getValue();
}
public boolean getShow() {
return show.getValue();
}
public boolean isMovable() {
return movable.getValue();
}
/**
* Method to return the name of the entity. Used when building Edit tree labels.
* @return the unique identifier of the entity, <region>/<entityName>, unless region == null or the default region
*/
public String toString() {
if(( currentRegion == simulation.getDefaultRegion() ) || (currentRegion == null) ) {
return getName();
}
else {
return (currentRegion.getName()+"/"+getName() );
}
}
public boolean showToolTip() {
return showToolTip.getValue();
}
public void validate()
throws InputErrorException {
super.validate();
Input.validateIndexedLists(displayModelList.getValue(), levelOfDetail.getValue(), "DisplayModel", "LevelOfDetail");
if(getRelativeEntity() == this) {
this.warning("validate()", "Relative Entities should not be defined in a circular loop", "");
}
}
/**
* This method updates the DisplayEntity for changes in the given input
*/
public void updateForInput( Input<?> in ) {
super.updateForInput( in );
if( in == positionInput ) {
this.setPosition( positionInput.getValue() );
return;
}
if( in == sizeInput ) {
this.setSize( sizeInput.getValue() );
return;
}
if( in == orientationInput ) {
this.setOrientation( orientationInput.getValue() );
return;
}
if( in == alignmentInput ) {
this.setAlignment( alignmentInput.getValue() );
return;
}
if( in == regionInput ) {
this.enterRegion( regionInput.getValue() );
return;
}
if( in == mouseNodesExtentInput ) {
this.setMouseNodesSize( mouseNodesExtentInput.getValue() );
return;
}
}
}
|
package com.sandwell.JavaSimulation3D;
import com.sandwell.JavaSimulation.Entity;
import com.sandwell.JavaSimulation.Vector;
import com.sun.j3d.utils.behaviors.vp.ViewPlatformAWTBehavior;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.event.MouseEvent;
import java.awt.event.MouseWheelEvent;
import com.sandwell.JavaSimulation3D.util.Rectangle;
import com.sandwell.JavaSimulation3D.util.Shape;
import javax.media.j3d.Transform3D;
import javax.vecmath.Point3d;
import javax.vecmath.Vector3d;
/**
* Provides mouse events processing of moving the viewer within a J3D environment.<br>
* Provides this functionality by providing the viewer location, the point to look at and the up vector.<br>
* Provides changes of the viewer of: zoom, pan, translate, orbit and field of view angle<br>
* Provides the position of the locator in model units
*/
public class OrbitBehavior extends ViewPlatformAWTBehavior {
public static final double DEFAULT_FOV = Math.PI / 3.15789d; // default if 57 degrees (about human FOV)
public static final double DEFAULT_RADIUS = 2.41d;
static final double MIN_RADIUS = 0.0000001d;
static final double MAX_RADIUS = Double.POSITIVE_INFINITY;
private static final double ORBIT_ANGLE_FACTOR = -0.01d;
// Temporary place where all the entityTooltip state will be shared
static MouseEvent tootipEvent = null;
static OrbitBehavior tooltipBehavior = null;
static boolean showtooltip = true;
static EntityToolTip entityToolTip = null;
// The enumerated mouse behavior modes
static final int CHANGE_PAN = 2;
static final int CHANGE_ROTATION = 4;
static final int CHANGE_TRANSLATION = 8;
static final int CHANGE_ZOOM_BOX = 64;
static final int CHANGE_NODE = 128;
static enum Plane { XY_PLANE, XZ_PLANE, YZ_PLANE };
private final Sim3DWindow window;
private final ModelView modelView;
private final Vector3d orbitCenter;
private final Vector3d orbitAngles;
private double orbitRadius;
private double fov;
// used for calculations (only create once)
private Vector3d universeDatumPoint = new Vector3d();
// Zoom box parameters
private int mouseX = 0;
private int mouseY = 0;
private Rectangle rectangle;
// Do/undo parameters
private Vector undoSteps = new Vector( 10, 1 ); // contains zoom steps
private int undoStep = 0; // The position of the current zoom step in undoSteps
private boolean windowMovedAndResized = false; // true => window both resized and moved
private static int mouseMode = OrbitBehavior.CHANGE_TRANSLATION;
private static boolean positionMode = true;
private static String currentCreationClass;
private Vector3d dragEntityStartPosition = new Vector3d();
// resize
protected static DisplayEntity selectedEntity = null;
private final Vector3d selectedStart = new Vector3d();
// moving in z direction
private int mouseXForZDragging; // x location needs to be fixed while moving in z direction
private boolean zDragging = false;
private static boolean resizeBounds = false;
public static final int CORNER_BOTTOMLEFT = 1;
public static final int CORNER_BOTTOMCENTER = 2;
public static final int CORNER_BOTTOMRIGHT = 3;
public static final int CORNER_MIDDLERIGHT = 4;
public static final int CORNER_TOPRIGHT = 5;
public static final int CORNER_TOPCENTER = 6;
public static final int CORNER_TOPLEFT = 7;
public static final int CORNER_MIDDLELEFT = 8;
public static final int CORNER_ROTATE = 9;
public static int resizeType = 0;
/**
* Creates a new OrbitBehavior
*
* @param c The Canvas3D to add the behavior to
* @param flags The option flags
*/
public OrbitBehavior(ModelView v, Sim3DWindow window) {
super(v.getCanvas3D(), MOUSE_LISTENER | MOUSE_MOTION_LISTENER);
modelView = v;
this.window = window;
setEnable( true );
orbitCenter = new Vector3d();
orbitAngles = new Vector3d();
orbitRadius = DEFAULT_RADIUS;
fov = DEFAULT_FOV;
integrateTransforms();
}
protected synchronized void processAWTEvents( final java.awt.AWTEvent[] events ) {
motion = false;
for( int i = 0; i < events.length; i++ ) {
if( events[i] instanceof MouseEvent ) {
MouseEvent evt = (MouseEvent)events[i];
// Check if the next event is the same as this event to suppress
// a large class of duplicates (dragging/moving)
if (i + 1 < events.length && events[i + 1] instanceof MouseEvent) {
MouseEvent nextevt = (MouseEvent)events[i + 1];
// events have the same ID
if (evt.getID() == nextevt.getID()) {
if (evt.getID() == MouseEvent.MOUSE_DRAGGED)
continue;
if (evt.getID() == MouseEvent.MOUSE_MOVED)
continue;
}
}
processMouseEvent(evt);
}
}
GraphicsUpdateBehavior.forceUpdate = true;
}
public void destroy() {
canvases = null;
}
static void enableTooltip(boolean enable) {
if (!enable)
OrbitBehavior.killToolTip();
OrbitBehavior.showtooltip = enable;
}
static void killToolTip() {
if( entityToolTip != null ) {
entityToolTip.abort();
entityToolTip = null;
}
}
public static void selectEntity(Entity ent) {
if(ent == selectedEntity)
return;
// Unselect previous entity
resizeObjectDeselected();
if (ent instanceof DisplayEntity) {
selectedEntity = (DisplayEntity)ent;
resizeBounds = true;
selectedEntity.setResizeBounds( true );
}
GraphicsUpdateBehavior.forceUpdate = true;
}
protected void processMouseEvent( final MouseEvent evt ) {
if (evt.getID() == MouseEvent.MOUSE_WHEEL) {
orbitRadius *= Math.pow(0.9d, -((MouseWheelEvent)evt).getWheelRotation());
// Cap the radius to a minimum value
orbitRadius = Math.max(orbitRadius, MIN_RADIUS);
motion = true;
return;
}
// ToolTip belongs to this window now
if (evt.getID() == MouseEvent.MOUSE_ENTERED) {
if (OrbitBehavior.showtooltip && entityToolTip == null) {
entityToolTip = new EntityToolTip();
entityToolTip.start();
}
tooltipBehavior = this;
return;
}
if (evt.getID() == MouseEvent.MOUSE_EXITED) {
tooltipBehavior = null;
tootipEvent = null;
// display nothing for the position
if (positionMode)
DisplayEntity.simulation.getGUIFrame().showLocatorPosition(null, window.getRegion());
return;
}
Vector3d currentMousePosition = getUniversePointFromMouseLoc(evt.getX(), evt.getY(), Plane.XY_PLANE, 0.0d);
if(evt.getClickCount() >= 2) {
// Just catch everything and move on
try {
DisplayEntity.simulation.getGUIFrame().copyLocationToClipBoard(currentMousePosition);
}
catch (Throwable e) {}
}
// calculate and display the position in the UI
if (positionMode)
DisplayEntity.simulation.getGUIFrame().showLocatorPosition(currentMousePosition, window.getRegion());
// Select the new entity
DisplayEntity closest = window.getPicker().getClosestEntity(evt);
// display the location of the locator when the mouse moves
if( evt.getID() == MouseEvent.MOUSE_MOVED ) {
// This is the new mousEvent for the tooltip
tootipEvent = evt;
// mouse moves inside the entity with resizeBounds set
if (selectedEntity == closest && resizeBounds) {
if( !(selectedEntity instanceof MouseNode) ){
selectedStart.set(this.getUniversePointFromMouseLoc(
evt.getX(), evt.getY(), Plane.XY_PLANE,
selectedEntity.getAbsoluteCenter().z));
// Pick the right mouse icon
resizeType = edgeSelected(selectedEntity, selectedStart);
}
}
else {
// Back to default mouse icon
edgeSelected(null, null);
}
return;
}
// Suppress tooltip when not a MOUSE_MOVED event
tootipEvent = null;
checkZDragging(evt);
// A) THE FIRST TIME MOUSE IS PRESSED
// setup the starting point
if( evt.getID() == MouseEvent.MOUSE_PRESSED ) {
this.storeUndoSteps();
FrameBox.setSelectedEntity( closest );
mouseX = evt.getX();
mouseY = evt.getY();
motion = true;
universeDatumPoint.set(currentMousePosition);
// ZOOM BOX INITIALIZATION
// The first point of the rectangle (Zoom box)
if( zoomBox( evt ) ) {
rectangle = new Rectangle(universeDatumPoint.x, universeDatumPoint.y, 0, 0, 0, Shape.SHAPE_OUTLINE);
rectangle.setLineStyle( Rectangle.LINE_DASH_1PX ); // box style
rectangle.setLayer( 4 );
rectangle.setColor( 1 ); // Black colour for the box
window.getRegion().addShape( rectangle );
}
if( drag( evt ) ) {
closest = window.getPicker().getClosestEntity(evt);
if (selectedEntity != null) {
// mouse clicked inside the entity with resizeBounds set
if (selectedEntity == closest && resizeBounds && !zDragging) {
selectedStart.set(this.getUniversePointFromMouseLoc(evt.getX(), evt.getY(), Plane.XY_PLANE, selectedEntity.getAbsoluteCenter().z));
}
else if(zDragging) {
selectedStart.set(this.getUniversePointFromMouseLoc(mouseXForZDragging, evt.getY(), Plane.XZ_PLANE, selectedEntity.getAbsoluteCenter().y));
}
}
} else if ( "add Node".equals(currentCreationClass) ) {
Vector3d posn = new Vector3d(currentMousePosition);
if (closest != null) {
closest.addMouseNodeAt(posn);
}
}
}
// B) MOUSE IS MOVING WHILE IT IS PRESSED
// handle the motions as they occur
else if( evt.getID() == MouseEvent.MOUSE_DRAGGED ) {
int xchange = evt.getX() - mouseX;
int ychange = evt.getY() - mouseY;
// 1) ZOOM BOX
if( zoomBox( evt ) && rectangle != null ) {
double h = currentMousePosition.y - universeDatumPoint.y;
double w = currentMousePosition.x - universeDatumPoint.x;
// System.out.println( "h:" + h + " w: " + w );
rectangle.setSize(w, h);
rectangle.setCenter( universeDatumPoint.x + w/2, universeDatumPoint.y + h/2, 0 );
rectangle.updateGeometry();
}
// 2) PAN
// translate the viewer and center (viewer and direction of view are translated)
else if( translate( evt ) && selectedEntity == null) {
Vector3d translateDiff = new Vector3d();
translateDiff.sub(universeDatumPoint, currentMousePosition);
translateDiff.z = 0.0d;
orbitCenter.add(translateDiff);
integrateTransforms();
return;
}
// 3) ROTATION
// rotate the viewer (viewer orbits about viewpoint, direction of view changes distance does not)
if( rotate( evt ) ) {
double phi = orbitAngles.x + ychange * ORBIT_ANGLE_FACTOR;
if (phi < -Math.PI)
phi = -Math.PI;
if (phi > Math.PI)
phi = Math.PI;
orbitAngles.x = phi;
double theta = orbitAngles.z + xchange * ORBIT_ANGLE_FACTOR;
theta %= 2.0d * Math.PI;
orbitAngles.z = theta;
}
// 4) POSITION OBJECTS
// 5) Resize Object
// 6) Dragging object:
if( drag( evt ) ) {
if (selectedEntity != null) {
// Check if we are resizing
Vector3d dragEnd = this.getUniversePointFromMouseLoc(evt.getX(), evt.getY(), Plane.XY_PLANE, selectedEntity.getAbsoluteCenter().z);
if (resizeBounds == true && resizeType > 0 && !zDragging) {
resizeObject(selectedEntity, selectedStart, dragEnd);
}
// Otherwise it is object dragging
else {
Vector3d dragdist = new Vector3d();
// z-axis dragging
if (zDragging) {
dragEnd = this.getUniversePointFromMouseLoc(mouseXForZDragging, evt.getY(), Plane.XZ_PLANE, selectedEntity.getAbsoluteCenter().y);
}
dragdist.sub(dragEnd, selectedStart);
selectedEntity.dragged(dragdist);
}
// update the start position for the net darg we process
selectedStart.set(dragEnd);
}
}
// IN ANY OF THE 1 TO 7 CASES
// reset values for next change
mouseX = evt.getX();
mouseY = evt.getY();
motion = true;
}
// C) MOUSE IS RELEASED
// when the motion has finished
else if( evt.getID() == MouseEvent.MOUSE_RELEASED ) {
// entity has been dragged
if( selectedEntity != null && resizeBounds == false ) {
// find distance to check if it has been dragged
Vector3d distanceVec = selectedEntity.getPosition();
distanceVec.sub(dragEntityStartPosition);
// completed drag, update entity center
selectedEntity.postDrag();
selectedEntity = null;
}
if( selectedEntity != null && resizeBounds == true && !zDragging ) {
selectedEntity.updateGraphics();
}
// Zooming to the box and removing the rectangle
if( zoomBox( evt ) && rectangle != null) {
Dimension d = modelView.getCanvas3D().getSize();
double aspect = (double)d.width / d.height;
// Find the physical width that will be viewed
// (Note: field of view uses only the horizontal width)
double rectWidth = Math.abs( rectangle.getWidth() );
double rectHeight = Math.abs( rectangle.getHeight() );
double widthOfView = Math.max(rectWidth, rectHeight * aspect);
// Only if the size of the zoom box is not zero
if( widthOfView > 0 ) {
// Distance of the eye point from the model (in z=0)
double zDistance = (widthOfView / 2) / Math.tan(fov / 2);
Point3d temp = rectangle.getCenterInDouble();
temp.z = 0.0d;
setOrbitCenter(temp);
temp.z = zDistance;
this.setViewer(temp);
// Needs to update the graphics properly
motion = true;
}
window.getRegion().removeShape(rectangle);
rectangle = null;
}
this.updateBehaviour();
this.storeUndoSteps();
// Update view inputs
if(zoomBox( evt ) || translate( evt )) {
window.getRegion().updateViewCenterInput();
window.getRegion().updateViewerInput();
window.getRegion().updateFOVInput();
}
}
this.updateBehaviour();
}
private void checkZDragging(MouseEvent evt) {
if(selectedEntity != null) {
if ( (evt.getModifiersEx() & MouseEvent.SHIFT_DOWN_MASK) == MouseEvent.SHIFT_DOWN_MASK ) {
// The first time that shift was pressed (dragging starts in z direction)
if(!zDragging) {
mouseXForZDragging = evt.getX();
selectedStart.set(this.getUniversePointFromMouseLoc(mouseXForZDragging, evt.getY(), Plane.XZ_PLANE, selectedEntity.getAbsoluteCenter().y));
zDragging = true;
}
}
// Shift just released (dragging or resizing/rotating in xy plane)
else if(zDragging){
selectedStart.set(this.getUniversePointFromMouseLoc(evt.getX(), evt.getY(), Plane.XY_PLANE, selectedEntity.getAbsoluteCenter().z));
zDragging = false;
}
}
}
protected synchronized void integrateTransforms() {
Transform3D cameraTransform = new Transform3D();
Vector3d translation = new Vector3d(0.0d, 0.0d, orbitRadius);
cameraTransform.setEuler(orbitAngles);
cameraTransform.transform(translation);
translation.add(orbitCenter);
cameraTransform.setTranslation(translation);
modelView.setViewState(cameraTransform, fov, orbitRadius);
}
public void setOrbitCenter(Point3d cent) {
orbitCenter.set(cent);
}
public Point3d getCenterPosition() {
// make a copy and return the copy
Point3d ret = new Point3d();
ret.set(orbitCenter);
return ret;
}
public void setOrbitAngles(double phi, double theta) {
orbitAngles.set(phi, 0.0d, theta);
}
public void setViewer(Point3d view) {
Vector3d relView = new Vector3d();
relView.sub(view, orbitCenter);
double dist1 = Math.hypot(relView.x, relView.y);
// suppress small-angle errors
if (dist1 < 0.0001d)
dist1 = 0.0d;
double phi = Math.atan2(dist1, relView.z);
// calculate the theta Eular angle, the Pi/2 addition is to account for
// the initial rotation towards the negative y-axis when off the z-axis
double theta = Math.atan2(relView.y, relView.x);
if (dist1 == 0.0d)
theta = 0.0d;
if (phi > 0.0d)
theta += Math.PI / 2.0d;
orbitAngles.set(phi, 0.0d, theta);
orbitRadius = relView.length();
}
public Point3d getViewer() {
Transform3D eular = new Transform3D();
Vector3d translation = new Vector3d(0.0d, 0.0d, orbitRadius);
eular.setEuler(orbitAngles);
eular.transform(translation);
translation.add(orbitCenter);
return new Point3d(translation);
}
public double getFOV() {
return fov;
}
public void setFOV(double fov) {
this.fov = fov;
}
public void positionViewer(Region aRegion) {
this.positionViewer(aRegion.getCurrentCenter(),
aRegion.getCurrentViewer(),
aRegion.getCurrentFOV());
}
private void positionViewer(Point3d centerPosition, Point3d viewerPosition, double fov) {
this.fov = fov;
setOrbitCenter( centerPosition );
setViewer(viewerPosition);
integrateTransforms();
}
Sim3DWindow getWindow() {
return window;
}
boolean rotate(MouseEvent evt) {
return mouseMode == OrbitBehavior.CHANGE_ROTATION && !evt.isMetaDown() && selectedEntity == null;
}
boolean zoomBox(MouseEvent evt) {
return mouseMode == OrbitBehavior.CHANGE_ZOOM_BOX && !evt.isMetaDown() && selectedEntity == null;
}
boolean translate(MouseEvent evt) {
return mouseMode == OrbitBehavior.CHANGE_TRANSLATION && !evt.isMetaDown() && selectedEntity == null;
}
boolean drag(MouseEvent evt) {
return !evt.isMetaDown() && mouseMode != OrbitBehavior.CHANGE_NODE;
}
public static void setCreationBehaviour(String entityTypeToCreate) {
OrbitBehavior.setViewerBehaviour(OrbitBehavior.CHANGE_TRANSLATION);
DisplayEntity.simulation.pause();
if ("add Node".equals(entityTypeToCreate)) {
OrbitBehavior.setViewerBehaviour(OrbitBehavior.CHANGE_NODE);
}
OrbitBehavior.currentCreationClass = entityTypeToCreate;
}
public static void setViewerBehaviour(int behaviour) {
OrbitBehavior.currentCreationClass = null;
if (mouseMode == OrbitBehavior.CHANGE_NODE) {
OrbitBehavior.resizeObjectDeselected();
}
mouseMode = behaviour;
}
public static void showPosition( boolean show ) {
positionMode = show;
}
public Vector3d getUniversePointFromMouseLoc( int x, int y, Plane plane, double planeHeight) {
// get the location of eye and the locator in the image plate
Point3d eyePosn = new Point3d();
modelView.getCanvas3D().getCenterEyeInImagePlate(eyePosn);
Point3d mousePosn = new Point3d();
modelView.getCanvas3D().getPixelLocationInImagePlate(x, y, mousePosn);
// get the transform to convert imageplate to virtual world
Transform3D locatorTrans = new Transform3D();
modelView.getCanvas3D().getImagePlateToVworld(locatorTrans);
// convert the image plate points to the virtual world
locatorTrans.transform(eyePosn);
locatorTrans.transform(mousePosn);
// calculate the view vector for the locator
Vector3d universePos = new Vector3d();
universePos.sub(mousePosn, eyePosn);
universePos.normalize();
// determine the distance from the plane and scale the vector
double scale = 0.0d;
switch (plane) {
case XZ_PLANE:
scale = -(eyePosn.y - planeHeight) / universePos.y;
break;
case YZ_PLANE:
scale = -(eyePosn.x - planeHeight) / universePos.x;
break;
case XY_PLANE:
scale = -(eyePosn.z - planeHeight) / universePos.z;
break;
}
universePos.scale(scale);
universePos.add(eyePosn);
// If this is a view of another region, then it has a current region
Region aRegion = window.getRegion();
if (aRegion.getCurrentRegion() != null) {
aRegion = aRegion.getCurrentRegion();
}
// scale by the Region's position for region coordinates
universePos.sub( aRegion.getPositionForAlignment(new Vector3d()) );
Vector3d regionScale = aRegion.getScale();
universePos.x /= regionScale.x;
universePos.y /= regionScale.y;
universePos.z /= regionScale.z;
// return the Universe position
return universePos;
}
// Updates both Sim3Dwindow and OrbitBehavior
public void updateViewerAndWindow( Point3d centerPosition, Point3d viewerPosition, java.awt.Point position, java.awt.Dimension size, double fov ) {
this.positionViewer(centerPosition, viewerPosition, fov);
// Window size has been changed by do or undo in the program (not by the user)
if( ! window.getSize().equals( size ) ) {
window.setInteractiveSizeChenge( false );
window.setSize(size);
}
// Window location has been changed by do or undo in the program (not by the user)
if( ! window.getLocation().equals( position ) ) {
window.setInteractiveLocationChenge( false );
window.setLocation(position);
}
window.getRegion().updatePositionViewer(centerPosition, viewerPosition, position, size, fov);
}
public void updateBehaviour() {
// If this is not the active window
if (Sim3DWindow.lastActiveWindow != window)
return;
window.getRegion().updatePositionViewer( this.getCenterPosition(), this.getViewer(), window.getLocation(), window.getSize(), fov);
if( undoStep > 1 || ( undoStep == 1 && ( this.viewerChanged() || ( ( window.moved() || window.resized() ) && ! windowMovedAndResized ) ) ) ) {
DisplayEntity.simulation.getGUIFrame().setToolButtonUndoEnable( true );
}
else {
DisplayEntity.simulation.getGUIFrame().setToolButtonUndoEnable( false );
}
if( undoStep == ( undoSteps.size() / 6 ) || ( undoStep == undoSteps.size() / 6 - 1 && ( this.viewerChanged() || ( ( window.moved() || window.resized() ) && ! windowMovedAndResized ) ) ) ) {
DisplayEntity.simulation.getGUIFrame().setToolButtonRedoEnable( false );
}
else {
DisplayEntity.simulation.getGUIFrame().setToolButtonRedoEnable( true );
}
}
public boolean viewerChanged() {
// Any step but the first
if( undoStep > 0 && undoSteps.size() > 0 ) {
Point3d viewer = this.getViewer();
// Viewer changed
if( ! orbitCenter.equals( undoSteps.get( (undoStep - 1)*6 )) || ! viewer.equals( (Point3d) undoSteps.get( (undoStep -1)*6 + 1 )) ||
! ( fov == ((Double) undoSteps.get( (undoStep - 1)*6 + 5 )).doubleValue() ) ) {
return true;
}
}
// The first step
if( undoStep == 0 && undoSteps.size() > 0 ) {
Point3d viewer = this.getViewer();
// Viewer changed
if( ! orbitCenter.equals( undoSteps.get( (undoStep )*6 )) || ! viewer.equals( (Point3d) undoSteps.get( (undoStep )*6 + 1 )) ||
! ( fov == ((Double) undoSteps.get( (undoStep )*6 + 5 )).doubleValue() ) ) {
return true;
}
}
return false;
}
public int getUndoStep() {
return undoStep;
}
public Vector getUndoSteps() {
return undoSteps;
}
public void storeUndoSteps( ) {
//System.out.println( "storeZoomSteps " );
if( ! ( this.viewerChanged() || window.moved() || window.resized() ) && undoSteps.size() != 0 ) {
return;
}
// TODO: We could have ignored this step if the componentMoved event fired after the window has been moved; this event keeps firing while the window is moving;
//////////// The above is a known bug in component listener
// viewer has not changed
if( ! this.viewerChanged() ) {
// 1) Window both moved and resized
if( ( window.moved() && window.resized() ) || windowMovedAndResized ) {
windowMovedAndResized = true;
// a) componentResized of the window has been triggered
if ( window.resizeTriggered() ) {
windowMovedAndResized = false;
window.setResizeTriggered( false );
}
// b) Wait until componentMoved is triggered
else {
return;
}
}
// 2) Window moved only
else if ( window.moved() && undoStep > 1 ) {
undoStep
// The only difference in last two undo steps is the window location
if ( window.moved() ) {
undoStep++;
// Only update the window location in the last undo step
undoSteps.setElementAt( window.getLocation(), undoSteps.size() - 3 );
return;
}
undoStep++;
}
// 3) Window resized only is a normal situation
}
// Remove the steps which were undid ( when undo several steps and then modify the view or window, the redo steps after the current step should be removed )
for( int i = undoSteps.size() - 1; i >= undoStep*6 && i >= 6; i
undoSteps.removeElementAt( i );
}
//System.out.println( "adding a new step: Position:" + window.getWindowPosition() + " -- Size:" + window.getWindowSize());
//System.out.println( "center:" + center + " viewer:" + viewer + " up:" + up + " fov:" + fov );
undoSteps.add(orbitCenter.clone());
undoSteps.add(this.getViewer());
undoSteps.add( new Vector3d() );
undoSteps.add( window.getLocation() );
undoSteps.add( window.getSize() );
undoSteps.add( new Double(fov) );
undoStep++;
this.updateBehaviour();
}
/** Undo the previous zoom step */
public boolean undoPreviousStep() {
// the current step is the last step
if( undoStep == undoSteps.size() / 6 ) {
storeUndoSteps();
undoStep
}
// There is at least one step to undo
if( undoStep > 0 ) {
undoStep
this.updateViewerAndWindow(new Point3d((Vector3d)undoSteps.get( undoStep*6 )), (Point3d) undoSteps.get( undoStep*6 + 1), (java.awt.Point) undoSteps.get( undoStep*6 + 3 ), (java.awt.Dimension) undoSteps.get( undoStep*6 + 4 ), ((Double) undoSteps.get( undoStep*6 + 5 )).doubleValue());
}
updateBehaviour();
// There is no more step to undo
if( undoStep == 0 ) {
return false;
}
// Undo is still possible
else {
return true;
}
}
/** Redo the previous step */
public boolean redoPreviousStep() {
// The current step is not the last step
if( undoStep < ( undoSteps.size() / 6 - 1) ) {
undoStep++;
this.updateViewerAndWindow(new Point3d((Vector3d)undoSteps.get( undoStep*6 )), (Point3d) undoSteps.get( undoStep*6 + 1), (java.awt.Point) undoSteps.get( undoStep*6 + 3 ), (java.awt.Dimension) undoSteps.get( undoStep*6 + 4 ), ((Double) undoSteps.get( undoStep*6 + 5 )).doubleValue());
}
updateBehaviour();
// This is the last step
if( undoStep == ( undoSteps.size() / 6 - 1) ) {
return false;
}
// redo is still possible
else {
return true;
}
}
private static void resizeObjectDeselected(){
if (selectedEntity == null)
return;
resizeBounds = false;
resizeType = 0;
selectedEntity.setResizeBounds( false );
selectedEntity = null;
}
/**
* resize the selected Object
*/
private void resizeObject(DisplayEntity ent, Vector3d start, Vector3d end){
if (ent == null)
return;
double resizeAverage = 0; // used for corners
Vector3d center = ent.getAbsoluteCenter();
Vector3d orient = ent.getOrientation();
// get current point
Vector3d resizeStartRotated = ent.getCoordinatesForRotationAroundPointByAngleForPosition(center, -orient.z, start);
Vector3d resizeEndRotated = ent.getCoordinatesForRotationAroundPointByAngleForPosition(center, -orient.z, end);
Vector3d resizediff = new Vector3d();
resizediff.sub( resizeEndRotated, resizeStartRotated );
Vector3d selectedEntitySize = ent.getSize();
// resize the object according to which corner was selected
switch( resizeType ){
case CORNER_BOTTOMLEFT:
// take the average change (equal horizontal and vertical resize);
resizeAverage = (resizediff.x + resizediff.y);
selectedEntitySize.x -= resizeAverage;
selectedEntitySize.y -= resizeAverage;
// new size of entity is the old size + dragged amount
ent.setSize(selectedEntitySize);
ent.updateInputPosition();
ent.updateInputSize();
break;
case CORNER_BOTTOMCENTER:
// Adjust only y
// multiply by 2 to adjust both top and bottom
resizeAverage = 2 * resizediff.y;
selectedEntitySize.y -= resizeAverage;
ent.setSize(selectedEntitySize);
ent.updateInputPosition();
ent.updateInputSize();
break;
case CORNER_BOTTOMRIGHT:
resizeAverage = (resizediff.x - resizediff.y);
selectedEntitySize.x += resizeAverage;
selectedEntitySize.y += resizeAverage;
ent.setSize(selectedEntitySize);
ent.updateInputPosition();
ent.updateInputSize();
break;
case CORNER_MIDDLERIGHT:
resizeAverage = 2 * resizediff.x;
selectedEntitySize.x += resizeAverage;
ent.setSize(selectedEntitySize);
ent.updateInputPosition();
ent.updateInputSize();
break;
case CORNER_TOPRIGHT:
resizeAverage = (resizediff.x + resizediff.y);
selectedEntitySize.x += resizeAverage;
selectedEntitySize.y += resizeAverage;
selectedEntitySize.add(resizediff);
ent.setSize(selectedEntitySize);
ent.updateInputPosition();
ent.updateInputSize();
break;
case CORNER_TOPCENTER:
resizeAverage = 2 * resizediff.y;
selectedEntitySize.y += resizeAverage;
ent.setSize(selectedEntitySize);
ent.updateInputPosition();
ent.updateInputSize();
break;
case CORNER_TOPLEFT:
// top left
resizeAverage = ( resizediff.y - resizediff.x );
selectedEntitySize.x += resizeAverage;
selectedEntitySize.y += resizeAverage;
ent.setSize(selectedEntitySize);
ent.updateInputPosition();
ent.updateInputSize();
break;
case CORNER_MIDDLELEFT:
// middle left
resizeAverage = 2 * resizediff.x;
selectedEntitySize.x -= resizeAverage;
ent.setSize(selectedEntitySize);
ent.updateInputPosition();
ent.updateInputSize();
break;
case CORNER_ROTATE:
Vector3d diff = new Vector3d();
diff.sub(end, center);
// add PI as the resize line points to the left
double zAngle = Math.atan2(diff.y, diff.x) + Math.PI;
diff.set(orient.x, orient.y, zAngle);
ent.setOrientation(diff);
ent.updateInputOrientation();
break;
}
}
private boolean calcEdgeDistance(DisplayEntity ent, Vector3d pt, Vector3d align, double dist) {
Vector3d alignPoint = ent.getAbsolutePositionForAlignment(align);
alignPoint.sub(pt);
return alignPoint.lengthSquared() < dist;
}
/**
* Find the corner that has been selected or mouse over and change the mouse icon
* to resize icon if a corner has been selected
* @param currentPoint
* @return
*/
private int edgeSelected(DisplayEntity ent, Vector3d currentPoint) {
if (ent == null) {
window.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
return 0;
}
// the square of the radius of the circles at each corner that are
// used for resizing
Vector3d tmp = ent.getSize();
double distSquare = 0.10 * Math.min(tmp.x, tmp.y);
distSquare = distSquare * distSquare;
tmp.set(-0.5d, -0.5d, 0.0d);
if (calcEdgeDistance(ent, currentPoint, tmp, distSquare)) {
setCursor(1, ent);
return CORNER_BOTTOMLEFT;
}
tmp.set(0.0d, -0.5d, 0.0d);
if (calcEdgeDistance(ent, currentPoint, tmp, distSquare)) {
setCursor(2, ent);
return CORNER_BOTTOMCENTER;
}
tmp.set(0.5d, -0.5d, 0.0d);
if (calcEdgeDistance(ent, currentPoint, tmp, distSquare)) {
setCursor(3, ent);
return CORNER_BOTTOMRIGHT;
}
tmp.set(0.5d, 0.0d, 0.0d);
if (calcEdgeDistance(ent, currentPoint, tmp, distSquare)) {
setCursor(0, ent);
return CORNER_MIDDLERIGHT;
}
tmp.set(0.5d, 0.5d, 0.0d);
if (calcEdgeDistance(ent, currentPoint, tmp, distSquare)) {
setCursor(1, ent);
return CORNER_TOPRIGHT;
}
tmp.set(0.0d, 0.5d, 0.0d);
if (calcEdgeDistance(ent, currentPoint, tmp, distSquare)) {
setCursor(2, ent);
return CORNER_TOPCENTER;
}
tmp.set(-0.5d, 0.5d, 0.0d);
if (calcEdgeDistance(ent, currentPoint, tmp, distSquare)) {
setCursor(3, ent);
return CORNER_TOPLEFT;
}
tmp.set(-0.5d, 0.0d, 0.0d);
if (calcEdgeDistance(ent, currentPoint, tmp, distSquare)) {
setCursor(0, ent);
return CORNER_MIDDLELEFT;
}
tmp.set(-1.0d, 0.0d, 0.0d);
if (calcEdgeDistance(ent, currentPoint, tmp, distSquare)) {
window.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
return CORNER_ROTATE;
}
window.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
return 0;
}
/**
* set cursor to match the selected edge
* @param cursor
* @param degree
*/
private void setCursor(int cursor, DisplayEntity ent) {
int rotate;
double degree = ent.getOrientation().z % Math.PI;
// If entity has been rotated, change resize cursor direction
if( degree > 2.7488 ){
// rotate 157.5 degree to 180 degree
rotate = 0;
} else if ( degree > 1.963495 ){
// rotate 112.5 degree to 157.5 degree
rotate = 3;
} else if( degree > 1.170097225 ){
// rotate 67.5 degree to 112.5 degree
rotate = 2;
} else if ( degree > 0.392699 ){
// rotate 22.5 degree to 67.5 degree
rotate = 1;
} else {
// no rotation
rotate = 0;
}
cursor = (cursor + rotate)%4;
switch(cursor) {
case 0: window.setCursor(new Cursor(Cursor.E_RESIZE_CURSOR)); break;
case 1: window.setCursor(new Cursor(Cursor.NE_RESIZE_CURSOR)); break;
case 2: window.setCursor(new Cursor(Cursor.N_RESIZE_CURSOR)); break;
case 3: window.setCursor(new Cursor(Cursor.NW_RESIZE_CURSOR)); break;
}
}
}
|
package org.jboss.as.server.deployment;
import java.util.Map;
import java.util.Set;
import org.jboss.msc.service.ServiceName;
/**
* An action that sets up and tears down some form of context (e.g. the TCCL, JNDI context etc).
* <p>
* Implementations need to be thread safe, as multiple threads can be setting up and tearing down contexts at any given time.
*
* @author Stuart Douglas
*
*/
public interface SetupAction {
/**
* Sets up the context. If this method throws an exception then the {@link #teardown(java.util.Map)} method will not be called, so this
* method should be implmeneted in an atomic manner.
*
* @param properties data that a caller may provide to help configure the behavior of the action. May be {@code null}. An implementation
* that expects certain properties should either require it is only used in cases where those properties will be provided,
* or do something reasonable (e.g. become a no-op) if they are not provided.
*/
void setup(Map<String, Object> properties);
/**
* Tears down the context that was set up and restores the previous context state.
*
* @param properties data that a caller may provide to help configure the behavior of the action. May be {@code null}. An implementation
* that expects certain properties should either require it is only used in cases where those properties will be provided,
* or do something reasonable (e.g. become a no-op) if they are not provided.
*/
void teardown(Map<String, Object> properties);
/**
* Higher priority setup actions run first
*
* @return the priority
*/
int priority();
/**
* Any dependencies that this action requires
*
* @return the names of the services this action requires. Will not be {@code null}.
*/
Set<ServiceName> dependencies();
}
|
package dominio;
import razas.*;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import dominio.*;
public abstract class Personaje implements Peleador {
protected int vida,
experiencia,
nivel,
energia,
ataque,
defensa,
magia,
//dao, // @Mauro - Este atributo me parece al dope
destreza,
velocidad,
potencia;
protected String raza;
protected Casta clase;
protected ArrayList<PersonajeEquipado> lista = new ArrayList<>();
protected Map<String, Ataque> ataques = new HashMap<String, Ataque>();
protected Usuario usuarioPersonaje;
//protected Alianza alianzaActual;
public Personaje(String nombre, String password){
//usuarioPersonaje = new Usuario(username,password);
usuarioPersonaje = new Usuario(nombre,password);
this.vida = 100;
this.energia = 100;
this.experiencia = 0;
this.nivel = 1;
}
public Personaje(Personaje p){
//super(p.getUsername(),p.getPassword());
this.usuarioPersonaje = p.usuarioPersonaje;
this.vida = 100;
this.energia = 100;
this.experiencia = 0;
this.nivel = 1;
}
/* @mauroat - 18/10/16
* Se modifica este mtodo para que se sume ms experiencia en caso que mate al atacado.
* Mi idea es que cuando esten implementadas las razas tambien afecten la experiencia.
*
* */
// Esto recibia un Atacable
public final void atacar(Personaje atacado) throws FileNotFoundException {
if(atacado.estaVivo()){
if (this.puedeAtacar()) {
atacado.serAtacado(calcularPuntosDeAtaque());
// El siguiente metodo podr implementarse cuando definamos la ubicacin de los personajes
//atacado.despuesDeSerAtacado();
this.energia -= calcularPuntosDeAtaque();
if(atacado.estaVivo()){
// Por cada ataque que haga, mi experiencia sube en 8
this.experiencia += 8;
} else {
// Si en cambio, mato al atacado, mi experiencia sube en 10*el nivel del atacado
this.experiencia+=(atacado.getNivel()*10);
}
this.despuesDeAtacar();
} else{
System.out.println(this.usuarioPersonaje.getUsername() +" no tiene energa suficiente para atacar!");
//System.out.println(this.getUsername()+" no tiene energa suficiente para atacar!");
}
}
else{
// Esta linea se va a comentar
System.out.println("El atacado est muerto, no se lo puede atacar.");
}
}
/* @mauroat - 18/10/16
* Se sobrecarga el mtodo atacar, para que se apliquen los daos causados por los ataques que posee cada personaje.
* */
public final void atacar(Personaje atacado, Ataque a) throws FileNotFoundException {
if(atacado.estaVivo()){
if (this.puedeAtacar()) {
atacado.serAtacado(calcularPuntosDeAtaque()+a.aplicarAtaque());
// El siguiente mtodo podr implementarse cuando definamos la ubicacin de los personajes
//atacado.despuesDeSerAtacado();
this.energia -= calcularPuntosDeAtaque()+a.aplicarAtaque();
if(atacado.estaVivo()){
// Por cada ataque que haga, mi experiencia sube en 8
this.experiencia += 8;
} else {
// Si en cambio, mato al atacado, mi experiencia sube en 10*el nivel del atacado
this.experiencia+=(atacado.getNivel()*10);
}
this.despuesDeAtacar();
} else{
System.out.println(this.usuarioPersonaje.getUsername() +" no tiene energa suficiente para atacar!");
//System.out.println(this.getUsername()+" no tiene energa suficiente para atacar!");
}
}
else{
// Esta linea se va a comentar
System.out.println("El atacado est muerto, no se lo puede atacar.");
}
}
public void despuesDeSerAtacado(){
if(this.vida <=0)
this.morir();
}
public void verEstado(){
System.out.println("Personaje: "+this.usuarioPersonaje.getUsername());
System.out.println("Salud: "+this.vida);
System.out.println("Energia: "+this.energia);
System.out.println("
System.out.println("Raza: "+this.getRaza());
System.out.println("Nivel: "+this.nivel);
System.out.println("Experiencia: "+this.experiencia);
System.out.println("
System.out.println("Ataque: "+this.calcularPuntosDeAtaque());
System.out.println("Defensa: "+this.calcularPuntosDeDefensa());
System.out.println("Magia: "+this.calcularPuntosDeMagia());
System.out.println("
System.out.println("Destreza: "+this.destreza);
System.out.println("Velocidad: "+this.velocidad);
System.out.println("Potencia: "+this.potencia);
System.out.println("===============");
}
public void despuesDeAtacar() throws FileNotFoundException {
this.verificarNivel();
}
private void verificarNivel() throws FileNotFoundException {
if(this.experiencia >= experienciaRequerida(this.nivel)){
this.nivel++;
}
}
private int experienciaRequerida(int nivel) throws FileNotFoundException{
try{
// Esto ser reemplazado por una consulta a una base de datos
Scanner sc = new Scanner (new File ("config/niveles.cfg"));
while(sc.hasNextLine()){
if(nivel == sc.nextInt()){
return sc.nextInt();
}
sc.nextInt();
}
sc.close();
} catch(Exception e){
e.printStackTrace();
}
return 0;
}
public abstract boolean puedeAtacar();
public abstract int calcularPuntosDeAtaque();
public abstract int calcularPuntosDeDefensa();
public abstract int calcularPuntosDeMagia();
public abstract String getRaza();
public void morir(){
this.vida=0;
//Tengo que dejar el mejor item
//this.dejarItem();
this.reaparecer();
this.revivir();
}
private void revivir() {
this.serCurado();
this.serEnergizado();
}
private void reaparecer() {
// Este mtodo tiene que reubicarme en una zona segura
}
public boolean estaVivo() {
return this.vida > 0;
}
/* @mauroat - 18/10/16
* Modifico este mtodo para que los puntos de defensa amortiguen el dao recibido en los ataques
* */
@Override
public void serAtacado(int dao) {
this.vida -= dao-this.calcularPuntosDeDefensa();
}
public void serCurado() {
this.vida = 100;
}
public void serEnergizado() {
this.energia = 100;
}
public int getVida() {
return vida;
}
public int getExperiencia() {
return experiencia;
}
public void setExperiencia(int experiencia) {
this.experiencia = experiencia;
}
public int getNivel() {
return nivel;
}
public void setNivel(int nivel) {
this.nivel = nivel;
}
public int getEnergia() {
return energia;
}
public void setEnergia(int energia) {
this.energia = energia;
}
public int getDestreza() {
return destreza;
}
public void setDestreza(int destreza) {
this.destreza = destreza;
}
public int getVelocidad() {
return velocidad;
}
public void setVelocidad(int velocidad) {
this.velocidad = velocidad;
}
public int getPotencia() {
return potencia;
}
public void setPotencia(int potencia) {
this.potencia = potencia;
}
public void setRaza(String raza) {
this.raza = raza;
}
public void setVida(int vida) {
this.vida = vida;
}
/* LISTA DE ITEMS */
public void getLista() {
System.out.println("Cantidad de items: "+lista.size());
for(int i=0; i<lista.size();i++)
System.out.println(lista.get(i));
}
public int getTamaoLista() {
return lista.size();
}
public void agregarALista(PersonajeEquipado pe) {
//this.lista.add(pe);
this.lista.addAll(Arrays.asList(pe));
}
public PersonajeEquipado getItemMasPrioritario() {
PersonajeEquipado aux = null;
int max = -1;
for(int i=0; i<lista.size();i++){
if(max < lista.get(i).getPrioridad()){
max = lista.get(i).getPrioridad();
aux = lista.get(i);
}
}
return aux;
}
/* HASMAP DE ATAQUES */
public void agregarAtaque(Ataque a){
this.ataques.put(a.getNombre(), a);
}
public void quitarAtaque(Ataque a){
this.ataques.remove(a.getNombre());
}
public void getListaAtaques(){
int i = 1;
for (Map.Entry<String, Ataque> entry : this.ataques.entrySet()) {
System.out.println("Ataque "+i+": "+entry.getKey());
i++;
}
}
public int getCantidadAtaques(){
return this.ataques.size();
}
public Ataque getAtaque(String ataque){
return this.ataques.get(ataque);
}
public String toString()
{
return this.usuarioPersonaje.getUsername();
}
public boolean inteactuarConOtroPersonaje(Personaje obj)
{
return obj.respuesta();
}
public boolean respuesta()
{
return true;
}
public boolean equals(Personaje obj)
{
if(this.usuarioPersonaje.equals(obj.usuarioPersonaje))
return true;
return false;
}
}
|
package controllers;
import static org.apache.commons.httpclient.HttpStatus.SC_FORBIDDEN;
import static org.apache.commons.httpclient.HttpStatus.SC_OK;
import static org.junit.Assert.assertEquals;
import static org.sagebionetworks.bridge.TestConstants.STUDYCONSENT_ACTIVE_URL;
import static org.sagebionetworks.bridge.TestConstants.STUDYCONSENT_URL;
import static org.sagebionetworks.bridge.TestConstants.TIMEOUT;
import static play.test.Helpers.running;
import static play.test.Helpers.testServer;
import java.util.List;
import javax.annotation.Resource;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.sagebionetworks.bridge.BridgeConstants;
import org.sagebionetworks.bridge.TestConstants.TestUser;
import org.sagebionetworks.bridge.TestUserAdminHelper;
import org.sagebionetworks.bridge.TestUtils;
import org.sagebionetworks.bridge.models.UserSession;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import play.libs.WS.Response;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Lists;
@ContextConfiguration("classpath:test-context.xml")
@RunWith(SpringJUnit4ClassRunner.class)
public class StudyConsentControllerTest {
private ObjectMapper mapper = new ObjectMapper();
public StudyConsentControllerTest() {
mapper.setSerializationInclusion(Include.NON_NULL);
}
@Resource
private TestUserAdminHelper helper;
private UserSession adminSession;
private UserSession userSession;
@Before
public void before() {
List<String> roles = Lists.newArrayList(BridgeConstants.ADMIN_GROUP);
// TODO: When you create two users, they need different email/names. Randomize this in the helper
// so you don't have to spell this out.
adminSession = helper.createUser(new TestUser("admin-user", "admin-user@sagebridge.org", "P4ssword"), roles,
helper.getStudy(), true, true);
userSession = helper.createUser(new TestUser("normal-user", "normal-user@sagebridge.org", "P4ssword"), null,
helper.getStudy(), true, true);
}
@After
public void after() {
helper.deleteUser(adminSession);
helper.deleteUser(userSession);
}
@Test
public void test() {
running(testServer(3333), new TestUtils.FailableRunnable() {
@Override
public void testCode() throws Exception {
// Fields are order independent.
String consent = "{\"minAge\":17,\"path\":\"fake-path\\to\\StudyConsentControllerTest\"}";
Response addConsentFail = TestUtils.getURL(userSession.getSessionToken(), STUDYCONSENT_URL)
.post(consent).get(TIMEOUT);
assertEquals("Must be admin to access consent.", SC_FORBIDDEN, addConsentFail.getStatus());
Response addConsent = TestUtils.getURL(adminSession.getSessionToken(), STUDYCONSENT_URL).post(consent)
.get(TIMEOUT);
assertEquals("Successfully add consent.", SC_OK, addConsent.getStatus());
// Get timeout to access this consent later.
String createdOn = addConsent.asJson().get("createdOn").asText();
Response setActive = TestUtils
.getURL(adminSession.getSessionToken(), STUDYCONSENT_ACTIVE_URL + "/" + createdOn).post("")
.get(TIMEOUT);
assertEquals("Successfully set active consent.", SC_OK, setActive.getStatus());
Response getActive = TestUtils.getURL(adminSession.getSessionToken(), STUDYCONSENT_ACTIVE_URL).get()
.get(TIMEOUT);
assertEquals("Successfully get active consent.", SC_OK, getActive.getStatus());
Response getAll = TestUtils.getURL(adminSession.getSessionToken(), STUDYCONSENT_URL).get().get(TIMEOUT);
assertEquals("Successfully get all consents.", SC_OK, getAll.getStatus());
}
});
}
}
|
package dmh.kuebiko.controller;
import static com.google.common.collect.Iterables.getOnlyElement;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertTrue;
import java.util.List;
import org.testng.annotations.Test;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import dmh.kuebiko.model.Note;
import dmh.kuebiko.test.TestHelper;
/**
* TestNG test class for the NoteManager controller class.
* @see dmh.kuebiko.controller.NoteManager
*
* @author davehuffman
*/
public class NoteManagerTest {
@Test(expectedExceptions = UnsupportedOperationException.class)
public void immutableNotesTest() {
TestHelper.newNoteManager().getNotes().add(new Note());
}
@Test
public void addNewNoteWithTitleTest() {
final NoteManager noteMngr = TestHelper.newNoteManager();
// Fill a list of dummy note titles.
final int noteCount = 1000;
final List<String> dummyTitles = Lists.newArrayListWithCapacity(noteCount);
for (int i = 0; i < noteCount; i++) {
dummyTitles.add(String.format("foobar-%d", i));
}
for (String dummyTitle: dummyTitles) {
noteMngr.addNewNote(dummyTitle);
}
assertEquals(dummyTitles.size(), noteMngr.getNotes().size(),
"Note stack should contain same number of added notes.");
for (String dummyTitle: dummyTitles) {
assertTrue(noteMngr.getNoteTitles().contains(dummyTitle),
"Note stack should contain each added note.");
}
}
@Test
public void addOneNewNoteWIthoutTitleTest() {
final NoteManager noteMngr = TestHelper.newNoteManager();
assertEquals(0, noteMngr.getNoteCount(), "Note stack should be empty.");
final String newNoteTitle = noteMngr.addNewNote();
assertEquals(NoteManager.DEFAULT_NOTE_TITLE, newNoteTitle,
"First untitled note should have dafault title.");
assertEquals(newNoteTitle, getOnlyElement(noteMngr.getNotes()).getTitle(),
"Note in stack should have returned title.");
}
@Test
public void addNewNotesWithoutTitlesTest() {
final NoteManager noteMngr = TestHelper.newNoteManager();
// Fill a list of dummy note titles.
final int noteCount = 10;
List<String> titles = Lists.newArrayList();
for (int i = 0; i < noteCount; i++) {
String title = noteMngr.addNewNote();
assertFalse(titles.contains(title), "New title should be unique.");
titles.add(title);
}
assertEquals(noteCount, Sets.newHashSet(titles).size(),
"Should have expected number of unique titles.");
assertEquals(noteMngr.getNoteCount(),
Sets.newHashSet(noteMngr.getNoteTitles()).size(),
"All notes should have unique titles.");
// Save the added notes; this will invoke validation what will ensure
// that all the notes have unique titles.
noteMngr.saveAll();
}
@Test(expectedExceptions = DataStoreException.class)
public void saveNotesWithDuplicateTitlesTest() {
final NoteManager noteMngr = TestHelper.newNoteManager();
final String title = "foobar";
noteMngr.addNewNote(title);
assertEquals(1, noteMngr.getNotes().size(),
"There should be only one note in the stack.");
assertEquals(title, getOnlyElement(noteMngr.getNotes()).getTitle(),
"The only note in the stack should be the added note.");
noteMngr.addNewNote(title);
noteMngr.saveAll();
}
}
|
package edu.cmu.minorthird.classify;
import edu.cmu.minorthird.classify.experiments.Evaluation;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import edu.cmu.minorthird.classify.algorithms.svm.SVMLearner;
import edu.cmu.minorthird.classify.*;
import junit.framework.Test;
import junit.framework.TestSuite;
import libsvm.*;
import org.apache.log4j.Logger;
import org.apache.log4j.Level;
import java.io.*;
import java.util.StringTokenizer;
/**
*
* This class is responsible for...
*
* @author ksteppe
*/
public class LibsvmTest extends AbstractClassificationChecks
{
Logger log = Logger.getLogger(this.getClass());
private static final String trainFile = "test/edu/cmu/minorthird/classify/testData/a1a.dat";
private static final String model = "modelFile.dat";
private static final String testFile = "test/edu/cmu/minorthird/classify/testData/a1a.t.dat";
/**
* Standard test class constructior for LibsvmTest
* @param name Name of the test
*/
public LibsvmTest(String name)
{
super(name);
}
/**
* Convinence constructior for LibsvmTest
*/
public LibsvmTest()
{
super("LibsvmTest");
}
/**
* setUp to run before each test
*/
protected void setUp()
{
org.apache.log4j.Logger.getRootLogger().removeAllAppenders();
org.apache.log4j.BasicConfigurator.configure();
log.setLevel(Level.DEBUG);
super.setCheckStandards(false);
//TODO add initializations if needed
}
/**
* clean up to run after each test
*/
protected void tearDown()
{
//TODO clean up resources if needed
}
/**
* tests using svm_train.main, etc.
*/
public void testDirectCode() {
log.debug("start");
try {
//svm_train.main(new String[]{"-t", "0", trainFile, model});
log.debug("trained, sent model to: " + model);
/*double[] results = prediction(new String[]{testFile, model, "results.dat"});
log.debug("ran predict on testfile");
double[] expect = new double[]{0.8352766230693838, 0.6588935077224645, 0.28752077092970524};
checkStats(results, expect);
*/
}
catch (Exception e) {
log.error(e, e);
fail("exception");
}
}
/**
* use wrapper on the provided data, should get same results
* as the direct
*/
public void testWrapper()
{
try {
//get datasets
Dataset trainData = DatasetLoader.loadSVMStyle(new File(trainFile));
Dataset testData = DatasetLoader.loadSVMStyle(new File(testFile));
//send expectations to checkClassifyText()
double[] expect = new double[]{0.13769470404984424, 0.6011745705024105, 0.6934812760055479, 1.3132616875183545};
super.setCheckStandards(true);
super.checkClassify(new SVMLearner(), trainData, testData, expect);
}
catch (Exception e) {
log.error(e, e);
}
}
/**
* run the svm wrapper on the sample data
*/
public void testSampleData()
{
double[] refs = new double[]{0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, //0-6 are 0
1.0, 1.0, //7-8 are 1
1.3132616875182228,
1.0, 1.0, 1.0, //10-12 are 1
1.0 }; //13 is 1
super.checkClassify(new SVMLearner(), SampleDatasets.toyTrain(), SampleDatasets.toyTest(), refs);
}
/**
* Test a full cycle of training, testing, saving (serializing), loading, and testing again.
**/
public void testSerialization() {
try {
// Create a classifier using the SVMLearner and the toyTrain dataset
SVMLearner l = new SVMLearner();
Classifier c1 = new DatasetClassifierTeacher(SampleDatasets.toyTrain()).train(l);
File tempFile = File.createTempFile("SVMTest", "classifier");
// Evaluate it immediately saving the stats
Evaluation e1 = new Evaluation(SampleDatasets.toyTrain().getSchema());
e1.extend(c1, SampleDatasets.toyTest(), 1);
double[] stats1 = new double[4];
stats1[0] = e1.errorRate();
stats1[1] = e1.averagePrecision();
stats1[2] = e1.maxF1();
stats1[3] = e1.averageLogLoss();
// Serialize the classifier to disk
//ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream("SVMTest.classifier")));
ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(tempFile)));
out.writeObject(c1);
out.flush();
out.close();
// Load it back in.
//ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(new FileInputStream("SVMTest.classifier")));
ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(new FileInputStream(tempFile)));
Classifier c2 = (Classifier)in.readObject();
in.close();
// Evaluate again saving the stats
Evaluation e2 = new Evaluation(SampleDatasets.toyTrain().getSchema());
e2.extend(c2, SampleDatasets.toyTest(), 1);
//double[] stats2 = e2.summaryStatistics();
double[] stats2 = new double[4];
stats2[0] = e2.errorRate();
stats2[1] = e2.averagePrecision();
stats2[2] = e2.maxF1();
stats2[3] = e2.averageLogLoss();
// Only use the basic stats for now because some of the advanced stats
// come back as NaN for both datasets and the check stats method can't
// handle NaN's
log.info("using Standard stats only (4 of them)");
// Compare the stats produced from each run to make sure they are identical
checkStats(stats1, stats2);
// Remove the temporary classifier file
tempFile.delete();
}
catch (Exception e) {
e.printStackTrace();
}
}
/**
* Creates a TestSuite from all testXXX methods
* @return TestSuite
*/
public static Test suite()
{
return new TestSuite(LibsvmTest.class);
}
/**
* Run the full suite of tests with text output
* @param args - unused
*/
public static void main(String args[])
{
junit.textui.TestRunner.run(suite());
}
// Crap from svm_predict.java
private double[] predict(BufferedReader input, DataOutputStream output, svm_model model) throws IOException
{
int correct = 0;
int total = 0;
double error = 0;
double sumv = 0, sumy = 0, sumvv = 0, sumyy = 0, sumvy = 0;
while (true)
{
String line = input.readLine();
if (line == null) break;
StringTokenizer st = new StringTokenizer(line, " \t\n\r\f:");
double target = atof(st.nextToken());
int m = st.countTokens() / 2;
svm_node[] x = new svm_node[m];
for (int j = 0; j < m; j++)
{
x[j] = new svm_node();
x[j].index = atoi(st.nextToken());
x[j].value = atof(st.nextToken());
}
double v = svm.svm_predict(model, x);
if (v == target)
++correct;
error += (v - target) * (v - target);
sumv += v;
sumy += target;
sumvv += v * v;
sumyy += target * target;
sumvy += v * target;
++total;
// output.writeBytes(v+"\n");
}
log.debug("Accuracy = " + (double)correct / total * 100 +
"% (" + correct + "/" + total + ") (classification)\n");
log.debug("Mean squared error = " + error / total + " (regression)\n");
log.debug("Squared correlation coefficient = " +
((total * sumvy - sumv * sumy) * (total * sumvy - sumv * sumy)) /
((total * sumvv - sumv * sumv) * (total * sumyy - sumy * sumy)) + " (regression)\n"
);
double[] rvalues = new double[3];
rvalues[0] = (double)correct / (double)total;
rvalues[1] = error / (double)total;
rvalues[2] = ((total * sumvy - sumv * sumy) * (total * sumvy - sumv * sumy)) /
((total * sumvv - sumv * sumv) * (total * sumyy - sumy * sumy));
return rvalues;
}
private double[] prediction(String argv[]) throws IOException
{
if (argv.length != 3)
{
System.err.print("usage: svm-predict test_file model_file output_file\n");
System.exit(1);
}
BufferedReader input = new BufferedReader(new FileReader(argv[0]));
DataOutputStream output = new DataOutputStream(new FileOutputStream(argv[2]));
svm_model model = svm.svm_load_model(argv[1]);
return predict(input, output, model);
}
private static double atof(String s)
{
return Double.valueOf(s).doubleValue();
}
private static int atoi(String s)
{
return Integer.parseInt(s);
}
}
|
package ie.ucd.clops.codegeneration;
import ie.ucd.clops.codegeneration.GeneratedCodeUnit.Visibility;
import ie.ucd.clops.dsl.OptionType;
import ie.ucd.clops.dsl.structs.AssignmentDescription;
import ie.ucd.clops.dsl.structs.DSLInformation;
import ie.ucd.clops.dsl.structs.FlyRuleDescription;
import ie.ucd.clops.dsl.structs.OptionDescription;
import ie.ucd.clops.dsl.structs.OptionGroupDescription;
import ie.ucd.clops.logging.CLOLogger;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.util.Collection;
import java.util.Map.Entry;
import java.util.logging.Level;
/**
* A class used to generate java code from a DSL.
* @author Fintan
* @author Mikolas Janota
*/
public class CodeGenerator {
/** Put quotes around the given String */
public static String quoteSimpleString(String s) {
return "\"" + s + "\"";
}
/** Produces java String constant containing a given String that may contain newlines.*/
public static String quoteMultilineString(String s) {
String[] lines = s.split("\n");
String retv = null;
for (String line : lines) {
line = line.trim();
if (line.isEmpty()) continue;
if (retv == null) retv = "";
else retv += "+ \n ";
retv += quoteSimpleString(line);
}
if (retv == null || retv.isEmpty()) retv = quoteSimpleString("");
return retv;
}
public static void createCode(DSLInformation dslInfo, File outputDir, boolean genTest) {
String parserName = dslInfo.getParserName();
String formatString = dslInfo.getFormatString();
Collection<OptionDescription> opDescriptions = dslInfo.getOptionDescriptions();
Collection<OptionGroupDescription> opGroupDescriptions = dslInfo.getOptionGroupDescriptions();
Collection<FlyRuleDescription> overrideRuleDescriptions = dslInfo.getFlyRuleDescriptions();
//Specific parser
GeneratedClassOrInterface specificParser = createSpecificParser(parserName, formatString, opDescriptions, opGroupDescriptions, overrideRuleDescriptions, dslInfo.getPackageName());
//OptionsInterface
GeneratedClassOrInterface optionsInterface = createOptionsInterface(parserName, opDescriptions, dslInfo.getPackageName());
//SpecifiOptionsStore
GeneratedClassOrInterface specificOptionStore = createSpecificOptionStore(parserName, opDescriptions, opGroupDescriptions, dslInfo.getPackageName());
try {
if (!genTest) {
writeGeneratedClasses(outputDir, specificParser, optionsInterface, specificOptionStore);
} else {
GeneratedClassOrInterface tester = createTester(parserName, dslInfo.getPackageName());
writeGeneratedClasses(outputDir, specificParser, optionsInterface, specificOptionStore, tester);
}
} catch (FileNotFoundException fnfe) {
CLOLogger.getLogger().log(Level.SEVERE, "Error creating file. " + fnfe);
}
}
private static void writeGeneratedClasses(File outputDir, GeneratedClassOrInterface... classes) throws FileNotFoundException {
for (GeneratedClassOrInterface genClass : classes) {
writeGeneratedClass(outputDir, genClass);
}
}
private static void writeGeneratedClass(File outputDir, GeneratedClassOrInterface... genClasses) throws FileNotFoundException {
for (GeneratedClassOrInterface genClass : genClasses) {
PrintWriter pw = new PrintWriter(new FileOutputStream(outputDir.getAbsolutePath() + File.separator + genClass.getName() + ".java"));
new GeneratedCodePrinter(pw).printClass(genClass);
pw.flush();
pw.close();
}
}
private static GeneratedMethod createOptionInitialisationMethod(
String parserName,
String packageName,
GeneratedClassOrInterface specificParser,
Collection<OptionDescription> opDescriptions,
Collection<OptionGroupDescription> opGroupDescriptions) {
GeneratedMethod createOps = new GeneratedMethod("createOptionStore", getQualifiedClassName(parserName + "OptionStore", packageName), Visibility.Private);
createOps.addException("ie.ucd.clops.runtime.options.InvalidOptionPropertyValueException");
createOps.addStatement("return new " + parserName + "OptionStore()");
return createOps;
}
private static void createFlyRuleInitialisationCode(GeneratedClassOrInterface specificParser, Collection<FlyRuleDescription> overrideRuleDescriptions) {
GeneratedMethod createOverrideRules = new GeneratedMethod("createFlyRuleStore", "ie.ucd.clops.runtime.flyrules.FlyRuleStore", Visibility.Private);
specificParser.addMethod(createOverrideRules);
createOverrideRules.addStatement("ie.ucd.clops.runtime.flyrules.FlyRuleStore flyStore = new ie.ucd.clops.runtime.flyrules.FlyRuleStore()");
for (FlyRuleDescription orDescription : overrideRuleDescriptions) {
String opId = orDescription.getTriggeringOptionIdentifier();
for (AssignmentDescription desc : orDescription.getAssignments()) {
createOverrideRules.addStatement("flyStore.addAssignmentForOption(\"" + opId + "\", new ie.ucd.clops.runtime.options.OptionAssignment(\"" + desc.getOptionIdentifier() + "\", \"" + desc.getValue() + "\"))");
}
}
createOverrideRules.addStatement("return flyStore");
}
private static GeneratedClassOrInterface createOptionsInterface(String parserName, Collection<OptionDescription> opDescriptions, String outputPackage) {
GeneratedClassOrInterface optionsInterface = new GeneratedClassOrInterface(parserName + "OptionsInterface", true, outputPackage, Visibility.Public);
for (OptionDescription od : opDescriptions) {
GeneratedMethod isSetMethod = new GeneratedMethod("is" + od.getIdentifier() + "Set", "boolean", Visibility.Public);
isSetMethod.setAbstract(true);
GeneratedMethod getValueMethod = new GeneratedMethod("get" + od.getIdentifier(), od.getType().getOptionValueTypeClass(), Visibility.Public);
getValueMethod.setAbstract(true);
optionsInterface.addMethod(isSetMethod);
optionsInterface.addMethod(getValueMethod);
}
return optionsInterface;
}
private static GeneratedClassOrInterface createSpecificParser(
String parserName,
String formatString,
Collection<OptionDescription> opDescriptions,
Collection<OptionGroupDescription> opGroupDescriptions,
Collection<FlyRuleDescription> overrideRuleDescriptions,
String outputPackage) {
GeneratedClassOrInterface specificParser = new GeneratedClassOrInterface(parserName + "Parser", false, outputPackage, Visibility.Public);
GeneratedField optionStore = new GeneratedField("optionStore", getQualifiedClassName(parserName + "OptionStore", outputPackage));
optionStore.addModifier("final");
specificParser.addField(optionStore);
specificParser.addMethod(createGetter(optionStore));
GeneratedField flyRuleStore = new GeneratedField("flyRuleStore", "ie.ucd.clops.runtime.flyrules.FlyRuleStore");
optionStore.addModifier("final");
specificParser.addMethod(createGetter(flyRuleStore));
specificParser.addField(flyRuleStore);
specificParser.setSuperClass("ie.ucd.clops.runtime.parser.AbstractSpecificCLParser");
GeneratedMethod constructor = new GeneratedConstructor(parserName + "Parser", Visibility.Public);
constructor.addException("ie.ucd.clops.runtime.options.InvalidOptionPropertyValueException");
constructor.addStatement("optionStore = createOptionStore()");
constructor.addStatement("flyRuleStore = createFlyRuleStore()");
specificParser.addMethod(constructor);
//Create the method that will initialise the OptionStore
specificParser.addMethod(createOptionInitialisationMethod(parserName, outputPackage, specificParser, opDescriptions, opGroupDescriptions));
//Create the method that will initialise the override rules
createFlyRuleInitialisationCode(specificParser, overrideRuleDescriptions);
GeneratedMethod createFormat = new GeneratedMethod("getFormatString", "String", Visibility.Public);
createFormat.addStatement("return \"" + formatString + "\"");
specificParser.addMethod(createFormat);
return specificParser;
}
private static GeneratedClassOrInterface createSpecificOptionStore(
String parserName,
Collection<OptionDescription> opDescriptions,
Collection<OptionGroupDescription> opGroupDescriptions,
String outputPackage) {
final String className = "OptionStore";
GeneratedClassOrInterface specificOptionStore = new GeneratedClassOrInterface(parserName + className, false, outputPackage, Visibility.Public);
specificOptionStore.setSuperClass("ie.ucd.clops.runtime.options.OptionStore");
specificOptionStore.addImplementedInterface(parserName + "OptionsInterface");
final String pack = "ie.ucd.clops.runtime.options";
specificOptionStore.addImport(pack + ".OptionGroup");
for (OptionDescription opDesc : opDescriptions) {
GeneratedField field = new GeneratedField(opDesc.getIdentifier(), opDesc.getType().getOptionTypeClass(), Visibility.Private);
field.addModifier("final");
specificOptionStore.addField(field);
}
GeneratedConstructor constructor = new GeneratedConstructor(parserName + className, Visibility.Public);
constructor.addException("ie.ucd.clops.runtime.options.InvalidOptionPropertyValueException");
//Create and add each Option
for (OptionDescription opDesc : opDescriptions) {
constructor.addStatement(opDesc.getIdentifier() + " = new " + opDesc.getType().getOptionTypeClass() + "(\"" + opDesc.getIdentifier() + "\", \"" + OptionType.unifyRegexps(opDesc.getPrefixRegexps()) + "\")");
for (Entry<String,String> entry : opDesc.getProperties().entrySet()) {
constructor.addStatement(opDesc.getIdentifier() + ".setProperty(\"" + entry.getKey() + "\",\"" + entry.getValue() + "\")");
}
if (opDesc.getDescription() != null) {
String desc = quoteMultilineString(opDesc.getDescription());
constructor.addStatement(opDesc.getIdentifier() + ".setProperty(\"description\", " + desc + ")");
}
constructor.addStatement("addOption(" + opDesc.getIdentifier() + ")");
}
//Create and add each OptionGroup
for (OptionGroupDescription opGroupDesc : opGroupDescriptions) {
constructor.addStatement("OptionGroup " + opGroupDesc.getIdentifier() + " = new OptionGroup(\"" + opGroupDesc.getIdentifier() + "\")");
constructor.addStatement("addOptionGroup(" + opGroupDesc.getIdentifier() + ")");
}
//Loop again, this time adding the children
for (OptionGroupDescription opGroupDesc : opGroupDescriptions) {
for (String child : opGroupDesc.getChildren()) {
constructor.addStatement(opGroupDesc.getIdentifier() + ".addOptionOrGroup(" + child + ")");
}
}
specificOptionStore.addMethod(constructor);
for (OptionDescription od : opDescriptions) {
GeneratedMethod isSetMethod = new GeneratedMethod("is" + od.getIdentifier() + "Set", "boolean", Visibility.Public);
isSetMethod.addStatement("return " + od.getIdentifier() + ".hasValue()");
specificOptionStore.addMethod(isSetMethod);
GeneratedMethod getValueMethod = new GeneratedMethod("get" + od.getIdentifier(), od.getType().getOptionValueTypeClass(), Visibility.Public);
getValueMethod.addStatement("return " + od.getIdentifier() + ".getValue()");
specificOptionStore.addMethod(getValueMethod);
GeneratedMethod getOptionMethod = new GeneratedMethod("get" + od.getIdentifier() + "Option", od.getType().getOptionTypeClass(), Visibility.Public);
getOptionMethod.addStatement("return " + od.getIdentifier());
specificOptionStore.addMethod(getOptionMethod);
}
return specificOptionStore;
}
private static GeneratedClassOrInterface createTester(String parserName, String outputPackage) {
GeneratedClassOrInterface tester = new GeneratedClassOrInterface("Main", false, outputPackage, Visibility.Public);
tester.addImport("java.util.logging.Level");
tester.addImport("ie.ucd.clops.logging.CLOLogger");
tester.addImport("ie.ucd.clops.runtime.options.InvalidOptionPropertyValueException");
GeneratedMethod main = new GeneratedMethod("main", "void", Visibility.Public);
main.addModifier("static");
main.addArg(new GeneratedArgument("args", "String[]"));
main.addStatement("CLOLogger.setLogLevel(Level.FINE)");
main.addStatement("try {", false);
main.addStatement(" " + parserName + "Parser parser = new " + parserName + "Parser()");
main.addStatement(" boolean success = parser.parse(args)");
main.addStatement(" if (success) {", false);
main.addStatement(" CLOLogger.getLogger().log(Level.INFO, \"Successful parse.\")");
main.addStatement(" } else {", false);
main.addStatement(" CLOLogger.getLogger().log(Level.INFO, \"Parse did not succeed.\")");
main.addStatement(" }", false);
main.addStatement("} catch (InvalidOptionPropertyValueException e) {", false);
main.addStatement(" CLOLogger.getLogger().log(Level.SEVERE, \"Error setting initial property values for options.\")");
main.addStatement("}", false);
tester.addMethod(main);
return tester;
}
private static GeneratedMethod createGetter(GeneratedField field) {
String methodName = "get" + Character.toUpperCase(field.getName().charAt(0)) + field.getName().substring(1);
return createGetter(field, methodName);
}
private static GeneratedMethod createGetter(GeneratedField field, String methodName) {
GeneratedMethod method = new GeneratedMethod(methodName, field.getType(), Visibility.Public);
method.addStatement("return " + field.getName());
return method;
}
private static String getQualifiedClassName(String name, String packageName) {
if (packageName.equals("")) {
return name;
} else {
return packageName + '.' + name;
}
}
}
|
package gov.nih.nci.cbiit.cdms.formula;
import gov.nih.nci.cbiit.cdms.formula.common.util.FileUtil;
import gov.nih.nci.cbiit.cdms.formula.core.FormulaMeta;
import gov.nih.nci.cbiit.cdms.formula.core.FormulaStore;
import gov.nih.nci.cbiit.cdms.formula.core.OperationType;
import gov.nih.nci.cbiit.cdms.formula.core.TermMeta;
import java.io.*;
import java.net.URL;
import java.util.HashMap;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.namespace.QName;
import javax.xml.transform.stream.StreamSource;
public class FormulaFactory {
private static FormulaStore commonStore;
private static FormulaStore localStore;
private static HashMap<String, TermMeta> expressionTemplate;
public static TermMeta createTemplateTerm(OperationType type)
{
if (expressionTemplate==null
||
expressionTemplate.isEmpty())
{
try {
FormulaStore templateStore=loadFormulaStore("datastore/expressionTemplate.xml");
expressionTemplate=new HashMap<String, TermMeta>();
for (FormulaMeta formula:templateStore.getFormula())
{
String expressionKey=formula.getExpression().getOperation().value();
expressionTemplate.put(expressionKey, formula.getExpression());
}
} catch (JAXBException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
TermMeta expressionTerm=expressionTemplate.get(type.value());
if (expressionTerm!=null)
return (TermMeta)expressionTerm.clone();
return null;
}
public static void updateLocalStore(FormulaStore store)
{
if (store!=null)
localStore=store;
}
public static FormulaStore getLocalStore()
{
return localStore;
}
public static FormulaStore getCommonStore()
{
if (commonStore==null)
try {
commonStore=loadFormulaStore("datastore/commonFormulae.xml");
} catch (JAXBException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return commonStore;
}
public static FormulaStore loadFormulaStore(String uri) throws IOException, JAXBException
{
URL fileUrl=FileUtil.retrieveResourceURL(uri);
System.out.println("FormulaFactory.loadFormulaStore()...formula:\n"+fileUrl);
StreamSource in=new StreamSource(fileUrl.openStream());
return loadFormulaStoreStream(in);
}
private static FormulaStore loadFormulaStoreStream(StreamSource stream) throws JAXBException
{
JAXBContext jc=getJAXBContext();
Unmarshaller u=jc.createUnmarshaller();
JAXBElement<FormulaStore> jaxbFormula=u.unmarshal(stream, FormulaStore.class);
return jaxbFormula.getValue();
}
public static FormulaStore loadFormulaStore(File f) throws JAXBException
{
return loadFormulaStoreStream(new StreamSource(f));
}
/**
* Save a local formula store into a file
* @param store local formula store
* @param targetFile target XML file to save
* @throws IOException
* @throws JAXBException
*/
public static void saveFormulaStore(FormulaStore store, File targetFile) throws IOException, JAXBException
{
FileWriter writer =new FileWriter(targetFile);
JAXBContext jc=getJAXBContext();
Marshaller m = jc.createMarshaller();
m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, new Boolean(true));
m.marshal(new JAXBElement<FormulaStore>(new QName("formulaStore"),FormulaStore.class, store), writer);
writer.close();
}
public static FormulaMeta loadFormula(String str) throws JAXBException
{
JAXBContext jc=getJAXBContext();
Unmarshaller u=jc.createUnmarshaller();
JAXBElement<FormulaMeta> jaxbFormula=u.unmarshal(new StreamSource(new CharArrayReader(str.toCharArray())), FormulaMeta.class);
return jaxbFormula.getValue();
}
public static String convertFormulaToXml(FormulaMeta formula)
{
StringWriter writer=new StringWriter();
try {
writerFormula(formula, writer);
} catch (JAXBException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return writer.getBuffer().toString();
}
private static void writerFormula(FormulaMeta formula, Writer writer) throws JAXBException
{
JAXBContext jc=getJAXBContext();
Marshaller m = jc.createMarshaller();
m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, new Boolean(true));
m.marshal(new JAXBElement<FormulaMeta>(new QName("formula"),FormulaMeta.class, formula), writer);
}
public static void saveFormula(FormulaMeta formula, File f) throws JAXBException, IOException
{
FileWriter writer =new FileWriter(f);
writerFormula(formula, writer);
writer.close();
// JAXBContext jc=getJAXBContext();
// Marshaller m = jc.createMarshaller();
// m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, new Boolean(true));
// m.marshal(new JAXBElement<FormulaMeta>(new QName("formula"),FormulaMeta.class, formula), f);
}
private static JAXBContext getJAXBContext() throws JAXBException
{
JAXBContext jc=null;
// jc = JAXBContext.newInstance( "gov.nih.nci.cbiit.cmts.core" );
// jc=com.sun.xml.internal.bind.v2.runtime.JAXBContextImpl.newInstance("gov.nih.nci.cbiit.cdms.formula.core");
jc=JAXBContext.newInstance("gov.nih.nci.cbiit.cdms.formula.core");
return jc;
}
}
|
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
/**
* Write a description of class MyWorld here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class GameWorld extends World
{
private int timer = 3600;
/**
* Constructor for objects of class MyWorld.
*
*/
public GameWorld()
{
// Create a new world with 600x400 cells with a cell size of 1x1 pixels.
super(1024, 768, 1);
//prepare();
Greenfoot.setWorld(new GameMenu());
// Use for testing purpose
//Greenfoot.setWorld(new Level3());
}
public void act(){
if(timer > 0){
timer
}
else{
Greenfoot.stop();
}
System.out.println("Your Score:" + timer);
}
/**
* Prepare the world for the start of the program.
* That is: create the initial objects and add them to the world.
*/
}
|
package hudson;
import org.jvnet.hudson.test.HudsonTestCase;
import hudson.model.Descriptor;
import hudson.model.Describable;
import hudson.model.Hudson;
import hudson.util.DescriptorList;
/**
* @author Kohsuke Kawaguchi
*/
public class ExtensionListTest extends HudsonTestCase {
// non-Descriptor extension point
public interface Animal extends ExtensionPoint {
}
@Extension
public static class Dog implements Animal {
}
@Extension
public static class Cat implements Animal {
}
public void testAutoDiscovery() throws Exception {
ExtensionList<Animal> list = hudson.getExtensionList(Animal.class);
assertEquals(2,list.size());
assertNotNull(list.get(Dog.class));
assertNotNull(list.get(Cat.class));
}
// Descriptor extension point
public static abstract class FishDescriptor extends Descriptor<Fish> {
public String getDisplayName() {
return clazz.getName();
}
}
public static abstract class Fish implements Describable<Fish> {
public Descriptor<Fish> getDescriptor() {
return Hudson.getInstance().getDescriptor(getClass());
}
}
public static class Tai extends Fish {
@Extension
public static final class DescriptorImpl extends FishDescriptor {}
}
public static class Saba extends Fish {
@Extension
public static final class DescriptorImpl extends FishDescriptor {}
}
public static class Sishamo extends Fish {
public static final class DescriptorImpl extends FishDescriptor {}
}
public void testFishDiscovery() throws Exception {
// imagine that this is a static instance, like it is in many LIST static field in Hudson.
DescriptorList<Fish> LIST = new DescriptorList<Fish>(Fish.class);
DescriptorExtensionList<Fish> list = hudson.getDescriptorList(Fish.class);
assertEquals(2,list.size());
assertNotNull(list.get(Tai.DescriptorImpl.class));
assertNotNull(list.get(Saba.DescriptorImpl.class));
// registration can happen later, and it should be still visible
LIST.add(new Sishamo.DescriptorImpl());
assertEquals(3,list.size());
assertNotNull(list.get(Sishamo.DescriptorImpl.class));
// all 3 should be visisble from LIST, too
assertEquals(3,LIST.size());
assertNotNull(LIST.findByName(Tai.class.getName()));
assertNotNull(LIST.findByName(Sishamo.class.getName()));
assertNotNull(LIST.findByName(Saba.class.getName()));
// DescriptorList can be gone and new one created but it should still have the same list
LIST = new DescriptorList<Fish>(Fish.class);
assertEquals(3,LIST.size());
assertNotNull(LIST.findByName(Tai.class.getName()));
assertNotNull(LIST.findByName(Sishamo.class.getName()));
assertNotNull(LIST.findByName(Saba.class.getName()));
}
public void testLegacyDescriptorList() throws Exception {
// created in a legacy fashion without any tie to ExtensionList
DescriptorList<Fish> LIST = new DescriptorList<Fish>();
// we won't auto-discover anything
assertEquals(0,LIST.size());
// registration can happen later, and it should be still visible
LIST.add(new Sishamo.DescriptorImpl());
assertEquals(1,LIST.size());
assertNotNull(LIST.findByName(Sishamo.class.getName()));
// create a new list and it forgets everything.
LIST = new DescriptorList<Fish>();
assertEquals(0,LIST.size());
}
}
|
package todomore.android;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.util.ArrayList;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import todomore.android.sync.TodoSyncAdapter;
public class SynchAdapterLogicTest {
// Inputs
List<AndroidTask> local;
List<AndroidTask> remote;
// Outputs
List<AndroidTask> toSaveRemotely;
List<AndroidTask> toSaveLocally;
// Test objects
AndroidTask localTaskWithLocalId;
AndroidTask localTaskWithBothIds;
AndroidTask aRemoteTask;
long lastSyncTime;
// Configure the List<Task>s
@Before
public void configureLists() {
local = new ArrayList<AndroidTask>();
remote = new ArrayList<AndroidTask>();
// Outputs
toSaveRemotely = new ArrayList<AndroidTask>();
toSaveLocally = new ArrayList<AndroidTask>();
lastSyncTime = System.currentTimeMillis();
// Let the clock tick so mtimes are after fake synch time used in tests
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// Can't happen
}
// Test objects
localTaskWithBothIds = new AndroidTask("localTaskWithBothIds", null, "Writing");
localTaskWithBothIds.setId(1234); // remote id
localTaskWithBothIds.set_Id(1); // Local Id
localTaskWithLocalId = new AndroidTask("localTaskWithLocalId", "Reno", "Home");
localTaskWithLocalId.set_Id(2); // Local Id
aRemoteTask = new AndroidTask("remoteTask", "Upgrades", "Work");
aRemoteTask.setId(54321);
}
@Test
public void testSendLocalWithLowModTime() {
local.add(localTaskWithBothIds);
local.add(localTaskWithLocalId);
// Call onSynchronize core
TodoSyncAdapter.algorithm(local, remote, lastSyncTime, toSaveLocally, toSaveRemotely);
// Assert calls based on lists
assertTrue(toSaveRemotely.contains(localTaskWithLocalId));
// Initially we will upload this task as its mtime is zero
assertTrue(toSaveRemotely.contains(localTaskWithBothIds));
// So there should be 2
assertEquals("Upload both", 2, toSaveRemotely.size());
}
@Test
public void testSendLocalWithHighModTime() {
// Set this one's mod time past lastsynchtime so it should be sent
localTaskWithBothIds.setModified(System.currentTimeMillis() + 1000);
local.add(localTaskWithBothIds);
local.add(localTaskWithLocalId);
// Call onSynchronize core
TodoSyncAdapter.algorithm(local, remote, lastSyncTime, toSaveLocally, toSaveRemotely);
// Assert calls based on lists
assertTrue(toSaveRemotely.contains(localTaskWithLocalId));
// Should upload this task as its mtime is high
assertTrue(toSaveRemotely.contains(localTaskWithBothIds));
assertEquals("Size", 2, toSaveRemotely.size());
}
@Test
public void testSaveNewRemoteItem() {
remote.add(aRemoteTask);
aRemoteTask.setModified(lastSyncTime - 1000);
TodoSyncAdapter.algorithm(local, remote, lastSyncTime, toSaveLocally, toSaveRemotely);
assertTrue(toSaveLocally.contains(aRemoteTask));
assertTrue(!toSaveRemotely.contains(aRemoteTask));
}
@Test
public void testSaveModifiedRemoteItem() {
aRemoteTask.set_Id(222); // So it won't be saved for not having a local ID
aRemoteTask.setModified(System.currentTimeMillis() + 1000); // Should be saved for mtime
remote.add(aRemoteTask);
TodoSyncAdapter.algorithm(local, remote, lastSyncTime, toSaveLocally, toSaveRemotely);
assertTrue(toSaveLocally.contains(aRemoteTask));
}
}
|
package org.voltdb.iv2;
import static junit.framework.Assert.assertEquals;
import static junit.framework.Assert.assertFalse;
import static junit.framework.Assert.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
import org.junit.BeforeClass;
import org.junit.Test;
import org.voltcore.messaging.TransactionInfoBaseMessage;
import org.voltcore.messaging.VoltMessage;
import org.voltdb.ParameterSet;
import org.voltdb.StoredProcedureInvocation;
import org.voltdb.TheHashinator;
import org.voltdb.TheHashinator.HashinatorType;
import org.voltdb.messaging.CompleteTransactionMessage;
import org.voltdb.messaging.FragmentTaskMessage;
import org.voltdb.messaging.InitiateTaskMessage;
import org.voltdb.messaging.Iv2InitiateTaskMessage;
import org.voltdb.messaging.Iv2RepairLogResponseMessage;
public class TestRepairLog
{
VoltMessage truncInitMsg(long truncPt, long handle)
{
Iv2InitiateTaskMessage msg = mock(Iv2InitiateTaskMessage.class);
when(msg.getTruncationHandle()).thenReturn(truncPt);
when(msg.getSpHandle()).thenReturn(handle);
return msg;
}
VoltMessage nonTruncInitMsg()
{
return truncInitMsg(Long.MIN_VALUE, 0);
}
VoltMessage truncFragMsg(long truncPt, long mpTxnId)
{
FragmentTaskMessage msg = mock(FragmentTaskMessage.class);
when(msg.getTxnId()).thenReturn(mpTxnId);
when(msg.getTruncationHandle()).thenReturn(truncPt);
return msg;
}
VoltMessage truncCompleteMsg(long truncPt, long mpTxnId)
{
CompleteTransactionMessage msg = mock(CompleteTransactionMessage.class);
when(msg.getTxnId()).thenReturn(mpTxnId);
when(msg.getTruncationHandle()).thenReturn(truncPt);
return msg;
}
// a message that should never be logged.
private static class FooMessage extends VoltMessage
{
@Override
protected void initFromBuffer(ByteBuffer buf) throws IOException {
}
@Override
public void flattenToBuffer(ByteBuffer buf) throws IOException {
}
}
@BeforeClass
static public void initializeHashinator() {
TheHashinator.setConfiguredHashinatorType(HashinatorType.ELASTIC);
TheHashinator.initialize(TheHashinator.getConfiguredHashinatorClass(), TheHashinator.getConfigureBytes(8));
}
@Test
public void testOffer()
{
// offer some various messages to log and check
// that it keeps the expected ones.
RepairLog rl = new RepairLog();
VoltMessage m1 = nonTruncInitMsg();
VoltMessage m2 = nonTruncInitMsg();
rl.deliver(m1);
rl.deliver(m2);
List<Iv2RepairLogResponseMessage> contents = rl.contents(1l, false);
assertEquals(3, contents.size());
assertEquals(m1, contents.get(1).getPayload());
assertEquals(m2, contents.get(2).getPayload());
}
@Test
public void testOfferWithTruncation()
{
RepairLog rl = new RepairLog();
// add m1
VoltMessage m1 = truncInitMsg(0L, 1L);
rl.deliver(m1);
assertEquals(2, rl.contents(1L, false).size());
// add m2
VoltMessage m2 = truncInitMsg(0L, 2L);
rl.deliver(m2);
assertEquals(3, rl.contents(1L, false).size());
// trim m1. add m3
VoltMessage m3 = truncInitMsg(1L, 3L);
rl.deliver(m3);
assertEquals(3, rl.contents(1L, false).size());
assertEquals(m2, rl.contents(1L, false).get(1).getPayload());
assertEquals(2L, rl.contents(1L, false).get(1).getHandle());
assertEquals(m3, rl.contents(1L, false).get(2).getPayload());
assertEquals(3L, rl.contents(1L, false).get(2).getHandle());
}
@Test
public void testOfferUneededMessage()
{
RepairLog rl = new RepairLog();
VoltMessage m1 = truncInitMsg(0L, 1L);
rl.deliver(m1);
// deliver a non-logged message (this is the test).
rl.deliver(new FooMessage());
VoltMessage m2 = truncInitMsg(0L, 2L);
rl.deliver(m2);
assertEquals(3, rl.contents(1L, false).size());
assertEquals(m1, rl.contents(1L, false).get(1).getPayload());
assertEquals(m2, rl.contents(1L, false).get(2).getPayload());
}
@Test
public void testOfferFragmentTaskMessage()
{
RepairLog rl = new RepairLog();
// trunc(trunc point, txnId).
VoltMessage m1 = truncFragMsg(0L, 1L);
rl.deliver(m1);
assertEquals(2, rl.contents(1L, false).size());
VoltMessage m2 = truncFragMsg(0L, 2L);
rl.deliver(m2);
assertEquals(3, rl.contents(1L, false).size());
// only the first message for a transaction is logged.
VoltMessage m2b = truncFragMsg(0L, 2L);
rl.deliver(m2b);
assertEquals(3, rl.contents(1L, false).size());
// trim m1. add m3
VoltMessage m3 = truncFragMsg(1L, 3L);
rl.deliver(m3);
assertEquals(3, rl.contents(1L, false).size());
assertEquals(m2, rl.contents(1L, false).get(1).getPayload());
assertEquals(2L, rl.contents(1L, false).get(1).getTxnId());
assertEquals(m3, rl.contents(1L, false).get(2).getPayload());
assertEquals(3L, rl.contents(1L, false).get(2).getTxnId());
}
@Test
public void testOfferCompleteMessage()
{
RepairLog rl = new RepairLog();
// trunc(trunc point, txnId).
VoltMessage m1 = truncCompleteMsg(0L, 1L);
rl.deliver(m1);
assertEquals(2, rl.contents(1L, false).size());
VoltMessage m2 = truncCompleteMsg(0L, 2L);
rl.deliver(m2);
assertEquals(3, rl.contents(1L, false).size());
// trim m1. add m3
VoltMessage m3 = truncCompleteMsg(1L, 3L);
rl.deliver(m3);
assertEquals(3, rl.contents(1L, false).size());
assertEquals(m2, rl.contents(1L, false).get(1).getPayload());
assertEquals(2L, rl.contents(1L, false).get(1).getTxnId());
assertEquals(m3, rl.contents(1L, false).get(2).getPayload());
assertEquals(3L, rl.contents(1L, false).get(2).getTxnId());
}
@Test
public void testTruncationAfterPromotion()
{
RepairLog rl = new RepairLog();
VoltMessage m1 = truncInitMsg(0L, 1L);
rl.deliver(m1);
VoltMessage m2 = truncInitMsg(0L, 2L);
rl.deliver(m2);
assertEquals(3, rl.contents(1L, false).size());
rl.setLeaderState(true);
assertEquals(1, rl.contents(1L, false).size());
}
// validate the invariants on the RepairLog contents:
// Every entry in the log should have a unique, constantly increasing SP handle.
// There should be only one FragmentTaskMessage per MP TxnID
// There should be at most one FragmentTaskMessage uncovered by a CompleteTransactionMessage
// There should be no CompleteTransactionMessages indicating restart
private void validateRepairLog(List<Iv2RepairLogResponseMessage> stuff, long binaryLogUniqueId)
{
long prevHandle = Long.MIN_VALUE;
Long mpTxnId = null;
for (Iv2RepairLogResponseMessage imsg : stuff) {
if (imsg.getSequence() > 0) {
assertTrue(imsg.getHandle() > prevHandle);
prevHandle = imsg.getHandle();
if (imsg.getPayload() instanceof FragmentTaskMessage) {
assertEquals(null, mpTxnId);
mpTxnId = imsg.getTxnId();
} else if (imsg.getPayload() instanceof CompleteTransactionMessage) {
// can see bare CompleteTransactionMessage, but if we've got an MP
// in progress this should close it
assertFalse(((CompleteTransactionMessage)imsg.getPayload()).isRestart());
if (mpTxnId != null) {
assertEquals((long)mpTxnId, imsg.getTxnId());
}
mpTxnId = null;
}
} else {
assertTrue(imsg.hasHashinatorConfig());
assertEquals(binaryLogUniqueId, imsg.getBinaryLogUniqueId());
}
}
}
public static long setBinaryLogUniqueId(TransactionInfoBaseMessage msg, UniqueIdGenerator uig) {
Iv2InitiateTaskMessage taskMsg = null;
if (msg instanceof Iv2InitiateTaskMessage) {
taskMsg = (Iv2InitiateTaskMessage) msg;
} else if (msg instanceof FragmentTaskMessage) {
taskMsg = ((FragmentTaskMessage) msg).getInitiateTask();
}
if (taskMsg != null && taskMsg.getStoredProcedureName().startsWith("@ApplyBinaryLog")) {
ParameterSet params = taskMsg.getStoredProcedureInvocation().getParams();
long uid = uig.getNextUniqueId();
when(params.toArray()).thenReturn(new Object[] {null, 0l, 0l, uid, null});
return uid;
}
return Long.MIN_VALUE;
}
@Test
public void testFuzz()
{
TxnEgo sphandle = TxnEgo.makeZero(0);
UniqueIdGenerator uig = new UniqueIdGenerator(0, 0);
UniqueIdGenerator spbuig = new UniqueIdGenerator(0, 0);
UniqueIdGenerator mpbuig = new UniqueIdGenerator(0, 0);
sphandle = sphandle.makeNext();
RandomMsgGenerator msgGen = new RandomMsgGenerator();
RepairLog dut = new RepairLog();
long binaryLogSpUniqueId = Long.MIN_VALUE;
long binaryLogMpUniqueId = Long.MIN_VALUE;
for (int i = 0; i < 4000; i++) {
// get next message, update the sphandle according to SpScheduler rules,
// but only submit messages that would have been forwarded by the master
// to the repair log.
TransactionInfoBaseMessage msg = msgGen.generateRandomMessageInStream();
msg.setSpHandle(sphandle.getTxnId());
if (msg instanceof InitiateTaskMessage) {
binaryLogSpUniqueId = Math.max(binaryLogSpUniqueId, setBinaryLogUniqueId(msg, spbuig));
} else if (msg instanceof FragmentTaskMessage) {
binaryLogMpUniqueId = Math.max(binaryLogMpUniqueId, setBinaryLogUniqueId(msg, mpbuig));
}
sphandle = sphandle.makeNext();
if (!msg.isReadOnly() || msg instanceof CompleteTransactionMessage) {
dut.deliver(msg);
}
}
List<Iv2RepairLogResponseMessage> stuff = dut.contents(1l, false);
validateRepairLog(stuff, binaryLogSpUniqueId);
// Also check the MP version
stuff = dut.contents(1l, true);
validateRepairLog(stuff, binaryLogMpUniqueId);
}
@Test
public void testComparator()
{
RepairLog dut = new RepairLog();
Random rand = new Random();
List<RepairLog.Item> items = new ArrayList<RepairLog.Item>();
for (int i = 0; i < 1000000; i++) {
RepairLog.Item item = new RepairLog.Item(true, null, rand.nextInt(), i);
items.add(item);
}
Collections.sort(items, dut.m_handleComparator);
}
@Test
public void testTrackBinaryLogUniqueId() {
// The end unique id for an @ApplyBinaryLogSP invocation is recorded
// as its fifth parameter. Create a realistic invocation, deliver it
// to the repair log, and see what we get
final long endUniqueId = 42;
StoredProcedureInvocation spi = new StoredProcedureInvocation();
spi.setProcName("@ApplyBinaryLogSP");
spi.setParams(0, endUniqueId - 10, endUniqueId, endUniqueId, new byte[]{0});
spi.setOriginalUniqueId(endUniqueId - 10);
spi.setOriginalTxnId(endUniqueId -15);
Iv2InitiateTaskMessage msg =
new Iv2InitiateTaskMessage(0l, 0l, 0l, Long.MIN_VALUE, 0l, false, true,
spi, 0l, 0l, false);
msg.setSpHandle(900l);
RepairLog log = new RepairLog();
log.deliver(msg);
validateRepairLog(log.contents(1l, false), endUniqueId);
}
}
|
package genqa;
import java.net.Socket;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;
import genqa.VerifierUtils.Config;
public class JDBCGetData {
static Connection conn;
static String selectSql = "SELECT * FROM \"EXPORT_PARTITIONED_TABLE\" where \"ROWID\" = ?;";
static PreparedStatement selectStmt = null;
/**
* Connect and prepare the select to make the per row handling
* as efficient as possible, though it's still pretty pokey
* @param config
* @return
*/
public static Connection jdbcConnect(Config config) {
/* some jdbc drivers may not support connection timout semantics,
so pre-test the connection.
*/
String[] a = config.host_port.split(":");
try {
Socket s = new Socket(a[0], Integer.valueOf(a[1]));
s.close();
} catch (Exception e) {
System.err.println("Service is not up at '" + config.host_port + "' " + e);
e.printStackTrace();
System.exit(-1);
}
try {
Class.forName(config.driver);
} catch (ClassNotFoundException e) {
System.err.println("Could not find the JDBC driver class.\n");
e.printStackTrace();
System.exit(-1);
}
String connectString = "jdbc:" + config.jdbcDBMS + "://" + config.host_port + "/" + config.jdbcDatabase;
Properties myProp = new Properties();
myProp.put("user", config.jdbcUser);
myProp.put("password", config.jdbcPassword);
try {
conn = DriverManager.getConnection(connectString, myProp);
System.out.println("Connected!");
selectStmt = conn.prepareStatement(selectSql);
} catch (SQLException e) {
System.err.println("Could not connect to the database with connect string " + connectString + ", exception: " + e);
e.printStackTrace();
System.exit(-1);
}
return conn;
}
static ResultSet jdbcRead(long rowid) {
ResultSet rs = null;
try {
selectStmt.setLong(1, rowid);
rs = selectStmt.executeQuery();
} catch (SQLException e) {
System.err.println("Exception in DB row access.\n");
e.printStackTrace();
System.exit(-1);
}
return rs;
}
}
|
package org.jactiveresource.test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import java.util.Date;
import org.jactiveresource.ResourceConnection;
import org.jactiveresource.ResourceFactory;
import org.junit.Before;
import org.junit.Test;
/**
*
* @version $LastChangedRevision$ <br>
* $LastChangedDate$
* @author $LastChangedBy$
*/
public class TestPerson {
private ResourceConnection c;
// private PersonFactory pf;
private ResourceFactory pf;
private Person p;
@Before
public void setUp() throws Exception {
c = new ResourceConnection("http://localhost:3000");
c.setUsername("Ace");
c.setPassword("newenglandclamchowder");
pf = new ResourceFactory(c, Person.class);
}
@Test
public void testBasicOperations() throws Exception {
p = pf.instantiate();
assertNull(p.getId());
p.setName("King Tut");
Date old = new Date(new Long("-99999999999999"));
p.setBirthdate(old);
p.save();
String id = p.getId();
assertEquals(p.getName(), "King Tut");
assertNotNull("No id present", p.getId());
p = pf.find(id);
assertEquals(p.getName(), "King Tut");
p.setName("Alexander the Great");
p.save();
p = pf.find(id);
assertEquals(p.getName(), "Alexander the Great");
assertTrue(pf.exists(id));
p.delete();
assertFalse(pf.exists(id));
}
}
|
import java.util.logging.Level;
import java.util.logging.Logger;
//Class: vMinecraftListener
//Use: The listener to catch incoming chat and commands
public class vMinecraftListener extends PluginListener {
public int damagetype;
protected static final Logger log = Logger.getLogger("Minecraft");
//Function: disable
//Input: None
//Output: None
//Use: Disables vMinecraft, but why would you want to do that? ;)
public void disable() {
log.log(Level.INFO, "vMinecraft disabled");
}
//Function: onChat
//Input: Player player: The player calling the command
// String message: The message to color
//Output: boolean: If the user has access to the command
// and it is enabled
//Use: Checks for quote, rage, and colors
public boolean onChat(Player player, String message){
//Quote (Greentext)
if (message.startsWith("@") ||
vMinecraftSettings.getInstance().isAdminToggled(player.getName()))
return vMinecraftChat.adminChat(player, message);
else if (message.startsWith(">"))
return vMinecraftChat.quote(player, message);
//Rage (FFF)
else if (message.startsWith("FFF"))
return vMinecraftChat.rage(player, message);
//Send through quakeColors otherwise
else
return vMinecraftChat.quakeColors(player, message);
}
//Function: onCommand
//Input: Player player: The player calling the command
// String[] split: The arguments
//Output: boolean: If the user has access to the command
// and it is enabled
//Use: Checks for exploits and runs the commands
public boolean onCommand(Player player, String[] split) {
//Copy the arguments into their own array.
String[] args = new String[split.length - 1];
System.arraycopy(split, 1, args, 0, args.length);
//Return the results of the command
int exitCode = vMinecraftCommands.cl.call(split[0], player, args);
if(exitCode == 0)
return false;
else if(exitCode == 1)
return true;
else
return false;
}
//Function: onHealthChange
//Input: Player player: The player calling the command
// int oldValue: The old health value;
// int newValue: The new health value
//Output: boolean: If the user has access to the command
// and it is enabled
//Use: Checks for exploits and runs the commands
public boolean onHealthChange(Player player,int oldValue,int newValue){
if (vMinecraftSettings.getInstance().isEzModo(player.getName())) {
return oldValue > newValue;
}
return false;
}
public void onLogin(Player player){
vMinecraftUsers.addUser(player);
}
public boolean onIgnite(Block block, Player player) {
if(vMinecraftSettings.stopFire){
if (vMinecraftSettings.fireNoSpread.contains(block)){
return true;
}
}
return false;
}
public boolean onDamage(PluginLoader.DamageType type, BaseEntity attacker, BaseEntity defender, int amount) {
if(defender.isPlayer()){
Player player = (Player)defender;
if (attacker.isPlayer()) {
Player pAttacker = (Player)attacker;
if(player.getHealth() < 1){
vMinecraftChat.gmsg(player, pAttacker.getName() + " has murdered " + player.getName());
}
}
if (player.getHealth() < 1 && !attacker.isPlayer()) {
if (type == type.CREEPER_EXPLOSION) {
damagetype = 1; //Creeper
} else if(type == type.FALL){
damagetype = 2; //Fall
} else if(type == type.FIRE){
damagetype = 3; //Fire going to make it share with firetick since its similar
} else if (type == type.FIRE_TICK){
damagetype = 4; //Firetick
} else if (type == type.LAVA){
damagetype = 5; //Lava
} else if (type == type.WATER){
damagetype = 6; //Water
}
//This should trigger the player death message
} else if (player.getHealth() < 1 && attacker.isPlayer()){
damagetype = 7; //Player
}
if(damagetype == 1){
vMinecraftChat.gmsg(player,player.getName() + Colors.Red + " was blown to bits by a creeper");
damagetype = 0;
} else if (damagetype == 2) {
vMinecraftChat.gmsg(player,player.getName() + Colors.Red + " fell to death!");
damagetype = 0;
} else if (damagetype ==3){
vMinecraftChat.gmsg(player, player.getName() + Colors.Red + " was incinerated");
damagetype = 0;
} else if (damagetype == 4){
vMinecraftChat.gmsg(player, Colors.Red + " Stop drop and roll, not scream, run, and burn " + player.getName());
damagetype = 0;
} else if (damagetype == 5){
vMinecraftChat.gmsg(player, Colors.Red + player.getName() + " drowned in lava");
damagetype = 0;
} else if (damagetype == 6){
vMinecraftChat.gmsg(player, Colors.Blue + player.getName() + " should've attended that swimming class");
damagetype = 0;
} else if (damagetype == 7){
Player pAttacker = (Player)attacker;
vMinecraftChat.gmsg(player, pAttacker.getName() + " has murdered " + player.getName());
damagetype = 0;
}
else {
vMinecraftChat.gmsg(player, Colors.Gray + player.getName() + " " + vMinecraftSettings.randomDeathMsg());
}
}
return false;
}
}
|
package com.rho.net;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Calendar;
import com.rho.net.IHttpConnection;
import com.xruby.runtime.builtin.RubyArray;
import com.xruby.runtime.builtin.RubyHash;
import com.xruby.runtime.lang.RubyConstant;
import com.xruby.runtime.lang.RubyValue;
import com.xruby.runtime.lang.RhoSupport;
import com.rho.net.URI;
import com.rho.sync.SyncThread;
import com.rho.*;
import com.rho.file.SimpleFile;
public class RhoConnection implements IHttpConnection {
private static final RhoLogger LOG = RhoLogger.RHO_STRIP_LOG ? new RhoEmptyLogger() :
new RhoLogger("RhoConnection");
RhoConf RHOCONF(){ return RhoConf.getInstance(); }
/** Request URI **/
URI uri, uri_orig;
String url_external;
/** Method - GET, POST, HEAD **/
String method;
/** Numeric code returned from HTTP response header. */
protected int responseCode = 200;
/** Message string from HTTP response header. */
protected String responseMsg = "OK";
/** Content-Length from response header, or -1 if missing. */
private int contentLength = -1;
/** Collection of request headers as name/value pairs. */
protected Properties reqHeaders = new Properties();
/** Collection of response headers as name/value pairs. */
protected Properties resHeaders = new Properties();
/** Request state **/
protected boolean requestProcessed = false;
protected boolean m_isDispatchCall = false;
/** Input/Output streams **/
private /*ByteArray*/InputStream responseData = null;
private ByteArrayOutputStream postData = new ByteArrayOutputStream();
private SimpleFile m_file = null;
/** Construct connection using URI **/
public RhoConnection(URI _uri)
{
url_external = _uri.toString();
uri_orig = _uri;
uri = new URI(url_external);
if ( !uri.getPath().startsWith("/apps") )
uri.setPath("/apps" + uri.getPath());
else
uri.setPath(uri.getPath());
}
public void resetUrl(String url)
{
url_external = url;
uri = new URI(url_external);
if ( !uri.getPath().startsWith("/apps") )
uri.setPath("/apps" + uri.getPath());
else
uri.setPath(uri.getPath());
method = "";
responseCode = 200;
responseMsg = "OK";
contentLength = -1;
reqHeaders.clear();
resHeaders.clear();
requestProcessed = false;
try{
clean();
}catch(IOException exc)
{
LOG.ERROR("clean failed.", exc);
}
}
private void clean() throws IOException
{
if ( m_file != null ){
m_file.close();
m_file = null;
}else if (responseData != null)
responseData.close();
responseData = null;
if ( postData != null )
postData.close();
}
public void close() throws IOException
{
clean();
LOG.TRACE("Close browser connection.");
}
public boolean isDispatchCall(){ return m_isDispatchCall; }
public Object getNativeConnection() {
throw new RuntimeException("getNativeConnection - Not implemented");
}
public long getDate() throws IOException {
LOG.TRACE("getDate");
return getHeaderFieldDate("date", 0);
}
public long getExpiration() throws IOException {
LOG.TRACE("getExpiration");
return getHeaderFieldDate("expires", 0);
}
public String getFile() {
LOG.TRACE("getFile");
if (uri!=null) {
String path = uri.getPath();
if (path!=null) {
int s0 = path.lastIndexOf('/');
int s1 = path.lastIndexOf('\\');
if (s1>s0) s0=s1;
if (s0<0) s0 = 0;
return path.substring(s0);
}
}
return null;
}
public String getHeaderField(String name) throws IOException {
LOG.TRACE("getHeaderField: " + name);
processRequest();
return resHeaders.getPropertyIgnoreCase(name);
}
public String getHeaderField(int index) throws IOException {
LOG.TRACE("getHeaderField: " + index);
processRequest();
if (index >= resHeaders.size()) {
return null;
}
return resHeaders.getValueAt(index);
}
public long getHeaderFieldDate(String name, long def) throws IOException {
LOG.TRACE("getHeaderFieldDate: " + name);
processRequest();
try {
return DateTimeTokenizer.parse(getHeaderField(name));
} catch (NumberFormatException nfe) {
// fall through
} catch (IllegalArgumentException iae) {
// fall through
} catch (NullPointerException npe) {
// fall through
}
return def;
}
public int getHeaderFieldInt(String name, int def) throws IOException {
LOG.TRACE("getHeaderFieldInt: " + name);
processRequest();
try {
return Integer.parseInt(getHeaderField(name));
} catch (IllegalArgumentException iae) {
// fall through
} catch (NullPointerException npe) {
// fall through
}
return def;
}
public String getHeaderFieldKey(int index) throws IOException {
LOG.TRACE("getHeaderFieldKey: " + index);
processRequest();
if (index >= resHeaders.size())
return null;
return ((String)(resHeaders.getKeyAt(index)));
}
public String getHost() {
LOG.TRACE("getHost: " + uri.getHost());
return uri.getHost();
}
public long getLastModified() throws IOException {
LOG.TRACE("getLastModified");
return getHeaderFieldDate("last-modified", 0);
}
public int getPort() {
LOG.TRACE("getPort: " + uri.getPort());
return uri.getPort();
}
public String getProtocol() {
LOG.TRACE("getProtocol: " + uri.getScheme());
return uri.getScheme();
}
public String getQuery() {
LOG.TRACE("getQuery: " + uri.getQueryString());
return uri.getQueryString();
}
public String getRef() {
LOG.TRACE("getRef: " + uri.getFragment());
return uri.getFragment() != null ? uri.getFragment() : "";
}
public String getRequestMethod() {
LOG.TRACE("getRequestMethod: " + method);
return method;
}
public String getRequestProperty(String key) {
LOG.TRACE("getRequestProperty: " + key);
return reqHeaders.getPropertyIgnoreCase(key);
}
public int getResponseCode() throws IOException {
processRequest();
LOG.TRACE("getResponseCode" + responseCode);
return responseCode;
}
public String getResponseMessage() throws IOException {
LOG.TRACE("getResponseMessage: " + responseMsg);
processRequest();
return responseMsg;
}
public String getURL() {
LOG.TRACE("getURL: " + url_external);
return url_external;
}
public void setRequestMethod(String method) throws IOException {
LOG.TRACE("setRequestMethod: " + method);
/*
* The request method can not be changed once the output stream has been
* opened.
*/
// if (streamConnection != null) {
// throw new IOException("connection already open");
if (!method.equals(HEAD) &&
!method.equals(GET) &&
!method.equals(POST)) {
throw new IOException("unsupported method: " + method);
}
this.method = method;
}
public void setRequestProperty(String key, String value) throws IOException {
//LOG.TRACE("setRequestProperty: key = " + key + "; value = " + value);
int index = 0;
/*
* The request headers can not be changed once the output stream has
* been opened.
*/
// if (streamConnection != null) {
// throw new IOException("connection already open");
// Look to see if a programmer embedded any extra fields.
for (;;) {
index = value.indexOf("\r\n", index);
if (index == -1) {
break;
}
index += 2;
if (index >= value.length() || (value.charAt(index) != ' ' &&
value.charAt(index) != '\t')) {
throw new IllegalArgumentException("illegal value found");
}
}
setRequestField(key, value);
}
/**
* Add the named field to the list of request fields. This method is where a
* subclass should override properties.
*
* @param key
* key for the request header field.
* @param value
* the value for the request header field.
*/
protected void setRequestField(String key, String value) {
LOG.TRACE("setRequestField: key = " + key + "; value = " + value);
/*
* If application setRequestProperties("Connection", "close") then we
* need to know this & take appropriate default close action
*/
// if ((key.equalsIgnoreCase("connection")) &&
// (value.equalsIgnoreCase("close"))) {
// ConnectionCloseFlag = true;
/*
* Ref . Section 3.6 of RFC2616 : All transfer-coding values are
* case-insensitive.
*/
// if ((key.equalsIgnoreCase("transfer-encoding")) &&
// (value.equalsIgnoreCase("chunked"))) {
// chunkedOut = true;
reqHeaders.setPropertyIgnoreCase(key, value);
}
public String getEncoding() {
LOG.TRACE("getEncloding");
try {
return getHeaderField("content-encoding");
} catch (IOException x) {
return null;
}
}
public long getLength() {
LOG.TRACE("getLength: " + contentLength);
try {
processRequest();
} catch (IOException ioe) {
// Fall through to return -1 for length
}
return contentLength;
}
public String getType() {
LOG.TRACE("getType");
try {
return getHeaderField("content-type");
} catch (IOException x) {
return null;
}
}
public DataInputStream openDataInputStream() throws IOException {
LOG.TRACE("openDataInputStream");
return new DataInputStream(openInputStream());
}
public InputStream openInputStream() throws IOException {
LOG.TRACE("openInputStream");
processRequest();
if ( responseData != null )
return responseData;
throw new IOException("Not found: " + url_external);
}
public DataOutputStream openDataOutputStream() throws IOException {
LOG.TRACE("openDataOutputStream");
return new DataOutputStream(postData);
}
public OutputStream openOutputStream() throws IOException {
LOG.TRACE("openOutputStream");
return postData;
}
static private class UrlParser{
String strPath;
int nStart = 0;
UrlParser( String url ){
strPath = url;
nStart = strPath.charAt(0) == '/' ? 1 : 0;
}
public boolean isEnd(){ return nStart >= strPath.length(); }
public String next(){
if ( isEnd() )
return null;
int nEnd = strPath.indexOf('/',nStart);
if ( nEnd < 0 )
nEnd = strPath.length();
String res = strPath.substring(nStart, nEnd);
nStart = nEnd+1;
return URI.urlDecode(res).trim();
}
}
void respondMoved( String location ){
responseCode = HTTP_MOVED_PERM;
responseMsg = "Moved Permanently";
String strLoc = location;
if ( strLoc.startsWith("/apps"))
strLoc = strLoc.substring(5);
String strQuery = uri.getQueryString();
if ( strQuery != null && strQuery.length() > 0 )
strLoc += "?" + strQuery;
resHeaders.addProperty("Location", strLoc );
contentLength = 0;
responseData = new ByteArrayInputStream("".getBytes());
}
void respondOK(){
responseCode = HTTP_OK;
responseMsg = "Success";
contentLength = 0;
responseData = new ByteArrayInputStream("".getBytes());
}
void respondNotModified(){
responseCode = HTTP_NOTMODIFIED;
responseMsg = "Success";
contentLength = 0;
responseData = new ByteArrayInputStream("".getBytes());
}
void respondNotFound( String strError ){
responseCode = HTTP_NOT_FOUND;
responseMsg = "Not found";
if ( strError != null && strError.length() != 0 )
responseMsg += ".Error: " + strError;
String strBody = "Page not found: " + uri.getPath();
contentLength = strBody.length();
responseData = new ByteArrayInputStream(strBody.getBytes());
resHeaders.addProperty("Content-Type", "text/html" );
resHeaders.addProperty("Content-Length", Integer.toString( contentLength ) );
}
String getContentType(){
String contType = reqHeaders.getProperty("Content-Type");
if ( contType == null || contType.length() == 0 )
contType = reqHeaders.getProperty("content-type");
if ( contType != null && contType.length() > 0 )
return contType;
String path = uri.getPath();
int nPoint = path.lastIndexOf('.');
String strExt = "";
if ( nPoint > 0 )
strExt = path.substring(nPoint+1);
if ( strExt.equals("png") )
return "image/png";
else if ( strExt.equals("jpeg") )
return "image/jpeg";
else if ( strExt.equals("jpg") )
return "image/jpg";
else if ( strExt.equals("js") )
return "application/javascript";
else if ( strExt.equals("css") )
return "text/css";
else if ( strExt.equals("gif") )
return "image/gif";
else if ( strExt.equals("html") || strExt.equals("htm") )
return "text/html";
else if ( strExt.equals("txt") )
return "text/plain";
return "";
}
static final String[] m_arIndexes = {"index_erb.iseq", "index.html", "index.htm"};
public static int findIndex(String strUrl){
String filename;
int nLastSlash = strUrl.lastIndexOf('/');
if ( nLastSlash >= 0 )
filename = strUrl.substring(nLastSlash+1);
else
filename = strUrl;
for( int i = 0; i < m_arIndexes.length; i++ ){
if ( filename.equalsIgnoreCase(m_arIndexes[i]) )
return i;
}
return -1;
}
protected boolean httpGetIndexFile(){
String strIndex = null;
for( int i = 0; i < m_arIndexes.length; i++ ){
String name = FilePath.join( URI.urlDecode(uri.getPath()), m_arIndexes[i] );
String nameClass = name;
if ( nameClass.endsWith(".iseq"))
nameClass = nameClass.substring(0, nameClass.length()-5);
if ( RhoSupport.findClass(nameClass) != null || RhoRuby.resourceFileExists(name) ){
strIndex = name;
break;
}
}
if ( strIndex == null )
return false;
respondMoved(strIndex);
return true;
}
private String getLocalHttpTimeString()
{
final String[] months= { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
final String[] wdays= { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
//Thu, 01 Dec 2010 16:00:00 GMT
Calendar time = Calendar.getInstance();
String strTime = "";
strTime += wdays[time.get(Calendar.DAY_OF_WEEK)-1] + ", " +
time.get(Calendar.DATE) + " " +
months[time.get(Calendar.MONTH)] + " " +
time.get(Calendar.YEAR) + " " +
time.get(Calendar.HOUR_OF_DAY) + ":" +
time.get(Calendar.MINUTE) + ":" +
time.get(Calendar.SECOND) + " " +
"GMT";
return strTime;
}
protected boolean isDbFilesPath(String strPath)
{
return strPath.startsWith("/apps/app/db/db-files") || strPath.startsWith("/apps/db/db-files");
}
protected boolean httpServeFile(String strContType)throws IOException
{
String strPath = URI.urlDecode(uri.getPath());
//if ( !strPath.startsWith("/apps") )
// strPath = "/apps" + strPath;
LOG.TRACE("httpServeFile: " + strPath);
if ( !isDbFilesPath(strPath) )
{
if ( strContType.equals("application/javascript")){
responseData = RhoRuby.loadFile(strPath);
if ( responseData == null ){
String str = "";
responseData = new ByteArrayInputStream(str.getBytes());
}
}
else
responseData = RhoRuby.loadFile(strPath);
}else
{
if ( strPath.startsWith("/apps/app/db/db-files") )
strPath = strPath.substring(9);// remove /apps/app
else
strPath = strPath.substring(5);// remove /apps
}
if (responseData == null){
SimpleFile file = null;
try{
file = RhoClassFactory.createFile();
String strFileName = strPath;
// if ( strFileName.startsWith("/apps") )
// strFileName = strPath.substring(5);
file.open(strFileName, true, true);
responseData = file.getInputStream();
if (responseData != null) {
contentLength = (int) file.length();
}
m_file = file;
}catch(Exception exc){
if ( file != null )
file.close();
}
} else {
if (responseData != null) {
contentLength = responseData.available();
}
}
if (responseData== null)
return false;
if ( strContType.length() > 0 )
resHeaders.addProperty("Content-Type", strContType );
resHeaders.addProperty("Content-Length", Integer.toString( contentLength ) );
//resHeaders.addProperty("Date",getLocalHttpTimeString());
//resHeaders.addProperty("Cache-control", "public, max-age=3600" );
//resHeaders.addProperty("Expires", "Thu, 01 Dec 2010 16:00:00 GMT" );
return true;
}
private boolean isKnownExtension(String strPath)
{
int nDot = strPath.lastIndexOf('.');
if ( nDot >= 0 )
{
String strExt = strPath.substring(nDot+1);
return strExt.equalsIgnoreCase("png") || strExt.equalsIgnoreCase("jpg") ||
strExt.equalsIgnoreCase("css") || strExt.equalsIgnoreCase("js");
}
return false;
}
protected boolean httpGetFile(String strContType)throws IOException
{
String strPath = URI.urlDecode(uri.getPath());
if ( !isDbFilesPath(strPath) && !isKnownExtension(strPath) && strContType.length() == 0 )
{
String strTemp = FilePath.join(strPath, "/");
if( RhoSupport.findClass(strTemp + "controller") != null )
return false;
int nPos = findIndex(strPath);
if ( nPos >= 0 )
{
String url = strPath;// + (nPos == 0 ? ".iseq" : "");
Properties reqHash = new Properties();
doDispatch(reqHash, url);
// RubyValue res = RhoRuby.processIndexRequest(url);//erb-compiled should load from class
//processResponse(res);
//RhodesApp.getInstance().keepLastVisitedUrl(url_external);
return true;
}
if( httpGetIndexFile() )
return true;
}
return httpServeFile(strContType);
}
protected boolean checkRhoExtensions(String application, String model ){
if ( application.equalsIgnoreCase("AppManager") ){
//TODO: AppManager
respondOK();
return true;
}else if ( application.equalsIgnoreCase("system") ){
if ( model.equalsIgnoreCase("geolocation") ){
showGeoLocation();
return true;
}else if ( model.equalsIgnoreCase("loadserversources") ){
RhoAppAdapter.loadServerSources(postData.toString());
return true;
}else if ( model.equalsIgnoreCase("loadallsyncsources") ){
RhoAppAdapter.loadAllSyncSources();
return true;
}else if ( model.equalsIgnoreCase("resetDBOnSyncUserChanged") ){
RhoAppAdapter.resetDBOnSyncUserChanged();
return true;
}else if ( model.equalsIgnoreCase("logger") ){
processLogger();
return true;
}
}else if ( application.equalsIgnoreCase("shared") )
return false;
return false;
}
void processLogger()
{
int nLevel = 0;
String strMsg = "", strCategory = "";
Tokenizer oTokenizer = new Tokenizer(uri.getQueryString(), "&");
while (oTokenizer.hasMoreTokens())
{
String tok = oTokenizer.nextToken();
if (tok.length() == 0)
continue;
if ( tok.startsWith("level=") )
{
String strLevel = tok.substring(6);
nLevel = Integer.parseInt(strLevel);
}else if ( tok.startsWith("msg=") )
{
strMsg = URI.urlDecode(tok.substring(4));
}else if ( tok.startsWith( "cat=") )
{
strCategory = URI.urlDecode(tok.substring(4));
}
}
RhoLogger log = new RhoLogger(strCategory);
log.logMessage(nLevel, strMsg );
respondOK();
}
void showGeoLocation(){
String location = "";
try {
IRhoRubyHelper helper = RhoClassFactory.createRhoRubyHelper();
location = helper.getGeoLocationText();
}catch(Exception exc)
{
LOG.ERROR("getGeoLocationText failed", exc);
}
respondOK();
contentLength = location.length();
responseData = new ByteArrayInputStream(location.getBytes());
resHeaders.addProperty("Content-Type", "text/html" );
resHeaders.addProperty("Content-Length", Integer.toString( contentLength ) );
}
protected boolean dispatch()throws IOException
{
//LOG.INFO("dispatch start : " + uri.getPath());
UrlParser up = new UrlParser(uri.getPath());
String apps = up.next();
String application;
if ( apps.equalsIgnoreCase("apps") )
application = up.next();
else
application = apps;
String model = up.next();
if ( model == null || model.length() == 0 )
return false;
if ( checkRhoExtensions(application, model ) )
return true;
// Convert CamelCase to underscore_case
StringBuffer cName = new StringBuffer();
byte[] modelname = model.getBytes();
char ch;
for (int i = 0; i != model.length(); ++i) {
if (modelname[i] >= (byte)'A' && modelname[i] <= (byte)'Z') {
ch = (char)(modelname[i] + 0x20);
if (i != 0)
cName.append('_');
}
else ch = (char)modelname[i];
cName.append(ch);
}
String controllerName = cName.toString();
String strCtrl = "apps/" + application + '/' + model + '/' + controllerName + "_controller";
if (RhoSupport.findClass(strCtrl) == null) {
strCtrl = "apps/" + application + '/' + model + '/' + "controller";
if( RhoSupport.findClass(strCtrl) == null )
return false;
}
Properties reqHash = new Properties();
String actionid = up.next();
String actionnext = up.next();
if ( actionid != null && actionid.length() > 0 ){
if ( actionid.length() > 6 && actionid.startsWith("%7B") &&
actionid.endsWith("%7D") )
actionid = "{" + actionid.substring(3, actionid.length()-3) + "}";
if ( actionid.length() > 2 &&
actionid.charAt(0)=='{' && actionid.charAt(actionid.length()-1)=='}' ){
reqHash.setProperty( "id", actionid);
reqHash.setProperty( "action", actionnext);
}else{
reqHash.setProperty( "id", actionnext);
reqHash.setProperty( "action", actionid);
}
}
reqHash.setProperty( "application",application);
reqHash.setProperty( "model", model);
doDispatch( reqHash, null);
if ( actionid !=null && actionid.length() > 2 &&
actionid.charAt(0)=='{' && actionid.charAt(actionid.length()-1)=='}' )
SyncThread.getInstance().addobjectnotify_bysrcname( model, actionid);
return true;
}
void doDispatch( Properties reqHash, String strIndex)throws IOException
{
reqHash.setProperty("request-method", this.method);
reqHash.setProperty("request-uri", uri.getPath());
reqHash.setProperty("request-query", uri.getQueryString());
if ( postData != null && postData.size() > 0 )
{
if ( !RHOCONF().getBool("log_skip_post") )
LOG.TRACE(postData.toString());
reqHash.setProperty("request-body", postData.toString());
}
RubyValue res = RhoRuby.processRequest( reqHash, reqHeaders, resHeaders, strIndex);
processResponse(res);
RhodesApp.getInstance().keepLastVisitedUrl(url_external);
LOG.INFO("dispatch end");
}
public void processRequest() throws IOException{
if (!requestProcessed) {
String strErr = "";
LOG.TRACE("processRequest: " + getURL() );
String strReferer = reqHeaders != null ? reqHeaders.getPropertyIgnoreCase("Referer") : "";
if ( getRef() != null && getRef().length() > 0 && strReferer != null &&
strReferer.equalsIgnoreCase(uri_orig.getPathNoFragment()) )
{
respondNotModified();
}else
{
String strContType = getContentType();
if ( uri.getPath().startsWith("/apps/public"))
{
httpServeFile(strContType);
}else
{
if ( this.method.equals("POST") || strContType.length() == 0 ||
strContType.indexOf("application/x-www-form-urlencoded") >= 0)
{
if ( dispatch() )
{
requestProcessed = true;
m_isDispatchCall = true;
return;
}
}
if ( /*this.method == "GET" &&*/ httpGetFile(strContType) ){
//}else if ( dispatch() ){
}else{
respondNotFound(strErr);
}
}
}
requestProcessed = true;
}
}
private void processResponse(RubyValue res){
if ( res != null && res != RubyConstant.QNIL && res instanceof RubyHash ){
RubyHash resHash = (RubyHash)res;
RubyValue resBody = null;
RubyArray arKeys = resHash.keys();
RubyArray arValues = resHash.values();
for( int i = 0; i < arKeys.size(); i++ ){
String strKey = arKeys.get(i).toString();
if ( strKey.equals("request-body") )
resBody = arValues.get(i);
else if (strKey.equals("status"))
responseCode = arValues.get(i).toInt();
else if (strKey.equals("message"))
responseMsg = arValues.get(i).toString();
else
resHeaders.addProperty( strKey, arValues.get(i).toString() );
}
String strBody = "";
if ( resBody != null && resBody != RubyConstant.QNIL )
strBody = resBody.toRubyString().toString();
if ( !RHOCONF().getBool("log_skip_post") )
LOG.TRACE(strBody);
try{
responseData = new ByteArrayInputStream(strBody.getBytes("UTF-8"));
}catch(java.io.UnsupportedEncodingException exc)
{
LOG.ERROR("Error getting utf-8 body :", exc);
}
if ( responseData != null )
contentLength = Integer.parseInt(resHeaders.getPropertyIgnoreCase("Content-Length"));
}
}
}
|
package com.knox.heap;
import com.knox.Asserts;
import com.knox.tree.printer.BinaryTreeInfo;
import com.knox.tree.printer.BinaryTrees;
import java.util.Comparator;
public class BinaryHeap<T> implements Heap<T>, BinaryTreeInfo {
private static int DEFAULT_CAPACITY = 10;
private T[] elements;
private int size;
private Comparator<T> comparator;
public BinaryHeap(Comparator<T> comparator) {
this.comparator = comparator;
elements = (T[]) new Object[DEFAULT_CAPACITY];
}
public BinaryHeap() {
this((Comparator<T>)null);
}
private BinaryHeap(T[] elements, Comparator<T> comparator) {
this.comparator = comparator;
if (elements == null && elements.length == 0) {
this.elements = (T[]) new Object[DEFAULT_CAPACITY];
} else {
int length = elements.length;
int campacity = Math.max(elements.length, DEFAULT_CAPACITY);
this.elements = (T[]) new Object[campacity];
for (int i = 0; i < length; i++) {
this.elements[i] = elements[i];
}
size = length;
heapify();
}
}
private BinaryHeap(T[] elements) {
this(elements, null);
}
private void heapify() {
heapify_v2();
}
private void heapify_v1() {
for (int i = 0; i < size; i++) {
siftUp(i);
}
}
/*
*
*
* 1) ,
* 2) , ,
* 3) index = (size >> 1) - 1
* */
private void heapify_v2() {
int index = (size >> 1) - 1;
for (int i = index; i >= 0 ; i
siftDown(i);
}
}
@Override
public int size() {
return size;
}
@Override
public boolean isEmpty() {
return size == 0;
}
@Override
public void clear() {
for (int i = 0; i < size; i++) {
elements[i] = null;
}
size = 0;
}
@Override
public void add(T element) {
checkElementNotNull(element);
ensureCapacity();
elements[size] = element;
size++;
siftUp(size - 1);
}
@Override
public T get() {
emptyCheck();
return elements[0];
}
@Override
public T remove() {
emptyCheck();
int lastIndex = size - 1;
T element = elements[lastIndex];
elements[0] = element;
elements[lastIndex] = null;
size
siftDown(0);
return element;
}
@Override
public T replace(T element) {
if (size == 0) {
elements[0] = element;
size++;
return null;
}
T old = elements[0];
elements[0] = element;
siftDown(0);
return old;
}
private void siftUp(int index) {
// siftUp_v1(index);
siftUp_v2(index);
}
private void siftUp_v1(int index) {
while (index > 0) {
int parentIndex = index >> 1;
T element = elements[index];
T parent = elements[parentIndex];
if (compare(element, parent) <= 0) return;
// indexparentIndex
T tmp = elements[index];
elements[index] = elements[parentIndex];
elements[parentIndex] = tmp;
index = parentIndex;
}
}
/*
* siftUp_v1, index,
* 1. index
* 2. , parentindex
* 3. index
* 4. , 3log(n) log(n) + 1
* */
private void siftUp_v2(int index) {
T element = elements[index];
while (index > 0) {
int parentIndex = index >> 1;
T parent = elements[parentIndex];
if (compare(element, parent) < 0) break;
// parentindex
elements[index] = parent;
index = parentIndex;
}
elements[index] = element;
}
private void siftDown(int index) {
T element = elements[index];
int half = size >> 1;
// == , floor(size / 2)
// index <
while (index < half) {
int maxIndex = (index << 1) + 1;
int rightIndex = maxIndex + 1;
T maxChild = elements[maxIndex];
if (rightIndex < size && compare(elements[rightIndex], maxChild) > 0) {
maxIndex = rightIndex;
maxChild = elements[rightIndex];
}
if (compare(element, maxChild) >= 0) break;
elements[index] = maxChild;
index = maxIndex;
}
elements[index] = element;
}
private void ensureCapacity() {
if (elements.length > size) return;
int newCapacity = elements.length << 1;
T[] oldElements = elements;
elements = (T[]) new Object[newCapacity];
for (int i = 0; i < size; i++) {
elements[i] = oldElements[i];
}
}
private int compare(T e1, T e2) {
if (comparator == null) {
return ((Comparable)e1).compareTo(e2);
} else {
return comparator.compare(e1, e2);
}
}
private void checkElementNotNull(T element) {
if (element == null) {
throw new IllegalArgumentException("element must not be null");
}
}
private void emptyCheck() {
if (size == 0) {
throw new IndexOutOfBoundsException("Heap is empty");
}
}
@Override
public Object root() {
return 0;
}
@Override
public Object left(Object node) {
int index = ((int)node << 1) + 1;
return index < size ? index : null;
}
@Override
public Object right(Object node) {
int index = ((int)node << 1) + 2;
return index < size ? index : null;
}
@Override
public Object string(Object node) {
return elements[(int)node];
}
public static void main(String[] args) {
BinaryHeap<Integer> heap = new BinaryHeap<>();
Asserts.testTrue(heap.isEmpty());
// test add
heap.add(10);
Asserts.testEqual(heap.size(), 1);
Asserts.testEqual(heap.get(), 10);
heap.add(20);
Asserts.testEqual(heap.get(), 20);
heap.add(15);
heap.add(11);
heap.add(23);
heap.add(9);
Asserts.testEqual(heap.get(), 23);
Asserts.testEqual(heap.size(), 6);
Asserts.testFalse(heap.isEmpty());
BinaryTrees.print(heap);
// test remove
heap.remove();
BinaryTrees.print(heap);
Asserts.testEqual(heap.get(), 20);
heap.remove();
Asserts.testEqual(heap.get(), 15);
heap.remove();
Asserts.testEqual(heap.get(), 11);
heap.remove();
Asserts.testEqual(heap.get(), 10);
heap.remove();
Asserts.testEqual(heap.get(), 9);
heap.remove();
Asserts.testTrue(heap.isEmpty());
test_replace();
test_heapify();
test_topK();
}
static void test_replace() {
BinaryHeap<Integer> heap = new BinaryHeap<>();
heap.add(15);
heap.add(11);
heap.add(23);
heap.add(9);
Asserts.testEqual(heap.get(), 23);
Asserts.testEqual(heap.replace(50), 23);
Asserts.testEqual(heap.get(), 50);
BinaryTrees.print(heap);
}
static void test_heapify() {
BinaryHeap<Integer> heap = new BinaryHeap<>(new Integer[] {
92, 98, 32, 91, 50, 17, 12, 6, 84, 80, 45, 47, 54, 44, 16, 27, 78
});
BinaryTrees.print(heap);
}
/*
* n, K(nk)
* , k
* topKO(nlogk)
* */
static void test_topK() {
Integer[] elements = new Integer[] {
92, 98, 32, 91, 50, 17, 12, 6, 84, 80, 45, 47, 54, 44, 16, 27, 78
};
int topK = 5;
BinaryHeap<Integer> heap = new BinaryHeap<>(new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return o2 - o1;
}
});
for (int i = 0; i < elements.length; i++) {
if (heap.size < topK) {
heap.add(elements[i]);
} else if (elements[i] > heap.get()) {
heap.replace(elements[i]);
}
}
System.out.println("
BinaryTrees.print(heap);
}
}
|
package main;
import search.RoomMappingA;
import search.SqRoomExploration;
import search.SquareMapping;
import lejos.nxt.Button;
import lejos.nxt.LightSensor;
import lejos.nxt.MotorPort;
import lejos.nxt.NXTRegulatedMotor;
import lejos.nxt.SensorPort;
import lejos.robotics.navigation.DifferentialPilot;
public class StartUp {
public static void main(String[] args) {
/* Brian do the thing
* Joey do the thing
* Jeff don't do the thing, you'd screw it up, learn to Java
*/
NXTRegulatedMotor motorB = new NXTRegulatedMotor(MotorPort.B);
NXTRegulatedMotor motorC = new NXTRegulatedMotor(MotorPort.C);
DifferentialPilot pilot = new DifferentialPilot(8, 31.2, motorB, motorC, true);
LightSensor lighter= new LightSensor(SensorPort.S1, true);
Compass norty = new Compass(lighter, pilot);
GUI gui = new GUI();
gui.setStrobeDelay(10);
Button.waitForAnyPress();
gui.setStrobeDelay(100);
gui.execute("Calibration: 1");
SquareMapping spinner = new SquareMapping(pilot, norty);
gui.execute("Calibration: 2");
norty.calibrate();
norty.goNorth();
gui.execute("Exploring");
SqRoomExploration mapper = new SqRoomExploration(pilot, spinner, 30, 30);
mapper.exploreRoom();
gui.execute("All Done!");
// PANIC CODE
//BasicCleaner bc = new BasicCleaner(pilot, rma);
//bc.cleanRoom(50);
}
public void angleTesting(int Range, DifferentialPilot pilot){
RoomMappingA rma = new RoomMappingA(pilot, SensorPort.S3, SensorPort.S4);
for(int angel = Range; Range<200; Range+= 5){
pilot.rotate(angel);
System.out.println("Rotation Degree: " + angel);
rma.waitForBumperPress();
}
}
}
|
package bisq.common.util;
import bisq.common.crypto.LimitedKeyStrengthException;
import org.bitcoinj.core.Utils;
import com.google.gson.ExclusionStrategy;
import com.google.gson.FieldAttributes;
import com.google.gson.FieldNamingPolicy;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.common.base.Splitter;
import com.google.common.util.concurrent.ListeningExecutorService;
import com.google.common.util.concurrent.MoreExecutors;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import javafx.scene.input.Clipboard;
import javafx.scene.input.ClipboardContent;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyCodeCombination;
import javafx.scene.input.KeyCombination;
import javafx.scene.input.KeyEvent;
import javax.crypto.Cipher;
import java.security.NoSuchAlgorithmException;
import java.net.URI;
import java.net.URISyntaxException;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.Collection;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashSet;
import java.util.Locale;
import java.util.Random;
import java.util.Set;
import java.util.TimeZone;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import lombok.extern.slf4j.Slf4j;
import javax.annotation.Nullable;
import static com.google.common.base.Preconditions.checkNotNull;
import static java.awt.Desktop.Action;
import static java.awt.Desktop.getDesktop;
import static java.awt.Desktop.isDesktopSupported;
@Slf4j
public class Utilities {
private static long lastTimeStamp = System.currentTimeMillis();
public static final String LB = System.getProperty("line.separator");
// TODO check out Jackson lib
public static String objectToJson(Object object) {
Gson gson = new GsonBuilder()
.setExclusionStrategies(new AnnotationExclusionStrategy())
/*.excludeFieldsWithModifiers(Modifier.TRANSIENT)*/
/* .setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE)*/
.setPrettyPrinting()
.create();
return gson.toJson(object);
}
public static ListeningExecutorService getListeningSingleThreadExecutor(String name) {
return MoreExecutors.listeningDecorator(getSingleThreadExecutor(name));
}
public static ListeningExecutorService getSingleThreadExecutor(String name) {
final ThreadFactory threadFactory = new ThreadFactoryBuilder()
.setNameFormat(name)
.setDaemon(true)
.build();
return MoreExecutors.listeningDecorator(Executors.newSingleThreadExecutor(threadFactory));
}
public static ListeningExecutorService getListeningExecutorService(String name,
int corePoolSize,
int maximumPoolSize,
long keepAliveTimeInSec) {
return MoreExecutors.listeningDecorator(getThreadPoolExecutor(name, corePoolSize, maximumPoolSize, keepAliveTimeInSec));
}
public static ThreadPoolExecutor getThreadPoolExecutor(String name,
int corePoolSize,
int maximumPoolSize,
long keepAliveTimeInSec) {
final ThreadFactory threadFactory = new ThreadFactoryBuilder()
.setNameFormat(name)
.setDaemon(true)
.build();
ThreadPoolExecutor executor = new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTimeInSec,
TimeUnit.SECONDS, new ArrayBlockingQueue<>(maximumPoolSize), threadFactory);
executor.allowCoreThreadTimeOut(true);
executor.setRejectedExecutionHandler((r, e) -> log.debug("RejectedExecutionHandler called"));
return executor;
}
@SuppressWarnings("SameParameterValue")
public static ScheduledThreadPoolExecutor getScheduledThreadPoolExecutor(String name,
int corePoolSize,
int maximumPoolSize,
long keepAliveTimeInSec) {
final ThreadFactory threadFactory = new ThreadFactoryBuilder()
.setNameFormat(name)
.setDaemon(true)
.setPriority(Thread.MIN_PRIORITY)
.build();
ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(corePoolSize, threadFactory);
executor.setKeepAliveTime(keepAliveTimeInSec, TimeUnit.SECONDS);
executor.allowCoreThreadTimeOut(true);
executor.setMaximumPoolSize(maximumPoolSize);
executor.setExecuteExistingDelayedTasksAfterShutdownPolicy(false);
executor.setRejectedExecutionHandler((r, e) -> log.debug("RejectedExecutionHandler called"));
return executor;
}
/**
* @return true if <code>defaults read -g AppleInterfaceStyle</code> has an exit status of <code>0</code> (i.e. _not_ returning "key not found").
*/
public static boolean isMacMenuBarDarkMode() {
try {
// check for exit status only. Once there are more modes than "dark" and "default", we might need to analyze string contents..
Process process = Runtime.getRuntime().exec(new String[]{"defaults", "read", "-g", "AppleInterfaceStyle"});
process.waitFor(100, TimeUnit.MILLISECONDS);
return process.exitValue() == 0;
} catch (IOException | InterruptedException | IllegalThreadStateException ex) {
return false;
}
}
public static boolean isUnix() {
return isOSX() || isLinux() || getOSName().contains("freebsd");
}
public static boolean isWindows() {
return getOSName().contains("win");
}
public static boolean isOSX() {
return getOSName().contains("mac") || getOSName().contains("darwin");
}
public static boolean isLinux() {
return getOSName().contains("linux");
}
public static boolean isDebianLinux() {
return isLinux() && new File("/etc/debian_version").isFile();
}
public static boolean isRedHatLinux() {
return isLinux() && new File("/etc/redhat-release").isFile();
}
private static String getOSName() {
return System.getProperty("os.name").toLowerCase(Locale.US);
}
public static String getOSArchitecture() {
String osArch = System.getProperty("os.arch");
if (isWindows()) {
// See: Like always windows needs extra treatment
String arch = System.getenv("PROCESSOR_ARCHITECTURE");
String wow64Arch = System.getenv("PROCESSOR_ARCHITEW6432");
return arch.endsWith("64")
|| wow64Arch != null && wow64Arch.endsWith("64")
? "64" : "32";
} else if (osArch.contains("arm")) {
// armv8 is 64 bit, armv7l is 32 bit
return osArch.contains("64") || osArch.contains("v8") ? "64" : "32";
} else if (isLinux()) {
return osArch.startsWith("i") ? "32" : "64";
} else {
return osArch.contains("64") ? "64" : osArch;
}
}
public static void printSysInfo() {
log.info("System info: os.name={}; os.version={}; os.arch={}; sun.arch.data.model={}; JRE={}; JVM={}",
System.getProperty("os.name"),
System.getProperty("os.version"),
System.getProperty("os.arch"),
getJVMArchitecture(),
(System.getProperty("java.runtime.version", "-") + " (" + System.getProperty("java.vendor", "-") + ")"),
(System.getProperty("java.vm.version", "-") + " (" + System.getProperty("java.vm.name", "-") + ")")
);
}
public static String getJVMArchitecture() {
return System.getProperty("sun.arch.data.model");
}
public static boolean isCorrectOSArchitecture() {
boolean result = getOSArchitecture().endsWith(getJVMArchitecture());
if (!result) {
log.warn("System.getProperty(\"os.arch\") " + System.getProperty("os.arch"));
log.warn("System.getenv(\"ProgramFiles(x86)\") " + System.getenv("ProgramFiles(x86)"));
log.warn("System.getenv(\"PROCESSOR_ARCHITECTURE\")" + System.getenv("PROCESSOR_ARCHITECTURE"));
log.warn("System.getenv(\"PROCESSOR_ARCHITEW6432\") " + System.getenv("PROCESSOR_ARCHITEW6432"));
log.warn("System.getProperty(\"sun.arch.data.model\") " + System.getProperty("sun.arch.data.model"));
}
return result;
}
public static void openURI(URI uri) throws IOException {
if (!isLinux()
&& isDesktopSupported()
&& getDesktop().isSupported(Action.BROWSE)) {
getDesktop().browse(uri);
} else {
// Maybe Application.HostServices works in those cases?
// HostServices hostServices = getHostServices();
// hostServices.showDocument(uri.toString());
// On Linux Desktop is poorly implemented.
if (!DesktopUtil.browse(uri))
throw new IOException("Failed to open URI: " + uri.toString());
}
}
public static void openFile(File file) throws IOException {
if (!isLinux()
&& isDesktopSupported()
&& getDesktop().isSupported(Action.OPEN)) {
getDesktop().open(file);
} else {
// Maybe Application.HostServices works in those cases?
// HostServices hostServices = getHostServices();
// hostServices.showDocument(uri.toString());
// On Linux Desktop is poorly implemented.
if (!DesktopUtil.open(file))
throw new IOException("Failed to open file: " + file.toString());
}
}
public static String getTmpDir() {
return System.getProperty("java.io.tmpdir");
}
public static String getDownloadOfHomeDir() {
File file = new File(getSystemHomeDirectory() + "/Downloads");
if (file.exists())
return file.getAbsolutePath();
else
return getSystemHomeDirectory();
}
public static void printSystemLoad() {
Runtime runtime = Runtime.getRuntime();
long free = runtime.freeMemory() / 1024 / 1024;
long total = runtime.totalMemory() / 1024 / 1024;
long used = total - free;
log.info("System load (no. threads/used memory (MB)): " + Thread.activeCount() + "/" + used);
}
public static void copyToClipboard(String content) {
try {
if (content != null && content.length() > 0) {
Clipboard clipboard = Clipboard.getSystemClipboard();
ClipboardContent clipboardContent = new ClipboardContent();
clipboardContent.putString(content);
clipboard.setContent(clipboardContent);
}
} catch (Throwable e) {
log.error("copyToClipboard failed " + e.getMessage());
e.printStackTrace();
}
}
public static byte[] concatByteArrays(byte[]... arrays) {
int totalLength = 0;
for (byte[] array : arrays) {
totalLength += array.length;
}
byte[] result = new byte[totalLength];
int currentIndex = 0;
for (byte[] array : arrays) {
System.arraycopy(array, 0, result, currentIndex, array.length);
currentIndex += array.length;
}
return result;
}
public static <T> T jsonToObject(String jsonString, Class<T> classOfT) {
Gson gson = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE).setPrettyPrinting().create();
return gson.fromJson(jsonString, classOfT);
}
public static <T extends Serializable> T deserialize(byte[] data) {
ByteArrayInputStream bis = new ByteArrayInputStream(data);
ObjectInput in = null;
Object result = null;
try {
in = new ObjectInputStream(bis);
result = in.readObject();
if (!(result instanceof Serializable))
throw new RuntimeException("Object not of type Serializable");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
bis.close();
} catch (IOException ex) {
// ignore close exception
}
try {
if (in != null) {
in.close();
}
} catch (IOException ex) {
// ignore close exception
}
}
//noinspection unchecked,ConstantConditions
return (T) result;
}
public static byte[] serialize(Serializable object) {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutput out = null;
byte[] result = null;
try {
out = new ObjectOutputStream(bos);
out.writeObject(object);
out.flush();
result = bos.toByteArray().clone();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (out != null) {
out.close();
}
} catch (IOException ignore) {
}
try {
bos.close();
} catch (IOException ignore) {
}
}
return result;
}
public static <T extends Serializable> T cloneObject(Serializable object) {
return deserialize(serialize(object));
}
@SuppressWarnings("SameParameterValue")
private static void printElapsedTime(String msg) {
if (!msg.isEmpty()) {
msg += " / ";
}
long timeStamp = System.currentTimeMillis();
log.debug(msg + "Elapsed: " + String.valueOf(timeStamp - lastTimeStamp));
lastTimeStamp = timeStamp;
}
public static void printElapsedTime() {
printElapsedTime("");
}
public static void setThreadName(String name) {
Thread.currentThread().setName(name + "-" + new Random().nextInt(10000));
}
public static boolean isDirectory(String path) {
return new File(path).isDirectory();
}
public static String getSystemHomeDirectory() {
return Utilities.isWindows() ? System.getenv("USERPROFILE") : System.getProperty("user.home");
}
public static String encodeToHex(@Nullable byte[] bytes, boolean allowNullable) {
if (allowNullable)
return bytes != null ? Utils.HEX.encode(bytes) : "null";
else
return Utils.HEX.encode(checkNotNull(bytes, "bytes must not be null at encodeToHex"));
}
public static String bytesAsHexString(@Nullable byte[] bytes) {
return encodeToHex(bytes, true);
}
public static String encodeToHex(@Nullable byte[] bytes) {
return encodeToHex(bytes, false);
}
public static byte[] decodeFromHex(String encoded) {
return Utils.HEX.decode(encoded);
}
public static boolean isAltOrCtrlPressed(KeyCode keyCode, KeyEvent keyEvent) {
return isAltPressed(keyCode, keyEvent) || isCtrlPressed(keyCode, keyEvent);
}
public static boolean isCtrlPressed(KeyCode keyCode, KeyEvent keyEvent) {
return new KeyCodeCombination(keyCode, KeyCombination.SHORTCUT_DOWN).match(keyEvent) ||
new KeyCodeCombination(keyCode, KeyCombination.CONTROL_DOWN).match(keyEvent);
}
public static boolean isAltPressed(KeyCode keyCode, KeyEvent keyEvent) {
return new KeyCodeCombination(keyCode, KeyCombination.ALT_DOWN).match(keyEvent);
}
public static byte[] concatenateByteArrays(byte[] array1, byte[] array2) {
return ArrayUtils.addAll(array1, array2);
}
public static byte[] concatenateByteArrays(byte[] array1, byte[] array2, byte[] array3) {
return ArrayUtils.addAll(array1, ArrayUtils.addAll(array2, array3));
}
public static byte[] concatenateByteArrays(byte[] array1, byte[] array2, byte[] array3, byte[] array4) {
return ArrayUtils.addAll(array1, ArrayUtils.addAll(array2, ArrayUtils.addAll(array3, array4)));
}
public static byte[] concatenateByteArrays(byte[] array1, byte[] array2, byte[] array3, byte[] array4, byte[] array5) {
return ArrayUtils.addAll(array1, ArrayUtils.addAll(array2, ArrayUtils.addAll(array3, ArrayUtils.addAll(array4, array5))));
}
public static Date getUTCDate(int year, int month, int dayOfMonth) {
GregorianCalendar calendar = new GregorianCalendar(year, month, dayOfMonth);
calendar.setTimeZone(TimeZone.getTimeZone("UTC"));
return calendar.getTime();
}
/**
* @param stringList String of comma separated tokens.
* @param allowWhitespace If white space inside the list tokens is allowed. If not the token will be ignored.
* @return Set of tokens
*/
public static Set<String> commaSeparatedListToSet(String stringList, boolean allowWhitespace) {
if (stringList != null) {
return Splitter.on(",")
.splitToList(allowWhitespace ? stringList : StringUtils.deleteWhitespace(stringList))
.stream()
.filter(e -> !e.isEmpty())
.collect(Collectors.toSet());
} else {
return new HashSet<>();
}
}
public static String getPathOfCodeSource() throws URISyntaxException {
return new File(Utilities.class.getProtectionDomain().getCodeSource().getLocation().toURI()).getPath();
}
private static class AnnotationExclusionStrategy implements ExclusionStrategy {
@Override
public boolean shouldSkipField(FieldAttributes f) {
return f.getAnnotation(JsonExclude.class) != null;
}
@Override
public boolean shouldSkipClass(Class<?> clazz) {
return false;
}
}
public static void checkCryptoPolicySetup() throws NoSuchAlgorithmException, LimitedKeyStrengthException {
if (Cipher.getMaxAllowedKeyLength("AES") > 128)
log.debug("Congratulations, you have unlimited key length support!");
else
throw new LimitedKeyStrengthException();
}
public static String toTruncatedString(Object message) {
return toTruncatedString(message, 200, true);
}
public static String toTruncatedString(Object message, int maxLength) {
return toTruncatedString(message, maxLength, true);
}
public static String toTruncatedString(Object message, boolean removeLinebreaks) {
return toTruncatedString(message, 200, removeLinebreaks);
}
public static String toTruncatedString(Object message, int maxLength, boolean removeLinebreaks) {
if (message == null)
return "null";
String result = StringUtils.abbreviate(message.toString(), maxLength);
if (removeLinebreaks)
return result.replace("\n", "");
return result;
}
public static String getRandomPrefix(int minLength, int maxLength) {
int length = minLength + new Random().nextInt(maxLength - minLength + 1);
String result;
switch (new Random().nextInt(3)) {
case 0:
result = RandomStringUtils.randomAlphabetic(length);
break;
case 1:
result = RandomStringUtils.randomNumeric(length);
break;
case 2:
default:
result = RandomStringUtils.randomAlphanumeric(length);
}
switch (new Random().nextInt(3)) {
case 0:
result = result.toUpperCase();
break;
case 1:
result = result.toLowerCase();
break;
case 2:
default:
}
return result;
}
public static String getShortId(String id) {
return getShortId(id, "-");
}
@SuppressWarnings("SameParameterValue")
public static String getShortId(String id, String sep) {
String[] chunks = id.split(sep);
if (chunks.length > 0)
return chunks[0];
else
return id.substring(0, Math.min(8, id.length()));
}
public static String collectionToCSV(Collection<String> collection) {
return collection.stream().map(Object::toString).collect(Collectors.joining(","));
}
public static byte[] integerToByteArray(int intValue, int numBytes) {
byte[] bytes = new byte[numBytes];
for (int i = numBytes - 1; i >= 0; i
bytes[i] = ((byte) (intValue & 0xFF));
intValue >>>= 8;
}
return bytes;
}
public static int byteArrayToInteger(byte[] bytes) {
int result = 0;
for (byte aByte : bytes) {
result = result << 8 | aByte & 0xff;
}
return result;
}
}
|
package etomica.interfacial;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import etomica.action.activity.ActivityIntegrate;
import etomica.api.IAtomList;
import etomica.api.IAtomType;
import etomica.api.IBox;
import etomica.api.IMoleculeList;
import etomica.api.ISpecies;
import etomica.api.IVector;
import etomica.api.IVectorMutable;
import etomica.atom.AtomSourceRandomSpecies;
import etomica.atom.DiameterHashByType;
import etomica.box.Box;
import etomica.chem.elements.ElementSimple;
import etomica.config.Configuration;
import etomica.data.AccumulatorAverage;
import etomica.data.AccumulatorAverageFixed;
import etomica.data.AccumulatorHistory;
import etomica.data.DataDump;
import etomica.data.DataFork;
import etomica.data.DataPump;
import etomica.data.DataPumpListener;
import etomica.data.DataSourceCountSteps;
import etomica.data.meter.MeterNMolecules;
import etomica.data.meter.MeterPotentialEnergy;
import etomica.data.meter.MeterPotentialEnergyFromIntegrator;
import etomica.data.meter.MeterProfileByVolume;
import etomica.graphics.DisplayPlot;
import etomica.graphics.SimulationGraphic;
import etomica.integrator.IntegratorMC;
import etomica.integrator.mcmove.MCMoveAtom;
import etomica.integrator.mcmove.MCMoveStepTracker;
import etomica.listener.IntegratorListenerAction;
import etomica.nbr.cell.PotentialMasterCell;
import etomica.potential.P2LennardJones;
import etomica.potential.P2SoftSphericalTruncatedForceShifted;
import etomica.potential.Potential1;
import etomica.simulation.Simulation;
import etomica.space.BoundaryRectangularSlit;
import etomica.space.ISpace;
import etomica.space3d.Space3D;
import etomica.species.SpeciesSpheresMono;
import etomica.util.HistoryCollapsingAverage;
import etomica.util.ParameterBase;
import etomica.util.ParseArgs;
/**
* Simple Lennard-Jones molecular dynamics simulation in 3D
*/
public class LjMC3D extends Simulation {
public final PotentialMasterCell potentialMasterCell;
public final ActivityIntegrate ai;
public IntegratorMC integrator;
public SpeciesSpheresMono speciesFluid, speciesTopWall, speciesBottomWall;
public IBox box;
public P2SoftSphericalTruncatedForceShifted pFF, pTW, pBW;
public ConfigurationLammps config;
public LjMC3D(double temperature, double Lxy, String lammpsFile) {
super(Space3D.getInstance());
BoundaryRectangularSlit boundary = new BoundaryRectangularSlit(2, space);
IVectorMutable bs = (IVectorMutable)boundary.getBoxSize();
bs.setX(0, Lxy);
bs.setX(1, Lxy);
boundary.setBoxSize(bs);
box = new Box(boundary, space);
addBox(box);
speciesFluid = new SpeciesSpheresMono(space, new ElementSimple("F"));
addSpecies(speciesFluid);
speciesTopWall = new SpeciesSpheresMono(space, new ElementSimple("TW"));
addSpecies(speciesTopWall);
speciesBottomWall = new SpeciesSpheresMono(space, new ElementSimple("BW"));
addSpecies(speciesBottomWall);
config = new ConfigurationLammps(space, lammpsFile, speciesTopWall, speciesBottomWall, speciesFluid);
config.initializeCoordinates(box);
potentialMasterCell = new PotentialMasterCell(this, 5.49925, space);
potentialMasterCell.setCellRange(2);
integrator = new IntegratorMC(this, potentialMasterCell);
integrator.setTemperature(temperature);
MCMoveAtom mcMoveAtom = new MCMoveAtom(random, potentialMasterCell, space);
mcMoveAtom.setAtomSource(new AtomSourceRandomSpecies(getRandom(), speciesFluid));
MCMoveAtom mcMoveAtomBig = new MCMoveAtom(random, potentialMasterCell, space);
mcMoveAtomBig.setAtomSource(new AtomSourceRandomSpecies(getRandom(), speciesFluid));
mcMoveAtomBig.setStepSize(0.5*Lxy);
((MCMoveStepTracker)mcMoveAtomBig.getTracker()).setTunable(false);
integrator.getMoveManager().addMCMove(mcMoveAtom);
integrator.getMoveManager().addMCMove(mcMoveAtomBig);
ai = new ActivityIntegrate(integrator);
getController().addAction(ai);
pFF = new P2SoftSphericalTruncatedForceShifted(space, new P2LennardJones(space, 1.0, 1.0), 2.5);
IAtomType leafType = speciesFluid.getLeafType();
potentialMasterCell.addPotential(pFF,new IAtomType[]{leafType,leafType});
pBW = new P2SoftSphericalTruncatedForceShifted(space, new P2LennardJones(space, 1.09985, 0.4), 5.49925);
potentialMasterCell.addPotential(pBW,new IAtomType[]{leafType,speciesBottomWall.getLeafType()});
pTW = new P2SoftSphericalTruncatedForceShifted(space, new P2LennardJones(space, 1.5, 0.1), 1.68);
potentialMasterCell.addPotential(pTW,new IAtomType[]{leafType,speciesTopWall.getLeafType()});
Potential1 p1F = new Potential1(space) {
public double energy(IAtomList atoms) {
IVector p = atoms.getAtom(0).getPosition();
double z = p.getX(2);
double Lz = boundary.getBoxSize().getX(2);
return (Math.abs(z) > 0.5*Lz) ? Double.POSITIVE_INFINITY : 0;
}
};
potentialMasterCell.addPotential(p1F,new IAtomType[]{leafType});
integrator.setBox(box);
integrator.getMoveEventManager().addListener(potentialMasterCell.getNbrCellManager(box).makeMCMoveListener());
potentialMasterCell.getNbrCellManager(box).assignCellAll();
}
public static void main(String[] args) {
// according to Mastny & de Pablo
// triple point
// T = 0.694
// liquid density = 0.845435
// Agrawal and Kofke:
// small large
// T 0.698 0.687(4)
// p 0.0013 0.0011
// rho 0.854 0.850
// T = 0.7085(5)
// P = 0.002264(17)
// rhoL = 0.8405(3)
// rhoFCC = 0.9587(2)
// rhoV = 0.002298(18)
LjMC3DParams params = new LjMC3DParams();
ParseArgs.doParseArgs(params, args);
if (args.length==0) {
params.graphics = false;
params.lammpsFile = "eq.data.2";
params.steps = 10000;
params.T = 0.8;
params.Lxy = 15.239984;
}
final double temperature = params.T;
final double Lxy = params.Lxy;
long steps = params.steps;
boolean graphics = params.graphics;
String lammpsFile = params.lammpsFile;
if (!graphics) {
System.out.println("Running MC with T="+temperature);
System.out.println(steps+" steps");
}
final LjMC3D sim = new LjMC3D(temperature, Lxy, lammpsFile);
MeterPotentialEnergyFromIntegrator meterPE = new MeterPotentialEnergyFromIntegrator();
meterPE.setIntegrator(sim.integrator);
DataFork forkPE = new DataFork();
DataPumpListener pumpPE = new DataPumpListener(meterPE, forkPE, 10);
sim.integrator.getEventManager().addListener(pumpPE);
MeterWallForce meterWF = new MeterWallForce(sim.space, sim.potentialMasterCell, sim.box, sim.speciesTopWall);
DataFork forkWF = new DataFork();
DataPumpListener pumpWF = new DataPumpListener(meterWF, forkWF, 1000);
sim.integrator.getEventManager().addListener(pumpWF);
MeterPotentialEnergy meterPE2 = new MeterPotentialEnergy(sim.potentialMasterCell);
meterPE2.setBox(sim.box);
double u = meterPE2.getDataAsScalar();
System.out.println("Potential energy: "+u);
System.out.println("Wall force: "+meterWF.getDataAsScalar());
MeterProfileByVolume densityProfileMeter = new MeterProfileByVolume(sim.space);
densityProfileMeter.setProfileDim(2);
densityProfileMeter.setBox(sim.box);
MeterNMolecules meterNMolecules = new MeterNMolecules();
meterNMolecules.setSpecies(sim.speciesFluid);
densityProfileMeter.setDataSource(meterNMolecules);
AccumulatorAverageFixed densityProfileAvg = new AccumulatorAverageFixed(10);
densityProfileAvg.setPushInterval(10);
DataPump profilePump = new DataPumpListener(densityProfileMeter, densityProfileAvg, 1000);
DataDump profileDump = new DataDump();
densityProfileAvg.addDataSink(profileDump, new AccumulatorAverage.StatType[]{densityProfileAvg.AVERAGE});
IntegratorListenerAction profilePumpListener = new IntegratorListenerAction(profilePump);
sim.integrator.getEventManager().addListener(profilePumpListener);
profilePumpListener.setInterval(10);
if (graphics) {
final String APP_NAME = "LjMC3D";
final SimulationGraphic simGraphic = new SimulationGraphic(sim, SimulationGraphic.TABBED_PANE, APP_NAME, 3, sim.getSpace(), sim.getController());
List<DataPump> dataStreamPumps = simGraphic.getController().getDataStreamPumps();
dataStreamPumps.add(profilePump);
simGraphic.getController().getReinitButton().setPostAction(simGraphic.getPaintAction(sim.box));
simGraphic.makeAndDisplayFrame(APP_NAME);
DiameterHashByType dh = (DiameterHashByType)simGraphic.getDisplayBox(sim.box).getDiameterHash();
dh.setDiameter(sim.speciesFluid.getLeafType(), 1.0);
dh.setDiameter(sim.speciesBottomWall.getLeafType(), 1.09885);
dh.setDiameter(sim.speciesTopWall.getLeafType(), 1.5);
DataSourceCountSteps dsSteps = new DataSourceCountSteps(sim.integrator);
AccumulatorHistory historyPE = new AccumulatorHistory(new HistoryCollapsingAverage());
historyPE.setTimeDataSource(dsSteps);
forkPE.addDataSink(historyPE);
DisplayPlot plotPE = new DisplayPlot();
historyPE.setDataSink(plotPE.getDataSet().makeDataSink());
plotPE.setLabel("PE");
simGraphic.add(plotPE);
AccumulatorHistory historyWF = new AccumulatorHistory(new HistoryCollapsingAverage());
historyWF.setTimeDataSource(dsSteps);
forkWF.addDataSink(historyWF);
DisplayPlot plotWF = new DisplayPlot();
historyWF.setDataSink(plotWF.getDataSet().makeDataSink());
plotWF.setLabel("Force");
simGraphic.add(plotWF);
DisplayPlot profilePlot = new DisplayPlot();
densityProfileAvg.addDataSink(profilePlot.getDataSet().makeDataSink(), new AccumulatorAverage.StatType[]{densityProfileAvg.AVERAGE});
profilePlot.setLabel("density");
simGraphic.add(profilePlot);
return;
}
long bs = steps/100000;
if (bs==0) bs=1;
AccumulatorAverageFixed accPE = new AccumulatorAverageFixed(bs);
forkPE.addDataSink(accPE);
AccumulatorAverageFixed accWF = new AccumulatorAverageFixed(bs);
forkWF.addDataSink(accWF);
sim.ai.setMaxSteps(steps);
sim.getController().actionPerformed();
u = meterPE2.getDataAsScalar();
System.out.println("Potential energy: "+u);
System.out.println("Wall force: "+meterWF.getDataAsScalar());
double avgPE = accPE.getData().getValue(accPE.AVERAGE.index);
double errPE = accPE.getData().getValue(accPE.ERROR.index);
double corPE = accPE.getData().getValue(accPE.BLOCK_CORRELATION.index);
double avgWF = accWF.getData().getValue(accPE.AVERAGE.index);
double errWF = accWF.getData().getValue(accPE.ERROR.index);
double corWF = accWF.getData().getValue(accPE.BLOCK_CORRELATION.index);
if (steps>100000) {
System.out.println(String.format("Average potential energy: %25.15e %10.4e % 5.3f\n",avgPE,errPE,corPE));
System.out.println(String.format("Average wall force: %25.15e %10.4e % 5.3f\n",avgWF,errWF,corWF));
}
else {
System.out.println("Average potential energy: "+avgPE);
System.out.println("Average wall force: "+avgWF);
}
WriteConfigurationInterfacial configWriter = new WriteConfigurationInterfacial(sim.space);
configWriter.setSpecies(sim.speciesFluid);
IVectorMutable unshift = sim.space.makeVector();
unshift.Ea1Tv1(-1, sim.config.getShift());
configWriter.setShift(unshift);
configWriter.setBox(sim.box);
configWriter.setFileName("xyz_000.dat");
configWriter.actionPerformed();
}
public static class ConfigurationLammps implements Configuration {
protected final ISpace space;
protected final String filename;
protected final ISpecies[] species;
protected IVectorMutable shift;
public ConfigurationLammps(ISpace space, String filename, ISpecies topWall, ISpecies bottomWall, ISpecies fluid) {
this.space = space;
this.filename = filename;
this.species = new ISpecies[]{topWall, fluid, bottomWall};
shift = space.makeVector();
}
public void initializeCoordinates(IBox box) {
List<IVectorMutable>[] coords = new List[3];
coords[0] = new ArrayList<IVectorMutable>();
coords[1] = new ArrayList<IVectorMutable>();
coords[2] = new ArrayList<IVectorMutable>();
double zMin = Double.POSITIVE_INFINITY;
double zMax = -Double.POSITIVE_INFINITY;
try {
FileReader fr = new FileReader(filename);
BufferedReader bufReader = new BufferedReader(fr);
String line = null;
while ((line = bufReader.readLine()) != null) {
String[] bits = line.split("\\t");
if (bits.length != 5) continue;
int aType = Integer.parseInt(bits[1]);
IVectorMutable xyz = space.makeVector();
for (int i=0; i<3; i++) {
xyz.setX(i, Double.parseDouble(bits[2+i]));
}
if (xyz.getX(2) > zMax) zMax = xyz.getX(2);
if (xyz.getX(2) < zMin) zMin = xyz.getX(2);
coords[aType-1].add(xyz);
}
bufReader.close();
}
catch (IOException ex) {
throw new RuntimeException(ex);
}
double Lz = zMax-zMin + 0.8;
IVectorMutable bs = (IVectorMutable)box.getBoundary().getBoxSize();
bs.setX(2, Lz);
box.getBoundary().setBoxSize(bs);
shift.setX(0, -0.5*bs.getX(0));
shift.setX(1, -0.5*bs.getX(1));
shift.setX(2, -0.5*Lz - zMin);
for (int i=0; i<3; i++) {
box.setNMolecules(species[i], coords[i].size());
IMoleculeList m = box.getMoleculeList(species[i]);
for (int j=0; j<coords[i].size(); j++) {
IVectorMutable p = m.getMolecule(j).getChildList().getAtom(0).getPosition();
p.Ev1Pv2(coords[i].get(j), shift);
}
}
}
public IVector getShift() {
return shift;
}
}
public static class LjMC3DParams extends ParameterBase {
public double T = 2.0;
public long steps = 100000;
public boolean graphics = false;
public double Lxy = 0;
public String lammpsFile = "";
}
}
|
package etomica.graphics;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Panel;
import javax.vecmath.Point3f;
import org.jmol.g3d.Graphics3D;
import etomica.action.activity.Controller;
import etomica.api.IAtom;
import etomica.api.IAtomList;
import etomica.api.IAtomPositioned;
import etomica.api.IAtomTypeSphere;
import etomica.api.IBoundary;
import etomica.api.IBox;
import etomica.api.IVector;
import etomica.api.IVectorMutable;
import etomica.atom.AtomFilter;
import etomica.atom.AtomFilterCollective;
import etomica.atom.AtomLeafAgentManager;
import etomica.atom.AtomLeafAgentManager.AgentSource;
import etomica.math.geometry.LineSegment;
import etomica.math.geometry.Plane;
import etomica.math.geometry.Polytope;
import etomica.space.Boundary;
import etomica.space.ISpace;
import etomica.util.Arrays;
import g3dsys.control.G3DSys;
import g3dsys.images.Ball;
import g3dsys.images.Bond;
import g3dsys.images.Figure;
import g3dsys.images.Line;
import g3dsys.images.Triangle;
public class DisplayBoxCanvasG3DSys extends DisplayCanvas implements
AgentSource, BondManager {
// will handle all actual drawing
private G3DSys gsys;
private final double[] coords;
private AtomLeafAgentManager aam;
private Polytope oldPolytope;
private Line[] polytopeLines;
private boolean boundaryDisplayed = false;
private Color backgroundColor;
private Color boundaryFrameColor;
private Color planeColor;
private Panel panel = null;
private boolean initialOrient = false;
private Plane[] planes;
private Triangle[][] planeTriangles;
private IVectorMutable[] planeIntersections;
private IVectorMutable work, work2, work3;
private double[] planeAngles;
private final ISpace space;
public DisplayBoxCanvasG3DSys(DisplayBox _box, ISpace _space, Controller controller) {
super(controller);
displayBox = _box;
space = _space;
// init G3DSys
// adding JPanel flickers, Panel does not. Nobody knows why.
/*
* Set visible false here to be toggled later; seems to fix the
* 'sometimes gray' bug
*/
// this.setVisible(false); // to be set visible later by
// SimulationGraphic
panel = new Panel();
this.setLayout(new java.awt.GridLayout());
panel.setLayout(new java.awt.GridLayout());
panel.setSize(1600, 1600);
this.add(panel);
coords = new double[3];
gsys = new G3DSys(panel);
setBackgroundColor(Color.BLACK);
setBoundaryFrameColor(Color.WHITE);
setPlaneColor(Color.YELLOW);
// init AtomAgentManager, to sync G3DSys and Etomica models
// this automatically adds the atoms
aam = new AtomLeafAgentManager(this, displayBox.getBox());
planes = new Plane[0];
planeTriangles = new Triangle[0][0];
planeIntersections = new IVectorMutable[0];
planeAngles = new double[0];
work = space.makeVector();
work2 = space.makeVector();
work3 = space.makeVector();
}
public G3DSys getG3DSys() {
return gsys;
}
/**
* Sets the size of the display to a new value and scales the image so that
* the box fits in the canvas in the same proportion as before.
*/
public void scaleSetSize(int width, int height) {
if (getBounds().width * getBounds().height != 0) { // reset scale based
// on larger size
// change
double ratio1 = (double) width / (double) getBounds().width;
double ratio2 = (double) height / (double) getBounds().height;
double factor = Math.min(ratio1, ratio2);
// double factor = (Math.abs(Math.log(ratio1)) >
// Math.abs(Math.log(ratio2))) ? ratio1 : ratio2;
displayBox.setScale(displayBox.getScale() * factor);
setSize(width, height);
}
}
// Override superclass methods for changing size so that scale is reset with
// any size change
// this setBounds is ultimately called by all other setSize, setBounds
// methods
public void setBounds(int x, int y, int width, int height) {
if (width <= 0 || height <= 0)
return;
super.setBounds(x, y, width, height);
createOffScreen(width, height);
}
/**
* Sets the background color of the display box canvas.
* @param Color : color to set background to
*/
public void setBackgroundColor(Color color) {
backgroundColor = color;
gsys.setBGColor(color);
panel.setBackground(color);
}
/**
* Gets the background color of the display box canvas.
* @return Color : Current color of background
*/
public Color getBackgroundColor() {
return backgroundColor;
}
/**
* Sets the color of the box boundary.
* @param Color : color to set box boundary
*/
public void setBoundaryFrameColor(Color color) {
boundaryFrameColor = color;
oldPolytope = null;
}
/**
* Gets the color of box boundary.
* @return Color : Current color of box boundary
*/
public Color getBoundaryFrameColor() {
return boundaryFrameColor;
}
/**
* Sets the color of the plane.
* @param Color : color to set plane
*/
public void setPlaneColor(Color color) {
planeColor = color;
}
/**
* Gets the color of the plane.
* @return Color : Current color of plane
*/
public Color getPlaneColor() {
return planeColor;
}
public void removeObjectByBox(IBox p) {
// Remove old box atoms
IAtomList leafList = p.getLeafList();
int nLeaf = leafList.getAtomCount();
for (int iLeaf = 0; iLeaf < nLeaf; iLeaf++) {
IAtom a = leafList.getAtom(iLeaf);
if (a == null || !(a.getType() instanceof IAtomTypeSphere))
continue;
Ball ball = (Ball) aam.getAgent(a);
if (ball == null) {
continue;
}
gsys.removeFig(ball);
}
}
/**
* refreshAtomAgentMgr() - sets the new atom manager based upon the box.
* Would only need to be called if it's DisplayBoxs' box has changed.
*
*/
public void refreshAtomAgentMgr() {
// Set new atom manager
aam = null;
aam = new AtomLeafAgentManager(this, displayBox.getBox());
initialOrient = true;
}
public void doPaint(Graphics g) {
// handle pending bond addition requests
if (pendingBonds.size() > 0) {
for (int i = 0; i < pendingBonds.size(); i++) {
Object[] o = pendingBonds.get(i);
Ball ball0 = (Ball) o[0];
Ball ball1 = (Ball) o[1];
// can't do anything with bondType for now
Figure f = new Bond(gsys, ball0, ball1);
gsys.addFig(f);
}
}
/*
UNCOMMENT THIS CODE IF APPLICATIONS START ADDING THEIR OWN DRAWABLES
//do drawing of all drawing objects that have been added to the display
for(Iterator iter=displayBox.getDrawables().iterator(); iter.hasNext(); ) {
Drawable obj = (Drawable)iter.next();
obj.draw(g, displayBox.getOrigin(), displayBox.getToPixels());
}
*/
AtomFilter atomFilter = displayBox.getAtomFilter();
if (atomFilter instanceof AtomFilterCollective) {
((AtomFilterCollective)atomFilter).resetFilter();
}
ColorScheme colorScheme = displayBox.getColorScheme();
if (colorScheme instanceof ColorSchemeCollective) {
((ColorSchemeCollective) colorScheme).colorAllAtoms();
}
IAtomList leafList = displayBox.getBox().getLeafList();
int nLeaf = leafList.getAtomCount();
for (int iLeaf = 0; iLeaf < nLeaf; iLeaf++) {
IAtom a = null;
Ball ball = null;
try {
a = leafList.getAtom(iLeaf);
if (a == null || !(a.getType() instanceof IAtomTypeSphere))
continue;
ball = (Ball) aam.getAgent(a);
}
catch (ArrayIndexOutOfBoundsException e) {
System.out.println("oops, array index out of bounds");
//atoms might have been removed on another thread
break;
}
catch (IndexOutOfBoundsException e) {
System.out.println("oops, index out of bounds");
//atoms might have been removed on another thread
break;
}
if (ball == null) {
continue;
}
/*
* Atomfilter changes the drawable flag in spheres; bonds respect
* this and will not draw themselves either. Wireframe mode, on the
* other hand, tells G3DSys to ignore spheres entirely regardless of
* drawable flag. This makes it possible to filter bonds in
* wireframe mode as well.
*/
boolean drawable = atomFilter == null ? true : atomFilter.accept(a);
ball.setDrawable(drawable);
if (!drawable) {
continue;
}
((IAtomPositioned)a).getPosition().assignTo(coords);
float diameter = (float) ((IAtomTypeSphere) a.getType())
.getDiameter();
ball.setColor(G3DSys.getColix(colorScheme.getAtomColor(a)));
ball.setD(diameter);
ball.setX((float) coords[0]);
ball.setY((float) coords[1]);
ball.setZ((float) coords[2]);
}
for (int i=0; i<planes.length; i++) {
drawPlane(i);
}
IBoundary boundary = displayBox.getBox().getBoundary();
// Do not draw bounding box around figure if the boundary
// is not an etomica.space.Boundary
if(boundary instanceof Boundary) {
Polytope polytope = ((Boundary)boundary).getShape();
if (polytope != oldPolytope) {
// send iterator to g3dsys
gsys.setBoundaryVectorsIterator(wrapIndexIterator((((Boundary)boundary)
.getIndexIterator())));
if (polytopeLines != null) {
for (int i = 0; i < polytopeLines.length; i++) {
gsys.removeFig(polytopeLines[i]);
}
}
LineSegment[] lines = polytope.getEdges();
polytopeLines = new Line[lines.length];
for (int i = 0; i < lines.length; i++) {
IVector[] vertices = lines[i].getVertices();
polytopeLines[i] = new Line(gsys, G3DSys
.getColix(boundaryFrameColor), new Point3f(
(float) vertices[0].x(0), (float) vertices[0].x(1),
(float) vertices[0].x(2)), new Point3f(
(float) vertices[1].x(0), (float) vertices[1].x(1),
(float) vertices[1].x(2)));
if (displayBox.getShowBoundary() == true) {
gsys.addFig(polytopeLines[i]);
}
}
oldPolytope = polytope;
} else {
LineSegment[] lines = polytope.getEdges();
for (int i = 0; i < lines.length; i++) {
IVector[] vertices = lines[i].getVertices();
polytopeLines[i].setStart((float) vertices[0].x(0),
(float) vertices[0].x(1), (float) vertices[0].x(2));
polytopeLines[i].setEnd((float) vertices[1].x(0),
(float) vertices[1].x(1), (float) vertices[1].x(2));
if (displayBox.getShowBoundary() == false
&& boundaryDisplayed == true) {
gsys.removeFig(polytopeLines[i]);
} else if (displayBox.getShowBoundary() == true
&& boundaryDisplayed == false) {
gsys.addFig(polytopeLines[i]);
}
}
}
if (displayBox.getShowBoundary() == false) {
boundaryDisplayed = false;
} else {
boundaryDisplayed = true;
}
// set boundary vectors for image shell
int n=0;
for (int i=0; i<space.D(); i++) {
if (boundary.getPeriodicity(i)) {
n++;
}
}
double[] dvecs = new double[n * 3]; // assuming
// 3-dimensional vectors
int j = 0;
for (int i = 0; i < space.D(); i++) {
IVector v = boundary.getEdgeVector(i);
if (!boundary.getPeriodicity(i)) {
continue;
}
dvecs[j * 3] = v.x(0);
dvecs[j * 3 + 1] = v.x(1);
dvecs[j * 3 + 2] = v.x(2);
j++;
}
gsys.setBoundaryVectors(dvecs);
}
IVector bounds = boundary.getDimensions();
gsys.setBoundingBox((float) (-bounds.x(0) * 0.5),
(float) (-bounds.x(1) * 0.5), (float) (-bounds.x(2) * 0.5),
(float) (bounds.x(0) * 0.5), (float) (bounds.x(1) * 0.5),
(float) (bounds.x(2) * 0.5));
// If displaying a new box, make it fit on the screen
if(initialOrient == true) {
gsys.scaleFitToScreen();
initialOrient = false;
}
gsys.fastRefresh();
}
public void addPlane(Plane newPlane) {
planes = (Plane[])Arrays.addObject(planes, newPlane);
planeTriangles = (Triangle[][])Arrays.addObject(planeTriangles, new Triangle[0]);
}
public void removePlane(Plane oldPlane) {
for (int i=0; i<planes.length; i++) {
if (planes[i] == oldPlane) {
for (int j=0; j<planeTriangles[i].length; j++) {
gsys.removeFig(planeTriangles[i][j]);
}
planeTriangles = (Triangle[][])Arrays.removeObject(planeTriangles, planeTriangles[i]);
planes = (Plane[])Arrays.removeObject(planes, oldPlane);
return;
}
}
throw new RuntimeException("I don't know about that plane");
}
public synchronized void drawPlane(int iPlane) {
IBoundary boundary = displayBox.getBox().getBoundary();
if(!(boundary instanceof Boundary)) {
throw new RuntimeException("Unable to drawPlane for a Boundary not a subclass of etomica.space.Boundary");
}
Plane plane = planes[iPlane];
Polytope polytope = ((Boundary)boundary).getShape();
LineSegment[] lines = polytope.getEdges();
int intersectionCount = 0;
for (int i = 0; i < lines.length; i++) {
IVector[] vertices = lines[i].getVertices();
work.Ev1Mv2(vertices[1], vertices[0]);
// this happens to do what we want
double alpha = -plane.distanceTo(vertices[0]) /
(plane.distanceTo(work) - plane.getD());
if (alpha >= 0 && alpha <= 1) {
IVectorMutable newIntersection;
if (planeIntersections.length == intersectionCount) {
newIntersection = space.makeVector();
planeIntersections = (IVectorMutable[])Arrays.addObject(planeIntersections, newIntersection);
}
else {
newIntersection = planeIntersections[intersectionCount];
}
intersectionCount++;
newIntersection.E(vertices[0]);
newIntersection.PEa1Tv1(alpha, work);
}
}
if (intersectionCount < 3) {
for (int i=0; i<planeTriangles[iPlane].length; i++) {
gsys.removeFig(planeTriangles[iPlane][i]);
}
planeTriangles[iPlane] = new Triangle[0];
return;
}
//find the center of the polygon
work.E(0);
for (int i=0; i<intersectionCount; i++) {
work.PE(planeIntersections[i]);
}
work.TE(1.0/intersectionCount);
// convert the vertices to be vectors from the center
// we'll switch back later
for (int i=0; i<intersectionCount; i++) {
planeIntersections[i].ME(work);
}
if (planeAngles.length < intersectionCount-1) {
planeAngles = new double[intersectionCount-1];
}
work2.E(planeIntersections[0]);
work2.XE(planeIntersections[1]);
for (int i=1; i<intersectionCount; i++) {
// If you understood this without reading this comment, I'll be
// impressed. The purpose here is to put the array of
// intersections in order such that they form a polygon and lines
// drawn between consecutive points don't intersect. So we
// calculate the angle between the first polygon point (which is
// arbitrary), the center and each other point. And we sort the
// points by that angle. We check the cross product so we can
// distinguish 30 degrees from 330 degrees.
double dot = planeIntersections[0].dot(planeIntersections[i]);
double angle = Math.acos(dot / Math.sqrt(planeIntersections[0].squared() * planeIntersections[i].squared()));
work3.E(planeIntersections[0]);
work3.XE(planeIntersections[i]);
// work2 dot work3 should be |work2|^2 or -|work2|^2. Positive
// indicates the angle is <180, negative indicates >180.
if (work3.dot(work2) < 0) {
angle = 2*Math.PI - angle;
}
boolean success = false;
for (int j=1; j<i; j++) {
if (angle < planeAngles[j-1]) {
// insert the i point at position j, shift existing points
IVectorMutable intersection = planeIntersections[i];
for (int k=i; k>j; k
planeAngles[k-1] = planeAngles[k-2];
planeIntersections[k] = planeIntersections[k-1];
}
planeIntersections[j] = intersection;
planeAngles[j-1] = angle;
success = true;
break;
}
}
if (!success) {
planeAngles[i-1] = angle;
}
}
// we need N-2 triangles
while (intersectionCount < planeTriangles[iPlane].length+2) {
Triangle triangle = planeTriangles[iPlane][planeTriangles[iPlane].length-1];
gsys.removeFig(planeTriangles[iPlane][planeTriangles[iPlane].length-1]);
planeTriangles[iPlane] = (Triangle[])Arrays.removeObject(planeTriangles[iPlane], triangle);
}
while (intersectionCount > planeTriangles[iPlane].length+2) {
planeTriangles[iPlane] = (Triangle[])Arrays.addObject(planeTriangles[iPlane], new Triangle(
gsys, Graphics3D.getColixTranslucent(G3DSys.getColix(planeColor), true, 0.5f), new Point3f(), new Point3f(), new Point3f()));
gsys.addFig(planeTriangles[iPlane][planeTriangles[iPlane].length-1]);
}
for (int i=0; i<intersectionCount; i++) {
planeIntersections[i].PE(work);
}
for (int i=0; i<planeTriangles[iPlane].length; i++) {
Triangle triangle = planeTriangles[iPlane][i];
Point3f p = triangle.getVertex1();
p.x = (float)planeIntersections[0].x(0);
p.y = (float)planeIntersections[0].x(1);
p.z = (float)planeIntersections[0].x(2);
p = triangle.getVertex2();
p.x = (float)planeIntersections[i+1].x(0);
p.y = (float)planeIntersections[i+1].x(1);
p.z = (float)planeIntersections[i+1].x(2);
p = triangle.getVertex3();
p.x = (float)planeIntersections[i+2].x(0);
p.y = (float)planeIntersections[i+2].x(1);
p.z = (float)planeIntersections[i+2].x(2);
}
}
/**
* Add a bond to the graphical display between the given pairs. The given
* bondType is used to decide how the bond should be drawn.
*/
public Object makeBond(IAtomList pair, Object bondType) {
/*
* Ball objects here could be null if the bond is created before the
* atoms have been added. Check for this and store atoms locally in a
* list. In doPaint check list for pending additions and add them.
*/
// bondType is a potential right now
// best to ignore it for now; all bonds are equal
Ball ball0 = (Ball) aam.getAgent(pair.getAtom(0));
Ball ball1 = (Ball) aam.getAgent(pair.getAtom(1));
if (ball0 == null || ball1 == null) {
System.out.println("NULL!!!");
pendingBonds.add(new Object[] { ball0, ball1, bondType });
return null;
}
// make a bond object (Figure)
Figure f = new Bond(gsys, ball0, ball1);
gsys.addFig(f);
return f;
}
private java.util.ArrayList<Object[]> pendingBonds = new java.util.ArrayList<Object[]>();
/**
* Removes the given bond from the graphical display. The bond must be an
* Object returned by the makeBond method.
*/
public void releaseBond(Object bond) {
Figure figure = (Figure) bond;
if (figure.getID() == -1) {
throw new RuntimeException(figure + " has already been removed");
}
gsys.removeFig(figure);
}
public Class getAgentClass() {
return Figure.class;
}
public Object makeAgent(IAtom a) {
if (!(a.getType() instanceof IAtomTypeSphere))
return null;
((IAtomPositioned) a).getPosition().assignTo(coords);
float diameter = (float) ((IAtomTypeSphere) a.getType()).getDiameter();
Ball newBall = new Ball(gsys, G3DSys.getColix((displayBox
.getColorScheme().getAtomColor(a))), (float) coords[0],
(float) coords[1], (float) coords[2], diameter);
gsys.addFig(newBall);
return newBall;
}
public void releaseAgent(Object agent, IAtom atom) {
gsys.removeFig((Figure) agent);
}
/**
* Set slab percentage
*
* @param slab
* the slab percentage to set
*/
public void setSlab(double slab) {
gsys.setSlabPercent((int) slab);
}
/**
* Get depth percentage
*
* @return returns current depth percentage
*/
public double getSlab() {
return gsys.getSlabPercent();
}
/**
* Set depth percentage
*
* @param depth
* the depth percentage to set
*/
public void setDepth(double depth) {
gsys.setDepthPercent((int) depth);
}
/**
* Get depth percentage
*
* @return returns current depth percentage
*/
public double getDepth() {
return gsys.getDepthPercent();
}
public void stopRotate() {
gsys.stopRotation();
}
/**
* Wraps an etomica index iterator in an equivalent g3dsys interface for
* transport; removes g3dsys dependency from all but the etomica.graphics
* package.
*
* @param iter
* the etomica index iterator to wrap
* @return returns the g3dsys index iterator
*/
private g3dsys.control.IndexIterator wrapIndexIterator(
etomica.lattice.IndexIteratorSizable iter) {
final etomica.lattice.IndexIteratorSizable i = iter;
return new g3dsys.control.IndexIterator() {
private etomica.lattice.IndexIteratorSizable ii = i;
public int getD() {
return ii.getD();
}
public boolean hasNext() {
return ii.hasNext();
}
public int[] next() {
return ii.next();
}
public void reset() {
ii.reset();
}
public void setSize(int[] size) {
ii.setSize(size);
}
public boolean isLazySafe() {
/*
* For now all boundaries are lazy-safe, including truncated
* octahedron. If this changes, check for that boundary type
* here (instanceof IndexIteratorSequentialFiltered, say, after
* making the class public) and use appropriate boolean.
*/
return true;
}
};
}
}
|
package etomica.integrator.mcmove;
import java.io.Serializable;
import etomica.api.IBox;
import etomica.api.IRandom;
public class MCMoveManager implements Serializable {
public MCMoveManager(IRandom random) {
this.random = random;
}
/**
* Sets moves in given array to be integrator's set of moves, deleting any
* existing moves.
*/
public void setMCMoves(MCMove[] moves) {
firstMoveLink = null;
moveCount = 0;
for (int i = 0; i < moves.length; i++) {
addMCMove(moves[i]);
}
}
/**
* Constructs and returns array of all moves added to the integrator.
*/
public MCMove[] getMCMoves() {
MCMove[] moves = new MCMove[moveCount];
int i = 0;
for (MCMoveLinker link = firstMoveLink; link != null; link = link.nextLink) {
moves[i++] = link.move;
}
return moves;
}
/**
* Adds the given MCMove to the set of moves performed by the integrator and
* recalculates move frequencies. If the MCMoveManager has been given a
* Box, the MCMove added here must be of type MCMoveBox.
*
* @throws ClassCastException if this MCMoveManager has a Box and the
* given MCMove is not an MCMoveBox
*/
public void addMCMove(MCMove move) {
//make sure move wasn't added already
for (MCMoveLinker link = firstMoveLink; link != null; link = link.nextLink) {
if (move == link.move)
return;
}
if (firstMoveLink == null) {
firstMoveLink = new MCMoveLinker(move);
lastMoveLink = firstMoveLink;
} else {
lastMoveLink.nextLink = new MCMoveLinker(move);
lastMoveLink = lastMoveLink.nextLink;
}
MCMoveTracker tracker = move.getTracker();
if (tracker instanceof MCMoveStepTracker) {
((MCMoveStepTracker)tracker).setTunable(isEquilibrating);
}
if (box != null) {
((MCMoveBox)move).setBox(box);
}
moveCount++;
recomputeMoveFrequencies();
}
/**
* Removes the given MCMove from the set of moves performed by the integrator and
* recalculates move frequencies. Returns false if the move was not used by
* the integrator.
*/
public boolean removeMCMove(MCMove move) {
//make sure move wasn't added already
if (move == firstMoveLink.move) {
firstMoveLink = firstMoveLink.nextLink;
moveCount
recomputeMoveFrequencies();
return true;
}
for (MCMoveLinker link = firstMoveLink; link.nextLink != null; link = link.nextLink) {
if (move == link.nextLink.move) {
if (link.nextLink == lastMoveLink) {
lastMoveLink = link;
}
link.nextLink = link.nextLink.nextLink;
moveCount
recomputeMoveFrequencies();
return true;
}
}
return false;
}
/**
* Invokes superclass method and informs all MCMoves about the new box.
* The moves are assumed to all be of type MCMoveBox.
*
* @throws ClassCastException if any move is not an MCMoveBox
*/
public void setBox(IBox p) {
box = p;
for (MCMoveLinker link = firstMoveLink; link != null; link = link.nextLink) {
((MCMoveBox)link.move).setBox(box);
}
}
/**
* @return Returns the box.
*/
public IBox getBox() {
return box;
}
/**
* Selects a MCMove instance from among those added to the integrator, with
* probability in proportion to the frequency value assigned to the move.
*/
public MCMove selectMove() {
if (firstMoveLink == null || frequencyTotal == 0) {
selectedLink = null;
return null;
}
int i = random.nextInt(frequencyTotal);
selectedLink = firstMoveLink;
while ((i -= selectedLink.fullFrequency) >= 0) {
selectedLink = selectedLink.nextLink;
}
selectedLink.selectionCount++;
return selectedLink.move;
}
public MCMove getSelectedMove() {
return selectedLink.move;
}
/**
* Recomputes all the move frequencies.
*/
public void recomputeMoveFrequencies() {
frequencyTotal = 0;
for (MCMoveLinker link = firstMoveLink; link != null; link = link.nextLink) {
link.resetFullFrequency();
frequencyTotal += link.fullFrequency;
}
}
public void setEquilibrating(boolean equilibrating) {
isEquilibrating = equilibrating;
for (MCMoveLinker link = firstMoveLink; link != null; link = link.nextLink) {
MCMoveTracker tracker = link.move.getTracker();
if (tracker instanceof MCMoveStepTracker) {
((MCMoveStepTracker)tracker).setTunable(isEquilibrating);
}
}
}
/**
* Returns the trial frequency set for the given move, over and above the
* move's nominal frequency. The frequency is 1.0 by default.
*
* This method should not be called with a move not contained by this
* manager.
*/
public double getFrequency(MCMove move) {
for (MCMoveLinker link = firstMoveLink; link != null; link = link.nextLink) {
if (link.move == move) {
return link.frequency;
}
}
throw new IllegalArgumentException("I don't have "+move);
}
/**
* Sets the trial frequency for the given move to the given frequency. The
* frequency is used in conjunction with the move's own nominal frequency.
*
* This method should not be called with a move not contained by this
* manager.
*/
public void setFrequency(MCMove move, double newFrequency) {
for (MCMoveLinker link = firstMoveLink; link != null; link = link.nextLink) {
if (link.move == move) {
link.frequency = newFrequency;
recomputeMoveFrequencies();
return;
}
}
throw new IllegalArgumentException("I don't have "+move);
}
private static final long serialVersionUID = 1L;
private IBox box;
private MCMoveLinker firstMoveLink, lastMoveLink;
private MCMoveLinker selectedLink;
private int frequencyTotal;
private int moveCount;
private boolean isEquilibrating = true;
private final IRandom random;
/**
* Linker used to construct linked-list of MCMove instances
*/
private static class MCMoveLinker implements java.io.Serializable {
private static final long serialVersionUID = 1L;
int fullFrequency;
double frequency;
final MCMove move;
int selectionCount;
MCMoveLinker nextLink;
MCMoveLinker(MCMove move) {
this.move = move;
frequency = 1.0;
}
/**
* Updates the full frequency based on the current value of the
* frequency, the status of the perParticleFrequency flag, and the
* current number of molecules in the boxes affected by the move.
*/
void resetFullFrequency() {
fullFrequency = (int)Math.round(frequency * move.getNominalFrequency());
if ((move instanceof MCMoveBox) && ((MCMoveBox)move).getBox() != null
&& ((MCMoveBox)move).isNominallyPerParticleFrequency() ) {
fullFrequency *= ((MCMoveBox)move).getBox().getMoleculeList().getMoleculeCount();
}
}
}
}
|
package mobi.hsz.idea.gitignore.ui;
import com.intellij.application.options.colors.NewColorAndFontPanel;
import com.intellij.ide.DataManager;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.command.CommandProcessor;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.EditorFactory;
import com.intellij.openapi.editor.event.DocumentEvent;
import com.intellij.openapi.editor.event.DocumentListener;
import com.intellij.openapi.options.SearchableConfigurable;
import com.intellij.openapi.options.newEditor.OptionsEditor;
import com.intellij.openapi.ui.InputValidatorEx;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.ui.Splitter;
import com.intellij.openapi.util.ActionCallback;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.ui.AddEditDeleteListPanel;
import com.intellij.ui.components.JBLabel;
import com.intellij.ui.components.JBPanel;
import com.intellij.ui.components.labels.LinkLabel;
import com.intellij.ui.components.labels.LinkListener;
import com.intellij.util.containers.ContainerUtil;
import mobi.hsz.idea.gitignore.IgnoreBundle;
import mobi.hsz.idea.gitignore.settings.IgnoreSettings;
import mobi.hsz.idea.gitignore.util.Utils;
import mobi.hsz.idea.gitignore.vcs.IgnoreFileStatusProvider;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import java.awt.*;
import java.util.ArrayList;
import java.util.List;
/**
* UI form for {@link IgnoreSettings} edition.
*
* @author Jakub Chrzanowski <jakub@hsz.mobi>
* @since 0.6.1
*/
public class IgnoreSettingsPanel implements Disposable {
private static final String FILE_STATUS_CONFIGURABLE_ID = "reference.settingsdialog.IDE.editor.colors.File Status";
/** The parent panel for the form. */
public JPanel panel;
/** Form element for {@link IgnoreSettings#missingGitignore}. */
public JCheckBox missingGitignore;
/** Templates list panel. */
public TemplatesListPanel templatesListPanel;
/** Enable ignored file status coloring. */
public JCheckBox ignoredFileStatus;
/** Enable outer ignore rules. */
public JCheckBox outerIgnoreRules;
/** Splitter element. */
private Splitter templatesSplitter;
/** Link to the Colors & Fonts settings. */
private JLabel editIgnoredFilesTextLabel;
/** Editor panel element. */
private EditorPanel editorPanel;
/** Create UI components. */
private void createUIComponents() {
templatesListPanel = new TemplatesListPanel();
editorPanel = new EditorPanel();
editorPanel.setPreferredSize(new Dimension(Integer.MAX_VALUE, 200));
templatesSplitter = new Splitter(false, 0.3f);
templatesSplitter.setFirstComponent(templatesListPanel);
templatesSplitter.setSecondComponent(editorPanel);
editIgnoredFilesTextLabel = new LinkLabel(IgnoreBundle.message("settings.general.ignoredColor"), null, new LinkListener() {
@Override
public void linkSelected(LinkLabel aSource, Object aLinkData) {
final OptionsEditor optionsEditor = OptionsEditor.KEY.getData(DataManager.getInstance().getDataContext(panel));
if (optionsEditor != null) {
final SearchableConfigurable configurable = optionsEditor.findConfigurableById(FILE_STATUS_CONFIGURABLE_ID);
if (configurable != null) {
final NewColorAndFontPanel colorAndFontPanel = ((NewColorAndFontPanel) configurable.createComponent());
ActionCallback callback = optionsEditor.select(configurable);
if (colorAndFontPanel != null) {
final Runnable showOption = colorAndFontPanel.showOption(IgnoreFileStatusProvider.IGNORED.getId());
if (showOption != null) {
callback.doWhenDone(showOption);
}
}
}
}
}
});
editIgnoredFilesTextLabel.setBorder(BorderFactory.createEmptyBorder(0, 26, 0, 0));
}
@Override
public void dispose() {
if (!editorPanel.preview.isDisposed()) {
EditorFactory.getInstance().releaseEditor(editorPanel.preview);
}
}
/**
* Extension for the CRUD list panel.
*/
public class TemplatesListPanel extends AddEditDeleteListPanel<IgnoreSettings.UserTemplate> {
/** Constructs CRUD panel with list listener for editor updating. */
public TemplatesListPanel() {
super(null, ContainerUtil.<IgnoreSettings.UserTemplate>newArrayList());
myList.addListSelectionListener(new ListSelectionListener() {
@Override
public void valueChanged(ListSelectionEvent e) {
boolean enabled = myListModel.size() > 0;
editorPanel.setEnabled(enabled);
if (enabled) {
IgnoreSettings.UserTemplate template = getCurrentItem();
editorPanel.setContent(template != null ? template.getContent() : "");
}
}
});
}
/**
* Opens edit dialog for new template.
*
* @return template
*/
@Nullable
@Override
protected IgnoreSettings.UserTemplate findItemToAdd() {
return showEditDialog(new IgnoreSettings.UserTemplate());
}
/**
* SHows edit dialog and validates user's input name.
*
* @param initialValue template
* @return modified template
*/
@Nullable
private IgnoreSettings.UserTemplate showEditDialog(@NotNull final IgnoreSettings.UserTemplate initialValue) {
String name = Messages.showInputDialog(this,
IgnoreBundle.message("settings.userTemplates.dialogDescription"),
IgnoreBundle.message("settings.userTemplates.dialogTitle"),
Messages.getQuestionIcon(), initialValue.getName(), new InputValidatorEx() {
/**
* Checks whether the <code>inputString</code> is valid. It is invoked each time
* input changes.
*
* @param inputString the input to check
* @return true if input string is valid
*/
@Override
public boolean checkInput(String inputString) {
return !StringUtil.isEmpty(inputString);
}
/**
* This method is invoked just before message dialog is closed with OK code.
* If <code>false</code> is returned then then the message dialog will not be closed.
*
* @param inputString the input to check
* @return true if the dialog could be closed, false otherwise.
*/
@Override
public boolean canClose(String inputString) {
return !StringUtil.isEmpty(inputString);
}
/**
* Returns error message depending on the input string.
*
* @param inputString the input to check
* @return error text
*/
@Nullable
@Override
public String getErrorText(String inputString) {
if (!checkInput(inputString)) {
return IgnoreBundle.message("settings.userTemplates.dialogError");
}
return null;
}
});
if (name != null) {
initialValue.setName(name);
}
return initialValue.isEmpty() ? null : initialValue;
}
/**
* Fills list element with given templates list.
*
* @param userTemplates templates list
*/
public void resetFrom(List<IgnoreSettings.UserTemplate> userTemplates) {
myListModel.clear();
for (IgnoreSettings.UserTemplate template : userTemplates) {
myListModel.addElement(new IgnoreSettings.UserTemplate(template.getName(), template.getContent()));
}
}
/**
* Edits given template.
*
* @param item template
* @return modified template
*/
@Override
protected IgnoreSettings.UserTemplate editSelectedItem(IgnoreSettings.UserTemplate item) {
return showEditDialog(item);
}
/**
* Returns current templates list.
*
* @return templates list
*/
public List<IgnoreSettings.UserTemplate> getList() {
ArrayList<IgnoreSettings.UserTemplate> list = ContainerUtil.newArrayList();
for (int i = 0; i < myListModel.size(); i++) {
list.add((IgnoreSettings.UserTemplate) myListModel.getElementAt(i));
}
return list;
}
/**
* Updates editor component with given content.
*
* @param content new content
*/
public void updateContent(String content) {
IgnoreSettings.UserTemplate template = getCurrentItem();
if (template != null) {
template.setContent(content);
}
}
/**
* Returns currently selected template.
*
* @return template or null if none selected
*/
@Nullable
public IgnoreSettings.UserTemplate getCurrentItem() {
int index = myList.getSelectedIndex();
if (index == -1) {
return null;
}
return (IgnoreSettings.UserTemplate) myListModel.get(index);
}
}
/**
* Editor panel class that displays document editor or label if no template is selected.
*/
private class EditorPanel extends JBPanel {
private final Editor preview;
private final JBLabel label;
private final Document previewDocument;
/**
* Constructor that creates document editor, empty content label.
*/
public EditorPanel() {
super(new BorderLayout());
this.previewDocument = EditorFactory.getInstance().createDocument("");
this.label = new JBLabel(IgnoreBundle.message("settings.userTemplates.noTemplateSelected"), JBLabel.CENTER);
this.preview = Utils.createPreviewEditor(previewDocument, null, false);
this.preview.getDocument().addDocumentListener(new DocumentListener() {
@Override
public void beforeDocumentChange(DocumentEvent event) {
}
@Override
public void documentChanged(DocumentEvent event) {
templatesListPanel.updateContent(event.getDocument().getText());
}
});
setEnabled(false);
}
/**
* Shows or hides label and editor.
*
* @param enabled if true shows editor, else shows label
*/
public void setEnabled(boolean enabled) {
if (enabled) {
remove(this.label);
add(this.preview.getComponent());
} else {
add(this.label);
remove(this.preview.getComponent());
}
revalidate();
repaint();
}
/**
* Sets new content to the editor component.
*
* @param content new content
*/
public void setContent(@NotNull final String content) {
ApplicationManager.getApplication().runWriteAction(new Runnable() {
@Override
public void run() {
CommandProcessor.getInstance().runUndoTransparentAction(new Runnable() {
@Override
public void run() {
previewDocument.replaceString(0, previewDocument.getTextLength(), content);
}
});
}
});
}
}
}
|
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
import javax.swing.JPanel;
import javax.swing.JTable;
import javax.swing.JOptionPane;
import java.awt.GridBagLayout;
import java.awt.GridBagConstraints;
import javax.swing.BorderFactory;
import java.io.Serializable;
/**
* The entry point and glue code for the game. It also contains some helpful
* global utility methods.
* @author Geoffrey Washburn <<a href="mailto:geoffw@cis.upenn.edu">geoffw@cis.upenn.edu</a>>
* @version $Id: Mazewar.java 371 2004-02-10 21:55:32Z geoffw $
*/
public class Mazewar extends JFrame {
/**
* The default width of the {@link Maze}.
*/
private final int mazeWidth = 20;
/**
* The default height of the {@link Maze}.
*/
private final int mazeHeight = 10;
/**
* The default random seed for the {@link Maze}.
* All implementations of the same protocol must use
* the same seed value, or your mazes will be different.
*/
private final int mazeSeed = 42;
/**
* The {@link Maze} that the game uses.
*/
private Maze maze = null;
/**
* The {@link GUIClient} for the game.
*/
private GUIClient guiClient = null;
/**
* The panel that displays the {@link Maze}.
*/
private OverheadMazePanel overheadPanel = null;
/**
* The table the displays the scores.
*/
private JTable scoreTable = null;
/**
* Create the textpane statically so that we can
* write to it globally using
* the static consolePrint methods
*/
private static final JTextPane console = new JTextPane();
/**
* Write a message to the console followed by a newline.
* @param msg The {@link String} to print.
*/
public static synchronized void consolePrintLn(String msg) {
console.setText(console.getText()+msg+"\n");
}
/**
* Write a message to the console.
* @param msg The {@link String} to print.
*/
public static synchronized void consolePrint(String msg) {
console.setText(console.getText()+msg);
}
/**
* Clear the console.
*/
public static synchronized void clearConsole() {
console.setText("");
}
/**
* Static method for performing cleanup before exiting the game.
*/
public static void quit() {
// Put any network clean-up code you might have here.
// (inform other implementations on the network that you have
// left, etc.)
System.exit(0);
}
/**
* The place where all the pieces are put together.
*/
public Mazewar(String host, int port_num) {
super("ECE419 Mazewar");
consolePrintLn("ECE419 Mazewar started!");
// Create the maze
maze = new MazeImpl(new Point(mazeWidth, mazeHeight), mazeSeed);
assert(maze != null);
// Have the ScoreTableModel listen to the maze to find
// out how to adjust scores.
ScoreTableModel scoreModel = new ScoreTableModel();
assert(scoreModel != null);
maze.addMazeListener(scoreModel);
// Throw up a dialog to get the GUIClient name.
String name = JOptionPane.showInputDialog("Enter your name");
if((name == null) || (name.length() == 0)) {
Mazewar.quit();
}
// Connect local client to the server, and obtain info about remote clients from the server
int NumPlayers = 3; // Total number of other players needed to play the Mazewar game
//Create an array of RemoteClients to add remote players into the maze
RemoteClient[] RemotePlayers = new RemoteClient[NumPlayers];
int NumConnected = 0; // Number of other players connected to the Mazewar server
String serv_hostname = host; // Machine that hosts the server
int serv_port = port_num; // Port number of the server
// Initialise a socket that listens for player details from the server
Socket PlayerSock = new Socket(serv_hostname, serv_port);
// Input and output streams for the socket
ObjectInputStream FromServ = new ObjectInputStream(PlayerSock.getInputStream());
ObjectOutputStream ToServ = new ObjectOutputStream(PlayerSock.getOutputStream());
// Packet that will contain info about a player connecting to the server
MazewarPacket PackFromServ;
// Packet that will contain info about local client to be sent to the server and other clients
// NOTE: MazewarPacket may be altered, so make changes to this when MazewarPacket is modified
MazewarPacket PackToServ = new MazewarPacket();
// Create the GUIClient
guiClient = new GUIClient(name,host,port_num);
maze.addClient(guiClient);
this.addKeyListener(guiClient);
// Set the fields for the PackToServ packet
PackToServ.Player = guiClient.getName();
PackToServ.StartPoint = guiClient.getPoint();
PackToServ.dir = guiClient.getOrientation();
PackToServ.type = MazewarPacket.MW_JOIN;
// Send out the packet containing the local client's info to the server
ToServ.writeObject(PackToServ);
while((NumConnected < NumPlayers) && ((PackFromServ = (MazewarPacket) FromServ.readObject()) != null)){
if(PackFromServ.type == MazewarPacket.MW_JOIN && PackFromServ.Player != guiClient.getName()){
RemotePlayers[NumConnected] = new RemoteClient(PackFromServ.Player);
maze.addClient(RemotePlayers[NumConnected]);
this.addKeyListener(RemotePlayers[NumConnected]);
NumConnected++;
continue;
}
else if(PackFromServ.type = MazewarPaccket.MW_START){
break;
}
}
//Perform some cleanup
PlayerSock.close();
FromServ.close();
ToServ.close();
// Use braces to force constructors not to be called at the beginning of the
// constructor.
/*{
maze.addClient(new RobotClient("Norby"));
maze.addClient(new RobotClient("Robbie"));
maze.addClient(new RobotClient("Clango"));
maze.addClient(new RobotClient("Marvin"));
}*/
// Create the panel that will display the maze.
overheadPanel = new OverheadMazePanel(maze, guiClient);
assert(overheadPanel != null);
maze.addMazeListener(overheadPanel);
// Don't allow editing the console from the GUI
console.setEditable(false);
console.setFocusable(false);
console.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder()));
// Allow the console to scroll by putting it in a scrollpane
JScrollPane consoleScrollPane = new JScrollPane(console);
assert(consoleScrollPane != null);
consoleScrollPane.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(), "Console"));
// Create the score table
scoreTable = new JTable(scoreModel);
assert(scoreTable != null);
scoreTable.setFocusable(false);
scoreTable.setRowSelectionAllowed(false);
// Allow the score table to scroll too.
JScrollPane scoreScrollPane = new JScrollPane(scoreTable);
assert(scoreScrollPane != null);
scoreScrollPane.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(), "Scores"));
// Create the layout manager
GridBagLayout layout = new GridBagLayout();
GridBagConstraints c = new GridBagConstraints();
getContentPane().setLayout(layout);
// Define the constraints on the components.
c.fill = GridBagConstraints.BOTH;
c.weightx = 1.0;
c.weighty = 3.0;
c.gridwidth = GridBagConstraints.REMAINDER;
layout.setConstraints(overheadPanel, c);
c.gridwidth = GridBagConstraints.RELATIVE;
c.weightx = 2.0;
c.weighty = 1.0;
layout.setConstraints(consoleScrollPane, c);
c.gridwidth = GridBagConstraints.REMAINDER;
c.weightx = 1.0;
layout.setConstraints(scoreScrollPane, c);
// Add the components
getContentPane().add(overheadPanel);
getContentPane().add(consoleScrollPane);
getContentPane().add(scoreScrollPane);
// Pack everything neatly.
pack();
// Let the magic begin.
setVisible(true);
overheadPanel.repaint();
this.requestFocusInWindow();
}
/**
* Entry point for the game.
* @param args Command-line arguments.
*/
public static void main(String args[]) {
String hostname;
int port;
if(args.length == 2){
hostname = args[0];
port = Integer.parseInt(args[1]);
}
/* Create the GUI */
new Mazewar(hostname,port);
}
}
|
package meizhuo.org.lightmeeting.model;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONObject;
import com.google.gson.Gson;
@SuppressWarnings("serial")
public class Member implements Serializable{
/**
*
* @param json
* @return
*/
public static Member create_by_json(String json){
try {
Gson gson = new Gson();
return (Member)gson.fromJson(json, Member.class);
} catch (Exception e) {
// TODO: handle exception
return null;
}
}
/**
*
* @param jsonarray
* @return
*/
public static List<Member>create_by_jsonarray(String jsonarray){
List<Member>list = new ArrayList<Member>();
JSONObject obj = null;
JSONArray array = null;
try {
obj = new JSONObject(jsonarray);
array = obj.getJSONArray("response");
for(int i=0 ; i<array.length();i++)
{
list.add(create_by_json(array.getJSONObject(i).toString()));
}
} catch (Exception e) {
// TODO: handle exception
list = null;
}
return list;
}
@Override
public String toString() {
return "Member [id=" + id + ", username=" + username + ", nickname="
+ nickname + ", sex=" + sex + ", company=" + company
+ ", position=" + position + ", phone=" + phone + ", email="
+ email + ", birth=" + birth + ", ctime=" + ctime
+ ", lasttime=" + lasttime + ", stime=" + stime + ", checkin="
+ checkin + ", checkin_time=" + checkin_time + "]";
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getNickname() {
return nickname;
}
public void setNickname(String nickname) {
this.nickname = nickname;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getCompany() {
return company;
}
public void setCompany(String company) {
this.company = company;
}
public String getPosition() {
return position;
}
public void setPosition(String position) {
this.position = position;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getBirth() {
return birth;
}
public void setBirth(String birth) {
this.birth = birth;
}
public String getCtime() {
return ctime;
}
public void setCtime(String ctime) {
this.ctime = ctime;
}
public String getLasttime() {
return lasttime;
}
public void setLasttime(String lasttime) {
this.lasttime = lasttime;
}
public String getStime() {
return stime;
}
public void setStime(String stime) {
this.stime = stime;
}
public String getCheckin() {
return checkin;
}
public void setCheckin(String checkin) {
this.checkin = checkin;
}
public String getCheckin_time() {
return checkin_time;
}
public void setCheckin_time(String checkin_time) {
this.checkin_time = checkin_time;
}
private String id;
private String username;
private String nickname;
private String sex;
private String company;
private String position;
private String phone;
private String email;
private String birth;
/**ctime*/
private String ctime;
private String lasttime;
private String stime;
/** 0 1*/
private String checkin;
private String checkin_time;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.