answer
stringlengths 17
10.2M
|
|---|
/*
* $Id: PortlandPressArticleIteratorFactory.java,v 1.4 2013-10-02 19:15:14 etenbrink Exp $
*/
package org.lockss.plugin.portlandpress;
import java.util.Iterator;
import java.util.regex.*;
import org.lockss.daemon.*;
import org.lockss.extractor.*;
import org.lockss.plugin.*;
import org.lockss.util.Logger;
public class PortlandPressArticleIteratorFactory
implements ArticleIteratorFactory,
ArticleMetadataExtractorFactory {
protected static Logger log =
Logger.getLogger("PortlandPressArticleIteratorFactory");
protected static final String ROOT_TEMPLATE =
"\"%s%s/%s/\", base_url, journal_id, volume_name";
// pick up the abstract as the logical definition of one article
// - lives one level higher than pdf & fulltext
// pick up <lettersnums>.htm, but not <lettersnums>add.htm
protected static final String PATTERN_TEMPLATE =
"\"^%s%s/%s/(?![^/]+add[.]htm)%.3s[^/]+[.]htm\", " +
"base_url,journal_id, volume_name, journal_id";
@Override
public Iterator<ArticleFiles> createArticleIterator(ArchivalUnit au,
MetadataTarget target)
throws PluginException {
SubTreeArticleIteratorBuilder builder = new SubTreeArticleIteratorBuilder(au);
/*
* Article lives at three locations:
* <baseurl>/<jid>/<volnum>/ : Abstract
* <lettersnums>.htm
* <lettersnums>add.htm - supplementary stuff
* <lettersnums>add.mov - ex - quicktime movie
* <lettersnums>add.pdf - ex - online data
* <base-url>/<jid>/<volnum>/startpagenum/ : PDF & legacy html
* <lettersnums>.htm
* <lettersnums>.pdf (note that pdf filename does not start with jid)
* <base-url>/<jid>/ev/<volnum>/<stpage> : Enhanced full text version
* <lettersnums_ev.htm>
* notes: startpagenum can have letters in it
* lettersnums seems to be concatenated <jid{max 3 chars}><volnum><startpagenum>
* except for pdf which is <volnum><startpagenum>
*/
// various aspects of an article
// Identify groups in the pattern "/(<jid>)/(<volnum>)/(<articlenum>).htm
// articlenum is <jid><volnum><pageno> and we need pageno to find the content files
final Pattern ABSTRACT_PATTERN = Pattern.compile(
"/([^/]{1,3})([^/]*)/([^/]+)/\\1\\3([^/]+)[.]htm$", Pattern.CASE_INSENSITIVE);
final Pattern HTML_PATTERN = Pattern.compile(
"/([^/]{1,3})([^/]*)/([^/]+)/([^/]+)/\\1\\3\\4[.]htm$", Pattern.CASE_INSENSITIVE);
final Pattern PDF_PATTERN = Pattern.compile(
"/([^/]{1,3})([^/]*)/([^/]+)/([^/]+)/\\3\\4[.]pdf$", Pattern.CASE_INSENSITIVE);
// how to change from one form (aspect) of article to another
final String ABSTRACT_REPLACEMENT = "/$1$2/$3/$1$3$4.htm";
final String HTML_REPLACEMENT = "/$1$2/$3/$4/$1$3$4.htm";
final String PDF_REPLACEMENT = "/$1$2/$3/$4/$3$4.pdf";
final String ADD_REPLACEMENT = "/$1$2/$3/$1$3$4add.htm";
final String EV_REPLACEMENT = "/$1$2/ev/$3/$4/$1$3$4_ev.htm";
builder.setSpec(target,
ROOT_TEMPLATE, PATTERN_TEMPLATE, Pattern.CASE_INSENSITIVE);
// set up abstract to be an aspect that will trigger an ArticleFiles
// NOTE - for the moment this also means it is considered a FULL_TEXT_CU
// until this fulltext concept is deprecated
builder.addAspect(
ABSTRACT_PATTERN, ABSTRACT_REPLACEMENT,
ArticleFiles.ROLE_ABSTRACT,
ArticleFiles.ROLE_ARTICLE_METADATA,
ArticleFiles.ROLE_FULL_TEXT_PDF_LANDING_PAGE);
builder.addAspect(
EV_REPLACEMENT,
ArticleFiles.ROLE_FULL_TEXT_HTML);
builder.addAspect(
HTML_PATTERN, HTML_REPLACEMENT,
ArticleFiles.ROLE_FULL_TEXT_HTML,
ArticleFiles.ROLE_ARTICLE_METADATA);
builder.addAspect(
PDF_PATTERN, PDF_REPLACEMENT,
ArticleFiles.ROLE_FULL_TEXT_PDF);
// set up *add.htm to be a suppl aspect
builder.addAspect(ADD_REPLACEMENT,
ArticleFiles.ROLE_SUPPLEMENTARY_MATERIALS);
// The order in which we want to define full_text_cu.
// First one that exists will get the job
builder.setFullTextFromRoles(
ArticleFiles.ROLE_FULL_TEXT_HTML,
ArticleFiles.ROLE_FULL_TEXT_PDF,
ArticleFiles.ROLE_ABSTRACT);
return builder.getSubTreeArticleIterator();
}
@Override
public ArticleMetadataExtractor createArticleMetadataExtractor(MetadataTarget target)
throws PluginException {
return new BaseArticleMetadataExtractor(ArticleFiles.ROLE_ARTICLE_METADATA);
}
}
|
package org.mybatis.jpetstore.domain;
import java.io.Serializable;
import java.math.BigDecimal;
public class Calculate implements Serializable {
public void hello()
{
System.out.println("JPET Store Application");
System.out.println("Class name: Calculate.java");
System.out.println("Hello World");
System.out.println("Making a new Entry at Fri Jan 20 11:00:15 UTC 2017");
System.out.println("Fri Jan 20 11:00:15 UTC 2017");
System.out.println("Making a new Entry at Wed Jan 18 11:00:15 UTC 2017");
System.out.println("Wed Jan 18 11:00:15 UTC 2017");
System.out.println("Making a new Entry at Mon Jan 16 11:00:15 UTC 2017");
System.out.println("Mon Jan 16 11:00:15 UTC 2017");
System.out.println("Making a new Entry at Sat Jan 14 11:00:15 UTC 2017");
System.out.println("Sat Jan 14 11:00:15 UTC 2017");
System.out.println("Making a new Entry at Thu Jan 12 11:00:15 UTC 2017");
System.out.println("Thu Jan 12 11:00:15 UTC 2017");
System.out.println("Making a new Entry at Tue Jan 10 11:00:15 UTC 2017");
System.out.println("Tue Jan 10 11:00:15 UTC 2017");
System.out.println("Making a new Entry at Sun Jan 8 11:00:15 UTC 2017");
System.out.println("Sun Jan 8 11:00:15 UTC 2017");
System.out.println("Making a new Entry at Fri Jan 6 11:00:15 UTC 2017");
System.out.println("Fri Jan 6 11:00:15 UTC 2017");
System.out.println("Making a new Entry at Wed Jan 4 11:00:15 UTC 2017");
System.out.println("Wed Jan 4 11:00:15 UTC 2017");
System.out.println("Making a new Entry at Mon Jan 2 11:00:15 UTC 2017");
System.out.println("Mon Jan 2 11:00:15 UTC 2017");
System.out.println("Making a new Entry at Fri Dec 30 11:00:16 UTC 2016");
System.out.println("Fri Dec 30 11:00:16 UTC 2016");
System.out.println("Making a new Entry at Wed Dec 28 11:00:16 UTC 2016");
System.out.println("Wed Dec 28 11:00:16 UTC 2016");
System.out.println("Making a new Entry at Mon Dec 26 11:00:16 UTC 2016");
System.out.println("Mon Dec 26 11:00:16 UTC 2016");
System.out.println("Making a new Entry at Sat Dec 24 11:00:16 UTC 2016");
System.out.println("Sat Dec 24 11:00:16 UTC 2016");
System.out.println("Making a new Entry at Thu Dec 22 11:00:16 UTC 2016");
System.out.println("Thu Dec 22 11:00:16 UTC 2016");
System.out.println("Making a new Entry at Tue Dec 20 11:00:16 UTC 2016");
System.out.println("Tue Dec 20 11:00:16 UTC 2016");
System.out.println("Making a new Entry at Sun Dec 18 11:00:16 UTC 2016");
System.out.println("Sun Dec 18 11:00:16 UTC 2016");
System.out.println("Making a new Entry at Fri Dec 16 11:00:16 UTC 2016");
System.out.println("Fri Dec 16 11:00:16 UTC 2016");
System.out.println("Making a new Entry at Wed Dec 14 11:00:16 UTC 2016");
System.out.println("Wed Dec 14 11:00:16 UTC 2016");
System.out.println("Making a new Entry at Mon Dec 12 11:00:16 UTC 2016");
System.out.println("Mon Dec 12 11:00:16 UTC 2016");
System.out.println("Making a new Entry at Sat Dec 10 11:00:16 UTC 2016");
System.out.println("Sat Dec 10 11:00:16 UTC 2016");
System.out.println("Making a new Entry at Thu Dec 8 11:00:16 UTC 2016");
System.out.println("Thu Dec 8 11:00:16 UTC 2016");
System.out.println("Making a new Entry at Tue Dec 6 11:00:16 UTC 2016");
System.out.println("Tue Dec 6 11:00:16 UTC 2016");
System.out.println("Making a new Entry at Fri Dec 2 12:52:58 UTC 2016");
System.out.println("Fri Dec 2 12:52:58 UTC 2016");
}
}
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
|
// $Id: ParlorManager.java,v 1.16 2002/02/20 02:10:02 shaper Exp $
package com.threerings.parlor.server;
import com.samskivert.util.Config;
import com.samskivert.util.HashIntMap;
import com.threerings.presents.server.InvocationManager;
import com.threerings.presents.server.ServiceFailedException;
import com.threerings.crowd.data.BodyObject;
import com.threerings.crowd.server.CrowdServer;
import com.threerings.parlor.Log;
import com.threerings.parlor.client.ParlorCodes;
import com.threerings.parlor.game.GameConfig;
import com.threerings.parlor.game.GameManager;
/**
* The parlor manager is responsible for the parlor services in
* aggregate. This includes maintaining the registry of active games,
* handling the necessary coordination for the matchmaking services and
* anything else that falls outside the scope of an actual in-progress
* game.
*/
public class ParlorManager
implements ParlorCodes
{
/**
* Initializes the parlor manager. This should be called by the server
* that is making use of the parlor services on the single instance of
* parlor manager that it has created.
*
* @param config the configuration object in use by this server.
* @param invmgr a reference to the invocation manager in use by this
* server.
*/
public void init (Config config, InvocationManager invmgr)
{
// register our invocation provider
ParlorProvider pprov = new ParlorProvider(this);
invmgr.registerProvider(MODULE_NAME, pprov);
// keep this around for later
_invmgr = invmgr;
}
/**
* Issues an invitation from the <code>inviter</code> to the
* <code>invitee</code> for a game as described by the supplied config
* object.
*
* @param inviter the player initiating the invitation.
* @param invitee the player being invited.
* @param config the configuration of the game being proposed.
*
* @return the invitation identifier for the newly created invitation
* record.
*
* @exception ServiceFailedException thrown if the invitation was not
* able to be processed for some reason (like the invited player has
* requested not to be disturbed). The explanation will be provided in
* the message data of the exception.
*/
public int invite (BodyObject inviter, BodyObject invitee,
GameConfig config)
throws ServiceFailedException
{
// Log.info("Received invitation request [inviter=" + inviter +
// ", invitee=" + invitee + ", config=" + config + "].");
// here we should check to make sure the invitee hasn't muted the
// inviter, and that the inviter isn't shunned and all that other
// access control type stuff
// create a new invitation record for this invitation
Invitation invite = new Invitation(inviter, invitee, config);
// stick it in the pending invites table
_invites.put(invite.inviteId, invite);
// deliver an invite notification to the invitee
Object[] args = new Object[] {
new Integer(invite.inviteId), inviter.username, config };
_invmgr.sendNotification(
invitee.getOid(), MODULE_NAME, INVITE_ID, args);
// and let the caller know the invite id we assigned
return invite.inviteId;
}
/**
* Effects a response to an invitation (accept, refuse or counter),
* made by the specified source user with the specified arguments.
*
* @param source the body object of the user that is issuing this
* response.
* @param inviteId the identifier of the invitation to which we are
* responding.
* @param code the response code (either {@link
* #INVITATION_ACCEPTED}, {@link #INVITATION_REFUSED} or {@link
* #INVITATION_COUNTERED}).
* @param arg the argument that goes along with the response: an
* explanatory message in the case of a refusal (the empty string, not
* null, if no message was provided) or the new game configuration in
* the case of a counter-invitation.
*/
public void respondToInvite (BodyObject source, int inviteId, int code,
Object arg)
{
// look up the invitation
Invitation invite = (Invitation)_invites.get(inviteId);
if (invite == null) {
Log.warning("Requested to respond to non-existent invitation " +
"[source=" + source + ", inviteId=" + inviteId +
", code=" + code + ", arg=" + arg + "].");
return;
}
// make sure this response came from the proper person
if (source != invite.invitee) {
Log.warning("Got response from non-invitee [source=" + source +
", invite=" + invite + ", code=" + code +
", arg=" + arg + "].");
return;
}
// let the other user know that a response was made to this
// invitation
Object[] args = new Object[] {
new Integer(invite.inviteId), new Integer(code), arg };
_invmgr.sendNotification(
invite.inviter.getOid(), MODULE_NAME, RESPOND_INVITE_ID, args);
switch (code) {
case INVITATION_ACCEPTED:
// the invitation was accepted, so we'll need to start up the
// game and get the necessary balls rolling
processAcceptedInvitation(invite);
// and remove the invitation from the pending table
_invites.remove(inviteId);
break;
case INVITATION_REFUSED:
// remove the invitation record from the pending table as it
// is no longer pending
_invites.remove(inviteId);
break;
case INVITATION_COUNTERED:
// swap control of the invitation to the invitee
invite.swapControl();
break;
default:
Log.warning("Requested to respond to invitation with " +
"unknown response code [source=" + source +
", invite=" + invite + ", code=" + code +
", arg=" + arg + "].");
break;
}
}
/**
* Requests that an outstanding invitation be cancelled.
*
* @param source the body object of the user that is making the
* request.
* @param inviteId the unique id of the invitation to be cancelled.
*/
public void cancelInvite (BodyObject source, int inviteId)
{
// TBD
}
/**
* Starts up and configures the game manager for an accepted
* invitation.
*/
protected void processAcceptedInvitation (Invitation invite)
{
try {
Log.info("Creating game manager [invite=" + invite + "].");
// create the game manager and begin it's initialization
// process. the game manager will take care of notifying the
// started up (which is done by the place registry once the
// game object creation has completed)
GameManager gmgr = (GameManager)
CrowdServer.plreg.createPlace(invite.config, null);
// provide the game manager with the player list
gmgr.setPlayers(new String[] {
invite.invitee.username, invite.inviter.username });
} catch (Exception e) {
Log.warning("Unable to create game manager [invite=" + invite +
", error=" + e + "].");
Log.logStackTrace(e);
}
}
/**
* The invitation record is used by the parlor manager to keep track
* of pending invitations.
*/
protected static class Invitation
{
/** The unique identifier for this invitation. */
public int inviteId = _nextInviteId++;
/** The person proposing the invitation. */
public BodyObject inviter;
/** The person to whom the invitation is proposed. */
public BodyObject invitee;
/** The configuration of the game being proposed. */
public GameConfig config;
/**
* Constructs a new invitation with the specified participants and
* configuration.
*/
public Invitation (BodyObject inviter, BodyObject invitee,
GameConfig config)
{
this.inviter = inviter;
this.invitee = invitee;
this.config = config;
}
/**
* Swaps the inviter and invitee which is necessary when the
* invitee responds with a counter-invitation.
*/
public void swapControl ()
{
BodyObject tmp = inviter;
inviter = invitee;
invitee = tmp;
}
}
/** A reference to the invocation manager in operation on this server. */
protected InvocationManager _invmgr;
/** The table of pending invitations. */
protected HashIntMap _invites = new HashIntMap();
/** A counter used to generate unique identifiers for invitation
* records. */
protected static int _nextInviteId = 0;
}
|
package org.mybatis.jpetstore.domain;
import java.io.Serializable;
import java.math.BigDecimal;
public class Calculate implements Serializable {
public void hello()
{
System.out.println("JPET Store Application");
System.out.println("Class name: Calculate.java");
System.out.println("Hello World");
System.out.println("Making a new Entry at Thu Jul 20 11:00:00 UTC 2017");
System.out.println("Thu Jul 20 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Tue Jul 18 11:00:00 UTC 2017");
System.out.println("Tue Jul 18 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Sun Jul 16 11:00:00 UTC 2017");
System.out.println("Sun Jul 16 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Fri Jul 14 11:00:00 UTC 2017");
System.out.println("Fri Jul 14 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Wed Jul 12 11:00:00 UTC 2017");
System.out.println("Wed Jul 12 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Mon Jul 10 11:00:00 UTC 2017");
System.out.println("Mon Jul 10 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Sat Jul 8 11:00:00 UTC 2017");
System.out.println("Sat Jul 8 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Thu Jul 6 11:00:00 UTC 2017");
System.out.println("Thu Jul 6 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Tue Jul 4 11:00:00 UTC 2017");
System.out.println("Tue Jul 4 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Sun Jul 2 11:00:00 UTC 2017");
System.out.println("Sun Jul 2 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Fri Jun 30 11:00:00 UTC 2017");
System.out.println("Fri Jun 30 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Wed Jun 28 11:00:00 UTC 2017");
System.out.println("Wed Jun 28 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Mon Jun 26 11:00:00 UTC 2017");
System.out.println("Mon Jun 26 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Sat Jun 24 11:00:00 UTC 2017");
System.out.println("Sat Jun 24 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Thu Jun 22 11:00:00 UTC 2017");
System.out.println("Thu Jun 22 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Tue Jun 20 11:00:00 UTC 2017");
System.out.println("Tue Jun 20 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Sun Jun 18 11:00:00 UTC 2017");
System.out.println("Sun Jun 18 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Fri Jun 16 11:00:00 UTC 2017");
System.out.println("Fri Jun 16 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Wed Jun 14 11:00:00 UTC 2017");
System.out.println("Wed Jun 14 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Mon Jun 12 11:00:00 UTC 2017");
System.out.println("Mon Jun 12 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Sat Jun 10 11:00:00 UTC 2017");
System.out.println("Sat Jun 10 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Thu Jun 8 11:00:00 UTC 2017");
System.out.println("Thu Jun 8 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Tue Jun 6 11:00:00 UTC 2017");
System.out.println("Tue Jun 6 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Sun Jun 4 11:00:00 UTC 2017");
System.out.println("Sun Jun 4 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Fri Jun 2 11:00:00 UTC 2017");
System.out.println("Fri Jun 2 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Tue May 30 11:00:00 UTC 2017");
System.out.println("Tue May 30 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Sun May 28 11:00:00 UTC 2017");
System.out.println("Sun May 28 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Fri May 26 11:00:00 UTC 2017");
System.out.println("Fri May 26 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Wed May 24 11:00:00 UTC 2017");
System.out.println("Wed May 24 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Mon May 22 11:00:00 UTC 2017");
System.out.println("Mon May 22 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Sat May 20 11:00:00 UTC 2017");
System.out.println("Sat May 20 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Thu May 18 11:00:00 UTC 2017");
System.out.println("Thu May 18 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Tue May 16 11:00:00 UTC 2017");
System.out.println("Tue May 16 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Sun May 14 11:00:00 UTC 2017");
System.out.println("Sun May 14 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Fri May 12 11:00:00 UTC 2017");
System.out.println("Fri May 12 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Wed May 10 11:00:00 UTC 2017");
System.out.println("Wed May 10 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Mon May 8 11:00:00 UTC 2017");
System.out.println("Mon May 8 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Sat May 6 11:00:00 UTC 2017");
System.out.println("Sat May 6 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Thu May 4 11:00:00 UTC 2017");
System.out.println("Thu May 4 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Tue May 2 11:00:00 UTC 2017");
System.out.println("Tue May 2 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Sun Apr 30 11:00:00 UTC 2017");
System.out.println("Sun Apr 30 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Fri Apr 28 11:00:00 UTC 2017");
System.out.println("Fri Apr 28 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Wed Apr 26 11:00:00 UTC 2017");
System.out.println("Wed Apr 26 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Mon Apr 24 11:00:00 UTC 2017");
System.out.println("Mon Apr 24 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Sat Apr 22 11:00:00 UTC 2017");
System.out.println("Sat Apr 22 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Thu Apr 20 11:00:00 UTC 2017");
System.out.println("Thu Apr 20 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Tue Apr 18 11:00:00 UTC 2017");
System.out.println("Tue Apr 18 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Sun Apr 16 11:00:00 UTC 2017");
System.out.println("Sun Apr 16 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Fri Apr 14 11:00:00 UTC 2017");
System.out.println("Fri Apr 14 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Wed Apr 12 11:00:00 UTC 2017");
System.out.println("Wed Apr 12 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Mon Apr 10 11:00:00 UTC 2017");
System.out.println("Mon Apr 10 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Sat Apr 8 11:00:00 UTC 2017");
System.out.println("Sat Apr 8 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Thu Apr 6 11:00:00 UTC 2017");
System.out.println("Thu Apr 6 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Tue Apr 4 11:00:00 UTC 2017");
System.out.println("Tue Apr 4 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Sun Apr 2 11:00:00 UTC 2017");
System.out.println("Sun Apr 2 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Thu Mar 30 11:00:00 UTC 2017");
System.out.println("Thu Mar 30 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Tue Mar 28 11:00:00 UTC 2017");
System.out.println("Tue Mar 28 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Sun Mar 26 11:00:00 UTC 2017");
System.out.println("Sun Mar 26 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Fri Mar 24 11:00:00 UTC 2017");
System.out.println("Fri Mar 24 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Wed Mar 22 11:00:00 UTC 2017");
System.out.println("Wed Mar 22 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Mon Mar 20 11:00:00 UTC 2017");
System.out.println("Mon Mar 20 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Sat Mar 18 11:00:00 UTC 2017");
System.out.println("Sat Mar 18 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Thu Mar 16 11:00:00 UTC 2017");
System.out.println("Thu Mar 16 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Tue Mar 14 11:00:00 UTC 2017");
System.out.println("Tue Mar 14 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Sun Mar 12 11:00:00 UTC 2017");
System.out.println("Sun Mar 12 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Fri Mar 10 11:00:00 UTC 2017");
System.out.println("Fri Mar 10 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Wed Mar 8 11:00:00 UTC 2017");
System.out.println("Wed Mar 8 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Mon Mar 6 11:00:00 UTC 2017");
System.out.println("Mon Mar 6 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Sat Mar 4 11:00:00 UTC 2017");
System.out.println("Sat Mar 4 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Thu Mar 2 11:00:00 UTC 2017");
System.out.println("Thu Mar 2 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Tue Feb 28 11:00:00 UTC 2017");
System.out.println("Tue Feb 28 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Sun Feb 26 11:00:00 UTC 2017");
System.out.println("Sun Feb 26 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Fri Feb 24 11:00:00 UTC 2017");
System.out.println("Fri Feb 24 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Wed Feb 22 11:00:00 UTC 2017");
System.out.println("Wed Feb 22 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Mon Feb 20 11:00:00 UTC 2017");
System.out.println("Mon Feb 20 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Sat Feb 18 11:00:00 UTC 2017");
System.out.println("Sat Feb 18 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Thu Feb 16 11:00:00 UTC 2017");
System.out.println("Thu Feb 16 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Tue Feb 14 11:00:00 UTC 2017");
System.out.println("Tue Feb 14 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Sun Feb 12 11:00:00 UTC 2017");
System.out.println("Sun Feb 12 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Fri Feb 10 11:00:00 UTC 2017");
System.out.println("Fri Feb 10 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Wed Feb 8 11:00:00 UTC 2017");
System.out.println("Wed Feb 8 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Mon Feb 6 11:00:00 UTC 2017");
System.out.println("Mon Feb 6 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Sat Feb 4 11:00:00 UTC 2017");
System.out.println("Sat Feb 4 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Thu Feb 2 11:00:00 UTC 2017");
System.out.println("Thu Feb 2 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Mon Jan 30 11:00:00 UTC 2017");
System.out.println("Mon Jan 30 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Sat Jan 28 11:00:15 UTC 2017");
System.out.println("Sat Jan 28 11:00:15 UTC 2017");
System.out.println("Making a new Entry at Thu Jan 26 11:00:15 UTC 2017");
System.out.println("Thu Jan 26 11:00:15 UTC 2017");
System.out.println("Making a new Entry at Tue Jan 24 11:00:15 UTC 2017");
System.out.println("Tue Jan 24 11:00:15 UTC 2017");
System.out.println("Making a new Entry at Sun Jan 22 11:00:15 UTC 2017");
System.out.println("Sun Jan 22 11:00:15 UTC 2017");
System.out.println("Making a new Entry at Fri Jan 20 11:00:15 UTC 2017");
System.out.println("Fri Jan 20 11:00:15 UTC 2017");
System.out.println("Making a new Entry at Wed Jan 18 11:00:15 UTC 2017");
System.out.println("Wed Jan 18 11:00:15 UTC 2017");
System.out.println("Making a new Entry at Mon Jan 16 11:00:15 UTC 2017");
System.out.println("Mon Jan 16 11:00:15 UTC 2017");
System.out.println("Making a new Entry at Sat Jan 14 11:00:15 UTC 2017");
System.out.println("Sat Jan 14 11:00:15 UTC 2017");
System.out.println("Making a new Entry at Thu Jan 12 11:00:15 UTC 2017");
System.out.println("Thu Jan 12 11:00:15 UTC 2017");
System.out.println("Making a new Entry at Tue Jan 10 11:00:15 UTC 2017");
System.out.println("Tue Jan 10 11:00:15 UTC 2017");
System.out.println("Making a new Entry at Sun Jan 8 11:00:15 UTC 2017");
System.out.println("Sun Jan 8 11:00:15 UTC 2017");
System.out.println("Making a new Entry at Fri Jan 6 11:00:15 UTC 2017");
System.out.println("Fri Jan 6 11:00:15 UTC 2017");
System.out.println("Making a new Entry at Wed Jan 4 11:00:15 UTC 2017");
System.out.println("Wed Jan 4 11:00:15 UTC 2017");
System.out.println("Making a new Entry at Mon Jan 2 11:00:15 UTC 2017");
System.out.println("Mon Jan 2 11:00:15 UTC 2017");
System.out.println("Making a new Entry at Fri Dec 30 11:00:16 UTC 2016");
System.out.println("Fri Dec 30 11:00:16 UTC 2016");
System.out.println("Making a new Entry at Wed Dec 28 11:00:16 UTC 2016");
System.out.println("Wed Dec 28 11:00:16 UTC 2016");
System.out.println("Making a new Entry at Mon Dec 26 11:00:16 UTC 2016");
System.out.println("Mon Dec 26 11:00:16 UTC 2016");
System.out.println("Making a new Entry at Sat Dec 24 11:00:16 UTC 2016");
System.out.println("Sat Dec 24 11:00:16 UTC 2016");
System.out.println("Making a new Entry at Thu Dec 22 11:00:16 UTC 2016");
System.out.println("Thu Dec 22 11:00:16 UTC 2016");
System.out.println("Making a new Entry at Tue Dec 20 11:00:16 UTC 2016");
System.out.println("Tue Dec 20 11:00:16 UTC 2016");
System.out.println("Making a new Entry at Sun Dec 18 11:00:16 UTC 2016");
System.out.println("Sun Dec 18 11:00:16 UTC 2016");
System.out.println("Making a new Entry at Fri Dec 16 11:00:16 UTC 2016");
System.out.println("Fri Dec 16 11:00:16 UTC 2016");
System.out.println("Making a new Entry at Wed Dec 14 11:00:16 UTC 2016");
System.out.println("Wed Dec 14 11:00:16 UTC 2016");
System.out.println("Making a new Entry at Mon Dec 12 11:00:16 UTC 2016");
System.out.println("Mon Dec 12 11:00:16 UTC 2016");
System.out.println("Making a new Entry at Sat Dec 10 11:00:16 UTC 2016");
System.out.println("Sat Dec 10 11:00:16 UTC 2016");
System.out.println("Making a new Entry at Thu Dec 8 11:00:16 UTC 2016");
System.out.println("Thu Dec 8 11:00:16 UTC 2016");
System.out.println("Making a new Entry at Tue Dec 6 11:00:16 UTC 2016");
System.out.println("Tue Dec 6 11:00:16 UTC 2016");
System.out.println("Making a new Entry at Fri Dec 2 12:52:58 UTC 2016");
System.out.println("Fri Dec 2 12:52:58 UTC 2016");
}
}
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
|
package org.apache.cassandra.heartbeat;
import java.lang.management.ManagementFactory;
import java.net.InetAddress;
import java.nio.ByteBuffer;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentSkipListSet;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import javax.management.MBeanServer;
import javax.management.ObjectName;
import org.apache.cassandra.concurrent.DebuggableScheduledThreadPoolExecutor;
import org.apache.cassandra.config.CFMetaData;
import org.apache.cassandra.config.DatabaseDescriptor;
import org.apache.cassandra.config.Schema;
import org.apache.cassandra.cql3.UntypedResultSet.Row;
import org.apache.cassandra.db.ColumnFamily;
import org.apache.cassandra.db.Mutation;
import org.apache.cassandra.gms.FailureDetector;
import org.apache.cassandra.gms.IFailureDetectionEventListener;
import org.apache.cassandra.heartbeat.extra.HBConsts;
import org.apache.cassandra.heartbeat.extra.Version;
import org.apache.cassandra.net.MessageOut;
import org.apache.cassandra.net.MessagingService;
import org.apache.cassandra.utils.keyvaluestore.ConfReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.util.concurrent.Uninterruptibles;
/**
* Periodically send out heart beat msgs
*
* @author XiGuan
*
*/
public class HeartBeater implements IFailureDetectionEventListener, HeartBeaterMBean {
private static final Logger logger = LoggerFactory.getLogger(HeartBeater.class);
private static final String MBEAN_NAME = "org.apache.cassandra.net:type=HeartBeater";
private static final DebuggableScheduledThreadPoolExecutor executor = new DebuggableScheduledThreadPoolExecutor(
"HeartBeatTasks");
public final static int intervalInMillis = ConfReader.instance.getHeartbeatInterval();
private final Comparator<InetAddress> inetcomparator = new Comparator<InetAddress>() {
public int compare(InetAddress addr1, InetAddress addr2) {
return addr1.getHostAddress().compareTo(addr2.getHostAddress());
}
};
Set<InetAddress> destinations = new ConcurrentSkipListSet<InetAddress>(inetcomparator);
/**
* Used to send out status message
*/
ConcurrentHashMap<InetAddress, StatusSynMsg> m_statusMsgMap = new ConcurrentHashMap<InetAddress, StatusSynMsg>();
private ScheduledFuture<?> scheduledHeartBeatTask;
private AtomicInteger version = new AtomicInteger(0);
public static final HeartBeater instance = new HeartBeater();
private HeartBeater() {
/* register with the Failure Detector for receiving Failure detector events */
FailureDetector.instance.registerFailureDetectionEventListener(this);
// Register this instance with JMX
try {
MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
mbs.registerMBean(this, new ObjectName(MBEAN_NAME));
} catch (Exception e) {
logger.error("exception when register HeartBeater", e);
throw new RuntimeException(e);
}
}
private class HeartBeatTask implements Runnable {
@Override
public void run() {
// wait on messaging service to start listening
MessagingService.instance().waitUntilListening();
if (!m_statusMsgMap.isEmpty()) {
// update heartbeat version
version.incrementAndGet();
long sendTime = System.currentTimeMillis();
// Send out status syn msg
for (Map.Entry<InetAddress, StatusSynMsg> entry : m_statusMsgMap.entrySet()) {
InetAddress destination = entry.getKey();
StatusSynMsg statusSynMsg = entry.getValue();
statusSynMsg.updateTimestamp(sendTime);
MessageOut<StatusSynMsg> finalMsg = new MessageOut<StatusSynMsg>(
MessagingService.Verb.HEARTBEAT_DIGEST, statusSynMsg, StatusSynMsg.serializer);
MessagingService.instance().sendOneWay(finalMsg, destination);
logger.info("send out status msg to {} with msg {}", destination, statusSynMsg);
}
}
// Clear status map
clearStatusMap();
}
}
public void start() {
initializeStatusMsg();
logger.info("Schedule task to send out heartbeat if needed");
scheduledHeartBeatTask = executor.scheduleWithFixedDelay(new HeartBeatTask(), HeartBeater.intervalInMillis,
HeartBeater.intervalInMillis, TimeUnit.MILLISECONDS);
}
public void stop() {
logger.info("Stop Heartbeater");
if (scheduledHeartBeatTask != null)
scheduledHeartBeatTask.cancel(false);
Uninterruptibles.sleepUninterruptibly(intervalInMillis * 2, TimeUnit.MILLISECONDS);
@SuppressWarnings("rawtypes")
MessageOut message = new MessageOut(MessagingService.Verb.HEARTBEAT_SHOWDOWN);
for (InetAddress ep : destinations)
MessagingService.instance().sendOneWay(message, ep);
}
@Override
public void convict(InetAddress ep, double phi) {
// Remove it from destination set
destinations.remove(ep);
}
private void initializeStatusMsg() {
logger.info("Initalize status msg");
Set<KeyMetaData> keys = HBUtils.getLocalSavedPartitionKeys();
for (KeyMetaData keyMetaData : keys) {
updateStatusMsgMap(keyMetaData.getKsName(), keyMetaData.getCfName(), keyMetaData.getKey());
}
}
public void updateStatusMsgMap(Mutation mutation) {
ByteBuffer partitionKey = mutation.key();
String ksName = mutation.getKeyspaceName();
if (!HBUtils.SYSTEM_KEYSPACES.contains(ksName)) {
for (ColumnFamily cf : mutation.getColumnFamilies()) {
Version version = HBUtils.getMutationVersion(cf);
if (version != null)
updateStatusMsgMap(ksName, cf.metadata().cfName, partitionKey, version.getLocalVersion(),
version.getTimestamp());
}
}
}
private void updateStatusMsgMap(String inKSName, String inCFName, ByteBuffer partitionKey) {
Row value = HBUtils.getKeyValue(inKSName, inCFName, partitionKey);
if (value != null) {
try {
long versionNo = value.getLong(HBConsts.VERSON_NO);
long ts = value.getLong(HBConsts.VERSION_WRITE_TIME) / 1000;
updateStatusMsgMap(inKSName, inCFName, partitionKey, ts, versionNo);
} catch (Exception e) {
logger.debug("Exception when update status msg mp", e);
}
}
}
/**
* Update status map info
*
* @param partitionKey
* @param version
* @param timestamp
*/
private void updateStatusMsgMap(String inKSName, String inCFName, ByteBuffer partitionKey, Long version,
long timestamp) {
List<InetAddress> replicaList = HBUtils.getReplicaList(inKSName, partitionKey);
replicaList.remove(replicaList.remove(DatabaseDescriptor.getListenAddress()));
CFMetaData cfMetaData = Schema.instance.getKSMetaData(inKSName).cfMetaData().get(inCFName);
for (InetAddress inetAddress : replicaList) {
StatusSynMsg statusMsgSyn = m_statusMsgMap.get(inetAddress);
if (statusMsgSyn == null) {
statusMsgSyn = new StatusSynMsg(DatabaseDescriptor.getLocalDataCenter(), null,
System.currentTimeMillis());
m_statusMsgMap.put(inetAddress, statusMsgSyn);
}
statusMsgSyn.addKeyVersion(HBUtils.byteBufferToString(cfMetaData, partitionKey), version, timestamp);
}
}
private void clearStatusMap() {
for (StatusSynMsg msg : m_statusMsgMap.values()) {
msg.cleanData();
}
}
}
|
package org.mybatis.jpetstore.domain;
import java.io.Serializable;
import java.math.BigDecimal;
public class Calculate implements Serializable {
public void hello()
{
System.out.println("JPET Store Application");
System.out.println("Class name: Calculate.java");
System.out.println("Hello World");
System.out.println("Making a new Entry at Sun Jan 22 11:00:15 UTC 2017");
System.out.println("Sun Jan 22 11:00:15 UTC 2017");
System.out.println("Making a new Entry at Fri Jan 20 11:00:15 UTC 2017");
System.out.println("Fri Jan 20 11:00:15 UTC 2017");
System.out.println("Making a new Entry at Wed Jan 18 11:00:15 UTC 2017");
System.out.println("Wed Jan 18 11:00:15 UTC 2017");
System.out.println("Making a new Entry at Mon Jan 16 11:00:15 UTC 2017");
System.out.println("Mon Jan 16 11:00:15 UTC 2017");
System.out.println("Making a new Entry at Sat Jan 14 11:00:15 UTC 2017");
System.out.println("Sat Jan 14 11:00:15 UTC 2017");
System.out.println("Making a new Entry at Thu Jan 12 11:00:15 UTC 2017");
System.out.println("Thu Jan 12 11:00:15 UTC 2017");
System.out.println("Making a new Entry at Tue Jan 10 11:00:15 UTC 2017");
System.out.println("Tue Jan 10 11:00:15 UTC 2017");
System.out.println("Making a new Entry at Sun Jan 8 11:00:15 UTC 2017");
System.out.println("Sun Jan 8 11:00:15 UTC 2017");
System.out.println("Making a new Entry at Fri Jan 6 11:00:15 UTC 2017");
System.out.println("Fri Jan 6 11:00:15 UTC 2017");
System.out.println("Making a new Entry at Wed Jan 4 11:00:15 UTC 2017");
System.out.println("Wed Jan 4 11:00:15 UTC 2017");
System.out.println("Making a new Entry at Mon Jan 2 11:00:15 UTC 2017");
System.out.println("Mon Jan 2 11:00:15 UTC 2017");
System.out.println("Making a new Entry at Fri Dec 30 11:00:16 UTC 2016");
System.out.println("Fri Dec 30 11:00:16 UTC 2016");
System.out.println("Making a new Entry at Wed Dec 28 11:00:16 UTC 2016");
System.out.println("Wed Dec 28 11:00:16 UTC 2016");
System.out.println("Making a new Entry at Mon Dec 26 11:00:16 UTC 2016");
System.out.println("Mon Dec 26 11:00:16 UTC 2016");
System.out.println("Making a new Entry at Sat Dec 24 11:00:16 UTC 2016");
System.out.println("Sat Dec 24 11:00:16 UTC 2016");
System.out.println("Making a new Entry at Thu Dec 22 11:00:16 UTC 2016");
System.out.println("Thu Dec 22 11:00:16 UTC 2016");
System.out.println("Making a new Entry at Tue Dec 20 11:00:16 UTC 2016");
System.out.println("Tue Dec 20 11:00:16 UTC 2016");
System.out.println("Making a new Entry at Sun Dec 18 11:00:16 UTC 2016");
System.out.println("Sun Dec 18 11:00:16 UTC 2016");
System.out.println("Making a new Entry at Fri Dec 16 11:00:16 UTC 2016");
System.out.println("Fri Dec 16 11:00:16 UTC 2016");
System.out.println("Making a new Entry at Wed Dec 14 11:00:16 UTC 2016");
System.out.println("Wed Dec 14 11:00:16 UTC 2016");
System.out.println("Making a new Entry at Mon Dec 12 11:00:16 UTC 2016");
System.out.println("Mon Dec 12 11:00:16 UTC 2016");
System.out.println("Making a new Entry at Sat Dec 10 11:00:16 UTC 2016");
System.out.println("Sat Dec 10 11:00:16 UTC 2016");
System.out.println("Making a new Entry at Thu Dec 8 11:00:16 UTC 2016");
System.out.println("Thu Dec 8 11:00:16 UTC 2016");
System.out.println("Making a new Entry at Tue Dec 6 11:00:16 UTC 2016");
System.out.println("Tue Dec 6 11:00:16 UTC 2016");
System.out.println("Making a new Entry at Fri Dec 2 12:52:58 UTC 2016");
System.out.println("Fri Dec 2 12:52:58 UTC 2016");
}
}
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
|
package org.apache.commons.digester;
import java.lang.reflect.Method;
import java.lang.ClassLoader;
import org.xml.sax.Attributes;
import org.apache.commons.beanutils.ConvertUtils;
public class CallMethodRule extends Rule {
/**
* Construct a "call method" rule with the specified method name. The
* parameter types (if any) default to java.lang.String.
*
* @param digester The associated Digester
* @param methodName Method name of the parent method to call
* @param paramCount The number of parameters to collect, or
* zero for a single argument from the body of this element.
*/
public CallMethodRule(Digester digester, String methodName,
int paramCount) {
this(digester, methodName, paramCount, (Class[]) null);
}
/**
* Construct a "call method" rule with the specified method name.
*
* @param digester The associated Digester
* @param methodName Method name of the parent method to call
* @param paramCount The number of parameters to collect, or
* zero for a single argument from the body of ths element
* @param paramTypes The Java class names of the arguments
* (if you wish to use a primitive type, specify the corresonding
* Java wrapper class instead, such as <code>java.lang.Boolean</code>
* for a <code>boolean</code> parameter)
*/
public CallMethodRule(Digester digester, String methodName,
int paramCount, String paramTypes[]) {
super(digester);
this.methodName = methodName;
this.paramCount = paramCount;
if (paramTypes == null) {
this.paramTypes = new Class[paramCount];
for (int i = 0; i < this.paramTypes.length; i++)
this.paramTypes[i] = "abc".getClass();
} else {
this.paramTypes = new Class[paramTypes.length];
for (int i = 0; i < this.paramTypes.length; i++) {
try {
this.paramTypes[i] =
digester.getClassLoader().loadClass(paramTypes[i]);
} catch (ClassNotFoundException e) {
this.paramTypes[i] = null; // Will cause NPE later
}
}
}
}
/**
* Construct a "call method" rule with the specified method name.
*
* @param digester The associated Digester
* @param methodName Method name of the parent method to call
* @param paramCount The number of parameters to collect, or
* zero for a single argument from the body of ths element
* @param paramTypes The Java classes that represent the
* parameter types of the method arguments
* (if you wish to use a primitive type, specify the corresonding
* Java wrapper class instead, such as <code>java.lang.Boolean.TYPE</code>
* for a <code>boolean</code> parameter)
*/
public CallMethodRule(Digester digester, String methodName,
int paramCount, Class paramTypes[]) {
super(digester);
this.methodName = methodName;
this.paramCount = paramCount;
if (paramTypes == null) {
this.paramTypes = new Class[paramCount];
for (int i = 0; i < this.paramTypes.length; i++)
this.paramTypes[i] = "abc".getClass();
} else {
this.paramTypes = new Class[paramTypes.length];
for (int i = 0; i < this.paramTypes.length; i++)
this.paramTypes[i] = paramTypes[i];
}
}
/**
* The body text collected from this element.
*/
protected String bodyText = null;
/**
* The method name to call on the parent object.
*/
protected String methodName = null;
/**
* The number of parameters to collect from <code>MethodParam</code> rules.
* If this value is zero, a single parameter will be collected from the
* body of this element.
*/
protected int paramCount = 0;
/**
* The parameter types of the parameters to be collected.
*/
protected Class paramTypes[] = null;
/**
* Process the start of this element.
*
* @param attributes The attribute list for this element
*/
public void begin(Attributes attributes) throws Exception {
// Push an array to capture the parameter values if necessary
if (paramCount > 0) {
String parameters[] = new String[paramCount];
for (int i = 0; i < parameters.length; i++)
parameters[i] = null;
digester.pushParams(parameters);
}
}
/**
* Process the body text of this element.
*
* @param bodyText The body text of this element
*/
public void body(String bodyText) throws Exception {
if (paramCount == 0)
this.bodyText = bodyText;
}
/**
* Process the end of this element.
*/
public void end() throws Exception {
// Retrieve or construct the parameter values array
String parameters[] = null;
if (paramCount > 0) {
parameters = (String[]) digester.popParams();
// In the case where the parameter for the method
// is taken from an attribute, and that attribute
// isn't actually defined in the source XML file.
if (paramCount == 1 && parameters[0] == null) {
return;
}
}
else {
parameters = new String[1];
parameters[0] = bodyText;
if (paramTypes.length == 0) {
paramTypes = new Class[1];
paramTypes[0] = "abc".getClass();
}
}
// Construct the parameter values array we will need
Object paramValues[] = new Object[paramTypes.length];
for (int i = 0; i < paramTypes.length; i++)
paramValues[i] =
ConvertUtils.convert(parameters[i], paramTypes[i]);
// Invoke the required method on the top object
Object top = digester.peek();
if (digester.getDebug() >= 1) {
StringBuffer sb = new StringBuffer("Call ");
sb.append(top.getClass().getName());
sb.append(".");
sb.append(methodName);
sb.append("(");
for (int i = 0; i < paramValues.length; i++) {
if (i > 0)
sb.append(",");
if (paramValues[i] == null)
sb.append("null");
else
sb.append(paramValues[i].toString());
sb.append("/");
if (paramTypes[i] == null)
sb.append("null");
else
sb.append(paramTypes[i].getName());
}
sb.append(")");
digester.log(sb.toString());
}
Method method = top.getClass().getMethod(methodName, paramTypes);
method.invoke(top, paramValues);
}
/**
* Clean up after parsing is complete.
*/
public void finish() throws Exception {
bodyText = null;
}
/**
* Render a printable version of this Rule.
*/
public String toString() {
StringBuffer sb = new StringBuffer("CallMethodRule[");
sb.append("methodName=");
sb.append(methodName);
sb.append(", paramCount=");
sb.append(paramCount);
sb.append(", paramTypes={");
if (paramTypes != null) {
for (int i = 0; i < paramTypes.length; i++) {
if (i > 0)
sb.append(", ");
sb.append(paramTypes[i].getName());
}
}
sb.append("}");
sb.append("]");
return (sb.toString());
}
}
|
package org.cleartk.classifier.opennlp;
import java.io.DataInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.jar.JarFile;
import java.util.zip.GZIPInputStream;
import java.util.zip.ZipEntry;
import opennlp.maxent.MaxentModel;
import opennlp.maxent.io.BinaryGISModelReader;
import org.apache.uima.UimaContext;
import org.apache.uima.resource.ResourceInitializationException;
import org.cleartk.Initializable;
import org.cleartk.classifier.Classifier_ImplBase;
import org.cleartk.classifier.Feature;
import org.cleartk.classifier.ScoredValue;
import org.cleartk.classifier.Viterbi;
import org.cleartk.classifier.encoder.features.NameNumber;
import org.cleartk.util.UIMAUtil;
public class MaxentClassifier extends Classifier_ImplBase<String, String, List<NameNumber>> implements Initializable {
protected MaxentModel model;
int sequenceBeamSize = 1;
public MaxentClassifier(JarFile modelFile) throws IOException {
super(modelFile);
ZipEntry modelEntry = modelFile.getEntry("model.maxent");
this.model = new BinaryGISModelReader(new DataInputStream(new GZIPInputStream(modelFile
.getInputStream(modelEntry)))).getModel();
}
public void initialize(UimaContext context) throws ResourceInitializationException {
sequenceBeamSize = (Integer) UIMAUtil.getDefaultingConfigParameterValue(context, Viterbi.PARAM_BEAM_SIZE, 1);
}
@Override
public String classify(List<Feature> features) {
EvalParams evalParams = convertToEvalParams(features);
String encodedOutcome = this.model.getBestOutcome(this.model.eval(evalParams.getContext(), evalParams
.getValues()));
return outcomeEncoder.decode(encodedOutcome);
}
@Override
public List<ScoredValue<String>> score(List<Feature> features, int maxResults) {
EvalParams evalParams = convertToEvalParams(features);
double[] evalResults = this.model.eval(evalParams.getContext(), evalParams.getValues());
String[] encodedOutcomes = (String[]) this.model.getDataStructures()[2];
List<ScoredValue<String>> returnValues = new ArrayList<ScoredValue<String>>();
if (maxResults == 1) {
String encodedBestOutcome = outcomeEncoder.decode(this.model.getBestOutcome(evalResults));
double bestResult = evalResults[this.model.getIndex(encodedBestOutcome)];
returnValues.add(new ScoredValue<String>(encodedBestOutcome, bestResult));
return returnValues;
}
else {
for (int i = 0; i < evalResults.length; i++) {
returnValues.add(new ScoredValue<String>(outcomeEncoder.decode(encodedOutcomes[i]), evalResults[i]));
}
Collections.sort(returnValues);
if (returnValues.size() > maxResults) {
return returnValues.subList(0, maxResults);
}
else {
return returnValues;
}
}
}
@Override
public List<String> classifySequence(List<List<Feature>> features){
if(sequenceBeamSize == 1)
return super.classifySequence(features);
else {
return Viterbi.classifySequence(features, sequenceBeamSize, String.class, this, outcomeFeatureExtractors, false);
}
}
/**
* @return false
*/
@Override
public boolean isSequential() {
return false;
}
private EvalParams convertToEvalParams(List<Feature> features) {
String[] context = new String[features.size()];
float[] values = new float[features.size()];
List<NameNumber> contexts = featuresEncoder.encodeAll(features);
for (int i = 0; i < contexts.size(); i++) {
NameNumber contextValue = contexts.get(i);
context[i] = contextValue.name;
values[i] = contextValue.number.floatValue();
}
return new EvalParams(context, values);
}
public class EvalParams {
private String[] context;
private float[] values;
public String[] getContext() {
return context;
}
public float[] getValues() {
return values;
}
public EvalParams(String[] context, float[] values) {
this.context = context;
this.values = values;
}
}
}
//List<ScoredValue<List<String>>> returnValues = new ArrayList<ScoredValue<List<String>>>();
//if (features == null || features.size() == 0) {
// return Collections.emptyList();
//List<ScoredValue<String>> scoredOutcomes = score(features.get(0), maxResults);
//for (ScoredValue<String> scoredOutcome : scoredOutcomes) {
// double score = scoredOutcome.getScore();
// List<String> sequence = new ArrayList<String>();
// sequence.add(scoredOutcome.getValue());
// returnValues.add(new ScoredValue<List<String>>(sequence, score));
//Map<String, Double> l = new HashMap<String, Double>();
//Map<String, List<String>> m = new HashMap<String, List<String>>();
//for (int i = 1; i < features.size(); i++) {
// List<Feature> instanceFeatures = features.get(i);
// l.clear();
// m.clear();
// for (ScoredValue<List<String>> scoredSequence : returnValues) {
// // add features from previous outcomes from each scoredSequence
// // in returnValues
// int outcomeFeaturesCount = 0;
// List<Object> previousOutcomes = new ArrayList<Object>(scoredSequence.getValue());
// for (OutcomeFeatureExtractor outcomeFeatureExtractor : outcomeFeatureExtractors) {
// List<Feature> outcomeFeatures = outcomeFeatureExtractor.extractFeatures(previousOutcomes);
// instanceFeatures.addAll(outcomeFeatures);
// outcomeFeaturesCount += outcomeFeatures.size();
// // score the instance features using the features added by the
// // outcomeFeatureExtractors
// scoredOutcomes = score(instanceFeatures, maxResults);
// // remove the added features from previous outcomes for this
// // scoredSequence
// instanceFeatures = instanceFeatures.subList(0, instanceFeatures.size() - outcomeFeaturesCount);
// for (ScoredValue<String> scoredOutcome : scoredOutcomes) {
// if (!l.containsKey(scoredOutcome.getValue())) {
// double score = scoredSequence.getScore() + scoredOutcome.getScore();
// l.put(scoredOutcome.getValue(), score);
// m.put(scoredOutcome.getValue(), new ArrayList<String>(scoredSequence.getValue()));
// else {
// double newScore = scoredSequence.getScore() + scoredOutcome.getScore();
// double bestScore = l.get(scoredOutcome.getValue());
// if (newScore > bestScore) {
// l.put(scoredOutcome.getValue(), newScore);
// m.put(scoredOutcome.getValue(), new ArrayList<String>(scoredSequence.getValue()));
// returnValues.clear();
// for (String outcome : l.keySet()) {
// List<String> outcomeSequence = m.get(outcome);
// outcomeSequence.add(outcome);
// double score = l.get(outcome);
// ScoredValue<List<String>> returnValue = new ScoredValue<List<String>>(outcomeSequence, score);
// returnValues.add(returnValue);
// Collections.sort(returnValues);
//Collections.sort(returnValues);
//return returnValues;
|
package org.openspaces.servicegrid;
import java.net.URI;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ws.rs.core.MediaType;
import org.openspaces.servicegrid.state.Etag;
import org.openspaces.servicegrid.state.EtagPreconditionNotMetException;
import org.openspaces.servicegrid.state.EtagState;
import org.openspaces.servicegrid.state.StateReader;
import org.openspaces.servicegrid.state.StateWriter;
import org.openspaces.servicegrid.streams.StreamUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Function;
import com.google.common.base.Preconditions;
import com.google.common.base.Throwables;
import com.google.common.collect.Iterables;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.ClientResponse.Status;
import com.sun.jersey.api.client.UniformInterfaceException;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
import com.sun.jersey.api.client.filter.LoggingFilter;
public class StateClient implements StateReader, StateWriter {
private final ObjectMapper mapper;
private final URI restUri;
private WebResource webResource;
private final Logger logger = Logger.getLogger(this.getClass().getName());
private boolean enableHttpLogging = false;
public StateClient(URI restUri) {
this.restUri = restUri;
mapper = StreamUtils.newObjectMapper();
final ClientConfig clientConfig = new DefaultClientConfig();
final Client client = Client.create(clientConfig);
if (enableHttpLogging) {
client.addFilter(new LoggingFilter(logger));
}
webResource = client.resource(restUri);
}
@Override
public Etag put(URI id, Object state, Etag etag) {
final String path = getPathFromId(id);
final String json = StreamUtils.toJson(mapper,state);
Preconditions.checkState(json.length() > 0);
final int retries = 30;
for (int i = 0 ; ; i ++) {
final ClientResponse response = put(path, json, etag);
if (response.getClientResponseStatus() == ClientResponse.Status.OK) {
return Etag.create(response);
}
else if ((i < (retries-1)) && response.getClientResponseStatus()== ClientResponse.Status.BAD_REQUEST) {
//retry
logger.warning("received error " + response.getEntity(String.class));
continue;
}
else if (response.getClientResponseStatus()== ClientResponse.Status.PRECONDITION_FAILED) {
throw new EtagPreconditionNotMetException(id, Etag.create(response), etag);
}
throw new UniformInterfaceException(response);
}
}
private ClientResponse put(final String path, final String json, Etag etag) {
ClientResponse response;
if (etag.equals(Etag.empty())) {
response =
webResource
.path(path)
.header("If-None-Match", "*")
.header("Content-Length", json.length())
.type(MediaType.APPLICATION_JSON)
.put(ClientResponse.class, json);
}
else {
response =
webResource
.path(path)
.header("If-Match", etag.toString())
.header("Content-Length", json.length())
.type(MediaType.APPLICATION_JSON)
.put(ClientResponse.class, json);
}
return response;
}
@Override
public <T> EtagState<T> get(URI id, Class<? extends T> clazz) {
final String path = getPathFromId(id);
final int maxRetries = 30;
for(int i =0 ; ; i++) {
try {
return get(path, clazz);
} catch (Exception e) {
int numberOfRetriesLeft = maxRetries - i -1;
if (numberOfRetriesLeft > 0) {
logger.log(Level.INFO, "GET failed. will try " + numberOfRetriesLeft + " more time(s).", e);
}
else {
throw Throwables.propagate(e);
}
}
}
}
private <T> EtagState<T> get(final String path, Class<? extends T> clazz) {
final ClientResponse response = webResource.path(path).get(ClientResponse.class);
final Status status = response.getClientResponseStatus();
if (status == ClientResponse.Status.OK) {
final String json = response.getEntity(String.class);
if (json.length() == 0) {
Preconditions.checkState(json.length() > 0, "Retrieved empty string value for path " + path);
}
final Etag etag = Etag.create(response);
final T state = StreamUtils.fromJson(mapper, json, clazz);
return new EtagState<T>(etag, state);
}
else if (status == ClientResponse.Status.NOT_FOUND) {
return null;
}
else {
throw new UniformInterfaceException(response);
}
}
private String getPathFromId(URI id) {
Preconditions.checkArgument(id.toString().startsWith(restUri.toString()));
return StreamUtils.fixSlash(id.toString().substring(restUri.toString().length()));
}
public boolean stateEquals(TaskConsumerState state1, TaskConsumerState state2) {
return StreamUtils.elementEquals(mapper, state1, state2);
}
@Override
public Iterable<URI> getElementIdsStartingWith(final URI idPrefix) {
final String path = getPathFromId(idPrefix)+"_list";
final String json = webResource.path(path).get(String.class);
@SuppressWarnings("unchecked")
final List<String> uris = StreamUtils.fromJson(mapper, json, List.class);
return Iterables.transform(uris, new Function<String,URI>(){
@Override
public URI apply(String uri) {
return StreamUtils.newURI(uri);
}});
}
}
|
package org.exist.xquery.modules.sql;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;
import org.apache.log4j.Logger;
import org.exist.xquery.AbstractInternalModule;
import org.exist.xquery.FunctionDef;
import org.exist.xquery.XQueryContext;
/**
* eXist SQL Module Extension
*
* An extension module for the eXist Native XML Database that allows queries
* against SQL Databases, returning an XML representation of the result set.
*
* @author Adam Retter <adam@exist-db.org>
* @serial 2008-05-19
* @version 1.1
*
* @see org.exist.xquery.AbstractInternalModule#AbstractInternalModule(org.exist.xquery.FunctionDef[])
*/
public class SQLModule extends AbstractInternalModule {
protected final static Logger LOG = Logger.getLogger(SQLModule.class);
public final static String NAMESPACE_URI = "http://exist-db.org/xquery/sql";
public final static String PREFIX = "sql";
public final static String INCLUSION_DATE = "2006-09-25";
public final static String RELEASED_IN_VERSION = "eXist-1.2";
private final static FunctionDef[] functions = {
new FunctionDef(GetConnectionFunction.signatures[0],
GetConnectionFunction.class),
new FunctionDef(GetConnectionFunction.signatures[1],
GetConnectionFunction.class),
new FunctionDef(GetConnectionFunction.signatures[2],
GetConnectionFunction.class),
new FunctionDef(GetJNDIConnectionFunction.signatures[0],
GetJNDIConnectionFunction.class),
new FunctionDef(GetJNDIConnectionFunction.signatures[1],
GetJNDIConnectionFunction.class),
new FunctionDef(ExecuteFunction.signatures[0],
ExecuteFunction.class),
};
private static long currentConnectionUID = System.currentTimeMillis();
public final static String CONNECTIONS_CONTEXTVAR = "_eXist_sql_connections";
public SQLModule() {
super(functions);
}
public String getNamespaceURI() {
return NAMESPACE_URI;
}
public String getDefaultPrefix() {
return PREFIX;
}
public String getDescription() {
return "A module for performing SQL queries against Databases, returning XML representations of the result sets.";
}
/**
* Retrieves a previously stored Connection from the Context of an XQuery
*
* @param context
* The Context of the XQuery containing the Connection
* @param connectionUID
* The UID of the Connection to retrieve from the Context of the
* XQuery
*/
public final static Connection retrieveConnection(XQueryContext context,
long connectionUID) {
// get the existing connections map from the context
HashMap connections = (HashMap) context
.getXQueryContextVar(SQLModule.CONNECTIONS_CONTEXTVAR);
if (connections == null) {
return null;
}
// get the connection
return (Connection) connections.get(new Long(connectionUID));
}
/**
* Stores a Connection in the Context of an XQuery
*
* @param context
* The Context of the XQuery to store the Connection in
* @param con
* The connection to store
*
* @return A unique ID representing the connection
*/
public final static synchronized long storeConnection(
XQueryContext context, Connection con) {
// get the existing connections map from the context
HashMap connections = (HashMap) context
.getXQueryContextVar(SQLModule.CONNECTIONS_CONTEXTVAR);
if (connections == null) {
// if there is no connections map, create a new one
connections = new HashMap();
}
// get an id for the connection
long conID = getUID();
// place the connection in the connections map
connections.put(new Long(conID), con);
// store the updated connections map back in the context
context.setXQueryContextVar(SQLModule.CONNECTIONS_CONTEXTVAR,
connections);
return conID;
}
/**
* Closes all the open DB connections for the specified XQueryContext
*
* @param xqueryContext
* The context to close JDBC connections for
*/
private final static void closeAllConnections(XQueryContext xqueryContext) {
// get the existing connections map from the context
HashMap connections = (HashMap) xqueryContext
.getXQueryContextVar(SQLModule.CONNECTIONS_CONTEXTVAR);
if (connections != null) {
// iterate over each connection
Set keys = connections.keySet();
for (Iterator itKeys = keys.iterator(); itKeys.hasNext();) {
// get the connection
Long conID = (Long) itKeys.next();
Connection con = (Connection) connections.get(conID);
try {
// close the connection
con.close();
// remove it from the connections map
connections.remove(conID);
} catch (SQLException se) {
LOG.debug("Unable to close JDBC connection", se);
}
}
// update the context
xqueryContext.setXQueryContextVar(SQLModule.CONNECTIONS_CONTEXTVAR,
connections);
}
}
/**
* Returns a Unique ID based on the System Time
*
* @return The Unique ID
*/
private static synchronized long getUID() {
return currentConnectionUID++;
}
/**
* Resets the Module Context and closes any DB connections for the
* XQueryContext
*
* @param xqueryContext
* The XQueryContext
*/
public void reset(XQueryContext xqueryContext) {
// reset the module context
super.reset(xqueryContext);
// close any open connections
closeAllConnections(xqueryContext);
}
}
|
package org.cocolab.inpro.features;
import weka.core.Attribute;
import weka.core.FastVector;
import weka.core.Instance;
import weka.core.Instances;
import edu.cmu.sphinx.util.props.Resetable;
public class EOTFeatureAggregator implements Resetable {
private static final int[] energyRegressionSteps = {5, 10, 20, 50, 100, 200};
private static final int[] voicedEnergyRegressionSteps = {50, 100, 200, 500};
private static final int[] pitchRegressionSteps = {5, 10, 20, 50, 100, 200, 500};
private static final String[] regressionParams = {"Mean", "Slope", "MSE", "PredictionError", "Range"};
private Attribute framesIntoTurnAttribute;
/* private Attribute wordsIntoTurnAttribute;
private Attribute framesIntoLastWordAttribute;
private Attribute asrResultsLagAttribute;
*/
private Attribute currentFrameEnergyAttribute;
// for each time in energyRegressions: mean, slope, mse, predictionError, range
private Attribute[] energyRegressionAttributes;
private Attribute[] voicedEnergyRegressionAttributes;
private Attribute currentVoicingAttribute;
private Attribute currentPitchAttribute;
// for each time in pitchRegressions: mean, slope, mse, predictionError, range
private Attribute[] pitchRegressionAttributes;
protected final static boolean CLUSTERED_TIME = false; // FIXME: this should be configurable (maybe via configurable)
protected final static boolean CONTINUOUS_TIME = true; // FIXME: this should be configurable (via configurable interface)
protected Attribute timeToEOT;
protected Attribute clusteredTimeToEOT;
protected Instances instances;
int framesIntoTurnValue;
/* int wordsIntoTurnValue;
int framesIntoLastWordValue;
int asrResultsLagValue;
*/
double currentFrameEnergyValue;
TimeShiftingAnalysis[] energyRegressions;
TimeShiftingAnalysis[] voicedEnergyRegressions;
boolean currentVoicingValue;
double currentPitchValue;
TimeShiftingAnalysis[] pitchRegressions;
int numAttributes;
private static Attribute[] createRegressionAttributesFor(int[] steps, String name, FastVector attInfo) {
Attribute[] attributes = new Attribute[regressionParams.length * steps.length];
int i = 0;
for (int frames : steps) {
for (String param : regressionParams) {
attributes[i] = new Attribute(name + frames + "0ms" + param);
attInfo.addElement(attributes[i]);
i++;
}
}
return attributes;
}
private static TimeShiftingAnalysis[] createRegressions(int[] steps) {
TimeShiftingAnalysis[] tsas = new TimeShiftingAnalysis[steps.length];
int i = 0;
for (int frames : steps) {
tsas[i] = new TimeShiftingAnalysis(frames);
i++;
}
return tsas;
}
private void setRegressionValues(Attribute[] atts, TimeShiftingAnalysis[] tsas, Instance instance) {
// when more parameters are added, this procedure has to be changed
assert regressionParams.length == 5;
assert atts.length == tsas.length * 5;
int i = 0;
for (TimeShiftingAnalysis tsa : tsas) {
instance.setValue(atts[i++], tsa.getMean());
instance.setValue(atts[i++], tsa.getSlope());
instance.setValue(atts[i++], tsa.getMSE());
instance.setValue(atts[i++], tsa.predictValueAt(framesIntoTurnValue) - tsa.getLastValue());
instance.setValue(atts[i++], tsa.getRange());
}
}
public EOTFeatureAggregator() {
FastVector attInfo = new FastVector(10000); // allow for a lot of elements, trim later on
framesIntoTurnAttribute = new Attribute("timeIntoTurn");
attInfo.addElement(framesIntoTurnAttribute);
/* wordsIntoTurnAttribute = new Attribute("wordsIntoTurn");
attInfo.addElement(wordsIntoTurnAttribute);
framesIntoLastWordAttribute = new Attribute("timeIntoLastWord");
attInfo.addElement(framesIntoLastWordAttribute);
asrResultsLagAttribute = new Attribute("asrResultsLag");
attInfo.addElement(asrResultsLagAttribute);
*/
currentFrameEnergyAttribute = new Attribute("currentFrameEnergy");
attInfo.addElement(currentFrameEnergyAttribute);
energyRegressionAttributes = createRegressionAttributesFor(energyRegressionSteps, "energy", attInfo);
energyRegressions = createRegressions(energyRegressionSteps);
voicedEnergyRegressionAttributes = createRegressionAttributesFor(voicedEnergyRegressionSteps, "voicedEnergy", attInfo);
voicedEnergyRegressions = createRegressions(voicedEnergyRegressionSteps);
currentVoicingAttribute = new Attribute("currentVoicing");
attInfo.addElement(currentVoicingAttribute);
currentPitchAttribute = new Attribute("currentPitch");
attInfo.addElement(currentPitchAttribute);
pitchRegressionAttributes = createRegressionAttributesFor(pitchRegressionSteps, "pitch", attInfo);
pitchRegressions = createRegressions(pitchRegressionSteps);
if (CLUSTERED_TIME) {
clusteredTimeToEOT = EOTBins.eotBinsAttribute();
attInfo.addElement(clusteredTimeToEOT);
}
if (CONTINUOUS_TIME) {
timeToEOT = new Attribute("timeToEOT");
attInfo.addElement(timeToEOT);
}
instances = new Instances("eotFeatures", attInfo, 0);
// instances.setClass(framesIntoTurnAttribute);
if (CONTINUOUS_TIME) {
instances.setClass(timeToEOT);
}
if (CLUSTERED_TIME) {
instances.setClass(clusteredTimeToEOT);
}
attInfo.trimToSize();
numAttributes = attInfo.size();
reset();
}
protected Instance getNewestFeatures() {
Instance instance = new Instance(numAttributes);
instance.setValue(framesIntoTurnAttribute, ((double) framesIntoTurnValue) / 100.0);
/* instance.setValue(wordsIntoTurnAttribute, wordsIntoTurnValue);
instance.setValue(framesIntoLastWordAttribute, ((double) framesIntoLastWordValue) / 100.0);
instance.setValue(asrResultsLagAttribute, asrResultsLagValue);
*/
instance.setValue(currentFrameEnergyAttribute, currentFrameEnergyValue);
setRegressionValues(energyRegressionAttributes, energyRegressions, instance);
setRegressionValues(voicedEnergyRegressionAttributes, voicedEnergyRegressions, instance);
instance.setValue(currentVoicingAttribute, currentVoicingValue ? 1.0 : 0.0);
instance.setValue(currentPitchAttribute, currentPitchValue);
setRegressionValues(pitchRegressionAttributes, pitchRegressions, instance);
instance.setDataset(instances);
instance.setClassMissing();
return instance;
}
public void setFramesIntoTurn(int f) {
framesIntoTurnValue = f;
}
public double getFramesIntoTurn() {
return framesIntoTurnValue;
}
/*
public void setASRResultsLag(int frames) {
asrResultsLagValue = frames;
}
*/
public double getTimeIntoTurn() {
return ((double) framesIntoTurnValue) / 100.0; // FIXME: the frame rate should be configurable
}
/*
public void setWordsIntoTurn(int wordsIntoTurn) {
wordsIntoTurnValue = wordsIntoTurn;
}
public void setFramesIntoLastWord(int framesIntoLastWord) {
framesIntoLastWordValue = framesIntoLastWord;
}
*/
public void setCurrentFrameEnergy(double logEnergy) {
currentFrameEnergyValue = logEnergy;
for (TimeShiftingAnalysis tsa : energyRegressions) {
tsa.add(framesIntoTurnValue, logEnergy);
if (currentVoicingValue) {
tsa.add(framesIntoTurnValue, logEnergy);
}
}
}
public void setCurrentVoicing(boolean voicing) {
currentVoicingValue = voicing;
}
public void setCurrentPitch(double pitch) {
currentPitchValue = pitch;
for (TimeShiftingAnalysis tsa : pitchRegressions) {
if (pitch > 0.0) {
tsa.add(framesIntoTurnValue, pitch);
} else {
tsa.shiftTime(framesIntoTurnValue);
}
}
}
public void reset() {
framesIntoTurnValue = -1;
/* wordsIntoTurnValue = -1;
framesIntoLastWordValue = -1;
*/ currentFrameEnergyValue = -1.0;
for (TimeShiftingAnalysis tsa : energyRegressions) {
tsa.reset();
}
for (TimeShiftingAnalysis tsa : pitchRegressions) {
tsa.reset();
}
}
}
/*
private Attribute frameEnergy50msMeanAttribute;
private Attribute frameEnergy50msSlopeAttribute;
private Attribute frameEnergy50msPredictionErrorAttribute;
private Attribute frameEnergy100msMeanAttribute;
private Attribute frameEnergy100msSlopeAttribute;
private Attribute frameEnergy100msPredictionErrorAttribute;
private Attribute frameEnergy200msMeanAttribute;
private Attribute frameEnergy200msSlopeAttribute;
private Attribute frameEnergy200msPredictionErrorAttribute;
private Attribute pitch50msMeanAttribute;
private Attribute pitch50msSlopeAttribute;
private Attribute pitch50msPredictionErrorAttribute;
private Attribute pitch100msMeanAttribute;
private Attribute pitch100msSlopeAttribute;
private Attribute pitch100msPredictionErrorAttribute;
private Attribute pitch200msMeanAttribute;
private Attribute pitch200msSlopeAttribute;
private Attribute pitch200msPredictionErrorAttribute;
private Attribute pitch500msMeanAttribute;
private Attribute pitch500msSlopeAttribute;
private Attribute pitch500msPredictionErrorAttribute;
private Attribute pitch1000msMeanAttribute;
private Attribute pitch1000msSlopeAttribute;
private Attribute pitch1000msPredictionErrorAttribute;
private Attribute pitch2000msMeanAttribute;
private Attribute pitch2000msSlopeAttribute;
private Attribute pitch2000msPredictionErrorAttribute;
TimeShiftingAnalysis frameEnergy50ms = new TimeShiftingAnalysis(5);
TimeShiftingAnalysis frameEnergy100ms = new TimeShiftingAnalysis(10);
TimeShiftingAnalysis frameEnergy200ms = new TimeShiftingAnalysis(20);
TimeShiftingAnalysis pitch50ms = new TimeShiftingAnalysis(5);
TimeShiftingAnalysis pitch100ms = new TimeShiftingAnalysis(10);
TimeShiftingAnalysis pitch200ms = new TimeShiftingAnalysis(20);
TimeShiftingAnalysis pitch500ms = new TimeShiftingAnalysis(50);
TimeShiftingAnalysis pitch1000ms = new TimeShiftingAnalysis(100);
TimeShiftingAnalysis pitch2000ms = new TimeShiftingAnalysis(200);
frameEnergy50msMeanAttribute = new Attribute("frameEnergy50msMean");
attInfo.setCapacity(++numAttributes);
attInfo.addElement(frameEnergy50msMeanAttribute);
frameEnergy50msSlopeAttribute = new Attribute("frameEnergy50msSlope");
attInfo.setCapacity(++numAttributes);
attInfo.addElement(frameEnergy50msSlopeAttribute);
frameEnergy50msPredictionErrorAttribute = new Attribute("frameEnergy50msPredictionError");
attInfo.setCapacity(++numAttributes);
attInfo.addElement(frameEnergy50msPredictionErrorAttribute);
frameEnergy100msMeanAttribute = new Attribute("frameEnergy100msMean");
attInfo.setCapacity(++numAttributes);
attInfo.addElement(frameEnergy100msMeanAttribute);
frameEnergy100msSlopeAttribute = new Attribute("frameEnergy100msSlope");
attInfo.setCapacity(++numAttributes);
attInfo.addElement(frameEnergy100msSlopeAttribute);
frameEnergy100msPredictionErrorAttribute = new Attribute("frameEnergy100msPredictionError");
attInfo.setCapacity(++numAttributes);
attInfo.addElement(frameEnergy100msPredictionErrorAttribute);
frameEnergy200msMeanAttribute = new Attribute("frameEnergy200msMean");
attInfo.setCapacity(++numAttributes);
attInfo.addElement(frameEnergy200msMeanAttribute);
frameEnergy200msSlopeAttribute = new Attribute("frameEnergy200msSlope");
attInfo.setCapacity(++numAttributes);
attInfo.addElement(frameEnergy200msSlopeAttribute);
frameEnergy200msPredictionErrorAttribute = new Attribute("frameEnergy200msPredictionError");
attInfo.setCapacity(++numAttributes);
attInfo.addElement(frameEnergy200msPredictionErrorAttribute);
instance.setValue(frameEnergy50msMeanAttribute,
frameEnergy50ms.getMean());
instance.setValue(frameEnergy50msSlopeAttribute,
frameEnergy50ms.getSlope());
instance.setValue(frameEnergy50msPredictionErrorAttribute,
frameEnergy50ms.predictValueAt(framesIntoTurnValue) - currentFrameEnergyValue);
instance.setValue(frameEnergy100msMeanAttribute,
frameEnergy100ms.getMean());
instance.setValue(frameEnergy100msSlopeAttribute,
frameEnergy100ms.getSlope());
instance.setValue(frameEnergy100msPredictionErrorAttribute,
frameEnergy100ms.predictValueAt(framesIntoTurnValue) - currentFrameEnergyValue);
instance.setValue(frameEnergy200msMeanAttribute,
frameEnergy200ms.getMean());
instance.setValue(frameEnergy200msSlopeAttribute,
frameEnergy200ms.getSlope());
instance.setValue(frameEnergy200msPredictionErrorAttribute,
frameEnergy200ms.predictValueAt(framesIntoTurnValue) - currentFrameEnergyValue);
instance.setValue(pitch50msMeanAttribute,
pitch50ms.getMean());
instance.setValue(pitch50msSlopeAttribute,
pitch50ms.getSlope());
instance.setValue(pitch50msPredictionErrorAttribute,
pitch50ms.predictValueAt(framesIntoTurnValue) - currentPitchValue);
instance.setValue(pitch100msMeanAttribute,
pitch100ms.getMean());
instance.setValue(pitch100msSlopeAttribute,
pitch100ms.getSlope());
instance.setValue(pitch100msPredictionErrorAttribute,
pitch100ms.predictValueAt(framesIntoTurnValue) - currentPitchValue);
instance.setValue(pitch200msMeanAttribute,
pitch200ms.getMean());
instance.setValue(pitch200msSlopeAttribute,
pitch200ms.getSlope());
instance.setValue(pitch200msPredictionErrorAttribute,
pitch200ms.predictValueAt(framesIntoTurnValue) - currentPitchValue);
instance.setValue(pitch500msMeanAttribute,
pitch500ms.getMean());
instance.setValue(pitch500msSlopeAttribute,
pitch500ms.getSlope());
instance.setValue(pitch500msPredictionErrorAttribute,
pitch500ms.predictValueAt(framesIntoTurnValue) - currentPitchValue);
instance.setValue(pitch1000msMeanAttribute,
pitch1000ms.getMean());
instance.setValue(pitch1000msSlopeAttribute,
pitch1000ms.getSlope());
instance.setValue(pitch1000msPredictionErrorAttribute,
pitch1000ms.predictValueAt(framesIntoTurnValue) - currentPitchValue);
instance.setValue(pitch2000msMeanAttribute,
pitch2000ms.getMean());
instance.setValue(pitch2000msSlopeAttribute,
pitch2000ms.getSlope());
instance.setValue(pitch2000msPredictionErrorAttribute,
pitch2000ms.predictValueAt(framesIntoTurnValue) - currentPitchValue);
frameEnergy50ms.add(framesIntoTurnValue, logEnergy);
frameEnergy100ms.add(framesIntoTurnValue, logEnergy);
frameEnergy200ms.add(framesIntoTurnValue, logEnergy);
if (pitch > 0.0) {
pitch50ms.add(framesIntoTurnValue, pitch);
pitch100ms.add(framesIntoTurnValue, pitch);
pitch200ms.add(framesIntoTurnValue, pitch);
pitch500ms.add(framesIntoTurnValue, pitch);
pitch1000ms.add(framesIntoTurnValue, pitch);
pitch2000ms.add(framesIntoTurnValue, pitch);
} else {
pitch50ms.shiftTime(framesIntoTurnValue);
pitch100ms.shiftTime(framesIntoTurnValue);
pitch200ms.shiftTime(framesIntoTurnValue);
pitch500ms.shiftTime(framesIntoTurnValue);
pitch1000ms.shiftTime(framesIntoTurnValue);
pitch2000ms.shiftTime(framesIntoTurnValue);
}
frameEnergy50ms.reset();
frameEnergy100ms.reset();
frameEnergy200ms.reset();
pitch50ms.reset();
pitch100ms.reset();
pitch200ms.reset();
pitch500ms.reset();
pitch1000ms.reset();
pitch2000ms.reset();
*/
|
package com.charlesmadere.hummingbird.activities;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.LayoutRes;
import android.support.annotation.Nullable;
import android.support.annotation.StringRes;
import android.support.v4.app.NavUtils;
import android.support.v4.app.TaskStackBuilder;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import com.charlesmadere.hummingbird.R;
import com.charlesmadere.hummingbird.misc.ActivityRegister;
import com.charlesmadere.hummingbird.misc.Timber;
import com.charlesmadere.hummingbird.models.UiColorSet;
import com.charlesmadere.hummingbird.preferences.Preferences;
import butterknife.BindView;
import butterknife.ButterKnife;
public abstract class BaseActivity extends AppCompatActivity {
private static final String TAG = "BaseActivity";
private static final String CNAME = BaseActivity.class.getCanonicalName();
protected static final String EXTRA_UI_COLOR_SET = CNAME + ".UiColorSet";
@Nullable
@BindView(R.id.toolbar)
protected Toolbar mToolbar;
protected void applyUiColorSet(final UiColorSet uiColorSet) {
if (mToolbar != null) {
mToolbar.setBackgroundColor(uiColorSet.getDarkVibrantColor());
}
}
public abstract String getActivityName();
@Nullable
public CharSequence getSubtitle() {
final ActionBar actionBar = getSupportActionBar();
if (actionBar == null) {
return null;
} else {
return actionBar.getSubtitle();
}
}
public boolean isAlive() {
return !isFinishing() && !isDestroyed();
}
protected void navigateUp() {
final Intent upIntent = NavUtils.getParentActivityIntent(this);
if (upIntent == null) {
finish();
} else if (NavUtils.shouldUpRecreateTask(this, upIntent)) {
TaskStackBuilder.create(this)
.addNextIntentWithParentStack(upIntent)
.startActivities();
} else {
NavUtils.navigateUpTo(this, upIntent);
}
}
@Override
protected void onCreate(final Bundle savedInstanceState) {
// noinspection ConstantConditions, WrongConstant
getDelegate().setLocalNightMode(Preferences.General.Theme.get().getThemeValue());
super.onCreate(savedInstanceState);
Timber.d(TAG, '"' + getActivityName() + "\" created");
ActivityRegister.attach(this);
}
@Override
protected void onDestroy() {
ActivityRegister.detach(this);
super.onDestroy();
}
@Override
public boolean onOptionsItemSelected(final MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
navigateUp();
return true;
}
return super.onOptionsItemSelected(item);
}
protected void onViewsBound() {
ButterKnife.bind(this);
if (mToolbar != null) {
prepareToolbar();
}
final Intent intent = getIntent();
if (intent != null && intent.hasExtra(EXTRA_UI_COLOR_SET)) {
final UiColorSet uiColorSet = intent.getParcelableExtra(EXTRA_UI_COLOR_SET);
applyUiColorSet(uiColorSet);
}
}
private void prepareToolbar() {
setSupportActionBar(mToolbar);
final ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
}
@Override
public void setContentView(@LayoutRes final int layoutResID) {
super.setContentView(layoutResID);
onViewsBound();
}
public void setSubtitle(@StringRes final int resId) {
setSubtitle(getText(resId));
}
public void setSubtitle(@Nullable final CharSequence subtitle) {
final ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setSubtitle(subtitle);
}
}
@Override
public String toString() {
return getActivityName();
}
}
|
package org.apache.commons.vfs;
import org.apache.commons.vfs.util.Messages;
import java.io.IOException;
public final class FileSystemException
extends IOException
{
/**
* The Throwable that caused this exception to be thrown.
*/
private final Throwable throwable;
/**
* The message code.
*/
private final String code;
/**
* array of complementary info (context).
*/
private final String[] info;
/**
* Constructs exception with the specified detail message.
*
* @param code the error code of the message.
*/
public FileSystemException( final String code )
{
this( code, null, null );
}
/**
* Constructs exception with the specified detail message.
*
* @param code the error code of the message.
* @param info0 one context information.
*/
public FileSystemException( final String code, final Object info0 )
{
this( code, new Object[]{info0}, null );
}
/**
* Constructs exception with the specified detail message.
*
* @param code the error code of the message.
* @param info0 one context information.
* @param throwable the cause.
*/
public FileSystemException( final String code,
final Object info0,
final Throwable throwable )
{
this( code, new Object[]{info0}, throwable );
}
/**
* Constructs exception with the specified detail message.
*
* @param code the error code of the message.
* @param info array of complementary info (context).
*/
public FileSystemException( final String code, final Object[] info )
{
this( code, info, null );
}
/**
* Constructs exception with the specified detail message.
*
* @param code the error code of the message.
* @param info array of complementary info (context).
* @param throwable the cause.
*/
public FileSystemException( final String code,
final Object[] info,
final Throwable throwable )
{
super( Messages.getString( code, info ) );
if ( info == null )
{
this.info = new String[ 0 ];
}
else
{
this.info = new String[ info.length ];
for ( int i = 0; i < info.length; i++ )
{
this.info[ i ] = String.valueOf( info[ i ] );
}
}
this.code = code;
this.throwable = throwable;
}
/**
* Constructs wrapper exception.
*
* @param throwable the root cause to wrap.
*/
public FileSystemException( final Throwable throwable )
{
this( throwable.getMessage(), null, throwable );
}
/**
* Retrieve root cause of the exception.
*
* @return the root cause
*/
public final Throwable getCause()
{
return throwable;
}
/**
* Retrieve error code of the exception.
* Could be used as key for internationalization.
*
* @return the code.
*/
public String getCode()
{
return code;
}
/**
* Retrieve array of complementary info (context).
* Could be used as parameter for internationalization.
*
* @return the context info.
*/
public String[] getInfo()
{
return info;
}
}
|
package org.orbeon.oxf.xforms;
import org.orbeon.oxf.common.ValidationException;
import org.orbeon.oxf.properties.Properties;
import org.orbeon.oxf.xml.dom4j.LocationData;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
public class XFormsProperties {
public static final String[] EMPTY_STRING_ARRAY = new String[]{};
public static final String XFORMS_PROPERTY_PREFIX = "oxf.xforms.";
// Document properties
public static final String FUNCTION_LIBRARY_PROPERTY = "function-library";
public static final String STATE_HANDLING_PROPERTY = "state-handling";
public static final String STATE_HANDLING_SERVER_VALUE = "server";
public static final String STATE_HANDLING_CLIENT_VALUE = "client";
public static final String NOSCRIPT_SUPPORT_PROPERTY = "noscript-support";
public static final String NOSCRIPT_PROPERTY = "noscript";
public static final String NOSCRIPT_TEMPLATE = "noscript-template";
public static final String NOSCRIPT_TEMPLATE_STATIC_VALUE = "static";
public static final String READONLY_APPEARANCE_PROPERTY = "readonly-appearance";
public static final String READONLY_APPEARANCE_STATIC_VALUE = "static";
public static final String READONLY_APPEARANCE_DYNAMIC_VALUE = "dynamic";
public static final String READONLY_APPEARANCE_STATIC_SELECT_PROPERTY = "readonly-appearance.static.select";
public static final String READONLY_APPEARANCE_STATIC_SELECT1_PROPERTY = "readonly-appearance.static.select1";
public static final String ORDER_PROPERTY = "order";
public static final String DEFAULT_ORDER_PROPERTY = "label control help alert hint";
public static final String HOST_LANGUAGE = "host-language";
public static final String LABEL_ELEMENT_NAME_PROPERTY = "label-element";
public static final String HINT_ELEMENT_NAME_PROPERTY = "hint-element";
public static final String HELP_ELEMENT_NAME_PROPERTY = "help-element";
public static final String ALERT_ELEMENT_NAME_PROPERTY = "alert-element";
public static final String LABEL_APPEARANCE_PROPERTY = "label.appearance";
public static final String HINT_APPEARANCE_PROPERTY = "hint.appearance";
public static final String HELP_APPEARANCE_PROPERTY = "help.appearance";
public static final String UPLOAD_MAX_SIZE_PROPERTY = "upload.max-size";
public static final String EXTERNAL_EVENTS_PROPERTY = "external-events";
public static final String OPTIMIZE_GET_ALL_PROPERTY = "optimize-get-all";
public static final String OPTIMIZE_LOCAL_SUBMISSION_REPLACE_ALL_PROPERTY = "optimize-local-submission";
public static final String LOCAL_SUBMISSION_FORWARD_PROPERTY = "local-submission-forward";
public static final String LOCAL_SUBMISSION_INCLUDE_PROPERTY = "local-submission-include";
public static final String LOCAL_INSTANCE_INCLUDE_PROPERTY = "local-instance-include";
// public static final String XFORMS_OPTIMIZE_LOCAL_INSTANCE_LOADS_PROPERTY = "optimize-local-instance-loads";
public static final String EXPOSE_XPATH_TYPES_PROPERTY = "expose-xpath-types";
public static final String AJAX_UPDATE_FULL_THRESHOLD = "ajax.update.full.threshold";
public static final String NO_UPDATES = "no-updates";
public static final String TYPE_OUTPUT_FORMAT_PROPERTY_PREFIX = "format.output.";
public static final String TYPE_INPUT_FORMAT_PROPERTY_PREFIX = "format.input.";
public static final String DATE_FORMAT_PROPERTY = TYPE_OUTPUT_FORMAT_PROPERTY_PREFIX + "date";
public static final String DATETIME_FORMAT_PROPERTY = TYPE_OUTPUT_FORMAT_PROPERTY_PREFIX + "dateTime";
public static final String TIME_FORMAT_PROPERTY = TYPE_OUTPUT_FORMAT_PROPERTY_PREFIX + "time";
public static final String DECIMAL_FORMAT_PROPERTY = TYPE_OUTPUT_FORMAT_PROPERTY_PREFIX + "decimal";
public static final String INTEGER_FORMAT_PROPERTY = TYPE_OUTPUT_FORMAT_PROPERTY_PREFIX + "integer";
public static final String FLOAT_FORMAT_PROPERTY = TYPE_OUTPUT_FORMAT_PROPERTY_PREFIX + "float";
public static final String DOUBLE_FORMAT_PROPERTY = TYPE_OUTPUT_FORMAT_PROPERTY_PREFIX + "double";
public static final String DATE_FORMAT_INPUT_PROPERTY = TYPE_INPUT_FORMAT_PROPERTY_PREFIX + "date";
public static final String TIME_FORMAT_INPUT_PROPERTY = TYPE_INPUT_FORMAT_PROPERTY_PREFIX + "time";
public static final String DATEPICKER_NAVIGATOR_PROPERTY = "datepicker.navigator";
public static final String DATEPICKER_TWO_MONTHS_PROPERTY = "datepicker.two-months";
public static final String SHOW_ERROR_DIALOG_PROPERTY = "show-error-dialog";
public static final String SHOW_RECOVERABLE_ERRORS_PROPERTY = "show-recoverable-errors";
public static final String LOGIN_PAGE_DETECTION_REGEXP = "login-page-detection-regexp";
public static final String CLIENT_EVENTS_MODE_PROPERTY = "client.events.mode";
public static final String CLIENT_EVENTS_FILTER_PROPERTY = "client.events.filter";
public static final String SESSION_HEARTBEAT_PROPERTY = "session-heartbeat";
public static final String SESSION_HEARTBEAT_DELAY_PROPERTY = "session-heartbeat-delay";
public static final String DELAY_BEFORE_INCREMENTAL_REQUEST_PROPERTY = "delay-before-incremental-request";
public static final String INTERNAL_SHORT_DELAY_PROPERTY = "internal-short-delay";
public static final String DELAY_BEFORE_DISPLAY_LOADING_PROPERTY = "delay-before-display-loading";
// Could be `upload.delay-before-progress-refresh` for consistency with new properties
public static final String DELAY_BEFORE_UPLOAD_PROGRESS_REFRESH_PROPERTY = "delay-before-upload-progress-refresh";
public static final String REVISIT_HANDLING_PROPERTY = "revisit-handling";
public static final String REVISIT_HANDLING_RESTORE_VALUE = "restore";
public static final String REVISIT_HANDLING_RELOAD_VALUE = "reload";
public static final String HELP_HANDLER_PROPERTY = "help-handler";
public static final String HELP_TOOLTIP_PROPERTY = "help-tooltip";
public static final String ASYNC_SUBMISSION_POLL_DELAY = "submission-poll-delay";
public static final String DELAY_BEFORE_AJAX_TIMEOUT_PROPERTY = "delay-before-ajax-timeout";
public static final String UPLOAD_DELAY_BEFORE_XFORMS_TIMEOUT_PROPERTY = "upload.delay-before-xforms-timeout";
public static final String RETRY_DELAY_INCREMENT = "retry.delay-increment";
public static final String RETRY_MAX_DELAY = "retry.max-delay";
public static final String USE_ARIA = "use-aria";
public static final String XFORMS11_SWITCH_PROPERTY = "xforms11-switch";
public static final String ENCRYPT_ITEM_VALUES_PROPERTY = "encrypt-item-values";
public static final String XPATH_ANALYSIS_PROPERTY = "xpath-analysis";
public static final String CALCULATE_ANALYSIS_PROPERTY = "analysis.calculate";
// TODO: Make this a global property: right now it is used 1/2 global, 1/2 document
public static final String CACHE_DOCUMENT_PROPERTY = "cache.document";
public static final boolean CACHE_DOCUMENT_DEFAULT = true;
public static final String SANITIZE_PROPERTY = "sanitize";
public static final String ASSETS_BASELINE_EXCLUDES_PROPERTY = "assets.baseline.excludes";
public static class PropertyDefinition {
public final String name;
public final Object defaultValue;
public final boolean isPropagateToClient;
public PropertyDefinition(String name, String defaultValue, boolean propagateToClient) {
this.name = name;
this.defaultValue = defaultValue;
isPropagateToClient = propagateToClient;
}
public PropertyDefinition(String name, boolean defaultValue, boolean propagateToClient) {
this.name = name;
this.defaultValue = defaultValue;
isPropagateToClient = propagateToClient;
}
public PropertyDefinition(String name, int defaultValue, boolean propagateToClient) {
this.name = name;
this.defaultValue = defaultValue;
isPropagateToClient = propagateToClient;
}
public final Object parseProperty(String value) {
if (defaultValue instanceof Integer) {
return Integer.parseInt(value);
} else if (defaultValue instanceof Boolean) {
return Boolean.valueOf(value);
} else {
return value;
}
}
public void validate(Object value, LocationData locationData) {}
}
public static final PropertyDefinition[] SUPPORTED_DOCUMENT_PROPERTIES_DEFAULTS = {
new PropertyDefinition(STATE_HANDLING_PROPERTY, STATE_HANDLING_SERVER_VALUE, false) {
@Override
public void validate(Object value, LocationData locationData) {
final String stringValue = value.toString();
if (!(stringValue.equals(XFormsProperties.STATE_HANDLING_SERVER_VALUE)
|| stringValue.equals(XFormsProperties.STATE_HANDLING_CLIENT_VALUE)))
throw new ValidationException("Invalid xxf:" + name
+ " property value value: " + stringValue, locationData);
}
},
new PropertyDefinition(READONLY_APPEARANCE_PROPERTY, READONLY_APPEARANCE_DYNAMIC_VALUE, false) {
@Override
public void validate(Object value, LocationData locationData) {
final String stringValue = value.toString();
if (! XFormsUtils.maybeAVT(stringValue) && !(stringValue.equals(XFormsProperties.READONLY_APPEARANCE_STATIC_VALUE)
|| stringValue.equals(XFormsProperties.READONLY_APPEARANCE_DYNAMIC_VALUE)))
throw new ValidationException("Invalid xxf:" + name
+ " property value value: " + stringValue, locationData);
}
},
new PropertyDefinition(
DATE_FORMAT_PROPERTY,
"if (. castable as xs:date) then format-date(xs:date(.), '[FNn] [MNn] [D], [Y] [ZN]', 'en', (), ()) else .",
false
),
new PropertyDefinition(
DATETIME_FORMAT_PROPERTY,
"if (. castable as xs:dateTime) then format-dateTime(xs:dateTime(.), '[FNn] [MNn] [D], [Y] [H01]:[m01]:[s01] [ZN]', 'en', (), ()) else .",
false
),
new PropertyDefinition(
TIME_FORMAT_PROPERTY,
"if (. castable as xs:time) then format-time(xs:time(.), '[H01]:[m01]:[s01] [ZN]', 'en', (), ()) else .",
false
),
new PropertyDefinition(
DECIMAL_FORMAT_PROPERTY,
"if (. castable as xs:decimal) then format-number(xs:decimal(.),'
false
),
new PropertyDefinition(
INTEGER_FORMAT_PROPERTY,
"if (. castable as xs:integer) then format-number(xs:integer(.),'
false
),
new PropertyDefinition(
FLOAT_FORMAT_PROPERTY,
"if (. castable as xs:float) then format-number(xs:float(.),'#,##0.000') else .",
false
),
new PropertyDefinition(
DOUBLE_FORMAT_PROPERTY,
"if (. castable as xs:double) then format-number(xs:double(.),'#,##0.000') else .",
false
),
new PropertyDefinition(FUNCTION_LIBRARY_PROPERTY , "", false),
new PropertyDefinition(NOSCRIPT_SUPPORT_PROPERTY , true, false),
new PropertyDefinition(NOSCRIPT_PROPERTY , false, false),
new PropertyDefinition(NOSCRIPT_TEMPLATE , NOSCRIPT_TEMPLATE_STATIC_VALUE, false),
new PropertyDefinition(READONLY_APPEARANCE_STATIC_SELECT_PROPERTY , "full", false),
new PropertyDefinition(READONLY_APPEARANCE_STATIC_SELECT1_PROPERTY , "full", false),
new PropertyDefinition(ORDER_PROPERTY , DEFAULT_ORDER_PROPERTY, false),
new PropertyDefinition(HOST_LANGUAGE , "xhtml", false),
new PropertyDefinition(LABEL_ELEMENT_NAME_PROPERTY , "label", false),
new PropertyDefinition(HINT_ELEMENT_NAME_PROPERTY , "span", false),
new PropertyDefinition(HELP_ELEMENT_NAME_PROPERTY , "span", false),
new PropertyDefinition(ALERT_ELEMENT_NAME_PROPERTY , "span", false),
new PropertyDefinition(LABEL_APPEARANCE_PROPERTY , "full", false),
new PropertyDefinition(HINT_APPEARANCE_PROPERTY , "full", false),
new PropertyDefinition(HELP_APPEARANCE_PROPERTY , "dialog", false),
new PropertyDefinition(UPLOAD_MAX_SIZE_PROPERTY , "", false), // blank default (see #2956)
new PropertyDefinition(UPLOAD_DELAY_BEFORE_XFORMS_TIMEOUT_PROPERTY , 45000, false),
new PropertyDefinition(EXTERNAL_EVENTS_PROPERTY , "", false),
new PropertyDefinition(OPTIMIZE_GET_ALL_PROPERTY , true, false),
new PropertyDefinition(OPTIMIZE_LOCAL_SUBMISSION_REPLACE_ALL_PROPERTY, true, false),
new PropertyDefinition(LOCAL_SUBMISSION_FORWARD_PROPERTY , true, false),
new PropertyDefinition(LOCAL_SUBMISSION_INCLUDE_PROPERTY , false, false),
new PropertyDefinition(LOCAL_INSTANCE_INCLUDE_PROPERTY , false, false),
new PropertyDefinition(EXPOSE_XPATH_TYPES_PROPERTY , false, false),
new PropertyDefinition(SHOW_RECOVERABLE_ERRORS_PROPERTY , 10, false),
new PropertyDefinition(ENCRYPT_ITEM_VALUES_PROPERTY , true, false),
new PropertyDefinition(ASYNC_SUBMISSION_POLL_DELAY , 10 * 1000, false),
new PropertyDefinition(AJAX_UPDATE_FULL_THRESHOLD , 20, false),
new PropertyDefinition(NO_UPDATES , false, false),
new PropertyDefinition(XFORMS11_SWITCH_PROPERTY , false, false),
new PropertyDefinition(XPATH_ANALYSIS_PROPERTY , false, false),
new PropertyDefinition(CALCULATE_ANALYSIS_PROPERTY , false, false),
new PropertyDefinition(CACHE_DOCUMENT_PROPERTY , CACHE_DOCUMENT_DEFAULT, false),
new PropertyDefinition(SANITIZE_PROPERTY , "", false),
new PropertyDefinition(ASSETS_BASELINE_EXCLUDES_PROPERTY , "", false),
// Properties to propagate to the client
new PropertyDefinition(RETRY_DELAY_INCREMENT , 5000, true),
new PropertyDefinition(RETRY_MAX_DELAY , 30000, true),
new PropertyDefinition(USE_ARIA , false, true),
new PropertyDefinition(SESSION_HEARTBEAT_PROPERTY , true, true),
new PropertyDefinition(SESSION_HEARTBEAT_DELAY_PROPERTY , 12 * 60 * 60 * 800, true), // dynamic; 80 % of 12 hours in ms
new PropertyDefinition(DELAY_BEFORE_INCREMENTAL_REQUEST_PROPERTY , 500, true),
new PropertyDefinition(DELAY_BEFORE_AJAX_TIMEOUT_PROPERTY , 30000, true),
new PropertyDefinition(INTERNAL_SHORT_DELAY_PROPERTY , 10, true),
new PropertyDefinition(DELAY_BEFORE_DISPLAY_LOADING_PROPERTY , 500, true),
new PropertyDefinition(DELAY_BEFORE_UPLOAD_PROGRESS_REFRESH_PROPERTY , 2000, true),
new PropertyDefinition(REVISIT_HANDLING_PROPERTY , REVISIT_HANDLING_RESTORE_VALUE, true),
new PropertyDefinition(HELP_HANDLER_PROPERTY , false, true), // dynamic
new PropertyDefinition(HELP_TOOLTIP_PROPERTY , false, true),
new PropertyDefinition(DATE_FORMAT_INPUT_PROPERTY , "[M]/[D]/[Y]", true),
new PropertyDefinition(TIME_FORMAT_INPUT_PROPERTY , "[h]:[m]:[s] [P]", true),
new PropertyDefinition(DATEPICKER_NAVIGATOR_PROPERTY , true, true),
new PropertyDefinition(DATEPICKER_TWO_MONTHS_PROPERTY , false, true),
new PropertyDefinition(SHOW_ERROR_DIALOG_PROPERTY , true, true),
new PropertyDefinition(LOGIN_PAGE_DETECTION_REGEXP , "", true),
new PropertyDefinition(CLIENT_EVENTS_MODE_PROPERTY , "default", true),
new PropertyDefinition(CLIENT_EVENTS_FILTER_PROPERTY , "", true),
};
public static final Map<String, PropertyDefinition> SUPPORTED_DOCUMENT_PROPERTIES;
static {
final Map<String, PropertyDefinition> tempMap = new HashMap<String, PropertyDefinition>();
for (final PropertyDefinition propertyDefinition: SUPPORTED_DOCUMENT_PROPERTIES_DEFAULTS) {
tempMap.put(propertyDefinition.name, propertyDefinition);
}
SUPPORTED_DOCUMENT_PROPERTIES = Collections.unmodifiableMap(tempMap);
}
// Global properties
public static final String GZIP_STATE_PROPERTY = XFORMS_PROPERTY_PREFIX + "gzip-state"; // global but could possibly be per document
public static final boolean GZIP_STATE_DEFAULT = true;
public static final String HOST_LANGUAGE_AVTS_PROPERTY = XFORMS_PROPERTY_PREFIX + "host-language-avts"; // global but should be per document
public static final String ADDITIONAL_AVT_ELEMENT_NAMESPACES = XFORMS_PROPERTY_PREFIX + "additional-avt-element-namespaces"; // global but should be per document
public static final String ADDITIONAL_REF_ID_ATTRIBUTE_NAMES = XFORMS_PROPERTY_PREFIX + "additional-ref-id-attribute-names"; // global but should be per document
public static final boolean HOST_LANGUAGE_AVTS_DEFAULT = false;
public static final String MINIMAL_RESOURCES_PROPERTY = XFORMS_PROPERTY_PREFIX + "minimal-resources";
public static final boolean MINIMAL_RESOURCES_PROPERTY_DEFAULT = true;
public static final String COMBINE_RESOURCES_PROPERTY = XFORMS_PROPERTY_PREFIX + "combine-resources";
public static final boolean COMBINE_RESOURCES_PROPERTY_DEFAULT = true;
public static final String CACHE_COMBINED_RESOURCES_PROPERTY = XFORMS_PROPERTY_PREFIX + "cache-combined-resources";
public static final boolean CACHE_COMBINED_RESOURCES_DEFAULT = false;
public static final String JAVASCRIPT_AT_BOTTOM_PROPERTY = XFORMS_PROPERTY_PREFIX + "resources.javascript-at-bottom";
public static final boolean JAVASCRIPT_AT_BOTTOM_PROPERTY_DEFAULT = true;
public static final String ENCODE_VERSION_PROPERTY = XFORMS_PROPERTY_PREFIX + "resources.encode-version";
public static final boolean ENCODE_VERSION_PROPERTY_DEFAULT = true;
public static final String DEBUG_LOGGING_PROPERTY = XFORMS_PROPERTY_PREFIX + "logging.debug";
public static final String ERROR_LOGGING_PROPERTY = XFORMS_PROPERTY_PREFIX + "logging.error";
public static final String DEBUG_LOG_XPATH_ANALYSIS_PROPERTY = XFORMS_PROPERTY_PREFIX + "debug.log-xpath-analysis";
public static final String DEBUG_REQUEST_STATS_PROPERTY = XFORMS_PROPERTY_PREFIX + "debug.log-request-stats";
public static final String LOCATION_MODE_PROPERTY = XFORMS_PROPERTY_PREFIX + "location-mode";
/**
* Return a PropertyDefinition given a property name.
*
* @param propertyName property name
* @return PropertyDefinition
*/
public static PropertyDefinition getPropertyDefinition(String propertyName) {
return SUPPORTED_DOCUMENT_PROPERTIES.get(propertyName);
}
public static Set<String> getDebugLogging() {
final Set<String> result = Properties.instance().getPropertySet().getNmtokens(DEBUG_LOGGING_PROPERTY);
return (result != null) ? result : Collections.<String>emptySet();
}
public static Set<String> getErrorLogging() {
final Set<String> result = Properties.instance().getPropertySet().getNmtokens(ERROR_LOGGING_PROPERTY);
return (result != null) ? result : Collections.<String>emptySet();
}
public static boolean isCacheDocument() {
return Properties.instance().getPropertySet().getBoolean
(CACHE_DOCUMENT_PROPERTY, CACHE_DOCUMENT_DEFAULT);
}
public static boolean isGZIPState() {
return Properties.instance().getPropertySet().getBoolean
(GZIP_STATE_PROPERTY, GZIP_STATE_DEFAULT);
}
public static boolean isHostLanguageAVTs() {
return Properties.instance().getPropertySet().getBoolean
(HOST_LANGUAGE_AVTS_PROPERTY, HOST_LANGUAGE_AVTS_DEFAULT);
}
public static String[] getAdditionalAvtElementNamespaces() {
final String additionalElementNamespacesStr = Properties.instance().getPropertySet().getString
(ADDITIONAL_AVT_ELEMENT_NAMESPACES);
return additionalElementNamespacesStr != null ? additionalElementNamespacesStr.split("\\s+") : EMPTY_STRING_ARRAY;
}
public static String[] getAdditionalRefIdAttributeNames() {
String additionalRefIdAttributeNames = Properties.instance().getPropertySet().getString
(ADDITIONAL_REF_ID_ATTRIBUTE_NAMES);
return additionalRefIdAttributeNames != null ? additionalRefIdAttributeNames.split("\\s+") : EMPTY_STRING_ARRAY;
}
public static boolean isMinimalResources() {
return Properties.instance().getPropertySet().getBoolean
(MINIMAL_RESOURCES_PROPERTY, MINIMAL_RESOURCES_PROPERTY_DEFAULT);
}
public static boolean isCombinedResources() {
return Properties.instance().getPropertySet().getBoolean
(COMBINE_RESOURCES_PROPERTY, COMBINE_RESOURCES_PROPERTY_DEFAULT);
}
public static boolean isCacheCombinedResources() {
return Properties.instance().getPropertySet().getBoolean
(CACHE_COMBINED_RESOURCES_PROPERTY, CACHE_COMBINED_RESOURCES_DEFAULT);
}
public static boolean isJavaScriptAtBottom() {
return Properties.instance().getPropertySet().getBoolean
(JAVASCRIPT_AT_BOTTOM_PROPERTY, JAVASCRIPT_AT_BOTTOM_PROPERTY_DEFAULT);
}
public static boolean isEncodeVersion() {
return Properties.instance().getPropertySet().getBoolean
(ENCODE_VERSION_PROPERTY, ENCODE_VERSION_PROPERTY_DEFAULT);
}
public static boolean getDebugLogXPathAnalysis() {
return Properties.instance().getPropertySet().getBoolean(DEBUG_LOG_XPATH_ANALYSIS_PROPERTY, false);
}
public static boolean isRequestStats() {
return Properties.instance().getPropertySet().getBoolean(DEBUG_REQUEST_STATS_PROPERTY, false);
}
public static long getAjaxTimeout() {
return (long) Properties.instance().getPropertySet().getInteger(XFORMS_PROPERTY_PREFIX + DELAY_BEFORE_AJAX_TIMEOUT_PROPERTY, ((Integer) getPropertyDefinition(DELAY_BEFORE_AJAX_TIMEOUT_PROPERTY).defaultValue).intValue());
}
public static long uploadXFormsAccessTimeout() {
return (long) Properties.instance().getPropertySet().getInteger(XFORMS_PROPERTY_PREFIX + UPLOAD_DELAY_BEFORE_XFORMS_TIMEOUT_PROPERTY, ((Integer) getPropertyDefinition(UPLOAD_DELAY_BEFORE_XFORMS_TIMEOUT_PROPERTY).defaultValue).intValue());
}
public static int getRetryDelayIncrement() {
return Properties.instance().getPropertySet().getInteger(XFORMS_PROPERTY_PREFIX + RETRY_DELAY_INCREMENT, ((Integer) getPropertyDefinition(RETRY_DELAY_INCREMENT).defaultValue).intValue());
}
public static boolean isKeepLocation() {
return ! Properties.instance().getPropertySet().getString(LOCATION_MODE_PROPERTY, "none").equals("none");
}
}
|
package org.duckdns.raven.ttscallresponder;
import org.duckdns.raven.ttscallresponder.answeredCallList.ActivityAnsweredCallList;
import org.duckdns.raven.ttscallresponder.domain.PersistentAnsweredCallList;
import org.duckdns.raven.ttscallresponder.domain.PersistentPreparedResponseList;
import org.duckdns.raven.ttscallresponder.domain.PreparedResponse;
import org.duckdns.raven.ttscallresponder.preparedTextList.ActivityPreparedResponseList;
import org.duckdns.raven.ttscallresponder.settings.ActivitySettings;
import org.duckdns.raven.ttscallresponder.settings.SettingsManager;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.text.format.Time;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
private final static String TAG = "MainActivity";
private Switch swiAutoRespond = null;
private TextView currentPreparedResponseTitle = null;
private TextView numberOfAnsweredCalls = null;
private final Time lastBackPressed = new Time();
private TtsCallResponderService mCallResponderService = null;
private final ServiceConnection mConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName className, IBinder service) {
MainActivity.this.mCallResponderService = ((TtsCallResponderService.LocalBinder) service).getService();
MainActivity.this.applyCallReceiverState();
}
@Override
public void onServiceDisconnected(ComponentName className) {
MainActivity.this.mCallResponderService = null;
MainActivity.this.applyCallReceiverState();
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
Log.i(MainActivity.TAG, "Enter on Create");
super.onCreate(savedInstanceState);
this.setContentView(R.layout.activity_main);
// Instantiate needed stuff
SettingsManager.setContext(this);
// Bind responder service
Intent bindCallReceiverService = new Intent(this, TtsCallResponderService.class);
this.bindService(bindCallReceiverService, this.mConnection, BIND_AUTO_CREATE);
// Get access to UI elements
this.swiAutoRespond = (Switch) this.findViewById(R.id.switch_answerCalls);
this.currentPreparedResponseTitle = (TextView) this.findViewById(R.id.textView_currentPreparedResponseTitle);
this.numberOfAnsweredCalls = (TextView) this.findViewById(R.id.textView_numberOfAnsweredCalls);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
this.getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public void onResume() {
super.onResume();
String currentTitle = null;
// Retrieve data
PreparedResponse currentPreparedResponse = PersistentPreparedResponseList.getSingleton(this.getFilesDir())
.getItemWithId(SettingsManager.getCurrentPreparedResponseId());
if (currentPreparedResponse == null) {
Log.d(MainActivity.TAG, "No current response set");
currentTitle = "<None>";
} else
currentTitle = currentPreparedResponse.getTitle();
// Initialize UI elements
this.currentPreparedResponseTitle.setText(currentTitle);
this.applyCallReceiverState();
this.updateNumberOfAnsweredCalls();
}
private void applyCallReceiverState() {
boolean running = false;
if (this.mCallResponderService != null)
running = this.mCallResponderService.isRunning();
this.swiAutoRespond.setChecked(running);
}
public void updateNumberOfAnsweredCalls() {
this.numberOfAnsweredCalls.setText("" + PersistentAnsweredCallList.getSingleton(this.getFilesDir()).getCount());
}
private void startCallReceiverService() {
Intent startCallReceiverService = new Intent(this, TtsCallResponderService.class);
this.startService(startCallReceiverService);
}
private void stopCallReceiverService() {
Intent stopCallReceiverService = new Intent(this, TtsCallResponderService.class);
this.mCallResponderService.stopService(stopCallReceiverService);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
Intent switchToSettings = new Intent(this, ActivitySettings.class);
this.startActivity(switchToSettings);
return true;
}
return super.onOptionsItemSelected(item);
}
public void onSwitchAutorespondClick(View view) {
Switch swiAutoRespond = (Switch) this.findViewById(R.id.switch_answerCalls);
if (swiAutoRespond.isChecked())
this.startCallReceiverService();
else
this.stopCallReceiverService();
}
public void onShowAnsweredCallListClick(View view) {
Intent switchToCallList = new Intent(this, ActivityAnsweredCallList.class);
switchToCallList.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
this.startActivity(switchToCallList);
}
public void onShowPreparedResopnseList(View view) {
Intent switchToPreparedResopnseList = new Intent(this, ActivityPreparedResponseList.class);
this.startActivity(switchToPreparedResopnseList);
}
@Override
protected void onDestroy() {
Log.i(MainActivity.TAG, "Enter onDestroy");
this.unbindService(this.mConnection);
super.onDestroy();
}
@Override
public void finish() {
this.stopCallReceiverService();
super.finish();
}
@Override
public void onBackPressed() {
Time nowBackPressed = new Time();
nowBackPressed.setToNow();
if (this.mCallResponderService == null || !this.mCallResponderService.isRunning()) {
this.finish();
return;
}
if (nowBackPressed.toMillis(true) - this.lastBackPressed.toMillis(true) < 3000) {
this.finish();
} else {
Toast.makeText(this,
"Press \'Back\' again to stop receiving calls.\nTo keep the receiver running, use \'Home\'.",
Toast.LENGTH_LONG).show();
this.lastBackPressed.setToNow();
}
}
}
|
package org.batfish.common.bdd;
import static com.google.common.base.Preconditions.checkArgument;
import static org.batfish.common.bdd.BDDUtils.swapPairing;
import com.google.common.base.Suppliers;
import com.google.common.collect.ImmutableMap;
import com.google.errorprone.annotations.concurrent.LazyInit;
import java.io.IOException;
import java.io.Serializable;
import java.util.BitSet;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.function.BiFunction;
import java.util.function.Supplier;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import net.sf.javabdd.BDD;
import net.sf.javabdd.BDDFactory;
import net.sf.javabdd.BDDPairing;
import net.sf.javabdd.JFactory;
import org.batfish.common.bdd.BDDFlowConstraintGenerator.FlowPreference;
import org.batfish.datamodel.Flow;
import org.batfish.datamodel.Ip;
import org.batfish.datamodel.IpProtocol;
import org.batfish.datamodel.acl.AclLineMatchExprs;
/**
* A collection of attributes describing an packet, represented using BDDs
*
* @author Ryan Beckett
*/
public class BDDPacket implements Serializable {
/*
* Initial size of the BDD factory node table. Automatically resized as needed. Increasing this
* will reduce time spent garbage collecting for large computations, but will waste memory for
* smaller ones.
*/
private static final int JFACTORY_INITIAL_NODE_TABLE_SIZE = 1_000_000;
/*
* The ratio of node table size to node cache size to preserve when resizing. The default
* value is 0, which means never resize the cache.
*/
private static final int JFACTORY_CACHE_RATIO = 8;
/*
* Initial size of the BDD factory node cache. Automatically resized when the node table is,
* to preserve the cache ratio.
*/
private static final int JFACTORY_INITIAL_NODE_CACHE_SIZE =
(JFACTORY_INITIAL_NODE_TABLE_SIZE + JFACTORY_CACHE_RATIO - 1) / JFACTORY_CACHE_RATIO;
/*
* The first BDD variable used to encode packets. Clients can use these bits anyway they want to.
*/
public static final int FIRST_PACKET_VAR = 100;
private static final int DSCP_LENGTH = 6;
private static final int ECN_LENGTH = 2;
private static final int FRAGMENT_OFFSET_LENGTH = 13;
private static final int ICMP_CODE_LENGTH = 8;
private static final int ICMP_TYPE_LENGTH = 8;
private static final int IP_LENGTH = 32;
private static final int IP_PROTOCOL_LENGTH = 8;
private static final int PORT_LENGTH = 16;
private static final int TCP_FLAG_LENGTH = 1;
private static final int PACKET_LENGTH_LENGTH = 16;
private final Map<Integer, String> _bitNames;
private final BDDFactory _factory;
private int _nextFreeBDDVarIdxBeforePacketVars = 0;
private int _nextFreeBDDVarIdx = FIRST_PACKET_VAR;
// Packet bits
private final @Nonnull ImmutableBDDInteger _dscp;
private final @Nonnull PrimedBDDInteger _dstIp;
private final @Nonnull PrimedBDDInteger _dstPort;
private final @Nonnull ImmutableBDDInteger _ecn;
private final @Nonnull ImmutableBDDInteger _fragmentOffset;
private final @Nonnull BDDIcmpCode _icmpCode;
private final @Nonnull BDDIcmpType _icmpType;
private final @Nonnull BDDIpProtocol _ipProtocol;
private final @Nonnull BDDPacketLength _packetLength;
private final @Nonnull PrimedBDDInteger _srcIp;
private final @Nonnull PrimedBDDInteger _srcPort;
private final @Nonnull BDD _tcpAck;
private final @Nonnull BDD _tcpCwr;
private final @Nonnull BDD _tcpEce;
private final @Nonnull BDD _tcpFin;
private final @Nonnull BDD _tcpPsh;
private final @Nonnull BDD _tcpRst;
private final @Nonnull BDD _tcpSyn;
private final @Nonnull BDD _tcpUrg;
private final @Nonnull BDD _tcpFlags;
private final BDDPairing _swapSourceAndDestinationPairing;
@LazyInit private @Nullable BDD _saneFlow;
// Generating flow preference for representative flow picking
private transient Supplier<BDDFlowConstraintGenerator> _flowConstraintGeneratorSupplier;
private transient IpSpaceToBDD _dstIpSpaceToBDD;
private transient IpSpaceToBDD _srcIpSpaceToBDD;
public static BDDFactory defaultFactory(BiFunction<Integer, Integer, BDDFactory> init) {
BDDFactory factory =
init.apply(JFACTORY_INITIAL_NODE_TABLE_SIZE, JFACTORY_INITIAL_NODE_CACHE_SIZE);
factory.setCacheRatio(JFACTORY_CACHE_RATIO);
return factory;
}
/**
* Creates a collection of BDD variables representing the various attributes of a control plane
* advertisement.
*/
public BDDPacket() {
this(defaultFactory(JFactory::init));
}
/**
* Creates a collection of BDD variables representing the various attributes of a control plane
* advertisement using the given existing {@link BDDFactory}.
*/
public BDDPacket(BDDFactory factory) {
_factory = factory;
// Make sure we have the right number of variables
int numNeeded =
FIRST_PACKET_VAR // reserved for auxiliary variables before packet vars
+ IP_LENGTH * 4 // primed/unprimed src/dst
+ PORT_LENGTH * 4 // primed/unprimed src/dst
+ IP_PROTOCOL_LENGTH
+ ICMP_CODE_LENGTH
+ ICMP_TYPE_LENGTH
+ TCP_FLAG_LENGTH * 8
+ DSCP_LENGTH
+ ECN_LENGTH
+ FRAGMENT_OFFSET_LENGTH
+ PACKET_LENGTH_LENGTH;
if (_factory.varNum() < numNeeded) {
_factory.setVarNum(numNeeded);
}
_bitNames = new HashMap<>();
_dstIp = allocatePrimedBDDInteger("dstIp", IP_LENGTH);
_srcIp = allocatePrimedBDDInteger("srcIp", IP_LENGTH);
_dstPort = allocatePrimedBDDInteger("dstPort", PORT_LENGTH);
_srcPort = allocatePrimedBDDInteger("srcPort", PORT_LENGTH);
_ipProtocol = new BDDIpProtocol(allocateBDDInteger("ipProtocol", IP_PROTOCOL_LENGTH));
_icmpCode = new BDDIcmpCode(allocateBDDInteger("icmpCode", ICMP_CODE_LENGTH));
_icmpType = new BDDIcmpType(allocateBDDInteger("icmpType", ICMP_TYPE_LENGTH));
_tcpAck = allocateBDDBit("tcpAck");
_tcpCwr = allocateBDDBit("tcpCwr");
_tcpEce = allocateBDDBit("tcpEce");
_tcpFin = allocateBDDBit("tcpFin");
_tcpPsh = allocateBDDBit("tcpPsh");
_tcpRst = allocateBDDBit("tcpRst");
_tcpSyn = allocateBDDBit("tcpSyn");
_tcpUrg = allocateBDDBit("tcpUrg");
_tcpFlags =
factory.andLiterals(_tcpAck, _tcpCwr, _tcpEce, _tcpFin, _tcpPsh, _tcpRst, _tcpSyn, _tcpUrg);
_dscp = allocateBDDInteger("dscp", DSCP_LENGTH);
_ecn = allocateBDDInteger("ecn", ECN_LENGTH);
_fragmentOffset = allocateBDDInteger("fragmentOffset", FRAGMENT_OFFSET_LENGTH);
_packetLength = new BDDPacketLength(allocateBDDInteger("packetLength", PACKET_LENGTH_LENGTH));
_swapSourceAndDestinationPairing =
swapPairing(
BDDUtils.concatBitvectors(_dstIp.getVar()._bitvec, _dstPort.getVar()._bitvec),
BDDUtils.concatBitvectors(_srcIp.getVar()._bitvec, _srcPort.getVar()._bitvec));
initTransientFields();
}
private void initTransientFields() {
_flowConstraintGeneratorSupplier =
Suppliers.memoize(() -> new BDDFlowConstraintGenerator(this));
_dstIpSpaceToBDD = new IpSpaceToBDD(_dstIp.getVar());
_srcIpSpaceToBDD = new IpSpaceToBDD(_srcIp.getVar());
}
private void readObject(java.io.ObjectInputStream stream)
throws IOException, ClassNotFoundException {
stream.defaultReadObject();
initTransientFields();
}
public @Nonnull BDD getSaneFlowConstraint() {
BDD ret = _saneFlow;
if (ret == null) {
IpAccessListToBdd toBdd =
new IpAccessListToBddImpl(
this, BDDSourceManager.empty(this), ImmutableMap.of(), ImmutableMap.of());
ret = toBdd.convert(AclLineMatchExprs.VALID_FLOWS);
_saneFlow = ret;
}
// Make a copy, just in case the caller does something silly like try to free it.
return ret.id();
}
/*
* Helper function that builds a map from BDD variable index
* to some more meaningful name. Helpful for debugging.
*/
private void addBitNames(String s, int length, int index) {
for (int i = index; i < index + length; i++) {
_bitNames.put(i, s + (i - index + 1));
}
}
/**
* Allocate a new single-bit {@link BDD} variable.
*
* @param name Used for debugging.
* @return A {@link BDD} representing the sentence "this variable is true" for the new variable.
*/
public BDD allocateBDDBit(String name) {
return allocateBDDBitAfterPacketVars(name);
}
/**
* Allocate a new single-bit {@link BDD} variable.
*
* @param name Used for debugging.
* @param preferBeforePacketVars Whether the variable should be allocated before the variables
* used to encode packet headers. If true, and there are no remaining variables before the
* packet headers, will try to allocate after.
* @return A {@link BDD} representing the sentence "this variable is true" for the new variable.
*/
public BDD allocateBDDBit(String name, boolean preferBeforePacketVars) {
return preferBeforePacketVars && _nextFreeBDDVarIdxBeforePacketVars < FIRST_PACKET_VAR
? allocateBDDBitBeforePacketVars(name)
: allocateBDDBitAfterPacketVars(name);
}
private BDD allocateBDDBitAfterPacketVars(String name) {
if (_factory.varNum() < _nextFreeBDDVarIdx + 1) {
_factory.setVarNum(_nextFreeBDDVarIdx + 1);
}
_bitNames.put(_nextFreeBDDVarIdx, name);
BDD bdd = _factory.ithVar(_nextFreeBDDVarIdx);
_nextFreeBDDVarIdx++;
return bdd;
}
/**
* Allocate a new single-bit {@link BDD} variable before the variables used to encode packet
* headers. Requires such a variable is available.
*
* @param name Used for debugging.
* @return A {@link BDD} representing the sentence "this variable is true" for the new variable.
*/
private BDD allocateBDDBitBeforePacketVars(String name) {
checkArgument(
_nextFreeBDDVarIdxBeforePacketVars < FIRST_PACKET_VAR,
"No unassigned variable before packet vars");
_bitNames.put(_nextFreeBDDVarIdxBeforePacketVars, name);
BDD bdd = _factory.ithVar(_nextFreeBDDVarIdxBeforePacketVars);
_nextFreeBDDVarIdxBeforePacketVars++;
return bdd;
}
/**
* Allocate a new {@link ImmutableBDDInteger} variable.
*
* @param name Used for debugging.
* @param bits The number of bits to allocate.
* @return The new variable.
*/
public ImmutableBDDInteger allocateBDDInteger(String name, int bits) {
return allocateBDDInteger(name, bits, false);
}
/**
* Allocate a new {@link ImmutableBDDInteger} variable.
*
* @param name Used for debugging.
* @param bits The number of bits to allocate.
* @param preferBeforePacketVars Whether the variable should be allocated before the variables
* used to encode packet headers. If true, and there are no remaining variables before the
* packet headers, will try to allocate after.
* @return The new variable.
*/
public ImmutableBDDInteger allocateBDDInteger(
String name, int bits, boolean preferBeforePacketVars) {
BDD[] vars =
preferBeforePacketVars && _nextFreeBDDVarIdxBeforePacketVars + bits < FIRST_PACKET_VAR
? allocateBDDBitsBeforePacketVars(name, bits)
: allocateBDDBitsAfterPacketVars(name, bits);
return new ImmutableBDDInteger(_factory, vars);
}
/**
* Allocate {@link BDD} variables before the variables used to encode packet headers. Requires
* there are enough such variables available.
*
* @param name Used for debugging.
* @param bits The number of bits to allocate.
* @return An array of the new {@link BDD} variables.
*/
private BDD[] allocateBDDBitsBeforePacketVars(String name, int bits) {
checkArgument(
_nextFreeBDDVarIdxBeforePacketVars + bits < FIRST_PACKET_VAR,
"not enough unassigned variables before packet vars");
BDD[] bdds = new BDD[bits];
for (int i = 0; i < bits; i++) {
bdds[i] = _factory.ithVar(_nextFreeBDDVarIdxBeforePacketVars + i);
}
addBitNames(name, bits, _nextFreeBDDVarIdxBeforePacketVars);
_nextFreeBDDVarIdxBeforePacketVars += bits;
return bdds;
}
/**
* Allocate {@link BDD} variables.
*
* @param name Used for debugging.
* @param bits The number of bits to allocate.
* @return An array of the new {@link BDD} variables.
*/
private BDD[] allocateBDDBitsAfterPacketVars(String name, int bits) {
if (_factory.varNum() < _nextFreeBDDVarIdx + bits) {
_factory.setVarNum(_nextFreeBDDVarIdx + bits);
}
BDD[] bdds = new BDD[bits];
for (int i = 0; i < bits; i++) {
bdds[i] = _factory.ithVar(_nextFreeBDDVarIdx + i);
}
addBitNames(name, bits, _nextFreeBDDVarIdx);
_nextFreeBDDVarIdx += bits;
return bdds;
}
/** Create a new {@link PrimedBDDInteger} with interleaved unprimed and primed variables. */
private PrimedBDDInteger allocatePrimedBDDInteger(String name, int length) {
checkArgument(
_factory.varNum() >= _nextFreeBDDVarIdx + length * 2,
"Not enough variables to create PrimedBDDInteger");
BDD[] vars = new BDD[length];
BDD[] primedVars = new BDD[length];
for (int i = 0; i < length; i++) {
_bitNames.put(_nextFreeBDDVarIdx, name + i);
vars[i] = _factory.ithVar(_nextFreeBDDVarIdx++);
_bitNames.put(_nextFreeBDDVarIdx, name + "'" + i);
primedVars[i] = _factory.ithVar(_nextFreeBDDVarIdx++);
}
return new PrimedBDDInteger(_factory, vars, primedVars);
}
public IpSpaceToBDD getDstIpSpaceToBDD() {
return _dstIpSpaceToBDD;
}
public IpSpaceToBDD getSrcIpSpaceToBDD() {
return _srcIpSpaceToBDD;
}
/**
* @return The {@link BDDFactory} used by this packet.
*/
public BDDFactory getFactory() {
return _factory;
}
/**
* Get a representative flow in a BDD according to a given preference.
*
* @param bdd a BDD representing a set of packet headers
* @param preference a FlowPreference representing flow preference
* @return A Flow.Builder for a representative of the set, if it's non-empty
*/
public Optional<Flow.Builder> getFlow(BDD bdd, FlowPreference preference) {
BDD saneBDD = bdd.and(getSaneFlowConstraint());
if (saneBDD.isZero()) {
return Optional.empty();
}
BDD representativeBDD = getFlowBDD(saneBDD, preference);
if (representativeBDD.isZero()) {
// Should not be possible if the preference is well-formed.
return Optional.of(getRepresentativeFlow(saneBDD));
}
return Optional.of(getRepresentativeFlow(representativeBDD));
}
/**
* Restrict a BDD according to a given flow preference.
*
* @param bdd a BDD representing a set of packet headers
* @param preference a FlowPreference representing flow preference
* @return A BDD restricted to more preferred flows. Note that the return value is NOT a full
* assignment.
*/
public @Nonnull BDD getFlowBDD(BDD bdd, FlowPreference preference) {
BDD saneBDD = bdd.and(getSaneFlowConstraint());
if (saneBDD.isZero()) {
return saneBDD;
}
return BDDRepresentativePicker.pickRepresentative(
saneBDD, _flowConstraintGeneratorSupplier.get().getFlowPreference(preference));
}
/**
* Get a representative flow in a BDD. First, try to get an ICMP echo request flow; second, try to
* get a UDP flow used for traceroute; third, try to get a TCP flow with a named port; finally try
* to get an arbitrary one.
*
* @param bdd a BDD representing a set of packet headers
* @return A Flow.Builder for a representative of the set, if it's non-empty
*/
public Optional<Flow.Builder> getFlow(BDD bdd) {
return getFlow(bdd, FlowPreference.DEBUGGING);
}
public @Nonnull Flow.Builder getRepresentativeFlow(BDD bdd) {
BDD saneBDD = bdd.and(getSaneFlowConstraint());
checkArgument(!saneBDD.isZero(), "The input set of flows does not contain any valid flows");
return getFromFromAssignment(saneBDD.minAssignmentBits());
}
public Flow.Builder getFromFromAssignment(BitSet bits) {
IpProtocol protocol = _ipProtocol.satAssignmentToValue(bits);
Flow.Builder fb = Flow.builder();
fb.setDstIp(Ip.create(_dstIp.getVar().satAssignmentToLong(bits)));
fb.setSrcIp(Ip.create(_srcIp.getVar().satAssignmentToLong(bits)));
fb.setIpProtocol(protocol);
fb.setDscp(_dscp.satAssignmentToInt(bits));
fb.setEcn(_ecn.satAssignmentToInt(bits));
fb.setFragmentOffset(_fragmentOffset.satAssignmentToInt(bits));
fb.setPacketLength(_packetLength.satAssignmentToValue(bits));
if (IpProtocol.IP_PROTOCOLS_WITH_PORTS.contains(protocol)) {
fb.setDstPort(_dstPort.getVar().satAssignmentToInt(bits));
fb.setSrcPort(_srcPort.getVar().satAssignmentToInt(bits));
}
if (protocol == IpProtocol.ICMP) {
fb.setIcmpCode(_icmpCode.satAssignmentToValue(bits));
fb.setIcmpType(_icmpType.satAssignmentToValue(bits));
}
if (protocol == IpProtocol.TCP) {
fb.setTcpFlagsAck(bits.get(_tcpAck.level()));
fb.setTcpFlagsCwr(bits.get(_tcpCwr.level()));
fb.setTcpFlagsEce(bits.get(_tcpEce.level()));
fb.setTcpFlagsFin(bits.get(_tcpFin.level()));
fb.setTcpFlagsPsh(bits.get(_tcpPsh.level()));
fb.setTcpFlagsRst(bits.get(_tcpRst.level()));
fb.setTcpFlagsSyn(bits.get(_tcpSyn.level()));
fb.setTcpFlagsUrg(bits.get(_tcpUrg.level()));
}
return fb;
}
@Nonnull
public ImmutableBDDInteger getDscp() {
return _dscp;
}
@Nonnull
public ImmutableBDDInteger getDstIp() {
return _dstIp.getVar();
}
@Nonnull
public PrimedBDDInteger getDstIpPrimedBDDInteger() {
return _dstIp;
}
@Nonnull
public ImmutableBDDInteger getDstPort() {
return _dstPort.getVar();
}
@Nonnull
public PrimedBDDInteger getDstPortPrimedBDDInteger() {
return _dstPort;
}
@Nonnull
public ImmutableBDDInteger getEcn() {
return _ecn;
}
@Nonnull
public ImmutableBDDInteger getFragmentOffset() {
return _fragmentOffset;
}
@Nonnull
public BDDIcmpCode getIcmpCode() {
return _icmpCode;
}
@Nonnull
public BDDIcmpType getIcmpType() {
return _icmpType;
}
@Nonnull
public BDDIpProtocol getIpProtocol() {
return _ipProtocol;
}
@Nonnull
public BDDPacketLength getPacketLength() {
return _packetLength;
}
@Nonnull
public ImmutableBDDInteger getSrcIp() {
return _srcIp.getVar();
}
@Nonnull
public PrimedBDDInteger getSrcIpPrimedBDDInteger() {
return _srcIp;
}
@Nonnull
public ImmutableBDDInteger getSrcPort() {
return _srcPort.getVar();
}
@Nonnull
public PrimedBDDInteger getSrcPortPrimedBDDInteger() {
return _srcPort;
}
/**
* Returns an assignment BDD with all TCP flags true.
*
* <p>May be useful for {@link BDD#project(BDD)}, {@link BDD#testsVars(BDD)}, or similar
* operations.
*/
@Nonnull
public BDD getTcpFlagsVars() {
return _tcpFlags;
}
@Nonnull
public BDD getTcpAck() {
return _tcpAck;
}
@Nonnull
public BDD getTcpCwr() {
return _tcpCwr;
}
@Nonnull
public BDD getTcpEce() {
return _tcpEce;
}
@Nonnull
public BDD getTcpFin() {
return _tcpFin;
}
@Nonnull
public BDD getTcpPsh() {
return _tcpPsh;
}
@Nonnull
public BDD getTcpRst() {
return _tcpRst;
}
@Nonnull
public BDD getTcpSyn() {
return _tcpSyn;
}
@Nonnull
public BDD getTcpUrg() {
return _tcpUrg;
}
@Override
public int hashCode() {
int result = _dstIp.hashCode();
result = 31 * result + _srcIp.hashCode();
result = 31 * result + _dstPort.hashCode();
result = 31 * result + _srcPort.hashCode();
result = 31 * result + _icmpCode.hashCode();
result = 31 * result + _icmpType.hashCode();
result = 31 * result + _ipProtocol.hashCode();
result = 31 * result + _tcpAck.hashCode();
result = 31 * result + _tcpCwr.hashCode();
result = 31 * result + _tcpEce.hashCode();
result = 31 * result + _tcpFin.hashCode();
result = 31 * result + _tcpPsh.hashCode();
result = 31 * result + _tcpRst.hashCode();
result = 31 * result + _tcpSyn.hashCode();
result = 31 * result + _tcpUrg.hashCode();
result = 31 * result + _dscp.hashCode();
result = 31 * result + _ecn.hashCode();
result = 31 * result + _fragmentOffset.hashCode();
return result;
}
@Override
public boolean equals(Object o) {
if (!(o instanceof BDDPacket)) {
return false;
}
BDDPacket other = (BDDPacket) o;
return _dstIp.equals(other._dstIp)
&& _srcIp.equals(other._srcIp)
&& _srcPort.equals(other._srcPort)
&& _dstPort.equals(other._dstPort)
&& _icmpCode.equals(other._icmpCode)
&& _icmpType.equals(other._icmpType)
&& _ipProtocol.equals(other._ipProtocol)
&& _tcpAck.equals(other._tcpAck)
&& _tcpCwr.equals(other._tcpCwr)
&& _tcpEce.equals(other._tcpEce)
&& _tcpFin.equals(other._tcpFin)
&& _tcpPsh.equals(other._tcpPsh)
&& _tcpRst.equals(other._tcpRst)
&& _tcpSyn.equals(other._tcpSyn)
&& _tcpUrg.equals(other._tcpUrg)
&& _dscp.equals(other._dscp)
&& _ecn.equals(other._ecn)
&& _fragmentOffset.equals(other._fragmentOffset);
}
public BDD swapSourceAndDestinationFields(BDD bdd) {
return bdd.replace(_swapSourceAndDestinationPairing);
}
}
|
package com.groupon.lex.metrics;
import com.groupon.lex.metrics.api.ApiServer;
import com.groupon.lex.metrics.config.Configuration;
import com.groupon.lex.metrics.config.ConfigurationException;
import com.groupon.lex.metrics.history.CollectHistory;
import com.groupon.lex.metrics.httpd.EndpointRegistration;
import java.io.File;
import java.io.IOException;
import java.io.Reader;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import static java.util.Collections.singletonList;
import java.util.List;
import lombok.NonNull;
public class PipelineBuilder {
/**
* A supplier for Push Processors.
*
* The supplier takes an endpoint registration object, which can be used to
* create additional endpoints for this processor.
*/
public static interface PushProcessorSupplier {
public PushProcessor build(EndpointRegistration epr) throws Exception;
}
public static final int DEFAULT_API_PORT = 9998;
public static final int DEFAULT_COLLECT_INTERVAL_SECONDS = 60;
@NonNull
private final Configuration cfg_;
private InetSocketAddress api_sockaddr_ = new InetSocketAddress(DEFAULT_API_PORT);
private CollectHistory history_;
private EndpointRegistration epr_;
private int collect_interval_seconds_ = DEFAULT_COLLECT_INTERVAL_SECONDS;
/** Create a new pipeline with the given configuration. */
public PipelineBuilder(@NonNull Configuration cfg) {
cfg_ = cfg;
}
/** Create a new pipeline builder from a reader. */
public PipelineBuilder(File dir, Reader reader) throws IOException, ConfigurationException {
cfg_ = Configuration.readFromFile(dir, reader).resolve();
}
/** Create a new pipeline builder from the given file. */
public PipelineBuilder(File file) throws IOException, ConfigurationException {
cfg_ = Configuration.readFromFile(file).resolve();
}
/** Make the API listen on the specified port. */
public PipelineBuilder withApiPort(int api_port) {
return withApiSockaddr(new InetSocketAddress(api_port));
}
/** Make the API listen on the specified address. */
public PipelineBuilder withApiSockaddr(@NonNull InetSocketAddress api_sockaddr) {
api_sockaddr_ = api_sockaddr;
return this;
}
/** Use a non-standard API server. */
public PipelineBuilder withApi(EndpointRegistration epr) {
epr_ = epr;
return this;
}
/** Add a history module. */
public PipelineBuilder withHistory(CollectHistory history) {
history_ = history;
return this;
}
/** Use the specified seconds as scrape interval. */
public PipelineBuilder withCollectIntervalSeconds(int seconds) {
if (seconds <= 0) throw new IllegalArgumentException("not enough seconds: " + seconds);
collect_interval_seconds_ = seconds;
return this;
}
/**
* Creates a push processor.
*
* The API server is started by this method.
* The returned push processor is not started.
* @param processor_suppliers A list of PushProcessorSupplier, that will instantiate the push processors.
* @return A Push Processor pipeline. You'll need to start it yourself.
* @throws Exception indicating construction failed.
* Push Processors that were created before the exception was thrown, will be closed.
*/
public PushProcessorPipeline build(List<PushProcessorSupplier> processor_suppliers) throws Exception {
ApiServer api = null;
PushMetricRegistryInstance registry = null;
final List<PushProcessor> processors = new ArrayList<>(processor_suppliers.size());
try {
final EndpointRegistration epr;
if (epr_ == null)
epr = api = new ApiServer(api_sockaddr_);
else
epr = epr_;
registry = cfg_.create(epr);
for (PushProcessorSupplier pps : processor_suppliers)
processors.add(pps.build(api));
if (history_ != null)
registry.setHistory(history_);
if (api != null) api.start();
return new PushProcessorPipeline(registry, collect_interval_seconds_, processors);
} catch (Exception ex) {
if (api != null) api.close();
if (registry != null) registry.close();
for (PushProcessor pp : processors)
pp.close();
throw ex;
}
}
/**
* Creates a push processor.
*
* The API server is started by this method.
* The returned push processor is not started.
* @param processor_supplier A PushProcessorSupplier, that will instantiate the push processor.
* @return A Push Processor pipeline. You'll need to start it yourself.
* @throws Exception indicating construction failed.
* Push Processors that were created before the exception was thrown, will be closed.
*/
public PushProcessorPipeline build(PushProcessorSupplier processor_supplier) throws Exception {
return build(singletonList(processor_supplier));
}
}
|
package org.osiam.storage.entities;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
import org.osiam.resources.scim.Group;
import com.google.common.collect.ImmutableSet;
/**
* Entity class for {@link Group} resources
*/
@Entity
@Table(name = "scim_group")
public class GroupEntity extends ResourceEntity {
@ManyToMany
private Set<ResourceEntity> members = new HashSet<>();
@Column(unique = true, nullable = false)
private String displayName;
public GroupEntity() {
getMeta().setResourceType("Group");
}
public Set<ResourceEntity> getMembers() {
return ImmutableSet.copyOf(members);
}
public void addMember(ResourceEntity member) {
if (members.contains(member)) {
return;
}
this.members.add(member);
member.addToGroup(this);
}
public void removeMember(ResourceEntity member) {
if (!members.contains(member)) {
return;
}
members.remove(member);
member.removeFromGroup(this);
}
/**
* Removes all members from this group.
*/
public void removeAllMembers() {
Set<ResourceEntity> membersToRemove = ImmutableSet.copyOf(members);
for (ResourceEntity member : membersToRemove) {
removeMember(member);
}
}
@Override
public String getDisplayName() {
return displayName;
}
public void setDisplayName(String displayName) {
this.displayName = displayName;
}
@Override
public String toString() {
return "GroupEntity{" +
"UUID='" + getId() + "\', " +
"displayName='" + displayName + '\'' +
'}';
}
}
|
package com.firefly.mvc.web.view;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.firefly.mvc.web.View;
import com.firefly.mvc.web.servlet.SystemHtmlPage;
import com.firefly.server.exception.HttpServerException;
import com.firefly.server.http.Config;
import com.firefly.server.http.Constants;
import com.firefly.server.http.HttpServletResponseImpl;
import com.firefly.server.io.StaticFileOutputStream;
import com.firefly.utils.RandomUtils;
import com.firefly.utils.StringUtils;
import com.firefly.utils.VerifyUtils;
import com.firefly.utils.log.Log;
import com.firefly.utils.log.LogFactory;
public class StaticFileView implements View {
private static Log log = LogFactory.getInstance().getLog("firefly-system");
public static final String CRLF = "\r\n";
private static Set<String> ALLOW_METHODS = new HashSet<String>(Arrays.asList("GET", "POST", "HEAD"));
private static String RANGE_ERROR_HTML = SystemHtmlPage.systemPageTemplate(416,
"None of the range-specifier values in the Range request-header field overlap the current extent of the selected resource.");
private static Config CONFIG;
private static String TEMPLATE_PATH;
private final String inputPath;
public StaticFileView(String path) {
this.inputPath = path;
}
public static void init(Config serverConfig, String tempPath) {
if(CONFIG == null && serverConfig != null)
CONFIG = serverConfig;
if(TEMPLATE_PATH == null && tempPath != null)
TEMPLATE_PATH = tempPath;
}
@Override
public void render(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
if(inputPath.startsWith(TEMPLATE_PATH)) {
SystemHtmlPage.responseSystemPage(request, response,
CONFIG.getEncoding(), HttpServletResponse.SC_NOT_FOUND,
request.getRequestURI() + " not found");
return;
}
if(!ALLOW_METHODS.contains(request.getMethod())) {
response.setHeader("Allow", "GET,POST,HEAD");
SystemHtmlPage.responseSystemPage(request, response, CONFIG.getEncoding(),
HttpServletResponse.SC_METHOD_NOT_ALLOWED, "Only support GET, POST or HEAD method");
return;
}
String path = CONFIG.getFileAccessFilter().doFilter(request, response, inputPath);
if (VerifyUtils.isEmpty(path))
return;
File file = new File(CONFIG.getServerHome(), path);
if (!file.exists() || file.isDirectory()) {
SystemHtmlPage.responseSystemPage(request, response,
CONFIG.getEncoding(), HttpServletResponse.SC_NOT_FOUND,
request.getRequestURI() + " not found");
return;
}
String fileSuffix = getFileSuffix(file.getName()).toLowerCase();
String contentType = Constants.MIME.get(fileSuffix);
if (contentType == null) {
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment; filename="
+ file.getName());
} else {
String[] type = StringUtils.split(contentType, '/');
if ("application".equals(type[0])) {
response.setHeader("Content-Disposition",
"attachment; filename=" + file.getName());
} else if ("text".equals(type[0])) {
contentType += "; charset=" + CONFIG.getEncoding();
}
response.setContentType(contentType);
}
StaticFileOutputStream out = null;
try {
out = ((HttpServletResponseImpl) response)
.getStaticFileOutputStream();
long fileLen = file.length();
String range = request.getHeader("Range");
if (range == null) {
out.write(file);
} else {
String[] rangesSpecifier = StringUtils.split(range, '=');
if (rangesSpecifier.length != 2) {
response.setStatus(416);
out.write(RANGE_ERROR_HTML.getBytes(CONFIG.getEncoding()));
return;
}
String byteRangeSet = rangesSpecifier[1].trim();
String[] byteRangeSets = StringUtils.split(byteRangeSet, ',');
if (byteRangeSets.length > 1) { // multipart/byteranges
String boundary = "ff10" + RandomUtils.randomString(13);
if (byteRangeSets.length > CONFIG.getMaxRangeNum()) {
log.error("multipart range more than {}",
CONFIG.getMaxRangeNum());
response.setStatus(416);
out.write(RANGE_ERROR_HTML.getBytes(CONFIG
.getEncoding()));
return;
}
// multipart output
List<MultipartByteranges> tmpByteRangeSets = new ArrayList<MultipartByteranges>(
CONFIG.getMaxRangeNum());
// long otherLen = 0;
for (String t : byteRangeSets) {
String tmp = t.trim();
String[] byteRange = StringUtils.split(tmp, '-');
if (byteRange.length == 1) {
long pos = Long.parseLong(byteRange[0].trim());
if (pos == 0)
continue;
if (tmp.charAt(0) == '-') {
long lastBytePos = fileLen - 1;
long firstBytePos = lastBytePos - pos + 1;
if (firstBytePos > lastBytePos)
continue;
MultipartByteranges multipartByteranges = getMultipartByteranges(
contentType, firstBytePos, lastBytePos,
fileLen, boundary);
tmpByteRangeSets.add(multipartByteranges);
} else if (tmp.charAt(tmp.length() - 1) == '-') {
long firstBytePos = pos;
long lastBytePos = fileLen - 1;
if (firstBytePos > lastBytePos)
continue;
MultipartByteranges multipartByteranges = getMultipartByteranges(
contentType, firstBytePos, lastBytePos,
fileLen, boundary);
tmpByteRangeSets.add(multipartByteranges);
}
} else {
long firstBytePos = Long.parseLong(byteRange[0]
.trim());
long lastBytePos = Long.parseLong(byteRange[1]
.trim());
if (firstBytePos > fileLen
|| firstBytePos >= lastBytePos)
continue;
MultipartByteranges multipartByteranges = getMultipartByteranges(
contentType, firstBytePos, lastBytePos,
fileLen, boundary);
tmpByteRangeSets.add(multipartByteranges);
}
}
if (tmpByteRangeSets.size() > 0) {
response.setStatus(206);
response.setHeader("Accept-Ranges", "bytes");
response.setHeader("Content-Type",
"multipart/byteranges; boundary=" + boundary);
for (MultipartByteranges m : tmpByteRangeSets) {
long length = m.lastBytePos - m.firstBytePos + 1;
out.write(m.head.getBytes(CONFIG.getEncoding()));
out.write(file, m.firstBytePos, length);
}
out.write((CRLF + "--" + boundary + "--" + CRLF)
.getBytes(CONFIG.getEncoding()));
log.debug("multipart download|{}", range);
} else {
response.setStatus(416);
out.write(RANGE_ERROR_HTML.getBytes(CONFIG
.getEncoding()));
return;
}
} else {
String tmp = byteRangeSets[0].trim();
String[] byteRange = StringUtils.split(tmp, '-');
if (byteRange.length == 1) {
long pos = Long.parseLong(byteRange[0].trim());
if (pos == 0) {
response.setStatus(416);
out.write(RANGE_ERROR_HTML.getBytes(CONFIG
.getEncoding()));
return;
}
if (tmp.charAt(0) == '-') {
long lastBytePos = fileLen - 1;
long firstBytePos = lastBytePos - pos + 1;
writePartialFile(request, response, out, file,
firstBytePos, lastBytePos, fileLen);
} else if (tmp.charAt(tmp.length() - 1) == '-') {
writePartialFile(request, response, out, file, pos,
fileLen - 1, fileLen);
} else {
response.setStatus(416);
out.write(RANGE_ERROR_HTML.getBytes(CONFIG
.getEncoding()));
return;
}
} else {
long firstBytePos = Long.parseLong(byteRange[0].trim());
long lastBytePos = Long.parseLong(byteRange[1].trim());
if (firstBytePos > fileLen
|| firstBytePos >= lastBytePos) {
response.setStatus(416);
out.write(RANGE_ERROR_HTML.getBytes(CONFIG
.getEncoding()));
return;
}
if (lastBytePos >= fileLen)
lastBytePos = fileLen - 1;
writePartialFile(request, response, out, file,
firstBytePos, lastBytePos, fileLen);
}
log.debug("single range download|{}", range);
}
}
} catch (Throwable e) {
throw new HttpServerException("get static file output stream error");
} finally {
if (out != null)
try {
// System.out.println("close~~");
out.close();
} catch (IOException e) {
throw new HttpServerException(
"static file output stream close error");
}
}
}
private void writePartialFile(HttpServletRequest request,
HttpServletResponse response, StaticFileOutputStream out,
File file, long firstBytePos, long lastBytePos, long fileLen)
throws Throwable {
long length = lastBytePos - firstBytePos + 1;
if (length <= 0) {
response.setStatus(416);
out.write(RANGE_ERROR_HTML.getBytes(CONFIG.getEncoding()));
return;
}
response.setStatus(206);
response.setHeader("Accept-Ranges", "bytes");
response.setHeader("Content-Range", "bytes " + firstBytePos + "-"
+ lastBytePos + "/" + fileLen);
out.write(file, firstBytePos, length);
}
public static String getFileSuffix(String name) {
if (name.charAt(name.length() - 1) == '.')
return "*";
for (int i = name.length() - 2; i >= 0; i
if (name.charAt(i) == '.') {
return name.substring(i + 1, name.length());
}
}
return "*";
}
private class MultipartByteranges {
public String head;
public long firstBytePos, lastBytePos;
}
private MultipartByteranges getMultipartByteranges(String contentType,
long firstBytePos, long lastBytePos, long fileLen, String boundary) {
MultipartByteranges ret = new MultipartByteranges();
ret.firstBytePos = firstBytePos;
ret.lastBytePos = lastBytePos;
ret.head = CRLF + "--" + boundary + CRLF + "Content-Type: "
+ contentType + CRLF + "Content-range: bytes " + firstBytePos
+ "-" + lastBytePos + "/" + fileLen + CRLF + CRLF;
return ret;
}
}
|
package gov.nih.nci.cabig.caaers.api;
import gov.nih.nci.cabig.caaers.CaaersTestCase;
import gov.nih.nci.cabig.caaers.api.impl.StudyProcessorImpl;
import gov.nih.nci.cabig.caaers.dao.StudyDao;
import gov.nih.nci.cabig.caaers.domain.CtepStudyDisease;
import gov.nih.nci.cabig.caaers.domain.Identifier;
import gov.nih.nci.cabig.caaers.domain.Organization;
import gov.nih.nci.cabig.caaers.domain.Study;
import gov.nih.nci.cabig.caaers.domain.TreatmentAssignment;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
/**
* Test case to test convrsion of jaxb study object to domain study object and call to studymigrator with study domain object.
* @author Monish Dombla
*
*/
public class StudyProcessorImplTest extends CaaersTestCase {
private StudyProcessorImpl studyProcessorImpl = null;
private JAXBContext jaxbContext = null;
private Unmarshaller unmarshaller = null;
private gov.nih.nci.cabig.caaers.webservice.Studies studies = null;
private File xmlFile = null;
private StudyDao studyDao = null;
Identifier identifier = null;
Organization organization = null;
Study updatedStudy = null;
@Override
protected void setUp() throws Exception {
super.setUp();
jaxbContext = JAXBContext.newInstance("gov.nih.nci.cabig.caaers.webservice");
unmarshaller = jaxbContext.createUnmarshaller();
studyProcessorImpl = (StudyProcessorImpl)getDeployedApplicationContext().getBean("studyProcessorImpl");
studyDao = (StudyDao)getDeployedApplicationContext().getBean("studyDao");
updatedStudy = studyDao.getByShortTitle("Study_PCS");
if(updatedStudy != null){
updatedStudy = studyDao.getStudyDesignById(updatedStudy.getId());
studyDao.delete(updatedStudy);
}
}
@Override
protected void tearDown() throws Exception {
super.tearDown();
}
/**
* Tests the update of attributes shortTitle,longTitle,percis,description,phaseCode,
* status,design,multiInsitutionIndicator,adeersReporting,
* Also tests the update of Study Therapies.
* DrugAdministrationTherapyType,RadiationTherapyType,DeviceTherapyType,SurgeryTherapyType,
* BehavioralTherapyType
*
*/
public void testStudyUpdateOfInstanceAtt(){
createStudy("classpath*:gov/nih/nci/cabig/caaers/impl/studydata/CreateStudyTest.xml");
try {
xmlFile = getResources("classpath*:gov/nih/nci/cabig/caaers/impl/studydata/StudyUpdateOfInstanceAtt.xml")[0].getFile();
studies = (gov.nih.nci.cabig.caaers.webservice.Studies)unmarshaller.unmarshal(xmlFile);
List<gov.nih.nci.cabig.caaers.webservice.Study> studyList = studies.getStudy();
if(studyList!=null && !studyList.isEmpty()){
Iterator<gov.nih.nci.cabig.caaers.webservice.Study> iterator = studyList.iterator();
while(iterator.hasNext()){
gov.nih.nci.cabig.caaers.webservice.Study studyDto = iterator.next();
studyProcessorImpl.updateStudy(studyDto);
}
}
updatedStudy = studyDao.getByShortTitle("Study_PCS_Updated");
updatedStudy = studyDao.getStudyDesignById(updatedStudy.getId());
assertNotNull(updatedStudy);
assertEquals("Pancreatic Cancer Study ph 5 Updated", updatedStudy.getLongTitle());
assertEquals("Precis_Updated", updatedStudy.getPrecis());
assertEquals("Test Study_Updated", updatedStudy.getDescription());
assertEquals("Phase III Trial", updatedStudy.getPhaseCode());
assertEquals("Temporarily Closed to Accrual", updatedStudy.getStatus());
assertEquals("BLIND", updatedStudy.getDesign().name());
assertFalse(updatedStudy.getMultiInstitutionIndicator());
assertFalse(updatedStudy.getAdeersReporting());
assertFalse(updatedStudy.getDrugAdministrationTherapyType());
assertFalse(updatedStudy.getRadiationTherapyType());
assertFalse(updatedStudy.getDeviceTherapyType());
assertFalse(updatedStudy.getSurgeryTherapyType());
assertFalse(updatedStudy.getBehavioralTherapyType());
if(updatedStudy != null){
studyDao.delete(updatedStudy);
}
} catch (IOException e) {
e.printStackTrace();
fail("Error running test: " + e.getMessage());
} catch (JAXBException e) {
e.printStackTrace();
fail("Error running test: " + e.getMessage());
}
}
/**
* theCode1 and theCode3 are 2 TreatmentAssignments for the study with shorttitle Study PSC.
* Tests Treatmentassignment updates. The attributes doseLevelOrder,description and comments
* are updated for 2 exisitng treatmentassignments.
*/
public void testStudyUpdateOfTreatmentAssignmentAttr(){
createStudy("classpath*:gov/nih/nci/cabig/caaers/impl/studydata/CreateStudyTest.xml");
try {
xmlFile = getResources("classpath*:gov/nih/nci/cabig/caaers/impl/studydata/StudyUpdateOfTreatmentAssignmentAttr.xml")[0].getFile();
studies = (gov.nih.nci.cabig.caaers.webservice.Studies)unmarshaller.unmarshal(xmlFile);
List<gov.nih.nci.cabig.caaers.webservice.Study> studyList = studies.getStudy();
if(studyList!=null && !studyList.isEmpty()){
Iterator<gov.nih.nci.cabig.caaers.webservice.Study> iterator = studyList.iterator();
while(iterator.hasNext()){
gov.nih.nci.cabig.caaers.webservice.Study studyDto = iterator.next();
studyProcessorImpl.updateStudy(studyDto);
}
}
updatedStudy = studyDao.getByShortTitle("Study_PCS");
updatedStudy = studyDao.getStudyDesignById(updatedStudy.getId());
assertNotNull(updatedStudy);
assertEquals(2, updatedStudy.getTreatmentAssignments().size());
for(TreatmentAssignment treatmentAssignment : updatedStudy.getTreatmentAssignments()){
if(treatmentAssignment.getCode().equals("theCode1")){
assertEquals(2, treatmentAssignment.getDoseLevelOrder().intValue());
assertEquals("Description_Updated", treatmentAssignment.getDescription());
assertEquals("Comments_Updated", treatmentAssignment.getComments());
}
if(treatmentAssignment.getCode().equals("theCode3")){
assertEquals(3, treatmentAssignment.getDoseLevelOrder().intValue());
assertEquals("Description3_Updated", treatmentAssignment.getDescription());
assertEquals("Comments3_Updated", treatmentAssignment.getComments());
}
}
if(updatedStudy != null){
studyDao.delete(updatedStudy);
}
} catch (IOException e) {
e.printStackTrace();
fail("Error running test: " + e.getMessage());
} catch (JAXBException e) {
e.printStackTrace();
fail("Error running test: " + e.getMessage());
}
}
/**
* Study with short title Study PSC has 2 TreatmentAssignments.
* This testcase tests the addition of a TreatmentAssignment to an existing study.
* theCode1 and theCode3 are the existing treatment assignments.
* theCode4 is the new treamentAssignment.
*/
public void testStudyUpdateOfTreatmentAssignmentAdd(){
createStudy("classpath*:gov/nih/nci/cabig/caaers/impl/studydata/CreateStudyTest.xml");
try {
xmlFile = getResources("classpath*:gov/nih/nci/cabig/caaers/impl/studydata/StudyUpdateOfTreatmentAssignmentAdd.xml")[0].getFile();
studies = (gov.nih.nci.cabig.caaers.webservice.Studies)unmarshaller.unmarshal(xmlFile);
List<gov.nih.nci.cabig.caaers.webservice.Study> studyList = studies.getStudy();
if(studyList!=null && !studyList.isEmpty()){
Iterator<gov.nih.nci.cabig.caaers.webservice.Study> iterator = studyList.iterator();
while(iterator.hasNext()){
gov.nih.nci.cabig.caaers.webservice.Study studyDto = iterator.next();
studyProcessorImpl.updateStudy(studyDto);
}
}
updatedStudy = studyDao.getByShortTitle("Study_PCS");
updatedStudy = studyDao.getStudyDesignById(updatedStudy.getId());
assertNotNull(updatedStudy);
assertEquals(3, updatedStudy.getTreatmentAssignments().size());
for(TreatmentAssignment treatmentAssignment : updatedStudy.getTreatmentAssignments()){
if(treatmentAssignment.getCode().equals("theCode1")){
assertEquals(1, treatmentAssignment.getDoseLevelOrder().intValue());
assertEquals("description1", treatmentAssignment.getDescription());
assertEquals("Comments1", treatmentAssignment.getComments());
}
if(treatmentAssignment.getCode().equals("theCode3")){
assertEquals(2, treatmentAssignment.getDoseLevelOrder().intValue());
assertEquals("description3", treatmentAssignment.getDescription());
assertEquals("Comments3", treatmentAssignment.getComments());
}
if(treatmentAssignment.getCode().equals("theCode4")){
assertEquals(4, treatmentAssignment.getDoseLevelOrder().intValue());
assertEquals("description4", treatmentAssignment.getDescription());
assertEquals("Comments4", treatmentAssignment.getComments());
}
}
if(updatedStudy != null){
studyDao.delete(updatedStudy);
}
} catch (IOException e) {
e.printStackTrace();
fail("Error running test: " + e.getMessage());
} catch (JAXBException e) {
e.printStackTrace();
fail("Error running test: " + e.getMessage());
}
}
/**
* Study with short title Study PSC has 2 TreatmentAssignments.
* This testcase tests the deletion of a TreatmentAssignment from existing study.
* theCode1 and theCode3 are the existing treatment assignments.
* theCode3 is the treamentAssignment removed/deleted.
*/
public void testStudyUpdateOfTreatmentAssignmentRemove(){
createStudy("classpath*:gov/nih/nci/cabig/caaers/impl/studydata/CreateStudyTest.xml");
try {
xmlFile = getResources("classpath*:gov/nih/nci/cabig/caaers/impl/studydata/StudyUpdateOfTreatmentAssignmentRemove.xml")[0].getFile();
studies = (gov.nih.nci.cabig.caaers.webservice.Studies)unmarshaller.unmarshal(xmlFile);
List<gov.nih.nci.cabig.caaers.webservice.Study> studyList = studies.getStudy();
if(studyList!=null && !studyList.isEmpty()){
Iterator<gov.nih.nci.cabig.caaers.webservice.Study> iterator = studyList.iterator();
while(iterator.hasNext()){
gov.nih.nci.cabig.caaers.webservice.Study studyDto = iterator.next();
studyProcessorImpl.updateStudy(studyDto);
}
}
updatedStudy = studyDao.getByShortTitle("Study_PCS");
updatedStudy = studyDao.getStudyDesignById(updatedStudy.getId());
assertNotNull(updatedStudy);
assertEquals(1, updatedStudy.getTreatmentAssignments().size());
for(TreatmentAssignment treatmentAssignment : updatedStudy.getTreatmentAssignments()){
if(treatmentAssignment.getCode().equals("theCode1")){
assertEquals(1, treatmentAssignment.getDoseLevelOrder().intValue());
assertEquals("description1", treatmentAssignment.getDescription());
assertEquals("Comments1", treatmentAssignment.getComments());
}
}
if(updatedStudy != null){
studyDao.delete(updatedStudy);
}
} catch (IOException e) {
e.printStackTrace();
fail("Error running test: " + e.getMessage());
} catch (JAXBException e) {
e.printStackTrace();
fail("Error running test: " + e.getMessage());
}
}
/**
* 2 ctepStudyDiseases with term "Chondrosarcoma" and "Medulloblastoma" exists.
* Tests the addition of an other ctepStudyDisease with term "Osteosarcoma"
*/
public void testStudyUpdateOfCtepStudyDiseasesAdd(){
createStudy("classpath*:gov/nih/nci/cabig/caaers/impl/studydata/CreateStudyTest.xml");
try {
xmlFile = getResources("classpath*:gov/nih/nci/cabig/caaers/impl/studydata/StudyUpdateOfCtepStudyDiseasesAdd.xml")[0].getFile();
studies = (gov.nih.nci.cabig.caaers.webservice.Studies)unmarshaller.unmarshal(xmlFile);
List<gov.nih.nci.cabig.caaers.webservice.Study> studyList = studies.getStudy();
if(studyList!=null && !studyList.isEmpty()){
Iterator<gov.nih.nci.cabig.caaers.webservice.Study> iterator = studyList.iterator();
while(iterator.hasNext()){
gov.nih.nci.cabig.caaers.webservice.Study studyDto = iterator.next();
studyProcessorImpl.updateStudy(studyDto);
}
}
updatedStudy = studyDao.getByShortTitle("Study_PCS");
updatedStudy = studyDao.getStudyDesignById(updatedStudy.getId());
assertNotNull(updatedStudy);
assertEquals(3, updatedStudy.getCtepStudyDiseases().size());
for(CtepStudyDisease ctepStudyDisease : updatedStudy.getCtepStudyDiseases()){
if(ctepStudyDisease.getDiseaseTerm().getCtepTerm().equals("Chondrosarcoma")){
assertFalse(ctepStudyDisease.getLeadDisease());
}
if(ctepStudyDisease.getDiseaseTerm().getCtepTerm().equals("Osteosarcoma")){
assertFalse(ctepStudyDisease.getLeadDisease());
}
if(ctepStudyDisease.getDiseaseTerm().getCtepTerm().equals("Medulloblastoma")){
assertTrue(ctepStudyDisease.getLeadDisease());
}
}
if(updatedStudy != null){
studyDao.delete(updatedStudy);
}
} catch (IOException e) {
e.printStackTrace();
fail("Error running test: " + e.getMessage());
} catch (JAXBException e) {
e.printStackTrace();
fail("Error running test: " + e.getMessage());
}
}
/**
* 2 ctepStudyDiseases with terms "Chondrosarcoma" and "Medulloblastoma" exists.
* Tests the deletion of ctepStudyDisease with term "Chondrosarcoma"
*/
public void testStudyUpdateOfCtepStudyDiseasesRemove(){
createStudy("classpath*:gov/nih/nci/cabig/caaers/impl/studydata/CreateStudyTest.xml");
try {
xmlFile = getResources("classpath*:gov/nih/nci/cabig/caaers/impl/studydata/StudyUpdateOfCtepStudyDiseasesRemove.xml")[0].getFile();
studies = (gov.nih.nci.cabig.caaers.webservice.Studies)unmarshaller.unmarshal(xmlFile);
List<gov.nih.nci.cabig.caaers.webservice.Study> studyList = studies.getStudy();
if(studyList!=null && !studyList.isEmpty()){
Iterator<gov.nih.nci.cabig.caaers.webservice.Study> iterator = studyList.iterator();
while(iterator.hasNext()){
gov.nih.nci.cabig.caaers.webservice.Study studyDto = iterator.next();
studyProcessorImpl.updateStudy(studyDto);
}
}
updatedStudy = studyDao.getByShortTitle("Study_PCS");
updatedStudy = studyDao.getStudyDesignById(updatedStudy.getId());
assertNotNull(updatedStudy);
assertEquals(1, updatedStudy.getCtepStudyDiseases().size());
for(CtepStudyDisease ctepStudyDisease : updatedStudy.getCtepStudyDiseases()){
if(ctepStudyDisease.getDiseaseTerm().getCtepTerm().equals("Chondrosarcoma")){
assertFalse(ctepStudyDisease.getLeadDisease());
}
if(ctepStudyDisease.getDiseaseTerm().getCtepTerm().equals("Medulloblastoma")){
assertTrue(ctepStudyDisease.getLeadDisease());
}
}
if(updatedStudy != null){
studyDao.delete(updatedStudy);
}
} catch (IOException e) {
e.printStackTrace();
fail("Error running test: " + e.getMessage());
} catch (JAXBException e) {
e.printStackTrace();
fail("Error running test: " + e.getMessage());
}
}
/**
* 2 ctepStudyDiseases with terms "Chondrosarcoma" and "Medulloblastoma" exists.
* leadDisease = false for Chondrosarcoma
* leadDisease = true for Medulloblastoma
*
* Tests the leadDisease change.
* leadDisease = true for Chondrosarcoma
* leadDisease = false for Medulloblastoma
*/
public void testStudyUpdateOfCtepStudyDiseasesUpdate(){
createStudy("classpath*:gov/nih/nci/cabig/caaers/impl/studydata/CreateStudyTest.xml");
try {
xmlFile = getResources("classpath*:gov/nih/nci/cabig/caaers/impl/studydata/StudyUpdateOfCtepStudyDiseasesUpdate.xml")[0].getFile();
studies = (gov.nih.nci.cabig.caaers.webservice.Studies)unmarshaller.unmarshal(xmlFile);
List<gov.nih.nci.cabig.caaers.webservice.Study> studyList = studies.getStudy();
if(studyList!=null && !studyList.isEmpty()){
Iterator<gov.nih.nci.cabig.caaers.webservice.Study> iterator = studyList.iterator();
while(iterator.hasNext()){
gov.nih.nci.cabig.caaers.webservice.Study studyDto = iterator.next();
studyProcessorImpl.updateStudy(studyDto);
}
}
updatedStudy = studyDao.getByShortTitle("Study_PCS");
updatedStudy = studyDao.getStudyDesignById(updatedStudy.getId());
assertNotNull(updatedStudy);
assertEquals(2, updatedStudy.getCtepStudyDiseases().size());
for(CtepStudyDisease ctepStudyDisease : updatedStudy.getCtepStudyDiseases()){
System.out.println("Term " + ctepStudyDisease.getDiseaseTerm().getCtepTerm());
if(ctepStudyDisease.getDiseaseTerm().getCtepTerm().equals("Chondrosarcoma")){
assertTrue(ctepStudyDisease.getLeadDisease());
}
if(ctepStudyDisease.getDiseaseTerm().getCtepTerm().equals("Medulloblastoma")){
assertFalse(ctepStudyDisease.getLeadDisease());
}
}
if(updatedStudy != null){
studyDao.delete(updatedStudy);
}
} catch (IOException e) {
e.printStackTrace();
fail("Error running test: " + e.getMessage());
} catch (JAXBException e) {
e.printStackTrace();
fail("Error running test: " + e.getMessage());
}
}
private void createStudy(String studyXmlLocation){
try {
xmlFile = getResources(studyXmlLocation)[0].getFile();
studies = (gov.nih.nci.cabig.caaers.webservice.Studies)unmarshaller.unmarshal(xmlFile);
List<gov.nih.nci.cabig.caaers.webservice.Study> studyList = studies.getStudy();
if(studyList!=null && !studyList.isEmpty()){
Iterator<gov.nih.nci.cabig.caaers.webservice.Study> iterator = studyList.iterator();
while(iterator.hasNext()){
gov.nih.nci.cabig.caaers.webservice.Study studyDto = iterator.next();
studyProcessorImpl.createStudy(studyDto);
}
}
} catch (IOException e) {
e.printStackTrace();
fail("Error running test: " + e.getMessage());
} catch (JAXBException e) {
e.printStackTrace();
fail("Error running test: " + e.getMessage());
}
}
private static Resource[] getResources(String pattern) throws IOException {
ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
Resource[] resources = resolver.getResources(pattern);
return resources;
}
}
|
package org.osiam.storage.query;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.Expression;
import javax.persistence.criteria.Join;
import javax.persistence.criteria.JoinType;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.persistence.criteria.SetJoin;
import javax.persistence.metamodel.SetAttribute;
import org.joda.time.format.ISODateTimeFormat;
import org.osiam.resources.scim.Address;
import org.osiam.resources.scim.Email;
import org.osiam.resources.scim.Entitlement;
import org.osiam.resources.scim.Im;
import org.osiam.resources.scim.PhoneNumber;
import org.osiam.resources.scim.Photo;
import org.osiam.storage.entities.AddressEntity;
import org.osiam.storage.entities.AddressEntity_;
import org.osiam.storage.entities.BaseMultiValuedAttributeEntityWithValue_;
import org.osiam.storage.entities.BaseMultiValuedAttributeEntity_;
import org.osiam.storage.entities.EmailEntity;
import org.osiam.storage.entities.EmailEntity_;
import org.osiam.storage.entities.EntitlementEntity;
import org.osiam.storage.entities.EntitlementEntity_;
import org.osiam.storage.entities.GroupEntity;
import org.osiam.storage.entities.GroupEntity_;
import org.osiam.storage.entities.ImEntity;
import org.osiam.storage.entities.ImEntity_;
import org.osiam.storage.entities.MetaEntity_;
import org.osiam.storage.entities.NameEntity_;
import org.osiam.storage.entities.PhoneNumberEntity;
import org.osiam.storage.entities.PhoneNumberEntity_;
import org.osiam.storage.entities.PhotoEntity;
import org.osiam.storage.entities.PhotoEntity_;
import org.osiam.storage.entities.ResourceEntity;
import org.osiam.storage.entities.ResourceEntity_;
import org.osiam.storage.entities.RoleEntity;
import org.osiam.storage.entities.UserEntity;
import org.osiam.storage.entities.UserEntity_;
import org.osiam.storage.entities.X509CertificateEntity;
public enum UserQueryField implements QueryField<UserEntity> {
EXTERNALID("externalid") {
@Override
public Predicate addFilter(Root<UserEntity> root,
FilterConstraint constraint, String value, CriteriaBuilder cb) {
return constraint.createPredicateForStringField(root.get(ResourceEntity_.externalId), value, cb);
}
@Override
public Expression<?> createSortByField(Root<UserEntity> root, CriteriaBuilder cb) {
return root.get(ResourceEntity_.externalId);
}
},
META_CREATED("meta.created") {
@Override
public Predicate addFilter(Root<UserEntity> root,
FilterConstraint constraint, String value, CriteriaBuilder cb) {
Date date = ISODateTimeFormat.dateTimeParser().parseDateTime(value).toDate();
return constraint.createPredicateForDateField(root.get(ResourceEntity_.meta).get(MetaEntity_.created),
date, cb);
}
@Override
public Expression<?> createSortByField(Root<UserEntity> root, CriteriaBuilder cb) {
return root.get(ResourceEntity_.meta).get(MetaEntity_.created);
}
},
META_LASTMODIFIED("meta.lastmodified") {
@Override
public Predicate addFilter(Root<UserEntity> root,
FilterConstraint constraint, String value, CriteriaBuilder cb) {
Date date = ISODateTimeFormat.dateTimeParser().parseDateTime(value).toDate();
return constraint.createPredicateForDateField(
root.get(ResourceEntity_.meta).get(MetaEntity_.lastModified),
date, cb);
}
@Override
public Expression<?> createSortByField(Root<UserEntity> root, CriteriaBuilder cb) {
return root.get(ResourceEntity_.meta).get(MetaEntity_.lastModified);
}
},
META_LOCATION("meta.location") {
@Override
public Predicate addFilter(Root<UserEntity> root,
FilterConstraint constraint, String value, CriteriaBuilder cb) {
return constraint.createPredicateForStringField(root.get(ResourceEntity_.meta)
.get(MetaEntity_.location), value, cb);
}
@Override
public Expression<?> createSortByField(Root<UserEntity> root, CriteriaBuilder cb) {
return root.get(ResourceEntity_.meta).get(MetaEntity_.location);
}
},
USERNAME("username") {
@Override
public Predicate addFilter(Root<UserEntity> root, FilterConstraint constraint,
String value, CriteriaBuilder cb) {
return constraint.createPredicateForStringField(root.get(UserEntity_.userName), value, cb);
}
@Override
public Expression<?> createSortByField(Root<UserEntity> root, CriteriaBuilder cb) {
return root.get(UserEntity_.userName);
}
},
DISPLAYNAME("displayname") {
@Override
public Predicate addFilter(Root<UserEntity> root, FilterConstraint constraint,
String value, CriteriaBuilder cb) {
return constraint.createPredicateForStringField(root.get(UserEntity_.displayName), value, cb);
}
@Override
public Expression<?> createSortByField(Root<UserEntity> root, CriteriaBuilder cb) {
return root.get(UserEntity_.displayName);
}
},
NICKNAME("nickname") {
@Override
public Predicate addFilter(Root<UserEntity> root, FilterConstraint constraint,
String value, CriteriaBuilder cb) {
return constraint.createPredicateForStringField(root.get(UserEntity_.nickName), value, cb);
}
@Override
public Expression<?> createSortByField(Root<UserEntity> root, CriteriaBuilder cb) {
return root.get(UserEntity_.nickName);
}
},
PROFILEURL("profileurl") {
@Override
public Predicate addFilter(Root<UserEntity> root, FilterConstraint constraint,
String value, CriteriaBuilder cb) {
return constraint.createPredicateForStringField(root.get(UserEntity_.profileUrl), value, cb);
}
@Override
public Expression<?> createSortByField(Root<UserEntity> root, CriteriaBuilder cb) {
return root.get(UserEntity_.profileUrl);
}
},
TITLE("title") {
@Override
public Predicate addFilter(Root<UserEntity> root, FilterConstraint constraint,
String value, CriteriaBuilder cb) {
return constraint.createPredicateForStringField(root.get(UserEntity_.title), value, cb);
}
@Override
public Expression<?> createSortByField(Root<UserEntity> root, CriteriaBuilder cb) {
return root.get(UserEntity_.title);
}
},
USERTYPE("usertype") {
@Override
public Predicate addFilter(Root<UserEntity> root, FilterConstraint constraint,
String value, CriteriaBuilder cb) {
return constraint.createPredicateForStringField(root.get(UserEntity_.userType), value, cb);
}
@Override
public Expression<?> createSortByField(Root<UserEntity> root, CriteriaBuilder cb) {
return root.get(UserEntity_.userType);
}
},
PREFERREDLANGUAGE("preferredlanguage") {
@Override
public Predicate addFilter(Root<UserEntity> root, FilterConstraint constraint,
String value, CriteriaBuilder cb) {
return constraint.createPredicateForStringField(root.get(UserEntity_.preferredLanguage), value, cb);
}
@Override
public Expression<?> createSortByField(Root<UserEntity> root, CriteriaBuilder cb) {
return root.get(UserEntity_.preferredLanguage);
}
},
LOCALE("locale") {
@Override
public Predicate addFilter(Root<UserEntity> root, FilterConstraint constraint,
String value, CriteriaBuilder cb) {
return constraint.createPredicateForStringField(root.get(UserEntity_.locale), value, cb);
}
@Override
public Expression<?> createSortByField(Root<UserEntity> root, CriteriaBuilder cb) {
return root.get(UserEntity_.locale);
}
},
TIMEZONE("timezone") {
@Override
public Predicate addFilter(Root<UserEntity> root, FilterConstraint constraint,
String value, CriteriaBuilder cb) {
return constraint.createPredicateForStringField(root.get(UserEntity_.timezone), value, cb);
}
@Override
public Expression<?> createSortByField(Root<UserEntity> root, CriteriaBuilder cb) {
return root.get(UserEntity_.timezone);
}
},
ACTIVE("active") {
@Override
public Predicate addFilter(Root<UserEntity> root, FilterConstraint constraint,
String value, CriteriaBuilder cb) {
return constraint.createPredicateForBooleanField(root.get(UserEntity_.active), Boolean.valueOf(value),
cb);
}
@Override
public Expression<?> createSortByField(Root<UserEntity> root, CriteriaBuilder cb) {
return root.get(UserEntity_.active);
}
},
NAME_FORMATTED("name.formatted") {
@Override
public Predicate addFilter(Root<UserEntity> root, FilterConstraint constraint,
String value, CriteriaBuilder cb) {
return constraint.createPredicateForStringField(root.get(UserEntity_.name).get(NameEntity_.formatted),
value, cb);
}
@Override
public Expression<?> createSortByField(Root<UserEntity> root, CriteriaBuilder cb) {
return root.get(UserEntity_.name).get(NameEntity_.formatted);
}
},
NAME_FAMILYNAME("name.familyname") {
@Override
public Predicate addFilter(Root<UserEntity> root, FilterConstraint constraint,
String value, CriteriaBuilder cb) {
return constraint.createPredicateForStringField(root.get(UserEntity_.name).get(NameEntity_.familyName),
value, cb);
}
@Override
public Expression<?> createSortByField(Root<UserEntity> root, CriteriaBuilder cb) {
return root.get(UserEntity_.name).get(NameEntity_.familyName);
}
},
NAME_GIVENNAME("name.givenname") {
@Override
public Predicate addFilter(Root<UserEntity> root, FilterConstraint constraint,
String value, CriteriaBuilder cb) {
return constraint.createPredicateForStringField(root.get(UserEntity_.name).get(NameEntity_.givenName),
value, cb);
}
@Override
public Expression<?> createSortByField(Root<UserEntity> root, CriteriaBuilder cb) {
return root.get(UserEntity_.name).get(NameEntity_.givenName);
}
},
NAME_MIDDLENAME("name.middlename") {
@Override
public Predicate addFilter(Root<UserEntity> root, FilterConstraint constraint,
String value, CriteriaBuilder cb) {
return constraint.createPredicateForStringField(root.get(UserEntity_.name).get(NameEntity_.middleName),
value, cb);
}
@Override
public Expression<?> createSortByField(Root<UserEntity> root, CriteriaBuilder cb) {
return root.get(UserEntity_.name).get(NameEntity_.middleName);
}
},
NAME_HONORIFICPREFIX("name.honorificprefix") {
@Override
public Predicate addFilter(Root<UserEntity> root, FilterConstraint constraint,
String value, CriteriaBuilder cb) {
return constraint.createPredicateForStringField(
root.get(UserEntity_.name).get(NameEntity_.honorificPrefix), value, cb);
}
@Override
public Expression<?> createSortByField(Root<UserEntity> root, CriteriaBuilder cb) {
return root.get(UserEntity_.name).get(NameEntity_.honorificPrefix);
}
},
NAME_HONORIFICSUFFIX("name.honorificsuffix") {
@Override
public Predicate addFilter(Root<UserEntity> root, FilterConstraint constraint,
String value, CriteriaBuilder cb) {
return constraint.createPredicateForStringField(
root.get(UserEntity_.name).get(NameEntity_.honorificSuffix), value, cb);
}
@Override
public Expression<?> createSortByField(Root<UserEntity> root, CriteriaBuilder cb) {
return root.get(UserEntity_.name).get(NameEntity_.honorificSuffix);
}
},
EMAILS("emails") {
@Override
public Predicate addFilter(Root<UserEntity> root, FilterConstraint constraint,
String value, CriteriaBuilder cb) {
SetJoin<UserEntity, EmailEntity> join = createOrGetJoin(EMAIL_ALIAS, root, UserEntity_.emails);
return constraint.createPredicateForStringField(join.get(BaseMultiValuedAttributeEntityWithValue_.value),
value, cb);
}
@Override
public Expression<?> createSortByField(Root<UserEntity> root, CriteriaBuilder cb) {
throw handleSortByFieldNotSupported(toString());
}
},
EMAILS_VALUE("emails.value") {
@Override
public Predicate addFilter(Root<UserEntity> root, FilterConstraint constraint,
String value, CriteriaBuilder cb) {
SetJoin<UserEntity, EmailEntity> join = createOrGetJoin(EMAIL_ALIAS, root, UserEntity_.emails);
return constraint.createPredicateForStringField(join.get(BaseMultiValuedAttributeEntityWithValue_.value),
value, cb);
}
@Override
public Expression<?> createSortByField(Root<UserEntity> root, CriteriaBuilder cb) {
throw handleSortByFieldNotSupported(toString());
}
},
EMAILS_TYPE("emails.type") {
@Override
public Predicate addFilter(Root<UserEntity> root, FilterConstraint constraint,
String value, CriteriaBuilder cb) {
Email.Type emailType = null;
if (constraint != FilterConstraint.PRESENT) {
emailType = new Email.Type(value);
}
SetJoin<UserEntity, EmailEntity> join = createOrGetJoin(EMAIL_ALIAS, root, UserEntity_.emails);
return constraint.createPredicateForMultiValuedAttributeTypeField(join.get(EmailEntity_.type), // NOSONAR -
// XEntity_.X
// will
// be filled by JPA provider
emailType, cb);
}
@Override
public Expression<?> createSortByField(Root<UserEntity> root, CriteriaBuilder cb) {
throw handleSortByFieldNotSupported(toString());
}
},
EMAILS_PRIMARY("emails.primary") {
@Override
public Predicate addFilter(Root<UserEntity> root, FilterConstraint constraint,
String value, CriteriaBuilder cb) {
SetJoin<UserEntity, EmailEntity> join = createOrGetJoin(EMAIL_ALIAS, root, UserEntity_.emails);
return constraint.createPredicateForBooleanField(join.get(BaseMultiValuedAttributeEntity_.primary), // NOSONAR
// XEntity_.X
// will be filled by JPA provider
Boolean.valueOf(value), cb);
}
@Override
public Expression<?> createSortByField(Root<UserEntity> root, CriteriaBuilder cb) {
throw handleSortByFieldNotSupported(toString());
}
},
PHONENUMBERS("phoneNumbers") {
@Override
public Predicate addFilter(Root<UserEntity> root, FilterConstraint constraint,
String value, CriteriaBuilder cb) {
SetJoin<UserEntity, PhoneNumberEntity> join = createOrGetJoin(PHONENUMBERS_ALIAS, root,
UserEntity_.phoneNumbers);
return constraint.createPredicateForStringField(join.get(BaseMultiValuedAttributeEntityWithValue_.value),
value, cb);
}
@Override
public Expression<?> createSortByField(Root<UserEntity> root, CriteriaBuilder cb) {
throw handleSortByFieldNotSupported(toString());
}
},
PHONENUMBERS_VALUE("phonenumbers.value") {
@Override
public Predicate addFilter(Root<UserEntity> root, FilterConstraint constraint,
String value, CriteriaBuilder cb) {
SetJoin<UserEntity, PhoneNumberEntity> join = createOrGetJoin(PHONENUMBERS_ALIAS, root,
UserEntity_.phoneNumbers);
return constraint.createPredicateForStringField(join.get(BaseMultiValuedAttributeEntityWithValue_.value),
value, cb);
}
@Override
public Expression<?> createSortByField(Root<UserEntity> root, CriteriaBuilder cb) {
throw handleSortByFieldNotSupported(toString());
}
},
PHONENUMBERS_TYPE("phonenumbers.type") {
@Override
public Predicate addFilter(Root<UserEntity> root, FilterConstraint constraint,
String value, CriteriaBuilder cb) {
PhoneNumber.Type phoneNumberType = null;
if (constraint != FilterConstraint.PRESENT) {
phoneNumberType = new PhoneNumber.Type(value);
}
SetJoin<UserEntity, PhoneNumberEntity> join = createOrGetJoin(PHONENUMBERS_ALIAS, root,
UserEntity_.phoneNumbers);
return constraint.createPredicateForMultiValuedAttributeTypeField(join.get(PhoneNumberEntity_.type), // NOSONAR -
// XEntity_.X will be filled by JPA provider
phoneNumberType, cb);
}
@Override
public Expression<?> createSortByField(Root<UserEntity> root, CriteriaBuilder cb) {
throw handleSortByFieldNotSupported(toString());
}
},
IMS("ims") {
@Override
public Predicate addFilter(Root<UserEntity> root, FilterConstraint constraint,
String value, CriteriaBuilder cb) {
SetJoin<UserEntity, ImEntity> join = createOrGetJoin(IMS_ALIAS, root, UserEntity_.ims);
return constraint.createPredicateForStringField(join.get(BaseMultiValuedAttributeEntityWithValue_.value),
value, cb);
}
@Override
public Expression<?> createSortByField(Root<UserEntity> root, CriteriaBuilder cb) {
throw handleSortByFieldNotSupported(toString());
}
},
IMS_VALUE("ims.value") {
@Override
public Predicate addFilter(Root<UserEntity> root, FilterConstraint constraint,
String value, CriteriaBuilder cb) {
SetJoin<UserEntity, ImEntity> join = createOrGetJoin(IMS_ALIAS, root, UserEntity_.ims);
return constraint.createPredicateForStringField(join.get(BaseMultiValuedAttributeEntityWithValue_.value),
value, cb);
}
@Override
public Expression<?> createSortByField(Root<UserEntity> root, CriteriaBuilder cb) {
throw handleSortByFieldNotSupported(toString());
}
},
IMS_TYPE("ims.type") {
@Override
public Predicate addFilter(Root<UserEntity> root, FilterConstraint constraint,
String value, CriteriaBuilder cb) {
Im.Type imType = null;
if (constraint != FilterConstraint.PRESENT) {
imType = new Im.Type(value);
}
SetJoin<UserEntity, ImEntity> join = createOrGetJoin(IMS_ALIAS, root, UserEntity_.ims);
return constraint.createPredicateForMultiValuedAttributeTypeField(join.get(ImEntity_.type), imType, cb); // NOSONAR -
// XEntity_.X will be filled by JPA provider
}
@Override
public Expression<?> createSortByField(Root<UserEntity> root, CriteriaBuilder cb) {
throw handleSortByFieldNotSupported(toString());
}
},
PHOTOS("photos") {
@Override
public Predicate addFilter(Root<UserEntity> root, FilterConstraint constraint,
String value, CriteriaBuilder cb) {
SetJoin<UserEntity, PhotoEntity> join = createOrGetJoin(PHOTOS_ALIAS, root, UserEntity_.photos);
return constraint.createPredicateForStringField(join.get(BaseMultiValuedAttributeEntityWithValue_.value),
value, cb); // NOSONAR -
// XEntity_.X will be filled by JPA provider
}
@Override
public Expression<?> createSortByField(Root<UserEntity> root, CriteriaBuilder cb) {
throw handleSortByFieldNotSupported(toString());
}
},
PHOTOS_VALUE("photos.value") {
@Override
public Predicate addFilter(Root<UserEntity> root, FilterConstraint constraint,
String value, CriteriaBuilder cb) {
SetJoin<UserEntity, PhotoEntity> join = createOrGetJoin(PHOTOS_ALIAS, root, UserEntity_.photos);
return constraint.createPredicateForStringField(join.get(BaseMultiValuedAttributeEntityWithValue_.value),
value, cb);
}
@Override
public Expression<?> createSortByField(Root<UserEntity> root, CriteriaBuilder cb) {
throw handleSortByFieldNotSupported(toString());
}
},
PHOTOS_TYPE("photos.type") {
@Override
public Predicate addFilter(Root<UserEntity> root, FilterConstraint constraint,
String value, CriteriaBuilder cb) {
Photo.Type photoType = null;
if (constraint != FilterConstraint.PRESENT) {
photoType = new Photo.Type(value);
}
SetJoin<UserEntity, PhotoEntity> join = createOrGetJoin(PHOTOS_ALIAS, root, UserEntity_.photos);
return constraint.createPredicateForMultiValuedAttributeTypeField(join.get(PhotoEntity_.type), photoType, cb); // NOSONAR -
// XEntity_.X will be filled by JPA provider
}
@Override
public Expression<?> createSortByField(Root<UserEntity> root, CriteriaBuilder cb) {
throw handleSortByFieldNotSupported(toString());
}
},
ADDRESS_REGION("address.region") {
@Override
public Predicate addFilter(Root<UserEntity> root, FilterConstraint constraint, String value, CriteriaBuilder cb) {
SetJoin<UserEntity, AddressEntity> join = createOrGetJoin(ADDRESS_ALIAS, root,
UserEntity_.addresses);
return constraint.createPredicateForStringField(join.get(AddressEntity_.region), value, cb);
}
@Override
public Expression<?> createSortByField(Root<UserEntity> root, CriteriaBuilder cb) {
throw handleSortByFieldNotSupported(toString());
}
},
ADDRESS_STREETADDRESS("address.streetaddress") {
@Override
public Predicate addFilter(Root<UserEntity> root, FilterConstraint constraint, String value, CriteriaBuilder cb) {
SetJoin<UserEntity, AddressEntity> join = createOrGetJoin(ADDRESS_ALIAS, root,
UserEntity_.addresses);
return constraint.createPredicateForStringField(join.get(AddressEntity_.streetAddress), value, cb);
}
@Override
public Expression<?> createSortByField(Root<UserEntity> root, CriteriaBuilder cb) {
throw handleSortByFieldNotSupported(toString());
}
},
ADDRESS_FORMATTED("address.formatted") {
@Override
public Predicate addFilter(Root<UserEntity> root, FilterConstraint constraint, String value, CriteriaBuilder cb) {
SetJoin<UserEntity, AddressEntity> join = createOrGetJoin(ADDRESS_ALIAS, root,
UserEntity_.addresses);
return constraint.createPredicateForStringField(join.get(AddressEntity_.formatted), value, cb);
}
@Override
public Expression<?> createSortByField(Root<UserEntity> root, CriteriaBuilder cb) {
throw handleSortByFieldNotSupported(toString());
}
},
ADDRESS_POSTALCODE("address.postalcode") {
@Override
public Predicate addFilter(Root<UserEntity> root, FilterConstraint constraint, String value, CriteriaBuilder cb) {
SetJoin<UserEntity, AddressEntity> join = createOrGetJoin(ADDRESS_ALIAS, root,
UserEntity_.addresses);
return constraint.createPredicateForStringField(join.get(AddressEntity_.postalCode), value, cb);
}
@Override
public Expression<?> createSortByField(Root<UserEntity> root, CriteriaBuilder cb) {
throw handleSortByFieldNotSupported(toString());
}
},
ADDRESS_LOCALITY("address.locality") {
@Override
public Predicate addFilter(Root<UserEntity> root, FilterConstraint constraint, String value, CriteriaBuilder cb) {
SetJoin<UserEntity, AddressEntity> join = createOrGetJoin(ADDRESS_ALIAS, root,
UserEntity_.addresses);
return constraint.createPredicateForStringField(join.get(AddressEntity_.locality), value, cb);
}
@Override
public Expression<?> createSortByField(Root<UserEntity> root, CriteriaBuilder cb) {
throw handleSortByFieldNotSupported(toString());
}
},
ADDRESS_TYPE("address.type") {
@Override
public Predicate addFilter(Root<UserEntity> root, FilterConstraint constraint, String value, CriteriaBuilder cb) {
Address.Type addressType = null;
if (constraint != FilterConstraint.PRESENT) {
addressType = new Address.Type(value);
}
SetJoin<UserEntity, AddressEntity> join = createOrGetJoin(ADDRESS_ALIAS, root, UserEntity_.addresses);
return constraint.createPredicateForMultiValuedAttributeTypeField(join.get(AddressEntity_.type),
addressType, cb);
}
@Override
public Expression<?> createSortByField(Root<UserEntity> root, CriteriaBuilder cb) {
throw handleSortByFieldNotSupported(toString());
}
},
ADDRESS_COUNTRY("address.country") {
@Override
public Predicate addFilter(Root<UserEntity> root, FilterConstraint constraint, String value, CriteriaBuilder cb) {
SetJoin<UserEntity, AddressEntity> join = createOrGetJoin(ADDRESS_ALIAS, root,
UserEntity_.addresses);
return constraint.createPredicateForStringField(join.get(AddressEntity_.country), value, cb);
}
@Override
public Expression<?> createSortByField(Root<UserEntity> root, CriteriaBuilder cb) {
throw handleSortByFieldNotSupported(toString());
}
},
ENTITLEMENTS("entitlements") {
@Override
public Predicate addFilter(Root<UserEntity> root, FilterConstraint constraint,
String value, CriteriaBuilder cb) {
SetJoin<UserEntity, EntitlementEntity> join = createOrGetJoin("entitlements", root,
UserEntity_.entitlements);
return constraint.createPredicateForStringField(join.get(BaseMultiValuedAttributeEntityWithValue_.value),
value, cb);
}
@Override
public Expression<?> createSortByField(Root<UserEntity> root, CriteriaBuilder cb) {
throw handleSortByFieldNotSupported(toString());
}
},
ENTITLEMENTS_VALUE("entitlements.value") {
@Override
public Predicate addFilter(Root<UserEntity> root, FilterConstraint constraint,
String value, CriteriaBuilder cb) {
SetJoin<UserEntity, EntitlementEntity> join = createOrGetJoin("entitlements", root,
UserEntity_.entitlements);
return constraint.createPredicateForStringField(join.get(BaseMultiValuedAttributeEntityWithValue_.value),
value, cb);
}
@Override
public Expression<?> createSortByField(Root<UserEntity> root, CriteriaBuilder cb) {
throw handleSortByFieldNotSupported(toString());
}
},
ENTITLEMENTS_TYPE("entitlements.type") {
@Override
public Predicate addFilter(Root<UserEntity> root, FilterConstraint constraint, String value, CriteriaBuilder cb) {
Entitlement.Type type = null;
if (constraint != FilterConstraint.PRESENT) {
type = new Entitlement.Type(value);
}
SetJoin<UserEntity, EntitlementEntity> join = createOrGetJoin(ENTITLEMENTS_ALIAS, root, UserEntity_.entitlements);
return constraint.createPredicateForMultiValuedAttributeTypeField(join.get(EntitlementEntity_.type),
type, cb);
}
@Override
public Expression<?> createSortByField(Root<UserEntity> root, CriteriaBuilder cb) {
throw handleSortByFieldNotSupported(toString());
}
},
ROLES("roles") {
@Override
public Predicate addFilter(Root<UserEntity> root, FilterConstraint constraint,
String value, CriteriaBuilder cb) {
SetJoin<UserEntity, RoleEntity> join = createOrGetJoin("roles", root,
UserEntity_.roles);
return constraint.createPredicateForStringField(join.get(BaseMultiValuedAttributeEntityWithValue_.value),
value, cb);
}
@Override
public Expression<?> createSortByField(Root<UserEntity> root, CriteriaBuilder cb) {
throw handleSortByFieldNotSupported(toString());
}
},
ROLES_VALUE("roles.value") {
@Override
public Predicate addFilter(Root<UserEntity> root, FilterConstraint constraint,
String value, CriteriaBuilder cb) {
SetJoin<UserEntity, RoleEntity> join = createOrGetJoin("roles", root,
UserEntity_.roles);
return constraint.createPredicateForStringField(join.get(BaseMultiValuedAttributeEntityWithValue_.value),
value, cb);
}
@Override
public Expression<?> createSortByField(Root<UserEntity> root, CriteriaBuilder cb) {
throw handleSortByFieldNotSupported(toString());
}
},
X509CERTIFICATES("x509certificates") {
@Override
public Predicate addFilter(Root<UserEntity> root, FilterConstraint constraint,
String value, CriteriaBuilder cb) {
SetJoin<UserEntity, X509CertificateEntity> join = createOrGetJoin("x509Certificates", root,
UserEntity_.x509Certificates);
return constraint.createPredicateForStringField(join.get(BaseMultiValuedAttributeEntityWithValue_.value),
value, cb);
}
@Override
public Expression<?> createSortByField(Root<UserEntity> root, CriteriaBuilder cb) {
throw handleSortByFieldNotSupported(toString());
}
},
X509CERTIFICATES_VALUE("x509certificates.value") {
@Override
public Predicate addFilter(Root<UserEntity> root, FilterConstraint constraint,
String value, CriteriaBuilder cb) {
SetJoin<UserEntity, X509CertificateEntity> join = createOrGetJoin("x509Certificates", root,
UserEntity_.x509Certificates);
return constraint.createPredicateForStringField(join.get(BaseMultiValuedAttributeEntityWithValue_.value),
value, cb);
}
@Override
public Expression<?> createSortByField(Root<UserEntity> root, CriteriaBuilder cb) {
throw handleSortByFieldNotSupported(toString());
}
},
GROUPS("groups") {
@Override
public Predicate addFilter(Root<UserEntity> root, FilterConstraint constraint,
String value, CriteriaBuilder cb) {
SetJoin<UserEntity, GroupEntity> join = createOrGetJoinForGroups(GROUPS_ALIAS, root,
ResourceEntity_.groups);
return constraint.createPredicateForStringField(join.get(ResourceEntity_.id), value, cb);
}
@Override
public Expression<?> createSortByField(Root<UserEntity> root, CriteriaBuilder cb) {
throw handleSortByFieldNotSupported(toString());
}
},
GROUPS_VALUE("groups.value") {
@Override
public Predicate addFilter(Root<UserEntity> root, FilterConstraint constraint,
String value, CriteriaBuilder cb) {
SetJoin<UserEntity, GroupEntity> join = createOrGetJoinForGroups(GROUPS_ALIAS, root,
ResourceEntity_.groups);
return constraint.createPredicateForStringField(join.get(ResourceEntity_.id), value, cb);
}
@Override
public Expression<?> createSortByField(Root<UserEntity> root, CriteriaBuilder cb) {
throw handleSortByFieldNotSupported(toString());
}
},
GROUPS_DISPLAY("groups.display") {
@Override
public Predicate addFilter(Root<UserEntity> root, FilterConstraint constraint,
String value, CriteriaBuilder cb) {
SetJoin<UserEntity, GroupEntity> join = createOrGetJoinForGroups(GROUPS_ALIAS, root,
ResourceEntity_.groups);
return constraint.createPredicateForStringField(join.get(GroupEntity_.displayName), value, cb);
}
@Override
public Expression<?> createSortByField(Root<UserEntity> root, CriteriaBuilder cb) {
throw handleSortByFieldNotSupported(toString());
}
};
private static final Map<String, UserQueryField> STRING_TO_ENUM = new HashMap<>();
static {
for (UserQueryField filterField : values()) {
STRING_TO_ENUM.put(filterField.toString(), filterField);
}
}
private final String name;
private static final String EMAIL_ALIAS = "emails";
private static final String PHONENUMBERS_ALIAS = "phoneNumbers";
private static final String IMS_ALIAS = "ims";
private static final String PHOTOS_ALIAS = "photos";
private static final String ADDRESS_ALIAS = "addresses";
private static final String GROUPS_ALIAS = "groups";
private static final String ENTITLEMENTS_ALIAS = "entitlements";
private UserQueryField(String name) {
this.name = name;
}
protected RuntimeException handleSortByFieldNotSupported(String fieldName) {
throw new RuntimeException("Sorting by " + fieldName + " is not supported yet"); // NOSONAR - will be removed
// after implementing
}
@Override
public String toString() {
return name;
}
public static UserQueryField fromString(String name) {
return STRING_TO_ENUM.get(name);
}
@SuppressWarnings("unchecked")
protected <T> SetJoin<UserEntity, T> createOrGetJoin(String alias, Root<UserEntity> root,
SetAttribute<UserEntity, T> attribute) {
for (Join<UserEntity, ?> currentJoin : root.getJoins()) {
if (currentJoin.getAlias().equals(alias)) {
return (SetJoin<UserEntity, T>) currentJoin;
}
}
SetJoin<UserEntity, T> join = root.join(attribute, JoinType.LEFT);
join.alias(alias);
return join;
}
@SuppressWarnings("unchecked")
protected SetJoin<UserEntity, GroupEntity> createOrGetJoinForGroups(String alias, Root<UserEntity> root,
SetAttribute<ResourceEntity, GroupEntity> attribute) {
for (Join<UserEntity, ?> currentJoin : root.getJoins()) {
if (currentJoin.getAlias().equals(alias)) {
return (SetJoin<UserEntity, GroupEntity>) currentJoin;
}
}
final SetJoin<UserEntity, GroupEntity> join = root.join(attribute, JoinType.LEFT);
join.alias(alias);
return join;
}
}
|
package test.http.router.handler;
import com.firefly.$;
import com.firefly.client.http2.*;
import com.firefly.codec.http2.frame.DataFrame;
import com.firefly.codec.http2.frame.HeadersFrame;
import com.firefly.codec.http2.frame.SettingsFrame;
import com.firefly.codec.http2.model.*;
import com.firefly.codec.http2.stream.*;
import com.firefly.server.http2.HTTP2Server;
import com.firefly.server.http2.ServerHTTPHandler;
import com.firefly.server.http2.ServerSessionListener;
import com.firefly.utils.concurrent.Callback;
import com.firefly.utils.concurrent.FuturePromise;
import com.firefly.utils.io.BufferUtils;
import org.junit.Assert;
import org.junit.Test;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.Phaser;
import static com.firefly.utils.io.BufferUtils.toBuffer;
import static org.hamcrest.Matchers.is;
/**
* @author Pengtao Qiu
*/
public class TestH2cUpgrade extends AbstractHTTPHandlerTest {
@Test
public void test() throws Exception {
Phaser phaser = new Phaser(5);
HTTP2Server server = createServer();
HTTP2Client client = createClient(phaser);
phaser.arriveAndAwaitAdvance();
server.stop();
client.stop();
}
private static class TestH2cHandler extends ClientHTTPHandler.Adapter {
protected final ByteBuffer[] buffers;
protected final List<ByteBuffer> contentList = new CopyOnWriteArrayList<>();
public TestH2cHandler() {
buffers = null;
}
public TestH2cHandler(ByteBuffer[] buffers) {
this.buffers = buffers;
}
@Override
public void continueToSendData(MetaData.Request request, MetaData.Response response, HTTPOutputStream output,
HTTPConnection connection) {
System.out.println("client received 100 continue");
Assert.assertTrue(buffers != null);
try (HTTPOutputStream out = output) {
for (ByteBuffer buf : buffers) {
out.write(buf);
}
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public boolean content(ByteBuffer item, MetaData.Request request, MetaData.Response response,
HTTPOutputStream output,
HTTPConnection connection) {
System.out.println("client received data: " + BufferUtils.toUTF8String(item));
contentList.add(item);
return false;
}
}
private HTTP2Client createClient(Phaser phaser) throws Exception {
final HTTP2Configuration http2Configuration = new HTTP2Configuration();
http2Configuration.setFlowControlStrategy("simple");
http2Configuration.getTcpConfiguration().setTimeout(60 * 1000);
HTTP2Client client = new HTTP2Client(http2Configuration);
FuturePromise<HTTPClientConnection> promise = new FuturePromise<>();
client.connect(host, port, promise);
final HTTPClientConnection httpConnection = promise.get();
HTTPClientRequest request = new HTTPClientRequest("GET", "/index");
Map<Integer, Integer> settings = new HashMap<>();
settings.put(SettingsFrame.HEADER_TABLE_SIZE, http2Configuration.getMaxDynamicTableSize());
settings.put(SettingsFrame.INITIAL_WINDOW_SIZE, http2Configuration.getInitialStreamSendWindow());
SettingsFrame settingsFrame = new SettingsFrame(settings, false);
FuturePromise<HTTP2ClientConnection> http2Promise = new FuturePromise<>();
httpConnection.upgradeHTTP2(request, settingsFrame, http2Promise, new TestH2cHandler() {
@Override
public boolean messageComplete(MetaData.Request request, MetaData.Response response,
HTTPOutputStream output,
HTTPConnection connection) {
System.out.println("client received frame: " + response.getStatus() + ", " + response.getReason());
System.out.println(response.getFields());
System.out.println("
Assert.assertThat(response.getStatus(), is(HttpStatus.SWITCHING_PROTOCOLS_101));
Assert.assertThat(response.getFields().get(HttpHeader.UPGRADE), is("h2c"));
phaser.arrive();
return true;
}
});
HTTP2ClientConnection clientConnection = http2Promise.get();
HttpFields fields = new HttpFields();
fields.put(HttpHeader.USER_AGENT, "Firefly Client 1.0");
MetaData.Request post = new MetaData.Request("POST", HttpScheme.HTTP,
new HostPortHttpField(host + ":" + port),
"/data", HttpVersion.HTTP_1_1, fields);
clientConnection.sendRequestWithContinuation(post, new TestH2cHandler(new ByteBuffer[]{
ByteBuffer.wrap("hello world!".getBytes("UTF-8")),
ByteBuffer.wrap("big hello world!".getBytes("UTF-8"))}) {
@Override
public boolean messageComplete(MetaData.Request request, MetaData.Response response,
HTTPOutputStream output,
HTTPConnection connection) {
return dataComplete(phaser, BufferUtils.toString(contentList), response);
}
});
MetaData.Request get = new MetaData.Request("GET", HttpScheme.HTTP,
new HostPortHttpField(host + ":" + port),
"/test2", HttpVersion.HTTP_1_1, new HttpFields());
clientConnection.send(get, new TestH2cHandler() {
@Override
public boolean messageComplete(MetaData.Request request, MetaData.Response response,
HTTPOutputStream output,
HTTPConnection connection) {
System.out.println("client received frame: " + response.getStatus() + ", " + response.getReason());
System.out.println(response.getFields());
System.out.println("
Assert.assertThat(response.getStatus(), is(HttpStatus.NOT_FOUND_404));
phaser.arrive();
return true;
}
});
MetaData.Request post2 = new MetaData.Request("POST", HttpScheme.HTTP,
new HostPortHttpField(host + ":" + port),
"/data", HttpVersion.HTTP_1_1, fields);
clientConnection.send(post2, new ByteBuffer[]{
ByteBuffer.wrap("test data 2".getBytes("UTF-8")),
ByteBuffer.wrap("finished test data 2".getBytes("UTF-8"))}, new TestH2cHandler() {
@Override
public boolean messageComplete(MetaData.Request request, MetaData.Response response,
HTTPOutputStream output,
HTTPConnection connection) {
return dataComplete(phaser, BufferUtils.toString(contentList), response);
}
});
return client;
}
public boolean dataComplete(Phaser phaser, String content, MetaData.Response response) {
System.out.println("client received frame: " + response.getStatus() + ", " + response.getReason());
System.out.println(response.getFields());
System.out.println("
Assert.assertThat(response.getStatus(), is(HttpStatus.OK_200));
Assert.assertThat(content, is("Receive data stream successful. Thank you!"));
phaser.arrive();
return true;
}
private HTTP2Server createServer() {
final HTTP2Configuration http2Configuration = new HTTP2Configuration();
http2Configuration.setFlowControlStrategy("simple");
http2Configuration.getTcpConfiguration().setTimeout(60 * 1000);
HTTP2Server server = new HTTP2Server(host, port, http2Configuration, new ServerHTTPHandler.Adapter() {
@Override
public boolean accept100Continue(MetaData.Request request, MetaData.Response response, HTTPOutputStream output,
HTTPConnection connection) {
System.out.println("received expect continue ");
return false;
}
@Override
public boolean content(ByteBuffer item, MetaData.Request request, MetaData.Response response, HTTPOutputStream output,
HTTPConnection connection) {
System.out.println("received data: " + BufferUtils.toString(item, StandardCharsets.UTF_8));
return false;
}
@Override
public boolean messageComplete(MetaData.Request request, MetaData.Response response, HTTPOutputStream outputStream,
HTTPConnection connection) {
HttpURI uri = request.getURI();
System.out.println("message complete: " + uri);
System.out.println(request.getFields());
System.out.println("
switch (uri.getPath()) {
case "/index":
response.setStatus(HttpStatus.Code.OK.getCode());
response.setReason(HttpStatus.Code.OK.getMessage());
try (HTTPOutputStream output = outputStream) {
output.writeWithContentLength(toBuffer("receive initial stream successful", StandardCharsets.UTF_8));
} catch (IOException e) {
e.printStackTrace();
}
break;
case "/data":
response.setStatus(HttpStatus.Code.OK.getCode());
response.setReason(HttpStatus.Code.OK.getMessage());
try (HTTPOutputStream output = outputStream) {
output.write(toBuffer("Receive data stream successful. ", StandardCharsets.UTF_8));
output.write(toBuffer("Thank you!", StandardCharsets.UTF_8));
} catch (IOException e) {
e.printStackTrace();
}
break;
default:
response.setStatus(HttpStatus.Code.NOT_FOUND.getCode());
response.setReason(HttpStatus.Code.NOT_FOUND.getMessage());
try (HTTPOutputStream output = outputStream) {
output.writeWithContentLength(toBuffer(uri.getPath() + " not found", StandardCharsets.UTF_8));
} catch (IOException e) {
e.printStackTrace();
}
break;
}
return true;
}
});
server.start();
return server;
}
// @Test
public void testLowLevelAPI() throws Exception {
Phaser phaser = new Phaser(2);
HTTP2Server server = createServerLowLevelAPI();
HTTP2Client client = createClientLowLevelClient(phaser);
phaser.arriveAndAwaitAdvance();
server.stop();
client.stop();
}
public HTTP2Server createServerLowLevelAPI() {
final HTTP2Configuration http2Configuration = new HTTP2Configuration();
http2Configuration.setFlowControlStrategy("simple");
http2Configuration.getTcpConfiguration().setTimeout(60 * 1000);
HTTP2Server server = new HTTP2Server(host, port, http2Configuration, new ServerSessionListener.Adapter() {
@Override
public Map<Integer, Integer> onPreface(Session session) {
System.out.println("session preface: " + session);
final Map<Integer, Integer> settings = new HashMap<>();
settings.put(SettingsFrame.HEADER_TABLE_SIZE, http2Configuration.getMaxDynamicTableSize());
settings.put(SettingsFrame.INITIAL_WINDOW_SIZE, http2Configuration.getInitialStreamSendWindow());
return settings;
}
@Override
public Stream.Listener onNewStream(Stream stream, HeadersFrame frame) {
System.out.println("Server new stream, " + frame.getMetaData() + "|" + stream);
MetaData metaData = frame.getMetaData();
Assert.assertTrue(metaData.isRequest());
final MetaData.Request request = (MetaData.Request) metaData;
if (frame.isEndStream()) {
if (request.getURI().getPath().equals("/index")) {
MetaData.Response response = new MetaData.Response(HttpVersion.HTTP_2, 200, new HttpFields());
HeadersFrame headersFrame = new HeadersFrame(stream.getId(), response, null, true);
stream.headers(headersFrame, Callback.NOOP);
}
}
List<ByteBuffer> contentList = new CopyOnWriteArrayList<>();
return new Stream.Listener.Adapter() {
@Override
public void onHeaders(Stream stream, HeadersFrame frame) {
System.out.println("Server stream on headers " + frame.getMetaData() + "|" + stream);
}
@Override
public void onData(Stream stream, DataFrame frame, Callback callback) {
System.out.println("Server stream on data: " + frame);
contentList.add(frame.getData());
if (frame.isEndStream()) {
MetaData.Response response = new MetaData.Response(HttpVersion.HTTP_2, 200, new HttpFields());
HeadersFrame responseFrame = new HeadersFrame(stream.getId(), response, null, false);
System.out.println("Server session on data end: " + BufferUtils.toString(contentList));
stream.headers(responseFrame, new Callback() {
@Override
public void succeeded() {
DataFrame dataFrame = new DataFrame(stream.getId(), BufferUtils.toBuffer("The server received data"), true);
stream.data(dataFrame, Callback.NOOP);
}
});
}
callback.succeeded();
}
};
}
@Override
public void onAccept(Session session) {
System.out.println("accept a new session " + session);
}
}, new ServerHTTPHandler.Adapter());
server.start();
return server;
}
public HTTP2Client createClientLowLevelClient(Phaser phaser) throws Exception {
final HTTP2Configuration http2Configuration = new HTTP2Configuration();
http2Configuration.setFlowControlStrategy("simple");
http2Configuration.getTcpConfiguration().setTimeout(60 * 1000);
HTTP2Client client = new HTTP2Client(http2Configuration);
FuturePromise<HTTPClientConnection> promise = new FuturePromise<>();
client.connect(host, port, promise);
HTTPConnection connection = promise.get();
Assert.assertThat(connection.getHttpVersion(), is(HttpVersion.HTTP_1_1));
final HTTP1ClientConnection httpConnection = (HTTP1ClientConnection) connection;
HTTPClientRequest request = new HTTPClientRequest("GET", "/index");
Map<Integer, Integer> settings = new HashMap<>();
settings.put(SettingsFrame.HEADER_TABLE_SIZE, http2Configuration.getMaxDynamicTableSize());
settings.put(SettingsFrame.INITIAL_WINDOW_SIZE, http2Configuration.getInitialStreamSendWindow());
SettingsFrame settingsFrame = new SettingsFrame(settings, false);
FuturePromise<HTTP2ClientConnection> http2promise = new FuturePromise<>();
FuturePromise<Stream> initStream = new FuturePromise<>();
httpConnection.upgradeHTTP2(request, settingsFrame, http2promise, initStream, new Stream.Listener.Adapter() {
@Override
public void onHeaders(Stream stream, HeadersFrame frame) {
System.out.println($.string.replace("client stream {} received init headers: {}", stream.getId(), frame.getMetaData()));
}
}, new Session.Listener.Adapter() {
@Override
public Map<Integer, Integer> onPreface(Session session) {
System.out.println($.string.replace("client preface: {}", session));
Map<Integer, Integer> settings = new HashMap<>();
settings.put(SettingsFrame.HEADER_TABLE_SIZE, http2Configuration.getMaxDynamicTableSize());
settings.put(SettingsFrame.INITIAL_WINDOW_SIZE, http2Configuration.getInitialStreamSendWindow());
return settings;
}
@Override
public void onFailure(Session session, Throwable failure) {
failure.printStackTrace();
}
}, new ClientHTTPHandler.Adapter());
HTTP2ClientConnection clientConnection = http2promise.get();
Assert.assertThat(clientConnection.getHttpVersion(), is(HttpVersion.HTTP_2));
HttpFields fields = new HttpFields();
fields.put(HttpHeader.ACCEPT, "text/html");
fields.put(HttpHeader.USER_AGENT, "Firefly Client 1.0");
fields.put(HttpHeader.CONTENT_LENGTH, "28");
MetaData.Request metaData = new MetaData.Request("POST", HttpScheme.HTTP,
new HostPortHttpField(host + ":" + port), "/data", HttpVersion.HTTP_2, fields);
FuturePromise<Stream> streamPromise = new FuturePromise<>();
clientConnection.getHttp2Session().newStream(new HeadersFrame(metaData, null, false), streamPromise,
new Stream.Listener.Adapter() {
@Override
public void onHeaders(Stream stream, HeadersFrame frame) {
System.out.println($.string.replace("client received headers: {}", frame.getMetaData()));
}
@Override
public void onData(Stream stream, DataFrame frame, Callback callback) {
System.out.println($.string.replace("client received data: {}, {}", BufferUtils.toUTF8String(frame.getData()), frame));
if (frame.isEndStream()) {
phaser.arrive();
}
callback.succeeded();
}
});
final Stream clientStream = streamPromise.get();
System.out.println("client stream id: " + clientStream.getId());
clientStream.data(new DataFrame(clientStream.getId(),
toBuffer("hello world!", StandardCharsets.UTF_8), false), new Callback() {
@Override
public void succeeded() {
clientStream.data(new DataFrame(clientStream.getId(),
toBuffer("big hello world!", StandardCharsets.UTF_8), true), Callback.NOOP);
}
});
return client;
}
}
|
package com.opengamma.masterdb.holiday;
import java.sql.Date;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.sql.Types;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.EnumMap;
import java.util.List;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.ResultSetExtractor;
import org.threeten.bp.LocalDate;
import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.Timer;
import com.opengamma.core.holiday.HolidayType;
import com.opengamma.core.holiday.WeekendType;
import com.opengamma.core.holiday.WeekendTypeProvider;
import com.opengamma.elsql.ElSqlBundle;
import com.opengamma.id.ExternalId;
import com.opengamma.id.ExternalIdSearch;
import com.opengamma.id.ExternalIdSearchType;
import com.opengamma.id.ObjectId;
import com.opengamma.id.ObjectIdentifiable;
import com.opengamma.id.UniqueId;
import com.opengamma.id.VersionCorrection;
import com.opengamma.master.AbstractHistoryRequest;
import com.opengamma.master.AbstractHistoryResult;
import com.opengamma.master.holiday.HolidayDocument;
import com.opengamma.master.holiday.HolidayHistoryRequest;
import com.opengamma.master.holiday.HolidayHistoryResult;
import com.opengamma.master.holiday.HolidayMaster;
import com.opengamma.master.holiday.HolidayMetaDataRequest;
import com.opengamma.master.holiday.HolidayMetaDataResult;
import com.opengamma.master.holiday.HolidaySearchRequest;
import com.opengamma.master.holiday.HolidaySearchResult;
import com.opengamma.master.holiday.HolidaySearchSortOrder;
import com.opengamma.master.holiday.ManageableHoliday;
import com.opengamma.master.holiday.ManageableHolidayWithWeekend;
import com.opengamma.masterdb.AbstractDocumentDbMaster;
import com.opengamma.util.ArgumentChecker;
import com.opengamma.util.db.DbConnector;
import com.opengamma.util.db.DbDateUtils;
import com.opengamma.util.db.DbMapSqlParameterSource;
import com.opengamma.util.money.Currency;
import com.opengamma.util.paging.Paging;
/**
* A holiday master implementation using a database for persistence.
* <p>
* This is a full implementation of the holiday master using an SQL database.
* Full details of the API are in {@link HolidayMaster}.
* <p>
* The SQL is stored externally in {@code DbHolidayMaster.elsql}.
* Alternate databases or specific SQL requirements can be handled using database
* specific overrides, such as {@code DbHolidayMaster-MySpecialDB.elsql}.
* <p>
* This class is mutable but must be treated as immutable after configuration.
*/
public class DbHolidayMaster extends AbstractDocumentDbMaster<HolidayDocument> implements HolidayMaster {
/** Logger. */
private static final Logger s_logger = LoggerFactory.getLogger(DbHolidayMaster.class);
/**
* The default scheme for unique identifiers.
*/
public static final String IDENTIFIER_SCHEME_DEFAULT = "DbHol";
/**
* SQL order by.
*/
protected static final EnumMap<HolidaySearchSortOrder, String> ORDER_BY_MAP = new EnumMap<>(HolidaySearchSortOrder.class);
static {
ORDER_BY_MAP.put(HolidaySearchSortOrder.OBJECT_ID_ASC, "oid ASC");
ORDER_BY_MAP.put(HolidaySearchSortOrder.OBJECT_ID_DESC, "oid DESC");
ORDER_BY_MAP.put(HolidaySearchSortOrder.VERSION_FROM_INSTANT_ASC, "ver_from_instant ASC");
ORDER_BY_MAP.put(HolidaySearchSortOrder.VERSION_FROM_INSTANT_DESC, "ver_from_instant DESC");
ORDER_BY_MAP.put(HolidaySearchSortOrder.NAME_ASC, "name ASC");
ORDER_BY_MAP.put(HolidaySearchSortOrder.NAME_DESC, "name DESC");
}
// TIMERS FOR METRICS GATHERING
// By default these do nothing. Registration will replace them
// so that they actually do something.
private Timer _insertTimer = new Timer();
/**
* Creates an instance.
*
* @param dbConnector the database connector, not null
*/
public DbHolidayMaster(final DbConnector dbConnector) {
super(dbConnector, IDENTIFIER_SCHEME_DEFAULT);
setElSqlBundle(ElSqlBundle.of(dbConnector.getDialect().getElSqlConfig(), DbHolidayMaster.class));
}
@Override
public void registerMetrics(final MetricRegistry summaryRegistry, final MetricRegistry detailedRegistry, final String namePrefix) {
super.registerMetrics(summaryRegistry, detailedRegistry, namePrefix);
_insertTimer = summaryRegistry.timer(namePrefix + ".insert");
}
@Override
public HolidayMetaDataResult metaData(final HolidayMetaDataRequest request) {
ArgumentChecker.notNull(request, "request");
final HolidayMetaDataResult result = new HolidayMetaDataResult();
if (request.isHolidayTypes()) {
result.getHolidayTypes().addAll(Arrays.asList(HolidayType.values()));
}
return result;
}
@Override
public HolidaySearchResult search(final HolidaySearchRequest request) {
ArgumentChecker.notNull(request, "request");
ArgumentChecker.notNull(request.getPagingRequest(), "request.pagingRequest");
ArgumentChecker.notNull(request.getVersionCorrection(), "request.versionCorrection");
s_logger.debug("search {}", request);
final VersionCorrection vc = request.getVersionCorrection().withLatestFixed(now());
final HolidaySearchResult result = new HolidaySearchResult(vc);
final ExternalIdSearch regionSearch = request.getRegionExternalIdSearch();
final ExternalIdSearch exchangeSearch = request.getExchangeExternalIdSearch();
final ExternalIdSearch customSearch = request.getCustomExternalIdSearch();
final String currencyISO = request.getCurrency() != null ? request.getCurrency().getCode() : null;
if (request.getHolidayObjectIds() != null && request.getHolidayObjectIds().size() == 0 ||
ExternalIdSearch.canMatch(regionSearch) == false ||
ExternalIdSearch.canMatch(exchangeSearch) == false) {
result.setPaging(Paging.of(request.getPagingRequest(), 0));
return result;
}
final DbMapSqlParameterSource args = createParameterSource()
.addTimestamp("version_as_of_instant", vc.getVersionAsOf())
.addTimestamp("corrected_to_instant", vc.getCorrectedTo())
.addValueNullIgnored("name", getDialect().sqlWildcardAdjustValue(request.getName()))
.addValueNullIgnored("hol_type", request.getType() != null ? request.getType().name() : null)
.addValueNullIgnored("currency_iso", currencyISO);
if (request.getProviderId() != null) {
args.addValue("provider_scheme", request.getProviderId().getScheme().getName());
args.addValue("provider_value", request.getProviderId().getValue());
}
if (regionSearch != null) {
if (regionSearch.getSearchType() != ExternalIdSearchType.ANY) {
throw new IllegalArgumentException("Unsupported search type: " + regionSearch.getSearchType());
}
int i = 0;
for (final ExternalId idKey : regionSearch.getExternalIds()) {
args.addValue("region_scheme" + i, idKey.getScheme().getName());
args.addValue("region_value" + i, idKey.getValue());
i++;
}
args.addValue("sql_search_region_ids", sqlSelectIdKeys(request.getRegionExternalIdSearch(), "region"));
}
if (exchangeSearch != null) {
if (exchangeSearch.getSearchType() != ExternalIdSearchType.ANY) {
throw new IllegalArgumentException("Unsupported search type: " + exchangeSearch.getSearchType());
}
int i = 0;
for (final ExternalId idKey : exchangeSearch.getExternalIds()) {
args.addValue("exchange_scheme" + i, idKey.getScheme().getName());
args.addValue("exchange_value" + i, idKey.getValue());
i++;
}
args.addValue("sql_search_exchange_ids", sqlSelectIdKeys(request.getExchangeExternalIdSearch(), "exchange"));
}
if (customSearch != null) {
if (customSearch.getSearchType() != ExternalIdSearchType.ANY) {
throw new IllegalArgumentException("Unsupported search type: " + customSearch.getSearchType());
}
int i = 0;
for (final ExternalId idKey : customSearch.getExternalIds()) {
args.addValue("custom_scheme" + i, idKey.getScheme().getName());
args.addValue("custom_value" + i, idKey.getValue());
i++;
}
args.addValue("sql_search_custom_ids", sqlSelectIdKeys(request.getCustomExternalIdSearch(), "custom"));
}
if (request.getHolidayObjectIds() != null) {
final StringBuilder buf = new StringBuilder(request.getHolidayObjectIds().size() * 10);
for (final ObjectId objectId : request.getHolidayObjectIds()) {
checkScheme(objectId);
buf.append(extractOid(objectId)).append(", ");
}
buf.setLength(buf.length() - 2);
args.addValue("sql_search_object_ids", buf.toString());
}
args.addValue("sort_order", ORDER_BY_MAP.get(request.getSortOrder()));
args.addValue("paging_offset", request.getPagingRequest().getFirstItem());
args.addValue("paging_fetch", request.getPagingRequest().getPagingSize());
final String[] sql = {getElSqlBundle().getSql("Search", args), getElSqlBundle().getSql("SearchCount", args)};
doSearch(request.getPagingRequest(), sql, args, new HolidayDocumentExtractor(), result);
return result;
}
/**
* Gets the SQL to search for ids.
* <p>
* This is too complex for the elsql mechanism.
*
* @param bundle the bundle, not null
* @param type the type to search for, not null
* @return the SQL search and count, not null
*/
protected String sqlSelectIdKeys(final ExternalIdSearch bundle, final String type) {
final List<String> list = new ArrayList<>();
for (int i = 0; i < bundle.size(); i++) {
list.add("(" + type + "_scheme = :" + type + "_scheme" + i + " AND " + type + "_value = :" + type + "_value" + i + ") ");
}
return StringUtils.join(list, "OR ");
}
@Override
public HolidayDocument get(final UniqueId uniqueId) {
return doGet(uniqueId, new HolidayDocumentExtractor(), "Holiday");
}
@Override
public HolidayDocument get(final ObjectIdentifiable objectId, final VersionCorrection versionCorrection) {
return doGetByOidInstants(objectId, versionCorrection, new HolidayDocumentExtractor(), "Holiday");
}
@Override
public HolidayHistoryResult history(final HolidayHistoryRequest request) {
return doHistory(request, new HolidayHistoryResult(), new HolidayDocumentExtractor());
}
/**
* Inserts a new document.
*
* @param document the document, not null
* @return the new document, not null
*/
@Override
protected HolidayDocument insert(final HolidayDocument document) {
ArgumentChecker.notNull(document.getHoliday(), "document.holiday");
ArgumentChecker.notNull(document.getHoliday().getType(), "document.holiday.type");
ArgumentChecker.notNull(document.getName(), "document.name");
switch (document.getHoliday().getType()) {
case BANK:
ArgumentChecker.notNull(document.getHoliday().getRegionExternalId(), "document.holiday.region");
break;
case CURRENCY:
ArgumentChecker.notNull(document.getHoliday().getCurrency(), "document.holiday.currency");
break;
case TRADING:
case SETTLEMENT:
ArgumentChecker.notNull(document.getHoliday().getExchangeExternalId(), "document.holiday.exchange");
break;
case CUSTOM:
ArgumentChecker.notNull(document.getHoliday().getCustomExternalId(), "document.holiday.custom");
break;
default:
throw new IllegalArgumentException("Holiday type not set");
}
try (Timer.Context context = _insertTimer.time()) {
final long docId = nextId("hol_holiday_seq");
final long docOid = document.getUniqueId() != null ? extractOid(document.getUniqueId()) : docId;
// the arguments for inserting into the holiday table
final ManageableHoliday holiday = document.getHoliday();
final DbMapSqlParameterSource docArgs = createParameterSource()
.addValue("doc_id", docId)
.addValue("doc_oid", docOid)
.addTimestamp("ver_from_instant", document.getVersionFromInstant())
.addTimestampNullFuture("ver_to_instant", document.getVersionToInstant())
.addTimestamp("corr_from_instant", document.getCorrectionFromInstant())
.addTimestampNullFuture("corr_to_instant", document.getCorrectionToInstant())
.addValue("name", document.getName())
.addValue("provider_scheme",
document.getProviderId() != null ? document.getProviderId().getScheme().getName() : null,
Types.VARCHAR)
.addValue("provider_value",
document.getProviderId() != null ? document.getProviderId().getValue() : null,
Types.VARCHAR)
.addValue("hol_type", holiday.getType().name())
.addValue("region_scheme",
holiday.getRegionExternalId() != null ? holiday.getRegionExternalId().getScheme().getName() : null,
Types.VARCHAR)
.addValue("region_value",
holiday.getRegionExternalId() != null ? holiday.getRegionExternalId().getValue() : null,
Types.VARCHAR)
.addValue("exchange_scheme",
holiday.getExchangeExternalId() != null ? holiday.getExchangeExternalId().getScheme().getName() : null,
Types.VARCHAR)
.addValue("exchange_value",
holiday.getExchangeExternalId() != null ? holiday.getExchangeExternalId().getValue() : null,
Types.VARCHAR)
.addValue("custom_scheme",
holiday.getCustomExternalId() != null ? holiday.getCustomExternalId().getValue() : null,
Types.VARCHAR)
.addValue("custom_value",
holiday.getCustomExternalId() != null ? holiday.getCustomExternalId().getValue() : null,
Types.VARCHAR)
.addValue("currency_iso",
holiday.getCurrency() != null ? holiday.getCurrency().getCode() : null,
Types.VARCHAR)
.addValue("weekend_type",
holiday instanceof WeekendTypeProvider ? ((WeekendTypeProvider) holiday).getWeekendType().name() : null,
Types.VARCHAR);
// the arguments for inserting into the date table
final List<DbMapSqlParameterSource> dateList = new ArrayList<>();
for (final LocalDate date : holiday.getHolidayDates()) {
final DbMapSqlParameterSource dateArgs = createParameterSource()
.addValue("doc_id", docId)
.addDate("hol_date", date);
dateList.add(dateArgs);
}
final String sqlDoc = getElSqlBundle().getSql("Insert", docArgs);
final String sqlDate = getElSqlBundle().getSql("InsertDate");
getJdbcTemplate().update(sqlDoc, docArgs);
getJdbcTemplate().batchUpdate(sqlDate, dateList.toArray(new DbMapSqlParameterSource[dateList.size()]));
// set the uniqueId
final UniqueId uniqueId = createUniqueId(docOid, docId);
holiday.setUniqueId(uniqueId);
document.setUniqueId(uniqueId);
return document;
}
}
/**
* Mapper from SQL rows to a HolidayDocument.
*/
protected final class HolidayDocumentExtractor implements ResultSetExtractor<List<HolidayDocument>> {
private long _lastDocId = -1;
private ManageableHoliday _holiday;
private final List<HolidayDocument> _documents = new ArrayList<>();
@Override
public List<HolidayDocument> extractData(final ResultSet rs) throws SQLException, DataAccessException {
while (rs.next()) {
final long docId = rs.getLong("DOC_ID");
if (_lastDocId != docId) {
_lastDocId = docId;
buildHoliday(rs, docId);
}
// allow an empty set of holidays
final Date sqlDate = rs.getDate("HOL_DATE");
if (sqlDate != null) {
final LocalDate holDate = DbDateUtils.fromSqlDate(rs.getDate("HOL_DATE"));
_holiday.getHolidayDates().add(holDate);
}
}
return _documents;
}
private void buildHoliday(final ResultSet rs, final long docId) throws SQLException {
final long docOid = rs.getLong("DOC_OID");
final Timestamp versionFrom = rs.getTimestamp("VER_FROM_INSTANT");
final Timestamp versionTo = rs.getTimestamp("VER_TO_INSTANT");
final Timestamp correctionFrom = rs.getTimestamp("CORR_FROM_INSTANT");
final Timestamp correctionTo = rs.getTimestamp("CORR_TO_INSTANT");
final String name = rs.getString("NAME");
final String type = rs.getString("HOL_TYPE");
final String providerScheme = rs.getString("PROVIDER_SCHEME");
final String providerValue = rs.getString("PROVIDER_VALUE");
final String regionScheme = rs.getString("REGION_SCHEME");
final String regionValue = rs.getString("REGION_VALUE");
final String exchangeScheme = rs.getString("EXCHANGE_SCHEME");
final String exchangeValue = rs.getString("EXCHANGE_VALUE");
final String customScheme = rs.getString("CUSTOM_SCHEME");
final String customValue = rs.getString("CUSTOM_VALUE");
final String currencyISO = rs.getString("CURRENCY_ISO");
final String weekendType = rs.getString("WEEKEND_TYPE");
final UniqueId uniqueId = createUniqueId(docOid, docId);
final ManageableHoliday holiday = weekendType == null ? new ManageableHoliday() : new ManageableHolidayWithWeekend();
holiday.setUniqueId(uniqueId);
holiday.setType(HolidayType.valueOf(type));
if (regionScheme != null && regionValue != null) {
holiday.setRegionExternalId(ExternalId.of(regionScheme, regionValue));
}
if (exchangeScheme != null && exchangeValue != null) {
holiday.setExchangeExternalId(ExternalId.of(exchangeScheme, exchangeValue));
}
if (customScheme != null && customValue != null) {
holiday.setCustomExternalId(ExternalId.of(customScheme, customValue));
}
if (currencyISO != null) {
holiday.setCurrency(Currency.of(currencyISO));
}
if (weekendType != null) {
((ManageableHolidayWithWeekend) holiday).setWeekendType(WeekendType.valueOf(weekendType));
}
final HolidayDocument doc = new HolidayDocument(holiday);
doc.setVersionFromInstant(DbDateUtils.fromSqlTimestamp(versionFrom));
doc.setVersionToInstant(DbDateUtils.fromSqlTimestampNullFarFuture(versionTo));
doc.setCorrectionFromInstant(DbDateUtils.fromSqlTimestamp(correctionFrom));
doc.setCorrectionToInstant(DbDateUtils.fromSqlTimestampNullFarFuture(correctionTo));
doc.setUniqueId(uniqueId);
doc.setName(name);
if (providerScheme != null && providerValue != null) {
doc.setProviderId(ExternalId.of(providerScheme, providerValue));
}
_holiday = doc.getHoliday();
_documents.add(doc);
}
}
@Override
protected AbstractHistoryResult<HolidayDocument> historyByVersionsCorrections(final AbstractHistoryRequest request) {
final HolidayHistoryRequest historyRequest = new HolidayHistoryRequest();
historyRequest.setCorrectionsFromInstant(request.getCorrectionsFromInstant());
historyRequest.setCorrectionsToInstant(request.getCorrectionsToInstant());
historyRequest.setVersionsFromInstant(request.getVersionsFromInstant());
historyRequest.setVersionsToInstant(request.getVersionsToInstant());
historyRequest.setObjectId(request.getObjectId());
return history(historyRequest);
}
}
|
package com.dtflys.forest.utils;
import java.util.Base64;
/**
* Base64
* @author gongjun[dt_flys@hotmail.com]
* @since 2020-08-04 19:05
*/
public class Base64Utils {
private final static Base64.Decoder DECODER = Base64.getDecoder();
private final static Base64.Encoder ENCODER = Base64.getEncoder();
public static String encode(String str) {
return ENCODER.encodeToString(str.getBytes());
}
public static byte[] decode(String str) {
return DECODER.decode(str);
}
}
|
package org.jdesktop.swingx.painter;
import java.awt.*;
import java.awt.geom.RoundRectangle2D;
/**
* Draws a capsule. This is a rectangle capped by two semi circles. You can draw only a
* portion of a capsule using the portion property.
* @author joshy
*/
public class CapsulePainter extends AbstractAreaPainter {
public enum Portion { Top, Full, Bottom, Left, Right }
private Portion portion;
/**
* Create a new CapsulePainter that draws a full capsule.
*/
public CapsulePainter() {
this.setPortion(Portion.Full);
}
/**
* Create a new CapsulePainter that only draws the portion specified.
* @param portion the portion to draw
*/
public CapsulePainter(Portion portion) {
this.setPortion(portion);
}
/**
* Returns the current portion property. This property determines
* which part of the capsule will be drawn.
* @return the current portion
*/
public Portion getPortion() {
return portion;
}
/**
* Sets the current portion property. This property determines
* which part of the capsule will be drawn.
* @param portion the new portion
*/
public void setPortion(Portion portion) {
Portion old = this.portion;
this.portion = portion;
firePropertyChange("portion",old,getPortion());
}
/**
* {@inheritDoc}
*/
@Override
protected void doPaint(Graphics2D g, Object component, int width, int height) {
Shape rect = provideShape(g,component,width,height);
if(getStyle() == Style.BOTH || getStyle() == Style.FILLED) {
g.setPaint(getFillPaint());
g.fill(rect);
}
if(getStyle() == Style.BOTH || getStyle() == Style.OUTLINE) {
g.setPaint(getBorderPaint());
g.draw(rect);
}
}
/**
* {@inheritDoc}
*/
@Override
protected Shape provideShape(Graphics2D g, Object comp, int width, int height) {
int round = 10;
int rheight = height;
int ry = 0;
if(getPortion() == Portion.Top) {
round = height*2;
rheight = height*2;
}
if(getPortion() == Portion.Bottom) {
round = height*2;
rheight = height*2;
ry = -height;
}
// need to support left and right!
return new RoundRectangle2D.Double(0, ry, width, rheight, round, round);
}
}
|
package org.rslite.worldselector;
import org.rslite.RSLiteConfig;
import org.rslite.jagex.world.Location;
import org.rslite.jagex.world.WorldInfo;
import org.rslite.jagex.world.WorldParser;
import org.rslite.loader.Loader;
import org.rslite.loader.LoaderConfigs;
import org.rslite.util.LatencyChecker;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPopupMenu;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
import javax.swing.table.TableRowSorter;
import java.awt.Color;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
public class WorldSelector extends javax.swing.JFrame {
private static final Color FAVORITE_COLOR = new Color(237, 218, 116);
/**
* Preloaded location icons for the world list table
*/
private static final ImageIcon[] LOCATION_ICONS = new ImageIcon[] {
new ImageIcon(WorldSelector.class.getResource("/flags/us.png")),
new ImageIcon(WorldSelector.class.getResource("/flags/gb.png")),
new ImageIcon(WorldSelector.class.getResource("/flags/ca.png")),
new ImageIcon(WorldSelector.class.getResource("/flags/au.png")),
new ImageIcon(WorldSelector.class.getResource("/flags/nl.png")),
new ImageIcon(WorldSelector.class.getResource("/flags/se.png")),
new ImageIcon(WorldSelector.class.getResource("/flags/fi.png")),
new ImageIcon(WorldSelector.class.getResource("/flags/de.png"))
};
private static final WorldParser parser = new WorldParser();
private static final Random random = new Random();
private DefaultTableModel worldTableModel;
private List<WorldInfo> worldList;
private ScheduledFuture<?> updateFuture;
private List<Integer> favorites;
/**
* Creates new form WorldSelector
*/
public WorldSelector() {
super("RSLite - World Select");
try {
setIconImage(ImageIO.read(this.getClass().getResource("/icon.png")));
} catch (IOException e) {
// Simply unable to load, meh.
}
initComponents();
new Thread(new Runnable() {
@Override
public void run() {
initWorldStatuses();
}
}).start();
}
@SuppressWarnings("unchecked")
private void initComponents() {
favorites = new ArrayList<>();
if (RSLiteConfig.hasProperty("favorites")) {
String[] strings = RSLiteConfig.getProperty("favorites").split(",");
for(String s : strings) {
favorites.add(Integer.parseInt(s));
}
}
jScrollPane1 = new javax.swing.JScrollPane();
worldTable = new javax.swing.JTable() {
private Color basicColor = null;
@Override
public Component prepareRenderer(TableCellRenderer renderer, int row, int column) {
Component c = super.prepareRenderer(renderer, row, column);
if (basicColor == null) {
basicColor = c.getBackground();
}
if (!isRowSelected(row)) {
if (favorites.contains(getValueAt(row, 0))) {
c.setBackground(FAVORITE_COLOR);
} else {
c.setBackground(basicColor);
}
}
return c;
}
};
playButton = new javax.swing.JButton();
playRandomButton = new javax.swing.JButton();
playBestButton = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
worldTable.setModel(worldTableModel = new javax.swing.table.DefaultTableModel(
new Object[][]{
},
new String[]{
"World", "Location", "Activity", "Players", "Special Info", "Response Time"
}
) {
Class[] types = new Class[]{
java.lang.Integer.class, javax.swing.ImageIcon.class, java.lang.Object.class, java.lang.Integer.class, java.lang.Object.class, java.lang.Integer.class
};
public Class getColumnClass(int columnIndex) {
return types[columnIndex];
}
boolean[] canEdit = new boolean[]{
false, false, false, false, false, false
};
public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEdit[columnIndex];
}
});
jScrollPane1.setViewportView(worldTable);
for (int i = 0; i < worldTable.getColumnModel().getColumnCount(); i++) {
TableColumn column = worldTable.getColumnModel().getColumn(i);
column.setResizable(false);
}
if (worldTable.getColumnModel().getColumnCount() > 0) {
worldTable.getColumnModel().getColumn(0).setResizable(false);
worldTable.getColumnModel().getColumn(0).setPreferredWidth(20);
worldTable.getColumnModel().getColumn(1).setResizable(false);
worldTable.getColumnModel().getColumn(1).setPreferredWidth(30);
worldTable.getColumnModel().getColumn(2).setResizable(false);
worldTable.getColumnModel().getColumn(2).setPreferredWidth(200);
worldTable.getColumnModel().getColumn(3).setResizable(false);
worldTable.getColumnModel().getColumn(3).setPreferredWidth(20);
worldTable.getColumnModel().getColumn(4).setResizable(false);
worldTable.getColumnModel().getColumn(5).setResizable(false);
worldTable.getColumnModel().getColumn(5).setPreferredWidth(50);
}
// Add the favorite sorter
TableRowSorter<DefaultTableModel> sorter = new TableRowSorter<>(worldTableModel);
worldTable.setRowSorter(sorter);
sorter.setComparator(0, new Comparator<Integer>() {
@Override
public int compare(Integer worldId1, Integer worldId2) {
if (favorites.contains(worldId1) && !favorites.contains(worldId2)) {
return -1;
} else if (!favorites.contains(worldId1) && favorites.contains(worldId2)) {
return 1;
}
return worldId1.compareTo(worldId2);
}
});
worldTable.addMouseListener(new MouseAdapter() {
@Override
public void mouseReleased(MouseEvent e) {
int r = worldTable.rowAtPoint(e.getPoint());
if (r >= 0 && r < worldTable.getRowCount()) {
worldTable.setRowSelectionInterval(r, r);
} else {
worldTable.clearSelection();
}
int rowIndex = worldTable.getSelectedRow();
if (rowIndex < 0)
return;
if (e.isPopupTrigger() && e.getComponent() instanceof JTable) {
JPopupMenu popup = createPopupMenu(rowIndex);
popup.show(e.getComponent(), e.getX(), e.getY());
}
}
});
playButton.setText("Play");
playButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
playButtonActionPerformed(evt);
}
});
playRandomButton.setText("Play on a random world");
playRandomButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
playRandomButtonActionPerformed(evt);
}
});
playBestButton.setText("Play on the best (lowest ping) server");
playBestButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
playBestButtonActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(playButton, javax.swing.GroupLayout.PREFERRED_SIZE, 222, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 31, Short.MAX_VALUE)
.addComponent(playBestButton, javax.swing.GroupLayout.PREFERRED_SIZE, 242, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 31, Short.MAX_VALUE)
.addComponent(playRandomButton, javax.swing.GroupLayout.PREFERRED_SIZE, 222, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(jScrollPane1))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(playButton, javax.swing.GroupLayout.DEFAULT_SIZE, 42, Short.MAX_VALUE)
.addComponent(playBestButton, javax.swing.GroupLayout.DEFAULT_SIZE, 42, Short.MAX_VALUE))
.addComponent(playRandomButton, javax.swing.GroupLayout.DEFAULT_SIZE, 42, Short.MAX_VALUE))
.addContainerGap())
);
pack();
}
private JPopupMenu createPopupMenu(int row) {
JPopupMenu popup = new JPopupMenu();
final int world = (int) worldTable.getValueAt(row, 0);
JMenuItem play = new JMenuItem("Play");
play.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
dispose();
startClient(world);
}
});
popup.add(play);
JMenuItem favorite = new JMenuItem();
if (favorites.contains(world)) {
favorite.setText("Remove from favorites");
favorite.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
favorites.remove((Object) world);
worldTable.getRowSorter().allRowsChanged();
saveFavorites();
}
});
} else {
favorite.setText("Add to favorites");
favorite.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
favorites.add(world);
worldTable.getRowSorter().allRowsChanged();
saveFavorites();
}
});
}
popup.add(favorite);
return popup;
}
private void saveFavorites() {
StringBuilder out = new StringBuilder();
for (Iterator<Integer> it$ = favorites.iterator(); it$.hasNext();) {
out.append(it$.next());
if (it$.hasNext()) {
out.append(',');
}
}
RSLiteConfig.setProperty("favorites", out.toString());
}
/**
* Initialize the world statuses on the rows
*/
private void initWorldStatuses() {
try {
worldList = new LinkedList<>();
// Load in standard worlds
worldList.addAll(parser.parse());
// Load in extra worlds
try (BufferedReader reader = new BufferedReader(new InputStreamReader(this.getClass().getResourceAsStream("/worlds.csv")))) {
String line;
while ((line = reader.readLine()) != null) {
String[] s = line.split(",");
worldList.add(new WorldInfo(Integer.parseInt(s[0]), s[1], s[2], 0, Location.valueOf(s[3]), Boolean.parseBoolean(s[4]), Boolean.parseBoolean(s[5]), Boolean.parseBoolean(s[6])));
}
}
for (WorldInfo info : worldList) {
addWorld(info);
}
worldTable.getRowSorter().toggleSortOrder(0);
ExecutorService pingService = Executors.newFixedThreadPool(2);
// After it's populated let's start off pinging servers
for (WorldInfo info : worldList) {
pingService.execute(new LatencyCheckRunnable(info));
}
} catch (IOException e) {
JOptionPane.showMessageDialog(null, "Unable to load the world list due to a connection error.\nPlease re-load RSLite and try again.", "Error", JOptionPane.ERROR_MESSAGE);
System.exit(1);
}
updateFuture = Executors.newSingleThreadScheduledExecutor().scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
updateWorldStatuses();
}
}, 30, 30, TimeUnit.SECONDS);
}
private void addWorld(WorldInfo info) {
StringBuilder extra = new StringBuilder();
if (info.isPvp()) {
extra.append("PvP");
}
if (info.isHighRisk()) {
if (extra.length() > 0)
extra.append(", ");
extra.append("High Risk");
}
worldTableModel.addRow(new Object[]{
info.getWorldId() - 300, // Get the actual world id
getWorldLocation(info.getLocation()),
info.getActivity(),
info.getPlayerCount(),
extra.toString(),
-1
});
}
/**
* Update the world status from the page
* This used to overwrite worldList, but it wouldn't let us have custom worlds.
*/
private void updateWorldStatuses() {
if (!isActive()) {
return; // It may have been disposed and not canceled yet.
}
try {
List<WorldInfo> worldList = parser.parse();
for (WorldInfo info : worldList) {
int row = findWorldRow(info.getWorldId());
if (row != -1) {
worldTableModel.setValueAt(info.getPlayerCount(), row, 3);
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* Find a row id by the world id
* @param worldId The world id to search for
* @return The row, or -1 if not found
*/
private int findWorldRow(int worldId) {
if (worldId > 300) {
worldId -= 300;
}
for (int i = 0; i < worldTableModel.getRowCount(); i++) {
int id = (int) worldTable.getValueAt(i, 0);
if (id == worldId) {
return i;
}
}
return -1;
}
/**
* Get the location icon for a world's location
* @param location The location to get the icon for
* @return The preloaded ImageIcon
*/
private ImageIcon getWorldLocation(Location location) {
return LOCATION_ICONS[location.ordinal()];
}
/**
* Start the game client with the selected row as the world.
*
* @param evt A standard action event, useless for us.
*/
private void playButtonActionPerformed(java.awt.event.ActionEvent evt) {
int row = worldTable.getSelectedRow();
if (row == -1) {
JOptionPane.showMessageDialog(this, "Please select a world.", "Error", JOptionPane.ERROR_MESSAGE);
return;
}
dispose();
int worldId = (int) worldTable.getValueAt(row, 0);
RSLiteConfig.setProperty("lastWorld", worldId);
startClient(worldId);
}
/**
* Start the game client with us choosing the lowest latency option
*
* @param evt A standard action event, useless for us.
*/
private void playBestButtonActionPerformed(java.awt.event.ActionEvent evt) {
int lowestId = -1;
long lowestValue = -1;
for (int i = 0; i < worldTableModel.getRowCount(); i++) {
int value = (int) worldTable.getValueAt(i, 5);
// Make sure it's not a pvp world. High risk are semi-ok I guess?
if (!worldTable.getValueAt(i, 4).toString().contains("PvP") && (lowestValue == -1 || value != -1 && value < lowestValue)) {
lowestValue = value;
lowestId = (int) worldTable.getValueAt(i, 0);
}
}
dispose();
RSLiteConfig.setProperty("lastWorld", lowestId);
if (lowestId != -1) {
startClient(lowestId);
}
}
/**
* Start the game client with the selected row as the world.
*
* @param evt A standard action event, useless for us.
*/
private void playRandomButtonActionPerformed(java.awt.event.ActionEvent evt) {
WorldInfo info = null;
// Choose a world until we find one that isn't pvp, high risk, or full.
while (info == null || info.isPvp() || info.isHighRisk() || info.getPlayerCount() >= 2000) {
info = worldList.get(random.nextInt(worldList.size()));
}
dispose();
RSLiteConfig.setProperty("lastWorld", info.getWorldId() - 300);
startClient(info.getWorldId());
}
/**
* Start the loader in a new thread
* @param world The world to load. This will automatically be converted from a 3** world to the oldschool format
*/
private void startClient(final int world) {
new Thread(new Runnable() {
@Override
public void run() {
try {
Loader l = new Loader(LoaderConfigs.RUNESCAPE_OLDSCHOOL, world > 300 ? world - 300 : world);
l.load();
l.initFrame();
} catch (IOException e) {
JOptionPane.showMessageDialog(null, "Unable to load Runescape due to a connection error.", "Error", JOptionPane.ERROR_MESSAGE);
}
}
}).start();
}
@Override
public void dispose() {
super.dispose();
updateFuture.cancel(true);
}
// Variables declaration - do not modify
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JButton playBestButton;
private javax.swing.JButton playButton;
private javax.swing.JButton playRandomButton;
private javax.swing.JTable worldTable;
// End of variables declaration
private class LatencyCheckRunnable implements Runnable {
private WorldInfo info;
public LatencyCheckRunnable(WorldInfo info) {
this.info = info;
}
@Override
public void run() {
try {
long latency = LatencyChecker.checkLatency(info.getHost(), 43594);
int row = findWorldRow(info.getWorldId());
worldTableModel.setValueAt((int) latency, row, 5);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
|
package org.elasticsearch.upgrades;
import org.apache.http.HttpEntity;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.elasticsearch.client.Response;
import org.hamcrest.Matchers;
import java.util.Collections;
import java.util.List;
import java.util.Map;
public class IndexAuditUpgradeIT extends AbstractUpgradeTestCase {
public void testDocsAuditedInOldCluster() throws Exception {
assumeTrue("only runs against old cluster", clusterType == CLUSTER_TYPE.OLD);
assertBusy(() -> {
assertAuditDocsExist();
assertNumUniqueNodeNameBuckets(2);
});
}
public void testDocsAuditedInMixedCluster() throws Exception {
assumeTrue("only runs against mixed cluster", clusterType == CLUSTER_TYPE.MIXED);
assertBusy(() -> {
assertAuditDocsExist();
assertNumUniqueNodeNameBuckets(2);
});
}
public void testDocsAuditedInUpgradedCluster() throws Exception {
assumeTrue("only runs against upgraded cluster", clusterType == CLUSTER_TYPE.UPGRADED);
assertBusy(() -> {
assertAuditDocsExist();
assertNumUniqueNodeNameBuckets(4);
});
}
private void assertAuditDocsExist() throws Exception {
Response response = client().performRequest("GET", "/.security_audit_log*/doc/_count");
assertEquals(200, response.getStatusLine().getStatusCode());
Map<String, Object> responseMap = entityAsMap(response);
assertNotNull(responseMap.get("count"));
assertThat((Integer) responseMap.get("count"), Matchers.greaterThanOrEqualTo(1));
}
private void assertNumUniqueNodeNameBuckets(int numBuckets) throws Exception {
// call API that will hit all nodes
assertEquals(200, client().performRequest("GET", "/_nodes").getStatusLine().getStatusCode());
HttpEntity httpEntity = new StringEntity(
"{\n" +
" \"aggs\" : {\n" +
" \"nodes\" : {\n" +
" \"terms\" : { \"field\" : \"node_name\" }\n" +
" }\n" +
" }\n" +
"}", ContentType.APPLICATION_JSON);
Response aggResponse = client().performRequest("GET", "/.security_audit_log*/_search",
Collections.singletonMap("pretty", "true"), httpEntity);
Map<String, Object> aggResponseMap = entityAsMap(aggResponse);
logger.debug("aggResponse {}", aggResponseMap);
Map<String, Object> aggregations = (Map<String, Object>) aggResponseMap.get("aggregations");
assertNotNull(aggregations);
Map<String, Object> nodesAgg = (Map<String, Object>) aggregations.get("nodes");
assertNotNull(nodesAgg);
List<Map<String, Object>> buckets = (List<Map<String, Object>>) nodesAgg.get("buckets");
assertNotNull(buckets);
assertEquals(numBuckets, buckets.size());
}
}
|
package org.kwstudios.play.ragemode.commands;
import org.bukkit.ChatColor;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.entity.Player;
import org.kwstudios.play.ragemode.gameLogic.PlayerList;
import org.kwstudios.play.ragemode.toolbox.ConstantHolder;
import org.kwstudios.play.ragemode.toolbox.GetGames;
public class RemoveGame {
public RemoveGame(Player player, String label, String[] args, FileConfiguration fileConfiguration) {
if(args.length >= 2) {
String game = args[1];
if(!GetGames.isGameExistent(game, fileConfiguration)) {
player.sendMessage(ConstantHolder.RAGEMODE_PREFIX + ChatColor.DARK_RED + "Don't remove nonexistent games!");
return;
}
else {
if(PlayerList.isGameRunning(game)) {
player.sendMessage(ConstantHolder.RAGEMODE_PREFIX + ChatColor.DARK_RED + "This game is running at the moment. Please wait until it is over.");
return;
}
else {
fileConfiguration.set("settings.games." + game, null);
player.sendMessage(ConstantHolder.RAGEMODE_PREFIX + "The game " + game + " was removed successfully.");
}
}
}
else {
player.sendMessage(ConstantHolder.RAGEMODE_PREFIX + ChatColor.DARK_RED + "Missing arguments. Usage: /rm remove <GameName>");
return;
}
}
}
|
package com.sshtools.forker.client;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.StringTokenizer;
import org.apache.commons.io.IOUtils;
import com.sshtools.forker.common.Cookie;
import com.sshtools.forker.common.Cookie.Instance;
import com.sshtools.forker.common.IO;
import com.sshtools.forker.common.OS;
import com.sshtools.forker.common.States;
/**
* Replacement for {@link Runtime#exec(String)} and friends.
*
* @see ForkerBuilder
*
*/
public class Forker {
final static String[] FORKER_DIRS = { ".*[/\\\\]forker-client[/\\\\].*", ".*[/\\\\]forker-wrapper[/\\\\].*",
".*[/\\\\]forker-pty[/\\\\].*", ".*[/\\\\]forker-common[/\\\\].*", ".*[/\\\\]forker-daemon[/\\\\].*",
".*[/\\\\]pty4j[/\\\\].*" };
/*
* The jars forker daemon needs. If it's dependencies ever change, this will
* have to updated too.
*
* TODO Is there a better way to discover this? perhaps looking at maven
* meta-data
*/
final static String[] FORKER_JARS = { "^jna.*", "^commons-lang3.*", "^commons-io.*", "^jna-platform.*", "^purejavacomm.*",
"^guava.*", "^log4j.*", "^forker-common.*", "^forker-client.*", "^forker-daemon.*", "^pty4j.*",
"^forker-wrapper.*", "^forker-pty.*", "^jsr305.*", "^checker-qua.*", "^error_prone_annotations.*",
"^jobjc-annotations.*", "^animal-sniffer-annotations.*" };
private static boolean daemonAdministrator;
private static String daemonClasspath;
private static boolean daemonLoaded;
private static Socket daemonMaintenanceSocket;
private static boolean daemonRunning;
private final static Forker INSTANCE = new Forker();
private static boolean wrapped;
/**
* @param io IO
* @param command command
* @return process process
* @throws IOException on any error
*/
public Process exec(IO io, String command) throws IOException {
return exec(io, command, null, null);
}
/**
* @param io IO
* @param cmdarray command
* @return process
* @throws IOException on any error
*
* @deprecated
* @see OSCommand
*/
public Process exec(IO io, String... cmdarray) throws IOException {
return exec(io, cmdarray, null, null);
}
/**
* @param io IO
* @param command command
* @param envp environment
* @return process
* @throws IOException on any error
*
*
* @deprecated
* @see OSCommand
*/
public Process exec(IO io, String command, String[] envp) throws IOException {
return exec(io, command, envp, null);
}
/**
* @param io IO
* @param command command
* @param envp environment
* @param dir working directory
* @return process
* @throws IOException on any error
*
* @deprecated
* @see OSCommand
*/
public Process exec(IO io, String command, String[] envp, File dir) throws IOException {
if (command.length() == 0)
throw new IllegalArgumentException("Empty command");
StringTokenizer st = new StringTokenizer(command);
String[] cmdarray = new String[st.countTokens()];
for (int i = 0; st.hasMoreTokens(); i++)
cmdarray[i] = st.nextToken();
return exec(io, cmdarray, envp, dir);
}
/**
* @param io IO
* @param cmdarray command
* @param envp environment
* @return process
* @throws IOException on any error
*
* @deprecated
* @see OSCommand
*/
public Process exec(IO io, String[] cmdarray, String[] envp) throws IOException {
return exec(io, cmdarray, envp, null);
}
/**
* @param io IO
* @param cmdarray command
* @param envp environment
* @param dir working directory
* @return process
* @throws IOException on any error
*
* @deprecated
* @see OSCommand
*/
public Process exec(IO io, String[] cmdarray, String[] envp, File dir) throws IOException {
return new ForkerBuilder(cmdarray).io(io).environment(envp).directory(dir).start();
}
/**
* Connect to the forker daemon using a known cookie. This is useful for
* debugging, as you can run a separate Forker daemon (as any user) and
* connect to it.
*
* @param cookie daemon cookiie
*/
public static void connectDaemon(Instance cookie) {
loadDaemon(cookie, null, true);
}
/**
* Connect to the forker daemon running in unauthenticated mode on a known
* port
*
* @param port daemon port
*/
public static void connectUnauthenticatedDaemon(int port) {
connectDaemon(new Instance("NOAUTH", port));
}
/**
* @return instance
* @deprecated
* @see OSCommand
*/
public static Forker get() {
return INSTANCE;
}
/**
* Get the classpath to be used to load the daemon. Attempts will be made to
* determine this automatically, but this may not always work, for example
* when running inside Maven the classpath must be built from the plugin
* dependencies.
*
* @return classpath
*/
public static String getDaemonClasspath() {
return daemonClasspath == null ? System.getProperty("java.class.path") : daemonClasspath;
}
/**
* Get a cut-down classpath that may be used to launch forker from the
* current classpath.
*
* @return forker classpath
*/
public static String getForkerClasspath() {
return getForkerClasspath(getDaemonClasspath());
}
/**
* Get a cut-down classpath that may be used to launch forker given a
* complete classpath.
*
* @param forkerClasspath complete forker classpath
* @return cut down forker classpath
*/
public static String getForkerClasspath(String forkerClasspath) {
StringBuilder cp = new StringBuilder();
for (String p : forkerClasspath.split(File.pathSeparator)) {
File f = new File(p);
if (f.isDirectory()) {
/*
* A directory, so this is likely in dev environment
*/
for (String regex : FORKER_DIRS) {
if (f.getPath().matches(regex)) {
if (cp.length() > 0)
cp.append(File.pathSeparator);
cp.append(p);
}
}
} else {
for (String regex : FORKER_JARS) {
if (f.getName().matches(regex)) {
if (cp.length() > 0)
cp.append(File.pathSeparator);
cp.append(p);
break;
}
}
}
}
String classpath = cp.toString();
return classpath;
}
/**
* Get whether any attempt has been made to load the daemon (if it failed,
* it won't be attempted again).
*
* @return daemon load attempted
*/
public static boolean isDaemonLoaded() {
return daemonLoaded;
}
/**
* Get whether the daemon was load successfully and is now running.
*
* @return daemon loaded and running
*/
public static boolean isDaemonRunning() {
return daemonRunning;
}
/**
* Get whether the daemon was load successfully and is now running as an
* administrator.
*
* @return daemon loaded and running as administrator
*/
public static boolean isDaemonRunningAsAdministrator() {
return daemonRunning && daemonAdministrator;
}
/**
* Get whether the application is currently running via the wrapper.
*
* @return wrapper
*/
public static boolean isWrapped() {
return wrapped;
}
/**
* Start the forker daemon (if it is not already started) using the current
* user.
*/
public static void loadDaemon() {
loadDaemon(false);
}
/**
* Start the forker daemon (if it is not already started), optionally as an
* administrator. Note, great care should be taken in doing this, as it will
* allow subsequent processes to run as administrator with no further
* authentication. When <code>true</code>, the daemon started will be
* isolated and only usable by this runtime.
*
* @param asAdministrator load daemon as administrator
*/
public static void loadDaemon(boolean asAdministrator) {
if (!daemonLoaded) {
loadDaemon(asAdministrator ? EffectiveUserFactory.getDefault().administrator() : null);
daemonAdministrator = asAdministrator;
}
}
/**
* Start the forker daemon (if it is not already started), optionally as
* another user. Note, great care should be taken in doing this, as it will
* allow subsequent processes to run as this user with no further
* authentication. Also, external applications that have access to the
* cookie file may connect to the forker daemon and ask it to run processes
* too.
*
* @param effectiveUser effective user
*/
public static void loadDaemon(final EffectiveUser effectiveUser) {
loadDaemon(null, effectiveUser, effectiveUser != null);
}
/**
* Start the forker daemon (if it is not already started) as the current
* user making it <b>isolated</b>, i.e. usable only by this runtime.
*/
public static void loadIsolatedDaemon() {
loadDaemon(null, null, true);
}
/**
* This is used when an application is launched from Forker Wrapper. The
* daemon cookie is passed in as the first line of stdin. The first argument
* is a boolean indicating if the daemon is running as an administrator, the
* second is the class name to actually load, the remaining arguments are
* the program arguments.
*
* @param args command line arguments
* @throws Exception on any error
*/
public static void main(String[] args) throws Exception {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String cookieText = reader.readLine();
final Instance cookie = new Instance(cookieText);
Cookie.get().set(cookie);
daemonLoaded = true;
wrapped = true;
daemonRunning = true;
List<String> argList = new ArrayList<String>(Arrays.asList(args));
daemonAdministrator = "true".equals(argList.remove(0));
String classname = argList.remove(0);
Class<?> clazz = Class.forName(classname);
@SuppressWarnings("resource")
final Socket daemonSocket = new Socket();
long started = System.currentTimeMillis();
while (true) {
try {
daemonSocket.connect(new InetSocketAddress("127.0.0.1", cookie.getPort()), 5000);
} catch (Exception e) {
if ((System.currentTimeMillis() - started) > 30000) {
return;
}
continue;
}
break;
}
/*
* Make a connection back to forker daemon and keep it open, waiting for
* a reply that will never come. If the connection closes, forker
* wrapper process has died, and so we should shutdown too
*/
new Thread() {
{
setDaemon(true);
setPriority(MIN_PRIORITY);
setName("ForkerWrapperLink");
}
public void run() {
try {
DataOutputStream dos = new DataOutputStream(daemonSocket.getOutputStream());
dos.writeUTF(cookie.getCookie());
dos.writeByte(2);
dos.flush();
DataInputStream din = new DataInputStream(daemonSocket.getInputStream());
while (true) {
if (din.readInt() != States.OK)
throw new Exception("Unexpected response.");
dos.writeByte(0);
dos.flush();
}
// Now we leave this open
} catch (Exception e) {
if (daemonSocket != null) {
try {
daemonSocket.close();
} catch (IOException e1) {
}
}
} finally {
System.err.println("Process terminated due to wrapper process terminating");
System.exit(1);
}
}
}.start();
clazz.getMethod("main", String[].class).invoke(null, new Object[] { argList.toArray(new String[0]) });
}
/**
* Get a stream that may be used to read from a file accessible by the user
* that is running the daemon. For example, if the daemon is running as
* administrator, this includes files that are normally only accessible by
* an administrative user.
*
* @param file file
* @return stream to read from
* @throws IOException on any I/O error
*/
public static InputStream readFile(File file) throws IOException {
Cookie cookie = Cookie.get();
Instance instance = cookie.load();
final Socket daemonSocket = new Socket("127.0.0.1", instance.getPort());
try {
DataOutputStream dos = new DataOutputStream(daemonSocket.getOutputStream());
dos.writeUTF(instance.getCookie());
dos.writeByte(3);
dos.writeUTF(file.getAbsolutePath());
dos.flush();
DataInputStream din = new DataInputStream(daemonSocket.getInputStream());
if (din.readInt() != States.OK)
throw new IOException(din.readUTF());
din.readLong(); // Length, not needed for now
return new FilterInputStream(daemonSocket.getInputStream()) {
@Override
public void close() throws IOException {
try {
super.close();
} finally {
daemonSocket.close();
}
}
};
// Now we leave this open
} catch (IOException e) {
daemonSocket.close();
throw e;
}
}
/**
* Set the classpath to be used to load the daemon. Attempts will be made to
* determine this automatically, but this may not always work, for example
* when running inside Maven the classpath must be built from the plugin
* dependencies.
*
* This must be called before the daemon is loaded
*
* @param cp classpath
*/
public static void setDaemonClasspath(String cp) {
if (isDaemonRunning())
throw new IllegalStateException("Daemon is already running.");
daemonClasspath = cp;
}
/**
* Get a stream that may be used to write to a file accessible by the user
* that is running the daemon. For example, if the daemon is running as
* administrator, this includes files that are normally only accessible by
* an administrative user.
*
* @param file file
* @param append open and append
* @return stream to write to
* @throws IOException on any I/O error
*/
public static OutputStream writeFile(File file, boolean append) throws IOException {
Cookie cookie = Cookie.get();
Instance instance = cookie.load();
final Socket daemonSocket = new Socket("127.0.0.1", instance.getPort());
try {
final DataOutputStream dos = new DataOutputStream(daemonSocket.getOutputStream());
dos.writeUTF(instance.getCookie());
dos.writeByte(4);
dos.writeUTF(file.getAbsolutePath());
dos.writeBoolean(append);
dos.flush();
final DataInputStream din = new DataInputStream(daemonSocket.getInputStream());
if (din.readInt() != States.OK)
throw new IOException(din.readUTF());
return new OutputStream() {
@Override
public void close() throws IOException {
try {
dos.writeInt(0);
din.readInt();
} catch (IOException ioe) {
daemonSocket.close();
throw ioe;
}
}
@Override
public void flush() throws IOException {
try {
dos.flush();
} catch (IOException ioe) {
daemonSocket.close();
throw ioe;
}
}
@Override
public void write(byte[] b) throws IOException {
try {
if (b.length > 0) {
dos.writeInt(b.length);
dos.write(b);
}
} catch (IOException ioe) {
daemonSocket.close();
throw ioe;
}
}
@Override
public void write(byte[] b, int off, int len) throws IOException {
try {
if (len > 0) {
dos.writeInt(len);
dos.write(b, off, len);
}
} catch (IOException ioe) {
daemonSocket.close();
throw ioe;
}
}
@Override
public void write(int b) throws IOException {
try {
dos.writeInt(1);
dos.writeByte(b);
} catch (IOException ioe) {
daemonSocket.close();
throw ioe;
}
}
};
} catch (IOException e) {
daemonSocket.close();
throw e;
}
}
private static void loadDaemon(Instance fixedCookie, final EffectiveUser effectiveUser, boolean isolated) {
if (!daemonLoaded) {
/* Only attempt this if forker daemon is on the class path */
try {
Class.forName("com.sshtools.forker.daemon.Forker");
try {
/*
* If running as another user, always create a new isolated
* forker daemon
*/
Instance cookie = fixedCookie == null ? (isolated ? null : Cookie.get().load()) : fixedCookie;
boolean isRunning = cookie != null && cookie.isRunning();
if (!isRunning) {
if (fixedCookie != null) {
System.err.println("[WARNING] A fixed cookie of " + fixedCookie
+ " was provided, but a daemon for this is not running.");
return;
}
final ForkerDaemonThread fdt = new ForkerDaemonThread(effectiveUser, isolated);
fdt.start();
// Wait for a little bit for the daemon to start
long now = System.currentTimeMillis();
long expire = now + (Integer.parseInt(System.getProperty("forker.daemon.launchTimeout", "180")) * 1000);
while (now < expire && !fdt.errored) {
try {
cookie = Cookie.get().load();
if (cookie != null && cookie.isRunning())
break;
} catch (Exception e) {
}
now = System.currentTimeMillis();
Thread.sleep(500);
}
if (cookie == null || !cookie.isRunning())
throw new RuntimeException("Failed to start forker daemon.");
daemonRunning = true;
if (isolated) {
/*
* Open a connection to the forker daemon and keep
* it open. When forker see this connection go down,
* it will shut itself down
*
* NOTE
*
* VERY STRANGE. Unless this Socket object has a
* strong reference, it will close when we leave
* this scope!?!?!?! As far as I know the should not
* happen. The symptom is forker daemon will
* shutdown as this socket has been closed (so any
* any new commands to execute will get rejected).
*/
daemonMaintenanceSocket = null;
try {
daemonMaintenanceSocket = new Socket("127.0.0.1", cookie.getPort());
DataOutputStream dos = new DataOutputStream(daemonMaintenanceSocket.getOutputStream());
dos.writeUTF(cookie.getCookie());
dos.writeByte(1);
dos.flush();
DataInputStream din = new DataInputStream(daemonMaintenanceSocket.getInputStream());
if (din.readInt() != States.OK)
throw new Exception("Unexpected response.");
// Now we leave this open
} catch (Exception e) {
if (daemonMaintenanceSocket != null) {
daemonMaintenanceSocket.close();
}
}
}
} else {
daemonRunning = true;
if (fixedCookie != null) {
Cookie.get().set(fixedCookie);
}
}
} catch (InterruptedException e) {
} catch (IOException ioe) {
System.err.println("[WARNING] Could not load cookie, and so could not start a daemon.");
}
} catch (ClassNotFoundException cnfe) {
} finally {
// Don't try again whatever
daemonLoaded = true;
}
}
}
private static final class ForkerDaemonThread extends Thread {
private final EffectiveUser effectiveUser;
private boolean errored;
private boolean isolated;
private Process process;
private ForkerDaemonThread(EffectiveUser effectiveUser, boolean isolated) {
super("ForkerDaemon");
this.effectiveUser = effectiveUser;
this.isolated = isolated;
setDaemon(true);
}
public void run() {
String javaExe = OS.getJavaPath();
/*
* Build up a cut down classpath with only the jars forker daemon
* needs
*/
String forkerClasspath = (daemonClasspath == null ? System.getProperty("java.class.path", "") : daemonClasspath);
String classpath = getForkerClasspath(forkerClasspath);
ForkerBuilder fb = new ForkerBuilder(javaExe, "-Xmx" + System.getProperty("forker.daemon.maxMemory", "8m"),
"-Djava.library.path=" + System.getProperty("java.library.path", ""), "-classpath", classpath,
"com.sshtools.forker.daemon.Forker");
if (effectiveUser != null) {
fb.effectiveUser(effectiveUser);
}
if (isolated) {
fb.command().add("--isolated");
}
fb.io(IO.DEFAULT);
// fb.background(true);
fb.redirectErrorStream(true);
try {
process = fb.start();
try {
InputStream inputStream = process.getInputStream();
/*
* Need stdin in case we need to elevate and dont have a
* GUI. Must flush after every character too
*/
new Thread() {
public void run() {
try {
OutputStream outputStream = process.getOutputStream();
while (true) {
int r = System.in.read();
if (r == -1)
break;
outputStream.write(r);
outputStream.flush();
}
} catch (IOException e) {
}
}
}.start();
if (isolated) {
/*
* Wait for cookie. We can't just read stdout line by
* line, as there may be output from a console based
* 'askpass' that we need to display immediately, but we
* want to extract and NOT display the forker cookie
* when authentication succeeds.
*/
StringBuffer line = new StringBuffer();
String matchStr = "FORKER-COOKIE: ";
int matched = 0;
while (true) {
int r = inputStream.read();
if (r == -1) {
break;
} else {
char chr = (char) r;
if (r == 13 || r == 10) {
matched = 0;
String l = line.toString();
if (l.startsWith("FORKER-COOKIE: ")) {
Cookie.get().set(new Instance(l.substring(15)));
break;
}
line.setLength(0);
System.out.print(chr);
} else {
line.append(chr);
if (chr == matchStr.charAt(matched)) {
matched++;
if (matched == matchStr.length()) {
Cookie.get().set(new Instance(
new BufferedReader(new InputStreamReader(inputStream)).readLine()));
break;
}
} else {
if (matched > 0) {
matched = 0;
System.out.print(line.toString());
}
System.out.print(chr);
}
}
}
}
}
// Now just read till it dies (or we die)
IOUtils.copy(inputStream, System.err);
} finally {
process.waitFor();
}
if (process.exitValue() != 0)
throw new IOException("Attempt to start forker daemon returned exit code " + process.exitValue());
} catch (Exception e) {
e.printStackTrace();
errored = true;
}
}
}
}
|
package org.snomed.otf.scheduler.domain;
import java.util.*;
import javax.persistence.*;
@Entity
public class JobRun {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
UUID id;
String jobName;
@ElementCollection
@CollectionTable(name = "job_run_parameters")
@MapKeyColumn(name="param_name", length=25)
@Column(name="value")
Map<String, String> parameters = new HashMap<>();
String terminologyServerUrl;
Date requestTime;
String user;
String authToken;
JobStatus status;
String debugInfo;
Date resultTime;
Integer issuesReported;
String resultUrl;
private JobRun () {}
static public JobRun create(String jobName, String user) {
JobRun j = new JobRun();
j.id = UUID.randomUUID();
j.jobName = jobName;
j.user = user;
j.requestTime = new Date();
return j;
}
static public JobRun create(JobSchedule jobSchedule) {
JobRun j = new JobRun();
j.id = UUID.randomUUID();
j.jobName = jobSchedule.getJobName();
j.user = jobSchedule.getUser();
j.setParameters(new HashMap<>(jobSchedule.getParameters()));
j.requestTime = new Date();
return j;
}
public String getJobName() {
return jobName;
}
public void setJobName(String jobName) {
this.jobName = jobName;
}
public Map<String, String> getParameters() {
return parameters;
}
public String getParameter(String key) {
if (parameters.containsKey(key)) {
return parameters.get(key);
}
return null;
}
public void setParameters(Map<String, String> parameters) {
this.parameters = parameters;
}
public void setParameter(String key, Object value) {
this.parameters.put(key, value.toString());
}
public String getTerminologyServerUrl() {
return terminologyServerUrl;
}
public void setTerminologyServerUrl(String terminologyServerUrl) {
this.terminologyServerUrl = terminologyServerUrl;
}
public Date getRequestTime() {
return requestTime;
}
public void setRequestTime(Date requestTime) {
this.requestTime = requestTime;
}
public String getUser() {
return user;
}
public String getAuthToken() {
return authToken;
}
public void setAuthToken(String authToken) {
this.authToken = authToken;
}
public JobStatus getStatus() {
return status;
}
public void setStatus(JobStatus status) {
this.status = status;
}
public String getDebugInfo() {
return debugInfo;
}
public void setDebugInfo(String debugInfo) {
this.debugInfo = debugInfo;
}
public Date getResultTime() {
return resultTime;
}
public void setResultTime(Date resultTime) {
this.resultTime = resultTime;
}
public Integer getIssuesReported() {
return issuesReported;
}
public void setIssuesReported(Integer issuesReported) {
this.issuesReported = issuesReported;
}
public String getResultUrl() {
return resultUrl;
}
public void setResultUrl(String resultUrl) {
this.resultUrl = resultUrl;
}
public UUID getId() {
return id;
}
public void setId(UUID id) {
this.id = id;
}
public void setUser(String user) {
this.user = user;
}
public String toString() {
return jobName + " (" + id + ")"
+ " for user '" + user + "' in status: "
+ status
+ debugInfo == null? "" : " (" + debugInfo + ")";
}
}
|
package org.jaxen.saxpath.base;
import junit.framework.TestCase;
public class XPathLexerTest extends TestCase
{
private XPathLexer lexer;
private Token token;
public XPathLexerTest(String name)
{
super( name );
}
public void setUp()
{
}
public void tearDown()
{
setLexer( null );
setToken( null );
}
public void testNamespace()
{
setText( "a:b" );
nextToken();
assertEquals( TokenTypes.IDENTIFIER,
tokenType() );
assertEquals( "a",
tokenText() );
nextToken();
assertEquals( TokenTypes.COLON,
tokenType() );
nextToken();
assertEquals( TokenTypes.IDENTIFIER,
tokenType() );
assertEquals( "b",
tokenText() );
}
public void testIdentifier()
{
setText( "foo" );
nextToken();
assertEquals( TokenTypes.IDENTIFIER,
tokenType() );
assertEquals( "foo",
tokenText() );
setText( "foo.bar" );
nextToken();
assertEquals( TokenTypes.IDENTIFIER,
tokenType() );
assertEquals( "foo.bar",
tokenText() );
}
public void testBurmeseIdentifier()
{
setText( "\u1000foo" );
nextToken();
assertEquals( TokenTypes.ERROR,
tokenType() );
}
public void testIdentifierAndOperator()
{
setText( "foo and bar" );
nextToken();
assertEquals( TokenTypes.IDENTIFIER,
tokenType() );
assertEquals( "foo",
tokenText() );
nextToken();
assertEquals( TokenTypes.AND,
tokenType() );
nextToken();
assertEquals( TokenTypes.IDENTIFIER,
tokenType() );
assertEquals( "bar",
tokenText() );
}
public void testTrickyIdentifierAndOperator()
{
setText( "and and and" );
nextToken();
assertEquals( TokenTypes.IDENTIFIER,
tokenType() );
assertEquals( "and",
tokenText() );
nextToken();
assertEquals( TokenTypes.AND,
tokenType() );
nextToken();
assertEquals( TokenTypes.IDENTIFIER,
tokenType() );
assertEquals( "and",
tokenText() );
}
public void testInteger()
{
setText( "1234" );
nextToken();
assertEquals( TokenTypes.INTEGER,
tokenType() );
assertEquals( "1234",
tokenText() );
}
public void testDouble()
{
setText( "12.34" );
nextToken();
assertEquals( TokenTypes.DOUBLE,
tokenType() );
assertEquals( "12.34",
tokenText() );
}
public void testDoubleOnlyDecimal()
{
setText( ".34" );
nextToken();
assertEquals( TokenTypes.DOUBLE,
tokenType() );
assertEquals( ".34",
tokenText() );
}
public void testNumbersAndMode()
{
setText( "12.34 mod 3" );
nextToken();
assertEquals( TokenTypes.DOUBLE,
tokenType() );
assertEquals( "12.34",
tokenText() );
nextToken();
assertEquals( TokenTypes.MOD,
tokenType() );
nextToken();
assertEquals( TokenTypes.INTEGER,
tokenType() );
}
public void testSlash()
{
setText( "/" );
nextToken();
assertEquals( TokenTypes.SLASH,
tokenType() );
}
public void testDoubleSlash()
{
setText( "
nextToken();
assertEquals( TokenTypes.DOUBLE_SLASH,
tokenType() );
}
public void testIdentifierWithColon()
{
setText ( "foo:bar" );
nextToken();
assertEquals( TokenTypes.IDENTIFIER,
tokenType() );
assertEquals( "foo",
tokenText() );
nextToken();
assertEquals( TokenTypes.COLON,
tokenType() );
nextToken();
assertEquals( TokenTypes.IDENTIFIER,
tokenType() );
assertEquals( "bar",
tokenText() );
}
public void testEOF()
{
setText( "foo" );
nextToken();
assertEquals( TokenTypes.IDENTIFIER,
tokenType() );
assertEquals( "foo",
tokenText() );
nextToken();
assertEquals( TokenTypes.EOF,
tokenType() );
}
/*
public void testAttributeWithUnderscore()
{
setText( "@_foo" );
nextToken();
assertEquals( TokenTypes.IDENTIFIER,
tokenType() );
assertEquals( "_foo",
tokenText() );
nextToken();
assertEquals( TokenTypes.EOF,
tokenType() );
}
*/
public void testWhitespace()
{
setText ( " / \tfoo:bar" );
nextToken();
assertEquals( TokenTypes.SLASH,
tokenType() );
nextToken();
assertEquals( TokenTypes.IDENTIFIER,
tokenType() );
assertEquals( "foo",
tokenText() );
nextToken();
assertEquals( TokenTypes.COLON,
tokenType() );
nextToken();
assertEquals( TokenTypes.IDENTIFIER,
tokenType() );
assertEquals( "bar",
tokenText() );
}
private void nextToken()
{
setToken( getLexer().nextToken() );
}
private int tokenType()
{
return getToken().getTokenType();
}
private String tokenText()
{
return getToken().getTokenText();
}
private Token getToken()
{
return this.token;
}
private void setToken(Token token)
{
this.token = token;
}
private void setText(String text)
{
this.lexer = new XPathLexer( text );
}
private void setLexer(XPathLexer lexer)
{
this.lexer = lexer;
}
private XPathLexer getLexer()
{
return this.lexer;
}
}
|
package tests;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.lib.RepositoryBuilder;
import org.eclipse.jgit.util.FileUtils;
import org.kercoin.magrit.Context;
import org.kercoin.magrit.utils.GitUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* A very different place from {@link GitUtils} for git utilities ; to be used by unit tests
* @author ptitfred
*
*/
public final class GitTestsUtils {
protected static final Logger log = LoggerFactory.getLogger(GitTestsUtils.class);
public static Repository inflate(File archive, File where) throws Exception {
assert archive.exists();
assert archive.isFile();
assert archive.canRead();
assert where.exists();
assert where.isDirectory();
assert where.canWrite();
if (where.list().length > 0) {
FileUtils.delete(where, FileUtils.RECURSIVE);
if (!where.exists()) {
where.mkdir();
} else if (where.list().length > 0) {
throw new Exception("Couldn't clean up !");
}
}
final int BUFFER = 2048;
try {
ZipInputStream zin = new ZipInputStream(new BufferedInputStream(
new FileInputStream(archive)));
ZipEntry entry;
while ((entry = zin.getNextEntry()) != null) {
File output = new File(where, entry.getName());
output.getParentFile().mkdirs();
if (!entry.isDirectory()) {
FileOutputStream fos = new FileOutputStream(
output.getAbsolutePath()
);
BufferedOutputStream dest = new BufferedOutputStream(fos,
BUFFER);
int count;
byte data[] = new byte[BUFFER];
while ((count = zin.read(data, 0, BUFFER)) != -1) {
dest.write(data, 0, count);
}
dest.flush();
dest.close();
}
}
zin.close();
} catch (IOException e) {
log.error("Error while inflating repository from " + archive.getPath(), e);
}
try {
return Git.open(where).getRepository();
} catch (IOException e) {
log.error("Error while opening repository " + where.getPath(), e);
}
return null;
}
public static Repository open(Context context, String repoPath) throws IOException {
RepositoryBuilder builder = new RepositoryBuilder();
builder.setGitDir(new File(context.configuration().getRepositoriesHomeDir(), repoPath));
return builder.build();
}
}
|
package sudoku.parse;
import common.Pair;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.function.Function;
import sudoku.Sudoku;
/**
* <p>A utility class that tries to parse a target out of a text source via a specified Scanner that
* scans from that text.</p> <p>Used by Puzzle to read a sudoku puzzle of unknown dimensions from a
* .txt file and to extract both the content of the puzzle and the
* {@link Sudoku#magnitude() magnitude} of the puzzle without requiring separate passes for each of
* those results.</p>
* @author fiveham
* @author fiveham
*
*/
public class TxtParser implements Parser{
private int mag;
private final List<Integer> values;
/**
* <p>Constructs a Parser that extracts and parses text via the specified Scanner. {@code s} is
* closed by this constructor.</p>
* @param s the Scanner that sources the text that this Parser analyses. {@code s} is closed by
* this constructor
*/
public TxtParser(File f, String charset) throws FileNotFoundException{
Pair<List<Integer>,Integer> pair = null;
for(TextFormatStyle style : TextFormatStyle.values()){
pair = style.parse.apply(new Scanner(f, charset));
if(pair != null){
break;
}
}
if(pair == null){
throw new IllegalArgumentException("Could not parse specified file as txt.");
}
this.values = pair.getA();
this.mag = pair.getB();
}
public static final int TYPICAL_BLOCK_SIDE_LENGTH = 9;
private static enum TextFormatStyle{
BLOCK((s) -> {
List<String> lines = new ArrayList<>(TYPICAL_BLOCK_SIDE_LENGTH);
do{
if(!s.hasNextLine()){
return null;
}
String line = s.nextLine();
lines.add(line);
if(line.length() != lines.get(0).length()){
return null;
}
} while(lines.size() < lines.get(0).length());
int mag = (int) Math.sqrt(lines.size());
if(mag*mag != lines.size()){ //side-length of square is a square number?
return null;
}
List<Integer> result = new ArrayList<>(lines.size() * lines.size());
for(String line : lines){
for(int i = 0; i<line.length(); ++i){
try{
result.add(Integer.parseInt(line.substring(i, i+1), lines.size()+1));
} catch(NumberFormatException e){
return null;
}
}
}
return new Pair<>(result,mag);
}),
TOKEN((s) -> {
List<Integer> val = new ArrayList<>();
while(s.hasNextInt()){
val.add(s.nextInt());
}
int mag = (int) Math.sqrt(Math.sqrt(val.size()));
if(mag*mag*mag*mag != val.size()
|| val.stream().anyMatch((i) -> i > mag*mag)){
return null;
}
return new Pair<>(val,mag);
});
private final Function<Scanner, Pair<List<Integer>, Integer>> parse;
private TextFormatStyle(Function<Scanner, Pair<List<Integer>, Integer>> parse){
this.parse = parse;
}
}
/**
* <p>Returns the magnitude of the puzzle specified by the text behind the Scanner sent to the
* {@link #Parser(Scanner) constructor}, which is determined as a side-effect of the
* {@link #parse(Scanner) parsing} process.</p>
* @return the magnitude of the puzzle specified by the text behind the Scanner sent to the
* {@link #Parser(Scanner) constructor}
*/
@Override
public int mag(){
return mag;
}
/**
* <p>Returns a list of the integers present in the text of the puzzle as read from the text
* source specified by the Scanner sent to the {@link #Parser(Scanner) constructor}.</p>
* @return the initial values in the cells of this Parser's puzzle, where 0 represents an empty
* cell
*/
@Override
public List<Integer> values(){
return values;
}
}
|
package org.rabix.executor.service.impl;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import org.rabix.executor.engine.EngineStub;
import org.rabix.executor.execution.JobHandlerCommandDispatcher;
import org.rabix.executor.execution.command.StartCommand;
import org.rabix.executor.execution.command.StatusCommand;
import org.rabix.executor.execution.command.StopCommand;
import org.rabix.executor.model.JobData;
import org.rabix.executor.model.JobData.JobDataStatus;
import org.rabix.executor.service.JobDataService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.base.Preconditions;
import com.google.inject.Inject;
import com.google.inject.Provider;
public class JobDataServiceImpl implements JobDataService {
private final static Logger logger = LoggerFactory.getLogger(JobDataServiceImpl.class);
private final Map<String, Map<String, JobData>> jobDataMap = new HashMap<>();
private Provider<StopCommand> stopCommandProvider;
private Provider<StartCommand> startCommandProvider;
private Provider<StatusCommand> statusCommandProvider;
private JobHandlerCommandDispatcher jobHandlerCommandDispatcher;
private EngineStub engineStub;
private ScheduledExecutorService starter = Executors.newSingleThreadScheduledExecutor();
@Inject
public JobDataServiceImpl(JobHandlerCommandDispatcher jobHandlerCommandDispatcher,
Provider<StopCommand> stopCommandProvider, Provider<StartCommand> startCommandProvider,
Provider<StatusCommand> statusCommandProvider) {
this.jobHandlerCommandDispatcher = jobHandlerCommandDispatcher;
this.stopCommandProvider = stopCommandProvider;
this.startCommandProvider = startCommandProvider;
this.statusCommandProvider = statusCommandProvider;
}
@Override
public void initialize(EngineStub engineStub) {
this.engineStub = engineStub;
this.starter.scheduleAtFixedRate(new JobStatusHandler(), 0, 100, TimeUnit.MILLISECONDS);
}
@Override
public JobData find(String id, String contextId) {
Preconditions.checkNotNull(id);
synchronized (jobDataMap) {
logger.debug("find(id={})", id);
return getJobDataMap(contextId).get(id);
}
}
@Override
public List<JobData> find(JobDataStatus... statuses) {
Preconditions.checkNotNull(statuses);
synchronized (jobDataMap) {
List<JobDataStatus> statusList = Arrays.asList(statuses);
logger.debug("find(status={})", statusList);
List<JobData> jobDataByStatus = new ArrayList<>();
for (Entry<String, Map<String, JobData>> entry : jobDataMap.entrySet()) {
for (JobData jobData : entry.getValue().values()) {
if (statusList.contains(jobData.getStatus())) {
jobDataByStatus.add(jobData);
}
}
}
return jobDataByStatus;
}
}
@Override
public void save(JobData jobData) {
Preconditions.checkNotNull(jobData);
synchronized (jobDataMap) {
logger.debug("save(jobData={})", jobData);
getJobDataMap(jobData.getJob().getRootId()).put(jobData.getId(), jobData);
}
}
@Override
public JobData save(JobData jobData, String message, JobDataStatus status) {
Preconditions.checkNotNull(jobData);
synchronized (jobDataMap) {
logger.debug("save(jobData={}, message={}, status={})", jobData, message, status);
jobData = JobData.cloneWithStatusAndMessage(jobData, status, message);
save(jobData);
return jobData;
}
}
private Map<String, JobData> getJobDataMap(String contextId) {
synchronized (jobDataMap) {
Map<String, JobData> jobList = jobDataMap.get(contextId);
if (jobList == null) {
jobList = new HashMap<>();
jobDataMap.put(contextId, jobList);
}
return jobList;
}
}
private class JobStatusHandler implements Runnable {
private int maxRunningJobs = 200;
@Override
public void run() {
synchronized (jobDataMap) {
List<JobData> aborting = find(JobDataStatus.ABORTING);
for (JobData jobData : aborting) {
save(JobData.cloneWithStatus(jobData, JobDataStatus.ABORTED));
jobHandlerCommandDispatcher.dispatch(jobData, stopCommandProvider.get(), engineStub);
}
List<JobData> pending = find(JobDataStatus.PENDING);
List<JobData> running = find(JobDataStatus.RUNNING, JobDataStatus.STARTED);
if (maxRunningJobs - running.size() == 0) {
logger.info("Running {} jobs. Waiting for some to finish...", running.size());
} else {
for (int i = 0; i < Math.min(pending.size(), maxRunningJobs - running.size()); i++) {
JobData jobData = pending.get(i);
save(JobData.cloneWithStatus(jobData, JobDataStatus.READY));
jobHandlerCommandDispatcher.dispatch(jobData, startCommandProvider.get(), engineStub);
jobHandlerCommandDispatcher.dispatch(jobData, statusCommandProvider.get(), engineStub);
}
}
}
}
}
}
|
package org.intermine.api.bag;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import org.apache.commons.lang.ObjectUtils;
import org.apache.commons.lang.StringUtils;
import org.intermine.api.InterMineAPI;
import org.intermine.api.profile.InterMineBag;
import org.intermine.api.profile.Profile;
import org.intermine.api.profile.ProfileManager;
import org.intermine.api.util.TextUtil;
import org.intermine.model.userprofile.SavedBag;
import org.intermine.objectstore.ObjectStore;
import org.intermine.objectstore.ObjectStoreException;
import org.intermine.objectstore.intermine.ObjectStoreWriterInterMineImpl;
import org.intermine.objectstore.intermine.SQLOperation;
/**
* A representation of an invitation to share a resource.
*
* @author Alex Kalderimis
*/
public class SharingInvite
{
private static final class FetchInviteData extends SQLOperation<IntermediateRepresentation>
{
private final String token;
private FetchInviteData(String token) {
this.token = token;
}
@Override
public IntermediateRepresentation run(PreparedStatement stm) throws SQLException {
stm.setString(1, token);
ResultSet rs = stm.executeQuery();
while (rs.next()) {
return toIntermediateReps(rs);
}
return null;
}
}
/**
* Exception thrown when we can't find a shared invitation.
* @author Alex Kalderimis
*
*/
public static class NotFoundException extends Exception
{
private static final long serialVersionUID = 4508741600952344965L;
/** @param msg the reason it could not be found **/
NotFoundException(String msg) {
super(msg);
}
}
/** The DB table that holds the invitations **/
public static final String TABLE_NAME = "baginvites";
private static final String TABLE_DEFINITION =
"CREATE TABLE " + TABLE_NAME + " ("
+ "bagid integer NOT NULL, "
+ "inviterid integer NOT NULL, "
+ "token char(20) UNIQUE NOT NULL, "
+ "createdat timestamp DEFAULT NOW(), "
+ "acceptedat timestamp,"
+ "accepted boolean, "
+ "invitee text NOT NULL)";
/** @return the SQL needed to create the table **/
public static String getTableDefinition() {
return TABLE_DEFINITION;
}
private static final String FETCH_ALL_SQL =
"SELECT bagid, inviterid, createdat, accepted, acceptedat, invitee, token FROM "
+ TABLE_NAME;
private static final String FETCH_MINE_SQL =
FETCH_ALL_SQL + " WHERE inviterid = ?";
private static final String FETCH_SQL = FETCH_ALL_SQL + " WHERE token = ?";
private static final String SAVE_SQL =
"INSERT INTO " + TABLE_NAME + " (bagid, inviterid, token, invitee) "
+ "VALUES (?, ?, ?, ?)";
private static final String FULL_SAVE_SQL =
"INSERT INTO " + TABLE_NAME
+ " (bagid, inviterid, token, invitee, createdat, acceptedat, accepted) "
+ " VALUES (?, ?, ?, ?, ?, ?, ?)";
private static final String DELETE_SQL = "DELETE FROM " + TABLE_NAME + " WHERE token = ?";
private static final String RECORD_ACCEPTANCE_SQL =
"UPDATE " + TABLE_NAME + " SET acceptedat = ?, accepted = ? WHERE token = ?";
private static final String RECORD_UNACCEPTANCE_SQL =
"UPDATE " + TABLE_NAME + " SET acceptedat = NULL, accepted = NULL WHERE token = ?";
private final InterMineBag bag;
private final String invitee;
private final String token;
private final ObjectStoreWriterInterMineImpl os;
private Date createdAt = null;
private Date acceptedAt = null;
private Boolean accepted = null;
private boolean inDB = false;
/**
* Constructor.
*
* @param bag the bag to share
* @param invitee the person to share the list with
*/
protected SharingInvite(InterMineBag bag, String invitee) {
this(bag, invitee, TextUtil.generateRandomUniqueString(20));
}
/**
* Constructor.
*
* @param bag the bag to share
* @param invitee the person to share the list with
* @param token the User token
*/
protected SharingInvite(
InterMineBag bag,
String invitee,
String token) {
this(bag, invitee, token, null, null, null);
}
/**
* Constructor.
*
* @param bag the bag to share
* @param invitee the person to share the list with
* @param token the User token
* @param createdAt date created
* @param acceptedAt date accepted
* @param accepted true if accepted
*/
protected SharingInvite(
InterMineBag bag, String invitee, String token,
Date createdAt, Date acceptedAt, Boolean accepted) {
if (invitee == null) {
throw new IllegalArgumentException("the invitee may not be null");
}
if (StringUtils.isBlank(invitee)) {
throw new IllegalArgumentException("the invitee may not be blank");
}
if (StringUtils.isBlank(token)) {
throw new IllegalArgumentException("the token must not be blank");
}
if (bag == null) {
throw new IllegalArgumentException("the bag must not be null");
}
this.bag = bag;
this.invitee = invitee;
this.token = token;
this.acceptedAt = acceptedAt;
this.createdAt = createdAt;
this.accepted = accepted;
try {
this.os = (ObjectStoreWriterInterMineImpl) bag.getUserProfileWriter();
} catch (ClassCastException cce) {
throw new RuntimeException("Hey, that isn't an intermine object-store!");
}
}
/**
* @throws SQLException database has wrong model
* @throws NotFoundException invite not found
*/
public void delete() throws SQLException, NotFoundException {
if (!inDB) {
throw new NotFoundException("This invite is not stored in the DB");
}
os.performUnsafeOperation(DELETE_SQL, new SQLOperation<Void>() {
@Override
public Void run(PreparedStatement stm) throws SQLException {
stm.setString(0, token);
stm.executeUpdate();
inDB = false;
return null;
}
});
}
/**
*
* @param wasAccepted true if accepted
* @throws SQLException database has wrong model
*/
protected void setAccepted(final Boolean wasAccepted) throws SQLException {
if (acceptedAt != null) {
throw new IllegalStateException("This invitation has already been accepted");
}
os.performUnsafeOperation(RECORD_ACCEPTANCE_SQL, new SQLOperation<Void>() {
@Override
public Void run(PreparedStatement stm) throws SQLException {
Date now = new Date();
stm.setDate(1, new java.sql.Date(now.getTime()));
stm.setBoolean(2, wasAccepted);
stm.setString(3, token);
stm.executeUpdate();
acceptedAt = now;
accepted = wasAccepted;
return null;
}
});
}
/**
* @throws SQLException database has wrong model
*/
protected void unaccept() throws SQLException {
if (acceptedAt == null) {
throw new IllegalStateException("This invitation has not been accepted");
}
os.performUnsafeOperation(RECORD_UNACCEPTANCE_SQL, new SQLOperation<Void>() {
@Override
public Void run(PreparedStatement stm) throws SQLException {
stm.setString(1, token);
stm.executeUpdate();
return null;
}
});
}
/**
* @throws SQLException database has wrong model
*/
protected void save() throws SQLException {
if (inDB) {
return;
}
if (createdAt == null) { // New - we can go ahead and only save the interesting bits.
os.performUnsafeOperation(SAVE_SQL, new SQLOperation<Void>() {
@Override
public Void run(PreparedStatement stm) throws SQLException {
stm.setInt(1, bag.getSavedBagId());
stm.setInt(2, bag.getProfileId());
stm.setString(3, token);
stm.setString(4, invitee);
stm.executeUpdate();
return null;
}
});
} else { // Needs full serialisation.
os.performUnsafeOperation(FULL_SAVE_SQL, new SQLOperation<Void>() {
@Override
public Void run(PreparedStatement stm) throws SQLException {
stm.setInt(1, bag.getSavedBagId());
stm.setInt(2, bag.getProfileId());
stm.setString(3, token);
stm.setString(4, invitee);
stm.setDate(5, new java.sql.Date(createdAt.getTime()));
if (acceptedAt == null) {
stm.setNull(6, java.sql.Types.DATE);
} else {
stm.setDate(6, new java.sql.Date(acceptedAt.getTime()));
}
if (accepted == null) {
stm.setNull(7, java.sql.Types.BOOLEAN);
} else {
stm.setBoolean(7, accepted);
}
stm.executeUpdate();
return null;
}
});
inDB = true;
}
}
/**
* @param pm profile manager
* @param inviter user who send the invite
* @return collection of objects holding the invite data
* @throws SQLException userprofile database doesn't have the correct model
*/
public static Collection<IntermediateRepresentation> getInviteData(final ProfileManager pm,
final Profile inviter)
throws SQLException {
ObjectStoreWriterInterMineImpl osw = (ObjectStoreWriterInterMineImpl)
pm.getProfileObjectStoreWriter();
return osw.performUnsafeOperation(FETCH_MINE_SQL,
new SQLOperation<Collection<IntermediateRepresentation>>() {
@Override
public Collection<IntermediateRepresentation> run(PreparedStatement stm)
throws SQLException {
stm.setInt(1, inviter.getUserId());
ResultSet rs = stm.executeQuery();
final List<IntermediateRepresentation> results
= new ArrayList<IntermediateRepresentation>();
while (rs.next()) {
results.add(toIntermediateReps(rs));
}
return results;
}
});
}
/**
* Get the invitations this profile has made.
* @param im The API of the data-warehouse
* @param inviter The profile of the user that made the invitations.
* @return A list of invitations
* @throws SQLException If a connection cannot be established, or the SQL is bad.
* @throws ObjectStoreException If the bag referenced by the invitation doesn't exist.
*/
public static Collection<SharingInvite> getInvites(final InterMineAPI im, final Profile inviter)
throws SQLException, ObjectStoreException {
return getInvites(im.getProfileManager(), im.getBagManager(), inviter);
}
/**
* Get the invitations this profile has made.
* @param pm profile manager
* @param bm bag manager
* @param inviter The profile of the user that made the invitations.
* @return A list of invitations
* @throws SQLException If a connection cannot be established, or the SQL is bad.
* @throws ObjectStoreException If the bag referenced by the invitation doesn't exist.
*/
public static Collection<SharingInvite> getInvites(final ProfileManager pm, final BagManager bm,
final Profile inviter)
throws SQLException, ObjectStoreException {
Collection<IntermediateRepresentation> rows = getInviteData(pm, inviter);
List<SharingInvite> retval = new ArrayList<SharingInvite>();
for (IntermediateRepresentation rep: rows) {
retval.add(restoreFromRow(pm, bm, rep));
}
return retval;
}
private static SharingInvite restoreFromRow(
ProfileManager pm, BagManager bm,
IntermediateRepresentation rep) throws ObjectStoreException {
ObjectStore os = pm.getProfileObjectStoreWriter();
Profile inviter = pm.getProfile(rep.inviterId);
SavedBag savedBag = (SavedBag) os.getObjectById(rep.bagId, SavedBag.class);
InterMineBag bag = bm.getBag(inviter, savedBag.getName());
return new SharingInvite(bag,
rep.invitee, rep.token, rep.createdAt, rep.acceptedAt, rep.accepted);
}
/**
* A structure for holding data we read from the DB.
* @author Alex Kalderimis
*
*/
public static class IntermediateRepresentation
{
int bagId;
int inviterId;
String token;
String invitee;
Date acceptedAt;
Date createdAt;
Boolean accepted;
/**
* @return id of the bag shared
*/
public int getBagId() {
return bagId;
}
/**
* @return id of user who sent invite
*/
public int getInviterId() {
return inviterId;
}
/**
* @return user token
*/
public String getToken() {
return token;
}
/**
* @return user invited to share the list
*/
public String getInvitee() {
return invitee;
}
/**
* @return date invitee accepted the invitation
*/
public Date getAcceptedAt() {
return acceptedAt;
}
/**
* @return data the user sent the invitation
*/
public Date getCreatedAt() {
return createdAt;
}
/**
* @return true if the invitee accepted the invitation
*/
public Boolean getAccepted() {
return accepted;
}
}
private static IntermediateRepresentation toIntermediateReps(final ResultSet rs)
throws SQLException {
IntermediateRepresentation rep = new IntermediateRepresentation();
rep.bagId = rs.getInt("bagid");
rep.inviterId = rs.getInt("inviterid");
rep.token = rs.getString("token");
rep.invitee = rs.getString("invitee");
rep.acceptedAt = rs.getDate("acceptedat");
rep.createdAt = rs.getDate("createdat");
rep.accepted = rs.getBoolean("accepted");
return rep;
}
/**
* @param im API for databases
* @param token user auth token
* @return object representing the invite
* @throws ObjectStoreException error storing the data
* @throws SQLException database has wrong model
* @throws NotFoundException invite not found
*/
public static SharingInvite getByToken(final InterMineAPI im, final String token)
throws SQLException, ObjectStoreException, NotFoundException {
// Unpack what we want from the API.
ProfileManager pm = im.getProfileManager();
BagManager bm = im.getBagManager();
ObjectStoreWriterInterMineImpl osw = (ObjectStoreWriterInterMineImpl)
pm.getProfileObjectStoreWriter();
IntermediateRepresentation row =
osw.performUnsafeOperation(FETCH_SQL, new FetchInviteData(token));
if (row == null) {
throw new NotFoundException("token not found");
}
SharingInvite invite = restoreFromRow(pm, bm, row);
invite.inDB = true;
return invite;
}
/**
* @return token
*/
public String getToken() {
return token;
}
/**
* @return list being shared
*/
public InterMineBag getBag() {
return bag;
}
/**
* @return user that received the invite
*/
public String getInvitee() {
return invitee;
}
/**
* @return date invite created
*/
public Date getCreatedAt() {
return createdAt;
}
/**
* @return data invite accepted by recipient
*/
public Date getAcceptedAt() {
return acceptedAt;
}
/**
* @return true if recipient accepted the invite
*/
public Boolean getAccepted() {
return accepted;
}
@Override
public boolean equals(Object other) {
if (other == null) {
return false;
}
if (!(other instanceof SharingInvite)) {
return this.equals(other);
}
if (other == this) {
return true;
}
SharingInvite oi = (SharingInvite) other;
return token.equals(oi.getToken());
}
@Override
public int hashCode() {
return ObjectUtils.hashCode(token);
}
@Override
public String toString() {
return String.format("[%s: token=%s bag=%s invitee=%s]",
getClass().getName(), token, bag.getName(), invitee);
}
}
|
/*
* $Id: SubTreeArticleIteratorBuilder.java,v 1.5 2014-01-06 18:18:45 etenbrink Exp $
*/
package org.lockss.plugin;
import java.util.*;
import java.util.regex.*;
import org.lockss.extractor.MetadataTarget;
import org.lockss.util.Logger;
public class SubTreeArticleIteratorBuilder {
/**
* <p>
* A programmatically buildable subtree article iterator.
* </p>
* <p>
* Currently this class can only be exposed by its enclosing class
* {@link SubTreeArticleIteratorBuilder}, but this may change in the future.
* </p>
*
* @author Thib Guicherd-Callin
* @since 1.60
*/
protected static class BuildableSubTreeArticleIterator extends SubTreeArticleIterator {
/**
* <p>
* Describes an aspect of an article, that is, one of its renditions, or
* components, or display structures.
* </p>
* <p>
* Currently this class is a non-static inner class of its enclosing class
* {@link BuildableSubTreeArticleIterator}, but this may change in the
* future.
* </p>
*
* @author Thib Guicherd-Callin
* @since 1.60
*/
protected class Aspect {
/**
* This aspect's ordered matcher replacement strings.
* @since 1.60
*/
protected List<String> matcherReplacements;
/**
* This aspect's ordered patterns.
* @since 1.60
*/
protected List<Pattern> patterns;
/**
* This aspect's roles, set if it recognizes a URL.
* @since 1.60
*/
protected List<String> roles;
/**
* <p>
* Builds a new aspect.
* </p>
* @since 1.60
*/
public Aspect() {
this.patterns = new ArrayList<Pattern>();
this.matcherReplacements = new ArrayList<String>();
this.roles = new ArrayList<String>();
}
/**
* <p>
* Determines if the given URL matches any of this aspect's patterns.
* </p>
* <p>
* Matching is adjudicated by {@link Matcher#find()}.
* </p>
*
* @param url
* A URL string.
* @return A {@link Matcher} corresponding to the {@link Pattern} that
* matched the given URL, or <code>null</code> if none did.
* @since 1.60
*/
public Matcher findCuAmongPatterns(String url) {
for (Pattern pat : patterns) {
Matcher mat = pat.matcher(url);
if (mat.find()) {
return mat;
}
}
return null;
}
/**
* <p>
* Determines if the AU contains a URL corresponding to this aspect, by
* applying its replacement strings to the given matcher.
* </p>
*
* @param matcher
* A matcher for a given URL (having matched another aspect).
* @return A {@link CachedUrl} corresponding to a URL for a successful
* matcher replacement, or <code>null</code> if no such URL exists
* in the AU.
* @since 1.60
*/
public CachedUrl findCuByPatternReplacement(Matcher matcher) {
for (String matcherReplacement : matcherReplacements) {
CachedUrl replacedCu = au.makeCachedUrl(matcher.replaceFirst(matcherReplacement));
if (replacedCu.hasContent()) {
return replacedCu;
}
}
return null;
}
/**
* <p>
* Store the given cached URL as the value of this aspect's roles in the
* given {@link ArticleFiles} instance, for any roles not already set.
* </p>
*
* @param af
* An {@link ArticleFiles} instance.
* @param cu
* A cached URL.
* @since 1.60
*/
public void processRoles(ArticleFiles af, CachedUrl cu) {
for (String role : roles) {
if (af.getRoleCu(role) == null) {
af.setRoleCu(role, cu);
}
}
}
}
/**
* <p>
* This buildable iterator's aspects.
* </p>
*
* @since 1.60
*/
protected List<Aspect> aspects;
/**
* <p>
* This aspect's ordered list of roles to be used to choose the full text
* CU.
* </p>
*
* @since 1.60
*/
protected List<String> rolesForFullText;
/**
* <p>
* A map from a role to the ordered list of roles to be used to choose the
* CU associated with that role.
* </p>
*
* @since 1.60
*/
protected Map<String, List<String>> rolesFromOtherRoles;
/**
* <p>
* Makes a new buildable iterator for the given AU using the given subtree
* article iterator specification.
* </p>
*
* @param au
* An archival unit.
* @param spec
* A subtree article iterator specification.
* @since 1.60
*/
public BuildableSubTreeArticleIterator(ArchivalUnit au, SubTreeArticleIterator.Spec spec) {
super(au, spec);
this.aspects = new ArrayList<Aspect>();
this.rolesForFullText = new ArrayList<String>();
this.rolesFromOtherRoles = new LinkedHashMap<String, List<String>>();
if (logger.isDebug2()) {
logger.debug2(String.format("Processing AU: %s", au.getName()));
}
}
/**
* <p>
* A custom implementation of
* {@link SubTreeArticleIterator#createArticleFiles(CachedUrl)} performing
* the aspect-based logic of this buildable iterator.
* </p>
*
* @param cu
* The cached URL currently under consideration.
*
* @since 1.60
*/
@Override
protected ArticleFiles createArticleFiles(CachedUrl cu) {
boolean isDebug2 = logger.isDebug2();
// Process this CU
String url = cu.getUrl();
if (isDebug2) {
logger.debug2(String.format("Processing: %s", url));
}
// Try each aspect
for (int ci = 0 ; ci < aspects.size() ; ++ci) {
Aspect aspect = aspects.get(ci);
Matcher matcher = aspect.findCuAmongPatterns(url);
if (matcher != null) {
// Does this aspect defer to a higher aspect?
for (int cj = 0 ; cj < ci ; ++cj) {
Aspect higherAspect = aspects.get(cj);
CachedUrl higherCu = higherAspect.findCuByPatternReplacement(matcher);
if (higherCu != null) {
// Defer
if (isDebug2) {
logger.debug2(String.format("Deferring to: %s", higherCu.getUrl()));
}
AuUtil.safeRelease(higherCu);
return null;
}
}
// Process this aspect; full text CU (might be overridden later)
ArticleFiles af = new ArticleFiles();
af.setFullTextCu(cu);
aspect.processRoles(af, cu);
if (isDebug2) {
logger.debug2(String.format("Full text CU set to: %s", url));
}
// Process lower aspects (unless only counting articles)
if (spec.getTarget() != null && !spec.getTarget().isArticle()) {
if (isDebug2) {
logger.debug2("Processing additional aspects");
}
for (int cj = ci + 1; cj < aspects.size(); ++cj) {
Aspect lowerAspect = aspects.get(cj);
CachedUrl lowerCu = lowerAspect.findCuByPatternReplacement(matcher);
if (lowerCu != null) {
lowerAspect.processRoles(af, lowerCu);
}
}
}
else {
if (isDebug2) {
logger.debug2("Skipping additional aspects");
}
}
// Override full text CU if order specified
if (rolesForFullText.size() > 0) {
if (isDebug2) {
logger.debug2("Overriding full text CU");
}
af.setFullTextCu(null);
for (String role : rolesForFullText) {
CachedUrl foundCu = af.getRoleCu(role);
if (foundCu != null) {
if (isDebug2) {
logger.debug2(String.format("Full text CU reset to: %s", foundCu.getUrl()));
}
af.setFullTextCu(foundCu);
break;
}
}
}
// Set roles from other roles if orders specified (unless only counting articles)
if (spec.getTarget() != null && !spec.getTarget().isArticle()) {
for (Map.Entry<String, List<String>> entry : rolesFromOtherRoles.entrySet()) {
String role = entry.getKey();
for (String otherRole : entry.getValue()) {
CachedUrl foundCu = af.getRoleCu(otherRole);
if (foundCu != null) {
if (isDebug2) {
logger.debug2(String.format("CU for %s set to: %s", otherRole, foundCu.getUrl()));
}
af.setRoleCu(role, foundCu);
break;
}
}
}
}
// Callers should call emitArticleFiles(af);
return af;
}
}
logger.warning(String.format("%s in %s did not match any expected patterns", url, au.getName()));
return null;
}
}
/**
* <p>
* A logger for use by this class and nested classes.
* </p>
*
* @since 1.60
*/
private static final Logger logger = Logger.getLogger(SubTreeArticleIteratorBuilder.class);
/**
* <p>
* The AU associated with this builder.
* </p>
*
* @since 1.60
*/
protected ArchivalUnit au;
/**
* <p>
* The most recently created aspect.
* </p>
*
* @since 1.60
*/
protected BuildableSubTreeArticleIterator.Aspect currentAspect;
/**
* <p>
* The current buildable iterator.
* </p>
*
* @since 1.60
*/
protected BuildableSubTreeArticleIterator iterator;
/**
* <p>
* The subtree article iterator specification associated with this builder.
* </p>
*
* @since 1.60
*/
protected SubTreeArticleIterator.Spec spec;
/**
* <p>
* Makes a new builder.
* </p>
*
* @since 1.60
*/
public SubTreeArticleIteratorBuilder() {
// nothing
}
/**
* <p>
* Convenience method equivalent to calling
* {@link #SubTreeArticleIteratorBuilder()} then
* {@link #setArchivalUnit(ArchivalUnit)} with the given AU.
* </p>
*
* @param au
* An archival unit.
* @since 1.60
*/
public SubTreeArticleIteratorBuilder(ArchivalUnit au) {
this();
setArchivalUnit(au);
}
public void addAspect() {
if (iterator == null) {
throw new IllegalStateException("Cannot create an aspect until the AU and the spec are set");
}
currentAspect = iterator.new Aspect();
iterator.aspects.add(currentAspect);
}
/**
* <p>
* Convenience method equivalent to calling {@link #addAspect()}, then
* {@link #addPatterns(List)} with the given list of patterns, then
* {@link #addMatcherReplacements(List)} with the given list of matcher
* replacement strings, then {@link #addRoles(String...)} with the given
* sequence of roles.
* </p>
*
* @param patterns
* A list of patterns for the new aspect.
* @param matcherReplacements
* A list of matcher replacement strings for the new aspect.
* @param roles
* A sequence of roles for the new aspect.
* @since 1.60
*/
public void addAspect(List<Pattern> patterns, List<String> matcherReplacements, String... roles) {
addAspect();
addPatterns(patterns);
addMatcherReplacements(matcherReplacements);
addRoles(roles);
}
/**
* <p>
* Convenience method equivalent to calling {@link #addAspect()}, then
* {@link #addPatterns(List)} with the given list of patterns, then
* {@link #addMatcherReplacements(List)} with a singleton list containing the
* given matcher replacement string, then {@link #addRoles(String...)} with
* the given sequence of roles.
* </p>
*
* @param patterns
* A list of patterns for the new aspect.
* @param matcherReplacement
* A matcher replcamanet string for the new aspect.
* @param roles
* A sequence of roles for the new aspect.
* @since 1.60
*/
public void addAspect(List<Pattern> patterns, String matcherReplacement, String... roles) {
addAspect(patterns, Arrays.asList(matcherReplacement), roles);
}
/**
* <p>
* Convenience method equivalent to calling {@link #addAspect()}, then
* {@link #addMatcherReplacements(List)} with the given list of matcher
* replacement strings, then {@link #addRoles(String...)} with the given
* sequence of roles.
* </p>
*
* @param matcherReplacements
* A list of matcher replacement strings for the new aspect.
* @param roles
* A sequence of roles for the new aspect.
* @since 1.60
*/
public void addAspect(List<String> matcherReplacements, String... roles) {
addAspect();
addMatcherReplacements(matcherReplacements);
addRoles(roles);
}
/**
* <p>
* Convenience method equivalent to calling {@link #addAspect()}, then
* {@link #addPatterns(List)} with a singleton list containing the given
* pattern, then {@link #addMatcherReplacements(List)} with the given list of
* matcher replacement strings, then {@link #addRoles(String...)} with the
* given sequence of roles.
* </p>
*
* @param pattern
* A pattern for the new aspect.
* @param matcherReplacements
* A list of matcher replacement strings for the new aspect.
* @param roles
* A sequence of roles for the new aspect.
* @since 1.60
*/
public void addAspect(Pattern pattern, List<String> matcherReplacements, String... roles) {
addAspect(Arrays.asList(pattern), matcherReplacements, roles);
}
/**
* <p>
* Convenience method equivalent to calling {@link #addAspect()}, then
* {@link #addPatterns(List)} with a singleton list containing the given
* pattern, then {@link #addMatcherReplacements(List)} with a singleton list containing the given
* matcher replacement string, then {@link #addRoles(String...)} with the
* given sequence of roles.
* </p>
*
* @param pattern
* A pattern for the new aspect.
* @param matcherReplacement
* A matcher replacement string for the new aspect.
* @param roles
* A sequence of roles for the new aspect.
* @since 1.60
*/
public void addAspect(Pattern pattern, String matcherReplacement, String... roles) {
addAspect(Arrays.asList(pattern), Arrays.asList(matcherReplacement), roles);
}
/**
* <p>
* Convenience method equivalent to calling {@link #addAspect()}, then
* {@link #addMatcherReplacements(List)} with a singleton list containing the
* given matcher replacement string, then {@link #addRoles(String...)} with
* the given sequence of roles.
* </p>
*
* @param matcherReplacement
* A matcher replacement string for the new aspect.
* @param roles
* A sequence of roles for the new aspect.
* @since 1.60
*/
public void addAspect(String matcherReplacement, String... roles) {
addAspect(Arrays.asList(matcherReplacement), roles);
}
public void addMatcherReplacements(List<String> matcherReplacements) {
if (currentAspect == null) {
throw new IllegalStateException("No aspect has been created");
}
if (matcherReplacements.size() < 1) {
throw new IllegalArgumentException("Must define at least one matcher replacement");
}
currentAspect.matcherReplacements.addAll(matcherReplacements);
}
/**
* <p>
* Convenience method that calls {@link #addMatcherReplacements(List)} by
* turning the given sequence of matcher replacement strings into a list.
* </p>
*
* @param matcherReplacements
* A sequence of matcher replacement strings.
* @since 1.60
*/
public void addMatcherReplacements(String... matcherReplacements) {
addMatcherReplacements(Arrays.asList(matcherReplacements));
}
public void addPatterns(List<Pattern> patterns) {
if (currentAspect == null) {
throw new IllegalStateException("No aspect has been created");
}
if (patterns.size() < 1) {
throw new IllegalArgumentException("Must define at least one pattern");
}
currentAspect.patterns.addAll(patterns);
}
/**
* <p>
* Convenience method that calls {@link #addPatterns(List)} by turning the
* given sequence of patterns into a list.
* </p>
*
* @param patterns
* A sequence of patterns.
* @since 1.60
*/
public void addPatterns(Pattern... patterns) {
addPatterns(Arrays.asList(patterns));
}
public void addRoles(List<String> roles) {
if (currentAspect == null) {
throw new IllegalStateException("No aspect has been created");
}
if (roles.size() < 1) {
throw new IllegalArgumentException("Must define at least one role");
}
currentAspect.roles.addAll(roles);
}
/**
* <p>
* Convenience method that calls {@link #addRoles(List)} by turning the given
* sequence of roles into a list.
* </p>
*
* @param roles
* A sequence of roles.
* @since 1.60
*/
public void addRoles(String... roles) {
addRoles(Arrays.asList(roles));
}
/**
* <p>
* Returns the buildable subtree article iterator as it currently is.
* </p>
*
* @return The currently built subtree article iterator.
* @since 1.60
*/
public SubTreeArticleIterator getSubTreeArticleIterator() {
if (iterator == null) {
throw new IllegalStateException("Cannot create a subtree article iterator until the AU and the spec are set");
}
return iterator;
}
/**
* <p>
* Convenience method to obtain a new subtree article iterator specficiation
* object.
* </p>
*
* @return A new spec.
* @since 1.60
*/
public SubTreeArticleIterator.Spec newSpec() {
return new SubTreeArticleIterator.Spec();
}
public void setArchivalUnit(ArchivalUnit au) {
if (this.au != null) {
throw new IllegalStateException("AU is already set to " + au.getName());
}
this.au = au;
maybeMakeSubTreeArticleIterator();
}
public void setFullTextFromRoles(List<String> roles) {
if (iterator == null) {
throw new IllegalStateException("Cannot create a subtree article iterator until the AU and the spec are set");
}
if (roles.size() < 1) {
throw new IllegalArgumentException("Full text role order must contain at least one role");
}
iterator.rolesForFullText.addAll(roles);
}
/**
* <p>
* Convenience method that calls {@link #setFullTextFromRoles(List)} by
* turning the given sequence of roles into a list.
* </p>
*
* @param roles
* A sequence of roles.
* @since 1.60
*/
public void setFullTextFromRoles(String... roles) {
setFullTextFromRoles(Arrays.asList(roles));
}
/**
* @since 1.60
*/
public void setRoleFromOtherRoles(String newRole, List<String> otherRoles) {
if (iterator == null) {
throw new IllegalStateException("Cannot create a subtree article iterator until the AU and the spec are set");
}
if (otherRoles.size() < 1) {
throw new IllegalArgumentException("Other role order must contain at least one role");
}
iterator.rolesFromOtherRoles.put(newRole, otherRoles);
}
/**
* @since 1.60
*/
public void setRoleFromOtherRoles(String newRole, String... otherRoles) {
setRoleFromOtherRoles(newRole, Arrays.asList(otherRoles));
}
/**
* @since 1.60
*/
public void setSpec(MetadataTarget target,
List<String> rootTemplates,
String patternTemplate) {
setSpec(target, rootTemplates, patternTemplate, 0);
}
/**
* @since 1.60
*/
public void setSpec(MetadataTarget target,
List<String> rootTemplates,
String patternTemplate,
int patternTemplateFlags) {
SubTreeArticleIterator.Spec spec = newSpec();
spec.setTarget(target);
spec.setRootTemplates(rootTemplates);
spec.setPatternTemplate(patternTemplate, patternTemplateFlags);
setSpec(spec);
}
/**
* @since 1.60
*/
public void setSpec(MetadataTarget target,
String rootTemplate,
String patternTemplate) {
setSpec(target, Arrays.asList(rootTemplate), patternTemplate, 0);
}
/**
* @since 1.60
*/
public void setSpec(MetadataTarget target,
String rootTemplate,
String patternTemplate,
int patternTemplateFlags) {
setSpec(target, Arrays.asList(rootTemplate), patternTemplate, patternTemplateFlags);
}
/**
* @since 1.60
*/
public void setSpec(SubTreeArticleIterator.Spec spec) {
if (this.spec != null) {
throw new IllegalStateException("Spec is already set");
}
this.spec = spec;
maybeMakeSubTreeArticleIterator();
}
/**
* <p>
* Instantiates a {@link BuildableSubTreeArticleIterator}. If you override
* this class, you may also need to override
* {@link BuildableSubTreeArticleIterator} accordingly, as the two
* collaborate.
* </p>
*
* @return An instance of {@link BuildableSubTreeArticleIterator}.
* @since 1.63
*/
protected BuildableSubTreeArticleIterator instantiateBuildableIterator() {
return new BuildableSubTreeArticleIterator(au, spec);
}
/**
* @since 1.60
*/
protected void maybeMakeSubTreeArticleIterator() {
if (au != null && spec != null && iterator == null) {
this.iterator = instantiateBuildableIterator();
}
}
}
|
package org.spongepowered.api.block;
/**
* An enumeration of all possible {@link BlockType}s in vanilla minecraft.
*/
public class BlockTypes {
public static final BlockType AIR = null;
public static final BlockType STONE = null;
public static final BlockType GRASS = null;
public static final BlockType DIRT = null;
public static final BlockType COBBLESTONE = null;
public static final BlockType PLANKS = null;
public static final BlockType SAPLING = null;
public static final BlockType BEDROCK = null;
public static final BlockType FLOWING_WATER = null;
public static final BlockType WATER = null;
public static final BlockType FLOWING_LAVA = null;
public static final BlockType LAVA = null;
public static final BlockType SAND = null;
public static final BlockType GRAVEL = null;
public static final BlockType GOLD_ORE = null;
public static final BlockType IRON_ORE = null;
public static final BlockType COAL_ORE = null;
public static final BlockType LOG = null;
public static final BlockType LOG2 = null;
public static final BlockType LEAVES = null;
public static final BlockType LEAVES2 = null;
public static final BlockType SPONGE = null;
public static final BlockType GLASS = null;
public static final BlockType LAPIS_ORE = null;
public static final BlockType LAPIS_BLOCK = null;
public static final BlockType DISPENSER = null;
public static final BlockType SANDSTONE = null;
public static final BlockType NOTEBLOCK = null;
public static final BlockType BED = null;
public static final BlockType GOLDEN_RAIL = null;
public static final BlockType DETECTOR_RAIL = null;
public static final BlockType STICKY_PISTON = null;
public static final BlockType WEB = null;
public static final BlockType TALLGRASS = null;
public static final BlockType DEADBUSH = null;
public static final BlockType PISTON = null;
public static final BlockType PISTON_HEAD = null;
public static final BlockType WOOL = null;
public static final BlockType PISTON_EXTENSION = null;
public static final BlockType YELLOW_FLOWER = null;
public static final BlockType RED_FLOWER = null;
public static final BlockType BROWN_MUSHROOM = null;
public static final BlockType RED_MUSHROOM = null;
public static final BlockType GOLD_BLOCK = null;
public static final BlockType IRON_BLOCK = null;
public static final BlockType DOUBLE_STONE_SLAB = null;
public static final BlockType STONE_SLAB = null;
public static final BlockType BRICK_BLOCK = null;
public static final BlockType TNT = null;
public static final BlockType BOOKSHELF = null;
public static final BlockType MOSSY_COBBLESTONE = null;
public static final BlockType OBSIDIAN = null;
public static final BlockType TORCH = null;
public static final BlockType FIRE = null;
public static final BlockType MOB_SPAWNER = null;
public static final BlockType OAK_STAIRS = null;
public static final BlockType CHEST = null;
public static final BlockType REDSTONE_WIRE = null;
public static final BlockType DIAMOND_ORE = null;
public static final BlockType DIAMOND_BLOCK = null;
public static final BlockType CRAFTING_TABLE = null;
public static final BlockType WHEAT = null;
public static final BlockType FARMLAND = null;
public static final BlockType FURNACE = null;
public static final BlockType LIT_FURNACE = null;
public static final BlockType STANDING_SIGN = null;
public static final BlockType WOODEN_DOOR = null;
public static final BlockType SPRUCE_DOOR = null;
public static final BlockType BIRCH_DOOR = null;
public static final BlockType JUNGLE_DOOR = null;
public static final BlockType ACACIA_DOOR = null;
public static final BlockType DARK_OAK_DOOR = null;
public static final BlockType LADDER = null;
public static final BlockType RAIL = null;
public static final BlockType STONE_STAIRS = null;
public static final BlockType WALL_SIGN = null;
public static final BlockType LEVER = null;
public static final BlockType STONE_PRESSURE_PLATE = null;
public static final BlockType IRON_DOOR = null;
public static final BlockType WOODEN_PRESSURE_PLATE = null;
public static final BlockType REDSTONE_ORE = null;
public static final BlockType LIT_REDSTONE_ORE = null;
public static final BlockType UNLIT_REDSTONE_TORCH = null;
public static final BlockType REDSTONE_TORCH = null;
public static final BlockType STONE_BUTTON = null;
public static final BlockType SNOW_LAYER = null;
public static final BlockType ICE = null;
public static final BlockType SNOW = null;
public static final BlockType CACTUS = null;
public static final BlockType CLAY = null;
public static final BlockType REEDS = null;
public static final BlockType JUKEBOX = null;
public static final BlockType FENCE = null;
public static final BlockType SPRUCE_FENCE = null;
public static final BlockType BIRCH_FENCE = null;
public static final BlockType JUNGLE_FENCE = null;
public static final BlockType DARK_OAK_FENCE = null;
public static final BlockType ACACIA_FENCE = null;
public static final BlockType PUMPKIN = null;
public static final BlockType NETHERRACK = null;
public static final BlockType SOUL_SAND = null;
public static final BlockType GLOWSTONE = null;
public static final BlockType PORTAL = null;
public static final BlockType LIT_PUMPKIN = null;
public static final BlockType CAKE = null;
public static final BlockType UNPOWERED_REPEATER = null;
public static final BlockType POWERED_REPEATER = null;
public static final BlockType TRAPDOOR = null;
public static final BlockType MONSTER_EGG = null;
public static final BlockType STONEBRICK = null;
public static final BlockType BROWN_MUSHROOM_BLOCK = null;
public static final BlockType RED_MUSHROOM_BLOCK = null;
public static final BlockType IRON_BARS = null;
public static final BlockType GLASS_PANE = null;
public static final BlockType MELON_BLOCK = null;
public static final BlockType PUMPKIN_STEM = null;
public static final BlockType MELON_STEM = null;
public static final BlockType VINE = null;
public static final BlockType FENCE_GATE = null;
public static final BlockType SPRUCE_FENCE_GATE = null;
public static final BlockType BIRCH_FENCE_GATE = null;
public static final BlockType JUNGLE_FENCE_GATE = null;
public static final BlockType DARK_OAK_FENCE_GATE = null;
public static final BlockType ACACIA_FENCE_GATE = null;
public static final BlockType BRICK_STAIRS = null;
public static final BlockType STONE_BRICK_STAIRS = null;
public static final BlockType MYCELIUM = null;
public static final BlockType WATERLILY = null;
public static final BlockType NETHER_BRICK = null;
public static final BlockType NETHER_BRICK_FENCE = null;
public static final BlockType NETHER_BRICK_STAIRS = null;
public static final BlockType NETHER_WART = null;
public static final BlockType ENCHANTING_TABLE = null;
public static final BlockType BREWING_STAND = null;
public static final BlockType CAULDRON = null;
public static final BlockType END_PORTAL = null;
public static final BlockType END_PORTAL_FRAME = null;
public static final BlockType END_STONE = null;
public static final BlockType DRAGON_EGG = null;
public static final BlockType REDSTONE_LAMP = null;
public static final BlockType LIT_REDSTONE_LAMP = null;
public static final BlockType DOUBLE_WOODEN_SLAB = null;
public static final BlockType WOODEN_SLAB = null;
public static final BlockType COCOA = null;
public static final BlockType SANDSTONE_STAIRS = null;
public static final BlockType EMERALD_ORE = null;
public static final BlockType ENDER_CHEST = null;
public static final BlockType TRIPWIRE_HOOK = null;
public static final BlockType TRIPWIRE = null;
public static final BlockType EMERALD_BLOCK = null;
public static final BlockType SPRUCE_STAIRS = null;
public static final BlockType BIRCH_STAIRS = null;
public static final BlockType JUNGLE_STAIRS = null;
public static final BlockType COMMAND_BLOCK = null;
public static final BlockType BEACON = null;
public static final BlockType COBBLESTONE_WALL = null;
public static final BlockType FLOWER_POT = null;
public static final BlockType CARROTS = null;
public static final BlockType POTATOES = null;
public static final BlockType WOODEN_BUTTON = null;
public static final BlockType SKULL = null;
public static final BlockType ANVIL = null;
public static final BlockType TRAPPED_CHEST = null;
public static final BlockType LIGHT_WEIGHTED_PRESSURE_PLATE = null;
public static final BlockType HEAVY_WEIGHTED_PRESSURE_PLATE = null;
public static final BlockType UNPOWERED_COMPARATOR = null;
public static final BlockType POWERED_COMPARATOR = null;
public static final BlockType DAYLIGHT_DETECTOR = null;
public static final BlockType DAYLIGHT_DETECTOR_INVERTED = null;
public static final BlockType REDSTONE_BLOCK = null;
public static final BlockType QUARTZ_ORE = null;
public static final BlockType HOPPER = null;
public static final BlockType QUARTZ_BLOCK = null;
public static final BlockType QUARTZ_STAIRS = null;
public static final BlockType ACTIVATOR_RAIL = null;
public static final BlockType DROPPER = null;
public static final BlockType STAINED_HARDENED_CLAY = null;
public static final BlockType BARRIER = null;
public static final BlockType IRON_TRAPDOOR = null;
public static final BlockType HAY_BLOCK = null;
public static final BlockType CARPET = null;
public static final BlockType HARDENED_CLAY = null;
public static final BlockType COAL_BLOCK = null;
public static final BlockType PACKED_ICE = null;
public static final BlockType ACACIA_STAIRS = null;
public static final BlockType DARK_OAK_STAIRS = null;
public static final BlockType SLIME = null;
public static final BlockType DOUBLE_PLANT = null;
public static final BlockType STAINED_GLASS = null;
public static final BlockType STAINED_GLASS_PANE = null;
public static final BlockType PRISMARINE = null;
public static final BlockType SEA_LANTERN = null;
public static final BlockType STANDING_BANNER = null;
public static final BlockType WALL_BANNER = null;
public static final BlockType RED_SANDSTONE = null;
public static final BlockType RED_SANDSTONE_STAIRS = null;
public static final BlockType DOUBLE_STONE_SLAB2 = null;
public static final BlockType STONE_SLAB2 = null;
}
|
package io.spine.server.delivery;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.ImmutableList;
import com.google.protobuf.Duration;
import com.google.protobuf.util.Durations;
import io.spine.annotation.Internal;
import io.spine.logging.Logging;
import io.spine.server.BoundedContext;
import io.spine.server.NodeId;
import io.spine.server.ServerEnvironment;
import io.spine.server.bus.MulticastDispatchListener;
import io.spine.server.delivery.memory.InMemoryShardedWorkRegistry;
import io.spine.server.projection.ProjectionRepository;
import io.spine.string.Stringifiers;
import io.spine.type.TypeUrl;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Stream;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.flogger.LazyArgs.lazy;
import static java.util.Collections.synchronizedList;
/**
* Delivers the messages to the entities.
*
* <p>Splits the incoming messages into shards and allows to deliver the
* messages to their destinations on a per-shard basis. Guarantees that one and only one
* application server node serves the messages from the given shard at a time, thus preventing
* any concurrent modifications of entity state.
*
* <p>Delegates the message dispatching and low-level handling of message duplicates to
* {@link #newInbox(TypeUrl) Inbox}es of each target entity. The respective {@code Inbox} instances
* should be created in each of {@code Entity} repositories.
*
* <h1>Configuration</h1>
*
* <h2>Delivery Strategy</h2>
*
* <p>By default, a shard is assigned according to the identifier of the target entity. The
* messages heading to a single entity will always reside in a single shard. However,
* the framework users may {@linkplain DeliveryBuilder#setStrategy(DeliveryStrategy) customize}
* this behavior.
*
* <p>The typical customization would be to specify the same shard index for the related targets.
* E.g. if there is an {@code OrderAggregate}, {@code OrderItemAggregate}
* and {@code OrderItemProjection}, they could share the same shard index. In this way the messages
* headed to these entities will be dispatched and processed together. In turn, that will reduce
* the eventual consistency lag between {@code C} side (i.e. aggregate state updates)
* and {@code Q} side (i.e. the respective updates in projections).
*
* <h2>Deduplication</h2>
*
* <p>As long as the underlying storage and transport mechanisms are restricted by the CAP theorem,
* there may be duplicates in the messages written, read or dispatched. The {@code Delivery}
* responds to it by storing some of the already delivered messages for longer and using them as
* a source for deduplication.
*
* <p>{@linkplain DeliveryBuilder#setDeduplicationWindow(Duration) Provides} the time-based
* deduplication capabilities to eliminate the messages, which may have been already delivered
* to their targets. The duplicates will be detected among the messages, which are not older, than
* {@code now - [deduplication window]}.
*
* <h2>Customizing {@code InboxStorage}</h2>
*
* <p>{@code Delivery} is responsible for providing the {@link InboxStorage} for every inbox
* registered. Framework users may {@linkplain DeliveryBuilder#setInboxStorage(InboxStorage)
* configure} the storage, taking into account that it is typically multi-tenant. By default,
* the {@code InboxStorage} for the delivery is provided by the environment-specific
* {@linkplain ServerEnvironment#storageFactory() storage factory} and is multi-tenant.
*
* <h2>Catch-up</h2>
*
* <p>In addition to delivering the messages sent in a real-time, {@code Delivery} dispatches
* the historical events sent to the catching-up projections. These events are dispatched through
* the same shards as the live messages. A special {@link CatchUpStation} is responsible for
* handling this use-case. See more on that in the respective section.
*
* <p>To control how many historical events are read and put into shards, the end-users may
* configure the {@linkplain DeliveryBuilder#setCatchUpPageSize(int) maximum number of messages}
* read from the history at a time. This is helpful to balance the per-shard throughput, so
* that the live messages are still dispatched through the same shards in a reasonable time.
*
* <p>The statuses of the ongoing catch-up processes are stored in a dedicated
* {@link CatchUpStorage}. The {@code DeliveryBuilder} {@linkplain
* DeliveryBuilder#setCatchUpStorage(CatchUpStorage) exposes an API} for the customization of this
* storage.
*
* <h2>Observers</h2>
*
* <p>Once a message is written to the {@code Inbox},
* the {@linkplain Delivery#subscribe(ShardObserver) pre-configured shard observers} are
* {@linkplain ShardObserver#onMessage(InboxMessage) notified}. In this way any third-party
* environment planners, load balancers, and schedulers may plug into the delivery and perform
* various routines to enable the further processing of the sharded messages. In a distributed
* environment a message queue may be used to notify the node cluster of a shard that has some
* messages pending for the delivery.
*
* <h2>Work registry</h2>
*
* <p>Once an application node picks the shard to deliver the messages from it, it registers itself
* in a {@link ShardedWorkRegistry}. It serves as a list of locks-per-shard that only allows
* to pick a shard to a single node at a time. The framework users may configure the implementation
* of the registry by calling {@link DeliveryBuilder#setWorkRegistry(ShardedWorkRegistry)}.
*
* <h2>Dispatching messages</h2>
*
* <h3>Delivery stages</h3>
*
* <p>The delivery process for each shard index is split into {@link DeliveryStage}s. In scope of
* each stage, a certain number of messages is read from the respective shard of the {@code Inbox}.
* The messages are grouped per-target and delivered in batches if possible. The maximum
* number of the messages within a {@code DeliveryStage} can be
* {@linkplain DeliveryBuilder#setPageSize(int) configured}.
*
* <p>After each {@code DeliveryStage} it is possible to stop the delivery by
* {@link DeliveryBuilder#setMonitor(DeliveryMonitor) supplying} a custom delivery monitor.
* Please refer to the {@link DeliveryMonitor documentation} for the details.
*
* <h3>Conveyor and stations</h3>
*
* <p>In a scope of {@code DeliveryStage} the page of the {@code InboxMessage}s is placed
* to the {@link Conveyor} responsible for tracking the status of each message.
* The conveyor is run through the pipeline of stations, each modifying the state of the messages.
* At the end of the pipeline, the changed made to the messages are committed to the underlying
* {@code InboxStorage} in a bulk. Such an approach allows to minimize the number of the requests
* sent to the storage.
*
* <p>As long as the new {@code DeliveryStage} is started, the new instance of the {@code Conveyor}
* is created.
*
* <p>Below is the list of the conveyor stations in the pipeline.
*
* <b>1. Catch-up station</b>
*
* <p>This station is responsible for dispatching the historical events in
* {@link InboxMessageStatus#TO_CATCH_UP TO_CATCH_UP} status to the respective targets. Also,
* while the target entity is under a catch-up, all the live messages headed to it are ignored.
* Once the catch-up is completed, this station handles the transition period, in which the last
* batch of the historical events and live messages are dispatched together.
* See {@link CatchUpStation} for more details.
*
* <b>2. Live delivery station</b>
*
* <p>This station is responsible for dispatching the messages sent in a real-time. It ignores
* the messages in {@link InboxMessageStatus#TO_CATCH_UP TO_CATCH_UP} status. Another responsibility
* of this station is to set for how long the delivered messages should be kept according to the
* {@linkplain DeliveryBuilder#setDeduplicationWindow(Duration) deduplication window} settings.
* See {@link LiveDeliveryStation} for more details.
*
* <b>3. Cleanup station</b>
*
* <p>This station removes the messages which are already delivered and are no longer needed for the
* deduplication. See {@link CleanupStation} for the description.
*
* <b>Deduplication</b>
*
* <p>During the dispatching, {@code Conveyor} keeps track of the delivered messages. The stations
* performing the actual message dispatching rely onto this knowledge and deduplicate
* the messages prior to calling the target's endpoint.
*
* <p>Additionally, the {@code Delivery} provides a {@linkplain DeliveredMessages cache of recently
* delivered messages}. Each instance of the {@code Conveyor} has an access to it and uses it
* in deduplication procedures.
*
* <h2>Local environment</h2>
*
* <p>By default, the delivery is configured to {@linkplain Delivery#local() run locally}. It
* uses {@linkplain LocalDispatchingObserver see-and-dispatch observer}, which delivers the
* messages from the observed shard once a message is passed to its
* {@link LocalDispatchingObserver#onMessage(InboxMessage) onMessage(InboxMessage)} method. This
* process is synchronous.
*
* <p>To deal with the multi-threaded access in a local mode,
* an {@linkplain InMemoryShardedWorkRegistry} is used. It operates on top of the
* {@code synchronized} in-memory data structures and prevents several threads from picking up the
* same shard.
*
* <h2>Shard maintenance</h2>
*
* <p>To perform the maintenance procedures, the {@code Delivery} requires all the {@code
* BoundedContext}s to register themselves in it. Upon this registration, a special
* {@link ShardMaintenanceProcess} is registered as an event dispatcher in a passed
* {@code BoundedContext}. Such a registration is performed automatically when the context is
* {@linkplain io.spine.server.BoundedContextBuilder#build() built}.
*/
@SuppressWarnings({"OverlyCoupledClass", "ClassWithTooManyMethods"}) // It's fine for a centerpiece.
public final class Delivery implements Logging {
/**
* The width of the deduplication window in a local environment.
*
* <p>Selected to be pretty big to avoid dispatching duplicates to any entities.
*/
private static final Duration LOCAL_DEDUPLICATION_WINDOW = Durations.fromSeconds(30);
/**
* The strategy of assigning a shard index for a message that is delivered to a particular
* target.
*/
private final DeliveryStrategy strategy;
/**
* For how long we keep the previously delivered message per-target to ensure the new messages
* aren't duplicates.
*/
private final Duration deduplicationWindow;
/**
* The delivery strategies to use for the postponed message dispatching.
*
* <p>Stored per {@link TypeUrl}, which is a state type of a target {@code Entity}.
*
* <p>Once messages arrive for the postponed processing, a corresponding delivery is selected
* according to the message contents. The {@code TypeUrl} in this map is stored
* as {@code String} to avoid an extra boxing into {@code TypeUrl} of the value,
* which resides as a Protobuf {@code string} inside an incoming message.
*/
private final InboxDeliveries deliveries;
/**
* The observers that are notified when a message is written into a particular shard.
*/
private final List<ShardObserver> shardObservers;
/**
* The registry keeping track of which shards are processed by which application nodes.
*/
private final ShardedWorkRegistry workRegistry;
/**
* The storage of messages to deliver.
*/
private final InboxStorage inboxStorage;
/**
* The storage of ongoing catch-up process states.
*/
private final CatchUpStorage catchUpStorage;
/**
* How many messages to read per query when recalling the historical events from the event log
* during the catch-up.
*/
private final int catchUpPageSize;
/**
* The monitor of delivery stages.
*/
private final DeliveryMonitor monitor;
/**
* The cache of the locally delivered messages.
*/
private final DeliveredMessages deliveredMessages;
/**
* The maximum amount of messages to deliver within a {@link DeliveryStage}.
*/
private final int pageSize;
/**
* The listener of the dispatching operations inside the {@link io.spine.server.bus.MulticastBus
* MulticastBus}es.
*
* <p>Responsible for sending the notifications to the shard observers.
*/
private final DeliveryDispatchListener dispatchListener =
new DeliveryDispatchListener(this::onNewMessage);
Delivery(DeliveryBuilder builder) {
this.strategy = builder.getStrategy();
this.workRegistry = builder.getWorkRegistry();
this.deduplicationWindow = builder.getDeduplicationWindow();
this.inboxStorage = builder.getInboxStorage();
this.catchUpStorage = builder.getCatchUpStorage();
this.catchUpPageSize = builder.getCatchUpPageSize();
this.monitor = builder.getMonitor();
this.pageSize = builder.getPageSize();
this.deliveries = new InboxDeliveries();
this.shardObservers = synchronizedList(new ArrayList<>());
this.deliveredMessages = new DeliveredMessages();
}
/**
* Creates an instance of new {@code Builder} of {@code Delivery}.
*/
public static DeliveryBuilder newBuilder() {
return new DeliveryBuilder();
}
/**
* Creates a new instance of {@code Delivery} suitable for local and development environment.
*
* <p>In this setup, the {@code InboxMessage}s are delivered to their targets synchronously.
*
* <p>Uses a {@linkplain UniformAcrossAllShards#singleShard() single-shard} splitting.
*
* <p>To construct a {@code Delivery} instance, a {@code StorageFactory} is needed.
* If it was not configured in the {@code ServerEnvironment}, uses a new {@code
* InMemoryStorageFactory}.
*
* @see #localAsync() to create an asynchronous version of the local {@code Delivery}
*/
public static Delivery local() {
return localWithShardsAndWindow(1, LOCAL_DEDUPLICATION_WINDOW);
}
/**
* Creates a new instance of {@code Delivery} for local and development environment.
*
* <p>The {@code InboxMessage}s are delivered to their targets asynchronously.
*
* <p>The returned instance of {@code Delivery} is configured to use
* {@linkplain UniformAcrossAllShards#singleShard() the single shard}.
*
* <p>To construct a {@code Delivery} instance, a {@code StorageFactory} is needed.
* If it was not configured in the {@code ServerEnvironment}, a new {@code
* InMemoryStorageFactory} used.
*
* @see #local() to create a syncrhonous version of the local {@code Delivery}
*/
public static Delivery localAsync() {
Delivery delivery = newBuilder()
.setStrategy(UniformAcrossAllShards.singleShard())
.build();
delivery.subscribe(new LocalDispatchingObserver(true));
return delivery;
}
/**
* Creates a new instance of {@code Delivery} suitable for local and development environment
* with the given number of shards.
*/
@VisibleForTesting
static Delivery localWithShardsAndWindow(int shardCount, Duration deduplicationWindow) {
checkArgument(shardCount > 0, "Shard count must be positive");
checkNotNull(deduplicationWindow);
DeliveryStrategy strategy = UniformAcrossAllShards.forNumber(shardCount);
return localWithStrategyAndWindow(strategy, deduplicationWindow);
}
@VisibleForTesting
static Delivery localWithStrategyAndWindow(DeliveryStrategy strategy,
Duration deduplicationWindow) {
Delivery delivery =
newBuilder().setDeduplicationWindow(deduplicationWindow)
.setStrategy(strategy)
.build();
delivery.subscribe(new LocalDispatchingObserver());
return delivery;
}
/**
* Delivers the messages put into the shard with the passed index to their targets.
*
* <p>At a given moment of time, exactly one application node may serve messages from
* a particular shard. Therefore, in scope of this delivery, an approach based on pessimistic
* locking per-{@code ShardIndex} is applied.
*
* <p>In case the given shard is already processed by some node, this method does nothing and
* returns {@code Optional.empty()}.
*
* <p>The content of the shard is read and delivered on page-by-page basis. The runtime
* exceptions occurring while a page is being delivered are accumulated and then the first
* exception is rethrown, if any.
*
* <p>After all the pages are read, the delivery process is launched again for the same shard.
* It is required in order to handle the messages, that may have been put to the same shard
* as an outcome of the first-wave messages.
*
* <p>Once the shard has no more messages to deliver, the delivery process ends, releasing
* the lock for the respective {@code ShardIndex}.
*
* @param index
* the shard index to deliver the messages from.
* @return the statistics on the performed delivery, or {@code Optional.empty()} if there
* were no delivery performed
*/
public Optional<DeliveryStats> deliverMessagesFrom(ShardIndex index) {
NodeId currentNode = ServerEnvironment.instance()
.nodeId();
Optional<ShardProcessingSession> picked = workRegistry.pickUp(index, currentNode);
if (!picked.isPresent()) {
return Optional.empty();
}
ShardProcessingSession session = picked.get();
monitor.onDeliveryStarted(index);
RunResult runResult;
int totalDelivered = 0;
try {
do {
runResult = runDelivery(session);
totalDelivered += runResult.deliveredCount();
} while (runResult.shouldRunAgain());
} finally {
session.complete();
}
DeliveryStats stats = new DeliveryStats(index, totalDelivered);
monitor.onDeliveryCompleted(stats);
Optional<InboxMessage> lateMessage = inboxStorage.newestMessageToDeliver(index);
lateMessage.ifPresent(this::onNewMessage);
return Optional.of(stats);
}
/**
* Runs the delivery for the shard, which session is passed.
*
* <p>The messages are read page-by-page according to the {@link #pageSize page size} setting.
*
* <p>After delivering each page of messages, a {@code DeliveryStage} is produced.
* The configured {@link #monitor DeliveryMonitor} may stop the execution according to
* the monitored {@code DeliveryStage}.
*
* @return the results of the run
*/
private RunResult runDelivery(ShardProcessingSession session) {
ShardIndex index = session.shardIndex();
Page<InboxMessage> startingPage = inboxStorage.readAll(index, pageSize);
Optional<Page<InboxMessage>> maybePage = Optional.of(startingPage);
boolean continueAllowed = true;
List<DeliveryStage> stages = new ArrayList<>();
while (continueAllowed && maybePage.isPresent()) {
Page<InboxMessage> currentPage = maybePage.get();
ImmutableList<InboxMessage> messages = currentPage.contents();
if (!messages.isEmpty()) {
DeliveryAction action = new GroupByTargetAndDeliver(deliveries);
Conveyor conveyor = new Conveyor(messages, deliveredMessages);
Iterable<CatchUp> catchUpJobs = catchUpStorage.readAll();
List<Station> stations = conveyorStationsFor(catchUpJobs, action);
DeliveryStage stage = launch(conveyor, stations, index);
continueAllowed = monitorTellsToContinue(stage);
stages.add(stage);
}
if (continueAllowed) {
maybePage = currentPage.next();
}
}
int totalMessagesDelivered = stages.stream()
.map(DeliveryStage::getMessagesDelivered)
.reduce(0, Integer::sum);
return new RunResult(totalMessagesDelivered, !continueAllowed);
}
/**
* Launches the conveyor, running it through the passed stations and processing the messages
* in the specified shard.
*
* <p>Once all the stations complete their routine, this {@code DeliveryStage} is considered
* completed.
*
* @return the delivery stage results
*/
private DeliveryStage launch(Conveyor conveyor, Iterable<Station> stations, ShardIndex index) {
int deliveredInBatch = 0;
for (Station station : stations) {
Station.Result result = station.process(conveyor);
result.errors()
.throwIfAny();
deliveredInBatch += result.deliveredCount();
}
notifyOfDuplicatesIn(conveyor);
conveyor.flushTo(inboxStorage);
return newStage(index, deliveredInBatch);
}
private ImmutableList<Station> conveyorStationsFor(Iterable<CatchUp> catchUpJobs,
DeliveryAction action) {
return ImmutableList.of(
new CatchUpStation(action, catchUpJobs),
new LiveDeliveryStation(action, deduplicationWindow),
new CleanupStation()
);
}
private void notifyOfDuplicatesIn(Conveyor conveyor) {
Stream<InboxMessage> streamOfDuplicates = conveyor.recentDuplicates();
streamOfDuplicates.forEach((message) -> {
ShardedMessageDelivery<InboxMessage> delivery = deliveries.get(message);
delivery.onDuplicate(message);
});
}
private static DeliveryStage newStage(ShardIndex index, int deliveredInBatch) {
return DeliveryStage
.newBuilder()
.setIndex(index)
.setMessagesDelivered(deliveredInBatch)
.vBuild();
}
private boolean monitorTellsToContinue(DeliveryStage stage) {
return monitor.shouldContinueAfter(stage);
}
/**
* Notifies that the contents of the shard with the given index have been updated
* with some message.
*
* @param message
* a message that was written into the shard
*/
@SuppressWarnings("OverlyBroadCatchBlock")
private void onNewMessage(InboxMessage message) {
for (ShardObserver observer : shardObservers) {
try {
observer.onMessage(message);
} catch (Exception e) {
_error().withCause(e)
.log("Error calling a shard observer with the message %s.",
lazy(() -> Stringifiers.toString(message)));
}
}
}
/**
* Creates an instance of {@link Inbox.Builder} for the given entity type.
*
* @param entityType
* the type of the entity, to which the inbox will belong
* @param <I>
* the type if entity identifiers
* @return the builder for the {@code Inbox}
*/
public <I> Inbox.Builder<I> newInbox(TypeUrl entityType) {
return Inbox.newBuilder(entityType, inboxWriter());
}
/**
* Creates a new instance of the builder for {@link CatchUpProcess}.
*
* @param repo
* projection repository for which the catch-up process will be created
* @param <I>
* the type of identifiers of entities managed by the projection repository
* @return new builder for the {@code CatchUpProcess}
*/
public <I> CatchUpProcessBuilder<I> newCatchUpProcess(ProjectionRepository<I, ?, ?> repo) {
CatchUpProcessBuilder<I> builder = CatchUpProcess.newBuilder(repo);
return builder.setStorage(catchUpStorage)
.setPageSize(catchUpPageSize);
}
/**
* Registers the internal {@code Delivery} message dispatchers
* in the given {@code BoundedContext}.
*
* <p>The registration of the dispatchers allows to handle the {@code Delivery}-specific events.
*
* @param context Bounded Context in which the message dispatchers should be registered
*/
@Internal
public void registerDispatchersIn(BoundedContext context) {
context.internalAccess()
.registerEventDispatcher(new ShardMaintenanceProcess(this));
}
/**
* Returns a listener of the dispatching operations occurring in the
* {@link io.spine.server.bus.MulticastBus MulticastBus}es.
*/
@Internal
public MulticastDispatchListener dispatchListener() {
return dispatchListener;
}
/**
* Subscribes to the updates of shard contents.
*
* <p>The passed observer will be notified that the contents of a shard with a particular index
* were changed.
*
* @param observer
* an observer to notify of updates.
*/
public void subscribe(ShardObserver observer) {
shardObservers.add(observer);
}
/**
* Registers the passed {@code Inbox} and puts its {@linkplain Inbox#delivery() delivery
* callbacks} into the list of those to be called, when the previously sharded messages
* are dispatched to their targets.
*/
void register(Inbox<?> inbox) {
deliveries.register(inbox);
}
/**
* Determines the shard index for the message, judging on the identifier of the entity,
* to which this message is dispatched.
*
* @param entityId
* the ID of the entity, to which the message is heading
* @param entityStateType
* the state type of the entity, to which the message is heading
* @return the index of the shard for the message
*/
ShardIndex whichShardFor(Object entityId, TypeUrl entityStateType) {
return strategy.determineIndex(entityId, entityStateType);
}
/**
* Unregisters the given {@code Inbox} and removes all the {@linkplain Inbox#delivery()
* delivery callbacks} previously registered by this {@code Inbox}.
*/
void unregister(Inbox<?> inbox) {
deliveries.unregister(inbox);
}
@VisibleForTesting
InboxStorage inboxStorage() {
return inboxStorage;
}
int shardCount() {
return strategy.shardCount();
}
@VisibleForTesting
ImmutableList<ShardObserver> shardObservers() {
return ImmutableList.copyOf(shardObservers);
}
private InboxWriter inboxWriter() {
return new NotifyingWriter(inboxStorage) {
@Override
protected void onShardUpdated(InboxMessage message) {
Delivery.this.dispatchListener.notifyOf(message);
}
};
}
}
|
package org.objectweb.proactive.core.rmi;
import org.apache.log4j.Logger;
public class RegistryHelper {
protected static Logger logger = Logger.getLogger(RegistryHelper.class.getName());
protected final static int DEFAULT_REGISTRY_PORT = 1099;
/**
* settings of the registry
*/
protected int registryPortNumber = DEFAULT_REGISTRY_PORT;
protected boolean shouldCreateRegistry = true;
protected boolean registryChecked;
public RegistryHelper() {
String port = System.getProperty("proactive.rmi.port");
if (port != null) {
setRegistryPortNumber(new Integer(port).intValue());
}
}
public int getRegistryPortNumber() {
return registryPortNumber;
}
public void setRegistryPortNumber(int v) {
registryPortNumber = v;
registryChecked = false;
}
public boolean shouldCreateRegistry() {
return shouldCreateRegistry;
}
public void setShouldCreateRegistry(boolean v) {
shouldCreateRegistry = v;
}
public synchronized void initializeRegistry()
throws java.rmi.RemoteException {
try {
if (!shouldCreateRegistry) {
return; // don't bother
}
if (registryChecked) {
return; // already done for this VM
}
getOrCreateRegistry(registryPortNumber);
registryChecked = true;
} catch (Exception e) {
e.printStackTrace();
}
}
private static java.rmi.registry.Registry createRegistry(int port)
throws java.rmi.RemoteException {
return java.rmi.registry.LocateRegistry.createRegistry(port);
}
private static java.rmi.registry.Registry detectRegistry(int port) {
java.rmi.registry.Registry registry = null;
try {
// whether an effective registry exists or not we should get a reference
registry = java.rmi.registry.LocateRegistry.getRegistry(port);
if (registry == null) {
return null;
}
// doing a lookup should produce ConnectException if registry doesn't exist
// and no exception or NotBoundException if the registry does exist.
java.rmi.Remote r = registry.lookup("blah!");
logger.info("Detected an existing RMI Registry on port " + port);
return registry;
} catch (java.rmi.NotBoundException e) {
logger.info("Detected an existing RMI Registry on port " + port);
return registry;
} catch (java.rmi.RemoteException e) {
return null;
}
}
private static java.rmi.registry.Registry getOrCreateRegistry(int port)
throws java.rmi.RemoteException {
java.rmi.registry.Registry registry = detectRegistry(port);
if (registry != null) {
return registry;
}
// no registry created
try {
registry = createRegistry(port);
logger.info("Created a new registry on port " + port);
return registry;
} catch (java.rmi.RemoteException e) {
// try to find the rmi registry one more time
registry = detectRegistry(port);
if (registry != null) {
return registry;
}
logger.error("Cannot detect an existing RMI Registry on port " +
port + " nor create one e=" + e);
throw e;
}
}
}
|
package org.spout.physics.engine;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import gnu.trove.map.TObjectIntMap;
import gnu.trove.map.hash.TObjectIntHashMap;
import org.spout.physics.ReactDefaults;
import org.spout.physics.ReactDefaults.ContactsPositionCorrectionTechnique;
import org.spout.physics.Utilities.IntPair;
import org.spout.physics.body.RigidBody;
import org.spout.physics.collision.BroadPhasePair;
import org.spout.physics.collision.shape.CollisionShape;
import org.spout.physics.constraint.BallAndSocketJoint;
import org.spout.physics.constraint.BallAndSocketJoint.BallAndSocketJointInfo;
import org.spout.physics.constraint.Constraint;
import org.spout.physics.constraint.Constraint.ConstraintInfo;
import org.spout.physics.constraint.ConstraintSolver;
import org.spout.physics.constraint.ContactPoint;
import org.spout.physics.constraint.ContactPoint.ContactPointInfo;
import org.spout.physics.constraint.FixedJoint;
import org.spout.physics.constraint.FixedJoint.FixedJointInfo;
import org.spout.physics.constraint.HingeJoint;
import org.spout.physics.constraint.HingeJoint.HingeJointInfo;
import org.spout.physics.constraint.SliderJoint;
import org.spout.physics.constraint.SliderJoint.SliderJointInfo;
import org.spout.physics.math.Matrix3x3;
import org.spout.physics.math.Quaternion;
import org.spout.physics.math.Transform;
import org.spout.physics.math.Vector3;
/**
* This class represents a dynamics world. This class inherits from the CollisionWorld class. In a dynamics world bodies can collide and their movements are simulated using the laws of physics.
*/
public class DynamicsWorld extends CollisionWorld {
private final Timer mTimer;
private final ContactSolver mContactSolver;
private final ConstraintSolver mConstraintSolver;
private int mNbVelocitySolverIterations;
private int mNbPositionSolverIterations;
private boolean mIsDeactivationActive;
private final Set<RigidBody> mRigidBodies = new HashSet<>();
private final List<ContactManifold> mContactManifolds = new ArrayList<>();
private final Set<Constraint> mJoints = new HashSet<>();
private final Vector3 mGravity;
private boolean mIsGravityOn = true;
private final ArrayList<Vector3> mConstrainedLinearVelocities = new ArrayList<>();
private final ArrayList<Vector3> mConstrainedAngularVelocities = new ArrayList<>();
private final ArrayList<Vector3> mConstrainedPositions = new ArrayList<>();
private final ArrayList<Quaternion> mConstrainedOrientations = new ArrayList<>();
private final TObjectIntMap<RigidBody> mMapBodyToConstrainedVelocityIndex = new TObjectIntHashMap<>();
private boolean isTicking = false;
// Tick cache
private final Set<RigidBody> mRigidBodiesToAddCache = new HashSet<>();
private final Set<RigidBody> mRigidBodiesToDeleteCache = new HashSet<>();
/**
* Constructs a new dynamics world from the gravity and the default time step.
*
* @param gravity The gravity
*/
public DynamicsWorld(Vector3 gravity) {
this(gravity, ReactDefaults.DEFAULT_TIMESTEP);
}
/**
* Constructs a new dynamics world from the gravity and the time step.
*
* @param gravity The gravity
* @param timeStep The time step
*/
public DynamicsWorld(Vector3 gravity, float timeStep) {
mTimer = new Timer(timeStep);
mGravity = gravity;
mContactSolver = new ContactSolver(mContactManifolds, mConstrainedLinearVelocities, mConstrainedAngularVelocities, mMapBodyToConstrainedVelocityIndex);
mConstraintSolver = new ConstraintSolver(mJoints, mConstrainedLinearVelocities, mConstrainedAngularVelocities, mConstrainedPositions, mConstrainedOrientations,
mMapBodyToConstrainedVelocityIndex);
mNbVelocitySolverIterations = ReactDefaults.DEFAULT_VELOCITY_SOLVER_NB_ITERATIONS;
mNbPositionSolverIterations = ReactDefaults.DEFAULT_POSITION_SOLVER_NB_ITERATIONS;
mIsDeactivationActive = ReactDefaults.DEACTIVATION_ENABLED;
}
/**
* Starts the physics simulation.
*/
public void start() {
mTimer.start();
}
/**
* Stops the physics simulation.
*/
public void stop() {
mTimer.stop();
}
/**
* Sets the number of iterations for the velocity constraint solver.
*
* @param nbIterations The number of iterations to do
*/
public void setNbIterationsVelocitySolver(int nbIterations) {
mNbVelocitySolverIterations = nbIterations;
}
/**
* Sets the number of iterations for the position constraint solver.
*
* @param nbIterations The number of iterations to do
*/
public void setNbIterationsPositionSolver(int nbIterations) {
mNbPositionSolverIterations = nbIterations;
}
/**
* Sets the position correction technique used for contacts.
*
* @param technique The technique to use
*/
public void setContactsPositionCorrectionTechnique(ContactsPositionCorrectionTechnique technique) {
if (technique == ContactsPositionCorrectionTechnique.BAUMGARTE_CONTACTS) {
mContactSolver.setIsSplitImpulseActive(false);
} else {
mContactSolver.setIsSplitImpulseActive(true);
}
}
/**
* Activates or deactivates the solving of friction constraints at the center of the contact manifold instead of solving them at each contact point.
*
* @param isActive Whether or not to solve the friction constraint at the center of the manifold
*/
public void setSolveFrictionAtContactManifoldCenterActive(boolean isActive) {
mContactSolver.setSolveFrictionAtContactManifoldCenterActive(isActive);
}
/**
* Returns the gravity vector for the world.
*
* @return The gravity vector
*/
public Vector3 getGravity() {
return mGravity;
}
/**
* Returns true if the gravity is on.
*
* @return Whether or not the gravity is on
*/
public boolean isGravityOn() {
return mIsGravityOn;
}
/**
* Sets the gravity on if true, off is false.
*
* @param gravityOn True to turn on the gravity, false to turn it off
*/
public void setGravityOn(boolean gravityOn) {
mIsGravityOn = gravityOn;
}
/**
* Gets the number of rigid bodies in the world.
*
* @return The number of rigid bodies in the world
*/
public int getNbRigidBodies() {
return mRigidBodies.size();
}
/**
* Returns the number of joints in the world.
*
* @return The number of joints
*/
public int getNbJoints() {
return mJoints.size();
}
/**
* Gets the set of bodies of the physics world.
*
* @return The rigid bodies
*/
public Set<RigidBody> getRigidBodies() {
return mRigidBodies;
}
/**
* Returns a reference to the contact manifolds of the world.
*
* @return The contact manifolds
*/
public List<ContactManifold> getContactManifolds() {
return mContactManifolds;
}
/**
* Gets the number of contact manifolds in the world.
*
* @return The number of contact manifolds in the world
*/
public int getNbContactManifolds() {
return mContactManifolds.size();
}
/**
* Returns the current physics time (in seconds)
*
* @return The current physics time
*/
public double getPhysicsTime() {
return mTimer.getPhysicsTime();
}
/**
* Updates the physics simulation. The elapsed time is determined by the timer. A step is only actually taken if enough time has passed. If a lot of time has passed, more than twice the time step,
* multiple steps will be taken, to catch up.
*/
public void update() {
if (!mTimer.isRunning()) {
throw new IllegalStateException("timer must be running");
}
mTimer.update();
isTicking = true;
while (mTimer.isPossibleToTakeStep()) {
mContactManifolds.clear();
mCollisionDetection.computeCollisionDetection();
integrateRigidBodiesVelocities();
resetBodiesMovementVariable();
mTimer.nextStep();
solveContactsAndConstraints();
integrateRigidBodiesPositions();
solvePositionCorrection();
updateRigidBodiesAABB();
mContactSolver.cleanup();
cleanupConstrainedVelocitiesArray();
}
isTicking = false;
setInterpolationFactorToAllBodies();
disperseCache();
}
// Resets the boolean movement variable for each body.
private void resetBodiesMovementVariable() {
for (RigidBody rigidBody : mRigidBodies) {
rigidBody.setHasMoved(false);
}
}
// Integrates the position and orientation of the rigid bodies using the provided time delta.
// The positions and orientations of the bodies are integrated using the symplectic Euler time stepping scheme.
private void integrateRigidBodiesPositions() {
final float dt = (float) mTimer.getTimeStep();
for (RigidBody rigidBody : mRigidBodies) {
if (rigidBody.getIsMotionEnabled()) {
final int indexArray = mMapBodyToConstrainedVelocityIndex.get(rigidBody);
final Vector3 newLinVelocity = mConstrainedLinearVelocities.get(indexArray);
final Vector3 newAngVelocity = mConstrainedAngularVelocities.get(indexArray);
rigidBody.setLinearVelocity(newLinVelocity);
rigidBody.setAngularVelocity(newAngVelocity);
if (mContactSolver.isConstrainedBody(rigidBody) && mContactSolver.isSplitImpulseActive()) {
newLinVelocity.add(mContactSolver.getSplitLinearVelocityOfBody(rigidBody));
newAngVelocity.add(mContactSolver.getSplitAngularVelocityOfBody(rigidBody));
}
final Vector3 currentPosition = rigidBody.getTransform().getPosition();
final Quaternion currentOrientation = rigidBody.getTransform().getOrientation();
final Vector3 newPosition = Vector3.add(currentPosition, Vector3.multiply(newLinVelocity, dt));
final Quaternion newOrientation = Quaternion.add(currentOrientation, Quaternion.multiply(Quaternion.multiply(new Quaternion(0, newAngVelocity), currentOrientation), 0.5f * dt));
final Transform newTransform = new Transform(newPosition, newOrientation.getUnit());
rigidBody.setTransform(newTransform);
}
}
}
// Updates the AABBs of the bodies
private void updateRigidBodiesAABB() {
for (RigidBody rigidBody : mRigidBodies) {
if (rigidBody.getHasMoved()) {
rigidBody.updateAABB();
}
}
}
// Computes and set the interpolation factor for all bodies.
private void setInterpolationFactorToAllBodies() {
final float factor = mTimer.computeInterpolationFactor();
if (factor < 0 && factor > 1) {
throw new IllegalStateException("interpolation factor must be greater or equal to zero"
+ " and smaller or equal to one");
}
for (RigidBody rigidBody : mRigidBodies) {
if (rigidBody == null) {
throw new IllegalStateException("rigid body cannot be null");
}
rigidBody.setInterpolationFactor(factor);
}
}
// Integrates the constrained velocities array using the provided time delta.
// This method only sets the temporary velocities and does not update
// the actual velocities of the bodies. The velocities updated in this method
// might violate the constraints and will be corrected in the constraint and
// contact solver.
private void integrateRigidBodiesVelocities() {
mConstrainedLinearVelocities.clear();
mConstrainedLinearVelocities.ensureCapacity(mRigidBodies.size());
mConstrainedAngularVelocities.clear();
mConstrainedAngularVelocities.ensureCapacity(mRigidBodies.size());
final float dt = (float) mTimer.getTimeStep();
int i = 0;
for (RigidBody rigidBody : mRigidBodies) {
mMapBodyToConstrainedVelocityIndex.put(rigidBody, i);
if (rigidBody.getIsMotionEnabled()) {
mConstrainedLinearVelocities.add(i, Vector3.add(
rigidBody.getLinearVelocity(),
Vector3.multiply(dt * rigidBody.getMassInverse(), rigidBody.getExternalForce())));
mConstrainedAngularVelocities.add(i, Vector3.add(
rigidBody.getAngularVelocity(),
Matrix3x3.multiply(
Matrix3x3.multiply(dt, rigidBody.getInertiaTensorInverseWorld()),
rigidBody.getExternalTorque())
));
if (rigidBody.isGravityEnabled() && mIsGravityOn) {
mConstrainedLinearVelocities.get(i).add(Vector3.multiply(dt * rigidBody.getMassInverse() * rigidBody.getMass(), mGravity));
}
rigidBody.updateOldTransform();
} else {
mConstrainedLinearVelocities.add(i, new Vector3(0, 0, 0));
mConstrainedAngularVelocities.add(i, new Vector3(0, 0, 0));
}
i++;
}
if (mMapBodyToConstrainedVelocityIndex.size() != mRigidBodies.size()) {
throw new IllegalStateException("The size of the map from body to constrained velocity index should be the same as the number of rigid bodies");
}
}
// Solves the contacts and constraints
private void solveContactsAndConstraints() {
final float dt = (float) mTimer.getTimeStep();
final boolean isConstraintsToSolve = !mJoints.isEmpty();
final boolean isContactsToSolve = !mContactManifolds.isEmpty();
if (!isConstraintsToSolve && !isContactsToSolve) {
return;
}
if (isContactsToSolve) {
mContactSolver.initialize(dt);
mContactSolver.warmStart();
}
if (isConstraintsToSolve) {
mConstraintSolver.initialize(dt);
}
for (int i = 0; i < mNbVelocitySolverIterations; i++) {
if (isConstraintsToSolve) {
mConstraintSolver.solveVelocityConstraints();
}
if (isContactsToSolve) {
mContactSolver.solve();
}
}
if (isContactsToSolve) {
mContactSolver.storeImpulses();
}
}
public void solvePositionCorrection() {
if (mJoints.isEmpty()) {
return;
}
// TODO : Use better memory allocation here
mConstrainedPositions.clear();
mConstrainedPositions.ensureCapacity(mRigidBodies.size());
mConstrainedOrientations.clear();
mConstrainedOrientations.ensureCapacity(mRigidBodies.size());
for (int i = 0; i < mRigidBodies.size(); i++) {
mConstrainedPositions.add(null);
mConstrainedOrientations.add(null);
}
for (RigidBody rigidBody : mRigidBodies) {
if (mConstraintSolver.isConstrainedBody(rigidBody)) {
final int index = mMapBodyToConstrainedVelocityIndex.get(rigidBody);
final Transform transform = rigidBody.getTransform();
mConstrainedPositions.set(index, new Vector3(transform.getPosition()));
mConstrainedOrientations.set(index, new Quaternion(transform.getOrientation()));
}
}
for (int i = 0; i < mNbPositionSolverIterations; i++) {
mConstraintSolver.solvePositionConstraints();
}
for (RigidBody rigidBody : mRigidBodies) {
if (mConstraintSolver.isConstrainedBody(rigidBody)) {
final int index = mMapBodyToConstrainedVelocityIndex.get(rigidBody);
final Vector3 newPosition = mConstrainedPositions.get(index);
final Quaternion newOrientation = mConstrainedOrientations.get(index);
final Transform newTransform = new Transform(newPosition, newOrientation.getUnit());
rigidBody.setTransform(newTransform);
}
}
}
// Cleans up the constrained velocities array at each step.
private void cleanupConstrainedVelocitiesArray() {
mConstrainedLinearVelocities.clear();
mConstrainedAngularVelocities.clear();
mMapBodyToConstrainedVelocityIndex.clear();
}
/**
* Creates a mobile rigid body and adds it to the physics world. The inertia tensor will be computed from the shape and mass.
*
* @param transform The transform (position and orientation) of the body
* @param mass The mass of the body
* @param collisionShape The collision shape
* @return The new rigid body
*/
public RigidBody createRigidBody(Transform transform, float mass, CollisionShape collisionShape) {
final Matrix3x3 inertiaTensor = new Matrix3x3();
collisionShape.computeLocalInertiaTensor(inertiaTensor, mass);
return createRigidBody(transform, mass, inertiaTensor, collisionShape);
}
/**
* Creates a mobile rigid body and adds it to the physics world.
*
* @param transform The transform (position and orientation) of the body
* @param mass The mass of the body
* @param inertiaTensorLocal The local inertia tensor
* @param collisionShape The collision shape
* @return The new rigid body
*/
public RigidBody createRigidBody(Transform transform, float mass, Matrix3x3 inertiaTensorLocal, CollisionShape collisionShape) {
final CollisionShape newCollisionShape = createCollisionShape(collisionShape);
final RigidBody mobileBody = new RigidBody(transform, mass, inertiaTensorLocal, newCollisionShape, getNextFreeID());
addRigidBody(mobileBody);
return mobileBody;
}
/**
* Adds a rigid body to the body collections and the collision detection, even if a tick is in progress.
*
* @param body The body to add
*/
protected void addRigidBodyIgnoreTick(RigidBody body) {
mBodies.add(body);
mRigidBodies.add(body);
mCollisionDetection.addBody(body);
}
/**
* Adds a rigid body to the body collections and the collision detection. If a tick is in progress, the body is added at the end.
*
* @param body The body to add
*/
public void addRigidBody(RigidBody body) {
if (!isTicking) {
mBodies.add(body);
mRigidBodies.add(body);
mCollisionDetection.addBody(body);
} else {
mRigidBodiesToAddCache.add(body);
}
}
/**
* Destroys a rigid body and all the joints to which it belongs.
*
* @param rigidBody The rigid body to destroy
*/
public void destroyRigidBody(RigidBody rigidBody) {
if (!isTicking) {
mCollisionDetection.removeBody(rigidBody);
mFreeBodiesIDs.push(rigidBody.getID());
mBodies.remove(rigidBody);
mRigidBodies.remove(rigidBody);
removeCollisionShape(rigidBody.getCollisionShape());
final int idToRemove = rigidBody.getID();
for (Constraint joint : mJoints) {
if (joint.getFirstBody().getID() == idToRemove || joint.getSecondBody().getID() == idToRemove) {
destroyJoint(joint);
}
}
} else {
mRigidBodiesToDeleteCache.add(rigidBody);
}
}
/**
* Creates a joint between two bodies in the world and returns the new joint.
*
* @param jointInfo The information to use for creating the joint
* @return The new joint
*/
public Constraint createJoint(ConstraintInfo jointInfo) {
final Constraint newJoint;
switch (jointInfo.getType()) {
case BALLSOCKETJOINT: {
final BallAndSocketJointInfo info = (BallAndSocketJointInfo) jointInfo;
newJoint = new BallAndSocketJoint(info);
break;
}
case SLIDERJOINT: {
final SliderJointInfo info = (SliderJointInfo) jointInfo;
newJoint = new SliderJoint(info);
break;
}
case HINGEJOINT: {
final HingeJointInfo info = (HingeJointInfo) jointInfo;
newJoint = new HingeJoint(info);
break;
}
case FIXEDJOINT: {
final FixedJointInfo info = (FixedJointInfo) jointInfo;
newJoint = new FixedJoint(info);
break;
}
default:
throw new IllegalArgumentException("Unsupported joint type +" + jointInfo.getType());
}
if (!jointInfo.isCollisionEnabled()) {
mCollisionDetection.addNoCollisionPair(jointInfo.getFirstBody(), jointInfo.getSecondBody());
}
mJoints.add(newJoint);
return newJoint;
}
/**
* Destroys a joint.
*
* @param joint The joint to destroy
*/
public void destroyJoint(Constraint joint) {
if (joint == null) {
throw new IllegalArgumentException("Joint cannot be null");
}
if (!joint.isCollisionEnabled()) {
mCollisionDetection.removeNoCollisionPair(joint.getFirstBody(), joint.getSecondBody());
}
mJoints.remove(joint);
}
@Override
public void notifyAddedOverlappingPair(BroadPhasePair addedPair) {
final IntPair indexPair = addedPair.getBodiesIndexPair();
final OverlappingPair newPair = new OverlappingPair(addedPair.getFirstBody(), addedPair.getSecondBody());
final OverlappingPair oldPair = mOverlappingPairs.put(indexPair, newPair);
if (oldPair != null) {
throw new IllegalStateException("overlapping pair was already in the overlapping pairs map");
}
}
@Override
public void updateOverlappingPair(BroadPhasePair pair) {
final IntPair indexPair = pair.getBodiesIndexPair();
final OverlappingPair overlappingPair = mOverlappingPairs.get(indexPair);
overlappingPair.update();
}
@Override
public void notifyRemovedOverlappingPair(BroadPhasePair removedPair) {
final IntPair indexPair = removedPair.getBodiesIndexPair();
mOverlappingPairs.remove(indexPair);
}
@Override
public void notifyNewContact(BroadPhasePair broadPhasePair, ContactPointInfo contactInfo) {
final ContactPoint contact = new ContactPoint(contactInfo);
final IntPair indexPair = broadPhasePair.getBodiesIndexPair();
final OverlappingPair overlappingPair = mOverlappingPairs.get(indexPair);
if (overlappingPair == null) {
throw new IllegalArgumentException("broad phase pair is not in the overlapping pairs");
}
overlappingPair.addContact(contact);
mContactManifolds.add(overlappingPair.getContactManifold());
}
/**
* Returns if the world is currently undertaking a tick
*
* @return True if ticking, false if not
*/
public boolean isTicking() {
return isTicking;
}
/**
* Disperses the cache of bodies added/removed during the physics tick.
*/
public void disperseCache() {
mRigidBodiesToAddCache.removeAll(mRigidBodiesToDeleteCache);
for (RigidBody body : mRigidBodiesToDeleteCache) {
destroyRigidBody(body);
}
for (RigidBody body : mRigidBodiesToAddCache) {
addRigidBody(body);
}
mRigidBodiesToAddCache.clear();
mRigidBodiesToDeleteCache.clear();
}
}
|
package jadx.core.dex.visitors;
import java.util.ArrayList;
import java.util.List;
import org.jetbrains.annotations.Nullable;
import jadx.core.codegen.TypeGen;
import jadx.core.deobf.NameMapper;
import jadx.core.dex.attributes.AFlag;
import jadx.core.dex.attributes.AType;
import jadx.core.dex.attributes.nodes.EnumClassAttr;
import jadx.core.dex.attributes.nodes.EnumClassAttr.EnumField;
import jadx.core.dex.info.AccessInfo;
import jadx.core.dex.info.ClassInfo;
import jadx.core.dex.info.FieldInfo;
import jadx.core.dex.info.MethodInfo;
import jadx.core.dex.instructions.IndexInsnNode;
import jadx.core.dex.instructions.InsnType;
import jadx.core.dex.instructions.args.ArgType;
import jadx.core.dex.instructions.args.InsnArg;
import jadx.core.dex.instructions.args.InsnWrapArg;
import jadx.core.dex.instructions.args.RegisterArg;
import jadx.core.dex.instructions.mods.ConstructorInsn;
import jadx.core.dex.nodes.BlockNode;
import jadx.core.dex.nodes.ClassNode;
import jadx.core.dex.nodes.DexNode;
import jadx.core.dex.nodes.FieldNode;
import jadx.core.dex.nodes.InsnNode;
import jadx.core.dex.nodes.MethodNode;
import jadx.core.dex.visitors.shrink.CodeShrinkVisitor;
import jadx.core.utils.ErrorsCounter;
import jadx.core.utils.InsnUtils;
import jadx.core.utils.exceptions.JadxException;
@JadxVisitor(
name = "EnumVisitor",
desc = "Restore enum classes",
runAfter = { CodeShrinkVisitor.class, ModVisitor.class }
)
public class EnumVisitor extends AbstractVisitor {
@Override
public boolean visit(ClassNode cls) throws JadxException {
if (!convertToEnum(cls)) {
AccessInfo accessFlags = cls.getAccessFlags();
if (accessFlags.isEnum()) {
cls.addAttr(AType.COMMENTS, "'enum' modifier should be removed");
}
}
return true;
}
private boolean convertToEnum(ClassNode cls) {
if (!cls.isEnum()) {
return false;
}
// search class init method
MethodNode staticMethod = null;
for (MethodNode mth : cls.getMethods()) {
MethodInfo mi = mth.getMethodInfo();
if (mi.isClassInit()) {
staticMethod = mth;
break;
}
}
if (staticMethod == null) {
ErrorsCounter.classWarn(cls, "Enum class init method not found");
return false;
}
ArgType clsType = cls.getClassInfo().getType();
String enumConstructor = "<init>(Ljava/lang/String;I)V";
// TODO: detect these methods by analyzing method instructions
String valuesOfMethod = "valueOf(Ljava/lang/String;)" + TypeGen.signature(clsType);
String valuesMethod = "values()" + TypeGen.signature(ArgType.array(clsType));
// collect enum fields, remove synthetic
List<FieldNode> enumFields = new ArrayList<>();
for (FieldNode f : cls.getFields()) {
if (f.getAccessFlags().isEnum()) {
enumFields.add(f);
f.add(AFlag.DONT_GENERATE);
} else if (f.getAccessFlags().isSynthetic()) {
f.add(AFlag.DONT_GENERATE);
}
}
// remove synthetic methods
for (MethodNode mth : cls.getMethods()) {
MethodInfo mi = mth.getMethodInfo();
if (mi.isClassInit()) {
continue;
}
String shortId = mi.getShortId();
boolean isSynthetic = mth.getAccessFlags().isSynthetic();
if (mi.isConstructor() && !isSynthetic) {
if (shortId.equals(enumConstructor)) {
mth.add(AFlag.DONT_GENERATE);
}
} else if (isSynthetic
|| shortId.equals(valuesMethod)
|| shortId.equals(valuesOfMethod)) {
mth.add(AFlag.DONT_GENERATE);
}
}
EnumClassAttr attr = new EnumClassAttr(enumFields.size());
cls.addAttr(attr);
attr.setStaticMethod(staticMethod);
ClassInfo classInfo = cls.getClassInfo();
// move enum specific instruction from static method to separate list
BlockNode staticBlock = staticMethod.getBasicBlocks().get(0);
List<InsnNode> enumPutInsns = new ArrayList<>();
List<InsnNode> list = staticBlock.getInstructions();
int size = list.size();
for (int i = 0; i < size; i++) {
InsnNode insn = list.get(i);
if (insn.getType() != InsnType.SPUT) {
continue;
}
FieldInfo f = (FieldInfo) ((IndexInsnNode) insn).getIndex();
if (!f.getDeclClass().equals(classInfo)) {
continue;
}
FieldNode fieldNode = cls.searchField(f);
if (fieldNode != null && isEnumArrayField(classInfo, fieldNode)) {
if (i == size - 1) {
staticMethod.add(AFlag.DONT_GENERATE);
} else {
list.subList(0, i + 1).clear();
}
break;
} else {
enumPutInsns.add(insn);
}
}
for (InsnNode putInsn : enumPutInsns) {
ConstructorInsn co = getConstructorInsn(putInsn);
if (co == null || co.getArgsCount() < 2) {
continue;
}
ClassInfo clsInfo = co.getClassType();
ClassNode constrCls = cls.dex().resolveClass(clsInfo);
if (constrCls == null) {
continue;
}
if (!clsInfo.equals(classInfo) && !constrCls.getAccessFlags().isEnum()) {
continue;
}
FieldInfo fieldInfo = (FieldInfo) ((IndexInsnNode) putInsn).getIndex();
String name = getConstString(cls.dex(), co.getArg(0));
if (name != null
&& !fieldInfo.getAlias().equals(name)
&& NameMapper.isValidAndPrintable(name)
&& cls.root().getArgs().isRenameValid()) {
fieldInfo.setAlias(name);
}
EnumField field = new EnumField(fieldInfo, co, 2);
attr.getFields().add(field);
if (!co.getClassType().equals(classInfo)) {
// enum contains additional methods
for (ClassNode innerCls : cls.getInnerClasses()) {
processEnumInnerCls(co, field, innerCls);
}
}
}
return true;
}
private static void processEnumInnerCls(ConstructorInsn co, EnumField field, ClassNode innerCls) {
if (!innerCls.getClassInfo().equals(co.getClassType())) {
return;
}
// remove constructor, because it is anonymous class
for (MethodNode innerMth : innerCls.getMethods()) {
if (innerMth.getAccessFlags().isConstructor()) {
innerMth.add(AFlag.DONT_GENERATE);
}
}
field.setCls(innerCls);
innerCls.add(AFlag.DONT_GENERATE);
}
private boolean isEnumArrayField(ClassInfo classInfo, FieldNode fieldNode) {
if (fieldNode.getAccessFlags().isSynthetic()) {
ArgType fType = fieldNode.getType();
return fType.isArray() && fType.getArrayRootElement().equals(classInfo.getType());
}
return false;
}
private ConstructorInsn getConstructorInsn(InsnNode putInsn) {
if (putInsn.getArgsCount() != 1) {
return null;
}
InsnArg arg = putInsn.getArg(0);
if (arg.isInsnWrap()) {
return castConstructorInsn(((InsnWrapArg) arg).getWrapInsn());
}
if (arg.isRegister()) {
return castConstructorInsn(((RegisterArg) arg).getAssignInsn());
}
return null;
}
@Nullable
private ConstructorInsn castConstructorInsn(InsnNode coCandidate) {
if (coCandidate != null && coCandidate.getType() == InsnType.CONSTRUCTOR) {
return (ConstructorInsn) coCandidate;
}
return null;
}
private String getConstString(DexNode dex, InsnArg arg) {
if (arg.isInsnWrap()) {
InsnNode constInsn = ((InsnWrapArg) arg).getWrapInsn();
Object constValue = InsnUtils.getConstValueByInsn(dex, constInsn);
if (constValue instanceof String) {
return (String) constValue;
}
}
return null;
}
}
|
package org.team2471.frc.lib.io;
import java.util.function.DoubleFunction;
@FunctionalInterface
public interface ControllerAxis {
double get();
default ControllerAxis map(DoubleFunction<Double> function) {
return () -> function.apply(get());
}
default ControllerAxis withDeadband(double tolerance, boolean scale) {
return map(value -> {
value = Math.abs(value) < tolerance ? 0 : value;
if (scale && value != 0) {
value = (value - tolerance) * (1 / (1 - tolerance));
}
return value;
});
}
default ControllerAxis withDeadband(double tolerance) {
return withDeadband(tolerance, false);
}
default ControllerAxis withInvert() {
return map(value -> - value);
}
default ControllerAxis withExponentialScaling(int exponent) {
return map(value -> Math.pow(value, exponent) * Math.signum(value));
}
default ControllerAxis withLinearScaling(double factor) {
return map(value -> value * factor);
}
}
|
package org.opencms.ade.contenteditor;
import org.opencms.acacia.shared.CmsAttributeConfiguration;
import org.opencms.acacia.shared.CmsEntity;
import org.opencms.acacia.shared.CmsEntityAttribute;
import org.opencms.acacia.shared.CmsEntityHtml;
import org.opencms.acacia.shared.CmsType;
import org.opencms.acacia.shared.CmsValidationResult;
import org.opencms.ade.containerpage.CmsContainerpageService;
import org.opencms.ade.containerpage.CmsElementUtil;
import org.opencms.ade.containerpage.shared.CmsCntPageData;
import org.opencms.ade.containerpage.shared.CmsContainer;
import org.opencms.ade.containerpage.shared.CmsContainerElement;
import org.opencms.ade.contenteditor.shared.CmsContentDefinition;
import org.opencms.ade.contenteditor.shared.CmsEditorConstants;
import org.opencms.ade.contenteditor.shared.rpc.I_CmsContentService;
import org.opencms.file.CmsFile;
import org.opencms.file.CmsObject;
import org.opencms.file.CmsPropertyDefinition;
import org.opencms.file.CmsResource;
import org.opencms.file.CmsResourceFilter;
import org.opencms.file.collectors.A_CmsResourceCollector;
import org.opencms.file.types.CmsResourceTypeXmlContent;
import org.opencms.flex.CmsFlexController;
import org.opencms.gwt.CmsGwtService;
import org.opencms.gwt.CmsRpcException;
import org.opencms.gwt.shared.CmsModelResourceInfo;
import org.opencms.i18n.CmsEncoder;
import org.opencms.i18n.CmsLocaleManager;
import org.opencms.json.JSONObject;
import org.opencms.main.CmsException;
import org.opencms.main.CmsLog;
import org.opencms.main.OpenCms;
import org.opencms.search.CmsSearchManager;
import org.opencms.search.galleries.CmsGallerySearch;
import org.opencms.search.galleries.CmsGallerySearchResult;
import org.opencms.util.CmsStringUtil;
import org.opencms.util.CmsUUID;
import org.opencms.workplace.CmsDialog;
import org.opencms.workplace.editors.CmsEditor;
import org.opencms.workplace.editors.CmsXmlContentEditor;
import org.opencms.workplace.explorer.CmsNewResourceXmlContent;
import org.opencms.xml.CmsXmlContentDefinition;
import org.opencms.xml.CmsXmlEntityResolver;
import org.opencms.xml.CmsXmlException;
import org.opencms.xml.CmsXmlUtils;
import org.opencms.xml.I_CmsXmlDocument;
import org.opencms.xml.containerpage.CmsADESessionCache;
import org.opencms.xml.content.CmsXmlContent;
import org.opencms.xml.content.CmsXmlContentErrorHandler;
import org.opencms.xml.content.CmsXmlContentFactory;
import org.opencms.xml.content.I_CmsXmlContentEditorChangeHandler;
import org.opencms.xml.types.I_CmsXmlContentValue;
import org.opencms.xml.types.I_CmsXmlSchemaType;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.TreeMap;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.logging.Log;
import org.dom4j.Element;
/**
* Service to provide entity persistence within OpenCms. <p>
*/
public class CmsContentService extends CmsGwtService implements I_CmsContentService {
/** The logger for this class. */
protected static final Log LOG = CmsLog.getLog(CmsContentService.class);
/** The type name prefix. */
static final String TYPE_NAME_PREFIX = "http://opencms.org/types/";
/** The serial version id. */
private static final long serialVersionUID = 7873052619331296648L;
/** The session cache. */
private CmsADESessionCache m_sessionCache;
/** The current users workplace locale. */
private Locale m_workplaceLocale;
/**
* Returns the entity attribute name representing the given content value.<p>
*
* @param contentValue the content value
*
* @return the attribute name
*/
public static String getAttributeName(I_CmsXmlContentValue contentValue) {
return getTypeUri(contentValue.getContentDefinition()) + "/" + contentValue.getName();
}
/**
* Returns the entity attribute name to use for this element.<p>
*
* @param elementName the element name
* @param parentType the parent type
*
* @return the attribute name
*/
public static String getAttributeName(String elementName, String parentType) {
return parentType + "/" + elementName;
}
/**
* Returns the entity id to the given content value.<p>
*
* @param contentValue the content value
*
* @return the entity id
*/
public static String getEntityId(I_CmsXmlContentValue contentValue) {
String result = CmsContentDefinition.uuidToEntityId(
contentValue.getDocument().getFile().getStructureId(),
contentValue.getLocale().toString());
String valuePath = contentValue.getPath();
if (valuePath.contains("/")) {
result += "/" + valuePath.substring(0, valuePath.lastIndexOf("/"));
}
if (contentValue.isChoiceOption()) {
result += "/"
+ CmsType.CHOICE_ATTRIBUTE_NAME
+ "_"
+ contentValue.getName()
+ "["
+ contentValue.getXmlIndex()
+ "]";
}
return result;
}
/**
* Returns the RDF annotations required for in line editing.<p>
*
* @param parentValue the parent XML content value
* @param childNames the child attribute names separated by '|'
*
* @return the RDFA
*/
public static String getRdfaAttributes(I_CmsXmlContentValue parentValue, String childNames) {
StringBuffer result = new StringBuffer();
result.append("about=\"");
result.append(CmsContentDefinition.uuidToEntityId(
parentValue.getDocument().getFile().getStructureId(),
parentValue.getLocale().toString()));
result.append("/").append(parentValue.getPath());
result.append("\" ");
String[] children = childNames.split("\\|");
result.append("property=\"");
for (int i = 0; i < children.length; i++) {
I_CmsXmlSchemaType schemaType = parentValue.getContentDefinition().getSchemaType(
parentValue.getName() + "/" + children[i]);
if (schemaType != null) {
if (i > 0) {
result.append(" ");
}
result.append(getTypeUri(schemaType.getContentDefinition())).append("/").append(children[i]);
}
}
result.append("\"");
return result.toString();
}
/**
* Returns the RDF annotations required for in line editing.<p>
*
* @param document the parent XML document
* @param contentLocale the content locale
* @param childName the child attribute name
*
* @return the RDFA
*/
public static String getRdfaAttributes(I_CmsXmlDocument document, Locale contentLocale, String childName) {
I_CmsXmlSchemaType schemaType = document.getContentDefinition().getSchemaType(childName);
StringBuffer result = new StringBuffer();
if (schemaType != null) {
result.append("about=\"");
result.append(CmsContentDefinition.uuidToEntityId(
document.getFile().getStructureId(),
contentLocale.toString()));
result.append("\" property=\"");
result.append(getTypeUri(schemaType.getContentDefinition())).append("/").append(childName);
result.append("\"");
}
return result.toString();
}
/**
* Returns the type URI.<p>
*
* @param xmlContentDefinition the type content definition
*
* @return the type URI
*/
public static String getTypeUri(CmsXmlContentDefinition xmlContentDefinition) {
return xmlContentDefinition.getSchemaLocation() + "/" + xmlContentDefinition.getTypeName();
}
/**
* Fetches the initial content definition.<p>
*
* @param request the current request
*
* @return the initial content definition
*
* @throws CmsRpcException if something goes wrong
*/
public static CmsContentDefinition prefetch(HttpServletRequest request) throws CmsRpcException {
CmsContentService srv = new CmsContentService();
srv.setCms(CmsFlexController.getCmsObject(request));
srv.setRequest(request);
CmsContentDefinition result = null;
try {
result = srv.prefetch();
} finally {
srv.clearThreadStorage();
}
return result;
}
/**
* @see org.opencms.ade.contenteditor.shared.rpc.I_CmsContentService#callEditorChangeHandlers(java.lang.String, org.opencms.acacia.shared.CmsEntity, java.util.Collection, java.util.Collection)
*/
public CmsContentDefinition callEditorChangeHandlers(
String entityId,
CmsEntity editedLocaleEntity,
Collection<String> skipPaths,
Collection<String> changedScopes) throws CmsRpcException {
CmsContentDefinition result = null;
CmsUUID structureId = CmsContentDefinition.entityIdToUuid(editedLocaleEntity.getId());
if (structureId != null) {
CmsObject cms = getCmsObject();
CmsResource resource = null;
Locale locale = CmsLocaleManager.getLocale(CmsContentDefinition.getLocaleFromId(entityId));
try {
resource = cms.readResource(structureId, CmsResourceFilter.IGNORE_EXPIRATION);
ensureLock(resource);
CmsFile file = cms.readFile(resource);
CmsXmlContent content = getContentDocument(file, true).clone();
checkAutoCorrection(cms, content);
synchronizeLocaleIndependentForEntity(file, content, skipPaths, editedLocaleEntity);
for (I_CmsXmlContentEditorChangeHandler handler : content.getContentDefinition().getContentHandler().getEditorChangeHandlers()) {
Set<String> handlerScopes = evaluateScope(handler.getScope(), content.getContentDefinition());
if (!Collections.disjoint(changedScopes, handlerScopes)) {
handler.handleChange(cms, content, locale, changedScopes);
}
}
result = readContentDefinition(file, content, entityId, locale, false);
} catch (Exception e) {
error(e);
}
}
return result;
}
/**
* @see org.opencms.ade.contenteditor.shared.rpc.I_CmsContentService#cancelEdit(org.opencms.util.CmsUUID, boolean)
*/
public void cancelEdit(CmsUUID structureId, boolean delete) throws CmsRpcException {
try {
getSessionCache().uncacheXmlContent(structureId);
CmsResource resource = getCmsObject().readResource(structureId, CmsResourceFilter.IGNORE_EXPIRATION);
if (delete) {
ensureLock(resource);
getCmsObject().deleteResource(
getCmsObject().getSitePath(resource),
CmsResource.DELETE_PRESERVE_SIBLINGS);
}
tryUnlock(resource);
} catch (Throwable t) {
error(t);
}
}
/**
* @see org.opencms.ade.contenteditor.shared.rpc.I_CmsContentService#copyLocale(java.util.Collection, org.opencms.acacia.shared.CmsEntity)
*/
public void copyLocale(Collection<String> locales, CmsEntity sourceLocale) throws CmsRpcException {
try {
CmsUUID structureId = CmsContentDefinition.entityIdToUuid(sourceLocale.getId());
CmsResource resource = getCmsObject().readResource(structureId, CmsResourceFilter.IGNORE_EXPIRATION);
CmsFile file = getCmsObject().readFile(resource);
CmsXmlContent content = getSessionCache().getCacheXmlContent(structureId);
synchronizeLocaleIndependentForEntity(file, content, Collections.<String> emptyList(), sourceLocale);
Locale sourceContentLocale = CmsLocaleManager.getLocale(CmsContentDefinition.getLocaleFromId(sourceLocale.getId()));
for (String loc : locales) {
Locale targetLocale = CmsLocaleManager.getLocale(loc);
if (content.hasLocale(targetLocale)) {
content.removeLocale(targetLocale);
}
content.copyLocale(sourceContentLocale, targetLocale);
}
} catch (Throwable t) {
error(t);
}
}
/**
* @see org.opencms.acacia.shared.rpc.I_CmsContentService#loadContentDefinition(java.lang.String)
*/
public CmsContentDefinition loadContentDefinition(String entityId) throws CmsRpcException {
throw new CmsRpcException(new UnsupportedOperationException());
}
/**
* @see org.opencms.ade.contenteditor.shared.rpc.I_CmsContentService#loadDefinition(java.lang.String, org.opencms.acacia.shared.CmsEntity, java.util.Collection)
*/
public CmsContentDefinition loadDefinition(
String entityId,
CmsEntity editedLocaleEntity,
Collection<String> skipPaths) throws CmsRpcException {
CmsContentDefinition definition = null;
try {
CmsUUID structureId = CmsContentDefinition.entityIdToUuid(entityId);
CmsResource resource = getCmsObject().readResource(structureId, CmsResourceFilter.IGNORE_EXPIRATION);
Locale contentLocale = CmsLocaleManager.getLocale(CmsContentDefinition.getLocaleFromId(entityId));
CmsFile file = getCmsObject().readFile(resource);
CmsXmlContent content = getContentDocument(file, true);
if (editedLocaleEntity != null) {
synchronizeLocaleIndependentForEntity(file, content, skipPaths, editedLocaleEntity);
}
definition = readContentDefinition(
file,
content,
CmsContentDefinition.uuidToEntityId(structureId, contentLocale.toString()),
contentLocale,
false);
} catch (Exception e) {
error(e);
}
return definition;
}
/**
* @see org.opencms.ade.contenteditor.shared.rpc.I_CmsContentService#loadInitialDefinition(java.lang.String, java.lang.String, org.opencms.util.CmsUUID, java.lang.String, java.lang.String, java.lang.String)
*/
public CmsContentDefinition loadInitialDefinition(
String entityId,
String newLink,
CmsUUID modelFileId,
String editContext,
String mode,
String postCreateHandler) throws CmsRpcException {
CmsContentDefinition result = null;
getCmsObject().getRequestContext().setAttribute(CmsXmlContentEditor.ATTRIBUTE_EDITCONTEXT, editContext);
try {
CmsUUID structureId = CmsContentDefinition.entityIdToUuid(entityId);
CmsResource resource = getCmsObject().readResource(structureId, CmsResourceFilter.IGNORE_EXPIRATION);
Locale contentLocale = CmsLocaleManager.getLocale(CmsContentDefinition.getLocaleFromId(entityId));
if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(newLink)) {
result = readContentDefnitionForNew(
newLink,
resource,
modelFileId,
contentLocale,
mode,
postCreateHandler);
} else {
CmsFile file = getCmsObject().readFile(resource);
CmsXmlContent content = getContentDocument(file, false);
result = readContentDefinition(
file,
content,
CmsContentDefinition.uuidToEntityId(structureId, contentLocale.toString()),
contentLocale,
false);
}
} catch (Throwable t) {
error(t);
}
return result;
}
/**
* @see org.opencms.ade.contenteditor.shared.rpc.I_CmsContentService#loadNewDefinition(java.lang.String, org.opencms.acacia.shared.CmsEntity, java.util.Collection)
*/
public CmsContentDefinition loadNewDefinition(
String entityId,
CmsEntity editedLocaleEntity,
Collection<String> skipPaths) throws CmsRpcException {
CmsContentDefinition definition = null;
try {
CmsUUID structureId = CmsContentDefinition.entityIdToUuid(entityId);
CmsResource resource = getCmsObject().readResource(structureId, CmsResourceFilter.IGNORE_EXPIRATION);
Locale contentLocale = CmsLocaleManager.getLocale(CmsContentDefinition.getLocaleFromId(entityId));
CmsFile file = getCmsObject().readFile(resource);
CmsXmlContent content = getContentDocument(file, true);
synchronizeLocaleIndependentForEntity(file, content, skipPaths, editedLocaleEntity);
definition = readContentDefinition(
file,
content,
CmsContentDefinition.uuidToEntityId(structureId, contentLocale.toString()),
contentLocale,
true);
} catch (Exception e) {
error(e);
}
return definition;
}
/**
* @see org.opencms.ade.contenteditor.shared.rpc.I_CmsContentService#prefetch()
*/
public CmsContentDefinition prefetch() throws CmsRpcException {
String paramResource = getRequest().getParameter(CmsDialog.PARAM_RESOURCE);
String paramDirectEdit = getRequest().getParameter(CmsEditor.PARAM_DIRECTEDIT);
boolean isDirectEdit = false;
if (paramDirectEdit != null) {
isDirectEdit = Boolean.parseBoolean(paramDirectEdit);
}
String paramNewLink = getRequest().getParameter(CmsXmlContentEditor.PARAM_NEWLINK);
boolean createNew = false;
if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(paramNewLink)) {
createNew = true;
paramNewLink = decodeNewLink(paramNewLink);
}
String paramLocale = getRequest().getParameter(CmsEditor.PARAM_ELEMENTLANGUAGE);
Locale locale = null;
CmsObject cms = getCmsObject();
if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(paramResource)) {
try {
CmsResource resource = cms.readResource(paramResource, CmsResourceFilter.IGNORE_EXPIRATION);
if (CmsResourceTypeXmlContent.isXmlContent(resource)) {
if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(paramLocale)) {
locale = CmsLocaleManager.getLocale(paramLocale);
}
CmsContentDefinition result;
if (createNew) {
if (locale == null) {
locale = OpenCms.getLocaleManager().getDefaultLocale(cms, paramResource);
}
CmsUUID modelFileId = null;
String paramModelFile = getRequest().getParameter(CmsNewResourceXmlContent.PARAM_MODELFILE);
if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(paramModelFile)) {
modelFileId = cms.readResource(paramModelFile).getStructureId();
}
String mode = getRequest().getParameter(CmsEditorConstants.PARAM_MODE);
String postCreateHandler = getRequest().getParameter(
CmsEditorConstants.PARAM_POST_CREATE_HANDLER);
result = readContentDefnitionForNew(
paramNewLink,
resource,
modelFileId,
locale,
mode,
postCreateHandler);
} else {
CmsFile file = cms.readFile(resource);
CmsXmlContent content = CmsXmlContentFactory.unmarshal(cms, file);
getSessionCache().setCacheXmlContent(resource.getStructureId(), content);
if (locale == null) {
locale = getBestAvailableLocale(resource, content);
}
result = readContentDefinition(file, content, null, locale, false);
}
result.setDirectEdit(isDirectEdit);
return result;
}
} catch (Throwable e) {
error(e);
}
}
return null;
}
/**
* @see org.opencms.ade.contenteditor.shared.rpc.I_CmsContentService#saveAndDeleteEntities(org.opencms.acacia.shared.CmsEntity, java.util.List, java.util.Collection, java.lang.String, boolean)
*/
public CmsValidationResult saveAndDeleteEntities(
CmsEntity lastEditedEntity,
List<String> deletedEntities,
Collection<String> skipPaths,
String lastEditedLocale,
boolean clearOnSuccess) throws CmsRpcException {
CmsUUID structureId = null;
if (lastEditedEntity != null) {
structureId = CmsContentDefinition.entityIdToUuid(lastEditedEntity.getId());
}
if ((structureId == null) && !deletedEntities.isEmpty()) {
structureId = CmsContentDefinition.entityIdToUuid(deletedEntities.get(0));
}
if (structureId != null) {
CmsObject cms = getCmsObject();
CmsResource resource = null;
try {
resource = cms.readResource(structureId, CmsResourceFilter.IGNORE_EXPIRATION);
ensureLock(resource);
CmsFile file = cms.readFile(resource);
CmsXmlContent content = getContentDocument(file, true);
checkAutoCorrection(cms, content);
if (lastEditedEntity != null) {
synchronizeLocaleIndependentForEntity(file, content, skipPaths, lastEditedEntity);
}
for (String deleteId : deletedEntities) {
Locale contentLocale = CmsLocaleManager.getLocale(CmsContentDefinition.getLocaleFromId(deleteId));
if (content.hasLocale(contentLocale)) {
content.removeLocale(contentLocale);
}
}
CmsValidationResult validationResult = validateContent(cms, structureId, content);
if (validationResult.hasErrors()) {
return validationResult;
}
writeContent(cms, file, content, getFileEncoding(cms, file));
// update offline indices
OpenCms.getSearchManager().updateOfflineIndexes(2 * CmsSearchManager.DEFAULT_OFFLINE_UPDATE_FREQNENCY);
if (clearOnSuccess) {
tryUnlock(resource);
getSessionCache().uncacheXmlContent(structureId);
}
} catch (Exception e) {
if (resource != null) {
tryUnlock(resource);
getSessionCache().uncacheXmlContent(structureId);
}
error(e);
}
}
return null;
}
/**
* @see org.opencms.acacia.shared.rpc.I_CmsContentService#saveEntities(java.util.List)
*/
public CmsValidationResult saveEntities(List<CmsEntity> entities) {
throw new UnsupportedOperationException();
}
/**
* @see org.opencms.acacia.shared.rpc.I_CmsContentService#saveEntity(org.opencms.acacia.shared.CmsEntity)
*/
public CmsValidationResult saveEntity(CmsEntity entity) {
throw new UnsupportedOperationException();
}
/**
* @see org.opencms.acacia.shared.rpc.I_CmsContentService#updateEntityHtml(org.opencms.acacia.shared.CmsEntity, java.lang.String, java.lang.String)
*/
public CmsEntityHtml updateEntityHtml(CmsEntity entity, String contextUri, String htmlContextInfo) throws Exception {
CmsUUID structureId = CmsContentDefinition.entityIdToUuid(entity.getId());
if (structureId != null) {
CmsObject cms = getCmsObject();
try {
CmsResource resource = cms.readResource(structureId, CmsResourceFilter.IGNORE_EXPIRATION);
CmsFile file = cms.readFile(resource);
CmsXmlContent content = CmsXmlContentFactory.unmarshal(cms, file);
String entityId = entity.getId();
Locale contentLocale = CmsLocaleManager.getLocale(CmsContentDefinition.getLocaleFromId(entityId));
if (content.hasLocale(contentLocale)) {
content.removeLocale(contentLocale);
}
content.addLocale(cms, contentLocale);
addEntityAttributes(cms, content, "", entity, contentLocale);
CmsValidationResult validationResult = validateContent(cms, structureId, content);
String htmlContent = null;
if (!validationResult.hasErrors()) {
file.setContents(content.marshal());
JSONObject contextInfo = new JSONObject(htmlContextInfo);
String containerName = contextInfo.getString(CmsCntPageData.JSONKEY_NAME);
String containerType = contextInfo.getString(CmsCntPageData.JSONKEY_TYPE);
int containerWidth = contextInfo.getInt(CmsCntPageData.JSONKEY_WIDTH);
int maxElements = contextInfo.getInt(CmsCntPageData.JSONKEY_MAXELEMENTS);
boolean detailView = contextInfo.getBoolean(CmsCntPageData.JSONKEY_DETAILVIEW);
CmsContainer container = new CmsContainer(
containerName,
containerType,
null,
containerWidth,
maxElements,
detailView,
true,
Collections.<CmsContainerElement> emptyList(),
null,
null);
CmsUUID detailContentId = null;
if (contextInfo.has(CmsCntPageData.JSONKEY_DETAIL_ELEMENT_ID)) {
detailContentId = new CmsUUID(contextInfo.getString(CmsCntPageData.JSONKEY_DETAIL_ELEMENT_ID));
}
CmsElementUtil elementUtil = new CmsElementUtil(
cms,
contextUri,
detailContentId,
getThreadLocalRequest(),
getThreadLocalResponse(),
contentLocale);
htmlContent = elementUtil.getContentByContainer(
file,
contextInfo.getString(CmsCntPageData.JSONKEY_ELEMENT_ID),
container,
true);
}
return new CmsEntityHtml(htmlContent, validationResult);
} catch (Exception e) {
error(e);
}
}
return null;
}
/**
* @see org.opencms.acacia.shared.rpc.I_CmsContentService#validateEntities(java.util.List)
*/
public CmsValidationResult validateEntities(List<CmsEntity> changedEntities) throws CmsRpcException {
CmsUUID structureId = null;
if (changedEntities.isEmpty()) {
return new CmsValidationResult(null, null);
}
structureId = CmsContentDefinition.entityIdToUuid(changedEntities.get(0).getId());
if (structureId != null) {
CmsObject cms = getCmsObject();
try {
CmsResource resource = cms.readResource(structureId, CmsResourceFilter.IGNORE_EXPIRATION);
CmsFile file = cms.readFile(resource);
CmsXmlContent content = CmsXmlContentFactory.unmarshal(cms, file);
for (CmsEntity entity : changedEntities) {
String entityId = entity.getId();
Locale contentLocale = CmsLocaleManager.getLocale(CmsContentDefinition.getLocaleFromId(entityId));
if (content.hasLocale(contentLocale)) {
content.removeLocale(contentLocale);
}
content.addLocale(cms, contentLocale);
addEntityAttributes(cms, content, "", entity, contentLocale);
}
return validateContent(cms, structureId, content);
} catch (Exception e) {
error(e);
}
}
return new CmsValidationResult(null, null);
}
/**
* Decodes the newlink request parameter if possible.<p>
*
* @param newLink the parameter to decode
*
* @return the decoded value
*/
protected String decodeNewLink(String newLink) {
String result = newLink;
if (result == null) {
return null;
}
try {
result = CmsEncoder.decode(result);
try {
result = CmsEncoder.decode(result);
} catch (Throwable e) {
LOG.info(e.getLocalizedMessage(), e);
}
} catch (Throwable e) {
LOG.info(e.getLocalizedMessage(), e);
}
return result;
}
/**
* Returns the element name to the given element.<p>
*
* @param attributeName the attribute name
*
* @return the element name
*/
protected String getElementName(String attributeName) {
if (attributeName.contains("/")) {
return attributeName.substring(attributeName.lastIndexOf("/") + 1);
}
return attributeName;
}
/**
* Helper method to determine the encoding of the given file in the VFS,
* which must be set using the "content-encoding" property.<p>
*
* @param cms the CmsObject
* @param file the file which is to be checked
* @return the encoding for the file
*/
protected String getFileEncoding(CmsObject cms, CmsResource file) {
String result;
try {
result = cms.readPropertyObject(file, CmsPropertyDefinition.PROPERTY_CONTENT_ENCODING, true).getValue(
OpenCms.getSystemInfo().getDefaultEncoding());
} catch (CmsException e) {
result = OpenCms.getSystemInfo().getDefaultEncoding();
}
return CmsEncoder.lookupEncoding(result, OpenCms.getSystemInfo().getDefaultEncoding());
}
/**
* Parses the element into an entity.<p>
*
* @param content the entity content
* @param element the current element
* @param locale the content locale
* @param entityId the entity id
* @param parentPath the parent path
* @param typeName the entity type name
* @param visitor the content type visitor
* @param includeInvisible include invisible attributes
*
* @return the entity
*/
protected CmsEntity readEntity(
CmsXmlContent content,
Element element,
Locale locale,
String entityId,
String parentPath,
String typeName,
CmsContentTypeVisitor visitor,
boolean includeInvisible) {
String newEntityId = entityId + (CmsStringUtil.isNotEmptyOrWhitespaceOnly(parentPath) ? "/" + parentPath : "");
CmsEntity newEntity = new CmsEntity(newEntityId, typeName);
CmsEntity result = newEntity;
List<Element> elements = element.elements();
CmsType type = visitor.getTypes().get(typeName);
boolean isChoice = type.isChoice();
String choiceTypeName = null;
// just needed for choice attributes
Map<String, Integer> attributeCounter = null;
if (isChoice) {
choiceTypeName = type.getAttributeTypeName(CmsType.CHOICE_ATTRIBUTE_NAME);
type = visitor.getTypes().get(type.getAttributeTypeName(CmsType.CHOICE_ATTRIBUTE_NAME));
attributeCounter = new HashMap<String, Integer>();
}
int counter = 0;
CmsObject cms = getCmsObject();
String previousName = null;
if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(parentPath)) {
parentPath += "/";
}
for (Element child : elements) {
String attributeName = getAttributeName(child.getName(), typeName);
String subTypeName = type.getAttributeTypeName(attributeName);
if (visitor.getTypes().get(subTypeName) == null) {
// in case there is no type configured for this element, the schema may have changed, skip the element
continue;
}
if (!includeInvisible && !visitor.getAttributeConfigurations().get(attributeName).isVisible()) {
// skip attributes marked as invisible, there content should not be transfered to the client
continue;
}
if (isChoice && (attributeCounter != null)) {
if (!attributeName.equals(previousName)) {
if (attributeCounter.get(attributeName) != null) {
counter = attributeCounter.get(attributeName).intValue();
} else {
counter = 0;
}
previousName = attributeName;
}
attributeCounter.put(attributeName, Integer.valueOf(counter + 1));
} else if (!attributeName.equals(previousName)) {
// reset the attribute counter for every attribute name
counter = 0;
previousName = attributeName;
}
if (isChoice) {
result = new CmsEntity(newEntityId
+ "/"
+ CmsType.CHOICE_ATTRIBUTE_NAME
+ "_"
+ child.getName()
+ "["
+ counter
+ "]", choiceTypeName);
newEntity.addAttributeValue(CmsType.CHOICE_ATTRIBUTE_NAME, result);
}
String path = parentPath + child.getName();
if (visitor.getTypes().get(subTypeName).isSimpleType()) {
I_CmsXmlContentValue value = content.getValue(path, locale, counter);
result.addAttributeValue(attributeName, value.getStringValue(cms));
} else {
CmsEntity subEntity = readEntity(
content,
child,
locale,
entityId,
path + "[" + (counter + 1) + "]",
subTypeName,
visitor,
includeInvisible);
result.addAttributeValue(attributeName, subEntity);
}
counter++;
}
return newEntity;
}
/**
* Reads the types from the given content definition and adds the to the map of already registered
* types if necessary.<p>
*
* @param xmlContentDefinition the XML content definition
* @param locale the messages locale
*
* @return the types of the given content definition
*/
protected Map<String, CmsType> readTypes(CmsXmlContentDefinition xmlContentDefinition, Locale locale) {
CmsContentTypeVisitor visitor = new CmsContentTypeVisitor(getCmsObject(), null, locale);
visitor.visitTypes(xmlContentDefinition, locale);
return visitor.getTypes();
}
/**
* Synchronizes the locale independent fields.<p>
*
* @param file the content file
* @param content the XML content
* @param skipPaths the paths to skip during locale synchronization
* @param entities the edited entities
* @param lastEdited the last edited locale
*
* @throws CmsXmlException if something goes wrong
*/
protected void synchronizeLocaleIndependentFields(
CmsFile file,
CmsXmlContent content,
Collection<String> skipPaths,
Collection<CmsEntity> entities,
Locale lastEdited) throws CmsXmlException {
CmsEntity lastEditedEntity = null;
for (CmsEntity entity : entities) {
if (lastEdited.equals(CmsLocaleManager.getLocale(CmsContentDefinition.getLocaleFromId(entity.getId())))) {
lastEditedEntity = entity;
} else {
synchronizeLocaleIndependentForEntity(file, content, skipPaths, entity);
}
}
if (lastEditedEntity != null) {
// prepare the last edited last, to sync locale independent fields
synchronizeLocaleIndependentForEntity(file, content, skipPaths, lastEditedEntity);
}
}
/**
* Transfers values marked as invisible from the original entity to the target entity.<p>
*
* @param original the original entity
* @param target the target entiy
* @param visitor the type visitor holding the content type configuration
*/
protected void transferInvisibleValues(CmsEntity original, CmsEntity target, CmsContentTypeVisitor visitor) {
List<String> invisibleAttributes = new ArrayList<String>();
for (Entry<String, CmsAttributeConfiguration> configEntry : visitor.getAttributeConfigurations().entrySet()) {
if (!configEntry.getValue().isVisible()) {
invisibleAttributes.add(configEntry.getKey());
}
}
CmsContentDefinition.transferValues(
original,
target,
invisibleAttributes,
visitor.getTypes(),
visitor.getAttributeConfigurations(),
true);
}
/**
* Adds the attribute values of the entity to the given XML content.<p>
*
* @param cms the current cms context
* @param content the XML content
* @param parentPath the parent path
* @param entity the entity
* @param contentLocale the content locale
*/
private void addEntityAttributes(
CmsObject cms,
CmsXmlContent content,
String parentPath,
CmsEntity entity,
Locale contentLocale) {
for (CmsEntityAttribute attribute : entity.getAttributes()) {
if (CmsType.CHOICE_ATTRIBUTE_NAME.equals(attribute.getAttributeName())) {
List<CmsEntity> choiceEntities = attribute.getComplexValues();
for (int i = 0; i < choiceEntities.size(); i++) {
List<CmsEntityAttribute> choiceAttributes = choiceEntities.get(i).getAttributes();
// each choice entity may only have a single attribute with a single value
assert (choiceAttributes.size() == 1) && choiceAttributes.get(0).isSingleValue() : "each choice entity may only have a single attribute with a single value";
CmsEntityAttribute choiceAttribute = choiceAttributes.get(0);
String elementPath = parentPath + getElementName(choiceAttribute.getAttributeName());
if (choiceAttribute.isSimpleValue()) {
String value = choiceAttribute.getSimpleValue();
I_CmsXmlContentValue field = content.getValue(elementPath, contentLocale, i);
if (field == null) {
field = content.addValue(cms, elementPath, contentLocale, i);
}
field.setStringValue(cms, value);
} else {
CmsEntity child = choiceAttribute.getComplexValue();
I_CmsXmlContentValue field = content.getValue(elementPath, contentLocale, i);
if (field == null) {
field = content.addValue(cms, elementPath, contentLocale, i);
}
addEntityAttributes(cms, content, field.getPath() + "/", child, contentLocale);
}
}
} else {
String elementPath = parentPath + getElementName(attribute.getAttributeName());
if (attribute.isSimpleValue()) {
List<String> values = attribute.getSimpleValues();
for (int i = 0; i < values.size(); i++) {
String value = values.get(i);
I_CmsXmlContentValue field = content.getValue(elementPath, contentLocale, i);
if (field == null) {
field = content.addValue(cms, elementPath, contentLocale, i);
}
field.setStringValue(cms, value);
}
} else {
List<CmsEntity> entities = attribute.getComplexValues();
for (int i = 0; i < entities.size(); i++) {
CmsEntity child = entities.get(i);
I_CmsXmlContentValue field = content.getValue(elementPath, contentLocale, i);
if (field == null) {
field = content.addValue(cms, elementPath, contentLocale, i);
}
addEntityAttributes(cms, content, field.getPath() + "/", child, contentLocale);
}
}
}
}
}
/**
* Check if automatic content correction is required. Returns <code>true</code> if the content was changed.<p>
*
* @param cms the cms context
* @param content the content to check
*
* @return <code>true</code> if the content was changed
* @throws CmsXmlException if the automatic content correction failed
*/
private boolean checkAutoCorrection(CmsObject cms, CmsXmlContent content) throws CmsXmlException {
boolean performedAutoCorrection = false;
try {
content.validateXmlStructure(new CmsXmlEntityResolver(cms));
} catch (CmsXmlException eXml) {
// validation failed
content.setAutoCorrectionEnabled(true);
content.correctXmlStructure(cms);
performedAutoCorrection = true;
}
return performedAutoCorrection;
}
/**
* Evaluates any wildcards in the given scope and returns all allowed permutations of it.<p>
*
* a path like Paragraph* /Image should result in Paragraph[0]/Image, Paragraph[1]/Image and Paragraph[2]/Image
* in case max occurrence for Paragraph is 3
*
* @param scope the scope
* @param definition the content definition
*
* @return the evaluate scope permutations
*/
private Set<String> evaluateScope(String scope, CmsXmlContentDefinition definition) {
Set<String> evaluatedScopes = new HashSet<String>();
if (scope.contains("*")) {
// evaluate wildcards to get all allowed permutations of the scope
// a path like Paragraph*/Image should result in Paragraph[0]/Image, Paragraph[1]/Image and Paragraph[2]/Image
// in case max occurrence for Paragraph is 3
String[] pathElements = scope.split("/");
String parentPath = "";
for (int i = 0; i < pathElements.length; i++) {
String elementName = pathElements[i];
boolean hasWildCard = elementName.endsWith("*");
if (hasWildCard) {
elementName = elementName.substring(0, elementName.length() - 1);
parentPath = CmsStringUtil.joinPaths(parentPath, elementName);
I_CmsXmlSchemaType type = definition.getSchemaType(parentPath);
Set<String> tempScopes = new HashSet<String>();
if (type.getMaxOccurs() == Integer.MAX_VALUE) {
throw new IllegalStateException(
"Can not use fields with unbounded maxOccurs in scopes for editor change handler.");
}
for (int j = 0; j < type.getMaxOccurs(); j++) {
if (evaluatedScopes.isEmpty()) {
tempScopes.add(elementName + "[" + (j + 1) + "]");
} else {
for (String evScope : evaluatedScopes) {
tempScopes.add(CmsStringUtil.joinPaths(evScope, elementName + "[" + (j + 1) + "]"));
}
}
}
evaluatedScopes = tempScopes;
} else {
parentPath = CmsStringUtil.joinPaths(parentPath, elementName);
Set<String> tempScopes = new HashSet<String>();
if (evaluatedScopes.isEmpty()) {
tempScopes.add(elementName);
} else {
for (String evScope : evaluatedScopes) {
tempScopes.add(CmsStringUtil.joinPaths(evScope, elementName));
}
}
evaluatedScopes = tempScopes;
}
}
} else {
evaluatedScopes.add(scope);
}
return evaluatedScopes;
}
/**
* Evaluates the values of the locale independent fields and the paths to skip during locale synchronization.<p>
*
* @param content the XML content
* @param syncValues the map of synchronization values
* @param skipPaths the list o paths to skip
*/
private void evaluateSyncLocaleValues(
CmsXmlContent content,
Map<String, String> syncValues,
Collection<String> skipPaths) {
CmsObject cms = getCmsObject();
for (Locale locale : content.getLocales()) {
for (String elementPath : content.getContentDefinition().getContentHandler().getSynchronizations()) {
for (I_CmsXmlContentValue contentValue : content.getSimpleValuesBelowPath(elementPath, locale)) {
String valuePath = contentValue.getPath();
boolean skip = false;
for (String skipPath : skipPaths) {
if (valuePath.startsWith(skipPath)) {
skip = true;
break;
}
}
if (!skip) {
String value = contentValue.getStringValue(cms);
if (syncValues.containsKey(valuePath)) {
if (!syncValues.get(valuePath).equals(value)) {
// in case the current value does not match the previously stored value,
// remove it and add the parent path to the skipPaths list
syncValues.remove(valuePath);
int pathLevelDiff = (CmsResource.getPathLevel(valuePath) - CmsResource.getPathLevel(elementPath)) + 1;
for (int i = 0; i < pathLevelDiff; i++) {
valuePath = CmsXmlUtils.removeLastXpathElement(valuePath);
}
skipPaths.add(valuePath);
}
} else {
syncValues.put(valuePath, value);
}
}
}
}
}
}
/**
* Returns the best available locale present in the given XML content, or the default locale.<p>
*
* @param resource the resource
* @param content the XML content
*
* @return the locale
*/
private Locale getBestAvailableLocale(CmsResource resource, CmsXmlContent content) {
CmsObject cms = getCmsObject();
Locale locale = OpenCms.getLocaleManager().getDefaultLocale(getCmsObject(), resource);
if (!content.hasLocale(locale)) {
// if the requested locale is not available, get the first matching default locale,
// or the first matching available locale
boolean foundLocale = false;
if (content.getLocales().size() > 0) {
List<Locale> locales = OpenCms.getLocaleManager().getDefaultLocales(cms, resource);
for (Locale defaultLocale : locales) {
if (content.hasLocale(defaultLocale)) {
locale = defaultLocale;
foundLocale = true;
break;
}
}
if (!foundLocale) {
locales = OpenCms.getLocaleManager().getAvailableLocales(cms, resource);
for (Locale availableLocale : locales) {
if (content.hasLocale(availableLocale)) {
locale = availableLocale;
foundLocale = true;
break;
}
}
}
}
}
return locale;
}
/**
* Returns the change handler scopes.<p>
*
* @param definition the content definition
*
* @return the scopes
*/
private Set<String> getChangeHandlerScopes(CmsXmlContentDefinition definition) {
List<I_CmsXmlContentEditorChangeHandler> changeHandlers = definition.getContentHandler().getEditorChangeHandlers();
Set<String> scopes = new HashSet<String>();
for (I_CmsXmlContentEditorChangeHandler handler : changeHandlers) {
String scope = handler.getScope();
scopes.addAll(evaluateScope(scope, definition));
}
return scopes;
}
/**
* Returns the XML content document.<p>
*
* @param file the resource file
* @param fromCache <code>true</code> to use the cached document
*
* @return the content document
*
* @throws CmsXmlException if reading the XML fails
*/
private CmsXmlContent getContentDocument(CmsFile file, boolean fromCache) throws CmsXmlException {
CmsXmlContent content;
if (fromCache) {
content = getSessionCache().getCacheXmlContent(file.getStructureId());
} else {
content = CmsXmlContentFactory.unmarshal(getCmsObject(), file);
getSessionCache().setCacheXmlContent(file.getStructureId(), content);
}
return content;
}
/**
* Returns the path elements for the given content value.<p>
*
* @param content the XML content
* @param value the content value
*
* @return the path elements
*/
private String[] getPathElements(CmsXmlContent content, I_CmsXmlContentValue value) {
List<String> pathElements = new ArrayList<String>();
String[] paths = value.getPath().split("/");
String path = "";
for (int i = 0; i < paths.length; i++) {
path += paths[i];
I_CmsXmlContentValue ancestor = content.getValue(path, value.getLocale());
int valueIndex = ancestor.getXmlIndex();
if (ancestor.isChoiceOption()) {
Element parent = ancestor.getElement().getParent();
valueIndex = parent.indexOf(ancestor.getElement());
}
String pathElement = getAttributeName(ancestor.getName(), getTypeUri(ancestor.getContentDefinition()));
pathElements.add(pathElement + "[" + valueIndex + "]");
path += "/";
}
return pathElements.toArray(new String[pathElements.size()]);
}
/**
* Returns the session cache.<p>
*
* @return the session cache
*/
private CmsADESessionCache getSessionCache() {
if (m_sessionCache == null) {
m_sessionCache = CmsADESessionCache.getCache(getRequest(), getCmsObject());
}
return m_sessionCache;
}
/**
* Returns the workplace locale.<p>
*
* @param cms the current OpenCms context
*
* @return the current users workplace locale
*/
private Locale getWorkplaceLocale(CmsObject cms) {
if (m_workplaceLocale == null) {
m_workplaceLocale = OpenCms.getWorkplaceManager().getWorkplaceLocale(cms);
}
return m_workplaceLocale;
}
/**
* Reads the content definition for the given resource and locale.<p>
*
* @param file the resource file
* @param content the XML content
* @param entityId the entity id
* @param locale the content locale
* @param newLocale if the locale content should be created as new
*
* @return the content definition
*
* @throws CmsException if something goes wrong
*/
private CmsContentDefinition readContentDefinition(
CmsFile file,
CmsXmlContent content,
String entityId,
Locale locale,
boolean newLocale) throws CmsException {
long timer = 0;
if (LOG.isDebugEnabled()) {
timer = System.currentTimeMillis();
}
CmsObject cms = getCmsObject();
List<Locale> availableLocalesList = OpenCms.getLocaleManager().getAvailableLocales(cms, file);
if (!availableLocalesList.contains(locale)) {
availableLocalesList.retainAll(content.getLocales());
List<Locale> defaultLocales = OpenCms.getLocaleManager().getDefaultLocales(cms, file);
Locale replacementLocale = OpenCms.getLocaleManager().getBestMatchingLocale(
locale,
defaultLocales,
availableLocalesList);
LOG.info("Can't edit locale "
+ locale
+ " of file "
+ file.getRootPath()
+ " because it is not configured as available locale. Using locale "
+ replacementLocale
+ " instead.");
locale = replacementLocale;
entityId = CmsContentDefinition.uuidToEntityId(file.getStructureId(), locale.toString());
}
if (CmsStringUtil.isEmptyOrWhitespaceOnly(entityId)) {
entityId = CmsContentDefinition.uuidToEntityId(file.getStructureId(), locale.toString());
}
boolean performedAutoCorrection = checkAutoCorrection(cms, content);
if (performedAutoCorrection) {
content.initDocument();
}
if (LOG.isDebugEnabled()) {
LOG.debug(Messages.get().getBundle().key(
Messages.LOG_TAKE_UNMARSHALING_TIME_1,
"" + (System.currentTimeMillis() - timer)));
}
CmsContentTypeVisitor visitor = new CmsContentTypeVisitor(cms, file, locale);
if (LOG.isDebugEnabled()) {
timer = System.currentTimeMillis();
}
visitor.visitTypes(content.getContentDefinition(), getWorkplaceLocale(cms));
if (LOG.isDebugEnabled()) {
LOG.debug(Messages.get().getBundle().key(
Messages.LOG_TAKE_VISITING_TYPES_TIME_1,
"" + (System.currentTimeMillis() - timer)));
}
CmsEntity entity = null;
Map<String, String> syncValues = new HashMap<String, String>();
Collection<String> skipPaths = new HashSet<String>();
evaluateSyncLocaleValues(content, syncValues, skipPaths);
if (content.hasLocale(locale) && newLocale) {
// a new locale is requested, so remove the present one
content.removeLocale(locale);
}
if (!content.hasLocale(locale)) {
content.addLocale(cms, locale);
// sync the locale values
if (!visitor.getLocaleSynchronizations().isEmpty() && (content.getLocales().size() > 1)) {
for (Locale contentLocale : content.getLocales()) {
if (!contentLocale.equals(locale)) {
content.synchronizeLocaleIndependentValues(cms, skipPaths, contentLocale);
}
}
}
}
Element element = content.getLocaleNode(locale);
if (LOG.isDebugEnabled()) {
timer = System.currentTimeMillis();
}
entity = readEntity(
content,
element,
locale,
entityId,
"",
getTypeUri(content.getContentDefinition()),
visitor,
false);
if (LOG.isDebugEnabled()) {
LOG.debug(Messages.get().getBundle().key(
Messages.LOG_TAKE_READING_ENTITY_TIME_1,
"" + (System.currentTimeMillis() - timer)));
}
List<String> contentLocales = new ArrayList<String>();
for (Locale contentLocale : content.getLocales()) {
contentLocales.add(contentLocale.toString());
}
Locale workplaceLocale = OpenCms.getWorkplaceManager().getWorkplaceLocale(cms);
TreeMap<String, String> availableLocales = new TreeMap<String, String>();
for (Locale availableLocale : OpenCms.getLocaleManager().getAvailableLocales(cms, file)) {
availableLocales.put(availableLocale.toString(), availableLocale.getDisplayName(workplaceLocale));
}
String title = cms.readPropertyObject(file, CmsPropertyDefinition.PROPERTY_TITLE, false).getValue();
try {
CmsGallerySearchResult searchResult = CmsGallerySearch.searchById(cms, file.getStructureId(), locale);
title = searchResult.getTitle();
} catch (CmsException e) {
LOG.warn(e.getLocalizedMessage(), e);
}
String typeName = OpenCms.getResourceManager().getResourceType(file.getTypeId()).getTypeName();
boolean autoUnlock = OpenCms.getWorkplaceManager().shouldAcaciaUnlock();
Map<String, CmsEntity> entities = new HashMap<String, CmsEntity>();
entities.put(entityId, entity);
return new CmsContentDefinition(
entityId,
entities,
visitor.getAttributeConfigurations(),
visitor.getWidgetConfigurations(),
visitor.getComplexWidgetData(),
visitor.getTypes(),
visitor.getTabInfos(),
locale.toString(),
contentLocales,
availableLocales,
visitor.getLocaleSynchronizations(),
syncValues,
skipPaths,
title,
cms.getSitePath(file),
typeName,
performedAutoCorrection,
autoUnlock,
getChangeHandlerScopes(content.getContentDefinition()));
}
/**
* Creates a new resource according to the new link, or returns the model file informations
* modelFileId is <code>null</code> but required.<p>
*
* @param newLink the new link
* @param referenceResource the reference resource
* @param modelFileId the model file structure id
* @param locale the content locale
* @param mode the content creation mode
* @param postCreateHandler the class name for the post-create handler
*
* @return the content definition
*
* @throws CmsException if creating the resource failed
*/
private CmsContentDefinition readContentDefnitionForNew(
String newLink,
CmsResource referenceResource,
CmsUUID modelFileId,
Locale locale,
String mode,
String postCreateHandler) throws CmsException {
String sitePath = getCmsObject().getSitePath(referenceResource);
String resourceType = OpenCms.getResourceManager().getResourceType(referenceResource.getTypeId()).getTypeName();
String modelFile = null;
if (modelFileId == null) {
List<CmsResource> modelResources = CmsNewResourceXmlContent.getModelFiles(
getCmsObject(),
CmsResource.getFolderPath(sitePath),
resourceType);
if (!modelResources.isEmpty()) {
List<CmsModelResourceInfo> modelInfos = CmsContainerpageService.generateModelResourceList(
getCmsObject(),
resourceType,
modelResources,
locale);
return new CmsContentDefinition(
modelInfos,
newLink,
referenceResource.getStructureId(),
locale.toString());
}
} else if (!modelFileId.isNullUUID()) {
modelFile = getCmsObject().getSitePath(
getCmsObject().readResource(modelFileId, CmsResourceFilter.IGNORE_EXPIRATION));
}
String newFileName = A_CmsResourceCollector.createResourceForCollector(
getCmsObject(),
newLink,
locale,
sitePath,
modelFile,
mode,
postCreateHandler);
CmsResource resource = getCmsObject().readResource(newFileName, CmsResourceFilter.IGNORE_EXPIRATION);
CmsFile file = getCmsObject().readFile(resource);
CmsXmlContent content = getContentDocument(file, false);
CmsContentDefinition contentDefinition = readContentDefinition(file, content, null, locale, false);
contentDefinition.setDeleteOnCancel(true);
return contentDefinition;
}
/**
* Synchronizes the locale independent fields for the given entity.<p>
*
* @param file the content file
* @param content the XML content
* @param skipPaths the paths to skip during locale synchronization
* @param entity the entity
*
* @throws CmsXmlException if something goes wrong
*/
private void synchronizeLocaleIndependentForEntity(
CmsFile file,
CmsXmlContent content,
Collection<String> skipPaths,
CmsEntity entity) throws CmsXmlException {
CmsObject cms = getCmsObject();
String entityId = entity.getId();
Locale contentLocale = CmsLocaleManager.getLocale(CmsContentDefinition.getLocaleFromId(entityId));
CmsContentTypeVisitor visitor = null;
CmsEntity originalEntity = null;
if (content.getHandler().hasVisibilityHandlers()) {
visitor = new CmsContentTypeVisitor(cms, file, contentLocale);
visitor.visitTypes(content.getContentDefinition(), getWorkplaceLocale(cms));
}
if (content.hasLocale(contentLocale)) {
if ((visitor != null) && visitor.hasInvisibleFields()) {
// we need to add invisible content values to the entity before saving
Element element = content.getLocaleNode(contentLocale);
originalEntity = readEntity(
content,
element,
contentLocale,
entityId,
"",
getTypeUri(content.getContentDefinition()),
visitor,
true);
}
content.removeLocale(contentLocale);
}
content.addLocale(cms, contentLocale);
if ((visitor != null) && visitor.hasInvisibleFields()) {
transferInvisibleValues(originalEntity, entity, visitor);
}
addEntityAttributes(cms, content, "", entity, contentLocale);
content.synchronizeLocaleIndependentValues(cms, skipPaths, contentLocale);
}
/**
* Validates the given XML content.<p>
*
* @param cms the cms context
* @param structureId the structure id
* @param content the XML content
*
* @return the validation result
*/
private CmsValidationResult validateContent(CmsObject cms, CmsUUID structureId, CmsXmlContent content) {
CmsXmlContentErrorHandler errorHandler = content.validate(cms);
Map<String, Map<String[], String>> errorsByEntity = new HashMap<String, Map<String[], String>>();
if (errorHandler.hasErrors()) {
for (Entry<Locale, Map<String, String>> localeEntry : errorHandler.getErrors().entrySet()) {
Map<String[], String> errors = new HashMap<String[], String>();
for (Entry<String, String> error : localeEntry.getValue().entrySet()) {
I_CmsXmlContentValue value = content.getValue(error.getKey(), localeEntry.getKey());
errors.put(getPathElements(content, value), error.getValue());
}
errorsByEntity.put(
CmsContentDefinition.uuidToEntityId(structureId, localeEntry.getKey().toString()),
errors);
}
}
Map<String, Map<String[], String>> warningsByEntity = new HashMap<String, Map<String[], String>>();
if (errorHandler.hasWarnings()) {
for (Entry<Locale, Map<String, String>> localeEntry : errorHandler.getWarnings().entrySet()) {
Map<String[], String> warnings = new HashMap<String[], String>();
for (Entry<String, String> warning : localeEntry.getValue().entrySet()) {
I_CmsXmlContentValue value = content.getValue(warning.getKey(), localeEntry.getKey());
warnings.put(getPathElements(content, value), warning.getValue());
}
warningsByEntity.put(
CmsContentDefinition.uuidToEntityId(structureId, localeEntry.getKey().toString()),
warnings);
}
}
return new CmsValidationResult(errorsByEntity, warningsByEntity);
}
/**
* Writes the xml content to the vfs and re-initializes the member variables.<p>
*
* @param cms the cms context
* @param file the file to write to
* @param content the content
* @param encoding the file encoding
*
* @return the content
*
* @throws CmsException if writing the file fails
*/
private CmsXmlContent writeContent(CmsObject cms, CmsFile file, CmsXmlContent content, String encoding)
throws CmsException {
String decodedContent = content.toString();
try {
file.setContents(decodedContent.getBytes(encoding));
} catch (UnsupportedEncodingException e) {
throw new CmsException(org.opencms.workplace.editors.Messages.get().container(
org.opencms.workplace.editors.Messages.ERR_INVALID_CONTENT_ENC_1,
file.getRootPath()), e);
}
// the file content might have been modified during the write operation
file = cms.writeFile(file);
return CmsXmlContentFactory.unmarshal(cms, file);
}
}
|
package jadx.gui.ui.codearea;
import java.util.Set;
import javax.swing.text.Segment;
import org.fife.ui.rsyntaxtextarea.Token;
import org.fife.ui.rsyntaxtextarea.TokenImpl;
import org.fife.ui.rsyntaxtextarea.TokenTypes;
import org.fife.ui.rsyntaxtextarea.modes.JavaTokenMaker;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import jadx.api.JavaClass;
import jadx.api.JavaNode;
import static jadx.api.plugins.utils.Utils.constSet;
public final class JadxTokenMaker extends JavaTokenMaker {
private static final Logger LOG = LoggerFactory.getLogger(JadxTokenMaker.class);
private final CodeArea codeArea;
public JadxTokenMaker(CodeArea codeArea) {
this.codeArea = codeArea;
}
@Override
public Token getTokenList(Segment text, int initialTokenType, int startOffset) {
Token tokens = super.getTokenList(text, initialTokenType, startOffset);
if (tokens.getType() != TokenTypes.NULL) {
try {
processTokens(tokens);
} catch (Exception e) {
LOG.error("Process tokens failed for text: {}", text, e);
}
}
return tokens;
}
private void processTokens(Token tokens) {
Token prev = null;
Token current = tokens;
while (current != null) {
if (prev != null) {
switch (current.getType()) {
case TokenTypes.RESERVED_WORD:
fixContextualKeyword(current);
break;
case TokenTypes.IDENTIFIER:
current = mergeLongClassNames(prev, current, false);
break;
case TokenTypes.ANNOTATION:
current = mergeLongClassNames(prev, current, true);
break;
}
}
prev = current;
current = current.getNextToken();
}
}
private static final Set<String> CONTEXTUAL_KEYWORDS = constSet(
"exports", "module", "non-sealed", "open", "opens", "permits", "provides", "record",
"requires", "sealed", "to", "transitive", "uses", "var", "with", "yield");
private static void fixContextualKeyword(Token token) {
String lexeme = token.getLexeme(); // TODO: create new string every call, better to avoid
if (lexeme != null && CONTEXTUAL_KEYWORDS.contains(lexeme)) {
token.setType(TokenTypes.IDENTIFIER);
}
}
@NotNull
private Token mergeLongClassNames(Token prev, Token current, boolean annotation) {
int offset = current.getTextOffset();
if (annotation) {
offset++;
}
JavaNode javaNode = codeArea.getJavaNodeAtOffset(offset);
if (javaNode instanceof JavaClass) {
String name = javaNode.getName();
String lexeme = current.getLexeme();
if (annotation && lexeme.length() > 1) {
lexeme = lexeme.substring(1);
}
if (!lexeme.equals(name) && isClassNameStart(javaNode, lexeme)) {
// try to replace long class name with one token
Token replace = concatTokensUntil(current, name);
if (replace != null && prev instanceof TokenImpl) {
TokenImpl impl = ((TokenImpl) prev);
impl.setNextToken(replace);
current = replace;
}
}
}
return current;
}
private boolean isClassNameStart(JavaNode javaNode, String lexeme) {
if (javaNode.getFullName().startsWith(lexeme)) {
// full class name
return true;
}
if (javaNode.getTopParentClass().getName().startsWith(lexeme)) {
// inner class references from parent class
return true;
}
return false;
}
@Nullable
private Token concatTokensUntil(Token start, String endText) {
StringBuilder sb = new StringBuilder();
Token current = start;
while (current != null && current.getType() != TokenTypes.NULL) {
String text = current.getLexeme();
if (text != null) {
sb.append(text);
if (text.equals(endText)) {
char[] line = sb.toString().toCharArray();
TokenImpl token = new TokenImpl(line, 0, line.length - 1, start.getOffset(),
start.getType(), start.getLanguageIndex());
token.setNextToken(current.getNextToken());
return token;
}
}
current = current.getNextToken();
}
return null;
}
}
|
package org.testng.reporters;
import org.testng.IInvokedMethod;
import org.testng.IReporter;
import org.testng.IResultMap;
import org.testng.ISuite;
import org.testng.ISuiteResult;
import org.testng.ITestClass;
import org.testng.ITestContext;
import org.testng.ITestNGMethod;
import org.testng.ITestResult;
import org.testng.Reporter;
import org.testng.collections.Lists;
import org.testng.internal.Utils;
import org.testng.log4testng.Logger;
import org.testng.reporters.util.StackTraceTools;
import org.testng.xml.XmlSuite;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.Arrays;
import java.util.Collection;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* Reported designed to render self-contained HTML top down view of a testing
* suite.
*
* @author Paul Mendelson
* @since 5.2
* @version $Revision: 719 $
*/
public class EmailableReporter implements IReporter {
private static final Logger L = Logger.getLogger(EmailableReporter.class);
private PrintWriter m_out;
private int m_row;
private int m_methodIndex;
private int m_rowTotal;
/** Creates summary of the run */
@Override
public void generateReport(List<XmlSuite> xml, List<ISuite> suites, String outdir) {
try {
m_out = createWriter(outdir);
}
catch (IOException e) {
L.error("output file", e);
return;
}
startHtml(m_out);
generateSuiteSummaryReport(suites);
generateMethodSummaryReport(suites);
generateMethodDetailReport(suites);
endHtml(m_out);
m_out.flush();
m_out.close();
}
protected PrintWriter createWriter(String outdir) throws IOException {
new File(outdir).mkdirs();
return new PrintWriter(new BufferedWriter(new FileWriter(new File(outdir,
"emailable-report.html"))));
}
/** Creates a table showing the highlights of each test method with links to the method details */
protected void generateMethodSummaryReport(List<ISuite> suites) {
m_methodIndex = 0;
startResultSummaryTable("passed");
for (ISuite suite : suites) {
if(suites.size()>1) {
titleRow(suite.getName(), 4);
}
Map<String, ISuiteResult> r = suite.getResults();
for (ISuiteResult r2 : r.values()) {
ITestContext testContext = r2.getTestContext();
String testName = testContext.getName();
resultSummary(suite, testContext.getFailedConfigurations(), testName,
"failed", " (configuration methods)");
resultSummary(suite, testContext.getFailedTests(), testName, "failed",
"");
resultSummary(suite, testContext.getSkippedConfigurations(), testName,
"skipped", " (configuration methods)");
resultSummary(suite, testContext.getSkippedTests(), testName,
"skipped", "");
resultSummary(suite, testContext.getPassedTests(), testName, "passed",
"");
}
}
m_out.println("</table>");
}
/** Creates a section showing known results for each method */
protected void generateMethodDetailReport(List<ISuite> suites) {
m_methodIndex = 0;
for (ISuite suite : suites) {
Map<String, ISuiteResult> r = suite.getResults();
for (ISuiteResult r2 : r.values()) {
ITestContext testContext = r2.getTestContext();
if (r.values().size() > 0) {
m_out.println("<h1>" + testContext.getName() + "</h1>");
}
resultDetail(testContext.getFailedConfigurations());
resultDetail(testContext.getFailedTests());
resultDetail(testContext.getSkippedConfigurations());
resultDetail(testContext.getSkippedTests());
resultDetail(testContext.getPassedTests());
}
}
}
/**
* @param tests
*/
private void resultSummary(ISuite suite, IResultMap tests, String testname, String style,
String details) {
if (tests.getAllResults().size() > 0) {
StringBuffer buff = new StringBuffer();
String lastClassName = "";
int mq = 0;
int cq = 0;
for (ITestNGMethod method : getMethodSet(tests, suite)) {
m_row += 1;
m_methodIndex += 1;
ITestClass testClass = method.getTestClass();
String className = testClass.getName();
if (mq == 0) {
titleRow(testname + " — " + style + details, 4);
}
if (!className.equalsIgnoreCase(lastClassName)) {
if (mq > 0) {
cq += 1;
m_out.println("<tr class=\"" + style
+ (cq % 2 == 0 ? "even" : "odd") + "\">" + "<td rowspan=\""
+ mq + "\">" + lastClassName + "</td>" + buff);
}
mq = 0;
buff.setLength(0);
lastClassName = className;
}
Set<ITestResult> resultSet = tests.getResults(method);
long end = Long.MIN_VALUE;
long start = Long.MAX_VALUE;
for (ITestResult testResult : tests.getResults(method)) {
if (testResult.getEndMillis() > end) {
end = testResult.getEndMillis();
}
if (testResult.getStartMillis() < start) {
start = testResult.getStartMillis();
}
}
mq += 1;
if (mq > 1) {
buff.append("<tr class=\"" + style + (cq % 2 == 0 ? "odd" : "even")
+ "\">");
}
String description = method.getDescription();
String testInstanceName = resultSet.toArray(new ITestResult[]{})[0].getTestName();
buff.append("<td><a href=\"#m" + m_methodIndex + "\">"
+ qualifiedName(method)
+ " " + (description != null && description.length() > 0
? "(\"" + description + "\")"
: "")
+ "</a>" + (null == testInstanceName ? "" : "<br>(" + testInstanceName + ")")
+ "</td>"
+ "<td class=\"numi\">" + resultSet.size() + "</td>"
+ "<td>" + start + "</td>"
+ "<td class=\"numi\">" + (end - start) + "</td>"
+ "</tr>");
}
if (mq > 0) {
cq += 1;
m_out.println("<tr class=\"" + style + (cq % 2 == 0 ? "even" : "odd")
+ "\">" + "<td rowspan=\"" + mq + "\">" + lastClassName + "</td>" + buff);
}
}
}
/** Starts and defines columns result summary table */
private void startResultSummaryTable(String style) {
tableStart(style, "summary");
m_out.println("<tr><th>Class</th>"
+ "<th>Method</th><th># of<br/>Scenarios</th><th>Start</th><th>Time<br/>(ms)</th></tr>");
m_row = 0;
}
private String qualifiedName(ITestNGMethod method) {
StringBuilder addon = new StringBuilder();
String[] groups = method.getGroups();
int length = groups.length;
if (length > 0 && !"basic".equalsIgnoreCase(groups[0])) {
addon.append("(");
for (int i = 0; i < length; i++) {
if (i > 0) {
addon.append(", ");
}
addon.append(groups[i]);
}
addon.append(")");
}
return "<b>" + method.getMethodName() + "</b> " + addon;
}
private void resultDetail(IResultMap tests) {
for (ITestResult result : tests.getAllResults()) {
ITestNGMethod method = result.getMethod();
m_methodIndex++;
String cname = method.getTestClass().getName();
m_out.println("<h2 id=\"m" + m_methodIndex + "\">" + cname + ":"
+ method.getMethodName() + "</h2>");
Set<ITestResult> resultSet = tests.getResults(method);
generateForResult(result, method, resultSet.size());
m_out.println("<p class=\"totop\"><a href=\"#summary\">back to summary</a></p>");
}
}
private void generateForResult(ITestResult ans, ITestNGMethod method, int resultSetSize) {
Object[] parameters = ans.getParameters();
boolean hasParameters = parameters != null && parameters.length > 0;
if (hasParameters) {
tableStart("param", null);
m_out.print("<tr>");
for (int x = 1; x <= parameters.length; x++) {
m_out
.print("<th style=\"padding-left:1em;padding-right:1em\">Parameter
+ x + "</th>");
}
m_out.println("</tr>");
m_out.print("<tr class=\"stripe\">");
for (Object p : parameters) {
m_out.println("<td style=\"padding-left:.5em;padding-right:2em\">"
+ toString(p) + "</td>");
}
m_out.println("</tr>");
}
List<String> msgs = Reporter.getOutput(ans);
boolean hasReporterOutput = msgs.size() > 0;
Throwable exception=ans.getThrowable();
boolean hasThrowable = exception!=null;
if (hasReporterOutput||hasThrowable) {
String indent = " style=\"padding-left:3em\"";
if (hasParameters) {
m_out.println("<tr><td" + indent + " colspan=\"" + parameters.length + "\">");
}
else {
m_out.println("<div" + indent + ">");
}
if (hasReporterOutput) {
if(hasThrowable) {
m_out.println("<h3>Test Messages</h3>");
}
for (String line : msgs) {
m_out.println(line + "<br/>");
}
}
if(hasThrowable) {
boolean wantsMinimalOutput = ans.getStatus()==ITestResult.SUCCESS;
if(hasReporterOutput) {
m_out.println("<h3>"
+(wantsMinimalOutput?"Expected Exception":"Failure")
+"</h3>");
}
generateExceptionReport(exception,method);
}
if (hasParameters) {
m_out.println("</td></tr>");
}
else {
m_out.println("</div>");
}
}
if (hasParameters) {
m_out.println("</table>");
}
}
protected void generateExceptionReport(Throwable exception,ITestNGMethod method) {
generateExceptionReport(exception, method, exception.getLocalizedMessage());
}
private void generateExceptionReport(Throwable exception,ITestNGMethod method,String title) {
m_out.println("<p>" + Utils.escapeHtml(title) + "</p>");
StackTraceElement[] s1= exception.getStackTrace();
Throwable t2= exception.getCause();
if(t2 == exception) {
t2= null;
}
int maxlines= Math.min(100,StackTraceTools.getTestRoot(s1, method));
for(int x= 0; x <= maxlines; x++) {
m_out.println((x>0 ? "<br/>at " : "") + Utils.escapeHtml(s1[x].toString()));
}
if(maxlines < s1.length) {
m_out.println("<br/>" + (s1.length-maxlines) + " lines not shown");
}
if(t2 != null) {
generateExceptionReport(t2, method, "Caused by " + t2.getLocalizedMessage());
}
}
/**
* Since the methods will be sorted chronologically, we want to return
* the ITestNGMethod from the invoked methods.
*/
private Collection<ITestNGMethod> getMethodSet(IResultMap tests, ISuite suite) {
List<IInvokedMethod> r = Lists.newArrayList();
List<IInvokedMethod> invokedMethods = suite.getAllInvokedMethods();
for (IInvokedMethod im : invokedMethods) {
if (tests.getAllMethods().contains(im.getTestMethod())) {
r.add(im);
}
}
Arrays.sort(r.toArray(new IInvokedMethod[r.size()]), new TestSorter());
List<ITestNGMethod> result = Lists.newArrayList();
// Add all the invoked methods
for (IInvokedMethod m : r) {
result.add(m.getTestMethod());
}
// Add all the methods that weren't invoked (e.g. skipped) that we
// haven't added yet
for (ITestNGMethod m : tests.getAllMethods()) {
if (!result.contains(m)) {
result.add(m);
}
}
return result;
}
public void generateSuiteSummaryReport(List<ISuite> suites) {
tableStart("param", null);
m_out.print("<tr><th>Test</th>");
tableColumnStart("Methods<br/>Passed");
tableColumnStart("Scenarios<br/>Passed");
tableColumnStart("# skipped");
tableColumnStart("# failed");
tableColumnStart("Total<br/>Time");
tableColumnStart("Included<br/>Groups");
tableColumnStart("Excluded<br/>Groups");
m_out.println("</tr>");
NumberFormat formatter = new DecimalFormat("
int qty_tests = 0;
int qty_pass_m = 0;
int qty_pass_s = 0;
int qty_skip = 0;
int qty_fail = 0;
long time_start = Long.MAX_VALUE;
long time_end = Long.MIN_VALUE;
for (ISuite suite : suites) {
if (suites.size() > 1) {
titleRow(suite.getName(), 7);
}
Map<String, ISuiteResult> tests = suite.getResults();
for (ISuiteResult r : tests.values()) {
qty_tests += 1;
ITestContext overview = r.getTestContext();
startSummaryRow(overview.getName());
int q = getMethodSet(overview.getPassedTests(), suite).size();
qty_pass_m += q;
summaryCell(q,Integer.MAX_VALUE);
q = overview.getPassedTests().size();
qty_pass_s += q;
summaryCell(q,Integer.MAX_VALUE);
q = getMethodSet(overview.getSkippedTests(), suite).size();
qty_skip += q;
summaryCell(q,0);
q = getMethodSet(overview.getFailedTests(), suite).size();
qty_fail += q;
summaryCell(q,0);
time_start = Math.min(overview.getStartDate().getTime(), time_start);
time_end = Math.max(overview.getEndDate().getTime(), time_end);
summaryCell(formatter.format(
(overview.getEndDate().getTime() - overview.getStartDate().getTime()) / 1000.)
+ " seconds", true);
summaryCell(overview.getIncludedGroups());
summaryCell(overview.getExcludedGroups());
m_out.println("</tr>");
}
}
if (qty_tests > 1) {
m_out.println("<tr class=\"total\"><td>Total</td>");
summaryCell(qty_pass_m,Integer.MAX_VALUE);
summaryCell(qty_pass_s,Integer.MAX_VALUE);
summaryCell(qty_skip,0);
summaryCell(qty_fail,0);
summaryCell(formatter.format((time_end - time_start) / 1000.) + " seconds", true);
m_out.println("<td colspan=\"2\"> </td></tr>");
}
m_out.println("</table>");
}
private void summaryCell(String[] val) {
StringBuffer b = new StringBuffer();
for (String v : val) {
b.append(v + " ");
}
summaryCell(b.toString(),true);
}
private void summaryCell(String v,boolean isgood) {
m_out.print("<td class=\"numi"+(isgood?"":"_attn")+"\">" + v + "</td>");
}
private void startSummaryRow(String label) {
m_row += 1;
m_out.print("<tr" + (m_row % 2 == 0 ? " class=\"stripe\"" : "")
+ "><td style=\"text-align:left;padding-right:2em\">" + label
+ "</td>");
}
private void summaryCell(int v,int maxexpected) {
summaryCell(String.valueOf(v),v<=maxexpected);
m_rowTotal += v;
}
private void tableStart(String cssclass, String id) {
m_out.println("<table cellspacing=\"0\" cellpadding=\"0\""
+ (cssclass != null ? " class=\"" + cssclass + "\""
: " style=\"padding-bottom:2em\"")
+ (id != null ? " id=\"" + id + "\"" : "")
+ ">");
m_row = 0;
}
private void tableColumnStart(String label) {
m_out.print("<th class=\"numi\">" + label + "</th>");
}
private void titleRow(String label, int cq) {
m_out.println("<tr><th colspan=\"" + cq + "\">" + label + "</th></tr>");
m_row = 0;
}
String toString(Object obj) {
String result;
if (obj != null) {
if( obj instanceof boolean[] ) {
result = Arrays.toString((boolean[])obj);
}
else if( obj instanceof byte[] ) {
result = Arrays.toString((byte[])obj);
}
else if( obj instanceof char[] ) {
result = Arrays.toString((char[])obj);
}
else if( obj instanceof double[] ) {
result = Arrays.toString((double[])obj);
}
else if( obj instanceof float[] ) {
result = Arrays.toString((float[])obj);
}
else if( obj instanceof int[] ) {
result = Arrays.toString((int[])obj);
}
else if( obj instanceof long[] ) {
result = Arrays.toString((long[])obj);
}
else if( obj instanceof Object[] ) {
result = Arrays.deepToString((Object[])obj);
}
else if( obj instanceof short[] ) {
result = Arrays.toString((short[])obj);
}
else {
result = obj.toString();
}
} else {
result = "null";
}
return Utils.escapeHtml(result);
}
protected void writeStyle(String[] formats,String[] targets) {
}
/** Starts HTML stream */
protected void startHtml(PrintWriter out) {
out.println("<!DOCTYPE html PUBLIC \"-
out.println("<html xmlns=\"http:
out.println("<head>");
out.println("<title>TestNG: Unit Test</title>");
out.println("<style type=\"text/css\">");
out.println("table caption,table.info_table,table.param,table.passed,table.failed {margin-bottom:10px;border:1px solid #000099;border-collapse:collapse;empty-cells:show;}");
out.println("table.info_table td,table.info_table th,table.param td,table.param th,table.passed td,table.passed th,table.failed td,table.failed th {");
out.println("border:1px solid #000099;padding:.25em .5em .25em .5em");
out.println("}");
out.println("table.param th {vertical-align:bottom}");
out.println("td.numi,th.numi,td.numi_attn {");
out.println("text-align:right");
out.println("}");
out.println("tr.total td {font-weight:bold}");
out.println("table caption {");
out.println("text-align:center;font-weight:bold;");
out.println("}");
out.println("table.passed tr.stripe td,table tr.passedodd td {background-color: #00AA00;}");
out.println("table.passed td,table tr.passedeven td {background-color: #33FF33;}");
out.println("table.passed tr.stripe td,table tr.skippedodd td {background-color: #cccccc;}");
out.println("table.passed td,table tr.skippedodd td {background-color: #dddddd;}");
out.println("table.failed tr.stripe td,table tr.failedodd td,table.param td.numi_attn {background-color: #FF3333;}");
out.println("table.failed td,table tr.failedeven td,table.param tr.stripe td.numi_attn {background-color: #DD0000;}");
out.println("tr.stripe td,tr.stripe th {background-color: #E6EBF9;}");
out.println("p.totop {font-size:85%;text-align:center;border-bottom:2px black solid}");
out.println("div.shootout {padding:2em;border:3px #4854A8 solid}");
out.println("</style>");
out.println("</head>");
out.println("<body>");
}
/** Finishes HTML stream */
protected void endHtml(PrintWriter out) {
out.println("</body></html>");
}
/** Arranges methods by classname and method name */
private class TestSorter implements Comparator<IInvokedMethod> {
/** Arranges methods by classname and method name */
@Override
public int compare(IInvokedMethod o1, IInvokedMethod o2) {
// System.out.println("Comparing " + o1.getMethodName() + " " + o1.getDate()
// + " and " + o2.getMethodName() + " " + o2.getDate());
return (int) (o1.getDate() - o2.getDate());
// int r = ((T) o1).getTestClass().getName().compareTo(((T) o2).getTestClass().getName());
// if (r == 0) {
// r = ((T) o1).getMethodName().compareTo(((T) o2).getMethodName());
// return r;
}
}
}
|
package alien4cloud.brooklyn;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import javax.ws.rs.core.Response;
import lombok.SneakyThrows;
import org.elasticsearch.common.collect.Lists;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import alien4cloud.application.ApplicationService;
import alien4cloud.exception.NotFoundException;
import alien4cloud.model.application.Application;
import alien4cloud.model.cloud.CloudResourceMatcherConfig;
import alien4cloud.model.cloud.CloudResourceType;
import alien4cloud.model.common.Tag;
import alien4cloud.model.components.AbstractPropertyValue;
import alien4cloud.model.components.ScalarPropertyValue;
import alien4cloud.model.topology.NodeTemplate;
import alien4cloud.model.topology.Topology;
import alien4cloud.paas.IConfigurablePaaSProvider;
import alien4cloud.paas.IPaaSCallback;
import alien4cloud.paas.exception.MaintenanceModeException;
import alien4cloud.paas.exception.OperationExecutionException;
import alien4cloud.paas.exception.PluginConfigurationException;
import alien4cloud.paas.model.AbstractMonitorEvent;
import alien4cloud.paas.model.DeploymentStatus;
import alien4cloud.paas.model.InstanceInformation;
import alien4cloud.paas.model.NodeOperationExecRequest;
import alien4cloud.paas.model.PaaSDeploymentContext;
import alien4cloud.paas.model.PaaSTopologyDeploymentContext;
import brooklyn.rest.client.BrooklynApi;
import brooklyn.util.text.Strings;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;
@Component
@Scope(value = "prototype")
public class BrooklynProvider implements IConfigurablePaaSProvider<Configuration> {
private static final Logger log = LoggerFactory.getLogger(BrooklynProvider.class);
private Configuration configuration;
private BrooklynApi brooklynApi;
// TODO mock cache while we flesh out the impl
protected Map<String,Object> knownDeployments = Maps.newLinkedHashMap();
@Autowired
private ApplicationService applicationService;
@Autowired
private BrooklynCatalogMapper catalogMapper;
ThreadLocal<ClassLoader> oldContextClassLoader = new ThreadLocal<ClassLoader>();
private void useLocalContextClassLoader() {
if (oldContextClassLoader.get()==null) {
oldContextClassLoader.set( Thread.currentThread().getContextClassLoader() );
}
Thread.currentThread().setContextClassLoader(getClass().getClassLoader());
}
private void revertContextClassLoader() {
if (oldContextClassLoader.get()==null) {
log.warn("No local context class loader to revert");
}
Thread.currentThread().setContextClassLoader(oldContextClassLoader.get());
oldContextClassLoader.remove();
}
@Override
public void init(Map<String, PaaSTopologyDeploymentContext> activeDeployments) {
useLocalContextClassLoader();
try {
log.info("INIT: " + activeDeployments);
brooklynApi = new BrooklynApi(configuration.getUrl(), configuration.getUser(), configuration.getPassword());
catalogMapper.mapBrooklynEntities(brooklynApi);
} finally { revertContextClassLoader(); }
}
@Override
@SneakyThrows
public void deploy(PaaSTopologyDeploymentContext deploymentContext, IPaaSCallback<?> callback) {
log.info("DEPLOY "+deploymentContext+" / "+callback);
knownDeployments.put(deploymentContext.getDeploymentId(), deploymentContext);
// TODO only does node templates
// and for now it builds up camp yaml
Map<String,Object> campYaml = Maps.newLinkedHashMap();
Topology topology = deploymentContext.getTopology();
addRootPropertiesAsCamp(deploymentContext, campYaml);
campYaml.put("brooklyn.config", ImmutableMap.of("tosca.id", deploymentContext.getDeploymentId()));
List<Object> svcs = Lists.newArrayList();
addNodeTemplatesAsCampServicesList(svcs, topology);
campYaml.put("services", svcs);
if (Strings.isNonBlank(configuration.getLocation()))
campYaml.put("location", configuration.getLocation());
try {
useLocalContextClassLoader();
String campYamlString = new ObjectMapper().writeValueAsString(campYaml);
log.info("DEPLOYING: "+campYamlString);
Response result = brooklynApi.getApplicationApi().createFromYaml( campYamlString );
log.info("RESULT: "+result.getEntity());
validate(result);
// (the result is a 204 creating, whose entity is a TaskSummary
// with an entityId of the entity which is created and id of the task)
// TODO set the brooklyn entityId somewhere that it can be recorded in A4C for easy cross-referencing
} catch (Throwable e) {
log.warn("ERROR DEPLOYING", e);
throw e;
} finally { revertContextClassLoader(); }
if (callback!=null) callback.onSuccess(null);
}
private void validate(Response r) {
if (r==null) return;
if ((r.getStatus() / 100)==2) return;
throw new IllegalStateException("Server returned "+r.getStatus());
}
private void addRootPropertiesAsCamp(PaaSTopologyDeploymentContext deploymentContext, Map<String,Object> result) {
if (applicationService!=null) {
try {
Application app = applicationService.getOrFail(deploymentContext.getDeployment().getSourceId());
if (app!=null) {
result.put("name", app.getName());
if (app.getDescription()!=null) result.put("description", app.getDescription());
List<String> tags = Lists.newArrayList();
for (Tag tag: app.getTags()) {
tags.add(tag.getName()+": "+tag.getValue());
}
if (!tags.isEmpty())
result.put("tags", tags);
// TODO icon, from app.getImageId());
return;
}
log.warn("Application null when deploying "+deploymentContext+"; using less information");
} catch (NotFoundException e) {
// ignore, fall through to below
log.warn("Application instance not found when deploying "+deploymentContext+"; using less information");
}
} else {
log.warn("Application service not available when deploying "+deploymentContext+"; using less information");
}
// no app or app service - use what limited information we have
result.put("name", "A4C: "+deploymentContext.getDeployment().getSourceName());
result.put("description", "Created by Alien4Cloud from application "+deploymentContext.getDeployment().getSourceId());
}
private void addNodeTemplatesAsCampServicesList(List<Object> svcs, Topology topology) {
for (Entry<String, NodeTemplate> nodeEntry : topology.getNodeTemplates().entrySet()) {
Map<String,Object> svc = Maps.newLinkedHashMap();
NodeTemplate nt = nodeEntry.getValue();
svc.put("name", nodeEntry.getKey());
// TODO mangle according to the tag brooklyn_blueprint_catalog_id on the type (but how do we get the IndexedNodeType?)
// this will give us the type, based on TopologyValidationService
// IndexedNodeType relatedIndexedNodeType = csarRepoSearchService.getRequiredElementInDependencies(IndexedNodeType.class, nodeTemp.getType(),
// topology.getDependencies());
svc.put("type", nt.getType());
for (Entry<String, AbstractPropertyValue> prop: nt.getProperties().entrySet()) {
String propName = prop.getKey();
// TODO mangle prop name according to the tag brooklyn_property_map__<propName>
AbstractPropertyValue v = prop.getValue();
Object propValue = null;
if (v instanceof ScalarPropertyValue) {
propValue = ((ScalarPropertyValue)v).getValue();
} else {
log.warn("Ignoring non-scalar property value for "+propName+": "+v);
}
if (propValue!=null) {
svc.put(propName, propValue);
}
}
svcs.add(svc);
}
}
@Override
public void undeploy(PaaSDeploymentContext deploymentContext, IPaaSCallback<?> callback) {
knownDeployments.remove(deploymentContext.getDeploymentId());
log.info("UNDEPLOY "+deploymentContext+" / "+callback);
if (callback!=null) callback.onSuccess(null);
}
@Override
public void scale(PaaSDeploymentContext deploymentContext, String nodeTemplateId, int instances, IPaaSCallback<?> callback) {
log.warn("SCALE not supported");
}
@Override
public void getStatus(PaaSDeploymentContext deploymentContext, IPaaSCallback<DeploymentStatus> callback) {
Object dep = knownDeployments.get(deploymentContext.getDeploymentId());
log.info("GET STATUS - "+dep);
if (callback!=null) callback.onSuccess(dep==null ? DeploymentStatus.UNDEPLOYED : DeploymentStatus.DEPLOYED);
}
@Override
public void getInstancesInformation(PaaSDeploymentContext deploymentContext, Topology topology,
IPaaSCallback<Map<String, Map<String, InstanceInformation>>> callback) {
// TODO
}
@Override
public void getEventsSince(Date date, int maxEvents, IPaaSCallback<AbstractMonitorEvent[]> eventCallback) {
// TODO
}
@Override
public void executeOperation(PaaSTopologyDeploymentContext deploymentContext, NodeOperationExecRequest request,
IPaaSCallback<Map<String, String>> operationResultCallback) throws OperationExecutionException {
log.warn("EXEC OP not supported: " + request);
}
@Override
public String[] getAvailableResourceIds(CloudResourceType resourceType) {
return new String[0];
}
@Override
public String[] getAvailableResourceIds(CloudResourceType resourceType, String imageId) {
return new String[0];
}
@Override
public void updateMatcherConfig(CloudResourceMatcherConfig config) {
log.info("MATCHER CONFIG (ignored): " + config);
}
@Override
public void switchMaintenanceMode(PaaSDeploymentContext deploymentContext, boolean maintenanceModeOn) throws MaintenanceModeException {
log.info("MAINT MODE (ignored): " + maintenanceModeOn);
}
@Override
public void switchInstanceMaintenanceMode(PaaSDeploymentContext deploymentContext, String nodeId, String instanceId, boolean maintenanceModeOn)
throws MaintenanceModeException {
log.info("MAINT MODE for INSTANCE (ignored): " + maintenanceModeOn);
}
@Override
public void setConfiguration(Configuration configuration) throws PluginConfigurationException {
log.info("Setting configuration: " + configuration);
this.configuration = configuration;
}
}
|
package com.love320.stats.core;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import javax.annotation.PostConstruct;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.love320.stats.filter.FilterService;
import com.love320.stats.filter.ZInteger;
import com.love320.stats.filter.ZString;
import com.love320.stats.filter.Zbase;
import com.love320.stats.handler.Handler;
import com.love320.stats.handler.HandlerService;
import com.love320.stats.storage.impl.AfterService;
import com.love320.stats.storage.impl.LocalJVMData;
import com.love320.stats.storage.impl.MysqlDataBase;
import com.love320.stats.task.TaskService;
import com.love320.stats.utils.ConcatUtil;
/**
*
*
* @author love320
*
*/
@Service
public class InitApp {
private static final Logger logger = LoggerFactory.getLogger(InitApp.class);
@Autowired
private FilterService filterService;
@Autowired
private HandlerService handlerService;
@Autowired
private LocalJVMData localJVMData;
@Autowired
private TaskService taskService;
@Autowired
private MysqlDataBase mysqlDataBase;
@Autowired
private AfterService afterService;
@PostConstruct
public boolean initConfig() {
logger.info("...");
List<Config> configs = configList();
for(Config sing:configs){
Handler handler = new Handler(sing);
localJVMData.initDB(ConcatUtil.undbkey(sing));
localJVMData.initDB(ConcatUtil.dbkey(sing));
handler.setStorage(localJVMData);
handler.setFilterService(filterService);
filterService.add(sing, filters(sing));
handlerService.add(handler);
taskService.add(sing, localJVMData,mysqlDataBase,afterService);
if(!StringUtils.isBlank(sing.getSrcIndex())) afterService.addSrcIndex(sing.getSrcIndex());
}
goThread(afterService);
goThread(mysqlDataBase);
return true;
}
/**
*
* @param config
* @return
*/
private CopyOnWriteArrayList<Zbase> filters(Config config){
CopyOnWriteArrayList<Zbase> zbase = new CopyOnWriteArrayList<Zbase>();
List<String> filters = config.getFilters();
for(String sing:filters){
String[] strs = StringUtils.split(sing,Constant.COLONS);
if(strs.length == 2){
if(strs[0].equals("S")) zbase.add(new ZString(strs[1]));
if(strs[0].equals("I")) zbase.add(new ZInteger(strs[1]));
}
}
return zbase;
}
private boolean goThread(Runnable run){
Thread thread = new Thread(run);
thread.start();
return true;
}
/**
*
* @return
*/
private List<Config> configList() {
List<Config> cs = new ArrayList<Config>();
cs.add(configPv10());// pv 10
cs.add(configPvSrc10());// configPv10
cs.add(configPvSrcMin());
cs.add(configUv30());// uv 30
return cs;
}
/**
* pv 10
* @return
*/
private Config configPv10() {
Config config = new Config();
config.setIndex("jWhn48iO");
String[] filters = { "S:mid", "S:version", "S:appId", "I:calcCount" };
config.setFilters(Arrays.asList(filters));
config.setIsize(false);
config.setValue("calcCount");
String[] columns = { "S:channel", "S:version", "S:appId" };
config.setColumns(Arrays.asList(columns));
config.setCron("0/15 * * * * ?");
config.setSleep(3000);
config.setTable("statsTables_PV");
return config;
}
/**
* pv 10
* @return
*/
private Config configPvSrc10() {
Config config = new Config();
config.setIndex("BPqlPV4N");
config.setSrcIndex("jWhn48iO");
String[] filters = { "S:jWhn48iO"};
config.setFilters(Arrays.asList(filters));
config.setIsize(false);
config.setValue("value");
String[] columns = { "S:channel", "S:version", "S:appId" };
config.setColumns(Arrays.asList(columns));
config.setCron("0/50 * * * * ?");
config.setSleep(3000);
config.setTable("statsTables_PV_hour");
return config;
}
private Config configPvSrcMin() {
Config config = new Config();
config.setIndex("VHX9Nr22");
config.setSrcIndex("BPqlPV4N");
String[] filters = { "S:BPqlPV4N"};
config.setFilters(Arrays.asList(filters));
config.setIsize(false);
config.setValue("value");
String[] columns = { "S:channel", "S:version", "S:appId" };
config.setColumns(Arrays.asList(columns));
config.setCron("2 0/2 * * * ?");
config.setSleep(3000);
config.setTable("statsTables_PV_Min");
return config;
}
/**
* uv 30
* @return
*/
private Config configUv30() {
Config config = new Config();
config.setIndex("i5ZjweSq");
String[] filters = { "S:mid", "S:appId" };
config.setFilters(Arrays.asList(filters));
config.setIsize(true);
config.setValue("mid");
String[] columns = { "S:channel", "S:appId" };
config.setColumns(Arrays.asList(columns));
config.setCron("0/20 * * * * ?");
config.setSleep(3000);
config.setTable("statsTables_UV");
return config;
}
}
|
package org.pentaho.di.core.database;
import org.pentaho.di.core.Const;
import org.pentaho.di.core.exception.KettleDatabaseException;
import org.pentaho.di.core.row.ValueMetaInterface;
/**
* Contains Oracle specific information through static final members
*
* @author Matt
* @since 11-mrt-2005
*/
public class OracleDatabaseMeta extends BaseDatabaseMeta implements DatabaseInterface
{
/**
* Construct a new database connections. Note that not all these parameters are not allways mandatory.
*
* @param name The database name
* @param access The type of database access
* @param host The hostname or IP address
* @param db The database name
* @param port The port on which the database listens.
* @param user The username
* @param pass The password
*/
public OracleDatabaseMeta(String name, String access, String host, String db, String port, String user, String pass)
{
super(name, access, host, db, port, user, pass);
}
public OracleDatabaseMeta()
{
}
public String getDatabaseTypeDesc()
{
return "ORACLE";
}
public String getDatabaseTypeDescLong()
{
return "Oracle";
}
/**
* @return Returns the databaseType.
*/
public int getDatabaseType()
{
return DatabaseMeta.TYPE_DATABASE_ORACLE;
}
public int[] getAccessTypeList()
{
return new int[] { DatabaseMeta.TYPE_ACCESS_NATIVE, DatabaseMeta.TYPE_ACCESS_ODBC, DatabaseMeta.TYPE_ACCESS_OCI, DatabaseMeta.TYPE_ACCESS_JNDI };
}
public int getDefaultDatabasePort()
{
if (getAccessType()==DatabaseMeta.TYPE_ACCESS_NATIVE) return 1521;
return -1;
}
/**
* @return Whether or not the database can use auto increment type of fields (pk)
*/
public boolean supportsAutoInc()
{
return false;
}
/**
* @see org.pentaho.di.core.database.DatabaseInterface#getLimitClause(int)
*/
public String getLimitClause(int nrRows)
{
return " WHERE ROWNUM <= "+nrRows;
}
/**
* Returns the minimal SQL to launch in order to determine the layout of the resultset for a given database table
* @param tableName The name of the table to determine the layout for
* @return The SQL to launch.
*/
public String getSQLQueryFields(String tableName)
{
return "SELECT /*+FIRST_ROWS*/ * FROM "+tableName+" WHERE ROWNUM < 1";
}
public String getSQLTableExists(String tablename)
{
return getSQLQueryFields(tablename);
}
public boolean needsToLockAllTables()
{
return false;
}
public String getDriverClass()
{
if (getAccessType()==DatabaseMeta.TYPE_ACCESS_ODBC)
{
return "sun.jdbc.odbc.JdbcOdbcDriver";
}
else
{
return "oracle.jdbc.driver.OracleDriver";
}
}
public String getURL(String hostname, String port, String databaseName) throws KettleDatabaseException
{
if (getAccessType()==DatabaseMeta.TYPE_ACCESS_ODBC)
{
return "jdbc:odbc:"+databaseName;
}
else
if (getAccessType()==DatabaseMeta.TYPE_ACCESS_NATIVE)
{
// the database name can be a SID (starting with :) or a Service (starting with /)
//<host>:<port>/<service>
//<host>:<port>:<SID>
if (databaseName != null && databaseName.length()>0 &&
(databaseName.startsWith("/") || databaseName.startsWith(":"))) {
return "jdbc:oracle:thin:@"+hostname+":"+port+databaseName;
}
else {
// by default we assume a SID
return "jdbc:oracle:thin:@"+hostname+":"+port+":"+databaseName;
}
}
else // OCI
{
// Let's see if we have an database name
if (getDatabaseName()!=null && getDatabaseName().length()>0)
{
// Has the user specified hostname & port number?
if (getHostname()!=null && getHostname().length()>0 && getDatabasePortNumberString()!=null && getDatabasePortNumberString().length()>0) {
// User wants the full url
return "jdbc:oracle:oci:@(description=(address=(host="+getHostname()+")(protocol=tcp)(port="+getDatabasePortNumberString()+"))(connect_data=(sid="+getDatabaseName()+")))";
} else {
// User wants the shortcut url
return "jdbc:oracle:oci:@"+getDatabaseName();
}
}
else
{
throw new KettleDatabaseException("Unable to construct a JDBC URL: at least the database name must be specified");
}
}
}
/**
* Oracle doesn't support options in the URL, we need to put these in a Properties object at connection time...
*/
public boolean supportsOptionsInURL()
{
return false;
}
/**
* @return true if the database supports sequences
*/
public boolean supportsSequences()
{
return true;
}
/**
* Check if a sequence exists.
* @param sequenceName The sequence to check
* @return The SQL to get the name of the sequence back from the databases data dictionary
*/
public String getSQLSequenceExists(String sequenceName)
{
return "SELECT * FROM USER_SEQUENCES WHERE SEQUENCE_NAME = '"+sequenceName.toUpperCase()+"'";
}
/**
* Get the current value of a database sequence
* @param sequenceName The sequence to check
* @return The current value of a database sequence
*/
public String getSQLCurrentSequenceValue(String sequenceName)
{
return "SELECT "+sequenceName+".currval FROM DUAL";
}
/**
* Get the SQL to get the next value of a sequence. (Oracle only)
* @param sequenceName The sequence name
* @return the SQL to get the next value of a sequence. (Oracle only)
*/
public String getSQLNextSequenceValue(String sequenceName)
{
return "SELECT "+sequenceName+".nextval FROM dual";
}
/**
* @return true if we need to supply the schema-name to getTables in order to get a correct list of items.
*/
public boolean useSchemaNameForTableList()
{
return true;
}
/**
* @return true if the database supports synonyms
*/
public boolean supportsSynonyms()
{
return true;
}
/**
* Generates the SQL statement to add a column to the specified table
* @param tablename The table to add
* @param v The column defined as a value
* @param tk the name of the technical key field
* @param use_autoinc whether or not this field uses auto increment
* @param pk the name of the primary key field
* @param semicolon whether or not to add a semi-colon behind the statement.
* @return the SQL statement to add a column to the specified table
*/
public String getAddColumnStatement(String tablename, ValueMetaInterface v, String tk, boolean use_autoinc, String pk, boolean semicolon)
{
return "ALTER TABLE "+tablename+" ADD ( "+getFieldDefinition(v, tk, pk, use_autoinc, true, false)+" ) ";
}
/**
* Generates the SQL statement to drop a column from the specified table
* @param tablename The table to add
* @param v The column defined as a value
* @param tk the name of the technical key field
* @param use_autoinc whether or not this field uses auto increment
* @param pk the name of the primary key field
* @param semicolon whether or not to add a semi-colon behind the statement.
* @return the SQL statement to drop a column from the specified table
*/
public String getDropColumnStatement(String tablename, ValueMetaInterface v, String tk, boolean use_autoinc, String pk, boolean semicolon)
{
return "ALTER TABLE "+tablename+" DROP ( "+v.getName()+" ) "+Const.CR;
}
/**
* Generates the SQL statement to modify a column in the specified table
* @param tablename The table to add
* @param v The column defined as a value
* @param tk the name of the technical key field
* @param use_autoinc whether or not this field uses auto increment
* @param pk the name of the primary key field
* @param semicolon whether or not to add a semi-colon behind the statement.
* @return the SQL statement to modify a column in the specified table
*/
public String getModifyColumnStatement(String tablename, ValueMetaInterface v, String tk, boolean use_autoinc, String pk, boolean semicolon)
{
ValueMetaInterface tmpColumn = v.clone();
int threeoh = v.getName().length()>=30 ? 30 : v.getName().length();
tmpColumn.setName(v.getName().substring(0,threeoh)+"_KTL"); // should always be less then 35
String sql="";
// Create a new tmp column
sql+=getAddColumnStatement(tablename, tmpColumn, tk, use_autoinc, pk, semicolon)+";"+Const.CR;
// copy the old data over to the tmp column
sql+="UPDATE "+tablename+" SET "+tmpColumn.getName()+"="+v.getName()+";"+Const.CR;
// drop the old column
sql+=getDropColumnStatement(tablename, v, tk, use_autoinc, pk, semicolon)+";"+Const.CR;
// create the wanted column
sql+=getAddColumnStatement(tablename, v, tk, use_autoinc, pk, semicolon)+";"+Const.CR;
// copy the data from the tmp column to the wanted column (again)
// All this to avoid the rename clause as this is not supported on all Oracle versions
sql+="UPDATE "+tablename+" SET "+v.getName()+"="+tmpColumn.getName()+";"+Const.CR;
// drop the temp column
sql+=getDropColumnStatement(tablename, tmpColumn, tk, use_autoinc, pk, semicolon);
return sql;
}
public String getFieldDefinition(ValueMetaInterface v, String tk, String pk, boolean use_autoinc, boolean add_fieldname, boolean add_cr)
{
StringBuffer retval=new StringBuffer(128);
String fieldname = v.getName();
int length = v.getLength();
int precision = v.getPrecision();
if (add_fieldname) retval.append(fieldname).append(' ');
int type = v.getType();
switch(type)
{
case ValueMetaInterface.TYPE_DATE : retval.append("DATE"); break;
case ValueMetaInterface.TYPE_BOOLEAN: retval.append("CHAR(1)"); break;
case ValueMetaInterface.TYPE_NUMBER :
case ValueMetaInterface.TYPE_BIGNUMBER:
retval.append("NUMBER");
if (length>0)
{
retval.append('(').append(length);
if (precision>0)
{
retval.append(", ").append(precision);
}
retval.append(')');
}
break;
case ValueMetaInterface.TYPE_INTEGER:
retval.append("INTEGER");
break;
case ValueMetaInterface.TYPE_STRING:
if (length>=DatabaseMeta.CLOB_LENGTH)
{
retval.append("CLOB");
}
else
{
if (length>0 && length<=2000)
{
retval.append("VARCHAR2(").append(length).append(')');
}
else
{
if (length<=0)
{
retval.append("VARCHAR2(2000)"); // We don't know, so we just use the maximum...
}
else
{
retval.append("CLOB");
}
}
}
break;
case ValueMetaInterface.TYPE_BINARY: // the BLOB can contain binary data.
{
retval.append("BLOB");
}
break;
default:
retval.append(" UNKNOWN");
break;
}
if (add_cr) retval.append(Const.CR);
return retval.toString();
}
/* (non-Javadoc)
* @see com.ibridge.kettle.core.database.DatabaseInterface#getReservedWords()
*/
public String[] getReservedWords()
{
return new String[]
{
"ACCESS", "ADD", "ALL", "ALTER", "AND", "ANY", "ARRAYLEN", "AS", "ASC", "AUDIT", "BETWEEN",
"BY", "CHAR", "CHECK", "CLUSTER", "COLUMN", "COMMENT", "COMPRESS", "CONNECT", "CREATE", "CURRENT", "DATE",
"DECIMAL", "DEFAULT", "DELETE", "DESC", "DISTINCT", "DROP", "ELSE", "EXCLUSIVE", "EXISTS", "FILE", "FLOAT",
"FOR", "FROM", "GRANT", "GROUP", "HAVING", "IDENTIFIED", "IMMEDIATE", "IN", "INCREMENT", "INDEX", "INITIAL",
"INSERT", "INTEGER", "INTERSECT", "INTO", "IS", "LEVEL", "LIKE", "LOCK", "LONG", "MAXEXTENTS", "MINUS",
"MODE", "MODIFY", "NOAUDIT", "NOCOMPRESS", "NOT", "NOTFOUND", "NOWAIT", "NULL", "NUMBER", "OF", "OFFLINE",
"ON", "ONLINE", "OPTION", "OR", "ORDER", "PCTFREE", "PRIOR", "PRIVILEGES", "PUBLIC", "RAW", "RENAME",
"RESOURCE", "REVOKE", "ROW", "ROWID", "ROWLABEL", "ROWNUM", "ROWS", "SELECT", "SESSION", "SET", "SHARE",
"SIZE", "SMALLINT", "SQLBUF", "START", "SUCCESSFUL", "SYNONYM", "SYSDATE", "TABLE", "THEN", "TO", "TRIGGER",
"UID", "UNION", "UNIQUE", "UPDATE", "USER", "VALIDATE", "VALUES", "VARCHAR", "VARCHAR2", "VIEW", "WHENEVER",
"WHERE", "WITH"
};
}
/**
* @return The SQL on this database to get a list of stored procedures.
*/
public String getSQLListOfProcedures()
{
return "SELECT DISTINCT DECODE(package_name, NULL, '', package_name||'.')||object_name FROM user_arguments";
}
public String getSQLLockTables(String tableNames[])
{
StringBuffer sql=new StringBuffer(128);
for (int i=0;i<tableNames.length;i++)
{
sql.append("LOCK TABLE ").append(tableNames[i]).append(" IN EXCLUSIVE MODE;").append(Const.CR);
}
return sql.toString();
}
public String getSQLUnlockTables(String tableNames[])
{
return null; // commit handles the unlocking!
}
/**
* @return extra help text on the supported options on the selected database platform.
*/
public String getExtraOptionsHelpText()
{
return "http://www.oracle.com/technology/tech/java/sqlj_jdbc/htdocs/jdbc_faq.htm#05_00";
}
public String[] getUsedLibraries()
{
return new String[] { "ojdbc14.jar", "orai18n.jar" };
}
}
|
package permafrost.tundra.server;
import com.wm.app.b2b.server.BaseService;
import com.wm.app.b2b.server.InvokeState;
import com.wm.app.b2b.server.ServerAPI;
import com.wm.app.b2b.server.Service;
import com.wm.app.b2b.server.ServiceException;
import com.wm.app.b2b.server.ServiceSetupException;
import com.wm.app.b2b.server.ServiceThread;
import com.wm.app.b2b.server.ns.NSDependencyManager;
import com.wm.app.b2b.server.ns.Namespace;
import com.wm.data.IData;
import com.wm.data.IDataCursor;
import com.wm.data.IDataFactory;
import com.wm.data.IDataUtil;
import com.wm.lang.ns.DependencyManager;
import com.wm.lang.ns.NSName;
import com.wm.lang.ns.NSNode;
import com.wm.lang.ns.NSService;
import com.wm.lang.ns.NSServiceType;
import com.wm.net.HttpHeader;
import permafrost.tundra.collection.ListHelper;
import permafrost.tundra.data.IDataHelper;
import permafrost.tundra.data.IDataMap;
import permafrost.tundra.lang.BytesHelper;
import permafrost.tundra.lang.CharsetHelper;
import permafrost.tundra.lang.ExceptionHelper;
import permafrost.tundra.lang.StringHelper;
import permafrost.tundra.math.IntegerHelper;
import permafrost.tundra.math.gauss.ServiceEstimator;
import permafrost.tundra.mime.MIMETypeHelper;
import permafrost.tundra.net.http.HTTPHelper;
import javax.activation.MimeType;
import javax.activation.MimeTypeParseException;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.SortedMap;
import java.util.SortedSet;
import java.util.TreeMap;
import java.util.TreeSet;
/**
* A collection of convenience methods for working with webMethods Integration Server services.
*/
public final class ServiceHelper {
/**
* Disallow instantiation of this class.
*/
private ServiceHelper() {}
/**
* Returns a copy of the call stack for the current invocation.
*
* @return A copy of the call stack for the current invocation.
*/
@SuppressWarnings("unchecked")
public static List<NSService> getCallStack() {
List<NSService> stack = (List<NSService>)InvokeState.getCurrentState().getCallStack();
if (stack == null) {
return Collections.emptyList();
} else {
return new ArrayList<NSService>(stack);
}
}
/**
* Returns true if the calling service is the top-level initiating service of the current thread.
*
* @return True if the calling service is the top-level initiating service of the current thread.
*/
public static boolean isInitiator() {
return getCallStack().size() <= 1;
}
/**
* Returns the top-level service that initiated this call, or null if unknown.
*
* @return the top-level service that initiated this call, or null if unknown.
*/
public static NSService getInitiator() {
List<NSService> stack = getCallStack();
return stack.size() > 0 ? stack.get(0) : null;
}
/**
* Creates a new service in the given package with the given name.
*
* @param packageName The name of the package to create the service in.
* @param serviceName The fully-qualified name of the service to be created.
* @param type The type of service to be created.
* @param subtype The subtype of service to be created.
* @throws ServiceException If an error creating the service occurs.
*/
private static void create(String packageName, String serviceName, String type, String subtype) throws ServiceException {
if (!PackageHelper.exists(packageName)) {
throw new IllegalArgumentException("package does not exist: " + packageName);
}
if (NodeHelper.exists(serviceName)) throw new IllegalArgumentException("node already exists: " + serviceName);
NSName service = NSName.create(serviceName);
if (type == null) type = NSServiceType.SVC_FLOW;
if (subtype == null) subtype = NSServiceType.SVCSUB_UNKNOWN;
NSServiceType serviceType = NSServiceType.create(type, subtype);
try {
ServerAPI.registerService(packageName, service, true, serviceType, null, null, null);
} catch (ServiceSetupException ex) {
ExceptionHelper.raise(ex);
}
}
/**
* Creates a new flow service in the given package with the given name.
*
* @param packageName The name of the package to create the service in.
* @param serviceName The fully-qualified name of the service to be created.
* @throws ServiceException If an error creating the service occurs.
*/
public static void create(String packageName, String serviceName) throws ServiceException {
create(packageName, serviceName, null, null);
}
/**
* Returns information about the service with the given name.
*
* @param serviceName The name of the service to be reflected on.
* @return An IData document containing information about the service.
*/
public static IData reflect(String serviceName) {
if (serviceName == null) return null;
BaseService service = Namespace.getService(NSName.create(serviceName));
if (service == null) return null;
IData output = IDataFactory.create();
IDataCursor cursor = output.getCursor();
IDataUtil.put(cursor, "name", serviceName);
IDataUtil.put(cursor, "type", service.getServiceType().getType());
IDataUtil.put(cursor, "package", service.getPackageName());
IDataHelper.put(cursor, "description", service.getComment(), false);
IDataUtil.put(cursor, "references", getReferences(service.getNSName().getFullName()));
IDataUtil.put(cursor, "dependents", getDependents(service.getNSName().getFullName()));
cursor.destroy();
return output;
}
/**
* Returns the list of services that are dependent on the given list of services.
*
* @param services The services to get dependents for.
* @return The list of dependents for the given services.
*/
public static IData getDependents(String ...services) {
DependencyManager manager = NSDependencyManager.current();
Namespace namespace = Namespace.current();
SortedSet<String> packages = new TreeSet<String>();
SortedMap<String, IData> nodes = new TreeMap<String, IData>();
if (services != null) {
for (String service : services) {
if (service != null) {
NSNode node = namespace.getNode(service);
if (node != null) {
IData results = manager.getDependent(node, null);
if (results != null) {
IDataCursor resultsCursor = results.getCursor();
IData[] referencedBy = IDataUtil.getIDataArray(resultsCursor, "referencedBy");
resultsCursor.destroy();
if (referencedBy != null) {
for (IData dependent : referencedBy) {
if (dependent != null) {
IDataCursor dependentCursor = dependent.getCursor();
String name = IDataUtil.getString(dependentCursor, "name");
dependentCursor.destroy();
String[] parts = name.split("\\/");
if (parts.length > 1) {
IData result = IDataFactory.create();
IDataCursor resultCursor = result.getCursor();
IDataUtil.put(resultCursor, "package", parts[0]);
IDataUtil.put(resultCursor, "node", parts[1]);
resultCursor.destroy();
packages.add(parts[0]);
nodes.put(name, result);
}
}
}
}
}
}
}
}
}
IData output = IDataFactory.create();
IDataCursor cursor = output.getCursor();
IDataUtil.put(cursor, "packages", packages.toArray(new String[0]));
IDataUtil.put(cursor, "packages.length", IntegerHelper.emit(packages.size()));
IDataUtil.put(cursor, "nodes", nodes.values().toArray(new IData[0]));
IDataUtil.put(cursor, "nodes.length", IntegerHelper.emit(nodes.size()));
cursor.destroy();
return output;
}
/**
* Returns the list of elements referenced by the given list of services.
*
* @param services The list of services to get references for.
* @return The list of references for the given services.
*/
public static IData getReferences(String ...services) {
DependencyManager manager = NSDependencyManager.current();
Namespace namespace = Namespace.current();
SortedSet<String> packages = new TreeSet<String>();
SortedMap<String, IData> resolved = new TreeMap<String, IData>();
SortedSet<String> unresolved = new TreeSet<String>();
if (services != null) {
for (String service : services) {
if (service != null) {
NSNode node = namespace.getNode(service);
IData results = manager.getReferenced(node, null);
if (results != null) {
IDataCursor resultsCursor = results.getCursor();
IData[] references = IDataUtil.getIDataArray(resultsCursor, "reference");
resultsCursor.destroy();
if (references != null) {
for (IData reference : references) {
if (reference != null) {
IDataCursor referenceCursor = reference.getCursor();
String name = IDataUtil.getString(referenceCursor, "name");
String status = IDataUtil.getString(referenceCursor, "status");
referenceCursor.destroy();
if (status.equals("unresolved")) {
unresolved.add(name);
} else {
String[] parts = name.split("\\/");
if (parts.length > 1) {
IData result = IDataFactory.create();
IDataCursor resultCursor = result.getCursor();
IDataUtil.put(resultCursor, "package", parts[0]);
IDataUtil.put(resultCursor, "node", parts[1]);
resultCursor.destroy();
packages.add(parts[0]);
resolved.put(name, result);
}
}
}
}
}
}
}
}
}
IData output = IDataFactory.create();
IDataCursor cursor = output.getCursor();
IDataUtil.put(cursor, "packages", packages.toArray(new String[0]));
IDataUtil.put(cursor, "packages.length", IntegerHelper.emit(packages.size()));
IDataUtil.put(cursor, "nodes", resolved.values().toArray(new IData[0]));
IDataUtil.put(cursor, "nodes.length", IntegerHelper.emit(resolved.size()));
IDataUtil.put(cursor, "unresolved", unresolved.toArray(new String[0]));
IDataUtil.put(cursor, "unresolved.length", IntegerHelper.emit(unresolved.size()));
cursor.destroy();
return output;
}
/**
* Returns the invoking service.
*
* @return The invoking service.
*/
public static NSService self() {
return Service.getCallingService();
}
/**
* Sets the HTTP response status, headers, and body for the current service invocation.
*
* @param code The HTTP response status code to be returned.
* @param message The HTTP response status message to be returned; if null, the standard message for the given
* code will be used.
* @param headers The HTTP headers to be returned; if null, no custom headers will be added to the response.
* @param content The HTTP response body to be returned.
* @param contentType The MIME content type of the response body being returned.
* @param charset The character set used if a text response is being returned.
* @throws ServiceException If an I/O error occurs.
*/
public static void respond(int code, String message, IData headers, InputStream content, String contentType, Charset charset) throws ServiceException {
try {
HttpHeader response = Service.getHttpResponseHeader();
if (response == null) {
// service was not invoked via HTTP, so throw an exception for HTTP statuses >= 400
if (code >= 400) ExceptionHelper.raise(StringHelper.normalize(content, charset));
} else {
if (charset == null && MIMETypeHelper.isText(MIMETypeHelper.of(contentType))) {
charset = CharsetHelper.DEFAULT_CHARSET;
}
setResponseStatus(response, code, message);
setContentType(response, contentType, charset);
setHeaders(response, headers);
setResponseBody(response, content);
}
} catch (IOException ex) {
ExceptionHelper.raise(ex);
}
}
/**
* Sets the response body in the given HTTP response.
*
* @param response The HTTP response to set the response body in.
* @param content The content to set the response body to.
* @throws ServiceException If an I/O error occurs.
*/
private static void setResponseBody(HttpHeader response, InputStream content) throws ServiceException {
if (response == null) return;
try {
if (content == null) content = new ByteArrayInputStream(new byte[0]);
Service.setResponse(BytesHelper.normalize(content));
} catch (IOException ex) {
ExceptionHelper.raise(ex);
}
}
/**
* Sets the response status code and message in the given HTTP response.
*
* @param response The HTTP response to set the response status in.
* @param code The response status code.
* @param message The response status message.
*/
private static void setResponseStatus(HttpHeader response, int code, String message) {
if (response != null) {
if (message == null) message = HTTPHelper.getResponseStatusMessage(code);
response.setResponse(code, message);
}
}
/**
* Sets the Content-Type header in the given HTTP response.
*
* @param response The HTTP response to set the header in.
* @param contentType The MIME content type.
* @param charset The character set used by the content, or null if not applicable.
* @throws ServiceException If the MIME content type is malformed.
*/
private static void setContentType(HttpHeader response, String contentType, Charset charset) throws ServiceException {
if (contentType == null) contentType = MIMETypeHelper.DEFAULT_MIME_TYPE_STRING;
try {
MimeType mimeType = new MimeType(contentType);
if (charset != null) mimeType.setParameter("charset", charset.displayName());
setHeader(response, "Content-Type", mimeType);
} catch (MimeTypeParseException ex) {
ExceptionHelper.raise(ex);
}
}
/**
* Sets all HTTP header with the given keys to their associated values from the given IData document in the given
* HTTP response.
*
* @param response The HTTP response to add the header to.
* @param headers An IData document containing key value pairs to be set as headers in the given response.
*/
private static void setHeaders(HttpHeader response, IData headers) {
for (Map.Entry<String, Object> entry : IDataMap.of(headers)) {
setHeader(response, entry.getKey(), entry.getValue());
}
}
/**
* Sets the HTTP header with the given key to the given value in the given HTTP response.
*
* @param response The HTTP response to add the header to.
* @param key The header's key.
* @param value The header's value.
*/
private static void setHeader(HttpHeader response, String key, Object value) {
if (response != null && key != null) {
response.clearField(key);
if (value != null) response.addField(key, value.toString());
}
}
/**
* Returns true if the given service exists in Integration Server.
*
* @param service The service to check existence of.
* @return True if the given service exists in Integration Server.
*/
public static boolean exists(String service) {
boolean exists = false;
try {
exists = exists(service, false);
} catch(ServiceException ex) {
// ignore exceptions
}
return exists;
}
/**
* Returns true if the given service exists in Integration Server.
*
* @param service The service to check existence of.
* @param raise If true and the service does not exist, an exception will be thrown.
* @return True if the given service exists in Integration Server.
* @throws ServiceException If raise is true and the given service does not exist.
*/
public static boolean exists(String service, boolean raise) throws ServiceException {
boolean exists = NodeHelper.exists(service) && "service".equals(NodeHelper.getNodeType(service).toString());
if (raise && !exists) ExceptionHelper.raise("Service does not exist: " + service);
return exists;
}
/**
* Invokes the given service with the given pipeline synchronously.
*
* @param service The service to be invoked.
* @param pipeline The input pipeline used when invoking the service.
* @return The output pipeline returned by the service invocation.
* @throws ServiceException If the service throws an exception while being invoked.
*/
public static IData invoke(String service, IData pipeline) throws ServiceException {
return invoke(service, pipeline, true);
}
/**
* Invokes the given service with the given pipeline synchronously.
*
* @param service The service to be invoked.
* @param pipeline The input pipeline used when invoking the service.
* @param raise If true will rethrow exceptions thrown by the invoked service.
* @return The output pipeline returned by the service invocation.
* @throws ServiceException If raise is true and the service throws an exception while being invoked.
*/
public static IData invoke(String service, IData pipeline, boolean raise) throws ServiceException {
return invoke(service, pipeline, raise, true);
}
/**
* Invokes the given service with the given pipeline synchronously.
*
* @param service The service to be invoked.
* @param pipeline The input pipeline used when invoking the service.
* @param raise If true will rethrow exceptions thrown by the invoked service.
* @param clone If true the pipeline will first be cloned before being used by the invocation.
* @return The output pipeline returned by the service invocation.
* @throws ServiceException If raise is true and the service throws an exception while being invoked.
*/
public static IData invoke(String service, IData pipeline, boolean raise, boolean clone) throws ServiceException {
return invoke(service, pipeline, raise, true, false);
}
/**
* Invokes the given service with the given pipeline synchronously.
*
* @param service The service to be invoked.
* @param pipeline The input pipeline used when invoking the service.
* @param raise If true will rethrow exceptions thrown by the invoked service.
* @param clone If true the pipeline will first be cloned before being used by the invocation.
* @param logError Logs a caught exception if true and raise is false, otherwise exception is not logged.
* @return The output pipeline returned by the service invocation.
* @throws ServiceException If raise is true and the service throws an exception while being invoked.
*/
public static IData invoke(String service, IData pipeline, boolean raise, boolean clone, boolean logError) throws ServiceException {
if (service != null) {
if (pipeline == null) pipeline = IDataFactory.create();
try {
IDataUtil.merge(Service.doInvoke(NSName.create(service), normalize(pipeline, clone)), pipeline);
} catch (Exception exception) {
if (raise) {
ExceptionHelper.raise(exception);
} else {
pipeline = addExceptionToPipeline(pipeline, exception);
if (logError) ServerAPI.logError(exception);
}
}
}
return pipeline;
}
/**
* Executes a list of services in the order specified.
*
* @param services The list of services to be invoked.
* @param pipeline The input pipeline passed to the first service in the chain.
* @return The output pipeline returned by the final service in the chain.
* @throws ServiceException If an exception is thrown by one of the invoked services.
*/
public static IData chain(String[] services, IData pipeline) throws ServiceException {
return chain(ListHelper.of(services), pipeline);
}
/**
* Executes a list of services in the order specified.
*
* @param services The list of services to be invoked.
* @param pipeline The input pipeline passed to the first service in the chain.
* @return The output pipeline returned by the final service in the chain.
* @throws ServiceException If an exception is thrown by one of the invoked services.
*/
public static IData chain(Iterable<String> services, IData pipeline) throws ServiceException {
if (services != null) {
for (String service : services) {
pipeline = ServiceHelper.invoke(service, pipeline);
}
}
return pipeline;
}
/**
* Invokes the given service with the given pipeline asynchronously (in another thread).
*
* @param service The service to be invoked.
* @param pipeline The input pipeline used when invoking the service.
* @return The thread on which the service is being invoked.
*/
public static ServiceThread fork(String service, IData pipeline) {
if (service == null) return null;
return Service.doThreadInvoke(NSName.create(service), normalize(pipeline));
}
/**
* Waits for an asynchronously invoked service to complete.
*
* @param serviceThread The service thread to wait on to finish.
* @return The output pipeline from the service invocation executed by the given thread.
* @throws ServiceException If an error occurs when waiting on the thread to finish.
*/
public static IData join(ServiceThread serviceThread) throws ServiceException {
return join(serviceThread, true);
}
/**
* Waits for an asynchronously invoked service to complete.
*
* @param serviceThread The service thread to wait on to finish.
* @param raise If true rethrows any exception thrown by the invoked service.
* @return The output pipeline from the service invocation executed by the given thread.
* @throws ServiceException If raise is true and an error occurs when waiting on the thread to finish.
*/
public static IData join(ServiceThread serviceThread, boolean raise) throws ServiceException {
IData pipeline = null;
if (serviceThread != null) {
try {
pipeline = serviceThread.getIData();
} catch (Throwable exception) {
if (raise) {
ExceptionHelper.raise(exception);
} else {
pipeline = addExceptionToPipeline(null, exception);
}
}
}
return pipeline;
}
/**
* Invokes the given service a given number of times, and returns execution duration statistics. Exceptions thrown
* by the service are ignored / suppressed.
*
* @param service The service to benchmark.
* @param pipeline The input pipeline used when invoking the service.
* @param count The sample count, or in other words the number of times to invoke the service.
* @return Execution duration statistics generated by benchmarking the given service.
*/
public static ServiceEstimator.Results benchmark(String service, IData pipeline, int count) {
ServiceEstimator.Results results;
try {
return benchmark(service, pipeline, count, false);
} catch(ServiceException ex) {
throw new IllegalStateException(ex);
}
}
/**
* Invokes the given service a given number of times, and returns execution duration statistics.
*
* @param service The service to benchmark.
* @param pipeline The input pipeline used when invoking the service.
* @param count The sample count, or in other words the number of times to invoke the service.
* @param raise If true, exceptions thrown by the service will abort the benchmark.
* @return Execution duration statistics generated by benchmarking the given service.
* @throws ServiceException If the invoked service throws an exception and raise is true.
*/
public static ServiceEstimator.Results benchmark(String service, IData pipeline, int count, boolean raise) throws ServiceException {
if (service == null) throw new NullPointerException("service must not be null");
if (count <= 0) throw new IllegalArgumentException("count must be greater than zero");
if (pipeline == null) pipeline = IDataFactory.create();
ServiceEstimator estimator = new ServiceEstimator(service, "seconds");
exists(service, true);
for (int i = 0; i < count; i++) {
IData scope = IDataUtil.clone(pipeline);
boolean success = false;
long start = System.nanoTime();
try {
invoke(service, scope, raise, false);
success = true;
} finally {
long end = System.nanoTime();
estimator.add(new ServiceEstimator.Sample(success, (end - start) / 1000000000.0));
}
}
return estimator.getResults();
}
/**
* Provides a try/catch/finally pattern for flow services.
*
* @param tryService The service to be executed in the try clause of the try/catch/finally pattern.
* @param catchService The service to be executed in the catch clause of the try/catch/finally pattern.
* @param finallyService The service to be executed in the finally clause of the try/catch/finally pattern.
* @param pipeline The input pipeline used when invoking the services.
* @return The output pipeline containing the results of the try/catch/finally pattern.
* @throws ServiceException If the service throws an exception while being invoked, and either no catch service is
* specified, or the catch service rethrows the exception.
*/
public static IData ensure(String tryService, String catchService, String finallyService, IData pipeline) throws ServiceException {
return ensure(tryService, catchService, finallyService, pipeline, null, null);
}
/**
* Provides a try/catch/finally pattern for flow services.
*
* @param tryService The service to be executed in the try clause of the try/catch/finally pattern.
* @param catchService The service to be executed in the catch clause of the try/catch/finally pattern.
* @param finallyService The service to be executed in the finally clause of the try/catch/finally pattern.
* @param pipeline The input pipeline used when invoking the services.
* @param catchPipeline Optional additional variables to be merged with the pipeline before calling the
* catch service.
* @param finallyPipeline Optional additional variables to be merged with the pipeline before calling the
* finally service.
* @return The output pipeline containing the results of the try/catch/finally pattern.
* @throws ServiceException If the service throws an exception while being invoked, and either no catch service is
* specified, or the catch service rethrows the exception.
*/
public static IData ensure(String tryService, String catchService, String finallyService, IData pipeline, IData catchPipeline, IData finallyPipeline) throws ServiceException {
try {
pipeline = invoke(tryService, pipeline);
} catch (Throwable exception) {
if (catchPipeline != null) pipeline = IDataHelper.mergeInto(pipeline, catchPipeline);
pipeline = rescue(catchService, pipeline, exception);
} finally {
if (finallyPipeline != null) pipeline = IDataHelper.mergeInto(pipeline, finallyPipeline);
pipeline = invoke(finallyService, pipeline);
}
return pipeline;
}
/**
* Handles an exception using the given catch service.
*
* @param catchService The service to invoke to handle the given exception.
* @param pipeline The input pipeline for the service.
* @param exception The exception to be handled.
* @return The output pipeline returned by invoking the given catchService.
* @throws ServiceException If the given catchService encounters an error.
*/
public static IData rescue(String catchService, IData pipeline, Throwable exception) throws ServiceException {
if (catchService == null) {
ExceptionHelper.raise(exception);
} else {
pipeline = invoke(catchService, addExceptionToPipeline(pipeline, exception));
}
return pipeline;
}
/**
* Adds the given exception and related variables that describe the exception to the given IData pipeline.
*
* @param pipeline The pipeline to add the exception to.
* @param exception The exception to be added.
* @return The pipeline with the added exception.
*/
public static IData addExceptionToPipeline(IData pipeline, Throwable exception) {
if (pipeline == null) pipeline = IDataFactory.create();
if (exception != null) {
IDataCursor cursor = pipeline.getCursor();
try {
IData exceptionInfo = null;
String exceptionService = null, exceptionPackage = null;
InvokeState invokeState = InvokeState.getCurrentState();
if (invokeState != null) {
exceptionInfo = IDataHelper.duplicate(invokeState.getErrorInfoFormatted(), true);
if (exceptionInfo != null) {
IDataCursor ec = exceptionInfo.getCursor();
exceptionService = IDataHelper.get(ec, "service", String.class);
if (exceptionService != null) {
BaseService baseService = Namespace.getService(NSName.create(exceptionService));
if (baseService != null) {
exceptionPackage = baseService.getPackageName();
IDataHelper.put(ec, "package", exceptionPackage, false);
}
}
IData exceptionPipeline = IDataHelper.remove(ec, "pipeline", IData.class);
// deep clone the exception pipeline, to prevent recursive references causing stack overflows
IDataHelper.put(ec, "pipeline", IDataHelper.duplicate(exceptionPipeline), false);
ec.destroy();
}
}
IDataHelper.put(cursor, "$exception", exception, false);
IDataHelper.put(cursor, "$exception?", true, String.class);
IDataHelper.put(cursor, "$exception.class", exception.getClass().getName(), false);
IDataHelper.put(cursor, "$exception.message", exception.getMessage(), false);
IDataHelper.put(cursor, "$exception.service", exceptionService, false);
IDataHelper.put(cursor, "$exception.package", exceptionPackage, false);
IDataHelper.put(cursor, "$exception.info", exceptionInfo, false);
IDataHelper.put(cursor, "$exception.stack", ExceptionHelper.getStackTrace(exception), false);
} finally {
cursor.destroy();
}
}
return pipeline;
}
/**
* Returns a new IData if the given pipeline is null, otherwise returns a clone of the given pipeline.
*
* @param pipeline The pipeline to be normalized.
* @return The normalized pipeline.
*/
private static IData normalize(IData pipeline) {
return normalize(pipeline, true);
}
/**
* Returns a new IData if the given pipeline is null, otherwise returns a clone of the given pipeline.
*
* @param pipeline The pipeline to be normalized.
* @param clone If true the pipeline will be cloned, otherwise it will be returned as is.
* @return The normalized pipeline.
*/
private static IData normalize(IData pipeline, boolean clone) {
if (pipeline == null) {
pipeline = IDataFactory.create();
} else if (clone) {
pipeline = IDataUtil.clone(pipeline);
}
return pipeline;
}
/**
* Returns a BaseService object given a service name.
*
* @param serviceName The name of the service to be returned.
* @return The BaseService object representing the service with the given name.
*/
public static BaseService getService(String serviceName) {
if (serviceName == null) return null;
return Namespace.getService(NodeHelper.getName(serviceName));
}
/**
* Returns the name of the package the given service resides in.
*
* @param serviceName The name of the service whose package is to be returned.
* @return The name of the package the given service resides in.
*/
public static String getPackageName(String serviceName) {
return getPackageName(getService(serviceName));
}
/**
* Returns the name of the package the given service resides in.
*
* @param service The service whose package is to be returned.
* @return The name of the package the given service resides in.
*/
public static String getPackageName(BaseService service) {
if (service == null) return null;
return service.getPackageName();
}
}
|
package at.ac.tuwien.kr.alpha.common;
import at.ac.tuwien.kr.alpha.grounder.NonGroundRule;
import at.ac.tuwien.kr.alpha.grounder.Substitution;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import static at.ac.tuwien.kr.alpha.common.ConstantTerm.getInstance;
/**
* Atoms corresponding to rule bodies use this predicate, first term is rule number,
* second is a term containing variable substitutions.
*/
public class RuleAtom implements Atom {
public static final Predicate PREDICATE = new BasicPredicate("_R_", 2);
private final List<Term> terms;
private RuleAtom(List<Term> terms) {
if (terms.size() != 2) {
throw new IllegalArgumentException();
}
this.terms = terms;
}
public RuleAtom(NonGroundRule nonGroundRule, Substitution substitution) {
this(Arrays.asList(
getInstance(Integer.toString(nonGroundRule.getRuleId())),
getInstance(substitution.toUniformString())
));
}
public RuleAtom(Term... terms) {
this(Arrays.asList(terms));
}
@Override
public Predicate getPredicate() {
return PREDICATE;
}
@Override
public List<Term> getTerms() {
return terms;
}
@Override
public boolean isGround() {
// NOTE: Both terms are ConstantTerms, which are ground by definition.
return true;
}
@Override
public boolean isInternal() {
return true;
}
@Override
public List<VariableTerm> getOccurringVariables() {
// NOTE: Both terms are ConstantTerms, which have no variables by definition.
return Collections.emptyList();
}
@Override
public Atom substitute(Substitution substitution) {
return new RuleAtom(terms.stream().map(t -> {
return t.substitute(substitution);
}).collect(Collectors.toList()));
}
@Override
public int compareTo(Atom o) {
if (!(o instanceof RuleAtom)) {
return 1;
}
RuleAtom other = (RuleAtom)o;
int result = terms.get(0).compareTo(other.terms.get(0));
if (result != 0) {
return result;
}
return terms.get(1).compareTo(other.terms.get(1));
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
RuleAtom that = (RuleAtom) o;
return terms.equals(that.terms);
}
@Override
public int hashCode() {
return 31 * PREDICATE.hashCode() + terms.hashCode();
}
@Override
public String toString() {
return PREDICATE.getPredicateName() + "(" + terms.get(0) + "," + terms.get(1) + ')';
}
}
|
package net.ossrs.yasea;
import android.content.Context;
import android.content.res.Configuration;
import android.graphics.ImageFormat;
import android.graphics.SurfaceTexture;
import android.hardware.Camera;
import android.opengl.GLES20;
import android.opengl.GLSurfaceView;
import android.opengl.Matrix;
import android.util.AttributeSet;
import com.seu.magicfilter.base.gpuimage.GPUImageFilter;
import com.seu.magicfilter.utils.MagicFilterFactory;
import com.seu.magicfilter.utils.MagicFilterType;
import com.seu.magicfilter.utils.OpenGLUtils;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.IntBuffer;
import java.util.List;
import java.util.concurrent.ConcurrentLinkedQueue;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;
public class SrsCameraView extends GLSurfaceView implements GLSurfaceView.Renderer {
private GPUImageFilter magicFilter;
private SurfaceTexture surfaceTexture;
private int mOESTextureId = OpenGLUtils.NO_TEXTURE;
private int mSurfaceWidth;
private int mSurfaceHeight;
private int mPreviewWidth;
private int mPreviewHeight;
private volatile boolean mIsEncoding;
private boolean mIsTorchOn = false;
private float mInputAspectRatio;
private float mOutputAspectRatio;
private float[] mProjectionMatrix = new float[16];
private float[] mSurfaceMatrix = new float[16];
private float[] mTransformMatrix = new float[16];
private Camera mCamera;
private ByteBuffer mGLPreviewBuffer;
private int mCamId = -1;
private int mPreviewRotation = 90;
private int mPreviewOrientation = Configuration.ORIENTATION_PORTRAIT;
private Thread worker;
private final Object writeLock = new Object();
private ConcurrentLinkedQueue<IntBuffer> mGLIntBufferCache = new ConcurrentLinkedQueue<>();
private PreviewCallback mPrevCb;
public SrsCameraView(Context context) {
this(context, null);
}
public SrsCameraView(Context context, AttributeSet attrs) {
super(context, attrs);
setEGLContextClientVersion(2);
setRenderer(this);
setRenderMode(GLSurfaceView.RENDERMODE_WHEN_DIRTY);
}
@Override
public void onSurfaceCreated(GL10 gl, EGLConfig config) {
GLES20.glDisable(GL10.GL_DITHER);
GLES20.glClearColor(0, 0, 0, 0);
magicFilter = new GPUImageFilter(MagicFilterType.NONE);
magicFilter.init(getContext().getApplicationContext());
magicFilter.onInputSizeChanged(mPreviewWidth, mPreviewHeight);
mOESTextureId = OpenGLUtils.getExternalOESTextureID();
surfaceTexture = new SurfaceTexture(mOESTextureId);
surfaceTexture.setOnFrameAvailableListener(new SurfaceTexture.OnFrameAvailableListener() {
@Override
public void onFrameAvailable(SurfaceTexture surfaceTexture) {
requestRender();
}
});
// For camera preview on activity creation
if (mCamera != null) {
try {
mCamera.setPreviewTexture(surfaceTexture);
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
@Override
public void onSurfaceChanged(GL10 gl, int width, int height) {
GLES20.glViewport(0, 0, width, height);
mSurfaceWidth = width;
mSurfaceHeight = height;
magicFilter.onDisplaySizeChanged(width, height);
magicFilter.onInputSizeChanged(mPreviewWidth, mPreviewHeight);
mOutputAspectRatio = width > height ? (float) width / height : (float) height / width;
float aspectRatio = mOutputAspectRatio / mInputAspectRatio;
if (width > height) {
Matrix.orthoM(mProjectionMatrix, 0, -1.0f, 1.0f, -aspectRatio, aspectRatio, -1.0f, 1.0f);
} else {
Matrix.orthoM(mProjectionMatrix, 0, -aspectRatio, aspectRatio, -1.0f, 1.0f, -1.0f, 1.0f);
}
}
@Override
public void onDrawFrame(GL10 gl) {
GLES20.glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT | GLES20.GL_DEPTH_BUFFER_BIT);
surfaceTexture.updateTexImage();
surfaceTexture.getTransformMatrix(mSurfaceMatrix);
Matrix.multiplyMM(mTransformMatrix, 0, mSurfaceMatrix, 0, mProjectionMatrix, 0);
magicFilter.setTextureTransformMatrix(mTransformMatrix);
magicFilter.onDrawFrame(mOESTextureId);
if (mIsEncoding) {
mGLIntBufferCache.add(magicFilter.getGLFboBuffer());
synchronized (writeLock) {
writeLock.notifyAll();
}
}
}
public void setPreviewCallback(PreviewCallback cb) {
mPrevCb = cb;
}
public Camera getCamera(){
return this.mCamera;
}
public void setPreviewCallback(Camera.PreviewCallback previewCallback){
this.mCamera.setPreviewCallback(previewCallback);
}
public int[] setPreviewResolution(int width, int height) {
if (mCamera != null) {
stopCamera();
}
mCamera = openCamera();
mPreviewWidth = width;
mPreviewHeight = height;
Camera.Size rs = adaptPreviewResolution(mCamera.new Size(width, height));
if (rs != null) {
mPreviewWidth = rs.width;
mPreviewHeight = rs.height;
}
getHolder().setFixedSize(mPreviewWidth, mPreviewHeight);
mCamera.getParameters().setPreviewSize(mPreviewWidth, mPreviewHeight);
mGLPreviewBuffer = ByteBuffer.allocate(mPreviewWidth * mPreviewHeight * 4);
mInputAspectRatio = mPreviewWidth > mPreviewHeight ?
(float) mPreviewWidth / mPreviewHeight : (float) mPreviewHeight / mPreviewWidth;
return new int[] { mPreviewWidth, mPreviewHeight };
}
public boolean setFilter(final MagicFilterType type) {
if (mCamera == null) {
return false;
}
queueEvent(new Runnable() {
@Override
public void run() {
if (magicFilter != null) {
magicFilter.destroy();
}
magicFilter = MagicFilterFactory.initFilters(type);
if (magicFilter != null) {
magicFilter.init(getContext().getApplicationContext());
magicFilter.onInputSizeChanged(mPreviewWidth, mPreviewHeight);
magicFilter.onDisplaySizeChanged(mSurfaceWidth, mSurfaceHeight);
}
}
});
requestRender();
return true;
}
private void deleteTextures() {
if (mOESTextureId != OpenGLUtils.NO_TEXTURE) {
queueEvent(new Runnable() {
@Override
public void run() {
GLES20.glDeleteTextures(1, new int[]{ mOESTextureId }, 0);
mOESTextureId = OpenGLUtils.NO_TEXTURE;
}
});
}
}
public void setCameraId(int id) {
stopTorch();
mCamId = id;
setPreviewOrientation(mPreviewOrientation);
}
public void setPreviewOrientation(int orientation) {
mPreviewOrientation = orientation;
Camera.CameraInfo info = new Camera.CameraInfo();
Camera.getCameraInfo(mCamId, info);
if (orientation == Configuration.ORIENTATION_PORTRAIT) {
if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
mPreviewRotation = info.orientation % 360;
mPreviewRotation = (360 - mPreviewRotation) % 360; // compensate the mirror
} else {
mPreviewRotation = (info.orientation + 360) % 360;
}
} else if (orientation == Configuration.ORIENTATION_LANDSCAPE) {
if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
mPreviewRotation = (info.orientation - 90) % 360;
mPreviewRotation = (360 - mPreviewRotation) % 360; // compensate the mirror
} else {
mPreviewRotation = (info.orientation + 90) % 360;
}
}
}
public int getCameraId() {
return mCamId;
}
public void enableEncoding() {
worker = new Thread(new Runnable() {
@Override
public void run() {
while (!Thread.interrupted()) {
while (!mGLIntBufferCache.isEmpty()) {
IntBuffer picture = mGLIntBufferCache.poll();
mGLPreviewBuffer.asIntBuffer().put(picture.array());
mPrevCb.onGetRgbaFrame(mGLPreviewBuffer.array(), mPreviewWidth, mPreviewHeight);
}
// Waiting for next frame
synchronized (writeLock) {
try {
// isEmpty() may take some time, so we set timeout to detect next frame
writeLock.wait(500);
} catch (InterruptedException ie) {
worker.interrupt();
}
}
}
}
});
worker.start();
mIsEncoding = true;
}
public void disableEncoding() {
mIsEncoding = false;
mGLIntBufferCache.clear();
mGLPreviewBuffer.clear();
if (worker != null) {
worker.interrupt();
try {
worker.join();
} catch (InterruptedException e) {
e.printStackTrace();
worker.interrupt();
}
worker = null;
}
}
public boolean startCamera() {
if (mCamera == null) {
mCamera = openCamera();
if (mCamera == null) {
return false;
}
}
Camera.Parameters params = mCamera.getParameters();
params.setPictureSize(mPreviewWidth, mPreviewHeight);
params.setPreviewSize(mPreviewWidth, mPreviewHeight);
int[] range = adaptFpsRange(SrsEncoder.VFPS, params.getSupportedPreviewFpsRange());
params.setPreviewFpsRange(range[0], range[1]);
params.setPreviewFormat(ImageFormat.NV21);
params.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
params.setWhiteBalance(Camera.Parameters.WHITE_BALANCE_AUTO);
params.setSceneMode(Camera.Parameters.SCENE_MODE_AUTO);
params.setRecordingHint(true);
List<String> supportedFocusModes = params.getSupportedFocusModes();
if (supportedFocusModes != null && !supportedFocusModes.isEmpty()) {
if (supportedFocusModes.contains(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE)) {
params.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE);
} else if (supportedFocusModes.contains(Camera.Parameters.FOCUS_MODE_AUTO)) {
params.setFocusMode(Camera.Parameters.FOCUS_MODE_AUTO);
mCamera.autoFocus(null);
} else {
params.setFocusMode(supportedFocusModes.get(0));
}
}
List<String> supportedFlashModes = params.getSupportedFlashModes();
if (supportedFlashModes != null && !supportedFlashModes.isEmpty()) {
if (supportedFlashModes.contains(Camera.Parameters.FLASH_MODE_TORCH)) {
if (mIsTorchOn) {
params.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
}
} else {
params.setFlashMode(supportedFlashModes.get(0));
}
}
mCamera.setParameters(params);
mCamera.setDisplayOrientation(mPreviewRotation);
try {
mCamera.setPreviewTexture(surfaceTexture);
} catch (IOException e) {
e.printStackTrace();
}
mCamera.startPreview();
return true;
}
public void stopCamera() {
disableEncoding();
stopTorch();
if (mCamera != null) {
mCamera.setPreviewCallback(null);
mCamera.stopPreview();
mCamera.release();
mCamera = null;
}
}
private Camera openCamera() {
Camera camera;
if (mCamId < 0) {
Camera.CameraInfo info = new Camera.CameraInfo();
int numCameras = Camera.getNumberOfCameras();
int frontCamId = -1;
int backCamId = -1;
for (int i = 0; i < numCameras; i++) {
Camera.getCameraInfo(i, info);
if (info.facing == Camera.CameraInfo.CAMERA_FACING_BACK) {
backCamId = i;
} else if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
frontCamId = i;
break;
}
}
if (frontCamId != -1) {
mCamId = frontCamId;
} else if (backCamId != -1) {
mCamId = backCamId;
} else {
mCamId = 0;
}
}
try {
camera = Camera.open(mCamId);
}catch (Exception e){
e.printStackTrace();
}
return camera;
}
private Camera.Size adaptPreviewResolution(Camera.Size resolution) {
float diff = 100f;
float xdy = (float) resolution.width / (float) resolution.height;
Camera.Size best = null;
for (Camera.Size size : mCamera.getParameters().getSupportedPreviewSizes()) {
if (size.equals(resolution)) {
return size;
}
float tmp = Math.abs(((float) size.width / (float) size.height) - xdy);
if (tmp < diff) {
diff = tmp;
best = size;
}
}
return best;
}
private int[] adaptFpsRange(int expectedFps, List<int[]> fpsRanges) {
expectedFps *= 1000;
int[] closestRange = fpsRanges.get(0);
int measure = Math.abs(closestRange[0] - expectedFps) + Math.abs(closestRange[1] - expectedFps);
for (int[] range : fpsRanges) {
if (range[0] <= expectedFps && range[1] >= expectedFps) {
int curMeasure = Math.abs(range[0] - expectedFps) + Math.abs(range[1] - expectedFps);
if (curMeasure < measure) {
closestRange = range;
measure = curMeasure;
}
}
}
return closestRange;
}
public boolean startTorch() {
if (mCamera != null) {
Camera.Parameters params = mCamera.getParameters();
List<String> supportedFlashModes = params.getSupportedFlashModes();
if (supportedFlashModes != null && !supportedFlashModes.isEmpty()) {
if (supportedFlashModes.contains(Camera.Parameters.FLASH_MODE_TORCH)) {
params.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
mCamera.setParameters(params);
return true;
}
}
}
return false;
}
public void stopTorch() {
if (mCamera != null) {
Camera.Parameters params = mCamera.getParameters();
params.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
mCamera.setParameters(params);
}
}
public interface PreviewCallback {
void onGetRgbaFrame(byte[] data, int width, int height);
}
}
|
package org.pikater.core.options;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Scanner;
import org.pikater.core.dataStructures.options.OptionDefault;
import org.pikater.core.dataStructures.options.StepanuvOption;
import org.pikater.core.dataStructures.options.types.AbstractOption;
import org.pikater.core.dataStructures.options.types.OptionInterval;
import org.pikater.core.dataStructures.options.types.OptionList;
import org.pikater.core.dataStructures.options.types.OptionValue;
import org.pikater.core.dataStructures.slots.Slot;
import com.thoughtworks.xstream.XStream;
public class LogicalUnitDescription
{
// TODO: use AppHelper instead?
public static String filePath = System.getProperty("user.dir")
+ System.getProperty("file.separator") + "src"
+ System.getProperty("file.separator") + "org"
+ System.getProperty("file.separator") + "pikater"
+ System.getProperty("file.separator") + "core"
+ System.getProperty("file.separator") + "options"
+ System.getProperty("file.separator");
protected Class<? extends Object> ontology = null;
private ArrayList<OptionDefault> options = new ArrayList<OptionDefault>();
private ArrayList<Slot> inputSlots = new ArrayList<Slot>();
private ArrayList<Slot> outputSlots = new ArrayList<Slot>();
public boolean getIsBox()
{
return this instanceof LogicalBoxDescription;
}
public Class<? extends Object> getOntology()
{
return ontology;
}
public void setOntology(Class<? extends Object> ontology)
{
this.ontology = ontology;
}
public ArrayList<OptionDefault> getOptions()
{
return options;
}
public void addOption(OptionDefault option)
{
this.options.add(option);
}
public ArrayList<Slot> getInputSlots()
{
return inputSlots;
}
public void setInputSlots(ArrayList<Slot> inputSlots)
{
this.inputSlots = inputSlots;
}
public void addInputSlot(Slot inputSlot)
{
this.inputSlots.add(inputSlot);
}
public ArrayList<Slot> getOutputSlots()
{
return outputSlots;
}
public void setOutputSlots(ArrayList<Slot> outputSlots)
{
this.outputSlots = outputSlots;
}
public void addOutputSlot(Slot outputSlot)
{
this.outputSlots.add(outputSlot);
}
public void exportXML() throws FileNotFoundException
{
// TODO: initialize XStream variable just once, with automatically processed aliases?
// TODO: see OptionXMLSerializer
System.out.println("Exporting: " + this.getClass().getSimpleName() + ".xml");
XStream xstream = new XStream();
if (this instanceof LogicalBoxDescription) {
xstream.alias("Box", this.getClass());
} else {
xstream.alias("LogicalUnit", this.getClass());
}
xstream.alias("AbstractOption", AbstractOption.class);
xstream.alias("OptionInterval", OptionInterval.class);
xstream.alias("OptionList", OptionList.class);
xstream.alias("OptionValue", OptionValue.class);
xstream.alias("OptionDefault", OptionDefault.class);
xstream.alias("Option", StepanuvOption.class);
xstream.aliasSystemAttribute("type", "class");
// TODO:
// xstream.alias("DataSlot", DataSlot.class);
// xstream.alias("ParameterSlot", ParameterSlot.class);
// xstream.alias("MethodSlot", MethodSlot.class);
String xml = xstream.toXML(this);
String fileName = filePath
+ this.getClass().getSimpleName() + ".xml";
PrintWriter file = new PrintWriter(fileName);
file.println(xml);
file.close();
}
public static LogicalUnitDescription importXML(File configFile) throws FileNotFoundException
{
// TODO: initialize XStream variable just once, with automatically processed aliases?
// TODO: see OptionXMLSerializer
System.out.println("Importing: " + configFile.getName());
Scanner scanner = new Scanner(configFile);
String content = scanner.useDelimiter("\\Z").next();
scanner.close();
XStream xstream = new XStream();
xstream.alias("LogicalUnit", LogicalUnitDescription.class);
xstream.alias("Box", LogicalBoxDescription.class);
xstream.alias("AbstractOption", AbstractOption.class);
xstream.alias("OptionInterval", OptionInterval.class);
xstream.alias("OptionList", OptionList.class);
xstream.alias("OptionValue", OptionValue.class);
xstream.alias("OptionDefault", OptionDefault.class);
xstream.alias("Option", StepanuvOption.class);
xstream.aliasSystemAttribute("type", "class");
// TODO:
// xstream.alias("DataSlot", DataSlot.class);
// xstream.alias("ParameterSlot", ParameterSlot.class);
// xstream.alias("MethodSlot", MethodSlot.class);
LogicalUnitDescription unit = (LogicalUnitDescription) xstream.fromXML(content);
return unit;
}
}
|
package org.broadinstitute.sting.utils.sam;
import net.sf.samtools.CigarOperator;
import net.sf.samtools.SAMRecord;
import net.sf.samtools.Cigar;
import net.sf.samtools.CigarElement;
import net.sf.samtools.util.StringUtil;
import org.broadinstitute.sting.gatk.contexts.ReferenceContext;
import org.broadinstitute.sting.utils.pileup.*;
import org.broadinstitute.sting.utils.StingException;
import org.broadinstitute.sting.utils.Utils;
import java.util.ArrayList;
import java.util.Arrays;
public class AlignmentUtils {
private static class MismatchCount {
public int numMismatches = 0;
public long mismatchQualities = 0;
}
/** Returns number of mismatches in the alignment <code>r</code> to the reference sequence
* <code>refSeq</code> assuming the alignment starts at (ZERO-based) position <code>refIndex</code> on the
* specified reference sequence; in other words, <code>refIndex</code> is used in place of alignment's own
* getAlignmentStart() coordinate and the latter is never used. However, the structure of the alignment <code>r</code>
* (i.e. it's cigar string with all the insertions/deletions it may specify) is fully respected.
*
* THIS CODE ASSUMES THAT ALL BYTES COME FROM UPPERCASED CHARS.
*
* @param r alignment
* @param refSeq chunk of reference sequence that subsumes the alignment completely (if alignment runs out of
* the reference string, IndexOutOfBound exception will be thrown at runtime).
* @param refIndex zero-based position, at which the alignment starts on the specified reference string.
* @return the number of mismatches
*/
public static int numMismatches(SAMRecord r, byte[] refSeq, int refIndex) {
return getMismatchCount(r, refSeq, refIndex).numMismatches;
}
@Deprecated
public static int numMismatches(SAMRecord r, String refSeq, int refIndex ) {
if ( r.getReadUnmappedFlag() ) return 1000000;
return numMismatches(r, StringUtil.stringToBytes(refSeq), refIndex);
}
public static long mismatchingQualities(SAMRecord r, byte[] refSeq, int refIndex) {
return getMismatchCount(r, refSeq, refIndex).mismatchQualities;
}
@Deprecated
public static long mismatchingQualities(SAMRecord r, String refSeq, int refIndex ) {
if ( r.getReadUnmappedFlag() ) return 1000000;
return numMismatches(r, StringUtil.stringToBytes(refSeq), refIndex);
}
// todo -- this code and mismatchesInRefWindow should be combined and optimized into a single
// todo -- high performance implementation. We can do a lot better than this right now
private static MismatchCount getMismatchCount(SAMRecord r, byte[] refSeq, int refIndex) {
MismatchCount mc = new MismatchCount();
int readIdx = 0;
byte[] readSeq = r.getReadBases();
Cigar c = r.getCigar();
for (int i = 0 ; i < c.numCigarElements() ; i++) {
CigarElement ce = c.getCigarElement(i);
switch ( ce.getOperator() ) {
case M:
for (int j = 0 ; j < ce.getLength() ; j++, refIndex++, readIdx++ ) {
if ( refIndex >= refSeq.length )
continue;
byte refChr = refSeq[refIndex];
byte readChr = readSeq[readIdx];
// Note: we need to count X/N's as mismatches because that's what SAM requires
//if ( BaseUtils.simpleBaseToBaseIndex(readChr) == -1 ||
// BaseUtils.simpleBaseToBaseIndex(refChr) == -1 )
// continue; // do not count Ns/Xs/etc ?
if ( readChr != refChr ) {
mc.numMismatches++;
mc.mismatchQualities += r.getBaseQualities()[readIdx];
}
}
break;
case I:
case S:
readIdx += ce.getLength();
break;
case D:
case N:
refIndex += ce.getLength();
break;
case H:
case P:
break;
default: throw new StingException("The " + ce.getOperator() + " cigar element is not currently supported");
}
}
return mc;
}
/** Returns the number of mismatches in the pileup within the given reference context.
*
* @param pileup the pileup with reads
* @param ref the reference context
* @param ignoreTargetSite if true, ignore mismatches at the target locus (i.e. the center of the window)
* @return the number of mismatches
*/
public static int mismatchesInRefWindow(ReadBackedPileup pileup, ReferenceContext ref, boolean ignoreTargetSite) {
int mismatches = 0;
for ( PileupElement p : pileup )
mismatches += mismatchesInRefWindow(p, ref, ignoreTargetSite);
return mismatches;
}
/** Returns the number of mismatches in the pileup element within the given reference context.
*
* @param p the pileup element
* @param ref the reference context
* @param ignoreTargetSite if true, ignore mismatches at the target locus (i.e. the center of the window)
* @return the number of mismatches
*/
public static int mismatchesInRefWindow(PileupElement p, ReferenceContext ref, boolean ignoreTargetSite) {
return mismatchesInRefWindow(p, ref, ignoreTargetSite, false);
}
/** Returns the number of mismatches in the pileup element within the given reference context.
*
* @param p the pileup element
* @param ref the reference context
* @param ignoreTargetSite if true, ignore mismatches at the target locus (i.e. the center of the window)
* @param qualitySumInsteadOfMismatchCount if true, return the quality score sum of the mismatches rather than the count
* @return the number of mismatches
*/
public static int mismatchesInRefWindow(PileupElement p, ReferenceContext ref, boolean ignoreTargetSite, boolean qualitySumInsteadOfMismatchCount) {
int sum = 0;
int windowStart = (int)ref.getWindow().getStart();
int windowStop = (int)ref.getWindow().getStop();
byte[] refBases = ref.getBases();
byte[] readBases = p.getRead().getReadBases();
byte[] readQualities = p.getRead().getBaseQualities();
Cigar c = p.getRead().getCigar();
int readIndex = 0;
int currentPos = p.getRead().getAlignmentStart();
int refIndex = Math.max(0, currentPos - windowStart);
for (int i = 0 ; i < c.numCigarElements() ; i++) {
CigarElement ce = c.getCigarElement(i);
int cigarElementLength = ce.getLength();
switch ( ce.getOperator() ) {
case M:
for (int j = 0; j < cigarElementLength; j++, readIndex++, currentPos++) {
// are we past the ref window?
if ( currentPos > windowStop )
break;
// are we before the ref window?
if ( currentPos < windowStart )
continue;
byte refChr = refBases[refIndex++];
// do we need to skip the target site?
if ( ignoreTargetSite && ref.getLocus().getStart() == currentPos )
continue;
byte readChr = readBases[readIndex];
if ( readChr != refChr )
sum += (qualitySumInsteadOfMismatchCount) ? readQualities[readIndex] : 1;
}
break;
case I:
case S:
readIndex += cigarElementLength;
break;
case D:
case N:
currentPos += cigarElementLength;
if ( currentPos > windowStart )
refIndex += Math.min(cigarElementLength, currentPos - windowStart);
break;
default:
// fail silently
return 0;
}
}
return sum;
}
/** Returns number of alignment blocks (continuous stretches of aligned bases) in the specified alignment.
* This method follows closely the SAMRecord::getAlignmentBlocks() implemented in samtools library, but
* it only counts blocks without actually allocating and filling the list of blocks themselves. Hence, this method is
* a much more efficient alternative to r.getAlignmentBlocks.size() in the situations when this number is all that is needed.
* Formally, this method simply returns the number of M elements in the cigar.
* @param r alignment
* @return number of continuous alignment blocks (i.e. 'M' elements of the cigar; all indel and clipping elements are ignored).
*/
public static int getNumAlignmentBlocks(final SAMRecord r) {
int n = 0;
final Cigar cigar = r.getCigar();
if (cigar == null) return 0;
for (final CigarElement e : cigar.getCigarElements()) {
if (e.getOperator() == CigarOperator.M ) n++;
}
return n;
}
public static char[] alignmentToCharArray( final Cigar cigar, final char[] read, final char[] ref ) {
final char[] alignment = new char[read.length];
int refPos = 0;
int alignPos = 0;
for ( int iii = 0 ; iii < cigar.numCigarElements() ; iii++ ) {
final CigarElement ce = cigar.getCigarElement(iii);
final int elementLength = ce.getLength();
switch( ce.getOperator() ) {
case I:
case S:
for ( int jjj = 0 ; jjj < elementLength; jjj++ ) {
alignment[alignPos++] = '+';
}
break;
case D:
case N:
refPos++;
break;
case M:
for ( int jjj = 0 ; jjj < elementLength; jjj++ ) {
alignment[alignPos] = ref[refPos];
alignPos++;
refPos++;
}
break;
case H:
case P:
break;
default:
throw new StingException( "Unsupported cigar operator: " + ce.getOperator() );
}
}
return alignment;
}
/**
* Due to (unfortunate) multiple ways to indicate that read is unmapped allowed by SAM format
* specification, one may need this convenience shortcut. Checks both 'read unmapped' flag and
* alignment reference index/start.
* @param r record
* @return true if read is unmapped
*/
public static boolean isReadUnmapped(final SAMRecord r) {
if ( r.getReadUnmappedFlag() ) return true;
// our life would be so much easier if all sam files followed the specs. In reality,
// sam files (including those generated by maq or bwa) miss headers alltogether. When
// reading such a SAM file, reference name is set, but since there is no sequence dictionary,
// null is always returned for referenceIndex. Let's be paranoid here, and make sure that
// we do not call the read "unmapped" when it has only reference name set with ref. index missing
// or vice versa.
if ( ( r.getReferenceIndex() != null && r.getReferenceIndex() != SAMRecord.NO_ALIGNMENT_REFERENCE_INDEX
|| r.getReferenceName() != null && r.getReferenceName() != SAMRecord.NO_ALIGNMENT_REFERENCE_NAME )
&& r.getAlignmentStart() != SAMRecord.NO_ALIGNMENT_START ) return false ;
return true;
}
/** Returns the array of base qualitites in the order the bases were read on the machine (i.e. always starting from
* cycle 1). In other words, if the read is unmapped or aligned in the forward direction, the read's own base
* qualities are returned as stored in the SAM record; if the read is aligned in the reverse direction, the array
* of read's base qualitites is inverted (in this case new array is allocated and returned).
* @param read
* @return
*/
public static byte [] getQualsInCycleOrder(SAMRecord read) {
if ( isReadUnmapped(read) || ! read.getReadNegativeStrandFlag() ) return read.getBaseQualities();
return Utils.reverse(read.getBaseQualities());
}
/** Takes the alignment of the read sequence <code>readSeq</code> to the reference sequence <code>refSeq</code>
* starting at 0-based position <code>refIndex</code> on the <code>refSeq</code> and specified by its <code>cigar</code>.
* The last argument <code>readIndex</code> specifies 0-based position on the read where the alignment described by the
* <code>cigar</code> starts. Usually cigars specify alignments of the whole read to the ref, so that readIndex is normally 0.
* Use non-zero readIndex only when the alignment cigar represents alignment of a part of the read. The refIndex in this case
* should be the position where the alignment of that part of the read starts at. In other words, both refIndex and readIndex are
* always the positions where the cigar starts on the ref and on the read, respectively.
*
* If the alignment has an indel, then this method attempts moving this indel left across a stretch of repetitive bases. For instance, if the original cigar
* specifies that (any) one AT is deleted from a repeat sequence TATATATA, the output cigar will always mark the leftmost AT
* as deleted. If there is no indel in the original cigar, or the indel position is determined unambiguously (i.e. inserted/deleted sequence
* is not repeated), the original cigar is returned.
* @param cigar structure of the original alignment
* @param refSeq reference sequence the read is aligned to
* @param readSeq read sequence
* @param refIndex 0-based alignment start position on ref
* @param readIndex 0-based alignment start position on read
* @return a cigar, in which indel is guaranteed to be placed at the leftmost possible position across a repeat (if any)
*/
public static Cigar leftAlignIndel(Cigar cigar, final byte[] refSeq, final byte[] readSeq, final int refIndex, final int readIndex) {
int indexOfIndel = -1;
for ( int i = 0; i < cigar.numCigarElements(); i++ ) {
CigarElement ce = cigar.getCigarElement(i);
if ( ce.getOperator() == CigarOperator.D || ce.getOperator() == CigarOperator.I ) {
// if there is more than 1 indel, don't left align
if ( indexOfIndel != -1 )
return cigar;
indexOfIndel = i;
}
}
// if there is no indel or if the alignment starts with an insertion (so that there
// is no place on the read to move that insertion further left), we are done
if ( indexOfIndel < 1 ) return cigar;
final int indelLength = cigar.getCigarElement(indexOfIndel).getLength();
byte[] altString = createIndelString(cigar, indexOfIndel, refSeq, readSeq, refIndex, readIndex);
Cigar newCigar = cigar;
for ( int i = 0; i < indelLength; i++ ) {
newCigar = moveCigarLeft(newCigar, indexOfIndel);
byte[] newAltString = createIndelString(newCigar, indexOfIndel, refSeq, readSeq, refIndex, readIndex);
// check to make sure we haven't run off the end of the read
boolean reachedEndOfRead = cigarHasZeroSizeElement(newCigar);
if ( Arrays.equals(altString, newAltString) ) {
cigar = newCigar;
i = -1;
if ( reachedEndOfRead )
cigar = cleanUpCigar(cigar);
}
if ( reachedEndOfRead )
break;
}
return cigar;
}
private static boolean cigarHasZeroSizeElement(Cigar c) {
for ( CigarElement ce : c.getCigarElements() ) {
if ( ce.getLength() == 0 )
return true;
}
return false;
}
private static Cigar cleanUpCigar(Cigar c) {
ArrayList<CigarElement> elements = new ArrayList<CigarElement>(c.numCigarElements()-1);
for ( CigarElement ce : c.getCigarElements() ) {
if ( ce.getLength() != 0 &&
(elements.size() != 0 || ce.getOperator() != CigarOperator.D) ) {
elements.add(ce);
}
}
return new Cigar(elements);
}
private static Cigar moveCigarLeft(Cigar cigar, int indexOfIndel) {
// get the first few elements
ArrayList<CigarElement> elements = new ArrayList<CigarElement>(cigar.numCigarElements());
for ( int i = 0; i < indexOfIndel - 1; i++)
elements.add(cigar.getCigarElement(i));
// get the indel element and move it left one base
CigarElement ce = cigar.getCigarElement(indexOfIndel-1);
elements.add(new CigarElement(ce.getLength()-1, ce.getOperator()));
elements.add(cigar.getCigarElement(indexOfIndel));
if ( indexOfIndel+1 < cigar.numCigarElements() ) {
ce = cigar.getCigarElement(indexOfIndel+1);
elements.add(new CigarElement(ce.getLength()+1, ce.getOperator()));
} else {
elements.add(new CigarElement(1, CigarOperator.M));
}
// get the last few elements
for ( int i = indexOfIndel + 2; i < cigar.numCigarElements(); i++)
elements.add(cigar.getCigarElement(i));
return new Cigar(elements);
}
private static byte[] createIndelString(final Cigar cigar, final int indexOfIndel, final byte[] refSeq, final byte[] readSeq, int refIndex, int readIndex) {
CigarElement indel = cigar.getCigarElement(indexOfIndel);
int indelLength = indel.getLength();
// the indel-based reference string
byte[] alt = new byte[refSeq.length + (indelLength * (indel.getOperator() == CigarOperator.D ? -1 : 1))];
for ( int i = 0; i < indexOfIndel; i++ ) {
CigarElement ce = cigar.getCigarElement(i);
int length = ce.getLength();
switch( ce.getOperator() ) {
case M:
readIndex += length;
refIndex += length;
break;
case S:
readIndex += length;
break;
case N:
refIndex += length;
break;
default:
break;
}
}
// add the bases before the indel
System.arraycopy(refSeq, 0, alt, 0, refIndex);
int currentPos = refIndex;
// take care of the indel
if ( indel.getOperator() == CigarOperator.D ) {
refIndex += indelLength;
} else {
System.arraycopy(readSeq, readIndex, alt, currentPos, indelLength);
currentPos += indelLength;
}
// add the bases after the indel
System.arraycopy(refSeq, refIndex, alt, currentPos, refSeq.length - refIndex);
return alt;
}
/** Takes the alignment of the read sequence <code>readSeq</code> to the reference sequence <code>refSeq</code>
* starting at 0-based position <code>refIndex</code> on the <code>refSeq</code> and specified by its <code>cigar</code>.
* The last argument <code>readIndex</code> specifies 0-based position on the read where the alignment described by the
* <code>cigar</code> starts. Usually cigars specify alignments of the whole read to the ref, so that readIndex is normally 0.
* Use non-zero readIndex only when the alignment cigar represents alignment of a part of the read. The refIndex in this case
* should be the position where the alignment of that part of the read starts at. In other words, both refIndex and readIndex are
* always the positions where the cigar starts on the ref and on the read, respectively.
*
* If the alignment has an indel, then this method attempts moving this indel left across a stretch of repetitive bases. For instance, if the original cigar
* specifies that (any) one AT is deleted from a repeat sequence TATATATA, the output cigar will always mark the leftmost AT
* as deleted. If there is no indel in the original cigar, or the indel position is determined unambiguously (i.e. inserted/deleted sequence
* is not repeated), the original cigar is returned.
* @param cigar structure of the original alignment
* @param refSeq reference sequence the read is aligned to
* @param readSeq read sequence
* @param refIndex 0-based alignment start position on ref
* @param readIndex 0-based alignment start position on read
* @return a cigar, in which indel is guaranteed to be placed at the leftmost possible position across a repeat (if any)
*/
}
|
package name.raev.kaloyan.android.sapdkomsofia2013;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.AnimationUtils;
import android.webkit.CookieSyncManager;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
public class MainActivity extends Activity {
private final static String HOME_PAGE_URL = "https://dkom.netweaver.ondemand.com/index1.html";
private final static String DKOM_SOFIA_WIKI_URL = "https://wiki.wdf.sap.corp/wiki/display/DKOM/Sofia";
private final static List<String> APP_HOSTS = Arrays.asList(
"dkom.hana.ondemand.com",
"dkom.netweaver.ondemand.com",
"api.twitter.com");
protected FrameLayout webViewPlaceholder;
protected WebView webView;
protected View splash;
protected View errorView;
protected View eventOverView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// initialize the cookie manager
CookieSyncManager.createInstance(this);
// initialize the UI
initUI();
}
@Override
protected void onResume() {
super.onResume();
// request the cookie manager to start sync
CookieSyncManager.getInstance().startSync();
}
@Override
protected void onPause() {
super.onPause();
// request the cookie manager to stop sync
CookieSyncManager.getInstance().stopSync();
}
protected void initUI() {
// retrieve UI elements
webViewPlaceholder = ((FrameLayout)findViewById(R.id.webViewPlaceholder));
// initialize the WebView if necessary
if (webView == null)
{
// create the web view
webView = new WebView(this);
// fill the entire activity
webView.setLayoutParams(new ViewGroup.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
// enable JavaScript
webView.getSettings().setJavaScriptEnabled(true);
// load images automatically
webView.getSettings().setLoadsImagesAutomatically(true);
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// create the splash screen
splash = inflater.inflate(R.layout.splash, null);
splash.setVisibility(View.GONE);
// create the error screen
errorView = inflater.inflate(R.layout.error, null);
errorView.setVisibility(View.GONE);
errorView.findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// reset the progress bar
ProgressBar progressBar = (ProgressBar) splash.findViewById(R.id.progress);
progressBar.setProgress(0);
// hide the error screen
errorView.setVisibility(View.GONE);
// reload the URL
webView.reload();
}
});
// create the "event is over" screen
eventOverView = inflater.inflate(R.layout.over, null);
eventOverView.setVisibility(View.GONE);
eventOverView.findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// load the DKOM wiki
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(DKOM_SOFIA_WIKI_URL));
startActivity(intent);
}
});
final Activity activity = this;
webView.setWebChromeClient(new WebChromeClient() {
@Override
public void onProgressChanged(WebView view, int progress) {
// update the progress bar with the progress of the web view
ProgressBar progressBar = (ProgressBar) splash.findViewById(R.id.progress);
progressBar.setProgress(progress);
}
});
webView.setWebViewClient(new WebViewClient() {
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
// show the splash screen
splash.setVisibility(View.VISIBLE);
}
@Override
public void onPageFinished(WebView view, String url) {
if (splash.getVisibility() == View.VISIBLE) {
// hide the splash screen with a fade out animation
splash.startAnimation(AnimationUtils.loadAnimation(activity, android.R.anim.fade_out));
splash.setVisibility(View.GONE);
}
}
@Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
// set the error message
TextView message = (TextView) errorView.findViewById(R.id.message);
message.setText(String.format(getResources().getString(R.string.connect_error), description));
// show the error screen
errorView.setVisibility(View.VISIBLE);
}
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
String host = Uri.parse(url).getHost();
if (APP_HOSTS.contains(host) && // this is my web site - let my WebView load the page
!url.contains("/ical/")) { // this is *.ics file - download with external browser
return false;
}
// otherwise, the link is not for a page on my site, so launch another Activity that handles URLs
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(intent);
return true;
}
});
if (isEventOver()) {
// show the "event is over" screen
eventOverView.setVisibility(View.VISIBLE);
} else {
// load the index page
webView.loadUrl(HOME_PAGE_URL);
}
}
// attach the web views and the other views to its placeholder
webViewPlaceholder.addView(webView);
webViewPlaceholder.addView(splash);
webViewPlaceholder.addView(errorView);
webViewPlaceholder.addView(eventOverView);
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
if (webView != null) {
// remove the web view and the other views from the old placeholder
webViewPlaceholder.removeView(eventOverView);
webViewPlaceholder.removeView(errorView);
webViewPlaceholder.removeView(splash);
webViewPlaceholder.removeView(webView);
}
super.onConfigurationChanged(newConfig);
// load the layout resource for the new configuration
setContentView(R.layout.activity_main);
// reinitialize the UI
initUI();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
// save the state of the WebView
webView.saveState(outState);
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
// restore the state of the WebView
webView.restoreState(savedInstanceState);
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
// check if the key event was the Back button and if there's history
if ((keyCode == KeyEvent.KEYCODE_BACK) && webView.canGoBack()) {
webView.goBack();
return true;
}
// if it wasn't the Back key or there's no web page history, bubble up
// to the default system behavior (probably exit the activity)
return super.onKeyDown(keyCode, event);
}
private boolean isEventOver() {
try {
Date now = new Date();
Date end = new SimpleDateFormat("yyyy-MM-dd").parse("2013-03-21"); // 21 March 2013
return now.after(end);
} catch (ParseException e) {
e.printStackTrace();
return false;
}
}
}
|
package org.plantuml.idea.toolwindow;
import com.intellij.openapi.actionSystem.ActionGroup;
import com.intellij.openapi.actionSystem.ActionManager;
import com.intellij.openapi.actionSystem.ActionPlaces;
import com.intellij.openapi.actionSystem.ActionToolbar;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.EditorFactory;
import com.intellij.openapi.editor.event.CaretEvent;
import com.intellij.openapi.editor.event.CaretListener;
import com.intellij.openapi.editor.event.DocumentEvent;
import com.intellij.openapi.editor.event.DocumentListener;
import com.intellij.openapi.fileEditor.FileEditorManager;
import com.intellij.openapi.fileEditor.FileEditorManagerEvent;
import com.intellij.openapi.fileEditor.FileEditorManagerListener;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.project.ProjectManager;
import com.intellij.openapi.project.ProjectManagerListener;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.wm.ToolWindow;
import com.intellij.ui.components.JBScrollPane;
import com.intellij.util.messages.MessageBus;
import org.jetbrains.annotations.NotNull;
import org.plantuml.idea.action.SelectPageAction;
import org.plantuml.idea.plantuml.PlantUml;
import org.plantuml.idea.plantuml.PlantUmlResult;
import org.plantuml.idea.util.LazyApplicationPoolExecutor;
import org.plantuml.idea.util.UIUtils;
import javax.swing.*;
import javax.swing.event.AncestorEvent;
import javax.swing.event.AncestorListener;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import static com.intellij.codeInsight.completion.CompletionInitializationContext.DUMMY_IDENTIFIER;
/**
* @author Eugene Steinberg
*/
public class PlantUmlToolWindow extends JPanel {
private static Logger logger = Logger.getInstance(PlantUmlToolWindow.class);
private ToolWindow toolWindow;
private JLabel imageLabel;
private int zoom = 100;
private int page = 0;
private int numPages = 1;
private String cachedSource = "";
private int cachedPage = page;
private int cachedZoom = zoom;
private FileEditorManagerListener plantUmlVirtualFileListener = new PlantUmlFileManagerListener();
private DocumentListener plantUmlDocumentListener = new PlantUmlDocumentListener();
private CaretListener plantUmlCaretListener = new PlantUmlCaretListener();
private AncestorListener plantUmlAncestorListener = new PlantUmlAncestorListener();
private ProjectManagerListener plantUmlProjectManagerListener = new PlantUmlProjectManagerListener();
private LazyApplicationPoolExecutor lazyExecutor = new LazyApplicationPoolExecutor();
private SelectPageAction selectPageAction;
public PlantUmlToolWindow(Project myProject, ToolWindow toolWindow) {
super(new BorderLayout());
this.toolWindow = toolWindow;
UIUtils.addProject(myProject, this);
setupUI();
registerListeners(myProject);
}
private void setupUI() {
ActionGroup group = (ActionGroup) ActionManager.getInstance().getAction("PlantUML.Toolbar");
final ActionToolbar actionToolbar = ActionManager.getInstance().createActionToolbar(ActionPlaces.UNKNOWN, group, true);
actionToolbar.setTargetComponent(this);
add(actionToolbar.getComponent(), BorderLayout.PAGE_START);
imageLabel = new JLabel();
JScrollPane scrollPane = new JBScrollPane(imageLabel);
add(scrollPane, BorderLayout.CENTER);
selectPageAction = (SelectPageAction) ActionManager.getInstance().getAction("PlantUML.SelectPage");
}
private void registerListeners(Project myProject) {
logger.debug("Registering listeners");
MessageBus messageBus = myProject.getMessageBus();
messageBus.connect().subscribe(FileEditorManagerListener.FILE_EDITOR_MANAGER, plantUmlVirtualFileListener);
EditorFactory.getInstance().getEventMulticaster().addDocumentListener(plantUmlDocumentListener);
EditorFactory.getInstance().getEventMulticaster().addCaretListener(plantUmlCaretListener);
toolWindow.getComponent().addAncestorListener(plantUmlAncestorListener);
ProjectManager.getInstance().addProjectManagerListener(plantUmlProjectManagerListener);
renderLater(myProject);
}
private void unregisterListeners() {
EditorFactory.getInstance().getEventMulticaster().removeDocumentListener(plantUmlDocumentListener);
EditorFactory.getInstance().getEventMulticaster().removeCaretListener(plantUmlCaretListener);
toolWindow.getComponent().removeAncestorListener(plantUmlAncestorListener);
ProjectManager.getInstance().removeProjectManagerListener(plantUmlProjectManagerListener);
}
private boolean renderRequired(String newSource) {
if (newSource.isEmpty())
return false;
if (!newSource.equals(cachedSource) || page != cachedPage || zoom != cachedZoom) {
cachedSource = newSource;
cachedPage = page;
cachedZoom = zoom;
return true;
}
return false;
}
private void renderLater(final Project project) {
if (project == null) return;
PlantUmlToolWindow toolWindow = UIUtils.getToolWindow(project);
if (toolWindow != this) {
if (toolWindow != null) {
toolWindow.renderLater(project);
}
return;
}
ApplicationManager.getApplication().invokeLater(new Runnable() {
@Override
public void run() {
if (!isProjectValid(project))
return;
final String source = UIUtils.getSelectedSourceWithCaret(project);
if (!renderRequired(source))
return;
final File selectedDir = UIUtils.getSelectedDir(project);
lazyExecutor.execute(
new Runnable() {
@Override
public void run() {
renderWithBaseDir(project, source, selectedDir, page);
}
}
);
}
});
}
private void renderWithBaseDir(Project myProject, String source, File baseDir, int pageNum) {
if (source.isEmpty())
return;
PlantUmlResult result = PlantUml.render(source, baseDir, pageNum);
try {
final BufferedImage image = UIUtils.getBufferedImage(result.getDiagramBytes());
if (image != null) {
ApplicationManager.getApplication().invokeLater(new Runnable() {
public void run() {
UIUtils.setImage(image, imageLabel, zoom);
}
});
}
setNumPages(myProject, result.getPages());
} catch (Exception e) {
logger.warn("Exception occurred rendering source = " + source + ": " + e);
}
}
public int getZoom() {
return zoom;
}
public void setZoom(Project myProject, int zoom) {
this.zoom = zoom;
renderLater(myProject);
}
public void setPage(Project myProject, int page) {
if (page >= 0 && page < numPages) {
this.page = page;
selectPageAction.setPage(page);
renderLater(myProject);
}
}
public void nextPage(Project myProject) {
setPage(myProject, this.page + 1);
}
public void prevPage(Project myProject) {
setPage(myProject, this.page - 1);
}
public void setNumPages(Project myProject, int numPages) {
this.numPages = numPages;
if (page >= numPages)
setPage(myProject, numPages - 1);
selectPageAction.setNumPages(numPages);
}
private class PlantUmlFileManagerListener implements FileEditorManagerListener {
public void fileOpened(@NotNull FileEditorManager source, @NotNull VirtualFile file) {
logger.debug("file opened " + file);
}
public void fileClosed(@NotNull FileEditorManager source, @NotNull VirtualFile file) {
logger.debug("file closed = " + file);
}
public void selectionChanged(@NotNull FileEditorManagerEvent event) {
logger.debug("selection changed" + event);
renderLater(event.getManager().getProject());
}
}
private class PlantUmlDocumentListener implements DocumentListener {
public void beforeDocumentChange(DocumentEvent event) {
}
public void documentChanged(DocumentEvent event) {
logger.debug("document changed " + event);
//#18 Strange "IntellijIdeaRulezzz" - filter code completion event.
if (!DUMMY_IDENTIFIER.equals(event.getNewFragment().toString())) {
Editor[] editors = EditorFactory.getInstance().getEditors(event.getDocument());
for (Editor editor : editors) {
renderLater(editor.getProject());
}
}
}
}
private boolean isProjectValid(Project project) {
return project != null && !project.isDisposed();
}
private class PlantUmlCaretListener implements CaretListener {
@Override
public void caretPositionChanged(final CaretEvent e) {
renderLater(e.getEditor().getProject());
}
@Override
public void caretAdded(CaretEvent e) {
renderLater(e.getEditor().getProject());
}
@Override
public void caretRemoved(CaretEvent e) {
// do nothing
}
}
private class PlantUmlAncestorListener implements AncestorListener {
@Override
public void ancestorAdded(AncestorEvent ancestorEvent) {
Project[] projects = ProjectManager.getInstance().getOpenProjects();
for (Project project : projects) {
renderLater(project);
}
}
@Override
public void ancestorRemoved(AncestorEvent ancestorEvent) {
// do nothing
}
@Override
public void ancestorMoved(AncestorEvent ancestorEvent) {
// do nothing
}
}
private class PlantUmlProjectManagerListener implements ProjectManagerListener {
@Override
public void projectOpened(Project project) {
logger.debug("opened project " + project);
registerListeners(project);
}
@Override
public boolean canCloseProject(Project project) {
return true;
}
@Override
public void projectClosed(Project project) {
logger.debug("closed project " + project);
}
@Override
public void projectClosing(Project project) {
UIUtils.removeProject(project);
unregisterListeners();
}
}
public int getPage() {
return page;
}
}
|
package pixlepix.minechem.common;
import cpw.mods.fml.common.registry.LanguageRegistry;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraftforge.common.Configuration;
import net.minecraftforge.oredict.OreDictionary;
import pixlepix.minechem.api.core.EnumElement;
import pixlepix.minechem.common.items.*;
import pixlepix.minechem.common.polytool.ItemPolytool;
import pixlepix.minechem.common.utils.MinechemHelper;
public class MinechemItems {
public static ItemElement element;
public static ItemMolecule molecule;
public static ItemLens lens;
public static ItemAtomicManipulator atomicManipulator;
public static ItemFusionStar fusionStar;
public static ItemBlueprint blueprint;
//public static ItemTestTube testTube;
public static ItemChemistJournal journal;
//public static ItemArmorRadiationShield hazmatFeet;
//public static ItemArmorRadiationShield hazmatLegs;
//public static ItemArmorRadiationShield hazmatTorso;
//public static ItemArmorRadiationShield hazmatHead;
public static ItemStack convexLens;
public static ItemStack concaveLens;
public static ItemStack projectorLens;
public static ItemStack microscopeLens;
public static PhotonicInduction IAintAvinit;
public static ItemPills EmptyPillz;
public static ItemStack minechempills;
public static Item polytool;
private static int polytoolID;
private static int elementID;
private static int moleculeID;
private static int atomicManipulatorID;
private static int lensID;
private static int fusionStarID;
private static int blueprintID;
private static int testTubeID;
private static int journalID;
private static int hazmatFeetID;
private static int hazmatLegsID;
private static int hazmatTorsoID;
private static int hazmatHeadID;
private static int photonID;
private static int pillzID;
public static void loadConfig(Configuration config) {
int baseID = 4736;
elementID = getItemConfig(config, "Element", baseID++);
moleculeID = getItemConfig(config, "Molecule", baseID++);
lensID = getItemConfig(config, "Lens", baseID++);
atomicManipulatorID = getItemConfig(config, "AtomicManipulator", baseID++);
fusionStarID = getItemConfig(config, "FusionStar", baseID++);
blueprintID = getItemConfig(config, "Blueprint", baseID++);
testTubeID = getItemConfig(config, "TestTube", baseID++);
journalID = getItemConfig(config, "ChemistJournal", baseID++);
hazmatFeetID = getItemConfig(config, "HazmatFeet", baseID++);
hazmatLegsID = getItemConfig(config, "HazmatLegs", baseID++);
hazmatTorsoID = getItemConfig(config, "HazmatTorso", baseID++);
hazmatHeadID = getItemConfig(config, "HazmatHead", baseID++);
//photonID = getItemConfig(config, "Hammer", baseID++);
pillzID = getItemConfig(config, "EmptyPills", baseID++);
polytoolID = getItemConfig(config, "Polytool", baseID++);
}
private static int getItemConfig(Configuration config, String key, int defaultID) {
return config.getItem(Configuration.CATEGORY_ITEM, key, defaultID).getInt(defaultID);
}
public static void registerItems() {
element = new ItemElement(elementID);
molecule = new ItemMolecule(moleculeID);
lens = new ItemLens(lensID);
atomicManipulator = new ItemAtomicManipulator(atomicManipulatorID);
fusionStar = new ItemFusionStar(fusionStarID);
blueprint = new ItemBlueprint(blueprintID);
//Test tube removed
//testTube = new ItemTestTube(testTubeID);
journal = new ItemChemistJournal(journalID);
//hazmatFeet = new ItemArmorRadiationShield(hazmatFeetID, 3, 0.1F, ConstantValue.HAZMAT_FEET_TEX);
//hazmatLegs = new ItemArmorRadiationShield(hazmatLegsID, 2, 0.1F, ConstantValue.HAZMAT_LEGS_TEX);
//hazmatTorso = new ItemArmorRadiationShield(hazmatTorsoID, 1, 0.5F, ConstantValue.HAZMAT_TORSO_TEX);
//hazmatHead = new ItemArmorRadiationShield(hazmatHeadID, 0, 0.2F, ConstantValue.HAZMAT_HEAD_TEX);
//IAintAvinit = new PhotonicInduction(photonID, EnumToolMaterial.IRON, 5F);
EmptyPillz = new ItemPills(pillzID, 0);
polytool = new ItemPolytool(polytoolID);
LanguageRegistry.addName(polytool, MinechemHelper.getLocalString("item.name.polytool"));
LanguageRegistry.addName(atomicManipulator, MinechemHelper.getLocalString("item.name.atomicmanipulator"));
LanguageRegistry.addName(fusionStar, MinechemHelper.getLocalString("item.name.fusionStar"));
//LanguageRegistry.addName(testTube, MinechemHelper.getLocalString("item.name.testtube"));
LanguageRegistry.addName(journal, MinechemHelper.getLocalString("item.name.chemistJournal"));
//LanguageRegistry.addName(hazmatFeet, MinechemHelper.getLocalString("item.name.hazmatFeet"));
//LanguageRegistry.addName(hazmatLegs, MinechemHelper.getLocalString("item.name.hazmatLegs"));
//LanguageRegistry.addName(hazmatTorso, MinechemHelper.getLocalString("item.name.hazmatTorso"));
//LanguageRegistry.addName(hazmatHead, MinechemHelper.getLocalString("item.name.hazmatHead"));
LanguageRegistry.addName(IAintAvinit, "PhotonicInduction's Hammer");
LanguageRegistry.addName(EmptyPillz, "Pills");
concaveLens = new ItemStack(lens, 1, 0);
convexLens = new ItemStack(lens, 1, 1);
microscopeLens = new ItemStack(lens, 1, 2);
projectorLens = new ItemStack(lens, 1, 3);
minechempills = new ItemStack(EmptyPillz, 1, 0);
}
public static void registerToOreDictionary() {
for (EnumElement element : EnumElement.values()) {
OreDictionary.registerOre("element" + element.descriptiveName(), new ItemStack(MinechemItems.element, 1, element.ordinal()));
}
}
}
|
package org.plugins.simplefreeze.managers;
import org.bukkit.entity.Player;
import org.plugins.simplefreeze.objects.FrozenPlayer;
import java.util.HashMap;
import java.util.UUID;
public class PlayerManager {
// private final SimpleFreezeMain plugin;
private HashMap<UUID, FrozenPlayer> frozenPlayers = new HashMap<UUID, FrozenPlayer>();
// public PlayerManager(SimpleFreezeMain plugin) {
// this.plugin = plugin;
public HashMap<UUID, FrozenPlayer> getFrozenPlayers() {
return this.frozenPlayers;
}
public void addFrozenPlayer(UUID uuid, FrozenPlayer frozenPlayer) {
this.frozenPlayers.put(uuid, frozenPlayer);
}
public void removeFrozenPlayer(Player p) {
this.frozenPlayers.remove(p.getUniqueId());
}
public void removeFrozenPlayer(UUID uuid) {
this.frozenPlayers.remove(uuid);
}
public boolean isFrozen(Player p) {
return this.isFrozen(p.getUniqueId());
}
public boolean isFrozen(UUID uuid) {
return this.frozenPlayers.containsKey(uuid);
}
public boolean isSQLFrozen(UUID uuid) {
return this.frozenPlayers.containsKey(uuid) ? this.frozenPlayers.get(uuid).isSqlFreeze() : false;
}
public FrozenPlayer getFrozenPlayer(Player p) {
return this.getFrozenPlayer(p.getUniqueId());
}
public FrozenPlayer getFrozenPlayer(UUID uuid) {
return this.isFrozen(uuid) ? this.frozenPlayers.get(uuid) : null;
}
}
|
// FIXME audit for any concurrency issues. It seems highly likely that the
// invalidation implied by the changed dict is robust, but need to verify
// via scenario analysis.
// However, current structures should be resilient against corruption.
// FIXME replace commented-out prints with appropriate logging, or remove
package org.python.tools.fireside;
import java.util.Collections;
import java.util.Enumeration;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutionException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import org.python.core.Py;
import org.python.core.PyObject;
import org.python.core.PyString;
import org.python.core.PyTuple;
import org.python.core.codecs;
import org.python.google.common.base.CharMatcher;
import org.python.google.common.cache.CacheBuilder;
import org.python.google.common.cache.CacheLoader;
import org.python.google.common.cache.LoadingCache;
import org.python.google.common.collect.ForwardingConcurrentMap;
import org.python.google.common.collect.ImmutableList;
import org.python.google.common.collect.Iterators;
public class RequestBridge {
private final HttpServletRequest request;
private final LoadingCache<PyObject, PyObject> cache;
private final Set<PyObject> changed = Collections.newSetFromMap(new ConcurrentHashMap());
private final Map<String, String> mapCGI;
// keys
private static final String WSGI_VERSION = "wsgi.version";
private static final String WSGI_MULTITHREAD = "wsgi.multithread";
private static final String WSGI_MULTIPROCESS = "wsgi.multiprocess";
private static final String WSGI_RUN_ONCE = "wsgi.run_once";
private static final String WSGI_ERRORS = "wsgi.errors";
private static final String WSGI_INPUT = "wsgi.input";
private static final String WSGI_URL_SCHEME = "wsgi.url_scheme";
private static final PyString PY_WSGI_URL_SCHEME = Py.newString(WSGI_URL_SCHEME);
private static final String REQUEST_METHOD = "REQUEST_METHOD";
private static final PyString PY_REQUEST_METHOD = Py.newString(REQUEST_METHOD);
private static final String SCRIPT_NAME = "SCRIPT_NAME";
private static final PyString PY_SCRIPT_NAME = Py.newString(SCRIPT_NAME);
private static final String PATH_INFO = "PATH_INFO";
private static final PyString PY_PATH_INFO = Py.newString(PATH_INFO);
private static final String QUERY_STRING = "QUERY_STRING";
private static final PyString PY_QUERY_STRING = Py.newString(QUERY_STRING);
private static final String CONTENT_TYPE = "CONTENT_TYPE";
private static final PyString PY_CONTENT_TYPE = Py.newString(CONTENT_TYPE);
private static final String REMOTE_ADDR = "REMOTE_ADDR";
private static final PyString PY_REMOTE_ADDR = Py.newString(REMOTE_ADDR);
private static final String REMOTE_HOST = "REMOTE_HOST";
private static final PyString PY_REMOTE_HOST = Py.newString(REMOTE_HOST);
private static final String REMOTE_PORT = "REMOTE_PORT";
private static final PyString PY_REMOTE_PORT = Py.newString(REMOTE_PORT);
private static final String SERVER_NAME = "SERVER_NAME";
private static final PyString PY_SERVER_NAME = Py.newString(SERVER_NAME);
private static final String SERVER_PORT = "SERVER_PORT";
private static final PyString PY_SERVER_PORT = Py.newString(SERVER_PORT);
private static final String SERVER_PROTOCOL = "SERVER_PROTOCOL";
private static final PyString PY_SERVER_PROTOCOL = Py.newString(SERVER_PROTOCOL);
private static final String CONTENT_LENGTH = "CONTENT_LENGTH";
private static final PyString PY_CONTENT_LENGTH = Py.newString(CONTENT_LENGTH);
public RequestBridge(final HttpServletRequest request, final PyObject errLog, final PyObject wsgiInputStream) {
this.request = request;
mapCGI = getMappingForCGI(request);
// Cache all keys for a request - we are effectively building up the environ lazily,
// while using updates to track for the request wrapper.
// This reduces overhead if not all keys are used, because of rewrites to/from latin1
// encoding and other conversions and especially if not all keys are rewritten
// in a servlet filter.
cache = CacheBuilder.newBuilder().build(
new CacheLoader<PyObject, PyObject>() {
public PyObject load(PyObject key) throws ExecutionException {
if (changed.contains(key)) {
System.err.println("Do not load key=" + key);
throw new ExecutionException(null);
}
System.err.println("Loading key=" + key);
// Unwrap so we can take advantage of Java 7's support for
// efficient string switch, via hashing. Effectively the below switch
// is a hash table.
String k = key.toString();
switch (k) {
case WSGI_VERSION:
return new PyTuple(Py.One, Py.Zero);
case WSGI_MULTITHREAD:
return Py.True;
case WSGI_MULTIPROCESS:
return Py.False;
case WSGI_RUN_ONCE:
return Py.False;
case WSGI_ERRORS:
return errLog;
case WSGI_INPUT:
return wsgiInputStream;
case WSGI_URL_SCHEME:
return latin1(request.getScheme());
case REQUEST_METHOD:
return latin1(request.getMethod());
case SCRIPT_NAME:
return latin1(request.getServletPath());
case PATH_INFO:
return emptyIfNull(request.getPathInfo());
case QUERY_STRING:
return emptyIfNull(request.getQueryString());
case CONTENT_TYPE:
return emptyIfNull(request.getContentType());
case REMOTE_ADDR:
return latin1(request.getRemoteAddr());
case REMOTE_HOST:
return latin1(request.getRemoteHost());
case REMOTE_PORT:
return Py.newString(String.valueOf(request.getRemotePort()));
case SERVER_NAME:
return latin1(request.getLocalName());
case SERVER_PORT:
return Py.newString(String.valueOf(request.getLocalPort()));
case SERVER_PROTOCOL:
return latin1(request.getProtocol());
case CONTENT_LENGTH:
return getContentLength();
default:
return getHeader(k);
}
}
});
}
static private PyString latin1(String s) {
if (CharMatcher.ASCII.matchesAllOf(s)) {
return Py.newString(s);
} else {
return Py.newString(codecs.PyUnicode_EncodeLatin1(s, s.length(), null));
}
}
static private PyString emptyIfNull(String s) {
if (s == null) {
return Py.EmptyString;
} else {
return latin1(s);
}
}
private PyString getContentLength() throws ExecutionException {
int length = request.getContentLength();
if (length != -1) {
return Py.newString(String.valueOf(length));
} else {
throw new ExecutionException(null);
}
}
private static Map<String, String> getMappingForCGI(HttpServletRequest request) {
Enumeration<String> names = request.getHeaderNames();
Map<String, String> mapping = new LinkedHashMap();
while (names.hasMoreElements()) {
String name = names.nextElement();
// It is possible that this mapping is not bijective, but that's just a basic
// problem with CGI/WSGI naming. Also I would assume that real usage of HTTP headers
// are not going to do that.
// Regardless, we preserve the ordering of entries via the LinkedHashMap.
String cgiName = "HTTP_" + name.replace('-', '_').toUpperCase();
mapping.put(cgiName, name);
}
return Collections.unmodifiableMap(mapping);
}
private PyString getHeader(String wsgiName) throws ExecutionException {
// FIXME does this handle HTTP_COOKIE, or do we need to dispatch through on that as well?
// System.err.println("mapCGI=" + mapCGI + ", wsgiName=" + wsgiName);
String name = mapCGI.get(wsgiName);
if (name != null) {
// Referenced CGI specs are not directly available (FIXME add wayback archive URLs?)
// but this seems reasonable:
Enumeration<String> values = request.getHeaders(name);
if (values == null) {
throw new ExecutionException(null);
}
StringBuilder builder = new StringBuilder();
boolean firstThru = true;
while (values.hasMoreElements()) {
if (!firstThru) {
builder.append(";");
}
String value = values.nextElement();
builder.append(latin1(value));
firstThru = false;
}
if (firstThru) {
// no header at all
throw new ExecutionException(null);
}
return Py.newString(builder.toString());
}
// FIXME support THE_REQUEST, which also needs query params
// FIXME support SSL_ prefixed headers by parsing req.getAttribute("javax.servlet.request.X509Certificate")
throw new ExecutionException(null);
}
// to be wrapped using jythonlib so it looks like a dict
public ConcurrentMap asMap() {
return new BridgeMap(this);
}
public HttpServletRequest asWrapper() {
return new BridgeWrapper(this);
}
public LoadingCache cache() {
return cache;
}
Iterable<String> settings() {
return ImmutableList.copyOf(Iterators.concat(
Iterators.forArray(
WSGI_VERSION, WSGI_MULTITHREAD, WSGI_MULTIPROCESS, WSGI_RUN_ONCE,
WSGI_ERRORS, WSGI_INPUT, WSGI_URL_SCHEME,
REQUEST_METHOD, SCRIPT_NAME, PATH_INFO, QUERY_STRING, CONTENT_TYPE,
REMOTE_ADDR, REMOTE_HOST, REMOTE_PORT,
SERVER_NAME, SERVER_PORT, SERVER_PROTOCOL), // FIXME add remaining keys
mapCGI.keySet().iterator()));
// FIXME should add CONTENT_LENGTH only if getContentLength() != -1
}
public void loadAll() {
System.err.println("loadAll changed=" + changed);
for (String k : settings()) {
try {
if (!changed.contains(Py.newString(k))) {
System.err.println("getting key=" + k);
cache.get(Py.newString(k));
}
} catch (ExecutionException e) {
e.printStackTrace();
}
}
}
static class BridgeWrapper extends HttpServletRequestWrapper {
RequestBridge bridge;
public BridgeWrapper(RequestBridge bridge) {
super(bridge.request);
this.bridge = bridge;
}
public String intercept(PyString key) {
try {
PyObject value = (PyObject) bridge.cache().get(key);
if (value == Py.None) {
return null;
} else {
String s = value.toString();
return codecs.PyUnicode_DecodeLatin1(s, s.length(), null);
}
} catch (ExecutionException e) {
return null;
}
}
public String getMethod() {
if (!bridge.changed.contains(PY_REQUEST_METHOD)) {
return bridge.request.getMethod();
} else {
return intercept(PY_REQUEST_METHOD);
}
}
public String getServletPath() {
if (!bridge.changed.contains(PY_SCRIPT_NAME)) {
return bridge.request.getServletPath();
} else {
return intercept(PY_SCRIPT_NAME);
}
}
public String getPathInfo() {
if (!bridge.changed.contains(PY_PATH_INFO)) {
return bridge.request.getPathInfo();
} else {
return intercept(PY_PATH_INFO);
}
}
// FIXME
// fill in additional methods from above
// also return HTTP_* headers that are set via getHeader, getHeaderNames;
// also support getDateHeader, getIntHeader helper methods
// getCookies should also work
// presumably we need to consider normalizing new HTTP_ headers, although we
// can retain existing names. Ahh, the complexity of it all!
}
static class BridgeMap extends ForwardingConcurrentMap {
private final RequestBridge bridge;
public BridgeMap(RequestBridge bridge) {
this.bridge = bridge;
}
public Object get(Object key) {
// System.err.println("Getting key=" + key);
try {
return bridge.cache().get(key);
} catch (ExecutionException e) {
return null; // throw Py.KeyError((PyObject) key);
}
}
public Object put(Object key, Object value) {
// System.err.println("Updating key=" + key + ", value=" + value);
bridge.changed.add((PyObject) key);
return super.put(key, value);
}
public void clear() {
// System.err.println("Clearing changes");
for (Object key : bridge.cache().asMap().keySet()) {
bridge.changed.add((PyObject) key);
}
super.clear();
}
public Object remove(Object key) {
PyObject pyKey = (PyObject) key;
// System.err.println("Removing key=" + (pyKey.__repr__()));
bridge.changed.add(pyKey);
// what if we remove a key that we haven't lazily loaded FIXME
return bridge.cache().asMap().remove(key);
}
// FIXME override putAll... any others?
protected ConcurrentMap delegate() {
return bridge.cache().asMap();
}
// FIXME
// probably do not have to override iterator remove, although I suppose if passed into Java this could cause issues;
// presumably we can just override the Iterator in this case
public Set keySet() {
// System.err.println("keySet");
// NB does not imply loadAll!
return new StandardKeySet() {
};
}
public Set<Map.Entry> entrySet() {
// System.err.println("entrySet" + bridge.cache().asMap());
bridge.loadAll();
return bridge.cache().asMap().entrySet();
}
}
}
|
package cat.nyaa.nyaacore.utils;
import net.minecraft.server.v1_13_R2.*;
import org.bukkit.GameMode;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.craftbukkit.v1_13_R2.CraftWorld;
import org.bukkit.craftbukkit.v1_13_R2.entity.CraftEntity;
import org.bukkit.craftbukkit.v1_13_R2.entity.CraftLivingEntity;
import org.bukkit.entity.Entity;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.bukkit.util.Vector;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Predicate;
public class RayTraceUtils {
public static Block rayTraceBlock(Player player) {
float distance = player.getGameMode() == GameMode.CREATIVE ? 5.0F : 4.5F;
Vector start = player.getEyeLocation().toVector();
Vector end = start.clone().add(player.getEyeLocation().getDirection().multiply(distance));
return rayTraceBlock(player.getWorld(), start, end, false, false, true);
}
public static Block rayTraceBlock(World world, Vector start, Vector end, boolean stopOnLiquid, boolean ignoreBlockWithoutBoundingBox, boolean returnLastUncollidableBlock) {
WorldServer worldServer = ((CraftWorld) world).getHandle();
MovingObjectPosition mop = worldServer.rayTrace(toVec3DInternal(start), toVec3DInternal(end),
stopOnLiquid ? FluidCollisionOption.ALWAYS : FluidCollisionOption.NEVER, ignoreBlockWithoutBoundingBox, returnLastUncollidableBlock);
if (mop != null) {
BlockPosition blockPos = null;
try {
blockPos = mop.getBlockPosition();
} catch (Exception e) {
try {
blockPos = (BlockPosition) ReflectionUtils.getMethod(MovingObjectPosition.class, "a").invoke(mop);
} catch (IllegalAccessException e1) {
e1.printStackTrace();
} catch (InvocationTargetException e1) {
e1.printStackTrace();
}
}
return world.getBlockAt(blockPos.getX(), blockPos.getY(), blockPos.getZ());
}
return null;
}
@SuppressWarnings({"rawtypes", "unchecked"})
public static List<LivingEntity> rayTraceEntites(Player player, float distance) {
return rayTraceEntites(player, distance, not(player).and(canInteract()));
}
@SuppressWarnings("rawtypes")
public static List<LivingEntity> rayTraceEntites(Player player, float distance, Predicate predicate) {
Vector start = player.getEyeLocation().toVector();
Vector end = start.clone().add(player.getEyeLocation().getDirection().multiply(distance));
return rayTraceEntites(player.getWorld(), start, end, predicate);
}
public static List<LivingEntity> rayTraceEntites(World world, Vector start, Vector end) {
return rayTraceEntites(world, start, end, canInteract());
}
@SuppressWarnings({"rawtypes", "unchecked"})
public static List<LivingEntity> rayTraceEntites(World world, Vector start, Vector end, Predicate predicate) {
WorldServer worldServer = ((CraftWorld) world).getHandle();
List<EntityLiving> entityLivings = worldServer.a(EntityLiving.class, (Predicate<EntityLiving>) predicate);
List<LivingEntity> result = new ArrayList<>();
for (EntityLiving e : entityLivings) {
AxisAlignedBB bb = e.getBoundingBox();
MovingObjectPosition hit = bb.b(toVec3DInternal(start), toVec3DInternal(end));
if (hit != null) {
result.add((LivingEntity) e.getBukkitEntity());
}
}
return result;
}
public static Object toVec3D(Vector v) {
return toVec3DInternal(v);
}
private static Vec3D toVec3DInternal(Vector v) {
return new Vec3D(v.getX(), v.getY(), v.getZ());
}
@SuppressWarnings("rawtypes")
public static Predicate isAPlayer() {
return (Object entity) -> entity instanceof EntityPlayer;
}
@SuppressWarnings("rawtypes")
public static Predicate not(Entity e) {
return (Object entity) ->
!((EntityLiving) entity).getUniqueID().equals(e.getUniqueId());
}
@SuppressWarnings({"rawtypes", "unchecked"})
public static Predicate canInteract() {
return (Object input) -> {
if (input instanceof EntityPlayer && ((EntityPlayer) input).isSpectator()) {
return false;
}
return input != null && ((net.minecraft.server.v1_13_R2.Entity) input).isInteractable();//canBeCollidedWith
};
}
public static Entity getTargetEntity(Player p) {
Vector start = p.getEyeLocation().toVector();
Vector end = start.clone().add(p.getEyeLocation().getDirection().multiply(p.getGameMode() == GameMode.CREATIVE ? 6.0F : 4.5F));
return getTargetEntity(p, getDistanceToBlock(p.getWorld(), start, end, false, false, true));
}
public static Entity getTargetEntity(LivingEntity p, float maxDistance, boolean ignoreBlocks) {
Vector start = p.getEyeLocation().toVector();
Vector end = start.clone().add(p.getEyeLocation().getDirection().multiply(maxDistance));
if (!ignoreBlocks) {
maxDistance = getDistanceToBlock(p.getWorld(), start, end, false, false, true);
}
return getTargetEntity(p, maxDistance);
}
public static float getDistanceToBlock(World world, Vector start, Vector end, boolean stopOnLiquid, boolean ignoreBlockWithoutBoundingBox, boolean returnLastUncollidableBlock) {
WorldServer worldServer = ((CraftWorld) world).getHandle();
MovingObjectPosition mop = worldServer.rayTrace((Vec3D) toVec3D(start), (Vec3D) toVec3D(end), stopOnLiquid ? FluidCollisionOption.ALWAYS : FluidCollisionOption.NEVER, ignoreBlockWithoutBoundingBox, returnLastUncollidableBlock);
if (mop != null && mop.type == MovingObjectPosition.EnumMovingObjectType.BLOCK) {
return (float) mop.pos.f((Vec3D) toVec3D(start));
}
return (float) start.distance(end);
}
@SuppressWarnings({"rawtypes", "unchecked"})
public static Entity getTargetEntity(LivingEntity entity, float maxDistance) {
EntityLiving nmsEntityLiving = ((CraftLivingEntity) entity).getHandle();
net.minecraft.server.v1_13_R2.World world = nmsEntityLiving.world;
Vec3D eyePos = nmsEntityLiving.i(1.0f);//getPositionEyes
Vec3D start = nmsEntityLiving.f(1.0f);//getLook
Vec3D end = eyePos.add(start.x * maxDistance, start.y * maxDistance, start.z * maxDistance);
//getEntityBoundingBox().expand().expand()
List<net.minecraft.server.v1_13_R2.Entity> entities = world.getEntities(nmsEntityLiving, nmsEntityLiving.getBoundingBox().b(start.x * maxDistance, start.y * maxDistance, start.z * maxDistance).grow(1.0D, 1.0D, 1.0D),
(Predicate<? super net.minecraft.server.v1_13_R2.Entity>) canInteract()
);
net.minecraft.server.v1_13_R2.Entity targetEntity = null;
double d2 = maxDistance;
//Vec3D hitVec = null;
for (net.minecraft.server.v1_13_R2.Entity entity1 : entities) {
//getEntityBoundingBox().grow((double)entity1.getCollisionBorderSize());
AxisAlignedBB axisAlignedBB = entity1.getBoundingBox().g((double) entity1.aM());
MovingObjectPosition rayTraceResult = axisAlignedBB.b(eyePos, end);//calculateIntercept
if (axisAlignedBB.b(eyePos)) {// contains
if (d2 >= 0.0) {
targetEntity = entity1;
//hitVec = rayTraceResult == null ? eyePos : rayTraceResult.pos;
d2 = 0.0;
}
} else if (rayTraceResult != null) {
double d3 = eyePos.f(rayTraceResult.pos);//distanceTo
if (d3 < d2 || d2 == 0.0D) {
if (entity1.getRootVehicle() == ((CraftEntity) entity).getHandle().getRootVehicle()) {//getLowestRidingEntity
if (d2 == 0.0D) {
targetEntity = entity1;
//hitVec = rayTraceResult.pos;
}
} else {
targetEntity = entity1;
//hitVec = rayTraceResult.pos;
d2 = d3;
}
}
}
}
//EntityLivingBase
if (targetEntity instanceof EntityLiving || targetEntity instanceof EntityItemFrame) {
return targetEntity.getBukkitEntity();
}
return null;
}
}
|
package com.krillsson.sysapi.core.metrics.macos;
import com.krillsson.sysapi.core.domain.drives.Drive;
import com.krillsson.sysapi.core.domain.drives.DriveLoad;
import com.krillsson.sysapi.core.domain.drives.DriveSpeed;
import com.krillsson.sysapi.core.domain.drives.DriveValues;
import com.krillsson.sysapi.core.metrics.defaultimpl.DefaultDriveProvider;
import com.krillsson.sysapi.core.speed.SpeedMeasurementManager;
import oshi.hardware.HWPartition;
import oshi.hardware.HardwareAbstractionLayer;
import oshi.software.os.OSFileStore;
import oshi.software.os.OperatingSystem;
import java.util.*;
import java.util.stream.Collectors;
import static java.util.stream.Collectors.toList;
public class MacOsDriveProvider extends DefaultDriveProvider {
private static final String FIRST_SECTOR_ON_DRIVE = "s1";
private static final String ROOT_MOUNT = "/";
protected MacOsDriveProvider(OperatingSystem operatingSystem, HardwareAbstractionLayer hal, SpeedMeasurementManager speedMeasurementManager) {
super(operatingSystem, hal, speedMeasurementManager);
}
@Override
public List<DriveLoad> driveLoads() {
//fix for a drive migrated to APFS having multiple entries
List<DriveLoad> result = new ArrayList<>();
Map<String, List<DriveLoad>> map = super.driveLoads()
.stream()
.collect(Collectors.groupingBy(DriveLoad::getSerial, HashMap::new, toList()));
map.forEach((s, driveLoads) -> {
if (driveLoads.size() > 1) {
DriveValues first = driveLoads.get(0).getValues();
DriveValues second = driveLoads.get(1).getValues();
DriveSpeed speed = first.getReads() > second.getReads() ? driveLoads.get(0).getSpeed() : driveLoads.get(
1).getSpeed();
DriveValues values = new DriveValues(
Math.max(first.getUsableSpace(), second.getUsableSpace()),
Math.max(first.getTotalSpace(), second.getTotalSpace()),
Math.max(first.getOpenFileDescriptors(), second.getOpenFileDescriptors()),
Math.max(first.getMaxFileDescriptors(), second.getMaxFileDescriptors()),
Math.max(first.getReads(), second.getReads()),
Math.max(first.getReadBytes(), second.getReadBytes()),
Math.max(first.getWrites(), second.getWrites()),
Math.max(first.getWriteBytes(), second.getWriteBytes())
);
DriveLoad driveLoad = new DriveLoad(
driveLoads.get(0).getName(),
driveLoads.get(0).getSerial(),
values,
speed,
driveLoads.get(0).getHealth()
);
result.add(driveLoad);
} else {
result.add(driveLoads.get(0));
}
});
return result;
}
@Override
public List<Drive> drives() {
List<Drive> result = new ArrayList<>();
HashMap<String, List<Drive>> map = super.drives()
.stream()
.collect(Collectors.groupingBy(Drive::getSerial, HashMap::new, toList()));
map.forEach((s, driveLoads) -> {
if (driveLoads.size() > 1) {
driveLoads.stream()
.max(Comparator.comparingInt(o -> (int) o.getDiskOsPartition().getUsableSpace()))
.ifPresent(result::add);
} else {
result.add(driveLoads.get(0));
}
});
return result;
}
@Override
protected Optional<String> pickMostSuitableOsPartition(Map<String, HWPartition> hwPartitions, Map<String, OSFileStore> osStores) {
Set<String> strings = hwPartitions.keySet();
/*intersection*/
strings.retainAll(osStores.keySet());
if (!strings.isEmpty()) {
String[] keys = strings.toArray(new String[0]);
if (keys.length == 1) {
return Optional.of(keys[0]);
} else {
// try to find the actual main partition (should cover 99% of the cases)
for (String key : keys) {
OSFileStore osFileStore = osStores.get(key);
if (osFileStore.getMount().equals(ROOT_MOUNT) || osFileStore.getName()
.endsWith(FIRST_SECTOR_ON_DRIVE)) {
return Optional.of(key);
}
}
return Optional.of(keys[0]);
}
} else {
return Optional.empty();
}
}
}
|
package com.jayway.jsonpath.old;
import com.jayway.jsonpath.BaseTest;
import com.jayway.jsonpath.Configuration;
import com.jayway.jsonpath.Criteria;
import com.jayway.jsonpath.DocumentContext;
import com.jayway.jsonpath.Filter;
import com.jayway.jsonpath.JsonPath;
import com.jayway.jsonpath.Option;
import com.jayway.jsonpath.PathNotFoundException;
import com.jayway.jsonpath.Predicate;
import com.jayway.jsonpath.internal.Utils;
import com.jayway.jsonpath.spi.json.GsonJsonProvider;
import com.jayway.jsonpath.spi.json.JacksonJsonProvider;
import com.jayway.jsonpath.spi.json.JsonProvider;
import com.jayway.jsonpath.spi.mapper.GsonMappingProvider;
import com.jayway.jsonpath.spi.mapper.JacksonMappingProvider;
import com.jayway.jsonpath.spi.mapper.MappingProvider;
import net.minidev.json.JSONAware;
import net.minidev.json.parser.JSONParser;
import org.assertj.core.api.Assertions;
import org.hamcrest.Matchers;
import org.junit.Assert;
import org.junit.Test;
import java.io.IOException;
import java.io.InputStream;
import java.util.Collections;
import java.util.EnumSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import static com.jayway.jsonpath.JsonPath.read;
import static junit.framework.Assert.assertNull;
import static junit.framework.Assert.assertTrue;
import static org.assertj.core.api.Assertions.failBecauseExceptionWasNotThrown;
import static org.assertj.core.api.Assertions.filter;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
public class IssuesTest extends BaseTest {
private static final JsonProvider jp = Configuration.defaultConfiguration().jsonProvider();
@Test
public void full_ones_can_be_filtered() {
String json = "[\n" +
" {\"kind\" : \"full\"},\n" +
" {\"kind\" : \"empty\"}\n" +
"]";
List<Map<String, String>> fullOnes = read(json, "$[?(@.kind == full)]");
assertEquals(1, fullOnes.size());
assertEquals("full", fullOnes.get(0).get("kind"));
}
@Test
public void issue_36() {
String json = "{\n" +
"\n" +
" \"arrayOfObjectsAndArrays\" : [ { \"k\" : [\"json\"] }, { \"k\":[\"path\"] }, { \"k\" : [\"is\"] }, { \"k\" : [\"cool\"] } ],\n" +
"\n" +
" \"arrayOfObjects\" : [{\"k\" : \"json\"}, {\"k\":\"path\"}, {\"k\" : \"is\"}, {\"k\" : \"cool\"}]\n" +
"\n" +
" }";
Object o1 = read(json, "$.arrayOfObjectsAndArrays..k ");
Object o2 = read(json, "$.arrayOfObjects..k ");
assertEquals("[[\"json\"],[\"path\"],[\"is\"],[\"cool\"]]", jp.toJson(o1));
assertEquals("[\"json\",\"path\",\"is\",\"cool\"]", jp.toJson(o2));
}
@Test
public void issue_11() throws Exception {
String json = "{ \"foo\" : [] }";
List<String> result = read(json, "$.foo[?(@.rel == 'item')][0].uri");
assertTrue(result.isEmpty());
}
@Test(expected = PathNotFoundException.class)
public void issue_11b() throws Exception {
String json = "{ \"foo\" : [] }";
read(json, "$.foo[0].uri");
}
@Test
public void issue_15() throws Exception {
String json = "{ \"store\": {\n" +
" \"book\": [ \n" +
" { \"category\": \"reference\",\n" +
" \"author\": \"Nigel Rees\",\n" +
" \"title\": \"Sayings of the Century\",\n" +
" \"price\": 8.95\n" +
" },\n" +
" { \"category\": \"fiction\",\n" +
" \"author\": \"Herman Melville\",\n" +
" \"title\": \"Moby Dick\",\n" +
" \"isbn\": \"0-553-21311-3\",\n" +
" \"price\": 8.99,\n" +
" \"retailer\": null, \n" +
" \"children\": true,\n" +
" \"number\": -2.99\n" +
" },\n" +
" { \"category\": \"fiction\",\n" +
" \"author\": \"J. R. R. Tolkien\",\n" +
" \"title\": \"The Lord of the Rings\",\n" +
" \"isbn\": \"0-395-19395-8\",\n" +
" \"price\": 22.99,\n" +
" \"number\":0,\n" +
" \"children\": false\n" +
" }\n" +
" ]\n" +
" }\n" +
"}";
List<String> titles = read(json, "$.store.book[?(@.children==true)].title");
assertThat(titles, Matchers.contains("Moby Dick"));
assertEquals(1, titles.size());
}
@Test
public void issue_24() {
InputStream is = null;
try {
is = this.getClass().getResourceAsStream("/issue_24.json");
//Object o = JsonPath.read(is, "$.project[?(@.template.@key == 'foo')].field[*].@key");
Object o = read(is, "$.project.field[*].@key");
//Object o = JsonPath.read(is, "$.project.template[?(@.@key == 'foo')].field[*].@key");
is.close();
} catch (Exception e) {
//e.printStackTrace();
Utils.closeQuietly(is);
}
}
@Test
public void issue_28_string() {
String json = "{\"contents\": [\"one\",\"two\",\"three\"]}";
List<String> result = read(json, "$.contents[?(@ == 'two')]");
assertThat(result, Matchers.contains("two"));
assertEquals(1, result.size());
}
@Test
public void issue_37() {
String json = "[\n" +
" {\n" +
" \"id\": \"9\",\n" +
" \"sku\": \"SKU-001\",\n" +
" \"compatible\": false\n" +
" },\n" +
" {\n" +
" \"id\": \"13\",\n" +
" \"sku\": \"SKU-005\",\n" +
" \"compatible\": true\n" +
" },\n" +
" {\n" +
" \"id\": \"11\",\n" +
" \"sku\": \"SKU-003\",\n" +
" \"compatible\": true\n" +
" }\n" +
"]";
List<String> result = read(json, "$.[?(@.compatible == true)].sku");
Assertions.assertThat(result).containsExactly("SKU-005", "SKU-003");
}
@Test
public void issue_38() {
String json = "{\n" +
" \"datapoints\":[\n" +
" [\n" +
" 10.1,\n" +
" 13.0\n" +
" ],\n" +
" [\n" +
" 21.0,\n" +
" 22.0\n" +
" ]\n" +
" ]\n" +
"}";
List<Double> result = read(json, "$.datapoints.[*].[0]");
assertThat(result.get(0), is(new Double(10.1)));
assertThat(result.get(1), is(new Double(21.0)));
}
@Test
public void issue_39() {
String json = "{\n" +
" \"obj1\": {\n" +
" \"arr\": [\"1\", \"2\"]\n" +
" },\n" +
" \"obj2\": {\n" +
" \"arr\": [\"3\", \"4\"]\n" +
" }\n" +
"}\n";
List<String> result = read(json, "$..arr");
assertThat(result.size(), is(2));
}
@Test
public void issue_28_int() {
String json = "{\"contents\": [1,2,3]}";
List<Integer> result = read(json, "$.contents[?(@ == 2)]");
assertThat(result, Matchers.contains(2));
assertEquals(1, result.size());
}
@Test
public void issue_28_boolean() {
String json = "{\"contents\": [true, true, false]}";
List<Boolean> result = read(json, "$.contents[?(@ == true)]");
assertThat(result, Matchers.contains(true, true));
assertEquals(2, result.size());
}
@Test(expected = PathNotFoundException.class)
public void issue_22() throws Exception {
Configuration configuration = Configuration.defaultConfiguration();
String json = "{\"a\":{\"b\":1,\"c\":2}}";
JsonPath.parse(json, configuration).read("a.d");
}
@Test
public void issue_22c() throws Exception {
//Configuration configuration = Configuration.builder().build();
Configuration configuration = Configuration.builder().options(Option.SUPPRESS_EXCEPTIONS).build();
String json = "{\"a\":{\"b\":1,\"c\":2}}";
assertNull(JsonPath.parse(json, configuration).read("a.d"));
}
@Test
public void issue_22b() throws Exception {
String json = "{\"a\":[{\"b\":1,\"c\":2},{\"b\":5,\"c\":2}]}";
List<Object> res = JsonPath.using(Configuration.defaultConfiguration().setOptions(Option.DEFAULT_PATH_LEAF_TO_NULL)).parse(json).read("a[?(@.b==5)].d");
Assertions.assertThat(res).hasSize(1).containsNull();
}
@Test(expected = PathNotFoundException.class)
public void issue_26() throws Exception {
String json = "[{\"a\":[{\"b\":1,\"c\":2}]}]";
Object o = read(json, "$.a");
}
@Test
public void issue_29_a() throws Exception {
String json = "{\"list\": [ { \"a\":\"atext\", \"b.b-a\":\"batext2\", \"b\":{ \"b-a\":\"batext\", \"b-b\":\"bbtext\" } }, { \"a\":\"atext2\", \"b\":{ \"b-a\":\"batext2\", \"b-b\":\"bbtext2\" } } ] }";
List<Map<String, Object>> result = read(json, "$.list[?(@['b.b-a']=='batext2')]");
assertEquals(1, result.size());
Object a = result.get(0).get("a");
assertEquals("atext", a);
result = read(json, "$.list[?(@.b.b-a=='batext2')]");
assertEquals(1, result.size());
assertEquals("atext2", result.get(0).get("a"));
}
@Test
public void issue_29_b() throws Exception {
String json = "{\"list\": [ { \"a\":\"atext\", \"b\":{ \"b-a\":\"batext\", \"b-b\":\"bbtext\" } }, { \"a\":\"atext2\", \"b\":{ \"b-a\":\"batext2\", \"b-b\":\"bbtext2\" } } ] }";
List<String> result = read(json, "$.list[?]", Filter.filter(Criteria.where("b.b-a").eq("batext2")));
assertTrue(result.size() == 1);
}
@Test
public void issue_30() throws Exception {
String json = "{\"foo\" : {\"@id\" : \"123\", \"$\" : \"hello\"}}";
assertEquals("123", read(json, "foo.@id"));
assertEquals("hello", read(json, "foo.$"));
}
@Test
public void issue_32() {
String json = "{\"text\" : \"skill: \\\"Heuristic Evaluation\\\"\", \"country\" : \"\"}";
assertEquals("skill: \"Heuristic Evaluation\"", read(json, "$.text"));
}
@Test
public void issue_33() {
String json = "{ \"store\": {\n" +
" \"book\": [ \n" +
" { \"category\": \"reference\",\n" +
" \"author\": {\n" +
" \"name\": \"Author Name\",\n" +
" \"age\": 36\n" +
" },\n" +
" \"title\": \"Sayings of the Century\",\n" +
" \"price\": 8.95\n" +
" },\n" +
" { \"category\": \"fiction\",\n" +
" \"author\": \"Evelyn Waugh\",\n" +
" \"title\": \"Sword of Honour\",\n" +
" \"price\": 12.99,\n" +
" \"isbn\": \"0-553-21311-3\"\n" +
" }\n" +
" ],\n" +
" \"bicycle\": {\n" +
" \"color\": \"red\",\n" +
" \"price\": 19.95\n" +
" }\n" +
" }\n" +
"}";
List<Map<String, Object>> result = read(json, "$.store.book[?(@.author.age == 36)]");
Assertions.assertThat(result).hasSize(1);
Assertions.assertThat(result.get(0)).containsEntry("title", "Sayings of the Century");
}
@Test
public void array_root() {
String json = "[\n" +
" {\n" +
" \"a\": 1,\n" +
" \"b\": 2,\n" +
" \"c\": 3\n" +
" }\n" +
"]";
assertEquals(1, read(json, "$[0].a"));
}
@Test(expected = PathNotFoundException.class)
public void a_test() {
String json = "{\n" +
" \"success\": true,\n" +
" \"data\": {\n" +
" \"user\": 3,\n" +
" \"own\": null,\n" +
" \"passes\": null,\n" +
" \"completed\": null\n" +
" },\n" +
" \"version\": 1371160528774\n" +
"}";
Object read = read(json, "$.data.passes[0].id");
}
@Test
public void issue_42() {
String json = "{" +
" \"list\": [{" +
" \"name\": \"My (String)\" " +
" }] " +
" }";
List<Map<String, String>> result = read(json, "$.list[?(@.name == 'My (String)')]");
Assertions.assertThat(result).containsExactly(Collections.singletonMap("name", "My (String)"));
}
@Test
public void issue_43() {
String json = "{\"test\":null}";
Assertions.assertThat(read(json, "test")).isNull();
Assertions.assertThat(JsonPath.using(Configuration.defaultConfiguration().setOptions(Option.SUPPRESS_EXCEPTIONS)).parse(json).read("nonExistingProperty")).isNull();
try {
read(json, "nonExistingProperty");
failBecauseExceptionWasNotThrown(PathNotFoundException.class);
} catch (PathNotFoundException e) {
}
try {
read(json, "nonExisting.property");
failBecauseExceptionWasNotThrown(PathNotFoundException.class);
} catch (PathNotFoundException e) {
}
}
@Test
public void issue_45() {
String json = "{\"rootkey\":{\"sub.key\":\"value\"}}";
Assertions.assertThat(read(json, "rootkey['sub.key']")).isEqualTo("value");
}
@Test
public void issue_46() {
String json = "{\"a\": {}}";
Configuration configuration = Configuration.defaultConfiguration().setOptions(Option.SUPPRESS_EXCEPTIONS);
Assertions.assertThat(JsonPath.using(configuration).parse(json).read("a.x")).isNull();
try {
read(json, "a.x");
failBecauseExceptionWasNotThrown(PathNotFoundException.class);
} catch (PathNotFoundException e) {
Assertions.assertThat(e).hasMessage("No results for path: $['a']['x']");
}
}
@Test
public void issue_x() {
String json = "{\n" +
" \"a\" : [\n" +
" {},\n" +
" { \"b\" : [ { \"c\" : \"foo\"} ] }\n" +
" ]\n" +
"}\n";
List<String> result = JsonPath.read(json, "$.a.*.b.*.c");
Assertions.assertThat(result).containsExactly("foo");
}
@Test
public void issue_60() {
String json = "[\n" +
"{\n" +
" \"mpTransactionId\": \"542986eae4b001fd500fdc5b-coreDisc_50-title\",\n" +
" \"resultType\": \"FAIL\",\n" +
" \"narratives\": [\n" +
" {\n" +
" \"ruleProcessingDate\": \"Nov 2, 2014 7:30:20 AM\",\n" +
" \"area\": \"Discovery\",\n" +
" \"phase\": \"Validation\",\n" +
" \"message\": \"Chain does not have a discovery event. Possible it was cut by the date that was picked\",\n" +
" \"ruleName\": \"Validate chain\\u0027s discovery event existence\",\n" +
" \"lastRule\": true\n" +
" }\n" +
" ]\n" +
"},\n" +
"{\n" +
" \"mpTransactionId\": \"54298649e4b001fd500fda3e-fixCoreDiscovery_3-title\",\n" +
" \"resultType\": \"FAIL\",\n" +
" \"narratives\": [\n" +
" {\n" +
" \"ruleProcessingDate\": \"Nov 2, 2014 7:30:20 AM\",\n" +
" \"area\": \"Discovery\",\n" +
" \"phase\": \"Validation\",\n" +
" \"message\": \"There is one and only discovery event ContentDiscoveredEvent(230) found.\",\n" +
" \"ruleName\": \"Marks existence of discovery event (230)\",\n" +
" \"lastRule\": false\n" +
" },\n" +
" {\n" +
" \"ruleProcessingDate\": \"Nov 2, 2014 7:30:20 AM\",\n" +
" \"area\": \"Discovery/Processing\",\n" +
" \"phase\": \"Validation\",\n" +
" \"message\": \"Chain does not have SLA start event (204) in Discovery or Processing. \",\n" +
" \"ruleName\": \"Check if SLA start event is not present (204). \",\n" +
" \"lastRule\": false\n" +
" },\n" +
" {\n" +
" \"ruleProcessingDate\": \"Nov 2, 2014 7:30:20 AM\",\n" +
" \"area\": \"Processing\",\n" +
" \"phase\": \"Transcode\",\n" +
" \"message\": \"No start transcoding events found\",\n" +
" \"ruleName\": \"Start transcoding events missing (240)\",\n" +
" \"lastRule\": true\n" +
" }\n" +
" ]\n" +
"}]";
List<String> problems = JsonPath.read(json, "$..narratives[?(@.lastRule==true)].message");
Assertions.assertThat(problems).containsExactly("Chain does not have a discovery event. Possible it was cut by the date that was picked", "No start transcoding events found");
}
@Test
public void stack_overflow_question_1() {
String json = "{\n" +
"\"store\": {\n" +
" \"book\": [\n" +
" {\n" +
" \"category\": \"reference\",\n" +
" \"authors\" : [\n" +
" {\n" +
" \"firstName\" : \"Nigel\",\n" +
" \"lastName\" : \"Rees\"\n" +
" }\n" +
" ],\n" +
" \"title\": \"Sayings of the Century\",\n" +
" \"price\": 8.95\n" +
" },\n" +
" {\n" +
" \"category\": \"fiction\",\n" +
" \"authors\": [\n" +
" {\n" +
" \"firstName\" : \"Evelyn\",\n" +
" \"lastName\" : \"Waugh\"\n" +
" },\n" +
" {\n" +
" \"firstName\" : \"Another\",\n" +
" \"lastName\" : \"Author\"\n" +
" }\n" +
" ],\n" +
" \"title\": \"Sword of Honour\",\n" +
" \"price\": 12.99\n" +
" }\n" +
" ]\n" +
" }\n" +
"}";
Filter filter = Filter.filter(Criteria.where("authors[*].lastName").contains("Waugh"));
Object read = JsonPath.parse(json).read("$.store.book[?]", filter);
System.out.println(read);
}
@Test
public void issue_71() {
String json = "{\n"
+ " \"logs\": [\n"
+ " {\n"
+ " \"message\": \"it's here\",\n"
+ " \"id\": 2\n"
+ " }\n"
+ " ]\n"
+ "}";
List<String> result = JsonPath.read(json, "$.logs[?(@.message == 'it\\'s here')].message");
Assertions.assertThat(result).containsExactly("it's here");
}
@Test
public void issue_76() throws Exception {
String json = "{\n" +
" \"cpus\": -8.88178419700125e-16,\n" +
" \"disk\": 0,\n" +
" \"mem\": 0\n" +
"}";
JSONParser parser = new JSONParser(JSONParser.MODE_PERMISSIVE);
JSONAware jsonModel = (JSONAware)parser.parse(json);
jsonModel.toJSONString();
}
@Test
public void issue_79() throws Exception {
String json = "{ \n" +
" \"c\": {\n" +
" \"d1\": {\n" +
" \"url\": [ \"url1\", \"url2\" ]\n" +
" },\n" +
" \"d2\": {\n" +
" \"url\": [ \"url3\", \"url4\",\"url5\" ]\n" +
" }\n" +
" }\n" +
"}";
List<String> res = JsonPath.read(json, "$.c.*.url[2]");
Assertions.assertThat(res).containsExactly("url5");
}
@Test
public void issue_97() throws Exception {
String json = "{ \"books\": [ " +
"{ \"category\": \"fiction\" }, " +
"{ \"category\": \"reference\" }, " +
"{ \"category\": \"fiction\" }, " +
"{ \"category\": \"fiction\" }, " +
"{ \"category\": \"reference\" }, " +
"{ \"category\": \"fiction\" }, " +
"{ \"category\": \"reference\" }, " +
"{ \"category\": \"reference\" }, " +
"{ \"category\": \"reference\" }, " +
"{ \"category\": \"reference\" }, " +
"{ \"category\": \"reference\" } ] }";
Configuration conf = Configuration.builder()
.jsonProvider(new GsonJsonProvider())
.mappingProvider(new GsonMappingProvider())
.build();
DocumentContext context = JsonPath.using(conf).parse(json);
context.delete("$.books[?(@.category == 'reference')]");
List<String> categories = context.read("$..category", List.class);
Assertions.assertThat(categories).containsOnly("fiction");
}
}
|
package org.zkoss.ganttz.data;
import static java.util.Arrays.asList;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import java.util.Queue;
import java.util.Set;
import org.apache.commons.lang.Validate;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jgrapht.DirectedGraph;
import org.jgrapht.graph.SimpleDirectedGraph;
import org.zkoss.ganttz.data.DependencyType.Point;
import org.zkoss.ganttz.data.constraint.Constraint;
import org.zkoss.ganttz.data.constraint.ConstraintOnComparableValues;
import org.zkoss.ganttz.data.constraint.ConstraintOnComparableValues.ComparisonType;
import org.zkoss.ganttz.data.criticalpath.ICriticalPathCalculable;
import org.zkoss.ganttz.util.IAction;
import org.zkoss.ganttz.util.PreAndPostNotReentrantActionsWrapper;
public class GanttDiagramGraph<V, D extends IDependency<V>> implements
ICriticalPathCalculable<V> {
private static final Log LOG = LogFactory.getLog(GanttDiagramGraph.class);
public static IDependenciesEnforcerHook doNothingHook() {
return new IDependenciesEnforcerHook() {
@Override
public void setNewEnd(GanttDate previousEnd, GanttDate newEnd) {
}
@Override
public void setStartDate(GanttDate previousStart,
GanttDate previousEnd, GanttDate newStart) {
}
};
}
private static final GanttZKAdapter GANTTZK_ADAPTER = new GanttZKAdapter();
public static IAdapter<Task, Dependency> taskAdapter() {
return GANTTZK_ADAPTER;
}
public interface IAdapter<V, D extends IDependency<V>> {
List<V> getChildren(V task);
boolean isContainer(V task);
void registerDependenciesEnforcerHookOn(V task,
IDependenciesEnforcerHookFactory<V> hookFactory);
GanttDate getStartDate(V task);
void setStartDateFor(V task, GanttDate newStart);
GanttDate getEndDateFor(V task);
void setEndDateFor(V task, GanttDate newEnd);
public List<Constraint<GanttDate>> getConstraints(
ConstraintCalculator<V> calculator, Set<D> withDependencies,
Point point);
List<Constraint<GanttDate>> getStartConstraintsFor(V task);
List<Constraint<GanttDate>> getEndConstraintsFor(V task);
V getSource(D dependency);
V getDestination(D dependency);
Class<D> getDependencyType();
D createInvisibleDependency(V origin, V destination, DependencyType type);
DependencyType getType(D dependency);
boolean isVisible(D dependency);
boolean isFixed(V task);
}
public static class GanttZKAdapter implements IAdapter<Task, Dependency> {
@Override
public List<Task> getChildren(Task task) {
return task.getTasks();
}
@Override
public Task getDestination(Dependency dependency) {
return dependency.getDestination();
}
@Override
public Task getSource(Dependency dependency) {
return dependency.getSource();
}
@Override
public boolean isContainer(Task task) {
return task.isContainer();
}
@Override
public void registerDependenciesEnforcerHookOn(Task task,
IDependenciesEnforcerHookFactory<Task> hookFactory) {
task.registerDependenciesEnforcerHook(hookFactory);
}
@Override
public Dependency createInvisibleDependency(Task origin,
Task destination, DependencyType type) {
return new Dependency(origin, destination, type, false);
}
@Override
public Class<Dependency> getDependencyType() {
return Dependency.class;
}
@Override
public DependencyType getType(Dependency dependency) {
return dependency.getType();
}
@Override
public boolean isVisible(Dependency dependency) {
return dependency.isVisible();
}
@Override
public GanttDate getEndDateFor(Task task) {
return task.getEndDate();
}
@Override
public void setEndDateFor(Task task, GanttDate newEnd) {
task.setEndDate(newEnd);
}
@Override
public GanttDate getStartDate(Task task) {
return task.getBeginDate();
}
@Override
public void setStartDateFor(Task task, GanttDate newStart) {
task.setBeginDate(newStart);
}
@Override
public List<Constraint<GanttDate>> getConstraints(
ConstraintCalculator<Task> calculator,
Set<Dependency> withDependencies, Point pointBeingModified) {
return Dependency.getConstraintsFor(calculator, withDependencies,
pointBeingModified);
}
@Override
public List<Constraint<GanttDate>> getStartConstraintsFor(Task task) {
return task.getStartConstraints();
}
@Override
public List<Constraint<GanttDate>> getEndConstraintsFor(Task task) {
return task.getEndConstraints();
}
@Override
public boolean isFixed(Task task) {
return task.isFixed();
}
}
public static class GanttZKDiagramGraph extends
GanttDiagramGraph<Task, Dependency> {
private GanttZKDiagramGraph(boolean scheduleBackwards,
List<Constraint<GanttDate>> globalStartConstraints,
List<Constraint<GanttDate>> globalEndConstraints,
boolean dependenciesConstraintsHavePriority) {
super(scheduleBackwards, GANTTZK_ADAPTER, globalStartConstraints,
globalEndConstraints,
dependenciesConstraintsHavePriority);
}
}
public interface IGraphChangeListener {
public void execute();
}
public static GanttZKDiagramGraph create(boolean scheduleBackwards,
List<Constraint<GanttDate>> globalStartConstraints,
List<Constraint<GanttDate>> globalEndConstraints,
boolean dependenciesConstraintsHavePriority) {
return new GanttZKDiagramGraph(scheduleBackwards,
globalStartConstraints,
globalEndConstraints, dependenciesConstraintsHavePriority);
}
private final IAdapter<V, D> adapter;
private final DirectedGraph<V, D> graph;
private List<V> topLevelTasks = new ArrayList<V>();
private Map<V, V> fromChildToParent = new HashMap<V, V>();
private final List<Constraint<GanttDate>> globalStartConstraints;
private final List<Constraint<GanttDate>> globalEndConstraints;
private final boolean scheduleBackwards;
private DependenciesEnforcer enforcer = new DependenciesEnforcer();
private final boolean dependenciesConstraintsHavePriority;
private final ReentranceGuard positionsUpdatingGuard = new ReentranceGuard();
private final PreAndPostNotReentrantActionsWrapper preAndPostActions = new PreAndPostNotReentrantActionsWrapper() {
@Override
protected void postAction() {
executeGraphChangeListeners(new ArrayList<IGraphChangeListener>(
postGraphChangeListeners));
}
@Override
protected void preAction() {
executeGraphChangeListeners(new ArrayList<IGraphChangeListener>(
preGraphChangeListeners));
}
private void executeGraphChangeListeners(List<IGraphChangeListener> graphChangeListeners) {
for (IGraphChangeListener each : graphChangeListeners) {
try {
each.execute();
} catch (Exception e) {
LOG.error("error executing execution listener", e);
}
}
}
};
private List<IGraphChangeListener> preGraphChangeListeners = new ArrayList<IGraphChangeListener>();
private List<IGraphChangeListener> postGraphChangeListeners = new ArrayList<IGraphChangeListener>();
public void addPreGraphChangeListener(IGraphChangeListener preGraphChangeListener) {
preGraphChangeListeners.add(preGraphChangeListener);
}
public void removePreGraphChangeListener(IGraphChangeListener preGraphChangeListener) {
preGraphChangeListeners.remove(preGraphChangeListener);
}
public void addPostGraphChangeListener(IGraphChangeListener postGraphChangeListener) {
postGraphChangeListeners.add(postGraphChangeListener);
}
public void removePostGraphChangeListener(IGraphChangeListener postGraphChangeListener) {
postGraphChangeListeners.remove(postGraphChangeListener);
}
public void addPreChangeListeners(
Collection<? extends IGraphChangeListener> preChangeListeners) {
for (IGraphChangeListener each : preChangeListeners) {
addPreGraphChangeListener(each);
}
}
public void addPostChangeListeners(
Collection<? extends IGraphChangeListener> postChangeListeners) {
for (IGraphChangeListener each : postChangeListeners) {
addPostGraphChangeListener(each);
}
}
public static <V, D extends IDependency<V>> GanttDiagramGraph<V, D> create(
boolean scheduleBackwards,
IAdapter<V, D> adapter,
List<Constraint<GanttDate>> globalStartConstraints,
List<Constraint<GanttDate>> globalEndConstraints,
boolean dependenciesConstraintsHavePriority) {
return new GanttDiagramGraph<V, D>(scheduleBackwards, adapter,
globalStartConstraints,
globalEndConstraints, dependenciesConstraintsHavePriority);
}
protected GanttDiagramGraph(boolean scheduleBackwards,
IAdapter<V, D> adapter,
List<Constraint<GanttDate>> globalStartConstraints,
List<Constraint<GanttDate>> globalEndConstraints,
boolean dependenciesConstraintsHavePriority) {
this.scheduleBackwards = scheduleBackwards;
this.adapter = adapter;
this.globalStartConstraints = globalStartConstraints;
this.globalEndConstraints = globalEndConstraints;
this.dependenciesConstraintsHavePriority = dependenciesConstraintsHavePriority;
this.graph = new SimpleDirectedGraph<V, D>(adapter.getDependencyType());
}
public void enforceAllRestrictions() {
enforcer.enforceRestrictionsOn(getTopLevelTasks());
}
public void addTopLevel(V task) {
topLevelTasks.add(task);
addTask(task);
}
public void addTopLevel(Collection<? extends V> tasks) {
for (V task : tasks) {
addTopLevel(task);
}
}
public void addTasks(Collection<? extends V> tasks) {
for (V t : tasks) {
addTask(t);
}
}
public void addTask(V original) {
List<V> stack = new LinkedList<V>();
stack.add(original);
List<D> dependenciesToAdd = new ArrayList<D>();
while (!stack.isEmpty()){
V task = stack.remove(0);
graph.addVertex(task);
adapter.registerDependenciesEnforcerHookOn(task, enforcer);
if (adapter.isContainer(task)) {
for (V child : adapter.getChildren(task)) {
fromChildToParent.put(child, task);
stack.add(0, child);
dependenciesToAdd.add(adapter.createInvisibleDependency(
child, task, DependencyType.END_END));
dependenciesToAdd.add(adapter.createInvisibleDependency(
task, child, DependencyType.START_START));
}
}
}
for (D each : dependenciesToAdd) {
add(each, false);
}
}
public interface IDependenciesEnforcerHook {
public void setStartDate(GanttDate previousStart,
GanttDate previousEnd, GanttDate newStart);
public void setNewEnd(GanttDate previousEnd, GanttDate newEnd);
}
public interface IDependenciesEnforcerHookFactory<T> {
public IDependenciesEnforcerHook create(T task,
INotificationAfterDependenciesEnforcement notification);
public IDependenciesEnforcerHook create(T task);
}
public interface INotificationAfterDependenciesEnforcement {
public void onStartDateChange(GanttDate previousStart,
GanttDate previousEnd, GanttDate newStart);
public void onEndDateChange(GanttDate previousEnd, GanttDate newEnd);
}
private static final INotificationAfterDependenciesEnforcement EMPTY_NOTIFICATOR = new INotificationAfterDependenciesEnforcement() {
@Override
public void onStartDateChange(GanttDate previousStart,
GanttDate previousEnd, GanttDate newStart) {
}
@Override
public void onEndDateChange(GanttDate previousEnd, GanttDate newEnd) {
}
};
public class DeferedNotifier {
private Map<V, NotificationPendingForTask> notificationsPending = new LinkedHashMap<V, NotificationPendingForTask>();
public void add(V task, StartDateNofitication notification) {
retrieveOrCreateFor(task).setStartDateNofitication(notification);
}
private NotificationPendingForTask retrieveOrCreateFor(V task) {
NotificationPendingForTask result = notificationsPending.get(task);
if (result == null) {
result = new NotificationPendingForTask();
notificationsPending.put(task, result);
}
return result;
}
void add(V task, LengthNotification notification) {
retrieveOrCreateFor(task).setLengthNofitication(notification);
}
public void doNotifications() {
for (NotificationPendingForTask each : notificationsPending
.values()) {
each.doNotification();
}
notificationsPending.clear();
}
}
private class NotificationPendingForTask {
private StartDateNofitication startDateNofitication;
private LengthNotification lengthNofitication;
void setStartDateNofitication(
StartDateNofitication startDateNofitication) {
this.startDateNofitication = this.startDateNofitication == null ? startDateNofitication
: this.startDateNofitication
.coalesce(startDateNofitication);
}
void setLengthNofitication(LengthNotification lengthNofitication) {
this.lengthNofitication = this.lengthNofitication == null ? lengthNofitication
: this.lengthNofitication.coalesce(lengthNofitication);
}
void doNotification() {
if (startDateNofitication != null) {
startDateNofitication.doNotification();
}
if (lengthNofitication != null) {
lengthNofitication.doNotification();
}
}
}
private class StartDateNofitication {
private final INotificationAfterDependenciesEnforcement notification;
private final GanttDate previousStart;
private final GanttDate previousEnd;
private final GanttDate newStart;
public StartDateNofitication(
INotificationAfterDependenciesEnforcement notification,
GanttDate previousStart, GanttDate previousEnd,
GanttDate newStart) {
this.notification = notification;
this.previousStart = previousStart;
this.previousEnd = previousEnd;
this.newStart = newStart;
}
public StartDateNofitication coalesce(
StartDateNofitication startDateNofitication) {
return new StartDateNofitication(notification, previousStart,
previousEnd, startDateNofitication.newStart);
}
void doNotification() {
notification
.onStartDateChange(previousStart, previousEnd, newStart);
}
}
private class LengthNotification {
private final INotificationAfterDependenciesEnforcement notification;
private final GanttDate previousEnd;
private final GanttDate newEnd;
public LengthNotification(
INotificationAfterDependenciesEnforcement notification,
GanttDate previousEnd, GanttDate newEnd) {
this.notification = notification;
this.previousEnd = previousEnd;
this.newEnd = newEnd;
}
public LengthNotification coalesce(LengthNotification lengthNofitication) {
return new LengthNotification(notification, previousEnd,
lengthNofitication.newEnd);
}
void doNotification() {
notification.onEndDateChange(previousEnd, newEnd);
}
}
private class DependenciesEnforcer implements
IDependenciesEnforcerHookFactory<V> {
private ThreadLocal<DeferedNotifier> deferedNotifier = new ThreadLocal<DeferedNotifier>();
@Override
public IDependenciesEnforcerHook create(V task,
INotificationAfterDependenciesEnforcement notificator) {
return onlyEnforceDependenciesOnEntrance(onEntrance(task),
onNotification(task, notificator));
}
@Override
public IDependenciesEnforcerHook create(V task) {
return create(task, EMPTY_NOTIFICATOR);
}
private IDependenciesEnforcerHook onEntrance(final V task) {
return new IDependenciesEnforcerHook() {
public void setStartDate(GanttDate previousStart,
GanttDate previousEnd, GanttDate newStart) {
taskPositionModified(task);
}
@Override
public void setNewEnd(GanttDate previousEnd, GanttDate newEnd) {
taskPositionModified(task);
}
};
}
private IDependenciesEnforcerHook onNotification(final V task,
final INotificationAfterDependenciesEnforcement notification) {
return new IDependenciesEnforcerHook() {
@Override
public void setStartDate(GanttDate previousStart,
GanttDate previousEnd, GanttDate newStart) {
StartDateNofitication startDateNotification = new StartDateNofitication(
notification, previousStart, previousEnd,
newStart);
deferedNotifier.get().add(task, startDateNotification);
}
@Override
public void setNewEnd(GanttDate previousEnd, GanttDate newEnd) {
LengthNotification lengthNotification = new LengthNotification(
notification, previousEnd, newEnd);
deferedNotifier.get().add(task, lengthNotification);
}
};
}
private IDependenciesEnforcerHook onlyEnforceDependenciesOnEntrance(
final IDependenciesEnforcerHook onEntrance,
final IDependenciesEnforcerHook notification) {
return new IDependenciesEnforcerHook() {
@Override
public void setStartDate(final GanttDate previousStart,
final GanttDate previousEnd, final GanttDate newStart) {
positionsUpdatingGuard
.entranceRequested(new IReentranceCases() {
@Override
public void ifNewEntrance() {
onNewEntrance(new IAction() {
@Override
public void doAction() {
notification.setStartDate(
previousStart,
previousEnd, newStart);
onEntrance.setStartDate(
previousStart, previousEnd,
newStart);
}
});
}
@Override
public void ifAlreadyInside() {
notification.setStartDate(previousStart,
previousEnd, newStart);
}
});
}
@Override
public void setNewEnd(final GanttDate previousEnd,
final GanttDate newEnd) {
positionsUpdatingGuard
.entranceRequested(new IReentranceCases() {
@Override
public void ifNewEntrance() {
onNewEntrance(new IAction() {
@Override
public void doAction() {
notification.setNewEnd(previousEnd,
newEnd);
onEntrance.setNewEnd(previousEnd,
newEnd);
}
});
}
@Override
public void ifAlreadyInside() {
notification.setNewEnd(previousEnd, newEnd);
}
});
}
};
}
void enforceRestrictionsOn(Collection<? extends V> tasks) {
List<Recalculation> allRecalculations = new ArrayList<Recalculation>();
for (V each : tasks) {
allRecalculations.addAll(getRecalculationsNeededFrom(each));
}
enforceRestrictionsOn(allRecalculations, tasks);
}
void enforceRestrictionsOn(V task) {
enforceRestrictionsOn(getRecalculationsNeededFrom(task),
Collections.singleton(task));
}
void enforceRestrictionsOn(final List<Recalculation> recalculations,
final Collection<? extends V> initiallyModified) {
executeWithPreAndPostActionsOnlyIfNewEntrance(new IAction() {
@Override
public void doAction() {
doRecalculations(recalculations, initiallyModified);
}
});
}
private void executeWithPreAndPostActionsOnlyIfNewEntrance(
final IAction action) {
positionsUpdatingGuard.entranceRequested(new IReentranceCases() {
@Override
public void ifAlreadyInside() {
action.doAction();
}
@Override
public void ifNewEntrance() {
onNewEntrance(action);
}
});
}
private void onNewEntrance(final IAction action) {
preAndPostActions.doAction(decorateWithNotifications(action));
}
private IAction decorateWithNotifications(final IAction action) {
return new IAction() {
@Override
public void doAction() {
deferedNotifier.set(new DeferedNotifier());
try {
action.doAction();
} finally {
DeferedNotifier notifier = deferedNotifier.get();
notifier.doNotifications();
deferedNotifier.set(null);
}
}
};
}
DeferedNotifier manualNotification(final IAction action) {
final DeferedNotifier result = new DeferedNotifier();
positionsUpdatingGuard.entranceRequested(new IReentranceCases() {
@Override
public void ifAlreadyInside() {
throw new RuntimeException("it cannot do a manual notification if it's already inside");
}
@Override
public void ifNewEntrance() {
preAndPostActions.doAction(new IAction() {
@Override
public void doAction() {
deferedNotifier.set(result);
try {
action.doAction();
} finally {
deferedNotifier.set(null);
}
}
});
}
});
return result;
}
private void taskPositionModified(final V task) {
executeWithPreAndPostActionsOnlyIfNewEntrance(new IAction() {
@Override
public void doAction() {
List<Recalculation> recalculationsNeededFrom = getRecalculationsNeededFrom(task);
doRecalculations(recalculationsNeededFrom,
Collections.singletonList(task));
}
});
}
private void doRecalculations(List<Recalculation> recalculationsNeeded,
Collection<? extends V> initiallyModified) {
Set<V> allModified = new HashSet<V>();
allModified.addAll(initiallyModified);
for (Recalculation each : recalculationsNeeded) {
boolean modified = each.doRecalculation();
if (modified) {
allModified.add(each.taskPoint.task);
}
}
List<V> shrunkContainers = shrunkContainersOfModified(allModified);
for (V each : getTaskAffectedByShrinking(shrunkContainers)) {
doRecalculations(getRecalculationsNeededFrom(each),
Collections.singletonList(each));
}
}
private List<V> getTaskAffectedByShrinking(List<V> shrunkContainers) {
List<V> tasksAffectedByShrinking = new ArrayList<V>();
for (V each : shrunkContainers) {
for (D eachDependency : graph.outgoingEdgesOf(each)) {
if (adapter.getType(eachDependency) == DependencyType.START_START
&& adapter.isVisible(eachDependency)) {
tasksAffectedByShrinking.add(adapter
.getDestination(eachDependency));
}
}
}
return tasksAffectedByShrinking;
}
private List<V> shrunkContainersOfModified(
Set<V> allModified) {
Set<V> topmostToShrink = getTopMostThatCouldPotentiallyNeedShrinking(allModified);
List<V> allToShrink = new ArrayList<V>();
for (V each : topmostToShrink) {
allToShrink.addAll(getContainersBottomUp(each));
}
List<V> result = new ArrayList<V>();
for (V each : allToShrink) {
boolean modified = enforceParentShrinkage(each);
if (modified) {
result.add(each);
}
}
return result;
}
private Set<V> getTopMostThatCouldPotentiallyNeedShrinking(
Collection<V> modified) {
Set<V> result = new HashSet<V>();
for (V each : modified) {
V t = getTopmostFor(each);
if (adapter.isContainer(t)) {
result.add(t);
}
}
return result;
}
private Collection<? extends V> getContainersBottomUp(
V container) {
List<V> result = new ArrayList<V>();
List<V> tasks = adapter.getChildren(container);
for (V each : tasks) {
if (adapter.isContainer(each)) {
result.addAll(getContainersBottomUp(each));
result.add(each);
}
}
result.add(container);
return result;
}
boolean enforceParentShrinkage(V container) {
GanttDate oldBeginDate = adapter.getStartDate(container);
GanttDate firstStart = getSmallestBeginDateFromChildrenFor(container);
GanttDate lastEnd = getBiggestEndDateFromChildrenFor(container);
GanttDate previousEnd = adapter.getEndDateFor(container);
if (firstStart.after(oldBeginDate) || previousEnd.after(lastEnd)) {
adapter.setStartDateFor(container,
GanttDate.max(firstStart, oldBeginDate));
adapter.setEndDateFor(container,
GanttDate.min(lastEnd, previousEnd));
return true;
}
return false;
}
}
private GanttDate getSmallestBeginDateFromChildrenFor(V container) {
return Collections.min(getChildrenDates(container, Point.START));
}
private GanttDate getBiggestEndDateFromChildrenFor(V container) {
return Collections.max(getChildrenDates(container, Point.END));
}
private List<GanttDate> getChildrenDates(V container, Point point) {
List<V> children = adapter.getChildren(container);
List<GanttDate> result = new ArrayList<GanttDate>();
if (children.isEmpty()) {
result.add(getDateFor(container, point));
}
for (V each : children) {
result.add(getDateFor(each, point));
}
return result;
}
GanttDate getDateFor(V task, Point point) {
if (point.equals(Point.START)) {
return adapter.getStartDate(task);
} else {
return adapter.getEndDateFor(task);
}
}
List<Recalculation> getRecalculationsNeededFrom(V task) {
List<Recalculation> result = new LinkedList<Recalculation>();
Set<Recalculation> parentRecalculationsAlreadyDone = new HashSet<Recalculation>();
Recalculation first = recalculationFor(allPointsPotentiallyModified(task));
first.couldHaveBeenModifiedBeforehand();
Queue<Recalculation> pendingOfNavigate = new LinkedList<Recalculation>();
result.addAll(getParentsRecalculations(parentRecalculationsAlreadyDone,
first.taskPoint));
result.add(first);
pendingOfNavigate.offer(first);
while (!pendingOfNavigate.isEmpty()) {
Recalculation current = pendingOfNavigate.poll();
for (TaskPoint each : current.taskPoint.getImmendiateReachable()) {
Recalculation recalculationToAdd = recalculationFor(each);
ListIterator<Recalculation> listIterator = result
.listIterator();
while (listIterator.hasNext()) {
Recalculation previous = listIterator.next();
if (previous.equals(recalculationToAdd)) {
listIterator.remove();
recalculationToAdd = previous;
break;
}
}
recalculationToAdd.comesFromPredecessor(current);
result.addAll(getParentsRecalculations(
parentRecalculationsAlreadyDone, each));
result.add(recalculationToAdd);
pendingOfNavigate.offer(recalculationToAdd);
}
}
return result;
}
private List<Recalculation> getParentsRecalculations(
Set<Recalculation> parentRecalculationsAlreadyDone,
TaskPoint taskPoint) {
List<Recalculation> result = new ArrayList<Recalculation>();
for (TaskPoint eachParent : parentsRecalculationsNeededFor(taskPoint)) {
Recalculation parentRecalculation = parentRecalculation(eachParent.task);
if (!parentRecalculationsAlreadyDone
.contains(parentRecalculation)) {
parentRecalculationsAlreadyDone.add(parentRecalculation);
result.add(parentRecalculation);
}
}
return result;
}
private Set<TaskPoint> parentsRecalculationsNeededFor(TaskPoint current) {
Set<TaskPoint> result = new LinkedHashSet<TaskPoint>();
if (current.areAllPointsPotentiallyModified()) {
List<V> path = fromTaskToTop(current.task);
if (path.size() > 1) {
path = path.subList(1, path.size());
Collections.reverse(path);
result.addAll(asBothPoints(path));
}
}
return result;
}
private Collection<? extends TaskPoint> asBothPoints(List<V> parents) {
List<TaskPoint> result = new ArrayList<TaskPoint>();
for (V each : parents) {
result.add(allPointsPotentiallyModified(each));
}
return result;
}
private List<V> fromTaskToTop(V task) {
List<V> result = new ArrayList<V>();
V current = task;
while (current != null) {
result.add(current);
current = fromChildToParent.get(current);
}
return result;
}
private Recalculation parentRecalculation(V task) {
return new Recalculation(allPointsPotentiallyModified(task), true);
}
private Recalculation recalculationFor(TaskPoint taskPoint) {
return new Recalculation(taskPoint, false);
}
private class Recalculation {
private final boolean parentRecalculation;
private final TaskPoint taskPoint;
private Set<Recalculation> recalculationsCouldAffectThis = new HashSet<Recalculation>();
private boolean recalculationCalled = false;
private boolean dataPointModified = false;
private boolean couldHaveBeenModifiedBeforehand = false;
Recalculation(TaskPoint taskPoint, boolean isParentRecalculation) {
Validate.notNull(taskPoint);
this.taskPoint = taskPoint;
this.parentRecalculation = isParentRecalculation;
}
public void couldHaveBeenModifiedBeforehand() {
couldHaveBeenModifiedBeforehand = true;
}
public void comesFromPredecessor(Recalculation predecessor) {
recalculationsCouldAffectThis.add(predecessor);
}
boolean doRecalculation() {
recalculationCalled = true;
dataPointModified = haveToDoCalculation()
&& taskChangesPosition();
return dataPointModified;
}
private boolean haveToDoCalculation() {
return (recalculationsCouldAffectThis.isEmpty() || parentsHaveBeenModified());
}
private boolean parentsHaveBeenModified() {
for (Recalculation each : recalculationsCouldAffectThis) {
if (!each.recalculationCalled) {
throw new RuntimeException(
"the parent must be called first");
}
if (each.dataPointModified
|| each.couldHaveBeenModifiedBeforehand) {
return true;
}
}
return false;
}
private boolean taskChangesPosition() {
ChangeTracker tracker = trackTaskChanges();
Constraint.initialValue(noRestrictions())
.withConstraints(getConstraintsToApply())
.apply();
return tracker.taskHasChanged();
}
@SuppressWarnings("unchecked")
private List<Constraint<PositionRestrictions>> getConstraintsToApply() {
List<Constraint<PositionRestrictions>> result = new ArrayList<Constraint<PositionRestrictions>>();
if (!scheduleBackwards) {
result.addAll(asList(new WeakBackwardsForces(),
new DominatingForwardForces()));
} else {
result.addAll(asList(new WeakForwardForces(),
new DominatingBackwardForces()));
}
return result;
}
abstract class PositionRestrictions {
abstract List<Constraint<GanttDate>> getStartConstraints();
abstract List<Constraint<GanttDate>> getEndConstraints();
abstract boolean satisfies(PositionRestrictions other);
}
private final class NoRestrictions extends PositionRestrictions {
@Override
List<Constraint<GanttDate>> getStartConstraints() {
return Collections.emptyList();
}
@Override
List<Constraint<GanttDate>> getEndConstraints() {
return Collections.emptyList();
}
@Override
boolean satisfies(PositionRestrictions restrictions) {
return true;
}
}
PositionRestrictions noRestrictions() {
return new NoRestrictions();
}
DatesBasedPositionRestrictions biggerThan(GanttDate start, GanttDate end) {
ComparisonType type = isScheduleForward() ? ComparisonType.BIGGER_OR_EQUAL_THAN
: ComparisonType.BIGGER_OR_EQUAL_THAN_LEFT_FLOATING;
return new DatesBasedPositionRestrictions(type, start, end);
}
DatesBasedPositionRestrictions lessThan(GanttDate start, GanttDate end) {
ComparisonType type = isScheduleForward() ? ComparisonType.LESS_OR_EQUAL_THAN_RIGHT_FLOATING
: ComparisonType.LESS_OR_EQUAL_THAN;
return new DatesBasedPositionRestrictions(type, start, end);
}
class DatesBasedPositionRestrictions extends PositionRestrictions {
private Constraint<GanttDate> startConstraint;
private Constraint<GanttDate> endConstraint;
private final GanttDate start;
private final GanttDate end;
public DatesBasedPositionRestrictions(
ComparisonType comparisonType, GanttDate start,
GanttDate end) {
this.start = start;
this.end = end;
this.startConstraint = ConstraintOnComparableValues
.instantiate(comparisonType, start);
this.endConstraint = ConstraintOnComparableValues.instantiate(
comparisonType, end);
}
boolean satisfies(PositionRestrictions other) {
if (DatesBasedPositionRestrictions.class.isInstance(other)) {
return satisfies(DatesBasedPositionRestrictions.class
.cast(other));
}
return false;
}
private boolean satisfies(DatesBasedPositionRestrictions other) {
return startConstraint.isSatisfiedBy(other.start)
&& endConstraint.isSatisfiedBy(other.end);
}
@Override
List<Constraint<GanttDate>> getStartConstraints() {
return Collections.singletonList(startConstraint);
}
@Override
List<Constraint<GanttDate>> getEndConstraints() {
return Collections.singletonList(endConstraint);
}
}
class ChangeTracker {
private GanttDate start;
private GanttDate end;
private final V task;
public ChangeTracker(V task) {
this.task = task;
this.start = adapter.getStartDate(task);
this.end = adapter.getEndDateFor(task);
}
public boolean taskHasChanged() {
return areNotEqual(adapter.getStartDate(task), this.start)
|| areNotEqual(adapter.getEndDateFor(task), this.end);
}
}
boolean areNotEqual(GanttDate a, GanttDate b) {
return a != b && a.compareTo(b) != 0;
}
protected ChangeTracker trackTaskChanges() {
return new ChangeTracker(taskPoint.task);
}
abstract class Forces extends Constraint<PositionRestrictions> {
protected final V task;
public Forces() {
this.task = taskPoint.task;
}
protected PositionRestrictions result;
protected PositionRestrictions applyConstraintTo(
PositionRestrictions restrictions) {
if (adapter.isFixed(task)) {
return restrictions;
}
result = enforceUsingPreviousRestrictions(restrictions);
return result;
}
public boolean isSatisfiedBy(PositionRestrictions value) {
return result.satisfies(value);
}
public void checkSatisfiesResult(PositionRestrictions finalResult) {
super.checkSatisfiesResult(finalResult);
if (DatesBasedPositionRestrictions.class
.isInstance(finalResult)) {
checkConstraintsAgainst(DatesBasedPositionRestrictions.class
.cast(finalResult));
}
}
private void checkConstraintsAgainst(
DatesBasedPositionRestrictions finalResult) {
checkStartConstraints(finalResult.start);
checkEndConstraints(finalResult.end);
}
private void checkStartConstraints(GanttDate finalStart) {
Constraint
.checkSatisfyResult(getStartConstraints(), finalStart);
}
private void checkEndConstraints(GanttDate finalEnd) {
Constraint.checkSatisfyResult(getEndConstraints(), finalEnd);
}
abstract List<Constraint<GanttDate>> getStartConstraints();
abstract List<Constraint<GanttDate>> getEndConstraints();
abstract PositionRestrictions enforceUsingPreviousRestrictions(
PositionRestrictions restrictions);
}
abstract class Dominating extends Forces {
private final Point primary;
private final Point secondary;
public Dominating(Point primary, Point secondary) {
Validate.isTrue(isSupportedPoint(primary));
Validate.isTrue(isSupportedPoint(secondary));
Validate.isTrue(!primary.equals(secondary));
this.primary = primary;
this.secondary = secondary;
}
private boolean isSupportedPoint(Point point) {
EnumSet<Point> validPoints = EnumSet.of(Point.START, Point.END);
return validPoints.contains(point);
}
private Point getPrimaryPoint() {
return primary;
}
private Point getSecondaryPoint() {
return secondary;
}
@Override
PositionRestrictions enforceUsingPreviousRestrictions(
PositionRestrictions restrictions) {
if (taskPoint.areAllPointsPotentiallyModified()) {
return enforceBoth(restrictions);
} else if (taskPoint.somePointPotentiallyModified()) {
return enforceSecondaryPoint(restrictions);
}
return restrictions;
}
private PositionRestrictions enforceBoth(
PositionRestrictions restrictions) {
ChangeTracker changeTracker = trackTaskChanges();
PositionRestrictions currentRestrictions = enforcePrimaryPoint(restrictions);
if (changeTracker.taskHasChanged() || parentRecalculation
|| couldHaveBeenModifiedBeforehand) {
return enforceSecondaryPoint(currentRestrictions);
}
return currentRestrictions;
}
private PositionRestrictions enforcePrimaryPoint(
PositionRestrictions originalRestrictions) {
GanttDate newDominatingPointDate = calculatePrimaryPointDate(originalRestrictions);
return enforceRestrictionsFor(primary, newDominatingPointDate);
}
/**
* Calculates the new date for the primary point based on the
* present constraints. If there are no constraints this method will
* return the existent commanding point date
* @param originalRestrictions
*/
private GanttDate calculatePrimaryPointDate(
PositionRestrictions originalRestrictions) {
GanttDate newDate = Constraint
.<GanttDate> initialValue(null)
.withConstraints(
getConstraintsFrom(originalRestrictions,
getPrimaryPoint()))
.withConstraints(getConstraintsFor(getPrimaryPoint()))
.applyWithoutFinalCheck();
if (newDate == null) {
return getTaskDateFor(getPrimaryPoint());
}
return newDate;
}
private List<Constraint<GanttDate>> getConstraintsFor(Point point) {
Validate.isTrue(isSupportedPoint(point));
switch (point) {
case START:
return getStartConstraints();
case END:
return getEndConstraints();
default:
throw new RuntimeException("shouldn't happen");
}
}
private PositionRestrictions enforceSecondaryPoint(
PositionRestrictions restrictions) {
GanttDate newSecondaryPointDate = calculateSecondaryPointDate(restrictions);
if (newSecondaryPointDate == null) {
return restrictions;
}
restrictions = enforceRestrictionsFor(getSecondaryPoint(),
newSecondaryPointDate);
if (taskPoint.onlyModifies(getSecondaryPoint())) {
// primary point constraints could be the ones "commanding"
// now
GanttDate potentialPrimaryDate = calculatePrimaryPointDate(restrictions);
if (!doSatisfyOrderCondition(potentialPrimaryDate,
getTaskDateFor(getPrimaryPoint()))) {
return enforceRestrictionsFor(getPrimaryPoint(),
potentialPrimaryDate);
}
}
return restrictions;
}
private GanttDate calculateSecondaryPointDate(
PositionRestrictions restrictions) {
GanttDate newEnd = Constraint
.<GanttDate> initialValue(null)
.withConstraints(
getConstraintsFrom(restrictions,
getSecondaryPoint()))
.withConstraints(getConstraintsFor(getSecondaryPoint()))
.applyWithoutFinalCheck();
return newEnd;
}
protected abstract boolean doSatisfyOrderCondition(
GanttDate supposedlyBefore, GanttDate supposedlyAfter);
private PositionRestrictions enforceRestrictionsFor(Point point,
GanttDate newDate) {
GanttDate old = getTaskDateFor(point);
if (areNotEqual(old, newDate)) {
setTaskDateFor(point, newDate);
}
return createRestrictionsFor(getTaskDateFor(Point.START),
getTaskDateFor(Point.END));
}
GanttDate getTaskDateFor(Point point) {
Validate.isTrue(isSupportedPoint(point));
return getDateFor(task, point);
}
protected abstract PositionRestrictions createRestrictionsFor(
GanttDate start, GanttDate end);
private void setTaskDateFor(Point point, GanttDate date) {
Validate.isTrue(isSupportedPoint(point));
switch (point) {
case START:
adapter.setStartDateFor(task, date);
break;
case END:
adapter.setEndDateFor(task, date);
}
}
private List<Constraint<GanttDate>> getConstraintsFrom(
PositionRestrictions restrictions, Point point) {
Validate.isTrue(isSupportedPoint(point));
switch (point) {
case START:
return restrictions.getStartConstraints();
case END:
return restrictions.getEndConstraints();
default:
throw new RuntimeException("shouldn't happen");
}
}
protected List<Constraint<GanttDate>> getConstraintsForPrimaryPoint() {
List<Constraint<GanttDate>> result = new ArrayList<Constraint<GanttDate>>();
if (dependenciesConstraintsHavePriority) {
result.addAll(getTaskConstraints(getPrimaryPoint()));
result.addAll(getDependenciesConstraintsFor(getPrimaryPoint()));
} else {
result.addAll(getDependenciesConstraintsFor(getPrimaryPoint()));
result.addAll(getTaskConstraints(getPrimaryPoint()));
}
result.addAll(globalStartConstraints);
return result;
}
protected List<Constraint<GanttDate>> getConstraintsForSecondaryPoint() {
return getDependenciesConstraintsFor(getSecondaryPoint());
}
private List<Constraint<GanttDate>> getDependenciesConstraintsFor(
Point point) {
final Set<D> withDependencies = getDependenciesAffectingThisTask();
return adapter.getConstraints(getCalculator(),
withDependencies, point);
}
protected abstract Set<D> getDependenciesAffectingThisTask();
private List<Constraint<GanttDate>> getTaskConstraints(Point point) {
Validate.isTrue(isSupportedPoint(point));
switch (point) {
case START:
return adapter.getStartConstraintsFor(task);
case END:
return adapter.getEndConstraintsFor(task);
default:
throw new RuntimeException("shouldn't happen");
}
}
protected abstract ConstraintCalculator<V> getCalculator();
protected ConstraintCalculator<V> createNormalCalculator() {
return createCalculator(false);
}
protected ConstraintCalculator<V> createBackwardsCalculator() {
return createCalculator(true);
}
private ConstraintCalculator<V> createCalculator(boolean inverse) {
return new ConstraintCalculator<V>(inverse) {
@Override
protected GanttDate getStartDate(V vertex) {
return adapter.getStartDate(vertex);
}
@Override
protected GanttDate getEndDate(V vertex) {
return adapter.getEndDateFor(vertex);
}
};
}
}
class DominatingForwardForces extends Dominating {
public DominatingForwardForces() {
super(Point.START, Point.END);
}
@Override
List<Constraint<GanttDate>> getStartConstraints() {
return getConstraintsForPrimaryPoint();
}
@Override
List<Constraint<GanttDate>> getEndConstraints() {
return getConstraintsForSecondaryPoint();
}
@Override
protected Set<D> getDependenciesAffectingThisTask() {
return graph.incomingEdgesOf(task);
}
@Override
protected ConstraintCalculator<V> getCalculator() {
return createNormalCalculator();
}
@Override
protected PositionRestrictions createRestrictionsFor(
GanttDate start, GanttDate end) {
return biggerThan(start, end);
}
@Override
protected boolean doSatisfyOrderCondition(
GanttDate supposedlyBefore,
GanttDate supposedlyAfter) {
return supposedlyBefore.compareTo(supposedlyAfter) <= 0;
}
}
class DominatingBackwardForces extends Dominating {
public DominatingBackwardForces() {
super(Point.END, Point.START);
}
@Override
List<Constraint<GanttDate>> getStartConstraints() {
return getConstraintsForSecondaryPoint();
}
@Override
List<Constraint<GanttDate>> getEndConstraints() {
return getConstraintsForPrimaryPoint();
}
@Override
protected Set<D> getDependenciesAffectingThisTask() {
return graph.outgoingEdgesOf(task);
}
@Override
protected ConstraintCalculator<V> getCalculator() {
return createBackwardsCalculator();
}
@Override
protected PositionRestrictions createRestrictionsFor(
GanttDate start, GanttDate end) {
return lessThan(start, end);
}
@Override
protected boolean doSatisfyOrderCondition(
GanttDate supposedlyBefore,
GanttDate supposedlyAfter) {
return supposedlyBefore.compareTo(supposedlyAfter) >= 0;
}
}
class WeakForwardForces extends Forces {
@Override
List<Constraint<GanttDate>> getStartConstraints() {
return adapter.getStartConstraintsFor(task);
}
@Override
List<Constraint<GanttDate>> getEndConstraints() {
return Collections.emptyList();
}
@Override
PositionRestrictions enforceUsingPreviousRestrictions(
PositionRestrictions restrictions) {
GanttDate result = Constraint.<GanttDate> initialValue(null)
.withConstraints(restrictions.getStartConstraints())
.withConstraints(getStartConstraints())
.applyWithoutFinalCheck();
if (result != null) {
return enforceRestrictions(result);
}
return restrictions;
}
private PositionRestrictions enforceRestrictions(GanttDate result) {
adapter.setStartDateFor(task, result);
return biggerThan(result, adapter.getEndDateFor(task));
}
}
class WeakBackwardsForces extends Forces {
@Override
PositionRestrictions enforceUsingPreviousRestrictions(
PositionRestrictions restrictions) {
GanttDate result = Constraint.<GanttDate> initialValue(null)
.withConstraints(restrictions.getEndConstraints())
.withConstraints(getEndConstraints())
.applyWithoutFinalCheck();
if (result != null) {
return enforceRestrictions(result);
}
return restrictions;
}
@Override
List<Constraint<GanttDate>> getStartConstraints() {
return Collections.emptyList();
}
@Override
List<Constraint<GanttDate>> getEndConstraints() {
List<Constraint<GanttDate>> result = new ArrayList<Constraint<GanttDate>>();
result.addAll(adapter.getEndConstraintsFor(task));
if (scheduleBackwards) {
result.addAll(globalEndConstraints);
}
return result;
}
private PositionRestrictions enforceRestrictions(GanttDate newEnd) {
adapter.setEndDateFor(task, newEnd);
return lessThan(adapter.getStartDate(task), newEnd);
}
}
@Override
public int hashCode() {
return new HashCodeBuilder()
.append(parentRecalculation)
.append(taskPoint)
.toHashCode();
}
@Override
public String toString() {
return String.format("%s, parentRecalculation: %s, parents: %s",
taskPoint, parentRecalculation,
asSimpleString(recalculationsCouldAffectThis));
}
private String asSimpleString(
Collection<? extends Recalculation> recalculations) {
StringBuilder result = new StringBuilder();
result.append("[");
for (Recalculation each : recalculations) {
result.append(each.taskPoint).append(", ");
}
result.append("]");
return result.toString();
}
@Override
public boolean equals(Object obj) {
if (Recalculation.class.isInstance(obj)) {
Recalculation other = Recalculation.class.cast(obj);
return new EqualsBuilder().append(parentRecalculation, other.parentRecalculation)
.append(taskPoint, other.taskPoint)
.isEquals();
}
return false;
}
}
public void remove(final V task) {
Set<V> needingEnforcing = getOutgoingTasksFor(task);
graph.removeVertex(task);
topLevelTasks.remove(task);
fromChildToParent.remove(task);
if (adapter.isContainer(task)) {
for (V t : adapter.getChildren(task)) {
remove(t);
}
}
enforcer.enforceRestrictionsOn(needingEnforcing);
}
public void removeDependency(D dependency) {
graph.removeEdge(dependency);
V destination = adapter.getDestination(dependency);
enforcer.enforceRestrictionsOn(destination);
}
public boolean canAddDependency(D dependency) {
return !isForbidden(dependency) && doesNotProvokeLoop(dependency);
}
private boolean isForbidden(D dependency) {
if (!adapter.isVisible(dependency)) {
// the invisible dependencies, the ones used to implement container
// behavior are not forbidden
return false;
}
boolean endEndDependency = DependencyType.END_END == dependency
.getType();
boolean startStartDependency = DependencyType.START_START == dependency
.getType();
V source = adapter.getSource(dependency);
V destination = adapter.getDestination(dependency);
boolean destinationIsContainer = adapter.isContainer(destination);
boolean sourceIsContainer = adapter.isContainer(source);
return (destinationIsContainer && endEndDependency)
|| (sourceIsContainer && startStartDependency);
}
public void add(D dependency) {
add(dependency, true);
}
public void addWithoutEnforcingConstraints(D dependency) {
add(dependency, false);
}
private void add(D dependency, boolean enforceRestrictions) {
if (isForbidden(dependency)) {
return;
}
V source = adapter.getSource(dependency);
V destination = adapter.getDestination(dependency);
graph.addEdge(source, destination, dependency);
if (enforceRestrictions) {
enforceRestrictions(destination);
}
}
public void enforceRestrictions(final V task) {
enforcer.taskPositionModified(task);
}
public DeferedNotifier manualNotificationOn(IAction action) {
return enforcer.manualNotification(action);
}
public boolean contains(D dependency) {
return graph.containsEdge(dependency);
}
public List<V> getTasks() {
return new ArrayList<V>(graph.vertexSet());
}
public List<D> getVisibleDependencies() {
ArrayList<D> result = new ArrayList<D>();
for (D dependency : graph.edgeSet()) {
if (adapter.isVisible(dependency)) {
result.add(dependency);
}
}
return result;
}
public List<V> getTopLevelTasks() {
return Collections.unmodifiableList(topLevelTasks);
}
public void childrenAddedTo(V task) {
enforcer.enforceRestrictionsOn(task);
}
public List<V> getInitialTasks() {
List<V> result = new ArrayList<V>();
for (V task : graph.vertexSet()) {
int dependencies = graph.inDegreeOf(task);
if ((dependencies == 0)
|| (dependencies == getNumberOfIncomingDependenciesByType(
task, DependencyType.END_END))) {
result.add(task);
}
}
return result;
}
public IDependency<V> getDependencyFrom(V from, V to) {
return graph.getEdge(from, to);
}
public Set<V> getOutgoingTasksFor(V task) {
Set<V> result = new HashSet<V>();
for (D dependency : graph.outgoingEdgesOf(task)) {
result.add(adapter.getDestination(dependency));
}
return result;
}
public Set<V> getIncomingTasksFor(V task) {
Set<V> result = new HashSet<V>();
for (D dependency : graph.incomingEdgesOf(task)) {
result.add(adapter.getSource(dependency));
}
return result;
}
public List<V> getLatestTasks() {
List<V> tasks = new ArrayList<V>();
for (V task : graph.vertexSet()) {
int dependencies = graph.outDegreeOf(task);
if ((dependencies == 0)
|| (dependencies == getNumberOfOutgoingDependenciesByType(
task, DependencyType.START_START))) {
tasks.add(task);
}
}
return tasks;
}
private int getNumberOfIncomingDependenciesByType(V task,
DependencyType dependencyType) {
int count = 0;
for (D dependency : graph.incomingEdgesOf(task)) {
if (adapter.getType(dependency).equals(dependencyType)) {
count++;
}
}
return count;
}
private int getNumberOfOutgoingDependenciesByType(V task,
DependencyType dependencyType) {
int count = 0;
for (D dependency : graph.outgoingEdgesOf(task)) {
if (adapter.getType(dependency).equals(dependencyType)) {
count++;
}
}
return count;
}
public boolean isContainer(V task) {
if (task == null) {
return false;
}
return adapter.isContainer(task);
}
public boolean contains(V container, V task) {
if ((container == null) || (task == null)) {
return false;
}
if (adapter.isContainer(container)) {
return adapter.getChildren(container).contains(task);
}
return false;
}
public boolean doesNotProvokeLoop(D dependency) {
Set<TaskPoint> reachableFromDestination = destinationPoint(dependency)
.getReachable();
for (TaskPoint each : reachableFromDestination) {
if (each.sendsModificationsThrough(dependency)) {
return false;
}
}
return true;
}
TaskPoint destinationPoint(D dependency) {
V source = getDependencyDestination(dependency);
return new TaskPoint(source,
potentiallyModifiedDestinationPoints(dependency.getType()));
}
private Set<Point> potentiallyModifiedDestinationPoints(DependencyType type) {
Point destinationPoint = getDestinationPoint(type);
if (isDominatingPoint(destinationPoint)) {
return EnumSet.of(Point.START, Point.END);
} else {
return EnumSet.of(destinationPoint);
}
}
/**
* The dominating point is the one that causes the other point to be
* modified; e.g. when doing forward scheduling the dominating point is the
* start.
*/
private boolean isDominatingPoint(Point point) {
return isScheduleForward() && point == Point.START
|| isScheduleBackwards() && point == Point.END;
}
private Point getDestinationPoint(DependencyType type) {
return type.getSourceAndDestination()[isScheduleForward() ? 1 : 0];
}
private V getDependencySource(D dependency) {
return isScheduleForward() ? adapter.getSource(dependency) : adapter
.getDestination(dependency);
}
private V getDependencyDestination(D dependency) {
return isScheduleForward() ? adapter.getDestination(dependency)
: adapter.getSource(dependency);
}
TaskPoint allPointsPotentiallyModified(V task) {
return new TaskPoint(task, EnumSet.of(Point.START, Point.END));
}
private class TaskPoint {
private final V task;
private final boolean isContainer;
private final Set<Point> pointsModified;
TaskPoint(V task, Set<Point> pointsModified) {
this.task = task;
this.pointsModified = Collections.unmodifiableSet(pointsModified);
this.isContainer = adapter.isContainer(task);
}
@Override
public String toString() {
return String.format("%s(%s)", task, pointsModified);
}
@Override
public boolean equals(Object obj) {
if (TaskPoint.class.isInstance(obj)) {
TaskPoint other = TaskPoint.class.cast(obj);
return new EqualsBuilder().append(task, other.task)
.append(pointsModified, other.pointsModified)
.isEquals();
}
return false;
}
@Override
public int hashCode() {
return new HashCodeBuilder().append(task).append(pointsModified)
.toHashCode();
}
public boolean areAllPointsPotentiallyModified() {
return pointsModified.size() > 1;
}
public boolean somePointPotentiallyModified() {
return pointsModified.contains(Point.START)
|| pointsModified.contains(Point.END);
}
public boolean onlyModifies(Point point) {
return pointsModified.size() == 1 && pointsModified.contains(point);
}
Set<TaskPoint> getReachable() {
Set<TaskPoint> result = new HashSet<TaskPoint>();
Queue<TaskPoint> pending = new LinkedList<TaskPoint>();
result.add(this);
pending.offer(this);
while (!pending.isEmpty()) {
TaskPoint current = pending.poll();
Set<TaskPoint> immendiate = current.getImmendiateReachable();
for (TaskPoint each : immendiate) {
if (!result.contains(each)) {
result.add(each);
pending.offer(each);
}
}
}
return result;
}
private Set<TaskPoint> getImmendiateReachable() {
Set<TaskPoint> result = new HashSet<TaskPoint>();
Set<D> candidates = immediateDependencies();
for (D each : candidates) {
if (this.sendsModificationsThrough(each)) {
result.add(destinationPoint(each));
}
}
return result;
}
private Set<D> immediateDependencies() {
return isScheduleForward() ? graph.outgoingEdgesOf(this.task)
: graph.incomingEdgesOf(this.task);
}
public boolean sendsModificationsThrough(D dependency) {
V source = getDependencySource(dependency);
Point dependencySourcePoint = getSourcePoint(adapter
.getType(dependency));
return source.equals(task)
&& (!isContainer || pointsModified
.contains(dependencySourcePoint));
}
private Point getSourcePoint(DependencyType type) {
Point[] sourceAndDestination = type.getSourceAndDestination();
return sourceAndDestination[isScheduleForward() ? 0 : 1];
}
}
private V getTopmostFor(V task) {
V result = task;
while (fromChildToParent.containsKey(result)) {
result = fromChildToParent.get(result);
}
return result;
}
public boolean isScheduleForward() {
return !isScheduleBackwards();
}
public boolean isScheduleBackwards() {
return scheduleBackwards;
}
@Override
public GanttDate getEndDateFor(V task) {
return adapter.getEndDateFor(task);
}
@Override
public List<Constraint<GanttDate>> getStartConstraintsFor(V task) {
return adapter.getStartConstraintsFor(task);
}
@Override
public GanttDate getStartDate(V task) {
return adapter.getStartDate(task);
}
@Override
public List<V> getChildren(V task) {
if (!isContainer(task)) {
return Collections.emptyList();
}
return adapter.getChildren(task);
}
}
interface IReentranceCases {
public void ifNewEntrance();
public void ifAlreadyInside();
}
class ReentranceGuard {
private final ThreadLocal<Boolean> inside = new ThreadLocal<Boolean>() {
protected Boolean initialValue() {
return false;
};
};
public void entranceRequested(IReentranceCases reentranceCases) {
if (inside.get()) {
reentranceCases.ifAlreadyInside();
return;
}
inside.set(true);
try {
reentranceCases.ifNewEntrance();
} finally {
inside.set(false);
}
}
}
|
package pokefenn.totemic.ceremony;
import net.minecraft.core.BlockPos;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.world.level.Level;
import pokefenn.totemic.api.ceremony.CeremonyEffectContext;
import pokefenn.totemic.api.ceremony.CeremonyInstance;
public class CeremonyRain extends CeremonyInstance {
private final boolean doRain;
public CeremonyRain(boolean doRain) {
this.doRain = doRain;
}
@Override
public void effect(Level level, BlockPos pos, CeremonyEffectContext context) {
if(level instanceof ServerLevel slevel && slevel.isRaining() != doRain) {
slevel.setWeatherParameters(
doRain ? 0 : 6000, //Clear weather time
doRain ? 6000 : 0, //Rain time
doRain, //raining
false); //thundering
}
}
}
|
package co.zpdev.bots.jitters.cmd;
import co.zpdev.bots.jitters.Jitters;
import co.zpdev.bots.jitters.lstnr.JoinLeaveLog;
import co.zpdev.core.discord.command.Command;
import co.zpdev.core.discord.exception.ExceptionHandler;
import net.dv8tion.jda.core.entities.Message;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;
/**
* @author ZP4RKER
*/
public class TestCommand {
@Command(
aliases = "test",
autodelete = true
)
public void onCommand(Message message) {
String intro;
BufferedReader rd = new BufferedReader(new InputStreamReader(Jitters.class.getResourceAsStream("intros.txt")));
String line; List<String> intros = new ArrayList<>();
try {
while ((line = rd.readLine()) != null) {
if (line.startsWith("//")) continue;
intros.add(line);
}
rd.close();
int rand = ThreadLocalRandom.current().nextInt(0, intros.size());
intro = intros.get(rand).replace("%user%", message.getAuthor().getAsMention());
} catch (IOException e) {
ExceptionHandler.handleException("reading file (intros.txt)", e);
intro = null;
}
message.getAuthor().openPrivateChannel().complete().sendMessage(intro == null ? "null" : "not null").complete();
}
}
|
package com.sintef_energy.ubisolar.resources;
import com.sintef_energy.ubisolar.ServerDAO;
import com.sintef_energy.ubisolar.structs.Device;
import com.sintef_energy.ubisolar.structs.DeviceUsage;
import com.yammer.dropwizard.jersey.params.LongParam;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.util.ArrayList;
import java.util.Random;
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
@Path("user/{user}/")
public class DataGeneratorResource {
private ServerDAO db;
private ArrayList<Device> devices;
public DataGeneratorResource(ServerDAO db) {
this.db = db;
this.devices = new ArrayList<Device>();
}
private void generateDevices(ArrayList<Device> devices, long user) {
long time = System.currentTimeMillis();
devices.add(new Device(time+1, user, "TV", "This is your TV", time/1000l, false, 1));
devices.add(new Device(time+2, user, "Stove", "This is your Stove", time/1000l, false, 2));
devices.add(new Device(time+3, user, "Fridge", "This is your Fridge", time/1000l, false, 3));
devices.add(new Device(time+4, user, "Heater", "This is your Heater", time/1000l, false, 4));
}
private ArrayList<DeviceUsage> generateUsage(Device d) {
ArrayList<DeviceUsage> usage = new ArrayList<DeviceUsage>();
Random r = new Random();
long time = System.currentTimeMillis();
double rangeMin = 5.0, rangeMax = 20.0;
double random;
long n = 125363;
for(int i = 0; i < 1000; i++) {
random = rangeMin + (rangeMax - rangeMin) * r.nextDouble();
rangeMin = random - 5;
rangeMax = random + 5;
if(random < 0) random = -random;
usage.add(new DeviceUsage(n++, d.getId(), (time/1000L) - (i*3600), random, false, time));
}
return usage;
}
@GET
@Path("generate/")
public Response generateData(@PathParam("user") LongParam user) {
ArrayList<DeviceUsage> usage;
this.generateDevices(this.devices, user.get());
db.createDevices(this.devices.iterator());
for(Device d : this.devices) {
usage = generateUsage(d);
db.addUsageForDevices(usage.iterator());
}
return Response.status(Response.Status.OK).build();
}
}
|
package com.horcrux.svg;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.Rect;
import android.net.Uri;
import com.facebook.common.executors.UiThreadImmediateExecutorService;
import com.facebook.common.logging.FLog;
import com.facebook.common.references.CloseableReference;
import com.facebook.datasource.DataSource;
import com.facebook.drawee.backends.pipeline.Fresco;
import com.facebook.imagepipeline.datasource.BaseBitmapDataSubscriber;
import com.facebook.imagepipeline.image.CloseableBitmap;
import com.facebook.imagepipeline.image.CloseableImage;
import com.facebook.imagepipeline.request.ImageRequest;
import com.facebook.imagepipeline.request.ImageRequestBuilder;
import com.facebook.react.bridge.ReadableMap;
import com.facebook.react.common.ReactConstants;
import com.facebook.react.uimanager.annotations.ReactProp;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
/**
* Shadow node for virtual RNSVGPath view
*/
public class RNSVGImageShadowNode extends RNSVGPathShadowNode {
private String mX;
private String mY;
private String mW;
private String mH;
private Uri mUri;
private boolean mLoading;
@ReactProp(name = "x")
public void setX(String x) {
mX = x;
markUpdated();
}
@ReactProp(name = "y")
public void setY(String y) {
mY = y;
markUpdated();
}
@ReactProp(name = "width")
public void setWidth(String width) {
mW = width;
markUpdated();
}
@ReactProp(name = "height")
public void seHeight(String height) {
mH = height;
markUpdated();
}
@ReactProp(name = "src")
public void setSrc(@Nullable ReadableMap src) {
if (src != null) {
String uriString = src.getString("uri");
if (uriString == null || uriString.isEmpty()) {
//TODO: give warning about this
return;
}
mUri = Uri.parse(uriString);
}
}
@Override
public void draw(final Canvas canvas, final Paint paint, final float opacity) {
final ImageRequest request = ImageRequestBuilder.newBuilderWithSource(mUri).build();
final boolean inMemoryCache = Fresco.getImagePipeline().isInBitmapMemoryCache(request);
if (inMemoryCache) {
tryRender(request, canvas, paint, opacity);
} else if (!mLoading) {
loadBitmap(request, canvas, paint);
}
}
private void loadBitmap(@Nonnull final ImageRequest request, @Nonnull final Canvas canvas, @Nonnull final Paint paint) {
final DataSource<CloseableReference<CloseableImage>> dataSource
= Fresco.getImagePipeline().fetchDecodedImage(request, getThemedContext());
dataSource.subscribe(new BaseBitmapDataSubscriber() {
@Override
public void onNewResultImpl(@Nullable Bitmap bitmap) {
if (bitmap != null) {
canvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR);
paint.reset();
getSvgShadowNode().drawChildren(canvas, paint);
mLoading = false;
}
}
@Override
public void onFailureImpl(DataSource dataSource) {
// No cleanup required here.
// TODO: more details about this failure
mLoading = false;
FLog.w(ReactConstants.TAG, dataSource.getFailureCause(), "RNSVG: fetchDecodedImage failed!");
}
},
UiThreadImmediateExecutorService.getInstance()
);
}
private void doRender(@Nonnull final Canvas canvas, @Nonnull final Paint paint, @Nonnull final Bitmap bitmap, final float opacity) {
final int count = saveAndSetupCanvas(canvas);
clip(canvas, paint);
float x = PropHelper.fromPercentageToFloat(mX, mWidth, 0, mScale);
float y = PropHelper.fromPercentageToFloat(mY, mHeight, 0, mScale);
float w = PropHelper.fromPercentageToFloat(mW, mWidth, 0, mScale);
float h = PropHelper.fromPercentageToFloat(mH, mHeight, 0, mScale);
canvas.drawBitmap(bitmap, null, new Rect((int) x, (int) y, (int) (x + w), (int) (y + h)), paint);
restoreCanvas(canvas, count);
markUpdateSeen();
}
private void tryRender(@Nonnull final ImageRequest request, @Nonnull final Canvas canvas, @Nonnull final Paint paint, final float opacity) {
// Fresco.getImagePipeline().prefetchToBitmapCache(request, getThemedContext());
final DataSource<CloseableReference<CloseableImage>> dataSource
= Fresco.getImagePipeline().fetchImageFromBitmapCache(request, getThemedContext());
try {
final CloseableReference<CloseableImage> imageReference = dataSource.getResult();
if (imageReference != null) {
try {
if (imageReference.get() instanceof CloseableBitmap) {
final Bitmap bitmap = ((CloseableBitmap) imageReference.get()).getUnderlyingBitmap();
if (bitmap != null) {
doRender(canvas, paint, bitmap, opacity);
}
}
} finally {
CloseableReference.closeSafely(imageReference);
}
}
} finally {
dataSource.close();
}
}
}
|
package programminglife.model.drawing;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.paint.Color;
import org.eclipse.collections.impl.factory.Sets;
import programminglife.model.GenomeGraph;
import programminglife.model.XYCoordinate;
import programminglife.utility.Console;
import java.util.*;
/**
* A part of a {@link programminglife.model.GenomeGraph}. It uses a centerNode and a radius.
* Roughly, every node reachable within radius steps from centerNode is included in this graph.
* When updating the centerNode or the radius, it also updates the Nodes within this SubGraph.
*/
public class SubGraph {
private static final int DEFAULT_DYNAMIC_RADIUS = 50;
private static final int DEFAULT_NODE_Y = 50;
private static final int BORDER_BUFFER = 40;
private static final int MIN_RADIUS_DEFAULT = 50;
/**
* The amount of padding between layers (horizontal padding).
*/
private static final double LAYER_PADDING = 20;
private static final double DIFF_LAYER_PADDING = 7;
private double zoomLevel;
/**
* The amount of padding between nodes within a Layer (vertical padding).
*/
private GenomeGraph graph;
private LinkedHashMap<Integer, DrawableNode> nodes;
private LinkedHashMap<Integer, DrawableNode> rootNodes;
private LinkedHashMap<Integer, DrawableNode> endNodes;
private ArrayList<Layer> layers;
private Map<DrawableNode, Map<DrawableNode, Collection<Integer>>> genomes;
private int numberOfGenomes;
private boolean replaceSNPs;
/**
* Create a SubGraph from a graph, without any nodes initially.
*
* @param graph The {@link GenomeGraph} that this SubGraph is based on.
* @param zoomLevel double of the zoomLevel.
* @param replaceSNPs boolean for if the SNPs need to be drawn.
*/
private SubGraph(GenomeGraph graph, double zoomLevel, boolean replaceSNPs) {
this(graph, zoomLevel, replaceSNPs, new LinkedHashMap<>(), new LinkedHashMap<>(), new LinkedHashMap<>());
}
/**
* Create a SubGraph with the specified nodes, rootNodes and endNodes.
*
* @param graph The {@link GenomeGraph} that this SubGraph is based on.
* @param zoomLevel double of the zoomLevel.
* @param replaceSNPs boolean for if the SNPs need to be drawn.
* @param nodes The nodes of this SubGraph.
* @param rootNodes The rootNodes of this SubGraph.
* @param endNodes The endNodes of this SubGraph.
*/
private SubGraph(GenomeGraph graph, double zoomLevel, boolean replaceSNPs,
LinkedHashMap<Integer, DrawableNode> nodes, LinkedHashMap<Integer, DrawableNode> rootNodes,
LinkedHashMap<Integer, DrawableNode> endNodes) {
this.graph = graph;
this.zoomLevel = zoomLevel;
this.nodes = nodes;
this.rootNodes = rootNodes;
this.endNodes = endNodes;
this.genomes = new LinkedHashMap<>();
this.numberOfGenomes = graph.getTotalGenomeNumber();
this.replaceSNPs = replaceSNPs;
this.replaceSNPs();
this.calculateGenomes();
this.createLayers();
}
/**
* Create a SubGraph using a centerNode and a radius around that centerNode.
* This SubGraph will include all Nodes within radius steps to a parent,
* and then another 2radius steps to a child, and symmetrically the same with children / parents reversed.
*
* @param centerNode The centerNode
* @param radius The radius
* @param replaceSNPs flag if SNPs should be collapsed
*/
public SubGraph(DrawableSegment centerNode, int radius, boolean replaceSNPs) {
this(centerNode, 1, MIN_RADIUS_DEFAULT, Math.max(radius, MIN_RADIUS_DEFAULT), replaceSNPs);
Layer firstLayer = layers.get(0);
assert (firstLayer != null);
firstLayer.setX(0);
firstLayer.setDrawLocations(DEFAULT_NODE_Y, zoomLevel);
this.setRightDrawLocations(this.layers, 0);
}
/**
* Create a SubGraph using a centerNode and a radius around that centerNode.
* This SubGraph will include all Nodes within radius steps to a parent,
* and then another 2radius steps to a child, and symmetrically the same with children / parents reversed.
*
* @param centerNode The centerNode
* @param zoomLevel double of the amount zoomed in/out
* @param minRadius The minimum radius.
* @param radius The radius
* @param replaceSNPs flag if SNPs should be collapsed
*/
private SubGraph(DrawableSegment centerNode, double zoomLevel, int minRadius, int radius, boolean replaceSNPs) {
assert (minRadius <= radius);
this.graph = centerNode.getGraph();
this.zoomLevel = zoomLevel;
this.layers = null;
this.genomes = new LinkedHashMap<>();
this.replaceSNPs = replaceSNPs;
this.numberOfGenomes = graph.getTotalGenomeNumber();
findNodes(this, Collections.singleton(centerNode), new LinkedHashMap<>(), radius);
this.replaceSNPs();
this.calculateGenomes();
this.layout();
this.colorize();
}
/**
* Detect SNPs and replace them.
*/
public void replaceSNPs() {
if (this.replaceSNPs) {
Map<Integer, DrawableNode> nodesCopy = new LinkedHashMap<>(this.nodes);
for (Map.Entry<Integer, DrawableNode> entry : nodesCopy.entrySet()) {
DrawableNode parent = entry.getValue();
DrawableSNP snp = parent.createSNPIfPossible(this);
if (snp != null) {
snp.getMutations().stream().map(DrawableNode::getIdentifier).forEach(id -> {
this.nodes.remove(id);
parent.getChildren().remove(id);
snp.getChild().getParents().remove(id);
});
this.nodes.put(snp.getIdentifier(), snp);
}
}
}
}
/**
* Find nodes within radius steps from centerNode.
* This resets the {@link #nodes}, {@link #rootNodes} and {@link #endNodes}
*
* @param subGraph The SubGraph to find these nodes for.
* @param startNodes The Nodes to start searching from.
* @param excludedNodes The nodes that will not be added to this graph, even if they are found.
* @param radius The number of steps to search.
*/
private static void findNodes(SubGraph subGraph, Collection<DrawableNode> startNodes,
LinkedHashMap<Integer, DrawableNode> excludedNodes, int radius) {
subGraph.nodes = new LinkedHashMap<>();
subGraph.rootNodes = new LinkedHashMap<>();
subGraph.endNodes = new LinkedHashMap<>();
LinkedHashMap<Integer, DrawableNode> foundNodes = new LinkedHashMap<>();
Queue<FoundNode> queue = new LinkedList<>();
startNodes.forEach(node -> queue.add(new FoundNode(node, null)));
queue.add(null);
boolean lastRow = radius == 0;
while (!queue.isEmpty()) {
FoundNode current = queue.poll(); // Note: may still be null if the actual element is null!
if (current == null) {
radius
if (radius == 0) {
lastRow = true;
} else if (radius < 0) {
break;
}
queue.add(null);
continue;
}
DrawableNode previous;
if (excludedNodes.containsKey(current.node.getIdentifier())) {
if (startNodes.contains(current.node) && !foundNodes.containsKey(current.node.getIdentifier())) {
previous = null; // to signify it did not exist in subGraph.nodes yet.
} else {
continue; // This is an excluded node, just continue with next
}
} else {
// normal (non-excluded) node, save this node, save the result to check whether we had found it earlier.
previous = subGraph.nodes.put(current.node.getIdentifier(), current.node);
}
if (lastRow) {
// last row, add this node to rootNodes / endNodes even if we already found this node
// (for when a node is both a root and an end node)
if (current.foundFrom == FoundNode.FoundFrom.CHILD
&& (previous == null || subGraph.endNodes.containsKey(current.node.getIdentifier()))) {
subGraph.rootNodes.put(current.node.getIdentifier(), current.node);
} else if (current.foundFrom == FoundNode.FoundFrom.PARENT
&& (previous == null || subGraph.rootNodes.containsKey(current.node.getIdentifier()))) {
subGraph.endNodes.put(current.node.getIdentifier(), current.node);
}
// else: current.foundFrom == null, true for the centerNode.
// Note: since radius is always at least MIN_RADIUS, we could else instead of else if.
// But that would be premature optimization.
} else if (previous != null) {
// we already found this node, continue to next node.
assert (previous.equals(current.node));
} else {
Collection<Integer> children = current.node.getChildren();
Collection<Integer> parents = current.node.getParents();
children.forEach(node -> {
if (node >= 0 && !foundNodes.containsKey(node)) {
DrawableSegment child = new DrawableSegment(subGraph.graph, node, subGraph.zoomLevel);
foundNodes.put(node, child);
queue.add(new FoundNode(child, FoundNode.FoundFrom.PARENT));
}
});
parents.forEach(node -> {
if (node >= 0 && !foundNodes.containsKey(node)) {
DrawableSegment parent = new DrawableSegment(subGraph.graph, node, subGraph.zoomLevel);
foundNodes.put(node, parent);
queue.add(new FoundNode(parent, FoundNode.FoundFrom.CHILD));
}
});
}
}
}
/**
* Checks whether a dynamic load is necessary. This includes both loading new nodes
* into the datastructure as well as removing nodes from the datastructure.
*
* @param leftBorder The left border of the canvas.
* @param rightBorder The right border of the canvas.
*/
public void checkDynamicLoad(int leftBorder, double rightBorder) {
assert (leftBorder < rightBorder);
// Note: It checks if layers.size() < BORDER_BUFFER, if so: we definitely need to load.
// Otherwise, check that there is enough of a buffer outside the borders.
if (layers.size() <= BORDER_BUFFER || layers.get(BORDER_BUFFER).getX() > leftBorder) {
this.addFromRootNodes(SubGraph.DEFAULT_DYNAMIC_RADIUS);
}
if (layers.size() <= BORDER_BUFFER || layers.get(layers.size() - BORDER_BUFFER - 1).getX() < rightBorder) {
this.addFromEndNodes(SubGraph.DEFAULT_DYNAMIC_RADIUS);
}
int amountOfLayersLeft = 0;
int amountOfLayersRight = 0;
for (int i = 0; i < layers.size(); i++) {
if (layers.get(i).getX() < 0) {
amountOfLayersLeft++;
} else if (layers.get(i).getX() > rightBorder) {
amountOfLayersRight = layers.size() - i;
break;
}
}
if (amountOfLayersLeft > 3 * BORDER_BUFFER) {
removeLeftLayers(BORDER_BUFFER);
}
if (amountOfLayersRight > 3 * BORDER_BUFFER) {
removeRightLayers(BORDER_BUFFER);
}
}
/**
* Removes layers from the right of the graph.
*
* @param numberOfLayers The number of layers to remove from the graph.
*/
private void removeRightLayers(int numberOfLayers) {
for (Layer layer : this.layers.subList(this.layers.size() - numberOfLayers, this.layers.size())) {
layer.forEach(node -> this.nodes.remove(node.getIdentifier()));
}
this.layers = new ArrayList<>(this.layers.subList(0, this.layers.size() - numberOfLayers));
this.endNodes = new LinkedHashMap<>();
this.layers.get(this.layers.size() - 1).
forEach(node -> endNodes.put(node.getIdentifier(), node));
}
/**
* Removes layers from the left of the graph.
*
* @param numberOfLayers The number of layers to remove from the graph.
*/
private void removeLeftLayers(int numberOfLayers) {
for (Layer layer : this.layers.subList(0, numberOfLayers)) {
layer.forEach(node -> this.nodes.remove(node.getIdentifier()));
}
this.layers = new ArrayList<>(this.layers.subList(numberOfLayers, this.layers.size()));
this.rootNodes = new LinkedHashMap<>();
this.layers.get(0).
forEach(node -> rootNodes.put(node.getIdentifier(), node));
}
public void setZoomLevel(double zoomLevel) {
this.zoomLevel = zoomLevel;
}
/**
* On click method
* @param x location
* @param y location
* @return Drawable on which clicked. if nothing null.
*/
public Drawable onClick(double x, double y, GraphicsContext gc) {
Drawable clicked;
// System.out.println(x + " "+ y);
//TODO implement this with a tree instead of iterating.
for (DrawableNode drawableNode : this.getNodes().values()) {
if (x >= drawableNode.getLocation().getX() && y >= drawableNode.getLocation().getY()
&& x <= drawableNode.getLocation().getX() + drawableNode.getWidth()
&& y <= drawableNode.getLocation().getY() + drawableNode.getHeight()) {
return drawableNode;
}
}
return onClickEdge(x, y, gc);
}
/**
* check if clicked on an edge.
*
* @param x location
* @param y location
* @return DrawableEdge
*/
private DrawableEdge onClickEdge(double x, double y, GraphicsContext gc) {
//Find layers on the left and the right of the clicked location.
int foundLayerIndex = getLayerIndex(layers, x);
int leftLayerIndex;
if (layers.get(foundLayerIndex).getX() > x) {
leftLayerIndex = foundLayerIndex - 1;
} else {
leftLayerIndex = foundLayerIndex;
}
//get the corresponding layers.
Layer leftLayer = layers.get(leftLayerIndex);
for (DrawableNode left : leftLayer.getNodes()) {
for (DrawableNode right : this.getChildren(left)) {
if (calculateEdge(left, right, x, y, gc)) {
return new DrawableEdge(left, right);
}
}
}
return null;
}
/**
* Cacluclates the edges and see if the onclick is on line
* @param left node of the edge.
* @param right node of the edge.
* @param x location
* @param y location
* @return true if clicked on edge, false if not
*/
private boolean calculateEdge(DrawableNode left, DrawableNode right, double x, double y, GraphicsContext gc) {
//calculate edge start
double leftLayerEnd = left.getLayer().getX() + left.getLayer().getWidth();
XYCoordinate start = left.getRightBorderCenter();
start.setX(leftLayerEnd); //make the start the layer end since this is where the edge starts to move.
XYCoordinate end = right.getLeftBorderCenter();
// System.out.println("Start Location: " + start);
// System.out.println("End Location: " + end);
//calculate differences.
double differenceX = end.getX() - start.getX();
double differenceY = end.getY() - start.getY(); //Negative if line is going up, positive if line is going down.
//calculate a out of the ax+b formula;
double deltaY = differenceY / differenceX;
// System.out.println("DeltaY is: " + deltaY);
double startX = start.getX();
double startY = start.getY();
double edgeY = startY + (deltaY * (x - startX));
//TODO change these numbers to edgethickness * zoom or something to make it work when zoomed in and zoomed out a lot.
//TODO when this is fixed make it a simple return (calculation).
double genomeFraction = getGenomesEdge(left.getParentSegment(), right.getChildSegment()).size() / (double) this.getNumberOfGenomes();
double minStrokeWidth = 1.d, maxStrokeWidth = 6.5;
double strokeWidth = minStrokeWidth + genomeFraction * (maxStrokeWidth - minStrokeWidth);
double easyness = 1.0; //How easy you want it to be click.
gc.setStroke(Color.RED);
gc.setLineWidth(1 * zoomLevel);
gc.strokeLine(x - 1, edgeY - strokeWidth * easyness * zoomLevel, x + 1, edgeY - strokeWidth * easyness * zoomLevel);
gc.strokeLine(x - 1, edgeY + strokeWidth * easyness * zoomLevel, x + 1, edgeY + strokeWidth * easyness * zoomLevel);
if (edgeY - strokeWidth * zoomLevel < y && edgeY + strokeWidth * zoomLevel > y){
// System.out.println("TRUE EdgY = " + edgeY);
return true;
}
// System.out.println("FALSE EdgY = " + edgeY);
return false;
}
public Collection<Integer> getGenomesEdge(DrawableNode parent, DrawableNode child){
Map<DrawableNode, Collection<Integer>> from = this.getGenomes().get(parent);
if (from != null) {
Collection<Integer> genomes = from.get(child);
return genomes;
}
return null;
}
/**
* A class for keeping track of how a Node was found. Only used within {@link SubGraph#findNodes}.
*/
private static final class FoundNode {
/**
* Whether a node was found from a parent or a child.
*/
private enum FoundFrom {
PARENT, CHILD
}
private final DrawableNode node;
private final FoundFrom foundFrom;
/**
* simple constructor for a FoundNode.
*
* @param node The node that was found.
* @param foundFrom Whether it was found from a parent or a child.
*/
private FoundNode(DrawableNode node, FoundFrom foundFrom) {
this.node = node;
this.foundFrom = foundFrom;
}
}
/**
* Find out which {@link Drawable} is at the given location.
*
* @param loc The location to search for Drawables.
* @return The {@link Drawable} that is on top at the given location.
*/
public Drawable atLocation(XYCoordinate loc) {
return this.atLocation(loc.getX(), loc.getY());
}
/**
* Find out which {@link Drawable} is at the given location.
*
* @param x The x coordinate
* @param y The y coordinate
* @return The {@link Drawable} that is on top at the given location.
*/
private Drawable atLocation(double x, double y) {
int layerIndex = getLayerIndex(this.layers, x);
// TODO: implement;
// 1: check that x is actually within the layer.
// 2: check nodes in layer for y coordinate.
throw new Error("Not implemented yet");
}
/**
* Get the index of the {@link Layer} closest to an x coordinate.
* If two layers are equally close (x is exactly in the middle of end
* of left layer and start of the right layer), the right Layer is returned, as this
* one is likely to have nodes closer (nodes in the left layer do not necessarily extend to the end)
*
* @param x The coordinate
* @param layers The list of layers to look through.
* @return The index of the closest layer.
*/
@SuppressWarnings("UnnecessaryLocalVariable")
private int getLayerIndex(List<Layer> layers, double x) {
int resultIndex = Collections.binarySearch(layers, x);
if (resultIndex >= layers.size()) {
// x is right outside list, last layer is closest.
return layers.size() - 1;
} else if (resultIndex >= 0) {
// x is exactly at the start of a layer, that layer is closest.
return resultIndex;
} else {
// x < 0, -x is the closest layer on the right, -x - 1 is the closest
// layer on the left. (see binarySearch documentation)
// check which of the two layers is closest.
int insertionPoint = -(resultIndex + 1);
int rightLayerIndex = insertionPoint;
int leftLayerIndex = insertionPoint - 1;
Layer rightLayer = layers.get(rightLayerIndex);
Layer leftLayer = layers.get(leftLayerIndex);
if (rightLayer.getX() - x > x - (leftLayer.getX() + leftLayer.getWidth())) {
// distance from right layer is greater, so left layer is closer
return leftLayerIndex;
} else {
return rightLayerIndex;
}
}
}
/**
* Lay out the {@link Drawable Drawables} in this SubGraph.
*/
private void layout() {
createLayers();
int minimumLayerIndex = findMinimumNodesLayerIndex(this.layers);
sortLayersLeftFrom(minimumLayerIndex);
sortLayersRightFrom(minimumLayerIndex);
}
/**
* Assign nodes to {@link Layer layers} and create dummyNodes for edges that span multiple layers.
*/
private void createLayers() {
this.layers = findLayers();
createDummyNodes(layers);
}
/**
* Set the coordinates for all {@link Layer layers} to the right of the given Layer.
*
* @param layers The Layers to set the coordinates for.
* @param setLayerIndex The index of the Layer to start from (exclusive,
* so coordinates are not set for this layer).
*/
private void setRightDrawLocations(ArrayList<Layer> layers, int setLayerIndex) {
ListIterator<Layer> layerIterator = layers.listIterator(setLayerIndex);
Layer setLayer = layerIterator.next();
double x = setLayer.getX() + setLayer.getWidth();
double firstY = setLayer.getY();
int size = setLayer.size();
while (layerIterator.hasNext()) {
Layer layer = layerIterator.next();
layer.setSize(zoomLevel);
int newSize = layer.size();
int diff = Math.abs(newSize - size);
x += (LAYER_PADDING * zoomLevel) + (DIFF_LAYER_PADDING * zoomLevel) * diff;
layer.setX(x);
layer.setDrawLocations(firstY, zoomLevel);
x += layer.getWidth() + (LAYER_PADDING * zoomLevel) * 0.1 + newSize;
size = newSize;
}
}
/**
* Set the coordinates for all {@link Layer layers} to the left of the given Layer.
*
* @param layers The Layers to set the coordinates for.
* @param setLayerIndex The index of the Layer to start from (exclusive,
* so coordinates are not set for this layer).
*/
private void setLeftDrawLocations(ArrayList<Layer> layers, int setLayerIndex) {
ListIterator<Layer> layerIterator = layers.listIterator(setLayerIndex + 1);
Layer setLayer = layerIterator.previous();
double x = setLayer.getX();
double firstY = setLayer.getY();
int size = setLayer.size();
while (layerIterator.hasPrevious()) {
Layer layer = layerIterator.previous();
layer.setSize(zoomLevel);
int newSize = layer.size();
int diff = Math.abs(newSize - size);
x -= (LAYER_PADDING * zoomLevel) + diff * (DIFF_LAYER_PADDING * zoomLevel)
+ layer.getWidth();
layer.setX(x);
layer.setDrawLocations(firstY, zoomLevel);
x -= (LAYER_PADDING * zoomLevel) * 0.1 + newSize;
size = newSize;
}
}
/**
* Create {@link DrawableDummy} nodes for layers to avoid more crossing edges.
*
* @param layers {@link List} representing all layers to be drawn.
*/
private void createDummyNodes(List<Layer> layers) {
Layer current = new Layer();
for (Layer next : layers) {
for (DrawableNode node : current) {
for (DrawableNode child : this.getChildren(node)) {
if (!next.contains(child)) {
DrawableDummy dummy = new DrawableDummy(
DrawableNode.getUniqueId(), node, child, this.getGraph(), this);
node.replaceChild(child, dummy);
child.replaceParent(node, dummy);
dummy.setWidth(next.getWidth());
this.nodes.put(dummy.getIdentifier(), dummy);
dummy.setLayer(next);
next.add(dummy);
}
}
}
current = next;
}
}
/**
* Put all nodes in {@link Layer Layers}. This method is used when {@link #layout laying out} the graph.
* This will put each node in a Layer one higher than each of its parents.
*
* @return A {@link List} of Layers with all the nodes (all nodes are divided over the Layers).
*/
private ArrayList<Layer> findLayers() {
long startTime = System.nanoTime();
List<DrawableNode> sorted = topoSort();
long finishTime = System.nanoTime();
long differenceTime = finishTime - startTime;
long millisecondTime = differenceTime / 1000000;
Console.println("TIME OF TOPOSORT: " + millisecondTime);
Console.println("Amount of nodes: " + sorted.size());
Map<DrawableNode, Integer> nodeLevel = new LinkedHashMap<>();
ArrayList<Layer> layerList = new ArrayList<>();
for (DrawableNode node : sorted) {
int maxParentLevel = -1;
for (DrawableNode parent : this.getParents(node)) {
Integer parentLevel = nodeLevel.get(parent);
if (maxParentLevel < parentLevel) {
maxParentLevel = parentLevel;
}
}
maxParentLevel++; // we want this node one level higher than the highest parent.
nodeLevel.put(node, maxParentLevel);
if (layerList.size() <= maxParentLevel) {
layerList.add(new Layer());
}
node.setLayer(layerList.get(maxParentLevel));
layerList.get(maxParentLevel).add(node);
}
return layerList;
}
/**
* Get the parents of {@link DrawableNode} node.
*
* @param node The {@link DrawableNode} to get
* @return A {@link Collection} of {@link DrawableNode}
*/
public Collection<DrawableNode> getParents(DrawableNode node) {
Collection<DrawableNode> parents = new LinkedHashSet<>();
for (int parentID : node.getParents()) {
if (this.nodes.containsKey(parentID)) {
parents.add(this.nodes.get(parentID));
}
}
return parents;
}
/**
* Get the children of {@link DrawableNode} node.
*
* @param node The {@link DrawableNode} to get
* @return A {@link Collection} of {@link DrawableNode}
*/
public Collection<DrawableNode> getChildren(DrawableNode node) {
Collection<DrawableNode> children = new LinkedHashSet<>();
for (int childID : node.getChildren()) {
if (this.nodes.containsKey(childID)) {
children.add(this.nodes.get(childID));
}
}
return children;
}
/**
* Find the Layer with the least number of nodes.
*
* @param layers The {@link Layer Layers} to search through.
* @return The index of the Layer with the minimum number of nodes, or -1 if the list of layers is empty.
*/
private int findMinimumNodesLayerIndex(List<Layer> layers) {
// find a layer with a single node
int index = -1;
int min = Integer.MAX_VALUE;
Iterator<Layer> layerIterator = layers.iterator();
for (int i = 0; layerIterator.hasNext(); i++) {
Layer currentLayer = layerIterator.next();
int currentSize = currentLayer.size();
if (currentSize < min) {
min = currentSize;
index = i;
if (currentSize <= 1) {
// There should be no layers with less than 1 node,
// so this layer has the least amount of nodes.
break;
}
}
}
return index;
}
/**
* Sort all {@link Layer Layers} right from a given layer.
*
* @param layerIndex The index of the layer to start sorting from (exclusive, so that layer is not sorted).
*/
private void sortLayersRightFrom(int layerIndex) {
ListIterator<Layer> iterator = layers.listIterator(layerIndex);
Layer prev = iterator.next();
while (iterator.hasNext()) {
Layer layer = iterator.next();
layer.sort(this, prev, true);
prev = layer;
}
}
/**
* Sort all {@link Layer Layers} left from a given layer.
*
* @param layerIndex The index of the layer to start sorting from (exclusive, so that layer is not sorted).
*/
private void sortLayersLeftFrom(int layerIndex) {
ListIterator<Layer> iterator = layers.listIterator(layerIndex + 1);
Layer prev = iterator.previous();
while (iterator.hasPrevious()) {
Layer layer = iterator.previous();
layer.sort(this, prev, false);
prev = layer;
}
}
/**
* Topologically sort the nodes from this graph.
*
* Assumption: graph is a DAG.
* @return a topologically sorted list of nodes
*/
public List<DrawableNode> topoSort() {
// topo sorted list
ArrayList<DrawableNode> res = new ArrayList<>(this.nodes.size());
// nodes that have not yet been added to the list.
LinkedHashSet<DrawableNode> found = new LinkedHashSet<>();
// tactic:
// take any node. see if any parents were not added yet.
// If so, clearly that parent needs to be added first. Continue searching from parent.
// If not, we found a node that can be next in the ordering. Add it to the list.
// Repeat until all nodes are added to the list.
for (DrawableNode n : this.nodes.values()) {
if (!found.add(n)) {
continue;
}
topoSortFromNode(res, found, n);
}
assert (res.size() == this.nodes.size());
return res;
}
/**
* Toposort all ancestors of a node.
*
* @param result The result list to which these nodes will be added,
* @param found The nodes that have already been found,
* @param node The node to start searching from.
*/
private void topoSortFromNode(ArrayList<DrawableNode> result,
LinkedHashSet<DrawableNode> found, DrawableNode node) {
for (int parentID : node.getParents()) {
DrawableNode drawableParent = this.nodes.get(parentID);
if (drawableParent != null && found.add(drawableParent)) {
topoSortFromNode(result, found, drawableParent);
}
}
result.add(node);
}
/**
* Calculate genomes through all outgoing edges of a parent.
*
* @param parent find all genomes through edges from this parent
* @return a {@link Map} of collections of genomes through links
*/
private Map<DrawableNode, Collection<Integer>> calculateGenomes(DrawableNode parent) {
Map<DrawableNode, Collection<Integer>> outgoingGenomes = new LinkedHashMap<>();
// Create set of parent genomes
Set<Integer> parentGenomes = new LinkedHashSet<>(parent.getParentGenomes());
// Topo sort (= natural order) children
Collection<DrawableNode> children = this.getChildren(parent);
// For every child (in order); do
children.stream()
.map(DrawableNode::getChildSegment)
.sorted(Comparator.comparingInt(DrawableNode::getIdentifier))
.forEach(child -> {
Set<Integer> childGenomes = new LinkedHashSet<>(child.getGenomes());
// Find mutual genomes between parent and child
Set<Integer> mutualGenomes = Sets.intersect(parentGenomes, childGenomes);
// Add mutual genomes to edge
outgoingGenomes.put(child, mutualGenomes);
// Subtract mutual genomes from parent set
parentGenomes.removeAll(mutualGenomes);
});
return outgoingGenomes;
}
/**
* Calculate genomes through edge, based on topological ordering and node-genome information.
*
* @return a {@link Map} of {@link Map Maps} of collections of genomes through links
*/
public Map<DrawableNode, Map<DrawableNode, Collection<Integer>>> calculateGenomes() {
// For every node in the subGraph
this.nodes.values().stream().map(DrawableNode::getParentSegment).forEach(parent -> {
Map<DrawableNode, Collection<Integer>> parentGenomes = this.calculateGenomes(parent);
this.genomes.put(parent, parentGenomes);
});
return this.genomes;
}
/**
* Add nodes from the {@link #rootNodes}.
*
* @param radius The number of steps to take from the rootNodes before stopping the search.
*/
private void addFromRootNodes(int radius) {
if (this.rootNodes.isEmpty()) {
return;
}
Console.println("Increasing graph with radius %d", radius);
SubGraph subGraph = new SubGraph(graph, zoomLevel, replaceSNPs);
this.rootNodes.forEach((id, node) -> this.endNodes.remove(id));
findNodes(subGraph, rootNodes.values(), this.nodes, radius);
subGraph.replaceSNPs();
subGraph.createLayers();
subGraph.calculateGenomes();
this.mergeLeftSubGraphIntoThisSubGraph(subGraph);
}
/**
* Add nodes from the {@link #endNodes}.
*
* @param radius The number of steps to take from the endNodes before stopping the search.
*/
private void addFromEndNodes(int radius) {
if (this.endNodes.isEmpty()) {
return;
}
Console.println("Increasing graph with radius %d", radius);
SubGraph subGraph = new SubGraph(graph, zoomLevel, replaceSNPs);
this.endNodes.forEach((id, node) -> System.out.print(id + " "));
System.out.println();
this.endNodes.forEach((id, node) -> this.rootNodes.remove(id));
findNodes(subGraph, endNodes.values(), this.nodes, radius);
subGraph.replaceSNPs();
subGraph.createLayers();
subGraph.calculateGenomes();
this.mergeRightSubGraphIntoThisSubGraph(subGraph);
}
/**
* Method to merge subGraphs with each other.
*
* @param rightSubGraph SubGraph to be merged into from the right.
*/
private void mergeRightSubGraphIntoThisSubGraph(SubGraph rightSubGraph) {
this.nodes.putAll(rightSubGraph.nodes);
this.endNodes = rightSubGraph.endNodes;
rightSubGraph.rootNodes.forEach((id, node) -> {
boolean addToEndNodes = false;
for (Integer parentId : node.getParents()) {
if (this.nodes.containsKey(parentId)) {
addToEndNodes = true;
break;
}
}
if (!addToEndNodes) {
for (Integer childId : node.getChildren()) {
if (this.nodes.containsKey(childId)) {
addToEndNodes = true;
break;
}
}
}
if (addToEndNodes) {
this.endNodes.put(id, node);
}
});
int oldLastIndex = this.layers.size() - 1;
this.layers.addAll(rightSubGraph.layers);
// TODO: find DummyNodes between subgraphs. Just use findDummyNodes on full graph?
rightSubGraph.genomes.forEach((parent, childMap) -> this.genomes
.computeIfAbsent(parent, parentId -> new LinkedHashMap<>())
.putAll(childMap));
rightSubGraph.colorize();
this.sortLayersRightFrom(oldLastIndex);
this.setRightDrawLocations(this.layers, oldLastIndex);
}
/**
* Merge another {@link SubGraph} into this SubGraph, by putting it on the left of this SubGraph,
* and then drawing connecting edges between nodes that should have them.
*
* @param leftSubGraph The other SubGraph that will be merged into this one.
*/
private void mergeLeftSubGraphIntoThisSubGraph(SubGraph leftSubGraph) {
this.nodes.putAll(leftSubGraph.nodes);
this.rootNodes = leftSubGraph.rootNodes;
leftSubGraph.endNodes.forEach((id, node) -> {
boolean addToRootNodes = false;
for (Integer childId : node.getChildren()) {
if (this.nodes.containsKey(childId)) {
addToRootNodes = true;
break;
}
}
if (!addToRootNodes) {
for (Integer parentId : node.getParents()) {
if (this.nodes.containsKey(parentId)) {
addToRootNodes = true;
break;
}
}
}
if (addToRootNodes) {
this.rootNodes.put(id, node);
}
});
int oldFirstIndex = leftSubGraph.layers.size();
this.layers.addAll(0, leftSubGraph.layers);
// TODO: find DummyNodes between subgraphs. Just use findDummyNodes on full graph?
leftSubGraph.genomes.forEach((parent, childMap) -> this.genomes
.computeIfAbsent(parent, parentId -> new LinkedHashMap<>())
.putAll(childMap));
leftSubGraph.colorize();
this.sortLayersLeftFrom(oldFirstIndex);
this.setLeftDrawLocations(this.layers, oldFirstIndex);
}
public LinkedHashMap<Integer, DrawableNode> getNodes() {
return this.nodes;
}
public GenomeGraph getGraph() {
return graph;
}
/**
* Method to translate the graph.
*
* @param xDifference difference in X direction.
* @param yDifference difference in Y direction.
*/
public void translate(double xDifference, double yDifference) {
for (Layer layer : this.layers) {
layer.setX(layer.getX() + xDifference);
for (DrawableNode node : layer) {
double oldX = node.getLocation().getX();
double oldY = node.getLocation().getY();
node.setLocation(oldX + xDifference, oldY + yDifference);
}
}
}
/**
* Method to set the zoom amount.
*
* @param scale double of the amount to zoom.
*/
public void zoom(double scale) {
zoomLevel /= scale;
for (Layer layer : this.layers) {
layer.setX(layer.getX() / scale);
for (DrawableNode node : layer) {
double oldXLocation = node.getLocation().getX();
double oldYLocation = node.getLocation().getY();
node.setHeight(node.getHeight() / scale);
node.setWidth(node.getWidth() / scale);
node.setStrokeWidth(node.getStrokeWidth() / scale);
node.setLocation(oldXLocation / scale, oldYLocation / scale);
}
}
}
/**
* Method to give color to the nodes.
*/
public void colorize() {
for (DrawableNode drawableNode : this.nodes.values()) {
drawableNode.colorize(this);
}
}
public Map<DrawableNode, Map<DrawableNode, Collection<Integer>>> getGenomes() {
return genomes;
}
public int getNumberOfGenomes() {
return numberOfGenomes;
}
public double getZoomLevel() {
return zoomLevel;
}
}
|
package project.drawwordchain.controller;
import java.io.IOException;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.ArrayList;
import java.util.List;
import java.util.Iterator;
import javax.websocket.OnOpen;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import project.drawwordchain.model.WebSocketUser;
@ServerEndpoint("/project/drawwordchain/startbroadcast")
public class StartWebSocket {
private static final Queue<Session> sessions = new ConcurrentLinkedQueue<>();
private static final List<WebSocketUser> userList = new ArrayList<WebSocketUser>();
@OnOpen
public void connect(Session session) {
System.out.println("open : " + session.getId());
sessions.add(session);
}
@OnClose
public void onClose(Session session) {
System.out.println("close : " + session.getId());
//IDname
for (int i = 0; i < userList.size(); i++) {
if( userList.get(i).getSessionId() == session.getId() ) {
userList.remove(i);
}
}
// sessions.clear();
// userList.clear();
sessions.remove(session);
userNameBroadcast();
}
@OnMessage
public void echoUserName(String userName, Session session) {
System.out.println("");
WebSocketUser wUser = new WebSocketUser();
wUser.setName(userName);
wUser.setSessionId(session.getId());
userList.add(wUser);
System.out.println(": "+userList.size());
userNameBroadcast();
}
public void userNameBroadcast() {
System.out.println("");
String userNameColumn = "";
Iterator<WebSocketUser> iterator = userList.iterator();
while(iterator.hasNext()){
userNameColumn += iterator.next().getName();
if(iterator.hasNext()) {
userNameColumn += ",";
}
}
System.out.println(":" + userNameColumn);
for ( Session s : sessions ) {
s.getAsyncRemote().sendText(userNameColumn);
}
}
}
|
package com.abusalimov.mrcalc.ui;
import com.abusalimov.mrcalc.CalcExecutor;
import com.abusalimov.mrcalc.diagnostic.Diagnostic;
import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.BadLocationException;
import javax.swing.text.DefaultHighlighter;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.util.Collections;
import java.util.List;
import java.util.function.Consumer;
/**
* @author - Eldar Abusalimov
*/
public class CodeTextPane extends JTextPane {
private static int squiggleSize = 2;
private static int squigglesAtEof = 2;
private final JTextArea outputTextArea;
private Consumer<List<Diagnostic>> errorListener;
private List<Diagnostic> diagnostics = Collections.emptyList();
public CodeTextPane(CalcExecutor calcExecutor, JTextArea outputTextArea) {
this.outputTextArea = outputTextArea;
getStyledDocument().addDocumentListener(new HighlightListener(calcExecutor));
ToolTipManager.sharedInstance().registerComponent(this);
}
@Override
public String getToolTipText(MouseEvent event) {
int offset = viewToModel(event.getPoint());
for (Diagnostic diagnostic : diagnostics) {
int startOffset = diagnostic.getLocation().getStartOffset();
int endOffset = diagnostic.getLocation().getEndOffset();
try {
if ((startOffset == endOffset || !onSameLine(startOffset, endOffset)) &&
offset == startOffset &&
modelToView(offset).x + squigglesAtEof * squiggleSize > event.getPoint().x)
return diagnostic.getMessage();
if (offset >= startOffset && offset < endOffset)
return diagnostic.getMessage();
} catch (BadLocationException e) {
e.printStackTrace();
}
}
return super.getToolTipText(event);
}
public void setErrorListener(Consumer<List<Diagnostic>> errorListener) {
this.errorListener = errorListener;
}
private void fireErrorListener(List<Diagnostic> diagnostics) {
if (errorListener != null)
errorListener.accept(diagnostics);
}
private boolean onSameLine(int startOffset, int endOffset) {
try {
return getDocument().getText(startOffset, endOffset - startOffset).indexOf('\n') == -1;
} catch (BadLocationException e) {
e.printStackTrace();
return false;
}
}
private class HighlightListener implements DocumentListener {
private final SquigglePainter squigglePainter = new SquigglePainter(Color.RED, squiggleSize);
private final DefaultHighlighter.DefaultHighlightPainter defaultPainter =
new DefaultHighlighter.DefaultHighlightPainter(new Color(255, 0, 0, 16));
private final SquigglePainter eofPainter = new SquigglePainter(Color.RED, squiggleSize) {
@Override
protected void paintSquiggles(Graphics g, Rectangle r) {
super.paintSquiggles(g, new Rectangle(r.x + r.width, r.y, squigglesAtEof *squiggle, r.height));
}
};
private final CalcExecutor calcExecutor;
public HighlightListener(CalcExecutor calcExecutor) {
this.calcExecutor = calcExecutor;
calcExecutor.setCallback(diagnostics -> SwingUtilities.invokeLater(() -> highlight(diagnostics)));
}
@Override
public void insertUpdate(DocumentEvent e) {
handleEvent();
}
@Override
public void removeUpdate(DocumentEvent e) {
handleEvent();
}
@Override
public void changedUpdate(DocumentEvent e) {
/* do nothing */
}
private void handleEvent() {
clearHighlight();
outputTextArea.setText("");
try {
String sourceCodeText = getDocument().getText(0, getDocument().getLength());
calcExecutor.execute(sourceCodeText, new TextAreaStream(outputTextArea));
} catch (BadLocationException e) {
e.printStackTrace();
}
}
private void clearHighlight() {
diagnostics = Collections.emptyList();
getHighlighter().removeAllHighlights();
fireErrorListener(diagnostics);
}
private void highlight(List<Diagnostic> diagnostics) {
if (!EventQueue.isDispatchThread())
throw new IllegalThreadStateException();
fireErrorListener(diagnostics);
diagnostics.forEach(this::highlight);
repaint();
}
private void highlight(Diagnostic diagnostic) {
int startOffset = diagnostic.getLocation().getStartOffset();
int endOffset = diagnostic.getLocation().getEndOffset();
try {
if (startOffset == endOffset) {
getHighlighter().addHighlight(startOffset, endOffset + 1, eofPainter);
} else if (!onSameLine(startOffset, endOffset)) {
getHighlighter().addHighlight(startOffset, endOffset, eofPainter);
} else {
getHighlighter().addHighlight(startOffset, endOffset, defaultPainter);
getHighlighter().addHighlight(startOffset, endOffset, squigglePainter);
}
} catch (BadLocationException e) {
e.printStackTrace();
}
}
}
}
|
package cgeo.geocaching.geopoint;
import java.util.Locale;
/**
* Formatting of Geopoint.
*/
public class GeopointFormatter
{
/**
* Predefined formats.
*/
public static enum Format {
/** Example: "10,123456 -0,123456" */
LAT_LON_DECDEGREE,
/** Example: "10.123456,-0.123456" (unlocalized) */
LAT_LON_DECDEGREE_COMMA,
LAT_LON_DECMINUTE,
LAT_LON_DECSECOND,
/** Example: "-0.123456" (unlocalized latitude) */
LAT_DECDEGREE_RAW,
LAT_DECMINUTE,
/** Example: "N 10 12,345" */
LAT_DECMINUTE_RAW,
/** Example: "-0.123456" (unlocalized longitude) */
LON_DECDEGREE_RAW,
LON_DECMINUTE,
/** Example: "W 5 12,345" */
LON_DECMINUTE_RAW;
}
/**
* Formats a Geopoint.
*
* @param gp
* the Geopoint to format
* @param format
* one of the predefined formats
* @return the formatted coordinates
*/
public static String format(final Format format, final Geopoint gp)
{
final double latSigned = gp.getLatitude();
final double lonSigned = gp.getLongitude();
final double lat = Math.abs(latSigned);
final double lon = Math.abs(lonSigned);
final double latFloor = Math.floor(lat);
final double lonFloor = Math.floor(lon);
final double latMin = (lat - latFloor) * 60;
final double lonMin = (lon - lonFloor) * 60;
final double latMinFloor = Math.floor(latMin);
final double lonMinFloor = Math.floor(lonMin);
final double latSec = (latMin - latMinFloor) * 60;
final double lonSec = (lonMin - lonMinFloor) * 60;
final char latDir = latSigned < 0 ? 'S' : 'N';
final char lonDir = lonSigned < 0 ? 'W' : 'E';
switch (format) {
case LAT_LON_DECDEGREE:
return String.format("%.6f %.6f", latSigned, lonSigned);
case LAT_LON_DECDEGREE_COMMA:
return String.format((Locale) null, "%.6f,%.6f", latSigned, lonSigned);
case LAT_LON_DECMINUTE:
return String.format("%c %02.0f° %06.3f %c %03.0f° %06.3f",
latDir, latFloor, latMin, lonDir, lonFloor, lonMin);
case LAT_LON_DECSECOND:
return String.format("%c %02.0f° %02.0f' %06.3f\" %c %03.0f° %02.0f' %06.3f\"",
latDir, latFloor, latMinFloor, latSec, lonDir, lonFloor, lonMinFloor, lonSec);
case LAT_DECDEGREE_RAW:
return String.format((Locale) null, "%.6f", latSigned);
case LAT_DECMINUTE:
return String.format("%c %02.0f° %06.3f", latDir, latFloor, latMin);
case LAT_DECMINUTE_RAW:
return String.format("%c %02.0f %06.3f", latDir, latFloor, latMin);
case LON_DECDEGREE_RAW:
return String.format((Locale) null, "%.6f", lonSigned);
case LON_DECMINUTE:
return String.format("%c %03.0f° %06.3f", lonDir, lonFloor, lonMin);
case LON_DECMINUTE_RAW:
return String.format("%c %03.0f %06.3f", lonDir, lonFloor, lonMin);
}
// Keep the compiler happy even though it cannot happen
return null;
}
}
|
package org.oskari.service.wfs.client;
import java.util.concurrent.TimeUnit;
import org.geotools.data.simple.SimpleFeatureCollection;
import org.geotools.geometry.jts.ReferencedEnvelope;
import org.opengis.filter.Filter;
import org.opengis.referencing.crs.CoordinateReferenceSystem;
import com.vividsolutions.jts.geom.Envelope;
import fi.nls.oskari.cache.CacheManager;
import fi.nls.oskari.cache.ComputeOnceCache;
public class CachingWFSClient {
private static final String CACHE_NAME = CachingWFSClient.class.getName();
// one user on z 7 will trigger about ~100 requests to the service since tiles are always loaded as z 8
// so this is enough for 100 users looking at different layers/areas without cache overflowing
// or 20 users looking at 5 wfs layers each on z 7
// consider using Redis for caching (how much does serialization/deserialization to GeoJSON add?)
private static final int CACHE_SIZE_LIMIT = 10000;
private static final long CACHE_EXPIRATION = TimeUnit.MINUTES.toMillis(5L);
private final ComputeOnceCache<SimpleFeatureCollection> cache;
public CachingWFSClient() {
cache = CacheManager.getCache(CACHE_NAME,
() -> new ComputeOnceCache<>(CACHE_SIZE_LIMIT, CACHE_EXPIRATION));
}
public SimpleFeatureCollection tryGetFeatures(String endPoint, String version,
String user, String pass, String typeName,
ReferencedEnvelope bbox, CoordinateReferenceSystem crs,
Integer maxFeatures, Filter filter) {
if (filter != null) {
// Don't cache requests with a Filter
return OskariWFSClient.tryGetFeatures(
endPoint, version,
user, pass, typeName,
bbox, crs, maxFeatures, filter);
}
String key = getCacheKey(endPoint, typeName, bbox, crs, maxFeatures);
return cache.get(key, __ -> OskariWFSClient.tryGetFeatures(
endPoint, version,
user, pass, typeName,
bbox, crs, maxFeatures, filter));
}
private String getCacheKey(String endPoint, String typeName, Envelope bbox,
CoordinateReferenceSystem crs, Integer maxFeatures) {
String bboxStr = bbox != null ? bbox.toString() : "null";
String maxFeaturesStr = maxFeatures != null ? maxFeatures.toString() : "null";
return String.join(",", endPoint, typeName, bboxStr,
crs.getIdentifiers().iterator().next().toString(), maxFeaturesStr);
}
}
|
package com.kerb4j.client;
import com.kerb4j.common.jaas.sun.Krb5LoginContext;
import com.kerb4j.common.util.JreVendor;
import com.kerb4j.common.util.LRUCache;
import com.kerb4j.common.util.SpnegoProvider;
import org.ietf.jgss.GSSContext;
import org.ietf.jgss.GSSCredential;
import org.ietf.jgss.GSSException;
import org.ietf.jgss.GSSName;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.security.auth.Subject;
import javax.security.auth.kerberos.KerberosKey;
import javax.security.auth.kerberos.KerberosPrincipal;
import javax.security.auth.kerberos.KerberosTicket;
import javax.security.auth.kerberos.KeyTab;
import javax.security.auth.login.LoginContext;
import javax.security.auth.login.LoginException;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;
import java.util.AbstractMap;
import java.util.ArrayList;
import java.util.Date;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public final class SpnegoClient {
private static final Logger LOGGER = LoggerFactory.getLogger(SpnegoClient.class);
private final AtomicReference<SubjectTgtPair> subjectTgtPairReference = new AtomicReference<>();
private final Callable<Subject> subjectSupplier;
private final Lock authenticateLock = new ReentrantLock();
private final static LRUCache<AbstractMap.SimpleEntry<String,String>, SpnegoClient> SPNEGO_CLIENT_CACHE = new LRUCache<>(1024);
public static void resetCache() {
synchronized (SPNEGO_CLIENT_CACHE) {
SPNEGO_CLIENT_CACHE.clear();
}
}
/**
* Creates an instance with provided LoginContext
*
* @param loginContextSupplier loginContextSupplier
*/
protected SpnegoClient(final Callable<LoginContext> loginContextSupplier) {
subjectSupplier = new Callable<Subject>() {
@Override
public Subject call() throws Exception {
LoginContext loginContext = loginContextSupplier.call();
Subject subject = loginContext.getSubject();
if (null == subject) try {
loginContext.login();
subject = loginContext.getSubject();
} catch (LoginException e) {
LOGGER.error(e.getMessage(), e);
throw new RuntimeException(e);
}
return subject;
}
};
}
public Subject getSubject() {
SubjectTgtPair subjectTgtPair = subjectTgtPairReference.get();
if (null == subjectTgtPair || subjectTgtPair.isExpired()) {
authenticateLock.lock();
try {
subjectTgtPair = subjectTgtPairReference.get();
if (null == subjectTgtPair || subjectTgtPair.isExpired()) {
Subject subject = subjectSupplier.call();
for (KerberosTicket ticket : subject.getPrivateCredentials(KerberosTicket.class)) {
if (ticket.getServer().getName().startsWith("krbtgt")) {
subjectTgtPairReference.set(new SubjectTgtPair(ticket, subject));
break;
}
}
subjectTgtPair = subjectTgtPairReference.get();
}
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
authenticateLock.unlock();
}
}
return subjectTgtPair.subject;
}
public KerberosKey[] getKerberosKeys() {
Set<KerberosKey> kerberosKeys = getSubject().getPrivateCredentials(KerberosKey.class);
if (!kerberosKeys.isEmpty()) {
return new ArrayList<>(kerberosKeys).toArray(new KerberosKey[kerberosKeys.size()]);
} else {
Set<KerberosPrincipal> kerberosPrincipals = getSubject().getPrincipals(KerberosPrincipal.class);
for (KerberosPrincipal kerberosPrincipal : kerberosPrincipals) {
Set<KeyTab> keyTabs = getSubject().getPrivateCredentials(KeyTab.class);
for (KeyTab keyTab : keyTabs) {
KerberosKey[] keys = keyTab.getKeys(kerberosPrincipal);
if (null != keys && keys.length > 0) return keys;
}
}
}
return null;
}
private static class SubjectTgtPair {
private final KerberosTicket tgt;
private final Subject subject;
private SubjectTgtPair(KerberosTicket tgt, Subject subject) {
this.tgt = tgt;
this.subject = subject;
}
private boolean isExpired() {
return tgt.getEndTime().before(new Date());
}
}
// TODO: add factory methods with implicit principal name
/**
* Creates an instance where authentication is done using username and password
*
* @param username username
* @param password password
*/
public static SpnegoClient loginWithUsernamePassword(final String username, final String password) {
return loginWithUsernamePassword(username, password, false);
}
/**
* Creates an instance where authentication is done using username and password
*
* @param username username
* @param password password
* @throws LoginException LoginException
*/
public static SpnegoClient loginWithUsernamePassword(final String username, final String password, final boolean useCache) {
if (!useCache) return loginWithUsernamePasswordImpl(username, password);
AbstractMap.SimpleEntry<String, String> entry = new AbstractMap.SimpleEntry<>(username, password);
SpnegoClient spnegoClient;
synchronized (SPNEGO_CLIENT_CACHE) {
spnegoClient = SPNEGO_CLIENT_CACHE.get(entry);
if (null == spnegoClient) {
spnegoClient = loginWithUsernamePasswordImpl(username, password);
SPNEGO_CLIENT_CACHE.put(entry, spnegoClient);
}
}
return spnegoClient;
}
private static SpnegoClient loginWithUsernamePasswordImpl(final String username, final String password) {
return new SpnegoClient(new Callable<LoginContext>() {
@Override
public LoginContext call() throws Exception {
return Krb5LoginContext.loginWithUsernameAndPassword(username, password);
}
});
}
/**
* Creates an instance where authentication is done using keytab file
*
* @param principal principal
* @param keyTabLocation keyTabLocation
*/
public static SpnegoClient loginWithKeyTab(final String principal, final String keyTabLocation) {
return new SpnegoClient(new Callable<LoginContext>() {
@Override
public LoginContext call() throws Exception {
return Krb5LoginContext.loginWithKeyTab(principal, keyTabLocation);
}
});
}
/**
* Creates an instance where authentication is done using ticket cache
*
* @param principal principal
*/
public static SpnegoClient loginWithTicketCache(final String principal) {
return new SpnegoClient(new Callable<LoginContext>() {
@Override
public LoginContext call() throws Exception {
return Krb5LoginContext.loginWithTicketCache(principal);
}
});
}
public SpnegoContext createContext(URL url) throws PrivilegedActionException, GSSException {
return new SpnegoContext(this, getGSSContext(url));
}
public SpnegoContext createContextForSPN(String spn) throws PrivilegedActionException, GSSException, MalformedURLException {
return new SpnegoContext(this, getGSSContextForSPN(spn));
}
public String createAuthroizationHeader(URL url) throws PrivilegedActionException, GSSException, IOException {
SpnegoContext context = createContext(url);
try {
return context.createTokenAsAuthroizationHeader();
} finally {
context.close();
}
}
public String createAuthroizationHeaderForSPN(String spn) throws PrivilegedActionException, GSSException, IOException {
SpnegoContext contextForSPN = createContextForSPN(spn);
try {
return contextForSPN.createTokenAsAuthroizationHeader();
} finally {
contextForSPN.close();
}
}
public SpnegoContext createAcceptContext() throws PrivilegedActionException {
return new SpnegoContext(this, Subject.doAs(getSubject(), new PrivilegedExceptionAction<GSSContext>() {
@Override
public GSSContext run() throws Exception {
// IBM JDK only understands indefinite lifetime
final int credentialLifetime;
if (JreVendor.IS_IBM_JVM) {
credentialLifetime = GSSCredential.INDEFINITE_LIFETIME;
} else {
credentialLifetime = GSSCredential.DEFAULT_LIFETIME;
}
GSSCredential credential = SpnegoProvider.GSS_MANAGER.createCredential(
null
, credentialLifetime
, SpnegoProvider.SUPPORTED_OIDS
, GSSCredential.ACCEPT_ONLY); // TODO should it be INIT and ACCEPT ?
return SpnegoProvider.GSS_MANAGER.createContext(credential);
}
}));
}
/**
* Returns a GSSContext for the given SPN with a default lifetime.
*
* @param spn
* @return GSSContext for the given url
*/
private GSSContext getGSSContextForSPN(String spn) throws GSSException, PrivilegedActionException {
return getGSSContext(SpnegoProvider.createGSSNameForSPN(spn));
}
/**
* Returns a GSSContext for the given url with a default lifetime.
*
* @param url http address
* @return GSSContext for the given url
*/
private GSSContext getGSSContext(URL url) throws GSSException, PrivilegedActionException {
return getGSSContext(SpnegoProvider.getServerName(url));
}
private GSSContext getGSSContext(final GSSName gssName) throws GSSException, PrivilegedActionException {
// TODO: is it still a thing?
// work-around to GSSContext/AD timestamp vs sequence field replay bug
try { Thread.sleep(31); } catch (InterruptedException e) { assert true; }
return Subject.doAs(getSubject(), new PrivilegedExceptionAction<GSSContext>() {
@Override
public GSSContext run() throws Exception {
GSSCredential credential = SpnegoProvider.GSS_MANAGER.createCredential(
null
, GSSCredential.DEFAULT_LIFETIME
, SpnegoProvider.SUPPORTED_OIDS
, GSSCredential.INITIATE_ONLY);
GSSContext context = SpnegoProvider.GSS_MANAGER.createContext(gssName
, SpnegoProvider.SPNEGO_OID
, credential
, GSSContext.DEFAULT_LIFETIME);
context.requestMutualAuth(true);
context.requestConf(true);
context.requestInteg(true);
context.requestReplayDet(true);
context.requestSequenceDet(true);
return context;
}
});
}
}
|
package com.bio4j.model.uniprot.nodes;
import com.bio4j.model.uniprot.UniprotGraph;
import com.bio4j.model.uniprot.relationships.ProteinKeyword;
import com.ohnosequences.typedGraphs.Node;
import com.ohnosequences.typedGraphs.Property;
import java.util.List;
public interface Keyword <
N extends Keyword<N, NT>,
NT extends UniprotGraph.KeywordType<N, NT>
>
extends Node<N, NT> {
public String name();
public String id();
// properties
public static interface name<
N extends Keyword<N, NT>,
NT extends UniprotGraph.KeywordType<N, NT>,
P extends name<N, NT, P>
>
extends Property<N, NT, P, String> {
@Override
public default String name() {
return "name";
}
@Override
public default Class<String> valueClass() {
return String.class;
}
}
public static interface id<
N extends Keyword<N, NT>,
NT extends UniprotGraph.KeywordType<N, NT>,
P extends id<N, NT, P>
>
extends Property<N, NT, P, String> {
@Override
public default String name() {
return "id";
}
@Override
public default Class<String> valueClass() {
return String.class;
}
}
// relationships
// proteinKeyword
// outgoing
public List<? extends ProteinKeyword> proteinKeyword_out();
public List<? extends Keyword> proteinKeyword_outNodes();
}
|
package org.kie.scanner;
import org.drools.core.common.ProjectClassLoader;
import org.drools.core.util.ClassUtils;
import org.drools.compiler.kproject.ReleaseIdImpl;
import org.drools.compiler.kproject.models.KieModuleModelImpl;
import org.drools.core.rule.TypeMetaInfo;
import org.kie.api.builder.ReleaseId;
import org.drools.compiler.kie.builder.impl.InternalKieModule;
import org.kie.internal.utils.CompositeClassLoader;
import org.sonatype.aether.artifact.Artifact;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.Collection;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import static org.drools.core.util.ClassUtils.convertResourceToClassName;
import static org.drools.core.util.IoUtils.readBytesFromZipEntry;
import static org.drools.core.rule.TypeMetaInfo.DEFAULT_TYPE_META_INFO;
import static org.drools.core.rule.TypeMetaInfo.unmarshallMetaInfos;
import static org.kie.scanner.ArtifactResolver.getResolverFor;
public class KieModuleMetaDataImpl implements KieModuleMetaData {
private final ArtifactResolver artifactResolver;
private final Map<String, Collection<String>> classes = new HashMap<String, Collection<String>>();
private final Map<String, String> processes = new HashMap<String, String>();
private final Map<URI, File> jars = new HashMap<URI, File>();
private final Map<String, TypeMetaInfo> typeMetaInfos = new HashMap<String, TypeMetaInfo>();
private ProjectClassLoader classLoader;
private ReleaseId releaseId;
private InternalKieModule kieModule;
public KieModuleMetaDataImpl(ReleaseId releaseId) {
this.artifactResolver = getResolverFor(releaseId, false);
this.releaseId = releaseId;
init();
}
public KieModuleMetaDataImpl(File pomFile) {
this.artifactResolver = getResolverFor(pomFile);
init();
}
public KieModuleMetaDataImpl(InternalKieModule kieModule) {
String pomXmlPath = ((ReleaseIdImpl)kieModule.getReleaseId()).getPomXmlPath();
InputStream pomStream = new ByteArrayInputStream(kieModule.getBytes(pomXmlPath));
this.artifactResolver = getResolverFor(pomStream);
this.kieModule = kieModule;
for (String file : kieModule.getFileNames()) {
if (!indexClass(file)) {
if (file.endsWith(KieModuleModelImpl.KMODULE_INFO_JAR_PATH)) {
indexMetaInfo(kieModule.getBytes(file));
}
}
}
init();
}
public Collection<String> getPackages() {
return classes.keySet();
}
public Collection<String> getClasses(String packageName) {
Collection<String> classesInPkg = classes.get(packageName);
return classesInPkg != null ? classesInPkg : Collections.<String>emptyList();
}
public Class<?> getClass(String pkgName, String className) {
try {
return Class.forName((pkgName == null || pkgName.trim().length() == 0) ? className : pkgName + "." + className, false, getClassLoader());
} catch (ClassNotFoundException e) {
return null;
}
}
public TypeMetaInfo getTypeMetaInfo(Class<?> clazz) {
TypeMetaInfo typeMetaInfo = typeMetaInfos.get(clazz.getName());
return typeMetaInfo != null ? typeMetaInfo : DEFAULT_TYPE_META_INFO;
}
private ClassLoader getClassLoader() {
if (classLoader == null) {
URL[] urls = new URL[jars.size()];
int i = 0;
for (File jar : jars.values()) {
try {
urls[i++] = jar.toURI().toURL();
} catch (MalformedURLException e) {
throw new RuntimeException(e);
}
}
classLoader = ProjectClassLoader.createProjectClassLoader(new URLClassLoader(urls));
if (kieModule != null) {
Map<String, byte[]> classes = kieModule.getClassesMap(true);
for (Map.Entry<String, byte[]> entry : classes.entrySet()) {
classLoader.defineClass(convertResourceToClassName(entry.getKey()), entry.getKey(), entry.getValue());
}
}
}
return classLoader;
}
private void init() {
if (releaseId != null) {
addArtifact(artifactResolver.resolveArtifact(releaseId.toString()));
}
for (DependencyDescriptor dep : artifactResolver.getAllDependecies()) {
addArtifact(artifactResolver.resolveArtifact(dep.toString()));
}
}
private void addArtifact(Artifact artifact) {
if (artifact != null && artifact.getExtension() != null && artifact.getExtension().equals("jar")) {
addJar(artifact.getFile());
}
}
private void addJar(File jarFile) {
URI uri = jarFile.toURI();
if (!jars.containsKey(uri)) {
jars.put(uri, jarFile);
scanJar(jarFile);
}
}
private void scanJar(File jarFile) {
ZipFile zipFile = null;
try {
zipFile = new ZipFile( jarFile );
Enumeration< ? extends ZipEntry> entries = zipFile.entries();
while ( entries.hasMoreElements() ) {
ZipEntry entry = entries.nextElement();
String pathName = entry.getName();
if(pathName.endsWith("bpmn2")){
processes.put(pathName, new String(readBytesFromZipEntry(jarFile, entry)));
}
if (!indexClass(pathName)) {
if (pathName.endsWith(KieModuleModelImpl.KMODULE_INFO_JAR_PATH)) {
indexMetaInfo(readBytesFromZipEntry(jarFile, entry));
}
}
}
} catch ( IOException e ) {
throw new RuntimeException( e );
} finally {
if ( zipFile != null ) {
try {
zipFile.close();
} catch ( IOException e ) {
throw new RuntimeException( e );
}
}
}
}
private boolean indexClass(String pathName) {
if (!pathName.endsWith(".class")) {
return false;
}
int separator = pathName.lastIndexOf( '/' );
String packageName = separator > 0 ? pathName.substring( 0, separator ).replace('/', '.') : "";
String className = pathName.substring( separator + 1, pathName.length() - ".class".length() );
Collection<String> pkg = classes.get(packageName);
if (pkg == null) {
pkg = new HashSet<String>();
classes.put(packageName, pkg);
}
pkg.add(className);
return true;
}
private void indexMetaInfo(byte[] bytes) {
typeMetaInfos.putAll(unmarshallMetaInfos(new String(bytes)));
}
@Override
public Map<String, String> getProcesses() {
return processes;
}
}
|
package org.kie.scanner;
import junit.framework.TestCase;
import org.drools.core.rule.TypeMetaInfo;
import org.junit.Ignore;
import org.junit.Test;
import org.kie.api.KieServices;
import org.kie.api.builder.KieBuilder;
import org.kie.api.builder.KieFileSystem;
import org.kie.api.builder.KieModule;
import org.kie.api.builder.Message;
import org.kie.api.builder.ReleaseId;
import org.drools.compiler.kie.builder.impl.InternalKieModule;
import org.kie.api.builder.model.KieModuleModel;
import org.kie.api.definition.type.Role;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.MessageFormat;
import java.util.Collection;
import java.util.List;
import static java.util.Arrays.asList;
import static junit.framework.Assert.assertEquals;
import static junit.framework.Assert.assertNotNull;
import static junit.framework.Assert.assertTrue;
import static junit.framework.TestCase.assertFalse;
import static org.drools.compiler.kie.builder.impl.KieBuilderImpl.generatePomXml;
import static org.junit.Assert.fail;
public class KieModuleMetaDataTest extends AbstractKieCiTest {
@Test
@Ignore
public void testKieModuleMetaData() throws Exception {
ReleaseId releaseId = KieServices.Factory.get().newReleaseId( "org.drools", "drools-core", "5.5.0.Final" );
KieModuleMetaData kieModuleMetaData = KieModuleMetaData.Factory.newKieModuleMetaData( releaseId );
checkDroolsCoreDep( kieModuleMetaData );
}
@Test
public void testKieModuleMetaDataInMemoryWithJavaClass() throws Exception {
testKieModuleMetaDataInMemory( false );
}
@Test
public void testKieModuleMetaDataInMemoryWithTypeDeclaration() throws Exception {
testKieModuleMetaDataInMemory( true );
}
@Test
public void testKieModuleMetaDataInMemoryUsingPOMWithTypeDeclaration() throws Exception {
testKieModuleMetaDataInMemoryUsingPOM( true );
}
@Test
public void testKieModuleMetaDataForDependenciesInMemory() throws Exception {
testKieModuleMetaDataForDependenciesInMemory( false );
}
@Test
public void testKieModuleMetaDataInMemoryWithJavaClassDefaultPackage() throws Exception {
final KieServices ks = KieServices.Factory.get();
final ReleaseId releaseId = ks.newReleaseId( "org.kie", "javaDefaultPackage", "1.0-SNAPSHOT" );
final KieModuleModel kproj = ks.newKieModuleModel();
final KieFileSystem kfs = ks.newKieFileSystem();
kfs.writeKModuleXML( kproj.toXML() )
.writePomXML( generatePomXml( releaseId ) )
.write( "src/main/java/test/Bean.java", createJavaSource() );
final KieBuilder kieBuilder = ks.newKieBuilder( kfs );
final List<Message> messages = kieBuilder.buildAll().getResults().getMessages();
assertTrue( messages.isEmpty() );
final KieModule kieModule = kieBuilder.getKieModule();
final KieModuleMetaData kieModuleMetaData = KieModuleMetaData.Factory.newKieModuleMetaData( kieModule );
//The call to kieModuleMetaData.getClass() assumes a Java file has an explicit package
final Class<?> beanClass = kieModuleMetaData.getClass( "", "test.Bean" );
assertNotNull( beanClass );
final TypeMetaInfo beanMetaInfo = kieModuleMetaData.getTypeMetaInfo( beanClass );
assertNotNull( beanMetaInfo );
}
@Test
public void testGetPackageNames() {
final KieServices ks = KieServices.Factory.get();
final KieFileSystem kfs = ks.newKieFileSystem();
kfs.write( "src/main/resources/test.drl",
"package org.test declare Bean end" );
final KieBuilder kieBuilder = ks.newKieBuilder( kfs );
final List<Message> messages = kieBuilder.buildAll().getResults().getMessages();
assertTrue( messages.isEmpty() );
final KieModule kieModule = kieBuilder.getKieModule();
final KieModuleMetaData kieModuleMetaData = KieModuleMetaData.Factory.newKieModuleMetaData( kieModule );
assertFalse( kieModuleMetaData.getPackages().isEmpty() );
TestCase.assertTrue( kieModuleMetaData.getPackages().contains( "org.test" ) );
}
@Test
public void testGetRuleNames() {
final KieServices ks = KieServices.Factory.get();
final KieFileSystem kfs = ks.newKieFileSystem();
kfs.write( "src/main/resources/test1.drl",
"package org.test\n" +
"rule A\n" +
" when\n" +
"then\n" +
"end\n" +
"rule B\n" +
" when\n" +
"then\n" +
"end\n" );
kfs.write( "src/main/resources/test2.drl",
"package org.test\n" +
"rule C\n" +
" when\n" +
"then\n" +
"end\n" );
final KieBuilder kieBuilder = ks.newKieBuilder( kfs );
final List<Message> messages = kieBuilder.buildAll().getResults().getMessages();
assertTrue( messages.isEmpty() );
final KieModule kieModule = kieBuilder.getKieModule();
final KieModuleMetaData kieModuleMetaData = KieModuleMetaData.Factory.newKieModuleMetaData( kieModule );
Collection<String> rules = kieModuleMetaData.getRuleNamesInPackage( "org.test" );
assertEquals( 3, rules.size() );
assertTrue( rules.containsAll( asList( "A", "B", "C" ) ) );
}
private String createJavaSource() {
return "package test;\n" +
"public class Bean {\n" +
" private int value;\n" +
" public int getValue() {\n" +
" return value;\n" +
" }\n" +
"}";
}
private void testKieModuleMetaDataInMemory( boolean useTypeDeclaration ) throws Exception {
KieServices ks = KieServices.Factory.get();
ReleaseId dependency = ks.newReleaseId( "org.drools", "drools-core", "5.5.0.Final" );
ReleaseId releaseId = ks.newReleaseId( "org.kie", "metadata-test", "1.0-SNAPSHOT" );
InternalKieModule kieModule = createKieJarWithClass( ks, releaseId, useTypeDeclaration, 2, 7, dependency );
KieModuleMetaData kieModuleMetaData = KieModuleMetaData.Factory.newKieModuleMetaData( kieModule );
checkDroolsCoreDep( kieModuleMetaData );
Collection<String> testClasses = kieModuleMetaData.getClasses( "org.kie.test" );
assertEquals( 1, testClasses.size() );
assertEquals( "Bean", testClasses.iterator().next() );
Class<?> beanClass = kieModuleMetaData.getClass( "org.kie.test", "Bean" );
assertNotNull( beanClass.getMethod( "getValue" ) );
TypeMetaInfo beanTypeInfo = kieModuleMetaData.getTypeMetaInfo( beanClass );
assertNotNull( beanTypeInfo );
assertTrue( beanTypeInfo.isEvent() );
Role role = beanClass.getAnnotation( Role.class );
assertNotNull( role );
assertEquals( Role.Type.EVENT, role.value() );
assertEquals( useTypeDeclaration, beanTypeInfo.isDeclaredType() );
}
private void testKieModuleMetaDataInMemoryUsingPOM( boolean useTypeDeclaration ) throws Exception {
//Build a KieModule jar, deploy it into local Maven repository
KieServices ks = KieServices.Factory.get();
ReleaseId dependency = ks.newReleaseId( "org.drools", "drools-core", "5.5.0.Final" );
ReleaseId releaseId = ks.newReleaseId( "org.kie", "metadata-test", "1.0-SNAPSHOT" );
InternalKieModule kieModule = createKieJarWithClass( ks, releaseId, useTypeDeclaration, 2, 7, dependency );
String pomText = getPom( dependency );
File pomFile = new File( System.getProperty( "java.io.tmpdir" ), MavenRepository.toFileName( releaseId, null ) + ".pom" );
try {
FileOutputStream fos = new FileOutputStream( pomFile );
fos.write( pomText.getBytes() );
fos.flush();
fos.close();
} catch ( IOException e ) {
throw new RuntimeException( e );
}
MavenRepository.getMavenRepository().deployArtifact( releaseId, kieModule, pomFile );
//Build a second KieModule, depends on the first KieModule jar which we have deployed into Maven
ReleaseId releaseId2 = ks.newReleaseId( "org.kie", "metadata-test-using-pom", "1.0-SNAPSHOT" );
String pomText2 = getPom( releaseId2, releaseId );
File pomFile2 = new File( System.getProperty( "java.io.tmpdir" ), MavenRepository.toFileName( releaseId2, null ) + ".pom" );
try {
FileOutputStream fos = new FileOutputStream( pomFile2 );
fos.write( pomText2.getBytes() );
fos.flush();
fos.close();
} catch ( IOException e ) {
throw new RuntimeException( e );
}
KieModuleMetaData kieModuleMetaData = KieModuleMetaData.Factory.newKieModuleMetaData( pomFile2 );
//checkDroolsCoreDep(kieModuleMetaData);
Collection<String> testClasses = kieModuleMetaData.getClasses( "org.kie.test" );
assertEquals( 1, testClasses.size() );
assertEquals( "Bean", testClasses.iterator().next() );
Class<?> beanClass = kieModuleMetaData.getClass( "org.kie.test", "Bean" );
assertNotNull( beanClass.getMethod( "getValue" ) );
if ( useTypeDeclaration ) {
assertTrue( kieModuleMetaData.getTypeMetaInfo( beanClass ).isEvent() );
}
}
private void checkDroolsCoreDep( KieModuleMetaData kieModuleMetaData ) {
assertEquals( 17, kieModuleMetaData.getClasses( "org.drools.runtime" ).size() );
Class<?> statefulKnowledgeSessionClass = kieModuleMetaData.getClass( "org.drools.runtime", "StatefulKnowledgeSession" );
assertTrue( statefulKnowledgeSessionClass.isInterface() );
assertEquals( 2, statefulKnowledgeSessionClass.getDeclaredMethods().length );
}
private void testKieModuleMetaDataForDependenciesInMemory( boolean useTypeDeclaration ) throws Exception {
KieServices ks = KieServices.Factory.get();
ReleaseId dependency = ks.newReleaseId( "org.drools", "drools-core", "5.5.0.Final" );
ReleaseId releaseId = ks.newReleaseId( "org.kie", "metadata-test", "1.0-SNAPSHOT" );
InternalKieModule kieModule = createKieJarWithClass( ks, releaseId, useTypeDeclaration, 2, 7, dependency );
KieModuleMetaData kieModuleMetaData = KieModuleMetaData.Factory.newKieModuleMetaData( kieModule );
checkDroolsCoreDep( kieModuleMetaData );
Collection<String> testClasses = kieModuleMetaData.getClasses( "org.drools" );
assertEquals( 55, testClasses.size() );
Class<?> beanClass = kieModuleMetaData.getClass( "org.drools", "QueryResult" );
assertNotNull( beanClass );
//Classes in dependencies should have TypeMetaInfo
TypeMetaInfo beanTypeInfo = kieModuleMetaData.getTypeMetaInfo( beanClass );
assertNotNull( beanTypeInfo );
if ( useTypeDeclaration ) {
assertTrue( beanTypeInfo.isEvent() );
}
assertEquals( useTypeDeclaration, beanTypeInfo.isDeclaredType() );
}
@Test
@Ignore("https://bugzilla.redhat.com/show_bug.cgi?id=1049674")
public void testKieMavenPluginEmptyProject() {
// According to https://bugzilla.redhat.com/show_bug.cgi?id=1049674#c2 the below is the minimal POM required to use KieMavenPlugin.
// However when we attempt to retrieve meta-data about the classes in the KieModule some are not accessible. IDK whether the minimal
// POM is correct; or whether KieModuleMetaData needs to ignore certain classes (e.g. if a transient dependency is optional?!?)
final KieServices ks = KieServices.Factory.get();
final KieFileSystem kfs = ks.newKieFileSystem();
kfs.write( "pom.xml",
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
+ "<project xsi:schemaLocation=\"http:
+ "<modelVersion>4.0.0</modelVersion>"
+ "<groupId>org.kie</groupId>"
+ "<artifactId>plugin-test</artifactId>"
+ "<version>1.0</version>"
+ "<packaging>kjar</packaging>"
+ "<dependencies>"
+ "<dependency>"
+ "<groupId>org.drools</groupId>"
+ "<artifactId>drools-compiler</artifactId>"
+ "<version>6.1.0-SNAPSHOT</version>"
+ "</dependency>"
+ "</dependencies>"
+ "<build>"
+ "<plugins>"
+ "<plugin>"
+ "<groupId>org.kie</groupId>"
+ "<artifactId>kie-maven-plugin</artifactId>"
+ "<version>6.1.0-SNAPSHOT</version>"
+ "<extensions>true</extensions>"
+ "</plugin>"
+ "</plugins>"
+ "</build>"
+ "</project>" );
final KieBuilder kieBuilder = ks.newKieBuilder( kfs );
final List<Message> messages = kieBuilder.buildAll().getResults().getMessages();
assertTrue( messages.isEmpty() );
final KieModule kieModule = kieBuilder.getKieModule();
final KieModuleMetaData kieModuleMetaData = KieModuleMetaData.Factory.newKieModuleMetaData( kieModule );
boolean fail = false;
for ( final String packageName : kieModuleMetaData.getPackages() ) {
for ( final String className : kieModuleMetaData.getClasses( packageName ) ) {
try {
kieModuleMetaData.getClass( packageName, className );
} catch ( Throwable e ) {
fail = true;
System.out.println( e );
}
}
}
if ( fail ) {
fail( "See console for details." );
}
}
}
|
package io.mangoo.core;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.google.inject.Singleton;
import io.mangoo.exceptions.MangooSchedulerException;
import io.mangoo.interfaces.MangooLifecycle;
import io.mangoo.managers.ExecutionManager;
import io.mangoo.providers.CacheProvider;
import io.mangoo.scheduler.Scheduler;
/**
*
* @author svenkubiak
*
*/
@Singleton
public class Shutdown extends Thread {
private static final Logger LOG = LogManager.getLogger(Shutdown.class);
public Shutdown() {
}
@Override
public void run() {
invokeLifecycle();
closeCaches();
stopScheduler();
stopUndertow();
stopExecutionManager();
}
private void invokeLifecycle() {
Application.getInstance(MangooLifecycle.class).applicationStopped();
}
private void stopExecutionManager() {
Application.getInstance(ExecutionManager.class).shutdown();
}
private void stopScheduler() {
Scheduler scheduler = Application.getInstance(Scheduler.class);
try {
if (scheduler != null && scheduler.isInitialize()) {
scheduler.shutdown();
}
} catch (MangooSchedulerException e) {
LOG.error("Failed to stop scheduler during application shutdown", e);
}
}
private void stopUndertow() {
Application.stopUndertow();
}
private void closeCaches() {
Application.getInstance(CacheProvider.class).close();
}
}
|
package natlab.backends.vrirGen;
import java.util.HashMap;
import java.util.Map;
public class LibFuncMapper {
private static Map<String, String> libFuncMap = new HashMap<String, String>();
static {
libFuncMap = new HashMap<>();
libFuncMap.put("sqrt", "sqrt");
libFuncMap.put("sin", "sin");
libFuncMap.put("asin", "asin");
libFuncMap.put("cos", "cos");
libFuncMap.put("acos", "acos");
libFuncMap.put("atan", "tan");
libFuncMap.put("abs", "abs");
libFuncMap.put("pow", "pow");
libFuncMap.put("log", "loge");
libFuncMap.put("log10", "log10");
libFuncMap.put("exp", "expe");
libFuncMap.put("sqrt", "sqrt");
libFuncMap.put("power", "pow");
libFuncMap.put("mpower", "pow");
libFuncMap.put("mtimes", "mmult");
libFuncMap.put("trans", "trans");
libFuncMap.put("plus", "plus");
libFuncMap.put("minus", "minus");
libFuncMap.put("times", "mult");
libFuncMap.put("div", "div");
libFuncMap.put("mrdivide", "div");
libFuncMap.put("rdivide", "div");
libFuncMap.put("trans", "trans");
}
public static String getFunc(String key) {
return libFuncMap.get(key);
}
@SuppressWarnings("unused")
private static void putFunc(String key, String val) {
libFuncMap.put(key, val);
}
public static boolean containsFunc(String key) {
return libFuncMap.containsKey(key);
}
}
|
package ui.components.pickers;
import backend.resource.TurboLabel;
import util.Utility;
import java.util.*;
import java.util.stream.Collectors;
public class LabelPickerState {
Set<String> addedLabels;
Set<String> removedLabels;
Set<String> initialLabels;
List<String> matchedLabels;
OptionalInt currentSuggestionIndex;
private LabelPickerState(Set<String> initialLabels,
Set<String> addedLabels,
Set<String> removedLabels,
List<String> matchedLabels,
OptionalInt currentSuggestionIndex) {
this.initialLabels = initialLabels;
this.addedLabels = addedLabels;
this.removedLabels = removedLabels;
this.matchedLabels = matchedLabels;
this.currentSuggestionIndex = currentSuggestionIndex;
}
private LabelPickerState(Set<String> initialLabels,
Set<String> addedLabels,
Set<String> removedLabels,
List<String> matchedLabels) {
this.initialLabels = initialLabels;
this.addedLabels = addedLabels;
this.removedLabels = removedLabels;
this.matchedLabels = matchedLabels;
this.currentSuggestionIndex = OptionalInt.empty();
}
/*
* Methods for Logic
*/
public LabelPickerState(Set<String> initialLabels) {
this.initialLabels = initialLabels;
this.addedLabels = new HashSet<>();
this.removedLabels = new HashSet<>();
this.matchedLabels = new ArrayList<>();
this.currentSuggestionIndex = OptionalInt.empty();
}
public LabelPickerState clearMatchedLabels() {
return new LabelPickerState(initialLabels, addedLabels, removedLabels,
new ArrayList<>(), currentSuggestionIndex);
}
public LabelPickerState toggleLabel(String name) {
if (isAnInitialLabel(name)) {
if (isARemovedLabel(name)) {
// add back initial label
removeConflictingLabels(name);
removedLabels.remove(name);
} else {
removedLabels.add(name);
}
} else {
if (isAnAddedLabel(name)) {
addedLabels.remove(name);
} else {
// add new label
removeConflictingLabels(name);
addedLabels.add(name);
}
}
return new LabelPickerState(initialLabels, addedLabels, removedLabels, new ArrayList<>());
}
private void removeConflictingLabels(String name) {
if (TurboLabel.getDelimiter(name).isPresent() && TurboLabel.getDelimiter(name).get().equals('.')) {
String group = getGroup(name);
// remove added labels in same group
addedLabels = addedLabels.stream()
.filter(label -> {
String labelGroup = getGroup(label);
return !labelGroup.equals(group);
})
.collect(Collectors.toSet());
// remove existing
removedLabels.addAll(initialLabels.stream()
.filter(label -> {
String labelGroup = getGroup(label);
return !labelGroup.equals(group) && !removedLabels.contains(name);
})
.collect(Collectors.toSet()));
}
}
public LabelPickerState nextSuggestion() {
if (currentSuggestionIndex.isPresent() && currentSuggestionIndex.getAsInt() < matchedLabels.size() - 1) {
return new LabelPickerState(initialLabels, removedLabels, addedLabels,
matchedLabels, OptionalInt.of(currentSuggestionIndex.getAsInt() + 1));
}
return this;
}
public LabelPickerState previousSuggestion() {
if (currentSuggestionIndex.isPresent() && currentSuggestionIndex.getAsInt() > 0) {
return new LabelPickerState(initialLabels, removedLabels, addedLabels,
matchedLabels, OptionalInt.of(currentSuggestionIndex.getAsInt() - 1));
}
return this;
}
public LabelPickerState updateMatchedLabels(Set<String> repoLabels, String query) {
List<String> newMatchedLabels = convertToList(repoLabels);
newMatchedLabels = filterByName(newMatchedLabels, getName(query));
newMatchedLabels = filterByGroup(newMatchedLabels, getGroup(query));
return new LabelPickerState(initialLabels, addedLabels, removedLabels, newMatchedLabels, currentSuggestionIndex);
}
private List<String> filterByName(List<String> repoLabels, String labelName) {
return repoLabels
.stream()
.filter(name -> Utility.containsIgnoreCase(getGroup(name), labelName))
.collect(Collectors.toList());
}
private List<String> filterByGroup(List<String> repoLabels, String labelGroup) {
return repoLabels
.stream()
.filter(name -> {
if (hasGroup(name)) {
return Utility.containsIgnoreCase(getGroup(name), labelGroup);
} else {
return false;
}
})
.collect(Collectors.toList());
}
private String getGroup(String name) {
if (hasGroup(name)) {
return name.substring(0, name.indexOf(TurboLabel.getDelimiter(name).get()));
} else {
return "";
}
}
private String getName(String name) {
if (hasGroup(name)) {
return name.substring(name.indexOf(TurboLabel.getDelimiter(name).get()) - 1);
} else {
return name;
}
}
private boolean hasGroup(String name) {
return TurboLabel.getDelimiter(name).isPresent();
}
private boolean isAnInitialLabel(String name) {
return this.initialLabels.contains(name);
}
private boolean isAnAddedLabel(String name) {
return this.addedLabels.contains(name);
}
private boolean isARemovedLabel(String name) {
return this.removedLabels.contains(name);
}
/*
* methods to update UI
*/
public List<String> getAssignedLabels() {
List<String> assignedLabels = new ArrayList<>();
assignedLabels.addAll(initialLabels);
assignedLabels.addAll(addedLabels);
assignedLabels.removeAll(removedLabels);
return assignedLabels;
}
public List<String> getInitialLabels() {
return convertToList(initialLabels);
}
public List<String> getRemovedLabels() {
return convertToList(removedLabels);
}
public List<String> getAddedLabels() {
return convertToList(addedLabels);
}
public Optional<String> getCurrentSuggestion() {
if (currentSuggestionIndex.isPresent()) {
if (currentSuggestionIndex.getAsInt() >= 0 && currentSuggestionIndex.getAsInt() < matchedLabels.size()) {
return Optional.of(matchedLabels.get(currentSuggestionIndex.getAsInt()));
}
}
return Optional.empty();
}
public List<String> getMatchedLabels() {
return matchedLabels;
}
private List<String> convertToList(Set<String> labelSet){
List<String> resultingList = new ArrayList<>();
resultingList.addAll(labelSet);
return resultingList;
}
}
|
package com.comandante.creeper.Items;
import com.comandante.creeper.player.EquipmentBuilder;
import com.comandante.creeper.server.Color;
import com.comandante.creeper.world.TimeTracker;
import com.google.common.collect.Sets;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import static com.comandante.creeper.server.Color.*;
public enum ItemType {
UNKNOWN(0, Arrays.asList(""), "", "", "", false, 0, 0, false, Rarity.RARE, 0, Sets.<TimeTracker.TimeOfDay>newHashSet()),
KEY(1, Arrays.asList("key", "gold key", "shiny gold key"),
"a shiny " + YELLOW + "gold key" + RESET,
"a shiny " + YELLOW + "gold key" + RESET + " catches your eye.",
"A basic key with nothing really remarkable other than its made of gold.",
false,
0,
60,
false,
Rarity.BASIC,
10, Sets.<TimeTracker.TimeOfDay>newHashSet(TimeTracker.TimeOfDay.NIGHT)),
BEER(2, Arrays.asList("beer", "can of beer", "b"),
"a dented can of " + CYAN + "beer" + RESET,
"a " + CYAN + "beer" + RESET + " lies on the ground, unopened",
"an ice cold " + CYAN + "beer" + RESET + " that restores 50 health" + RESET,
true,
0,
60,
false,
Rarity.BASIC,
1, Sets.<TimeTracker.TimeOfDay>newHashSet()),
BOOK(3, Arrays.asList("book", "used book"),
MAGENTA + "a leather book" + RESET,
MAGENTA + "a well used book" + RESET + " with what looks like a leather back rests here.",
"A book written in a foreign language. Doesn't matter as you can't read.",
false,
0,
60,
false,
Rarity.BASIC,
1, Sets.<TimeTracker.TimeOfDay>newHashSet()),
BROAD_SWORD(4, Arrays.asList("sword", "broad", "a broad sword", "the broad sword"),
Color.CYAN + "the broad sword" + Color.RESET,
"an iron broad sword rests upon the ground.",
"an iron broad sword",
false,
0,
60,
true,
Rarity.BASIC,
100, Sets.<TimeTracker.TimeOfDay>newHashSet()),
IRON_BOOTS(5, Arrays.asList("boots", "boot", "iron boots"),
Color.CYAN + "iron boots" + Color.RESET,
"a pair of iron boots are here on the ground.",
"a pair of iron boots",
false,
0,
60,
true,
Rarity.BASIC,
50, Sets.<TimeTracker.TimeOfDay>newHashSet()),
IRON_CHEST_PLATE(6, Arrays.asList("chest", "iron chest plate", "plate"),
"iron chest plate",
"an iron ches tplate is on the ground.",
"an iron chest plate",
false,
0,
60,
true,
Rarity.BASIC,
70, Sets.<TimeTracker.TimeOfDay>newHashSet()),
IRON_LEGGINGS(7, Arrays.asList("leggings", "iron leggings"),
"iron leggings",
"an a pair of iron leggings are here on the ground.",
"an iron pair of leggings",
false,
0,
60,
true,
Rarity.BASIC,
80, Sets.<TimeTracker.TimeOfDay>newHashSet()),
PHANTOM_SWORD(8, Arrays.asList("phantom", "phantom sword", "the phantom sword"),
Color.YELLOW + "the " + Color.CYAN + "phantom" + Color.RESET + Color.YELLOW + " sword" + Color.RESET,
"a " + Color.CYAN + "phantom" + Color.RESET + Color.YELLOW + " sword" + Color.RESET + " is on the ground.",
"a " + Color.CYAN + "phantom" + Color.RESET + Color.YELLOW + " sword" + Color.RESET,
false,
0,
60,
true,
Rarity.BASIC,
500, Sets.<TimeTracker.TimeOfDay>newHashSet()),
IRON_BRACERS(9, Arrays.asList("bracers", "iron bracers"),
"iron bracers",
"an a pair of iron bracers are here on the ground.",
"an iron pair of bracers",
false,
0,
60,
true,
Rarity.BASIC,
40, Sets.<TimeTracker.TimeOfDay>newHashSet()),
PHANTOM_HELMET(10, Arrays.asList("helmet", "phantom helmet", "the phantom helmet"),
Color.CYAN + "phantom" + Color.RESET + Color.YELLOW + " helmet" + Color.RESET,
"a " + Color.CYAN + "phantom" + Color.RESET + Color.YELLOW + " helmet" + Color.RESET + " is on the ground.",
"a " + Color.CYAN + "phantom" + Color.RESET + Color.YELLOW + " helmet" + Color.RESET,
false,
0,
60,
true,
Rarity.BASIC,
250, Sets.<TimeTracker.TimeOfDay>newHashSet()),
PHANTOM_CHESTPLATE(11, Arrays.asList("chestplate", "chest", "phantom chest plate", "the phantom chest plate"),
Color.CYAN + "phantom" + Color.RESET + Color.YELLOW + " chest plate" + Color.RESET,
"a " + Color.CYAN + "phantom" + Color.RESET + Color.YELLOW + " chest plate" + Color.RESET + " is on the ground.",
"a " + Color.CYAN + "phantom" + Color.RESET + Color.YELLOW + " chest plate" + Color.RESET,
false,
0,
60,
true,
Rarity.BASIC,
350, Sets.<TimeTracker.TimeOfDay>newHashSet()),
PHANTOM_BOOTS(12, Arrays.asList("boots", "phantom boots", "the phantom boots"),
Color.CYAN + "phantom" + Color.RESET + Color.YELLOW + " boots" + Color.RESET,
"a pair of " + Color.CYAN + "phantom" + Color.RESET + Color.YELLOW + " boots" + Color.RESET + " are on the ground.",
"a pair of " + Color.CYAN + "phantom" + Color.RESET + Color.YELLOW + " boots" + Color.RESET,
false,
0,
60,
true,
Rarity.BASIC,
280, Sets.<TimeTracker.TimeOfDay>newHashSet()),
PHANTOM_BRACERS(13, Arrays.asList("boots", "phantom bracers", "the phantom bracers"),
Color.CYAN + "phantom" + Color.RESET + Color.YELLOW + " bracers" + Color.RESET,
"a pair of " + Color.CYAN + "phantom" + Color.RESET + Color.YELLOW + " bracers" + Color.RESET + " are on the ground.",
"a pair of " + Color.CYAN + "phantom" + Color.RESET + Color.YELLOW + " bracers" + Color.RESET,
false,
0,
60,
true,
Rarity.BASIC,
250, Sets.<TimeTracker.TimeOfDay>newHashSet()),
PHANTOM_LEGGINGS(14, Arrays.asList("leggings", "phantom leggings", "the phantom leggings"),
Color.CYAN + "phantom" + Color.RESET + Color.YELLOW + " bracers" + Color.RESET,
"a pair of " + Color.CYAN + "phantom" + Color.RESET + Color.YELLOW + " leggings" + Color.RESET + " are on the ground.",
"a pair of " + Color.CYAN + "phantom" + Color.RESET + Color.YELLOW + " leggings" + Color.RESET,
false,
0,
60,
true,
Rarity.BASIC,
290, Sets.<TimeTracker.TimeOfDay>newHashSet()),
IRON_HELMET(15, Arrays.asList("helmet", "iron helmet"),
"iron helmet",
"an iron helmet is on the ground.",
"an iron helmet",
false,
0,
60,
true,
Rarity.BASIC,
80, Sets.<TimeTracker.TimeOfDay>newHashSet()),
MITHRIL_SWORD(16, Arrays.asList("sword", "mithril sword", "mithril sword"),
Color.MAGENTA + "mithril" + Color.RESET + Color.YELLOW + " sword" + Color.RESET,
"a " + Color.MAGENTA + "mithril" + Color.RESET + Color.YELLOW + " sword" + Color.RESET + " is on the ground.",
"a " + Color.MAGENTA + "mithril" + Color.RESET + Color.YELLOW + " sword" + Color.RESET,
false,
0,
60,
true,
Rarity.BASIC,
500, Sets.<TimeTracker.TimeOfDay>newHashSet()),
MITHRIL_CHESTPLATE(17, Arrays.asList("chestplate", "a mithril chestplate", "mithril chestplate"),
Color.MAGENTA + "mithril" + Color.RESET + Color.YELLOW + " chestplate" + Color.RESET,
"a " + Color.MAGENTA + "mithril" + Color.RESET + Color.YELLOW + " chestplate" + Color.RESET + " is on the ground.",
"a " + Color.MAGENTA + "mithril" + Color.RESET + Color.YELLOW + " chestplate" + Color.RESET,
false,
0,
60,
true,
Rarity.BASIC,
400, Sets.<TimeTracker.TimeOfDay>newHashSet()),
MITHRIL_HELMET(18, Arrays.asList("helmet", "a mithril helmet", "mithril helmet"),
Color.MAGENTA + "mithril" + Color.RESET + Color.YELLOW + " helmet" + Color.RESET,
"a " + Color.MAGENTA + "mithril" + Color.RESET + Color.YELLOW + " helmet" + Color.RESET + " is on the ground.",
"a " + Color.MAGENTA + "mithril" + Color.RESET + Color.YELLOW + " helmet" + Color.RESET,
false,
0,
60,
true,
Rarity.BASIC,
280, Sets.<TimeTracker.TimeOfDay>newHashSet()),
MITHRIL_BRACERS(19, Arrays.asList("helmet", "mithril bracers", "mithril bracers"),
Color.MAGENTA + "mithril" + Color.RESET + Color.YELLOW + " bracers" + Color.RESET,
"a pair of " + Color.MAGENTA + "mithril" + Color.RESET + Color.YELLOW + " bracers" + Color.RESET + " are on the ground.",
"a pair of " + Color.MAGENTA + "mithril" + Color.RESET + Color.YELLOW + " bracers" + Color.RESET,
false,
0,
60,
true,
Rarity.BASIC,
300, Sets.<TimeTracker.TimeOfDay>newHashSet()),
MITHRIL_LEGGINGS(20, Arrays.asList("helmet", "mithril leggings", "mithril leggings"),
Color.MAGENTA + "mithril" + Color.RESET + Color.YELLOW + " leggings" + Color.RESET,
"a pair of " + Color.MAGENTA + "mithril" + Color.RESET + Color.YELLOW + " leggings" + Color.RESET + " are on the ground.",
"a pair of " + Color.MAGENTA + "mithril" + Color.RESET + Color.YELLOW + " leggings" + Color.RESET,
false,
0,
60,
true,
Rarity.BASIC,
350, Sets.<TimeTracker.TimeOfDay>newHashSet()),
MITHRIL_BOOTS(21, Arrays.asList("helmet", "mithril boots"),
Color.MAGENTA + "mithril" + Color.RESET + Color.YELLOW + " boots" + Color.RESET,
"a pair of " + Color.MAGENTA + "mithril" + Color.RESET + Color.YELLOW + " boots" + Color.RESET + " are on the ground.",
"a pair of " + Color.MAGENTA + "mithril" + Color.RESET + Color.YELLOW + " boots" + Color.RESET,
false,
0,
60,
true,
Rarity.BASIC,
190, Sets.<TimeTracker.TimeOfDay>newHashSet()),
PYAMITE_SWORD(22, Arrays.asList("sword", "pyamite sword", "pyamite sword"),
Color.GREEN + "pyamite" + Color.RESET + Color.YELLOW + " sword" + Color.RESET,
"a " + Color.GREEN + "pyamite" + Color.RESET + Color.YELLOW + " sword" + Color.RESET + " is on the ground.",
"a " + Color.GREEN + "pyamite" + Color.RESET + Color.YELLOW + " sword" + Color.RESET,
false,
0,
60,
true,
Rarity.BASIC,
3000, Sets.<TimeTracker.TimeOfDay>newHashSet()),
PYAMITE_CHESTPLATE(23, Arrays.asList("chestplate", "a pyamite chestplate", "pyamite chestplate"),
Color.GREEN + "pyamite" + Color.RESET + Color.YELLOW + " chestplate" + Color.RESET,
"a " + Color.GREEN + "pyamite" + Color.RESET + Color.YELLOW + " chestplate" + Color.RESET + " is on the ground.",
"a " + Color.GREEN + "pyamite" + Color.RESET + Color.YELLOW + " chestplate" + Color.RESET,
false,
0,
60,
true,
Rarity.BASIC,
2700, Sets.<TimeTracker.TimeOfDay>newHashSet()),
PYAMITE_HELMET(24, Arrays.asList("helmet", "a pyamite helmet", "pyamite helmet"),
Color.GREEN + "pyamite" + Color.RESET + Color.YELLOW + " helmet" + Color.RESET,
"a " + Color.GREEN + "pyamite" + Color.RESET + Color.YELLOW + " helmet" + Color.RESET + " is on the ground.",
"a " + Color.GREEN + "pyamite" + Color.RESET + Color.YELLOW + " helmet" + Color.RESET,
false,
0,
60,
true,
Rarity.BASIC,
2000, Sets.<TimeTracker.TimeOfDay>newHashSet()),
PYAMITE_BRACERS(25, Arrays.asList("bracers", "pyamite bracers", "pyamite bracers"),
Color.GREEN + "pyamite" + Color.RESET + Color.YELLOW + " bracers" + Color.RESET,
"a pair of " + Color.GREEN + "pyamite" + Color.RESET + Color.YELLOW + " bracers" + Color.RESET + " are on the ground.",
"a pair of " + Color.GREEN + "pyamite" + Color.RESET + Color.YELLOW + " bracers" + Color.RESET,
false,
0,
60,
true,
Rarity.BASIC,
2100, Sets.<TimeTracker.TimeOfDay>newHashSet()),
PYAMITE_LEGGINGS(26, Arrays.asList("leggings", "pyamite leggings", "pyamite leggings"),
Color.GREEN + "pyamite" + Color.RESET + Color.YELLOW + " leggings" + Color.RESET,
"a pair of " + Color.GREEN + "pyamite" + Color.RESET + Color.YELLOW + " leggings" + Color.RESET + " are on the ground.",
"a pair of " + Color.GREEN + "pyamite" + Color.RESET + Color.YELLOW + " leggings" + Color.RESET,
false,
0,
60,
true,
Rarity.BASIC,
2900, Sets.<TimeTracker.TimeOfDay>newHashSet()),
PYAMITE_BOOTS(27, Arrays.asList("helmet", "pyamite boots"),
Color.GREEN + "pyamite" + Color.RESET + Color.YELLOW + " boots" + Color.RESET,
"a pair of " + Color.GREEN + "pyamite" + Color.RESET + Color.YELLOW + " boots" + Color.RESET + " are on the ground.",
"a pair of " + Color.GREEN + "pyamite" + Color.RESET + Color.YELLOW + " boots" + Color.RESET,
false,
0,
60,
true,
Rarity.BASIC,
2000, Sets.<TimeTracker.TimeOfDay>newHashSet()),
MARIJUANA(28, Arrays.asList("marijuana", "weed", "m", "w", "f", "flowers"),
Color.GREEN + "marijuana" + Color.RESET + " flowers" + Color.RESET,
"some " + Color.GREEN + "marijuana" + Color.RESET + " flowers" + Color.RESET + " are here on the ground.",
"some " + Color.GREEN + "marijuana" + Color.RESET + " flowers" + Color.RESET,
true,
0,
60,
false,
Rarity.BASIC,
80, Sets.<TimeTracker.TimeOfDay>newHashSet()),
TAPPERHET_SWORD(29, Arrays.asList("sword", "tapperhet sword"),
Color.BOLD_ON + Color.GREEN + "tapperhet" + Color.RESET + Color.YELLOW + " sword" + Color.RESET,
"a " + Color.BOLD_ON + Color.GREEN + "tapperhet" + Color.RESET + Color.YELLOW + " sword" + Color.RESET + " is on the ground.",
"a " + Color.BOLD_ON + Color.GREEN + "tapperhet" + Color.RESET + Color.YELLOW + " sword" + Color.RESET,
false,
0,
60,
true,
Rarity.BASIC,
7000, Sets.<TimeTracker.TimeOfDay>newHashSet()),
VULCERIUM_SWORD(30, Arrays.asList("sword", "vulcerium sword", "vulcerium sword"),
Color.RED + "vulcerium" + Color.RESET + Color.YELLOW + " sword" + Color.RESET,
"a " + Color.RED + "vulcerium" + Color.RESET + Color.YELLOW + " sword" + Color.RESET + " is on the ground.",
"a " + Color.RED + "vulcerium" + Color.RESET + Color.YELLOW + " sword" + Color.RESET,
false,
0,
60,
true,
Rarity.BASIC,
10000, Sets.<TimeTracker.TimeOfDay>newHashSet()),
VULCERIUM_CHESTPLATE(31, Arrays.asList("chestplate", "a vulcerium chestplate", "vulcerium chestplate"),
Color.RED + "vulcerium" + Color.RESET + Color.YELLOW + " chestplate" + Color.RESET,
"a " + Color.RED + "vulcerium" + Color.RESET + Color.YELLOW + " chestplate" + Color.RESET + " is on the ground.",
"a " + Color.RED + "vulcerium" + Color.RESET + Color.YELLOW + " chestplate" + Color.RESET,
false,
0,
60,
true,
Rarity.BASIC,
9000, Sets.<TimeTracker.TimeOfDay>newHashSet()),
VULCERIUM_HELMET(32, Arrays.asList("helmet", "a vulcerium helmet", "vulcerium helmet"),
Color.RED + "vulcerium" + Color.RESET + Color.YELLOW + " helmet" + Color.RESET,
"a " + Color.RED + "vulcerium" + Color.RESET + Color.YELLOW + " helmet" + Color.RESET + " is on the ground.",
"a " + Color.RED + "vulcerium" + Color.RESET + Color.YELLOW + " helmet" + Color.RESET,
false,
0,
60,
true,
Rarity.BASIC,
6000, Sets.<TimeTracker.TimeOfDay>newHashSet()),
VULCERIUM_BRACERS(33, Arrays.asList("bracers", "vulcerium bracers", "vulcerium bracers"),
Color.RED + "vulcerium" + Color.RESET + Color.YELLOW + " bracers" + Color.RESET,
"a pair of " + Color.RED + "vulcerium" + Color.RESET + Color.YELLOW + " bracers" + Color.RESET + " are on the ground.",
"a pair of " + Color.RED + "vulcerium" + Color.RESET + Color.YELLOW + " bracers" + Color.RESET,
false,
0,
60,
true,
Rarity.BASIC,
5900, Sets.<TimeTracker.TimeOfDay>newHashSet()),
VULCERIUM_LEGGINGS(34, Arrays.asList("leggings", "vulcerium leggings", "vulcerium leggings"),
Color.RED + "vulcerium" + Color.RESET + Color.YELLOW + " leggings" + Color.RESET,
"a pair of " + Color.RED + "vulcerium" + Color.RESET + Color.YELLOW + " leggings" + Color.RESET + " are on the ground.",
"a pair of " + Color.RED + "vulcerium" + Color.RESET + Color.YELLOW + " leggings" + Color.RESET,
false,
0,
60,
true,
Rarity.BASIC,
7500, Sets.<TimeTracker.TimeOfDay>newHashSet()),
VULCERIUM_BOOTS(35, Arrays.asList("boots", "vulcerium boots"),
Color.RED + "vulcerium" + Color.RESET + Color.YELLOW + " boots" + Color.RESET,
"a pair of " + Color.RED + "vulcerium" + Color.RESET + Color.YELLOW + " boots" + Color.RESET + " are on the ground.",
"a pair of " + Color.RED + "vulcerium" + Color.RESET + Color.YELLOW + " boots" + Color.RESET,
false,
0,
60,
true,
Rarity.BASIC,
7100, Sets.<TimeTracker.TimeOfDay>newHashSet()),
DWARF_BOOTS_OF_AGILITY(36, Arrays.asList("dwarf boots", "boots"),
Color.BLUE + "dwarf" + Color.RESET + Color.RED + " boots" + Color.RESET,
"a pair of " + Color.BLUE + "dwarf" + Color.RESET + Color.RED + " boots" + Color.RESET + " are on the ground.",
"a pair of " + Color.BLUE + "dwarf" + Color.RESET + Color.RED + " boots" + Color.RESET,
false,
0,
60,
true,
Rarity.UNCOMMON,
2500, Sets.<TimeTracker.TimeOfDay>newHashSet()),
DEATHCRAWLER_SCALES(37, Arrays.asList("deathcrawler scales", "scales"),
Color.BOLD_ON + Color.MAGENTA + "deathcrawler" + Color.RESET + Color.RED + " scales" + Color.RESET,
"some " + Color.BOLD_ON + Color.MAGENTA + "deathcrawler" + Color.RESET + Color.RED + " scales" + Color.RESET + " are on the ground.",
"some " + Color.BOLD_ON + Color.MAGENTA + "deathcrawler" + Color.RESET + Color.RED + " scales" + Color.RESET,
false,
0,
60,
false,
Rarity.BASIC,
700, Sets.<TimeTracker.TimeOfDay>newHashSet()),
DWARVEN_PENDANT(38, Arrays.asList("dwarven pendant", "pendant"),
Color.BOLD_ON + Color.MAGENTA + "dwarven" + Color.RESET + Color.RED + " pendant" + Color.RESET,
"a " + Color.BOLD_ON + Color.MAGENTA + "dwarven" + Color.RESET + Color.RED + " pendant" + Color.RESET + " are on the ground.",
"a " + Color.BOLD_ON + Color.MAGENTA + "dwarven" + Color.RESET + Color.RED + " pendant" + Color.RESET,
false,
0,
60,
false,
Rarity.BASIC,
450, Sets.<TimeTracker.TimeOfDay>newHashSet()),
BYSEN_BALLS(39, Arrays.asList("bysen balls", "balls"),
Color.BOLD_ON + Color.MAGENTA + "bysen" + Color.RESET + Color.RED + " balls" + Color.RESET,
"some " + Color.BOLD_ON + Color.MAGENTA + "bysen" + Color.RESET + Color.RED + " balls" + Color.RESET + " are on the ground.",
"some " + Color.BOLD_ON + Color.MAGENTA + "bysen" + Color.RESET + Color.RED + " balls" + Color.RESET,
false,
0,
60,
false,
Rarity.BASIC,
2000, Sets.<TimeTracker.TimeOfDay>newHashSet()),
PLASMA_TV(40, Arrays.asList("plasma tv", "plasma"),
Color.BOLD_ON + Color.MAGENTA + "plasma" + Color.RESET + Color.RED + " tv" + Color.RESET,
"a " + Color.BOLD_ON + Color.MAGENTA + "plasma" + Color.RESET + Color.RED + " tv" + Color.RESET + " is on the ground.",
"a " + Color.BOLD_ON + Color.MAGENTA + "plasma" + Color.RESET + Color.RED + " tv" + Color.RESET,
false,
0,
60,
false,
Rarity.BASIC,
6000, Sets.<TimeTracker.TimeOfDay>newHashSet()),
DOGDICKS(41, Arrays.asList("dog", "dick", "dog dick"),
Color.GREEN + "dog" + Color.RESET + " dick" + Color.RESET,
"a " + Color.GREEN + "dog" + Color.RESET + " dick" + Color.RESET + " is here on the ground.",
"a " + Color.GREEN + "dog" + Color.RESET + " dick" + Color.RESET,
true,
0,
60,
false,
Rarity.BASIC,
2500, Sets.<TimeTracker.TimeOfDay>newHashSet()),
PURPLE_DRANK(42, Arrays.asList("drank", "purple drank", "p", "purple", "lean", "sizzurp"),
"a double cup of " + MAGENTA + "purple" + RESET + " drank",
"a double cup of " + MAGENTA + "purple" + RESET + " drank rests on the ground.",
"a tonic called " + MAGENTA + "purple" + RESET + " drank that restores 500 health" + RESET,
true,
0,
60,
false,
Rarity.BASIC,
8, Sets.<TimeTracker.TimeOfDay>newHashSet()),
LEATHER_SATCHEL(43, Arrays.asList("leather satchel", "satchel"),
"a " + Color.GREEN + "leather satchel" + Color.RESET,
"a " + Color.GREEN + "leather satchel" + Color.RESET,
"a " + Color.GREEN + "leather satchel" + Color.RESET + " with room to store 10 items.",
false,
0,
60,
true,
Rarity.BASIC,
800, Sets.<TimeTracker.TimeOfDay>newHashSet()),
BIGGERS_SKIN_SATCHEL(44, Arrays.asList("biggers skin satchel", "skin satchel"),
"a " + Color.GREEN + "biggers skin satchel" + Color.RESET,
"a " + Color.GREEN + "biggers skin satchel" + Color.RESET,
"a " + Color.GREEN + "biggers skin satchel" + Color.RESET + " with room to store 100 items.",
false,
0,
60,
true,
Rarity.BASIC,
3000, Sets.<TimeTracker.TimeOfDay>newHashSet()),
STRENGTH_ELIXIR(45, Arrays.asList("strength", "strength elixir", "elixir", "s", "e"),
"an elixir of " + RED + "strength" + RESET,
"an elixir of " + RED + "strength" + RESET + " is in an crystal vessel on the ground.",
"an elixir of " + RED + "strength" + RESET + " that increases your might.",
true,
0,
60,
true,
Rarity.BASIC,
300, Sets.<TimeTracker.TimeOfDay>newHashSet()),
CHRONIC_JOOSE(46, Arrays.asList("chronic", "chronic joose", "joose", "c", "j"),
"an elixir of " + GREEN + "chronic" + RESET + " joose",
"an elixir of " + GREEN + "chronic" + RESET + " joose is in an crystal vessel on the ground.",
"an elixir of " + GREEN + "chronic" + RESET + " joose that increases your chronic-ness.",
true,
0,
60,
true,
Rarity.BASIC,
1000, Sets.<TimeTracker.TimeOfDay>newHashSet()),
BISMUTH_SWORD(47, Arrays.asList("sword", "bismuth sword", "bismuth sword"),
Color.BOLD_ON + Color.MAGENTA + "bismuth" + Color.RESET + Color.YELLOW + " sword" + Color.RESET,
"a " + Color.BOLD_ON + Color.MAGENTA + "bismuth" + Color.RESET + Color.YELLOW + " sword" + Color.RESET + " is on the ground.",
"a " + Color.BOLD_ON + Color.MAGENTA + "bismuth" + Color.RESET + Color.YELLOW + " sword" + Color.RESET,
false,
0,
60,
true,
Rarity.LEGENDARY,
1000000, Sets.<TimeTracker.TimeOfDay>newHashSet()),
BISMUTH_CHESTPLATE(48, Arrays.asList("chestplate", "a bismuth chestplate", "bismuth chestplate"),
Color.BOLD_ON + Color.MAGENTA + "bismuth" + Color.RESET + Color.YELLOW + " chestplate" + Color.RESET,
"a " + Color.BOLD_ON + Color.MAGENTA + "bismuth" + Color.RESET + Color.YELLOW + " chestplate" + Color.RESET + " is on the ground.",
"a " + Color.BOLD_ON + Color.MAGENTA + "bismuth" + Color.RESET + Color.YELLOW + " chestplate" + Color.RESET,
false,
0,
60,
true,
Rarity.LEGENDARY,
800000, Sets.<TimeTracker.TimeOfDay>newHashSet()),
BISMUTH_HELMET(49, Arrays.asList("helmet", "a bismuth helmet", "bismuth helmet"),
Color.BOLD_ON + Color.MAGENTA + "bismuth" + Color.RESET + Color.YELLOW + " helmet" + Color.RESET,
"a " + Color.BOLD_ON + Color.MAGENTA + "bismuth" + Color.RESET + Color.YELLOW + " helmet" + Color.RESET + " is on the ground.",
"a " + Color.BOLD_ON + Color.MAGENTA + "bismuth" + Color.RESET + Color.YELLOW + " helmet" + Color.RESET,
false,
0,
60,
true,
Rarity.LEGENDARY,
700000, Sets.<TimeTracker.TimeOfDay>newHashSet()),
BISMUTH_BRACERS(50, Arrays.asList("bracers", "bismuth bracers", "bismuth bracers"),
Color.BOLD_ON + Color.MAGENTA + "bismuth" + Color.RESET + Color.YELLOW + " bracers" + Color.RESET,
"a pair of " + Color.BOLD_ON + Color.MAGENTA + "bismuth" + Color.RESET + Color.YELLOW + " bracers" + Color.RESET + " are on the ground.",
"a pair of " + Color.BOLD_ON + Color.MAGENTA + "bismuth" + Color.RESET + Color.YELLOW + " bracers" + Color.RESET,
false,
0,
60,
true,
Rarity.LEGENDARY,
650000, Sets.<TimeTracker.TimeOfDay>newHashSet()),
BISMUTH_LEGGINGS(51, Arrays.asList("leggings", "bismuth leggings", "bismuth leggings"),
Color.BOLD_ON + Color.MAGENTA + "bismuth" + Color.RESET + Color.YELLOW + " leggings" + Color.RESET,
"a pair of " + Color.BOLD_ON + Color.MAGENTA + "bismuth" + Color.RESET + Color.YELLOW + " leggings" + Color.RESET + " are on the ground.",
"a pair of " + Color.BOLD_ON + Color.MAGENTA + "bismuth" + Color.RESET + Color.YELLOW + " leggings" + Color.RESET,
false,
0,
60,
true,
Rarity.LEGENDARY,
900000, Sets.<TimeTracker.TimeOfDay>newHashSet()),
BISMUTH_BOOTS(52, Arrays.asList("boots", "bismuth boots"),
Color.BOLD_ON + Color.MAGENTA + "bismuth" + Color.RESET + Color.YELLOW + " boots" + Color.RESET,
"a pair of " + Color.BOLD_ON + Color.MAGENTA + "bismuth" + Color.RESET + Color.YELLOW + " boots" + Color.RESET + " are on the ground.",
"a pair of " + Color.BOLD_ON + Color.MAGENTA + "bismuth" + Color.RESET + Color.YELLOW + " boots" + Color.RESET,
false,
0,
60,
true,
Rarity.RARE,
800000, Sets.<TimeTracker.TimeOfDay>newHashSet()),
GUCCI_PANTS(53, Arrays.asList("pants", "gucci pants", "gucci pants"),
Color.BOLD_ON + Color.CYAN + "gucci" + Color.RESET + Color.YELLOW + " pants" + Color.RESET,
"a " + Color.BOLD_ON + Color.CYAN + "gucci" + Color.RESET + Color.YELLOW + " pants" + Color.RESET + " is on the ground.",
"a " + Color.BOLD_ON + Color.CYAN + "gucci" + Color.RESET + Color.YELLOW + " pants" + Color.RESET,
false,
0,
60,
true,
Rarity.EXOTIC,
40000000, Sets.<TimeTracker.TimeOfDay>newHashSet()),
HAZE(54, Arrays.asList("haze", "lemon", "h", "l"),
Color.BOLD_ON + Color.YELLOW + "lemon" + Color.RESET + Color.GREEN + " haze" + Color.RESET,
"some " + Color.BOLD_ON + Color.YELLOW + "lemon" + Color.RESET + Color.GREEN + " haze" + Color.RESET + " flowers" + Color.RESET + " are here on the ground.",
"some " + Color.BOLD_ON + Color.YELLOW + "lemon" + Color.RESET + Color.GREEN + " haze" + Color.RESET + " flowers" + Color.RESET,
true,
0,
60,
false,
Rarity.RARE,
5000, Sets.<TimeTracker.TimeOfDay>newHashSet()),
YETI_CLAW(55, Arrays.asList("yeti claw", "yeti"),
Color.BOLD_ON + "yeti" + Color.RESET + Color.RED + " claw" + Color.RESET,
"a " + Color.BOLD_ON + "yeti" + Color.RESET + Color.RED + " claw" + Color.RESET + " is on the ground.",
"a " + Color.BOLD_ON + "yeti" + Color.RESET + Color.RED + " claw" + Color.RESET,
false,
0,
60,
false,
Rarity.LEGENDARY,
1100000, Sets.<TimeTracker.TimeOfDay>newHashSet()),
CRYSTAL_DAGGER(56, Arrays.asList("crystal dagger", "dagger"),
Color.BOLD_ON + Color.CYAN + "crystal" + Color.RESET + Color.RED + " dagger" + Color.RESET,
"a " + Color.BOLD_ON + Color.CYAN + "crystal" + Color.RESET + Color.RED + " dagger" + Color.RESET + " is on the ground.",
"a " + Color.BOLD_ON + Color.CYAN + "crystal" + Color.RESET + Color.RED + " dagger" + Color.RESET,
false,
0,
60,
false,
Rarity.LEGENDARY,
1400000, Sets.<TimeTracker.TimeOfDay>newHashSet()),
GOLDEN_WAND(57, Arrays.asList("golden wand", "golden"),
Color.BOLD_ON + Color.YELLOW + "golden" + Color.RESET + Color.RED + " wand" + Color.RESET,
"a " + Color.BOLD_ON + Color.YELLOW + "golden" + Color.RESET + Color.RED + " wand" + Color.RESET + " is on the ground.",
"a " + Color.BOLD_ON + Color.YELLOW + "golden" + Color.RESET + Color.RED + " wand" + Color.RESET,
false,
0,
60,
false,
Rarity.LEGENDARY,
1200000, Sets.<TimeTracker.TimeOfDay>newHashSet()),
GLOWING_ORB(58, Arrays.asList("glowing orb", "orb"),
Color.BOLD_ON + "glowing" + Color.RESET + Color.CYAN + " orb" + Color.RESET,
"a " + Color.BOLD_ON + "glowing" + Color.RESET + Color.CYAN + " orb" + Color.RESET + " is on the ground.",
"a " + Color.BOLD_ON + "glowing" + Color.RESET + Color.CYAN + " orb" + Color.RESET,
false,
0,
60,
false,
Rarity.LEGENDARY,
1000000, Sets.<TimeTracker.TimeOfDay>newHashSet()),
WOODEN_CHEST(59, Arrays.asList("wooden chest", "chest"),
Color.BOLD_ON + "wooden" + Color.RESET + Color.RED + " chest" + Color.RESET,
"a " + Color.BOLD_ON + "wooden" + Color.RESET + Color.RED + " chest" + Color.RESET + " is on the ground.",
"a " + Color.BOLD_ON + "wooden" + Color.RESET + Color.RED + " chest" + Color.RESET,
false,
0,
60,
false,
Rarity.LEGENDARY,
1100000, Sets.<TimeTracker.TimeOfDay>newHashSet()),
ENCHANTED_SHIELD(60, Arrays.asList("enchanted shield", "enchanted"),
Color.BOLD_ON + Color.CYAN + "enchanted" + Color.RESET + Color.CYAN + " shield" + Color.RESET,
"a " + Color.BOLD_ON + Color.CYAN + "enchanted" + Color.RESET + Color.CYAN + " shield" + Color.RESET + " is on the ground.",
"a " + Color.BOLD_ON + Color.CYAN + "enchanted" + Color.RESET + Color.CYAN + " shield" + Color.RESET,
false,
0,
60,
false,
Rarity.EXOTIC,
50000000, Sets.<TimeTracker.TimeOfDay>newHashSet()),
AMETHYST_VIAL(61, Arrays.asList("amethyst vial", "vial"),
Color.BOLD_ON + Color.MAGENTA + "amethyst" + Color.RESET + Color.CYAN + " vial" + Color.RESET,
"a " + Color.BOLD_ON + Color.MAGENTA + "amethyst" + Color.RESET + Color.CYAN + " vial" + Color.RESET + " is on the ground.",
"a " + Color.BOLD_ON + Color.MAGENTA + "amethyst" + Color.RESET + Color.CYAN + " vial" + Color.RESET,
false,
0,
60,
false,
Rarity.LEGENDARY,
1500000, Sets.<TimeTracker.TimeOfDay>newHashSet()),
AMETHYST_RING(62, Arrays.asList("amethyst ring", "ring"),
Color.BOLD_ON + Color.MAGENTA + "amethyst" + Color.RESET + Color.CYAN + " ring" + Color.RESET,
"a " + Color.BOLD_ON + Color.MAGENTA + "amethyst" + Color.RESET + Color.CYAN + " ring" + Color.RESET + " is on the ground.",
"a " + Color.BOLD_ON + Color.MAGENTA + "amethyst" + Color.RESET + Color.CYAN + " ring" + Color.RESET,
false,
0,
60,
false,
Rarity.LEGENDARY,
1800000, Sets.<TimeTracker.TimeOfDay>newHashSet()),
VULCERIUM_CHAIN(63, Arrays.asList("vulcerium chain", "chain"),
Color.RED + "vulcerium" + Color.RESET + Color.CYAN + " chain" + Color.RESET,
"a " + Color.RED + "vulcerium" + Color.RESET + Color.CYAN + " chain" + Color.RESET + " is on the ground.",
"a " + Color.RED + "vulcerium" + Color.RESET + Color.CYAN + " chain" + Color.RESET,
false,
0,
60,
false,
Rarity.LEGENDARY,
3000000, Sets.<TimeTracker.TimeOfDay>newHashSet()),
LION_TAIL(64, Arrays.asList("lion tail", "tail"),
Color.BOLD_ON + "lion" + Color.RESET + Color.RED + " tail" + Color.RESET,
"a " + Color.BOLD_ON + "lion" + Color.RESET + Color.RED + " tail" + Color.RESET + " is on the ground.",
"a " + Color.BOLD_ON + "lion" + Color.RESET + Color.RED + " tail" + Color.RESET,
false,
0,
60,
false,
Rarity.LEGENDARY,
2200000, Sets.<TimeTracker.TimeOfDay>newHashSet()),
SOLAR_PENDANT(65, Arrays.asList("solar pendant", "pendant"),
Color.BOLD_ON + Color.YELLOW + "solar" + Color.RESET + " pendant" + Color.RESET,
"a " + Color.BOLD_ON + "solar" + Color.RESET + " pendant" + Color.RESET + " is on the ground.",
"a " + Color.BOLD_ON + "solar" + Color.RESET + " pendant" + Color.RESET,
false,
0,
60,
false,
Rarity.LEGENDARY,
1700000, Sets.<TimeTracker.TimeOfDay>newHashSet()),
SILVER_STAR(66, Arrays.asList("silver star", "star"),
Color.BOLD_ON + "silver" + Color.RESET + Color.CYAN + " star" + Color.RESET,
"a " + Color.BOLD_ON + "silver" + Color.RESET + Color.CYAN + " star" + Color.RESET + " is on the ground.",
"a " + Color.BOLD_ON + "silver" + Color.RESET + Color.CYAN + " star" + Color.RESET,
false,
0,
60,
false,
Rarity.LEGENDARY,
1500000, Sets.<TimeTracker.TimeOfDay>newHashSet()),
GOLDEN_AXE(67, Arrays.asList("golden axe", "axe"),
Color.BOLD_ON + Color.YELLOW + "golden" + Color.RESET + Color.CYAN + " axe" + Color.RESET,
"a " + Color.BOLD_ON + Color.YELLOW + "golden" + Color.RESET + Color.CYAN + " axe" + Color.RESET + " is on the ground.",
"a " + Color.BOLD_ON + Color.YELLOW + "golden" + Color.RESET + Color.CYAN + " axe" + Color.RESET,
false,
0,
60,
false,
Rarity.LEGENDARY,
5000000, Sets.<TimeTracker.TimeOfDay>newHashSet()),
GOLDEN_PRISM(68, Arrays.asList("golden prism", "prism"),
Color.BOLD_ON + Color.YELLOW + "golden" + Color.RESET + Color.CYAN + " prism" + Color.RESET,
"a " + Color.BOLD_ON + Color.YELLOW + "golden" + Color.RESET + Color.CYAN + " prism" + Color.RESET + " is on the ground.",
"a " + Color.BOLD_ON + Color.YELLOW + "golden" + Color.RESET + Color.CYAN + " prism" + Color.RESET,
false,
0,
60,
false,
Rarity.EXOTIC,
100000000, Sets.<TimeTracker.TimeOfDay>newHashSet()),
OBSIDIAN_BLADE(69, Arrays.asList("obsidian blade", "blade"),
Color.BOLD_ON + Color.BLUE + "obsidian" + Color.RESET + Color.CYAN + " blade" + Color.RESET,
"a " + Color.BOLD_ON + Color.BLUE + "obsidian" + Color.RESET + Color.CYAN + " blade" + Color.RESET + " is on the ground.",
"a " + Color.BOLD_ON + Color.BLUE + "obsidian" + Color.RESET + Color.CYAN + " blade" + Color.RESET,
false,
0,
60,
false,
Rarity.LEGENDARY,
4000000, Sets.<TimeTracker.TimeOfDay>newHashSet()),
BOOK_OF_THORBRAND(70, Arrays.asList("Book of Thorbrand", "book", "Book"),
Color.BOLD_ON + Color.YELLOW + "Book" + Color.RESET + " of" + Color.CYAN + " Thorbrand" + Color.RESET,
"a " + Color.BOLD_ON + Color.YELLOW + "Book" + Color.RESET + " of" + Color.CYAN + " Thorbrand" + Color.RESET + " is on the ground.",
"a " + Color.BOLD_ON + Color.YELLOW + "Book" + Color.RESET + " of" + Color.CYAN + " Thorbrand" + Color.RESET,
false,
0,
60,
false,
Rarity.LEGENDARY,
5000000, Sets.<TimeTracker.TimeOfDay>newHashSet()),
GOLDEN_HARP(71, Arrays.asList("golden harp", "harp"),
Color.BOLD_ON + Color.YELLOW + "golden" + Color.RESET + Color.CYAN + " harp" + Color.RESET,
"a " + Color.BOLD_ON + Color.YELLOW + "golden" + Color.RESET + Color.CYAN + " harp" + Color.RESET + " is on the ground.",
"a " + Color.BOLD_ON + Color.YELLOW + "golden" + Color.RESET + Color.CYAN + " harp" + Color.RESET,
false,
0,
60,
false,
Rarity.LEGENDARY,
5000000, Sets.<TimeTracker.TimeOfDay>newHashSet()),
SILK_SCROLL(72, Arrays.asList("silk scroll", "scroll"),
Color.BOLD_ON + Color.WHITE + "silk" + Color.RESET + Color.CYAN + " scroll" + Color.RESET,
"a " + Color.BOLD_ON + Color.WHITE + "silk" + Color.RESET + Color.CYAN + " scroll" + Color.RESET + " is on the ground.",
"a " + Color.BOLD_ON + Color.WHITE + "silk" + Color.RESET + Color.CYAN + " scroll" + Color.RESET,
false,
0,
60,
false,
Rarity.LEGENDARY,
5300000, Sets.<TimeTracker.TimeOfDay>newHashSet()),
BLACK_TRUFFLE(73, Arrays.asList("black truffle", "truffle"),
Color.BOLD_ON + Color.BLUE + "black" + Color.RESET + Color.WHITE + Color.BOLD_ON + " truffle" + Color.RESET,
"a " + Color.BOLD_ON + Color.BLUE + "black" + Color.RESET + Color.WHITE + Color.BOLD_ON + " truffle" + Color.RESET + " is on the ground.",
"a " + Color.BOLD_ON + Color.BLUE + "black" + Color.RESET + Color.WHITE + Color.BOLD_ON + " truffle" + Color.RESET,
false,
0,
60,
false,
Rarity.LEGENDARY,
6000000, Sets.<TimeTracker.TimeOfDay>newHashSet()),
EMERALD_STATUE(74, Arrays.asList("emerald statue", "statue"),
Color.BOLD_ON + Color.GREEN + "emerald" + Color.RESET + Color.CYAN + " statue" + Color.RESET,
"a " + Color.BOLD_ON + Color.GREEN + "emerald" + Color.RESET + Color.CYAN + " statue" + Color.RESET + " is on the ground.",
"a " + Color.BOLD_ON + Color.GREEN + "emerald" + Color.RESET + Color.CYAN + " statue" + Color.RESET,
false,
0,
60,
false,
Rarity.LEGENDARY,
7000000, Sets.<TimeTracker.TimeOfDay>newHashSet()),
DEMONIC_TALISMAN(75, Arrays.asList("demonic talisman", "talisman"),
Color.BOLD_ON + Color.RED + "demonic" + Color.RESET + Color.CYAN + " talisman" + Color.RESET,
"a " + Color.BOLD_ON + Color.RED + "demonic" + Color.RESET + Color.CYAN + " talisman" + Color.RESET + " is on the ground.",
"a " + Color.BOLD_ON + Color.RED + "demonic" + Color.RESET + Color.CYAN + " talisman" + Color.RESET,
false,
0,
60,
false,
Rarity.LEGENDARY,
8000000, Sets.<TimeTracker.TimeOfDay>newHashSet()),
EYE_OF_NJAL(76, Arrays.asList("Eye of Njal", "Eye", "eye"),
Color.BOLD_ON + Color.WHITE + "Eye" + Color.RESET + " of" + Color.RED + " Njal" + Color.RESET,
"a " + Color.BOLD_ON + Color.WHITE + "Eye" + Color.RESET + " of" + Color.RED + " Njal" + Color.RESET + " is on the ground.",
"a " + Color.BOLD_ON + Color.WHITE + "Eye" + Color.RESET + " of" + Color.RED + " Njal" + Color.RESET,
false,
0,
60,
false,
Rarity.LEGENDARY,
8000000, Sets.<TimeTracker.TimeOfDay>newHashSet()),
VALGARD_STONE(77, Arrays.asList("Valgard stone", "stone"),
Color.BOLD_ON + Color.YELLOW + "Valgard" + Color.RESET + Color.CYAN + " stone" + Color.RESET,
"a " + Color.BOLD_ON + Color.YELLOW + "Valgard" + Color.RESET + Color.CYAN + " stone" + Color.RESET + " is on the ground.",
"a " + Color.BOLD_ON + Color.YELLOW + "Valgard" + Color.RESET + Color.CYAN + " stone" + Color.RESET,
false,
0,
60,
false,
Rarity.LEGENDARY,
8300000, Sets.<TimeTracker.TimeOfDay>newHashSet()),
BLOODSTONE(78, Arrays.asList("bloodstone", "stone"),
Color.BOLD_ON + Color.RED + "bloodstone" + Color.RESET,
"a " + Color.BOLD_ON + Color.RED + "bloodstone" + Color.RESET + " is on the ground.",
"a " + Color.BOLD_ON + Color.RED + "bloodstone" + Color.RESET,
false,
0,
60,
false,
Rarity.LEGENDARY,
8500000, Sets.<TimeTracker.TimeOfDay>newHashSet()),
HORN_OF_KOLSKEGG(79, Arrays.asList("Horn of Kolskegg", "Horn", "horn"),
Color.BOLD_ON + Color.YELLOW + "Horn" + Color.RESET + " of" + Color.CYAN + " Kolskegg" + Color.RESET,
"a " + Color.BOLD_ON + Color.YELLOW + "Horn" + Color.RESET + " of" + Color.CYAN + " Kolskegg" + Color.RESET + " is on the ground.",
"a " + Color.BOLD_ON + Color.YELLOW + "Horn" + Color.RESET + " of" + Color.CYAN + " Kolskegg" + Color.RESET,
false,
0,
60,
false,
Rarity.LEGENDARY,
12000000, Sets.<TimeTracker.TimeOfDay>newHashSet()),
ANCIENT_RUNESTONE(80, Arrays.asList("ancient runestone", "runestone"),
Color.BOLD_ON + Color.YELLOW + "ancient" + Color.RESET + Color.WHITE + Color.BOLD_ON + " runestone" + Color.RESET,
"a " + Color.BOLD_ON + Color.YELLOW + "ancient" + Color.RESET + Color.WHITE + Color.BOLD_ON + " runestone" + Color.RESET + " is on the ground.",
"a " + Color.BOLD_ON + Color.YELLOW + "ancient" + Color.RESET + Color.WHITE + Color.BOLD_ON + " runestone" + Color.RESET,
false,
0,
60,
false,
Rarity.LEGENDARY,
15000000, Sets.<TimeTracker.TimeOfDay>newHashSet()),
AEGIRS_PIPE(81, Arrays.asList("Aegirs pipe", "pipe"),
Color.BOLD_ON + Color.YELLOW + "Aegirs" + Color.RESET + Color.CYAN + " pipe" + Color.RESET,
"a " + Color.BOLD_ON + Color.YELLOW + "Aegirs" + Color.RESET + Color.CYAN + " pipe" + Color.RESET + " is on the ground.",
"a " + Color.BOLD_ON + Color.YELLOW + "Aegirs" + Color.RESET + Color.CYAN + " pipe" + Color.RESET,
false,
0,
60,
false,
Rarity.LEGENDARY,
15000000, Sets.<TimeTracker.TimeOfDay>newHashSet()),
SERPENT_IDOL(82, Arrays.asList("serpent idol", "idol"),
Color.BOLD_ON + Color.MAGENTA + "serpent" + Color.RESET + Color.CYAN + " idol" + Color.RESET,
"a " + Color.BOLD_ON + Color.MAGENTA + "serpent" + Color.RESET + Color.CYAN + " idol" + Color.RESET + " is on the ground.",
"a " + Color.BOLD_ON + Color.MAGENTA + "serpent" + Color.RESET + Color.CYAN + " idol" + Color.RESET,
false,
0,
60,
false,
Rarity.LEGENDARY,
20000000, Sets.<TimeTracker.TimeOfDay>newHashSet()),
SORCERORS_MONOCLE(83, Arrays.asList("Sorcerors monocle", "monocle"),
Color.BOLD_ON + Color.RED + "Sorcerors" + Color.RESET + Color.WHITE + " monocle" + Color.RESET,
"a " + Color.BOLD_ON + Color.RED + "Sorcerors" + Color.RESET + Color.WHITE + " monocle" + Color.RESET + " is on the ground.",
"a " + Color.BOLD_ON + Color.RED + "Sorcerors" + Color.RESET + Color.WHITE + " monocle" + Color.RESET,
false,
0,
60,
false,
Rarity.LEGENDARY,
20000000, Sets.<TimeTracker.TimeOfDay>newHashSet()),
SPIDER_FANG(84, Arrays.asList("spider fang", "fang"),
Color.BOLD_ON + Color.YELLOW + "spider" + Color.RESET + Color.RED + " fang" + Color.RESET,
"a " + Color.BOLD_ON + Color.YELLOW + "spider" + Color.RESET + Color.RED + " fang" + Color.RESET + " is on the ground.",
"a " + Color.BOLD_ON + Color.YELLOW + "spider" + Color.RESET + Color.RED + " fang" + Color.RESET,
false,
0,
60,
false,
Rarity.LEGENDARY,
25000000, Sets.<TimeTracker.TimeOfDay>newHashSet()),
SPIDERSILK_POUCH(85, Arrays.asList("spidersilk pouch", "pouch"),
Color.BOLD_ON + Color.YELLOW + "spidersilk" + Color.RESET + Color.CYAN + " pouch" + Color.RESET,
"a " + Color.BOLD_ON + Color.YELLOW + "spidersilk" + Color.RESET + Color.CYAN + " pouch" + Color.RESET + " is on the ground.",
"a " + Color.BOLD_ON + Color.YELLOW + "spidersilk" + Color.RESET + Color.CYAN + " pouch" + Color.RESET,
false,
0,
60,
false,
Rarity.LEGENDARY,
30000000, Sets.<TimeTracker.TimeOfDay>newHashSet()),
CRYSTAL_SPIDER(86, Arrays.asList("crystal spider", "spider"),
Color.BOLD_ON + Color.CYAN + "crystal" + Color.RESET + Color.RED + " spider" + Color.RESET,
"a " + Color.BOLD_ON + Color.CYAN + "crystal" + Color.RESET + Color.RED + " spider" + Color.RESET + " is on the ground.",
"a " + Color.BOLD_ON + Color.CYAN + "crystal" + Color.RESET + Color.RED + " spider" + Color.RESET,
false,
0,
60,
false,
Rarity.LEGENDARY,
32000000, Sets.<TimeTracker.TimeOfDay>newHashSet()),
AEXIUM_SWORD(87, Arrays.asList("sword", "aexium sword", "aexium sword"),
Color.BOLD_ON + Color.CYAN + "aexium" + Color.RESET + Color.YELLOW + " sword" + Color.RESET,
"a " + Color.BOLD_ON + Color.CYAN + "aexium" + Color.RESET + Color.YELLOW + " sword" + Color.RESET + " is on the ground.",
"a " + Color.BOLD_ON + Color.CYAN + "aexium" + Color.RESET + Color.YELLOW + " sword" + Color.RESET,
false,
0,
60,
true,
Rarity.LEGENDARY,
2000000, Sets.<TimeTracker.TimeOfDay>newHashSet()),
AEXIUM_CHESTPLATE(88, Arrays.asList("chestplate", "a aexium chestplate", "aexium chestplate"),
Color.BOLD_ON + Color.CYAN + "aexium" + Color.RESET + Color.YELLOW + " chestplate" + Color.RESET,
"a " + Color.BOLD_ON + Color.CYAN + "aexium" + Color.RESET + Color.YELLOW + " chestplate" + Color.RESET + " is on the ground.",
"a " + Color.BOLD_ON + Color.CYAN + "aexium" + Color.RESET + Color.YELLOW + " chestplate" + Color.RESET,
false,
0,
60,
true,
Rarity.LEGENDARY,
1800000, Sets.<TimeTracker.TimeOfDay>newHashSet()),
AEXIUM_HELMET(89, Arrays.asList("helmet", "a aexium helmet", "aexium helmet"),
Color.BOLD_ON + Color.CYAN + "aexium" + Color.RESET + Color.YELLOW + " helmet" + Color.RESET,
"a " + Color.BOLD_ON + Color.CYAN + "aexium" + Color.RESET + Color.YELLOW + " helmet" + Color.RESET + " is on the ground.",
"a " + Color.BOLD_ON + Color.CYAN + "aexium" + Color.RESET + Color.YELLOW + " helmet" + Color.RESET,
false,
0,
60,
true,
Rarity.LEGENDARY,
1700000, Sets.<TimeTracker.TimeOfDay>newHashSet()),
AEXIUM_BRACERS(90, Arrays.asList("bracers", "aexium bracers", "aexium bracers"),
Color.BOLD_ON + Color.CYAN + "aexium" + Color.RESET + Color.YELLOW + " bracers" + Color.RESET,
"a pair of " + Color.BOLD_ON + Color.CYAN + "aexium" + Color.RESET + Color.YELLOW + " bracers" + Color.RESET + " are on the ground.",
"a pair of " + Color.BOLD_ON + Color.CYAN + "aexium" + Color.RESET + Color.YELLOW + " bracers" + Color.RESET,
false,
0,
60,
true,
Rarity.LEGENDARY,
1650000, Sets.<TimeTracker.TimeOfDay>newHashSet()),
AEXIUM_LEGGINGS(91, Arrays.asList("leggings", "aexium leggings", "aexium leggings"),
Color.BOLD_ON + Color.CYAN + "aexium" + Color.RESET + Color.YELLOW + " leggings" + Color.RESET,
"a pair of " + Color.BOLD_ON + Color.CYAN + "aexium" + Color.RESET + Color.YELLOW + " leggings" + Color.RESET + " are on the ground.",
"a pair of " + Color.BOLD_ON + Color.CYAN + "aexium" + Color.RESET + Color.YELLOW + " leggings" + Color.RESET,
false,
0,
60,
true,
Rarity.LEGENDARY,
1900000, Sets.<TimeTracker.TimeOfDay>newHashSet()),
AEXIUM_BOOTS(92, Arrays.asList("boots", "aexium boots"),
Color.BOLD_ON + Color.CYAN + "aexium" + Color.RESET + Color.YELLOW + " boots" + Color.RESET,
"a pair of " + Color.BOLD_ON + Color.CYAN + "aexium" + Color.RESET + Color.YELLOW + " boots" + Color.RESET + " are on the ground.",
"a pair of " + Color.BOLD_ON + Color.CYAN + "aexium" + Color.RESET + Color.YELLOW + " boots" + Color.RESET,
false,
0,
60,
true,
Rarity.RARE,
1800000, Sets.<TimeTracker.TimeOfDay>newHashSet()),
AEXIRIAN_ROOT(93, Arrays.asList("aexirian", "root", "a", "r", "aexirian root"),
Color.GREEN + "aexirian" + Color.RESET + " root" + Color.RESET,
"an " + Color.GREEN + "aexirian" + Color.RESET + " root" + Color.RESET + " is here on the ground.",
"an " + Color.GREEN + "aexirian" + Color.RESET + " root" + Color.RESET,
true,
0,
60,
false,
Rarity.BASIC,
80, Sets.<TimeTracker.TimeOfDay>newHashSet()),
MITHAEM_LEAF(94, Arrays.asList("mithaem", "leaf", "m", "l", "mithaem leaf"),
Color.GREEN + "mithaem" + Color.RESET + " leaf" + Color.RESET,
"a " + Color.GREEN + "mithaem" + Color.RESET + " leaf" + Color.RESET + " is here on the ground.",
"a " + Color.GREEN + "mithaem" + Color.RESET + " leaf" + Color.RESET,
true,
0,
60,
false,
Rarity.BASIC,
80, Sets.<TimeTracker.TimeOfDay>newHashSet()),
DURICCA_ROOT(95, Arrays.asList("duricca", "root", "d", "r", "duricca root"),
Color.GREEN + "duricca" + Color.RESET + " root" + Color.RESET,
"a " + Color.GREEN + "duricca" + Color.RESET + " root" + Color.RESET + " is here on the ground.",
"a " + Color.GREEN + "duricca" + Color.RESET + " root" + Color.RESET,
true,
0,
60,
false,
Rarity.BASIC,
80, Sets.<TimeTracker.TimeOfDay>newHashSet()),
PONDESEL_BERRY(96, Arrays.asList("pondesel", "berry", "p", "b", "pondesel berry"),
Color.GREEN + "pondesel" + Color.RESET + " berry" + Color.RESET,
"a " + Color.GREEN + "pondesel" + Color.RESET + " berry" + Color.RESET + " is here on the ground.",
"a " + Color.GREEN + "pondesel" + Color.RESET + " berry" + Color.RESET,
true,
0,
60,
false,
Rarity.BASIC,
80, Sets.<TimeTracker.TimeOfDay>newHashSet()),
VIKALIONUS_CAP(97, Arrays.asList("vikalionus", "cap", "v", "c", "vikalionus cap"),
Color.GREEN + "vikalionus" + Color.RESET + " cap" + Color.RESET,
"a " + Color.GREEN + "vikalionus" + Color.RESET + " cap" + Color.RESET + " is here on the ground.",
"a " + Color.GREEN + "vikalionus" + Color.RESET + " cap" + Color.RESET,
true,
0,
60,
false,
Rarity.BASIC,
80, Sets.<TimeTracker.TimeOfDay>newHashSet()),
LOORNS_LACE(98, Arrays.asList("loorn's", "lace", "l", "loorn's lace"),
Color.GREEN + "loorn's" + Color.RESET + " lace" + Color.RESET,
"some " + Color.GREEN + "loorn's" + Color.RESET + " lace" + Color.RESET + " is here on the ground.",
"some " + Color.GREEN + "loorn's" + Color.RESET + " lace" + Color.RESET,
true,
0,
60,
false,
Rarity.BASIC,
80, Sets.<TimeTracker.TimeOfDay>newHashSet()),
TOURNEARES_LEAF(99, Arrays.asList("tourneares", "leaf", "t", "l", "tourneares leaf"),
Color.GREEN + "tourneares" + Color.RESET + " leaf" + Color.RESET,
"a " + Color.GREEN + "tourneares" + Color.RESET + " leaf" + Color.RESET + " is here on the ground.",
"a " + Color.GREEN + "tourneares" + Color.RESET + " leaf" + Color.RESET,
true,
0,
60,
false,
Rarity.BASIC,
80, Sets.<TimeTracker.TimeOfDay>newHashSet()),
HAUSSIAN_BERRY(100, Arrays.asList("haussian", "berry", "h", "b", "haussian berry"),
Color.GREEN + "haussian" + Color.RESET + " berry" + Color.RESET,
"a " + Color.GREEN + "haussian" + Color.RESET + " berry" + Color.RESET + " is here on the ground.",
"a " + Color.GREEN + "haussian" + Color.RESET + " berry" + Color.RESET,
true,
0,
60,
false,
Rarity.BASIC,
80, Sets.<TimeTracker.TimeOfDay>newHashSet()),
PERTILLIUM_ROOT(101, Arrays.asList("pertillium", "root", "p", "r", "pertillium root"),
Color.GREEN + "pertillium" + Color.RESET + " root" + Color.RESET,
"some " + Color.GREEN + "pertillium" + Color.RESET + " root" + Color.RESET + " is here on the ground.",
"some " + Color.GREEN + "pertillium" + Color.RESET + " root" + Color.RESET,
true,
0,
60,
false,
Rarity.BASIC,
80, Sets.<TimeTracker.TimeOfDay>newHashSet()),
HYCIANTHIS_BARK(102, Arrays.asList("hycianthis", "bark", "h", "b", "hycianthis bark"),
Color.GREEN + "hycianthis" + Color.RESET + " bark" + Color.RESET,
"some " + Color.GREEN + "hycianthis" + Color.RESET + " bark" + Color.RESET + " is here on the ground.",
"some " + Color.GREEN + "hycianthis" + Color.RESET + " bark" + Color.RESET,
true,
0,
60,
false,
Rarity.BASIC,
80, Sets.<TimeTracker.TimeOfDay>newHashSet()),
PUNILARE_FERN(103, Arrays.asList("punilare", "fern", "p", "f", "punilare fern"),
Color.GREEN + "punilare" + Color.RESET + " fern" + Color.RESET,
"a " + Color.GREEN + "punilare" + Color.RESET + " fern" + Color.RESET + " is here on the ground.",
"a " + Color.GREEN + "punilare" + Color.RESET + " fern" + Color.RESET,
true,
0,
60,
false,
Rarity.BASIC,
80, Sets.<TimeTracker.TimeOfDay>newHashSet()),
KEAKIAR_CAP(104, Arrays.asList("keakiar", "cap", "k", "c", "keakiar cap"),
Color.GREEN + "keakiar" + Color.RESET + " flowers" + Color.RESET,
"a " + Color.GREEN + "keakiar" + Color.RESET + " cap" + Color.RESET + " is here on the ground.",
"a " + Color.GREEN + "keakiar" + Color.RESET + " cap" + Color.RESET,
true,
0,
60,
false,
Rarity.BASIC,
80, Sets.<TimeTracker.TimeOfDay>newHashSet()),
DIRTY_BOMB(105, Arrays.asList("dirty bomb", "bomb"),
Color.YELLOW + "dirty" + Color.RESET + " bomb" + Color.RESET,
"a " + Color.YELLOW + "dirty" + Color.RESET + " bomb" + Color.RESET + " is here on the ground.",
"a " + Color.YELLOW + "dirty" + Color.RESET + " bomb" + Color.RESET,
true,
0,
60,
false,
Rarity.LEGENDARY,
4000000, Sets.<TimeTracker.TimeOfDay>newHashSet()),
JADE_FLASK(106, Arrays.asList("jade flask", "jade", "flask", "j", "f"),
Color.BOLD_ON + Color.GREEN + "jade" + Color.RESET + Color.WHITE + " flask" + Color.RESET,
"a " + Color.BOLD_ON + Color.GREEN + "jade" + Color.RESET + Color.WHITE + " flask" + Color.RESET + " is on the ground.",
"a " + Color.BOLD_ON + Color.GREEN + "jade" + Color.RESET + Color.WHITE + " flask" + Color.RESET,
false,
0,
60,
false,
Rarity.LEGENDARY,
8000000, Sets.<TimeTracker.TimeOfDay>newHashSet()),
HYCIANTHIS_FLUTE(107, Arrays.asList("hycianthis flute", "flute", "h", "f", "hycianthis"),
Color.BOLD_ON + Color.GREEN + "hycianthis" + Color.RESET + Color.RED + " flute" + Color.RESET,
"a " + Color.BOLD_ON + Color.GREEN + "hycianthis" + Color.RESET + Color.RED + " flute" + Color.RESET + " is on the ground.",
"a " + Color.BOLD_ON + Color.GREEN + "hycianthis" + Color.RESET + Color.RED + " flute" + Color.RESET,
false,
0,
60,
false,
Rarity.LEGENDARY,
8000000, Sets.<TimeTracker.TimeOfDay>newHashSet()),
CURSED_MIRROR(108, Arrays.asList("cursed", "mirror", "m", "c", "cursed mirror"),
Color.BOLD_ON + Color.RED + "cursed" + Color.RESET + Color.CYAN + " mirror" + Color.RESET,
"a " + Color.BOLD_ON + Color.RED + "cursed" + Color.RESET + Color.CYAN + " mirror" + Color.RESET + " is on the ground.",
"a " + Color.BOLD_ON + Color.RED + "cursed" + Color.RESET + Color.CYAN + " mirror" + Color.RESET,
false,
0,
60,
false,
Rarity.LEGENDARY,
8000000, Sets.<TimeTracker.TimeOfDay>newHashSet()),
IVORY_DART(109, Arrays.asList("ivory dart", "dart", "i", "d", "ivory"),
Color.BOLD_ON + Color.WHITE + "ivory" + Color.RESET + Color.MAGENTA + " dart" + Color.RESET,
"a " + Color.BOLD_ON + Color.WHITE + "ivory" + Color.RESET + Color.MAGENTA + " dart" + Color.RESET + " is on the ground.",
"a " + Color.BOLD_ON + Color.WHITE + "ivory" + Color.RESET + Color.MAGENTA + " dart" + Color.RESET,
false,
0,
60,
false,
Rarity.LEGENDARY,
8000000, Sets.<TimeTracker.TimeOfDay>newHashSet()),
VULCERIUM_ICEAXE(110, Arrays.asList("vulcerium ice axe", "ice axe", "axe", "v", "ice", "a"),
Color.BOLD_ON + Color.RED + "vulcerium" + Color.RESET + Color.CYAN + " ice " + Color.RESET + "axe",
"a " + Color.BOLD_ON + Color.RED + "vulcerium" + Color.RESET + Color.CYAN + " ice " + Color.RESET + "axe is on the ground.",
"a " + Color.BOLD_ON + Color.RED + "vulcerium" + Color.RESET + Color.CYAN + " ice " + Color.RESET + "axe",
false,
0,
60,
false,
Rarity.LEGENDARY,
8000000, Sets.<TimeTracker.TimeOfDay>newHashSet()),
HELGIS_POTION(111, Arrays.asList("Helgi's potion", "potion", "Helgi's", "H", "p"),
Color.BOLD_ON + Color.RED + "Helgi's" + Color.RESET + Color.MAGENTA + Color.BOLD_ON + " potion" + Color.RESET,
"a " + Color.BOLD_ON + Color.RED + "Helgi's" + Color.RESET + Color.MAGENTA + Color.BOLD_ON + " potion" + Color.RESET + " is on the ground.",
"a " + Color.BOLD_ON + Color.RED + "Helgi's" + Color.RESET + Color.MAGENTA + Color.BOLD_ON + " potion" + Color.RESET,
false,
0,
60,
false,
Rarity.LEGENDARY,
8000000, Sets.<TimeTracker.TimeOfDay>newHashSet()),
CELESTIAL_DIAL(112, Arrays.asList("celestial dial", "dial", "c", "d", "celestial"),
Color.BOLD_ON + Color.CYAN + "celestial" + Color.RESET + Color.WHITE + Color.BOLD_ON + " dial" + Color.RESET,
"a " + Color.BOLD_ON + Color.CYAN + "celestial" + Color.RESET + Color.WHITE + Color.BOLD_ON + " dial" + Color.RESET + " is on the ground.",
"a " + Color.BOLD_ON + Color.CYAN + "celestial" + Color.RESET + Color.WHITE + Color.BOLD_ON + " dial" + Color.RESET,
false,
0,
60,
false,
Rarity.LEGENDARY,
8000000, Sets.<TimeTracker.TimeOfDay>newHashSet()),
THORS_LANTERN(113, Arrays.asList("Thor's lantern", "lantern", "Thor's", "T", "l"),
Color.BOLD_ON + Color.RED + "Thor's" + Color.RESET + Color.YELLOW + " lantern" + Color.RESET,
"a " + Color.BOLD_ON + Color.RED + "Thor's" + Color.RESET + Color.YELLOW + " lantern" + Color.RESET + " is on the ground.",
"a " + Color.BOLD_ON + Color.RED + "Thor's" + Color.RESET + Color.YELLOW + " lantern" + Color.RESET,
false,
0,
60,
false,
Rarity.LEGENDARY,
8000000, Sets.<TimeTracker.TimeOfDay>newHashSet()),
ORNATE_CROWN(114, Arrays.asList("ornate crown", "crown", "o", "c", "ornate"),
Color.BOLD_ON + Color.MAGENTA + "ornate" + Color.RESET + Color.YELLOW + " crown" + Color.RESET,
"a " + Color.BOLD_ON + Color.MAGENTA + "ornate" + Color.RESET + Color.YELLOW + " crown" + Color.RESET + " is on the ground.",
"a " + Color.BOLD_ON + Color.MAGENTA + "ornate" + Color.RESET + Color.YELLOW + " crown" + Color.RESET,
false,
0,
60,
false,
Rarity.LEGENDARY,
8000000, Sets.<TimeTracker.TimeOfDay>newHashSet()),
PYAMITE_COMPASS(115, Arrays.asList("pyamite compass", "compass", "p", "c", "pyamite"),
Color.BOLD_ON + Color.GREEN + "pyamite" + Color.RESET + Color.CYAN + " compass" + Color.RESET,
"a " + Color.BOLD_ON + Color.GREEN + "pyamite" + Color.RESET + Color.CYAN + " compass" + Color.RESET + " is on the ground.",
"a " + Color.BOLD_ON + Color.GREEN + "pyamite" + Color.RESET + Color.CYAN + " compass" + Color.RESET,
false,
0,
60,
false,
Rarity.LEGENDARY,
8000000, Sets.<TimeTracker.TimeOfDay>newHashSet());
private final Integer itemTypeCode;
private final List<String> itemTriggers;
private final String restingName;
private final String itemName;
private final String itemDescription;
private final boolean isDisposable;
private final int maxUses;
private final int itemHalfLifeTicks;
private final boolean isEquipment;
private final Rarity rarity;
private final int valueInGold;
private final Set<TimeTracker.TimeOfDay> validTimeOfDays;
ItemType(Integer itemTypeCode, List<String> itemTriggers, String itemName, String restingName, String itemDescription, boolean isDisposable, int maxUses, int itemHalfLifeTicks, boolean isEquipment, Rarity rarity, int valueInGold, Set<TimeTracker.TimeOfDay> validTimeOfDays) {
this.itemTypeCode = itemTypeCode;
this.itemTriggers = itemTriggers;
this.itemName = itemName;
this.restingName = restingName;
this.itemDescription = itemDescription;
this.maxUses = maxUses;
this.isDisposable = maxUses > 0 || isDisposable;
this.itemHalfLifeTicks = itemHalfLifeTicks;
this.isEquipment = isEquipment;
this.rarity = rarity;
this.valueInGold = valueInGold;
this.validTimeOfDays = validTimeOfDays;
}
public Item create() {
Item newItem = new Item(getItemName(), getItemDescription(), getItemTriggers(), getRestingName(), UUID.randomUUID().toString(), getItemTypeCode(), 0, false, itemHalfLifeTicks, getRarity(), getValueInGold());
if (isEquipment) {
return EquipmentBuilder.Build(newItem);
}
return newItem;
}
public Rarity getRarity() {
return rarity;
}
public String getRestingName() {
return restingName;
}
public Integer getItemTypeCode() {
return itemTypeCode;
}
public List<String> getItemTriggers() {
return itemTriggers;
}
public String getItemName() {
return itemName;
}
public String getItemDescription() {
return itemDescription;
}
public boolean isDisposable() {
return isDisposable;
}
public int getMaxUses() {
return maxUses;
}
public int getValueInGold() {
return valueInGold;
}
public Set<TimeTracker.TimeOfDay> getValidTimeOfDays() {
return validTimeOfDays;
}
public static ItemType itemTypeFromCode(Integer code) {
ItemType[] values = values();
for (ItemType type : values) {
if (type.getItemTypeCode().equals(code)) {
return type;
}
}
return ItemType.UNKNOWN;
}
}
|
package matlabcontrol.link;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Serializable;
import java.lang.reflect.GenericArrayType;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable;
import java.lang.reflect.WildcardType;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
/**
* A holder of information about the Java method and the associated MATLAB function.
*
* @since 4.2.0
* @author <a href="mailto:nonother@gmail.com">Joshua Kaplan</a>
*/
class InvocationInfo implements Serializable {
private static final long serialVersionUID = 764281612994597133L;
/**
* The name of the function.
*/
final String name;
/**
* The directory containing the function. This is an absolute path to an m-file on the system, never inside of
* a compressed file such as a jar. {@code null} if the function is (supposed to be) on MATLAB's path.
*/
final String containingDirectory;
/**
* The types of each returned argument. The length of this array is the nargout to call the function with.
*/
final Class<?>[] returnTypes;
/**
* Array of generic type parameters of the return types. For instance for return type at index <i>i</i> in
* {@code returnTypes} the generic parameters are in the array returned by {@code returnTypeGenericParameters}
* at index <i>i</i>.
*/
final Class<?>[][] returnTypeParameters;
static InvocationInfo getInvocationInfo(Method method, MatlabFunction annotation) {
FunctionInfo funcInfo = getFunctionInfo(method, annotation);
ReturnTypeInfo returnInfo = getReturnTypes(method);
InvocationInfo invocationInfo = new InvocationInfo(funcInfo.name, funcInfo.containingDirectory,
returnInfo.returnTypes, returnInfo.returnTypeParameters);
return invocationInfo;
}
InvocationInfo(String name, String containingDirectory, Class<?>[] returnTypes, Class<?>[][] returnTypeParameters) {
this.name = name;
this.containingDirectory = containingDirectory;
this.returnTypes = returnTypes;
this.returnTypeParameters = returnTypeParameters;
}
@Override
public String toString() {
String genericParameters = "[";
for (int i = 0; i < returnTypeParameters.length; i++) {
genericParameters += classArrayToString(returnTypeParameters[i]);
if (i != returnTypeParameters.length - 1) {
genericParameters += " ";
}
}
genericParameters += "]";
return "[" + this.getClass().getSimpleName() +
" name=" + name + "," +
" containingDirectory=" + containingDirectory + "," +
" returnTypes=" + classArrayToString(returnTypes) + "," +
" returnTypesGenericParameters=" + genericParameters + "]";
}
private static String classArrayToString(Class<?>[] array) {
String str = "[";
for (int i = 0; i < array.length; i++) {
str += array[i].getCanonicalName();
if (i != array.length - 1) {
str += " ";
}
}
str += "]";
return str;
}
private static class FunctionInfo {
final String name;
final String containingDirectory;
public FunctionInfo(String name, String containingDirectory) {
this.name = name;
this.containingDirectory = containingDirectory;
}
}
private static FunctionInfo getFunctionInfo(Method method, MatlabFunction annotation) {
//Determine the function's name and if applicable, the directory the function is located in
String functionName;
String containingDirectory;
//If a function name
if (isFunctionName(annotation.value())) {
functionName = annotation.value();
containingDirectory = null;
}
//If a path
else {
String path = annotation.value();
//Retrieve location of function file
File functionFile;
if (new File(path).isAbsolute()) {
functionFile = new File(path);
} else {
functionFile = resolveRelativePath(method, path);
}
//Resolve canonical path
try {
functionFile = functionFile.getCanonicalFile();
} catch (IOException e) {
throw new LinkingException("Unable to resolve canonical path of specified function\n" +
"method: " + method.getName() + "\n" +
"path:" + path + "\n" +
"non-canonical path: " + functionFile.getAbsolutePath(), e);
}
//Validate file location
if (!functionFile.exists()) {
throw new LinkingException("Specified file does not exist\n" +
"method: " + method.getName() + "\n" +
"path: " + path + "\n" +
"resolved as: " + functionFile.getAbsolutePath());
}
if (!functionFile.isFile()) {
throw new LinkingException("Specified file is not a file\n" +
"method: " + method.getName() + "\n" +
"path: " + path + "\n" +
"resolved as: " + functionFile.getAbsolutePath());
}
if (!(functionFile.getName().endsWith(".m") || functionFile.getName().endsWith(".p"))) {
throw new LinkingException("Specified file does not end in .m or .p\n" +
"method: " + method.getName() + "\n" +
"path: " + path + "\n" +
"resolved as: " + functionFile.getAbsolutePath());
}
//Parse out the name of the function and the directory containing it
containingDirectory = functionFile.getParent();
functionName = functionFile.getName().substring(0, functionFile.getName().length() - 2);
//Validate the function name
if (!isFunctionName(functionName)) {
throw new LinkingException("Specified file's name is not a MATLAB function name\n" +
"Function Name: " + functionName + "\n" +
"File: " + functionFile.getAbsolutePath());
}
}
return new FunctionInfo(functionName, containingDirectory);
}
private static boolean isFunctionName(String functionName) {
boolean isFunctionName = true;
char[] nameChars = functionName.toCharArray();
if (!Character.isLetter(nameChars[0])) {
isFunctionName = false;
} else {
for (char element : nameChars) {
if (!(Character.isLetter(element) || Character.isDigit(element) || element == '_')) {
isFunctionName = false;
break;
}
}
}
return isFunctionName;
}
/**
* Cache used by {@link #resolveRelativePath(Method, String)}
*/
private static final ConcurrentHashMap<Class<?>, Map<String, File>> UNZIPPED_ENTRIES = new ConcurrentHashMap<Class<?>, Map<String, File>>();
/**
* Resolves the location of {@code relativePath} relative to the interface which declared {@code method}. If the
* interface is inside of a zip file (jar/war/ear etc. file) then the contents of the zip file may first need to be
* unzipped.
*
* @param method
* @param relativePath
* @return the absolute location of the file
*/
private static File resolveRelativePath(Method method, String relativePath) {
Class<?> theInterface = method.getDeclaringClass();
File interfaceLocation = getClassLocation(theInterface);
File functionFile;
//Code source is in a file, which means it should be jar/ear/war/zip etc.
if (interfaceLocation.isFile()) {
if (!UNZIPPED_ENTRIES.containsKey(theInterface)) {
UnzipResult unzipResult = unzip(interfaceLocation);
Map<String, File> mapping = unzipResult.unzippedMapping;
List<File> filesToDelete = new ArrayList<File>(mapping.values());
filesToDelete.add(unzipResult.rootDirectory);
//If there was a previous mapping, delete all of the files just unzipped
if (UNZIPPED_ENTRIES.putIfAbsent(theInterface, mapping) != null) {
deleteFiles(filesToDelete, true);
}
//No previous mapping, delete unzipped files on JVM exit
else {
deleteFiles(filesToDelete, false);
}
}
functionFile = UNZIPPED_ENTRIES.get(theInterface).get(relativePath);
if (functionFile == null) {
throw new LinkingException("Unable to find file inside of zip\n" +
"Method: " + method.getName() + "\n" +
"Relative Path: " + relativePath + "\n" +
"Zip File: " + interfaceLocation.getAbsolutePath());
}
}
//Code source is a directory, it code should not be inside a jar/ear/war/zip etc.
else {
functionFile = new File(interfaceLocation, relativePath);
}
return functionFile;
}
private static void deleteFiles(Collection<File> files, boolean deleteNow) {
ArrayList<File> sortedFiles = new ArrayList<File>(files);
Collections.sort(sortedFiles);
//Delete files in the opposite order so that files are deleted before their containing directories
if (deleteNow) {
for (int i = sortedFiles.size() - 1; i >= 0; i
sortedFiles.get(i).delete();
}
}
//Delete files in the existing order because the files will be deleted on exit in the opposite order
else {
for (File file : sortedFiles) {
file.deleteOnExit();
}
}
}
/**
* Cache used by {@link #getClassLocation(java.lang.Class)}}.
*/
private static final ConcurrentHashMap<Class<?>, File> CLASS_LOCATIONS = new ConcurrentHashMap<Class<?>, File>();
private static File getClassLocation(Class<?> clazz) {
if (!CLASS_LOCATIONS.containsKey(clazz)) {
try {
URL url = clazz.getProtectionDomain().getCodeSource().getLocation();
File file = new File(url.toURI().getPath()).getCanonicalFile();
if (!file.exists()) {
throw new LinkingException("Incorrectly resolved location of class\n" +
"class: " + clazz.getCanonicalName() + "\n" +
"location: " + file.getAbsolutePath());
}
CLASS_LOCATIONS.put(clazz, file);
} catch (IOException e) {
throw new LinkingException("Unable to determine location of " + clazz.getCanonicalName(), e);
} catch (URISyntaxException e) {
throw new LinkingException("Unable to determine location of " + clazz.getCanonicalName(), e);
}
}
return CLASS_LOCATIONS.get(clazz);
}
private static class UnzipResult {
final Map<String, File> unzippedMapping;
File rootDirectory;
private UnzipResult(Map<String, File> mapping, File root) {
this.unzippedMapping = mapping;
this.rootDirectory = root;
}
}
/**
* Unzips the file located at {@code zipLocation}.
*
* @param zipLocation the location of the file zip
* @return resulting files from unzipping
* @throws LinkingException if unable to unzip the zip file for any reason
*/
private static UnzipResult unzip(File zipLocation) {
ZipFile zip;
try {
zip = new ZipFile(zipLocation);
} catch (IOException e) {
throw new LinkingException("Unable to open zip file\n" +
"zip location: " + zipLocation.getAbsolutePath(), e);
}
try {
//Mapping from entry names to the unarchived location on disk
Map<String, File> entryMap = new HashMap<String, File>();
//Destination
File unzipDir = new File(System.getProperty("java.io.tmpdir"), "linked_" + UUID.randomUUID().toString());
for (Enumeration<? extends ZipEntry> entries = zip.entries(); entries.hasMoreElements();) {
ZipEntry entry = entries.nextElement();
//Directory
if (entry.isDirectory()) {
File destDir = new File(unzipDir, entry.getName());
destDir.mkdirs();
entryMap.put(entry.getName(), destDir);
}
//File
else {
//File should not exist, but confirm it
File destFile = new File(unzipDir, entry.getName());
if (destFile.exists()) {
throw new LinkingException("Cannot unzip file, randomly generated path already exists\n" +
"generated path: " + destFile.getAbsolutePath() + "\n" +
"zip file: " + zipLocation.getAbsolutePath());
}
destFile.getParentFile().mkdirs();
//Unarchive
try {
final int BUFFER_SIZE = 2048;
OutputStream dest = new BufferedOutputStream(new FileOutputStream(destFile), BUFFER_SIZE);
try {
InputStream entryStream = zip.getInputStream(entry);
try {
byte[] buffer = new byte[BUFFER_SIZE];
int count;
while ((count = entryStream.read(buffer, 0, BUFFER_SIZE)) != -1) {
dest.write(buffer, 0, count);
}
dest.flush();
} finally {
entryStream.close();
}
} finally {
dest.close();
}
} catch (IOException e) {
throw new LinkingException("Unable to unzip file entry\n" +
"entry: " + entry.getName() + "\n" +
"zip location: " + zipLocation.getAbsolutePath() + "\n" +
"destination file: " + destFile.getAbsolutePath(), e);
}
entryMap.put(entry.getName(), destFile);
}
}
return new UnzipResult(Collections.unmodifiableMap(entryMap), unzipDir);
} finally {
try {
zip.close();
} catch (IOException ex) {
throw new LinkingException("Unable to close zip file: " + zipLocation.getAbsolutePath(), ex);
}
}
}
private static class ReturnTypeInfo {
Class<?>[] returnTypes;
Class<?>[][] returnTypeParameters;
private ReturnTypeInfo(Class<?>[] returnTypes, Class<?>[][] returnTypeParameters) {
this.returnTypes = returnTypes;
this.returnTypeParameters = returnTypeParameters;
}
}
private static ReturnTypeInfo getReturnTypes(Method method) {
//The type-erasured return type of the method
Class<?> methodReturn = method.getReturnType();
//The return type of the method with type information
Type genericReturn = method.getGenericReturnType();
//The return types to be determined
Class<?>[] returnTypes;
Class<?>[][] returnTypeGenericParameters;
//0 return arguments
if (methodReturn.equals(void.class)) {
returnTypes = new Class<?>[0];
returnTypeGenericParameters = new Class<?>[0][0];
}
//1 return argument
else if (!MatlabReturns.ReturnN.class.isAssignableFrom(methodReturn)) {
//MatlabNumberArray subclasses are allowed to be parameterized
if (MatlabNumberArray.class.isAssignableFrom(methodReturn)) {
if (genericReturn instanceof ParameterizedType) {
Type[] parameterizedTypes = ((ParameterizedType) genericReturn).getActualTypeArguments();
Class<?> parameter = getMatlabNumberArrayParameter(parameterizedTypes[0], methodReturn, method);
returnTypeGenericParameters = new Class<?>[][]{{parameter}};
} else {
throw new LinkingException(method + " must parameterize " + methodReturn.getCanonicalName());
}
} else if (!methodReturn.equals(genericReturn)) {
throw new LinkingException(method + " may not have a return type that uses generics");
} else {
returnTypeGenericParameters = new Class<?>[1][0];
}
returnTypes = new Class<?>[]{methodReturn};
}
//2 or more return arguments
else {
if (genericReturn instanceof ParameterizedType) {
Type[] parameterizedTypes = ((ParameterizedType) genericReturn).getActualTypeArguments();
returnTypes = new Class<?>[parameterizedTypes.length];
returnTypeGenericParameters = new Class<?>[parameterizedTypes.length][];
for (int i = 0; i < parameterizedTypes.length; i++) {
Type type = parameterizedTypes[i];
if (type instanceof Class) {
Class<?> returnType = (Class<?>) type;
if (MatlabNumberArray.class.isAssignableFrom(returnType)) {
throw new LinkingException(method + " must parameterize " + returnType.getCanonicalName());
}
returnTypes[i] = returnType;
returnTypeGenericParameters[i] = new Class[0];
} else if (type instanceof GenericArrayType) {
returnTypes[i] = getClassOfArrayType((GenericArrayType) type, method);
returnTypeGenericParameters[i] = new Class[0];
} else if (type instanceof ParameterizedType) {
//MatlabNumberArray subclasses are allowed to be parameterized
ParameterizedType parameterizedType = (ParameterizedType) type;
Type rawType = parameterizedType.getRawType();
if (rawType instanceof Class && MatlabNumberArray.class.isAssignableFrom((Class<?>) rawType)) {
Class<?> returnType = (Class<?>) rawType;
returnTypes[i] = returnType;
Class<?> parameter = getMatlabNumberArrayParameter(
parameterizedType.getActualTypeArguments()[0], returnType, method);
returnTypeGenericParameters[i] = new Class[]{parameter};
} else {
throw new LinkingException(method + " may not parameterize " +
methodReturn.getCanonicalName() + " with a parameterized type");
}
} else if (type instanceof WildcardType) {
throw new LinkingException(method + " may not parameterize " + methodReturn.getCanonicalName() +
" with a wild card type");
} else if (type instanceof TypeVariable) {
throw new LinkingException(method + " may not parameterize " + methodReturn.getCanonicalName() +
" with a generic type");
} else {
throw new LinkingException(method + " may not parameterize " + methodReturn.getCanonicalName() +
" with " + type);
}
}
} else {
throw new LinkingException(method + " must parameterize " + methodReturn.getCanonicalName());
}
}
return new ReturnTypeInfo(returnTypes, returnTypeGenericParameters);
}
private static Class<?> getMatlabNumberArrayParameter(Type type, Class<?> matlabArrayClass, Method method) {
Class<?> parameter;
if (type instanceof GenericArrayType) {
parameter = getClassOfArrayType((GenericArrayType) type, method);
ClassInfo paramInfo = ClassInfo.getInfo(parameter);
boolean validParameter = ((matlabArrayClass.equals(MatlabInt8Array.class) && byte.class.equals(paramInfo.baseComponentType)) ||
(matlabArrayClass.equals(MatlabInt16Array.class) && short.class.equals(paramInfo.baseComponentType)) ||
(matlabArrayClass.equals(MatlabInt32Array.class) && int.class.equals(paramInfo.baseComponentType)) ||
(matlabArrayClass.equals(MatlabInt64Array.class) && long.class.equals(paramInfo.baseComponentType)) ||
(matlabArrayClass.equals(MatlabSingleArray.class) && float.class.equals(paramInfo.baseComponentType)) ||
(matlabArrayClass.equals(MatlabDoubleArray.class) && double.class.equals(paramInfo.baseComponentType)));
if (!validParameter) {
throw new LinkingException(method + " may not parameterize " + matlabArrayClass.getCanonicalName() +
" with " + parameter.getCanonicalName());
}
} else {
throw new LinkingException(method + " may not parameterize " + matlabArrayClass.getCanonicalName() +
" with " + type);
}
return parameter;
}
/**
*
* @param type
* @param method used for exception message only
* @return
*/
private static Class<?> getClassOfArrayType(GenericArrayType type, Method method) {
int dimensions = 1;
Type componentType = type.getGenericComponentType();
while (!(componentType instanceof Class)) {
dimensions++;
if (componentType instanceof GenericArrayType) {
componentType = ((GenericArrayType) componentType).getGenericComponentType();
} else if (componentType instanceof TypeVariable) {
throw new LinkingException(method + " may not parameterize " +
method.getReturnType().getCanonicalName() + " with a generic array");
} else {
throw new LinkingException(method + " may not parameterize " +
method.getReturnType().getCanonicalName() + " with an array of type " + type);
}
}
return ArrayUtils.getArrayClass((Class<?>) componentType, dimensions);
}
}
|
package xdi2.connect.acmepizza;
import java.net.URI;
import java.util.ArrayDeque;
import java.util.Date;
import java.util.Deque;
import java.util.Iterator;
import xdi2.agent.impl.XDIBasicAgent;
import xdi2.agent.routing.impl.http.XDIHttpDiscoveryAgentRouter;
import xdi2.client.XDIClientRoute;
import xdi2.client.exceptions.Xdi2ClientException;
import xdi2.connect.core.ConnectionResult;
import xdi2.core.Graph;
import xdi2.core.features.linkcontracts.instance.GenericLinkContract;
import xdi2.core.features.linkcontracts.instance.LinkContract;
import xdi2.core.syntax.XDIAddress;
import xdi2.core.util.XDIAddressUtil;
import xdi2.discovery.XDIDiscoveryClient;
import xdi2.messaging.Message;
import xdi2.messaging.MessageEnvelope;
public class AcmepizzaStatus {
private static Deque<Status> statuses = new ArrayDeque<Status> ();
public static String newStatus(ConnectionResult connectionResult, URI discovery) {
Status status = new Status();
status.date = new Date();
status.connectionResult = connectionResult;
status.discovery = discovery;
statuses.add(status);
if (statuses.size() > 10) statuses.removeFirst();
return status.getData();
}
public static String status() {
StringBuffer buffer = new StringBuffer();
for (Status status : statuses) {
buffer.insert(0, status.toString() + "\n");
}
return buffer.toString();
}
private static class Status {
private Date date;
private ConnectionResult connectionResult;
private URI discovery;
private String getData() {
Iterator<LinkContract> linkContracts = this.connectionResult.getLinkContracts();
if (linkContracts == null || ! linkContracts.hasNext()) return null;
GenericLinkContract linkContract = (GenericLinkContract) linkContracts.next();
XDIAddress requestingAuthority = linkContract.getRequestingAuthority();
XDIAddress authorizingAuthority = linkContract.getAuthorizingAuthority();
XDIBasicAgent XDIagent = new XDIBasicAgent(new XDIHttpDiscoveryAgentRouter(new XDIDiscoveryClient(this.discovery)));
StringBuffer buffer = new StringBuffer();
try {
XDIClientRoute<?> route = XDIagent.route(authorizingAuthority);
MessageEnvelope me = route.createMessageEnvelope();
Message m = route.createMessage(me, requestingAuthority);
m.setLinkContractXDIAddress(linkContract.getContextNode().getXDIAddress());
m.createGetOperation(XDIAddressUtil.concatXDIAddresses(authorizingAuthority, XDIAddress.create("$card<#first><#name>")));
m.createGetOperation(XDIAddressUtil.concatXDIAddresses(authorizingAuthority, XDIAddress.create("$card<#last><#name>")));
m.createGetOperation(XDIAddressUtil.concatXDIAddresses(authorizingAuthority, XDIAddress.create("$card#address<#street>")));
m.createGetOperation(XDIAddressUtil.concatXDIAddresses(authorizingAuthority, XDIAddress.create("$card#address<#postal><#code>")));
m.createGetOperation(XDIAddressUtil.concatXDIAddresses(authorizingAuthority, XDIAddress.create("$card#address<#locality>")));
m.createGetOperation(XDIAddressUtil.concatXDIAddresses(authorizingAuthority, XDIAddress.create("$card#address<#country>")));
Graph resultGraph = route.constructXDIClient().send(me).getResultGraph();
buffer.append("\n\n");
buffer.append(resultGraph.getDeepLiteralNode(XDIAddressUtil.concatXDIAddresses(authorizingAuthority, XDIAddress.create("$card<#first><#name>&"))).getLiteralDataString());
buffer.append(" ");
buffer.append(resultGraph.getDeepLiteralNode(XDIAddressUtil.concatXDIAddresses(authorizingAuthority, XDIAddress.create("$card<#last><#name>&"))).getLiteralDataString());
buffer.append("\n");
buffer.append(resultGraph.getDeepLiteralNode(XDIAddressUtil.concatXDIAddresses(authorizingAuthority, XDIAddress.create("$card#address<#street>&"))).getLiteralDataString());
buffer.append("\n");
buffer.append(resultGraph.getDeepLiteralNode(XDIAddressUtil.concatXDIAddresses(authorizingAuthority, XDIAddress.create("$card#address<#postal><#code>&"))).getLiteralDataString());
buffer.append("\n");
buffer.append(resultGraph.getDeepLiteralNode(XDIAddressUtil.concatXDIAddresses(authorizingAuthority, XDIAddress.create("$card#address<#locality>&"))).getLiteralDataString());
buffer.append("\n");
buffer.append(resultGraph.getDeepLiteralNode(XDIAddressUtil.concatXDIAddresses(authorizingAuthority, XDIAddress.create("$card#address<#country>&"))).getLiteralDataString());
buffer.append("\n");
} catch (Xdi2ClientException ex) {
return ex.getMessage();
}
return buffer.toString();
}
@Override
public String toString() {
String data = this.getData();
return this.date.toString() + ": " + data + "\n";
}
}
}
|
package com.github.nsnjson;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.node.*;
import java.util.Optional;
import static com.github.nsnjson.format.Format.*;
public abstract class AbstractFormatTest extends AbstractTest {
@Override
protected JsonNode getNullPresentation() {
ObjectNode presentation = new ObjectMapper().createObjectNode();
presentation.put(FIELD_TYPE, TYPE_MARKER_NULL);
return presentation;
}
@Override
protected JsonNode getNumberPresentation(NumericNode value) {
ObjectNode presentation = new ObjectMapper().createObjectNode();
presentation.put(FIELD_TYPE, TYPE_MARKER_NUMBER);
presentation.set(FIELD_VALUE, value);
return presentation;
}
@Override
protected JsonNode getStringPresentation(TextNode value) {
ObjectNode presentation = new ObjectMapper().createObjectNode();
presentation.put(FIELD_TYPE, TYPE_MARKER_STRING);
presentation.put(FIELD_VALUE, value.asText());
return presentation;
}
@Override
protected JsonNode getBooleanPresentation(BooleanNode value) {
ObjectNode presentation = new ObjectMapper().createObjectNode();
presentation.put(FIELD_TYPE, TYPE_MARKER_BOOLEAN);
presentation.put(FIELD_VALUE, value.asBoolean() ? BOOLEAN_TRUE : BOOLEAN_FALSE);
return presentation;
}
@Override
protected JsonNode getArrayPresentation(ArrayNode array) {
ObjectMapper objectMapper = new ObjectMapper();
ArrayNode itemsPresentation = objectMapper.createArrayNode();
for (JsonNode value : array) {
Optional<JsonNode> itemPresentationOption = getPresentation(value);
if (itemPresentationOption.isPresent()) {
itemsPresentation.add(itemPresentationOption.get());
}
}
ObjectNode presentation = objectMapper.createObjectNode();
presentation.put(FIELD_TYPE, TYPE_MARKER_ARRAY);
presentation.set(FIELD_VALUE, itemsPresentation);
return presentation;
}
@Override
protected JsonNode getObjectPresentation(ObjectNode object) {
ObjectMapper objectMapper = new ObjectMapper();
ArrayNode fieldsPresentation = objectMapper.createArrayNode();
object.fieldNames().forEachRemaining(name -> {
JsonNode value = object.get(name);
Optional<JsonNode> valuePresentationOption = getPresentation(value);
if (valuePresentationOption.isPresent()) {
JsonNode valuePresentation = valuePresentationOption.get();
ObjectNode fieldPresentation = objectMapper.createObjectNode();
fieldPresentation.put(FIELD_NAME, name);
if (valuePresentation.has(FIELD_TYPE)) {
fieldPresentation.set(FIELD_TYPE, valuePresentation.get(FIELD_TYPE));
}
if (valuePresentation.has(FIELD_VALUE)) {
fieldPresentation.set(FIELD_VALUE, valuePresentation.get(FIELD_VALUE));
}
fieldsPresentation.add(fieldPresentation);
}
});
ObjectNode presentation = objectMapper.createObjectNode();
presentation.put(FIELD_TYPE, TYPE_MARKER_OBJECT);
presentation.set(FIELD_VALUE, fieldsPresentation);
return presentation;
}
}
|
package org.sagebionetworks.bridge.dynamodb;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBHashKey;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBIgnore;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBIndexHashKey;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMappingException;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMarshaller;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMarshalling;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBRangeKey;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBTable;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import com.google.common.base.Throwables;
import com.google.common.collect.ImmutableList;
import org.sagebionetworks.bridge.exceptions.InvalidEntityException;
import org.sagebionetworks.bridge.json.BridgeObjectMapper;
import org.sagebionetworks.bridge.json.JsonUtils;
import org.sagebionetworks.bridge.models.upload.UploadFieldDefinition;
import org.sagebionetworks.bridge.models.upload.UploadSchema;
import org.sagebionetworks.bridge.models.upload.UploadSchemaType;
import org.sagebionetworks.bridge.validators.UploadSchemaValidator;
import org.sagebionetworks.bridge.validators.Validate;
/**
* The DynamoDB implementation of UploadSchema. This is a mutable class with getters and setters so that it can work
* with the DynamoDB mapper.
*/
@DynamoThroughput(readCapacity=50, writeCapacity=25)
@DynamoDBTable(tableName = "UploadSchema")
public class DynamoUploadSchema implements UploadSchema {
private static final BridgeObjectMapper MAPPER = BridgeObjectMapper.get();
private static final String FIELD_DEFINITIONS = "fieldDefinitions";
private List<UploadFieldDefinition> fieldDefList;
private String name;
private int rev;
private String schemaId;
private UploadSchemaType schemaType;
private String studyId;
/**
* Bypass all the object construction restrictions to return a complete validation error when the JSON sent from the
* server is syntactically valid but incorrect. We have two competing models in our system: object construction code
* that prevents server-side developers from creating invalid objects, and a user input system that depends on the
* ability of users to create invalid objects from JSON, which we then validate.
*
* This is the disaster that results when we have to harmonize the two. It may not always be possible, but here it
* is.
*
* @param node
* @return
*/
public static UploadSchema fromJson(JsonNode node) {
ArrayNode fieldDefinitionsNode = null;
List<UploadFieldDefinition> fieldDefinitions = new ArrayList<>();
Map<String,List<String>> errors = new HashMap<>();
// Remove field definitions.
if (node.has(FIELD_DEFINITIONS)) {
fieldDefinitionsNode = (ArrayNode)node.get(FIELD_DEFINITIONS);
((ObjectNode)node).remove(FIELD_DEFINITIONS);
}
// Validate them separately, storing their errors
if (fieldDefinitionsNode != null) {
for (int i=0; i < fieldDefinitionsNode.size(); i++) {
JsonNode defNode = fieldDefinitionsNode.get(i);
try {
UploadFieldDefinition definition = MAPPER.convertValue(defNode, UploadFieldDefinition.class);
fieldDefinitions.add(definition);
} catch(IllegalArgumentException iae) {
Throwable cause = Throwables.getRootCause(iae);
if (cause instanceof InvalidEntityException) {
InvalidEntityException e = (InvalidEntityException)cause;
for (Map.Entry<String, List<String>> entry: e.getErrors().entrySet()) {
String fieldName = FIELD_DEFINITIONS+i+"."+entry.getKey();
errors.put(fieldName, entry.getValue());
// We need to adjust the errors which now reference a field that is nested
for (int j=0; j < entry.getValue().size(); j++) {
String message = entry.getValue().get(j);
String replacedMessage = message.replaceFirst(entry.getKey(), fieldName);
entry.getValue().set(j, replacedMessage);
}
}
}
}
}
}
// Validate the entity which will always be invalid with at least one error (no field
// definitions); we're looking for additional errors
try {
UploadSchema schema = MAPPER.convertValue(node, UploadSchema.class);
Validate.entityThrowingException(UploadSchemaValidator.INSTANCE, schema);
} catch(InvalidEntityException e) {
for (Map.Entry<String, List<String>> entry: e.getErrors().entrySet()) {
if (!FIELD_DEFINITIONS.equals(entry.getKey())) {
errors.put(entry.getKey(), entry.getValue());
}
}
}
if (!errors.isEmpty()) {
String msg = Validate.convertSimpleMapResultToMessage("UploadSchema", errors);
throw new InvalidEntityException(null, msg, errors);
}
// Object is valid in its parts, restore field definitions and convert.
((ObjectNode)node).putPOJO(FIELD_DEFINITIONS, fieldDefinitionsNode);
return MAPPER.convertValue(node, UploadSchema.class);
}
/** {@inheritDoc} */
@DynamoDBMarshalling(marshallerClass = FieldDefinitionListMarshaller.class)
@Override
public List<UploadFieldDefinition> getFieldDefinitions() {
return fieldDefList;
}
/** @see org.sagebionetworks.bridge.models.upload.UploadSchema#getFieldDefinitions */
public void setFieldDefinitions(List<UploadFieldDefinition> fieldDefList) {
this.fieldDefList = ImmutableList.copyOf(fieldDefList);
}
/**
* This is the DynamoDB key. It is used by the DynamoDB mapper. This should not be used directly. The key format is
* "[studyID]:[schemaID]". The schema ID may contain colons. The study ID may not. Since the key is created
* from the study ID and schema ID, this will throw an InvalidEntityException if either one is blank.
*/
@DynamoDBHashKey
@JsonIgnore
public String getKey() throws InvalidEntityException {
if (Strings.isNullOrEmpty(studyId)) {
throw new InvalidEntityException(this, String.format(Validate.CANNOT_BE_BLANK, "studyId"));
}
if (Strings.isNullOrEmpty(schemaId)) {
throw new InvalidEntityException(this, String.format(Validate.CANNOT_BE_BLANK, "schemaId"));
}
return String.format("%s:%s", studyId, schemaId);
}
/**
* Sets the DynamoDB key. This is generally only called by the DynamoDB mapper. If the key is null, empty, or
* malformatted, this will throw.
*
* @see #getKey
*/
@JsonProperty
public void setKey(String key) {
Preconditions.checkNotNull(key, Validate.CANNOT_BE_NULL, "key");
Preconditions.checkArgument(!key.isEmpty(), Validate.CANNOT_BE_EMPTY_STRING, "key");
String[] parts = key.split(":", 2);
Preconditions.checkArgument(parts.length == 2, "key has wrong number of parts");
Preconditions.checkArgument(!parts[0].isEmpty(), "key has empty study ID");
Preconditions.checkArgument(!parts[1].isEmpty(), "key has empty schema ID");
this.studyId = parts[0];
this.schemaId = parts[1];
}
/** {@inheritDoc} */
@Override
public String getName() {
return name;
}
/** @see org.sagebionetworks.bridge.models.upload.UploadSchema#getName */
public void setName(String name) {
this.name = name;
}
/** {@inheritDoc} */
// We don't use the DynamoDBVersionAttribute here because we want to keep multiple versions of the schema so we can
// parse older versions of the data. Similarly, we make this a range key so that we can always find the latest
// version of the schema.
// Additionally, we don't need to use the version attribute to do optimistic locking, since we use a save
// expression that checks whether the row already exists. (See DynamoUploadSchemaDao for further details.)
@DynamoDBRangeKey
@Override
public int getRevision() {
return rev;
}
/** @see org.sagebionetworks.bridge.models.upload.UploadSchema#getRevision */
public void setRevision(int rev) {
this.rev = rev;
}
/** {@inheritDoc} */
@DynamoDBIgnore
@Override
public String getSchemaId() {
return schemaId;
}
/** @see org.sagebionetworks.bridge.models.upload.UploadSchema#getSchemaId */
public void setSchemaId(String schemaId) {
this.schemaId = schemaId;
}
/** {@inheritDoc} */
@DynamoDBMarshalling(marshallerClass = EnumMarshaller.class)
@Override
public UploadSchemaType getSchemaType() {
return schemaType;
}
/** @see org.sagebionetworks.bridge.models.upload.UploadSchema#getSchemaType */
public void setSchemaType(UploadSchemaType schemaType) {
this.schemaType = schemaType;
}
/**
* <p>
* The ID of the study that this schema lives in. This is not exposed to the callers of the upload schema API, but
* is needed internally to create a secondary index on the study. This index is needed by:
* <ul>
* <li>the exporter will want all schemas for a particular study to match a particular upload</li>
* <li>researchers may want to list all schemas in their study for schema management</li>
* </ul>
* </p>
*/
@DynamoDBIndexHashKey(attributeName = "studyId", globalSecondaryIndexName = "studyId-index")
@JsonIgnore
public String getStudyId() {
return studyId;
}
/** @see #getStudyId */
@JsonIgnore
public void setStudyId(String studyId) {
this.studyId = studyId;
}
/** Custom DynamoDB marshaller for the field definition list. This uses Jackson to convert to and from JSON. */
public static class FieldDefinitionListMarshaller implements DynamoDBMarshaller<List<UploadFieldDefinition>> {
/** {@inheritDoc} */
@Override
public String marshall(List<UploadFieldDefinition> fieldDefList) {
try {
return JsonUtils.INTERNAL_OBJECT_MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(
fieldDefList);
} catch (JsonProcessingException ex) {
throw new DynamoDBMappingException(ex);
}
}
/** {@inheritDoc} */
@Override
public List<UploadFieldDefinition> unmarshall(Class<List<UploadFieldDefinition>> clazz, String json) {
try {
return JsonUtils.INTERNAL_OBJECT_MAPPER.readValue(json,
new TypeReference<List<UploadFieldDefinition>>() {});
} catch (IOException ex) {
throw new DynamoDBMappingException(ex);
}
}
}
}
|
package com.eaglesakura.android.util;
import com.eaglesakura.lambda.Matcher1;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.graphics.Rect;
import android.support.annotation.IdRes;
import android.support.annotation.NonNull;
import android.text.Editable;
import android.text.InputType;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.EditText;
import android.widget.ImageView;
import java.util.ArrayList;
import java.util.List;
/**
* View
*/
public class ViewUtil {
/**
* CardViewitem
*/
public static void matchCardWidth(View itemView) {
if (itemView.getLayoutParams() == null) {
itemView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
}
}
/**
* ImageView
* <br>
* View
*/
public static void setWidthMatchImage(ImageView view, Bitmap image) {
Matrix matrix = new Matrix();
float scale = (float) view.getWidth() / (float) image.getWidth();
int newHeight = (int) (scale * image.getHeight());
matrix.postScale(
scale, scale
);
view.setScaleType(ImageView.ScaleType.MATRIX);
view.setImageMatrix(matrix);
setViewHeight(view, newHeight);
view.setImageBitmap(image);
}
/**
* View
*/
public static void setViewHeight(View itemView, int height) {
ViewGroup.LayoutParams params = itemView.getLayoutParams();
params.height = height;
itemView.setLayoutParams(params);
}
public static void insertTextInCursor(EditText editText, String text) {
int start = editText.getSelectionStart();
int end = editText.getSelectionEnd();
Editable editable = editText.getText();
editable.replace(Math.min(start, end), Math.max(start, end), text);
}
public static void setInputIntegerOnly(EditText editText) {
editText.setMaxLines(1);
editText.setInputType(InputType.TYPE_CLASS_NUMBER);
}
public static void setInputDecimal(EditText editText) {
editText.setMaxLines(1);
editText.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
}
public static double getDoubleValue(EditText text, double defValue) {
try {
return Double.valueOf(text.getText().toString());
} catch (Exception e) {
return defValue;
}
}
public static long getLongValue(EditText text, long defValue) {
try {
return Long.valueOf(text.getText().toString());
} catch (Exception e) {
return defValue;
}
}
public static int getTouchPointerId(MotionEvent event) {
int pointerId = (event.getAction() & MotionEvent.ACTION_POINTER_INDEX_MASK) >> MotionEvent.ACTION_POINTER_INDEX_SHIFT;
return event.getPointerId(pointerId);
}
@SuppressLint("SetJavaScriptEnabled")
public static WebView setupDefault(WebView webView) {
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setAppCacheEnabled(true);
webView.setWebChromeClient(new WebChromeClient());
webView.setWebViewClient(new WebViewClient() {
@Override
public boolean shouldOverrideUrlLoading(WebView view, final String url) {
return false;
}
});
return webView;
}
public static View findViewById(View view, @IdRes int... id) {
for (int i : id) {
if (view == null) {
return null;
}
view = view.findViewById(i);
}
return view;
}
public static View findViewById(Activity activity, @IdRes int... id) {
View view = null;
for (int i : id) {
if (view == null) {
view = activity.findViewById(i);
} else {
view = view.findViewById(i);
}
if (view == null) {
return null;
}
}
return view;
}
public static View findViewByMatcher(View view, Matcher1<View> matcher) {
if (view == null) {
return null;
}
try {
if (matcher.match(view)) {
return view;
}
if (view instanceof ViewGroup) {
ViewGroup viewGroup = (ViewGroup) view;
for (int i = 0; i < viewGroup.getChildCount(); ++i) {
View child = findViewByMatcher(viewGroup.getChildAt(i), matcher);
if (child != null) {
return child;
}
}
}
return null;
} catch (Throwable e) {
throw new RuntimeException(e);
}
}
public static List<View> listViews(View root, Matcher1<View> matcher) {
List<View> result = new ArrayList<>();
if (root == null) {
return result;
}
try {
if (matcher.match(root)) {
result.add(root);
}
if (root instanceof ViewGroup) {
ViewGroup viewGroup = (ViewGroup) root;
for (int i = 0; i < viewGroup.getChildCount(); ++i) {
result.addAll(listViews(viewGroup.getChildAt(i), matcher));
}
}
return result;
} catch (Throwable e) {
throw new RuntimeException(e);
}
}
public static Rect getScreenArea(@NonNull View view) {
Rect area = new Rect();
int[] viewInWindow = new int[2];
int[] viewOnScreen = new int[2];
int[] windowOnScreen = new int[2];
view.getLocationInWindow(viewInWindow);
view.getLocationOnScreen(viewOnScreen);
windowOnScreen[0] = viewOnScreen[0] - viewInWindow[0];
windowOnScreen[1] = viewOnScreen[1] - viewInWindow[1];
view.getGlobalVisibleRect(area);
area.offset(windowOnScreen[0], windowOnScreen[1]);
return area;
}
public static Rect getWindowArea(@NonNull View view) {
int[] xy = new int[2];
view.getLocationInWindow(xy);
return new Rect(xy[0], xy[1], xy[0] + view.getWidth(), xy[1] + view.getHeight());
}
}
|
package com.doos.update_module.update;
import com.doos.settings_manager.ApplicationConstants;
import com.doos.update_module.gui.UpdateDialog;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import org.bridj.Pointer;
import org.bridj.cpp.com.COMRuntime;
import org.bridj.cpp.com.shell.ITaskbarList3;
import org.bridj.jawt.JAWTUtils;
import javax.net.ssl.HttpsURLConnection;
import javax.swing.*;
import java.awt.*;
import java.io.*;
import java.net.URI;
import java.net.URL;
import static com.doos.settings_manager.core.SettingsManager.showErrorMessage;
public class Updater {
private static final String githubUrl = "https://api.github.com/repos/benchdoos/WeblocOpener/releases/latest";
private static final String DEFAULT_ENCODING = "UTF-8";
public static File installerFile = null;
private static HttpsURLConnection connection = null;
private AppVersion appVersion = null;
public Updater() {
try {
getConnection();
if (!connection.getDoOutput()) {
connection.setDoOutput(true);
}
if (!connection.getDoInput()) {
connection.setDoInput(true);
}
} catch (IOException e) {
e.printStackTrace();
}
try {
String input = null;
try (BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(connection.getInputStream(), DEFAULT_ENCODING))) {
input = bufferedReader.readLine();
JsonParser parser = new JsonParser();
JsonObject root = parser.parse(input).getAsJsonObject();
appVersion = new AppVersion();
appVersion.setVersion(root.getAsJsonObject().get("tag_name").getAsString());
JsonArray asserts = root.getAsJsonArray("assets");
for (JsonElement assert_ : asserts) {
JsonObject userObject = assert_.getAsJsonObject();
if (userObject.get("name").getAsString().equals("WeblocOpenerSetup.exe")) {
appVersion.setDownloadUrl(userObject.get("browser_download_url").getAsString());
appVersion.setSize(userObject.get("size").getAsInt());
}
}
} catch (NullPointerException e) {
e.getStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
showErrorMessage("Can not Update", "Can not connect to api.github.com");
}
}
public static int startUpdate(AppVersion appVersion) {
installerFile = new File(ApplicationConstants.UPDATE_PATH_FILE
+ "WeblocOpenerSetupV" + appVersion.getVersion() + ".exe");
if (!Thread.currentThread().isInterrupted()) {
if (!installerFile.exists()) {
installerFile = downloadNewVersionInstaller(appVersion);
}
int installationResult = 0;
try {
if (!Thread.currentThread().isInterrupted()) {
installationResult = update(installerFile);
}
} catch (IOException e) {
if (e.getMessage().contains("CreateProcess error=193")) {
try {
if (!Thread.currentThread().isInterrupted()) {
installerFile.delete();
installerFile = downloadNewVersionInstaller(appVersion); //Fixes corrupt file
installationResult = update(installerFile);
}
} catch (IOException e1) {
if (e1.getMessage().contains("CreateProcess error=193")) {
installerFile.delete();
return 193;
}
}
}
}
deleteFileIfSuccess(installationResult);
return installationResult;
} else {
return 0; //TODO maybe -1?
}
}
private static void deleteFileIfSuccess(int installationResult) {
if (installationResult == 0) {
installerFile.deleteOnExit();
}
}
private static int update(File file) throws IOException {
Runtime runtime = Runtime.getRuntime();
UpdateDialog.updateDialog.buttonCancel.setEnabled(false);
Process updateProcess;
updateProcess = runtime.exec(file.getAbsolutePath() + ApplicationConstants.APP_INSTALL_SILENT_KEY);
int result = -1;
try {
if (!Thread.currentThread().isInterrupted()) {
result = updateProcess.waitFor();
}
UpdateDialog.updateDialog.buttonCancel.setEnabled(true);
return result;
} catch (InterruptedException e) {
e.printStackTrace();
UpdateDialog.updateDialog.buttonCancel.setEnabled(true);
return 1;
}
}
private static File downloadNewVersionInstaller(AppVersion appVersion) {
JProgressBar progressBar = null;
if (UpdateDialog.updateDialog != null) {
progressBar = UpdateDialog.updateDialog.progressBar1;
}
ITaskbarList3 list = null;
Pointer<?> hwnd;
try {
list = COMRuntime.newInstance(ITaskbarList3.class);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
long hwndVal = JAWTUtils.getNativePeerHandle(UpdateDialog.updateDialog);
hwnd = Pointer.pointerToAddress(hwndVal);
try {
if (progressBar != null) {
progressBar.setStringPainted(true);
}
BufferedInputStream in = null;
FileOutputStream fout = null;
try {
in = new BufferedInputStream(new URL(appVersion.getDownloadUrl()).openStream());
try {
fout = new FileOutputStream(installerFile);
final int bufferLength = 1024 * 1024;
final byte data[] = new byte[bufferLength];
int count;
int progress = 0;
while ((count = in.read(data, 0, bufferLength)) != -1) {
if (Thread.currentThread().isInterrupted()) {
installerFile.delete();
if (progressBar != null) {
progressBar.setValue(0);
if (list != null) {
list.SetProgressValue((Pointer) hwnd, progressBar.getValue(),
progressBar.getMaximum());
}
}
break;
} else {
fout.write(data, 0, count);
progress += count;
int prg = (int) (((double) progress / appVersion.getSize()) * 100);
if (progressBar != null) {
progressBar.setValue(prg);
if (list != null) {
list.SetProgressValue((Pointer) hwnd, progressBar.getValue(),
progressBar.getMaximum());
}
}
}
}
} catch (FileNotFoundException e) {
if (installerFile.exists() && installerFile.getName().contains("WeblocOpenerSetup")) { //TODO FIX
// HERE
installerFile.delete();
fout = new FileOutputStream(installerFile);
}
}
} finally {
if (in != null) {
in.close();
}
if (fout != null) {
fout.close();
}
if (Thread.currentThread().isInterrupted()) {
installerFile.delete();
}
if (list != null) {
list.Release();
}
}
} catch (IOException e) {
e.printStackTrace();
}
return installerFile;
}
public static void openUrl(String url) {
if (!Desktop.isDesktopSupported()) {
return;
}
Desktop desktop = Desktop.getDesktop();
try {
desktop.browse(URI.create(url));
} catch (IOException e) {
JOptionPane.showMessageDialog(new Frame(), "URL is corrupt: " + url);
}
}
private HttpsURLConnection getConnection() throws IOException {
URL url = new URL(githubUrl);
//if (connection == null) {
connection = (HttpsURLConnection) url.openConnection();
return connection;
}
public AppVersion getAppVersion() {
return appVersion;
}
}
|
package com.ecbeta.common.core;
import static com.ecbeta.common.constants.Constants.AA_REFRESH_ZONES_NAME;
import static com.ecbeta.common.constants.Constants.ACTION_NAME;
import static com.ecbeta.common.constants.Constants.BTN_OPTION;
import static com.ecbeta.common.constants.Constants.JSON_REFRESH_TYPE;
import static com.ecbeta.common.constants.Constants.PROGRESS_PAGE_POSTBACK;
import static com.ecbeta.common.constants.Constants.REFRESH_TYPE;
import static com.ecbeta.common.constants.Constants.UNDER_LINE;
import static com.ecbeta.common.core.reflect.BingReflectUtils.automaticBindingJsonParams;
import static com.ecbeta.common.core.reflect.BingReflectUtils.automaticBindingParams;
import static com.ecbeta.common.core.reflect.BingReflectUtils.findAction;
import static com.ecbeta.common.core.reflect.BingReflectUtils.findActionMethod;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.Arrays;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.StringUtils;
import com.ecbeta.common.constants.Constants;
import com.ecbeta.common.core.annotation.Action;
import com.ecbeta.common.core.annotation.Actions;
import com.ecbeta.common.core.db.NavigationUtil;
import com.ecbeta.common.core.servlet.CoreServlet;
import com.ecbeta.common.core.viewer.BaseViewer;
import com.ecbeta.common.core.viewer.bean.ExportInformationBean;
import com.ecbeta.common.core.viewer.bean.NavigationBean;
import com.ecbeta.common.core.viewer.bean.PanelTab;
public abstract class AbstractWorker {
public static boolean debug = false;
public static final boolean _SHOW_EXCEPTION = true;
private static final int _PROCESS_STATUS_IGNORE = 0, _PROCESS_STATUS_SUCCESS = 1,
_PROCESS_STATUS_NOMETHOD = 2, _PROCESS_STATUS_FAIL = 3;
private final static Class<?> [][] PARAMETER_TYPES_ARRAY = new Class[][]{null, new Class[] { String.class },
new Class[] {HttpServletRequest.class, String.class }, new Class[] { String.class , HttpServletRequest.class } };
public static void main (String[] rags) {
}
private HttpServletRequest request;
private HttpServletResponse response;
private ServletContext servletContext;
private NavigationBean navigationBean;
private String jspPath;
public String btnClicked;
public boolean needForwordToJsp = true;
// private static Map<String, Boolean> autoBindingFlagCache = new
// HashMap<String, Boolean>();
public void addRefreshZone (String zones) {
if (zones == null || zones.trim().equals("")) return;
String s = (String) this.getRequest().getAttribute(AA_REFRESH_ZONES_NAME);
if (s == null) {
this.setRefreshZones(zones);
return;
}
if (s.endsWith(",")) {
this.setRefreshZones(s + zones);
} else {
this.setRefreshZones(s + "," + zones);
}
}
public String allRefreshZone () {
return "result,sourcePanelZone,topNavigationZone";
}
protected void bindJsonParams (HttpServletRequest request, String btnClicked, String actionMethod) {
automaticBindingJsonParams(request, btnClicked, actionMethod, this.getServicer());
automaticBindingJsonParams(request, btnClicked, actionMethod, this.getOtherServicers());
}
protected void bindParams (HttpServletRequest request, String btnClicked, String actionMethod) {
if (this.getServicer() != null) {
this.getServicer().beforeBinding(btnClicked);
}
automaticBindingParams(request, btnClicked, actionMethod, this.getServicer());
automaticBindingParams(request, btnClicked, actionMethod, this.getOtherServicers());
// TODO;
}
/*
public void bindParamsDisplayAndSort (HttpServletRequest request) {
// this.getServicer().getBaseServicerParameterBean().bindTopBart(request, this.getServicer().getBaseServicerParameterBean().getTopBarID("TopBar"));
}
public void changeDecimalAction () {
this.setRefreshZones("result");
this.getServicer().setReportDecimalControlList(TopBar2StateBean.parseOnlyDecimal(this.getRequest(), this.getServicer().getBaseServicerParameterBean().getTopBarID("TopBar")).getValue());
}
public void changePaginatorAction () {
PaginatorStateBean stateBean = this.getServicer().getPaginatorStateBean();
stateBean.parse(this.getRequest());
this.getServicer().handlePaginator(this.getServicer().getPanelIndex());
this.setRefreshZones("panelZone,result");
}*/
/* public void changePanelAction () {
this.setRefreshZones("result,topNavigationZone,sortDialogZone,filterDialogZone,displayDialogZone");
}
public void changeSortDisplayModeAction () {
this.setRefreshZones("result,sourcePanelZone");
}*/
/* public void changeTimeAction () {
}*/
public void clearResultAction () {
this.getServicer().destory();
this.getServicer().getBaseServicerParameterBean().setDisplayStage(false);
this.setRefreshZones(this.allRefreshZone());
}
/**
* this method only dispatch btnClicked action, don't write another
* logic in this method. all method should be use Action as suffix w/o
* or with btnClick as parameter as neccersy.
*
* @param btnClicked
*/
public String createAction (String btnClicked) {
if (btnClicked == null || btnClicked.trim().equals("")) return null;
String methodName = null;
if ("resetDialog".equals(btnClicked)) {
methodName = "resetDialog" + ACTION_NAME;
} else if (btnClicked.endsWith("Dialog")) {
methodName = "popupDialog" + ACTION_NAME;
} else if (btnClicked.startsWith("rspModule")) {
methodName = "changeRSPModule" + ACTION_NAME;
} else {
methodName = btnClicked.replaceAll(UNDER_LINE, "");
if (methodName.endsWith(ACTION_NAME)) {} else {
methodName = methodName + ACTION_NAME;
}
}
if (btnClicked.startsWith("refresh")) {
String s = btnClicked.replace("refresh", "");
if (s.length() >= 1) {
s = s.substring(0, 1).toLowerCase() + s.substring(1);
this.addRefreshZone(s + "Zone");
}
}
if (methodName.charAt(1) >= 'A' && methodName.charAt(1) <= 'Z') {
return methodName;
}
return methodName.substring(0, 1).toLowerCase() + methodName.substring(1);
}
/**
* @param btnClicked2
*/
public void dispatchAction (String btnClicked) {
}
/* @SuppressWarnings("unchecked")
public void displayRefreshAction () {
this.getServicer().updateDisplay(this.btnClicked);
this.setRefreshZones("result");
}
*/
private void doActionAnnotation (Action annotation) {
if (StringUtils.isNotEmpty(annotation.refreshZones())) {
this.addRefreshZone(annotation.refreshZones());
}
this.needForwordToJsp = annotation.needForwordToJsp();
if (annotation.clearResult()) {
this.clearResultAction();
}
}
private void doActionAnnotation (Method method, String action) {
if (method == null) return;
if (method.isAnnotationPresent(Action.class)) {
Action annotation = (Action) method.getAnnotation(Action.class);
this.doActionAnnotation(annotation);
} else if (method.isAnnotationPresent(Actions.class)) {
Actions actions = (Actions) method.getAnnotation(Actions.class);
Action act = findAction(actions, action);
if (act != null) {
this.doActionAnnotation(act);
}
}
}
protected boolean enableActionAnnotation () {
return false;
}
/* public void exportExcelAction () {
}*/
/*
public void exportPDFAction () {
this.needForwordToJsp = false;
}*/
/* public void filterRefreshAction () {
this.getServicer().processFilter();
this.setRefreshZones("result");
//
}
*/
private boolean findAnnotationInClassLevel ( Class<?> ownerClass, String action) {
if (ownerClass.isAnnotationPresent(Actions.class)) {
Actions actions = (Actions) ownerClass.getAnnotation(Actions.class);
Action act = findAction(actions, action);
if (act != null) {
this.doActionAnnotation(act);
return true;
}
}
return false;
}
/* public void downloadExcelAction(){
}*/
protected void forwardToJsp(String jsp) throws IOException, ServletException{
this.getServletContext().getRequestDispatcher(jspPath+jsp).forward(getRequest(), getResponse());
}
public String getAppName () {
String workerName = this.getWORKER_NAME();
return workerName.substring(0, workerName.length() - "Worker".length());
}
private final Object[][] getArgs(HttpServletRequest request, String btnClicked){
return new Object[][]{
null,
new Object[]{btnClicked},
new Object[]{request, btnClicked},
new Object[]{btnClicked, request},
};
}
/**
* @return the btnClicked
*/
public String getBtnClicked () {
return btnClicked;
}
public String getClearResultActions () {
return "";
}
public ExportInformationBean getExportInformationBean(){
return null;
}
/**
* @return the fORM_NAME
*/
public abstract String getFORM_NAME ();
/**
* @return the jSP_TOGO
*/
public String getJSP_TOGO(){
return this.getJSP_TOGO_PERIX()+".jsp";
}
public abstract String getJSP_TOGO_PERIX ();
public String getJspGoto () {
return getJSP_TOGO();
}
/**
* @return the navigationBean
*/
public NavigationBean getNavigationBean () {
return navigationBean;
}
public String getNavTier(){
if(this.navigationBean != null){
return this.navigationBean.getNavTier("_");
}
return "";
}
public Object[] getOtherServicers () {
return null;
}
public PanelTab[] getPanels(){
return this.getServicer().getPanels();
}
public String getRenderHTML () {
BaseViewer viewer = this.getViewer(true);
if (viewer != null) {
if (!this.hasData()) {
return "";
}
try {
viewer.export(new org.apache.commons.io.output.NullOutputStream(), this.getJSP_TOGO_PERIX() + ".html");
String s = viewer.toHTML();
return s;
} catch (Exception e) {
}
}
return "";
}
public HttpServletRequest getRequest () {
return request;
}
public HttpServletResponse getResponse () {
return response;
}
/**
* This is main servicer
* @return
*/
public abstract AbstractServicer getServicer ();
public ServletContext getServletContext () {
return servletContext;
}
public String getUrl () {
StringBuilder url = new StringBuilder();
url.append(this.navigationBean.getUrl(this.request.getContextPath()));
url.append("&");
url.append(Constants.SRC_JSP).append("=").append(this.getJSP_TOGO()).append("&");
url.append(Constants.BTN_OPTION).append("=");
return url.toString();
}
public BaseViewer getViewer (boolean isHTML) {
return null;
}
/**
* @return the wORKER_NAME
*/
public String getWORKER_NAME () {
return this.getClass().getSimpleName();
}
public boolean hasData (){
return true;
}
public void init (HttpServletRequest request, HttpServletResponse response, String jspPath, CoreServlet servlet, ServletContext servletContext) {
this.request = request;
this.response = response;
this.servletContext = servletContext;
String navTier = request.getParameter(Constants.NAV_TIERS);
if(StringUtils.isEmpty(navTier)){
navTier = "0_0_0_0";
}
this.navigationBean = servlet.find(navTier.split("_"));
this.btnClicked = request.getParameter(BTN_OPTION);
this.jspPath = jspPath;
}
public boolean isDebug () {
return debug;
}
public boolean isUseActionFromServicer () {
return true;
}
public void otherClickedAction () {
this.setRefreshZones("result");
}
/* public void popupDialogAction () {
this.setRefreshZones(this.btnClicked + "Zone," + this.btnClicked + "BottomZone");
}*/
public void processButtonClickedAction (String action) {
try{
Object[] _instance = this.isUseActionFromServicer() ? new Object[]{this, this.getServicer()} : new Object[]{this};
int []_processStatus = new int[_instance.length];
Arrays.fill(_processStatus, _PROCESS_STATUS_IGNORE);
Object[][] args = this.getArgs(this.getRequest(), btnClicked);
outer: for(int c = 0; c < _instance.length; c++){
for(int i = 0 ; i < PARAMETER_TYPES_ARRAY.length && i < args.length; i++){
_processStatus[c] = this.processButtonClickedAction(action, _instance[c].getClass() , _instance[c], PARAMETER_TYPES_ARRAY[i], args[i]);
if( _processStatus[c] != _PROCESS_STATUS_NOMETHOD){
break outer;
}
}
}
if(_processStatus[0] != _PROCESS_STATUS_SUCCESS && _processStatus[0] != _PROCESS_STATUS_IGNORE){
this.otherClickedAction();
this.dispatchAction(this.btnClicked);
}
if ( !"clearResultAction".equals(action) && StringUtils.isNotEmpty(this.getClearResultActions()) && (this.getClearResultActions().contains(this.btnClicked) || this.getClearResultActions().contains(action) )) {
this.clearResultAction();
}
}catch(Exception e){
e.printStackTrace();
}
}
protected void setJSONHeader() {
this.getResponse().setContentType("application/json; charset=UTF-8");
this.getResponse().setHeader("Cache-Control", "no-store, max-age=0, no-cache, must-revalidate");
this.getResponse().addHeader("Cache-Control", "post-check=0, pre-check=0");
this.getResponse().setHeader("Pragma", "no-cache");
}
protected void returnJSON(Object o) {
this.setJSONHeader();
try{
this.getResponse().getWriter().write(JSONObject.fromObject(o).toString());
}catch(Exception e){
e.printStackTrace();;
this.getResponse().getWriter().write(JSONArray.fromObject(o).toString());
}
}
private transient Object result;
private int processButtonClickedAction (String action, Class<?> ownerClass, Object instance , Class<?>[] _classTypes, Object[] args) {
if (action == null) return _PROCESS_STATUS_IGNORE;
if (enableActionAnnotation() && findAnnotationInClassLevel(ownerClass, action)) {
return _PROCESS_STATUS_SUCCESS;
}
String key = ownerClass.getName() + "_" + action;
Method method = null;
try {
if (enableActionAnnotation() && method == null) {
method = findActionMethod(ownerClass, action);
}
boolean withBtnPara = false;
if (null == method) {
method = ownerClass.getMethod(action, _classTypes);
withBtnPara = true;
}
this.result = withBtnPara ? method.invoke(instance, args) : method.invoke(instance);
this.doActionAnnotation(method, action);
return _PROCESS_STATUS_SUCCESS;
} catch (SecurityException e) {
this.showException(key + " " + (method == null ? "": method.toString() ) , e, true);
} catch (NoSuchMethodException e) {
this.showException(key + " " + (method == null ? "": method.toString() ) , e, false);
return _PROCESS_STATUS_NOMETHOD;
} catch (Exception e) {
this.showException(key + " " + (method == null ? "": method.toString() ) , e, false);
}
return _PROCESS_STATUS_FAIL;
}
public void processRequest () {
this.getResponse().setContentType("text/html");
this.needForwordToJsp = true;
this.result = null;
this.setRefreshZones("");
HttpServletRequest request = this.getRequest();
try {
if (this.getServicer().getExportInformationBean() == null) {
this.getServicer().setExportInformationBean(this.getExportInformationBean());
}
} catch (Exception e) {
e.printStackTrace();
}
try{
try {
this.btnClicked = request.getParameter(BTN_OPTION);
if(StringUtils.isEmpty(this.btnClicked)){
this.btnClicked = "";
}
String refresh = request.getParameter(REFRESH_TYPE);
this.needForwordToJsp = !(refresh != null && refresh.equals(JSON_REFRESH_TYPE) );
String action = this.createAction(btnClicked);
if (this.btnClicked.equals(PROGRESS_PAGE_POSTBACK)) {
} else if ((refresh != null && refresh.equals(JSON_REFRESH_TYPE) )) {
this.bindJsonParams(request, btnClicked, action);
} else {
this.bindParams(request, btnClicked, action);
}
if (this.btnClicked != null && !"".equals(this.btnClicked) && (!this.btnClicked.equals("") && (!this.btnClicked.equals(PROGRESS_PAGE_POSTBACK) ) )) {
this.processButtonClickedAction(action);
}
} catch (Exception e) {
e.printStackTrace();
}
String zones = request.getParameter(AA_REFRESH_ZONES_NAME);
if (StringUtils.isNotEmpty(zones)) {
this.addRefreshZone(zones);
}
if (StringUtils.isEmpty(request.getAttribute(AA_REFRESH_ZONES_NAME) + "")) {
this.addRefreshZone("result");
}
this.addRefreshZone("excludeDateTimeZone,footerZone,alwaysRefreshZone");
if(this.result != null && StringUtils.isNotEmpty(this.result.toString())){
returnJSON(this.result);
}else if (this.needForwordToJsp && (!getResponse().isCommitted() )) {
try {
forwardToJsp(getJSP_TOGO());
} catch (Exception e) {
e.printStackTrace();
}
}
}finally{
}
}
/* public void reloadFromSnapshotAction(){
this.clearResultAction();
}*/
public void resetDialogAction () {
this.setRefreshZones("sourcePanelZone,topNavigationZone,sortDialogZone,filterDialogZone,displayDialogZone");
}
public void setDebug (boolean debug) {
AbstractWorker.debug = debug;
}
public void setRefreshZones (String zones) {
this.getRequest().setAttribute(AA_REFRESH_ZONES_NAME, zones);
}
public void setRequest (HttpServletRequest request) {
this.request = request;
}
public void setResponse (HttpServletResponse response) {
this.response = response;
}
public void setServletContext (ServletContext servletContext) {
this.servletContext = servletContext;
}
private void showException(String acc, Exception e, boolean forceOut){
if (_SHOW_EXCEPTION || forceOut) {
e.printStackTrace();
}
}
/* public void sortRefreshAction () {
}
*/
public void submitAction () {
submitAction(false, false);
}
public void submitAction (boolean withOutSort, boolean withOutDisplay) {
final AbstractServicer servicer = this.getServicer();
servicer.destory();
try {
this.getServicer().retrieveData();
} catch (Exception e) {
e.printStackTrace();
}
if(!withOutSort){
servicer.sort();
}
if(!withOutDisplay){
servicer.updateDisplay(this.btnClicked);
}
servicer.getBaseServicerParameterBean().setDisplayStage(true);
servicer.getBaseServicerParameterBean().setSelectionPanelStatusOpen(false);
this.setRefreshZones("");
}
public void updateExportInformationBean () {
this.getServicer().updateExportInformationBean();
}
}
|
package model;
import java.io.IOException;
import org.apache.log4j.Logger;
public class ShellNotificationTarget implements NotificationTarget {
static Logger logger = Logger.getLogger(ShellNotificationTarget.class);
String template;
Runtime runtime;
int suppressedMinutes = 0;
public ShellNotificationTarget(String template) {
this.template = template;
this.runtime = Runtime.getRuntime();
}
public void suppressUntil(int contestMinutes) {
this.suppressedMinutes = contestMinutes;
}
@Override
public void notify(LoggableEvent event) {
if (event.time < suppressedMinutes) {
return;
}
String command = substituteTags(event);
try {
logger.info(String.format("Executing: %s", command));
runtime.exec(command);
} catch (IOException e) {
logger.error(String.format("Error executing '%s':%s", command, e));
}
}
public static String escape(String source) {
StringBuilder target = new StringBuilder();
for (int i=0; i<source.length(); i++) {
char c = source.charAt(i);
if (Character.isLetter(c)) {
target.append(c);
} else if (Character.isWhitespace(c)) {
target.append("_");
}
}
return target.toString();
}
private String substituteTags(LoggableEvent event) {
String output = template;
if (event.team != null) {
output = output.replace("{teamId}", Integer.toString(event.team.getTeamNumber()));
}
if (event.submission != null) {
output = output.replace("{runId}", Integer.toString(event.submission.id));
output = output.replace("{problemLetter}", event.submission.problem.getLetter());
output = output.replace("{teamName}", escape(event.team.getName()));
}
output = output.replace("{time}", Integer.toString(event.time));
if (event.supplements != null) {
for (String key : event.supplements.keySet()) {
String value = event.supplements.get(key);
output = output.replace("{"+key+"}", value);
}
}
return output;
}
}
|
package cmput301f17t26.smores.all_models;
import java.util.UUID;
public class Request {
private String mToUser;
private String mFromUser;
private String mID;
public Request(String fromUser, String toUser) {
mToUser = toUser;
mFromUser = fromUser;
mID = mToUser + mFromUser;
}
public String getID() {
return mID;
}
public String getToUser() {
return mToUser;
}
public String getFromUser() {
return mFromUser;
}
}
|
package org.aksw.kbox;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.URL;
import java.nio.file.InvalidPathException;
import org.aksw.kbox.utils.ArrayUtils;
import org.aksw.kbox.utils.ObjectUtils;
import org.apache.log4j.Logger;
public class KBox extends ObjectUtils {
private final static String KBOX_FOLDER = ".kbox";
private final static String KBOX_RESOURCE_FOLDER = "KBOX_RESOURCE_FOLDER";
private final static String KBOX_CONFIG_CONTEXT = "kbox";
public final static String KBOX_CONFIG_FILE = ".config";
public final static String KBOX_DIR = System.getProperty("user.home")
+ File.separator + KBOX_FOLDER;
private static final String CHK = ".chk";
private final static Logger logger = Logger.getLogger(KBox.class);
static {
try {
init();
} catch (Exception e) {
logger.error("Error initializing KBox.", e);
}
}
protected static void init() throws Exception {
File kBoxDir = new File(KBOX_DIR);
if (!kBoxDir.exists()) {
kBoxDir.mkdir();
setResourceFolder(KBOX_DIR);
}
}
private static CustomParams getParams() {
CustomParams params = new CustomParams(KBOX_DIR + File.separator
+ KBOX_CONFIG_FILE, KBOX_CONFIG_CONTEXT);
return params;
}
/**
* Converts an URL to a local path.
*
* @param url an URL.
*/
public static String urlToPath(URL url) {
String urlPath = url.getPath();
String host = url.getHost();
String protocol = url.getProtocol();
int port = url.getPort();
String[] pathDirs = urlPath.split("/");
String[] hostDirs = host.split("\\.");
ArrayUtils.reverse(hostDirs);
String path = protocol + File.separator;
if (port != -1) {
path += port + File.separator;
}
for (String hostDir : hostDirs) {
path += hostDir + File.separator;
}
for (String pathDir : pathDirs) {
pathDir = pathDir.replace(":", File.separator);
path += pathDir + File.separator;
}
path = path.substring(0, path.length() - 1);
return path;
}
/**
* Returns the local resource path of the give URL.
*
* @param url the resource URL
* @return the URL of the local resource path.
*/
public static File locate(URL url) throws Exception {
ResourceLocate locate = new ResourceLocate();
return locate(url, locate);
}
/**
* Returns the local resource path given by the locate.
*
* @param url the resource URL
* @return the local path of the resource.
*/
public static File locate(URL url, Locate locate) throws Exception {
return locate.locate(url);
}
/**
* Converts an URL to an absolute local path.
*
* @param url an URL.
*/
public static String urlToAbsolutePath(URL url) {
String resourceFolder = getResourceFolder();
File resource = new File(resourceFolder + File.separator
+ urlToPath(url));
return resource.getAbsolutePath();
}
/**
* Create a KBox directory representing the {@link URL}.
*
* @param the KBox directory representing the given {@link URL}.
*/
public static File newDir(URL url) {
File resource = new File(urlToAbsolutePath(url));
resource.mkdirs();
return resource;
}
/**
* Replace the old resource folder by the given one.
*
* @param resourceFolderPath - a full path folder where the
* resources were going to be saved.
* The default resource folder is "user/.kbox".
*
*/
public static void setResourceFolder(String resourceFolderPath) {
File resourceDir = new File(resourceFolderPath);
if (!(resourceDir.exists() || resourceDir.isDirectory())) {
throw new InvalidPathException(resourceFolderPath,
"The given path does not exist or is not a directory.");
}
CustomParams params = getParams();
params.setProperty(KBOX_RESOURCE_FOLDER, resourceFolderPath);
}
/**
* Get the default resource folder.
*
* @return the full path of the default resource folder.
*/
public static String getResourceFolder() {
CustomParams params = getParams();
String resourceFolderPath = params.getProperty(KBOX_RESOURCE_FOLDER,
KBOX_DIR);
return resourceFolderPath;
}
/**
* Get a local mirror of the given resource.
* This method will not try to install the resource and will return null in
* case it does not exists.
*
* @param url the remote {@link URL} of the resource to be retrieved.
*
* @return a file pointing to a local KBox resource.
*
* @throws Exception if the resource can not be located or some error occurs
* during the KBox resource lookup.
*/
public static File getResource(URL url) throws Exception {
return getResource(url, false);
}
/**
* Get a local mirror of the remote resource or null
* if does not exist.
* If the flag install is set to true, returns a local copy
* of the resource if it already exists or create it otherwise.
*
* @param url the remote {@link URL} of the resource to be retrieved.
* @param install specify if the resource should be installed in case in does
* no exist (true) or not (false).
*
* @return a file pointing to a local resource.
*
* @throws Exception if the resource can not be located or some error
* occurs while creating the local mirror.
*/
public static File getResource(URL url, boolean install) throws Exception {
ResourceLocate resourceLocate = new ResourceLocate();
ResourceInstall resourceInstall = new ResourceInstall();
return getResource(url, resourceLocate, resourceInstall, install);
}
/**
* Get a local mirror of the remote resource or null
* if does not exist.
* If the flag install is set to true, returns a local copy
* of the resource if it already exists or create it otherwise.
*
* @param url the remote URL of the resource to be retrieved.
* @param install specify if the resource should be installed (true) or not
* (false).
* @param method the method that will be used to install the resource in case
* it is not installed and install install param is set true.
*
* @return a {@link File} pointing to a local copy of the resource or {@link null} otherwise.
*
* @throws Exception if the resource can not be located or some error occurs
* while creating the local mirror.
*/
public static File getResource(URL url, Install method, boolean install)
throws Exception {
ResourceLocate resourceLocate = new ResourceLocate();
return getResource(url, resourceLocate, method, install);
}
/**
* Get a local mirror of the remote resource or null
* if does not exist.
* If the flag install is set to true, returns a local copy
* of the resource if it already exists or create it otherwise.
*
* @param url the remote {@link URL} of the resource to be retrieved.
* @param install specify if the resource should be installed (true) or not
* (false).
* @param method the method that will be used to install the resource in case
* it is not installed and install install param is set true.
*
* @return a {@link File} pointing to a local copy of the resource or {@link null} otherwise.
*
* @throws Exception if the resource can not be located or some error occurs
* while creating the local mirror.
*/
public static File getResource(URL url, Locate locateMethod, Install installMethod, boolean install)
throws Exception {
File resource = locateMethod.locate(url);
if (resource != null) {
return resource;
}
if(install) {
install(url, url, installMethod);
return locateMethod.locate(url);
}
return null;
}
/**
* Get a local mirror of the remote resource or {@link null} if it does
* not exist.
*
* @param url the remote {@link URL} of the resource to be retrieved.
*
* @return an {@link InputStream} pointing to a local copy of the
* resource.
*
* @throws Exception if the resource can not be located or some error occurs
* while creating the local mirror.
*/
public static InputStream getResourceAsStream(URL url) throws Exception {
return getResourceAsStream(url, false);
}
/**
* Get a local representation of the remote resource or null
* if does not exist.
* If the flag install is set to true, returns a local copy
* of the resource if it already exists or create it otherwise.
*
* This method will not try to install the resource and will return null in
* case it does not exists.
*
* @param url the remote {@link URL} of the resource to be retrieved.
* @param install specify if the resource should be installed in case in does
* no exist (true) or not (false).
*
* @return an {@link InputStream} pointing to a local copy of the
* resource.
*
* @throws Exception if the resource can not be located or some error occurs
* while copying the resource.
*/
public static InputStream getResourceAsStream(URL url, boolean install)
throws Exception {
return new FileInputStream(getResource(url, install));
}
/**
* Publish the dereferenced file in the given path on your Knowledge Box
* (KBox) resource folder. This function allows KBox to serve files to
* applications, acting as proxy to the published file. The file that is
* published in a give URL u will be located when the client execute the
* function KBox.getResource(u).
*
* @param source the {@link URL} of the file that is going to be published at the
* given {@link URL}.
* @param dest the {@link URL} were the dereferenced file is going to be
* published.
*
* @throws Exception if the resource does not exist or can not be copied
* or some error occurs during the resource publication.
*/
public static void install(URL source, URL dest) throws Exception {
try (InputStream is = source.openStream()) {
install(is, dest);
}
}
/**
* Publish the dereferenced file in a given {@link URL} in your corresponding local
* Knowledge Box (KBox) resource folder. This function allows KBox to serve
* files to applications, acting as proxy to the published file. The file
* that is installed in a give {@link URL} u will be located when the client
* executes the function KBox.getResource(u).
*
* @param url the {@link URL} of the resource that is going to be published at the
* given {@link URL}.
*
* @throws Exception if the resource does not exist or can not be copied or some
* error occurs during the resource publication.
*/
public static void install(URL url) throws Exception {
try (InputStream is = url.openStream()) {
install(is, url);
}
}
/**
* Publish the given input stream in the given {@link URL} on your local Knowledge
* Box (KBox) resource folder. This function allows KBox to serve files to
* applications, acting as proxy to the published file. The file that is
* installed in a give URL u will be located when the client execute the
* function KBox.getResource(u).
*
* @param source the {@link InputStream} that is going to be published in
* the given {@link URL}.
* @param dest the {@link URL} were the file is going to be published.
*
* @throws Exception if the resource does not exist or can not be copied or
* some error occurs during the resource publication.
*/
public static void install(InputStream source, URL dest)
throws Exception {
ResourceInstall resourceInstall = new ResourceInstall();
install(source, dest, resourceInstall);
}
/**
* Creates a mirror for the given file in a given {@link URL}. This function allows
* KBox to serve files to applications, acting as proxy to the mirrored
* file. The file that is published in a give {@link URL} u will be located when the
* client execute the function KBox.getResource(u).
*
* @param source the {@link URL} of the file that is going to be published at the
* given {@link URL}.
* @param dest the {@link URL} where the file is going to be published.
* @param install a customized method for installation.
*
* @throws Exception if the resource does not exist or can not be copied or some
* error occurs during the resource publication.
*/
public static void install(URL source, URL dest, Install install)
throws Exception {
install.install(source, dest);
}
/**
* Publish a given file in a given {@link URL} local directory. This function allows
* KBox to serve files to applications, acting as proxy to the published
* file. The file that is published in a give URL u will be located when the
* client execute the function KBox.getResource(u).
*
* @param source the {@link InputStream} of the file that is going to be published at
* the given {@link URL}.
* @param dest the {@link URL} where the file is going to be published.
* @param install the customized method for installation.
*
* @throws Exception if the resource does not exist or can not be copied or some
* error occurs during the resource publication.
*/
public static void install(InputStream source, URL dest, Install install)
throws Exception {
install.install(source, dest);
}
/**
* Install a given ZIP file from a given {@link URL}.
*
* @param source the source {@link URL} containing the ZIP file to be installed.
* @param dest the {@link URL} whereas the source will be installed.
*
* @throws Exception if an error occurs during the installation.
*/
public static void installFromZip(URL source, URL dest) throws Exception {
ZipInstall zipInstall = new ZipInstall();
install(source, dest, zipInstall);
}
/**
* Install a given ZIP file from a given {@link URL}.
*
* @param source the source {@link URL} containing the ZIP file to be installed.
*
* @throws Exception if an error occurs during the installation.
*/
public static void installFromZip(URL source) throws Exception {
installFromZip(source, source);
}
public static void validate(File resource) throws Exception {
validate(resource.getAbsolutePath());
}
public static void validate(String resourcePath) throws Exception {
String canonicalPath = getCanonicalPath(resourcePath);
File file = new File(canonicalPath + CHK);
file.createNewFile();
}
public static boolean isValid(String resourcePath) throws Exception {
String canonicalPath = getCanonicalPath(resourcePath);
File file = new File(canonicalPath + CHK);
return file.exists();
}
private static String getCanonicalPath(String path) throws Exception {
return getCanonicalPath(new File(path));
}
private static String getCanonicalPath(File path) throws Exception {
return path.getCanonicalPath();
}
}
|
package com.github.davidcarboni.restolino;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.net.URL;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpStatus;
import org.reflections.Reflections;
import org.reflections.util.ClasspathHelper;
import org.reflections.util.ConfigurationBuilder;
import com.github.davidcarboni.restolino.helpers.Path;
import com.github.davidcarboni.restolino.interfaces.Boom;
import com.github.davidcarboni.restolino.interfaces.Endpoint;
import com.github.davidcarboni.restolino.interfaces.Home;
import com.github.davidcarboni.restolino.interfaces.NotFound;
import com.github.davidcarboni.restolino.json.Serialiser;
/**
* This is the framework controller.
*
* @author David Carboni
*
*/
public class Api extends HttpServlet {
/**
* Generated by Eclipse.
*/
private static final long serialVersionUID = -6908094417492499433L;
Map<String, RequestHandler> get = new HashMap<>();
Map<String, RequestHandler> put = new HashMap<>();
Map<String, RequestHandler> post = new HashMap<>();
Map<String, RequestHandler> delete = new HashMap<>();
// Map<Class<?>, Map<String, RequestHandler>> methodsa = new
// HashMap<Class<?>, Map<String, RequestHandler>>();
// methodsa.put(GET.class, get);
// methodsa.put(PUT.class, put);
// methodsa.put(POST.class, post);
// methodsa.put(DELETE.class, delete);
private Map<String, RequestHandler> getMap(Class<? extends Annotation> type) {
if (GET.class.isAssignableFrom(type))
return get;
else if (PUT.class.isAssignableFrom(type))
return put;
else if (POST.class.isAssignableFrom(type))
return post;
else if (DELETE.class.isAssignableFrom(type))
return delete;
return null;
}
private Home home;
private Boom boom;
private NotFound notFound;
@Override
public void init() throws ServletException {
// Set up reflections:
ServletContext servletContext = getServletContext();
Set<URL> urls = new HashSet<>(
ClasspathHelper.forWebInfLib(servletContext));
urls.add(ClasspathHelper.forWebInfClasses(servletContext));
Reflections reflections = new Reflections(
new ConfigurationBuilder().setUrls(urls));
configureEndpoints(reflections);
configureHome(reflections);
configureNotFound(reflections);
configureBoom(reflections);
}
/**
* Searches for and configures all your lovely endpoints.
*
* @param reflections
* The instance to use to find classes.
*/
void configureEndpoints(Reflections reflections) {
System.out.println("Scanning for endpoints..");
Set<Class<?>> endpoints = reflections
.getTypesAnnotatedWith(Endpoint.class);
System.out.println("Found " + endpoints.size() + " endpoints.");
System.out.println("Examining endpoint methods..");
// Configure the classes:
for (Class<?> endpointClass : endpoints) {
System.out.println(" - " + endpointClass.getSimpleName());
for (Method method : endpointClass.getMethods()) {
// Skip Object methods
if (method.getDeclaringClass() == Object.class)
continue;
// We're looking for public methods that take reqest, responso
// and optionally a message type:
Class<?>[] parameterTypes = method.getParameterTypes();
// System.out.println("Examining method " + method.getName());
// if (Modifier.isPublic(method.getModifiers()))
// System.out.println(".public");
// System.out.println("." + parameterTypes.length +
// " parameters");
// if (parameterTypes.length == 2 || parameterTypes.length == 3)
// if (HttpServletRequest.class
// .isAssignableFrom(parameterTypes[0]))
// System.out.println(".request OK");
// if (HttpServletResponse.class
// .isAssignableFrom(parameterTypes[1]))
// System.out.println(".response OK");
if (Modifier.isPublic(method.getModifiers())
&& parameterTypes.length >= 2
&& HttpServletRequest.class
.isAssignableFrom(parameterTypes[0])
&& HttpServletResponse.class
.isAssignableFrom(parameterTypes[1])) {
// Which HTTP method(s) will this method respond to?
List<Annotation> annotations = Arrays.asList(method
.getAnnotations());
// System.out.println(" > processing " +
// method.getName());
// for (Annotation annotation : annotations)
// System.out.println(" > annotation " +
// annotation.getClass().getName());
for (Annotation annotation : annotations) {
String name = endpointClass.getSimpleName()
.toLowerCase();
Map<String, RequestHandler> map = getMap(annotation
.getClass());
if (map != null) {
clashCheck(name, annotation.getClass(),
endpointClass, method);
System.out.print(" - "
+ annotation.getClass().getInterfaces()[0]
.getSimpleName());
RequestHandler requestHandler = new RequestHandler();
requestHandler.endpointClass = endpointClass;
requestHandler.method = method;
System.out.print(" " + method.getName());
if (parameterTypes.length > 2) {
requestHandler.requestMessageType = parameterTypes[2];
System.out.print(" request:"
+ requestHandler.requestMessageType
.getSimpleName());
}
if (method.getReturnType() != void.class) {
requestHandler.responseMessageType = method
.getReturnType();
System.out.print(" response:"
+ requestHandler.responseMessageType
.getSimpleName());
}
map.put(name, requestHandler);
System.out.println();
}
}
}
}
}
}
private void clashCheck(String name,
Class<? extends Annotation> annotation, Class<?> endpointClass,
Method method) {
Map<String, RequestHandler> map = getMap(annotation);
if (map != null) {
if (map.containsKey(name))
System.out.println(" ! method " + method.getName() + " in "
+ endpointClass.getName() + " overwrites "
+ map.get(name).method.getName() + " in "
+ map.get(name).endpointClass.getName() + " for "
+ annotation.getSimpleName());
} else {
System.out.println("WAT. Expected GET/PUT/POST/DELETE but got "
+ annotation.getName());
}
}
// // Display the signature we've found:
// System.out.print(" - " + method.getName() + ": ");
// if (parameterTypes.length > 2)
// System.out.print("request:"
// + parameterTypes[2].getSimpleName() + " ");
// System.out.print("response:"
// + method.getReturnType().getSimpleName());
// List<String> httpMethods = new ArrayList<String>();
// for (Class<?> httpMethod : annotations.size()) {
// if (annotations.size() > 0) {
// StringUtils.join(httpMethods, ",");
// System.out.println(" ("+httpMethods+")");
/**
* Searches for and configures the / endpoint.
*
* @param reflections
* The instance to use to find classes.
*/
void configureHome(Reflections reflections) {
System.out.println("Checking for a / endpoint..");
home = getEndpoint(Home.class, "/", reflections);
if (home != null)
System.out.println("Class " + home.getClass().getSimpleName()
+ " configured as / endpoint");
}
/**
* Searches for and configures the not found endpoint.
*
* @param reflections
* The instance to use to find classes.
*/
void configureNotFound(Reflections reflections) {
System.out.println("Checking for a not-found endpoint..");
notFound = getEndpoint(NotFound.class, "not-found", reflections);
if (notFound != null)
System.out.println("Class " + notFound.getClass().getSimpleName()
+ " configured as not-found endpoint");
}
/**
* Searches for and configures the not found endpoint.
*
* @param reflections
* The instance to use to find classes.
*/
void configureBoom(Reflections reflections) {
System.out.println("Checking for an error endpoint..");
boom = getEndpoint(Boom.class, "error", reflections);
if (boom != null)
System.out.println("Class " + boom.getClass().getSimpleName()
+ " configured as error endpoint");
}
/**
* Locates a single endpoint class.
*
* @param type
* @param name
* @param reflections
* @return
*/
private static <E> E getEndpoint(Class<E> type, String name,
Reflections reflections) {
E result = null;
// Get annotated classes:
System.out.println("Looking for a " + name + " endpoint..");
Set<Class<? extends E>> endpointClasses = reflections
.getSubTypesOf(type);
if (endpointClasses.size() == 0)
// No endpoint found:
System.out.println("No " + name
+ " endpoint configured. Just letting you know.");
else {
// Dump multiple endpoints:
if (endpointClasses.size() > 1) {
System.out.println("Warning: found multiple candidates for "
+ name + " endpoint: " + endpointClasses);
}
// Instantiate the endpoint:
try {
result = endpointClasses.iterator().next().newInstance();
} catch (Exception e) {
System.out.println("Error: cannot instantiate " + name
+ " endpoint class "
+ endpointClasses.iterator().next());
e.printStackTrace();
}
}
return result;
}
@Override
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException {
if (home != null && StringUtils.equals("/", request.getPathInfo())) {
// Handle a / request:
Object responseMessage = home.get(request, response);
writeMessage(response, responseMessage.getClass(), responseMessage);
} else {
doMethod(request, response, get);
}
}
@Override
protected void doPut(HttpServletRequest request,
HttpServletResponse response) throws ServletException {
doMethod(request, response, put);
}
@Override
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException {
doMethod(request, response, post);
}
@Override
protected void doDelete(HttpServletRequest request,
HttpServletResponse response) throws ServletException {
doMethod(request, response, delete);
}
/**
* GO!
*
* @param request
* The request.
* @param response
* The response.
* @param requestHandlers
* One of the handler maps.
*/
private void doMethod(HttpServletRequest request,
HttpServletResponse response,
Map<String, RequestHandler> requestHandlers) {
// Locate a request handler:
RequestHandler requestHandler = mapRequestPath(requestHandlers, request);
try {
if (requestHandler != null) {
Object handler = instantiate(requestHandler.endpointClass);
Object responseMessage = invoke(request, response, handler,
requestHandler.method,
requestHandler.requestMessageType);
if (requestHandler.responseMessageType != null) {
writeMessage(response, requestHandler.responseMessageType,
responseMessage);
}
} else {
// Not found
response.setStatus(HttpStatus.SC_NOT_FOUND);
if (notFound != null)
notFound.handle(request, response);
}
} catch (Throwable t) {
// Set a default response code:
response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR);
if (boom != null) {
try {
// Attempt to handle the error gracefully:
boom.handle(request, response, requestHandler, t);
} catch (Throwable t2) {
t2.printStackTrace();
}
} else {
t.printStackTrace();
}
}
}
private static Object invoke(HttpServletRequest request,
HttpServletResponse response, Object handler, Method method,
Class<?> requestMessage) {
Object result = null;
System.out.println("Invoking method " + method.getName() + " on "
+ handler.getClass().getSimpleName() + " for request message "
+ requestMessage);
try {
if (requestMessage != null) {
Object message = readMessage(request, requestMessage);
result = method.invoke(handler, request, response, message);
} else {
result = method.invoke(handler, request, response);
}
} catch (Exception e) {
System.out.println("Error");
throw new RuntimeException("Error invoking method "
+ method.getName() + " on "
+ handler.getClass().getSimpleName());
}
System.out.println("Result is " + result);
return result;
}
private static Object readMessage(HttpServletRequest request,
Class<?> requestMessageType) {
try (InputStreamReader streamReader = new InputStreamReader(
request.getInputStream(), "UTF8")) {
return Serialiser.getBuilder().create()
.fromJson(streamReader, requestMessageType);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("Unsupported encoding", e);
} catch (IOException e) {
throw new RuntimeException("Error reading message", e);
}
}
private static void writeMessage(HttpServletResponse response,
Class<?> responseMessageType, Object responseMessage) {
if (responseMessage != null) {
response.setContentType("application/json");
response.setCharacterEncoding("UTF8");
try (OutputStreamWriter writer = new OutputStreamWriter(
response.getOutputStream(), "UTF8")) {
Serialiser.getBuilder().create()
.toJson(responseMessage, responseMessageType, writer);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("Unsupported encoding", e);
} catch (IOException e) {
throw new RuntimeException("Error reading message", e);
}
}
}
/**
* Locates a {@link RequestHandler} for the path of the given request.
*
* @param requestHandlers
* One of the handler maps.
* @param request
* The request.
* @return A matching handler, if one exists.
*/
private static RequestHandler mapRequestPath(
Map<String, RequestHandler> requestHandlers,
HttpServletRequest request) {
String endpointName = Path.newInstance(request).firstSegment();
endpointName = StringUtils.lowerCase(endpointName);
System.out.println("Mapping endpoint " + endpointName);
return requestHandlers.get(endpointName);
}
private static Object instantiate(Class<?> endpointClass) {
// Instantiate:
Object result = null;
try {
result = endpointClass.newInstance();
} catch (InstantiationException e) {
throw new RuntimeException("Unable to instantiate "
+ endpointClass.getSimpleName(), e);
} catch (IllegalAccessException e) {
throw new RuntimeException("Unable to access "
+ endpointClass.getSimpleName(), e);
} catch (NullPointerException e) {
throw new RuntimeException("No class to instantiate", e);
}
return result;
}
}
|
package co.epitre.aelf_lectures;
import android.accounts.Account;
import android.accounts.AccountManager;
import android.annotation.SuppressLint;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.view.GestureDetectorCompat;
import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.GestureDetector;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ArrayAdapter;
import android.widget.FrameLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.GregorianCalendar;
import java.util.List;
import co.epitre.aelf_lectures.data.LectureItem;
import co.epitre.aelf_lectures.data.LecturesController;
import co.epitre.aelf_lectures.data.LecturesController.WHAT;
class WhatWhen {
public LecturesController.WHAT what;
public GregorianCalendar when;
public boolean today;
public int position;
public boolean useCache = true;
}
public class LecturesActivity extends ActionBarActivity implements DatePickerFragment.CalendarDialogListener,
ActionBar.OnNavigationListener {
public static final String TAG = "AELFLecturesActivity";
public static final String PREFS_NAME = "aelf-prefs";
public static final long DATE_TODAY = 0;
/**
* 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}.
*/
LecturesController lecturesCtrl = null;
WhatWhen whatwhen;
Menu mMenu;
/**
* Gesture detector. Detect single taps that do not look like a dismiss to toggle
* full screen mode.
*/
private boolean isFullScreen = true;
private boolean isInLongPress = false;
private GestureDetectorCompat mGestureDetector;
List<LectureItem> networkError = new ArrayList<LectureItem>(1);
List<LectureItem> emptyOfficeError = new ArrayList<LectureItem>(1);
/**
* Sync account related vars
*/
// The authority for the sync adapter's content provider
public static final String AUTHORITY = "co.epitre.aelf"; // DANGER: must be the same as the provider's in the manifest
// An account type, in the form of a domain name
public static final String ACCOUNT_TYPE = "epitre.co";
// The account name
public static final String ACCOUNT = "www.aelf.org";
// Sync interval in s. ~ 1 Day
public static final long SYNC_INTERVAL = 60L*60L*22L;
// Instance fields
Account mAccount;
// action bar
protected ActionBar actionBar;
/**
* The {@link ViewPager} that will host the section contents.
*/
ViewPager mViewPager;
// TODO: detect first launch + trigger initial sync
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
int currentVersion, savedVersion;
// current version
PackageInfo packageInfo;
try {
packageInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
} catch (NameNotFoundException e) {
throw new RuntimeException("Could not determine current version");
}
currentVersion = packageInfo.versionCode;
// load saved version, if any
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
savedVersion = settings.getInt("version", -1);
// upgrade logic, primitive at the moment...
SharedPreferences.Editor editor = settings.edit();
if (savedVersion != currentVersion) {
if (savedVersion < 22) {
// delete cache DB: needs to force regenerate
getApplicationContext().deleteDatabase("aelf_cache.db");
// regenerate, according to user settings
do_manual_sync();
}
// update saved version
editor.putInt("version", currentVersion);
}
// migrate SyncPrefActivity.KEY_PREF_DISP_FONT_SIZE from text to int
try {
String fontSize = settings.getString(SyncPrefActivity.KEY_PREF_DISP_FONT_SIZE, "normal");
int zoom = 100;
switch (fontSize) {
case "big":
zoom = 150;
break;
case "huge":
zoom = 200;
break;
default:
// small is deprecated. Treat as "normal".
zoom = 100;
}
editor.putInt(SyncPrefActivity.KEY_PREF_DISP_FONT_SIZE, zoom);
} catch (ClassCastException e) {
// Ignore: already migrated :)
}
editor.commit();
// create dummy account for our background sync engine
try {
mAccount = CreateSyncAccount(this);
} catch (SecurityException e) {
// WTF ? are denied the tiny subset of autorization we ask for ? Anyway, fallback to best effort
Log.w(TAG, "Create/Get sync account was DENIED");
mAccount = null;
}
// init the lecture controller
lecturesCtrl = LecturesController.getInstance(this);
// Select where to go from here
whatwhen = new WhatWhen();
Uri uri = this.getIntent().getData();
if (uri != null) {
parseIntentUri(whatwhen, uri);
} else if(savedInstanceState != null) {
// Restore saved instance state. Especially useful on screen rotate on older phones
whatwhen.what = WHAT.values()[savedInstanceState.getInt("what")];
whatwhen.position = savedInstanceState.getInt("position");
long timestamp = savedInstanceState.getLong("when");
whatwhen.when = new GregorianCalendar();
if(timestamp == DATE_TODAY) {
whatwhen.when = new GregorianCalendar();
whatwhen.today = true;
} else {
whatwhen.when.setTimeInMillis(timestamp);
whatwhen.today = false;
}
} else {
// load the "lectures" for today
whatwhen.when = new GregorianCalendar();
whatwhen.today = true;
whatwhen.what = WHAT.MESSE;
whatwhen.position = 0; // 1st lecture of the office
}
// Error handler
networkError.add(new LectureItem("Oups...", "" +
"<h3>Oups... Une erreur s'est glissée lors du chargement des lectures</h3>" +
"<p>Saviez-vous que cette application est développée entièrement bénévolement ? Elle est construite en lien et avec le soutien de l'AELF, mais elle reste un projet indépendant, soutenue par <em>votre</em> prière !</p>\n" +
"<p>Si vous pensez qu'il s'agit d'une erreur, vous pouvez envoyer un mail à <a href=\"mailto:cathogeek@epitre.co\">cathogeek@epitre.co</a>.<p>", "erreur"));
emptyOfficeError.add(new LectureItem("Oups...", "" +
"<h3>Oups... Cet office ne contient pas de lectures</h3>" +
"<p>Cet office ne semble pas contenir de lecture. Si vous pensez qu'il s'agit d'un erreur, vous pouver essayer de \"Rafraîchir\" cet office.</p>" +
"<p>Saviez-vous que cette application est développée entièrement bénévolement ? Elle est construite en lien et avec le soutien de l'AELF, mais elle reste un projet indépendant, soutenue par <em>votre</em> prière !</p>\\n\" +\n" +
"<p>Si vous pensez qu'il s'agit d'une erreur, vous pouvez envoyer un mail à <a href=\"mailto:cathogeek@epitre.co\">cathogeek@epitre.co</a>.<p>", "erreur"));
// some UI. Most UI init are done in the prev async task
setContentView(R.layout.activity_lectures);
// prevent phone sleep
findViewById(android.R.id.content).setKeepScreenOn(true);
// Spinner
actionBar = getSupportActionBar();
Context context = actionBar.getThemedContext();
ArrayAdapter<CharSequence> list = ArrayAdapter.createFromResource(context, R.array.spinner, R.layout.support_simple_spinner_dropdown_item);
list.setDropDownViewResource(R.layout.support_simple_spinner_dropdown_item);
actionBar.setDisplayShowTitleEnabled(false);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
actionBar.setListNavigationCallbacks(list, this);
// restore active navigation item
actionBar.setSelectedNavigationItem(whatwhen.what.getPosition());
// On older phones >= 44 < 6.0, we can set status bar to transluent but not its color.
// the trick is to place a view under the status bar to emulate it.
if (Build.VERSION.SDK_INT >= 19 && Build.VERSION.SDK_INT < 21) {
getWindow().setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS, WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
View view = new View(this);
view.setLayoutParams(new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
view.getLayoutParams().height = get_status_bar_height();
((ViewGroup) getWindow().getDecorView()).addView(view);
view.setBackgroundColor(this.getResources().getColor(R.color.aelf_dark));
}
// finally, turn on periodic lectures caching
if(mAccount != null) {
ContentResolver.setIsSyncable(mAccount, AUTHORITY, 1);
ContentResolver.setSyncAutomatically(mAccount, AUTHORITY, true);
ContentResolver.addPeriodicSync(mAccount, AUTHORITY, new Bundle(1), SYNC_INTERVAL);
// If the account has not been synced in a long time, fallback on "manual" trigger. This is an attempt
// to solve Huawei y330 bug
// TODO: move last sync time to K/V store
long last_sync = getLasySyncTime();
long now = System.currentTimeMillis();
long days = (now - last_sync) / (1000 * 3600 * 24);
if(days >= 2) {
Log.w(TAG, "Automatic sync has not worked for at least 2 full days, attempting to force sync");
do_manual_sync();
}
}
// Install gesture detector
mGestureDetector = new GestureDetectorCompat(this, new TapGestureListener());
}
private void parseIntentUri(WhatWhen whatwhen, Uri uri) {
// Parse intent URI, update whatwhen in place
// http://www.aelf.org/#messe1_lecture4 --> messe du jour, lecture N
// http://www.aelf.org/2017-01-27/romain/messe#messe1_lecture3 --> messe du 2017-01-27, calendrier romain, lecture N
// http://www.aelf.org/2017-01-27/romain/complies#office_psaume1 --> office_TYPE[N]
// Legacy shortcut URLs:
String path = uri.getPath();
String host = uri.getHost();
String fragment = uri.getFragment();
// Set default values
whatwhen.what = WHAT.MESSE;
whatwhen.when = new GregorianCalendar();
whatwhen.today = true;
whatwhen.position = 0; // 1st lecture of the office
if (host.equals("www.aelf.org")) {
// AELF Website
String[] chunks = path.split("/");
if (chunks.length == 2 && chunks[1].startsWith("office-")) {
// Attempt to parse a legacy URL
String office_name = chunks[1].substring(7).toUpperCase();
try {
whatwhen.what = WHAT.valueOf(office_name);
} catch (IllegalArgumentException e) {
Log.w(TAG, "Failed to parse office '" + chunks[2] + "', falling back to messe", e);
whatwhen.what = WHAT.MESSE;
}
} else {
// Attempt to parse NEW url format, starting with a date
if (chunks.length >= 2) {
// Does it look like a date ?
String potential_date = chunks[1];
if (potential_date.matches("20[0-9]{2}-[0-9]{2}-[0-9]{2}")) {
String[] date_chunks = potential_date.split("-");
whatwhen.when.set(
Integer.parseInt(date_chunks[0]),
Integer.parseInt(date_chunks[1]) - 1,
Integer.parseInt(date_chunks[2])
);
} else {
Log.w(TAG, "String '" + potential_date + "' should look like a date, but it does not!");
}
}
// Attempt to parse office
if (chunks.length >= 4) {
String office_name = chunks[3].toUpperCase();
try {
whatwhen.what = WHAT.valueOf(office_name);
} catch (IllegalArgumentException e) {
Log.w(TAG, "Failed to parse office '" + chunks[2] + "', falling back to messe", e);
whatwhen.what = WHAT.MESSE;
}
}
// TODO: Attempt to parse anchor to go to the right slide ?
}
}
}
private long getLasySyncTime() {
// TODO: move this value to K/V store
long result = 0;
try {
Method getSyncStatus = ContentResolver.class.getMethod("getSyncStatus", Account.class, String.class);
if (mAccount != null) {
Object status = getSyncStatus.invoke(null, mAccount, AUTHORITY);
Class<?> statusClass = Class.forName("android.content.SyncStatusInfo");
boolean isStatusObject = statusClass.isInstance(status);
if (isStatusObject) {
Field successTime = statusClass.getField("lastSuccessTime");
result = successTime.getLong(status);
}
}
}
catch (NoSuchMethodException e) {}
catch (IllegalAccessException e) {}
catch (InvocationTargetException e) {}
catch (IllegalArgumentException e) {}
catch (ClassNotFoundException e) {}
catch (NoSuchFieldException e) {}
catch (NullPointerException e) {}
return result;
}
protected int get_status_bar_height() {
// Get status bar height
int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
int statusBarHeight = 0;
if (resourceId > 0) {
statusBarHeight = getResources().getDimensionPixelSize(resourceId);
}
return statusBarHeight;
}
public void prepare_fullscreen() {
Window window = getWindow();
// Android < 4.0 --> skip most logic
if (Build.VERSION.SDK_INT < 14) {
// Hide status (top) bar. Navigation bar (> 4.0) still visible.
window.setFlags(
WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN
);
return;
}
int uiOptions = 0;
if (isFullScreen) {
uiOptions |= View.SYSTEM_UI_FLAG_LOW_PROFILE;
uiOptions |= View.SYSTEM_UI_FLAG_HIDE_NAVIGATION;
if (Build.VERSION.SDK_INT >= 19) {
uiOptions |= View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY;
}
}
// Transluent bar
if (Build.VERSION.SDK_INT >= 19) {
window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
// Get action + status bar height
int height = actionBar.getHeight() + get_status_bar_height();
// Compensate height
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setPaddingRelative(0, height, 0, 0);
}
// Apply settings
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
View decorView = window.getDecorView();
decorView.setSystemUiVisibility(uiOptions);
}
}
public boolean do_manual_sync() {
if (mAccount == null) {
// TODO: patch the alg to work without ?
Log.w(TAG, "Failed to run manual sync: we have no account...");
return false;
}
// Pass the settings flags by inserting them in a bundle
Bundle settingsBundle = new Bundle();
settingsBundle.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);
settingsBundle.putBoolean(ContentResolver.SYNC_EXTRAS_EXPEDITED, true);
// start sync
ContentResolver.requestSync(mAccount, AUTHORITY, settingsBundle);
// done
return true;
}
@Override
public void onWindowFocusChanged(boolean hasFocus) {
// manage application's intrusiveness for different Android versions
super.onWindowFocusChanged(hasFocus);
// Always pretend we are going fullscreen. This limits flickering considerably
isFullScreen = true;
prepare_fullscreen();
}
private boolean isSameDay(GregorianCalendar when, GregorianCalendar other){
return (when.get(GregorianCalendar.ERA) == other.get(GregorianCalendar.ERA) &&
when.get(GregorianCalendar.YEAR) == other.get(GregorianCalendar.YEAR) &&
when.get(GregorianCalendar.DAY_OF_YEAR) == other.get(GregorianCalendar.DAY_OF_YEAR));
}
private boolean isToday(GregorianCalendar when){
GregorianCalendar today = new GregorianCalendar();
return isSameDay(when, today);
}
@Override
protected void onSaveInstanceState(Bundle outState) {
// Save instance state. Especially useful on screen rotate on older phones
// - what --> mass, tierce, ... ? (id)
// - when --> date (timestamp)
// - position --> active tab (id)
super.onSaveInstanceState(outState);
if(outState == null) return;
int position = 0; // first slide by default
int what = 0; // "Messe" by default
long when = DATE_TODAY;
if(whatwhen != null) {
if(whatwhen.what != null) what = whatwhen.what.getPosition();
if(mViewPager != null) position = mViewPager.getCurrentItem();
if(whatwhen.when != null && !whatwhen.today && !isToday(whatwhen.when)) {
when = whatwhen.when.getTimeInMillis();
}
}
outState.putInt("what", what);
outState.putInt("position", position);
outState.putLong("when", when);
}
public boolean onAbout(MenuItem item) {
AboutDialogFragment aboutDialog = new AboutDialogFragment();
aboutDialog.show(getSupportFragmentManager(), "aboutDialog");
return true;
}
public boolean onSyncPref(MenuItem item) {
Intent intent = new Intent(this, SyncPrefActivity.class);
startActivity(intent);
return true;
}
public boolean onSyncDo(MenuItem item) {
return do_manual_sync();
}
public boolean onRefresh(MenuItem item) {
whatwhen.useCache = false;
if(mViewPager != null) {
whatwhen.position = mViewPager.getCurrentItem();
} else {
whatwhen.position = 0;
}
new DownloadXmlTask().execute(whatwhen);
return true;
}
public boolean onCalendar(MenuItem item) {
Bundle args = new Bundle();
args.putLong("time", whatwhen.when.getTimeInMillis());
DatePickerFragment calendarDialog = new DatePickerFragment();
calendarDialog.setArguments(args);
calendarDialog.show(getSupportFragmentManager(), "datePicker");
return true;
}
@SuppressLint("SimpleDateFormat") // I know but currently French only
private void updateCalendarButtonLabel() {
MenuItem calendarItem = mMenu.findItem(R.id.action_calendar);
SimpleDateFormat actionDateFormat = new SimpleDateFormat("E d MMM y"); //TODO: move str to cst
calendarItem.setTitle(actionDateFormat.format(whatwhen.when.getTime()));
}
public void onCalendarDialogPicked(int year, int month, int day) {
GregorianCalendar date = new GregorianCalendar(year, month, day);
// do not refresh if date did not change to avoid unnecessary flickering
if(isSameDay(whatwhen.when, date))
return;
// Reset pager
whatwhen.today = isToday(date);
whatwhen.when = date;
whatwhen.position = 0;
new DownloadXmlTask().execute(whatwhen);
// Update to date button with "this.date"
updateCalendarButtonLabel();
}
@Override
public boolean onNavigationItemSelected(int position, long itemId) {
// Are we actually *changing* ? --> maybe not if coming from state reload
if(whatwhen.what != LecturesController.WHAT.values()[position]) {
whatwhen.what = LecturesController.WHAT.values()[position];
whatwhen.position = 0; // on what change, move to 1st
}
new DownloadXmlTask().execute(whatwhen);
return true;
}
@SuppressLint("SimpleDateFormat") // I know but currently French only
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar
getMenuInflater().inflate(R.menu.lectures, menu);
mMenu = menu;
// Update to date button with "this.date"
updateCalendarButtonLabel();
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_about:
return onAbout(item);
case R.id.action_sync_settings:
return onSyncPref(item);
case R.id.action_sync_do:
return onSyncDo(item);
case R.id.action_refresh:
return onRefresh(item);
case R.id.action_calendar:
return onCalendar(item);
}
return true;
}
/**
* Override event dispatcher to detect any event and especially, intercept "single tap" which
* we'll use to toggle fullscreen.
*
* @param event
* @return
*/
@Override
public boolean dispatchTouchEvent(MotionEvent event) {
mGestureDetector.onTouchEvent(event);
return super.dispatchTouchEvent(event);
}
/**
* Detect simple taps that are not immediately following a long press (ie: skip cancels)
*/
class TapGestureListener extends GestureDetector.SimpleOnGestureListener {
@Override
public void onLongPress(MotionEvent event) {
isInLongPress = true;
Log.d(TAG, "onLongPress: " + event.toString());
}
@Override
public boolean onSingleTapConfirmed(MotionEvent event) {
if (!isInLongPress) {
isFullScreen = !isFullScreen;
prepare_fullscreen();
}
isInLongPress = false;
return true;
}
}
/**
* Create a new dummy account for the sync adapter
*
* @param context The application context
*/
public static Account CreateSyncAccount(Context context) {
// Create the account type and default account
Account newAccount = new Account(ACCOUNT, ACCOUNT_TYPE);
// Get an instance of the Android account manager
AccountManager accountManager = (AccountManager) context.getSystemService(ACCOUNT_SERVICE);
/*
* Add the account and account type, no password or user data
* If successful, return the Account object, otherwise report an error.
*/
if (accountManager.addAccountExplicitly(newAccount, null, null)) {
return newAccount;
} else {
return accountManager.getAccountsByType(ACCOUNT_TYPE)[0];
}
}
protected void setLoading(final boolean loading) {
final RelativeLayout loadingOverlay = (RelativeLayout)findViewById(R.id.loadingOverlay);
final ProgressBar loadingIndicator = (ProgressBar)findViewById(R.id.loadingIndicator);
loadingOverlay.post(new Runnable() {
public void run() {
if(loading) {
loadingIndicator.getIndeterminateDrawable().setColorFilter(getResources().getColor(R.color.sepia_fg), android.graphics.PorterDuff.Mode.MULTIPLY);
loadingOverlay.setVisibility(View.VISIBLE);
} else {
loadingOverlay.setVisibility(View.INVISIBLE);
}
}
});
}
// Async loader
private class DownloadXmlTask extends AsyncTask<WhatWhen, Void, List<LectureItem>> {
LecturePagerAdapter mLecturesPager;
@Override
protected List<LectureItem> doInBackground(WhatWhen... whatwhen) {
WhatWhen ww = whatwhen[0];
try {
if(ww.useCache) {
// attempt to load from cache: skip loading indicator (avoids flickering)
List<LectureItem> lectures = lecturesCtrl.getLecturesFromCache(ww.what, ww.when);
if(lectures != null)
return lectures;
}
// attempts to load from network, with loading indicator
setLoading(true);
return lecturesCtrl.getLecturesFromNetwork(ww.what, ww.when);
} catch (IOException e) {
Log.e(TAG, "I/O error while loading. AELF servers down ?");
setLoading(false);
return null;
} finally {
// "useCache=false" is "fire and forget"
ww.useCache = true;
}
}
@Override
protected void onPostExecute(final List<LectureItem> lectures) {
List<LectureItem> pager_data;
// Failed to load
if(lectures == null) {
pager_data = networkError;
// Empty office ? Prevent crash
} else if(lectures.isEmpty()) {
pager_data = emptyOfficeError;
// Nominal case
} else {
pager_data = lectures;
}
// 1 slide fragment <==> 1 lecture
mLecturesPager= new LecturePagerAdapter(getSupportFragmentManager(), pager_data);
// Set up the ViewPager with the sections adapter.
try {
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mLecturesPager);
mViewPager.setCurrentItem(whatwhen.position);
setLoading(false);
} catch(IllegalStateException e) {
// Fragment manager has gone away, will reload anyway so silently give up
}
}
}
}
|
package com.github.davidcarboni.restolino;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.net.URL;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpStatus;
import org.reflections.Reflections;
import org.reflections.util.ClasspathHelper;
import org.reflections.util.ConfigurationBuilder;
import com.github.davidcarboni.restolino.helpers.Serialiser;
/**
* This is the framework controller.
*
* @author David Carboni
*
*/
public class App extends HttpServlet {
/**
* Generated by Eclipse.
*/
// private static final long serialVersionUID = -8124528033609567276L;
Map<String, RequestHandler> get = new HashMap<String, RequestHandler>();
Map<String, RequestHandler> put = new HashMap<String, RequestHandler>();
Map<String, RequestHandler> post = new HashMap<String, RequestHandler>();
Map<String, RequestHandler> delete = new HashMap<String, RequestHandler>();
// Map<Class<?>, Map<String, RequestHandler>> methodsa = new
// HashMap<Class<?>, Map<String, RequestHandler>>();
// methodsa.put(GET.class, get);
// methodsa.put(PUT.class, put);
// methodsa.put(POST.class, post);
// methodsa.put(DELETE.class, delete);
private Map<String, RequestHandler> getMap(Class<? extends Annotation> type) {
if (GET.class.isAssignableFrom(type))
return get;
else if (PUT.class.isAssignableFrom(type))
return put;
else if (POST.class.isAssignableFrom(type))
return post;
else if (DELETE.class.isAssignableFrom(type))
return delete;
return null;
}
private Home home;
private Boom boom;
private NotFound notFound;
@Override
public void init() throws ServletException {
// Set up reflections:
ServletContext servletContext = getServletContext();
Set<URL> urls = new HashSet<URL>(
ClasspathHelper.forWebInfLib(servletContext));
urls.add(ClasspathHelper.forWebInfClasses(servletContext));
Reflections reflections = new Reflections(
new ConfigurationBuilder().setUrls(urls));
configureEndpoints(reflections);
configureHome(reflections);
configureNotFound(reflections);
configureBoom(reflections);
}
/**
* Searches for and configures all your lovely endpoints.
*
* @param reflections
* The instance to use to find classes.
*/
@SuppressWarnings("unchecked")
void configureEndpoints(Reflections reflections) {
System.out.println("Scanning for endpoints..");
Set<Class<?>> endpoints = reflections
.getTypesAnnotatedWith(Endpoint.class);
System.out.println("Found " + endpoints.size() + " endpoints.");
System.out.println("Examining endpoint methods..");
// Configure the classes:
for (Class<?> endpointClass : endpoints) {
System.out.println(" - " + endpointClass.getSimpleName());
for (Method method : endpointClass.getMethods()) {
// Skip Object methods
if (method.getDeclaringClass() == Object.class)
continue;
// We're looking for public methods that take reqest, responso
// and optionally a message type:
Class<?>[] parameterTypes = method.getParameterTypes();
// System.out.println("Examining method " + method.getName());
// if (Modifier.isPublic(method.getModifiers()))
// System.out.println(".public");
// System.out.println("." + parameterTypes.length +
// " parameters");
// if (parameterTypes.length == 2 || parameterTypes.length == 3)
// if (HttpServletRequest.class
// .isAssignableFrom(parameterTypes[0]))
// System.out.println(".request OK");
// if (HttpServletResponse.class
// .isAssignableFrom(parameterTypes[1]))
// System.out.println(".response OK");
if (Modifier.isPublic(method.getModifiers())
&& parameterTypes.length >= 2
&& HttpServletRequest.class
.isAssignableFrom(parameterTypes[0])
&& HttpServletResponse.class
.isAssignableFrom(parameterTypes[1])) {
// Which HTTP method(s) will this method respond to?
List<Annotation> annotations = Arrays.asList(method
.getAnnotations());
// System.out.println(" > processing " +
// method.getName());
// for (Annotation annotation : annotations)
// System.out.println(" > annotation " +
// annotation.getClass().getName());
for (Annotation annotation : annotations) {
String name = endpointClass.getSimpleName()
.toLowerCase();
Map<String, RequestHandler> map = getMap(annotation
.getClass());
if (map != null) {
clashCheck(name, annotation.getClass(),
endpointClass, method);
System.out.print(" - "
+ annotation.getClass().getInterfaces()[0]
.getSimpleName());
RequestHandler requestHandler = new RequestHandler();
requestHandler.endpointClass = endpointClass;
requestHandler.method = method;
System.out.print(" " + method.getName());
if (parameterTypes.length > 2) {
requestHandler.requestMessageType = parameterTypes[2];
System.out.print(" request:"
+ requestHandler.requestMessageType
.getSimpleName());
}
if (method.getReturnType() != void.class) {
requestHandler.responseMessageType = method
.getReturnType();
System.out.print(" response:"
+ requestHandler.responseMessageType
.getSimpleName());
}
map.put(name, requestHandler);
System.out.println();
}
}
}
}
}
}
private void clashCheck(String name,
Class<? extends Annotation> annotation, Class<?> endpointClass,
Method method) {
Map<String, RequestHandler> map = getMap(annotation);
if (map != null) {
if (map.containsKey(name))
System.out.println(" ! method " + method.getName() + " in "
+ endpointClass.getName() + " overwrites "
+ map.get(name).method.getName() + " in "
+ map.get(name).endpointClass.getName() + " for "
+ annotation.getSimpleName());
} else {
System.out.println("WAT. Expected GET/PUT/POST/DELETE but got "
+ annotation.getName());
}
}
// // Display the signature we've found:
// System.out.print(" - " + method.getName() + ": ");
// if (parameterTypes.length > 2)
// System.out.print("request:"
// + parameterTypes[2].getSimpleName() + " ");
// System.out.print("response:"
// + method.getReturnType().getSimpleName());
// List<String> httpMethods = new ArrayList<String>();
// for (Class<?> httpMethod : annotations.size()) {
// if (annotations.size() > 0) {
// StringUtils.join(httpMethods, ",");
// System.out.println(" ("+httpMethods+")");
/**
* Searches for and configures the / endpoint.
*
* @param reflections
* The instance to use to find classes.
*/
@SuppressWarnings("unchecked")
void configureHome(Reflections reflections) {
System.out.println("Checking for a / endpoint..");
home = getEndpoint(Home.class, "/", reflections);
if (home != null)
System.out.println("Class " + home.getClass().getSimpleName()
+ " configured as / endpoint");
}
/**
* Searches for and configures the not found endpoint.
*
* @param reflections
* The instance to use to find classes.
*/
@SuppressWarnings("unchecked")
void configureNotFound(Reflections reflections) {
System.out.println("Checking for a not-found endpoint..");
notFound = getEndpoint(NotFound.class, "not-found", reflections);
if (notFound != null)
System.out.println("Class " + notFound.getClass().getSimpleName()
+ " configured as not-found endpoint");
}
/**
* Searches for and configures the not found endpoint.
*
* @param reflections
* The instance to use to find classes.
*/
@SuppressWarnings("unchecked")
void configureBoom(Reflections reflections) {
System.out.println("Checking for an error endpoint..");
boom = getEndpoint(Boom.class, "error", reflections);
if (boom != null)
System.out.println("Class " + boom.getClass().getSimpleName()
+ " configured as error endpoint");
}
/**
* Locates a single endpoint class.
*
* @param type
* @param name
* @param reflections
* @return
*/
private static <E> E getEndpoint(Class<E> type, String name,
Reflections reflections) {
E result = null;
// Get annotated classes:
System.out.println("Looking for a " + name + " endpoint..");
Set<Class<? extends E>> endpointClasses = reflections
.getSubTypesOf(type);
if (endpointClasses.size() == 0)
// No endpoint found:
System.out.println("No " + name
+ " endpoint configured. Just letting you know.");
else {
// Dump multiple endpoints:
if (endpointClasses.size() > 1) {
System.out.println("Warning: found multiple candidates for "
+ name + " endpoint: " + endpointClasses);
}
// Instantiate the endpoint:
try {
result = endpointClasses.iterator().next().newInstance();
} catch (Exception e) {
System.out.println("Error: cannot instantiate " + name
+ " endpoint class "
+ endpointClasses.iterator().next());
e.printStackTrace();
}
}
return result;
}
@Override
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException {
if (home != null && StringUtils.equals("/", request.getPathInfo())) {
// Handle a / request:
Object responseMessage = home.get(request, response);
writeMessage(response, responseMessage.getClass(), responseMessage);
} else {
doMethod(request, response, get);
}
}
@Override
protected void doPut(HttpServletRequest request,
HttpServletResponse response) throws ServletException {
doMethod(request, response, put);
}
@Override
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException {
doMethod(request, response, post);
}
@Override
protected void doDelete(HttpServletRequest request,
HttpServletResponse response) throws ServletException {
doMethod(request, response, delete);
}
/**
* GO!
*
* @param request
* The request.
* @param response
* The response.
* @param requestHandlers
* One of the handler maps.
*/
private void doMethod(HttpServletRequest request,
HttpServletResponse response,
Map<String, RequestHandler> requestHandlers) {
// Locate a request handler:
RequestHandler requestHandler = mapRequestPath(requestHandlers, request);
try {
if (requestHandler != null) {
Object handler = instantiate(requestHandler.endpointClass);
Object responseMessage = invoke(request, response, handler,
requestHandler.method,
requestHandler.requestMessageType);
if (requestHandler.responseMessageType != null) {
writeMessage(response, requestHandler.responseMessageType,
responseMessage);
}
} else {
// Not found
response.setStatus(HttpStatus.SC_NOT_FOUND);
if (notFound != null)
notFound.handle(request, response);
}
} catch (Throwable t) {
// Set a default response code:
response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR);
if (boom != null) {
try {
// Attempt to handle the error gracefully:
boom.handle(request, response, requestHandler, t);
} catch (Throwable t2) {
t2.printStackTrace();
}
} else {
t.printStackTrace();
}
}
}
private static Object invoke(HttpServletRequest request,
HttpServletResponse response, Object handler, Method method,
Class<?> requestMessage) {
Object result = null;
System.out.println("Invoking method " + method.getName() + " on "
+ handler.getClass().getSimpleName() + " for request message "
+ requestMessage);
try {
if (requestMessage != null) {
Object message = readMessage(request, requestMessage);
result = method.invoke(handler, request, response, message);
} else {
result = method.invoke(handler, request, response);
}
} catch (Exception e) {
System.out.println("Error");
throw new RuntimeException("Error invoking method "
+ method.getName() + " on "
+ handler.getClass().getSimpleName());
}
System.out.println("Result is " + result);
return result;
}
private static Object readMessage(HttpServletRequest request,
Class<?> requestMessageType) {
try (InputStreamReader streamReader = new InputStreamReader(
request.getInputStream(), "UTF8")) {
return Serialiser.getBuilder().create()
.fromJson(streamReader, requestMessageType);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("Unsupported encoding", e);
} catch (IOException e) {
throw new RuntimeException("Error reading message", e);
}
}
private static void writeMessage(HttpServletResponse response,
Class<?> responseMessageType, Object responseMessage) {
if (responseMessage != null) {
response.setContentType("application/json");
response.setCharacterEncoding("UTF8");
try (OutputStreamWriter writer = new OutputStreamWriter(
response.getOutputStream(), "UTF8")) {
Serialiser.getBuilder().create()
.toJson(responseMessage, responseMessageType, writer);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("Unsupported encoding", e);
} catch (IOException e) {
throw new RuntimeException("Error reading message", e);
}
}
}
/**
* Locates a {@link RequestHandler} for the path of the given request.
*
* @param requestHandlers
* One of the handler maps.
* @param request
* The request.
* @return A matching handler, if one exists.
*/
private static RequestHandler mapRequestPath(
Map<String, RequestHandler> requestHandlers,
HttpServletRequest request) {
String endpointName = Path.newInstance(request).firstSegment();
endpointName = StringUtils.lowerCase(endpointName);
System.out.println("Mapping endpoint " + endpointName);
return requestHandlers.get(endpointName);
}
private static Object instantiate(Class<?> endpointClass) {
// Instantiate:
Object result = null;
try {
result = endpointClass.newInstance();
} catch (InstantiationException e) {
throw new RuntimeException("Unable to instantiate "
+ endpointClass.getSimpleName(), e);
} catch (IllegalAccessException e) {
throw new RuntimeException("Unable to access "
+ endpointClass.getSimpleName(), e);
} catch (NullPointerException e) {
throw new RuntimeException("No class to instantiate", e);
}
return result;
}
}
|
package com.youcruit.onfido.api;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import java.io.IOException;
import java.net.URI;
import java.util.Calendar;
import java.util.TimeZone;
import java.util.UUID;
import org.junit.Test;
import com.neovisionaries.i18n.CountryCode;
import com.youcruit.onfido.api.applicants.ApplicantCreationRequest;
import com.youcruit.onfido.api.applicants.ApplicantId;
import com.youcruit.onfido.api.applicants.ApplicantList;
import com.youcruit.onfido.api.applicants.ApplicantResponse;
import com.youcruit.onfido.api.applicants.ApplicantsClient;
import com.youcruit.onfido.api.applicants.IdNumber;
import com.youcruit.onfido.api.applicants.IdNumberType;
import com.youcruit.onfido.api.http.FakeHttpClient;
import com.youcruit.onfido.api.http.OnfidoHttpClient;
public class ApplicantTest extends HttpIT {
private final OnfidoHttpClient client;
private final ApplicantsClient applicantsClient;
public ApplicantTest(Class<OnfidoHttpClient> httpClientClass) {
super(httpClientClass);
client = createClient();
applicantsClient = new ApplicantsClient(client);
}
@Test
public void runAllSequentialTests() throws IOException {
if (client instanceof FakeHttpClient) {
FakeHttpClient fakeClient = (FakeHttpClient) client;
fakeClient.addResponse(URI.create("https://api.onfido.com/v1/applicants"), "{\"id\":\"8d16119d-866e-4a05-8aa4-472c41608ef8\",\"created_at\":\"2016-03-02T19:13:33Z\",\"sandbox\":true,\"title\":null,\"first_name\":\"Foo\",\"middle_name\":\"FB\",\"last_name\":\"Bar\",\"email\":null,\"gender\":null,\"dob\":\"1980-03-02\",\"telephone\":null,\"mobile\":null,\"country\":\"gbr\",\"href\":\"/v1/applicants/8d16119d-866e-4a05-8aa4-472c41608ef8\",\"id_numbers\":[],\"addresses\":[]}");
fakeClient.addResponse(URI.create("https://api.onfido.com/v1/applicants?per_page=20&page=1"), "{\"applicants\":[{\"id\":\"8d16119d-866e-4a05-8aa4-472c41608ef8\",\"created_at\":\"2016-03-02T19:13:33Z\",\"sandbox\":true,\"title\":null,\"first_name\":\"Foo\",\"middle_name\":\"FB\",\"last_name\":\"Bar\",\"email\":null,\"gender\":null,\"dob\":\"1980-03-02\",\"telephone\":null,\"mobile\":null,\"country\":\"gbr\",\"href\":\"/v1/applicants/8d16119d-866e-4a05-8aa4-472c41608ef8\",\"id_numbers\":[],\"addresses\":[]},{\"id\":\"a9b56d17-935f-4fb0-a688-3022029625f1\",\"created_at\":\"2016-03-02T19:12:44Z\",\"sandbox\":true,\"title\":null,\"first_name\":\"Foo\",\"middle_name\":\"FB\",\"last_name\":\"Bar\",\"email\":null,\"gender\":null,\"dob\":\"1980-03-02\",\"telephone\":null,\"mobile\":null,\"country\":\"gbr\",\"href\":\"/v1/applicants/a9b56d17-935f-4fb0-a688-3022029625f1\",\"id_numbers\":[],\"addresses\":[]},{\"id\":\"c1464dec-4046-45a0-9c27-25ba522f94c9\",\"created_at\":\"2016-03-02T19:12:11Z\",\"sandbox\":true,\"title\":null,\"first_name\":\"Foo\",\"middle_name\":\"FB\",\"last_name\":\"Bar\",\"email\":null,\"gender\":null,\"dob\":\"1980-03-02\",\"telephone\":null,\"mobile\":null,\"country\":\"gbr\",\"href\":\"/v1/applicants/c1464dec-4046-45a0-9c27-25ba522f94c9\",\"id_numbers\":[],\"addresses\":[]},{\"id\":\"142f8eb6-152f-4e57-8acf-9a3d2f1d2f77\",\"created_at\":\"2016-03-02T16:56:26Z\",\"sandbox\":true,\"title\":null,\"first_name\":\"Foo\",\"middle_name\":\"FB\",\"last_name\":\"Bar\",\"email\":null,\"gender\":null,\"dob\":\"1980-03-02\",\"telephone\":null,\"mobile\":null,\"country\":\"gbr\",\"href\":\"/v1/applicants/142f8eb6-152f-4e57-8acf-9a3d2f1d2f77\",\"id_numbers\":[],\"addresses\":[]},{\"id\":\"b5a028b4-a716-4c28-a181-8f9b1951b1b0\",\"created_at\":\"2016-03-02T16:54:09Z\",\"sandbox\":true,\"title\":null,\"first_name\":\"Foo\",\"middle_name\":\"FB\",\"last_name\":\"Bar\",\"email\":null,\"gender\":null,\"dob\":\"1980-03-02\",\"telephone\":null,\"mobile\":null,\"country\":\"gbr\",\"href\":\"/v1/applicants/b5a028b4-a716-4c28-a181-8f9b1951b1b0\",\"id_numbers\":[],\"addresses\":[]},{\"id\":\"8b71ae80-6661-45c9-bcf8-89489ac5f001\",\"created_at\":\"2016-03-02T16:38:23Z\",\"sandbox\":true,\"title\":null,\"first_name\":\"Foo\",\"middle_name\":\"FB\",\"last_name\":\"Bar\",\"email\":null,\"gender\":null,\"dob\":\"1980-03-02\",\"telephone\":null,\"mobile\":null,\"country\":\"gbr\",\"href\":\"/v1/applicants/8b71ae80-6661-45c9-bcf8-89489ac5f001\",\"id_numbers\":[],\"addresses\":[]},{\"id\":\"5b14b454-8e47-41bf-99c3-f82d4a8c3bdf\",\"created_at\":\"2016-03-02T16:36:25Z\",\"sandbox\":true,\"title\":null,\"first_name\":\"Foo\",\"middle_name\":\"FB\",\"last_name\":\"Bar\",\"email\":null,\"gender\":null,\"dob\":\"1980-03-02\",\"telephone\":null,\"mobile\":null,\"country\":\"gbr\",\"href\":\"/v1/applicants/5b14b454-8e47-41bf-99c3-f82d4a8c3bdf\",\"id_numbers\":[],\"addresses\":[]},{\"id\":\"e1628b63-7335-4e1c-a22f-1fb16d3ebd85\",\"created_at\":\"2016-03-02T16:07:16Z\",\"sandbox\":true,\"title\":null,\"first_name\":\"Foo\",\"middle_name\":\"FB\",\"last_name\":\"Bar\",\"email\":null,\"gender\":null,\"dob\":\"1980-03-02\",\"telephone\":null,\"mobile\":null,\"country\":\"gbr\",\"href\":\"/v1/applicants/e1628b63-7335-4e1c-a22f-1fb16d3ebd85\",\"id_numbers\":[],\"addresses\":[]},{\"id\":\"c1e5ed2d-ae6c-46c7-a3ea-c2f4fbf88dca\",\"created_at\":\"2016-03-02T15:39:35Z\",\"sandbox\":true,\"title\":null,\"first_name\":\"Foo\",\"middle_name\":\"FB\",\"last_name\":\"Bar\",\"email\":null,\"gender\":null,\"dob\":\"2016-02-02\",\"telephone\":null,\"mobile\":null,\"country\":\"gbr\",\"href\":\"/v1/applicants/c1e5ed2d-ae6c-46c7-a3ea-c2f4fbf88dca\",\"id_numbers\":[],\"addresses\":[]},{\"id\":\"9c5a62bb-7eea-4e35-a221-3badc551b335\",\"created_at\":\"2016-03-02T15:39:17Z\",\"sandbox\":true,\"title\":null,\"first_name\":\"Foo\",\"middle_name\":\"FB\",\"last_name\":\"Bar\",\"email\":null,\"gender\":null,\"dob\":\"2016-02-02\",\"telephone\":null,\"mobile\":null,\"country\":\"gbr\",\"href\":\"/v1/applicants/9c5a62bb-7eea-4e35-a221-3badc551b335\",\"id_numbers\":[],\"addresses\":[]},{\"id\":\"4010f89a-0965-4ba2-9a53-73e363be6b39\",\"created_at\":\"2016-03-02T15:34:48Z\",\"sandbox\":true,\"title\":null,\"first_name\":\"Foo\",\"middle_name\":\"FB\",\"last_name\":\"Bar\",\"email\":null,\"gender\":null,\"dob\":\"2016-02-02\",\"telephone\":null,\"mobile\":null,\"country\":\"gbr\",\"href\":\"/v1/applicants/4010f89a-0965-4ba2-9a53-73e363be6b39\",\"id_numbers\":[],\"addresses\":[]},{\"id\":\"5285686f-d2eb-4608-8a41-a34dfc9df993\",\"created_at\":\"2016-03-02T15:34:05Z\",\"sandbox\":true,\"title\":null,\"first_name\":\"Foo\",\"middle_name\":\"FB\",\"last_name\":\"Bar\",\"email\":null,\"gender\":null,\"dob\":\"2016-02-02\",\"telephone\":null,\"mobile\":null,\"country\":\"gbr\",\"href\":\"/v1/applicants/5285686f-d2eb-4608-8a41-a34dfc9df993\",\"id_numbers\":[],\"addresses\":[]},{\"id\":\"3ddd142b-7ff2-4dfb-acbb-5ac04407083e\",\"created_at\":\"2016-03-02T15:33:49Z\",\"sandbox\":true,\"title\":null,\"first_name\":\"Foo\",\"middle_name\":\"FB\",\"last_name\":\"Bar\",\"email\":null,\"gender\":null,\"dob\":\"2016-02-02\",\"telephone\":null,\"mobile\":null,\"country\":\"gbr\",\"href\":\"/v1/applicants/3ddd142b-7ff2-4dfb-acbb-5ac04407083e\",\"id_numbers\":[],\"addresses\":[]},{\"id\":\"c3c1f7dc-42a0-447a-ade0-b2a5b015373f\",\"created_at\":\"2016-03-02T15:27:51Z\",\"sandbox\":true,\"title\":null,\"first_name\":\"Foo\",\"middle_name\":\"FB\",\"last_name\":\"Bar\",\"email\":null,\"gender\":null,\"dob\":\"2016-02-02\",\"telephone\":null,\"mobile\":null,\"country\":\"gbr\",\"href\":\"/v1/applicants/c3c1f7dc-42a0-447a-ade0-b2a5b015373f\",\"id_numbers\":[],\"addresses\":[]},{\"id\":\"8633a302-724e-42e5-9863-581235051d79\",\"created_at\":\"2016-03-02T15:27:02Z\",\"sandbox\":true,\"title\":null,\"first_name\":\"Foo\",\"middle_name\":\"FB\",\"last_name\":\"Bar\",\"email\":null,\"gender\":null,\"dob\":\"2016-02-02\",\"telephone\":null,\"mobile\":null,\"country\":\"gbr\",\"href\":\"/v1/applicants/8633a302-724e-42e5-9863-581235051d79\",\"id_numbers\":[],\"addresses\":[]},{\"id\":\"13b666ab-bee6-4dbd-98df-78222bb93269\",\"created_at\":\"2016-03-02T15:26:54Z\",\"sandbox\":true,\"title\":null,\"first_name\":\"Foo\",\"middle_name\":\"FB\",\"last_name\":\"Bar\",\"email\":null,\"gender\":null,\"dob\":\"2016-02-02\",\"telephone\":null,\"mobile\":null,\"country\":\"gbr\",\"href\":\"/v1/applicants/13b666ab-bee6-4dbd-98df-78222bb93269\",\"id_numbers\":[],\"addresses\":[]},{\"id\":\"25d8a366-c3eb-4b32-94b0-226e84f9abdd\",\"created_at\":\"2016-03-02T15:22:02Z\",\"sandbox\":true,\"title\":null,\"first_name\":\"Foo\",\"middle_name\":\"FB\",\"last_name\":\"Bar\",\"email\":null,\"gender\":null,\"dob\":\"2016-02-02\",\"telephone\":null,\"mobile\":null,\"country\":\"gbr\",\"href\":\"/v1/applicants/25d8a366-c3eb-4b32-94b0-226e84f9abdd\",\"id_numbers\":[],\"addresses\":[]},{\"id\":\"338b789c-440b-4a22-ba62-c93bbd48ebd7\",\"created_at\":\"2016-03-02T15:21:20Z\",\"sandbox\":true,\"title\":null,\"first_name\":\"Foo\",\"middle_name\":\"FB\",\"last_name\":\"Bar\",\"email\":null,\"gender\":null,\"dob\":\"2016-02-02\",\"telephone\":null,\"mobile\":null,\"country\":\"gbr\",\"href\":\"/v1/applicants/338b789c-440b-4a22-ba62-c93bbd48ebd7\",\"id_numbers\":[],\"addresses\":[]},{\"id\":\"e9e92bb8-33aa-4d19-b48c-8febc6fdfdfa\",\"created_at\":\"2016-03-02T15:19:27Z\",\"sandbox\":true,\"title\":null,\"first_name\":\"Foo\",\"middle_name\":\"FB\",\"last_name\":\"Bar\",\"email\":null,\"gender\":null,\"dob\":\"2016-02-02\",\"telephone\":null,\"mobile\":null,\"country\":\"gbr\",\"href\":\"/v1/applicants/e9e92bb8-33aa-4d19-b48c-8febc6fdfdfa\",\"id_numbers\":[],\"addresses\":[]},{\"id\":\"1e8ef058-8a51-417e-ae92-85b656465a86\",\"created_at\":\"2016-03-02T15:17:49Z\",\"sandbox\":true,\"title\":null,\"first_name\":\"Foo\",\"middle_name\":\"FB\",\"last_name\":\"Bar\",\"email\":null,\"gender\":null,\"dob\":\"2016-02-02\",\"telephone\":null,\"mobile\":null,\"country\":\"gbr\",\"href\":\"/v1/applicants/1e8ef058-8a51-417e-ae92-85b656465a86\",\"id_numbers\":[],\"addresses\":[]}]}");
fakeClient.addResponse(URI.create("https://api.onfido.com/v1/applicants/8d16119d-866e-4a05-8aa4-472c41608ef8"), "{\"id\":\"8d16119d-866e-4a05-8aa4-472c41608ef8\",\"created_at\":\"2016-03-02T19:13:33Z\",\"sandbox\":true,\"title\":null,\"first_name\":\"Foo\",\"middle_name\":\"FB\",\"last_name\":\"Bar\",\"email\":null,\"gender\":null,\"dob\":\"1980-03-02\",\"telephone\":null,\"mobile\":null,\"country\":\"gbr\",\"href\":\"/v1/applicants/8d16119d-866e-4a05-8aa4-472c41608ef8\",\"id_numbers\":[],\"addresses\":[]}");
}
// Far from optimal, but since all the tests require creation of a new applicant and doesn't modify it, do them sequentially
ApplicantId id = createApplicant();
listApplicants(id);
getApplicant(id);
}
private void getApplicant(ApplicantId id) throws IOException {
ApplicantResponse applicant = applicantsClient.getApplicant(id);
assertEquals(id, applicant.getId());
assertEquals("Foo", applicant.getFirstName());
}
private void listApplicants(ApplicantId id) throws IOException {
int page = 1;
ApplicantList list;
do {
list = applicantsClient.listApplicants(page, 20);
for (ApplicantResponse applicantResponse : list.getApplicants()) {
if (applicantResponse.getId().equals(id)) {
return;
}
}
} while (! list.getApplicants().isEmpty());
fail("Didn't find the applicant we're supposed to find");
}
public ApplicantId createApplicant() throws IOException {
ApplicantCreationRequest applicantCreationRequest = new ApplicantCreationRequest();
applicantCreationRequest.setFirstName("Foo");
applicantCreationRequest.setLastName("Bar");
applicantCreationRequest.setMiddleName("FB");
Calendar aestNow = Calendar.getInstance(TimeZone.getTimeZone("AEST"));
aestNow.set(Calendar.YEAR, 1980);
aestNow.set(Calendar.DAY_OF_YEAR, 62);
applicantCreationRequest.setDateOfBirth(aestNow);
applicantCreationRequest.setCountry(CountryCode.US);
String email = UUID.randomUUID().toString() + "@example.com";
applicantCreationRequest.setEmail(email);
IdNumber ssn = new IdNumber();
ssn.setType(IdNumberType.SSN);
ssn.setValue("404-35-0728");
ApplicantResponse applicant = applicantsClient.createApplicant(applicantCreationRequest);
assertEquals("Foo", applicant.getFirstName());
assertEquals("Bar", applicant.getLastName());
assertEquals("FB", applicant.getMiddleName());
assertSameDate(aestNow, applicant.getDateOfBirth());
assertEquals(CountryCode.US, applicant.getCountry());
assertEquals(email, applicant.getEmail());
return applicant.getId();
}
}
|
package com.abplus.qiitaly.app.utils;
import android.util.Log;
import com.abplus.qiitaly.app.api.models.Comment;
import com.abplus.qiitaly.app.api.models.Item;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
public class HtmlBuilder {
private Item item;
public HtmlBuilder(@Nullable Item.Cache cache) {
item = cache == null ? null : cache.toItem();
}
public HtmlBuilder(@NotNull Item item) {
this.item = item;
}
private String header() {
return "<html><head><meta http-equiv=\"content-type\" content=\"text/html;charset=UTF-8\">\n" +
"<meta name=\"viewport\" content=\"width=device-width,initial-scale=1.0\">\n" +
"<style>\n" +
"body {" +
" -webkit-text-size-adjust: 100%;" +
" font-size: 14px;" +
" line-height: 1.5;" +
" padding: 0px;" +
" margin: 0px;" +
"}\n" +
".container {" +
" padding: 8px;" +
"}\n" +
".article-header {" +
" width: 100%;" +
" background-color: #EEF2EA;" +
" padding: 0px;" +
" margin-top: 0px;" +
" margin-left: 0px;" +
" margin-right: 0px;" +
" margin-bottom: 8px;" +
"}\n" +
".article-description {" +
" clear: left;" +
" color: #999999;" +
" font-size: 12px;" +
" margin-left: 8px;" +
" padding-bottom: 8px;" +
"}\n" +
"img.profile-icon {" +
" width: 64px;" +
" height: 64px;" +
" margin: 8px;" +
"" +
"}\n" +
"img.comment-icon {" +
" width: 32px;" +
" height: 32px;" +
" margin: 8px;" +
"" +
"}\n" +
".comment-body {" +
" clear: left;" +
" color: #333333;" +
" padding: 4px;" +
" font-size: 12px;" +
"}\n" +
".article-header h1 {" +
" font-size: 18px;" +
" font-weight: 600;" +
" background-color: rgba(0, 0, 0, 0);" +
" padding: 4px;" +
" line-height: 1.2;" +
"}\n" +
"h1 {" +
" font-size: 24px;" +
" font-weight: 600;" +
" border-radius: 4px;" +
" background-color: rgba(0, 0, 0, 0.1);" +
" padding: 3px 10px;" +
" line-height: 1.2;" +
"}\n" +
"h2 {" +
" font-size: 22px;" +
" border-bottom-width: 1px;" +
" border-bottom-style: solid;" +
" border-bottom-color: #D4D4D4;" +
" font-weight: 600;" +
" line-height: 1.2;" +
"}\n" +
"h3 {" +
" font-size: 18px;" +
" font-weight: 600;" +
" line-height: 1.2;" +
"}\n" +
"h4 {" +
" font-size: 16px;" +
" font-weight: 600;" +
" line-height: 1.2;" +
"}\n" +
".code-frame {" +
" border-width: 1px;" +
" border-color: #D4D4D4;" +
" border-style: solid;" +
" padding: 8px;" +
" margin: 8px;" +
" line-height: 1.2;" +
"}\n" +
".code-frame .code-lang {" +
" border-bottom-width: 1px;" +
" border-bottom-style: solid;" +
" border-bottom-color: #D4D4D4;" +
" font-size: 12px;" +
" color: #666666;" +
"}\n" +
".code-frame .kd {" +
" color: #0000FF;" +
" font-weight: bold;" +
"}\n" +
".code-frame .c {" +
" color: #CC6699;" +
"}\n" +
".code-frame .cm {" +
" color: #CC6699;" +
"}\n" +
"</style>" +
"</head>";
}
private String footer() {
return "</body></html>";
}
private String articleHeader(@NotNull Item item) {
return "<header class=\"article-header\">" +
"<div><img class=\"profile-icon\" src=\"" + item.getUser().getProfileImageUrl() + "\" align=\"left\">" +
"<h1 class=\"item-title\">" + item.getTitle() + "</h1></div>" +
"<div><p class=\"article-description\">" + item.getUser().getUrlName() + "" + item.getCreatedAtInWords() + "</p></div>" +
"</header>";
}
private String comment(@NotNull Comment comment) {
return "<div><img class=\"comment-icon\" src=\"" + comment.getUser().getProfileImageUrl() + "\" align=\"left\">" +
"<p>" + comment.getUser().getUrlName() + "</p>" +
"<div class=\"comment-body\">" + comment.getBody() + "</div>";
}
public String build() {
StringBuilder builder = new StringBuilder();
builder.append(header());
if (item != null) {
builder.append(articleHeader(item));
builder.append("<div class=\"container\">");
builder.append(item.getBody());
builder.append("</div>");
if (item.getComments() != null && item.getComments().size() > 0) {
builder.append("<hr>");
for (Comment comment: item.getComments()) {
builder.append(comment(comment));
}
}
}
builder.append(footer());
Log.d("HtmlBuilder", builder.toString());
return builder.toString();
}
}
|
package com.github.dockerjava.core;
import java.util.regex.Pattern;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;
import com.github.dockerjava.api.model.AuthConfig;
public class NameParser {
private static final int RepositoryNameTotalLengthMax = 255;
private static final Pattern RepositoryNameComponentRegexp = Pattern.compile("[a-z0-9]+(?:[._-][a-z0-9]+)*");
private static final Pattern RepositoryNameComponentAnchoredRegexp = Pattern.compile("^"
+ RepositoryNameComponentRegexp.pattern() + "$");
// private static final Pattern RepositoryNameRegexp = Pattern.compile("(?:" +
// RepositoryNameComponentRegexp.pattern()
// + "/)*" + RepositoryNameComponentRegexp.pattern());
public static ReposTag parseRepositoryTag(String name) {
int n = name.lastIndexOf(':');
if (n < 0) {
return new ReposTag(name, "");
}
String tag = name.substring(n + 1);
if (!tag.contains("/")) {
return new ReposTag(name.substring(0, n), tag);
}
return new ReposTag(name, "");
}
public static class ReposTag {
public final String repos;
public final String tag;
public ReposTag(String repos, String tag) {
this.repos = repos;
this.tag = tag;
}
@Override
public boolean equals(Object obj) {
if (obj instanceof ReposTag) {
ReposTag other = (ReposTag) obj;
return new EqualsBuilder().append(repos, other.repos).append(tag, other.tag).isEquals();
} else {
return false;
}
}
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this, ToStringStyle.SIMPLE_STYLE);
}
}
public static void validateRepoName(String name) {
if (name.isEmpty()) {
throw new InvalidRepositoryNameException(String.format("Invalid empty repository name \"%s\"", name));
}
if (name.length() > RepositoryNameTotalLengthMax) {
throw new InvalidRepositoryNameException(String.format("Repository name \"%s\" is longer than "
+ RepositoryNameTotalLengthMax, name));
}
String[] components = name.split("/");
for (String component : components) {
if (!RepositoryNameComponentAnchoredRegexp.matcher(component).matches()) {
throw new InvalidRepositoryNameException(String.format(
"Repository name \"%s\" is invalid. Component: %s", name, component));
}
}
}
public static HostnameReposName resolveRepositoryName(String reposName) {
if (reposName.contains(":
// It cannot contain a scheme!
throw new InvalidRepositoryNameException();
}
String[] nameParts = reposName.split("/", 2);
if (nameParts.length == 1
|| (!nameParts[0].contains(".") && !nameParts[0].contains(":") && !nameParts[0].equals("localhost"))) {
return new HostnameReposName(AuthConfig.DEFAULT_SERVER_ADDRESS, reposName);
}
String hostname = nameParts[0];
reposName = nameParts[1];
if (hostname.contains("index.docker.io")) {
throw new InvalidRepositoryNameException(String.format("Invalid repository name, try \"%s\" instead",
reposName));
}
validateRepoName(reposName);
return new HostnameReposName(hostname, reposName);
}
public static class HostnameReposName {
public final String hostname;
public final String reposName;
public HostnameReposName(String hostname, String reposName) {
this.hostname = hostname;
this.reposName = reposName;
}
@Override
public boolean equals(Object obj) {
if (obj instanceof HostnameReposName) {
HostnameReposName other = (HostnameReposName) obj;
return new EqualsBuilder().append(hostname, other.hostname).append(reposName, other.reposName)
.isEquals();
} else {
return false;
}
}
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this, ToStringStyle.SIMPLE_STYLE);
}
}
}
|
package hudson.plugins.git.util;
import hudson.model.Api;
import hudson.model.Result;
import hudson.plugins.git.Branch;
import hudson.plugins.git.Revision;
import hudson.plugins.git.UserRemoteConfig;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Random;
import org.eclipse.jgit.lib.ObjectId;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.Test;
import org.jvnet.hudson.test.Issue;
/**
* @author Mark Waite
*/
public class BuildDataTest {
private BuildData data;
private final ObjectId sha1 = ObjectId.fromString("929e92e3adaff2e6e1d752a8168c1598890fe84c");
private final String remoteUrl = "https://github.com/jenkinsci/git-plugin";
@Before
public void setUp() throws Exception {
data = new BuildData();
}
@Test
public void testGetDisplayName() throws Exception {
assertThat(data.getDisplayName(), is("Git Build Data"));
}
@Test
public void testGetDisplayNameEmptyString() throws Exception {
String scmName = "";
BuildData dataWithSCM = new BuildData(scmName);
assertThat(dataWithSCM.getDisplayName(), is("Git Build Data"));
}
@Test
public void testGetDisplayNameNullSCMName() throws Exception {
BuildData dataWithNullSCM = new BuildData(null);
assertThat(dataWithNullSCM.getDisplayName(), is("Git Build Data"));
}
@Test
public void testGetDisplayNameWithSCM() throws Exception {
final String scmName = "testSCM";
final BuildData dataWithSCM = new BuildData(scmName);
assertThat("Git Build Data:" + scmName, is(dataWithSCM.getDisplayName()));
}
@Test
public void testGetIconFileName() {
assertThat(data.getIconFileName(), endsWith("/plugin/git/icons/git-32x32.png"));
}
@Test
public void testGetUrlName() {
assertThat(data.getUrlName(), is("git"));
}
@Test
public void testGetUrlNameMultipleEntries() {
Random random = new Random();
int randomIndex = random.nextInt(1234) + 1;
data.setIndex(randomIndex);
assertThat(data.getUrlName(), is("git-" + randomIndex));
}
@Test
public void testHasBeenBuilt() {
assertFalse(data.hasBeenBuilt(sha1));
}
@Test
public void testGetLastBuild() {
assertEquals(null, data.getLastBuild(sha1));
}
@Test
public void testSaveBuild() {
Revision revision = new Revision(sha1);
Build build = new Build(revision, 1, Result.SUCCESS);
data.saveBuild(build);
assertThat(data.getLastBuild(sha1), is(build));
}
@Test
public void testGetLastBuildOfBranch() {
String branchName = "origin/master";
assertEquals(null, data.getLastBuildOfBranch(branchName));
Collection<Branch> branches = new ArrayList<>();
Branch branch = new Branch(branchName, sha1);
branches.add(branch);
Revision revision = new Revision(sha1, branches);
Build build = new Build(revision, 13, Result.FAILURE);
data.saveBuild(build);
assertThat(data.getLastBuildOfBranch(branchName), is(build));
}
@Test
public void testGetLastBuiltRevision() {
Revision revision = new Revision(sha1);
Build build = new Build(revision, 1, Result.SUCCESS);
data.saveBuild(build);
assertThat(data.getLastBuiltRevision(), is(revision));
}
@Test
public void testGetBuildsByBranchName() {
assertTrue(data.getBuildsByBranchName().isEmpty());
}
@Test
public void testGetScmName() {
assertThat(data.getScmName(), is(""));
}
@Test
public void testSetScmName() {
final String scmName = "Some SCM name";
data.setScmName(scmName);
assertThat(data.getScmName(), is(scmName));
}
@Test
public void testAddRemoteUrl() {
data.addRemoteUrl(remoteUrl);
assertEquals(1, data.getRemoteUrls().size());
String remoteUrl2 = "https://github.com/jenkinsci/git-plugin.git/";
data.addRemoteUrl(remoteUrl2);
assertFalse(data.getRemoteUrls().isEmpty());
assertTrue("Second URL not found in remote URLs", data.getRemoteUrls().contains(remoteUrl2));
assertEquals(2, data.getRemoteUrls().size());
}
@Test
public void testHasBeenReferenced() {
assertFalse(data.hasBeenReferenced(remoteUrl));
data.addRemoteUrl(remoteUrl);
assertTrue(data.hasBeenReferenced(remoteUrl));
assertFalse(data.hasBeenReferenced(remoteUrl + "/"));
}
@Test
public void testGetApi() {
Api api = data.getApi();
Api apiClone = data.clone().getApi();
assertEquals(api, api);
assertEquals(api.getSearchUrl(), apiClone.getSearchUrl());
}
@Test
public void testToString() {
assertEquals(data.toString(), data.clone().toString());
}
@Test
public void testToStringEmptyBuildData() {
BuildData empty = new BuildData();
assertThat(empty.toString(), endsWith("[scmName=<null>,remoteUrls=[],buildsByBranchName={},lastBuild=null]"));
}
@Test
public void testToStringNullSCMBuildData() {
BuildData nullSCM = new BuildData(null);
assertThat(nullSCM.toString(), endsWith("[scmName=<null>,remoteUrls=[],buildsByBranchName={},lastBuild=null]"));
}
@Test
public void testToStringNonNullSCMBuildData() {
BuildData nonNullSCM = new BuildData("gitless");
assertThat(nonNullSCM.toString(), endsWith("[scmName=gitless,remoteUrls=[],buildsByBranchName={},lastBuild=null]"));
}
@Test
public void testEquals() {
// Null object not equal non-null
BuildData nullData = null;
assertFalse("Null object not equal non-null", data.equals(nullData));
// Object should equal itself
assertEquals("Object not equal itself", data, data);
assertTrue("Object not equal itself", data.equals(data));
assertEquals("Object hashCode not equal itself", data.hashCode(), data.hashCode());
// Cloned object equals original object
BuildData data1 = data.clone();
assertEquals("Cloned objects not equal", data1, data);
assertTrue("Cloned objects not equal", data1.equals(data));
assertTrue("Cloned objects not equal", data.equals(data1));
assertEquals("Cloned object hashCodes not equal", data.hashCode(), data1.hashCode());
// Saved build makes object unequal
Revision revision1 = new Revision(sha1);
Build build1 = new Build(revision1, 1, Result.SUCCESS);
data1.saveBuild(build1);
assertFalse("Distinct objects shouldn't be equal", data.equals(data1));
assertFalse("Distinct objects shouldn't be equal", data1.equals(data));
// Same saved build makes objects equal
BuildData data2 = data.clone();
data2.saveBuild(build1);
assertTrue("Objects with same saved build not equal", data2.equals(data1));
assertTrue("Objects with same saved build not equal", data1.equals(data2));
assertEquals("Objects with same saved build not equal hashCodes", data2.hashCode(), data1.hashCode());
// Add remote URL makes objects unequal
final String remoteUrl2 = "git://github.com/jenkinsci/git-plugin.git";
data1.addRemoteUrl(remoteUrl2);
assertFalse("Distinct objects shouldn't be equal", data.equals(data1));
assertFalse("Distinct objects shouldn't be equal", data1.equals(data));
// Add same remote URL makes objects equal
data2.addRemoteUrl(remoteUrl2);
assertTrue("Objects with same remote URL not equal", data2.equals(data1));
assertTrue("Objects with same remote URL not equal", data1.equals(data2));
assertEquals("Objects with same remote URL not equal hashCodes", data2.hashCode(), data1.hashCode());
// Another saved build still keeps objects equal
String branchName = "origin/master";
Collection<Branch> branches = new ArrayList<>();
Branch branch = new Branch(branchName, sha1);
branches.add(branch);
Revision revision2 = new Revision(sha1, branches);
Build build2 = new Build(revision2, 1, Result.FAILURE);
assertEquals(build1, build2); // Surprising, since build1 result is SUCCESS, build2 result is FAILURE
data1.saveBuild(build2);
data2.saveBuild(build2);
assertTrue(data1.equals(data2));
assertEquals(data1.hashCode(), data2.hashCode());
// Saving different build results still equal BuildData,
// because the different build results are equal
data1.saveBuild(build1);
data2.saveBuild(build2);
assertTrue(data1.equals(data2));
assertEquals(data1.hashCode(), data2.hashCode());
// Set SCM name doesn't change equality or hashCode
data1.setScmName("scm 1");
assertTrue(data1.equals(data2));
assertEquals(data1.hashCode(), data2.hashCode());
data2.setScmName("scm 2");
assertTrue(data1.equals(data2));
assertEquals(data1.hashCode(), data2.hashCode());
BuildData emptyData = new BuildData();
emptyData.remoteUrls = null;
assertNotEquals("Non-empty object equal empty", data, emptyData);
assertNotEquals("Empty object similar to non-empty", emptyData, data);
}
@Test
public void testSetIndex() {
data.setIndex(null);
assertEquals(null, data.getIndex());
data.setIndex(-1);
assertEquals(null, data.getIndex());
data.setIndex(0);
assertEquals(null, data.getIndex());
data.setIndex(13);
assertEquals(13, data.getIndex().intValue());
data.setIndex(-1);
assertEquals(null, data.getIndex());
}
@Test
public void testSimilarToHttpsRemoteURL() {
final String SIMPLE_URL = "https://github.com/jenkinsci/git-plugin";
BuildData simple = new BuildData("git-" + SIMPLE_URL);
simple.addRemoteUrl(SIMPLE_URL);
permuteBaseURL(SIMPLE_URL, simple);
}
@Test
public void testSimilarToScpRemoteURL() {
final String SIMPLE_URL = "git@github.com:jenkinsci/git-plugin";
BuildData simple = new BuildData("git-" + SIMPLE_URL);
simple.addRemoteUrl(SIMPLE_URL);
permuteBaseURL(SIMPLE_URL, simple);
}
@Test
public void testSimilarToSshRemoteURL() {
final String SIMPLE_URL = "ssh://git@github.com/jenkinsci/git-plugin";
BuildData simple = new BuildData("git-" + SIMPLE_URL);
simple.addRemoteUrl(SIMPLE_URL);
permuteBaseURL(SIMPLE_URL, simple);
}
private void permuteBaseURL(String simpleURL, BuildData simple) {
final String TRAILING_SLASH_URL = simpleURL + "/";
BuildData trailingSlash = new BuildData("git-" + TRAILING_SLASH_URL);
trailingSlash.addRemoteUrl(TRAILING_SLASH_URL);
assertTrue("Trailing slash not similar to simple URL " + TRAILING_SLASH_URL,
trailingSlash.similarTo(simple));
final String TRAILING_SLASHES_URL = TRAILING_SLASH_URL + "
BuildData trailingSlashes = new BuildData("git-" + TRAILING_SLASHES_URL);
trailingSlashes.addRemoteUrl(TRAILING_SLASHES_URL);
assertTrue("Trailing slashes not similar to simple URL " + TRAILING_SLASHES_URL,
trailingSlashes.similarTo(simple));
final String DOT_GIT_URL = simpleURL + ".git";
BuildData dotGit = new BuildData("git-" + DOT_GIT_URL);
dotGit.addRemoteUrl(DOT_GIT_URL);
assertTrue("Dot git not similar to simple URL " + DOT_GIT_URL,
dotGit.similarTo(simple));
final String DOT_GIT_TRAILING_SLASH_URL = DOT_GIT_URL + "/";
BuildData dotGitTrailingSlash = new BuildData("git-" + DOT_GIT_TRAILING_SLASH_URL);
dotGitTrailingSlash.addRemoteUrl(DOT_GIT_TRAILING_SLASH_URL);
assertTrue("Dot git trailing slash not similar to dot git URL " + DOT_GIT_TRAILING_SLASH_URL,
dotGitTrailingSlash.similarTo(dotGit));
final String DOT_GIT_TRAILING_SLASHES_URL = DOT_GIT_TRAILING_SLASH_URL + "
BuildData dotGitTrailingSlashes = new BuildData("git-" + DOT_GIT_TRAILING_SLASHES_URL);
dotGitTrailingSlashes.addRemoteUrl(DOT_GIT_TRAILING_SLASHES_URL);
assertTrue("Dot git trailing slashes not similar to dot git URL " + DOT_GIT_TRAILING_SLASHES_URL,
dotGitTrailingSlashes.similarTo(dotGit));
}
@Test
@Issue("JENKINS-43630")
public void testSimilarToContainsNullURL() {
final String SIMPLE_URL = "ssh://git@github.com/jenkinsci/git-plugin";
BuildData simple = new BuildData("git-" + SIMPLE_URL);
simple.addRemoteUrl(SIMPLE_URL);
simple.addRemoteUrl(null);
simple.addRemoteUrl(SIMPLE_URL);
BuildData simple2 = simple.clone();
assertTrue(simple.similarTo(simple2));
BuildData simple3 = new BuildData("git-" + SIMPLE_URL);
simple3.addRemoteUrl(SIMPLE_URL);
simple3.addRemoteUrl(null);
simple3.addRemoteUrl(SIMPLE_URL);
assertTrue(simple.similarTo(simple3));
}
@Test
public void testGetIndex() {
assertEquals(null, data.getIndex());
}
@Test
public void testGetRemoteUrls() {
assertTrue(data.getRemoteUrls().isEmpty());
}
@Test
public void testClone() {
// Tested in testSimilarTo and testEquals
}
@Test
public void testSimilarTo() {
data.addRemoteUrl(remoteUrl);
// Null object not similar to non-null
BuildData dataNull = null;
assertFalse("Null object similar to non-null", data.similarTo(dataNull));
BuildData emptyData = new BuildData();
assertFalse("Non-empty object similar to empty", data.similarTo(emptyData));
assertFalse("Empty object similar to non-empty", emptyData.similarTo(data));
emptyData.remoteUrls = null;
assertFalse("Non-empty object similar to empty", data.similarTo(emptyData));
assertFalse("Empty object similar to non-empty", emptyData.similarTo(data));
// Object should be similar to itself
assertTrue("Object not similar to itself", data.similarTo(data));
// Object should not be similar to constructed variants
Collection<UserRemoteConfig> emptyList = new ArrayList<>();
assertFalse("Object similar to data with SCM name", data.similarTo(new BuildData("abc")));
assertFalse("Object similar to data with SCM name & empty", data.similarTo(new BuildData("abc", emptyList)));
BuildData dataSCM = new BuildData("scm");
assertFalse("Object similar to data with SCM name", dataSCM.similarTo(data));
assertTrue("Object with SCM name not similar to data with SCM name", dataSCM.similarTo(new BuildData("abc")));
assertTrue("Object with SCM name not similar to data with SCM name & empty", dataSCM.similarTo(new BuildData("abc", emptyList)));
// Cloned object equals original object
BuildData dataClone = data.clone();
assertTrue("Clone not similar to origin", dataClone.similarTo(data));
assertTrue("Origin not similar to clone", data.similarTo(dataClone));
// Saved build makes objects dissimilar
Revision revision1 = new Revision(sha1);
Build build1 = new Build(revision1, 1, Result.SUCCESS);
dataClone.saveBuild(build1);
assertFalse("Unmodified origin similar to modified clone", data.similarTo(dataClone));
assertFalse("Modified clone similar to unmodified origin", dataClone.similarTo(data));
assertTrue("Modified clone not similar to itself", dataClone.similarTo(dataClone));
// Same saved build makes objects similar
BuildData data2 = data.clone();
data2.saveBuild(build1);
assertFalse("Unmodified origin similar to modified clone", data.similarTo(data2));
assertTrue("Objects with same saved build not similar (1)", data2.similarTo(dataClone));
assertTrue("Objects with same saved build not similar (2)", dataClone.similarTo(data2));
// Add remote URL makes objects dissimilar
final String remoteUrl = "git://github.com/jenkinsci/git-client-plugin.git";
dataClone.addRemoteUrl(remoteUrl);
assertFalse("Distinct objects shouldn't be similar (1)", data.similarTo(dataClone));
assertFalse("Distinct objects shouldn't be similar (2)", dataClone.similarTo(data));
// Add same remote URL makes objects similar
data2.addRemoteUrl(remoteUrl);
assertTrue("Objects with same remote URL dissimilar", data2.similarTo(dataClone));
assertTrue("Objects with same remote URL dissimilar", dataClone.similarTo(data2));
// Add different remote URL objects similar
final String trailingSlash = "git-client-plugin.git/"; // Unlikely as remote URL
dataClone.addRemoteUrl(trailingSlash);
assertFalse("Distinct objects shouldn't be similar", data.similarTo(dataClone));
assertFalse("Distinct objects shouldn't be similar", dataClone.similarTo(data));
data2.addRemoteUrl(trailingSlash);
assertTrue("Objects with same remote URL dissimilar", data2.similarTo(dataClone));
assertTrue("Objects with same remote URL dissimilar", dataClone.similarTo(data2));
// Add different remote URL objects
final String noSlash = "git-client-plugin"; // Unlikely as remote URL
dataClone.addRemoteUrl(noSlash);
assertFalse("Distinct objects shouldn't be similar", data.similarTo(dataClone));
assertFalse("Distinct objects shouldn't be similar", dataClone.similarTo(data));
data2.addRemoteUrl(noSlash);
assertTrue("Objects with same remote URL dissimilar", data2.similarTo(dataClone));
assertTrue("Objects with same remote URL dissimilar", dataClone.similarTo(data2));
// Another saved build still keeps objects similar
String branchName = "origin/master";
Collection<Branch> branches = new ArrayList<>();
Branch branch = new Branch(branchName, sha1);
branches.add(branch);
Revision revision2 = new Revision(sha1, branches);
Build build2 = new Build(revision2, 1, Result.FAILURE);
dataClone.saveBuild(build2);
assertTrue("Another saved build, still similar (1)", dataClone.similarTo(data2));
assertTrue("Another saved build, still similar (2)", data2.similarTo(dataClone));
data2.saveBuild(build2);
assertTrue("Another saved build, still similar (3)", dataClone.similarTo(data2));
assertTrue("Another saved build, still similar (4)", data2.similarTo(dataClone));
// Saving different build results still similar BuildData
dataClone.saveBuild(build1);
assertTrue("Saved build with different results, similar (5)", dataClone.similarTo(data2));
assertTrue("Saved build with different results, similar (6)", data2.similarTo(dataClone));
data2.saveBuild(build2);
assertTrue("Saved build with different results, similar (7)", dataClone.similarTo(data2));
assertTrue("Saved build with different results, similar (8)", data2.similarTo(dataClone));
// Set SCM name doesn't change similarity
dataClone.setScmName("scm 1");
assertTrue(dataClone.similarTo(data2));
data2.setScmName("scm 2");
assertTrue(dataClone.similarTo(data2));
}
@Test
public void testHashCodeEmptyData() {
BuildData emptyData = new BuildData();
assertEquals(emptyData.hashCode(), emptyData.hashCode());
emptyData.remoteUrls = null;
assertEquals(emptyData.hashCode(), emptyData.hashCode());
}
}
|
package com.github.lwhite1.tablesaw.api;
import com.github.lwhite1.tablesaw.columns.Column;
import com.github.lwhite1.tablesaw.filtering.Filter;
import com.github.lwhite1.tablesaw.io.csv.CsvReader;
import com.github.lwhite1.tablesaw.io.csv.CsvWriter;
import com.github.lwhite1.tablesaw.io.html.HtmlTableWriter;
import com.github.lwhite1.tablesaw.io.jdbc.SqlResultSetReader;
import com.github.lwhite1.tablesaw.reducing.NumericReduceFunction;
import com.github.lwhite1.tablesaw.reducing.functions.Count;
import com.github.lwhite1.tablesaw.reducing.functions.Maximum;
import com.github.lwhite1.tablesaw.reducing.functions.Mean;
import com.github.lwhite1.tablesaw.reducing.functions.Median;
import com.github.lwhite1.tablesaw.reducing.functions.Minimum;
import com.github.lwhite1.tablesaw.reducing.functions.StandardDeviation;
import com.github.lwhite1.tablesaw.reducing.functions.Sum;
import com.github.lwhite1.tablesaw.reducing.functions.SummaryFunction;
import com.github.lwhite1.tablesaw.reducing.functions.Variance;
import com.github.lwhite1.tablesaw.sorting.Sort;
import com.github.lwhite1.tablesaw.store.StorageManager;
import com.github.lwhite1.tablesaw.store.TableMetadata;
import com.github.lwhite1.tablesaw.table.Projection;
import com.github.lwhite1.tablesaw.table.Relation;
import com.github.lwhite1.tablesaw.table.Rows;
import com.github.lwhite1.tablesaw.table.ViewGroup;
import com.github.lwhite1.tablesaw.util.BitmapBackedSelection;
import com.github.lwhite1.tablesaw.util.IntComparatorChain;
import com.github.lwhite1.tablesaw.util.ReversingIntComparator;
import com.github.lwhite1.tablesaw.util.Selection;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
import it.unimi.dsi.fastutil.ints.IntArrayList;
import it.unimi.dsi.fastutil.ints.IntArrays;
import it.unimi.dsi.fastutil.ints.IntComparator;
import it.unimi.dsi.fastutil.ints.IntIterable;
import it.unimi.dsi.fastutil.ints.IntIterator;
import org.apache.commons.lang3.RandomUtils;
import java.io.IOException;
import java.io.InputStream;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.BitSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import static com.github.lwhite1.tablesaw.sorting.Sort.Order;
/**
* A table of data, consisting of some number of columns, each of which has the same number of rows.
* All the data in a column has the same type: integer, float, category, etc., but a table may contain an arbitrary
* number of columns of any type.
* <p>
* Tables are the main data-type and primary focus of Tablesaw.
*/
public class Table implements Relation, IntIterable {
/**
* The name of the table
*/
private String name;
/**
* The columns that hold the data in this table
*/
private final List<Column> columnList = new ArrayList<>();
/**
* Returns a new table initialized with the given name
*/
private Table(String name) {
this.name = name;
}
/**
* Returns a new table initialized with data from the given TableMetadata object
* <p>
* The metadata is used by the storage module to save tables and read their data from disk
*/
private Table(TableMetadata metadata) {
this.name = metadata.getName();
}
/**
* Returns a new Table initialized with the given names and columns
*
* @param name The name of the table
* @param columns One or more columns, all of which must have either the same length or size 0
*/
protected Table(String name, Column... columns) {
this(name);
for (Column column : columns) {
this.addColumn(column);
}
}
/**
* Returns a new, empty table (without rows or columns) with the given name
*/
public static Table create(String tableName) {
return new Table(tableName);
}
/**
* Returns a new, empty table constructed according to the given metadata
*/
public static Table create(TableMetadata metadata) {
return new Table(metadata);
}
/**
* Returns a new table with the given columns and given name
*
* @param columns One or more columns, all of the same @code{column.size()}
*/
public static Table create(String tableName, Column... columns) {
return new Table(tableName, columns);
}
/**
* Adds the given column to this table
*/
@Override
public void addColumn(Column... cols) {
for (Column c : cols) {
validateColumn(c);
columnList.add(c);
}
}
/**
* Throws a runtime exception if a column with the given name is already in the table
*/
private void validateColumn(Column newColumn) {
Preconditions.checkNotNull(newColumn, "Attempted to add a null to the columns in table " + name);
List<String> stringList = new ArrayList<>();
for (String name : columnNames()) {
stringList.add(name.toLowerCase());
}
if (stringList.contains(newColumn.name().toLowerCase())) {
String message = String.format("Cannot add column with duplicate name %s to table %s", newColumn, name);
throw new RuntimeException(message);
}
}
/**
* Adds the given column to this table at the given position in the column list
*
* @param index Zero-based index into the column list
* @param column Column to be added
*/
public void addColumn(int index, Column column) {
validateColumn(column);
columnList.add(index, column);
}
/**
* Sets the name of the table
*/
@Override
public void setName(String name) {
this.name = name;
}
/**
* Returns the column at the given index in the column list
*
* @param columnIndex an integer at least 0 and less than number of columns in the table
*/
@Override
public Column column(int columnIndex) {
return columnList.get(columnIndex);
}
/**
* Returns the number of columns in the table
*/
@Override
public int columnCount() {
return columnList.size();
}
/**
* Returns the number of rows in the table
*/
@Override
public int rowCount() {
int result = 0;
if (!columnList.isEmpty()) {
// all the columns have the same number of elements, so we can check any of them
result = columnList.get(0).size();
}
return result;
}
/**
* Returns the list of columns
*/
@Override
public List<Column> columns() {
return columnList;
}
/**
* Returns only the columns whose names are given in the input array
*/
public List<Column> columns(String... columnNames) {
List<Column> columns = new ArrayList<>();
for (String columnName : columnNames) {
columns.add(column(columnName));
}
return columns;
}
public int columnIndex(String columnName) {
int columnIndex = -1;
for (int i = 0; i < columnList.size(); i++) {
if (columnList.get(i).name().equalsIgnoreCase(columnName)) {
columnIndex = i;
break;
}
}
if (columnIndex == -1) {
throw new IllegalArgumentException(String.format("Column %s is not present in table %s", columnName, name));
}
return columnIndex;
}
public int columnIndex(Column column) {
int columnIndex = -1;
for (int i = 0; i < columnList.size(); i++) {
if (columnList.get(i).equals(column)) {
columnIndex = i;
break;
}
}
if (columnIndex == -1) {
throw new IllegalArgumentException(
String.format("Column %s is not present in table %s", column.name(), name));
}
return columnIndex;
}
/**
* Returns the name of the table
*/
@Override
public String name() {
return name;
}
/**
* Returns a List of the names of all the columns in this table
*/
public List<String> columnNames() {
List<String> names = new ArrayList<>(columnList.size());
names.addAll(columnList.stream().map(Column::name).collect(Collectors.toList()));
return names;
}
/**
* Returns a string representation of the value at the given row and column indexes
*
* @param c the column index, 0 based
* @param r the row index, 0 based
*/
@Override
public String get(int c, int r) {
Column column = column(c);
return column.getString(r);
}
/**
* Returns a table with the same columns as this table, but no data
*/
public Table emptyCopy() {
Table copy = new Table(name);
for (Column column : columnList) {
copy.addColumn(column.emptyCopy());
}
return copy;
}
/**
* Returns a table with the same columns as this table, but no data, initialized to the given row size
*/
public Table emptyCopy(int rowSize) {
Table copy = new Table(name);
for (Column column : columnList) {
copy.addColumn(column.emptyCopy(rowSize));
}
return copy;
}
/**
* Splits the table into two, randomly assigning records to each according to the proportion given in
* trainingProportion
*
* @param table1Proportion The proportion to go in the first table
* @return An array two tables, with the first table having the proportion specified in the method parameter,
* and the second table having the balance of the rows
*/
public Table[] sampleSplit(double table1Proportion) {
Table[] tables = new Table[2];
int table1Count = (int) Math.round(rowCount() * table1Proportion);
Selection table2Selection = new BitmapBackedSelection();
for (int i = 0; i < rowCount(); i++) {
table2Selection.add(i);
}
Selection table1Selection = new BitmapBackedSelection();
int[] table1Records = generateUniformBitmap(table1Count, rowCount());
for (int i = 0; i < table1Records.length; i++) {
table1Selection.add(table1Records[i]);
}
table2Selection.andNot(table1Selection);
tables[0] = selectWhere(table1Selection);
tables[1] = selectWhere(table2Selection);
return tables;
}
/**
* Clears all the data from this table
*/
@Override
public void clear() {
columnList.forEach(Column::clear);
}
/**
* Returns a new table containing the first {@code nrows} of data in this table
*/
public Table first(int nRows) {
nRows = Math.min(nRows, rowCount());
Table newTable = emptyCopy(nRows);
Rows.head(nRows, this, newTable);
return newTable;
}
/**
* Returns a new table containing the last {@code nrows} of data in this table
*/
public Table last(int nRows) {
nRows = Math.min(nRows, rowCount());
Table newTable = emptyCopy(nRows);
Rows.tail(nRows, this, newTable);
return newTable;
}
/**
* Returns a sort Key that can be used for simple or chained comparator sorting
* <p>
* You can extend the sort key by using .next() to fill more columns to the sort order
*/
private static Sort first(String columnName, Sort.Order order) {
return Sort.on(columnName, order);
}
/**
* Returns a copy of this table sorted on the given column names, applied in order,
* <p>
* if column name starts with - then sort that column descending otherwise sort ascending
*/
public Table sortOn(String... columnNames) {
Sort key = null;
Order order;
List<String> names = columnNames();
for (String columnName : columnNames) {
if (names.contains(columnName)) {
// the column name has not been annotated with a prefix.
order = Order.ASCEND;
} else {
// get the prefix which could be - or +
String prefix = columnName.substring(0, 1);
// remove - prefix so provided name matches actual column name
columnName = columnName.substring(1, columnName.length());
switch (prefix) {
case "+":
order = Order.ASCEND;
break;
case "-":
order = Order.DESCEND;
break;
default:
throw new IllegalStateException("Column prefix: " + prefix + " is unknown.");
}
}
if (key == null) { // key will be null the first time through
key = first(columnName, order);
} else {
key.next(columnName, order);
}
}
return sortOn(key);
}
/**
* Returns a copy of this table sorted in the order of the given column names, in ascending order
*/
public Table sortAscendingOn(String... columnNames) {
return this.sortOn(columnNames);
}
/**
* Returns a copy of this table sorted on the given column names, applied in order, descending
*/
public Table sortDescendingOn(String... columnNames) {
Sort key = getSort(columnNames);
return sortOn(key);
}
/**
* Returns an object that can be used to sort this table in the order specified for by the given column names
*/
@VisibleForTesting
public static Sort getSort(String... columnNames) {
Sort key = null;
for (String s : columnNames) {
if (key == null) {
key = first(s, Order.DESCEND);
} else {
key.next(s, Order.DESCEND);
}
}
return key;
}
/**
* Returns a copy of this table sorted on the given columns
* <p>
* The columns are sorted in reverse order if they value matching the name is {@code true}
*/
public Table sortOn(Sort key) {
Preconditions.checkArgument(!key.isEmpty());
if (key.size() == 1) {
IntComparator comparator = getComparator(key);
return sortOn(comparator);
}
IntComparatorChain chain = getChain(key);
return sortOn(chain);
}
/**
* Returns a comparator that can be used to sort the records in this table according to the given sort key
*/
public IntComparator getComparator(Sort key) {
Iterator<Map.Entry<String, Sort.Order>> entries = key.iterator();
Map.Entry<String, Sort.Order> sort = entries.next();
IntComparator comparator;
if (sort.getValue() == Order.ASCEND) {
comparator = rowComparator(sort.getKey(), false);
} else {
comparator = rowComparator(sort.getKey(), true);
}
return comparator;
}
/**
* Returns a comparator chain for sorting according to the given key
*/
private IntComparatorChain getChain(Sort key) {
Iterator<Map.Entry<String, Sort.Order>> entries = key.iterator();
Map.Entry<String, Sort.Order> sort = entries.next();
IntComparator comparator;
if (sort.getValue() == Order.ASCEND) {
comparator = rowComparator(sort.getKey(), false);
} else {
comparator = rowComparator(sort.getKey(), true);
}
IntComparatorChain chain = new IntComparatorChain(comparator);
while (entries.hasNext()) {
sort = entries.next();
if (sort.getValue() == Order.ASCEND) {
chain.addComparator(rowComparator(sort.getKey(), false));
} else {
chain.addComparator(rowComparator(sort.getKey(), true));
}
}
return chain;
}
/**
* Returns a copy of this table sorted using the given comparator
*/
public Table sortOn(IntComparator rowComparator) {
Table newTable = emptyCopy(rowCount());
int[] newRows = rows();
IntArrays.parallelQuickSort(newRows, rowComparator);
Rows.copyRowsToTable(IntArrayList.wrap(newRows), this, newTable);
return newTable;
}
/**
* Returns an array of ints of the same number of rows as the table
*/
@VisibleForTesting
public int[] rows() {
int[] rowIndexes = new int[rowCount()];
for (int i = 0; i < rowCount(); i++) {
rowIndexes[i] = i;
}
return rowIndexes;
}
/**
* Returns a comparator for the column matching the specified name
*
* @param columnName The name of the column to sort
* @param reverse {@code true} if the column should be sorted in reverse
*/
private IntComparator rowComparator(String columnName, boolean reverse) {
Column column = this.column(columnName);
IntComparator rowComparator = column.rowComparator();
if (reverse) {
return ReversingIntComparator.reverse(rowComparator);
} else {
return rowComparator;
}
}
public Table selectWhere(Selection selection) {
Table newTable = this.emptyCopy(selection.size());
Rows.copyRowsToTable(selection, this, newTable);
return newTable;
}
public BooleanColumn selectIntoColumn(String newColumnName, Selection selection) {
return BooleanColumn.create(newColumnName, selection, rowCount());
}
public Table selectWhere(Filter filter) {
Selection map = filter.apply(this);
Table newTable = this.emptyCopy(map.size());
Rows.copyRowsToTable(map, this, newTable);
return newTable;
}
public BooleanColumn selectIntoColumn(String newColumnName, Filter filter) {
return BooleanColumn.create(newColumnName, filter.apply(this), rowCount());
}
public ViewGroup splitOn(Column... columns) {
return new ViewGroup(this, columns);
}
public String printHtml() {
return HtmlTableWriter.write(this, "");
}
public Table structure() {
Table t = new Table("Structure of " + name());
IntColumn index = new IntColumn("Index", columnCount());
CategoryColumn columnName = new CategoryColumn("Column Name", columnCount());
CategoryColumn columnType = new CategoryColumn("Column Type", columnCount());
t.addColumn(index);
t.addColumn(columnName);
t.addColumn(columnType);
columnName.addAll(columnNames());
for (int i = 0; i < columnCount(); i++) {
Column column = columnList.get(i);
index.add(i);
columnType.add(column.type().name());
}
return t;
}
public Projection select(String... columnName) {
return new Projection(this, columnName);
}
/**
* Removes the given columns
*/
@Override
public void removeColumns(Column... columns) {
for (Column c : columns) {
columnList.remove(c);
}
}
/**
* Removes the given columns
*/
public void retainColumns(Column... columns) {
List<Column> retained = Arrays.asList(columns);
columnList.retainAll(retained);
}
public void retainColumns(String... columnNames) {
columnList.retainAll(columns(columnNames));
}
public Sum sum(String numericColumnName) {
return new Sum(this, numericColumnName);
}
public Mean mean(String numericColumnName) {
return new Mean(this, numericColumnName);
}
public Median median(String numericColumnName) {
return new Median(this, numericColumnName);
}
public Variance variance(String numericColumnName) {
return new Variance(this, numericColumnName);
}
public StandardDeviation stdDev(String numericColumnName) {
return new StandardDeviation(this, numericColumnName);
}
public Count count(String numericColumnName) {
return new Count(this, numericColumnName);
}
public Maximum max(String numericColumnName) {
return new Maximum(this, numericColumnName);
}
public Minimum minimum(String numericColumnName) {
return new Minimum(this, numericColumnName);
}
public void append(Table tableToAppend) {
for (Column column : columnList) {
Column columnToAppend = tableToAppend.column(column.name());
column.append(columnToAppend);
}
}
/**
* Exports this table as a CSV file with the name (and path) of the given file
*
* @param fileNameWithPath The name of the file to save to. By default, it writes to the working directory,
* but you can specify a different folder by providing the path (e.g. mydata/myfile.csv)
*/
public void exportToCsv(String fileNameWithPath) {
try {
CsvWriter.write(fileNameWithPath, this);
} catch (IOException e) {
System.err.println("Unable to export table as CSV file");
e.printStackTrace();
}
}
public String save(String folder) {
String storageFolder = "";
try {
storageFolder = StorageManager.saveTable(folder, this);
} catch (IOException e) {
System.err.println("Unable to save table in Tablesaw format");
e.printStackTrace();
}
return storageFolder;
}
public static Table readTable(String tableNameAndPath) {
Table t;
try {
t = StorageManager.readTable(tableNameAndPath);
} catch (IOException e) {
System.err.println("Unable to load table from Tablesaw table format");
e.printStackTrace();
return null;
}
return t;
}
public double reduce(String numericColumnName, NumericReduceFunction function) {
Column column = column(numericColumnName);
return function.reduce(column.toDoubleArray());
}
public SummaryFunction summarize(String numericColumnName, NumericReduceFunction function) {
return new SummaryFunction(this, numericColumnName) {
@Override
public NumericReduceFunction function() {
return function;
}
};
}
public Table countBy(CategoryColumn column) {
return column.countByCategory();
}
/**
* Returns a new table constructed from a character delimited (aka CSV) text file
* <p>
* It is assumed that the file is truly comma-separated, and that the file has a one-line header,
* which is used to populate the column names
*
* @param csvFileName The name of the file to import
* @throws IOException
*/
public static Table createFromCsv(String csvFileName) throws IOException {
return CsvReader.read(csvFileName, true, ',');
}
/**
* Returns a new table constructed from a character delimited (aka CSV) text file
* <p>
* It is assumed that the file is truly comma-separated, and that the file has a one-line header,
* which is used to populate the column names
*
* @param csvFileName The name of the file to import
* @param header True if the file has a single header row. False if it has no header row.
* Multi-line headers are not supported
* @throws IOException
*/
public static Table createFromCsv(String csvFileName, boolean header) throws IOException {
return CsvReader.read(csvFileName, header, ',');
}
/**
* Returns a new table constructed from a character delimited (aka CSV) text file
* <p>
* It is assumed that the file is truly comma-separated, and that the file has a one-line header,
* which is used to populate the column names
*
* @param csvFileName The name of the file to import
* @param header True if the file has a single header row. False if it has no header row.
* Multi-line headers are not supported
* @param delimiter a char that divides the columns in the source file, often a comma or tab
* @throws IOException
*/
public static Table createFromCsv(String csvFileName, boolean header, char delimiter) throws IOException {
return CsvReader.read(csvFileName, header, delimiter);
}
/**
* Returns a new table constructed from a character delimited (aka CSV) text file
* <p>
* It is assumed that the file is truly comma-separated, and that the file has a one-line header,
* which is used to populate the column names
*
* @param types The column types
* @param csvFileName The name of the file to import
* @throws IOException
*/
public static Table createFromCsv(ColumnType[] types, String csvFileName) throws IOException {
return CsvReader.read(types, true, ',', csvFileName);
}
/**
* Returns a new table constructed from a character delimited (aka CSV) text file
* <p>
* It is assumed that the file is truly comma-separated
*
* @param types The column types
* @param header True if the file has a single header row. False if it has no header row.
* Multi-line headers are not supported
* @param csvFileName the name of the file to import
* @throws IOException
*/
public static Table createFromCsv(ColumnType[] types, String csvFileName, boolean header) throws IOException {
return CsvReader.read(types, header, ',', csvFileName);
}
/**
* Returns a new table constructed from a character delimited (aka CSV) text file
*
* @param types The column types
* @param header true if the file has a single header row. False if it has no header row.
* Multi-line headers are not supported
* @param delimiter a char that divides the columns in the source file, often a comma or tab
* @param csvFileName the name of the file to import
* @throws IOException
*/
public static Table createFromCsv(ColumnType[] types, String csvFileName, boolean header, char delimiter)
throws IOException {
return CsvReader.read(types, header, delimiter, csvFileName);
}
/**
* Returns a new table constructed from a character delimited (aka CSV) text file
*
* @param types The column types
* @param header true if the file has a single header row. False if it has no header row.
* Multi-line headers are not supported
* @param delimiter a char that divides the columns in the source file, often a comma or tab
* @param stream an InputStream from a file, URL, etc.
* @param tableName the name of the resulting table
* @throws IOException
*/
public static Table createFromStream(ColumnType[] types, boolean header, char delimiter, InputStream stream,
String tableName) throws IOException {
return CsvReader.read(tableName, types, header, delimiter, stream);
}
/**
* Returns a new Table with the given name, and containing the data in the given result set
*/
public static Table create(ResultSet resultSet, String tableName) throws SQLException {
return SqlResultSetReader.read(resultSet, tableName);
}
*//*
/**
* Joins together this table and another table on the given column names. All the records of this table are included
* @return A new table derived from combining this table with {@code other} table
public Table innerJoin(Table other, String columnName, String otherColumnName) {
// create a new table like this one
Table table = new Table(this.name());
// add the columns from this table
for (Column column : columns()) {
table.addColumn(column);
}
// add the columns from the other table, but leave the data out for now
for (Column column : other.columns()) {
if (!column.name().equals(otherColumnName)) {
table.addColumn(column.emptyCopy());
}
}
// iterate over the rows in the new table, fetching rows from the other table that match on
Column joinColumn = column(columnName);
Column otherJoinColumn = other.column(otherColumnName);
for (int row : table) {
joinColumn.getString(row))
// Row otherRow = other.getFirst(otherColumnName, comparable);
if (otherRow != null) {
// fill in the values of other tables columns for that row.
for (Column c : other.columns()) {
if (!c.name().equals(otherColumnName)) {
row.set(c.name(), otherRow.get(c.name()));
}
}
}
}
return table;
}
*/
@Override
public String toString() {
return "Table " + name + ": Size = " + rowCount() + " x " + columnCount();
}
@Override
public IntIterator iterator() {
return new IntIterator() {
private int i = 0;
@Override
public int nextInt() {
return i++;
}
@Override
public int skip(int k) {
return i + k;
}
@Override
public boolean hasNext() {
return i < rowCount();
}
@Override
public Integer next() {
return i++;
}
};
}
static int[] generateUniformBitmap(int N, int Max) {
if (N > Max) throw new RuntimeException("not possible");
int[] ans = new int[N];
if (N == Max) {
for (int k = 0; k < N; ++k)
ans[k] = k;
return ans;
}
BitSet bs = new BitSet(Max);
int cardinality = 0;
while (cardinality < N) {
int v = RandomUtils.nextInt(0, Max);
if (!bs.get(v)) {
bs.set(v);
cardinality++;
}
}
int pos = 0;
for (int i = bs.nextSetBit(0); i >= 0; i = bs.nextSetBit(i + 1)) {
ans[pos++] = i;
}
return ans;
}
}
|
package com.bedrock.padder.activity;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.media.AudioManager;
import android.media.SoundPool;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.util.TypedValue;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.widget.Toast;
import com.afollestad.materialdialogs.MaterialDialog;
import com.bedrock.padder.R;
import com.bedrock.padder.fragment.AboutFragment;
import com.bedrock.padder.fragment.SettingsFragment;
import com.bedrock.padder.helper.AdmobHelper;
import com.bedrock.padder.helper.AnimateHelper;
import com.bedrock.padder.helper.FabHelper;
import com.bedrock.padder.helper.FileHelper;
import com.bedrock.padder.helper.IntentHelper;
import com.bedrock.padder.helper.SoundHelper;
import com.bedrock.padder.helper.ToolbarHelper;
import com.bedrock.padder.helper.TutorialHelper;
import com.bedrock.padder.helper.WindowHelper;
import com.bedrock.padder.model.FirebaseMetadata;
import com.bedrock.padder.model.about.About;
import com.bedrock.padder.model.about.Bio;
import com.bedrock.padder.model.about.Detail;
import com.bedrock.padder.model.about.Item;
import com.bedrock.padder.model.app.theme.ColorData;
import com.bedrock.padder.model.preset.Music;
import com.bedrock.padder.model.preset.Preset;
import com.google.gson.Gson;
import java.io.File;
import static com.bedrock.padder.helper.FirebaseHelper.PROJECT_LOCATION_PRESETS;
import static com.bedrock.padder.helper.WindowHelper.APPLICATION_ID;
@TargetApi(14)
@SuppressWarnings("deprecation")
public class MainActivity
extends AppCompatActivity
implements AboutFragment.OnFragmentInteractionListener, SettingsFragment.OnFragmentInteractionListener {
public static final String TAG = "MainActivity";
public static final String PRESET_KEY = "savedPreset";
public static boolean isPresetLoading = false;
public static boolean isPresetVisible = false;
public static boolean isPresetChanged = false;
public static boolean isTutorialVisible = false;
public static boolean isAboutVisible = false;
public static boolean isSettingVisible = false;
public static boolean isDeckShouldCleared = false;
public static Preset preset;
public static Preset currentPreset = null;
// Used for circularReveal
// End two is for settings coordination
public static int coord[] = {0, 0, 0, 0};
final AppCompatActivity a = this;
final String qs = "quickstart";
public boolean tgl1 = false;
public boolean tgl2 = false;
public boolean tgl3 = false;
public boolean tgl4 = false;
public boolean tgl5 = false;
public boolean tgl6 = false;
public boolean tgl7 = false;
public boolean tgl8 = false;
int currentVersionCode;
int themeColor = R.color.hello;
int color = R.color.cyan_400;
int toggleSoundId = 0;
int togglePatternId = 0;
private SharedPreferences prefs = null;
private AnimateHelper anim = new AnimateHelper();
private SoundHelper sound = new SoundHelper();
private WindowHelper w = new WindowHelper();
private FabHelper fab = new FabHelper();
private ToolbarHelper toolbar = new ToolbarHelper();
private TutorialHelper tut = new TutorialHelper();
private IntentHelper intent = new IntentHelper();
private AdmobHelper ad = new AdmobHelper();
private FileHelper file = new FileHelper();
private boolean doubleBackToExitPressedOnce = false;
private boolean isToolbarVisible = false;
private boolean isSettingsFromMenu = false;
private int circularRevealDuration = 400;
private int fadeAnimDuration = 200;
// private MaterialTapTargetPrompt promptToggle; // 1
// private MaterialTapTargetPrompt promptButton; // 2
// private MaterialTapTargetPrompt promptSwipe; // 3
// private MaterialTapTargetPrompt promptLoop; // 4
// private MaterialTapTargetPrompt promptPattern; // 5
// private MaterialTapTargetPrompt promptFab; // 6
// private MaterialTapTargetPrompt promptPreset; // 7
// private MaterialTapTargetPrompt promptInfo; // 8
// private MaterialTapTargetPrompt promptTutorial; // 9
private Gson gson = new Gson();
// TODO TAP launch
//IabHelper mHelper;
//IabBroadcastReceiver mBroadcastReceiver;
public static void largeLog(String tag, String content) {
if (content.length() > 4000) {
Log.d(tag, content.substring(0, 4000));
largeLog(tag, content.substring(4000));
} else {
Log.d(tag, content);
}
}
public static void showSettingsFragment(AppCompatActivity a) {
a.getSupportFragmentManager()
.beginTransaction()
.add(R.id.fragment_settings_container, new SettingsFragment())
.commit();
WindowHelper w = new WindowHelper();
w.getView(R.id.fragment_settings_container, a).setVisibility(View.VISIBLE);
setSettingVisible(true);
w.setRecentColor(R.string.settings, 0, R.color.colorAccent, a);
}
public static void setSettingVisible(boolean isVisible) {
isSettingVisible = isVisible;
Log.d("SettingVisible", String.valueOf(isSettingVisible));
}
public static void setAboutVisible(boolean isVisible) {
isAboutVisible = isVisible;
Log.d("AboutVisible", String.valueOf(isAboutVisible));
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
makeJson();
// TODO IAP launch
//String base64EncodePublicKey = constructBase64Key();
//mHelper = new IabHelper(this, base64EncodePublicKey);
//mHelper.enableDebugLogging(true);
// Start setup. This is asynchronous and the specified listener
// will be called once setup completes.
//Log.d(TAG, "Starting setup.");
//mHelper.startSetup(new IabHelper.OnIabSetupFinishedListener() {
// public void onIabSetupFinished(IabResult result) {
// Log.d(TAG, "Setup finished.");
// if (!result.isSuccess()) {
// // Oh noes, there was a problem.
// complain("Problem setting up in-app billing: " + result);
// return;
// // Have we been disposed of in the meantime? If so, quit.
// if (mHelper == null) return;
// // Important: Dynamically register for broadcast messages about updated purchases.
// // We register the receiver here instead of as a <receiver> in the Manifest
// // because we always call getPurchases() at startup, so therefore we can ignore
// // any broadcasts sent while the app isn't running.
// // Note: registering this listener in an Activity is a bad idea, but is done here
// // because this is a SAMPLE. Regardless, the receiver must be registered after
// // IabHelper is setup, but before first call to getPurchases().
// mBroadcastReceiver = new IabBroadcastReceiver(MainActivity.this);
// IntentFilter broadcastFilter = new IntentFilter(IabBroadcastReceiver.ACTION);
// registerReceiver(mBroadcastReceiver, broadcastFilter);
// // IAB is fully set up. Now, let's get an inventory of stuff we own.
// //Log.d(TAG, "Setup successful. Querying inventory.");
// //try {
// // mHelper.queryInventoryAsync(mGotInventoryListener);
// //} catch (IabAsyncInProgressException e) {
// // complain("Error querying inventory. Another async operation in progress.");
// sharedPrefs
Log.d(TAG, "Sharedprefs initialized");
prefs = this.getSharedPreferences(APPLICATION_ID, MODE_PRIVATE);
try {
currentVersionCode = a.getPackageManager().getPackageInfo(a.getPackageName(), 0).versionCode;
Log.i("versionCode", "versionCode retrieved = " + String.valueOf(currentVersionCode));
} catch (android.content.pm.PackageManager.NameNotFoundException e) {
// handle exception
currentVersionCode = -1;
Log.e("NameNotFound", "NNFE, currentVersionCode = -1");
}
// version checks
Intent launcherIntent = getIntent();
if (launcherIntent != null &&
launcherIntent.getStringExtra("version") != null) {
String version = launcherIntent.getStringExtra("version");
if (version.equals("new")) {
// new install, show intro
intent.intent(a, "activity.MainIntroActivity");
prefs.edit().putInt("versionCode", currentVersionCode).apply();
Log.d("VersionCode", "putInt " + String.valueOf(prefs.getInt("versionCode", -1)));
} else if (version.equals("updated")) {
// updated, show changelog
new MaterialDialog.Builder(a)
.title(w.getStringId("info_tapad_info_changelog"))
.content(w.getStringId("info_tapad_info_changelog_text"))
.contentColorRes(R.color.dark_primary)
.positiveText(R.string.dialog_close)
.positiveColorRes(R.color.colorAccent)
.dismissListener(new DialogInterface.OnDismissListener() {
@Override
public void onDismiss(DialogInterface dialogInterface) {
prefs.edit().putInt("versionCode", currentVersionCode).apply();
Log.d("VersionCode", "putInt " + String.valueOf(prefs.getInt("versionCode", -1)));
}
})
.show();
}
}
if (getSavedPreset() != null) {
try {
currentPreset = gson.fromJson(file.getStringFromFile(getCurrentPresetLocation() + "/about/json"), Preset.class);
} catch (Exception e) {
// corrupted preset
e.printStackTrace();
currentPreset = null;
}
}
if (!file.isPresetAvailable(currentPreset)) {
// preset corrupted or doesn't exist
currentPreset = null;
}
// for quickstart test
//prefs.edit().putInt(qs, 0).apply();
if (prefs.getBoolean("welcome", true)) {
prefs.edit().putBoolean("welcome", false).apply();
}
color = prefs.getInt("color", R.color.cyan_400);
toolbar.setActionBar(this);
toolbar.setStatusBarTint(this);
if (prefs.getString("colorData", null) == null) {
// First run colorData json set
ColorData placeHolderColorData = new ColorData(color);
String colorDataJson = gson.toJson(placeHolderColorData);
prefs.edit().putString("colorData", colorDataJson).apply();
Log.d("ColorData pref", prefs.getString("colorData", null));
}
a.setVolumeControlStream(AudioManager.STREAM_MUSIC);
// Set UI
clearToggleButton();
setFab();
setToolbar();
setPresetInfo();
setToggleButton(R.color.colorAccent);
enterAnim();
loadPreset(400);
setButtonLayout();
// Set transparent nav bar
w.setStatusBar(R.color.transparent, a);
w.setNavigationBar(R.color.transparent, a);
//ab.setStatusHeight(a);
clearDeck(a);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.actionbar_item, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch (id) {
case R.id.action_about:
intent.intentWithExtra(a, "activity.AboutActivity", "about", "tapad", 0);
break;
case R.id.action_settings:
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
showSettingsFragment(a);
isSettingsFromMenu = true;
}
}, 400);
break;
case R.id.action_help:
intent.intent(a, "activity.HelpActivity");
break;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onFragmentInteraction(Uri uri) {
// leave it empty
// used for fragments
}
@Override
public void onBackPressed() {
Log.i("BackPressed", "isAboutVisible " + String.valueOf(isAboutVisible));
Log.i("BackPressed", "isSettingVisible " + String.valueOf(isSettingVisible));
if (isToolbarVisible == true) {
if (prefs.getInt(qs, 0) > 0 && isAboutVisible == false && isSettingVisible == false) {
Log.i("BackPressed", String.valueOf(prefs.getInt(qs, 0)));
Log.i("BackPressed", "Quickstart tap target prompt is visible, backpress ignored.");
} else {
// new structure
if (isAboutVisible && isSettingVisible) {
// Setting is visible above about
closeSettings();
} else if (isSettingVisible) {
// Setting visible alone
closeSettings();
} else if (isAboutVisible) {
// About visible alone
closeAbout();
} else {
// Toolbar visible alone
closeToolbar(a);
}
}
} else if (isSettingVisible == true) {
// Setting is visible above about
closeSettings();
} else {
if (prefs.getInt(qs, 0) > 0) {
Log.i("BackPressed", "Tutorial prompt is visible, backpress ignored.");
} else {
Log.d("BackPressed", "Down");
if (doubleBackToExitPressedOnce) {
super.onBackPressed();
finish();
}
doubleBackToExitPressedOnce = true;
Toast.makeText(this, R.string.confirm_exit, Toast.LENGTH_SHORT).show();
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
doubleBackToExitPressedOnce = false;
}
}, 2000);
}
}
}
@Override
public void onWindowFocusChanged(boolean hasFocus) {
Log.i("MainActivity", "onWindowFocusChanged");
sound.soundAllStop();
int tutorial[] = {
R.id.btn00_tutorial,
R.id.tgl1_tutorial,
R.id.tgl2_tutorial,
R.id.tgl3_tutorial,
R.id.tgl4_tutorial,
R.id.tgl5_tutorial,
R.id.tgl6_tutorial,
R.id.tgl7_tutorial,
R.id.tgl8_tutorial,
R.id.btn11_tutorial,
R.id.btn12_tutorial,
R.id.btn13_tutorial,
R.id.btn14_tutorial,
R.id.btn21_tutorial,
R.id.btn22_tutorial,
R.id.btn23_tutorial,
R.id.btn24_tutorial,
R.id.btn31_tutorial,
R.id.btn32_tutorial,
R.id.btn33_tutorial,
R.id.btn34_tutorial,
R.id.btn41_tutorial,
R.id.btn42_tutorial,
R.id.btn43_tutorial,
R.id.btn44_tutorial};
for (int view : tutorial) {
w.setInvisible(view, 10, a);
}
color = prefs.getInt("color", R.color.cyan_400);
if (isPresetVisible) {
if (!isAboutVisible && !isSettingVisible) {
// preset store visible
closePresetStore();
}
isPresetVisible = false;
}
if (isPresetChanged) {
currentPreset = null;
if (getSavedPreset() != null) {
// preset loaded
Log.d(TAG, "changed");
currentPreset = gson.fromJson(file.getStringFromFile(getCurrentPresetLocation() + "/about/json"), Preset.class);
loadPreset(0);
} else {
Log.d(TAG, "removed");
}
setPresetInfo();
isPresetChanged = false;
}
clearToggleButton();
super.onWindowFocusChanged(hasFocus);
}
@Override
public void onPause() {
ad.pauseNativeAdView(R.id.adView_main, a);
super.onPause();
}
@Override
public void onResume() {
super.onResume();
if (isTutorialVisible == true) {
tut.tutorialStop(a);
}
Log.d("MainActivity", "onResume");
sound.soundAllStop();
int tutorial[] = {
R.id.btn00_tutorial,
R.id.tgl1_tutorial,
R.id.tgl2_tutorial,
R.id.tgl3_tutorial,
R.id.tgl4_tutorial,
R.id.tgl5_tutorial,
R.id.tgl6_tutorial,
R.id.tgl7_tutorial,
R.id.tgl8_tutorial,
R.id.btn11_tutorial,
R.id.btn12_tutorial,
R.id.btn13_tutorial,
R.id.btn14_tutorial,
R.id.btn21_tutorial,
R.id.btn22_tutorial,
R.id.btn23_tutorial,
R.id.btn24_tutorial,
R.id.btn31_tutorial,
R.id.btn32_tutorial,
R.id.btn33_tutorial,
R.id.btn34_tutorial,
R.id.btn41_tutorial,
R.id.btn42_tutorial,
R.id.btn43_tutorial,
R.id.btn44_tutorial};
for (int i = 0; i < tutorial.length; i++) {
w.setInvisible(tutorial[i], 10, a);
}
ad.resumeNativeAdView(R.id.adView_main, a);
if (currentPreset != null && !file.isPresetAvailable(currentPreset)) {
currentPreset = null;
}
setPresetInfo();
}
// TODO iap launch
// IabHelper.QueryInventoryFinishedListener mGotInventoryListener = new IabHelper.QueryInventoryFinishedListener() {
// public void onQueryInventoryFinished(IabResult result, Inventory inventory) {
// Log.d(TAG, "Query inventory finished.");
// // Have we been disposed of in the meantime? If so, quit.
// if (mHelper == null) return;
// // Is it a failure?
// if (result.isFailure()) {
// complain("Failed to query inventory: " + result);
// return;
// Log.d(TAG, "Query inventory was successful.");
// Log.d(TAG, "Initial inventory query finished; enabling main UI.");
// @NonNull
// private String constructBase64Key() {
// // TODO work on iap processes
// String encodedString = getResources().getString(R.string.base64_rsa_key);
// int base64Length = encodedString.length();
// char[] encodedStringArray = encodedString.toCharArray();
// char temp;
// for(int i = 0; i < base64Length / 2; i++) {
// if (i % 2 == 0) {
// temp = encodedStringArray[i];
// encodedStringArray[i] = encodedStringArray[base64Length - 1 - i];
// encodedStringArray[base64Length - 1 - i] = temp;
// return String.valueOf(encodedStringArray);
// private void complain(String message) {
// alert("Error: " + message);
// private void alert(String message) {
// AlertDialog.Builder bld = new AlertDialog.Builder(this);
// bld.setMessage(message);
// bld.setNeutralButton("OK", null);
// Log.d(TAG, "Showing alert dialog: " + message);
// bld.create().show();
@Override
protected void onDestroy() {
Log.d(TAG, "onDestroy");
sound.soundAllStop();
sound.cancelLoading();
ad.destroyNativeAdView(R.id.adView_main, a);
super.onDestroy();
}
private void showAboutFragment() {
getSupportFragmentManager()
.beginTransaction()
.add(R.id.fragment_about_container, new AboutFragment())
.commit();
WindowHelper w = new WindowHelper();
w.getView(R.id.fragment_about_container, a).setVisibility(View.VISIBLE);
setAboutVisible(true);
w.setRecentColor(R.string.about, 0, themeColor, a);
}
private void enterAnim() {
anim.fadeIn(R.id.actionbar_layout, 0, 200, "background", a);
anim.fadeIn(R.id.actionbar_image, 200, 200, "image", a);
isPresetLoading = true;
}
private void setButtonLayout() {
int screenWidthPx = (int) (w.getWindowWidthPx(a) * (0.8));
int marginPx = w.getWindowWidthPx(a) / 160;
int newWidthPx;
int newHeightPx;
int buttons[][] = {
// first row is root view
{R.id.ver0, R.id.tgl1, R.id.tgl2, R.id.tgl3, R.id.tgl4, R.id.btn00},
{R.id.ver1, R.id.btn11, R.id.btn12, R.id.btn13, R.id.btn14, R.id.tgl5},
{R.id.ver2, R.id.btn21, R.id.btn22, R.id.btn23, R.id.btn24, R.id.tgl6},
{R.id.ver3, R.id.btn31, R.id.btn32, R.id.btn33, R.id.btn34, R.id.tgl7},
{R.id.ver4, R.id.btn41, R.id.btn42, R.id.btn43, R.id.btn44, R.id.tgl8},
};
int tutorialButtons[][] = {
// first row is root view
{R.id.ver0_tutorial, R.id.tgl1_tutorial, R.id.tgl2_tutorial, R.id.tgl3_tutorial, R.id.tgl4_tutorial, R.id.btn00_tutorial},
{R.id.ver1_tutorial, R.id.btn11_tutorial, R.id.btn12_tutorial, R.id.btn13_tutorial, R.id.btn14_tutorial, R.id.tgl5_tutorial},
{R.id.ver2_tutorial, R.id.btn21_tutorial, R.id.btn22_tutorial, R.id.btn23_tutorial, R.id.btn24_tutorial, R.id.tgl6_tutorial},
{R.id.ver3_tutorial, R.id.btn31_tutorial, R.id.btn32_tutorial, R.id.btn33_tutorial, R.id.btn34_tutorial, R.id.tgl7_tutorial},
{R.id.ver4_tutorial, R.id.btn41_tutorial, R.id.btn42_tutorial, R.id.btn43_tutorial, R.id.btn44_tutorial, R.id.tgl8_tutorial},
};
for (int i = 0; i < 5; i++) {
if (i == 0) {
newHeightPx = screenWidthPx / 9;
} else {
newHeightPx = (screenWidthPx / 9) * 2;
}
for (int j = 0; j < 6; j++) {
if (j == 0) {
resizeView(tutorialButtons[i][j], 0, newHeightPx);
resizeView(buttons[i][j], 0, newHeightPx);
} else if (j == 5) {
newWidthPx = screenWidthPx / 9;
resizeView(tutorialButtons[i][j], newWidthPx, newHeightPx);
resizeView(buttons[i][j], newWidthPx - (marginPx * 2), newHeightPx - (marginPx * 2));
w.setMarginLinearPX(buttons[i][j], marginPx, marginPx, marginPx, marginPx, a);
if (i != 0) {
w.getTextView(buttons[i][j], a).setTextSize(TypedValue.COMPLEX_UNIT_PX, (float) (newWidthPx / 3));
}
} else {
newWidthPx = (screenWidthPx / 9) * 2;
resizeView(tutorialButtons[i][j], newWidthPx, newHeightPx);
resizeView(buttons[i][j], newWidthPx - (marginPx * 2), newHeightPx - (marginPx * 2));
w.setMarginLinearPX(buttons[i][j], marginPx, marginPx, marginPx, marginPx, a);
if (i == 0) {
w.getTextView(buttons[i][j], a).setTextSize(TypedValue.COMPLEX_UNIT_PX, (float) (newHeightPx / 3));
}
}
}
}
}
private void resizeView(int viewId, int newWidth, int newHeight) {
View view = a.findViewById(viewId);
Log.d("resizeView", "width " + newWidth + " X height " + newHeight);
if (newHeight > 0) {
view.getLayoutParams().height = newHeight;
}
if (newWidth > 0) {
view.getLayoutParams().width = newWidth;
}
view.setLayoutParams(view.getLayoutParams());
}
private void setFab() {
fab.setFab(a);
fab.setFabIcon(R.drawable.ic_info_white, a);
fab.showFab();
fab.setFabOnClickListener(new Runnable() {
@Override
public void run() {
if (isToolbarVisible == false) {
fab.hideFab(0, 200);
anim.fadeIn(R.id.toolbar, 200, 100, "toolbarIn", a);
// if (prefs.getInt(qs, 0) == 7) {
// Log.i("setQuickstart", "Quickstart started");
// if (promptInfo != null) {
// return;
// promptInfo = new MaterialTapTargetPrompt.Builder(a)
// .setTarget(a.findViewById(R.id.toolbar_info))
// .setPrimaryText(R.string.dialog_tap_target_info_primary)
// .setSecondaryText(R.string.dialog_tap_target_info_secondary)
// .setAnimationInterpolator(new FastOutSlowInInterpolator())
// .setFocalColourFromRes(R.color.blue_500)
// .setAutoDismiss(false)
// .setAutoFinish(false)
// .setCaptureTouchEventOutsidePrompt(true)
// .setOnHidePromptListener(new MaterialTapTargetPrompt.OnHidePromptListener() {
// @Override
// public void onHidePrompt(MotionEvent event, boolean tappedTarget) {
// if (tappedTarget) {
// promptInfo.finish();
// promptInfo = null;
// prefs.edit().putInt(qs, 8).apply();
// Log.i("sharedPrefs", "quickstart edited to 8");
// @Override
// public void onHidePromptComplete() {
// .show();
isToolbarVisible = true;
}
}
});
// set bottom margin
w.setMarginRelativePX(R.id.fab, 0, 0, w.convertDPtoPX(20, a), w.getNavigationBarFromPrefs(a) + w.convertDPtoPX(20, a), a);
}
private void setToolbar() {
// set bottom margin
w.setMarginRelativePX(R.id.toolbar, 0, 0, 0, w.getNavigationBarFromPrefs(a), a);
View info = findViewById(R.id.toolbar_info);
View tutorial = findViewById(R.id.toolbar_tutorial);
View preset = findViewById(R.id.toolbar_preset);
View settings = findViewById(R.id.toolbar_settings);
assert info != null;
info.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
coord[0] = (int) event.getRawX();
coord[1] = (int) event.getRawY();
return false;
}
});
info.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (isAboutVisible == false) {
anim.circularRevealInPx(R.id.placeholder,
coord[0], coord[1],
0, (int) Math.hypot(coord[0], coord[1]) + 200, new AccelerateDecelerateInterpolator(),
circularRevealDuration, 0, a);
Handler about = new Handler();
about.postDelayed(new Runnable() {
@Override
public void run() {
showAboutFragment();
}
}, circularRevealDuration);
anim.fadeOut(R.id.placeholder, circularRevealDuration, fadeAnimDuration, a);
isAboutVisible = true;
}
}
});
assert preset != null;
preset.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
coord[0] = (int) event.getRawX();
coord[1] = (int) event.getRawY();
return false;
}
});
preset.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (isPresetVisible == false) {
anim.circularRevealInPx(R.id.placeholder,
coord[0], coord[1],
0, (int) Math.hypot(coord[0], coord[1]) + 200, new AccelerateDecelerateInterpolator(),
circularRevealDuration, 0, a);
intent.intent(a, "activity.PresetStoreActivity", circularRevealDuration);
}
}
});
assert tutorial != null;
tutorial.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
coord[0] = (int) event.getRawX();
coord[1] = (int) event.getRawY();
return false;
}
});
tutorial.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
showTutorial();
}
});
assert settings != null;
settings.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
coord[2] = (int) event.getRawX();
coord[3] = (int) event.getRawY();
return false;
}
});
settings.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (isSettingVisible == false) {
w.setRecentColor(R.string.settings, 0, R.color.colorAccent, a);
anim.circularRevealInPx(R.id.placeholder,
coord[2], coord[3],
0, (int) Math.hypot(coord[2], coord[3]) + 200, new AccelerateDecelerateInterpolator(),
circularRevealDuration, 0, a);
Handler about = new Handler();
about.postDelayed(new Runnable() {
@Override
public void run() {
showSettingsFragment(a);
}
}, circularRevealDuration);
anim.fadeOut(R.id.placeholder, circularRevealDuration, fadeAnimDuration, a);
setSettingVisible(true);
}
}
});
}
private void closeToolbar(Activity activity) {
anim.fadeOut(R.id.toolbar, 0, 100, activity);
fab.showFab(100, 200);
isToolbarVisible = false;
}
private void closeAbout() {
Log.d("closeAbout", "triggered");
anim.circularRevealInPx(R.id.placeholder,
coord[0], coord[1],
(int) Math.hypot(coord[0], coord[1]) + 200, 0, new AccelerateDecelerateInterpolator(),
circularRevealDuration, fadeAnimDuration, a);
anim.fadeIn(R.id.placeholder, 0, fadeAnimDuration, "aboutOut", a);
setAboutVisible(false);
Handler closeAbout = new Handler();
closeAbout.postDelayed(new Runnable() {
@Override
public void run() {
setPresetInfo();
w.getView(R.id.fragment_about_container, a).setVisibility(View.GONE);
}
}, fadeAnimDuration);
// Firstrun tutorial
// if (prefs.getInt(qs, 0) == 8) {
// promptPreset = new MaterialTapTargetPrompt.Builder(a)
// .setTarget(a.findViewById(R.id.toolbar_preset))
// .setPrimaryText(R.string.dialog_tap_target_preset_primary)
// .setSecondaryText(R.string.dialog_tap_target_preset_secondary)
// .setAnimationInterpolator(new FastOutSlowInInterpolator())
// .setFocalColourFromRes(R.color.blue_500)
// .setAutoDismiss(false)
// .setAutoFinish(false)
// .setCaptureTouchEventOutsidePrompt(true)
// .setOnHidePromptListener(new MaterialTapTargetPrompt.OnHidePromptListener() {
// @Override
// public void onHidePrompt(MotionEvent event, boolean tappedTarget) {
// if (tappedTarget) {
// promptPreset.finish();
// promptPreset = null;
// prefs.edit().putInt(qs, 9).apply();
// Log.i("sharedPrefs", "quickstart edited to 9");
// @Override
// public void onHidePromptComplete() {
// // idk why is this here
// //isTutorialVisible = false;
// .show();
// reset the touch coords
coord[0] = 0;
coord[1] = 0;
}
private void showTutorial() {
if (isTutorialVisible == false) {
isTutorialVisible = true;
if (currentPreset != null) {
if (!isPresetLoading) {
String tutorialText = currentPreset.getAbout().getTutorialLink();
if (tutorialText == null || tutorialText.equals("null")) {
tutorialText = w.getStringFromId("dialog_tutorial_text_error", a);
}
new MaterialDialog.Builder(a)
.title(R.string.dialog_tutorial_title)
.content(tutorialText)
.neutralText(R.string.dialog_close)
.dismissListener(new DialogInterface.OnDismissListener() {
@Override
public void onDismiss(DialogInterface dialog) {
isTutorialVisible = false;
}
})
.show();
} else {
// still loading preset
Toast.makeText(a, R.string.tutorial_loading, Toast.LENGTH_LONG).show();
isTutorialVisible = false;
}
} else {
// no preset
Toast.makeText(a, R.string.tutorial_no_preset, Toast.LENGTH_LONG).show();
isTutorialVisible = false;
}
}
}
private void closeSettings() {
Log.d("closeSettings", "triggered");
if (isToolbarVisible && !isSettingsFromMenu) {
anim.circularRevealInPx(R.id.placeholder,
coord[2], coord[3],
(int) Math.hypot(coord[2], coord[3]) + 200, 0, new AccelerateDecelerateInterpolator(),
circularRevealDuration, fadeAnimDuration, a);
anim.fadeIn(R.id.placeholder, 0, fadeAnimDuration, "settingOut", a);
} else {
w.getView(R.id.fragment_settings_container, a).setVisibility(View.GONE);
isSettingsFromMenu = false;
}
color = prefs.getInt("color", R.color.cyan_400);
clearToggleButton();
setSettingVisible(false);
Handler closeSettings = new Handler();
closeSettings.postDelayed(new Runnable() {
@Override
public void run() {
if (isAboutVisible) {
// about visible set taskdesc
w.setRecentColor(R.string.about, 0, themeColor, a);
} else {
setPresetInfo();
}
w.getView(R.id.fragment_settings_container, a).setVisibility(View.GONE);
}
}, fadeAnimDuration);
// reset the touch coords
coord[2] = 0;
coord[3] = 0;
}
private void closePresetStore() {
setPresetInfo();
if (coord[0] > 0 && coord[1] > 0) {
anim.circularRevealInPx(R.id.placeholder,
coord[0], coord[1],
(int) Math.hypot(coord[0], coord[1]) + 200, 0, new AccelerateDecelerateInterpolator(),
circularRevealDuration, 200, a);
}
// if (prefs.getInt(qs, 0) == 7) {
// promptTutorial = new MaterialTapTargetPrompt.Builder(a)
// .setTarget(a.findViewById(R.id.toolbar_tutorial))
// .setPrimaryText(R.string.dialog_tap_target_tutorial_primary)
// .setSecondaryText(R.string.dialog_tap_target_tutorial_secondary)
// .setAnimationInterpolator(new FastOutSlowInInterpolator())
// .setFocalColourFromRes(R.color.blue_500)
// .setAutoDismiss(false)
// .setAutoFinish(false)
// .setCaptureTouchEventOutsidePrompt(true)
// .setOnHidePromptListener(new MaterialTapTargetPrompt.OnHidePromptListener() {
// @Override
// public void onHidePrompt(MotionEvent event, boolean tappedTarget) {
// if (tappedTarget) {
// promptTutorial.finish();
// promptTutorial = null;
// prefs.edit().putInt(qs, -1).apply();
// Log.i("sharedPrefs", "quickstart edited to -1, completed");
// @Override
// public void onHidePromptComplete() {
// .show();
}
private void loadPreset(int delay) {
if (currentPreset != null) {
Handler preset = new Handler();
preset.postDelayed(new Runnable() {
@Override
public void run() {
sound.loadSound(currentPreset, a);
}
}, delay);
}
}
private void setToggleButton(final int color_id) {
// 1 - 4
w.setOnTouch(R.id.tgl1, new Runnable() {
@Override
public void run() {
clearDeck(a);
if (tgl1 == false) {
toggleSoundId = 1;
if (tgl5 || tgl6 || tgl7 || tgl8) {
sound.setButtonToggle(toggleSoundId, color, togglePatternId, a);
} else {
sound.setButtonToggle(toggleSoundId, color, a);
}
w.setViewBackgroundColor(R.id.tgl1, color_id, a);
w.setViewBackgroundColor(R.id.tgl2, R.color.grey, a);
w.setViewBackgroundColor(R.id.tgl3, R.color.grey, a);
w.setViewBackgroundColor(R.id.tgl4, R.color.grey, a);
if (tgl2 || tgl3 || tgl4) {
sound.playToggleButtonSound(1);
}
} else {
w.setViewBackgroundColor(R.id.tgl1, R.color.grey, a);
toggleSoundId = 0;
sound.setButton(R.color.grey_dark, a);
sound.soundAllStop();
}
}
}, new Runnable() {
@Override
public void run() {
if (tgl1 == false) {
tgl1 = true;
tgl2 = false;
tgl3 = false;
tgl4 = false;
} else {
tgl1 = false;
}
}
}, a);
w.setOnTouch(R.id.tgl2, new Runnable() {
@Override
public void run() {
clearDeck(a);
if (tgl2 == false) {
toggleSoundId = 2;
if (tgl5 || tgl6 || tgl7 || tgl8) {
sound.setButtonToggle(toggleSoundId, color, togglePatternId, a);
} else {
sound.setButtonToggle(toggleSoundId, color, a);
}
w.setViewBackgroundColor(R.id.tgl2, color_id, a);
w.setViewBackgroundColor(R.id.tgl1, R.color.grey, a);
w.setViewBackgroundColor(R.id.tgl3, R.color.grey, a);
w.setViewBackgroundColor(R.id.tgl4, R.color.grey, a);
sound.playToggleButtonSound(2);
} else {
w.setViewBackgroundColor(R.id.tgl2, R.color.grey, a);
toggleSoundId = 0;
sound.setButton(R.color.grey_dark, a);
sound.soundAllStop();
}
}
}, new Runnable() {
@Override
public void run() {
if (tgl2 == false) {
tgl2 = true;
tgl1 = false;
tgl3 = false;
tgl4 = false;
} else {
tgl2 = false;
}
}
}, a);
w.setOnTouch(R.id.tgl3, new Runnable() {
@Override
public void run() {
clearDeck(a);
if (tgl3 == false) {
toggleSoundId = 3;
if (tgl5 || tgl6 || tgl7 || tgl8) {
sound.setButtonToggle(toggleSoundId, color, togglePatternId, a);
} else {
sound.setButtonToggle(toggleSoundId, color, a);
}
w.setViewBackgroundColor(R.id.tgl3, color_id, a);
w.setViewBackgroundColor(R.id.tgl2, R.color.grey, a);
w.setViewBackgroundColor(R.id.tgl1, R.color.grey, a);
w.setViewBackgroundColor(R.id.tgl4, R.color.grey, a);
sound.playToggleButtonSound(3);
} else {
w.setViewBackgroundColor(R.id.tgl3, R.color.grey, a);
toggleSoundId = 0;
sound.setButton(R.color.grey_dark, a);
sound.soundAllStop();
}
}
}, new Runnable() {
@Override
public void run() {
if (tgl3 == false) {
tgl3 = true;
tgl2 = false;
tgl1 = false;
tgl4 = false;
} else {
tgl3 = false;
}
}
}, a);
w.setOnTouch(R.id.tgl4, new Runnable() {
@Override
public void run() {
clearDeck(a);
if (tgl4 == false) {
toggleSoundId = 4;
if (tgl5 || tgl6 || tgl7 || tgl8) {
sound.setButtonToggle(toggleSoundId, color, togglePatternId, a);
} else {
sound.setButtonToggle(toggleSoundId, color, a);
}
w.setViewBackgroundColor(R.id.tgl4, color_id, a);
w.setViewBackgroundColor(R.id.tgl2, R.color.grey, a);
w.setViewBackgroundColor(R.id.tgl3, R.color.grey, a);
w.setViewBackgroundColor(R.id.tgl1, R.color.grey, a);
sound.playToggleButtonSound(4);
} else {
w.setViewBackgroundColor(R.id.tgl4, R.color.grey, a);
toggleSoundId = 0;
sound.setButton(R.color.grey_dark, a);
sound.soundAllStop();
}
}
}, new Runnable() {
@Override
public void run() {
if (tgl4 == false) {
tgl4 = true;
tgl2 = false;
tgl3 = false;
tgl1 = false;
} else {
tgl4 = false;
}
}
}, a);
// 5 - 8
w.setOnTouch(R.id.tgl5, new Runnable() {
@Override
public void run() {
if (tgl5 == false) {
togglePatternId = 1;
if (tgl1 || tgl2 || tgl3 || tgl4) {
sound.setButtonToggle(toggleSoundId, color, togglePatternId, a);
}
w.setViewBackgroundColor(R.id.tgl5, color_id, a);
w.setViewBackgroundColor(R.id.tgl6, R.color.grey, a);
w.setViewBackgroundColor(R.id.tgl7, R.color.grey, a);
w.setViewBackgroundColor(R.id.tgl8, R.color.grey, a);
} else {
w.setViewBackgroundColor(R.id.tgl5, R.color.grey, a);
togglePatternId = 0;
if (tgl1 || tgl2 || tgl3 || tgl4) {
sound.setButtonToggle(toggleSoundId, color, a);
}
}
}
}, new Runnable() {
@Override
public void run() {
if (tgl5 == false) {
tgl5 = true;
tgl6 = false;
tgl7 = false;
tgl8 = false;
} else {
tgl5 = false;
}
}
}, a);
w.setOnTouch(R.id.tgl6, new Runnable() {
@Override
public void run() {
if (tgl6 == false) {
togglePatternId = 2;
if (tgl1 || tgl2 || tgl3 || tgl4) {
sound.setButtonToggle(toggleSoundId, color, togglePatternId, a);
}
w.setViewBackgroundColor(R.id.tgl6, color_id, a);
w.setViewBackgroundColor(R.id.tgl5, R.color.grey, a);
w.setViewBackgroundColor(R.id.tgl7, R.color.grey, a);
w.setViewBackgroundColor(R.id.tgl8, R.color.grey, a);
} else {
w.setViewBackgroundColor(R.id.tgl6, R.color.grey, a);
togglePatternId = 0;
if (tgl1 || tgl2 || tgl3 || tgl4) {
sound.setButtonToggle(toggleSoundId, color, a);
}
}
}
}, new Runnable() {
@Override
public void run() {
if (tgl6 == false) {
tgl6 = true;
tgl5 = false;
tgl7 = false;
tgl8 = false;
} else {
tgl6 = false;
}
}
}, a);
w.setOnTouch(R.id.tgl7, new Runnable() {
@Override
public void run() {
if (tgl7 == false) {
togglePatternId = 3;
if (tgl1 || tgl2 || tgl3 || tgl4) {
sound.setButtonToggle(toggleSoundId, color, togglePatternId, a);
}
w.setViewBackgroundColor(R.id.tgl7, color_id, a);
w.setViewBackgroundColor(R.id.tgl6, R.color.grey, a);
w.setViewBackgroundColor(R.id.tgl5, R.color.grey, a);
w.setViewBackgroundColor(R.id.tgl8, R.color.grey, a);
} else {
w.setViewBackgroundColor(R.id.tgl7, R.color.grey, a);
togglePatternId = 0;
if (tgl1 || tgl2 || tgl3 || tgl4) {
sound.setButtonToggle(toggleSoundId, color, a);
}
}
}
}, new Runnable() {
@Override
public void run() {
if (tgl7 == false) {
tgl7 = true;
tgl6 = false;
tgl5 = false;
tgl8 = false;
} else {
tgl7 = false;
}
}
}, a);
w.setOnTouch(R.id.tgl8, new Runnable() {
@Override
public void run() {
if (tgl8 == false) {
togglePatternId = 4;
if (tgl1 || tgl2 || tgl3 || tgl4) {
sound.setButtonToggle(toggleSoundId, color, togglePatternId, a);
}
w.setViewBackgroundColor(R.id.tgl8, color_id, a);
w.setViewBackgroundColor(R.id.tgl6, R.color.grey, a);
w.setViewBackgroundColor(R.id.tgl7, R.color.grey, a);
w.setViewBackgroundColor(R.id.tgl5, R.color.grey, a);
} else {
w.setViewBackgroundColor(R.id.tgl8, R.color.grey, a);
togglePatternId = 0;
if (tgl1 || tgl2 || tgl3 || tgl4) {
sound.setButtonToggle(toggleSoundId, color, a);
}
}
}
}, new Runnable() {
@Override
public void run() {
if (tgl8 == false) {
tgl8 = true;
tgl6 = false;
tgl7 = false;
tgl5 = false;
} else {
tgl8 = false;
}
}
}, a);
}
public void clearDeck(Activity activity) {
// clear button colors
int buttonIds[] = {
R.id.btn00,
R.id.btn11,
R.id.btn12,
R.id.btn13,
R.id.btn14,
R.id.btn21,
R.id.btn22,
R.id.btn23,
R.id.btn24,
R.id.btn31,
R.id.btn32,
R.id.btn33,
R.id.btn34,
R.id.btn41,
R.id.btn42,
R.id.btn43,
R.id.btn44
};
for (int buttonId : buttonIds) {
View pad = activity.findViewById(buttonId);
pad.setBackgroundColor(activity.getResources().getColor(R.color.grey));
}
// stop all looping sounds
Integer streamIds[] = w.getLoopStreamIds();
SoundPool soundPool = sound.getSoundPool();
try {
for (Integer streamId : streamIds) {
soundPool.stop(streamId);
}
} finally {
w.clearLoopStreamId();
}
}
private void clearToggleButton() {
if (isDeckShouldCleared) {
w.setViewBackgroundColor(R.id.tgl1, R.color.grey, a);
w.setViewBackgroundColor(R.id.tgl2, R.color.grey, a);
w.setViewBackgroundColor(R.id.tgl3, R.color.grey, a);
w.setViewBackgroundColor(R.id.tgl4, R.color.grey, a);
w.setViewBackgroundColor(R.id.tgl5, R.color.grey, a);
w.setViewBackgroundColor(R.id.tgl6, R.color.grey, a);
w.setViewBackgroundColor(R.id.tgl7, R.color.grey, a);
w.setViewBackgroundColor(R.id.tgl8, R.color.grey, a);
tgl1 = false;
tgl2 = false;
tgl3 = false;
tgl4 = false;
tgl5 = false;
tgl6 = false;
tgl7 = false;
tgl8 = false;
sound.setButton(R.color.grey_dark, a);
toggleSoundId = 0;
sound.soundAllStop();
isDeckShouldCleared = false;
}
}
private void setPresetInfo() {
if (isSettingVisible == false && isAboutVisible == false && currentPreset != null) {
themeColor = currentPreset.getAbout().getActionbarColor();
toolbar.setActionBarTitle(0);
toolbar.setActionBarColor(themeColor, a);
toolbar.setActionBarPadding(a);
toolbar.setActionBarImage(
PROJECT_LOCATION_PRESETS + "/" + currentPreset.getFirebaseLocation() + "/about/artist_icon",
this);
w.setRecentColor(0, 0, themeColor, a);
w.setVisible(R.id.base, 0, a);
w.setGone(R.id.main_cardview_preset_store, 0, a);
} else if (currentPreset == null || getSavedPreset() == null) {
toolbar.setActionBarTitle(R.string.app_name);
toolbar.setActionBarColor(R.color.colorPrimary, a);
toolbar.setActionBarPadding(a);
toolbar.setActionBarImage(0, this);
w.setRecentColor(0, 0, R.color.colorPrimary, a);
w.getView(R.id.main_cardview_preset_store, a).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
intent.intent(a, "activity.PresetStoreActivity");
}
});
w.getView(R.id.main_cardview_preset_store_download, a).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
intent.intent(a, "activity.PresetStoreActivity");
}
});
w.setVisible(R.id.main_cardview_preset_store, 0, a);
w.setGone(R.id.base, 0, a);
}
}
public String getCurrentPresetLocation() {
if (getSavedPreset() != null) {
return PROJECT_LOCATION_PRESETS + "/" + getSavedPreset();
} else {
return null;
}
}
public String getSavedPreset() {
return prefs.getString(PRESET_KEY, null);
}
public void setSavedPreset(String savedPreset) {
prefs.edit().putString(PRESET_KEY, savedPreset).apply();
}
private String getAvailableDownloadedPreset() {
File directory = new File(PROJECT_LOCATION_PRESETS);
File[] files = directory.listFiles();
String presetName = null;
if (files != null) {
for (File dir : files) {
if (dir.isDirectory()) {
presetName = dir.getName();
if (isPresetExists(presetName)) {
if (file.isPresetAvailable(presetName)) {
// available preset
break;
}
}
}
}
}
return presetName;
}
private boolean isPresetExists(String presetName) {
// preset exist
File folder = new File(PROJECT_LOCATION_PRESETS + "/" + presetName); // folder check
return folder.isDirectory() && folder.exists();
}
private void makeJson() {
Item fadedItems[] = {
new Item("facebook", w.getStringFromId("preset_faded_detail_facebook", a)),
new Item("twitter", w.getStringFromId("preset_faded_detail_twitter", a)),
new Item("soundcloud", w.getStringFromId("preset_faded_detail_soundcloud", a)),
new Item("instagram", w.getStringFromId("preset_faded_detail_instagram", a)),
new Item("google_plus", w.getStringFromId("preset_faded_detail_google_plus", a)),
new Item("youtube", w.getStringFromId("preset_faded_detail_youtube", a)),
//new Item("twitch", w.getStringFromId("preset_faded_detail_twitch", a)), // only omfg
new Item("web", w.getStringFromId("preset_faded_detail_web", a))
};
Detail fadedDetail = new Detail(w.getStringFromId("preset_faded_detail_title", a), fadedItems);
Item fadedSongItems[] = {
new Item("soundcloud", w.getStringFromId("preset_faded_song_detail_soundcloud", a), false),
new Item("youtube", w.getStringFromId("preset_faded_song_detail_youtube", a), false),
new Item("spotify", w.getStringFromId("preset_faded_song_detail_spotify", a), false),
new Item("google_play_music", w.getStringFromId("preset_faded_song_detail_google_play_music", a), false),
new Item("apple", w.getStringFromId("preset_faded_song_detail_apple", a), false),
new Item("amazon", w.getStringFromId("preset_faded_song_detail_amazon", a), false),
new Item("pandora", w.getStringFromId("preset_faded_song_detail_pandora", a), false)
};
Detail fadedSongDetail = new Detail(w.getStringFromId("preset_faded_song_detail_title", a), fadedSongItems);
Bio fadedBio = new Bio(
w.getStringFromId("preset_faded_bio_title", a),
"alan_walker_faded_gesture",
w.getStringFromId("preset_faded_bio_name", a),
w.getStringFromId("preset_faded_bio_text", a),
w.getStringFromId("preset_faded_bio_source", a)
);
Detail fadedDetails[] = {
fadedDetail,
fadedSongDetail
};
About fadedAbout = new About(
w.getStringFromId("preset_faded_title", a),
"alan_walker_faded_gesture",
w.getStringFromId("preset_faded_tutorial_link", a),
"Studio Berict",
"#00D3BE",
fadedBio, fadedDetails
);
Music fadedMusic = new Music(
"preset_faded",
"alan_walker_faded_gesture",
true,
246,
90,
null
);
Preset fadedPreset = new Preset("alan_walker_faded_gesture", fadedMusic, fadedAbout);
largeLog("JSON", gson.toJson(fadedPreset));
Preset[] presets = {
fadedPreset
};
FirebaseMetadata firebaseMetadata = new FirebaseMetadata(presets, 15);
largeLog("Metadata", gson.toJson(firebaseMetadata));
// Bio tapadBio = new Bio(
// w.getStringFromId("info_tapad_bio_title", a),
// "about_bio_tapad",
// w.getStringFromId("info_tapad_bio_name", a),
// w.getStringFromId("info_tapad_bio_text", a),
// w.getStringFromId("info_tapad_bio_source", a)
// Item tapadInfo[] = {
// new Item("info_tapad_info_check_update", w.getStringFromId("info_tapad_info_check_update_hint", a), "google_play", true),
// new Item("info_tapad_info_tester", w.getStringFromId("info_tapad_info_tester_hint", a), "experiment", true),
// new Item("info_tapad_info_version", w.getStringFromId("info_tapad_info_version_hint", a), ""),
// new Item("info_tapad_info_build_date", w.getStringFromId("info_tapad_info_build_date_hint", a), ""),
// new Item("info_tapad_info_changelog", null, "changelog", false),
// new Item("info_tapad_info_thanks", null, "thanks", false),
// new Item("info_tapad_info_dev", w.getStringFromId("info_tapad_info_dev_hint", a), "developer", false)
// // TODO ADD ITEMS
// Item tapadOthers[] = {
// new Item("info_tapad_others_song", w.getStringFromId("info_tapad_others_song_hint", a), "song", true),
// new Item("info_tapad_others_feedback", w.getStringFromId("info_tapad_others_feedback_hint", a), "feedback", true),
// new Item("info_tapad_others_report_bug", w.getStringFromId("info_tapad_others_report_bug_hint", a), "report_bug", true),
// new Item("info_tapad_others_rate", w.getStringFromId("info_tapad_others_rate_hint", a), "rate", true),
// new Item("info_tapad_others_translate", w.getStringFromId("info_tapad_others_translate_hint", a), "web", false),
// new Item("info_tapad_others_recommend", w.getStringFromId("info_tapad_others_recommend_hint", a), "recommend", true)
// Detail tapadDetails[] = {
// new Detail(w.getStringFromId("info_tapad_info_title", a), tapadInfo),
// new Detail(w.getStringFromId("info_tapad_others_title", a), tapadOthers)
// About tapadAbout = new About(
// w.getStringFromId("info_tapad_title", a),
// "about_image_tapad",
// "#9C27B0",
// tapadBio, tapadDetails
// largeLog("tapadAboutJSON", gson.toJson(tapadAbout));
// Bio berictBio = new Bio(
// w.getStringFromId("info_berict_bio_title", a),
// null,
// w.getStringFromId("info_berict_bio_name", a),
// w.getStringFromId("info_berict_bio_text", a),
// w.getStringFromId("info_berict_bio_source", a)
// Item devItems[] = {
// new Item("facebook", w.getStringFromId("info_berict_detail_facebook", a)),
// new Item("twitter", w.getStringFromId("info_berict_detail_twitter", a)),
// new Item("google_plus", w.getStringFromId("info_berict_detail_google_plus", a)),
// new Item("youtube", w.getStringFromId("info_berict_detail_youtube", a)),
// new Item("discord", w.getStringFromId("info_berict_detail_discord", a)),
// new Item("web", w.getStringFromId("info_berict_detail_web", a))
// Item devSupport[] = {
// new Item("info_berict_action_report_bug", w.getStringFromId("info_berict_action_report_bug_hint", a), "report_bug", true),
// new Item("info_berict_action_rate", w.getStringFromId("info_berict_action_rate_hint", a), "rate", true),
// new Item("info_berict_action_translate", w.getStringFromId("info_berict_action_translate_hint", a), "translate", false),
// new Item("info_berict_action_donate", w.getStringFromId("info_berict_action_donate_hint", a), "donate", false)
// Detail berictDetails[] = {
// new Detail(w.getStringFromId("info_berict_detail_title", a), devItems),
// new Detail(w.getStringFromId("info_berict_action_title", a), devSupport)
// About berictAbout = new About(
// w.getStringFromId("info_berict_title", a),
// "about_image_berict",
// "#607D8B",
// berictBio, berictDetails
// largeLog("berictAboutJSON", gson.toJson(berictAbout));
}
}
|
package innovimax.mixthem.test001;
import innovimax.mixthem.MixThem;
import innovimax.mixthem.Constants;
import innovimax.mixthem.MixException;
import java.io.*;
import java.net.URL;
import org.junit.Assert;
import org.junit.Test;
public class GenericTest {
@Test
public final void check1() throws MixException, FileNotFoundException, IOException {
URL url1 = getClass().getResource("file1.txt");
URL url2 = getClass().getResource("file2.txt");
File file1 = new File(url1.getFile());
File file2 = new File(url2.getFile());
ByteArrayOutputStream baos_rule_1 = new ByteArrayOutputStream();
MixThem.processFiles(Constants.RULE_1, file1, file2, baos_rule_1);
Assert.assertTrue(checkFileEquals(file1, baos_rule_1.toByteArray()));
ByteArrayOutputStream baos_rule_2 = new ByteArrayOutputStream();
MixThem.processFiles(Constants.RULE_2, file1, file2, baos_rule_2);
Assert.assertTrue(checkFileEquals(file2, baos_rule_2.toByteArray()));
}
private static boolean checkFileEquals(File fileExpected, byte[] result) throws FileNotFoundException, IOException {
FileInputStream fisExpected = new FileInputStream(fileExpected);
int c;
int offset = 0;
while ((c = fisExpected.read()) != -1) {
if (offset >= result.length) return false;
int d = result[offset++];
if (c != d) return false;
}
if (offset > result.length) return false;
return true;
}
}
|
/*
* $Id: TestVoteBlockTallier.java,v 1.4 2012-06-25 23:30:10 barry409 Exp $
*/
package org.lockss.poller.v3;
import org.lockss.protocol.VoteBlock;
import org.lockss.test.*;
public class TestVoteBlockTallier extends LockssTestCase {
private ParticipantUserData[] testPeers;
public void setUp() throws Exception {
super.setUp();
setupPeers();
}
private void setupPeers() {
testPeers = new ParticipantUserData[10];
// todo(bhayes): None of the tests at present actually care about
// the actual ParticipantUserData.
}
public void testConstructPollTally() {
BlockTally tally = new BlockTally();
assertEquals(BlockTally.Result.NOQUORUM, tally.getTallyResult(5, 75));
}
public void testVoteWithBlockTallyPollerHas() {
VoteBlockTallier voteBlockTallier;
BlockTally tally;
VoteBlockTallier.HashBlockComparer comparer =
new VoteBlockTallier.HashBlockComparer() {
public boolean compare(VoteBlock voteBlock, int participantIndex) {
return participantIndex == 0;
}
};
voteBlockTallier = new VoteBlockTallier(comparer);
tally = new BlockTally();
voteBlockTallier.addTally(tally);
voteBlockTallier.voteSpoiled(testPeers[0]);
assertEquals("0/0/0/0", tally.votes());
voteBlockTallier = new VoteBlockTallier(comparer);
tally = new BlockTally();
voteBlockTallier.addTally(tally);
voteBlockTallier.voteMissing(testPeers[0]);
assertEquals("0/1/1/0", tally.votes());
voteBlockTallier = new VoteBlockTallier(comparer);
tally = new BlockTally();
voteBlockTallier.addTally(tally);
voteBlockTallier.vote(null, testPeers[0], 0);
assertEquals("1/0/0/0", tally.votes());
}
public void testVoteWithBlockTallyPollerDoesntHave() {
VoteBlockTallier voteBlockTallier;
BlockTally tally;
VoteBlockTallier.HashBlockComparer comparer =
new VoteBlockTallier.HashBlockComparer() {
public boolean compare(VoteBlock voteBlock, int participantIndex) {
return participantIndex == 0;
}
};
voteBlockTallier = new VoteBlockTallier();
tally = new BlockTally();
voteBlockTallier.addTally(tally);
voteBlockTallier.voteSpoiled(testPeers[0]);
assertEquals("0/0/0/0", tally.votes());
voteBlockTallier = new VoteBlockTallier();
tally = new BlockTally();
voteBlockTallier.addTally(tally);
voteBlockTallier.voteMissing(testPeers[0]);
assertEquals("1/0/0/0", tally.votes());
voteBlockTallier = new VoteBlockTallier();
tally = new BlockTally();
voteBlockTallier.addTally(tally);
voteBlockTallier.vote(null, testPeers[0], 0);
assertEquals("0/1/0/1", tally.votes());
}
public void testVoteWithParticipantUserData() {
ParticipantUserData voter;
VoteBlockTallier voteBlockTallier;
VoteBlockTallier.VoteBlockTally tally;
VoteBlockTallier.HashBlockComparer comparer =
new VoteBlockTallier.HashBlockComparer() {
public boolean compare(VoteBlock voteBlock, int participantIndex) {
return participantIndex == 0;
}
};
voteBlockTallier = new VoteBlockTallier(comparer);
voter = new ParticipantUserData();
tally = ParticipantUserData.voteTally;
voteBlockTallier.addTally(tally);
voteBlockTallier.vote(null, voter, 0);
assertEquals("1/0/0/0/0/0", voter.getVoteCounts().votes());
voteBlockTallier = new VoteBlockTallier(comparer);
voter = new ParticipantUserData();
tally = ParticipantUserData.voteTally;
voteBlockTallier.addTally(tally);
voteBlockTallier.vote(null, voter, 1);
assertEquals("0/1/0/0/0/0", voter.getVoteCounts().votes());
voteBlockTallier = new VoteBlockTallier(comparer);
voter = new ParticipantUserData();
tally = ParticipantUserData.voteTally;
voteBlockTallier.addTally(tally);
voteBlockTallier.voteMissing(voter);
assertEquals("0/0/1/0/0/0", voter.getVoteCounts().votes());
voteBlockTallier = new VoteBlockTallier();
voter = new ParticipantUserData();
tally = ParticipantUserData.voteTally;
voteBlockTallier.addTally(tally);
voteBlockTallier.vote(null, voter, 0);
assertEquals("0/0/0/1/0/0", voter.getVoteCounts().votes());
voteBlockTallier = new VoteBlockTallier(comparer);
voter = new ParticipantUserData();
tally = ParticipantUserData.voteTally;
voteBlockTallier.addTally(tally);
voteBlockTallier.voteSpoiled(voter);
assertEquals("0/0/0/0/0/1", voter.getVoteCounts().votes());
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.