answer
stringlengths 17
10.2M
|
|---|
package com.exedio.copernica;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.fileupload.FileItem;
import com.exedio.cope.lib.Attribute;
import com.exedio.cope.lib.BooleanAttribute;
import com.exedio.cope.lib.ConstraintViolationException;
import com.exedio.cope.lib.DateAttribute;
import com.exedio.cope.lib.DoubleAttribute;
import com.exedio.cope.lib.EnumAttribute;
import com.exedio.cope.lib.EnumValue;
import com.exedio.cope.lib.IntegerAttribute;
import com.exedio.cope.lib.Item;
import com.exedio.cope.lib.ItemAttribute;
import com.exedio.cope.lib.LongAttribute;
import com.exedio.cope.lib.MediaAttribute;
import com.exedio.cope.lib.Model;
import com.exedio.cope.lib.NestingRuntimeException;
import com.exedio.cope.lib.NoSuchIDException;
import com.exedio.cope.lib.NotNullViolationException;
import com.exedio.cope.lib.ObjectAttribute;
import com.exedio.cope.lib.StringAttribute;
import com.exedio.cope.lib.Type;
import com.exedio.cope.lib.pattern.Qualifier;
import com.exedio.cope.lib.search.EqualCondition;
import com.exedio.cops.CheckboxField;
import com.exedio.cops.DateField;
import com.exedio.cops.DoubleField;
import com.exedio.cops.Field;
import com.exedio.cops.Form;
import com.exedio.cops.IntegerField;
import com.exedio.cops.LongField;
import com.exedio.cops.RadioField;
import com.exedio.cops.StringField;
import com.exedio.cops.TextField;
final class ItemForm extends Form
{
static final String SAVE_BUTTON = "SAVE";
static final String CHECK_BUTTON = "CHECK";
static final String SECTION = "section";
final Item item;
final Type type;
/*TODO final*/ boolean hasFiles;
boolean toSave = false;
final CopernicaSection currentSection;
ItemForm(final ItemCop cop, final HttpServletRequest request)
{
super(request);
this.item = cop.item;
this.type = item.getType();
final CopernicaProvider provider = cop.provider;
final Model model = provider.getModel();
final List displayedAttributes;
final List hiddenAttributes;
final Collection sections = provider.getSections(type);
boolean sectionButton = false;
if(sections!=null)
{
{
CopernicaSection buttonSection = null;
CopernicaSection previousSection = null;
CopernicaSection firstSection = null;
final String previousSectionParam = getParameter(SECTION);
for(Iterator i = sections.iterator(); i.hasNext(); )
{
final CopernicaSection section = (CopernicaSection)i.next();
if(firstSection==null)
firstSection = section;
final String id = section.getCopernicaID();
if(getParameter(id)!=null)
{
buttonSection = section;
sectionButton = true;
break;
}
if(id.equals(previousSectionParam))
previousSection = section;
}
if(buttonSection!=null)
currentSection = buttonSection;
else if(previousSection!=null)
currentSection = previousSection;
else
currentSection = firstSection;
}
displayedAttributes = new ArrayList(provider.getMainAttributes(type));
hiddenAttributes = new ArrayList();
for(Iterator i = sections.iterator(); i.hasNext(); )
{
final CopernicaSection section = (CopernicaSection)i.next();
new Section(section.getCopernicaID(), section.getCopernicaName(cop.language));
final Collection sectionAttributes = section.getCopernicaAttributes();
if(section.equals(currentSection))
displayedAttributes.addAll(sectionAttributes);
else
hiddenAttributes.addAll(sectionAttributes);
}
}
else
{
currentSection = null;
displayedAttributes = type.getAttributes();
hiddenAttributes = Collections.EMPTY_LIST;
}
final ArrayList attributes = new ArrayList(displayedAttributes.size()+hiddenAttributes.size());
attributes.addAll(displayedAttributes);
attributes.addAll(hiddenAttributes);
final boolean save = getParameter(SAVE_BUTTON)!=null;
final boolean post = save || sectionButton || getParameter(CHECK_BUTTON)!=null;
boolean hasFilesTemp = false;
for(Iterator j = attributes.iterator(); j.hasNext(); )
{
final Attribute anyAttribute = (Attribute)j.next();
final Field field;
if(anyAttribute instanceof ObjectAttribute)
{
field = createField((ObjectAttribute)anyAttribute, post, cop, hiddenAttributes.contains(anyAttribute), model);
}
else if(anyAttribute instanceof MediaAttribute)
{
final MediaAttribute attribute = (MediaAttribute)anyAttribute;
field = new Field(this, attribute, null, true, "", hiddenAttributes.contains(attribute));
if(!attribute.isReadOnly())
{
toSave = true;
hasFilesTemp = true;
}
}
else
continue;
if(!field.isReadOnly())
toSave = true;
}
this.hasFiles = hasFilesTemp;
for(Iterator j = type.getQualifiers().iterator(); j.hasNext(); )
{
final Qualifier qualifier = (Qualifier)j.next();
final Collection values = qualifier.getQualifyUnique().getType().search(new EqualCondition(qualifier.getParent(), item));
for(Iterator k = qualifier.getAttributes().iterator(); k.hasNext(); )
{
final Attribute anyAttribute = (Attribute)k.next();
for(Iterator l = values.iterator(); l.hasNext(); )
{
final Item value = (Item)l.next();
if(anyAttribute instanceof ObjectAttribute)
{
final ObjectAttribute attribute = (ObjectAttribute)anyAttribute;
final Object qualifiedValue = value.getAttribute(attribute);
if(qualifiedValue!=null)
createField(attribute, value, value.getID()+'.'+attribute.getName(), true, false, cop, false, model);
}
}
}
}
if(save)
{
save();
}
}
private final Field createField(
final ObjectAttribute attribute,
final boolean post, final ItemCop cop, final boolean hidden, final Model model)
{
return createField(attribute, this.item, attribute.getName(), attribute.isReadOnly(), post, cop, hidden, model);
}
private final Field createField(
final ObjectAttribute attribute, final Item item, final String name, final boolean readOnly,
final boolean post, final ItemCop cop, final boolean hidden, final Model model)
{
if(attribute instanceof EnumAttribute)
{
if(post)
return new EnumField((EnumAttribute)attribute, hidden, cop);
else
return new EnumField((EnumAttribute)attribute, (EnumValue)item.getAttribute(attribute), hidden, cop);
}
else if(attribute instanceof BooleanAttribute)
{
if(attribute.isNotNull())
{
if(post)
return new CheckboxField(this, attribute, name, readOnly, hidden);
else
return new CheckboxField(this, attribute, name, readOnly, ((Boolean)item.getAttribute(attribute)).booleanValue(), hidden);
}
else
{
if(post)
return new BooleanEnumField((BooleanAttribute)attribute, hidden, cop);
else
return new BooleanEnumField((BooleanAttribute)attribute, (Boolean)item.getAttribute(attribute), hidden, cop);
}
}
else if(attribute instanceof IntegerAttribute)
{
if(post)
return new IntegerField(this, attribute, name, readOnly, hidden);
else
return new IntegerField(this, attribute, name, readOnly, (Integer)item.getAttribute(attribute), hidden);
}
else if(attribute instanceof LongAttribute)
{
if(post)
return new LongField(this, attribute, name, readOnly, hidden);
else
return new LongField(this, attribute, name, readOnly, (Long)item.getAttribute(attribute), hidden);
}
else if(attribute instanceof DoubleAttribute)
{
if(post)
return new DoubleField(this, attribute, name, readOnly, hidden);
else
return new DoubleField(this, attribute, name, readOnly, (Double)item.getAttribute(attribute), hidden);
}
else if(attribute instanceof DateAttribute)
{
if(post)
return new DateField(this, attribute, name, readOnly, hidden);
else
return new DateField(this, attribute, name, readOnly, (Date)item.getAttribute(attribute), hidden);
}
else if(attribute instanceof StringAttribute)
{
if(post)
return new StringField(this, attribute, name, readOnly, hidden);
else
return new StringField(this, attribute, name, readOnly, (String)item.getAttribute(attribute), hidden);
}
else if(attribute instanceof ItemAttribute)
{
if(post)
return new ItemField(attribute, name, readOnly, hidden, model, cop);
else
return new ItemField(attribute, name, readOnly, (Item)item.getAttribute(attribute), hidden, model, cop);
}
else
{
throw new RuntimeException(attribute.getClass().toString());
}
}
public class ItemField extends TextField
{
final Model model;
final ItemCop cop;
final Item content;
/**
* Constructs a form field with an initial value.
*/
public ItemField(final Object key, final String name, final boolean readOnly, final Item value, final boolean hidden, final Model model, final ItemCop cop)
{
super(ItemForm.this, key, name, readOnly, (value==null) ? "" : value.getID(), hidden);
this.model = model;
this.cop = cop;
this.content = value;
}
/**
* Constructs a form field with a value obtained from the submitted form.
*/
public ItemField(final Object key, final String name, final boolean readOnly, final boolean hidden, final Model model, final ItemCop cop)
{
super(ItemForm.this, key, name, readOnly, hidden);
this.model = model;
this.cop = cop;
final String value = this.value;
if(value.length()>0)
{
Item parsed = null;
try
{
parsed = model.findByID(value);
}
catch(NoSuchIDException e)
{
error = e.getMessage();
}
content = error==null ? parsed : null;
}
else
content = null;
}
public void write(final PrintStream out) throws IOException
{
super.write(out);
ItemCop_Jspm.write(out, this);
}
public Object getContent()
{
return content;
}
}
final class EnumField extends RadioField
{
private static final String VALUE_NULL = "null";
final EnumAttribute attribute;
final EnumValue content;
/**
* Constructs a form field with an initial value.
*/
EnumField(final EnumAttribute attribute, final EnumValue value, final boolean hidden, final ItemCop cop)
{
super(ItemForm.this, attribute, attribute.getName(), attribute.isReadOnly(), (value==null) ? VALUE_NULL : value.getCode(), hidden);
this.attribute = attribute;
this.content = value;
addOptions(cop);
}
/**
* Constructs a form field with a value obtained from the submitted form.
*/
EnumField(final EnumAttribute attribute, final boolean hidden, final ItemCop cop)
{
super(ItemForm.this, attribute, attribute.getName(), attribute.isReadOnly(), hidden);
this.attribute = attribute;
addOptions(cop);
final String value = this.value;
if(VALUE_NULL.equals(value))
content = null;
else
{
content = attribute.getValue(value);
if(content==null)
throw new RuntimeException(value);
}
}
private void addOptions(final ItemCop cop)
{
if(!attribute.isNotNull())
{
addOption(VALUE_NULL, cop.getDisplayNameNull());
}
for(Iterator k = attribute.getValues().iterator(); k.hasNext(); )
{
final EnumValue currentValue = (EnumValue)k.next();
final String currentCode = currentValue.getCode();
final String currentName = cop.getDisplayName(currentValue);
addOption(currentCode, currentName);
}
}
public Object getContent()
{
return content;
}
}
final class BooleanEnumField extends RadioField
{
private static final String VALUE_NULL = "null";
private static final String VALUE_ON = "on";
private static final String VALUE_OFF = "off";
final Boolean content;
/**
* Constructs a form field with an initial value.
*/
BooleanEnumField(final BooleanAttribute attribute, final Boolean value, final boolean hidden, final ItemCop cop)
{
super(ItemForm.this, attribute, attribute.getName(), attribute.isReadOnly(), value==null ? VALUE_NULL : value.booleanValue() ? VALUE_ON : VALUE_OFF, hidden);
this.content = value;
addOptions(cop);
}
/**
* Constructs a form field with a value obtained from the submitted form.
*/
BooleanEnumField(final BooleanAttribute attribute, final boolean hidden, final ItemCop cop)
{
super(ItemForm.this, attribute, attribute.getName(), attribute.isReadOnly(), hidden);
addOptions(cop);
final String value = this.value;
if(VALUE_NULL.equals(value))
content = null;
else if(VALUE_ON.equals(value))
content = Boolean.TRUE;
else if(VALUE_OFF.equals(value))
content = Boolean.FALSE;
else
throw new RuntimeException(value);
}
private final void addOptions(final ItemCop cop)
{
addOption(VALUE_NULL, cop.getDisplayNameNull());
addOption(VALUE_ON, cop.getDisplayNameOn());
addOption(VALUE_OFF, cop.getDisplayNameOff());
}
public Object getContent()
{
return content;
}
}
private void save()
{
for(Iterator i = getAllFields().iterator(); i.hasNext(); )
{
final Field field = (Field)i.next();
if(field.key instanceof MediaAttribute)
{
final MediaAttribute attribute = (MediaAttribute)field.key;
final FileItem fileItem = getParameterFile(attribute.getName());
if(fileItem!=null)
{
final String contentType = fileItem.getContentType();
if(contentType!=null)
{
final int pos = contentType.indexOf('/');
if(pos<=0)
throw new RuntimeException("invalid content type "+contentType);
final String mimeMajor = contentType.substring(0, pos);
String mimeMinor = contentType.substring(pos+1);
// fix for MSIE behaviour
if("image".equals(mimeMajor) && "pjpeg".equals(mimeMinor))
mimeMinor = "jpeg";
try
{
final InputStream data = fileItem.getInputStream();
item.setMediaData(attribute, data, mimeMajor, mimeMinor);
}
catch(IOException e)
{
throw new NestingRuntimeException(e);
}
catch(NotNullViolationException e)
{
throw new NestingRuntimeException(e);
}
}
}
}
if(!field.isReadOnly())
{
if(field.error==null)
{
try
{
final ObjectAttribute attribute = (ObjectAttribute)field.key;
item.setAttribute(attribute, field.getContent());
}
catch(NotNullViolationException e)
{
field.error = "error.notnull:"+e.getNotNullAttribute().toString();
}
catch(ConstraintViolationException e)
{
field.error = e.getClass().getName();
}
}
}
}
}
}
|
package hudson.scm;
import hudson.FilePath;
import hudson.Launcher;
import hudson.Proc;
import hudson.Util;
import hudson.model.Build;
import hudson.model.BuildListener;
import hudson.model.Descriptor;
import hudson.model.Project;
import hudson.model.TaskListener;
import hudson.util.ArgumentListBuilder;
import hudson.util.FormFieldValidator;
import org.apache.commons.digester.Digester;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
import org.xml.sax.SAXException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.StringTokenizer;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class SubversionSCM extends AbstractCVSFamilySCM {
private final String modules;
private boolean useUpdate;
private String username;
private String otherOptions;
SubversionSCM( String modules, boolean useUpdate, String username, String otherOptions ) {
StringBuilder normalizedModules = new StringBuilder();
StringTokenizer tokens = new StringTokenizer(modules);
while(tokens.hasMoreTokens()) {
if(normalizedModules.length()>0) normalizedModules.append(' ');
String m = tokens.nextToken();
if(m.endsWith("/"))
// the normalized name is always without the trailing '/'
m = m.substring(0,m.length()-1);
normalizedModules.append(m);
}
this.modules = normalizedModules.toString();
this.useUpdate = useUpdate;
this.username = nullify(username);
this.otherOptions = nullify(otherOptions);
}
/**
* Whitespace-separated list of SVN URLs that represent
* modules to be checked out.
*/
public String getModules() {
return modules;
}
public boolean isUseUpdate() {
return useUpdate;
}
public String getUsername() {
return username;
}
public String getOtherOptions() {
return otherOptions;
}
private Collection<String> getModuleDirNames() {
List<String> dirs = new ArrayList<String>();
StringTokenizer tokens = new StringTokenizer(modules);
while(tokens.hasMoreTokens()) {
dirs.add(getLastPathComponent(tokens.nextToken()));
}
return dirs;
}
private boolean calcChangeLog(Build build, File changelogFile, Launcher launcher, BuildListener listener) throws IOException {
if(build.getPreviousBuild()==null) {
// nothing to compare against
return createEmptyChangeLog(changelogFile, listener, "log");
}
PrintStream logger = listener.getLogger();
Map<String,Integer> previousRevisions = parseRevisionFile(build.getPreviousBuild());
Map<String,Integer> thisRevisions = parseRevisionFile(build);
Map env = createEnvVarMap(true);
for( String module : getModuleDirNames() ) {
Integer prevRev = previousRevisions.get(module);
if(prevRev==null) {
logger.println("no revision recorded for "+module+" in the previous build");
continue;
}
Integer thisRev = thisRevisions.get(module);
if(thisRev!=null && thisRev.equals(prevRev)) {
logger.println("no change for "+module+" since the previous build");
continue;
}
String cmd = DESCRIPTOR.getSvnExe()+" log -v --xml --non-interactive -r "+(prevRev+1)+":BASE "+module;
OutputStream os = new BufferedOutputStream(new FileOutputStream(changelogFile));
try {
int r = launcher.launch(cmd,env,os,build.getProject().getWorkspace()).join();
if(r!=0) {
listener.fatalError("revision check failed");
// report the output
FileInputStream log = new FileInputStream(changelogFile);
try {
Util.copyStream(log,listener.getLogger());
} finally {
log.close();
}
return false;
}
} finally {
os.close();
}
}
return true;
}
/*package*/ static Map<String,Integer> parseRevisionFile(Build build) throws IOException {
Map<String,Integer> revisions = new HashMap<String,Integer>(); // module -> revision
{// read the revision file of the last build
File file = getRevisionFile(build);
if(!file.exists())
// nothing to compare against
return revisions;
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while((line=br.readLine())!=null) {
int index = line.indexOf('/');
if(index<0) {
continue; // invalid line?
}
try {
revisions.put(line.substring(0,index), Integer.parseInt(line.substring(index+1)));
} catch (NumberFormatException e) {
// perhaps a corrupted line. ignore
}
}
}
return revisions;
}
public boolean checkout(Build build, Launcher launcher, FilePath workspace, BuildListener listener, File changelogFile) throws IOException {
boolean result;
if(useUpdate && isUpdatable(workspace,listener)) {
result = update(launcher,workspace,listener);
if(!result)
return false;
} else {
workspace.deleteContents();
StringTokenizer tokens = new StringTokenizer(modules);
while(tokens.hasMoreTokens()) {
ArgumentListBuilder cmd = new ArgumentListBuilder();
cmd.add(DESCRIPTOR.getSvnExe(),"co","-q","--non-interactive");
if(username!=null)
cmd.add("--username",username);
if(otherOptions!=null)
cmd.add(Util.tokenize(otherOptions));
cmd.add(tokens.nextToken());
result = run(launcher,cmd,listener,workspace);
if(!result)
return false;
}
}
// write out the revision file
PrintWriter w = new PrintWriter(new FileOutputStream(getRevisionFile(build)));
try {
Map<String,SvnInfo> revMap = buildRevisionMap(workspace,listener);
for (Entry<String,SvnInfo> e : revMap.entrySet()) {
w.println( e.getKey() +'/'+ e.getValue().revision );
}
} finally {
w.close();
}
return calcChangeLog(build, changelogFile, launcher, listener);
}
/**
* Output from "svn info" command.
*/
public static class SvnInfo {
/** The remote URL of this directory */
String url;
/** Current workspace revision. */
int revision = -1;
private SvnInfo() {}
/**
* Returns true if this object is fully populated.
*/
public boolean isComplete() {
return url!=null && revision!=-1;
}
public void setUrl(String url) {
this.url = url;
}
public void setRevision(int revision) {
this.revision = revision;
}
/**
* Executes "svn info" command and returns the parsed output
*
* @param subject
* The target to run "svn info". Either local path or remote URL.
*/
public static SvnInfo parse(String subject, Map env, FilePath workspace, TaskListener listener) throws IOException {
String cmd = DESCRIPTOR.getSvnExe()+" info --xml "+subject;
listener.getLogger().println("$ "+cmd);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int r = new Proc(cmd,env,baos,workspace.getLocal()).join();
if(r!=0) {
// failed. to allow user to diagnose the problem, send output to log
listener.getLogger().write(baos.toByteArray());
throw new IOException("svn info failed");
}
SvnInfo info = new SvnInfo();
Digester digester = new Digester();
digester.push(info);
digester.addBeanPropertySetter("info/entry/url");
digester.addSetProperties("info/entry/commit","revision","revision"); // set attributes. in particular @revision
try {
digester.parse(new ByteArrayInputStream(baos.toByteArray()));
} catch (SAXException e) {
// failed. to allow user to diagnose the problem, send output to log
listener.getLogger().write(baos.toByteArray());
e.printStackTrace(listener.fatalError("Failed to parse Subversion output"));
throw new IOException("Unabled to parse svn info output");
}
if(!info.isComplete())
throw new IOException("No revision in the svn info output");
return info;
}
}
/**
* Checks .svn files in the workspace and finds out revisions of the modules
* that the workspace has.
*
* @return
* null if the parsing somehow fails. Otherwise a map from module names to revisions.
*/
private Map<String,SvnInfo> buildRevisionMap(FilePath workspace, TaskListener listener) throws IOException {
PrintStream logger = listener.getLogger();
Map<String/*module name*/,SvnInfo> revisions = new HashMap<String,SvnInfo>();
Map env = createEnvVarMap(false);
// invoke the "svn info"
for( String module : getModuleDirNames() ) {
// parse the output
SvnInfo info = SvnInfo.parse(module,env,workspace,listener);
revisions.put(module,info);
logger.println("Revision:"+info.revision);
}
return revisions;
}
/**
* Gets the file that stores the revision.
*/
private static File getRevisionFile(Build build) {
return new File(build.getRootDir(),"revision.txt");
}
public boolean update(Launcher launcher, FilePath remoteDir, BuildListener listener) throws IOException {
ArgumentListBuilder cmd = new ArgumentListBuilder();
cmd.add(DESCRIPTOR.getSvnExe(), "update", "-q", "--non-interactive");
if(username!=null)
cmd.add(" --username ",username);
if(otherOptions!=null)
cmd.add(Util.tokenize(otherOptions));
StringTokenizer tokens = new StringTokenizer(modules);
while(tokens.hasMoreTokens()) {
if(!run(launcher,cmd,listener,new FilePath(remoteDir,getLastPathComponent(tokens.nextToken()))))
return false;
}
return true;
}
/**
* Returns true if we can use "svn update" instead of "svn checkout"
*/
private boolean isUpdatable(FilePath workspace,BuildListener listener) {
StringTokenizer tokens = new StringTokenizer(modules);
while(tokens.hasMoreTokens()) {
String url = tokens.nextToken();
String moduleName = getLastPathComponent(url);
File module = workspace.child(moduleName).getLocal();
try {
SvnInfo svnInfo = SvnInfo.parse(moduleName, createEnvVarMap(false), workspace, listener);
if(!svnInfo.url.equals(url)) {
listener.getLogger().println("Checking out a fresh workspace because the workspace is not "+url);
return false;
}
} catch (IOException e) {
listener.getLogger().println("Checking out a fresh workspace because Hudson failed to detect the current workspace "+module);
e.printStackTrace(listener.error(e.getMessage()));
return false;
}
}
return true;
}
public boolean pollChanges(Project project, Launcher launcher, FilePath workspace, TaskListener listener) throws IOException {
// current workspace revision
Map<String,SvnInfo> wsRev = buildRevisionMap(workspace,listener);
Map env = createEnvVarMap(false);
// check the corresponding remote revision
for (SvnInfo localInfo : wsRev.values()) {
SvnInfo remoteInfo = SvnInfo.parse(localInfo.url,env,workspace,listener);
listener.getLogger().println("Revision:"+remoteInfo.revision);
if(remoteInfo.revision > localInfo.revision)
return true; // change found
}
return false; // no change
}
public ChangeLogParser createChangeLogParser() {
return new SubversionChangeLogParser();
}
public DescriptorImpl getDescriptor() {
return DESCRIPTOR;
}
public void buildEnvVars(Map env) {
// no environment variable
}
public FilePath getModuleRoot(FilePath workspace) {
String s;
// if multiple URLs are specified, pick the first one
int idx = modules.indexOf(' ');
if(idx>=0) s = modules.substring(0,idx);
else s = modules;
return workspace.child(getLastPathComponent(s));
}
private String getLastPathComponent(String s) {
String[] tokens = s.split("/");
return tokens[tokens.length-1]; // return the last token
}
static final DescriptorImpl DESCRIPTOR = new DescriptorImpl();
public static final class DescriptorImpl extends Descriptor<SCM> {
/**
* Path to <tt>svn.exe</tt>. Null to default.
*/
private String svnExe;
DescriptorImpl() {
super(SubversionSCM.class);
}
protected void convert(Map<String, Object> oldPropertyBag) {
svnExe = (String)oldPropertyBag.get("svn_exe");
}
public String getDisplayName() {
return "Subversion";
}
public SCM newInstance(StaplerRequest req) {
return new SubversionSCM(
req.getParameter("svn_modules"),
req.getParameter("svn_use_update")!=null,
req.getParameter("svn_username"),
req.getParameter("svn_other_options")
);
}
public String getSvnExe() {
String value = svnExe;
if(value==null)
value = "svn";
return value;
}
public void setSvnExe(String value) {
svnExe = value;
save();
}
public boolean configure( HttpServletRequest req ) {
svnExe = req.getParameter("svn_exe");
return true;
}
/**
* Returns the Subversion version information.
*
* @return
* null if failed to obtain.
*/
public Version version(Launcher l, String svnExe) {
try {
if(svnExe==null || svnExe.equals("")) svnExe="svn";
ByteArrayOutputStream out = new ByteArrayOutputStream();
l.launch(new String[]{svnExe,"--version"},new String[0],out,FilePath.RANDOM).join();
// parse the first line for version
BufferedReader r = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(out.toByteArray())));
String line;
while((line = r.readLine())!=null) {
Matcher m = SVN_VERSION.matcher(line);
if(m.matches())
return new Version(Integer.parseInt(m.group(2)), m.group(1));
}
// ancient version of subversions didn't have the fixed version number line.
// or maybe something else is going wrong.
LOGGER.log(Level.WARNING, "Failed to parse the first line from svn output: "+line);
return new Version(0,"(unknown)");
} catch (IOException e) {
// Stack trace likely to be overkill for a problem that isn't necessarily a problem at all:
LOGGER.log(Level.WARNING, "Failed to check svn version: {0}", e.toString());
return null; // failed to obtain
}
}
// web methods
public void doVersionCheck(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
// this method runs a new process, so it needs to be protected
new FormFieldValidator(req,rsp,true) {
protected void check() throws IOException, ServletException {
String svnExe = request.getParameter("exe");
Version v = version(new Launcher(TaskListener.NULL),svnExe);
if(v==null) {
error("Failed to check subversion version info. Is this a valid path?");
return;
}
if(v.isOK()) {
ok();
} else {
error("Version "+v.versionId+" found, but 1.3.0 is required");
}
}
}.process();
}
}
public static final class Version {
private final int revision;
private String versionId;
public Version(int revision, String versionId) {
this.revision = revision;
this.versionId = versionId;
}
/**
* Repository revision ID of this build.
*/
public int getRevision() {
return revision;
}
/**
* Human-readable version string.
*/
public String getVersionId() {
return versionId;
}
/**
* We use "svn info --xml", which is new in 1.3.0
*/
public boolean isOK() {
return revision>=17949;
}
}
private static final Pattern SVN_VERSION = Pattern.compile("svn, .+ ([0-9.]+) \\(r([0-9]+)\\)");
private static final Logger LOGGER = Logger.getLogger(SubversionSCM.class.getName());
}
|
package org.funcj.util;
/**
* Interfaces for composable functions.
*/
public abstract class Functions {
/**
* Function of arity 0.
* @param <R> return type
*/
@FunctionalInterface
public interface F0<R> {
static <R> F0<R> of(F0<R> f) {
return f;
}
/**
* Return a zero-argument constant function that always returns the same value.
* @param r the value the function always returns
* @param <R> the value type
* @return a zero-argument constant function that always returns the same value
*/
static <R> F0<R> konst(R r) {
return () -> r;
}
/**
* Apply this function
* @return the result of applying this function
*/
R apply();
}
/**
* Function of arity 1.
* Note: if the input type to {@code F} fixed to type T then the result is a monad,
* where pure = {@code konst} and bind = {@code flatMap}.
* @param <A> 1st argument type
* @param <R> return type
*/
@FunctionalInterface
public interface F<A, R> {
static <A, R> F<A, R> of(F<A, R> f) {
return f;
}
/**
* The identity function, that simply returns its argument.
* @param <A> input and output type of function
* @return the identity function
*/
static <A> F<A, A> id() {
return x -> x;
}
/**
* The constant function, that always returns the same value, regardless of its argument
* @param r the value the constant function will return
* @param <A> the input type of the function
* @param <R> the type of the constant value {@code r}
* @return the constant function
*/
static <A, R> F<A, R> konst(R r) {
return a -> r;
}
/**
* Translate a curried function by inverting the order of its arguments
* @param f the function to be flipped
* @param <A> the function's first argument type
* @param <B> the function's second argument type
* @param <R> the function's return type
* @return the flipped function
*/
static <A, B, R> F<B, F<A, R>> flip(F<A, F<B, R>> f) {
return b -> a -> f.apply(a).apply(b);
}
/**
* Apply this function
* @param a the function argument
* @return the result of applying this function
*/
R apply(A a);
/**
* Compose this function with another,
* to create a function that first applies {@code f}
* and then applies this function to the result.
* @param f the function to compose with
* @param <T> the argument type to {@code f}
* @return a function that first applies {@code f} and then applies this function to the result.
*/
default <T> F<T, R> compose(F<? super T, ? extends A> f) {
return t -> this.apply(f.apply(t));
}
/**
* Compose this function with another,
* to create a function that first applies this function
* and then applies {@code f} to the result.
* @param f the function to compose with
* @param <T> the argument type to {@code f}
* @return a function that first applies this function and then applies {@code f} to the result.
*/
default <T> F<A, T> andThen(F<? super R, ? extends T> f) {
return t -> f.apply(this.apply(t));
}
/**
* Variant of {@link F#compose(F)} that lacks the wildcard generic types.
* @param f the function to compose with
* @param <T> the argument type to {@code f}
* @return a function that first applies {@code f} and then applies this function to the result.
*/
default <T> F<A, T> map(F<R, T> f) {
return f.compose(this);
}
default <B> F<A, B> app(F<A, F<R, B>> f) {
return s -> f.apply(s).apply(apply(s));
}
default <U> F<A, U> flatMap(F<R, F<A, U>> f) {
return s -> f.apply(apply(s)).apply(s);
}
}
/**
* Function of arity 2.
* @param <A> 1st argument type
* @param <B> 2nd argument type
* @param <R> return type
*/
@FunctionalInterface
public interface F2<A, B, R> {
static <A, B, R> F2<A, B, R> of(F2<A, B, R> f) {
return f;
}
static <A, B, R> F<A, F<B, R>> curry(F2<A, B, R> f) {
return f.curry();
}
static <A, B, R> F2<A, B, R> uncurry(F<A, F<B, R>> f) {
return (a, b) -> f.apply(a).apply(b);
}
static <A, B> F2<A, B, A> first() {
return (a, b) -> a;
}
static <A, B> F2<A, B, B> second() {
return (a, b) -> b;
}
R apply(A a, B b);
default F<B, R> partial(A a) {
return b -> apply(a, b);
}
default F<A, F<B, R>> curry() {
return a -> b -> apply(a, b);
}
default F2<B, A, R> flip() {
return (b, a) -> apply(a, b);
}
}
/**
* Function of arity 3.
* @param <A> 1st argument type
* @param <B> 2nd argument type
* @param <C> 3rd argument type
* @param <R> return type
*/
@FunctionalInterface
public interface F3<A, B, C, R> {
static <A, B, C, R> F3<A, B, C, R> of(F3<A, B, C, R> f) {
return f;
}
static <A, B, C, R> F<A, F<B, F<C, R>>> curry(F3<A, B, C, R> f) {
return f.curry();
}
static <A, B, C, R> F3<A, B, C, R> uncurry(F<A, F<B, F<C, R>>> f) {
return (a, b, c) -> f.apply(a).apply(b).apply(c);
}
R apply(A a, B b, C c);
default F2<B, C, R> partial(A a) {
return (b, c) -> apply(a, b, c);
}
default F<C, R> partial(A a, B b) {
return c -> apply(a, b, c);
}
default F<A, F<B, F<C, R>>> curry() {
return a -> b -> c -> apply(a, b, c);
}
}
/**
* Function of arity 4.
* @param <A> 1st argument type
* @param <B> 2nd argument type
* @param <C> 3rd argument type
* @param <D> 4th argument type
* @param <R> return type
*/
@FunctionalInterface
public interface F4<A, B, C, D, R> {
static <A, B, C, D, R> F4<A, B, C, D, R> of(F4<A, B, C, D, R> f) {
return f;
}
static <A, B, C, D, R> F<A, F<B, F<C, F<D, R>>>> curry(F4<A, B, C, D, R> f) {
return f.curry();
}
static <A, B, C, D, R> F4<A, B, C, D, R> uncurry(F<A, F<B, F<C, F<D, R>>>> f) {
return (a, b, c, d) -> f.apply(a).apply(b).apply(c).apply(d);
}
R apply(A a, B b, C c, D d);
default F3<B, C, D, R> partial(A a) {
return (b, c, d) -> apply(a, b, c, d);
}
default F2<C, D, R> partial(A a, B b) {
return (c, d) -> apply(a, b, c, d);
}
default F<D, R> partial(A a, B b, C c) {
return d -> apply(a, b, c, d);
}
default F<A, F<B, F<C, F<D, R>>>> curry() {
return a -> b -> c -> d -> apply(a, b, c, d);
}
}
/**
* Function of arity 5.
* @param <A> 1st argument type
* @param <B> 2nd argument type
* @param <C> 3rd argument type
* @param <D> 4th argument type
* @param <E> 5th argument type
* @param <R> return type
*/
@FunctionalInterface
public interface F5<A, B, C, D, E, R> {
static <A, B, C, D, E, R> F5<A, B, C, D, E, R> of(F5<A, B, C, D, E, R> f) {
return f;
}
static <A, B, C, D, E, R> F<A, F<B, F<C, F<D, F<E, R>>>>> curry(F5<A, B, C, D, E, R> f) {
return f.curry();
}
static <A, B, C, D, E, R> F5<A, B, C, D, E, R> uncurry(F<A, F<B, F<C, F<D, F<E, R>>>>> f) {
return (a, b, c, d, e) -> f.apply(a).apply(b).apply(c).apply(d).apply(e);
}
R apply(A a, B b, C c, D d, E e);
default F4<B, C, D, E, R> partial(A a) {
return (b, c, d, e) -> apply(a, b, c, d, e);
}
default F3<C, D, E, R> partial(A a, B b) {
return (c, d, e) -> apply(a, b, c, d, e);
}
default F2<D, E, R> partial(A a, B b, C c) {
return (d, e) -> apply(a, b, c, d, e);
}
default F<E, R> partial(A a, B b, C c, D d) {
return e -> apply(a, b, c, d, e);
}
default F<A, F<B, F<C, F<D, F<E, R>>>>> curry() {
return a -> b -> c -> d -> e -> apply(a, b, c, d, e);
}
}
/**
* Function of arity 6.
* @param <A> 1st argument type
* @param <B> 2nd argument type
* @param <C> 3rd argument type
* @param <D> 4th argument type
* @param <E> 5th argument type
* @param <G> 6th argument type
* @param <R> return type
*/
@FunctionalInterface
public interface F6<A, B, C, D, E, G, R> {
static <A, B, C, D, E, G, R> F6<A, B, C, D, E, G, R> of(F6<A, B, C, D, E, G, R> f) {
return f;
}
static <A, B, C, D, E, G, R> F<A, F<B, F<C, F<D, F<E, F<G, R>>>>>> curry(F6<A, B, C, D, E, G, R> f) {
return f.curry();
}
static <A, B, C, D, E, G, R> F6<A, B, C, D, E, G, R> uncurry(F<A, F<B, F<C, F<D, F<E, F<G, R>>>>>> f) {
return (a, b, c, d, e, g) -> f.apply(a).apply(b).apply(c).apply(d).apply(e).apply(g);
}
R apply(A a, B b, C c, D d, E e, G g);
default F5<B, C, D, E, G, R> partial(A a) {
return (b, c, d, e, g) -> apply(a, b, c, d, e, g);
}
default F4<C, D, E, G, R> partial(A a, B b) {
return (c, d, e, g) -> apply(a, b, c, d, e, g);
}
default F3<D, E, G, R> partial(A a, B b, C c) {
return (d, e, g) -> apply(a, b, c, d, e, g);
}
default F2<E, G, R> partial(A a, B b, C c, D d) {
return (e, g) -> apply(a, b, c, d, e, g);
}
default F<G, R> partial(A a, B b, C c, D d, E e) {
return g -> apply(a, b, c, d, e, g);
}
default F<A, F<B, F<C, F<D, F<E, F<G, R>>>>>> curry() {
return a -> b -> c -> d -> e -> g -> apply(a, b, c, d, e, g);
}
}
/**
* Unary operator interface.
* @param <T> operand type
*/
@FunctionalInterface
public interface Op<T> extends F<T, T> {
static <T> Op<T> of(Op<T> op) {
return op;
}
T apply(T t);
}
/**
* Binary operator interface.
* @param <T> operand type
*/
@FunctionalInterface
public interface Op2<T> extends F2<T, T, T> {
static <T> Op2<T> of(Op2<T> op) {
return op;
}
T apply(T l, T r);
default Op2<T> flip() {
return (b, a) -> apply(a, b);
}
}
/**
* Predicate interface
* @param <T> operand type
*/
@FunctionalInterface
public interface Predicate<T> extends F<T, Boolean> {
static <T> Predicate<T> of(Predicate<T> pr) {
return pr;
}
Boolean apply(T t);
}
}
|
package io.muoncore;
import io.muoncore.channel.support.Scheduler;
import io.muoncore.codec.CodecsSource;
import io.muoncore.config.MuonConfigurationSource;
import io.muoncore.protocol.introspection.client.IntrospectionClientProtocolStack;
import io.muoncore.transport.TransportClientSource;
import io.muoncore.transport.TransportControl;
/**
* Default set of protocol stacks.
*/
public interface Muon extends
ServerRegistrarSource,
IntrospectionClientProtocolStack,
TransportClientSource, CodecsSource, MuonConfigurationSource, DiscoverySource {
Scheduler getScheduler();
void shutdown();
TransportControl getTransportControl();
}
|
package hudson.cli;
import hudson.remoting.Channel;
import hudson.remoting.RemoteInputStream;
import hudson.remoting.RemoteOutputStream;
import hudson.remoting.PingThread;
import java.net.URL;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import java.util.ArrayList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
/**
* CLI entry point to Hudson.
*
* @author Kohsuke Kawaguchi
*/
public class CLI {
private final ExecutorService pool;
private final Channel channel;
private final CliEntryPoint entryPoint;
private final boolean ownsPool;
public CLI(URL hudson) throws IOException, InterruptedException {
this(hudson,null);
}
public CLI(URL hudson, ExecutorService exec) throws IOException, InterruptedException {
String url = hudson.toExternalForm();
if(!url.endsWith("/")) url+='/';
url+="cli";
hudson = new URL(url);
FullDuplexHttpStream con = new FullDuplexHttpStream(hudson);
ownsPool = exec==null;
pool = exec!=null ? exec : Executors.newCachedThreadPool();
channel = new Channel("Chunked connection to "+hudson,
pool,con.getInputStream(),con.getOutputStream());
new PingThread(channel,30*1000) {
protected void onDead() {
// noop. the point of ping is to keep the connection alive
// as most HTTP servers have a rather short read time out
}
}.start();
// execute the command
entryPoint = (CliEntryPoint)channel.waitForRemoteProperty(CliEntryPoint.class.getName());
if(entryPoint.protocolVersion()!=CliEntryPoint.VERSION)
throw new IOException(Messages.CLI_VersionMismatch());
}
public void close() throws IOException, InterruptedException {
channel.close();
channel.join();
if(ownsPool)
pool.shutdown();
}
public int execute(List<String> args, InputStream stdin, OutputStream stdout, OutputStream stderr) {
return entryPoint.main(args,Locale.getDefault(),
new RemoteInputStream(stdin),
new RemoteOutputStream(stdout),
new RemoteOutputStream(stderr));
}
public static void main(final String[] _args) throws Exception {
List<String> args = Arrays.asList(_args);
String url = System.getenv("HUDSON_URL");
while(!args.isEmpty()) {
String head = args.get(0);
if(head.equals("-s") && args.size()>=2) {
url = args.get(1);
args = args.subList(2,args.size());
continue;
}
break;
}
if(url==null) {
printUsageAndExit(Messages.CLI_NoURL());
return;
}
if(args.isEmpty())
args = Arrays.asList("help"); // default to help
CLI cli = new CLI(new URL(url));
try {
// execute the command
args = new ArrayList<String>(args);
System.exit(cli.execute(args, System.in, System.out, System.err));
} finally {
cli.close();
}
}
private static void printUsageAndExit(String msg) {
if(msg!=null) System.out.println(msg);
System.err.println(Messages.CLI_Usage());
System.exit(-1);
}
}
|
package net.kevxu.senselib;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.util.Log;
public class OrientationService implements SensorEventListener {
private static final String TAG = "SensorService";
private Context mContext;
private SensorManager mSensorManager;
private List<OrientationServiceListener> mOrientationServiceListeners;
private Sensor mGravitySensor;
private Sensor mMagneticFieldSensor;
private OrientationSensorThread mOrientationSensorThread;
public interface OrientationServiceListener {
public void onRotationMatrixChanged(float[] R, float[] I);
public void onMagneticFieldChanged(float[] values);
}
public OrientationService(Context context) throws SensorNotAvailableException {
this(context, null);
}
public OrientationService(Context context, OrientationServiceListener orientationServiceListener) throws SensorNotAvailableException {
mContext = context;
mSensorManager = (SensorManager) mContext.getSystemService(Context.SENSOR_SERVICE);
List<Sensor> gravitySensors = mSensorManager.getSensorList(Sensor.TYPE_GRAVITY);
List<Sensor> magneticFieldSensor = mSensorManager.getSensorList(Sensor.TYPE_MAGNETIC_FIELD);
if (gravitySensors.size() == 0) {
throw new SensorNotAvailableException(Sensor.TYPE_GRAVITY);
} else {
// Assume the first in the list is the default sensor
// Assumption may not be true though
mGravitySensor = gravitySensors.get(0);
}
if (magneticFieldSensor.size() == 0) {
throw new SensorNotAvailableException(Sensor.TYPE_MAGNETIC_FIELD);
} else {
// Assume the first in the list is the default sensor
// Assumption may not be true though
mMagneticFieldSensor = magneticFieldSensor.get(0);
}
mOrientationServiceListeners = new ArrayList<OrientationServiceListener>();
if (orientationServiceListener != null) {
mOrientationServiceListeners.add(orientationServiceListener);
}
}
/**
* Call this when resume.
*/
public void start() {
if (mOrientationSensorThread == null) {
mOrientationSensorThread = new OrientationSensorThread();
mOrientationSensorThread.start();
Log.i(TAG, "OrientationSensorThread started.");
}
if (mSensorManager == null) {
mSensorManager = (SensorManager) mContext.getSystemService(Context.SENSOR_SERVICE);
}
mSensorManager.registerListener(this, mGravitySensor, SensorManager.SENSOR_DELAY_GAME);
Log.i(TAG, "Gravity sensor registered.");
mSensorManager.registerListener(this, mMagneticFieldSensor, SensorManager.SENSOR_DELAY_GAME);
Log.i(TAG, "Magnetic field sensor registered.");
}
/**
* Call this when pause.
*/
public void stop() {
mOrientationSensorThread.terminate();
Log.i(TAG, "Waiting for OrientationSensorThread to stop.");
try {
mOrientationSensorThread.join();
} catch (InterruptedException e) {
Log.e(TAG, e.getMessage(), e);
}
Log.i(TAG, "OrientationSensorThread stopped.");
mOrientationSensorThread = null;
mSensorManager.unregisterListener(this);
Log.i(TAG, "Sensors unregistered.");
}
private final class OrientationSensorThread extends AbstractSensorWorkerThread {
private float[] R;
private float[] I;
private float[] gravity;
private float[] geomagnetic;
protected OrientationSensorThread() {
this(DEFAULT_INTERVAL);
}
protected OrientationSensorThread(long interval) {
super(interval);
R = new float[9];
I = new float[9];
}
public synchronized void pushGravity(float[] gravity) {
if (this.gravity == null) {
this.gravity = new float[3];
}
System.arraycopy(gravity, 0, this.gravity, 0, 3);
}
public synchronized void pushGeomagnetic(float[] geomagnetic) {
if (this.geomagnetic == null) {
this.geomagnetic = new float[3];
}
System.arraycopy(geomagnetic, 0, this.geomagnetic, 0, 3);
}
public synchronized float[] getGravity() {
return this.gravity;
}
public synchronized float[] getGeomagnetic() {
return this.geomagnetic;
}
@Override
public void run() {
while (!isTerminated()) {
if (getGravity() != null && getGeomagnetic() != null) {
SensorManager.getRotationMatrix(R, I, getGravity(), getGeomagnetic());
}
for (OrientationServiceListener orientationServiceListener : mOrientationServiceListeners) {
orientationServiceListener.onRotationMatrixChanged(R, I);
if (getGeomagnetic() != null) {
orientationServiceListener.onMagneticFieldChanged(getGeomagnetic());
}
}
try {
Thread.sleep(getInterval());
} catch (InterruptedException e) {
Log.w(TAG, e.getMessage(), e);
}
}
}
}
public void addListener(OrientationServiceListener orientationServiceListener) {
if (orientationServiceListener != null) {
mOrientationServiceListeners.add(orientationServiceListener);
} else {
throw new NullPointerException("OrientationServiceListener is null.");
}
}
public void removeListeners() {
mOrientationServiceListeners.clear();
}
@Override
public void onSensorChanged(SensorEvent event) {
synchronized (this) {
if (mOrientationSensorThread != null) {
Sensor sensor = event.sensor;
int type = sensor.getType();
if (type == Sensor.TYPE_GRAVITY) {
mOrientationSensorThread.pushGravity(event.values);
} else if (type == Sensor.TYPE_MAGNETIC_FIELD) {
mOrientationSensorThread.pushGeomagnetic(event.values);
}
}
}
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// Not implemented
}
}
|
/**
* A class to manage indices.
*/
package net.lucenews.model;
import java.io.*;
import java.util.*;
import net.lucenews.*;
import net.lucenews.model.event.*;
import net.lucenews.model.exception.*;
import org.apache.log4j.*;
import org.apache.lucene.index.*;
public class LuceneIndexManager implements LuceneIndexListener {
private Map<String,File> directories;
private LuceneWebService service;
public LuceneIndexManager (LuceneWebService service) {
this.service = service;
directories = new HashMap<String,File>();
LuceneIndex.addIndexListener( this );
}
/**
* Gets a particular index based on its index name. Will search
* through all paths, attempting to find a directory with that name.
*
* @param name the name of the index
* @return the LuceneIndex corresponding to the given name
*/
public LuceneIndex getIndex (String name) throws IndexNotFoundException, IOException {
if (!directories.containsKey(name)) {
// Perhaps we're a little old...
refresh();
}
File directory = directories.get( name );
if (directory == null) {
throw new IndexNotFoundException( name );
}
try {
return LuceneIndex.retrieve( directory );
}
catch (IndexNotFoundException infe) {
throw new IndexNotFoundException( name );
}
}
public LuceneIndex[] getIndices () throws IndicesNotFoundException, IOException {
guaranteeFreshDirectories();
// Get and sort directory names
List<String> namesList = new ArrayList<String>( directories.keySet() );
Collections.sort( namesList );
String[] names = namesList.toArray( new String[]{} );
LuceneIndex[] indices = new LuceneIndex[ names.length ];
for (int i = 0; i < names.length; i++) {
try {
indices[ i ] = LuceneIndex.retrieve( directories.get( names[ i ] ) );
}
catch (IndexNotFoundException infe) {
refresh();
throw infe;
}
}
return indices;
}
public LuceneIndex[] getIndices (String... names) throws IndicesNotFoundException, IOException {
LuceneIndex[] indices = new LuceneIndex[ names.length ];
for (int i = 0; i < names.length; i++) {
indices[ i ] = getIndex( names[ i ] );
}
return indices;
}
public File[] getIndicesDirectories ()
throws IOException
{
String directoryNames = null;
if ( directoryNames == null ) directoryNames = service.getProperty("index.directories");
if ( directoryNames == null ) directoryNames = service.getProperty("index.directory");
if ( directoryNames == null ) directoryNames = service.getProperty("directories");
if ( directoryNames == null ) directoryNames = service.getProperty("directory");
if ( directoryNames == null ) directoryNames = service.getProperty("indices.directories");
if ( directoryNames == null ) directoryNames = service.getProperty("index.directories");
if ( directoryNames == null ) directoryNames = service.getProperty("indexDirectory");
if ( directoryNames == null ) directoryNames = service.getProperty("indexDirectories");
// If none of these work, we will attempt to come up with a
// logical default based on what operating system this is using.
String os = System.getProperty("os.name");
Logger.getLogger( this.getClass() ).info("Operating system: " + os);
// attempt to determine a directory based on operating system
if ( directoryNames == null && os != null ) {
if ( os.startsWith("Windows") ) {
directoryNames = "C:\\indices";
}
else if ( os.startsWith("Linux") ) {
directoryNames = "/var/local/lucene";
}
}
if ( directoryNames == null ) directoryNames = "C:\\indices";
// split the directory names
String[] paths = directoryNames.split(";");
List<File> directories = new LinkedList<File>();
for ( int i = 0; i < paths.length; i++ ) {
String path = ServletUtils.clean( paths[ i ] );
if ( path != null ) {
directories.add( new File( path ) );
}
}
return directories.toArray( new File[]{} );
}
public File getCreatedIndicesDirectory () throws IOException {
return getIndicesDirectories()[ 0 ];
}
public void guaranteeFreshDirectories () throws IOException {
loadDirectories();
}
public void loadDirectories () throws IOException {
directories.clear();
File[] indicesDirectories = getIndicesDirectories();
for ( int i = 0; i < indicesDirectories.length; i++ ) {
if ( !indicesDirectories[ i ].isDirectory() ) {
continue;
}
File indicesDirectory = indicesDirectories[ i ];
File[] files = indicesDirectory.listFiles();
for ( int j = 0; j < files.length; j++ ) {
if ( !files[ j ].isDirectory() ) {
continue;
}
File directory = files[ j ];
if ( IndexReader.indexExists( directory ) ) {
String name = directory.getName();
if ( !directories.containsKey( name ) ) {
directories.put( name, directory );
}
}
}
}
}
public void indexCreated (LuceneIndexEvent e) {
try {
refresh();
}
catch (IOException ioe) {
}
}
public void indexDeleted (LuceneIndexEvent e) {
try {
refresh();
}
catch (IOException ioe) {
}
}
public void indexModified (LuceneIndexEvent e) {
}
public void refresh () throws IOException {
loadDirectories();
}
}
|
package org.apache.fop.render.pdf;
// FOP
import org.apache.fop.render.PrintRenderer;
import org.apache.fop.render.RendererContext;
import org.apache.fop.fo.FOUserAgent;
import org.apache.fop.image.FopImage;
import org.apache.fop.image.XMLImage;
import org.apache.fop.image.ImageFactory;
import org.apache.fop.apps.FOPException;
import org.apache.fop.apps.Version;
import org.apache.fop.fo.properties.RuleStyle;
import org.apache.fop.fo.properties.BackgroundRepeat;
import org.apache.fop.pdf.PDFStream;
import org.apache.fop.pdf.PDFDocument;
import org.apache.fop.pdf.PDFInfo;
import org.apache.fop.pdf.PDFResources;
import org.apache.fop.pdf.PDFResourceContext;
import org.apache.fop.pdf.PDFXObject;
import org.apache.fop.pdf.PDFPage;
import org.apache.fop.pdf.PDFState;
import org.apache.fop.pdf.PDFLink;
import org.apache.fop.pdf.PDFOutline;
import org.apache.fop.pdf.PDFAnnotList;
import org.apache.fop.pdf.PDFColor;
import org.apache.fop.extensions.BookmarkData;
import org.apache.fop.area.Trait;
import org.apache.fop.area.TreeExt;
import org.apache.fop.area.CTM;
import org.apache.fop.area.Title;
import org.apache.fop.area.PageViewport;
import org.apache.fop.area.Page;
import org.apache.fop.area.RegionViewport;
import org.apache.fop.area.Area;
import org.apache.fop.area.Block;
import org.apache.fop.area.BlockViewport;
import org.apache.fop.area.LineArea;
import org.apache.fop.area.inline.Character;
import org.apache.fop.area.inline.Word;
import org.apache.fop.area.inline.Viewport;
import org.apache.fop.area.inline.ForeignObject;
import org.apache.fop.area.inline.Image;
import org.apache.fop.area.inline.Leader;
import org.apache.fop.area.inline.InlineParent;
import org.apache.fop.layout.FontState;
import org.apache.fop.layout.FontMetric;
import org.apache.fop.traits.BorderProps;
import org.apache.fop.datatypes.ColorType;
import org.apache.avalon.framework.configuration.Configurable;
import org.apache.avalon.framework.configuration.Configuration;
import org.apache.avalon.framework.configuration.ConfigurationException;
import org.w3c.dom.Document;
// Java
import java.io.IOException;
import java.io.OutputStream;
import java.awt.Color;
import java.awt.geom.Rectangle2D;
import java.awt.geom.AffineTransform;
import java.util.HashMap;
import java.util.List;
import java.util.ArrayList;
/*
todo:
word rendering and optimistion
pdf state optimisation
line and border
background pattern
writing mode
text decoration
*/
/**
* Renderer that renders areas to PDF
*
*/
public class PDFRenderer extends PrintRenderer {
/**
* The mime type for pdf
*/
public static final String MIME_TYPE = "application/pdf";
/**
* the PDF Document being created
*/
protected PDFDocument pdfDoc;
/**
* Map of pages using the PageViewport as the key
* this is used for prepared pages that cannot be immediately
* rendered
*/
protected HashMap pages = null;
/**
* Page references are stored using the PageViewport as the key
* when a reference is made the PageViewport is used
* for pdf this means we need the pdf page reference
*/
protected HashMap pageReferences = new HashMap();
protected HashMap pvReferences = new HashMap();
private String producer = "FOP";
private String creator = null;
/**
* The output stream to write the document to
*/
protected OutputStream ostream;
/**
* the /Resources object of the PDF document being created
*/
protected PDFResources pdfResources;
/**
* the current stream to add PDF commands to
*/
protected PDFStream currentStream;
/**
* the current annotation list to add annotations to
*/
protected PDFResourceContext currentContext = null;
/**
* the current page to add annotations to
*/
protected PDFPage currentPage;
// drawing state
protected PDFState currentState = null;
protected String currentFontName = "";
protected int currentFontSize = 0;
protected int pageHeight;
protected HashMap filterMap = new HashMap();
/**
* true if a TJ command is left to be written
*/
protected boolean textOpen = false;
/**
* the previous Y coordinate of the last word written.
* Used to decide if we can draw the next word on the same line.
*/
protected int prevWordY = 0;
/**
* the previous X coordinate of the last word written.
* used to calculate how much space between two words
*/
protected int prevWordX = 0;
/**
* The width of the previous word. Used to calculate space between
*/
protected int prevWordWidth = 0;
/**
* reusable word area string buffer to reduce memory usage
*/
private StringBuffer wordAreaPDF = new StringBuffer();
/**
* create the PDF renderer
*/
public PDFRenderer() {
}
/**
* Configure the PDF renderer.
* Get the configuration to be used for pdf stream filters,
* fonts etc.
*/
public void configure(Configuration conf) throws ConfigurationException {
Configuration filters = conf.getChild("filterList");
Configuration[] filt = filters.getChildren("value");
ArrayList filterList = new ArrayList();
for (int i = 0; i < filt.length; i++) {
String name = filt[i].getValue();
filterList.add(name);
}
filterMap.put(PDFStream.DEFAULT_FILTER, filterList);
Configuration[] font = conf.getChildren("font");
for (int i = 0; i < font.length; i++) {
Configuration[] triple = font[i].getChildren("font-triplet");
ArrayList tripleList = new ArrayList();
for (int j = 0; j < triple.length; j++) {
tripleList.add(new FontTriplet(triple[j].getAttribute("name"),
triple[j].getAttribute("style"),
triple[j].getAttribute("weight")));
}
EmbedFontInfo efi;
efi = new EmbedFontInfo(font[i].getAttribute("metrics-url"),
font[i].getAttributeAsBoolean("kerning"),
tripleList, font[i].getAttribute("embed-url"));
if(fontList == null) {
fontList = new ArrayList();
}
fontList.add(efi);
}
}
/**
* set the document creator
*
* @param creator string indicating application that is creating the document
*/
public void setCreator(String crea) {
creator = crea;
}
/**
* set the PDF document's producer
*
* @param producer string indicating application producing PDF
*/
public void setProducer(String prod) {
producer = prod;
}
public void setUserAgent(FOUserAgent agent) {
super.setUserAgent(agent);
PDFXMLHandler xmlHandler = new PDFXMLHandler();
//userAgent.setDefaultXMLHandler(MIME_TYPE, xmlHandler);
String svg = "http:
userAgent.addXMLHandler(MIME_TYPE, svg, xmlHandler);
}
public void startRenderer(OutputStream stream) throws IOException {
ostream = stream;
producer = "FOP " + Version.getVersion();
this.pdfDoc = new PDFDocument(producer);
this.pdfDoc.setCreator(creator);
this.pdfDoc.setFilterMap(filterMap);
pdfDoc.outputHeader(stream);
}
public void stopRenderer() throws IOException {
FontSetup.addToResources(pdfDoc, pdfDoc.getResources(), fontInfo);
pdfDoc.outputTrailer(ostream);
this.pdfDoc = null;
ostream = null;
pages = null;
pageReferences.clear();
pvReferences.clear();
pdfResources = null;
currentStream = null;
currentContext = null;
currentPage = null;
currentState = null;
currentFontName = "";
wordAreaPDF = new StringBuffer();
}
public boolean supportsOutOfOrder() {
return true;
}
public void renderExtension(TreeExt ext) {
// render bookmark extension
if (ext instanceof BookmarkData) {
renderRootExtensions((BookmarkData)ext);
}
}
protected void renderRootExtensions(BookmarkData bookmarks) {
for (int i = 0; i < bookmarks.getCount(); i++) {
BookmarkData ext = bookmarks.getSubData(i);
renderOutline(ext, null);
}
}
private void renderOutline(BookmarkData outline, PDFOutline parentOutline) {
PDFOutline outlineRoot = pdfDoc.getOutlineRoot();
PDFOutline pdfOutline = null;
PageViewport pv = outline.getPage();
if(pv != null) {
Rectangle2D bounds = pv.getViewArea();
double h = bounds.getHeight();
float yoffset = (float)h / 1000f;
String intDest = (String)pageReferences.get(pv.getKey());
if (parentOutline == null) {
pdfOutline = pdfDoc.makeOutline(outlineRoot,
outline.getLabel(), intDest, yoffset);
} else {
PDFOutline pdfParentOutline = parentOutline;
pdfOutline = pdfDoc.makeOutline(pdfParentOutline,
outline.getLabel(), intDest, yoffset);
}
}
for (int i = 0; i < outline.getCount(); i++) {
renderOutline(outline.getSubData(i), pdfOutline);
}
}
/**
* Start the next page sequence.
* For the pdf renderer there is no concept of page sequences
* but it uses the first available page sequence title to set
* as the title of the pdf document.
*
* @param seqTitle the title of the page sequence
*/
public void startPageSequence(Title seqTitle) {
if (seqTitle != null) {
String str = convertTitleToString(seqTitle);
PDFInfo info = this.pdfDoc.getInfo();
info.setTitle(str);
}
}
/**
* The pdf page is prepared by making the page.
* The page is made in the pdf document without any contents
* and then stored to add the contents later.
* The page objects is stored using the area tree PageViewport
* as a key.
*
* @param page the page to prepare
*/
public void preparePage(PageViewport page) {
this.pdfResources = this.pdfDoc.getResources();
Rectangle2D bounds = page.getViewArea();
double w = bounds.getWidth();
double h = bounds.getHeight();
currentPage = this.pdfDoc.makePage(this.pdfResources,
(int) Math.round(w / 1000), (int) Math.round(h / 1000));
if (pages == null) {
pages = new HashMap();
}
pages.put(page, currentPage);
pageReferences.put(page.getKey(), currentPage.referencePDF());
pvReferences.put(page.getKey(), page);
}
/**
* This method creates a pdf stream for the current page
* uses it as the contents of a new page. The page is written
* immediately to the output stream.
*/
public void renderPage(PageViewport page) throws IOException,
FOPException {
if (pages != null
&& (currentPage = (PDFPage) pages.get(page)) != null) {
pages.remove(page);
Rectangle2D bounds = page.getViewArea();
double h = bounds.getHeight();
pageHeight = (int) h;
} else {
this.pdfResources = this.pdfDoc.getResources();
Rectangle2D bounds = page.getViewArea();
double w = bounds.getWidth();
double h = bounds.getHeight();
pageHeight = (int) h;
currentPage = this.pdfDoc.makePage(this.pdfResources,
(int) Math.round(w / 1000), (int) Math.round(h / 1000));
pageReferences.put(page.getKey(), currentPage.referencePDF());
pvReferences.put(page.getKey(), page);
}
currentStream =
this.pdfDoc.makeStream(PDFStream.CONTENT_FILTER, false);
currentState = new PDFState();
currentState.setTransform(new AffineTransform(1, 0, 0, -1, 0,
(int) Math.round(pageHeight / 1000)));
// Transform origin at top left to origin at bottom left
currentStream.add("1 0 0 -1 0 "
+ (int) Math.round(pageHeight / 1000) + " cm\n");
currentFontName = "";
Page p = page.getPage();
renderPageAreas(p);
this.pdfDoc.addStream(currentStream);
currentPage.setContents(currentStream);
PDFAnnotList annots = currentPage.getAnnotations();
if (annots != null) {
this.pdfDoc.addAnnotList(annots);
}
this.pdfDoc.addPage(currentPage);
this.pdfDoc.output(ostream);
}
protected void startVParea(CTM ctm) {
// Set the given CTM in the graphics state
currentState.push();
currentState.setTransform(
new AffineTransform(CTMHelper.toPDFArray(ctm)));
currentStream.add("q\n");
// multiply with current CTM
currentStream.add(CTMHelper.toPDFString(ctm) + " cm\n");
// Set clip?
currentStream.add("BT\n");
}
protected void endVParea() {
currentStream.add("ET\n");
currentStream.add("Q\n");
currentState.pop();
}
/**
* Handle the viewport traits.
* This is used to draw the traits for a viewport.
*
* @param region the viewport region to handle
*/
protected void handleViewportTraits(RegionViewport region) {
currentFontName = "";
float startx = 0;
float starty = 0;
Rectangle2D viewArea = region.getViewArea();
float width = (float)(viewArea.getWidth() / 1000f);
float height = (float)(viewArea.getHeight() / 1000f);
Trait.Background back;
back = (Trait.Background)region.getTrait(Trait.BACKGROUND);
drawBackAndBorders(region, startx, starty, width, height);
}
/**
* Handle block traits.
* The block could be any sort of block with any positioning
* so this should render the traits such as border and background
* in its position.
*
* @param block the block to render the traits
*/
protected void handleBlockTraits(Block block) {
float startx = currentIPPosition / 1000f;
float starty = currentBPPosition / 1000f;
drawBackAndBorders(block, startx, starty,
block.getWidth() / 1000f, block.getHeight() / 1000f);
}
/**
* Draw the background and borders.
* This draws the background and border traits for an area given
* the position.
*
* @param block the area to get the traits from
* @param startx the start x position
* @param starty the start y position
* @param width the width of the area
* @param height the height of the area
*/
protected void drawBackAndBorders(Area block, float startx, float starty, float width, float height) {
// draw background then border
boolean started = false;
Trait.Background back;
back = (Trait.Background)block.getTrait(Trait.BACKGROUND);
if(back != null) {
started = true;
closeText();
currentStream.add("ET\n");
//currentStream.add("q\n");
if (back.color != null) {
updateColor(back.color, true, null);
currentStream.add(startx + " " + starty + " "
+ width + " " + height + " re\n");
currentStream.add("f\n");
}
if (back.url != null) {
ImageFactory fact = ImageFactory.getInstance();
FopImage fopimage = fact.getImage(back.url, userAgent);
if (fopimage != null && fopimage.load(FopImage.DIMENSIONS, userAgent)) {
if (back.repeat == BackgroundRepeat.REPEAT) {
// create a pattern for the image
} else {
// place once
Rectangle2D pos;
pos = new Rectangle2D.Float((startx + back.horiz) * 1000,
(starty + back.vertical) * 1000,
fopimage.getWidth() * 1000,
fopimage.getHeight() * 1000);
putImage(back.url, pos);
}
}
}
}
BorderProps bps = (BorderProps)block.getTrait(Trait.BORDER_BEFORE);
if(bps != null) {
float endx = startx + width;
if(!started) {
started = true;
closeText();
currentStream.add("ET\n");
//currentStream.add("q\n");
}
float bwidth = bps.width / 1000f;
updateColor(bps.color, false, null);
currentStream.add(bwidth + " w\n");
drawLine(startx, starty + bwidth / 2, endx, starty + bwidth / 2);
}
bps = (BorderProps)block.getTrait(Trait.BORDER_START);
if(bps != null) {
float endy = starty + height;
if(!started) {
started = true;
closeText();
currentStream.add("ET\n");
//currentStream.add("q\n");
}
float bwidth = bps.width / 1000f;
updateColor(bps.color, false, null);
currentStream.add(bwidth + " w\n");
drawLine(startx + bwidth / 2, starty, startx + bwidth / 2, endy);
}
bps = (BorderProps)block.getTrait(Trait.BORDER_AFTER);
if(bps != null) {
float sy = starty + height;
float endx = startx + width;
if(!started) {
started = true;
closeText();
currentStream.add("ET\n");
//currentStream.add("q\n");
}
float bwidth = bps.width / 1000f;
updateColor(bps.color, false, null);
currentStream.add(bwidth + " w\n");
drawLine(startx, sy - bwidth / 2, endx, sy - bwidth / 2);
}
bps = (BorderProps)block.getTrait(Trait.BORDER_END);
if(bps != null) {
float sx = startx + width;
float endy = starty + height;
if(!started) {
started = true;
closeText();
currentStream.add("ET\n");
//currentStream.add("q\n");
}
float bwidth = bps.width / 1000f;
updateColor(bps.color, false, null);
currentStream.add(bwidth + " w\n");
drawLine(sx - bwidth / 2, starty, sx - bwidth / 2, endy);
}
if(started) {
//currentStream.add("Q\n");
currentStream.add("BT\n");
// font last set out of scope in text section
currentFontName = "";
}
}
/**
* Draw a line.
*
* @param startx the start x position
* @param starty the start y position
* @param endx the x end position
* @param endy the y end position
*/
private void drawLine(float startx, float starty, float endx, float endy) {
currentStream.add(startx + " " + starty + " m\n");
currentStream.add(endx + " " + endy + " l\n");
currentStream.add("S\n");
}
protected void renderBlockViewport(BlockViewport bv, List children) {
// clip and position viewport if necessary
// save positions
int saveIP = currentIPPosition;
int saveBP = currentBPPosition;
String saveFontName = currentFontName;
CTM ctm = bv.getCTM();
if (bv.getPositioning() == Block.ABSOLUTE) {
currentIPPosition = 0;
currentBPPosition = 0;
closeText();
currentStream.add("ET\n");
if (bv.getClip()) {
currentStream.add("q\n");
float x = (float)(bv.getXOffset() + containingIPPosition) / 1000f;
float y = (float)(bv.getYOffset() + containingBPPosition) / 1000f;
float width = (float)bv.getWidth() / 1000f;
float height = (float)bv.getHeight() / 1000f;
clip(x, y, width, height);
}
CTM tempctm = new CTM(containingIPPosition, containingBPPosition);
ctm = tempctm.multiply(ctm);
startVParea(ctm);
handleBlockTraits(bv);
renderBlocks(children);
endVParea();
if (bv.getClip()) {
currentStream.add("Q\n");
}
currentStream.add("BT\n");
// clip if necessary
currentIPPosition = saveIP;
currentBPPosition = saveBP;
} else {
if (ctm != null) {
currentIPPosition = 0;
currentBPPosition = 0;
closeText();
currentStream.add("ET\n");
double[] vals = ctm.toArray();
boolean aclock = vals[2] == 1.0;
if (vals[2] == 1.0) {
ctm = ctm.translate(-saveBP - bv.getHeight(), -saveIP);
} else if (vals[0] == -1.0) {
ctm = ctm.translate(-saveIP - bv.getWidth(), -saveBP - bv.getHeight());
} else {
ctm = ctm.translate(saveBP, saveIP - bv.getWidth());
}
}
// clip if necessary
if (bv.getClip()) {
if (ctm == null) {
closeText();
currentStream.add("ET\n");
}
currentStream.add("q\n");
float x = (float)bv.getXOffset() / 1000f;
float y = (float)bv.getYOffset() / 1000f;
float width = (float)bv.getWidth() / 1000f;
float height = (float)bv.getHeight() / 1000f;
clip(x, y, width, height);
}
if (ctm != null) {
startVParea(ctm);
}
handleBlockTraits(bv);
renderBlocks(children);
if (ctm != null) {
endVParea();
}
if (bv.getClip()) {
currentStream.add("Q\n");
if (ctm == null) {
currentStream.add("BT\n");
}
}
if (ctm != null) {
currentStream.add("BT\n");
}
currentIPPosition = saveIP;
currentBPPosition = saveBP;
currentBPPosition += (int)(bv.getHeight());
}
currentFontName = saveFontName;
}
/**
* Clip an area.
* write a clipping operation given coordinates in the current
* transform.
* @param x the x coordinate
* @param y the y coordinate
* @param width the width of the area
* @param height the height of the area
*/
protected void clip(float x, float y, float width, float height) {
currentStream.add(x + " " + y + " m\n");
currentStream.add((x + width) + " " + y + " l\n");
currentStream.add((x + width) + " " + (y + height) + " l\n");
currentStream.add(x + " " + (y + height) + " l\n");
currentStream.add("h\n");
currentStream.add("W\n");
currentStream.add("n\n");
}
protected void renderLineArea(LineArea line) {
super.renderLineArea(line);
closeText();
}
/**
* Render inline parent area.
* For pdf this handles the inline parent area traits such as
* links, border, background.
* @param ip the inline parent area
*/
public void renderInlineParent(InlineParent ip) {
float start = currentBlockIPPosition / 1000f;
float top = (ip.getOffset() + currentBPPosition) / 1000f;
float width = ip.getWidth() / 1000f;
float height = ip.getHeight() / 1000f;
drawBackAndBorders(ip, start, top, width, height);
// render contents
super.renderInlineParent(ip);
// place the link over the top
Object tr = ip.getTrait(Trait.INTERNAL_LINK);
boolean internal = false;
String dest = null;
float yoffset = 0;
if (tr == null) {
dest = (String)ip.getTrait(Trait.EXTERNAL_LINK);
} else {
String pvKey = (String)tr;
dest = (String)pageReferences.get(pvKey);
if(dest != null) {
PageViewport pv = (PageViewport)pvReferences.get(pvKey);
Rectangle2D bounds = pv.getViewArea();
double h = bounds.getHeight();
yoffset = (float)h / 1000f;
internal = true;
}
}
if (dest != null) {
// add link to pdf document
Rectangle2D rect = new Rectangle2D.Float(start, top, width, height);
// transform rect to absolute coords
AffineTransform transform = currentState.getTransform();
rect = transform.createTransformedShape(rect).getBounds();
int type = internal ? PDFLink.INTERNAL : PDFLink.EXTERNAL;
PDFLink pdflink = pdfDoc.makeLink(rect, dest, type, yoffset);
currentPage.addAnnotation(pdflink);
}
}
public void renderCharacter(Character ch) {
super.renderCharacter(ch);
}
public void renderWord(Word word) {
StringBuffer pdf = new StringBuffer();
String name = (String) word.getTrait(Trait.FONT_NAME);
int size = ((Integer) word.getTrait(Trait.FONT_SIZE)).intValue();
// This assumes that *all* CIDFonts use a /ToUnicode mapping
Font f = (Font) fontInfo.getFonts().get(name);
boolean useMultiByte = f.isMultiByte();
// String startText = useMultiByte ? "<FEFF" : "(";
String startText = useMultiByte ? "<" : "(";
String endText = useMultiByte ? "> " : ") ";
updateFont(name, size, pdf);
ColorType ct = (ColorType)word.getTrait(Trait.COLOR);
if(ct != null) {
updateColor(ct, true, pdf);
}
int rx = currentBlockIPPosition;
// int bl = pageHeight - currentBPPosition;
int bl = currentBPPosition + word.getOffset();
// Set letterSpacing
//float ls = fs.getLetterSpacing() / this.currentFontSize;
//pdf.append(ls).append(" Tc\n");
if (!textOpen || bl != prevWordY) {
closeText();
pdf.append("1 0 0 -1 " + (rx / 1000f) + " "
+ (bl / 1000f) + " Tm [" + startText);
prevWordY = bl;
textOpen = true;
} else {
// express the space between words in thousandths of an em
int space = prevWordX - rx + prevWordWidth;
float emDiff = (float) space / (float) currentFontSize * 1000f;
// this prevents a problem in Acrobat Reader and other viewers
// where large numbers cause text to disappear or default to
// a limit
if (emDiff < -33000) {
closeText();
pdf.append("1 0 0 1 " + (rx / 1000f) + " "
+ (bl / 1000f) + " Tm [" + startText);
textOpen = true;
} else {
pdf.append(Float.toString(emDiff));
pdf.append(" ");
pdf.append(startText);
}
}
prevWordWidth = word.getWidth();
prevWordX = rx;
String s = word.getWord();
FontMetric metrics = fontInfo.getMetricsFor(name);
FontState fs = new FontState(name, metrics, size);
escapeText(s, fs, useMultiByte, pdf);
pdf.append(endText);
currentStream.add(pdf.toString());
super.renderWord(word);
}
public void escapeText(String s, FontState fs,
boolean useMultiByte, StringBuffer pdf) {
String startText = useMultiByte ? "<" : "(";
String endText = useMultiByte ? "> " : ") ";
boolean kerningAvailable = false;
HashMap kerning = null;
kerning = fs.getKerning();
if (kerning != null && !kerning.isEmpty()) {
kerningAvailable = true;
}
int l = s.length();
for (int i = 0; i < l; i++) {
char ch = fs.mapChar(s.charAt(i));
if (!useMultiByte) {
if (ch > 127) {
pdf.append("\\");
pdf.append(Integer.toOctalString((int) ch));
} else {
switch (ch) {
case '(':
case ')':
case '\\':
pdf.append("\\");
break;
}
pdf.append(ch);
}
} else {
pdf.append(getUnicodeString(ch));
}
if (kerningAvailable && (i + 1) < l) {
addKerning(pdf, (new Integer((int) ch)),
(new Integer((int) fs.mapChar(s.charAt(i + 1)))
), kerning, startText, endText);
}
}
}
/**
* Convert a char to a multibyte hex representation
*/
private String getUnicodeString(char c) {
StringBuffer buf = new StringBuffer(4);
byte[] uniBytes = null;
try {
char[] a = {c};
uniBytes = new String(a).getBytes("UnicodeBigUnmarked");
} catch (java.io.UnsupportedEncodingException e) {
// This should never fail
}
for (int i = 0; i < uniBytes.length; i++) {
int b = (uniBytes[i] < 0) ? (int)(256 + uniBytes[i])
: (int) uniBytes[i];
String hexString = Integer.toHexString(b);
if (hexString.length() == 1) {
buf = buf.append("0" + hexString);
} else {
buf = buf.append(hexString);
}
}
return buf.toString();
}
private void addKerning(StringBuffer buf, Integer ch1, Integer ch2,
HashMap kerning, String startText, String endText) {
HashMap kernPair = (HashMap) kerning.get(ch1);
if (kernPair != null) {
Integer width = (Integer) kernPair.get(ch2);
if (width != null) {
buf.append(endText).append(-width.intValue());
buf.append(' ').append(startText);
}
}
}
/**
* Checks to see if we have some text rendering commands open
* still and writes out the TJ command to the stream if we do
*/
protected void closeText() {
if (textOpen) {
currentStream.add("] TJ\n");
textOpen = false;
prevWordX = 0;
prevWordY = 0;
}
}
private void updateColor(ColorType col, boolean fill, StringBuffer pdf) {
Color newCol = new Color(col.red(), col.green(), col.blue());
boolean update = false;
if (fill) {
update = currentState.setBackColor(newCol);
} else {
update = currentState.setColor(newCol);
}
if (update) {
PDFColor color = new PDFColor((double)col.red(),
(double)col.green(),
(double)col.blue());
closeText();
if(pdf != null) {
pdf.append(color.getColorSpaceOut(fill));
} else {
currentStream.add(color.getColorSpaceOut(fill));
}
}
}
private void updateFont(String name, int size, StringBuffer pdf) {
if ((!name.equals(this.currentFontName))
|| (size != this.currentFontSize)) {
closeText();
this.currentFontName = name;
this.currentFontSize = size;
pdf = pdf.append("/" + name + " " + ((float) size / 1000f)
+ " Tf\n");
}
}
public void renderImage(Image image, Rectangle2D pos) {
String url = image.getURL();
putImage(url, pos);
}
protected void putImage(String url, Rectangle2D pos) {
PDFXObject xobject = pdfDoc.getImage(url);
if (xobject != null) {
int w = (int) pos.getWidth() / 1000;
int h = (int) pos.getHeight() / 1000;
placeImage((int) pos.getX() / 1000,
(int) pos.getY() / 1000, w, h, xobject.getXNumber());
return;
}
ImageFactory fact = ImageFactory.getInstance();
FopImage fopimage = fact.getImage(url, userAgent);
if (fopimage == null) {
return;
}
if (!fopimage.load(FopImage.DIMENSIONS, userAgent)) {
return;
}
String mime = fopimage.getMimeType();
if ("text/xml".equals(mime)) {
if (!fopimage.load(FopImage.ORIGINAL_DATA, userAgent)) {
return;
}
Document doc = ((XMLImage) fopimage).getDocument();
String ns = ((XMLImage) fopimage).getNameSpace();
renderDocument(doc, ns, pos);
} else if ("image/svg+xml".equals(mime)) {
if (!fopimage.load(FopImage.ORIGINAL_DATA, userAgent)) {
return;
}
Document doc = ((XMLImage) fopimage).getDocument();
String ns = ((XMLImage) fopimage).getNameSpace();
renderDocument(doc, ns, pos);
} else if ("image/eps".equals(mime)) {
if (!fopimage.load(FopImage.ORIGINAL_DATA, userAgent)) {
return;
}
FopPDFImage pdfimage = new FopPDFImage(fopimage, url);
int xobj = pdfDoc.addImage(currentContext, pdfimage).getXNumber();
fact.releaseImage(url, userAgent);
} else if ("image/jpeg".equals(mime)) {
if (!fopimage.load(FopImage.ORIGINAL_DATA, userAgent)) {
return;
}
FopPDFImage pdfimage = new FopPDFImage(fopimage, url);
int xobj = pdfDoc.addImage(currentContext, pdfimage).getXNumber();
fact.releaseImage(url, userAgent);
int w = (int) pos.getWidth() / 1000;
int h = (int) pos.getHeight() / 1000;
placeImage((int) pos.getX() / 1000,
(int) pos.getY() / 1000, w, h, xobj);
} else {
if (!fopimage.load(FopImage.BITMAP, userAgent)) {
return;
}
FopPDFImage pdfimage = new FopPDFImage(fopimage, url);
int xobj = pdfDoc.addImage(currentContext, pdfimage).getXNumber();
fact.releaseImage(url, userAgent);
int w = (int) pos.getWidth() / 1000;
int h = (int) pos.getHeight() / 1000;
placeImage((int) pos.getX() / 1000,
(int) pos.getY() / 1000, w, h, xobj);
}
// output new data
try {
this.pdfDoc.output(ostream);
} catch (IOException ioe) {
// ioexception will be caught later
}
}
protected void placeImage(int x, int y, int w, int h, int xobj) {
currentStream.add("q\n" + ((float) w) + " 0 0 "
+ ((float) -h) + " "
+ (((float) currentBlockIPPosition) / 1000f + x) + " "
+ (((float)(currentBPPosition + 1000 * h)) / 1000f
+ y) + " cm\n" + "/Im" + xobj + " Do\nQ\n");
}
public void renderForeignObject(ForeignObject fo, Rectangle2D pos) {
Document doc = fo.getDocument();
String ns = fo.getNameSpace();
renderDocument(doc, ns, pos);
}
public void renderDocument(Document doc, String ns, Rectangle2D pos) {
RendererContext context;
context = new RendererContext(MIME_TYPE);
context.setUserAgent(userAgent);
context.setProperty(PDFXMLHandler.PDF_DOCUMENT, pdfDoc);
context.setProperty(PDFXMLHandler.OUTPUT_STREAM, ostream);
context.setProperty(PDFXMLHandler.PDF_STATE, currentState);
context.setProperty(PDFXMLHandler.PDF_PAGE, currentPage);
context.setProperty(PDFXMLHandler.PDF_CONTEXT, currentContext == null ? currentPage: currentContext);
context.setProperty(PDFXMLHandler.PDF_CONTEXT, currentContext);
context.setProperty(PDFXMLHandler.PDF_STREAM, currentStream);
context.setProperty(PDFXMLHandler.PDF_XPOS,
new Integer(currentBlockIPPosition + (int) pos.getX()));
context.setProperty(PDFXMLHandler.PDF_YPOS,
new Integer(currentBPPosition + (int) pos.getY()));
context.setProperty(PDFXMLHandler.PDF_FONT_INFO, fontInfo);
context.setProperty(PDFXMLHandler.PDF_FONT_NAME, currentFontName);
context.setProperty(PDFXMLHandler.PDF_FONT_SIZE,
new Integer(currentFontSize));
context.setProperty(PDFXMLHandler.PDF_WIDTH,
new Integer((int) pos.getWidth()));
context.setProperty(PDFXMLHandler.PDF_HEIGHT,
new Integer((int) pos.getHeight()));
userAgent.renderXML(context, doc, ns);
}
/**
* Render an inline viewport.
* This renders an inline viewport by clipping if necessary.
* @param viewport the viewport to handle
*/
public void renderViewport(Viewport viewport) {
closeText();
float x = currentBlockIPPosition / 1000f;
float y = (currentBPPosition + viewport.getOffset()) / 1000f;
float width = viewport.getWidth() / 1000f;
float height = viewport.getHeight() / 1000f;
drawBackAndBorders(viewport, x, y, width, height);
currentStream.add("ET\n");
if (viewport.getClip()) {
currentStream.add("q\n");
clip(x, y, width, height);
}
super.renderViewport(viewport);
if (viewport.getClip()) {
currentStream.add("Q\n");
}
currentStream.add("BT\n");
}
/**
* Render leader area.
* This renders a leader area which is an area with a rule.
* @param area the leader area to render
*/
public void renderLeader(Leader area) {
closeText();
currentStream.add("ET\n");
currentStream.add("q\n");
int style = area.getRuleStyle();
boolean alt = false;
switch(style) {
case RuleStyle.SOLID:
currentStream.add("[] 0 d\n");
break;
case RuleStyle.DOTTED:
currentStream.add("[2] 0 d\n");
break;
case RuleStyle.DASHED:
currentStream.add("[6 4] 0 d\n");
break;
case RuleStyle.DOUBLE:
case RuleStyle.GROOVE:
case RuleStyle.RIDGE:
alt = true;
break;
}
float startx = ((float) currentBlockIPPosition) / 1000f;
float starty = ((currentBPPosition + area.getOffset()) / 1000f);
float endx = (currentBlockIPPosition + area.getWidth()) / 1000f;
if (!alt) {
currentStream.add(area.getRuleThickness() / 1000f + " w\n");
drawLine(startx, starty, endx, starty);
} else {
if (style == RuleStyle.DOUBLE) {
float third = area.getRuleThickness() / 3000f;
currentStream.add(third + " w\n");
drawLine(startx, starty, endx, starty);
drawLine(startx, (starty + 2 * third), endx, (starty + 2 * third));
} else {
float half = area.getRuleThickness() / 2000f;
currentStream.add("1 g\n");
currentStream.add(startx + " " + starty + " m\n");
currentStream.add(endx + " " + starty + " l\n");
currentStream.add(endx + " " + (starty + 2 * half) + " l\n");
currentStream.add(startx + " " + (starty + 2 * half) + " l\n");
currentStream.add("h\n");
currentStream.add("f\n");
if (style == RuleStyle.GROOVE) {
currentStream.add("0 g\n");
currentStream.add(startx + " " + starty + " m\n");
currentStream.add(endx + " " + starty + " l\n");
currentStream.add(endx + " " + (starty + half) + " l\n");
currentStream.add((startx + half) + " " + (starty + half) + " l\n");
currentStream.add(startx + " " + (starty + 2 * half) + " l\n");
} else {
currentStream.add("0 g\n");
currentStream.add(endx + " " + starty + " m\n");
currentStream.add(endx + " " + (starty + 2 * half) + " l\n");
currentStream.add(startx + " " + (starty + 2 * half) + " l\n");
currentStream.add(startx + " " + (starty + half) + " l\n");
currentStream.add((endx - half) + " " + (starty + half) + " l\n");
}
currentStream.add("h\n");
currentStream.add("f\n");
}
}
currentStream.add("Q\n");
currentStream.add("BT\n");
super.renderLeader(area);
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.broad.igv.ui.panel;
import org.apache.log4j.Logger;
import org.broad.igv.Globals;
import org.broad.igv.PreferenceManager;
import org.broad.igv.feature.Chromosome;
import org.broad.igv.feature.Locus;
import org.broad.igv.feature.Range;
import org.broad.igv.feature.genome.Genome;
import org.broad.igv.feature.genome.GenomeManager;
import org.broad.igv.sam.InsertionManager;
import org.broad.igv.session.Session;
import org.broad.igv.ui.IGV;
import org.broad.igv.ui.event.IGVEventBus;
import org.broad.igv.ui.event.ViewChange;
import org.broad.igv.ui.util.MessageUtils;
import java.util.List;
/**
* @author jrobinso
*/
public class ReferenceFrame {
private static Logger log = Logger.getLogger(ReferenceFrame.class);
/**
* The origin in bp
*/
protected volatile double origin = 0;
/**
* The nominal viewport width in pixels.
*/
public static int binsPerTile = 700;
boolean visible = true;
private String name;
/**
* The chromosome currently in view
*/
protected String chrName = "chrAll";
/**
* The minimum zoom level for the current screen size + chromosome combination.
*/
private int minZoom = 0;
/**
* The maximum zoom level. Set to prevent integer overflow. This is a function
* of chromosome length.
*/
public int maxZoom = 23;
/**
* Minimum allowed range in base-pairs
*/
protected static final int minBP = 40;
/**
* The current zoom level. Zoom level -1 corresponds to the whole
* genome view (chromosome "all")
*/
protected int zoom = minZoom;
/**
* X location of the frame in pixels
*/
volatile int pixelX;
/**
* Width of the frame in pixels
*/
protected int widthInPixels;
/**
* The number of tiles for this zoom level, = 2^zoom
*/
protected double nTiles = 1;
/**
* The maximum virtual pixel value.
*/
//private double maxPixel;
/**
* The location (x axis) locationScale in base pairs / virtual pixel
*/
protected volatile double scale;
protected Locus initialLocus = null;
private List<InsertionManager.Insertion> insertions;
public ReferenceFrame(String name) {
this.name = name;
Genome genome = getGenome();
this.chrName = genome == null ? "" : genome.getHomeChromosome();
}
/**
* Copy constructor -- used by Sashimii plot
*
* @param otherFrame
*/
public ReferenceFrame(ReferenceFrame otherFrame) {
this.chrName = otherFrame.chrName;
this.initialLocus = otherFrame.initialLocus;
this.scale = otherFrame.scale;
this.minZoom = otherFrame.minZoom;
this.name = otherFrame.name;
this.nTiles = otherFrame.nTiles;
this.origin = otherFrame.origin;
this.pixelX = otherFrame.pixelX;
//this.setEnd = otherFrame.setEnd;
this.widthInPixels = otherFrame.widthInPixels;
this.zoom = otherFrame.zoom;
this.insertions = otherFrame.insertions;
this.maxZoom = otherFrame.maxZoom;
}
public boolean isVisible() {
return visible;
}
public void setVisible(boolean visible) {
this.visible = visible;
}
public IGVEventBus getEventBus() {
return IGVEventBus.getInstance();
}
public void dragStopped() {
setOrigin(Math.round(origin)); // Snap to gride
getEventBus().post(ViewChange.Result());
}
public void changeGenome(Genome genome) {
setChromosomeName(genome.getHomeChromosome(), true);
}
public void changeChromosome(String chrName, boolean recordHistory) {
boolean changed = setChromosomeName(chrName, false);
if (changed) {
ViewChange resultEvent = ViewChange.ChromosomeChangeResult(chrName);
resultEvent.setRecordHistory(recordHistory);
getEventBus().post(resultEvent);
changeZoom(0);
}
}
public void changeZoom(int newZoom) {
doSetZoom(newZoom);
ViewChange result = ViewChange.Result();
result.setRecordHistory(false);
getEventBus().post(result);
}
/**
* Set the position and width of the frame, in pixels
* The origin/end positions are kept fixed iff valid
*
* @param pixelX
* @param widthInPixels
*/
public synchronized void setBounds(int pixelX, int widthInPixels) {
this.pixelX = pixelX;
if (this.widthInPixels != widthInPixels) {
//If we have what looks like a valid end position we keep it
if (this.widthInPixels > 0 && this.initialLocus == null) {
int start = (int) getOrigin();
int end = (int) getEnd();
if (start >= 0 && end >= 1) {
this.initialLocus = new Locus(getChrName(), start, end);
}
}
this.widthInPixels = widthInPixels;
computeLocationScale();
computeZoom();
}
}
/**
* Sets zoom level and recomputes scale, iff newZoom != oldZoom
* min/maxZoom are recalculated and respected,
* and the locationScale is recomputed
*
* @param newZoom
*/
protected void setZoom(int newZoom) {
if (zoom != newZoom) {
synchronized (this) {
setZoomWithinLimits(newZoom);
computeLocationScale();
}
}
}
/**
* Set the origin of the frame, guarding against chromosome boundaries
*
* @param position
*/
public void setOrigin(double position) {
int windowLengthBP = (int) (widthInPixels * getScale());
double newOrigin;
if (PreferenceManager.getInstance().getAsBoolean(PreferenceManager.SAM_SHOW_SOFT_CLIPPED)) {
newOrigin = Math.max(-1000, Math.min(position, getMaxCoordinate() + 1000 - windowLengthBP));
} else {
newOrigin = Math.max(0, Math.min(position, getMaxCoordinate() - windowLengthBP));
}
origin = newOrigin;
}
protected synchronized void setZoomWithinLimits(int newZoom) {
zoom = Math.max(minZoom, Math.min(maxZoom, newZoom));
nTiles = Math.pow(2, zoom);
}
/**
* Increment the zoom level by {@code zoomIncrement}, leaving
* the center the same
*
* @param zoomIncrement
*/
public void doZoomIncrement(int zoomIncrement) {
double currentCenter = getGenomeCenterPosition();
doIncrementZoom(zoomIncrement, currentCenter);
}
/**
* Set the zoom level to {@code newZoom}, leaving
* the center the same
*
* @param newZoom
*/
public void doSetZoom(int newZoom) {
double currentCenter = getGenomeCenterPosition();
doSetZoomCenter(newZoom, currentCenter);
}
public void doIncrementZoom(final int zoomIncrement, final double newCenter) {
doSetZoomCenter(getZoom() + zoomIncrement, newCenter);
}
/**
* Intended to be called by UI elements, this method
* performs all actions necessary to set a new zoom
* and center location
*
* @param newZoom
* @param newCenter Center position, in genome coordinates
*/
public void doSetZoomCenter(final int newZoom, final double newCenter) {
if (chrName.equals(Globals.CHR_ALL)) {
chrName = getGenome().getHomeChromosome();
}
if (!chrName.equals(Globals.CHR_ALL)) {
setZoom(newZoom);
// Adjust origin so newCenter is centered
centerOnLocation(newCenter);
}
}
protected double getGenomeCenterPosition() {
return origin + ((widthInPixels / 2) * getScale());
}
/**
* Return the current locationScale in base pairs / pixel
*
* @return
*/
public double getScale() {
if (scale <= 0) {
computeLocationScale();
}
return scale;
}
/**
* Calls {@link #setChromosomeName(String, boolean)} with force = false
* It is preferred that you post an event to the EventBus instead, this is public
* as an implementation side effect
*
* @param name
* @return boolean indicating whether the chromosome actually changed
*/
public boolean setChromosomeName(String name) {
return setChromosomeName(name, false);
}
/**
* Change the frame to the specified chromosome, clearing all
* view parameters (zoom, locationScale) in the process
*
* @param name Name of the new chromosome
* @param force Whether to force a change to the new chromosome, even if it's
* the same name as the old one
* @return boolean indicating whether the chromosome actually changed
*/
public synchronized boolean setChromosomeName(String name, boolean force) {
if (shouldChangeChromosome(name) || force) {
chrName = name;
origin = 0;
this.scale = -1;
this.calculateMaxZoom();
this.zoom = -1;
setZoom(0);
//chromoObservable.setChangedAndNotify();
return true;
}
return false;
}
/**
* Record the current state of the frame in history.
* It is recommended that this NOT be called from within ReferenceFrame,
* and callers use it after making all changes
* <p>
* //TODO Should we save history by receiving events in History?
*/
public void recordHistory() {
IGV.getInstance().getSession().getHistory().push(getFormattedLocusString(), zoom);
}
public void shiftOriginPixels(int delta) {
// if(IGV.getInstance().getSession().expandInsertions) {
// return; // Disable panning in expanded insertion mode for now
double shiftBP = delta * getScale();
setOrigin(origin + shiftBP);
getEventBus().post(ViewChange.Result());
}
public void centerOnLocation(String chr, double chrLocation) {
if (!chrName.equals(chr)) {
setChromosomeName(chr);
}
centerOnLocation(chrLocation);
}
public void centerOnLocation(double chrLocation) {
double windowWidth = (widthInPixels * getScale()) / 2;
setOrigin(Math.round(chrLocation - windowWidth));
getEventBus().post(ViewChange.LocusChangeResult(chrName, origin, chrLocation + windowWidth));
}
public boolean windowAtEnd() {
double windowLengthBP = widthInPixels * getScale();
return origin + windowLengthBP + 1 > getMaxCoordinate();
}
/**
* Move the frame to the specified position. New zoom is calculated
* based on limits.
*
* @param chr
* @param start
* @param end
*/
public void jumpTo(String chr, int start, int end) {
Locus locus = new Locus(chr, start, end);
this.jumpTo(locus);
}
public void jumpTo(Locus locus) {
String chr = locus.getChr();
int start = locus.getStart();
int end = locus.getEnd();
Genome genome = getGenome();
if (chr != null) {
if (genome.getChromosome(chr) == null && !chr.contains(Globals.CHR_ALL)) {
MessageUtils.showMessage(chr + " is not a valid chromosome.");
return;
}
}
end = Math.min(getMaxCoordinate(chr), end);
synchronized (this) {
this.initialLocus = locus;
this.chrName = chr;
if (start >= 0 && end >= 0) {
this.origin = start;
beforeScaleZoom(locus);
computeLocationScale();
computeZoom();
}
}
if (log.isDebugEnabled()) {
log.debug("Data panel width = " + widthInPixels);
log.debug("New start = " + (int) origin);
log.debug("New end = " + (int) getEnd());
log.debug("New center = " + (int) getCenter());
log.debug("Scale = " + scale);
}
getEventBus().post(ViewChange.LocusChangeResult(chrName, start, end));
}
public double getOrigin() {
return origin;
}
public double getCenter() {
return origin + getScale() * widthInPixels / 2;
}
public double getEnd() {
return origin + getScale() * widthInPixels;
}
public int getZoom() {
return zoom;
}
/**
* Return the maximum zoom level
*
* @return
*/
public int getMaxZoom() {
return maxZoom;
}
public int getAdjustedZoom() {
return zoom - minZoom;
}
/**
* Determine if this view will change at all based on the {@code newChrName}
* The view changes if newChrName != {@code #this.chr} or if we are not
* at full chromosome view
*
* @param newChrName
* @return
*/
private boolean shouldChangeChromosome(String newChrName) {
return chrName == null || !chrName.equals(newChrName);
}
protected void calculateMaxZoom() {
this.maxZoom = Globals.CHR_ALL.equals(this.chrName) ? 0 :
(int) Math.ceil(Math.log(getChromosomeLength() / minBP) / Globals.log2);
}
public String getChrName() {
return chrName;
}
// TODO -- this parameter shouldn't be stored here. Maybe in a specialized
// layout manager?
public int getWidthInPixels() {
return widthInPixels;
}
/**
* Return the chromosome position corresponding to the pixel index. The
* pixel index is the pixel "position" translated by -origin.
*
* @param screenPosition
* @return
*/
public double getChromosomePosition(int screenPosition) {
if (IGV.getInstance().getSession().expandInsertions && insertions != null && insertions.size() > 0) {
double start = getOrigin();
double scale = getScale();
double a = 0,
b = 0;
//TODO -- replace this linear search
for (InsertionManager.Insertion i : insertions) {
b = a + (i.position - start) / scale; // Screen position of insertion start
if (screenPosition < b) {
return start + scale * (screenPosition - a);
}
a = b + i.size / scale; // Screen position of insertion end
if (screenPosition < a) {
return i.position; // In the gap
}
start = i.position;
}
return start + scale * (screenPosition - a);
} else {
return origin + getScale() * screenPosition;
}
}
/**
* Return the screen position corresponding to the chromosomal position.
*
* @param chromosomePosition
* @return
*/
public int getScreenPosition(double chromosomePosition) {
return (int) ((chromosomePosition - origin) / getScale());
}
public Chromosome getChromosome() {
Genome genome = getGenome();
if (genome == null) {
return null;
}
return genome.getChromosome(chrName);
}
/**
* The maximum coordinate currently allowed.
* In genomic coordinates this is the same as the chromosome length.
* In exome coordinates, the two are different
* (since ExomeReferenceFrame takes input in genomic coordinates)
*
* @return
* @see #getChromosomeLength()
*/
public int getMaxCoordinate() {
return this.getChromosomeLength();
}
private static int getMaxCoordinate(String chrName) {
return getChromosomeLength(chrName);
}
/**
* Chromosome length, in genomic coordinates.
* Intended to be used for scaling
*
* @return
* @see #getMaxCoordinate()
*/
public int getChromosomeLength() {
return getChromosomeLength(this.chrName);
}
public double getTilesTimesBinsPerTile() {
return nTiles * (double) binsPerTile;
}
public int getMidpoint() {
return pixelX + widthInPixels / 2;
}
/**
* Get the UCSC style locus string corresponding to the current view. THe UCSC
* conventions are followed for coordinates, specifically the internal representation
* is "zero" based (first base is numbered 0) but the display representation is
* "one" based (first base is numbered 1). Consequently 1 is added to the
* computed positions.
*
* @return
*/
public String getFormattedLocusString() {
if (zoom == 0) {
return getChrName();
} else {
Range range = getCurrentRange();
return Locus.getFormattedLocusString(range.getChr(), range.getStart(), range.getEnd());
}
}
public Range getCurrentRange() {
int start = 0;
int end = widthInPixels;
int startLoc = (int) getChromosomePosition(start) + 1;
int endLoc = (int) getChromosomePosition(end);
Range range = new Range(getChrName(), startLoc, endLoc);
return range;
}
public void reset() {
jumpTo(FrameManager.getLocus(name));
}
public String getName() {
return name;
}
public Locus getInitialLocus() {
return initialLocus;
}
public int getMinZoom() {
return minZoom;
}
public void setName(String name) {
this.name = name;
}
public int getStateHash() {
return (chrName + origin + scale + widthInPixels).hashCode();
}
/**
* Recalculate the locationScale, based on {@link #initialLocus}, {@link #origin}, and
* {@link #widthInPixels}
* DOES NOT alter zoom value
*/
private synchronized void computeLocationScale() {
Genome genome = getGenome();
//Should consider getting rid of this. We don't have
//a chromosome length without a genome, not always a problem
if (genome != null) {
// The end location, in base pairs.
// If negative, we use the whole chromosome
int setEnd = -1;
if (this.initialLocus != null) setEnd = this.initialLocus.getEnd();
if (setEnd > 0 && widthInPixels > 0) {
this.scale = ((setEnd - origin) / widthInPixels);
this.initialLocus = null;
} else {
double virtualPixelSize = getTilesTimesBinsPerTile();
double nPixel = Math.max(virtualPixelSize, widthInPixels);
this.scale = (((double) getChromosomeLength()) / nPixel);
}
}
}
/**
* Recalculate the zoom value based on current start/end
* locationScale is not altered
*/
private void computeZoom() {
int newZoom = calculateZoom(getOrigin(), getEnd());
setZoomWithinLimits(newZoom);
}
/**
* Called before scaling and zooming, during jumpTo.
* Intended to be overridden
*
* @param locus
*/
private void beforeScaleZoom(Locus locus) {
calculateMaxZoom();
}
/**
* Calculate the zoom level given start/end in bp.
* Doesn't change anything
*
* @param start
* @param end
* @return
*/
private int calculateZoom(double start, double end) {
return (int) Math.round((Math.log((getChromosomeLength() / (end - start)) * (((double) widthInPixels) / binsPerTile)) / Globals.log2));
}
private static int getChromosomeLength(String chrName) {
Genome genome = getGenome();
if (genome == null) {
return 1;
}
if (chrName.equals("All")) {
// Genome coordinates are in kb => divde by 1000
return (int) (genome.getNominalLength() / 1000);
} else {
Chromosome chromosome = genome.getChromosome(chrName);
if (chromosome == null) {
log.error("Null chromosome: " + chrName);
if (genome.getChromosomes().size() == 0) {
return 1;
} else {
return genome.getChromosomes().iterator().next().getLength();
}
}
return chromosome.getLength();
}
}
public void setInsertions(List<InsertionManager.Insertion> insertions) {
this.insertions = insertions;
}
public List<InsertionManager.Insertion> getInsertions() {
return insertions;
}
private static Genome getGenome() {
return GenomeManager.getInstance().getCurrentGenome();
}
}
|
package org.ensembl.healthcheck;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.TreeSet;
import java.util.logging.Handler;
import java.util.logging.Level;
import org.ensembl.healthcheck.testcase.EnsTestCase;
import org.ensembl.healthcheck.util.ConnectionPool;
import org.ensembl.healthcheck.util.LogFormatter;
import org.ensembl.healthcheck.util.MyStreamHandler;
import org.ensembl.healthcheck.util.Utils;
/**
* TestRunner optimised for outputting results to HTML.
*/
public class WebTestRunner extends TestRunner implements Reporter {
private boolean debug = false;
private String configFile = "web.properties";
private long testStartTime, appStartTime;
private static String TIMINGS_FILE = "timings.txt";
/**
* Main run method.
*
* @param args
* Command-line arguments.
*/
private void run(String[] args) {
// deleteTimingsFile();
appStartTime = System.currentTimeMillis();
ReportManager.setReporter(this);
parseCommandLine(args);
setupLogging();
Utils.readPropertiesFileIntoSystem(PROPERTIES_FILE);
Utils.readPropertiesFileIntoSystem(configFile);
parseProperties();
groupsToRun = getGroupsFromProperties();
List databaseRegexps = getDatabasesFromProperties();
outputLevel = setOutputLevelFromProperties();
TestRegistry testRegistry = new TestRegistry();
DatabaseRegistry databaseRegistry = new DatabaseRegistry(databaseRegexps, null, null);
if (databaseRegistry.getAll().length == 0) {
logger.warning("Warning: no database names matched any of the database regexps given");
}
runAllTests(databaseRegistry, testRegistry, false);
printOutput();
ConnectionPool.closeAll();
} // run
/**
* Command-line entry point.
*
* @param args
* Command line args.
*/
public static void main(String[] args) {
new WebTestRunner().run(args);
} // main
private void parseCommandLine(String[] args) {
for (int i = 0; i < args.length; i++) {
if (args[i].equals("-h")) {
printUsage();
System.exit(0);
} else if (args[i].equals("-config")) {
configFile = args[++i];
} else if (args[i].equals("-debug")) {
debug = true;
logger.finest("Running in debug mode");
}
}
} // parseCommandLine
private void printUsage() {
System.out.println("\nUsage: WebTestRunner {options} \n");
System.out.println("Options:");
System.out.println(" -config <file> Properties file to use instead of web.properties");
System.out.println(" -h This message.");
System.out.println(" -debug Print debugging info");
System.out.println();
System.out.println("All configuration information is read from the files database.properties and web.properties. ");
System.out.println("web.properties should contain the following properties:");
System.out.println(" webtestrunner.groups= A comma-separated list of the groups, or individual tests, to run");
System.out.println(" webtestrunner.databases= A comma-separated list of database regexps to match");
System.out.println(" webtestrunner.file= The name of the output file to write to ");
System.out
.println(" webtestrunner.outputlevel= How much output to write. Should be one of all, info, warning, correct or problem");
}
private void setupLogging() {
// stop parent logger getting the message
logger.setUseParentHandlers(false);
Handler myHandler = new MyStreamHandler(System.out, new LogFormatter());
logger.addHandler(myHandler);
logger.setLevel(Level.WARNING);
if (debug) {
logger.setLevel(Level.FINEST);
}
} // setupLogging
// Implementation of Reporter interface
/**
* Called when a message is to be stored in the report manager.
*
* @param reportLine
* The message to store.
*/
public void message(ReportLine reportLine) {
}
/**
* Called just before a test case is run.
*
* @param testCase
* The test case about to be run.
* @param dbre
* The database which testCase is to be run on, or null of no/several
* databases.
*/
public void startTestCase(EnsTestCase testCase, DatabaseRegistryEntry dbre) {
testStartTime = System.currentTimeMillis();
}
/**
* Should be called just after a test case has been run.
*
* @param testCase
* The test case that was run.
* @param result
* The result of testCase.
* @param dbre
* The database which testCase was run on, or null of no/several
* databases.
*/
public void finishTestCase(EnsTestCase testCase, boolean result, DatabaseRegistryEntry dbre) {
long duration = System.currentTimeMillis() - testStartTime;
String str = duration + "\t";
if (dbre != null) {
str += dbre.getName() + "\t";
}
str += testCase.getShortTestName() + "\t";
str += Utils.formatTimeString(duration);
Utils.writeStringToFile(TIMINGS_FILE, str, true, true);
}
private void parseProperties() {
if (System.getProperty("webtestrunner.groups") == null) {
System.err.println("No tests or groups specified in " + configFile);
System.exit(1);
}
if (System.getProperty("webtestrunner.databases") == null) {
System.err.println("No databases specified in " + configFile);
System.exit(1);
}
if (System.getProperty("webtestrunner.file") == null) {
System.err.println("No output file specified in " + configFile);
System.exit(1);
}
}
/**
* Get a list of test groups by parsing the appropriate property.
*
* @return the list of group or test names.
*/
private List getGroupsFromProperties() {
String[] groups = System.getProperty("webtestrunner.groups").split(",");
return Arrays.asList(groups);
}
/**
* Get a list of databases by parsing the appropriate property.
*
* @return The list of database names or patterns.
*/
private List getDatabasesFromProperties() {
String[] dbs = System.getProperty("webtestrunner.databases").split(",");
return Arrays.asList(dbs);
}
private int setOutputLevelFromProperties() {
String lstr = System.getProperty("webtestrunner.outputlevel").toLowerCase();
if (lstr.equals("all")) {
outputLevel = ReportLine.ALL;
} else if (lstr.equals("none")) {
outputLevel = ReportLine.NONE;
} else if (lstr.equals("problem")) {
outputLevel = ReportLine.PROBLEM;
} else if (lstr.equals("correct")) {
outputLevel = ReportLine.CORRECT;
} else if (lstr.equals("warning")) {
outputLevel = ReportLine.WARNING;
} else if (lstr.equals("info")) {
outputLevel = ReportLine.INFO;
} else {
System.err.println("Output level " + lstr + " not recognised; using 'all'");
}
return outputLevel;
}
/**
* Print formatted output held in outputBuffer to file specified in System
* property file.
*/
private void printOutput() {
String file = System.getProperty("webtestrunner.file");
try {
PrintWriter pw = new PrintWriter(new FileOutputStream(file));
printHeader(pw);
printNavigation(pw);
printExecutiveSummary(pw);
printSummaryByDatabase(pw);
printSummaryByTest(pw);
printReportsByDatabase(pw);
printReportsByTest(pw);
printFooter(pw);
pw.close();
} catch (Exception e) {
System.err.println("Error writing to " + file);
e.printStackTrace();
}
}
private void printHeader(PrintWriter pw) {
print(pw, "<html>");
print(pw, "<head>");
print(pw, "<style type=\"text/css\" media=\"all\">");
print(pw, "@import url(http:
print(pw, "@import url(http:
print(pw, "#page ul li { list-style-type:none; list-style-image: none; margin-left: -2em }");
print(pw, "</style>");
print(pw, "<title>" + System.getProperty("webtestrunner.title") + "</title>");
print(pw, "</head>");
print(pw, "<body>");
print(pw, "<div id='page'><div id='i1'><div id='i2'><div class='sptop'> </div>");
print(pw, "<div id='release'>" + System.getProperty("webtestrunner.title") + "</div>");
print(pw, "<hr>");
}
private void printReportsByDatabase(PrintWriter pw) {
print(pw, "<h2>Detailed reports by database</h2>");
Map reportsByDB = ReportManager.getAllReportsByDatabase(outputLevel);
TreeSet dbs = new TreeSet(reportsByDB.keySet());
Iterator it = dbs.iterator();
while (it.hasNext()) {
String database = (String) it.next();
List reports = (List) reportsByDB.get(database);
Iterator it2 = reports.iterator();
if (!reports.isEmpty()) {
String link = "<a name=\"" + database + "\">";
print(pw, "<h3 class='boxed'>" + link + database + "</a></h3>");
print(pw, "<p>");
String lastTest = "";
while (it2.hasNext()) {
ReportLine line = (ReportLine) it2.next();
String test = line.getShortTestCaseName();
if (!lastTest.equals("") && !test.equals(lastTest)) {
print(pw, "</p><p>");
}
lastTest = test;
String linkTarget = "<a name=\"" + database + ":" + test + "\"></a> ";
String s = linkTarget + getFontForReport(line) + "<strong>" + test + ": </strong>" + line.getMessage() + "</font>"
+ "<br>";
print(pw, s);
} // while it2
print(pw, "</p>");
}
} // while it
print(pw, "<hr>");
}
private void printReportsByTest(PrintWriter pw) {
print(pw, "<h2>Detailed reports by test case</h2>");
Map reportsByTC = ReportManager.getAllReportsByTestCase(outputLevel);
TreeSet dbs = new TreeSet(reportsByTC.keySet());
Iterator it = dbs.iterator();
while (it.hasNext()) {
String test = (String) it.next();
List reports = (List) reportsByTC.get(test);
Iterator it2 = reports.iterator();
if (!reports.isEmpty()) {
String link = "<a name=\"" + test + "\">";
print(pw, "<h3 class='boxed'>" + link + test + "</a></h3>");
print(pw, "<p>");
String lastDB = "";
while (it2.hasNext()) {
ReportLine line = (ReportLine) it2.next();
String database = line.getDatabaseName();
if (!lastDB.equals("") && !database.equals(lastDB)) {
print(pw, "</p><p>");
}
lastDB = database;
String linkTarget = "<a name=\"" + line.getShortTestCaseName() + ":" + database + "\"></a> ";
String s = linkTarget + getFontForReport(line) + "<strong>" + database + ": </strong>" + line.getMessage() + "</font>"
+ "<br>";
print(pw, s);
} // while it2
print(pw, "</p>");
}
} // while it
print(pw, "<hr>");
}
private String getFontForReport(ReportLine line) {
String s1 = "";
switch (line.getLevel()) {
case (ReportLine.PROBLEM):
s1 = "<font color='red'>";
break;
case (ReportLine.WARNING):
s1 = "<font color='black'>";
break;
case (ReportLine.INFO):
s1 = "<font color='grey'>";
break;
case (ReportLine.CORRECT):
s1 = "<font color='green'>";
break;
default:
s1 = "<font color='black'>";
}
return s1;
}
private void printFooter(PrintWriter pw) {
long runTime = System.currentTimeMillis() - appStartTime;
String runStr = Utils.formatTimeString(runTime);
print(pw, "<p>Test run was started at " + new Date(appStartTime).toString() + " and finished at " + new Date().toString()
+ "<br>");
print(pw, " Run time " + runStr + "</p>");
print(pw, "<h4>Configuration used:</h4>");
print(pw, "<pre>");
print(pw, "Tests/groups run: " + System.getProperty("webtestrunner.groups") + "<br>");
print(pw, "Database host: " + System.getProperty("host") + ":" + System.getProperty("port") + "<br>");
print(pw, "Database names: " + System.getProperty("webtestrunner.databases") + "<br>");
print(pw, "Output file: " + System.getProperty("webtestrunner.file") + "<br>");
print(pw, "Output level: " + System.getProperty("webtestrunner.outputlevel") + "<br>");
print(pw, "</pre>");
print(pw, "</div>");
print(pw, "</body>");
print(pw, "</html>");
print(pw, "<hr>");
}
private void print(PrintWriter pw, String s) {
pw.write(s + "\n");
}
private void printSummaryByDatabase(PrintWriter pw) {
print(pw, "<h2>Summary by database</h2>");
print(pw, "<p><table class='ss'>");
print(pw, "<tr><th>Database</th><th>Passed</th><th>Failed</th></tr>");
Map reportsByDB = ReportManager.getAllReportsByDatabase();
TreeSet databases = new TreeSet(reportsByDB.keySet());
Iterator it = databases.iterator();
while (it.hasNext()) {
String database = (String) it.next();
String link = "<a href=\"#" + database + "\">";
int[] passesAndFails = ReportManager.countPassesAndFailsDatabase(database);
String s = (passesAndFails[1] == 0) ? passFont() : failFont();
String[] t = { link + s + database + "</font></a>", passFont() + passesAndFails[0] + "</font>",
failFont() + passesAndFails[1] + "</font>" };
printTableLine(pw, t);
}
print(pw, "</table></p>");
print(pw, "<hr>");
}
private void printSummaryByTest(PrintWriter pw) {
print(pw, "<h2>Summary by test</h2>");
print(pw, "<p><table class='ss'>");
print(pw, "<tr><th>Test</th><th>Passed</th><th>Failed</th></tr>");
Map reports = ReportManager.getAllReportsByTestCase();
TreeSet tests = new TreeSet(reports.keySet());
Iterator it = tests.iterator();
while (it.hasNext()) {
String test = (String) it.next();
String link = "<a href=\"#" + test + "\">";
int[] passesAndFails = ReportManager.countPassesAndFailsTest(test);
String s = (passesAndFails[1] == 0) ? passFont() : failFont();
String[] t = { link + s + test + "</font></a>", passFont() + passesAndFails[0] + "</font>",
failFont() + passesAndFails[1] + "</font>" };
printTableLine(pw, t);
}
print(pw, "</table></p>");
print(pw, "<hr>");
}
private void printExecutiveSummary(PrintWriter pw) {
print(pw, "<h2>Summary</h2>");
int[] result = ReportManager.countPassesAndFailsAll();
StringBuffer s = new StringBuffer();
s.append("<p><strong>");
s.append(passFont() + result[0] + "</font> tests passed and ");
s.append(failFont() + result[1] + "</font> failed out of a total of ");
s.append((result[0] + result[1]) + " tests run.</strong></p>");
print(pw, s.toString());
print(pw, "<hr>");
}
private void printTableLine(PrintWriter pw, String[] s) {
pw.write("<tr>");
for (int i = 0; i < s.length; i++) {
pw.write("<td>" + s[i] + "</td>");
}
pw.write("</tr>\n");
}
private void printNavigation(PrintWriter pw) {
print(pw, "<div id='related'><div id='related-box'>");
print(pw, "<h2>Results by database</h2>");
print(pw, "<ul>");
Map reportsByDB = ReportManager.getAllReportsByDatabase();
TreeSet databases = new TreeSet(reportsByDB.keySet());
Iterator it = databases.iterator();
while (it.hasNext()) {
String database = (String) it.next();
if (database.length() > 27) {
database = "<font size=-2>" + database + "</font>";
}
String link = "<a href=\"#" + database + "\">";
print(pw, "<li>" + link + database + "</a></li>");
}
print(pw, "</ul>");
print(pw, "<h2>Results by test</h2>");
print(pw, "<ul>");
Map reports = ReportManager.getAllReportsByTestCase();
TreeSet tests = new TreeSet(reports.keySet());
it = tests.iterator();
while (it.hasNext()) {
String test = (String) it.next();
String name = test.substring(test.lastIndexOf('.') + 1);
if (name.length() > 27) {
name = "<font size=-2>" + name + "</font>";
}
String link = "<a href=\"#" + test + "\">";
print(pw, "<li>" + link + name + "</a></li>");
}
print(pw, "</ul>");
print(pw, "</div></div>");
}
private String passFont() {
return "<font color='green' size=-1>";
}
private String failFont() {
return "<font color='red' size=-1>";
}
} // WebTestRunner
|
package org.exist.http.servlets;
import java.io.File;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.xml.transform.OutputKeys;
import org.exist.source.FileSource;
import org.exist.source.Source;
import org.exist.storage.DBBroker;
import org.exist.xmldb.CollectionImpl;
import org.exist.xmldb.XQueryService;
import org.exist.xquery.XPathException;
import org.exist.xquery.functions.request.RequestModule;
import org.exist.xquery.util.HTTPUtils;
import org.exist.xquery.value.Sequence;
import org.xmldb.api.DatabaseManager;
import org.xmldb.api.base.Collection;
import org.xmldb.api.base.CompiledExpression;
import org.xmldb.api.base.Database;
import org.xmldb.api.base.Resource;
import org.xmldb.api.base.ResourceIterator;
import org.xmldb.api.base.ResourceSet;
import org.xmldb.api.base.XMLDBException;
/**
* Servlet to generate HTML output from an XQuery file.
*
* The servlet responds to an URL pattern as specified in the
* WEB-INF/web.xml configuration file of the application. It will
* interpret the path with which it is called as leading to a valid
* XQuery file. The XQuery file is loaded, compiled and executed.
* Any output of the script is sent back to the client.
*
* The servlet accepts the following initialization parameters in web.xml:
*
* <table border="0">
* <tr><td>user</td><td>The user identity with which the script is executed.</td></tr>
* <tr><td>password</td><td>Password for the user.</td></tr>
* <tr><td>uri</td><td>A valid XML:DB URI leading to the root collection used to
* process the request.</td></tr>
* <tr><td>encoding</td><td>The character encoding used for XQuery files.</td></tr>
* <tr><td>container-encoding</td><td>The character encoding used by the servlet
* container.</td></tr>
* <tr><td>form-encoding</td><td>The character encoding used by parameters posted
* from HTML forms.</td></tr>
* </table>
*
* User identity and password may also be specified through the HTTP session attributes
* "user" and "password". These attributes will overwrite any other settings.
*
* @author Wolfgang Meier (wolfgang@exist-db.org)
*/
public class XQueryServlet extends HttpServlet {
public final static String DEFAULT_USER = "guest";
public final static String DEFAULT_PASS = "guest";
public final static String DEFAULT_URI = "xmldb:exist://" + DBBroker.ROOT_COLLECTION;
public final static String DEFAULT_ENCODING = "UTF-8";
public final static String DEFAULT_CONTENT_TYPE = "text/html";
public final static String DRIVER = "org.exist.xmldb.DatabaseImpl";
private String user = null;
private String password = null;
private String collectionURI = null;
private String containerEncoding = null;
private String formEncoding = null;
private String encoding = null;
private String contentType = null;
/* (non-Javadoc)
* @see javax.servlet.GenericServlet#init(javax.servlet.ServletConfig)
*/
public void init(ServletConfig config) throws ServletException {
super.init(config);
user = config.getInitParameter("user");
if(user == null)
user = DEFAULT_USER;
password = config.getInitParameter("password");
if(password == null)
password = DEFAULT_PASS;
collectionURI = config.getInitParameter("uri");
if(collectionURI == null)
collectionURI = DEFAULT_URI;
formEncoding = config.getInitParameter("form-encoding");
if(formEncoding == null)
formEncoding = DEFAULT_ENCODING;
log("form-encoding = " + formEncoding);
containerEncoding = config.getInitParameter("container-encoding");
if(containerEncoding == null)
containerEncoding = DEFAULT_ENCODING;
log("container-encoding = " + containerEncoding);
encoding = config.getInitParameter("encoding");
if(encoding == null)
encoding = DEFAULT_ENCODING;
log("encoding = " + encoding);
contentType = config.getInitParameter("content-type");
if(contentType == null)
contentType = DEFAULT_CONTENT_TYPE;
try {
Class driver = Class.forName(DRIVER);
Database database = (Database)driver.newInstance();
database.setProperty("create-database", "true");
DatabaseManager.registerDatabase(database);
} catch(Exception e) {
throw new ServletException("Failed to initialize database driver: " + e.getMessage(), e);
}
// // set exist.home property if not set
// String homeDir = System.getProperty("exist.home");
// if(homeDir == null) {
// homeDir = config.getServletContext().getRealPath("/");
// System.setProperty("exist.home", homeDir);
}
/* (non-Javadoc)
* @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
process(request, response);
}
/* (non-Javadoc)
* @see javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
process(request, response);
}
/* (non-Javadoc)
* @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
*/
protected void process(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
ServletOutputStream sout = response.getOutputStream();
PrintWriter output =
new PrintWriter(new OutputStreamWriter(sout, formEncoding));
response.setContentType(contentType + "; charset=" + formEncoding);
response.addHeader( "pragma", "no-cache" );
response.addHeader( "Cache-Control", "no-cache" );
String path = request.getPathTranslated();
if(path == null) {
path = request.getRequestURI().substring(request.getContextPath().length());
int p = path.lastIndexOf(';');
if(p > -1)
path = path.substring(0, p);
path = getServletContext().getRealPath(path);
}
File f = new File(path);
if(!f.canRead()) {
sendError(output, "Cannot read source file", path);
return;
}
// Added by Igor Abade (igoravl@cosespseguros.com.br)
String contentType = this.contentType;
try {
contentType = getServletContext().getMimeType(path);
if (contentType == null)
contentType = this.contentType;
}
catch (Throwable e) {
contentType = this.contentType;
}
finally {
if (contentType.startsWith("text/") || (contentType.endsWith("+xml")))
contentType += ";charset=" + formEncoding;
response.setContentType(contentType );
}
String baseURI = request.getRequestURI();
int p = baseURI.lastIndexOf('/');
if(p > -1)
baseURI = baseURI.substring(0, p);
String moduleLoadPath = getServletContext().getRealPath(baseURI.substring(request.getContextPath().length()));
String actualUser = null;
String actualPassword = null;
HttpSession session = request.getSession();
if(session != null && request.isRequestedSessionIdValid()) {
actualUser = getSessionAttribute(session, "user");
actualPassword = getSessionAttribute(session, "password");
}
if(actualUser == null) actualUser = user;
if(actualPassword == null) actualPassword = password;
try {
Collection collection = DatabaseManager.getCollection(collectionURI, actualUser, actualPassword);
XQueryService service = (XQueryService)
collection.getService("XQueryService", "1.0");
service.setProperty("base-uri", baseURI);
service.setModuleLoadPath(moduleLoadPath);
String prefix = RequestModule.PREFIX;
//service.setNamespace(prefix, RequestModule.NAMESPACE_URI);
if(!((CollectionImpl)collection).isRemoteCollection()) {
service.declareVariable(prefix + ":request",
new HttpRequestWrapper(request, formEncoding, containerEncoding));
service.declareVariable(prefix + ":response", new HttpResponseWrapper(response));
service.declareVariable(prefix + ":session", new HttpSessionWrapper(session));
}
Source source = new FileSource(f, encoding, true);
ResourceSet result = service.execute(source);
String mediaType = service.getProperty(OutputKeys.MEDIA_TYPE);
if (mediaType != null) {
if (!response.isCommitted())
response.setContentType(mediaType + "; charset=" + formEncoding);
}
for(ResourceIterator i = result.getIterator(); i.hasMoreResources(); ) {
Resource res = i.nextResource();
output.println(res.getContent().toString());
}
} catch (XMLDBException e) {
log(e.getMessage(), e);
sendError(output, e.getMessage(), e);
}
output.flush();
}
private String getSessionAttribute(HttpSession session, String attribute) {
Object obj = session.getAttribute(attribute);
if(obj == null)
return null;
if(obj instanceof Sequence)
try {
return ((Sequence)obj).getStringValue();
} catch (XPathException e) {
return null;
}
return obj.toString();
}
private void sendError(PrintWriter out, String message, XMLDBException e) {
out.print("<html><head>");
out.print("<title>XQueryServlet Error</title>");
out.print("<link rel=\"stylesheet\" type=\"text/css\" href=\"error.css\"></head>");
out.print("<body><div id=\"container\"><h1>Error found</h1>");
Throwable t = e.getCause();
if (t instanceof XPathException) {
XPathException xe = (XPathException) t;
out.println(xe.getMessageAsHTML());
} else {
out.print("<h2>Message:");
out.print(message);
out.print("</h2>");
}
if(t!=null){
// t can be null
out.print(HTTPUtils.printStackTraceHTML(t));
}
out.print("</div></body></html>");
}
private void sendError(PrintWriter out, String message, String description) {
out.print("<html><head>");
out.print("<title>XQueryServlet Error</title>");
out.print("<link rel=\"stylesheet\" type=\"text/css\" href=\"error.css\"></head>");
out.println("<body><h1>Error found</h1>");
out.print("<div class='message'><b>Message: </b>");
out.print(message);
out.print("</div><div class='description'>");
out.print(description);
out.print("</div></body></html>");
out.flush();
}
private static final class CachedQuery {
long lastModified;
String sourcePath;
CompiledExpression expression;
public CachedQuery(File sourceFile, CompiledExpression expression) {
this.sourcePath = sourceFile.getAbsolutePath();
this.lastModified = sourceFile.lastModified();
this.expression = expression;
}
public boolean isValid() {
File f = new File(sourcePath);
if(f.lastModified() > lastModified)
return false;
return true;
}
public CompiledExpression getExpression() {
return expression;
}
}
}
|
/*
* $Id: FetchTimeExporter.java,v 1.7 2014-01-08 20:37:47 fergaloy-sf Exp $
*/
/**
* Periodically exports fetch times of recently added metadata items.
*
* @version 1.0
*/
package org.lockss.exporter;
import static org.lockss.db.DbManager.*;
import static org.lockss.metadata.MetadataManager.*;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import org.lockss.app.LockssDaemon;
import org.lockss.config.ConfigManager;
import org.lockss.config.Configuration;
import org.lockss.config.CurrentConfig;
import org.lockss.daemon.Cron;
import org.lockss.db.DbException;
import org.lockss.db.DbManager;
import org.lockss.metadata.MetadataManager;
import org.lockss.util.FileUtil;
import org.lockss.util.IOUtil;
import org.lockss.util.Logger;
import org.lockss.util.NumberUtil;
import org.lockss.util.StringUtil;
import org.lockss.util.TimeBase;
public class FetchTimeExporter {
/**
* Prefix for the export configuration entries.
*/
public static final String PREFIX = Configuration.PREFIX + "export.";
/**
* Frequency of fetch time export operations.
*/
public static final String PARAM_FETCH_TIME_EXPORT_TASK_FREQUENCY =
PREFIX + "fetchTimeExportFrequency";
/**
* Default value of the frequency of fetch time export operations.
*/
public static final String DEFAULT_FETCH_TIME_EXPORT_TASK_FREQUENCY =
"hourly";
/**
* Name of this server for the purpose of assigning to it the fetch time
* export output.
* <p />
* Defaults to the networking host name.
*/
public static final String PARAM_SERVER_NAME =
PREFIX + "fetchTimeExportServerName";
/**
* Name of the directory used to store the fetch time export output files.
* <p />
* Defaults to <code>fetchTime</code>.
*/
public static final String PARAM_FETCH_TIME_EXPORT_OUTPUTDIR = PREFIX
+ "fetchTimeExportDirectoryName";
/**
* Default value of the directory used to store the fetch time export output
* files.
*/
public static final String DEFAULT_FETCH_TIME_EXPORT_OUTPUTDIR = "fetchTime";
/**
* Name of the key used to store in the database the identifier of the last
* metadata item for which the data has been exported.
* <p />
* Defaults to <code>export_fetch_time_md_item_seq</code>.
*/
public static final String PARAM_FETCH_TIME_EXPORT_LAST_ITEM_LABEL =
PREFIX + "fetchTimeExportLastMdItemSeqLabel";
/**
* Default value of the key used to store in the database the identifier of
* the last metadata item for which the data has been exported.
*/
public static final String DEFAULT_FETCH_TIME_EXPORT_LAST_ITEM_LABEL =
"export_fetch_time_md_item_seq";
/**
* The maximum number of metadata items to process in one database read.
* <p />
* Defaults to <code>100</code>.
*/
public static final String PARAM_MAX_NUMBER_OF_EXPORTED_ITEMS_READ = PREFIX
+ "fetchTimeExportMaxNumberOfExportedItemsRead";
/**
* Default value of the maximum number of metadata items to process in one
* database read.
*/
public static final int DEFAULT_MAX_NUMBER_OF_EXPORTED_ITEMS_READ = 100;
/**
* The maximum number of metadata items to write to one file.
* <p />
* Defaults to <code>100000</code>.
*/
public static final String PARAM_MAX_NUMBER_OF_EXPORTED_ITEMS_PER_FILE =
PREFIX + "fetchTimeExportMaxNumberOfExportedItemsPerFile";
/**
* Default value of the maximum number of metadata items to write to one file.
*/
public static final int DEFAULT_MAX_NUMBER_OF_EXPORTED_ITEMS_PER_FILE =
100000;
private static final Logger log = Logger.getLogger(FetchTimeExporter.class);
// Query to get the identifier of the last metadata item for which the data
// has been exported.
private static final String GET_LAST_EXPORTED_MD_ITEM_QUERY = "select "
+ LAST_VALUE_COLUMN
+ " from " + LAST_RUN_TABLE
+ " where " + LABEL_COLUMN + " = ?";
// Query to update the identifier of the last metadata item for which the data
// has been exported.
private static final String INSERT_LAST_EXPORTED_MD_ITEM_QUERY = "insert "
+ "into " + LAST_RUN_TABLE
+ " (" + LABEL_COLUMN
+ "," + LAST_VALUE_COLUMN
+ ") values (?,?)";
// Query to get the data to be exported.
private static final String GET_EXPORT_FETCH_TIME_QUERY = "select "
+ "pr." + PUBLISHER_NAME_COLUMN
+ ", pl." + PLUGIN_ID_COLUMN
+ ", pl." + IS_BULK_CONTENT_COLUMN
+ ", min1." + NAME_COLUMN + " as PUBLICATION_NAME"
+ ", mit." + TYPE_NAME_COLUMN
+ ", mi2." + MD_ITEM_SEQ_COLUMN
+ ", min2." + NAME_COLUMN + " as ITEM_TITLE"
+ ", mi2." + DATE_COLUMN
+ ", mi2." + FETCH_TIME_COLUMN
+ ", a." + AU_KEY_COLUMN
+ ", u." + URL_COLUMN
+ ", d." + DOI_COLUMN
+ ", is1." + ISSN_COLUMN + " as " + P_ISSN_TYPE
+ ", is2." + ISSN_COLUMN + " as " + E_ISSN_TYPE
+ ", ib1." + ISBN_COLUMN + " as " + P_ISBN_TYPE
+ ", ib2." + ISBN_COLUMN + " as " + E_ISBN_TYPE
+ " from " + PUBLISHER_TABLE + " pr"
+ "," + PLUGIN_TABLE + " pl"
+ "," + PUBLICATION_TABLE + " pn"
+ "," + MD_ITEM_NAME_TABLE + " min1"
+ "," + MD_ITEM_NAME_TABLE + " min2"
+ "," + MD_ITEM_TYPE_TABLE + " mit"
+ "," + AU_MD_TABLE + " am"
+ "," + AU_TABLE + " a"
+ "," + URL_TABLE + " u"
+ "," + MD_ITEM_TABLE + " mi2"
+ " left outer join " + DOI_TABLE + " d"
+ " on mi2." + MD_ITEM_SEQ_COLUMN + " = d." + MD_ITEM_SEQ_COLUMN
+ " left outer join " + ISSN_TABLE + " is1"
+ " on mi2." + PARENT_SEQ_COLUMN + " = is1." + MD_ITEM_SEQ_COLUMN
+ " and is1." + ISSN_TYPE_COLUMN + " = '" + P_ISSN_TYPE + "'"
+ " left outer join " + ISSN_TABLE + " is2"
+ " on mi2." + PARENT_SEQ_COLUMN + " = is2." + MD_ITEM_SEQ_COLUMN
+ " and is2." + ISSN_TYPE_COLUMN + " = '" + E_ISSN_TYPE + "'"
+ " left outer join " + ISBN_TABLE + " ib1"
+ " on mi2." + PARENT_SEQ_COLUMN + " = ib1." + MD_ITEM_SEQ_COLUMN
+ " and ib1." + ISBN_TYPE_COLUMN + " = '" + P_ISBN_TYPE + "'"
+ " left outer join " + ISBN_TABLE + " ib2"
+ " on mi2." + PARENT_SEQ_COLUMN + " = ib2." + MD_ITEM_SEQ_COLUMN
+ " and ib2." + ISBN_TYPE_COLUMN + " = '" + E_ISBN_TYPE + "'"
+ " where pr." + PUBLISHER_SEQ_COLUMN + " = pn." + PUBLISHER_SEQ_COLUMN
+ " and pn." + MD_ITEM_SEQ_COLUMN + " = min1." + MD_ITEM_SEQ_COLUMN
+ " and pn." + MD_ITEM_SEQ_COLUMN + " = mi2." + PARENT_SEQ_COLUMN
+ " and mi2." + MD_ITEM_SEQ_COLUMN + " = min2." + MD_ITEM_SEQ_COLUMN
+ " and mi2." + MD_ITEM_TYPE_SEQ_COLUMN
+ " = mit." + MD_ITEM_TYPE_SEQ_COLUMN
+ " and mi2." + AU_MD_SEQ_COLUMN + " = am." + AU_MD_SEQ_COLUMN
+ " and am." + AU_SEQ_COLUMN + " = a." + AU_SEQ_COLUMN
+ " and a." + PLUGIN_SEQ_COLUMN + " = pl." + PLUGIN_SEQ_COLUMN
+ " and mi2." + MD_ITEM_SEQ_COLUMN + " = u." + MD_ITEM_SEQ_COLUMN
+ " and u." + FEATURE_COLUMN + " = '"
+ MetadataManager.ACCESS_URL_FEATURE + "'"
+ " and " + "mi2." + MD_ITEM_SEQ_COLUMN + " > ?"
+ " order by mi2." + MD_ITEM_SEQ_COLUMN;
// Query to update the identifier of the last metadata item for which the data
// has been exported.
private static final String UPDATE_LAST_EXPORTED_MD_ITEM_SEQ_QUERY = "update "
+ LAST_RUN_TABLE
+ " set " + LAST_VALUE_COLUMN + " = ?"
+ " where " + LABEL_COLUMN + " = ?";
// The format of a date as required by the export output file name.
private static final SimpleDateFormat dateFormat = new SimpleDateFormat(
"yyyy-MM-dd-HH-mm-ss");
private static final String SEPARATOR = "\t";
private final DbManager dbManager;
private final FetchTimeExportManager exportManager;
// The name of the server for the purpose of assigning to it the fetch time
// export output.
private String serverName = null;
// The directory where the fetch time export output files reside.
private File outputDir = null;
// The key used to store in the database the identifier of the last metadata
// item for which the data has been exported.
private String lastMdItemSeqLabel = null;
// The maximum number of metadata items to process in one database read.
private int maxNumberOfExportedItemsRead =
DEFAULT_MAX_NUMBER_OF_EXPORTED_ITEMS_READ;
// The maximum number of metadata items to write to one file.
private int maxNumberOfExportedItemsPerFile =
DEFAULT_MAX_NUMBER_OF_EXPORTED_ITEMS_PER_FILE;
// The version of the export file format.
private int exportVersion = 2;
/**
* Constructor.
*
* @param daemon
* A LockssDaemon with the application daemon.
*/
public FetchTimeExporter(LockssDaemon daemon) {
dbManager = daemon.getDbManager();
exportManager = daemon.getFetchTimeExportManager();
}
/**
* Provides the Cron task used to schedule the export.
*
* @return a Cron.Task with the task used to schedule the export.
*/
public Cron.Task getCronTask() {
return new FetchTimeExporterCronTask();
}
/**
* Performs the periodic task of exporting the fetch time data.
*
* @return <code>true</code> if the task can be considered executed,
* <code>false</code> otherwise.
*/
private boolean export() {
final String DEBUG_HEADER = "export(): ";
if (log.isDebug2()) log.debug2(DEBUG_HEADER + "Starting...");
// Do nothing more if the configuration failed.
if (!configure()) {
return true;
}
// Determine the report file name.
String fileName = getReportFileName();
if (log.isDebug2())
log.debug2(DEBUG_HEADER + "fileName = '" + fileName + "'.");
File exportFile = new File(outputDir, fileName + ".ignore");
if (log.isDebug2())
log.debug2(DEBUG_HEADER + "exportFile = '" + exportFile + "'.");
// Get the writer for this report.
PrintWriter writer = null;
try {
writer = new PrintWriter(new FileWriter(exportFile));
} catch (IOException ioe) {
log.error("Cannot get a PrintWriter for the export output file '"
+ exportFile + "'", ioe);
if (log.isDebug2()) log.debug2(DEBUG_HEADER + "Done.");
return true;
}
// Get a connection to the database.
Connection conn = null;
try {
conn = dbManager.getConnection();
} catch (DbException dbe) {
log.error("Cannot get a connection to the database", dbe);
IOUtil.safeClose(writer);
boolean deleted = exportFile.delete();
if (log.isDebug3()) log.debug3(DEBUG_HEADER + "deleted = " + deleted);
if (log.isDebug2()) log.debug2(DEBUG_HEADER + "Done.");
return true;
}
// An indication of whether any new data has been written out.
boolean newDataWritten = false;
try {
// Get the database version.
int dbVersion = dbManager.getDatabaseVersion(conn);
if (log.isDebug3()) log.debug3(DEBUG_HEADER + "dbVersion = " + dbVersion);
// Check whether the database version is appropriate.
if (dbVersion >= 10) {
// Yes: Perform the export.
newDataWritten = processExport(conn, exportFile, writer);
if (log.isDebug3())
log.debug3(DEBUG_HEADER + "newDataWritten = " + newDataWritten);
} else {
log.info("Database version is " + dbVersion
+ " (< 10). Export skipped.");
}
} catch (DbException dbe) {
log.error("Cannot export fetch times", dbe);
} finally {
DbManager.safeRollbackAndClose(conn);
IOUtil.safeClose(writer);
}
// Check whether any new data has been written out.
if (newDataWritten) {
// Yes: Rename the output file to mark it as available.
boolean renamed = exportFile.renameTo(new File(outputDir, fileName));
if (log.isDebug3()) log.debug3(DEBUG_HEADER + "renamed = " + renamed);
} else {
// No: Delete the empty file to avoid cluttering.
boolean deleted = exportFile.delete();
if (log.isDebug3()) log.debug3(DEBUG_HEADER + "deleted = " + deleted);
}
if (log.isDebug2()) log.debug2(DEBUG_HEADER + "Done.");
return true;
}
/**
* Handles configuration parameters.
*
* @return <code>true</code> if the configuration is successful,
* <code>false</code> otherwise.
*/
private boolean configure() {
final String DEBUG_HEADER = "configure(): ";
// Get the current configuration.
Configuration config = ConfigManager.getCurrentConfig();
// Do nothing more if the fetch time export subsystem is disabled.
if (!exportManager.isReady()) {
if (log.isDebug2())
log.debug2(DEBUG_HEADER + "Export of fetch times is disabled.");
return false;
}
// Get the name of the server for the purpose of assigning to it the fetch
// time export output.
try {
serverName = config.get(PARAM_SERVER_NAME,
InetAddress.getLocalHost().getHostName());
if (log.isDebug3())
log.debug3(DEBUG_HEADER + "serverName = '" + serverName + "'.");
} catch (UnknownHostException uhe) {
log.error("Export of fetch times is disabled: No server name.", uhe);
return false;
}
// Get the configured base directory for the export files.
File exportDir = exportManager.getExportDir();
if (log.isDebug3()) log.debug3(DEBUG_HEADER + "exportDir = '"
+ exportDir.getAbsolutePath() + "'.");
// Check whether it exists, creating it if necessary.
if (FileUtil.ensureDirExists(exportDir)) {
// Specify the configured directory where to put the fetch time export
// output files.
outputDir = new File(exportDir,
config.get(PARAM_FETCH_TIME_EXPORT_OUTPUTDIR,
DEFAULT_FETCH_TIME_EXPORT_OUTPUTDIR));
if (log.isDebug3()) log.debug3(DEBUG_HEADER + "outputDir = '"
+ outputDir.getAbsolutePath() + "'.");
// Check whether it exists, creating it if necessary.
if (!FileUtil.ensureDirExists(outputDir)) {
log.error("Error creating the fetch time export output directory '"
+ outputDir.getAbsolutePath() + "'.");
return false;
}
} else {
log.error("Error creating the export directory '"
+ exportDir.getAbsolutePath() + "'.");
return false;
}
// Get the label used to key in the database the identifier of the last
// metadata item for which the fetch time has been exported.
lastMdItemSeqLabel =
config.get(PARAM_FETCH_TIME_EXPORT_LAST_ITEM_LABEL,
DEFAULT_FETCH_TIME_EXPORT_LAST_ITEM_LABEL);
if (log.isDebug3()) log.debug3(DEBUG_HEADER + "lastMdItemSeqLabel = '"
+ lastMdItemSeqLabel + "'.");
// Get the maximum number of metadata items to process in one database read.
maxNumberOfExportedItemsRead =
config.getInt(PARAM_MAX_NUMBER_OF_EXPORTED_ITEMS_READ,
DEFAULT_MAX_NUMBER_OF_EXPORTED_ITEMS_READ);
if (log.isDebug3())
log.debug3(DEBUG_HEADER + "maxNumberOfExportedItemsRead = "
+ maxNumberOfExportedItemsRead + ".");
// Get the maximum number of metadata items to write to one file.
maxNumberOfExportedItemsPerFile =
config.getInt(PARAM_MAX_NUMBER_OF_EXPORTED_ITEMS_PER_FILE,
DEFAULT_MAX_NUMBER_OF_EXPORTED_ITEMS_PER_FILE);
if (log.isDebug3())
log.debug3(DEBUG_HEADER + "maxNumberOfExportedItemsPerFile = "
+ maxNumberOfExportedItemsPerFile + ".");
if (log.isDebug2()) log.debug2(DEBUG_HEADER + "Done.");
return true;
}
/**
* Provides the name of an export file.
*
* @return a String with the report file name. The format is
* 'fetch_time-serverName-yyyy-MM-dd-HH-mm-ss.tsv'.
*/
private String getReportFileName() {
return String.format("%s-%s-%s.%s", "fetch_time", serverName,
dateFormat.format(TimeBase.nowDate()), "tsv");
}
/**
* Exports the fetch time data.
*
* @param conn
* A Connection with the database connection to be used.
* @param exportFile
* A File where to export the data.
* @param writer
* A PrintWriter used to write the export file.
* @return <code>true</code> if any new data has been written out,
* <code>false</code> otherwise.
* @throws DbException
* if any problem occurred accessing the database.
*/
private boolean processExport(Connection conn, File exportFile,
PrintWriter writer) throws DbException {
final String DEBUG_HEADER = "processExport(): ";
if (log.isDebug2()) log.debug2(DEBUG_HEADER + "Starting...");
// An indication of whether any new data has been written out.
boolean newDataWritten = false;
// Get the identifier of the last metadata item for which the fetch time has
// been exported.
long lastMdItemSeq = getLastExportedMdItemSeq(conn);
if (log.isDebug3())
log.debug3(DEBUG_HEADER + "lastMdItemSeq = " + lastMdItemSeq);
// Export the data for metadata items newer than the last metadata item for
// which the fetch time has been exported and get the new value for the
// identifier of the last metadata item for which the fetch time has been
// exported.
long newLastMdItemSeq =
exportNewData(conn, lastMdItemSeq, exportFile, writer);
if (log.isDebug3())
log.debug3(DEBUG_HEADER + "newLastMdItemSeq = " + newLastMdItemSeq);
// Get the indication of whether any new data has been written out.
newDataWritten = newLastMdItemSeq > lastMdItemSeq;
if (log.isDebug3())
log.debug3(DEBUG_HEADER + "newDataWritten = " + newDataWritten);
// Check whether any new data has been written out.
if (newDataWritten) {
// Yes: Update in the database the identifier of the last metadata item
// for which the fetch time has been exported.
int count = updateLastExportedMdItemSeq(conn, newLastMdItemSeq);
if (log.isDebug3()) log.debug3(DEBUG_HEADER + "count = " + count);
DbManager.commitOrRollback(conn, log);
}
if (log.isDebug2())
log.debug2(DEBUG_HEADER + "newDataWritten = " + newDataWritten);
return newDataWritten;
}
/**
* Provides the identifier of the last metadata item for which the fetch time
* has been exported.
*
* @param conn
* A Connection with the database connection to be used.
* @return a long with the metadata item identifier.
* @throws DbException
* if any problem occurred accessing the database.
*/
private long getLastExportedMdItemSeq(Connection conn) throws DbException {
final String DEBUG_HEADER = "getLastExportedMdItemSeq(): ";
if (log.isDebug2()) log.debug2(DEBUG_HEADER + "Starting...");
if (conn == null) {
throw new DbException("Null connection");
}
long lastMdItemSeq = -1;
String lastMdItemSeqAsString = null;
PreparedStatement insertStmt = null;
PreparedStatement selectStmt = null;
ResultSet resultSet = null;
String sql = GET_LAST_EXPORTED_MD_ITEM_QUERY;
if (log.isDebug3()) log.debug3(DEBUG_HEADER + "sql = " + sql);
String message = "Cannot get the identifier of the last exported item";
try {
// Prepare the statement used to get from the database the identifier of
// the last metadata item for which the fetch time has been exported.
selectStmt = dbManager.prepareStatement(conn, sql);
selectStmt.setString(1, lastMdItemSeqLabel);
// Try to get the value from the database.
resultSet = dbManager.executeQuery(selectStmt);
// Check whether the value was found.
if (resultSet.next()) {
// Yes: Convert it from text to a numeric value.
lastMdItemSeqAsString = resultSet.getString(LAST_VALUE_COLUMN);
if (log.isDebug3()) log.debug3(DEBUG_HEADER + "lastMdItemSeqAsString = "
+ lastMdItemSeqAsString);
lastMdItemSeq = NumberUtil.parseLong(lastMdItemSeqAsString);
if (log.isDebug3())
log.debug3(DEBUG_HEADER + "lastMdItemSeq = " + lastMdItemSeq);
} else {
// No: Initialize it in the database because this is the first run.
sql = INSERT_LAST_EXPORTED_MD_ITEM_QUERY;
if (log.isDebug3()) log.debug3(DEBUG_HEADER + "sql = " + sql);
message = "Cannot initialize the identifier of the last exported item";
// Prepare the statement used to initialize the identifier of the last
// metadata item for which the fetch time has been exported.
insertStmt = dbManager.prepareStatement(conn, sql);
insertStmt.setString(1, lastMdItemSeqLabel);
insertStmt.setString(2, String.valueOf(lastMdItemSeq));
// Insert the record.
int count = dbManager.executeUpdate(insertStmt);
log.debug2(DEBUG_HEADER + "count = " + count);
DbManager.commitOrRollback(conn, log);
}
} catch (NumberFormatException nfe) {
log.error(message, nfe);
log.error("SQL = '" + sql + "'.");
log.error("lastMdItemSeqAsString = '" + lastMdItemSeqAsString + "'.");
} catch (SQLException sqle) {
log.error(message, sqle);
log.error("SQL = '" + sql + "'.");
throw new DbException(message, sqle);
} catch (DbException dbe) {
log.error(message, dbe);
log.error("SQL = '" + sql + "'.");
throw dbe;
} finally {
DbManager.safeCloseResultSet(resultSet);
DbManager.safeCloseStatement(selectStmt);
DbManager.safeCloseStatement(insertStmt);
}
if (log.isDebug2())
log.debug2(DEBUG_HEADER + "lastMdItemSeq = " + lastMdItemSeq);
return lastMdItemSeq;
}
/**
* Exports the data for metadata items newer than the last metadata item for
* which the fetch time has been exported.
*
* @param conn
* A Connection with the database connection to be used.
* @param lastMdItemSeq
* A long with the identifier of the last metadata item for which the
* fetch time has been exported.
* @param exportFile
* A File where to export the data.
* @param writer
* A PrintWriter used to write the export file.
* @return a long with the new value for the identifier of the last metadata
* item for which the fetch time has been exported.
* @throws DbException
* if any problem occurred accessing the database.
*/
private long exportNewData(Connection conn, long lastMdItemSeq,
File exportFile, PrintWriter writer) throws DbException {
final String DEBUG_HEADER = "exportNewData(): ";
if (log.isDebug2()) {
log.debug2(DEBUG_HEADER + "lastMdItemSeq = " + lastMdItemSeq);
log.debug2(DEBUG_HEADER + "exportFile = " + exportFile);
}
if (conn == null) {
throw new DbException("Null connection");
}
String message = "Cannot get the data to be exported";
String sql = GET_EXPORT_FETCH_TIME_QUERY;
if (log.isDebug3()) log.debug3(DEBUG_HEADER + "SQL = '" + sql + "'.");
int totalCount = 0;
boolean done = false;
// Loop while there are still more metadata item fetch times to be exported
// by this task.
while (!done) {
PreparedStatement getExportData = null;
ResultSet results = null;
int count = 0;
try {
// Prepare the statement used to get the data to be exported.
getExportData = dbManager.prepareStatement(conn, sql);
getExportData.setMaxRows(maxNumberOfExportedItemsRead);
getExportData.setLong(1, lastMdItemSeq);
// Get the data to be exported.
results = dbManager.executeQuery(getExportData);
// Loop through all the data to be exported.
while (results.next()) {
// Extract the fetch time.
Long fetchTime = results.getLong(FETCH_TIME_COLUMN);
if (log.isDebug3())
log.debug3(DEBUG_HEADER + "fetchTime = " + fetchTime);
// Check whether it has been initialized.
if (fetchTime >= 0) {
// Yes: Extract the other individual pieces of data to be exported.
String publisherName = results.getString(PUBLISHER_NAME_COLUMN);
if (log.isDebug3())
log.debug3(DEBUG_HEADER + "publisherName = " + publisherName);
String pluginId = results.getString(PLUGIN_ID_COLUMN);
if (log.isDebug3())
log.debug3(DEBUG_HEADER + "pluginId = " + pluginId);
boolean isBulkContent = results.getBoolean(IS_BULK_CONTENT_COLUMN);
if (log.isDebug3())
log.debug3(DEBUG_HEADER + "isBulkContent = " + isBulkContent);
String publicationName = results.getString("PUBLICATION_NAME");
if (log.isDebug3())
log.debug3(DEBUG_HEADER + "publicationName = " + publicationName);
String typeName = results.getString(TYPE_NAME_COLUMN);
if (log.isDebug3())
log.debug3(DEBUG_HEADER + "typeName = " + typeName);
String itemTitle = results.getString("ITEM_TITLE");
if (log.isDebug3())
log.debug3(DEBUG_HEADER + "itemTitle = " + itemTitle);
String date = results.getString(DATE_COLUMN);
if (log.isDebug3()) log.debug3(DEBUG_HEADER + "date = " + date);
String auKey = results.getString(AU_KEY_COLUMN);
if (log.isDebug3()) log.debug3(DEBUG_HEADER + "auKey = " + auKey);
String accessUrl = results.getString(URL_COLUMN);
if (log.isDebug3())
log.debug3(DEBUG_HEADER + "accessUrl = " + accessUrl);
String doi = results.getString(DOI_COLUMN);
if (log.isDebug3()) log.debug3(DEBUG_HEADER + "doi = " + doi);
String pIssn = results.getString(P_ISSN_TYPE);
if (log.isDebug3()) log.debug3(DEBUG_HEADER + "pIssn = " + pIssn);
String eIssn = results.getString(E_ISSN_TYPE);
if (log.isDebug3()) log.debug3(DEBUG_HEADER + "eIssn = " + eIssn);
String pIsbn = results.getString(P_ISBN_TYPE);
if (log.isDebug3()) log.debug3(DEBUG_HEADER + "pIsbn = " + pIsbn);
String eIsbn = results.getString(E_ISBN_TYPE);
if (log.isDebug3()) log.debug3(DEBUG_HEADER + "eIsbn = " + eIsbn);
// Create the line to be written to the output file.
StringBuilder sb = new StringBuilder();
sb.append(exportVersion).append(SEPARATOR)
.append(serverName).append(SEPARATOR)
.append(StringUtil.blankOutNlsAndTabs(publisherName))
.append(SEPARATOR)
.append(pluginId).append(SEPARATOR)
.append(auKey).append(SEPARATOR)
.append(isBulkContent).append(SEPARATOR)
.append(StringUtil.blankOutNlsAndTabs(publicationName))
.append(SEPARATOR)
.append(typeName).append(SEPARATOR)
.append(StringUtil.blankOutNlsAndTabs(itemTitle)).append(SEPARATOR)
.append(date).append(SEPARATOR)
.append(fetchTime).append(SEPARATOR)
.append(accessUrl).append(SEPARATOR)
.append(StringUtil.blankOutNlsAndTabs(doi)).append(SEPARATOR)
.append(StringUtil.blankOutNlsAndTabs(pIssn)).append(SEPARATOR)
.append(StringUtil.blankOutNlsAndTabs(eIssn)).append(SEPARATOR)
.append(StringUtil.blankOutNlsAndTabs(pIsbn)).append(SEPARATOR)
.append(StringUtil.blankOutNlsAndTabs(eIsbn));
// Write the line to the export output file.
writer.println(sb.toString());
// Check whether there were errors writing the line.
if (writer.checkError()) {
// Yes: Report the error.
writer.close();
message = "Encountered unrecoverable error writing " +
"export output file '" + exportFile + "'";
log.error(message);
throw new DbException(message);
}
writer.flush();
// Get the new value of the identifier of the last metadata item for
// which the fetch time has been exported.
lastMdItemSeq = results.getLong(MD_ITEM_SEQ_COLUMN);
if (log.isDebug3())
log.debug3(DEBUG_HEADER + "lastMdItemSeq = " + lastMdItemSeq);
// Count this exported metadata item fetch time.
count++;
}
}
if (log.isDebug3()) log.debug3(DEBUG_HEADER + "count = " + count);
// Increment the total count of exported metadata item fetch times.
totalCount += count;
if (log.isDebug3())
log.debug3(DEBUG_HEADER + "totalCount = " + totalCount);
// Determine whether this task has exported all the metadata item fetch
// times that needed to export.
done = count < maxNumberOfExportedItemsRead
|| totalCount >= maxNumberOfExportedItemsPerFile;
if (log.isDebug3()) log.debug3(DEBUG_HEADER + "done = " + done);
} catch (SQLException sqle) {
log.error(message, sqle);
log.error("SQL = '" + sql + "'.");
throw new DbException(message, sqle);
} catch (DbException dbe) {
log.error(message, dbe);
log.error("SQL = '" + sql + "'.");
throw dbe;
} finally {
DbManager.rollback(conn, log);
DbManager.safeCloseResultSet(results);
DbManager.safeCloseStatement(getExportData);
}
}
if (log.isDebug2())
log.debug2(DEBUG_HEADER + "lastMdItemSeq = " + lastMdItemSeq);
return lastMdItemSeq;
}
/**
* Updates in the database the value for the identifier of the last metadata
* item for which the fetch time has been exported.
*
* @param conn
* A Connection with the database connection to be used.
* @param lastMdItemSeq
* A long with the identifier of the last metadata item for which the
* fetch time has been exported.
* @return an int with the count of updated rows.
* @throws DbException
* if there are problems accessing the database.
*/
private int updateLastExportedMdItemSeq(Connection conn, long lastMdItemSeq)
throws DbException {
final String DEBUG_HEADER = "updateLastExportedMdItemSeq(): ";
if (log.isDebug2()) {
log.debug2(DEBUG_HEADER + "lastMdItemSeq = " + lastMdItemSeq);
}
String message =
"Cannot update the last item with exported data identifier";
String sql = UPDATE_LAST_EXPORTED_MD_ITEM_SEQ_QUERY;
if (log.isDebug3()) log.debug3(DEBUG_HEADER + "SQL = '" + sql + "'.");
PreparedStatement updateLastId = null;
int count = -1;
try {
// Prepare the statement used to update the identifier of the last
// metadata item for which the data has been exported.
updateLastId = dbManager.prepareStatement(conn, sql);
updateLastId.setString(1, String.valueOf(lastMdItemSeq));
updateLastId.setString(2, lastMdItemSeqLabel);
// Update the identifier of the last item with exported data.
count = dbManager.executeUpdate(updateLastId);
if (log.isDebug3()) log.debug3(DEBUG_HEADER + "count = " + count);
} catch (SQLException sqle) {
throw new DbException(message, sqle);
} finally {
DbManager.safeCloseStatement(updateLastId);
}
if (log.isDebug2()) log.debug2(DEBUG_HEADER + "count = " + count);
return count;
}
/**
* Provides the instant when this task needs to be executed based on the last
* execution and the frequency.
*
* @param lastTime
* A long with the instant of this task's last execution.
* @param frequency
* A String that represents the frequency.
* @return a long with the instant when this task needs to be executed.
*/
private long nextTimeA(long lastTime, String frequency) {
final String DEBUG_HEADER = "nextTime(): ";
log.debug2(DEBUG_HEADER + "lastTime = " + lastTime);
log.debug2(DEBUG_HEADER + "frequency = '" + frequency + "'.");
if ("hourly".equalsIgnoreCase(frequency)) {
return Cron.nextHour(lastTime);
} else if ("daily".equalsIgnoreCase(frequency)) {
return Cron.nextDay(lastTime);
} else if ("weekly".equalsIgnoreCase(frequency)) {
return Cron.nextWeek(lastTime);
} else {
return Cron.nextMonth(lastTime);
}
}
/**
* Implementation of the Cron task interface.
*/
public class FetchTimeExporterCronTask implements Cron.Task {
/**
* Performs the periodic task of exporting the fetch time data.
*
* @return <code>true</code> if the task can be considered executed,
* <code>false</code> otherwise.
*/
@Override
public boolean execute() {
return export();
}
/**
* Provides the identifier of the periodic task.
*
* @return a String with the identifier of the periodic task.
*/
@Override
public String getId() {
return "FetchTimeExporter";
}
/**
* Provides the instant when this task needs to be executed based on the
* last execution.
*
* @param lastTime
* A long with the instant of this task's last execution.
* @return a long with the instant when this task needs to be executed.
*/
@Override
public long nextTime(long lastTime) {
return nextTimeA(lastTime,
CurrentConfig.getParam(PARAM_FETCH_TIME_EXPORT_TASK_FREQUENCY,
DEFAULT_FETCH_TIME_EXPORT_TASK_FREQUENCY));
}
}
}
|
/*
* $Id: ProtocolException.java,v 1.4 2013-07-18 19:27:57 tlipkis Exp $
*/
package org.lockss.protocol;
import java.io.IOException;
/**
* ProtocolException: thrown if an LcapMessage is unparseable
* @author Claire Griffin
* @version 1.0
*/
public class ProtocolException extends IOException {
public ProtocolException() {
super();
}
public ProtocolException(String msg) {
super(msg);
}
public ProtocolException(Throwable cause) {
super(cause);
}
public ProtocolException(String msg, Throwable cause) {
super(msg, cause);
}
}
|
package org.mobop.flatseeker.model;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
public class StubFinder extends FlatFinder {
public Collection<Flat> Find(SearchParams params) {
ArrayList<Flat> flats = new ArrayList<Flat>();
SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy");
try {
if (params.city.toLowerCase().equals("neuchatel")) {
flats.add(new Flat(3.0, 67, 1200, 120, format.parse("01/03/2015"), "Neuchâtel", "Faubourg de l'Hopital", 2, 2));
flats.add(new Flat(3.5, 70, 1350, 120, format.parse("01/04/2015"), "Neuchâtel", "Avenue des Terreaux", 4, 1));
flats.add(new Flat(5.0, 130, 2100, 120, format.parse("01/02/2015"), "Neuchâtel", "Rue des Battieux", 7, 5));
} else if (params.city.toLowerCase().equals("lausanne")) {
flats.add(new Flat(5.0, 170, 2400, 280, format.parse("15/03/2015"), "Lausanne", "Rue St-Roch", 1, 3));
flats.add(new Flat(2.5, 57, 920, 60, format.parse("01/04/2015"), "Lausanne", "Avenue du Théatre", 56, 3));
flats.add(new Flat(1.5, 43, 650, 40, format.parse("15/02/2015"), "Lausanne", "Rue Caroline", 6, 2));
flats.add(new Flat(3.0, 62, 1400, 180, format.parse("01/02/2015"), "Neuchâtel", "Rue Centrale", 24, 8));
} else if (params.city.toLowerCase().equals("geneve")) {
flats.add(new Flat(3.5, 67, 1700, 210, format.parse("08/03/2015"), "Genêve", "Rue des Alpes", 3, 4));
}
} catch (ParseException e) {
e.printStackTrace();
}
return flats;
}
}
|
package org.myrobotlab.control.widget;
import java.awt.Component;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.text.DefaultCaret;
import org.apache.log4j.AppenderSkeleton;
import org.apache.log4j.PatternLayout;
import org.apache.log4j.spi.LoggingEvent;
import org.myrobotlab.framework.MRLListener;
import org.myrobotlab.framework.Message;
import org.myrobotlab.logging.LoggerFactory;
import org.myrobotlab.logging.LoggingFactory;
import org.myrobotlab.service.Runtime;
import org.myrobotlab.service.interfaces.ServiceInterface;
import org.slf4j.Logger;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.Appender;
import ch.qos.logback.core.Context;
import ch.qos.logback.core.LogbackException;
import ch.qos.logback.core.filter.Filter;
import ch.qos.logback.core.spi.FilterReply;
import ch.qos.logback.core.status.Status;
public class Console extends AppenderSkeleton implements Appender<ILoggingEvent> {
public JTextArea textArea = null;
public JScrollPane scrollPane = null;
private boolean logging = false;
// public int maxBuffer = 100000;
public Console() { // TODO boolean JFrame or component
textArea = new JTextArea();
scrollPane = new JScrollPane(textArea);
DefaultCaret caret = (DefaultCaret) textArea.getCaret();
caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);
}
/**
* Format and then append the loggingEvent to the stored JTextArea.
*/
@Override
public void append(LoggingEvent loggingEvent) {
if (logging) {
final String message = this.layout.format(loggingEvent);
// Append formatted message to textarea using the Swing Thread.
// SwingUtilities.invokeLater(new Runnable() { WOW, this was a nasty
// bug !
// public void run() {
textArea.append(message);
/*
* if (textArea.getText().length() > maxBuffer) {
* textArea.replaceRange("", 0, maxBuffer/10); // erase tenth }
*/
}
}
public void append(String msg) {
textArea.append(msg);
}
@Override
public void close() {
LoggingFactory.getInstance().removeAppender(this);
}
public JScrollPane getScrollPane() {
return scrollPane;
}
public Component getTextArea() {
return textArea;
}
@Override
public boolean requiresLayout() {
return true;
}
/**
* to begin logging call this function Log must not begin before the
* GUIService has finished drawing. For some reason, if log entries are
* written to a JScrollPane before the gui has completed the whole gui will
* tank
*
* by default logging is off
*/
public void startLogging() {
ch.qos.logback.classic.Logger root = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
root.setLevel(ch.qos.logback.classic.Level.INFO);
root.addAppender(this);
// PatternLayout layout = new PatternLayout("%-4r [%t] %-5p %c %x - %m%n");
// setLayout(layout);
// setName("ConsoleGUI");
// LoggingFactory.getInstance().addAppender(this);
logging = true;
}
public void stopLogging() {
LoggingFactory.getInstance().removeAppender(this);
logging = false;
}
@Override
public boolean isStarted() {
// logging interface stuff
return logging;
}
@Override
public void start() {
// TODO Auto-generated method stub
}
@Override
public void stop() {
// TODO Auto-generated method stub
}
@Override
public void addError(String arg0) {
// TODO Auto-generated method stub
}
@Override
public void addError(String arg0, Throwable arg1) {
// TODO Auto-generated method stub
}
@Override
public void addInfo(String info) {
// TODO: should we publish this info / invoke something?!
//invoke("publishLogEvent", info);
}
@Override
public void addInfo(String info, Throwable arg1) {
// TODO : should we invoke this publish method?
//invoke("publishLogEvent", info);
}
@Override
public void addStatus(Status arg0) {
// TODO Auto-generated method stub
}
@Override
public void addWarn(String arg0) {
// TODO Auto-generated method stub
}
@Override
public void addWarn(String arg0, Throwable arg1) {
// TODO Auto-generated method stub
}
@Override
public Context getContext() {
// TODO Auto-generated method stub
return null;
}
@Override
public void setContext(Context arg0) {
// TODO Auto-generated method stub
}
@Override
public void addFilter(Filter<ILoggingEvent> arg0) {
// TODO Auto-generated method stub
}
@Override
public void clearAllFilters() {
// TODO Auto-generated method stub
}
@Override
public List<Filter<ILoggingEvent>> getCopyOfAttachedFiltersList() {
// TODO Auto-generated method stub
return null;
}
@Override
public FilterReply getFilterChainDecision(ILoggingEvent arg0) {
// TODO Auto-generated method stub
return null;
}
@Override
public void doAppend(ILoggingEvent loggingEvent) throws LogbackException {
//append(loggingEvent);
if (logging) {
final String msg = String.format("[%s] %s", loggingEvent.getThreadName(), loggingEvent.toString()).trim();
// textarea not threadsafe, needs invokelater
EventQueue.invokeLater(new Runnable() {
//@Override
public void run() {
textArea.append(msg + "\n");
}
});
}
}
}
|
package org.objectweb.asm.tree.analysis;
import java.util.ArrayList;
import java.util.List;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.Type;
import org.objectweb.asm.tree.AbstractInsnNode;
import org.objectweb.asm.tree.IincInsnNode;
import org.objectweb.asm.tree.MethodInsnNode;
import org.objectweb.asm.tree.MultiANewArrayInsnNode;
import org.objectweb.asm.tree.VarInsnNode;
/**
* A symbolic execution stack frame. A stack frame contains a set of local
* variable slots, and an operand stack. Warning: long and double values are
* represented by <i>two</i> slots in local variables, and by <i>one</i> slot
* in the operand stack.
*
* @author Eric Bruneton
*/
public class Frame {
/**
* The local variables and operand stack of this frame.
*/
private Value[] values;
/**
* The number of local variables of this frame.
*/
private int locals;
/**
* The number of elements in the operand stack.
*/
private int top;
/**
* Constructs a new frame with the given size.
*
* @param nLocals the maximum number of local variables of the frame.
* @param nStack the maximum stack size of the frame.
*/
public Frame(final int nLocals, final int nStack) {
this.values = new Value[nLocals + nStack];
this.locals = nLocals;
}
/**
* Constructs a new frame that is identical to the given frame.
*
* @param src a frame.
*/
public Frame(final Frame src) {
this(src.locals, src.values.length - src.locals);
init(src);
}
/**
* Copies the state of the given frame into this frame.
*
* @param src a frame.
* @return this frame.
*/
public Frame init(final Frame src) {
System.arraycopy(src.values, 0, values, 0, values.length);
top = src.top;
return this;
}
/**
* Returns the maximum number of local variables of this frame.
*
* @return the maximum number of local variables of this frame.
*/
public int getLocals() {
return locals;
}
/**
* Returns the value of the given local variable.
*
* @param i a local variable index.
* @return the value of the given local variable.
* @throws IndexOutOfBoundsException if the variable does not exist.
*/
public Value getLocal(final int i) throws IndexOutOfBoundsException {
if (i >= locals) {
throw new IndexOutOfBoundsException("Trying to access an inexistant local variable");
}
return values[i];
}
/**
* Sets the value of the given local variable.
*
* @param i a local variable index.
* @param value the new value of this local variable.
* @throws IndexOutOfBoundsException if the variable does not exist.
*/
public void setLocal(final int i, final Value value)
throws IndexOutOfBoundsException
{
if (i >= locals) {
throw new IndexOutOfBoundsException("Trying to access an inexistant local variable");
}
values[i] = value;
}
/**
* Returns the number of values in the operand stack of this frame. Long and
* double values are treated as single values.
*
* @return the number of values in the operand stack of this frame.
*/
public int getStackSize() {
return top;
}
/**
* Returns the value of the given operand stack slot.
*
* @param i the index of an operand stack slot.
* @return the value of the given operand stack slot.
* @throws IndexOutOfBoundsException if the operand stack slot does not
* exist.
*/
public Value getStack(final int i) throws IndexOutOfBoundsException {
return values[i + locals];
}
/**
* Clears the operand stack of this frame.
*/
public void clearStack() {
top = 0;
}
/**
* Pops a value from the operand stack of this frame.
*
* @return the value that has been popped from the stack.
* @throws IndexOutOfBoundsException if the operand stack is empty.
*/
public Value pop() throws IndexOutOfBoundsException {
if (top == 0) {
throw new IndexOutOfBoundsException("Cannot pop operand off an empty stack.");
}
return values[--top + locals];
}
/**
* Pushes a value into the operand stack of this frame.
*
* @param value the value that must be pushed into the stack.
* @throws IndexOutOfBoundsException if the operand stack is full.
*/
public void push(final Value value) throws IndexOutOfBoundsException {
if (top + locals >= values.length) {
throw new IndexOutOfBoundsException("Insufficient maximum stack size.");
}
values[top++ + locals] = value;
}
public void execute(
final AbstractInsnNode insn,
final Interpreter interpreter) throws AnalyzerException
{
Value value1, value2, value3, value4;
List values;
int var;
switch (insn.getOpcode()) {
case Opcodes.NOP:
break;
case Opcodes.ACONST_NULL:
case Opcodes.ICONST_M1:
case Opcodes.ICONST_0:
case Opcodes.ICONST_1:
case Opcodes.ICONST_2:
case Opcodes.ICONST_3:
case Opcodes.ICONST_4:
case Opcodes.ICONST_5:
case Opcodes.LCONST_0:
case Opcodes.LCONST_1:
case Opcodes.FCONST_0:
case Opcodes.FCONST_1:
case Opcodes.FCONST_2:
case Opcodes.DCONST_0:
case Opcodes.DCONST_1:
case Opcodes.BIPUSH:
case Opcodes.SIPUSH:
case Opcodes.LDC:
push(interpreter.newOperation(insn));
break;
case Opcodes.ILOAD:
case Opcodes.LLOAD:
case Opcodes.FLOAD:
case Opcodes.DLOAD:
case Opcodes.ALOAD:
push(interpreter.copyOperation(insn,
getLocal(((VarInsnNode) insn).var)));
break;
case Opcodes.IALOAD:
case Opcodes.LALOAD:
case Opcodes.FALOAD:
case Opcodes.DALOAD:
case Opcodes.AALOAD:
case Opcodes.BALOAD:
case Opcodes.CALOAD:
case Opcodes.SALOAD:
value2 = pop();
value1 = pop();
push(interpreter.binaryOperation(insn, value1, value2));
break;
case Opcodes.ISTORE:
case Opcodes.LSTORE:
case Opcodes.FSTORE:
case Opcodes.DSTORE:
case Opcodes.ASTORE:
value1 = interpreter.copyOperation(insn, pop());
var = ((VarInsnNode) insn).var;
setLocal(var, value1);
if (value1.getSize() == 2) {
setLocal(var + 1, interpreter.newValue(null));
}
if (var > 0) {
Value local = getLocal(var - 1);
if (local != null && local.getSize() == 2) {
setLocal(var - 1, interpreter.newValue(null));
}
}
break;
case Opcodes.IASTORE:
case Opcodes.LASTORE:
case Opcodes.FASTORE:
case Opcodes.DASTORE:
case Opcodes.AASTORE:
case Opcodes.BASTORE:
case Opcodes.CASTORE:
case Opcodes.SASTORE:
value3 = pop();
value2 = pop();
value1 = pop();
interpreter.ternaryOperation(insn, value1, value2, value3);
break;
case Opcodes.POP:
if (pop().getSize() == 2) {
throw new AnalyzerException("Illegal use of POP");
}
break;
case Opcodes.POP2:
if (pop().getSize() == 1) {
if (pop().getSize() != 1) {
throw new AnalyzerException("Illegal use of POP2");
}
}
break;
case Opcodes.DUP:
value1 = pop();
if (value1.getSize() != 1) {
throw new AnalyzerException("Illegal use of DUP");
}
push(interpreter.copyOperation(insn, value1));
push(interpreter.copyOperation(insn, value1));
break;
case Opcodes.DUP_X1:
value1 = pop();
value2 = pop();
if (value1.getSize() != 1 || value2.getSize() != 1) {
throw new AnalyzerException("Illegal use of DUP_X1");
}
push(interpreter.copyOperation(insn, value1));
push(interpreter.copyOperation(insn, value2));
push(interpreter.copyOperation(insn, value1));
break;
case Opcodes.DUP_X2:
value1 = pop();
if (value1.getSize() == 1) {
value2 = pop();
if (value2.getSize() == 1) {
value3 = pop();
if (value3.getSize() == 1) {
push(interpreter.copyOperation(insn, value1));
push(interpreter.copyOperation(insn, value3));
push(interpreter.copyOperation(insn, value2));
push(interpreter.copyOperation(insn, value1));
break;
}
} else {
push(interpreter.copyOperation(insn, value1));
push(interpreter.copyOperation(insn, value2));
push(interpreter.copyOperation(insn, value1));
break;
}
}
throw new AnalyzerException("Illegal use of DUP_X2");
case Opcodes.DUP2:
value1 = pop();
if (value1.getSize() == 1) {
value2 = pop();
if (value2.getSize() == 1) {
push(interpreter.copyOperation(insn, value2));
push(interpreter.copyOperation(insn, value1));
push(interpreter.copyOperation(insn, value2));
push(interpreter.copyOperation(insn, value1));
break;
}
} else {
push(interpreter.copyOperation(insn, value1));
push(interpreter.copyOperation(insn, value1));
break;
}
throw new AnalyzerException("Illegal use of DUP2");
case Opcodes.DUP2_X1:
value1 = pop();
if (value1.getSize() == 1) {
value2 = pop();
if (value2.getSize() == 1) {
value3 = pop();
if (value3.getSize() == 1) {
push(interpreter.copyOperation(insn, value2));
push(interpreter.copyOperation(insn, value1));
push(interpreter.copyOperation(insn, value3));
push(interpreter.copyOperation(insn, value2));
push(interpreter.copyOperation(insn, value1));
break;
}
}
} else {
value2 = pop();
if (value2.getSize() == 1) {
push(interpreter.copyOperation(insn, value1));
push(interpreter.copyOperation(insn, value2));
push(interpreter.copyOperation(insn, value1));
break;
}
}
throw new AnalyzerException("Illegal use of DUP2_X1");
case Opcodes.DUP2_X2:
value1 = pop();
if (value1.getSize() == 1) {
value2 = pop();
if (value2.getSize() == 1) {
value3 = pop();
if (value3.getSize() == 1) {
value4 = pop();
if (value4.getSize() == 1) {
push(interpreter.copyOperation(insn, value2));
push(interpreter.copyOperation(insn, value1));
push(interpreter.copyOperation(insn, value4));
push(interpreter.copyOperation(insn, value3));
push(interpreter.copyOperation(insn, value2));
push(interpreter.copyOperation(insn, value1));
break;
}
} else {
push(interpreter.copyOperation(insn, value2));
push(interpreter.copyOperation(insn, value1));
push(interpreter.copyOperation(insn, value3));
push(interpreter.copyOperation(insn, value2));
push(interpreter.copyOperation(insn, value1));
break;
}
}
} else {
value2 = pop();
if (value2.getSize() == 1) {
value3 = pop();
if (value3.getSize() == 1) {
push(interpreter.copyOperation(insn, value1));
push(interpreter.copyOperation(insn, value3));
push(interpreter.copyOperation(insn, value2));
push(interpreter.copyOperation(insn, value1));
break;
}
} else {
push(interpreter.copyOperation(insn, value1));
push(interpreter.copyOperation(insn, value2));
push(interpreter.copyOperation(insn, value1));
break;
}
}
throw new AnalyzerException("Illegal use of DUP2_X2");
case Opcodes.SWAP:
value2 = pop();
value1 = pop();
if (value1.getSize() != 1 || value2.getSize() != 1) {
throw new AnalyzerException("Illegal use of SWAP");
}
push(interpreter.copyOperation(insn, value2));
push(interpreter.copyOperation(insn, value1));
break;
case Opcodes.IADD:
case Opcodes.LADD:
case Opcodes.FADD:
case Opcodes.DADD:
case Opcodes.ISUB:
case Opcodes.LSUB:
case Opcodes.FSUB:
case Opcodes.DSUB:
case Opcodes.IMUL:
case Opcodes.LMUL:
case Opcodes.FMUL:
case Opcodes.DMUL:
case Opcodes.IDIV:
case Opcodes.LDIV:
case Opcodes.FDIV:
case Opcodes.DDIV:
case Opcodes.IREM:
case Opcodes.LREM:
case Opcodes.FREM:
case Opcodes.DREM:
value2 = pop();
value1 = pop();
push(interpreter.binaryOperation(insn, value1, value2));
break;
case Opcodes.INEG:
case Opcodes.LNEG:
case Opcodes.FNEG:
case Opcodes.DNEG:
push(interpreter.unaryOperation(insn, pop()));
break;
case Opcodes.ISHL:
case Opcodes.LSHL:
case Opcodes.ISHR:
case Opcodes.LSHR:
case Opcodes.IUSHR:
case Opcodes.LUSHR:
case Opcodes.IAND:
case Opcodes.LAND:
case Opcodes.IOR:
case Opcodes.LOR:
case Opcodes.IXOR:
case Opcodes.LXOR:
value2 = pop();
value1 = pop();
push(interpreter.binaryOperation(insn, value1, value2));
break;
case Opcodes.IINC:
var = ((IincInsnNode) insn).var;
setLocal(var, interpreter.unaryOperation(insn, getLocal(var)));
break;
case Opcodes.I2L:
case Opcodes.I2F:
case Opcodes.I2D:
case Opcodes.L2I:
case Opcodes.L2F:
case Opcodes.L2D:
case Opcodes.F2I:
case Opcodes.F2L:
case Opcodes.F2D:
case Opcodes.D2I:
case Opcodes.D2L:
case Opcodes.D2F:
case Opcodes.I2B:
case Opcodes.I2C:
case Opcodes.I2S:
push(interpreter.unaryOperation(insn, pop()));
break;
case Opcodes.LCMP:
case Opcodes.FCMPL:
case Opcodes.FCMPG:
case Opcodes.DCMPL:
case Opcodes.DCMPG:
value2 = pop();
value1 = pop();
push(interpreter.binaryOperation(insn, value1, value2));
break;
case Opcodes.IFEQ:
case Opcodes.IFNE:
case Opcodes.IFLT:
case Opcodes.IFGE:
case Opcodes.IFGT:
case Opcodes.IFLE:
interpreter.unaryOperation(insn, pop());
break;
case Opcodes.IF_ICMPEQ:
case Opcodes.IF_ICMPNE:
case Opcodes.IF_ICMPLT:
case Opcodes.IF_ICMPGE:
case Opcodes.IF_ICMPGT:
case Opcodes.IF_ICMPLE:
case Opcodes.IF_ACMPEQ:
case Opcodes.IF_ACMPNE:
value2 = pop();
value1 = pop();
interpreter.binaryOperation(insn, value1, value2);
break;
case Opcodes.GOTO:
break;
case Opcodes.JSR:
push(interpreter.newOperation(insn));
break;
case Opcodes.RET:
break;
case Opcodes.TABLESWITCH:
case Opcodes.LOOKUPSWITCH:
case Opcodes.IRETURN:
case Opcodes.LRETURN:
case Opcodes.FRETURN:
case Opcodes.DRETURN:
case Opcodes.ARETURN:
interpreter.unaryOperation(insn, pop());
break;
case Opcodes.RETURN:
break;
case Opcodes.GETSTATIC:
push(interpreter.newOperation(insn));
break;
case Opcodes.PUTSTATIC:
interpreter.unaryOperation(insn, pop());
break;
case Opcodes.GETFIELD:
push(interpreter.unaryOperation(insn, pop()));
break;
case Opcodes.PUTFIELD:
value2 = pop();
value1 = pop();
interpreter.binaryOperation(insn, value1, value2);
break;
case Opcodes.INVOKEVIRTUAL:
case Opcodes.INVOKESPECIAL:
case Opcodes.INVOKESTATIC:
case Opcodes.INVOKEINTERFACE:
values = new ArrayList();
String desc = ((MethodInsnNode) insn).desc;
for (int i = Type.getArgumentTypes(desc).length; i > 0; --i) {
values.add(0, pop());
}
if (insn.getOpcode() != Opcodes.INVOKESTATIC) {
values.add(0, pop());
}
if (Type.getReturnType(desc) == Type.VOID_TYPE) {
interpreter.naryOperation(insn, values);
} else {
push(interpreter.naryOperation(insn, values));
}
break;
case Opcodes.NEW:
push(interpreter.newOperation(insn));
break;
case Opcodes.NEWARRAY:
case Opcodes.ANEWARRAY:
case Opcodes.ARRAYLENGTH:
push(interpreter.unaryOperation(insn, pop()));
break;
case Opcodes.ATHROW:
interpreter.unaryOperation(insn, pop());
break;
case Opcodes.CHECKCAST:
case Opcodes.INSTANCEOF:
push(interpreter.unaryOperation(insn, pop()));
break;
case Opcodes.MONITORENTER:
case Opcodes.MONITOREXIT:
interpreter.unaryOperation(insn, pop());
break;
case Opcodes.MULTIANEWARRAY:
values = new ArrayList();
for (int i = ((MultiANewArrayInsnNode) insn).dims; i > 0; --i) {
values.add(0, pop());
}
push(interpreter.naryOperation(insn, values));
break;
case Opcodes.IFNULL:
case Opcodes.IFNONNULL:
interpreter.unaryOperation(insn, pop());
break;
default:
throw new RuntimeException("Illegal opcode");
}
}
/**
* Merges this frame with the given frame.
*
* @param frame a frame.
* @param interpreter the interpreter used to merge values.
* @return <tt>true</tt> if this frame has been changed as a result of the
* merge operation, or <tt>false</tt> otherwise.
* @throws AnalyzerException if the frames have incompatible sizes.
*/
public boolean merge(final Frame frame, final Interpreter interpreter)
throws AnalyzerException
{
if (top != frame.top) {
throw new AnalyzerException("Incompatible stack heights");
}
boolean changes = false;
for (int i = 0; i < locals + top; ++i) {
Value v = interpreter.merge(values[i], frame.values[i]);
if (v != values[i]) {
values[i] = v;
changes |= true;
}
}
return changes;
}
/**
* Merges this frame with the given frame (case of a RET instruction).
*
* @param frame a frame
* @param access the local variables that have been accessed by the
* subroutine to which the RET instruction corresponds.
* @return <tt>true</tt> if this frame has been changed as a result of the
* merge operation, or <tt>false</tt> otherwise.
*/
public boolean merge(final Frame frame, final boolean[] access) {
boolean changes = false;
for (int i = 0; i < locals; ++i) {
if (!access[i] && !values[i].equals(frame.values[i])) {
values[i] = frame.values[i];
changes = true;
}
}
return changes;
}
/**
* Returns a string representation of this frame.
*
* @return a string representation of this frame.
*/
public String toString() {
StringBuffer b = new StringBuffer();
for (int i = 0; i < getLocals(); ++i) {
b.append(getLocal(i));
}
b.append(' ');
for (int i = 0; i < getStackSize(); ++i) {
b.append(getStack(i).toString());
}
return b.toString();
}
}
|
package org.opencms.jsp;
import org.opencms.file.CmsFile;
import org.opencms.file.CmsFolder;
import org.opencms.file.CmsObject;
import org.opencms.file.CmsProperty;
import org.opencms.file.CmsPropertyDefinition;
import org.opencms.file.CmsRequestContext;
import org.opencms.file.CmsResource;
import org.opencms.file.CmsResourceFilter;
import org.opencms.file.types.CmsResourceTypeXmlContent;
import org.opencms.file.types.CmsResourceTypeXmlPage;
import org.opencms.i18n.CmsLocaleGroup;
import org.opencms.jsp.util.CmsJspCategoryAccessBean;
import org.opencms.jsp.util.CmsJspContentAccessBean;
import org.opencms.jsp.util.CmsJspImageBean;
import org.opencms.jsp.util.CmsJspValueTransformers.CmsLocalePropertyLoaderTransformer;
import org.opencms.main.CmsException;
import org.opencms.main.CmsLog;
import org.opencms.main.OpenCms;
import org.opencms.relations.CmsRelation;
import org.opencms.relations.CmsRelationFilter;
import org.opencms.security.CmsSecurityException;
import org.opencms.util.CmsCollectionsGenericWrapper;
import org.opencms.util.CmsUUID;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.stream.Collectors;
import org.apache.commons.logging.Log;
import com.google.common.collect.Maps;
/**
* Wrapper subclass of CmsResource with some convenience methods.<p>
*/
public class CmsJspResourceWrapper extends CmsResource {
/** Serial version id. */
private static final long serialVersionUID = 1L;
/** Logger instance for this class. */
@SuppressWarnings("unused")
private static final Log LOG = CmsLog.getLog(CmsJspResourceWrapper.class);
/** The CMS context. */
private CmsObject m_cms;
/** The set of locale variants. */
private Map<String, CmsJspResourceWrapper> m_localeResources;
/** The main locale. */
private Locale m_mainLocale;
/** The file object for this resource. */
private CmsFile m_file;
/** The resource / file content as a String. */
private String m_content;
/** The calculated site path of the resource. */
private String m_sitePath;
/** Properties of this resource. */
private Map<String, String> m_properties;
/** Properties of this resource with search. */
private Map<String, String> m_propertiesSearch;
/** Locale properties of this resource. */
private Map<String, Map<String, String>> m_propertiesLocale;
/** Locale properties of this resource with search. */
private Map<String, Map<String, String>> m_propertiesLocaleSearch;
/** The XML content access bean. */
private CmsJspContentAccessBean m_xml;
/** Stores if this resource is an XML content or not. */
private Boolean m_isXml;
/** All parent folder of this resource in the current site as a list. */
public List<CmsJspResourceWrapper> m_parentFolders;
/** The parent folder of this resource in the current site. */
private CmsJspResourceWrapper m_parentFolder;
/** The default file of this resource, assumed that this resource is a folder. */
CmsJspResourceWrapper m_navigationDefaultFile;
/** The navigation builder for this resource. */
CmsJspNavBuilder m_navBuilder;
/** The navigation info elements in this resource, assuming that this resource is a folder. */
private List<CmsJspNavElement> m_navigationForFolder;
/** The navigation info element for this resource. */
private CmsJspNavElement m_navigation;
/** Image bean instance created from this resource. */
private CmsJspImageBean m_imageBean;
/** The category access bean for this resource. */
private CmsJspCategoryAccessBean m_categories;
/**
* Creates a new instance.<p>
*
* @param cms the current CMS context
* @param res the resource to wrap
*/
private CmsJspResourceWrapper(CmsObject cms, CmsResource res) {
super(
res.getStructureId(),
res.getResourceId(),
res.getRootPath(),
res.getTypeId(),
res.isFolder(),
res.getFlags(),
res.getProjectLastModified(),
res.getState(),
res.getDateCreated(),
res.getUserCreated(),
res.getDateLastModified(),
res.getUserLastModified(),
res.getDateReleased(),
res.getDateExpired(),
res.getSiblingCount(),
res.getLength(),
res.getDateContent(),
res.getVersion());
m_cms = cms;
m_file = null;
m_content = "";
}
/**
* Factory method to create a new {@link CmsJspResourceWrapper} instance from a {@link CmsResource}.<p>
*
* In case the parameter resource already is a wrapped resource AND the OpenCms request context is
* the same as the provided context, the parameter object is returned.<p>
*
* @param cms the current CMS context
* @param res the resource to wrap
*
* @return a new instance of a {@link CmsJspResourceWrapper}
*/
public static CmsJspResourceWrapper wrap(CmsObject cms, CmsResource res) {
CmsJspResourceWrapper result = null;
if ((cms != null) && (res != null)) {
if (res instanceof CmsJspResourceWrapper) {
CmsJspResourceWrapper wrapper = (CmsJspResourceWrapper)res;
if (cms.getRequestContext().getSiteRoot().equals(wrapper.getRequestContext().getSiteRoot())) {
result = wrapper;
} else {
result = new CmsJspResourceWrapper(cms, res);
}
} else {
result = new CmsJspResourceWrapper(cms, res);
}
}
return result;
}
/**
* Two resources are considered equal in case their structure id is equal.<p>
*
* @see CmsResource#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (obj == this) {
return true;
}
if (obj instanceof CmsResource) {
return ((CmsResource)obj).getStructureId().equals(getStructureId());
}
return false;
}
/**
* Returns the categories assigned to this resource.<p>
*
* @return the categories assigned to this resource
*/
public CmsJspCategoryAccessBean getCategories() {
if (m_categories == null) {
m_categories = new CmsJspCategoryAccessBean(m_cms, this);
}
return m_categories;
}
/**
* Returns the OpenCms user context this resource was initialized with.<p>
*
* @return the OpenCms user context this resource was initialized with
*/
public CmsObject getCmsObject() {
return m_cms;
}
/**
* Returns the content of the file as a String.<p>
*
* @return the content of the file as a String
*/
public String getContent() {
if ((m_content.length() == 0) && (getFile() != null)) {
m_content = new String(getFile().getContents());
}
return m_content;
}
/**
* Returns this resources name extension (if present).<p>
*
* The extension will always be lower case.<p>
*
* @return the extension or <code>null</code> if not available
*
* @see CmsResource#getExtension(String)
* @see org.opencms.jsp.util.CmsJspVfsAccessBean#getResourceExtension(Object)
*/
public String getExtension() {
return getExtension(getRootPath());
}
/**
* Returns the full file object for this resource.<p>
*
* @return the full file object for this resource
*/
public CmsFile getFile() {
if ((m_file == null) && !isFolder()) {
try {
m_file = m_cms.readFile(this);
} catch (CmsException e) {
// this should not happen since we are updating from a resource object
}
}
return m_file;
}
/**
* Returns the folder of this resource.<p>
*
* In case this resource already is a {@link CmsFolder}, it is returned without modification.
* In case it is a {@link CmsFile}, the parent folder of the file is returned.<p>
*
* @return the folder of this resource
*
* @see #getSitePathFolder()
*/
public CmsJspResourceWrapper getFolder() {
CmsJspResourceWrapper result;
if (isFolder()) {
result = this;
} else {
result = readResource(getSitePathFolder());
}
return result;
}
/**
* Gets a list of resource wrappers for resources with relations pointing to this resource.
*
* @return the list of resource wrappers
*/
public List<CmsJspResourceWrapper> getIncomingRelations() {
return getRelatedResources(CmsRelationFilter.relationsToStructureId(getStructureId()));
}
/**
* Gets a list of resource wrappers for resources with relations pointing to this resource, for a specific type.
*
* @param typeName name of the type to filter
* @return the list of resource wrappers
*/
public List<CmsJspResourceWrapper> getIncomingRelations(String typeName) {
return getIncomingRelations().stream().filter(
res -> OpenCms.getResourceManager().matchResourceType(typeName, res.getTypeId())).collect(
Collectors.toList());
}
/**
* Returns <code>true</code> in case this resource is an image in the VFS.<p>
*
* @return <code>true</code> in case this resource is an image in the VFS
*/
public boolean getIsImage() {
return getToImage().isImage();
}
/**
* Returns <code>true</code> in case this resource is an XML content.<p>
*
* @return <code>true</code> in case this resource is an XML content
*/
public boolean getIsXml() {
if (m_isXml == null) {
m_isXml = Boolean.valueOf(
CmsResourceTypeXmlPage.isXmlPage(this) || CmsResourceTypeXmlContent.isXmlContent(this));
}
return m_isXml.booleanValue();
}
/**
* Returns a substituted link to this resource.<p>
*
* @return the link
*/
public String getLink() {
return OpenCms.getLinkManager().substituteLinkForUnknownTarget(
m_cms,
m_cms.getRequestContext().getSitePath(this));
}
/**
* Returns a map of the locale group for the current resource, with locale strings as keys.<p>
*
* @return a map with locale strings as keys and resource wrappers for the corresponding locale variants
*/
public Map<String, CmsJspResourceWrapper> getLocaleResource() {
if (m_localeResources != null) {
return m_localeResources;
}
try {
CmsLocaleGroup localeGroup = m_cms.getLocaleGroupService().readLocaleGroup(this);
Map<Locale, CmsResource> resourcesByLocale = localeGroup.getResourcesByLocale();
Map<String, CmsJspResourceWrapper> result = Maps.newHashMap();
for (Map.Entry<Locale, CmsResource> entry : resourcesByLocale.entrySet()) {
result.put(entry.getKey().toString(), CmsJspResourceWrapper.wrap(m_cms, entry.getValue()));
}
m_localeResources = result;
return result;
} catch (CmsException e) {
return new HashMap<String, CmsJspResourceWrapper>();
}
}
/**
* Returns the main locale for this resource.<p>
*
* @return the main locale for this resource
*/
public Locale getMainLocale() {
if (m_mainLocale != null) {
return m_mainLocale;
}
try {
CmsLocaleGroup localeGroup = m_cms.getLocaleGroupService().readLocaleGroup(this);
m_mainLocale = localeGroup.getMainLocale();
return m_mainLocale;
} catch (CmsException e) {
return null;
}
}
/**
* Returns the mime type for this resource.<p>
*
* In case no valid mime type can be determined from the file extension, <code>text/plain</code> is returned.<p>
*
* @return the mime type for this resource
*/
public String getMimeType() {
return OpenCms.getResourceManager().getMimeType(getRootPath(), null, "text/plain");
}
/**
* Returns the navigation builder for this resource.<p>
*
* This will be initialized with this resource as default URI.<p>
*
* @return the navigation builder for this resource
*/
public CmsJspNavBuilder getNavBuilder() {
if (m_navBuilder == null) {
m_navBuilder = new CmsJspNavBuilder();
m_navBuilder.init(m_cms, null, getSitePath());
}
return m_navBuilder;
}
/**
* Returns the navigation info element for this resource.<p>
*
* @return the navigation info element for this resource
*/
public CmsJspNavElement getNavigation() {
if (m_navigation == null) {
m_navigation = getNavBuilder().getNavigationForResource();
}
return m_navigation;
}
/**
* Returns the default resource for this resource.<p>
*
* If this resource is a file, then this file is returned.<p>
*
* Otherwise, in case this resource is a folder:<br>
* <ol>
* <li>the {@link CmsPropertyDefinition#PROPERTY_DEFAULT_FILE} is checked, and
* <li>if still no file could be found, the configured default files in the
* <code>opencms-vfs.xml</code> configuration are iterated until a match is
* found, and
* <li>if still no file could be found, <code>null</code> is returned
* </ol>
*
* @return the default file for the given folder
*
* @see CmsObject#readDefaultFile(CmsResource, CmsResourceFilter)
*/
public CmsJspResourceWrapper getNavigationDefaultFile() {
if (m_navigationDefaultFile == null) {
if (isFolder()) {
try {
m_navigationDefaultFile = wrap(m_cms, m_cms.readDefaultFile(this, CmsResourceFilter.DEFAULT));
} catch (CmsSecurityException e) {
if (LOG.isDebugEnabled()) {
LOG.debug(e.getMessage(), e);
}
}
}
} else {
m_navigationDefaultFile = this;
}
return m_navigationDefaultFile;
}
/**
* Returns the navigation info elements in this resource, assuming that this resource is a folder.<p>
*
* @return the navigation info elements in this resource, assuming that this resource is a folder
*/
public List<CmsJspNavElement> getNavigationForFolder() {
if (m_navigationForFolder == null) {
m_navigationForFolder = getNavBuilder().getNavigationForFolder();
}
return m_navigationForFolder;
}
/**
* Gets a list of resources with relations pointing to them from this resources, as resource wrappers.
*
* @return the list of resource wrappers
*/
public List<CmsJspResourceWrapper> getOutgoingRelations() {
return getRelatedResources(CmsRelationFilter.relationsFromStructureId(getStructureId()));
}
/**
* Gets a list of resources with relations pointing to them from this resources, as resource wrappers.
*
* Only gets resources with the given type.
*
* @param typeName the name of the type to filter
* @return the list of resource wrappers
*/
public List<CmsJspResourceWrapper> getOutgoingRelations(String typeName) {
return getOutgoingRelations().stream().filter(
res -> OpenCms.getResourceManager().matchResourceType(typeName, res.getTypeId())).collect(
Collectors.toList());
}
/**
* Returns the parent folder of this resource in the current site.<p>
*
* The parent folder of a file is the folder of the file.
* The parent folder of a folder is the parent folder of the folder.
* The parent folder of the root folder is <code>null</code>.<p>
*
* @return the parent folder of this resource in the current site
*
* @see #getSitePathParentFolder()
* @see CmsResource#getParentFolder(String)
* @see org.opencms.jsp.util.CmsJspVfsAccessBean#getParentFolder(Object)
*/
public CmsJspResourceWrapper getParentFolder() {
if (m_parentFolder == null) {
String parentFolder = getSitePathParentFolder();
if (parentFolder != null) {
m_parentFolder = readResource(getSitePathParentFolder());
}
}
return m_parentFolder;
}
/**
* Returns all parent folder of this resource in the current site as a list.<p>
*
* First resource in the list will be the direct parent folder of this resource,
* the last element will be the site root folder.<p>
*
* @return all parent folder of this resource in the current site as a list
*/
public List<CmsJspResourceWrapper> getParentFolders() {
if (m_parentFolders == null) {
m_parentFolders = new ArrayList<CmsJspResourceWrapper>();
CmsJspResourceWrapper parentFolder = getParentFolder();
while (parentFolder != null) {
m_parentFolders.add(parentFolder);
parentFolder = parentFolder.getParentFolder();
}
}
return m_parentFolders;
}
/**
* Returns the direct properties of this resource in a map.<p>
*
* This is without "search", so it will not include inherited properties from the parent folders.<p>
*
* @return the direct properties of this resource in a map
*/
public Map<String, String> getProperty() {
if (m_properties == null) {
try {
List<CmsProperty> properties = m_cms.readPropertyObjects(this, false);
m_properties = CmsProperty.toMap(properties);
} catch (CmsException e) {
if (LOG.isDebugEnabled()) {
LOG.debug(e.getMessage(), e);
}
}
}
return m_properties;
}
/**
* Returns the direct properties of this resource in a map for a given locale.<p>
*
* This is without "search", so it will not include inherited properties from the parent folders.<p>
*
* @return the direct properties of this resource in a map for a given locale
*/
public Map<String, Map<String, String>> getPropertyLocale() {
if (m_propertiesLocale == null) {
m_propertiesLocale = CmsCollectionsGenericWrapper.createLazyMap(
new CmsLocalePropertyLoaderTransformer(getCmsObject(), this, false));
// result may still be null
return (m_propertiesLocale == null) ? Collections.EMPTY_MAP : m_propertiesLocale;
}
return m_propertiesLocale;
}
/**
* Returns the searched properties of this resource in a map for a given locale.<p>
*
* This is with "search", so it will include inherited properties from the parent folders.<p>
*
* @return the direct properties of this resource in a map for a given locale
*/
public Map<String, Map<String, String>> getPropertyLocaleSearch() {
if (m_propertiesLocaleSearch == null) {
m_propertiesLocaleSearch = CmsCollectionsGenericWrapper.createLazyMap(
new CmsLocalePropertyLoaderTransformer(getCmsObject(), this, true));
// result may still be null
return (m_propertiesLocaleSearch == null) ? Collections.EMPTY_MAP : m_propertiesLocaleSearch;
}
return m_propertiesLocaleSearch;
}
/**
* Returns the searched properties of this resource in a map.<p>
*
* This is with "search", so it will include inherited properties from the parent folders.<p>
*
* @return the direct properties of this resource in a map
*/
public Map<String, String> getPropertySearch() {
if (m_propertiesSearch == null) {
try {
List<CmsProperty> properties = m_cms.readPropertyObjects(this, true);
m_propertiesSearch = CmsProperty.toMap(properties);
} catch (CmsException e) {
if (LOG.isDebugEnabled()) {
LOG.debug(e.getMessage(), e);
}
}
}
return m_propertiesSearch;
}
/**
* Returns the OpenCms user request context this resource was initialized with.<p>
*
* @return the OpenCms user request context this resource was initialized with
*/
public CmsRequestContext getRequestContext() {
return m_cms.getRequestContext();
}
/**
* Returns this resources name extension (if present).<p>
*
* The extension will always be lower case.<p>
*
* @return the extension or <code>null</code> if not available
*
* @see CmsResource#getExtension(String)
* @see org.opencms.jsp.util.CmsJspVfsAccessBean#getResourceExtension(Object)
*/
public String getResourceExtension() {
return getExtension();
}
/**
* Returns the name of this resource without the path information.<p>
*
* The resource name of a file is the name of the file.
* The resource name of a folder is the folder name with trailing "/".
* The resource name of the root folder is <code>/</code>.<p>
*
* @return the name of this resource without the path information
*
* @see CmsResource#getName()
* @see org.opencms.jsp.util.CmsJspVfsAccessBean#getResourceName(Object)
*/
public String getResourceName() {
return getName();
}
/**
* Returns the folder name of this resource from the root site.<p>
*
* In case this resource already is a {@link CmsFolder}, the folder path is returned without modification.
* In case it is a {@link CmsFile}, the parent folder name of the file is returned.<p>
*
* @return the folder name of this resource from the root site
*/
public String getRootPathFolder() {
String result;
if (isFile()) {
result = getRootPathParentFolder();
} else {
result = getRootPath();
}
return result;
}
/**
* Returns the directory level of a resource from the root site.<p>
*
* The root folder "/" has level 0,
* a folder "/foo/" would have level 1,
* a folder "/foo/bar/" level 2 etc.<p>
*
* @return the directory level of a resource from the root site
*
* @see CmsResource#getPathLevel(String)
*/
public int getRootPathLevel() {
return getPathLevel(getRootPath());
}
/**
* Returns the parent folder of this resource from the root site.<p>
*
* @return the parent folder of this resource from the root site
*
* @see CmsResource#getParentFolder(String)
*/
public String getRootPathParentFolder() {
return getParentFolder(getRootPath());
}
/**
* Returns the current site path to this resource.<p>
*
* @return the current site path to this resource
*
* @see org.opencms.file.CmsRequestContext#getSitePath(CmsResource)
*/
public String getSitePath() {
if (m_sitePath == null) {
m_sitePath = m_cms.getRequestContext().getSitePath(this);
}
return m_sitePath;
}
/**
* Returns the folder name of this resource in the current site.<p>
*
* In case this resource already is a {@link CmsFolder}, the folder path is returned without modification.
* In case it is a {@link CmsFile}, the parent folder name of the file is returned.<p>
*
* @return the folder name of this resource in the current site
*/
public String getSitePathFolder() {
String result;
if (isFile()) {
result = getSitePathParentFolder();
} else {
result = getSitePath();
}
return result;
}
/**
* Returns the directory level of a resource in the current site.<p>
*
* The root folder "/" has level 0,
* a folder "/foo/" would have level 1,
* a folder "/foo/bar/" level 2 etc.<p>
*
* @return the directory level of a resource in the current site
*
* @see CmsResource#getPathLevel(String)
* @see org.opencms.jsp.util.CmsJspVfsAccessBean#getPathLevel(Object)
*/
public int getSitePathLevel() {
return getPathLevel(getSitePath());
}
/**
* Returns the parent folder of this resource in the current site.<p>
*
* The parent folder of a file is the folder of the file.
* The parent folder of a folder is the parent folder of the folder.
* The parent folder of the root folder is <code>null</code>.<p>
*
* @return the parent folder of this resource in the current site
*
* @see CmsResource#getParentFolder(String)
* @see org.opencms.jsp.util.CmsJspVfsAccessBean#getParentFolder(Object)
*/
public String getSitePathParentFolder() {
return getParentFolder(getSitePath());
}
/**
* Returns a scaled image bean from the wrapped value.<p>
*
* In case the value does not point to an image resource, <code>null</code> is returned.
*
* @return the scaled image bean
*/
public CmsJspImageBean getToImage() {
if (m_imageBean == null) {
m_imageBean = new CmsJspImageBean(getCmsObject(), this, null);
}
return m_imageBean;
}
/**
* Returns an XML content access bean created for this resource.<p>
*
* In case this resource is not an XML content, <code>null</code> is returned.<p>
*
* @return an XML content access bean created for this resource
*
* @see #getIsXml()
*/
public CmsJspContentAccessBean getToXml() {
if ((m_xml == null) && getIsXml()) {
m_xml = new CmsJspContentAccessBean(m_cms, this);
}
return m_xml;
}
/**
* Returns an XML content access bean created for this resource.<p>
*
* In case this resource is not an XML content, <code>null</code> is returned.<p>
*
* @return an XML content access bean created for this resource
*
* @see #getToXml()
* @see #getIsXml()
*/
public CmsJspContentAccessBean getXml() {
return getToXml();
}
/**
* @see CmsResource#hashCode()
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
if (getStructureId() != null) {
return getStructureId().hashCode();
}
return CmsUUID.getNullUUID().hashCode();
}
/**
* Returns <code>true</code> in case this resource is child resource of the provided resource which is assumed to be a folder.<p>
*
* @param resource the resource to check
*
* @return <code>true</code> in case this resource is child resource of the provided resource which is assumed to be a folder
*/
public boolean isChildResourceOf(CmsResource resource) {
return (resource != null)
&& resource.isFolder()
&& !(getStructureId().equals(resource.getStructureId()))
&& ((getRootPath().indexOf(resource.getRootPath()) == 0));
}
/**
* Returns <code>true</code> in case this resource is child resource of the provided resource path which is assumed to be a folder in the current site.<p>
*
* No check is performed to see if the provided site path resource actually exists.<p>
*
* @param sitePath the resource to check
*
* @return <code>true</code> in case this resource is child resource of the provided resource path which is assumed to be a folder in the current site
*/
public boolean isChildResourceOf(String sitePath) {
return (sitePath != null)
&& ((getSitePath().indexOf(sitePath) == 0))
&& (sitePath.length() < getSitePath().length());
}
/**
* Returns <code>true</code> in case this resource is a parent folder of the provided resource.<p>
*
* @param resource the resource to check
*
* @return <code>true</code> in case this resource is a parent folder of the provided resource
*/
public boolean isParentFolderOf(CmsResource resource) {
return (resource != null)
&& isFolder()
&& !(getStructureId().equals(resource.getStructureId()))
&& ((resource.getRootPath().indexOf(getRootPath()) == 0));
}
/**
* Returns <code>true</code> in case this resource is a parent folder of the provided resource path in the current site.<p>
*
* No check is performed to see if the provided site path resource actually exists.<p>
*
* @param sitePath the path to check
*
* @return <code>true</code> in case this resource is a parent folder of the provided resource path in the current site
*/
public boolean isParentFolderOf(String sitePath) {
return (sitePath != null)
&& isFolder()
&& ((sitePath.indexOf(getSitePath()) == 0))
&& (sitePath.length() > getSitePath().length());
}
/**
* Helper method for getting the related resources for this resource, with a given resource filter.
*
* @param filter the resource filter
* @return the list of related resources
*/
private List<CmsJspResourceWrapper> getRelatedResources(final CmsRelationFilter filter) {
CmsObject cms = getCmsObject();
List<CmsJspResourceWrapper> result = new ArrayList<>();
try {
List<CmsRelation> relations = cms.readRelations(filter);
for (CmsRelation rel : relations) {
try {
result.add(wrap(cms, rel.getSource(cms, CmsResourceFilter.DEFAULT)));
} catch (CmsException e) {
LOG.warn(e.getLocalizedMessage(), e);
}
}
} catch (Exception e) {
LOG.error(e.getLocalizedMessage(), e);
}
return result;
}
/**
* Reads a resource, suppressing possible exceptions.<p>
*
* @param sitePath the site path of the resource to read.
*
* @return the resource of <code>null</code> on case an exception occurred while reading
*/
private CmsJspResourceWrapper readResource(String sitePath) {
CmsJspResourceWrapper result = null;
try {
result = new CmsJspResourceWrapper(m_cms, m_cms.readResource(sitePath));
} catch (CmsException e) {
if (LOG.isDebugEnabled()) {
LOG.debug(e.getMessage(), e);
}
}
return result;
}
}
|
/*
* This is the master autonomous class
* Every other auto class inherits from this
*/
package org.usfirst.frc4946.autoMode;
import edu.wpi.first.wpilibj.DriverStationLCD;
import edu.wpi.first.wpilibj.Gyro;
import edu.wpi.first.wpilibj.RobotDrive;
import org.usfirst.frc4946.DistanceSensor;
import org.usfirst.frc4946.IntakeArm;
import org.usfirst.frc4946.Launcher;
import org.usfirst.frc4946.Loader;
import org.usfirst.frc4946.RobotConstants;
/**
*
* @author Stefan
*/
public abstract class AutoMode {
RobotDrive m_robotDrive;
Launcher m_launcher;
Loader m_loader;
IntakeArm m_intakeArm;
DistanceSensor m_distanceSensor;
protected DriverStationLCD m_driverStation = DriverStationLCD.getInstance();
Gyro m_gyro = new Gyro(RobotConstants.GYRO_SENSOR);
AutoMode(RobotDrive drive, Launcher launcher, Loader loader, IntakeArm intakeArm, DistanceSensor distanceSensor) {
m_robotDrive = drive;
m_launcher = launcher;
m_loader = loader;
m_intakeArm = intakeArm;
m_distanceSensor = distanceSensor;
m_gyro.reset();
}
protected boolean shooterIsAtTargetSpeed(double speed) {
return getCurrentShooterSpeed() >= (speed-50) && getCurrentShooterSpeed() <= (speed+50);
}
public void driveToDistance(double distance, double speed) {
double currentDistance = m_distanceSensor.getRangeInchs();
if (currentDistance >= distance && RobotConstants.DISTANCE_SENSOR_RANGE <= Math.abs(currentDistance - distance)) {
double angle = m_gyro.getAngle();
double correctedAngle = angle*-0.03;
drive(speed, correctedAngle);
}
//if (currentDistance <= distance && RobotConstants.DISTANCE_SENSOR_RANGE <= Math.abs(currentDistance - distance)) {
// drive(-speed, 0);
}
public void drive(double speed, double turn) {
m_robotDrive.drive(speed, turn);
}
public boolean atDistance(double distance) {
double currentDistance = m_distanceSensor.getRangeInchs();
return RobotConstants.DISTANCE_SENSOR_RANGE >= Math.abs(currentDistance - distance);
}
public void driveDistance(double distance, double speed) {
//get current distance
//subtract input distance from current distance and drive to that distance
double currentDistance = m_distanceSensor.getRangeInchs();
driveToDistance(currentDistance - distance, speed);
}
public void turnToAngle() {
//needs work, potentially use the gyro,compass, combo part we have?
}
public void updateShooter(boolean closedLoop) {
m_launcher.update();
}
public void startShooter(boolean closedLoop) {
if (closedLoop) {
m_launcher.setClosedLoopEnabled(true);
} else {
m_launcher.setOpenLoopEnabled(true);
}
}
public void setShooterSpeed(double speed, boolean closedLoop) {
if (closedLoop == true) {
m_launcher.setSpeedRPM(speed);
} else {
m_launcher.setSpeedOpenLoop(speed);
}
}
public void stopShooter(boolean closedLoop) {
if (closedLoop) {
m_launcher.setClosedLoopEnabled(false);
} else {
m_launcher.setOpenLoopEnabled(false);
}
}
public void extendArm() {
m_intakeArm.setExtended(true);
m_intakeArm.updateSolenoids();
}
public void retractArm() {
m_intakeArm.setExtended(false);
m_intakeArm.updateSolenoids();
}
public void enableRollers() {
m_intakeArm.setEnabledRollers(true);
}
public void disableRollers() {
m_intakeArm.setEnabledRollers(false);
}
public void extendLoader() {
m_loader.setExtended(true);
m_loader.updateSolenoids();
}
public void retractLoader() {
m_loader.setExtended(false);
m_loader.updateSolenoids();
}
public double getCurrentShooterSpeed() {
//return the speed
double rpm = m_launcher.getSpeedRPM();
return rpm;
}
}
|
package pacioli.visitors;
import java.util.ArrayList;
import java.util.List;
import pacioli.Location;
import pacioli.PacioliException;
import pacioli.ast.IdentityTransformation;
import pacioli.ast.Visitor;
import pacioli.ast.expression.ConversionNode;
import pacioli.ast.expression.IdentifierNode;
import pacioli.ast.expression.MatrixLiteralNode;
import pacioli.ast.expression.MatrixLiteralNode.ValueDecl;
import pacioli.types.TypeBase;
import pacioli.types.matrix.MatrixType;
import pacioli.types.matrix.VectorBase;
import uom.DimensionedNumber;
import uom.Fraction;
import uom.UnitFold;
/**
* Transforms all conversion nodes into matrix literal nodes with the proper
* conversion factors.
*
* This is more generic than what is needed because currently conversions are
* toplevels and cannot occur everywhere in an expression as is handled here.
*/
public class TransformConversions extends IdentityTransformation implements Visitor {
public TransformConversions() {
}
public void visit(ConversionNode node) {
Location location = node.getLocation();
MatrixType type = (MatrixType) node.typeNode.evalType(true);
DimensionedNumber<TypeBase> typeFactor = type.factor.flat();
if (!type.rowDimension.equals(type.columnDimension)) {
throw new RuntimeException("Invalid conversion",
new PacioliException(node.getLocation(), "Row and column dimension not the same"));
}
Boolean closedType = true;
if (closedType) {
// Compute the conversion factors
List<ValueDecl> conversionFactors = new ArrayList<ValueDecl>();
int nrItems = node.rowDim.size();
int width = node.rowDim.width();
for (int i = 0; i < nrItems; i++) {
final List<String> items = node.rowDim.ElementAt(i);
assert(items.size() == width);
UnitFold<TypeBase, DimensionedNumber<TypeBase>> folder =
new UnitFold<TypeBase, DimensionedNumber<TypeBase>>() {
@Override
public DimensionedNumber<TypeBase> map(TypeBase base) {
VectorBase vbase = (VectorBase) base;
String itemName = items.get(vbase.position);
DimensionedNumber<TypeBase> unit = vbase.vectorUnitInfo.getUnit(itemName);
return unit;
}
@Override
public DimensionedNumber<TypeBase> mult(DimensionedNumber<TypeBase> x,
DimensionedNumber<TypeBase> y) {
return x.multiply(y);
}
@Override
public DimensionedNumber<TypeBase> expt(DimensionedNumber<TypeBase> x, Fraction n) {
return x.raise(n);
}
@Override
public DimensionedNumber<TypeBase> one() {
return new DimensionedNumber<TypeBase>();
}
};
DimensionedNumber<TypeBase> rowUnit = type.rowUnit.fold(folder);
DimensionedNumber<TypeBase> columnsUnit = type.columnUnit.fold(folder);
DimensionedNumber<TypeBase> div =
typeFactor.multiply(rowUnit.multiply(columnsUnit.reciprocal()));
DimensionedNumber<TypeBase> flat = div.flat();
// todo: how to handle empty dimension?
List<IdentifierNode> key = new ArrayList<IdentifierNode>();
for (String item: items) {
key.add(new IdentifierNode(item, node.getLocation()));
}
for (String item: items) {
key.add(new IdentifierNode(item, node.getLocation()));
}
String value = flat.factor().toPlainString();
conversionFactors.add(new ValueDecl(key, value));
}
// Create a literal node of the same type with the conversion factors.
returnNode(new MatrixLiteralNode(location, node.typeNode, conversionFactors));
} else {
returnNode(node);
}
}
}
|
package parameter_estimation;
public class ChemkinConstants {
public static final String CHEMOUT = "chem.out";
public static final String CHEMASC = "chem.asc";
public static final String CHEMASU = "chem.asu";
public static final String TRANOUT = "tran.out";
public static final String TRANASC = "tran.asc";
static final String CHEMKINDATADTD = "chemkindata.dtd";
static final String CKSOLNLIST = "CKSolnList.txt";
public static final String XML = "XMLdata.zip";
public static final String CKCSVNAME = "CKSoln.ckcsv";
// input file to CKPreProcess routine:
public static final String PREPROCESSINPUT = "CKPreProc_template.input";
}
|
// VisBio.java
package loci.visbio;
import java.awt.Color;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import loci.visbio.util.SplashScreen;
/**
* VisBio is a biological visualization tool designed for easy
* visualization and analysis of multidimensional image data.
*
* This class is the main gateway into the application. It creates and displays
* a VisBioFrame via reflection, so that the splash screen appears as quickly
* as possible, before the class loader gets too far along.
*/
public class VisBio {
// -- Constants --
/** Application title. */
public static final String TITLE = "VisBio";
/** Application version. */
public static final String VERSION = "v3.00 beta4a";
/** Application author. */
public static final String AUTHOR = "Curtis Rueden, LOCI";
/** Application build date. */
public static final String DATE = "19 March 2005";
// -- Constructor --
/** Ensure this class can't be instantiated. */
private VisBio() { }
// -- Main --
/** Launches the VisBio GUI. */
public static void main(String[] args)
throws ClassNotFoundException, IllegalAccessException,
InstantiationException, InvocationTargetException, NoSuchMethodException
{
// display splash screen
String[] msg = {
TITLE + " " + VERSION + " - " + AUTHOR,
"VisBio is starting up..."
};
SplashScreen ss = new SplashScreen(
VisBio.class.getResource("visbio-logo.png"),
msg, new Color(255, 255, 220), new Color(255, 50, 50));
ss.show();
// construct VisBio interface via reflection
Class vb = Class.forName("loci.visbio.VisBioFrame");
Constructor con = vb.getConstructor(new Class[] {ss.getClass()});
con.newInstance(new Object[] {ss});
}
}
|
// VisBio.java
package loci.visbio;
import java.awt.Color;
import java.io.IOException;
import java.lang.reflect.*;
import loci.visbio.util.InstanceServer;
import loci.visbio.util.SplashScreen;
/**
* VisBio is a biological visualization tool designed for easy
* visualization and analysis of multidimensional image data.
*
* This class is the main gateway into the application. It creates and displays
* a VisBioFrame via reflection, so that the splash screen appears as quickly
* as possible, before the class loader gets too far along.
*/
public class VisBio {
// -- Constants --
/** Application title. */
public static final String TITLE = "VisBio";
/** Application version. */
public static final String VERSION = "v3.21a";
/** Application author. */
public static final String AUTHOR = "Curtis Rueden, LOCI";
/** Application build date. */
public static final String DATE = "20 December 2005";
/** Port to use for communicating between application instances. */
public static final int INSTANCE_PORT = 0xabcd;
// -- Constructor --
/** Ensure this class can't be instantiated. */
private VisBio() { }
// -- VisBio API methods --
/** Launches the VisBio GUI with no arguments, in a separate thread. */
public static void startProgram() {
new Thread() {
public void run() {
try { launch(new String[0]); }
catch (Exception exc) { exc.printStackTrace(); }
}
}.start();
}
/** Launches VisBio, returning the newly constructed VisBioFrame object. */
public static Object launch(String[] args)
throws ClassNotFoundException, IllegalAccessException,
InstantiationException, InvocationTargetException, NoSuchMethodException
{
// check whether VisBio is already running
boolean isRunning = true;
try { InstanceServer.sendArguments(args, INSTANCE_PORT); }
catch (IOException exc) { isRunning = false; }
if (isRunning) return null;
// display splash screen
String[] msg = {
TITLE + " " + VERSION + " - " + AUTHOR,
"VisBio is starting up..."
};
SplashScreen ss = new SplashScreen(
VisBio.class.getResource("visbio-logo.png"),
msg, new Color(255, 255, 220), new Color(255, 50, 50));
ss.show();
// toggle window decoration mode via reflection
boolean b = "true".equals(System.getProperty("visbio.decorateWindows"));
Class jf = Class.forName("javax.swing.JFrame");
Method m = jf.getMethod("setDefaultLookAndFeelDecorated",
new Class[] {boolean.class});
m.invoke(null, new Object[] {new Boolean(b)});
// construct VisBio interface via reflection
Class vb = Class.forName("loci.visbio.VisBioFrame");
Constructor con = vb.getConstructor(new Class[] {
ss.getClass(), String[].class
});
return con.newInstance(new Object[] {ss, args});
}
// -- Main --
/** Launches the VisBio GUI. */
public static void main(String[] args)
throws ClassNotFoundException, IllegalAccessException,
InstantiationException, InvocationTargetException, NoSuchMethodException
{
Object o = launch(args);
if (o == null) System.out.println("VisBio is already running.");
}
}
|
package com.qwertygid.deutschsim.GUI;
import javax.swing.AbstractAction;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JSplitPane;
import javax.swing.JScrollPane;
import javax.swing.JPanel;
import org.apache.commons.math3.complex.Complex;
import org.apache.commons.math3.linear.FieldVector;
import javax.swing.JTextPane;
import javax.swing.KeyStroke;
import javax.swing.JCheckBox;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.JMenuBar;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.io.File;
import java.io.IOException;
import com.qwertygid.deutschsim.IO.Serializer;
import com.qwertygid.deutschsim.Logic.Circuit;
import com.qwertygid.deutschsim.Miscellaneous.Tools;
public class GUI {
public GUI() {
frame = new JFrame("DeutschSim - Untitled");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(640, 480);
frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
SwingUtilities.updateComponentTreeUI(frame);
} catch (Exception e) {
Tools.error(frame, "Failed to set up the system look & feel, using" +
"the standard Swing look & feel");
}
setup();
frame.setVisible(true);
}
public void setup() {
JSplitPane main_split_pane = create_main_split_pane();
JSplitPane child_split_pane = setup_main_split_pane_top(main_split_pane);
setup_main_split_pane_bottom(main_split_pane);
setup_child_split_pane_left(child_split_pane);
setup_child_split_pane_right(child_split_pane);
JMenuBar menu_bar = create_menu_bar();
JMenu file_menu = create_menu("File", menu_bar);
add_item_new(file_menu);
add_item_open(file_menu);
add_item_save(file_menu);
add_item_save_as(file_menu);
file_menu.addSeparator();
add_item_load_circuit_gate(file_menu);
file_menu.addSeparator();
add_item_quit(file_menu);
JMenu circuit_menu = create_menu("Circuit", menu_bar);
add_item_simulate(circuit_menu);
add_item_change_qubits(circuit_menu);
circuit_menu.addSeparator();
add_item_create_custom_gate(circuit_menu);
JMenu help_menu = create_menu("Help", menu_bar);;
add_item_about(help_menu);
}
// Window GUI setup functions
private JSplitPane create_main_split_pane() {
JSplitPane main_split_pane = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
main_split_pane.setResizeWeight(main_split_pane_resize_weight);
frame.getContentPane().add(main_split_pane);
return main_split_pane;
}
private JSplitPane setup_main_split_pane_top(final JSplitPane split_pane) {
JSplitPane child_split_pane = new JSplitPane();
child_split_pane.setResizeWeight(child_split_pane_resize_weight);
split_pane.setLeftComponent(child_split_pane);
return child_split_pane;
}
private void setup_main_split_pane_bottom(final JSplitPane split_pane) {
JScrollPane list_scroll_pane = new JScrollPane();
split_pane.setRightComponent(list_scroll_pane);
gate_list = new GateList(gate_table_cell_size);
list_scroll_pane.setViewportView(gate_list);
}
private void setup_child_split_pane_left(final JSplitPane split_pane) {
JScrollPane quantum_system_scroll_pane = new JScrollPane();
split_pane.setLeftComponent(quantum_system_scroll_pane);
JPanel quantum_system_panel = new JPanel();
quantum_system_scroll_pane.setViewportView(quantum_system_panel);
qubit_table = new QubitTable(gate_table_row_height, qubit_table_column_width);
GridBagConstraints gbc_qubit_table = new GridBagConstraints();
gbc_qubit_table.gridx = 0;
gbc_qubit_table.gridy = 0;
quantum_system_panel.add(qubit_table, gbc_qubit_table);
gate_table = new GateTable(gate_table_cell_size, gate_table_row_height, frame);
GridBagConstraints gbc_gate_table = new GridBagConstraints();
gbc_gate_table.gridx = 1;
gbc_gate_table.gridy = 0;
quantum_system_panel.add(gate_table, gbc_gate_table);
GridBagLayout gbl_quantum_system_panel = new GridBagLayout();
gbl_quantum_system_panel.columnWidths = new int[]{qubit_table.getWidth(), gate_table.getWidth(), 0};
gbl_quantum_system_panel.rowHeights = new int[]{qubit_table.getHeight(), 0};
gbl_quantum_system_panel.columnWeights = new double[]{0.0, 0.0, Double.MIN_VALUE};
gbl_quantum_system_panel.rowWeights = new double[]{0.0, Double.MIN_VALUE};
quantum_system_panel.setLayout(gbl_quantum_system_panel);
}
private void setup_child_split_pane_right(final JSplitPane split_pane){
JScrollPane result_scroll_pane = new JScrollPane();
split_pane.setRightComponent(result_scroll_pane);
JPanel result_panel = new JPanel();
result_panel.setLayout(new BoxLayout(result_panel, BoxLayout.Y_AXIS));
result_scroll_pane.setViewportView(result_panel);
result_text_pane = new JTextPane();
result_text_pane.setEditable(false);
result_panel.add(result_text_pane);
JPanel checkbox_panel = new JPanel();
result_panel.add(checkbox_panel);
show_all_checkbox = new JCheckBox("Show all");
checkbox_panel.add(show_all_checkbox);
JScrollPane scrollPane = new JScrollPane();
result_panel.add(scrollPane);
}
// Menu setup functions
private JMenuBar create_menu_bar() {
JMenuBar menu_bar = new JMenuBar();
frame.setJMenuBar(menu_bar);
return menu_bar;
}
private JMenu create_menu(final String name, final JMenuBar menu_bar) {
JMenu menu = new JMenu(name);
menu_bar.add(menu);
return menu;
}
private void add_item_new(final JMenu file_menu) {
JMenuItem item_new = new JMenuItem(new AbstractAction("New") {
private static final long serialVersionUID = 3699016056959009199L;
@Override
public void actionPerformed(ActionEvent arg0) {
frame.getContentPane().removeAll();
setup();
// TODO add restoration of JSplitPanes' panels' sizes
frame.validate();
frame.setTitle("DeutschSim - Untitled");
current_file = null;
}
});
item_new.setAccelerator(KeyStroke.getKeyStroke('N', menu_mask));
file_menu.add(item_new);
}
private void add_item_open(final JMenu file_menu) {
JMenuItem item_open = new JMenuItem(new AbstractAction("Open") {
private static final long serialVersionUID = -4441750652720636192L;
@Override
public void actionPerformed(ActionEvent arg0) {
JFileChooser file_chooser = new JFileChooser();
file_chooser.setCurrentDirectory(new File("."));
FileNameExtensionFilter filter = new FileNameExtensionFilter(
"DeutschSim circuits", "dcirc");
file_chooser.setFileFilter(filter);
final int return_value = file_chooser.showOpenDialog(frame);
if (return_value == JFileChooser.APPROVE_OPTION) {
File file = file_chooser.getSelectedFile();
Serializer serializer = null;
try {
// Serializer constructor automatically calls valid() on itself
serializer = new Serializer(file);
} catch (RuntimeException | IOException ex) {
Tools.error(frame, "An exception has been caught:\n" +
ex.getMessage());
return;
}
qubit_table.set_qubits(serializer.get_qubit_sequence());
qubit_table.update_table();
gate_table.set_table(serializer.get_circuit().get_gates_table());
gate_table.update_size();
current_file = file;
frame.setTitle("DeutschSim - " + current_file.getName());
result_text_pane.setText("");
}
}
});
item_open.setAccelerator(KeyStroke.getKeyStroke('O', menu_mask));
file_menu.add(item_open);
}
private void add_item_save(final JMenu file_menu) {
JMenuItem item_save = new JMenuItem(new AbstractAction("Save") {
private static final long serialVersionUID = -4441750652720636192L;
@Override
public void actionPerformed(ActionEvent arg0) {
if (current_file == null) {
JFileChooser file_chooser = new JFileChooser() {
private static final long serialVersionUID = 4649847794719144813L;
@Override
public void approveSelection() {
File file = getSelectedFile();
if (file.exists()) {
final int result = JOptionPane.showConfirmDialog(this,
"The file exists, overwrite?", "File exists",
JOptionPane.YES_NO_OPTION);
if (result == JOptionPane.YES_OPTION)
super.approveSelection();
return;
}
super.approveSelection();
}
};
file_chooser.setCurrentDirectory(new File("."));
file_chooser.setSelectedFile(new File(".dcirc"));
FileNameExtensionFilter filter = new FileNameExtensionFilter(
"DeutschSim circuits", "dcirc");
file_chooser.setFileFilter(filter);
final int return_value = file_chooser.showSaveDialog(frame);
if (return_value == JFileChooser.APPROVE_OPTION) {
current_file = file_chooser.getSelectedFile();
frame.setTitle("DeutschSim - " + current_file.getName());
}
}
save();
}
private void save() {
try {
Serializer serializer = new Serializer(qubit_table.get_qubits(),
new Circuit(gate_table.get_table()));
serializer.serialize(current_file);
} catch (RuntimeException|IOException ex) {
Tools.error(frame, "An exception has been caught:\n" +
ex.getMessage());
}
}
});
item_save.setAccelerator(KeyStroke.getKeyStroke('S', menu_mask));
file_menu.add(item_save);
}
private void add_item_save_as(final JMenu file_menu) {
JMenuItem item_save_as = new JMenuItem("Save As");
item_save_as.setAccelerator(KeyStroke.getKeyStroke('S', menu_mask | KeyEvent.SHIFT_DOWN_MASK));
file_menu.add(item_save_as);
}
private void add_item_load_circuit_gate(final JMenu file_menu) {
JMenuItem item_load_circuit_gate = new JMenuItem("Load Gate");
item_load_circuit_gate.setAccelerator(KeyStroke.getKeyStroke('L', menu_mask));
file_menu.add(item_load_circuit_gate);
}
private void add_item_quit(final JMenu file_menu) {
JMenuItem item_quit = new JMenuItem(new AbstractAction("Quit") {
private static final long serialVersionUID = -4441750652720636192L;
@Override
public void actionPerformed(ActionEvent e) {
frame.dispose();
}
});
item_quit.setAccelerator(KeyStroke.getKeyStroke('Q', menu_mask));
file_menu.add(item_quit);
}
private void add_item_simulate(final JMenu circuit_menu) {
JMenuItem item_simulate = new JMenuItem(new AbstractAction("Simulate") {
private static final long serialVersionUID = 8549028014281850661L;
@Override
public void actionPerformed(ActionEvent arg0) {
try {
Circuit circuit = new Circuit(gate_table.get_table());
FieldVector<Complex> results = circuit.operate(qubit_table.get_qubits());
StringBuilder text = new StringBuilder("Simulation results:\n");
final int qubits_number = Integer.toBinaryString(results.getDimension() - 1).length();
for (int index = 0; index < results.getDimension(); index++) {
final Complex current = results.getEntry(index);
final double current_magnitude = current.abs();
if (!show_all_checkbox.isSelected() && Tools.equal(current_magnitude, 0))
continue;
double current_percentage = Math.pow(current_magnitude, 2) * 100;
if (Tools.equal(current_percentage, Math.round(current_percentage)))
current_percentage = Math.round(current_percentage);
StringBuilder qubits_values = new StringBuilder(Integer.toBinaryString(index));
for (int length = qubits_values.length(); length < qubits_number; length++)
qubits_values.insert(0, '0');
text.append(current.getReal() + (current.getImaginary() < 0 ? "" : "+") +
current.getImaginary() + "i |" + qubits_values + ">\t" +
current_percentage + "% chance\n");
}
result_text_pane.setText(text.toString());
} catch (RuntimeException ex) {
Tools.error(frame, "A runtime exception has been caught:\n" + ex.getMessage());
ex.printStackTrace();
}
}
});
item_simulate.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_W, 0));
circuit_menu.add(item_simulate);
}
private void add_item_change_qubits(final JMenu circuit_menu) {
JMenuItem item_change_qubits = new JMenuItem(new AbstractAction("Change Qubits") {
private static final long serialVersionUID = 8549028014281850661L;
@Override
public void actionPerformed(ActionEvent arg0) {
String new_qubits = (String) JOptionPane.showInputDialog(frame, "Enter a qubit sequence:",
"Change Qubits", JOptionPane.PLAIN_MESSAGE);
if (new_qubits == null)
return;
else if (!new_qubits.matches("[01]+")) {
Tools.error(frame, "The provided string is not a valid qubit sequence.\n" +
"A valid qubit sequence contains one or more '0' or '1' characters.");
return;
}
qubit_table.set_qubits(new_qubits);
qubit_table.update_table();
// TODO maybe instead of emptying the whole table this function should instead
// append/remove rows?
gate_table.get_table().empty();
for (int qubit = 0; qubit < qubit_table.get_qubits().length(); qubit++)
gate_table.get_table().add_row();
gate_table.get_table().add_col();
gate_table.update_size();
}
});
item_change_qubits.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Q, 0));
circuit_menu.add(item_change_qubits);
}
private void add_item_create_custom_gate(final JMenu circuit_menu) {
JMenuItem item_create_custom_gate = new JMenuItem("Create Custom Gate");
item_create_custom_gate.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_G, 0));
circuit_menu.add(item_create_custom_gate);
}
private void add_item_about(final JMenu help_menu) {
JMenuItem item_about = new JMenuItem("About");
help_menu.add(item_about);
}
private JFrame frame;
private QubitTable qubit_table;
private GateTable gate_table;
private JTextPane result_text_pane;
private JCheckBox show_all_checkbox;
private GateList gate_list;
private File current_file;
private static final int gate_table_cell_size = 43,
gate_table_row_height = gate_table_cell_size + 2,
qubit_table_column_width = 25;
private static final double main_split_pane_resize_weight = 0.85,
child_split_pane_resize_weight = 0.8;
private final static int menu_mask = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask();
}
|
package org.neo4j.impl.shell.apps;
import java.rmi.RemoteException;
import java.util.regex.Pattern;
import org.neo4j.api.core.Direction;
import org.neo4j.api.core.Node;
import org.neo4j.api.core.Relationship;
import org.neo4j.util.shell.AppCommandParser;
import org.neo4j.util.shell.OptionValueType;
import org.neo4j.util.shell.Output;
import org.neo4j.util.shell.Session;
import org.neo4j.util.shell.ShellException;
/**
* Mimics the POSIX application with the same name, i.e. lists
* properties/relationships on a node.
*/
public class Ls extends NodeOrRelationshipApp
{
/**
* Constructs a new "ls" application.
*/
public Ls()
{
super();
this.addValueType( "d", new OptionContext( OptionValueType.MUST,
"Direction filter for relationships: "
+ this.directionAlternatives() ) );
this.addValueType( "v", new OptionContext( OptionValueType.NONE,
"Verbose mode" ) );
this.addValueType( "q", new OptionContext( OptionValueType.NONE,
"Quiet mode" ) );
this.addValueType( "p", new OptionContext( OptionValueType.NONE,
"Lists properties" ) );
this.addValueType( "r", new OptionContext( OptionValueType.NONE,
"Lists relationships" ) );
this.addValueType( "f", new OptionContext( OptionValueType.MUST,
"Filters property keys/relationship types (regexp string)" ) );
this.addValueType( "e", new OptionContext( OptionValueType.MUST,
"Temporarily select a connected relationship to do the "
+ "operation on" ) );
}
@Override
public String getDescription()
{
return "Lists the current node. Optionally supply node id for "
+ "listing a certain node: ls <node-id>";
}
@Override
protected String exec( AppCommandParser parser, Session session, Output out )
throws ShellException, RemoteException
{
boolean verbose = parser.options().containsKey( "v" );
boolean displayValues = verbose || !parser.options().containsKey( "q" );
boolean displayProperties = parser.options().containsKey( "p" );
boolean displayRelationships = parser.options().containsKey( "r" );
String filter = parser.options().get( "f" );
if ( !displayProperties && !displayRelationships )
{
displayProperties = true;
displayRelationships = true;
}
Node node = null;
if ( parser.arguments().isEmpty() )
{
node = this.getCurrentNode( session );
}
else
{
node = this.getNodeById( Long
.parseLong( parser.arguments().get( 0 ) ) );
}
NodeOrRelationship thing = getNodeOrRelationship( node, parser );
this.displayProperties( thing, out, displayProperties, displayValues,
verbose, filter );
this.displayRelationships( parser, thing, out, displayRelationships,
verbose, filter );
return null;
}
private void displayProperties( NodeOrRelationship thing, Output out,
boolean displayProperties, boolean displayValues, boolean verbose,
String filter ) throws RemoteException
{
if ( !displayProperties )
{
return;
}
int longestKey = this.findLongestKey( thing );
Pattern propertyKeyPattern = filter == null ? null : Pattern
.compile( filter );
for ( String key : thing.getPropertyKeys() )
{
if ( propertyKeyPattern != null
&& !propertyKeyPattern.matcher( key ).find() )
{
continue;
}
out.print( "*" + key );
if ( displayValues )
{
this.printMany( out, " ", longestKey - key.length() + 1 );
Object value = thing.getProperty( key );
out.print( "=[" + value + "]" );
if ( verbose )
{
out.print( " (" + this.getNiceType( value ) + ")" );
}
}
out.println( "" );
}
}
private void displayRelationships( AppCommandParser parser,
NodeOrRelationship thing, Output out, boolean displayRelationships,
boolean verbose, String filter ) throws ShellException, RemoteException
{
if ( !displayRelationships )
{
return;
}
String directionFilter = parser.options().get( "d" );
Direction direction = this.getDirection( directionFilter );
boolean displayOutgoing = directionFilter == null
|| direction == Direction.OUTGOING;
boolean displayIncoming = directionFilter == null
|| direction == Direction.INCOMING;
Pattern filterPattern = filter == null ? null : Pattern
.compile( filter );
if ( displayOutgoing )
{
for ( Relationship rel : thing
.getRelationships( Direction.OUTGOING ) )
{
if ( filterPattern != null
&& !filterPattern.matcher( rel.getType().name() ).matches() )
{
continue;
}
StringBuffer buf = new StringBuffer(
getDisplayNameForCurrentNode() );
buf.append( " --[" ).append( rel.getType().name() );
if ( verbose )
{
buf.append( ", " ).append( rel.getId() );
}
buf.append( "]
buf.append( getDisplayNameForNode( rel.getEndNode() ) );
out.println( buf );
}
}
if ( displayIncoming )
{
for ( Relationship rel : thing
.getRelationships( Direction.INCOMING ) )
{
if ( filterPattern != null
&& !filterPattern.matcher( rel.getType().name() ).matches() )
{
continue;
}
StringBuffer buf = new StringBuffer(
getDisplayNameForCurrentNode() );
buf.append( " <--[" ).append( rel.getType().name() );
if ( verbose )
{
buf.append( ", " ).append( rel.getId() );
}
buf.append( "]
buf.append( getDisplayNameForNode( rel.getStartNode() ) );
out.println( buf );
}
}
}
private String getNiceType( Object value )
{
String cls = value.getClass().getName();
return cls.substring( String.class.getPackage().getName().length() + 1 );
}
private int findLongestKey( NodeOrRelationship thing )
{
int length = 0;
for ( String key : thing.getPropertyKeys() )
{
if ( key.length() > length )
{
length = key.length();
}
}
return length;
}
}
|
package jlibs.core.nio;
import jlibs.core.net.SSLUtil;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.TrustManagerFactory;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.ServerSocketChannel;
import java.security.KeyStore;
import java.util.ArrayList;
import java.util.List;
/**
* @author Santhosh Kumar T
*/
public class Proxy implements IOEvent<ServerChannel>{
Endpoint inboundEndpoint, outboundEndpoint;
private ServerChannel server;
public Proxy(Endpoint inboundEndpoint, Endpoint outboundEndpoint) throws IOException{
this.inboundEndpoint = inboundEndpoint;
this.outboundEndpoint = outboundEndpoint;
server = new ServerChannel(ServerSocketChannel.open());
server.bind(inboundEndpoint.address);
server.attach(this);
}
private int count;
public static SSLEngine createSSLEngine(boolean clientMode) throws IOException{
try{
SSLContext sslContext = SSLContext.getInstance("TLS");
if(clientMode){
sslContext.init(null, null, null);
}else{
KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
kmf.init(SSLUtil.newKeyStore(), SSLUtil.getKeyStorePassword());
sslContext.init(kmf.getKeyManagers(), null, null);
}
SSLEngine engine = sslContext.createSSLEngine();
engine.setUseClientMode(clientMode);
return engine;
}catch(Exception ex) {
throw new IOException(ex);
}
}
@Override
public void process(NIOSelector nioSelector, ServerChannel server) throws IOException{
ClientChannel inboundClient = server.accept(nioSelector);
if(inboundClient==null)
return;
count++;
ClientChannel outboundClient = nioSelector.newClient();
try{
System.out.println(" Inbound"+count+": client"+inboundClient.id+" accepted");
if(inboundEndpoint.enableSSL)
inboundClient.enableSSL(/*createSSLEngine(false)*/);
ByteBuffer buffer1 = ByteBuffer.allocate(9000);
ByteBuffer buffer2 = ByteBuffer.allocate(9000);
ClientListener inboundListener = new ClientListener(" Inbound"+count, buffer1, buffer2, null, outboundClient);
SSLEngine outboundSSLEngine = outboundEndpoint.enableSSL ? createSSLEngine(true) : null;
ClientListener outboundListener = new ClientListener("Outbound"+count, buffer2, buffer1, outboundSSLEngine, inboundClient);
inboundClient.attach(inboundListener);
outboundClient.attach(outboundListener);
if(outboundClient.connect(outboundEndpoint.address))
outboundListener.onConnect(outboundClient);
else
outboundClient.addInterest(ClientChannel.OP_CONNECT);
inboundClient.addInterest(ClientChannel.OP_READ);
}catch(Exception ex){
inboundClient.close();
outboundClient.close();
if(ex instanceof IOException)
throw (IOException)ex;
else
throw (RuntimeException)ex;
}
}
public static void main(String[] args) throws IOException{
System.setErr(System.out);
final NIOSelector nioSelector = new NIOSelector(5000);
if(args.length==0){
args = new String[]{
"tcp://localhost:1111=tcp://apigee.com:80",
"ssl://localhost:2222=tcp://apigee.com:80",
"tcp://localhost:3333=ssl://blog.torproject.org:443",
"ssl://localhost:4444=ssl://blog.torproject.org:443",
};
}
final List<Proxy> proxies = new ArrayList<Proxy>(args.length);
for(String arg: args){
int equal = arg.indexOf("=");
if(equal==-1)
throw new IllegalArgumentException();
String inbound = arg.substring(0, equal);
String outbound = arg.substring(equal+1);
Proxy proxy = new Proxy(new Endpoint(inbound), new Endpoint(outbound));
proxy.server.register(nioSelector);
proxies.add(proxy);
System.out.println("added proxy: "+inbound+" -> "+outbound);
}
final Thread nioThread = Thread.currentThread();
Runtime.getRuntime().addShutdownHook(new Thread(){
@Override
public void run(){
System.out.println("shutdown initiated");
nioSelector.shutdown();
try{
nioThread.join();
}catch(InterruptedException ex){
ex.printStackTrace();
}
for(Proxy proxy: proxies){
try{
proxy.server.close();
}catch (IOException ex){
ex.printStackTrace();
}
}
}
});
for(NIOChannel channel: nioSelector){
try{
((IOEvent)channel.attachment()).process(nioSelector, channel);
}catch(IOException ex){
ex.printStackTrace();
}
}
System.out.println("finished shutdown");
}
}
class Endpoint{
InetSocketAddress address;
boolean enableSSL;
public Endpoint(String str){
if(str.startsWith("tcp:
enableSSL = false;
str = str.substring("tcp://".length());
}else if(str.startsWith("ssl:
enableSSL = true;
str = str.substring("ssl://".length());
}else
throw new IllegalArgumentException();
int colon = str.indexOf(':');
if(colon==-1)
throw new IllegalArgumentException();
String host = str.substring(0, colon);
int port = Integer.parseInt(str.substring(colon+1));
address = new InetSocketAddress(host, port);
}
}
class ClientListener implements IOEvent<ClientChannel>{
private String name;
private ByteBuffer readBuffer, writeBuffer;
private SSLEngine engine;
private ClientChannel buddy;
ClientListener(String name, ByteBuffer readBuffer, ByteBuffer writeBuffer, SSLEngine engine, ClientChannel buddy){
this.name = name;
this.readBuffer = readBuffer;
this.writeBuffer = writeBuffer;
this.engine = engine;
this.buddy = buddy;
}
public void onConnect(ClientChannel client) throws IOException{
System.out.println(this+": Connection established");
if(engine!=null)
client.enableSSL(/*engine*/);
client.addInterest(ClientChannel.OP_READ);
}
int readCount, writeCount;
int lastRead, lastWrote;
@Override
public void process(NIOSelector nioSelector, ClientChannel client) throws IOException{
// System.out.println(this+": isReadable="+isReadable+" isWritable="+isWritable);
if(client.isTimeout()){
if(buddy.isOpen() && buddy.isTimeout()){
System.out.println(name+" timedout");
client.close();
buddy.close();
}
}
try{
if(client.isConnectable()){
if(client.finishConnect())
onConnect(client);
else
return;
}
if(client.isReadable()){
readBuffer.clear();
int read = client.read(readBuffer);
lastRead = read;
if(read==-1){
client.close();
if((buddy.interests()&ClientChannel.OP_WRITE)==0)
buddy.close();
}else if(read>0){
readCount++;
if(buddy.isOpen()){
readBuffer.flip();
buddy.addInterest(SelectionKey.OP_WRITE);
}else
client.close();
}else
client.addInterest(SelectionKey.OP_READ);
}
if(client.isWritable()){
int wrote = client.write(writeBuffer);
lastWrote = wrote;
if(writeBuffer.hasRemaining()){
writeCount++;
client.addInterest(SelectionKey.OP_WRITE);
}else{
if(buddy.isOpen()){
writeBuffer.flip();
buddy.addInterest(SelectionKey.OP_READ);
}else
client.close();
}
}
}catch(Exception ex){
client.close();
buddy.close();
if(ex instanceof IOException)
throw (IOException)ex;
else
throw (RuntimeException)ex;
}
if(client.interests()==0 && buddy.interests()==0){
System.out.println(this+": closing...");
client.close();
buddy.close();
}
}
@Override
public String toString(){
return name;
}
}
interface IOEvent<T extends NIOChannel>{
public void process(NIOSelector nioSelector, T channel) throws IOException;
}
|
package com.intellij.lang.ant;
import com.intellij.lang.CompositeLanguage;
import com.intellij.lang.StdLanguages;
import com.intellij.lang.ant.psi.AntFile;
import com.intellij.lang.ant.psi.changes.AntChangeVisitor;
import com.intellij.lang.xml.XMLLanguage;
import com.intellij.openapi.components.ApplicationComponent;
import com.intellij.openapi.fileTypes.FileType;
import com.intellij.openapi.fileTypes.FileTypeManager;
import com.intellij.openapi.fileTypes.LanguageFileType;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.FileViewProvider;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiManager;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.*;
public class AntSupport implements ApplicationComponent {
private static LanguageFileType ourFileType = null;
private static AntLanguage ourLanguage = null;
private static AntChangeVisitor ourChangeVisitor = null;
private static final Map<AntFile, WeakHashMap<AntFile, Boolean>> ourFileDependencies = new WeakHashMap<AntFile, WeakHashMap<AntFile, Boolean>>();
public AntSupport(FileTypeManager fileTypeManager) {
fileTypeManager.getRegisteredFileTypes();
((CompositeLanguage)StdLanguages.XML).registerLanguageExtension(new AntLanguageExtension());
}
public static synchronized AntLanguage getLanguage() {
if (ourLanguage == null) {
if (ourFileType == null) {
ourFileType = new AntFileType();
}
ourLanguage = (AntLanguage)ourFileType.getLanguage();
}
return ourLanguage;
}
public static synchronized AntChangeVisitor getChangeVisitor() {
if (ourChangeVisitor == null) {
ourChangeVisitor = new AntChangeVisitor();
}
return ourChangeVisitor;
}
@NotNull
@NonNls
public String getComponentName() {
return "AntSupport";
}
public void initComponent() {
}
public void disposeComponent() {
}
public static void markFileAsAntFile(final VirtualFile file, final FileViewProvider viewProvider, final boolean value) {
if (file.isValid() && ForcedAntFileAttribute.isAntFile(file) != value) {
ForcedAntFileAttribute.forceAntFile(file, value);
viewProvider.contentsSynchronized();
}
}
// Managing ant files dependencies via the <import> task.
public static synchronized List<AntFile> getImportingFiles(final AntFile imported) {
final WeakHashMap<AntFile, Boolean> files = ourFileDependencies.get(imported);
if (files != null) {
final int size = files.size();
if (size > 0) {
final List<AntFile> result = new ArrayList<AntFile>(size);
for (final AntFile file : files.keySet()) {
if (file != null) {
result.add(file);
}
}
return result;
}
}
return Collections.emptyList();
}
public static synchronized void registerDependency(final AntFile importing, final AntFile imported) {
final Map<AntFile, WeakHashMap<AntFile,Boolean>> dependencies = ourFileDependencies;
WeakHashMap<AntFile, Boolean> files = dependencies.get(imported);
if(files == null) {
files = new WeakHashMap<AntFile, Boolean>();
dependencies.put(imported, files);
}
files.put(importing, true);
}
public static AntFile getAntFile ( PsiFile psiFile ) {
if (psiFile instanceof AntFile) {
return (AntFile)psiFile;
}
else {
return (AntFile)psiFile.getViewProvider().getPsi(getLanguage());
}
}
@Nullable
public static AntFile toAntFile(VirtualFile vFile, final Project project) {
if (vFile == null) {
return null;
}
final FileType fileType = vFile.getFileType();
if (fileType instanceof AntFileType || XMLLanguage.INSTANCE.getAssociatedFileType() == fileType) {
final PsiFile psiFile = PsiManager.getInstance(project).findFile(vFile);
return psiFile != null? getAntFile(psiFile) : null;
}
return null;
}
}
|
package com.google.cordova;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import org.apache.cordova.CordovaArgs;
import org.apache.cordova.CordovaResourceApi;
import org.apache.cordova.CordovaResourceApi.OpenForReadResult;
import org.apache.cordova.JSONUtils;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.net.Uri;
import android.util.Log;
public class ChromeStorage extends CordovaPlugin {
private static final String LOG_TAG = "ChromeStorage";
@Override
public boolean execute(String action, CordovaArgs args, final CallbackContext callbackContext) throws JSONException {
if ("get".equals(action)) {
get(args, callbackContext);
return true;
} else if ("getBytesInUse".equals(action)) {
getBytesInUse(args, callbackContext);
return true;
} else if ("set".equals(action)) {
set(args, callbackContext);
return true;
} else if ("remove".equals(action)) {
remove(args, callbackContext);
return true;
} else if ("clear".equals(action)) {
clear(args, callbackContext);
return true;
}
return false;
}
private Uri getStorageFile(String namespace) {
String fileName = "__chromestorage_" + namespace;
File f = cordova.getActivity().getFileStreamPath(fileName);
return webView.getResourceApi().remapUri(Uri.fromFile(f));
}
private JSONObject getStorage(String namespace) throws IOException, JSONException {
JSONObject oldMap = new JSONObject();
CordovaResourceApi resourceApi = webView.getResourceApi();
try {
OpenForReadResult readResult = resourceApi.openForRead(getStorageFile(namespace));
ByteArrayOutputStream readBytes = new ByteArrayOutputStream((int)readResult.length);
resourceApi.copyResource(readResult, readBytes);
byte[] bytes = readBytes.toByteArray();
String content = (new String(bytes)).trim();
if (content.length() > 0) {
oldMap = new JSONObject(content);
}
} catch (FileNotFoundException e) {
//Suppress the file not found exception
}
return oldMap;
}
private void setStorage(String namespace, JSONObject map) throws IOException {
OutputStream outputStream = webView.getResourceApi().openOutputStream(getStorageFile(namespace));
try {
outputStream.write(map.toString().getBytes());
} finally {
outputStream.close();
}
}
private JSONObject getStoredValuesForKeys(CordovaArgs args, boolean useDefaultValues) {
JSONObject ret = new JSONObject();
try {
String namespace = args.getString(0);
JSONObject jsonObject = (JSONObject) args.optJSONObject(1);
JSONArray jsonArray = args.optJSONArray(1);
boolean isNull = args.isNull(1);
List<String> keys = new ArrayList<String>();
if (jsonObject != null) {
keys = JSONUtils.toStringList(jsonObject.names());
// Ensure default values of keys are maintained
if (useDefaultValues) {
ret = jsonObject;
}
} else if (jsonArray != null) {
keys = JSONUtils.toStringList(jsonArray);
} else if (isNull) {
keys = null;
}
if (keys != null && keys.isEmpty()) {
ret = new JSONObject();
} else {
JSONObject storage = getStorage(namespace);
if (keys == null) {
// return the whole storage if the key given is null
ret = storage;
} else {
// return the storage for the keys specified
for (String key : keys) {
if (storage.has(key)) {
Object value = storage.get(key);
ret.put(key, value);
}
}
}
}
} catch (JSONException e) {
Log.e(LOG_TAG, "Storage is corrupted!", e);
ret = null;
} catch (IOException e) {
Log.e(LOG_TAG, "Could not retrieve storage", e);
ret = null;
}
return ret;
}
private void get(final CordovaArgs args, final CallbackContext callbackContext) {
cordova.getThreadPool().execute(new Runnable() {
@Override
public void run() {
JSONObject storage = getStoredValuesForKeys(args, /*useDefaultValues*/ true);
if (storage == null) {
callbackContext.error("Could not retrieve storage");
} else {
callbackContext.success(storage);
}
}
});
}
private void getBytesInUse(final CordovaArgs args, final CallbackContext callbackContext) {
cordova.getThreadPool().execute(new Runnable() {
@Override
public void run() {
//Don't use default values as the keys that don't have values in storage don't affect size
JSONObject storage = getStoredValuesForKeys(args, /*useDefaultValues*/ false);
if (storage == null) {
callbackContext.error("Could not retrieve storage");
} else {
callbackContext.success(storage.toString().getBytes().length);
}
}
});
}
private void set(final CordovaArgs args, final CallbackContext callbackContext) {
cordova.getThreadPool().execute(new Runnable() {
@Override
public void run() {
try {
String namespace = args.getString(0);
JSONObject jsonObject = (JSONObject) args.getJSONObject(1);
JSONArray keyArray = jsonObject.names();
JSONObject oldValues = new JSONObject();
if (keyArray != null) {
List<String> keys = JSONUtils.toStringList(keyArray);
JSONObject storage = getStorage(namespace);
for (String key : keys) {
Object oldValue = storage.opt(key);
if(oldValue != null) {
oldValues.put(key, oldValue);
}
storage.put(key, jsonObject.get(key));
}
setStorage(namespace, storage);
}
callbackContext.success(oldValues);
} catch (Exception e) {
Log.e(LOG_TAG, "Could not update storage", e);
callbackContext.error("Could not update storage");
}
}
});
}
private void remove(final CordovaArgs args, final CallbackContext callbackContext) {
cordova.getThreadPool().execute(new Runnable() {
@Override
public void run() {
try {
String namespace = args.getString(0);
JSONObject jsonObject = (JSONObject) args.optJSONObject(1);
JSONArray jsonArray = args.optJSONArray(1);
boolean isNull = args.isNull(1);
List<String> keys = new ArrayList<String>();
JSONObject oldValues = new JSONObject();
if (jsonObject != null) {
keys = JSONUtils.toStringList(jsonObject.names());
} else if (jsonArray != null) {
keys = JSONUtils.toStringList(jsonArray);
} else if (isNull) {
keys = null;
}
if (keys != null && !keys.isEmpty()) {
JSONObject storage = getStorage(namespace);
for(String key : keys) {
Object oldValue = storage.opt(key);
if(oldValue != null) {
oldValues.put(key, oldValue);
}
storage.remove(key);
}
setStorage(namespace, storage);
}
callbackContext.success(oldValues);
} catch (Exception e) {
Log.e(LOG_TAG, "Could not update storage", e);
callbackContext.error("Could not update storage");
}
}
});
}
private void clear(final CordovaArgs args, final CallbackContext callbackContext) {
cordova.getThreadPool().execute(new Runnable() {
@Override
public void run() {
try {
String namespace = args.getString(0);
JSONObject oldValues = getStorage(namespace);
setStorage(namespace, new JSONObject());
callbackContext.success(oldValues);
} catch (Exception e) {
Log.e(LOG_TAG, "Could not clear storage", e);
callbackContext.error("Could not update storage");
}
}
});
}
}
|
package git4idea.log;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.components.ServiceManager;
import com.intellij.openapi.diagnostic.Attachment;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.registry.Registry;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vcs.FilePath;
import com.intellij.openapi.vcs.VcsException;
import com.intellij.openapi.vcs.VcsKey;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.util.*;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.containers.OpenTHashSet;
import com.intellij.util.messages.MessageBusConnection;
import com.intellij.vcs.log.*;
import com.intellij.vcs.log.data.VcsLogSorter;
import com.intellij.vcs.log.graph.GraphColorManager;
import com.intellij.vcs.log.graph.GraphCommit;
import com.intellij.vcs.log.graph.impl.facade.PermanentGraphImpl;
import com.intellij.vcs.log.impl.HashImpl;
import com.intellij.vcs.log.impl.LogDataImpl;
import com.intellij.vcs.log.util.StopWatch;
import com.intellij.vcs.log.util.UserNameRegex;
import com.intellij.vcs.log.util.VcsUserUtil;
import com.intellij.vcs.log.visible.filters.VcsLogFiltersKt;
import com.intellij.vcsUtil.VcsFileUtil;
import com.intellij.vcsUtil.VcsUtil;
import git4idea.*;
import git4idea.branch.GitBranchUtil;
import git4idea.branch.GitBranchesCollection;
import git4idea.config.GitVersionSpecialty;
import git4idea.history.GitLogUtil;
import git4idea.repo.GitRepository;
import git4idea.repo.GitRepositoryManager;
import git4idea.repo.GitSubmodule;
import git4idea.repo.GitSubmoduleKt;
import gnu.trove.THashSet;
import gnu.trove.TObjectHashingStrategy;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.*;
import static com.intellij.vcs.log.VcsLogFilterCollection.*;
public class GitLogProvider implements VcsLogProvider {
private static final Logger LOG = Logger.getInstance(GitLogProvider.class);
public static final Function<VcsRef, String> GET_TAG_NAME = ref -> ref.getType() == GitRefManager.TAG ? ref.getName() : null;
public static final TObjectHashingStrategy<VcsRef> DONT_CONSIDER_SHA = new TObjectHashingStrategy<VcsRef>() {
@Override
public int computeHashCode(@NotNull VcsRef ref) {
return 31 * ref.getName().hashCode() + ref.getType().hashCode();
}
@Override
public boolean equals(@NotNull VcsRef ref1, @NotNull VcsRef ref2) {
return ref1.getName().equals(ref2.getName()) && ref1.getType().equals(ref2.getType());
}
};
@NotNull private final Project myProject;
@NotNull private final GitVcs myVcs;
@NotNull private final GitRepositoryManager myRepositoryManager;
@NotNull private final VcsLogRefManager myRefSorter;
@NotNull private final VcsLogObjectsFactory myVcsObjectsFactory;
public GitLogProvider(@NotNull Project project) {
myProject = project;
myRepositoryManager = GitRepositoryManager.getInstance(project);
myRefSorter = new GitRefManager(myProject, myRepositoryManager);
myVcsObjectsFactory = ServiceManager.getService(project, VcsLogObjectsFactory.class);
myVcs = GitVcs.getInstance(project);
}
@NotNull
@Override
public DetailedLogData readFirstBlock(@NotNull VirtualFile root, @NotNull Requirements requirements) throws VcsException {
if (!isRepositoryReady(root)) {
return LogDataImpl.empty();
}
GitRepository repository = ObjectUtils.assertNotNull(myRepositoryManager.getRepositoryForRoot(root));
// need to query more to sort them manually; this doesn't affect performance: it is equal for -1000 and -2000
int commitCount = requirements.getCommitCount() * 2;
String[] params = new String[]{GitUtil.HEAD, "--branches", "--remotes", "--max-count=" + commitCount};
// NB: not specifying --tags, because it introduces great slowdown if there are many tags,
// but makes sense only if there are heads without branch or HEAD labels (rare case). Such cases are partially handled below.
boolean refresh = requirements instanceof VcsLogProviderRequirementsEx && ((VcsLogProviderRequirementsEx)requirements).isRefresh();
DetailedLogData data = GitLogUtil.collectMetadata(myProject, root, params);
Set<VcsRef> safeRefs = data.getRefs();
Set<VcsRef> allRefs = new OpenTHashSet<>(safeRefs, DONT_CONSIDER_SHA);
Set<VcsRef> branches = readBranches(repository);
addNewElements(allRefs, branches);
Collection<VcsCommitMetadata> allDetails;
Set<String> currentTagNames = null;
DetailedLogData commitsFromTags = null;
if (!refresh) {
allDetails = data.getCommits();
}
else {
// on refresh: get new tags, which point to commits not from the first block; then get history, walking down just from these tags
// on init: just ignore such tagged-only branches. The price for speed-up.
VcsLogProviderRequirementsEx rex = (VcsLogProviderRequirementsEx)requirements;
currentTagNames = readCurrentTagNames(root);
addOldStillExistingTags(allRefs, currentTagNames, rex.getPreviousRefs());
allDetails = newHashSet(data.getCommits());
Set<String> previousTags = newHashSet(ContainerUtil.mapNotNull(rex.getPreviousRefs(), GET_TAG_NAME));
Set<String> safeTags = newHashSet(ContainerUtil.mapNotNull(safeRefs, GET_TAG_NAME));
Set<String> newUnmatchedTags = remove(currentTagNames, previousTags, safeTags);
if (!newUnmatchedTags.isEmpty()) {
commitsFromTags = loadSomeCommitsOnTaggedBranches(root, commitCount, newUnmatchedTags);
addNewElements(allDetails, commitsFromTags.getCommits());
addNewElements(allRefs, commitsFromTags.getRefs());
}
}
StopWatch sw = StopWatch.start("sorting commits in " + root.getName());
List<VcsCommitMetadata> sortedCommits = VcsLogSorter.sortByDateTopoOrder(allDetails);
sortedCommits = ContainerUtil.getFirstItems(sortedCommits, requirements.getCommitCount());
sw.report();
if (LOG.isDebugEnabled()) {
validateDataAndReportError(root, allRefs, sortedCommits, data, branches, currentTagNames, commitsFromTags);
}
return new LogDataImpl(allRefs, GitBekParentFixer.fixCommits(sortedCommits));
}
private static void validateDataAndReportError(@NotNull final VirtualFile root,
@NotNull final Set<? extends VcsRef> allRefs,
@NotNull final List<? extends VcsCommitMetadata> sortedCommits,
@NotNull final DetailedLogData firstBlockSyncData,
@NotNull final Set<? extends VcsRef> manuallyReadBranches,
@Nullable final Set<String> currentTagNames,
@Nullable final DetailedLogData commitsFromTags) {
StopWatch sw = StopWatch.start("validating data in " + root.getName());
final Set<Hash> refs = ContainerUtil.map2Set(allRefs, VcsRef::getCommitHash);
PermanentGraphImpl.newInstance(sortedCommits, new GraphColorManager<Hash>() {
@Override
public int getColorOfBranch(@NotNull Hash headCommit) {
return 0;
}
@Override
public int getColorOfFragment(@NotNull Hash headCommit, int magicIndex) {
return 0;
}
@Override
public int compareHeads(@NotNull Hash head1, @NotNull Hash head2) {
if (!refs.contains(head1) || !refs.contains(head2)) {
LOG.error("GitLogProvider returned inconsistent data", new Attachment("error-details.txt",
printErrorDetails(root, allRefs, sortedCommits,
firstBlockSyncData, manuallyReadBranches,
currentTagNames, commitsFromTags)));
}
return 0;
}
}, refs);
sw.report();
}
@SuppressWarnings("StringConcatenationInsideStringBufferAppend")
private static String printErrorDetails(@NotNull VirtualFile root,
@NotNull Set<? extends VcsRef> allRefs,
@NotNull List<? extends VcsCommitMetadata> sortedCommits,
@NotNull DetailedLogData firstBlockSyncData,
@NotNull Set<? extends VcsRef> manuallyReadBranches,
@Nullable Set<String> currentTagNames,
@Nullable DetailedLogData commitsFromTags) {
StringBuilder sb = new StringBuilder();
sb.append("[" + root.getName() + "]\n");
sb.append("First block data from Git:\n");
sb.append(printLogData(firstBlockSyncData));
sb.append("\n\nManually read refs:\n");
sb.append(printRefs(manuallyReadBranches));
sb.append("\n\nCurrent tag names:\n");
if (currentTagNames != null) {
sb.append(StringUtil.join(currentTagNames, ", "));
if (commitsFromTags != null) {
sb.append(printLogData(commitsFromTags));
}
else {
sb.append("\n\nCommits from new tags were not read.\n");
}
}
else {
sb.append("\n\nCurrent tags were not read\n");
}
sb.append("\n\nResult:\n");
sb.append("\nCommits (last 100): \n");
sb.append(printCommits(sortedCommits));
sb.append("\nAll refs:\n");
sb.append(printRefs(allRefs));
return sb.toString();
}
@NotNull
private static String printLogData(@NotNull DetailedLogData firstBlockSyncData) {
return String
.format("Last 100 commits:\n%s\nRefs:\n%s", printCommits(firstBlockSyncData.getCommits()), printRefs(firstBlockSyncData.getRefs()));
}
@NotNull
private static String printCommits(@NotNull List<? extends VcsCommitMetadata> commits) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < Math.min(commits.size(), 100); i++) {
GraphCommit<Hash> commit = commits.get(i);
sb.append(
String
.format("%s -> %s\n", commit.getId().toShortString(), StringUtil.join(commit.getParents(), Hash::toShortString, ", ")));
}
return sb.toString();
}
@NotNull
private static String printRefs(@NotNull Set<? extends VcsRef> refs) {
return StringUtil.join(refs, ref -> ref.getCommitHash().toShortString() + " : " + ref.getName(), "\n");
}
private static void addOldStillExistingTags(@NotNull Set<? super VcsRef> allRefs,
@NotNull Set<String> currentTags,
@NotNull Collection<? extends VcsRef> previousRefs) {
for (VcsRef ref : previousRefs) {
if (!allRefs.contains(ref) && currentTags.contains(ref.getName())) {
allRefs.add(ref);
}
}
}
@NotNull
private Set<String> readCurrentTagNames(@NotNull VirtualFile root) throws VcsException {
StopWatch sw = StopWatch.start("reading tags in " + root.getName());
Set<String> tags = newHashSet();
tags.addAll(GitBranchUtil.getAllTags(myProject, root));
sw.report();
return tags;
}
@NotNull
private static <T> Set<T> remove(@NotNull Set<? extends T> original, @NotNull Set<T>... toRemove) {
Set<T> result = newHashSet(original);
for (Set<T> set : toRemove) {
result.removeAll(set);
}
return result;
}
private static <T> void addNewElements(@NotNull Collection<? super T> original, @NotNull Collection<? extends T> toAdd) {
for (T item : toAdd) {
if (!original.contains(item)) {
original.add(item);
}
}
}
@NotNull
private DetailedLogData loadSomeCommitsOnTaggedBranches(@NotNull VirtualFile root,
int commitCount,
@NotNull Collection<String> unmatchedTags) throws VcsException {
StopWatch sw = StopWatch.start("loading commits on tagged branch in " + root.getName());
List<String> params = new ArrayList<>();
params.add("--max-count=" + commitCount);
Set<VcsRef> refs = ContainerUtil.newHashSet();
Set<VcsCommitMetadata> commits = ContainerUtil.newHashSet();
VcsFileUtil.foreachChunk(new ArrayList<>(unmatchedTags), 1, tagsChunk -> {
String[] parameters = ArrayUtil.toStringArray(ContainerUtil.concat(params, tagsChunk));
DetailedLogData logData = GitLogUtil.collectMetadata(myProject, root, parameters);
refs.addAll(logData.getRefs());
commits.addAll(logData.getCommits());
});
sw.report();
return new LogDataImpl(refs, ContainerUtil.newArrayList(commits));
}
@Override
@NotNull
public LogData readAllHashes(@NotNull VirtualFile root, @NotNull final Consumer<? super TimedVcsCommit> commitConsumer) throws VcsException {
if (!isRepositoryReady(root)) {
return LogDataImpl.empty();
}
List<String> parameters = new ArrayList<>(GitLogUtil.LOG_ALL);
parameters.add("--date-order");
final GitBekParentFixer parentFixer = GitBekParentFixer.prepare(myProject, root);
Set<VcsUser> userRegistry = newHashSet();
Set<VcsRef> refs = newHashSet();
GitLogUtil.readTimedCommits(myProject, root, parameters, new CollectConsumer<>(userRegistry), new CollectConsumer<>(refs),
commit -> commitConsumer.consume(parentFixer.fixCommit(commit)));
return new LogDataImpl(refs, userRegistry);
}
@Override
public void readAllFullDetails(@NotNull VirtualFile root, @NotNull Consumer<? super VcsFullCommitDetails> commitConsumer) throws VcsException {
if (!isRepositoryReady(root)) {
return;
}
GitLogUtil.readFullDetails(myProject, root, commitConsumer, shouldIncludeRootChanges(root),
false, true, ArrayUtil.toStringArray(GitLogUtil.LOG_ALL));
}
@Override
public void readFullDetails(@NotNull VirtualFile root,
@NotNull List<String> hashes,
@NotNull Consumer<? super VcsFullCommitDetails> commitConsumer)
throws VcsException {
if (!isRepositoryReady(root)) {
return;
}
GitLogUtil.readFullDetailsForHashes(myProject, root, myVcs, commitConsumer, hashes, shouldIncludeRootChanges(root),
false, true, true, GitLogUtil.DiffRenameLimit.GIT_CONFIG);
}
@Override
public void readFullDetails(@NotNull VirtualFile root,
@NotNull List<String> hashes,
@NotNull Consumer<? super VcsFullCommitDetails> commitConsumer,
boolean isForIndexing) throws VcsException {
if (!isRepositoryReady(root)) {
return;
}
GitLogUtil.DiffRenameLimit renameLimit = isForIndexing ? GitLogUtil.DiffRenameLimit.REGISTRY : GitLogUtil.DiffRenameLimit.INFINITY;
GitLogUtil.readFullDetailsForHashes(myProject, root, myVcs, commitConsumer, hashes, shouldIncludeRootChanges(root),
isForIndexing, true, false, renameLimit);
}
private boolean shouldIncludeRootChanges(@NotNull VirtualFile root) {
GitRepository repository = getRepository(root);
if (repository == null) return true;
return !repository.getInfo().isShallow();
}
@NotNull
@Override
public List<? extends VcsCommitMetadata> readMetadata(@NotNull final VirtualFile root, @NotNull List<String> hashes)
throws VcsException {
return GitLogUtil.collectMetadata(myProject, myVcs, root, hashes);
}
@NotNull
private Set<VcsRef> readBranches(@NotNull GitRepository repository) {
StopWatch sw = StopWatch.start("readBranches in " + repository.getRoot().getName());
VirtualFile root = repository.getRoot();
repository.update();
GitBranchesCollection branches = repository.getBranches();
Collection<GitLocalBranch> localBranches = branches.getLocalBranches();
Collection<GitRemoteBranch> remoteBranches = branches.getRemoteBranches();
Set<VcsRef> refs = new THashSet<>(localBranches.size() + remoteBranches.size());
for (GitLocalBranch localBranch : localBranches) {
Hash hash = branches.getHash(localBranch);
assert hash != null;
refs.add(myVcsObjectsFactory.createRef(hash, localBranch.getName(), GitRefManager.LOCAL_BRANCH, root));
}
for (GitRemoteBranch remoteBranch : remoteBranches) {
Hash hash = branches.getHash(remoteBranch);
assert hash != null;
refs.add(myVcsObjectsFactory.createRef(hash, remoteBranch.getNameForLocalOperations(), GitRefManager.REMOTE_BRANCH, root));
}
String currentRevision = repository.getCurrentRevision();
if (currentRevision != null) { // null => fresh repository
refs.add(myVcsObjectsFactory.createRef(HashImpl.build(currentRevision), GitUtil.HEAD, GitRefManager.HEAD, root));
}
sw.report();
return refs;
}
@NotNull
@Override
public VcsKey getSupportedVcs() {
return GitVcs.getKey();
}
@NotNull
@Override
public VcsLogRefManager getReferenceManager() {
return myRefSorter;
}
@NotNull
@Override
public Disposable subscribeToRootRefreshEvents(@NotNull final Collection<? extends VirtualFile> roots,
@NotNull final VcsLogRefresher refresher) {
MessageBusConnection connection = myProject.getMessageBus().connect(myProject);
connection.subscribe(GitRepository.GIT_REPO_CHANGE, repository -> {
VirtualFile root = repository.getRoot();
if (roots.contains(root)) {
refresher.refresh(root);
}
});
return connection;
}
@NotNull
@Override
public List<TimedVcsCommit> getCommitsMatchingFilter(@NotNull final VirtualFile root,
@NotNull VcsLogFilterCollection filterCollection,
int maxCount) throws VcsException {
VcsLogRangeFilter rangeFilter = filterCollection.get(RANGE_FILTER);
if (rangeFilter == null) {
return getCommitsMatchingFilter(root, filterCollection, null, maxCount);
}
/*
We expect a "branch + range" combined filter to display the union of commits reachable from the branch,
and commits belonging to the range. But Git intersects results for such parameters.
=> to solve this, we make a query for branch filters, and then separate queries for each of the ranges.
*/
Set<TimedVcsCommit> commits = new LinkedHashSet<>();
if (filterCollection.get(BRANCH_FILTER) != null || filterCollection.get(REVISION_FILTER) != null) {
commits.addAll(getCommitsMatchingFilter(root, filterCollection, null, maxCount));
filterCollection = VcsLogFiltersKt.without(VcsLogFiltersKt.without(filterCollection, BRANCH_FILTER), REVISION_FILTER);
}
for (VcsLogRangeFilter.RefRange range : rangeFilter.getRanges()) {
commits.addAll(getCommitsMatchingFilter(root, filterCollection, range, maxCount));
}
return new ArrayList<>(commits);
}
@NotNull
private List<TimedVcsCommit> getCommitsMatchingFilter(@NotNull final VirtualFile root,
@NotNull VcsLogFilterCollection filterCollection,
@Nullable VcsLogRangeFilter.RefRange range,
int maxCount) throws VcsException {
if (!isRepositoryReady(root)) {
return Collections.emptyList();
}
List<String> filterParameters = ContainerUtil.newArrayList();
VcsLogBranchFilter branchFilter = filterCollection.get(BRANCH_FILTER);
VcsLogRevisionFilter revisionFilter = filterCollection.get(REVISION_FILTER);
if (branchFilter != null || revisionFilter != null || range != null) {
boolean atLeastOneBranchExists = false;
if (branchFilter != null) {
GitRepository repository = getRepository(root);
assert repository != null : "repository is null for root " + root + " but was previously reported as 'ready'";
Collection<GitBranch> branches = ContainerUtil
.newArrayList(ContainerUtil.concat(repository.getBranches().getLocalBranches(), repository.getBranches().getRemoteBranches()));
Collection<String> branchNames = GitBranchUtil.convertBranchesToNames(branches);
Collection<String> predefinedNames = ContainerUtil.list(GitUtil.HEAD);
for (String branchName : ContainerUtil.concat(branchNames, predefinedNames)) {
if (branchFilter.matches(branchName)) {
filterParameters.add(branchName);
atLeastOneBranchExists = true;
}
}
}
if (revisionFilter != null) {
for (CommitId commit : revisionFilter.getHeads()) {
if (commit.getRoot().equals(root)) {
filterParameters.add(commit.getHash().asString());
atLeastOneBranchExists = true;
}
}
}
if (range != null) {
filterParameters.add(range.getExclusiveRef() + ".." + range.getInclusiveRef());
}
if (range == null && !atLeastOneBranchExists) { // no such branches in this repository => filter matches nothing
return Collections.emptyList();
}
}
else {
filterParameters.addAll(GitLogUtil.LOG_ALL);
}
VcsLogDateFilter dateFilter = filterCollection.get(DATE_FILTER);
if (dateFilter != null) {
// assuming there is only one date filter, until filter expressions are defined
if (dateFilter.getAfter() != null) {
filterParameters.add(prepareParameter("after", dateFilter.getAfter().toString()));
}
if (dateFilter.getBefore() != null) {
filterParameters.add(prepareParameter("before", dateFilter.getBefore().toString()));
}
}
VcsLogTextFilter textFilter = filterCollection.get(TEXT_FILTER);
String text = textFilter != null ? textFilter.getText() : null;
boolean regexp = textFilter == null || textFilter.isRegex();
boolean caseSensitive = textFilter != null && textFilter.matchesCase();
appendTextFilterParameters(text, regexp, caseSensitive, filterParameters);
VcsLogUserFilter userFilter = filterCollection.get(USER_FILTER);
if (userFilter != null) {
Collection<String> names = ContainerUtil.map(userFilter.getUsers(root), VcsUserUtil::toExactString);
if (regexp) {
List<String> authors = ContainerUtil.map(names, UserNameRegex.EXTENDED_INSTANCE);
if (GitVersionSpecialty.LOG_AUTHOR_FILTER_SUPPORTS_VERTICAL_BAR.existsIn(myVcs.getVersion())) {
filterParameters.add(prepareParameter("author", StringUtil.join(authors, "|")));
}
else {
filterParameters.addAll(ContainerUtil.map(authors, a -> prepareParameter("author", a)));
}
}
else {
filterParameters.addAll(ContainerUtil.map(names, a -> prepareParameter("author", StringUtil.escapeBackSlashes(a))));
}
}
if (maxCount > 0) {
filterParameters.add(prepareParameter("max-count", String.valueOf(maxCount)));
}
// note: structure filter must be the last parameter, because it uses "--" which separates parameters from paths
VcsLogStructureFilter structureFilter = filterCollection.get(STRUCTURE_FILTER);
if (structureFilter != null) {
Collection<FilePath> files = structureFilter.getFiles();
if (!files.isEmpty()) {
filterParameters.add("--full-history");
filterParameters.add("--simplify-merges");
filterParameters.add("
for (FilePath file : files) {
filterParameters.add(VcsFileUtil.relativePath(root, file));
}
}
}
List<TimedVcsCommit> commits = ContainerUtil.newArrayList();
GitLogUtil.readTimedCommits(myProject, root, filterParameters, EmptyConsumer.getInstance(),
EmptyConsumer.getInstance(), new CollectConsumer<>(commits));
return commits;
}
public static void appendTextFilterParameters(@Nullable String text, boolean regexp, boolean caseSensitive,
@NotNull List<? super String> filterParameters) {
if (text != null) {
filterParameters.add(prepareParameter("grep", text));
}
filterParameters.add(regexp ? "--extended-regexp" : "--fixed-strings");
if (!caseSensitive) {
filterParameters.add("--regexp-ignore-case"); // affects case sensitivity of any filter (except file filter)
}
}
@Nullable
@Override
public VcsUser getCurrentUser(@NotNull VirtualFile root) {
return GitUserRegistry.getInstance(myProject).getOrReadUser(root);
}
@NotNull
@Override
public Collection<String> getContainingBranches(@NotNull VirtualFile root, @NotNull Hash commitHash) throws VcsException {
return GitBranchUtil.getBranches(myProject, root, true, true, commitHash.asString());
}
@Nullable
@Override
public String getCurrentBranch(@NotNull VirtualFile root) {
GitRepository repository = myRepositoryManager.getRepositoryForRoot(root);
if (repository == null) return null;
String currentBranchName = repository.getCurrentBranchName();
if (currentBranchName == null && repository.getCurrentRevision() != null) {
return GitUtil.HEAD;
}
return currentBranchName;
}
@Nullable
@Override
public VcsLogDiffHandler getDiffHandler() {
return new GitLogDiffHandler(myProject);
}
@Nullable
@Override
public VirtualFile getVcsRoot(@NotNull Project project, @NotNull FilePath path) {
VirtualFile file = path.getVirtualFile();
if (file != null && file.isDirectory()) {
GitRepository repository = myRepositoryManager.getRepositoryForRoot(file);
if (repository != null) {
GitSubmodule submodule = GitSubmoduleKt.asSubmodule(repository);
if (submodule != null) {
return submodule.getParent().getRoot();
}
}
}
return VcsUtil.getVcsRootFor(project, path);
}
@SuppressWarnings("unchecked")
@Nullable
@Override
public <T> T getPropertyValue(VcsLogProperties.VcsLogProperty<T> property) {
if (property == VcsLogProperties.LIGHTWEIGHT_BRANCHES) {
return (T)Boolean.TRUE;
}
else if (property == VcsLogProperties.SUPPORTS_INDEXING) {
return (T)Boolean.valueOf(isIndexingOn());
}
return null;
}
public static boolean isIndexingOn() {
return Registry.is("vcs.log.index.git");
}
private static String prepareParameter(String paramName, String value) {
return "--" + paramName + "=" + value; // no value quoting needed, because the parameter itself will be quoted by GeneralCommandLine
}
@Nullable
private GitRepository getRepository(@NotNull VirtualFile root) {
return myRepositoryManager.getRepositoryForRoot(root);
}
private boolean isRepositoryReady(@NotNull VirtualFile root) {
GitRepository repository = getRepository(root);
if (repository == null) {
LOG.error("Repository not found for root " + root);
return false;
}
else if (repository.isFresh()) {
LOG.info("Fresh repository: " + root);
return false;
}
return true;
}
@NotNull
private static <T> Set<T> newHashSet() {
return new THashSet<>();
}
@NotNull
private static <T> Set<T> newHashSet(@NotNull Collection<? extends T> initialCollection) {
return new THashSet<>(initialCollection);
}
}
|
package io.spacedog.utils;
import java.util.Collection;
import com.google.common.base.Strings;
public class Check {
public static void notNullOrEmpty(String value, String paramName) {
if (Strings.isNullOrEmpty(value))
throw new IllegalArgumentException(String.format("parameter [%s] is null or empty", paramName));
}
public static void notNullOrEmpty(Collection<?> value, String paramName) {
if (Utils.isNullOrEmpty(value))
throw new IllegalArgumentException(String.format("parameter [%s] is empty", paramName));
}
}
|
package org.openlca.app.db;
import java.io.File;
import java.util.Objects;
import org.openlca.app.App;
import org.openlca.core.database.ActorDao;
import org.openlca.core.database.BaseDao;
import org.openlca.core.database.CategorizedEntityDao;
import org.openlca.core.database.CategoryDao;
import org.openlca.core.database.CostCategoryDao;
import org.openlca.core.database.CurrencyDao;
import org.openlca.core.database.FlowDao;
import org.openlca.core.database.FlowPropertyDao;
import org.openlca.core.database.IDatabase;
import org.openlca.core.database.ImpactMethodDao;
import org.openlca.core.database.LocationDao;
import org.openlca.core.database.ParameterDao;
import org.openlca.core.database.ProcessDao;
import org.openlca.core.database.ProductSystemDao;
import org.openlca.core.database.ProjectDao;
import org.openlca.core.database.SocialIndicatorDao;
import org.openlca.core.database.SourceDao;
import org.openlca.core.database.UnitGroupDao;
import org.openlca.core.model.ModelType;
import org.openlca.core.model.descriptors.BaseDescriptor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** Database management of the application. */
public class Database {
private static IDatabase database;
private static IDatabaseConfiguration config;
private static DatabaseList configurations = loadConfigs();
private Database() {
}
public static IDatabase get() {
return database;
}
@SuppressWarnings("unchecked")
public static <T> T load(BaseDescriptor descriptor) {
if (descriptor == null || descriptor.getModelType() == null)
return null;
Class<?> clazz = descriptor.getModelType().getModelClass();
Object o = createDao(clazz).getForId(descriptor.getId());
return (T) o;
}
public static IDatabase activate(IDatabaseConfiguration config)
throws Exception {
try {
Database.database = config.createInstance();
Cache.create(database);
Database.config = config;
Logger log = LoggerFactory.getLogger(Database.class);
log.trace("activated database {} with version{}",
database.getName(), database.getVersion());
return Database.database;
} catch (Exception e) {
Database.database = null;
Cache.close();
Database.config = null;
throw e;
}
}
public static boolean isActive(IDatabaseConfiguration config) {
if (config == null)
return false;
return Objects.equals(config, Database.config);
}
/** Closes the active database. */
public static void close() throws Exception {
if (database == null)
return;
Cache.close();
database.close();
database = null;
config = null;
}
private static DatabaseList loadConfigs() {
File workspace = App.getWorkspace();
File listFile = new File(workspace, "databases.json");
if (!listFile.exists())
return new DatabaseList();
else
return DatabaseList.read(listFile);
}
private static void saveConfig() {
File workspace = App.getWorkspace();
File listFile = new File(workspace, "databases.json");
configurations.write(listFile);
}
public static DatabaseList getConfigurations() {
return configurations;
}
public static IDatabaseConfiguration getActiveConfiguration() {
for (IDatabaseConfiguration configuration : configurations
.getLocalDatabases())
if (isActive(configuration))
return configuration;
for (IDatabaseConfiguration configuration : configurations
.getRemoteDatabases())
if (isActive(configuration))
return configuration;
return null;
}
public static void register(DerbyConfiguration config) {
if (configurations.contains(config))
return;
configurations.getLocalDatabases().add(config);
saveConfig();
}
public static void remove(DerbyConfiguration config) {
if (!configurations.contains(config))
return;
configurations.getLocalDatabases().remove(config);
saveConfig();
}
public static void register(MySQLConfiguration config) {
if (configurations.contains(config))
return;
configurations.getRemoteDatabases().add(config);
saveConfig();
}
public static void remove(MySQLConfiguration config) {
if (!configurations.contains(config))
return;
configurations.getRemoteDatabases().remove(config);
saveConfig();
}
public static <T> BaseDao<T> createDao(Class<T> clazz) {
if (database == null)
return null;
else
return database.createDao(clazz);
}
public static CategorizedEntityDao<?, ?> createRootDao(ModelType type) {
if (database == null)
return null;
switch (type) {
case ACTOR:
return new ActorDao(database);
case COST_CATEGORY:
return new CostCategoryDao(database);
case CURRENCY:
return new CurrencyDao(database);
case FLOW:
return new FlowDao(database);
case FLOW_PROPERTY:
return new FlowPropertyDao(database);
case IMPACT_METHOD:
return new ImpactMethodDao(database);
case PROCESS:
return new ProcessDao(database);
case PRODUCT_SYSTEM:
return new ProductSystemDao(database);
case PROJECT:
return new ProjectDao(database);
case SOCIAL_INDICATOR:
return new SocialIndicatorDao(database);
case SOURCE:
return new SourceDao(database);
case UNIT_GROUP:
return new UnitGroupDao(database);
case LOCATION:
return new LocationDao(database);
case PARAMETER:
return new ParameterDao(database);
case CATEGORY:
return new CategoryDao(database);
default:
return null;
}
}
}
|
package hudson.model;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import hudson.console.HyperlinkNote;
import hudson.diagnosis.OldDataMonitor;
import hudson.util.XStream2;
import org.kohsuke.stapler.export.Exported;
import org.kohsuke.stapler.export.ExportedBean;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
/**
* Cause object base class. This class hierarchy is used to keep track of why
* a given build was started. This object encapsulates the UI rendering of the cause,
* as well as providing more useful information in respective subypes.
*
* The Cause object is connected to a build via the {@link CauseAction} object.
*
* <h2>Views</h2>
* <dl>
* <dt>description.jelly
* <dd>Renders the cause to HTML. By default, it puts the short description.
* </dl>
*
* @author Michael Donohue
* @see Run#getCauses()
* @see Queue.Item#getCauses()
*/
@ExportedBean
public abstract class Cause {
/**
* One-line human-readable text of the cause.
*
* <p>
* By default, this method is used to render HTML as well.
*/
@Exported(visibility=3)
public abstract String getShortDescription();
/**
* Called when the cause is registered to {@link AbstractBuild}.
*
* @param build
* never null
* @since 1.376
*/
public void onAddedTo(AbstractBuild build) {}
/**
* Report a line to the listener about this cause.
* @since 1.362
*/
public void print(TaskListener listener) {
listener.getLogger().println(getShortDescription());
}
/**
* Fall back implementation when no other type is available.
* @deprecated since 2009-02-08
*/
public static class LegacyCodeCause extends Cause {
private StackTraceElement [] stackTrace;
public LegacyCodeCause() {
stackTrace = new Exception().getStackTrace();
}
@Override
public String getShortDescription() {
return Messages.Cause_LegacyCodeCause_ShortDescription();
}
}
/**
* A build is triggered by the completion of another build (AKA upstream build.)
*/
public static class UpstreamCause extends Cause {
private String upstreamProject, upstreamUrl;
private int upstreamBuild;
/**
* @deprecated since 2009-02-28
*/
@Deprecated
private transient Cause upstreamCause;
private List<Cause> upstreamCauses;
/**
* @deprecated since 2009-02-28
*/
// for backward bytecode compatibility
public UpstreamCause(AbstractBuild<?,?> up) {
this((Run<?,?>)up);
}
public UpstreamCause(Run<?, ?> up) {
upstreamBuild = up.getNumber();
upstreamProject = up.getParent().getFullName();
upstreamUrl = up.getParent().getUrl();
upstreamCauses = new ArrayList<Cause>(up.getCauses());
}
/**
* Returns true if this cause points to a build in the specified job.
*/
public boolean pointsTo(Job<?,?> j) {
return j.getFullName().equals(upstreamProject);
}
/**
* Returns true if this cause points to the specified build.
*/
public boolean pointsTo(Run<?,?> r) {
return r.getNumber()==upstreamBuild && pointsTo(r.getParent());
}
@Exported(visibility=3)
public String getUpstreamProject() {
return upstreamProject;
}
@Exported(visibility=3)
public int getUpstreamBuild() {
return upstreamBuild;
}
@Exported(visibility=3)
public String getUpstreamUrl() {
return upstreamUrl;
}
@Override
public String getShortDescription() {
return Messages.Cause_UpstreamCause_ShortDescription(upstreamProject, upstreamBuild);
}
@Override
public void print(TaskListener listener) {
listener.getLogger().println(
Messages.Cause_UpstreamCause_ShortDescription(
HyperlinkNote.encodeTo('/'+upstreamUrl, upstreamProject),
HyperlinkNote.encodeTo('/'+upstreamUrl+upstreamBuild, Integer.toString(upstreamBuild)))
);
}
public static class ConverterImpl extends XStream2.PassthruConverter<UpstreamCause> {
public ConverterImpl(XStream2 xstream) { super(xstream); }
@Override protected void callback(UpstreamCause uc, UnmarshallingContext context) {
if (uc.upstreamCause != null) {
if (uc.upstreamCauses == null) uc.upstreamCauses = new ArrayList<Cause>();
uc.upstreamCauses.add(uc.upstreamCause);
uc.upstreamCause = null;
OldDataMonitor.report(context, "1.288");
}
}
}
}
/**
* A build is started by an user action.
*/
public static class UserCause extends Cause {
private String authenticationName;
public UserCause() {
this.authenticationName = Hudson.getAuthentication().getName();
}
@Exported(visibility=3)
public String getUserName() {
User u = User.get(authenticationName, false);
return u != null ? u.getDisplayName() : authenticationName;
}
@Override
public String getShortDescription() {
return Messages.Cause_UserCause_ShortDescription(authenticationName);
}
@Override
public boolean equals(Object o) {
return o instanceof UserCause && Arrays.equals(new Object[] {authenticationName},
new Object[] {((UserCause)o).authenticationName});
}
@Override
public int hashCode() {
return 295 + (this.authenticationName != null ? this.authenticationName.hashCode() : 0);
}
}
public static class RemoteCause extends Cause {
private String addr;
private String note;
public RemoteCause(String host, String note) {
this.addr = host;
this.note = note;
}
@Override
public String getShortDescription() {
if(note != null) {
return Messages.Cause_RemoteCause_ShortDescriptionWithNote(addr, note);
} else {
return Messages.Cause_RemoteCause_ShortDescription(addr);
}
}
@Override
public boolean equals(Object o) {
return o instanceof RemoteCause && Arrays.equals(new Object[] {addr, note},
new Object[] {((RemoteCause)o).addr, ((RemoteCause)o).note});
}
@Override
public int hashCode() {
int hash = 5;
hash = 83 * hash + (this.addr != null ? this.addr.hashCode() : 0);
hash = 83 * hash + (this.note != null ? this.note.hashCode() : 0);
return hash;
}
}
}
|
package hudson.model;
import hudson.Util;
import static hudson.Util.fixNull;
import hudson.slaves.NodeProvisioner;
import hudson.slaves.Cloud;
import org.kohsuke.stapler.export.Exported;
import org.kohsuke.stapler.export.ExportedBean;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.Collection;
import java.util.TreeSet;
import com.thoughtworks.xstream.converters.Converter;
import com.thoughtworks.xstream.converters.MarshallingContext;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
/**
* Group of {@link Node}s.
*
* @author Kohsuke Kawaguchi
* @see Hudson#getLabels()
* @see Hudson#getLabel(String)
*/
@ExportedBean
public class Label implements Comparable<Label>, ModelObject {
private final String name;
private volatile Set<Node> nodes;
private volatile Set<Cloud> clouds;
public final LoadStatistics loadStatistics;
public final NodeProvisioner nodeProvisioner;
public Label(String name) {
this.name = name;
// passing these causes an infinite loop - getTotalExecutors(),getBusyExecutors());
this.loadStatistics = new LoadStatistics(0,0) {
@Override
public int computeIdleExecutors() {
return Label.this.getIdleExecutors();
}
@Override
public int computeTotalExecutors() {
return Label.this.getTotalExecutors();
}
@Override
public int computeQueueLength() {
return Hudson.getInstance().getQueue().countBuildableItemsFor(Label.this);
}
};
this.nodeProvisioner = new NodeProvisioner(this, loadStatistics);
}
@Exported
public String getName() {
return name;
}
public String getDisplayName() {
return name;
}
/**
* Returns true if this label is a "self label",
* which means the label is the name of a {@link Node}.
*/
public boolean isSelfLabel() {
Set<Node> nodes = getNodes();
return nodes.size() == 1 && nodes.iterator().next().getSelfLabel() == this;
}
/**
* Gets all {@link Node}s that belong to this label.
*/
@Exported
public Set<Node> getNodes() {
if(nodes==null) {
Set<Node> r = new HashSet<Node>();
Hudson h = Hudson.getInstance();
if(h.getAssignedLabels().contains(this))
r.add(h);
for (Node n : h.getNodes()) {
if(n.getAssignedLabels().contains(this))
r.add(n);
}
nodes = Collections.unmodifiableSet(r);
}
return nodes;
}
/**
* Gets all {@link Cloud}s that can launch for this label.
*/
@Exported
public Set<Cloud> getClouds() {
if(clouds==null) {
Set<Cloud> r = new HashSet<Cloud>();
Hudson h = Hudson.getInstance();
for (Cloud c : h.clouds) {
if(c.canProvision(this))
r.add(c);
}
clouds = Collections.unmodifiableSet(r);
}
return clouds;
}
/**
* Can jobs be assigned to this label?
* <p>
* The answer is yes if there is a reasonable basis to believe that Hudson can have
* an executor under this label, given the current configuration. This includes
* situations such as (1) there are offline slaves that have this label (2) clouds exist
* that can provision slaves that have this label.
*/
public boolean isAssignable() {
for (Node n : getNodes())
if(n.getNumExecutors()>0)
return true;
return !getClouds().isEmpty();
}
/**
* Number of total {@link Executor}s that belong to this label.
* <p>
* This includes executors that belong to offline nodes, so the result
* can be thought of as a potential capacity, whereas {@link #getTotalExecutors()}
* is the currently functioning total number of executors.
* <p>
* This method doesn't take the dynamically allocatable nodes (via {@link Cloud})
* into account. If you just want to test if there's some executors, use {@link #isAssignable()}.
*/
public int getTotalConfiguredExecutors() {
int r=0;
for (Node n : getNodes())
r += n.getNumExecutors();
return r;
}
/**
* Number of total {@link Executor}s that belong to this label that are functioning.
* <p>
* This excludes executors that belong to offline nodes.
*/
@Exported
public int getTotalExecutors() {
int r=0;
for (Node n : getNodes()) {
Computer c = n.toComputer();
if(c!=null && c.isOnline())
r += c.countExecutors();
}
return r;
}
/**
* Number of busy {@link Executor}s that are carrying out some work right now.
*/
@Exported
public int getBusyExecutors() {
int r=0;
for (Node n : getNodes()) {
Computer c = n.toComputer();
if(c!=null && c.isOnline())
r += c.countBusy();
}
return r;
}
/**
* Number of idle {@link Executor}s that can start working immediately.
*/
@Exported
public int getIdleExecutors() {
int r=0;
for (Node n : getNodes()) {
Computer c = n.toComputer();
if(c!=null && (c.isOnline() || c.isConnecting()))
r += c.countIdle();
}
return r;
}
/**
* Returns true if all the nodes of this label is offline.
*/
@Exported
public boolean isOffline() {
for (Node n : getNodes()) {
if(n.toComputer() != null && !n.toComputer().isOffline())
return false;
}
return true;
}
/**
* Returns a human readable text that explains this label.
*/
@Exported
public String getDescription() {
Set<Node> nodes = getNodes();
if(nodes.isEmpty()) {
Set<Cloud> clouds = getClouds();
if(clouds.isEmpty())
return Messages.Label_InvalidLabel();
return Messages.Label_ProvisionedFrom(toString(clouds));
}
if(nodes.size()==1)
return nodes.iterator().next().getNodeDescription();
return Messages.Label_GroupOf(toString(nodes));
}
private String toString(Collection<? extends ModelObject> model) {
boolean first=true;
StringBuilder buf = new StringBuilder();
for (ModelObject c : model) {
if(buf.length()>80) {
buf.append(",...");
break;
}
if(!first) buf.append(',');
else first=false;
buf.append(c.getDisplayName());
}
return buf.toString();
}
/**
* Returns projects that are tied on this node.
*/
@Exported
public List<AbstractProject> getTiedJobs() {
List<AbstractProject> r = new ArrayList<AbstractProject>();
for( AbstractProject p : Util.filter(Hudson.getInstance().getItems(),AbstractProject.class) ) {
if(this.equals(p.getAssignedLabel()))
r.add(p);
}
return r;
}
public boolean contains(Node node) {
return getNodes().contains(node);
}
/**
* If there's no such label defined in {@link Node} or {@link Cloud}.
* This is usually used as a signal that this label is invalid.
*/
public boolean isEmpty() {
return getNodes().isEmpty() && getClouds().isEmpty();
}
/*package*/ void reset() {
nodes = null;
clouds = null;
}
/**
* Expose this object to the remote API.
*/
public Api getApi() {
return new Api(this);
}
public boolean equals(Object that) {
if (this == that) return true;
if (that == null || getClass() != that.getClass()) return false;
return name.equals(((Label)that).name);
}
public int hashCode() {
return name.hashCode();
}
public int compareTo(Label that) {
return this.name.compareTo(that.name);
}
@Override
public String toString() {
return name;
}
public static final class ConverterImpl implements Converter {
public ConverterImpl() {
}
public boolean canConvert(Class type) {
return type==Label.class;
}
public void marshal(Object source, HierarchicalStreamWriter writer, MarshallingContext context) {
Label src = (Label) source;
writer.setValue(src.getName());
}
public Object unmarshal(HierarchicalStreamReader reader, final UnmarshallingContext context) {
return Hudson.getInstance().getLabel(reader.getValue());
}
}
/**
* Convers a whitespace-separate list of tokens into a set of {@link Label}s.
*
* @param labels
* Strings like "abc def ghi". Can be empty or null.
* @return
* Can be empty but never null. A new writable set is always returned,
* so that the caller can add more to the set.
* @since 1.308
*/
public static Set<Label> parse(String labels) {
Set<Label> r = new TreeSet<Label>();
labels = fixNull(labels);
if(labels.length()>0)
for( String l : labels.split(" +"))
r.add(Hudson.getInstance().getLabel(l));
return r;
}
}
|
package io.grpc;
import com.google.common.base.Preconditions;
import com.google.common.base.Throwables;
import com.google.common.util.concurrent.Futures;
import io.grpc.transport.ServerListener;
import io.grpc.transport.ServerStream;
import io.grpc.transport.ServerStreamListener;
import io.grpc.transport.ServerTransport;
import io.grpc.transport.ServerTransportListener;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
/**
* Default implementation of {@link Server}, for creation by transports.
*
* <p>Expected usage (by a theoretical TCP transport):
* <pre><code>public class TcpTransportServerFactory {
* public static Server newServer(Executor executor, HandlerRegistry registry,
* String configuration) {
* return new ServerImpl(executor, registry, new TcpTransportServer(configuration));
* }
* }</code></pre>
*
* <p>Starting the server starts the underlying transport for servicing requests. Stopping the
* server stops servicing new requests and waits for all connections to terminate.
*/
public final class ServerImpl extends Server {
private static final ServerStreamListener NOOP_LISTENER = new NoopListener();
private static final Future<?> DEFAULT_TIMEOUT_FUTURE = Futures.immediateCancelledFuture();
/** Executor for application processing. */
private final Executor executor;
private final HandlerRegistry registry;
private boolean started;
private boolean shutdown;
private boolean terminated;
private Runnable terminationRunnable;
/** Service encapsulating something similar to an accept() socket. */
private final io.grpc.transport.Server transportServer;
private boolean transportServerTerminated;
/** {@code transportServer} and services encapsulating something similar to a TCP connection. */
private final Collection<ServerTransport> transports = new HashSet<ServerTransport>();
private final ScheduledExecutorService timeoutService;
/**
* Construct a server.
*
* @param executor to call methods on behalf of remote clients
* @param registry of methods to expose to remote clients.
*/
public ServerImpl(Executor executor, HandlerRegistry registry,
io.grpc.transport.Server transportServer) {
this.executor = Preconditions.checkNotNull(executor, "executor");
this.registry = Preconditions.checkNotNull(registry, "registry");
this.transportServer = Preconditions.checkNotNull(transportServer, "transportServer");
// TODO(carl-mastrangelo): replace this with the shared scheduler once PR #576 is merged.
this.timeoutService = Executors.newScheduledThreadPool(1);
}
/** Hack to allow executors to auto-shutdown. Not for general use. */
// TODO(ejona86): Replace with a real API.
synchronized void setTerminationRunnable(Runnable runnable) {
this.terminationRunnable = runnable;
}
public synchronized ServerImpl start() throws IOException {
if (started) {
throw new IllegalStateException("Already started");
}
// Start and wait for any port to actually be bound.
transportServer.start(new ServerListenerImpl());
started = true;
return this;
}
/**
* Initiates an orderly shutdown in which preexisting calls continue but new calls are rejected.
*/
public synchronized ServerImpl shutdown() {
if (shutdown) {
return this;
}
shutdown = true;
transportServer.shutdown();
timeoutService.shutdown();
return this;
}
/**
* Initiates a forceful shutdown in which preexisting and new calls are rejected. Although
* forceful, the shutdown process is still not instantaneous; {@link #isTerminated()} will likely
* return {@code false} immediately after this method returns.
*
* <p>NOT YET IMPLEMENTED. This method currently behaves identically to shutdown().
*/
// TODO(ejona86): cancel preexisting calls.
public synchronized ServerImpl shutdownNow() {
shutdown();
return this;
}
/**
* Returns whether the server is shutdown. Shutdown servers reject any new calls, but may still
* have some calls being processed.
*
* @see #shutdown()
* @see #isTerminated()
*/
public synchronized boolean isShutdown() {
return shutdown;
}
/**
* Waits for the server to become terminated, giving up if the timeout is reached.
*
* @return whether the server is terminated, as would be done by {@link #isTerminated()}.
*/
public synchronized boolean awaitTerminated(long timeout, TimeUnit unit)
throws InterruptedException {
long timeoutNanos = unit.toNanos(timeout);
long endTimeNanos = System.nanoTime() + timeoutNanos;
while (!terminated && (timeoutNanos = endTimeNanos - System.nanoTime()) > 0) {
TimeUnit.NANOSECONDS.timedWait(this, timeoutNanos);
}
return terminated;
}
/**
* Waits for the server to become terminated.
*/
public synchronized void awaitTerminated() throws InterruptedException {
while (!terminated) {
wait();
}
}
/**
* Returns whether the server is terminated. Terminated servers have no running calls and
* relevant resources released (like TCP connections).
*
* @see #isShutdown()
*/
public synchronized boolean isTerminated() {
return terminated;
}
/**
* Remove transport service from accounting collection and notify of complete shutdown if
* necessary.
*
* @param transport service to remove
*/
private synchronized void transportClosed(ServerTransport transport) {
if (!transports.remove(transport)) {
throw new AssertionError("Transport already removed");
}
checkForTermination();
}
/** Notify of complete shutdown if necessary. */
private synchronized void checkForTermination() {
if (shutdown && transports.isEmpty() && transportServerTerminated) {
if (terminated) {
throw new AssertionError("Server already terminated");
}
terminated = true;
notifyAll();
if (terminationRunnable != null) {
terminationRunnable.run();
}
}
}
private class ServerListenerImpl implements ServerListener {
@Override
public ServerTransportListener transportCreated(ServerTransport transport) {
synchronized (ServerImpl.this) {
transports.add(transport);
}
return new ServerTransportListenerImpl(transport);
}
@Override
public void serverShutdown() {
synchronized (ServerImpl.this) {
// transports collection can be modified during shutdown(), even if we hold the lock, due
// to reentrancy.
for (ServerTransport transport : new ArrayList<ServerTransport>(transports)) {
transport.shutdown();
}
transportServerTerminated = true;
checkForTermination();
}
}
}
private class ServerTransportListenerImpl implements ServerTransportListener {
private final ServerTransport transport;
public ServerTransportListenerImpl(ServerTransport transport) {
this.transport = transport;
}
@Override
public void transportTerminated() {
transportClosed(transport);
}
@Override
public ServerStreamListener streamCreated(final ServerStream stream, final String methodName,
final Metadata.Headers headers) {
final Future<?> timeout = scheduleTimeout(stream, headers);
SerializingExecutor serializingExecutor = new SerializingExecutor(executor);
final JumpToApplicationThreadServerStreamListener jumpListener
= new JumpToApplicationThreadServerStreamListener(serializingExecutor, stream);
// Run in serializingExecutor so jumpListener.setListener() is called before any callbacks
// are delivered, including any errors. Callbacks can still be triggered, but they will be
// queued.
serializingExecutor.execute(new Runnable() {
@Override
public void run() {
ServerStreamListener listener = NOOP_LISTENER;
try {
HandlerRegistry.Method method = registry.lookupMethod(methodName);
if (method == null) {
stream.close(
Status.UNIMPLEMENTED.withDescription("Method not found: " + methodName),
new Metadata.Trailers());
timeout.cancel(true);
return;
}
listener = startCall(stream, methodName, method.getMethodDefinition(), timeout,
headers);
} catch (Throwable t) {
stream.close(Status.fromThrowable(t), new Metadata.Trailers());
timeout.cancel(true);
throw Throwables.propagate(t);
} finally {
jumpListener.setListener(listener);
}
}
});
return jumpListener;
}
private Future<?> scheduleTimeout(final ServerStream stream, Metadata.Headers headers) {
Long timeoutMicros = headers.get(ChannelImpl.TIMEOUT_KEY);
if (timeoutMicros == null) {
return DEFAULT_TIMEOUT_FUTURE;
}
return timeoutService.schedule(new Runnable() {
@Override
public void run() {
// This should rarely get run, since the client will likely cancel the stream before
// the timeout is reached.
stream.cancel(Status.DEADLINE_EXCEEDED);
}
},
timeoutMicros,
TimeUnit.MICROSECONDS);
}
/** Never returns {@code null}. */
private <ReqT, RespT> ServerStreamListener startCall(ServerStream stream, String fullMethodName,
ServerMethodDefinition<ReqT, RespT> methodDef, Future<?> timeout,
Metadata.Headers headers) {
// TODO(ejona86): should we update fullMethodName to have the canonical path of the method?
final ServerCallImpl<ReqT, RespT> call = new ServerCallImpl<ReqT, RespT>(
stream, methodDef.getMethodDescriptor());
ServerCall.Listener<ReqT> listener
= methodDef.getServerCallHandler().startCall(fullMethodName, call, headers);
if (listener == null) {
throw new NullPointerException(
"startCall() returned a null listener for method " + fullMethodName);
}
return call.newServerStreamListener(listener, timeout);
}
}
private static class NoopListener implements ServerStreamListener {
@Override
public void messageRead(InputStream value) {
try {
value.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
@Override
public void halfClosed() {}
@Override
public void closed(Status status) {}
@Override
public void onReady() {}
}
/**
* Dispatches callbacks onto an application-provided executor and correctly propagates
* exceptions.
*/
private static class JumpToApplicationThreadServerStreamListener implements ServerStreamListener {
private final SerializingExecutor callExecutor;
private final ServerStream stream;
// Only accessed from callExecutor.
private ServerStreamListener listener;
public JumpToApplicationThreadServerStreamListener(SerializingExecutor executor,
ServerStream stream) {
this.callExecutor = executor;
this.stream = stream;
}
private ServerStreamListener getListener() {
if (listener == null) {
throw new IllegalStateException("listener unset");
}
return listener;
}
private void setListener(ServerStreamListener listener) {
Preconditions.checkNotNull(listener, "listener must not be null");
Preconditions.checkState(this.listener == null, "Listener already set");
this.listener = listener;
}
/**
* Like {@link ServerCall#close(Status, Metadata.Trailers)}, but thread-safe for internal use.
*/
private void internalClose(Status status, Metadata.Trailers trailers) {
// TODO(ejona86): this is not thread-safe :)
stream.close(status, trailers);
}
@Override
public void messageRead(final InputStream message) {
callExecutor.execute(new Runnable() {
@Override
public void run() {
try {
getListener().messageRead(message);
} catch (Throwable t) {
internalClose(Status.fromThrowable(t), new Metadata.Trailers());
throw Throwables.propagate(t);
}
}
});
}
@Override
public void halfClosed() {
callExecutor.execute(new Runnable() {
@Override
public void run() {
try {
getListener().halfClosed();
} catch (Throwable t) {
internalClose(Status.fromThrowable(t), new Metadata.Trailers());
throw Throwables.propagate(t);
}
}
});
}
@Override
public void closed(final Status status) {
callExecutor.execute(new Runnable() {
@Override
public void run() {
getListener().closed(status);
}
});
}
@Override
public void onReady() {
callExecutor.execute(new Runnable() {
@Override
public void run() {
getListener().onReady();
}
});
}
}
private static class ServerCallImpl<ReqT, RespT> extends ServerCall<RespT> {
private final ServerStream stream;
private final MethodDescriptor<ReqT, RespT> method;
private volatile boolean cancelled;
public ServerCallImpl(ServerStream stream, MethodDescriptor<ReqT, RespT> method) {
this.stream = stream;
this.method = method;
}
@Override
public void request(int numMessages) {
stream.request(numMessages);
}
@Override
public void sendHeaders(Metadata.Headers headers) {
stream.writeHeaders(headers);
}
@Override
public void sendPayload(RespT payload) {
try {
InputStream message = method.streamResponse(payload);
stream.writeMessage(message);
stream.flush();
} catch (Throwable t) {
close(Status.fromThrowable(t), new Metadata.Trailers());
throw Throwables.propagate(t);
}
}
@Override
public boolean isReady() {
return stream.isReady();
}
@Override
public void close(Status status, Metadata.Trailers trailers) {
stream.close(status, trailers);
}
@Override
public boolean isCancelled() {
return cancelled;
}
private ServerStreamListenerImpl newServerStreamListener(ServerCall.Listener<ReqT> listener,
Future<?> timeout) {
return new ServerStreamListenerImpl(listener, timeout);
}
/**
* All of these callbacks are assumed to called on an application thread, and the caller is
* responsible for handling thrown exceptions.
*/
private class ServerStreamListenerImpl implements ServerStreamListener {
private final ServerCall.Listener<ReqT> listener;
private final Future<?> timeout;
public ServerStreamListenerImpl(ServerCall.Listener<ReqT> listener, Future<?> timeout) {
this.listener = Preconditions.checkNotNull(listener, "listener must not be null");
this.timeout = timeout;
}
@Override
public void messageRead(final InputStream message) {
try {
if (cancelled) {
return;
}
listener.onPayload(method.parseRequest(message));
} finally {
try {
message.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
@Override
public void halfClosed() {
if (cancelled) {
return;
}
listener.onHalfClose();
}
@Override
public void closed(Status status) {
timeout.cancel(true);
if (status.isOk()) {
listener.onComplete();
} else {
cancelled = true;
listener.onCancel();
}
}
@Override
public void onReady() {
if (cancelled) {
return;
}
listener.onReady();
}
}
}
}
|
package org.bouncycastle.asn1.eac;
import org.bouncycastle.asn1.DERObjectIdentifier;
public interface EACObjectIdentifiers
{
// bsi-de OBJECT IDENTIFIER ::= {
// itu-t(0) identified-organization(4) etsi(0)
// reserved(127) etsi-identified-organization(0) 7
static final DERObjectIdentifier bsi_de = new DERObjectIdentifier("0.4.0.127.0.7");
// id-PK OBJECT IDENTIFIER ::= {
// bsi-de protocols(2) smartcard(2) 1
static final DERObjectIdentifier id_PK = new DERObjectIdentifier(bsi_de + ".2.2.1");
static final DERObjectIdentifier id_PK_DH = new DERObjectIdentifier(id_PK + ".1");
static final DERObjectIdentifier id_PK_ECDH = new DERObjectIdentifier(id_PK + ".2");
// id-CA OBJECT IDENTIFIER ::= {
// bsi-de protocols(2) smartcard(2) 3
static final DERObjectIdentifier id_CA = new DERObjectIdentifier(bsi_de + ".2.2.3");
static final DERObjectIdentifier id_CA_DH = new DERObjectIdentifier(id_CA + ".1");
static final DERObjectIdentifier id_CA_DH_3DES_CBC_CBC = new DERObjectIdentifier(id_CA_DH + ".1");
static final DERObjectIdentifier id_CA_ECDH = new DERObjectIdentifier(id_CA + ".2");
static final DERObjectIdentifier id_CA_ECDH_3DES_CBC_CBC = new DERObjectIdentifier(id_CA_ECDH + ".1");
// id-TA OBJECT IDENTIFIER ::= {
// bsi-de protocols(2) smartcard(2) 2
static final DERObjectIdentifier id_TA = new DERObjectIdentifier(bsi_de + ".2.2.2");
static final DERObjectIdentifier id_TA_RSA = new DERObjectIdentifier(id_TA + ".1");
static final DERObjectIdentifier id_TA_RSA_v1_5_SHA_1 = new DERObjectIdentifier(id_TA_RSA + ".1");
static final DERObjectIdentifier id_TA_RSA_v1_5_SHA_256 = new DERObjectIdentifier(id_TA_RSA + ".2");
static final DERObjectIdentifier id_TA_RSA_PSS_SHA_1 = new DERObjectIdentifier(id_TA_RSA + ".3");
static final DERObjectIdentifier id_TA_RSA_PSS_SHA_256 = new DERObjectIdentifier(id_TA_RSA + ".4");
static final DERObjectIdentifier id_TA_ECDSA = new DERObjectIdentifier(id_TA + ".2");
static final DERObjectIdentifier id_TA_ECDSA_SHA_1 = new DERObjectIdentifier(id_TA_ECDSA + ".1");
static final DERObjectIdentifier id_TA_ECDSA_SHA_224 = new DERObjectIdentifier(id_TA_ECDSA + ".2");
static final DERObjectIdentifier id_TA_ECDSA_SHA_256 = new DERObjectIdentifier(id_TA_ECDSA + ".3");
static final DERObjectIdentifier id_TA_ECDSA_SHA_384 = new DERObjectIdentifier(id_TA_ECDSA + ".4");
static final DERObjectIdentifier id_TA_ECDSA_SHA_512 = new DERObjectIdentifier(id_TA_ECDSA + ".5");
/**
* id-EAC-ePassport OBJECT IDENTIFIER ::= {
* bsi-de applications(3) mrtd(1) roles(2) 1}
*/
static final DERObjectIdentifier id_EAC_ePassport = new DERObjectIdentifier(bsi_de + ".3.1.2.1");
}
|
package org.objectweb.proactive.ext.util;
import org.objectweb.proactive.core.mop.ASMBytecodeStubBuilder;
import org.objectweb.proactive.core.mop.BytecodeStubBuilder;
import org.objectweb.proactive.core.mop.MOPClassLoader;
import java.io.File;
import java.io.FileOutputStream;
public class StubGenerator {
/**
* Turn a file name into a class name if necessary. Remove the ending .class and change all the '/' into '.'
* @param name
* @return
*/
protected static String processClassName(String name) {
int i = name.indexOf(".class");
String tmp = name;
System.out.println(name);
if (i < 0) {
return name;
} else {
tmp = name.substring(0, i);
}
String tmp2 = tmp.replace('/', '.');
if (tmp2.indexOf('.') == 0) {
return tmp2.substring(1);
} else {
return tmp2;
}
}
public static void printUsageAndExit() {
System.err.println("usage: java " + StubGenerator.class.getName() +
" <classes> ");
System.exit(0);
}
public static void main(String[] args) {
// This is the file into which we are about to write the bytecode for the stub
String fileName = null;
//the index of the first className
int classIndex = 0;
// Check number of arguments
if (args.length <= 0) {
printUsageAndExit();
}
String directoryName = "./";
if (args[0].equals("-d")) {
directoryName = args[1];
classIndex = 2;
}
// If the directory name does not end with a file separator, add one
if (!directoryName.endsWith(System.getProperty("file.separator"))) {
directoryName = directoryName +
System.getProperty("file.separator");
}
// Name of the class
for (int i = classIndex; i < args.length; i++) {
try {
generateClass(args[i], directoryName);
} catch (Throwable e) {
System.err.println(e);
}
}
}
/**
* @param args
* @param fileName
*/
protected static void generateClass(String arg, String directoryName) {
String className = processClassName(arg);
String fileName = null;
System.out.println("Now processing " + className);
String stubClassName;
try {
// Generates the bytecode for the class
//ASM is now the default bytecode manipulator
byte[] data;
if (MOPClassLoader.BYTE_CODE_MANIPULATOR.equals("ASM")) {
ASMBytecodeStubBuilder bsb = new ASMBytecodeStubBuilder(className);
data = bsb.create();
stubClassName = bsb.getStubClassFullName();
} else if (MOPClassLoader.BYTE_CODE_MANIPULATOR.equals("BCEL")) {
BytecodeStubBuilder bsb = new BytecodeStubBuilder(className);
data = bsb.create();
stubClassName = bsb.getStubClassFullName();
} else {
// that shouldn't happen, unless someone manually sets the BYTE_CODE_MANIPULATOR static variable
System.err.println(
"byteCodeManipulator argument is optionnal. If specified, it can only be set to BCEL.");
System.err.println(
"Any other setting will result in the use of ASM, the default bytecode manipulator framework");
stubClassName = null;
data = null;
}
char sep = System.getProperty("file.separator").toCharArray()[0];
fileName = directoryName + stubClassName.replace('.', sep) +
".class";
// And writes it to a file
new File(fileName.substring(0, fileName.lastIndexOf(sep))).mkdirs();
// String fileName = directoryName + System.getProperty ("file.separator") +
File f = new File(fileName);
FileOutputStream fos = new FileOutputStream(f);
fos.write(data);
fos.flush();
fos.close();
System.out.println("Wrote file " + fileName);
} catch (ClassNotFoundException e) {
System.err.println("Cannot find class " + className);
} catch (Exception e) {
System.err.println("Cannot write file " + fileName);
System.err.println("Reason is " + e);
}
}
}
|
package org.pentaho.di.job.entries.shell;
import static org.pentaho.di.job.entry.validator.AbstractFileValidator.putVariableSpace;
import static org.pentaho.di.job.entry.validator.AndValidator.putValidators;
import static org.pentaho.di.job.entry.validator.JobEntryValidatorUtils.andValidator;
import static org.pentaho.di.job.entry.validator.JobEntryValidatorUtils.fileExistsValidator;
import static org.pentaho.di.job.entry.validator.JobEntryValidatorUtils.notBlankValidator;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.commons.vfs.FileObject;
import org.pentaho.di.cluster.SlaveServer;
import org.pentaho.di.core.CheckResultInterface;
import org.pentaho.di.core.Const;
import org.pentaho.di.core.Result;
import org.pentaho.di.core.ResultFile;
import org.pentaho.di.core.RowMetaAndData;
import org.pentaho.di.core.database.DatabaseMeta;
import org.pentaho.di.core.exception.KettleDatabaseException;
import org.pentaho.di.core.exception.KettleException;
import org.pentaho.di.core.exception.KettleXMLException;
import org.pentaho.di.core.logging.Log4jFileAppender;
import org.pentaho.di.core.logging.LogLevel;
import org.pentaho.di.core.logging.LogWriter;
import org.pentaho.di.core.util.StreamLogger;
import org.pentaho.di.core.vfs.KettleVFS;
import org.pentaho.di.core.xml.XMLHandler;
import org.pentaho.di.i18n.BaseMessages;
import org.pentaho.di.job.JobMeta;
import org.pentaho.di.job.entry.JobEntryBase;
import org.pentaho.di.job.entry.JobEntryInterface;
import org.pentaho.di.job.entry.validator.ValidatorContext;
import org.pentaho.di.repository.Repository;
import org.pentaho.di.repository.ObjectId;
import org.pentaho.di.resource.ResourceEntry;
import org.pentaho.di.resource.ResourceReference;
import org.pentaho.di.resource.ResourceEntry.ResourceType;
import org.w3c.dom.Node;
/**
* Shell type of Job Entry. You can define shell scripts to be executed in a
* Job.
*
* @author Matt
* @since 01-10-2003, rewritten on 18-06-2004
*/
public class JobEntryShell extends JobEntryBase implements Cloneable, JobEntryInterface
{
private static Class<?> PKG = JobEntryShell.class; // for i18n purposes, needed by Translator2!! $NON-NLS-1$
private String filename;
private String workDirectory;
public String arguments[];
public boolean argFromPrevious;
public boolean setLogfile;
public String logfile, logext;
public boolean addDate, addTime;
public LogLevel logFileLevel;
public boolean execPerRow;
public boolean setAppendLogfile;
public boolean insertScript;
public String script;
public JobEntryShell(String name)
{
super(name, "");
}
public JobEntryShell()
{
this("");
clear();
}
public Object clone()
{
JobEntryShell je = (JobEntryShell) super.clone();
return je;
}
public String getXML()
{
StringBuffer retval = new StringBuffer(300);
retval.append(super.getXML());
retval.append(" ").append(XMLHandler.addTagValue("filename", filename));
retval.append(" ").append(XMLHandler.addTagValue("work_directory", workDirectory));
retval.append(" ").append(XMLHandler.addTagValue("arg_from_previous", argFromPrevious));
retval.append(" ").append(XMLHandler.addTagValue("exec_per_row", execPerRow));
retval.append(" ").append(XMLHandler.addTagValue("set_logfile", setLogfile));
retval.append(" ").append(XMLHandler.addTagValue("logfile", logfile));
retval.append(" ").append(XMLHandler.addTagValue("set_append_logfile", setAppendLogfile));
retval.append(" ").append(XMLHandler.addTagValue("logext", logext));
retval.append(" ").append(XMLHandler.addTagValue("add_date", addDate));
retval.append(" ").append(XMLHandler.addTagValue("add_time", addTime));
retval.append(" ").append(XMLHandler.addTagValue("insertScript", insertScript));
retval.append(" ").append(XMLHandler.addTagValue("script", script));
retval.append(" ").append(XMLHandler.addTagValue("loglevel", (logFileLevel == null) ? null : logFileLevel.getCode()));
if (arguments != null)
for (int i = 0; i < arguments.length; i++)
{
// THIS IS A VERY BAD WAY OF READING/SAVING AS IT MAKES
// THE XML "DUBIOUS". DON'T REUSE IT. (Sven B)
retval.append(" ").append(XMLHandler.addTagValue("argument" + i, arguments[i]));
}
return retval.toString();
}
public void loadXML(Node entrynode, List<DatabaseMeta> databases, List<SlaveServer> slaveServers,
Repository rep) throws KettleXMLException
{
try
{
super.loadXML(entrynode, databases, slaveServers);
setFileName(XMLHandler.getTagValue(entrynode, "filename"));
setWorkDirectory(XMLHandler.getTagValue(entrynode, "work_directory"));
argFromPrevious = "Y".equalsIgnoreCase(XMLHandler.getTagValue(entrynode, "arg_from_previous"));
execPerRow = "Y".equalsIgnoreCase(XMLHandler.getTagValue(entrynode, "exec_per_row"));
setLogfile = "Y".equalsIgnoreCase(XMLHandler.getTagValue(entrynode, "set_logfile"));
setAppendLogfile = "Y".equalsIgnoreCase( XMLHandler.getTagValue(entrynode, "set_append_logfile") );
addDate = "Y".equalsIgnoreCase(XMLHandler.getTagValue(entrynode, "add_date"));
addTime = "Y".equalsIgnoreCase(XMLHandler.getTagValue(entrynode, "add_time"));
logfile = XMLHandler.getTagValue(entrynode, "logfile");
logext = XMLHandler.getTagValue(entrynode, "logext");
logFileLevel = LogLevel.getLogLevelForCode(XMLHandler.getTagValue(entrynode, "loglevel"));
insertScript = "Y".equalsIgnoreCase(XMLHandler.getTagValue(entrynode, "insertScript"));
script= XMLHandler.getTagValue(entrynode, "script");
// How many arguments?
int argnr = 0;
while (XMLHandler.getTagValue(entrynode, "argument" + argnr) != null)
argnr++;
arguments = new String[argnr];
// Read them all...
// THIS IS A VERY BAD WAY OF READING/SAVING AS IT MAKES
// THE XML "DUBIOUS". DON'T REUSE IT.
for (int a = 0; a < argnr; a++)
arguments[a] = XMLHandler.getTagValue(entrynode, "argument" + a);
} catch (KettleException e)
{
throw new KettleXMLException("Unable to load job entry of type 'shell' from XML node", e);
}
}
// Load the jobentry from repository
public void loadRep(Repository rep, ObjectId id_jobentry, List<DatabaseMeta> databases,
List<SlaveServer> slaveServers) throws KettleException
{
try
{
setFileName(rep.getJobEntryAttributeString(id_jobentry, "file_name"));
setWorkDirectory(rep.getJobEntryAttributeString(id_jobentry, "work_directory"));
argFromPrevious = rep.getJobEntryAttributeBoolean(id_jobentry, "arg_from_previous");
execPerRow = rep.getJobEntryAttributeBoolean(id_jobentry, "exec_per_row");
setLogfile = rep.getJobEntryAttributeBoolean(id_jobentry, "set_logfile");
setAppendLogfile = rep.getJobEntryAttributeBoolean(id_jobentry, "set_append_logfile");
addDate = rep.getJobEntryAttributeBoolean(id_jobentry, "add_date");
addTime = rep.getJobEntryAttributeBoolean(id_jobentry, "add_time");
logfile = rep.getJobEntryAttributeString(id_jobentry, "logfile");
logext = rep.getJobEntryAttributeString(id_jobentry, "logext");
logFileLevel = LogLevel.getLogLevelForCode(rep.getJobEntryAttributeString(id_jobentry, "loglevel"));
insertScript = rep.getJobEntryAttributeBoolean(id_jobentry, "insertScript");
script = rep.getJobEntryAttributeString(id_jobentry, "script");
// How many arguments?
int argnr = rep.countNrJobEntryAttributes(id_jobentry, "argument");
arguments = new String[argnr];
// Read them all...
for (int a = 0; a < argnr; a++)
{
arguments[a] = rep.getJobEntryAttributeString(id_jobentry, a, "argument");
}
} catch (KettleDatabaseException dbe)
{
throw new KettleException(
"Unable to load job entry of type 'shell' from the repository with id_jobentry="
+ id_jobentry, dbe);
}
}
// Save the attributes of this job entry
public void saveRep(Repository rep, ObjectId id_job) throws KettleException
{
try
{
rep.saveJobEntryAttribute(id_job, getObjectId(), "file_name", filename);
rep.saveJobEntryAttribute(id_job, getObjectId(), "work_directory", workDirectory);
rep.saveJobEntryAttribute(id_job, getObjectId(), "arg_from_previous", argFromPrevious);
rep.saveJobEntryAttribute(id_job, getObjectId(), "exec_per_row", execPerRow);
rep.saveJobEntryAttribute(id_job, getObjectId(), "set_logfile", setLogfile);
rep.saveJobEntryAttribute(id_job, getObjectId(), "set_append_logfile", setAppendLogfile);
rep.saveJobEntryAttribute(id_job, getObjectId(), "add_date", addDate);
rep.saveJobEntryAttribute(id_job, getObjectId(), "add_time", addTime);
rep.saveJobEntryAttribute(id_job, getObjectId(), "logfile", logfile);
rep.saveJobEntryAttribute(id_job, getObjectId(), "logext", logext);
rep.saveJobEntryAttribute(id_job, getObjectId(), "loglevel", logFileLevel == null ? LogLevel.NOTHING.getCode() : logFileLevel.getCode());
rep.saveJobEntryAttribute(id_job, getObjectId(), "insertScript", insertScript);
rep.saveJobEntryAttribute(id_job, getObjectId(), "script", script);
// save the arguments...
if (arguments != null)
{
for (int i = 0; i < arguments.length; i++)
{
rep.saveJobEntryAttribute(id_job, getObjectId(), i, "argument", arguments[i]);
}
}
} catch (KettleDatabaseException dbe)
{
throw new KettleException("Unable to save job entry of type 'shell' to the repository", dbe);
}
}
public void clear()
{
super.clear();
filename = null;
workDirectory = null;
arguments = null;
argFromPrevious = false;
addDate = false;
addTime = false;
logfile = null;
logext = null;
setLogfile = false;
execPerRow = false;
setAppendLogfile=false;
insertScript=false;
script=null;
}
public void setFileName(String n)
{
filename = n;
}
public String getFilename()
{
return filename;
}
public String getRealFilename()
{
return environmentSubstitute(getFilename());
}
public void setWorkDirectory(String n)
{
workDirectory = n;
}
public String getWorkDirectory()
{
return workDirectory;
}
public void setScript(String scriptin)
{
script=scriptin;
}
public String getScript()
{
return script;
}
public String getLogFilename()
{
String retval = "";
if (setLogfile)
{
retval+=logfile==null?"":logfile;
Calendar cal = Calendar.getInstance();
if (addDate)
{
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
retval += "_" + sdf.format(cal.getTime());
}
if (addTime)
{
SimpleDateFormat sdf = new SimpleDateFormat("HHmmss");
retval += "_" + sdf.format(cal.getTime());
}
if (logext != null && logext.length() > 0)
{
retval += "." + logext;
}
}
return retval;
}
public Result execute(Result result, int nr) throws KettleException
{
Log4jFileAppender appender = null;
LogLevel shellLogLevel = parentJob.getLogLevel();
if (setLogfile)
{
String realLogFilename=environmentSubstitute(getLogFilename());
// We need to check here the log filename
// if we do not have one, we must fail
if(Const.isEmpty(realLogFilename)) {
logError(BaseMessages.getString(PKG, "JobEntryShell.Exception.LogFilenameMissing"));
result.setNrErrors(1);
result.setResult(false);
return result;
}
try
{
appender = LogWriter.createFileAppender(realLogFilename, true,setAppendLogfile);
LogWriter.getInstance().addAppender(appender);
} catch (KettleException e)
{
logError(BaseMessages.getString(PKG, "JobEntryShell.Error.UnableopenAppenderFile",getLogFilename(), e.toString()));
logError(Const.getStackTracker(e));
result.setNrErrors(1);
result.setResult(false);
return result;
}
shellLogLevel = logFileLevel;
}
log.setLogLevel(shellLogLevel);
result.setEntryNr(nr);
// "Translate" the arguments for later
String substArgs[] = null;
if (arguments != null)
{
substArgs = new String[arguments.length];
for (int idx = 0; idx < arguments.length; idx++)
{
substArgs[idx] = environmentSubstitute(arguments[idx]);
}
}
int iteration = 0;
String args[] = substArgs;
RowMetaAndData resultRow = null;
boolean first = true;
List<RowMetaAndData> rows = result.getRows();
if(log.isDetailed()) {
logDetailed(BaseMessages.getString(PKG, "JobEntryShell.Log.FoundPreviousRows",""+(rows != null ? rows.size() : 0)));
}
while ((first && !execPerRow)
|| (execPerRow && rows != null && iteration < rows.size() && result.getNrErrors() == 0))
{
first = false;
if (rows != null && execPerRow)
{
resultRow = (RowMetaAndData) rows.get(iteration);
} else
{
resultRow = null;
}
List<RowMetaAndData> cmdRows = null;
if (execPerRow) // Execute for each input row
{
if (argFromPrevious) // Copy the input row to the (command
// line) arguments
{
if (resultRow != null)
{
args = new String[resultRow.size()];
for (int i = 0; i < resultRow.size(); i++)
{
args[i] = resultRow.getString(i, null);
}
}
} else
{
// Just pass a single row
List<RowMetaAndData> newList = new ArrayList<RowMetaAndData>();
newList.add(resultRow);
cmdRows = newList;
}
} else
{
if (argFromPrevious)
{
// Only put the first Row on the arguments
args = null;
if (resultRow != null)
{
args = new String[resultRow.size()];
for (int i = 0; i < resultRow.size(); i++)
{
args[i] = resultRow.getString(i, null);
}
} else
{
cmdRows = rows;
}
} else
{
// Keep it as it was...
cmdRows = rows;
}
}
executeShell(result, cmdRows, args);
iteration++;
}
if (setLogfile)
{
if (appender != null)
{
LogWriter.getInstance().removeAppender(appender);
appender.close();
ResultFile resultFile = new ResultFile(ResultFile.FILE_TYPE_LOG, appender.getFile(), parentJob.getJobname(), getName());
result.getResultFiles().put(resultFile.getFile().toString(), resultFile);
}
}
return result;
}
private void executeShell(Result result, List<RowMetaAndData> cmdRows, String[] args)
{
FileObject fileObject = null;
String realScript=null;
FileObject tempFile=null;
try
{
// What's the exact command?
String base[] = null;
List<String> cmds = new ArrayList<String>();
if(log.isBasic()) logBasic(BaseMessages.getString(PKG, "JobShell.RunningOn",Const.getOS()));
if(insertScript)
{
realScript=environmentSubstitute(script);
}else
{
String realFilename = environmentSubstitute(getFilename());
fileObject = KettleVFS.getFileObject(realFilename, this);
}
if (Const.getOS().equals("Windows 95"))
{
base = new String[] { "command.com", "/C" };
if (insertScript) {
tempFile = KettleVFS.createTempFile("kettle", "shell.bat", environmentSubstitute(workDirectory), this);
fileObject = createTemporaryShellFile(tempFile, realScript);
}
} else if (Const.getOS().startsWith("Windows"))
{
base = new String[] { "cmd.exe", "/C" };
if (insertScript) {
tempFile = KettleVFS.createTempFile("kettle", "shell.bat", environmentSubstitute(workDirectory), this);
fileObject = createTemporaryShellFile(tempFile, realScript);
}
} else
{
if (insertScript) {
tempFile = KettleVFS.createTempFile("kettle", "shell", environmentSubstitute(workDirectory), this);
fileObject = createTemporaryShellFile(tempFile, realScript);
}
base = new String[] { KettleVFS.getFilename(fileObject) };
}
// Construct the arguments...
if (argFromPrevious && cmdRows != null)
{
// Add the base command...
for (int i = 0; i < base.length; i++)
cmds.add(base[i]);
if (Const.getOS().equals("Windows 95") || Const.getOS().startsWith("Windows"))
{
// for windows all arguments including the command itself
// need to be
// included in 1 argument to cmd/command.
StringBuffer cmdline = new StringBuffer(300);
cmdline.append('"');
cmdline.append(Const.optionallyQuoteStringByOS(KettleVFS.getFilename(fileObject)));
// Add the arguments from previous results...
for (int i = 0; i < cmdRows.size(); i++) // Normally just
// one row, but
// once in a
// while to
// remain
// compatible we
// have
// multiple.
{
RowMetaAndData r = (RowMetaAndData) cmdRows.get(i);
for (int j = 0; j < r.size(); j++)
{
cmdline.append(' ');
cmdline.append(Const.optionallyQuoteStringByOS(r.getString(j, null)));
}
}
cmdline.append('"');
cmds.add(cmdline.toString());
} else
{
// Add the arguments from previous results...
for (int i = 0; i < cmdRows.size(); i++) // Normally just
// one row, but
// once in a
// while to
// remain
// compatible we
// have
// multiple.
{
RowMetaAndData r = (RowMetaAndData) cmdRows.get(i);
for (int j = 0; j < r.size(); j++)
{
cmds.add(Const.optionallyQuoteStringByOS(r.getString(j, null)));
}
}
}
} else if (args != null)
{
// Add the base command...
for (int i = 0; i < base.length; i++)
cmds.add(base[i]);
if (Const.getOS().equals("Windows 95") || Const.getOS().startsWith("Windows"))
{
// for windows all arguments including the command itself
// need to be
// included in 1 argument to cmd/command.
StringBuffer cmdline = new StringBuffer(300);
cmdline.append('"');
cmdline.append(Const.optionallyQuoteStringByOS(KettleVFS.getFilename(fileObject)));
for (int i = 0; i < args.length; i++)
{
cmdline.append(' ');
cmdline.append(Const.optionallyQuoteStringByOS(args[i]));
}
cmdline.append('"');
cmds.add(cmdline.toString());
} else
{
for (int i = 0; i < args.length; i++)
{
cmds.add(args[i]);
}
}
}
StringBuffer command = new StringBuffer();
Iterator<String> it = cmds.iterator();
boolean first = true;
while (it.hasNext())
{
if (!first)
command.append(' ');
else
first = false;
command.append((String) it.next());
}
if(log.isBasic()) logBasic(BaseMessages.getString(PKG, "JobShell.ExecCommand",command.toString()));
// Build the environment variable list...
ProcessBuilder procBuilder = new ProcessBuilder(cmds);
Map<String, String> env = procBuilder.environment();
String[] variables = listVariables();
for (int i = 0; i < variables.length; i++)
{
env.put(variables[i], getVariable(variables[i]));
}
if (getWorkDirectory() != null && !Const.isEmpty(Const.rtrim(getWorkDirectory())))
{
String vfsFilename = environmentSubstitute(getWorkDirectory());
File file = new File(KettleVFS.getFilename(KettleVFS.getFileObject(vfsFilename, this)));
procBuilder.directory(file);
}
Process proc = procBuilder.start();
// any error message?
StreamLogger errorLogger = new StreamLogger(log, proc.getErrorStream(), "(stderr)");
// any output?
StreamLogger outputLogger = new StreamLogger(log, proc.getInputStream(), "(stdout)");
// kick them off
new Thread(errorLogger).start();
new Thread(outputLogger).start();
proc.waitFor();
if(log.isDetailed()) logDetailed(BaseMessages.getString(PKG, "JobShell.CommandFinished",command.toString()));
// What's the exit status?
result.setExitStatus(proc.exitValue());
if (result.getExitStatus() != 0)
{
if(log.isDetailed())
logDetailed(BaseMessages.getString(PKG, "JobShell.ExitStatus",environmentSubstitute(getFilename()),""+result.getExitStatus()));
result.setNrErrors(1);
}
// close the streams
// otherwise you get "Too many open files, java.io.IOException" after a lot of iterations
proc.getErrorStream().close();
proc.getOutputStream().close();
} catch (IOException ioe)
{
logError(BaseMessages.getString(PKG, "JobShell.ErrorRunningShell",environmentSubstitute(getFilename()),ioe.toString()), ioe);
result.setNrErrors(1);
} catch (InterruptedException ie)
{
logError(BaseMessages.getString(PKG, "JobShell.Shellinterupted",environmentSubstitute(getFilename()),ie.toString()), ie);
result.setNrErrors(1);
} catch (Exception e)
{
logError(BaseMessages.getString(PKG, "JobShell.UnexpectedError",environmentSubstitute(getFilename()),e.toString()), e);
result.setNrErrors(1);
}
finally {
// If we created a temporary file, remove it...
if (tempFile!=null) {
try {
tempFile.delete();
}
catch(Exception e) {
BaseMessages.getString(PKG, "JobShell.UnexpectedError",tempFile.toString(),e.toString());
}
}
}
if (result.getNrErrors() > 0)
{
result.setResult(false);
} else
{
result.setResult(true);
}
}
private FileObject createTemporaryShellFile(FileObject tempFile, String fileContent) throws Exception
{
// Create a unique new temporary filename in the working directory, put the script in there
if (tempFile != null && fileContent != null) {
try {
tempFile.createFile();
OutputStream outputStream = tempFile.getContent().getOutputStream();
outputStream.write(fileContent.getBytes());
outputStream.close();
if (!Const.getOS().startsWith("Windows")) {
String tempFilename = KettleVFS.getFilename(tempFile);
// Now we have to make this file executable...
// On Unix-like systems this is done using the command "/bin/chmod +x filename"
ProcessBuilder procBuilder = new ProcessBuilder("chmod", "+x", tempFilename);
Process proc = procBuilder.start();
// Eat/log stderr/stdout all messages in a different thread...
StreamLogger errorLogger = new StreamLogger(log, proc.getErrorStream(), toString() + " (stderr)");
StreamLogger outputLogger = new StreamLogger(log, proc.getInputStream(), toString() + " (stdout)");
new Thread(errorLogger).start();
new Thread(outputLogger).start();
proc.waitFor();
}
}
catch(Exception e) {
throw new Exception("Unable to create temporary file to execute script", e);
}
}
return tempFile;
}
public boolean evaluates()
{
return true;
}
public boolean isUnconditional()
{
return true;
}
public List<ResourceReference> getResourceDependencies(JobMeta jobMeta)
{
List<ResourceReference> references = super.getResourceDependencies(jobMeta);
if (!Const.isEmpty(filename))
{
String realFileName = jobMeta.environmentSubstitute(filename);
ResourceReference reference = new ResourceReference(this);
reference.getEntries().add(new ResourceEntry(realFileName, ResourceType.FILE));
references.add(reference);
}
return references;
}
@Override
public void check(List<CheckResultInterface> remarks, JobMeta jobMeta)
{
ValidatorContext ctx = new ValidatorContext();
putVariableSpace(ctx, getVariables());
putValidators(ctx, notBlankValidator(), fileExistsValidator());
andValidator().validate(this, "workDirectory", remarks, ctx); //$NON-NLS-1$
andValidator().validate(this, "filename", remarks, putValidators(notBlankValidator())); //$NON-NLS-1$
if (setLogfile)
{
andValidator().validate(this, "logfile", remarks, putValidators(notBlankValidator())); //$NON-NLS-1$
}
}
protected String getLogfile()
{
return logfile;
}
}
|
package org.pentaho.di.job.entries.trans;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Map;
import org.pentaho.di.cluster.SlaveServer;
import org.pentaho.di.core.CheckResult;
import org.pentaho.di.core.CheckResultInterface;
import org.pentaho.di.core.Const;
import org.pentaho.di.core.Result;
import org.pentaho.di.core.ResultFile;
import org.pentaho.di.core.RowMetaAndData;
import org.pentaho.di.core.SQLStatement;
import org.pentaho.di.core.database.DatabaseMeta;
import org.pentaho.di.core.exception.KettleDatabaseException;
import org.pentaho.di.core.exception.KettleException;
import org.pentaho.di.core.exception.KettleJobException;
import org.pentaho.di.core.exception.KettleXMLException;
import org.pentaho.di.core.logging.Log4jFileAppender;
import org.pentaho.di.core.logging.LogWriter;
import org.pentaho.di.core.variables.VariableSpace;
import org.pentaho.di.core.vfs.KettleVFS;
import org.pentaho.di.core.xml.XMLHandler;
import org.pentaho.di.job.Job;
import org.pentaho.di.job.JobEntryType;
import org.pentaho.di.job.JobMeta;
import org.pentaho.di.job.entry.JobEntryBase;
import org.pentaho.di.job.entry.JobEntryInterface;
import org.pentaho.di.repository.Repository;
import org.pentaho.di.repository.RepositoryDirectory;
import org.pentaho.di.resource.ResourceDefinition;
import org.pentaho.di.resource.ResourceEntry;
import org.pentaho.di.resource.ResourceNamingInterface;
import org.pentaho.di.resource.ResourceReference;
import org.pentaho.di.resource.ResourceEntry.ResourceType;
import org.pentaho.di.trans.Trans;
import org.pentaho.di.trans.TransExecutionConfiguration;
import org.pentaho.di.trans.TransMeta;
import org.pentaho.di.trans.cluster.TransSplitter;
import org.pentaho.di.www.SlaveServerTransStatus;
import org.pentaho.di.www.WebResult;
import org.w3c.dom.Node;
/**
* This is the job entry that defines a transformation to be run.
*
* @author Matt
* @since 1-10-2003, rewritten on 18-06-2004
*
*/
@org.pentaho.di.core.annotations.Job(image="TRN.png",id="TRANS",type=JobEntryType.TRANSFORMATION,tooltip="JobEntry.Trans.Tooltip")
public class JobEntryTrans extends JobEntryBase implements Cloneable, JobEntryInterface
{
private String transname;
private String filename;
private RepositoryDirectory directory;
public String arguments[];
public boolean argFromPrevious;
public boolean execPerRow;
public boolean clearResultRows;
public boolean clearResultFiles;
public boolean setLogfile;
public String logfile, logext;
public boolean addDate, addTime;
public int loglevel;
private String directoryPath;
private boolean clustering;
public JobEntryTrans(String name)
{
super(name, "");
setJobEntryType(JobEntryType.TRANSFORMATION);
}
public JobEntryTrans()
{
this("");
clear();
}
public Object clone()
{
JobEntryTrans je = (JobEntryTrans) super.clone();
return je;
}
public JobEntryTrans(JobEntryBase jeb)
{
super(jeb);
}
public void setFileName(String n)
{
filename=n;
}
/**
* @deprecated use getFilename() instead
* @return the filename
*/
public String getFileName()
{
return filename;
}
public String getFilename()
{
return filename;
}
public String getRealFilename()
{
return environmentSubstitute(getFilename());
}
public void setTransname(String transname)
{
this.transname=transname;
}
public String getTransname()
{
return transname;
}
public RepositoryDirectory getDirectory()
{
return directory;
}
public void setDirectory(RepositoryDirectory directory)
{
this.directory = directory;
}
public String getLogFilename()
{
String retval="";
if (setLogfile)
{
retval+=logfile;
Calendar cal = Calendar.getInstance();
if (addDate)
{
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
retval+="_"+sdf.format(cal.getTime());
}
if (addTime)
{
SimpleDateFormat sdf = new SimpleDateFormat("HHmmss");
retval+="_"+sdf.format(cal.getTime());
}
if (logext!=null && logext.length()>0)
{
retval+="."+logext;
}
}
return retval;
}
public String getXML()
{
StringBuffer retval = new StringBuffer(300);
retval.append(super.getXML());
retval.append(" ").append(XMLHandler.addTagValue("filename", filename));
retval.append(" ").append(XMLHandler.addTagValue("transname", transname));
if (directory!=null)
{
retval.append(" ").append(XMLHandler.addTagValue("directory", directory.getPath()));
}
else
if (directoryPath!=null)
{
retval.append(" ").append(XMLHandler.addTagValue("directory", directoryPath)); // don't loose this info (backup/recovery)
}
retval.append(" ").append(XMLHandler.addTagValue("arg_from_previous", argFromPrevious));
retval.append(" ").append(XMLHandler.addTagValue("exec_per_row", execPerRow));
retval.append(" ").append(XMLHandler.addTagValue("clear_rows", clearResultRows));
retval.append(" ").append(XMLHandler.addTagValue("clear_files", clearResultFiles));
retval.append(" ").append(XMLHandler.addTagValue("set_logfile", setLogfile));
retval.append(" ").append(XMLHandler.addTagValue("logfile", logfile));
retval.append(" ").append(XMLHandler.addTagValue("logext", logext));
retval.append(" ").append(XMLHandler.addTagValue("add_date", addDate));
retval.append(" ").append(XMLHandler.addTagValue("add_time", addTime));
retval.append(" ").append(XMLHandler.addTagValue("loglevel", LogWriter.getLogLevelDesc(loglevel)));
retval.append(" ").append(XMLHandler.addTagValue("cluster", clustering));
if (arguments!=null)
for (int i=0;i<arguments.length;i++)
{
retval.append(" ").append(XMLHandler.addTagValue("argument"+i, arguments[i]));
}
return retval.toString();
}
public void loadXML(Node entrynode, List<DatabaseMeta> databases, Repository rep) throws KettleXMLException
{
try
{
super.loadXML(entrynode, databases);
filename = XMLHandler.getTagValue(entrynode, "filename") ;
transname = XMLHandler.getTagValue(entrynode, "transname") ;
directoryPath = XMLHandler.getTagValue(entrynode, "directory");
if (rep!=null) // import from XML into a repository for example... (or copy/paste)
{
directory = rep.getDirectoryTree().findDirectory(directoryPath);
}
argFromPrevious = "Y".equalsIgnoreCase( XMLHandler.getTagValue(entrynode, "arg_from_previous") );
execPerRow = "Y".equalsIgnoreCase( XMLHandler.getTagValue(entrynode, "exec_per_row") );
clearResultRows = "Y".equalsIgnoreCase( XMLHandler.getTagValue(entrynode, "clear_rows") );
clearResultFiles = "Y".equalsIgnoreCase( XMLHandler.getTagValue(entrynode, "clear_files") );
setLogfile = "Y".equalsIgnoreCase( XMLHandler.getTagValue(entrynode, "set_logfile") );
addDate = "Y".equalsIgnoreCase( XMLHandler.getTagValue(entrynode, "add_date") );
addTime = "Y".equalsIgnoreCase( XMLHandler.getTagValue(entrynode, "add_time") );
logfile = XMLHandler.getTagValue(entrynode, "logfile");
logext = XMLHandler.getTagValue(entrynode, "logext");
loglevel = LogWriter.getLogLevel( XMLHandler.getTagValue(entrynode, "loglevel"));
clustering = "Y".equalsIgnoreCase( XMLHandler.getTagValue(entrynode, "cluster") );
// How many arguments?
int argnr = 0;
while ( XMLHandler.getTagValue(entrynode, "argument"+argnr)!=null) argnr++;
arguments = new String[argnr];
// Read them all...
for (int a=0;a<argnr;a++) arguments[a]=XMLHandler.getTagValue(entrynode, "argument"+a);
}
catch(KettleException e)
{
throw new KettleXMLException("Unable to load job entry of type 'trans' from XML node", e);
}
}
// Load the jobentry from repository
public void loadRep(Repository rep, long id_jobentry, List<DatabaseMeta> databases) throws KettleException
{
try
{
super.loadRep(rep, id_jobentry, databases);
transname = rep.getJobEntryAttributeString(id_jobentry, "name");
String dirPath = rep.getJobEntryAttributeString(id_jobentry, "dir_path");
directory = rep.getDirectoryTree().findDirectory(dirPath);
filename = rep.getJobEntryAttributeString(id_jobentry, "file_name");
argFromPrevious = rep.getJobEntryAttributeBoolean(id_jobentry, "arg_from_previous");
execPerRow = rep.getJobEntryAttributeBoolean(id_jobentry, "exec_per_row");
clearResultRows = rep.getJobEntryAttributeBoolean(id_jobentry, "clear_rows", true);
clearResultFiles = rep.getJobEntryAttributeBoolean(id_jobentry, "clear_files", true);
setLogfile = rep.getJobEntryAttributeBoolean(id_jobentry, "set_logfile");
addDate = rep.getJobEntryAttributeBoolean(id_jobentry, "add_date");
addTime = rep.getJobEntryAttributeBoolean(id_jobentry, "add_time");
logfile = rep.getJobEntryAttributeString(id_jobentry, "logfile");
logext = rep.getJobEntryAttributeString(id_jobentry, "logext");
loglevel = LogWriter.getLogLevel( rep.getJobEntryAttributeString(id_jobentry, "loglevel") );
clustering = rep.getJobEntryAttributeBoolean(id_jobentry, "cluster");
// How many arguments?
int argnr = rep.countNrJobEntryAttributes(id_jobentry, "argument");
arguments = new String[argnr];
// Read them all...
for (int a=0;a<argnr;a++)
{
arguments[a]= rep.getJobEntryAttributeString(id_jobentry, a, "argument");
}
}
catch(KettleDatabaseException dbe)
{
throw new KettleException("Unable to load job entry of type 'trans' from the repository for id_jobentry="+id_jobentry, dbe);
}
}
// Save the attributes of this job entry
public void saveRep(Repository rep, long id_job) throws KettleException
{
try
{
super.saveRep(rep, id_job);
long id_transformation = rep.getTransformationID(transname, directory.getID());
rep.saveJobEntryAttribute(id_job, getID(), "id_transformation", id_transformation);
rep.saveJobEntryAttribute(id_job, getID(), "name", getTransname());
rep.saveJobEntryAttribute(id_job, getID(), "dir_path", getDirectory()!=null?getDirectory().getPath():"");
rep.saveJobEntryAttribute(id_job, getID(), "file_name", filename);
rep.saveJobEntryAttribute(id_job, getID(), "arg_from_previous", argFromPrevious);
rep.saveJobEntryAttribute(id_job, getID(), "exec_per_row", execPerRow);
rep.saveJobEntryAttribute(id_job, getID(), "clear_rows", clearResultRows);
rep.saveJobEntryAttribute(id_job, getID(), "clear_files", clearResultFiles);
rep.saveJobEntryAttribute(id_job, getID(), "set_logfile", setLogfile);
rep.saveJobEntryAttribute(id_job, getID(), "add_date", addDate);
rep.saveJobEntryAttribute(id_job, getID(), "add_time", addTime);
rep.saveJobEntryAttribute(id_job, getID(), "logfile", logfile);
rep.saveJobEntryAttribute(id_job, getID(), "logext", logext);
rep.saveJobEntryAttribute(id_job, getID(), "loglevel", LogWriter.getLogLevelDesc(loglevel));
rep.saveJobEntryAttribute(id_job, getID(), "cluster", clustering);
// save the arguments...
if (arguments!=null)
{
for (int i=0;i<arguments.length;i++)
{
rep.saveJobEntryAttribute(id_job, getID(), i, "argument", arguments[i]);
}
}
}
catch(KettleDatabaseException dbe)
{
throw new KettleException("Unable to save job entry of type 'trans' to the repository for id_job="+id_job, dbe);
}
}
public void clear()
{
super.clear();
transname=null;
filename=null;
directory = new RepositoryDirectory();
arguments=null;
argFromPrevious=false;
execPerRow=false;
addDate=false;
addTime=false;
logfile=null;
logext=null;
setLogfile=false;
clearResultRows=true;
clearResultFiles=true;
}
/**
* Execute this job entry and return the result.
* In this case it means, just set the result boolean in the Result class.
* @param result The result of the previous execution
* @param nr the job entry number
* @param rep the repository connection to use
* @param parentJob the parent job
* @return The Result of the execution.
*/
public Result execute(Result result, int nr, Repository rep, Job parentJob) throws KettleException
{
LogWriter log = LogWriter.getInstance();
result.setEntryNr( nr );
Log4jFileAppender appender = null;
int backupLogLevel = log.getLogLevel();
if (setLogfile)
{
try
{
appender = LogWriter.createFileAppender(environmentSubstitute(getLogFilename()), true);
}
catch(KettleException e)
{
log.logError(toString(), "Unable to open file appender for file ["+getLogFilename()+"] : "+e.toString());
log.logError(toString(), Const.getStackTracker(e));
result.setNrErrors(1);
result.setResult(false);
return result;
}
log.addAppender(appender);
log.setLogLevel(loglevel);
}
// Open the transformation...
// Default directory for now...
log.logBasic(toString(), "Opening filename : ["+environmentSubstitute(getFilename())+"]");
if (!Const.isEmpty(getFilename()))
{
log.logBasic(toString(), "Opening transformation: ["+environmentSubstitute(getFilename())+"]");
}
else
{
log.logBasic(toString(), "Opening transformation: ["+environmentSubstitute(getTransname())+"] in directory ["+directory.getPath()+"]");
}
// Load the transformation only once for the complete loop!
TransMeta transMeta = getTransMeta(rep);
int iteration = 0;
String args1[] = arguments;
if (args1==null || args1.length==0) // No arguments set, look at the parent job.
{
args1 = parentJob.getJobMeta().getArguments();
}
initializeVariablesFrom(parentJob);
// For the moment only do variable translation at the start of a job, not
// for every input row (if that would be switched on). This is for safety,
// the real argument setting is later on.
String args[] = null;
if ( args1 != null )
{
args = new String[args1.length];
for ( int idx = 0; idx < args1.length; idx++ )
{
args[idx] = environmentSubstitute(args1[idx]);
}
}
RowMetaAndData resultRow = null;
boolean first = true;
List<RowMetaAndData> rows = result.getRows();
while( ( first && !execPerRow ) || ( execPerRow && rows!=null && iteration<rows.size() && result.getNrErrors()==0 ) && !parentJob.isStopped() )
{
first=false;
if (rows!=null && execPerRow)
{
resultRow = rows.get(iteration);
}
else
{
resultRow = null;
}
try
{
log.logDetailed(toString(), "Starting transformation...(file="+getFilename()+", name="+getName()+"), repinfo="+getDescription());
// Set the result rows for the next one...
transMeta.setPreviousResult(result);
if (clearResultRows)
{
transMeta.getPreviousResult().setRows(new ArrayList<RowMetaAndData>());
}
if (clearResultFiles)
{
transMeta.getPreviousResult().getResultFiles().clear();
}
/*
* Set one or more "result" rows on the transformation...
*/
if (execPerRow) // Execute for each input row
{
if (argFromPrevious) // Copy the input row to the (command line) arguments
{
args = null;
if (resultRow!=null)
{
args = new String[resultRow.size()];
for (int i=0;i<resultRow.size();i++)
{
args[i] = resultRow.getString(i, null);
}
}
}
else
{
// Just pass a single row
List<RowMetaAndData> newList = new ArrayList<RowMetaAndData>();
newList.add(resultRow);
// This previous result rows list can be either empty or not.
// Depending on the checkbox "clear result rows"
// In this case, it would execute the transformation with one extra row each time
// Can't figure out a real use-case for it, but hey, who am I to decide that, right?
transMeta.getPreviousResult().getRows().addAll(newList);
}
}
else
{
if (argFromPrevious)
{
// Only put the first Row on the arguments
args = null;
if (resultRow!=null)
{
args = new String[resultRow.size()];
for (int i=0;i<resultRow.size();i++)
{
args[i] = resultRow.getString(i, null);
}
}
}
else
{
// do nothing
}
}
if (clustering)
{
TransExecutionConfiguration executionConfiguration = new TransExecutionConfiguration();
executionConfiguration.setClusterPosting(true);
executionConfiguration.setClusterPreparing(true);
executionConfiguration.setClusterStarting(true);
executionConfiguration.setClusterShowingTransformation(false);
executionConfiguration.setSafeModeEnabled(false);
TransSplitter transSplitter = Trans.executeClustered(transMeta, executionConfiguration );
// See if the remote transformations have finished.
// We could just look at the master, but I doubt that that is enough in all situations.
SlaveServer[] slaveServers = transSplitter.getSlaveTargets(); // <-- ask these guys
TransMeta[] slaves = transSplitter.getSlaves();
SlaveServer masterServer = transSplitter.getMasterServer(); // <-- AND this one
TransMeta master = transSplitter.getMaster();
boolean allFinished = false;
long errors = 0L;
while (!allFinished && !parentJob.isStopped() && errors==0)
{
allFinished = true;
errors=0L;
// Slaves first...
for (int s=0;s<slaveServers.length && allFinished && errors==0;s++)
{
try
{
SlaveServerTransStatus transStatus = slaveServers[s].getTransStatus(slaves[s].getName());
if (transStatus.isRunning()) allFinished = false;
errors+=transStatus.getNrStepErrors();
}
catch(Exception e)
{
errors+=1;
log.logError(toString(), "Unable to contact slave server '"+slaveServers[s].getName()+"' to check slave transformation : "+e.toString());
}
}
// Check the master too
if (allFinished && errors==0 && master!=null && master.nrSteps()>0)
{
try
{
SlaveServerTransStatus transStatus = masterServer.getTransStatus(master.getName());
if (transStatus.isRunning()) allFinished = false;
errors+=transStatus.getNrStepErrors();
}
catch(Exception e)
{
errors+=1;
log.logError(toString(), "Unable to contact slave server '"+masterServer.getName()+"' to check master transformation : "+e.toString());
}
}
if (parentJob.isStopped() || errors != 0)
{
// Stop all slaves and the master on the slave servers
for (int s=0;s<slaveServers.length && allFinished && errors==0;s++)
{
try
{
WebResult webResult = slaveServers[s].stopTransformation(slaves[s].getName());
if (!WebResult.STRING_OK.equals(webResult.getResult()))
{
log.logError(toString(), "Unable to stop slave transformation '"+slaves[s].getName()+"' : "+webResult.getMessage());
}
}
catch(Exception e)
{
errors+=1;
log.logError(toString(), "Unable to contact slave server '"+slaveServers[s].getName()+"' to stop transformation : "+e.toString());
}
}
try
{
WebResult webResult = masterServer.stopTransformation(master.getName());
if (!WebResult.STRING_OK.equals(webResult.getResult()))
{
log.logError(toString(), "Unable to stop master transformation '"+masterServer.getName()+"' : "+webResult.getMessage());
}
}
catch(Exception e)
{
errors+=1;
log.logError(toString(), "Unable to contact master server '"+masterServer.getName()+"' to stop the master : "+e.toString());
}
}
// Keep waiting until all transformations have finished
// If needed, we stop them again and again until they yield.
if (!allFinished)
{
// Not finished or error: wait a bit longer
log.logDetailed(toString(), "Clustered transformation is still running, waiting 10 seconds...");
try { Thread.sleep(10000); } catch(Exception e) {} // Check all slaves every 10 seconds. TODO: add 10s as parameter
}
}
result.setNrErrors(errors);
}
else // Local execution...
{
// Create the transformation from meta-data
Trans trans = new Trans(transMeta);
if (parentJob.getJobMeta().isBatchIdPassed())
{
trans.setPassedBatchId(parentJob.getPassedBatchId());
}
// set the parent job on the transformation, variables are taken from here...
trans.setParentJob(parentJob);
trans.shareVariablesWith(this);
// Execute!
if (!trans.execute(args))
{
log.logError(toString(), "Unable to prepare for execution of the transformation");
result.setNrErrors(1);
}
else
{
while (!trans.isFinished() && !parentJob.isStopped() && trans.getErrors() == 0)
{
try { Thread.sleep(100);}
catch(InterruptedException e) { }
}
if (parentJob.isStopped() || trans.getErrors() != 0)
{
trans.stopAll();
trans.waitUntilFinished();
trans.endProcessing("stop");
result.setNrErrors(1);
}
else
{
trans.endProcessing("end");
}
Result newResult = trans.getResult();
result.clear(); // clear only the numbers, NOT the files or rows.
result.add(newResult);
// Set the result rows too...
result.setRows(newResult.getRows());
if (setLogfile)
{
ResultFile resultFile = new ResultFile(ResultFile.FILE_TYPE_LOG, KettleVFS.getFileObject(getLogFilename()), parentJob.getName(), toString());
result.getResultFiles().put(resultFile.getFile().toString(), resultFile);
}
}
}
}
catch(Exception e)
{
log.logError(toString(), "Unable to open transformation: "+e.getMessage());
log.logError(toString(), Const.getStackTracker(e));
result.setNrErrors(1);
}
iteration++;
}
if (setLogfile)
{
if (appender!=null)
{
log.removeAppender(appender);
appender.close();
try
{
ResultFile resultFile = new ResultFile(ResultFile.FILE_TYPE_LOG, KettleVFS.getFileObject(appender.getFile().getAbsolutePath()), parentJob.getJobname(), getName());
result.getResultFiles().put(resultFile.getFile().toString(), resultFile);
}
catch(IOException e)
{
log.logError(toString(), "Error getting file object from file ["+appender.getFile()+"] : "+e.toString());
}
}
log.setLogLevel(backupLogLevel);
}
if (result.getNrErrors()==0)
{
result.setResult( true );
}
else
{
result.setResult( false );
}
return result;
}
private TransMeta getTransMeta(Repository rep) throws KettleException
{
LogWriter log = LogWriter.getInstance();
TransMeta transMeta = null;
if (!Const.isEmpty(getFilename())) // Load from an XML file
{
log.logBasic(toString(), "Loading transformation from XML file ["+environmentSubstitute(getFilename())+"]");
transMeta = new TransMeta(environmentSubstitute(getFilename()));
}
else
if (!Const.isEmpty(getTransname()) && getDirectory() != null) // Load from the repository
{
log.logBasic(toString(), "Loading transformation from repository ["+environmentSubstitute(getTransname())+"] in directory ["+getDirectory()+"]");
if ( rep != null )
{
// It only makes sense to try to load from the repository when the repository is also filled in.
transMeta = new TransMeta(rep, environmentSubstitute(getTransname()), getDirectory());
}
else
{
throw new KettleException("No repository defined!");
}
}
else
{
throw new KettleJobException("The transformation to execute is not specified!");
}
// Set the arguments...
transMeta.setArguments(arguments);
return transMeta;
}
public boolean evaluates()
{
return true;
}
public boolean isUnconditional()
{
return true;
}
public List<SQLStatement> getSQLStatements(Repository repository) throws KettleException
{
TransMeta transMeta = getTransMeta(repository);
return transMeta.getSQLStatements();
}
/**
* @return Returns the directoryPath.
*/
public String getDirectoryPath()
{
return directoryPath;
}
/**
* @param directoryPath The directoryPath to set.
*/
public void setDirectoryPath(String directoryPath)
{
this.directoryPath = directoryPath;
}
/**
* @return the clustering
*/
public boolean isClustering()
{
return clustering;
}
/**
* @param clustering the clustering to set
*/
public void setClustering(boolean clustering)
{
this.clustering = clustering;
}
public void check(List<CheckResultInterface> remarks, JobMeta jobMeta) {
String transformation = null;
if (!Const.isEmpty(getFilename())) {
transformation = jobMeta.environmentSubstitute(getFilename());
} else if (!Const.isEmpty(getTransname()) && getDirectory() != null) { // Load from the repository
transformation = jobMeta.environmentSubstitute(getTransname());
}
if (transformation != null) {
remarks.add(new CheckResult(CheckResultInterface.TYPE_RESULT_OK, Messages.getString("JobEntryTrans.CheckResult.TransformationDefined", transformation), this)); //$NON-NLS-1$
} else {
remarks.add(new CheckResult(CheckResultInterface.TYPE_RESULT_ERROR, Messages.getString("JobEntryTrans.CheckResult.TransformationNotDefined"), this)); //$NON-NLS-1$
}
}
/**
* Get a list of all the resource dependencies that the step is depending on.
*
* @return a list of all the resource dependencies that the step is depending on
*/
public List<ResourceReference> getResourceDependencies() {
List<ResourceReference> references = new ArrayList<ResourceReference>();
if (!Const.isEmpty(filename)) {
List<ResourceEntry> entries = new ArrayList<ResourceEntry>();
ResourceReference resourceReference = new ResourceReference(this, entries);
entries.add(new ResourceEntry(filename, ResourceType.FILE));
references.add(resourceReference);
}
return references;
}
/**
* We're going to load the transformation meta data referenced here.
* Then we're going to give it a new filename, modify that filename in this entries.
* The parent caller will have made a copy of it, so it should be OK to do so.
*/
public String exportResources(VariableSpace space, Map<String, ResourceDefinition> definitions, ResourceNamingInterface namingInterface) throws KettleException {
// Try to load the transformation from repository or file.
// Modify this recursively too...
if (!Const.isEmpty(filename)) {
// AGAIN: there is no need to clone this job entry because the caller is responsible for this.
// First load the transformation metadata...
TransMeta transMeta = getTransMeta(null);
// Also go down into the transformation and export the files there. (mapping recursively down)
String newFilename = transMeta.exportResources(transMeta, definitions, namingInterface);
// Set the correct filename inside the XML.
// Replace if BEFORE XML generation occurs.
transMeta.setFilename(newFilename);
// change it in the job entry
filename = newFilename;
// Don't save it, that has already been done a few lines above, in transMeta.exportResources()
// String xml = transMeta.getXML();
// definitions.put(newFilename, new ResourceDefinition(newFilename, xml));
return newFilename;
}
else {
return null;
}
}
}
|
package org.pentaho.di.trans.step;
import java.util.List;
import org.pentaho.di.core.Const;
import org.pentaho.di.core.exception.KettleException;
import org.pentaho.di.core.exception.KettlePluginException;
import org.pentaho.di.core.plugins.PartitionerPluginType;
import org.pentaho.di.core.plugins.PluginInterface;
import org.pentaho.di.core.plugins.PluginRegistry;
import org.pentaho.di.core.row.RowMetaInterface;
import org.pentaho.di.core.xml.XMLHandler;
import org.pentaho.di.core.xml.XMLInterface;
import org.pentaho.di.partition.PartitionSchema;
import org.pentaho.di.trans.Partitioner;
import org.w3c.dom.Node;
public class StepPartitioningMeta implements XMLInterface, Cloneable
{
public static final int PARTITIONING_METHOD_NONE = 0;
public static final int PARTITIONING_METHOD_MIRROR = 1;
public static final int PARTITIONING_METHOD_SPECIAL = 2;
public static final String[] methodCodes = new String[] { "none", "Mirror", };
public static final String[] methodDescriptions = new String[] { "None", "Mirror to all partitions" };
private int methodType;
private String method;
private String partitionSchemaName; // to allow delayed binding...
private PartitionSchema partitionSchema;
private Partitioner partitioner;
private boolean hasChanged = false;
public StepPartitioningMeta()
{
method = "none";
methodType = PARTITIONING_METHOD_NONE;
partitionSchema = new PartitionSchema();
hasChanged = false;
}
/**
* @param method
* @param partitionSchema
*/
public StepPartitioningMeta(String method, PartitionSchema partitionSchema) throws KettlePluginException {
setMethod( method );
this.partitionSchema = partitionSchema;
hasChanged = false;
}
public StepPartitioningMeta clone()
{
try {
StepPartitioningMeta stepPartitioningMeta = new StepPartitioningMeta(method, partitionSchema!=null ? (PartitionSchema) partitionSchema.clone() : null);
stepPartitioningMeta.partitionSchemaName = partitionSchemaName;
stepPartitioningMeta.setMethodType(methodType);
stepPartitioningMeta.setPartitioner(partitioner == null? null : partitioner.clone());
return stepPartitioningMeta;
} catch(KettlePluginException e) {
throw new RuntimeException("Unable to load partitioning plugin", e);
}
}
/**
* @return true if the partition schema names are the same.
*/
@Override
public boolean equals(Object obj) {
if (obj==null) return false;
if (partitionSchemaName==null) return false;
StepPartitioningMeta meta = (StepPartitioningMeta) obj;
if (meta.partitionSchemaName==null) return false;
return partitionSchemaName.equalsIgnoreCase(meta.partitionSchemaName);
}
@Override
public String toString() {
String description;
if (partitioner!=null) {
description = partitioner.getDescription();
}
else {
description = getMethodDescription();
}
if (partitionSchema!=null) {
description += " / "+partitionSchema.toString();
}
return description;
}
/**
* @return the partitioningMethod
*/
public int getMethodType()
{
return methodType;
}
/**
* @param method the partitioning method to set
*/
public void setMethod(String method) throws KettlePluginException {
if( !method.equals(this.method) )
{
this.method = method;
createPartitioner(method);
hasChanged = true;
}
}
public String getXML()
{
StringBuffer xml = new StringBuffer(150);
xml.append(" <partitioning>").append(Const.CR);
xml.append(" ").append(XMLHandler.addTagValue("method", getMethodCode()));
xml.append(" ").append(XMLHandler.addTagValue("schema_name", partitionSchema!=null?partitionSchema.getName():""));
if( partitioner != null )
{
xml.append( partitioner.getXML() );
}
xml.append(" </partitioning>").append(Const.CR);
return xml.toString();
}
public StepPartitioningMeta(Node partitioningMethodNode) throws KettleException
{
this();
setMethod( getMethod( XMLHandler.getTagValue(partitioningMethodNode, "method") ) );
partitionSchemaName = XMLHandler.getTagValue(partitioningMethodNode, "schema_name");
hasChanged = false;
if( partitioner != null )
{
partitioner.loadXML(partitioningMethodNode);
}
}
public String getMethodCode()
{
if( methodType == PARTITIONING_METHOD_SPECIAL)
{
if( partitioner != null )
{
return partitioner.getId();
} else {
return methodCodes[PARTITIONING_METHOD_NONE];
}
}
return methodCodes[methodType];
}
public String getMethodDescription()
{
if( methodType != PARTITIONING_METHOD_SPECIAL )
{
return methodDescriptions[methodType];
}
else
{
return partitioner.getDescription();
}
}
public String getMethod( ) {
return method;
}
public static final String getMethod(String name)
{
if (Const.isEmpty(name)) return methodCodes[PARTITIONING_METHOD_NONE];
for (int i=0;i<methodDescriptions.length;i++)
{
if (methodDescriptions[i].equalsIgnoreCase(name)){
return methodCodes[i];
}
}
for (int i=0;i<methodCodes.length;i++)
{
if (methodCodes[i].equalsIgnoreCase(name)) return methodCodes[i];
}
PluginRegistry registry = PluginRegistry.getInstance();
PluginInterface plugin = registry.findPluginWithName(PartitionerPluginType.class, name);
if( plugin != null ) {
return name;
}
plugin = registry.findPluginWithId(PartitionerPluginType.class, name);
if( plugin != null ) {
return name;
}
return methodCodes[PARTITIONING_METHOD_NONE];
}
public static final int getMethodType(String description)
{
for (int i=0;i<methodDescriptions.length;i++)
{
if (methodDescriptions[i].equalsIgnoreCase(description)){
return i;
}
}
for (int i=0;i<methodCodes.length;i++)
{
if (methodCodes[i].equalsIgnoreCase(description)) return i;
}
PluginInterface plugin = PluginRegistry.getInstance().findPluginWithId(PartitionerPluginType.class, description );
if( plugin != null ) {
return PARTITIONING_METHOD_SPECIAL;
}
return PARTITIONING_METHOD_NONE;
}
public boolean isPartitioned()
{
return methodType!=PARTITIONING_METHOD_NONE;
}
public void setPartitionSchemaName(String partitionSchemaName) {
this.partitionSchemaName = partitionSchemaName;
}
/**
* @return the partitionSchema
*/
public PartitionSchema getPartitionSchema()
{
return partitionSchema;
}
/**
* @param partitionSchema the partitionSchema to set
*/
public void setPartitionSchema(PartitionSchema partitionSchema)
{
this.partitionSchema = partitionSchema;
hasChanged = true;
}
/**
* Set the partitioning schema after loading from XML or repository
* @param partitionSchemas the list of partitioning schemas
*/
public void setPartitionSchemaAfterLoading(List<PartitionSchema> partitionSchemas) throws KettleException
{
partitionSchema=null; // sorry, not found!
for (int i=0;i<partitionSchemas.size() && partitionSchema==null;i++)
{
PartitionSchema schema = partitionSchemas.get(i);
if (schema.getName().equalsIgnoreCase(partitionSchemaName))
{
partitionSchema = schema; // found!
}
}
/*
if (methodType!=PARTITIONING_METHOD_NONE && partitionSchema==null) {
String message = "Unable to set partition schema for name ["+partitionSchemaName+"], method: "+getMethodDescription()+Const.CR;
message += "This is the list of available partition schema:"+Const.CR;
for (int i=0;i<partitionSchemas.size() && partitionSchema==null;i++)
{
PartitionSchema schema = partitionSchemas.get(i);
message+=" --> "+schema.getName()+Const.CR;
}
throw new KettleException(message);
}
*/
}
public void createPartitioner( String method ) throws KettlePluginException {
methodType = getMethodType(method);
switch ( methodType ) {
case PARTITIONING_METHOD_SPECIAL: {
PluginRegistry registry = PluginRegistry.getInstance();
PluginInterface plugin = registry.findPluginWithId(PartitionerPluginType.class, method);
partitioner = (Partitioner) registry.loadClass(plugin);
partitioner.setId(plugin.getIds()[0]);
break;
}
case PARTITIONING_METHOD_NONE:
default: partitioner = null;
}
if( partitioner != null )
{
partitioner.setMeta(this);
}
}
public boolean isMethodMirror()
{
return methodType==PARTITIONING_METHOD_MIRROR;
}
public int getPartition(RowMetaInterface rowMeta, Object[] row) throws KettleException
{
if( partitioner != null ) {
return partitioner.getPartition(rowMeta, row);
}
return 0;
}
public Partitioner getPartitioner() {
return partitioner;
}
public void setPartitioner(Partitioner partitioner) {
this.partitioner = partitioner;
}
public boolean hasChanged() {
return hasChanged;
}
public void hasChanged(boolean hasChanged) {
this.hasChanged = hasChanged;
}
public void setMethodType(int methodType) {
this.methodType = methodType;
}
}
|
package net.sf.cglib.core;
import java.io.*;
import java.util.*;
import java.lang.ref.*;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.Type;
/**
* Abstract class for all code-generating CGLIB utilities.
* In addition to caching generated classes for performance, it provides hooks for
* customizing the <code>ClassLoader</code>, name of the generated class, and transformations
* applied before generation.
*/
abstract public class AbstractClassGenerator
implements ClassGenerator
{
private static final Object NAME_KEY = new Object();
private static final ThreadLocal CURRENT = new ThreadLocal();
private GeneratorStrategy strategy = DefaultGeneratorStrategy.INSTANCE;
private NamingPolicy namingPolicy = DefaultNamingPolicy.INSTANCE;
private Source source;
private ClassLoader classLoader;
private String namePrefix;
private Object key;
private boolean useCache = true;
private String className;
protected boolean attemptLoad;
protected static class Source {
String name;
Map cache = new WeakHashMap();
public Source(String name) {
this.name = name;
}
}
protected AbstractClassGenerator(Source source) {
this.source = source;
}
protected void setNamePrefix(String namePrefix) {
this.namePrefix = namePrefix;
}
final protected String getClassName() {
if (className == null)
className = getClassName(getClassLoader());
return className;
}
private String getClassName(ClassLoader loader) {
final Set nameCache = getClassNameCache(loader);
return namingPolicy.getClassName(namePrefix, source.name, key, new Predicate() {
public boolean evaluate(Object arg) {
return nameCache.contains(arg);
}
});
}
private Set getClassNameCache(ClassLoader loader) {
return (Set)((Map)source.cache.get(loader)).get(NAME_KEY);
}
/**
* Set the <code>ClassLoader</code> in which the class will be generated.
* Concrete subclasses of <code>AbstractClassGenerator</code> (such as <code>Enhancer</code>)
* will try to choose an appropriate default if this is unset.
* <p>
* Classes are cached per-<code>ClassLoader</code> using a <code>WeakHashMap</code>, to allow
* the generated classes to be removed when the associated loader is garbage collected.
* @param classLoader the loader to generate the new class with, or null to use the default
*/
public void setClassLoader(ClassLoader classLoader) {
this.classLoader = classLoader;
}
/**
* Override the default naming policy.
* @see DefaultNamingPolicy
* @param namingPolicy the custom policy, or null to use the default
*/
public void setNamingPolicy(NamingPolicy namingPolicy) {
if (namingPolicy == null)
namingPolicy = DefaultNamingPolicy.INSTANCE;
this.namingPolicy = namingPolicy;
}
/**
* @see #setNamingPolicy
*/
public NamingPolicy getNamingPolicy() {
return namingPolicy;
}
/**
* Whether use and update the static cache of generated classes
* for a class with the same properties. Default is <code>true</code>.
*/
public void setUseCache(boolean useCache) {
this.useCache = useCache;
}
/**
* @see #setUseCache
*/
public boolean getUseCache() {
return useCache;
}
/**
* If set, CGLIB will attempt to load classes from the specified
* <code>ClassLoader</code> before generating them. Because generated
* class names are not guaranteed to be unique, the default is <code>false</code>.
*/
public void setAttemptLoad(boolean attemptLoad) {
this.attemptLoad = attemptLoad;
}
public boolean getAttemptLoad() {
return attemptLoad;
}
/**
* Set the strategy to use to create the bytecode from this generator.
* By default an instance of {@see DefaultGeneratorStrategy} is used.
*/
public void setStrategy(GeneratorStrategy strategy) {
if (strategy == null)
strategy = DefaultGeneratorStrategy.INSTANCE;
this.strategy = strategy;
}
/**
* @see #setStrategy
*/
public GeneratorStrategy getStrategy() {
return strategy;
}
/**
* Used internally by CGLIB. Returns the <code>AbstractClassGenerator</code>
* that is being used to generate a class in the current thread.
*/
public static AbstractClassGenerator getCurrent() {
return (AbstractClassGenerator)CURRENT.get();
}
public ClassLoader getClassLoader() {
ClassLoader t = classLoader;
if (t == null) {
t = getDefaultClassLoader();
}
if (t == null) {
t = getClass().getClassLoader();
}
if (t == null) {
t = Thread.currentThread().getContextClassLoader();
}
if (t == null) {
throw new IllegalStateException("Cannot determine classloader");
}
return t;
}
abstract protected ClassLoader getDefaultClassLoader();
protected Object create(Object key) {
try {
Object instance = null;
synchronized (source) {
ClassLoader loader = getClassLoader();
Map cache2 = null;
cache2 = (Map)source.cache.get(loader);
if (cache2 == null) {
cache2 = new HashMap();
cache2.put(NAME_KEY, new HashSet());
source.cache.put(loader, cache2);
} else if (useCache) {
Reference ref = (Reference)cache2.get(key);
instance = ( ref == null ) ? null : ref.get();
}
if (instance == null) {
Object save = CURRENT.get();
CURRENT.set(this);
try {
this.key = key;
Class gen = null;
if (attemptLoad) {
try {
gen = loader.loadClass(getClassName());
} catch (ClassNotFoundException e) {
// ignore
}
}
if (gen == null) {
byte[] b = strategy.generate(this);
String className = ClassNameReader.getClassName(new ClassReader(b));
getClassNameCache(loader).add(className);
gen = ReflectUtils.defineClass(className, b, loader);
}
instance = firstInstance(gen);
if (useCache) {
cache2.put(key, new SoftReference(instance));
}
return instance;
} finally {
CURRENT.set(save);
}
}
}
return nextInstance(instance);
} catch (RuntimeException e) {
throw e;
} catch (Error e) {
throw e;
} catch (Exception e) {
throw new CodeGenerationException(e);
}
}
abstract protected Object firstInstance(Class type) throws Exception;
abstract protected Object nextInstance(Object instance) throws Exception;
}
|
package com.celci2015;
import com.celci2015.math.MathExpression;
public abstract class UserInterface {
public static final String OPERATION = "\\ ([+*-]|[e])\\ ";
//Pattern this form : # # # | # # # | .... operation # # # | # # # .... where operation can be *,+,- or e.
public static final String expressionPattern = "(-\\d+|\\d+)\\ (-\\d+|\\d+)\\ (-\\d+|\\d+)(\\ \\|\\ (-\\d+|\\d+)\\ (-\\d+|\\d+)\\ (-\\d+|\\d+))*\\ (([+*-]\\ (-\\d+|\\d+)\\ (-\\d+|\\d+)\\ (-\\d+|\\d+)(\\ \\|\\ (-\\d+|\\d+)\\ (-\\d+|\\d+)\\ (-\\d+|\\d+))*)|([e]\\ (-\\d+|\\d+)\\ (-\\d+|\\d+)))";
public static final String BAD_INPUT = "Bad input!";
public abstract void display(String result);
public void query(String queryString)
{
if (!queryString.matches(expressionPattern)) {// Verify expression
if (queryString.matches(Processor.expressionPattern))// verify is its a single expression
{
display(queryString);
return;
}
display(BAD_INPUT);
return;
}
String[] inputs = queryString.split(OPERATION);
MathExpression expression;
try{
//First we get the operation, then parse a math expression and then execute the other expression
switch (queryString.charAt(inputs[0].length() + 1)) {// get operation
case '*':
expression = new MathExpression(inputs[0]);
expression.times(new MathExpression(inputs[1]));
display(expression.toString());
break;
case '+':
expression = new MathExpression(inputs[0]);
expression.add(new MathExpression(inputs[1]));
display(expression.toString());
break;
case '-':
expression = new MathExpression(inputs[0]);
expression.minus(new MathExpression(inputs[1]));
display(expression.toString());
break;
case 'e':
String[] xy = inputs[1].split(" ");
int x = Integer.parseInt(xy[0]);
int y = Integer.parseInt(xy[1]);
display(new MathExpression(inputs[0]).eval(x,y) +" 0 0");
break;
default:
throw new Exception("Wrong Operation");
}}
catch(Exception e)
{
//e.printStackTrace();
display(BAD_INPUT +" "+ e.getMessage());// Display error messagee
}
}
}
|
package rtdc.web.test;
import org.junit.Assert;
import org.junit.Test;
import rtdc.core.Config;
import rtdc.core.event.*;
import rtdc.core.json.JSONArray;
import rtdc.core.json.JSONObject;
import rtdc.core.json.JSONTokener;
import rtdc.core.model.Unit;
import rtdc.core.model.User;
import javax.annotation.Nullable;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
public class ServiceTest {
private static final String _url = "http://" + Config.SERVER_IP + ":8888/api/";
private static final String USER_AGENT = "Mozilla/5.0";
private static final String TEST_USERNAME = "Nathaniel";
private static final String TEST_PASSWORD = "password";
/*
@Test
public void authenticateUser_existingUser_getUserPlusAuthToken() {
// Action;
JSONObject object = executeSyncRequest("auth/login", "username=Nathaniel&password=password", "POST", null);
// Assert
Assert.assertNotNull(object);
Assert.assertEquals(AuthenticationEvent.TYPE.getName(), object.get("_type").toString());
Assert.assertTrue(object.has("user"));
Assert.assertTrue(object.has("authenticationToken"));
User user = new User((JSONObject) object.get("user"));
Assert.assertEquals("Nathaniel", user.getFirstName());
Assert.assertEquals("Aumonttt", user.getLastName());
}
@Test
public void authenticateUser_badPassword_getNoUser() {
// Action
JSONObject object = executeSyncRequest("auth/login", "username=Nathaniel&password=pssword", "POST", null);
// Assert
Assert.assertNotNull(object);
Assert.assertEquals(ErrorEvent.TYPE.getName(), object.get("_type").toString());
Assert.assertEquals("Username / password mismatch", object.get("description"));
Assert.assertFalse(object.has("user"));
Assert.assertFalse(object.has("authenticationToken"));
}
@Test
public void authenticateUser_badUsername_getNoUser() {
// Action
JSONObject object = executeSyncRequest("auth/login", "username=Nahaniel&password=password", "POST", null);
// Assert
Assert.assertNotNull(object);
Assert.assertEquals(ErrorEvent.TYPE.getName(), object.get("_type").toString());
Assert.assertEquals("Username / password mismatch", object.get("description"));
Assert.assertFalse(object.has("user"));
Assert.assertFalse(object.has("authenticationToken"));
}
@Test
public void authenticateUser_badUsernameBadPassword_getNoUser() {
// Action
JSONObject object = executeSyncRequest("auth/login", "username=Nahaniel&password=pasword", "POST", null);
// Assert
Assert.assertNotNull(object);
Assert.assertEquals(ErrorEvent.TYPE.getName(), object.get("_type").toString());
Assert.assertEquals("Username / password mismatch", object.get("description"));
Assert.assertFalse(object.has("user"));
Assert.assertFalse(object.has("authenticationToken"));
}
@Test
public void authenticateUser_spaceUsernameSpacePassword_getNoUser() {
// Action
JSONObject object = executeSyncRequest("auth/login", "username= &password= ", "POST", null);
// Assert
Assert.assertNotNull(object);
Assert.assertEquals(ErrorEvent.TYPE.getName(), object.get("_type").toString());
Assert.assertEquals("Username / password mismatch", object.get("description"));
Assert.assertFalse(object.has("user"));
Assert.assertFalse(object.has("authenticationToken"));
}
@Test
public void authenticateUser_noUsernameNoPassword_getNoUser() {
// Action
JSONObject object = executeSyncRequest("auth/login", "username=&password=", "POST", null);
// Assert
Assert.assertNotNull(object);
Assert.assertEquals(ErrorEvent.TYPE.getName(), object.get("_type").toString());
Assert.assertEquals("Username cannot be empty", object.get("description"));
Assert.assertFalse(object.has("user"));
Assert.assertFalse(object.has("authenticationToken"));
}
@Test
public void authenticateUser_NoPassword_getNoUser() {
// Action
JSONObject object = executeSyncRequest("auth/login", "username=Nathaniel&password=", "POST", null);
// Assert
Assert.assertNotNull(object);
Assert.assertEquals(ErrorEvent.TYPE.getName(), object.get("_type").toString());
Assert.assertEquals("Password cannot be empty", object.get("description"));
Assert.assertFalse(object.has("user"));
Assert.assertFalse(object.has("authenticationToken"));
}
@Test
public void isAuthTokenValid_validToken_ok() {
// Arrange
String authToken = getAuthToken(TEST_USERNAME, TEST_PASSWORD);
// Action
JSONObject object2 = executeSyncRequest("auth/tokenValid", "", "POST", authToken);
// Assert
Assert.assertEquals(AuthenticationEvent.TYPE.getName(), object2.get("_type").toString());
}
@Test
public void logout_correctBehavior_userLoggedOut() {
// Arrange
String authToken = getAuthToken(TEST_USERNAME, TEST_PASSWORD);
// Action
JSONObject object2 = executeSyncRequest("auth/logout", null, "POST", authToken);
System.out.println(object2);
// Assert
Assert.assertEquals(LogoutEvent.TYPE.getName(), object2.get("_type").toString());
}
@Test
public void logout_noAuthToken_error() {
// Arrange
JSONObject object = executeSyncRequest("auth/login", "username=Nathaniel&password=password", "POST", null);
// Action
JSONObject object2 = executeSyncRequest("auth/logout", null, "POST", "");
// Assert
Assert.assertEquals(ErrorEvent.TYPE.getName(), object2.get("_type").toString());
}
@Test
public void getUnits_correctBehavior_gotAllUnits() {
// Arrange
String authToken = getAuthToken(TEST_USERNAME, TEST_PASSWORD);
// Action
JSONObject object2 = executeSyncRequest("units", null, "GET", authToken);
JSONArray unitsJsonArray = new JSONArray(new JSONTokener(object2.get("units").toString()));
// Assert
Assert.assertEquals(FetchUnitsEvent.TYPE.getName(), object2.get("_type"));
Assert.assertEquals(unitsJsonArray.length() > 0, true);
}
@Test
public void getUnits_noAuthToken_error() {
// Arrange
// Action
JSONObject object2 = executeSyncRequest("units", null, "GET", "");
// Assert
Assert.assertEquals(ErrorEvent.TYPE.getName(), object2.get("_type"));
// TODO: Check for correct description, but need to put string in resources file before
}
@Test
public void updateOrSaveUnit_newUnit_unitSaved() {
// Arrange
String authToken = getAuthToken(TEST_USERNAME, TEST_PASSWORD);
Unit testUnit = new Unit();
testUnit.setName("Test Unit " + (int) (Math.random() * 100));
testUnit.setAvailableBeds(20);
// Action
JSONObject object2 = executeSyncRequest("units", "unit=" + testUnit.toString(), "PUT", authToken);
Unit savedUnit = getSingleUnit(authToken, (int) object2.get("objectId"));
// Assert
Assert.assertEquals(ActionCompleteEvent.TYPE.getName(), object2.get("_type"));
Assert.assertTrue(object2.get("objectId") != null);
Assert.assertEquals(object2.get("action"), "update");
Assert.assertEquals(object2.get("objectType"), "unit");
Assert.assertEquals(savedUnit.getName(), testUnit.getName());
Assert.assertEquals(savedUnit.getAvailableBeds(), testUnit.getAvailableBeds());
}
@Test
public void updateOrSaveUnit_updateUnit_unitUpdated() {
// Arrange
String authToken = getAuthToken(TEST_USERNAME, TEST_PASSWORD);
JSONObject object2 = executeSyncRequest("units", null, "GET", authToken);
JSONArray unitJsonArray = new JSONArray(new JSONTokener(object2.get("units").toString()));
// Get units from object2
// Action
Unit unit = new Unit(new JSONObject(unitJsonArray.get(0).toString()));
unit.setName("Modified name");
JSONObject result = executeSyncRequest("units", "unit=" + unit.toString(), "PUT", authToken);
Unit savedUnit = getSingleUnit(authToken, unit.getId());
// Assert
Assert.assertEquals(ActionCompleteEvent.TYPE.getName(), result.get("_type"));
Assert.assertEquals(result.get("objectId"), unit.getId());
Assert.assertEquals(result.get("action"), "update");
Assert.assertEquals(result.get("objectType"), "unit");
Assert.assertEquals(savedUnit.getName(), unit.getName());
Assert.assertEquals(savedUnit.getAvailableBeds(), unit.getAvailableBeds());
}
@Test
public void updateOrSaveUnit_noAuthToken_error() {
// Arrange
Unit testUnit = new Unit();
testUnit.setName("Test Unit " + (int) (Math.random() * 100));
testUnit.setAvailableBeds(20);
// Action
JSONObject object2 = executeSyncRequest("units", "unit=" + testUnit.toString(), "PUT", null);
// Assert
Assert.assertEquals(ErrorEvent.TYPE.getName(), object2.get("_type"));
// TODO: Check for correct description, but need to put string in resources file before
}
@Test
public void deleteUnit_unitExists_unitDeleted() {
// Arrange
String authToken = getAuthToken(TEST_USERNAME, TEST_PASSWORD);
// Action
int unitId = 2;
JSONObject result = executeSyncRequest("units/" + unitId, null, "DELETE", authToken);
// Assert
Unit checkUnit = getSingleUnit(authToken, 1);
Assert.assertEquals(ActionCompleteEvent.TYPE.getName(), result.get("_type"));
Assert.assertNull(checkUnit);
// TODO: Check list of units ?
}
@Test
public void deleteUnit_unitNotFound_errorEvent() {
// Arrange
String authToken = getAuthToken(TEST_USERNAME, TEST_PASSWORD);
// Action
int unitId = 99999;
JSONObject result = executeSyncRequest("units/" + unitId, null, "DELETE", authToken);
// Assert
Assert.assertEquals(ErrorEvent.TYPE.getName(), result.get("_type"));
}
@Test
public void deleteUnit_noAuthToken_error() {
// Arrange
// Action
int unitId = 1;
JSONObject result = executeSyncRequest("units/" + unitId, null, "DELETE", "");
// Assert
Assert.assertEquals(ErrorEvent.TYPE.getName(), result.get("_type"));
// TODO: Check for correct description, but need to put string in resources file before
}
@Test
public void getUsers_correctBehavior_gotAllUsers() {
// Arrange
String authToken = getAuthToken(TEST_USERNAME, TEST_PASSWORD);
// Action
JSONObject object2 = executeSyncRequest("users", null, "GET", authToken);
// Assert
Assert.assertEquals(FetchUsersEvent.TYPE.getName(), object2.get("_type"));
}
@Test
public void getUsers_noAuthToken_error() {
// Arrange
// Action
JSONObject object2 = executeSyncRequest("users", null, "GET", null);
// Assert
Assert.assertEquals(ErrorEvent.TYPE.getName(), object2.get("_type"));
}
@Test
public void getUser_correctBehavior_getUser() {
// Arrange
String authToken = getAuthToken(TEST_USERNAME, TEST_PASSWORD);
// Action
JSONObject userJson = executeSyncRequest("users/" + TEST_USERNAME, null, "GET", authToken);
// Assert
Assert.assertEquals(FetchUserEvent.TYPE.getName(), userJson.get("_type"));
User user = new User(new JSONObject(userJson.get("user").toString()));
Assert.assertEquals(user.getUsername(), TEST_USERNAME);
}
@Test
public void getUser_userNotFound_error() {
// Arrange
String authToken = getAuthToken(TEST_USERNAME, TEST_PASSWORD);
// Action
JSONObject userJson = executeSyncRequest("users/" + "notauser", null, "GET", authToken);
// Assert
Assert.assertEquals(ErrorEvent.TYPE.getName(), userJson.get("_type"));
}
@Test
public void getUser_noAuthToken_error() {
// Arrange
// Action
JSONObject userJson = executeSyncRequest("users/" + TEST_USERNAME, null, "GET", "");
// Assert
Assert.assertEquals(ErrorEvent.TYPE.getName(), userJson.get("_type"));
}
// TODO: User is not added in DB
@Test
public void updateOrSaveUser_newUser_userSaved() {
// Arrange
String authToken = getAuthToken(TEST_USERNAME, TEST_PASSWORD);
User testUser = new User();
testUser.setUsername("test" + (int)(Math.random() * 100));
testUser.setFirstName("Test1232");
testUser.setLastName("Test2");
// Action
JSONObject object2 = executeSyncRequest("users", "password=password&user=" + testUser.toString(), "POST", authToken);
// Parse and get list of units
// Assert
Assert.assertEquals(ActionCompleteEvent.TYPE.getName(), object2.get("_type"));
JSONObject savedUserJson = executeSyncRequest("users/" + testUser.getUsername(), null, "GET", authToken);
Assert.assertEquals(FetchUserEvent.TYPE.getName(), savedUserJson.get("_type"));
}
@Test
public void updateOrSaveUser_updateUser_userUpdated() {
// Arrange
String authToken = getAuthToken(TEST_USERNAME, TEST_PASSWORD);
JSONObject object2 = executeSyncRequest("users", null, "GET", authToken);
JSONArray userJsonArray = new JSONArray(new JSONTokener(object2.get("users").toString()));
// Action
User user = new User(new JSONObject(userJsonArray.get(0).toString()));
user.setFirstName("Modified name");
JSONObject result = executeSyncRequest("users", user.toString(), "PUT", authToken);
// Assert
Assert.assertEquals(ActionCompleteEvent.TYPE.getName(), result.get("_type"));
// TODO: Verify if user is saved correctly?
}
@Test
public void updateOrSaveUser_noAuthToken_error() {
// Arrange
User testUser = new User();
testUser.setFirstName("Test 123");
testUser.setLastName("Test");
// Action
JSONObject result = executeSyncRequest("users", testUser.toString(), "PUT", null);
// Assert
Assert.assertEquals(ErrorEvent.TYPE.getName(), result.get("_type"));
}
@Test
public void deleteUser_userExists_userDeleted() {
// Arrange
String authToken = getAuthToken(TEST_USERNAME, TEST_PASSWORD);
// Action
int userId = 1;
JSONObject result = executeSyncRequest("users/" + userId, null, "DELETE", authToken);
// Assert
Assert.assertEquals(ActionCompleteEvent.TYPE.getName(), result.get("_type"));
// TODO: Check list of units ?
}
@Test
public void deleteUser_userNotFound_errorMessage() {
// Arrange
String authToken = getAuthToken(TEST_USERNAME, TEST_PASSWORD);
// Action
int userId = 99999;
JSONObject result = executeSyncRequest("users/" + userId, null, "DELETE", authToken);
// Assert
Assert.assertEquals(ErrorEvent.TYPE.getName(), result.get("_type"));
}
@Test
public void deleteUser_noAuthToken_error() {
// Arrange
// Action
int userId = 1;
JSONObject result = executeSyncRequest("users/" + userId, null, "DELETE", "");
// Assert
Assert.assertEquals(ErrorEvent.TYPE.getName(), result.get("_type"));
}
*/
private static JSONObject executeSyncRequest(String service, String urlParameters, String requestMethod, @Nullable String authToken) {
try {
URL urlObj = new URL(_url + service);
HttpURLConnection con = (HttpURLConnection) urlObj.openConnection();
con.setRequestMethod(requestMethod);
con.setRequestProperty("User-Agent", USER_AGENT);
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
con.setRequestProperty("Accept-Language", "en-us,en;q=0.5");
if (authToken != null)
con.setRequestProperty("auth_token", authToken);
con.setDoOutput(true);
if (urlParameters != null) {
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
}
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
JSONObject object = new JSONObject(response.toString());
return object;
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
// TODO: ErrorEvent: {"_type":"errorEvent","description":"could not initialize proxy - no Session"}
// Does not happen when debugging the server and stepping through the getUnit method in UnitServlet ??
private static Unit getSingleUnit(String authToken, int id) {
JSONObject unitJson = (executeSyncRequest("units/" + id, null, "GET", authToken));
if (unitJson.get("_type") == ErrorEvent.TYPE.getName()) {
return null;
}
JSONArray unitJsonArray = new JSONArray(new JSONTokener(unitJson.get("units").toString()));
Unit unit = new Unit(unitJsonArray.getJSONObject(0));
return unit;
}
private String getAuthToken(String username, String password) {
JSONObject object = executeSyncRequest("auth/login", "username=" + username + "&password=" + password, "POST", null);
return object.get("authenticationToken").toString();
}
}
|
package at.dhyan.open_imaging.test;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class TestImage {
public Path path;
public int width;
public int height;
public int frames;
public byte[] data;
public ByteArrayInputStream stream;
public TestImage(final String name, final int width, final int height,
final int frames) throws IOException {
path = Paths.get(GifDecoderTest.IN_FOLDER, name + ".gif");
this.width = width;
this.height = height;
this.frames = frames;
data = Files.readAllBytes(path);
stream = new ByteArrayInputStream(data);
stream.reset();
}
}
|
package ch.eitchnet.xmlpers.test;
import static ch.eitchnet.xmlpers.test.impl.TestConstants.TYPE_RES;
import static ch.eitchnet.xmlpers.test.model.ModelBuilder.RES_TYPE;
import static ch.eitchnet.xmlpers.test.model.ModelBuilder.createResource;
import static ch.eitchnet.xmlpers.test.model.ModelBuilder.updateResource;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import ch.eitchnet.xmlpers.api.IoMode;
import ch.eitchnet.xmlpers.api.PersistenceConstants;
import ch.eitchnet.xmlpers.api.PersistenceTransaction;
import ch.eitchnet.xmlpers.objref.IdOfSubTypeRef;
import ch.eitchnet.xmlpers.objref.LockableObject;
import ch.eitchnet.xmlpers.test.model.Resource;
/**
* @author Robert von Burg <eitch@eitchnet.ch>
*
*/
public class LockingTest extends AbstractPersistenceTest {
private static final String BASE_PATH = "target/db/LockingTest/"; //$NON-NLS-1$
private long waitForWorkersTime;
private boolean run;
@BeforeClass
public static void beforeClass() {
cleanPath(BASE_PATH);
}
@Before
public void before() {
Properties properties = new Properties();
properties.setProperty(PersistenceConstants.PROP_BASEPATH, BASE_PATH + IoMode.DOM.name());
properties.setProperty(PersistenceConstants.PROP_LOCK_TIME_MILLIS, Long.toString(500L));
setup(properties);
this.waitForWorkersTime = LockableObject.getLockTime() + this.getWaitForWorkersTime() + 300L;
}
@Test
public void shouldLockObjects() throws InterruptedException {
List<CreateResourceWorker> workers = new ArrayList<>(5);
String resoureId = "worker"; //$NON-NLS-1$
for (int i = 0; i < 5; i++) {
String workerName = resoureId + "_" + i; //$NON-NLS-1$
CreateResourceWorker worker = new CreateResourceWorker(workerName, workerName);
worker.start();
workers.add(worker);
logger.info("Setup thread " + worker.getName()); //$NON-NLS-1$
}
int nrOfSuccess = runWorkers(workers);
assertEquals("Only one thread should be able to perform the TX!", 5, nrOfSuccess); //$NON-NLS-1$
}
@Test
public void shouldFailIfResourceAlreadyExists() throws InterruptedException {
List<CreateResourceWorker> workers = new ArrayList<>(5);
String resourceId = "createWorkerRes"; //$NON-NLS-1$
for (int i = 0; i < 5; i++) {
String workerName = resourceId + "_" + i;
CreateResourceWorker worker = new CreateResourceWorker(workerName, resourceId);
worker.start();
workers.add(worker);
logger.info("Setup thread " + worker.getName()); //$NON-NLS-1$
}
int nrOfSuccess = runWorkers(workers);
assertEquals("Only one thread should be able to perform the TX!", 1, nrOfSuccess); //$NON-NLS-1$
}
@Test
public void shouldFailUpdateIfLockNotAcquirable() throws InterruptedException {
// prepare workers
List<UpdateResourceWorker> workers = new ArrayList<>(5);
String resourceId = "updatWorkerRes"; //$NON-NLS-1$
for (int i = 0; i < 5; i++) {
String workerName = resourceId + "_" + i; //$NON-NLS-1$
UpdateResourceWorker worker = new UpdateResourceWorker(workerName, resourceId);
worker.start();
workers.add(worker);
logger.info("Setup thread " + worker.getName()); //$NON-NLS-1$
}
// create resource which is to be updated
try (PersistenceTransaction tx = this.persistenceManager.openTx()) {
Resource resource = createResource(resourceId);
tx.getObjectDao().add(resource);
}
int nrOfSuccess = runWorkers(workers);
assertEquals("Only one thread should be able to perform the TX!", 1, nrOfSuccess); //$NON-NLS-1$
}
private int runWorkers(List<? extends AbstractWorker> workers) throws InterruptedException {
this.setRun(true);
for (AbstractWorker worker : workers) {
worker.join(this.getWaitForWorkersTime() + 2000L);
}
int nrOfSuccess = 0;
for (AbstractWorker worker : workers) {
if (worker.isSuccess())
nrOfSuccess++;
}
return nrOfSuccess;
}
public long getWaitForWorkersTime() {
return this.waitForWorkersTime;
}
public boolean isRun() {
return this.run;
}
public void setRun(boolean run) {
this.run = run;
}
public abstract class AbstractWorker extends Thread {
protected boolean success;
protected String resourceId;
public AbstractWorker(String name, String resourceId) {
super(name);
this.resourceId = resourceId;
}
public void run() {
logger.info("Waiting for ok to work..."); //$NON-NLS-1$
while (!LockingTest.this.isRun()) {
try {
Thread.sleep(10L);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
logger.info("Starting work..."); //$NON-NLS-1$
try (PersistenceTransaction tx = LockingTest.this.persistenceManager.openTx()) {
doWork(tx);
try {
Thread.sleep(getWaitForWorkersTime());
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
this.success = true;
}
logger.info("Work completed."); //$NON-NLS-1$
}
protected abstract void doWork(PersistenceTransaction tx);
public boolean isSuccess() {
return this.success;
}
}
public class CreateResourceWorker extends AbstractWorker {
public CreateResourceWorker(String name, String resourceId) {
super(name, resourceId);
}
@Override
protected void doWork(PersistenceTransaction tx) {
Resource resource = createResource(this.resourceId);
tx.getObjectDao().add(resource);
}
}
public class UpdateResourceWorker extends AbstractWorker {
public UpdateResourceWorker(String name, String resourceId) {
super(name, resourceId);
}
@Override
protected void doWork(PersistenceTransaction tx) {
IdOfSubTypeRef objectRef = tx.getObjectRefCache().getIdOfSubTypeRef(TYPE_RES, RES_TYPE, this.resourceId);
Resource resource = tx.getObjectDao().queryById(objectRef);
assertNotNull(resource);
updateResource(resource);
tx.getObjectDao().update(resource);
}
}
}
|
package com.uwetrottmann.trakt5;
import com.uwetrottmann.trakt5.entities.BaseEpisode;
import com.uwetrottmann.trakt5.entities.BaseMovie;
import com.uwetrottmann.trakt5.entities.BaseRatedEntity;
import com.uwetrottmann.trakt5.entities.BaseSeason;
import com.uwetrottmann.trakt5.entities.BaseShow;
import com.uwetrottmann.trakt5.entities.CastMember;
import com.uwetrottmann.trakt5.entities.Credits;
import com.uwetrottmann.trakt5.entities.CrewMember;
import com.uwetrottmann.trakt5.entities.Ratings;
import com.uwetrottmann.trakt5.entities.Stats;
import com.uwetrottmann.trakt5.enums.Type;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import org.junit.BeforeClass;
import retrofit2.Call;
import retrofit2.Response;
import java.io.IOException;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
public class BaseTestCase {
protected static final String TEST_CLIENT_ID = "35a671df22d3d98b09aab1c0bc52977e902e696a7704cab94f4d12c2672041e4";
public static final String TEST_ACCESS_TOKEN = "50b98abe67c5ffd4a533c42f479c6503e8b00a896ce9d0a1ba2d2eb86467066b"; // "sgtest" on production
private static final boolean DEBUG = true;
private static final TraktV2 trakt = new TestTraktV2(TEST_CLIENT_ID);
protected static final Integer DEFAULT_PAGE_SIZE = 10;
static class TestTraktV2 extends TraktV2 {
public TestTraktV2(String apiKey) {
super(apiKey);
}
public TestTraktV2(String apiKey, String clientSecret, String redirectUri) {
super(apiKey, clientSecret, redirectUri);
}
@Override
protected void setOkHttpClientDefaults(OkHttpClient.Builder builder) {
super.setOkHttpClientDefaults(builder);
if (DEBUG) {
// add logging
HttpLoggingInterceptor logging = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
@Override
public void log(String s) {
// standard output is easier to read
System.out.println(s);
}
});
logging.setLevel(HttpLoggingInterceptor.Level.BODY);
builder.addInterceptor(logging);
}
}
}
@BeforeClass
public static void setUpOnce() {
trakt.accessToken(TEST_ACCESS_TOKEN);
}
protected TraktV2 getTrakt() {
return trakt;
}
public <T> T executeCall(Call<T> call) throws IOException {
Response<T> response = call.execute();
if (response.isSuccessful()) {
return response.body();
} else {
handleFailedResponse(response);
}
return null;
}
public static void assertSuccessfulResponse(Response response) {
if (!response.isSuccessful()) {
handleFailedResponse(response);
}
}
private static void handleFailedResponse(Response response) {
if (response.code() == 401) {
fail("Authorization required, supply a valid OAuth access token: "
+ response.code() + " " + response.message());
} else {
fail("Request failed: " + response.code() + " " + response.message());
}
}
protected static <T extends BaseRatedEntity> void assertRatedEntities(List<T> ratedMovies) {
for (BaseRatedEntity movie : ratedMovies) {
assertThat(movie.rated_at).isNotNull();
assertThat(movie.rating).isNotNull();
}
}
public void assertRatings(Ratings ratings) {
// rating can be null, but we use a show where we can be sure it's rated
assertThat(ratings.rating).isGreaterThanOrEqualTo(0);
assertThat(ratings.votes).isGreaterThanOrEqualTo(0);
assertThat(ratings.distribution).hasSize(10);
}
public void assertStats(Stats stats) {
assertThat(stats.watchers).isGreaterThanOrEqualTo(0);
assertThat(stats.plays).isGreaterThanOrEqualTo(0);
assertThat(stats.collectors).isGreaterThanOrEqualTo(0);
assertThat(stats.comments).isGreaterThanOrEqualTo(0);
assertThat(stats.lists).isGreaterThanOrEqualTo(0);
assertThat(stats.votes).isGreaterThanOrEqualTo(0);
}
public void assertShowStats(Stats stats) {
assertStats(stats);
assertThat(stats.collected_episodes).isGreaterThanOrEqualTo(0);
}
protected static void assertSyncMovies(List<BaseMovie> movies, String type) {
for (BaseMovie movie : movies) {
assertThat(movie.movie).isNotNull();
switch (type) {
case "collection":
assertThat(movie.collected_at).isNotNull();
break;
case "watched":
assertThat(movie.plays).isPositive();
assertThat(movie.last_watched_at).isNotNull();
break;
case "watchlist":
assertThat(movie.listed_at).isNotNull();
break;
}
}
}
protected static void assertSyncShows(List<BaseShow> shows, String type) {
for (BaseShow show : shows) {
assertThat(show.show).isNotNull();
if ("collection".equals(type)) {
assertThat(show.last_collected_at).isNotNull();
} else if ("watched".equals(type)) {
assertThat(show.plays).isPositive();
assertThat(show.last_watched_at).isNotNull();
}
for (BaseSeason season : show.seasons) {
assertThat(season.number).isGreaterThanOrEqualTo(0);
for (BaseEpisode episode : season.episodes) {
assertThat(episode.number).isGreaterThanOrEqualTo(0);
if ("collection".equals(type)) {
assertThat(episode.collected_at).isNotNull();
} else if ("watched".equals(type)) {
assertThat(episode.plays).isPositive();
assertThat(episode.last_watched_at).isNotNull();
}
}
}
}
}
public void assertCast(Credits credits, Type type) {
for (CastMember castMember : credits.cast) {
assertThat(castMember.character).isNotNull();
if (type == Type.SHOW) {
assertThat(castMember.movie).isNull();
assertThat(castMember.show).isNotNull();
assertThat(castMember.person).isNull();
} else if (type == Type.MOVIE) {
assertThat(castMember.movie).isNotNull();
assertThat(castMember.show).isNull();
assertThat(castMember.person).isNull();
} else if (type == Type.PERSON) {
assertThat(castMember.movie).isNull();
assertThat(castMember.show).isNull();
assertThat(castMember.person).isNotNull();
}
}
}
public void assertCrew(Credits credits, Type type) {
if (credits.crew != null) {
assertCrewMembers(credits.crew.production, type);
assertCrewMembers(credits.crew.writing, type);
assertCrewMembers(credits.crew.directing, type);
assertCrewMembers(credits.crew.costumeAndMakeUp, type);
assertCrewMembers(credits.crew.sound, type);
assertCrewMembers(credits.crew.art, type);
assertCrewMembers(credits.crew.camera, type);
}
}
public void assertCrewMembers(List<CrewMember> crew, Type type) {
if (crew == null) {
return;
}
for (CrewMember crewMember : crew) {
assertThat(crewMember.job).isNotNull(); // may be empty, so not checking for now
if (type == Type.SHOW) {
assertThat(crewMember.movie).isNull();
assertThat(crewMember.show).isNotNull();
assertThat(crewMember.person).isNull();
} else if (type == Type.MOVIE) {
assertThat(crewMember.movie).isNotNull();
assertThat(crewMember.show).isNull();
assertThat(crewMember.person).isNull();
} else if (type == Type.PERSON) {
assertThat(crewMember.movie).isNull();
assertThat(crewMember.show).isNull();
assertThat(crewMember.person).isNotNull();
}
}
}
}
|
package es.uniovi.asw.cobertura;
import static org.junit.Assert.*;
import java.sql.Time;
import java.util.Date;
import org.junit.Test;
import es.uniovi.asw.model.Eleccion;
/**
* @author Amir
*
*/
public class EleccionTest {
private Eleccion e;
private Date date1= new Date();
private Time t1 = new Time(0);
private Time t2 = new Time(154651847);
private String nombre = "a";
/**
* Test method for {@link es.uniovi.asw.model.Eleccion#hashCode()}.
*/
@Test
public final void testHashCode() {
e = new Eleccion();
assertEquals(29791, e.hashCode());
e= new Eleccion("a" , null, null, new Time(0), new Time(1));
assertEquals(29888, e.hashCode());
}
/**
* Test method for {@link es.uniovi.asw.model.Eleccion#Eleccion(java.lang.String, java.util.Date, java.util.Date, java.sql.Time, java.sql.Time)}.
*/
@Test
public final void testEleccionStringDateDateTimeTime() {
Date date2= new Date();
e= new Eleccion(nombre , date1, date2, t1, t2);
assertEquals(nombre, e.getNombre());
assertEquals(date2, e.getFechaFin());
assertEquals(date1, e.getFechaInicio());
assertEquals(t2, e.getHoraFin());
assertEquals(t1, e.getHoraInicio());
assertNull(e.getNumeroOpciones());
assertNotNull(e.getOpciones());
assertEquals(0, e.getOpciones().size());
assertNull(e.getVotantes());
}
/**
* Test method for {@link es.uniovi.asw.model.Eleccion#Eleccion(java.lang.String)}.
*/
@Test
public final void testEleccionString() {
e= new Eleccion(nombre);
assertEquals(nombre, e.getNombre());
assertNull(e.getFechaFin());
assertNull(e.getHoraFin());
assertNull(e.getNumeroOpciones());
assertNotNull(e.getOpciones());
assertEquals(0, e.getOpciones().size());
assertNull( e.getVotantes());
}
/**
* Test method for {@link es.uniovi.asw.model.Eleccion#Eleccion()}.
*/
@Test
public final void testEleccion() {
e= new Eleccion();
assertNull(e.getHoraInicio());
assertNull(e.getNombre());
assertNull(e.getHoraInicio());
assertNull(e.getNumeroOpciones());
assertNotNull(e.getOpciones());
assertEquals(0, e.getOpciones().size());
assertNull(e.getVotantes());
}
/**
* Test method for {@link es.uniovi.asw.model.Eleccion#toString()}.
*/
@Test
public final void testToString() {
e= new Eleccion(nombre , null, null, null, null);
String s ="Eleccion [id=null, nombre=a, fechaInicio=null, fechaFin=null, horaInicio=null, horaFin=null, opciones=[]]";
assertEquals(s, e.toString());
}
/**
* Test method for {@link es.uniovi.asw.model.Eleccion#equals(java.lang.Object)}.
*/
@Test
public final void testEqualsObject() {
e= new Eleccion();
Eleccion e1, e2, e3;
Date date2= new Date();
e1= new Eleccion(nombre , date1, date2, t1, t2);
e2= new Eleccion("otroNombre");
e3= new Eleccion(nombre , date1, date2, t1, t2);
assertTrue(e.equals(e));
assertTrue(e1.equals(e3));
assertFalse(e.equals(new Object()));
assertFalse(e.equals("otraClase"));
assertFalse(e.equals(e1));
assertFalse(e1.equals(e));
assertFalse(e1.equals(e2));
assertFalse(e2.equals(e1));
e3.setNombre(null);
assertFalse(e1.equals(e3));
assertFalse(e3.equals(e1));
}
}
|
package eu.lp0.cursus.test.ui;
import java.awt.Window;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import javax.accessibility.Accessible;
import javax.accessibility.AccessibleAction;
import javax.accessibility.AccessibleContext;
import javax.accessibility.AccessibleSelection;
import javax.swing.JLayeredPane;
import javax.swing.JPanel;
import javax.swing.JRootPane;
import javax.swing.JSplitPane;
import javax.swing.JViewport;
import javax.swing.SwingUtilities;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import com.google.common.base.Objects;
import com.google.common.base.Predicate;
import com.google.common.base.Throwables;
import com.google.common.util.concurrent.SimpleTimeLimiter;
import eu.lp0.cursus.app.Main;
import eu.lp0.cursus.db.Database;
import eu.lp0.cursus.db.InvalidDatabaseException;
import eu.lp0.cursus.db.data.RaceEntity;
import eu.lp0.cursus.i18n.Messages;
import eu.lp0.cursus.test.db.AbstractDataTest;
import eu.lp0.cursus.ui.MainWindow;
import eu.lp0.cursus.ui.component.DatabaseWindow;
import eu.lp0.cursus.ui.menu.MainMenu;
import eu.lp0.cursus.ui.util.AccessibleComponents;
import eu.lp0.cursus.util.Background;
public class AbstractUITest extends AbstractDataTest {
private static final int CALL_TIMEOUT = 15000;
protected Main main;
protected Accessible mainWindow;
protected Accessible menuBar;
protected Accessible raceTree;
protected Accessible tabbedPane;
protected SimpleTimeLimiter limit = new SimpleTimeLimiter();
@Before
public void startApplication() throws Exception {
// Start the application
main = new Main(new String[] {}) {
@Override
protected Database createEmptyDatabase() throws InvalidDatabaseException, SQLException {
return AbstractUITest.this.createEmptyDatabase(super.createEmptyDatabase());
}
};
executeWithTimeout(new Runnable() {
@Override
public void run() {
main.setWindow(new MainWindow(main));
}
});
// Open the default database
Assert.assertTrue(executeWithTimeout(new Callable<Boolean>() {
@Override
public Boolean call() throws Exception {
return main.newDatabase();
}
}));
// Obtain the main window, menu bar, race tree and tabbed pane... this is considered accessible?
mainWindow = main.getWindow();
Accessible rootPane = findAccessibleChildByType(mainWindow, JRootPane.class);
Accessible layeredPane = findAccessibleChildByType(rootPane, JLayeredPane.class);
menuBar = findAccessibleChildByType(layeredPane, MainMenu.class);
Accessible contentPane = findAccessibleChildByType(layeredPane, JPanel.class);
Accessible splitPane = findAccessibleChildByType(contentPane, JSplitPane.class);
Accessible leftPane = findAccessibleChildByIndex(splitPane, 0);
Accessible leftViewport = findAccessibleChildByType(leftPane, JViewport.class);
raceTree = findAccessibleChild(leftViewport, AccessibleComponents.RACE_TREE);
tabbedPane = findAccessibleChildByIndex(splitPane, 1);
}
protected Database createEmptyDatabase(Database database) throws InvalidDatabaseException, SQLException {
return database;
}
@After
public void closeApplication() throws Exception {
executeWithTimeout(new Runnable() {
@Override
public void run() {
main.close(true);
if (mainWindow != null) {
((Window)mainWindow).dispose();
}
}
});
}
// @AfterClass
// public static void shutdownExecutor() throws InterruptedException {
// Background.shutdownAndWait(CALL_TIMEOUT, TimeUnit.MILLISECONDS);
public void syncOnEventThread() throws Exception {
runFromEventThread(new Runnable() {
@Override
public void run() {
}
});
}
public void syncOnBackgroundExecutor() throws Exception {
executeWithTimeout(new Runnable() {
@Override
public void run() {
}
});
}
public void syncOnDatabaseRefresh() throws Exception {
// Wait for the initiation of the database refresh to complete
syncOnEventThread();
// Wait for the database refresh to complete
syncOnBackgroundExecutor();
// Wait for the GUI update from the database refresh to complete
syncOnEventThread();
}
public void syncOnDatabaseChange() throws Exception {
// Wait for the change to complete
syncOnBackgroundExecutor();
syncOnDatabaseRefresh();
}
public void executeWithTimeout(Runnable run) throws Exception {
final FutureTask<Void> task = new FutureTask<Void>(run, null);
Background.execute(task);
task.get(CALL_TIMEOUT, TimeUnit.MILLISECONDS);
}
public <V> V executeWithTimeout(Callable<V> call) throws Exception {
final FutureTask<V> task = new FutureTask<V>(call);
Background.execute(task);
return task.get(CALL_TIMEOUT, TimeUnit.MILLISECONDS);
}
public <V> V callFromEventThread(final Callable<V> callable) throws Exception {
final CountDownLatch latch = new CountDownLatch(1);
final AtomicReference<V> value = new AtomicReference<V>();
final AtomicReference<Throwable> error = new AtomicReference<Throwable>();
Assert.assertFalse(SwingUtilities.isEventDispatchThread());
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
try {
value.set(callable.call());
} catch (Throwable t) {
error.set(t);
} finally {
latch.countDown();
}
}
});
latch.await(CALL_TIMEOUT, TimeUnit.MILLISECONDS);
Throwable t = error.get();
if (t != null) {
Throwables.propagate(t);
}
return value.get();
}
public void runFromEventThread(final Runnable runnable) throws Exception {
final CountDownLatch latch = new CountDownLatch(1);
final AtomicReference<Throwable> error = new AtomicReference<Throwable>();
Assert.assertFalse(SwingUtilities.isEventDispatchThread());
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
try {
runnable.run();
} catch (Throwable t) {
error.set(t);
} finally {
latch.countDown();
}
}
});
latch.await(CALL_TIMEOUT, TimeUnit.MILLISECONDS);
Throwable t = error.get();
if (t != null) {
throw new Exception(t);
}
}
public RaceEntity getSelectedRaceEntity() throws Exception {
return callFromEventThread(new Callable<RaceEntity>() {
@Override
public RaceEntity call() throws Exception {
return ((DatabaseWindow)mainWindow).getSelected();
}
});
}
public static String accessibleToString(Accessible accessible) {
AccessibleContext context = accessible.getAccessibleContext();
StringBuilder sb = new StringBuilder();
sb.append(accessible.getClass().getSimpleName());
sb.append(" [").append(context.getAccessibleChildrenCount()).append("]"); //$NON-NLS-1$ //$NON-NLS-2$
String name = context.getAccessibleName();
if (name == null) {
sb.append(" null"); //$NON-NLS-1$
} else {
sb.append(" \"").append(name).append("\""); //$NON-NLS-1$ //$NON-NLS-2$
}
String desc = context.getAccessibleDescription();
if (desc == null) {
sb.append(" (null)"); //$NON-NLS-1$
} else {
sb.append(" (\"").append(desc).append("\")"); //$NON-NLS-1$ //$NON-NLS-2$
}
return sb.toString();
}
private Accessible findAccessibleChildFromEventThread(Accessible parent, String name, Predicate<Accessible> predicate) {
Assert.assertTrue(SwingUtilities.isEventDispatchThread());
AccessibleContext context = parent.getAccessibleContext();
List<Accessible> found = new ArrayList<Accessible>();
log.debug("Accessible " + accessibleToString(parent)); //$NON-NLS-1$
for (int i = 0; i < context.getAccessibleChildrenCount(); i++) {
Accessible child = context.getAccessibleChild(i);
log.debug(" Child " + i + ": " + accessibleToString(child)); //$NON-NLS-1$ //$NON-NLS-2$
if (i != child.getAccessibleContext().getAccessibleIndexInParent()) {
// JTabbedPane components have inconsistent accessibility tree
log.warn(" Inconsistent child to parent index " + child.getAccessibleContext().getAccessibleIndexInParent()); //$NON-NLS-1$
}
if (predicate.apply(child)) {
found.add(child);
}
}
if (found.isEmpty()) {
log.error("Cannot find " + name + " in " + accessibleToString(parent)); //$NON-NLS-1$//$NON-NLS-2$
Assert.fail("Cannot find " + name + " in " + accessibleToString(parent)); //$NON-NLS-1$//$NON-NLS-2$
return null;
} else {
for (int i = 0; i < found.size(); i++) {
log.debug("Found " + i + ": " + accessibleToString(found.get(i))); //$NON-NLS-1$ //$NON-NLS-2$
}
if (found.size() > 1) {
log.error("Found more than one matching child (" + found.size() + ") for " + name); //$NON-NLS-1$ //$NON-NLS-2$
Assert.fail("Found more than one matching child (" + found.size() + ") for " + name); //$NON-NLS-1$ //$NON-NLS-2$
return null;
}
}
return found.get(0);
}
private Accessible findAccessibleChild(final Accessible parent, final String name, final Predicate<Accessible> predicate) throws Exception {
if (SwingUtilities.isEventDispatchThread()) {
return findAccessibleChildFromEventThread(parent, name, predicate);
} else {
return callFromEventThread(new Callable<Accessible>() {
@Override
public Accessible call() throws Exception {
return findAccessibleChildFromEventThread(parent, name, predicate);
}
});
}
}
public Accessible findAccessibleChild(Accessible parent, String key) throws Exception {
return findAccessibleChildByName(parent, Messages.getAccessibleName(key));
}
public Accessible findAccessibleChild(Accessible parent, String key, Object... args) throws Exception {
return findAccessibleChildByName(parent, Messages.getAccessibleName(key, args));
}
public Accessible findAccessibleChildByName(Accessible parent, final String name) throws Exception {
return findAccessibleChild(parent, "\"" + name + "\"", new Predicate<Accessible>() { //$NON-NLS-1$ //$NON-NLS-2$
@Override
public boolean apply(Accessible input) {
return Objects.equal(input.getAccessibleContext().getAccessibleName(), name);
}
});
}
public Accessible findAccessibleChildByIndex(final Accessible parent, final int index) throws Exception {
return findAccessibleChild(parent, String.valueOf(index), new Predicate<Accessible>() {
@Override
public boolean apply(Accessible input) {
if (input.getAccessibleContext().getAccessibleParent().getClass().getName().equals("javax.swing.JTabbedPane$Page")) { //$NON-NLS-1$
AccessibleContext context = parent.getAccessibleContext();
if (index < context.getAccessibleChildrenCount()) {
return input == context.getAccessibleChild(index);
}
return false;
} else {
return Objects.equal(input.getAccessibleContext().getAccessibleIndexInParent(), index);
}
}
});
}
public Accessible findAccessibleChildByType(Accessible parent, final Class<? extends Accessible> type) throws Exception {
return findAccessibleChild(parent, type.getSimpleName(), new Predicate<Accessible>() {
@Override
public boolean apply(Accessible input) {
return type.isAssignableFrom(input.getClass());
}
});
}
public void accessibleSelect(final Accessible child, final boolean select) throws Exception {
callFromEventThread(new Callable<Void>() {
@Override
public Void call() {
Accessible parent = child.getAccessibleContext().getAccessibleParent();
AccessibleSelection selection = parent.getAccessibleContext().getAccessibleSelection();
log.info("Selecting " + accessibleToString(child) //$NON-NLS-1$
+ " in " + accessibleToString(parent)); //$NON-NLS-1$
int index = child.getAccessibleContext().getAccessibleIndexInParent();
boolean selected = selection.isAccessibleChildSelected(index);
log.debug(" Before: " + selected); //$NON-NLS-1$
if (select) {
selection.addAccessibleSelection(index);
} else {
selection.removeAccessibleSelection(index);
}
selected = selection.isAccessibleChildSelected(index);
log.debug(" After: " + selected); //$NON-NLS-1$
Assert.assertEquals(select, selected);
return null;
}
});
}
public boolean accessibleAction(final Accessible accessible, final int index) throws Exception {
return callFromEventThread(new Callable<Boolean>() {
@Override
public Boolean call() {
log.debug("Accessible " + accessibleToString(accessible)); //$NON-NLS-1$
AccessibleAction action = accessible.getAccessibleContext().getAccessibleAction();
for (int i = 0; i < action.getAccessibleActionCount(); i++) {
log.debug(" Action " + i + ": \"" + action.getAccessibleActionDescription(i) + "\""); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
}
log.info("Performing " + index + ":" //$NON-NLS-1$ //$NON-NLS-2$
+ " \"" + action.getAccessibleActionDescription(index) + "\"" //$NON-NLS-1$ //$NON-NLS-2$
+ " on " + accessibleToString(accessible)); //$NON-NLS-1$
return action.doAccessibleAction(index);
}
});
}
}
|
package io.vertx.ext.asyncsql;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import io.vertx.test.core.VertxTestBase;
import org.junit.Test;
import java.util.concurrent.CountDownLatch;
public class PostgreSQLTest extends VertxTestBase {
AsyncSQLClient asyncSqlClient;
final String address = "campudus.postgresql";
final JsonObject config = new JsonObject()
.put("host", System.getProperty("db.host", "localhost"))
.put("postgresql", new JsonObject().put("address", address));
@Override
public void setUp() throws Exception {
super.setUp();
asyncSqlClient = PostgreSQLClient.createNonShared(vertx, config);
}
@Override
public void tearDown() throws Exception {
CountDownLatch latch;
if (this.asyncSqlClient != null) {
latch = new CountDownLatch(1);
this.asyncSqlClient.close((ar) -> {
latch.countDown();
});
this.awaitLatch(latch);
}
super.tearDown();
}
@Test
public void someTest() throws Exception {
asyncSqlClient.getConnection(onSuccess(conn -> {
conn.query("SELECT 1 AS something", onSuccess(resultSet -> {
System.out.println(resultSet.getResults());
assertNotNull(resultSet);
assertNotNull(resultSet.getColumnNames());
assertNotNull(resultSet.getResults());
assertEquals(new JsonArray().add(1), resultSet.getResults().get(0));
conn.close((ar) -> {
if (ar.succeeded()) {
testComplete();
} else {
fail("should be able to close the asyncSqlClient");
}
});
}));
}));
await();
}
@Test
public void queryTypeTimestampWithTimezoneTest() throws Exception {
asyncSqlClient.getConnection(onSuccess(conn -> {
conn.execute("CREATE TABLE IF NOT EXISTS timestamptest (ts timestamp with time zone)", onSuccess(resultSet -> {
conn.execute("INSERT INTO timestamptest (ts) VALUES (now())", onSuccess(rs1 -> {
conn.query("SELECT * FROM timestamptest;", onSuccess(rs2 -> {
assertNotNull(rs2);
assertNotNull(rs2.getResults());
conn.close((ar) -> {
if (ar.succeeded()) {
testComplete();
} else {
fail("should be able to close the asyncSqlClient");
}
});
}));
}));
}));
}));
await();
}
@Test
public void queryTypeTimestampWithoutTimezoneTest() throws Exception {
asyncSqlClient.getConnection(onSuccess(conn -> {
conn.execute("CREATE TABLE IF NOT EXISTS timestamptest (ts timestamp without time zone)", onSuccess(resultSet -> {
conn.execute("INSERT INTO timestamptest (ts) VALUES (now())", onSuccess(rs1 -> {
conn.query("SELECT * FROM timestamptest;", onSuccess(rs2 -> {
assertNotNull(rs2);
assertNotNull(rs2.getResults());
conn.close((ar) -> {
if (ar.succeeded()) {
testComplete();
} else {
fail("should be able to close the asyncSqlClient");
}
});
}));
}));
}));
}));
await();
}
}
|
package org.jboss.threads;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import junit.framework.TestCase;
public final class ThreadPoolTestCase extends TestCase {
private final JBossThreadFactory threadFactory = new JBossThreadFactory(null, null, null, "test thread %p %t", null, null);
private static final class SimpleTask implements Runnable {
private final CountDownLatch taskUnfreezer;
private final CountDownLatch taskFinishLine;
private SimpleTask(final CountDownLatch taskUnfreezer, final CountDownLatch taskFinishLine) {
this.taskUnfreezer = taskUnfreezer;
this.taskFinishLine = taskFinishLine;
}
public void run() {
try {
assertTrue(taskUnfreezer.await(800L, TimeUnit.MILLISECONDS));
} catch (InterruptedException e) {
fail("interrupted");
}
taskFinishLine.countDown();
}
}
public void testBasic() throws InterruptedException {
// Start some tasks, let them run, then shut down the executor
final int cnt = 100;
final CountDownLatch taskUnfreezer = new CountDownLatch(1);
final CountDownLatch taskFinishLine = new CountDownLatch(cnt);
final ExecutorService simpleQueueExecutor = new QueueExecutor(5, 5, 500L, TimeUnit.MILLISECONDS, 1000, threadFactory, true, null);
for (int i = 0; i < cnt; i ++) {
simpleQueueExecutor.execute(new SimpleTask(taskUnfreezer, taskFinishLine));
}
taskUnfreezer.countDown();
final boolean finished = taskFinishLine.await(800L, TimeUnit.MILLISECONDS);
assertTrue(finished);
simpleQueueExecutor.shutdown();
try {
simpleQueueExecutor.execute(new Runnable() {
public void run() {
}
});
fail("Task not rejected after shutdown");
} catch (Throwable t) {
assertTrue(t instanceof RejectedExecutionException);
}
assertTrue(simpleQueueExecutor.awaitTermination(800L, TimeUnit.MILLISECONDS));
}
public void testShutdownNow() throws InterruptedException {
final AtomicBoolean interrupted = new AtomicBoolean();
final AtomicBoolean ran = new AtomicBoolean();
final CountDownLatch startLatch = new CountDownLatch(1);
final CountDownLatch finLatch = new CountDownLatch(1);
final ExecutorService simpleQueueExecutor = new QueueExecutor(5, 5, 500L, TimeUnit.MILLISECONDS, 1000, threadFactory, true, null);
simpleQueueExecutor.execute(new Runnable() {
public void run() {
try {
ran.set(true);
startLatch.countDown();
Thread.sleep(5000L);
} catch (InterruptedException e) {
interrupted.set(true);
} finally {
finLatch.countDown();
}
}
});
assertTrue("Task not started", startLatch.await(300L, TimeUnit.MILLISECONDS));
assertTrue("Task returned", simpleQueueExecutor.shutdownNow().isEmpty());
try {
simpleQueueExecutor.execute(new Runnable() {
public void run() {
}
});
fail("Task not rejected after shutdown");
} catch (RejectedExecutionException t) {
}
assertTrue("Task not finished", finLatch.await(300L, TimeUnit.MILLISECONDS));
assertTrue("Executor not shut down in 800ms", simpleQueueExecutor.awaitTermination(800L, TimeUnit.MILLISECONDS));
assertTrue("Task wasn't run", ran.get());
assertTrue("Worker wasn't interrupted", interrupted.get());
}
private static class Holder<T> {
private T instance;
public Holder(T instance) {
this.instance = instance;
}
public T get() { return instance; }
public void set(T instance) {this.instance = instance;}
}
public void testBlocking() throws InterruptedException {
final int queueSize = 20;
final int coreThreads = 5;
final int extraThreads = 5;
final int cnt = queueSize + coreThreads + extraThreads;
final CountDownLatch taskUnfreezer = new CountDownLatch(1);
final CountDownLatch taskFinishLine = new CountDownLatch(cnt);
final ExecutorService simpleQueueExecutor = new QueueExecutor(coreThreads, coreThreads + extraThreads, 500L, TimeUnit.MILLISECONDS, new ArrayQueue<Runnable>(queueSize), threadFactory, true, null);
for (int i = 0; i < cnt; i ++) {
simpleQueueExecutor.execute(new SimpleTask(taskUnfreezer, taskFinishLine));
}
Thread.currentThread().interrupt();
try {
simpleQueueExecutor.execute(new Runnable() {
public void run() {
}
});
fail("Task was accepted");
} catch (RejectedExecutionException t) {
}
Thread.interrupted();
final CountDownLatch latch = new CountDownLatch(1);
final Thread otherThread = threadFactory.newThread(new Runnable() {
public void run() {
simpleQueueExecutor.execute(new Runnable() {
public void run() {
latch.countDown();
}
});
}
});
otherThread.start();
assertFalse("Task executed without wait", latch.await(100L, TimeUnit.MILLISECONDS));
// safe to say the other thread is blocking...?
taskUnfreezer.countDown();
assertTrue("Task never ran", latch.await(800L, TimeUnit.MILLISECONDS));
otherThread.join(500L);
assertTrue("Simple Tasks never ran", taskFinishLine.await(800L, TimeUnit.MILLISECONDS));
simpleQueueExecutor.shutdown();
final Holder<Boolean> callback = new Holder<Boolean>(false);
final CountDownLatch shutdownLatch = new CountDownLatch(1);
((QueueExecutor)simpleQueueExecutor).addShutdownListener(new EventListener<Object>() {
@Override
public void handleEvent(Object attachment) {
callback.set(true);
shutdownLatch.countDown();
} } , null);
shutdownLatch.await(100L, TimeUnit.MILLISECONDS);
assertTrue("Calback not called", callback.get());
assertTrue("Executor not shut down in 800ms", simpleQueueExecutor.awaitTermination(800L, TimeUnit.MILLISECONDS));
}
public void testBlockingEmpty() throws InterruptedException {
final int queueSize = 20;
final int coreThreads = 5;
final int extraThreads = 5;
final int cnt = queueSize + coreThreads + extraThreads;
final ExecutorService simpleQueueExecutor = new QueueExecutor(coreThreads, coreThreads + extraThreads, 500L, TimeUnit.MILLISECONDS, new ArrayQueue<Runnable>(queueSize), threadFactory, true, null);
simpleQueueExecutor.shutdown();
final Holder<Boolean> callback = new Holder<Boolean>(false);
((QueueExecutor)simpleQueueExecutor).addShutdownListener(new EventListener<Object>() {
@Override
public void handleEvent(Object attachment) {
callback.set(true);
} } , null);
assertTrue("Calback not called", callback.get());
assertTrue("Executor not shut down in 800ms", simpleQueueExecutor.awaitTermination(800L, TimeUnit.MILLISECONDS));
Thread.interrupted();
}
public void testQueuelessEmpty() throws InterruptedException {
final int queueSize = 20;
final int coreThreads = 5;
final int extraThreads = 5;
final int cnt = queueSize + coreThreads + extraThreads;
final ExecutorService simpleQueueExecutor = new QueuelessExecutor(threadFactory, SimpleDirectExecutor.INSTANCE, null, 500L);
simpleQueueExecutor.shutdown();
final Holder<Boolean> callback = new Holder<Boolean>(false);
((QueuelessExecutor)simpleQueueExecutor).addShutdownListener(new EventListener<Object>() {
@Override
public void handleEvent(Object attachment) {
callback.set(true);
} } , null);
assertTrue("Calback not called", callback.get());
assertTrue("Executor not shut down in 800ms", simpleQueueExecutor.awaitTermination(800L, TimeUnit.MILLISECONDS));
Thread.interrupted();
}
}
|
package org.littleshoot.proxy;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.littleshoot.proxy.ProxyUtils.parseHost;
import static org.littleshoot.proxy.ProxyUtils.parseHostAndPort;
/**
* Test for proxy utilities.
*/
public class ProxyUtilsTest {
@Test
public void testParseHost() throws Exception {
assertEquals("www.test.com", parseHost("http:
assertEquals("www.test.com", parseHost("http:
assertEquals("www.test.com", parseHost("https:
assertEquals("www.test.com", parseHost("www.test.com:80/test"));
assertEquals("www.test.com", parseHost("www.test.com"));
}
@Test
public void testParseHostAndPort() throws Exception {
assertEquals("www.test.com:80", parseHostAndPort("http:
assertEquals("www.test.com:80", parseHostAndPort("https:
assertEquals("www.test.com:80", parseHostAndPort("www.test.com:80/test"));
assertEquals("www.test.com", parseHostAndPort("http:
assertEquals("www.test.com", parseHostAndPort("www.test.com"));
}
}
|
package test.sanitycheck;
import org.testng.Assert;
import org.testng.TestListenerAdapter;
import org.testng.TestNG;
import org.testng.annotations.Test;
import org.testng.xml.Parser;
import org.testng.xml.XmlClass;
import org.testng.xml.XmlSuite;
import org.testng.xml.XmlTest;
import org.xml.sax.SAXException;
import test.SimpleBaseTest;
import java.io.IOException;
import java.util.Arrays;
import javax.xml.parsers.ParserConfigurationException;
public class CheckSuiteNamesTest extends SimpleBaseTest {
/**
* Child suites have different names
*/
@Test
public void checkChildSuites() {
TestListenerAdapter tla = new TestListenerAdapter();
TestNG tng = create();
String testngXmlPath = getPathToResource("sanitycheck/test-s-b.xml");
tng.setTestSuites(Arrays.asList(testngXmlPath));
tng.addListener(tla);
tng.run();
Assert.assertEquals(tla.getPassedTests().size(), 4);
}
/**
* Child suites have same names
*/
@Test
public void checkChildSuitesFails() {
TestListenerAdapter tla = new TestListenerAdapter();
TestNG tng = create();
String testngXmlPath = getPathToResource("sanitycheck/test-s-a.xml");
tng.setTestSuites(Arrays.asList(testngXmlPath));
tng.addListener(tla);
tng.run();
Assert.assertEquals(tla.getTestContexts().get(0).getSuite().getName(), "SanityCheck suites");
Assert.assertEquals(tla.getTestContexts().get(1).getSuite().getName(), "SanityCheck suites");
Assert.assertEquals(tla.getTestContexts().get(2).getSuite().getName(), "SanityCheck suites (0)");
Assert.assertEquals(tla.getTestContexts().get(3).getSuite().getName(), "SanityCheck suites (0)");
}
/**
* Checks that suites created programmatically also works as expected
*/
@Test
public void checkProgrammaticSuitesFails() {
XmlSuite xmlSuite1 = new XmlSuite();
xmlSuite1.setName("SanityCheckSuite");
{
XmlTest result = new XmlTest(xmlSuite1);
result.getXmlClasses().add(new XmlClass(SampleTest1.class.getCanonicalName()));
}
XmlSuite xmlSuite2 = new XmlSuite();
xmlSuite2.setName("SanityCheckSuite");
{
XmlTest result = new XmlTest(xmlSuite2);
result.getXmlClasses().add(new XmlClass(SampleTest2.class.getCanonicalName()));
}
TestNG tng = create();
tng.setXmlSuites(Arrays.asList(xmlSuite1, xmlSuite2));
tng.run();
Assert.assertEquals(xmlSuite1.getName(), "SanityCheckSuite");
Assert.assertEquals(xmlSuite2.getName(), "SanityCheckSuite (0)");
}
@Test
public void checkXmlSuiteAddition() throws ParserConfigurationException, SAXException, IOException {
TestNG tng = create();
String testngXmlPath = getPathToResource("sanitycheck/test-s-b.xml");
Parser parser = new Parser(testngXmlPath);
tng.setXmlSuites(parser.parseToList());
tng.initializeSuitesAndJarFile();
}
}
|
package co.aikar.taskchain;
import co.aikar.taskchain.TaskChainTasks.AsyncExecutingFirstTask;
import co.aikar.taskchain.TaskChainTasks.AsyncExecutingGenericTask;
import co.aikar.taskchain.TaskChainTasks.AsyncExecutingTask;
import co.aikar.taskchain.TaskChainTasks.FirstTask;
import co.aikar.taskchain.TaskChainTasks.GenericTask;
import co.aikar.taskchain.TaskChainTasks.LastTask;
import co.aikar.taskchain.TaskChainTasks.Task;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.TimeUnit;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
@SuppressWarnings({"unused", "FieldAccessedSynchronizedAndUnsynchronized"})
public class TaskChain <T> {
private static final ThreadLocal<TaskChain<?>> currentChain = new ThreadLocal<>();
private final boolean shared;
private final GameInterface impl;
private final TaskChainFactory factory;
private final String sharedName;
private final Map<String, Object> taskMap = new HashMap<>(0);
private final ConcurrentLinkedQueue<TaskHolder<?,?>> chainQueue = new ConcurrentLinkedQueue<>();
private boolean executed = false;
private boolean async;
private int actionIndex;
private int currentActionIndex;
boolean done = false;
private Object previous;
private TaskHolder<?, ?> currentHolder;
private Consumer<Boolean> doneCallback;
private BiConsumer<Exception, Task<?, ?>> errorHandler;
TaskChain(TaskChainFactory factory) {
this(factory, false, null);
}
TaskChain(TaskChainFactory factory, boolean shared, String sharedName) {
this.factory = factory;
this.impl = factory.getImplementation();
this.shared = shared;
this.sharedName = sharedName;
}
// <editor-fold desc="// Getters & Setters">
/**
* Called in an executing task, get the current action index.
* For every action that adds a task to the chain, the action index is increased.
*
* Useful in error or done handlers to know where you are in the chain when it aborted or threw exception.
* @return The current index
*/
public int getCurrentActionIndex() {
return currentActionIndex;
}
/**
* Changes the done callback handler for this chain
* @param doneCallback
*/
public void setDoneCallback(Consumer<Boolean> doneCallback) {
this.doneCallback = doneCallback;
}
/**
* @return The current error handler or null
*/
public BiConsumer<Exception, Task<?, ?>> getErrorHandler() {
return errorHandler;
}
/**
* Changes the error handler for this chain
* @param errorHandler
*/
public void setErrorHandler(BiConsumer<Exception, Task<?, ?>> errorHandler) {
this.errorHandler = errorHandler;
}
// </editor-fold>
//<editor-fold desc="// API Methods">
/**
* Call to abort execution of the chain. Should be called inside of an executing task.
*/
@SuppressWarnings("WeakerAccess")
public static void abort() {
TaskChainUtil.sneakyThrows(new AbortChainException());
}
/**
* Usable only inside of an executing Task or Chain Error/Done handlers
*
* Gets the current chain that is executing this Task or Error/Done handler
* This method should only be called on the same thread that is executing the method.
*
* In an AsyncExecutingTask, You must call this method BEFORE passing control to another thread.
*/
@SuppressWarnings("WeakerAccess")
public static TaskChain<?> getCurrentChain() {
return currentChain.get();
}
/**
* Checks if the chain has a value saved for the specified key.
* @param key Key to check if Task Data has a value for
*/
@SuppressWarnings("WeakerAccess")
public boolean hasTaskData(String key) {
return taskMap.containsKey(key);
}
/**
* Retrieves a value relating to a specific key, saved by a previous task.
*
* @param key Key to look up Task Data for
* @param <R> Type the Task Data value is expected to be
*/
@SuppressWarnings("WeakerAccess")
public <R> R getTaskData(String key) {
//noinspection unchecked
return (R) taskMap.get(key);
}
/**
* Saves a value for this chain so that a task furthur up the chain can access it.
*
* Useful for passing multiple values to the next (or furthur) tasks.
*
* @param key Key to store in Task Data
* @param val Value to store in Task Data
* @param <R> Type the Task Data value is expected to be
*/
@SuppressWarnings("WeakerAccess")
public <R> R setTaskData(String key, Object val) {
//noinspection unchecked
return (R) taskMap.put(key, val);
}
/**
* Removes a saved value on the chain.
*
* @param key Key to remove from Task Data
* @param <R> Type the Task Data value is expected to be
*/
@SuppressWarnings("WeakerAccess")
public <R> R removeTaskData(String key) {
//noinspection unchecked
return (R) taskMap.remove(key);
}
/**
* Takes the previous tasks return value, stores it to the specified key
* as Task Data, and then forwards that value to the next task.
*
* @param key Key to store the previous return value into Task Data
*/
@SuppressWarnings("WeakerAccess")
public TaskChain<T> storeAsData(String key) {
return current((val) -> {
setTaskData(key, val);
return val;
});
}
/**
* Reads the specified key from Task Data, and passes it to the next task.
*
* Will need to pass expected type such as chain.<Foo>returnData("key")
*
* @param key Key to retrieve from Task Data and pass to next task
* @param <R> Return type that the next parameter can expect as argument type
*/
@SuppressWarnings("WeakerAccess")
public <R> TaskChain<R> returnData(String key) {
//noinspection unchecked
return currentFirst(() -> (R) getTaskData(key));
}
/**
* Returns the chain itself to the next task.
*/
@SuppressWarnings("WeakerAccess")
public TaskChain<TaskChain<?>> returnChain() {
return currentFirst(() -> this);
}
/**
* Checks if the previous task return was null.
*
* If not null, the previous task return will forward to the next task.
*/
@SuppressWarnings("WeakerAccess")
public TaskChain<T> abortIfNull() {
return current((obj) -> {
if (obj == null) {
abort();
return null;
}
return obj;
});
}
/**
* {@link #abortIfNull(TaskChainNullAction, Object, Object, Object)}
*/
@SuppressWarnings("WeakerAccess")
public <A1> TaskChain<T> abortIfNull(TaskChainNullAction<A1, ?, ?> action, A1 arg1) {
return abortIfNull(action, arg1, null, null);
}
/**
* {@link #abortIfNull(TaskChainNullAction, Object, Object, Object)}
*/
@SuppressWarnings("WeakerAccess")
public <A1, A2> TaskChain<T> abortIfNull(TaskChainNullAction<A1, A2, ?> action, A1 arg1, A2 arg2) {
return abortIfNull(action, arg1, arg2, null);
}
/**
* Checks if the previous task return was null, and aborts if it was, optionally
* sending a message to the player.
*
* If not null, the previous task return will forward to the next task.
*/
@SuppressWarnings("WeakerAccess")
public <A1, A2, A3> TaskChain<T> abortIfNull(TaskChainNullAction<A1, A2, A3> action, A1 arg1, A2 arg2, A3 arg3) {
return current((obj) -> {
if (obj == null) {
if (action != null) {
final TaskChain<?> prev = currentChain.get();
try {
currentChain.set(this);
action.onNull(this, arg1, arg2, arg3);
} catch (Exception e) {
TaskChainUtil.logError("TaskChain Exception in Null Action handler: " + action.getClass().getName());
e.printStackTrace();
} finally {
currentChain.set(prev);
}
}
abort();
return null;
}
return obj;
});
}
/**
* IMPLEMENTATION SPECIFIC!!
* Consult your application implementation to understand how long 1 unit is.
*
* For example, in Minecraft it is a tick, which is roughly 50 milliseconds, but not guaranteed.
*
* Adds a delay to the chain execution.
*
* @param gameUnits # of game units to delay before next task
*/
@SuppressWarnings("WeakerAccess")
public TaskChain<T> delay(final int gameUnits) {
//noinspection CodeBlock2Expr
return currentCallback((input, next) -> {
impl.scheduleTask(gameUnits, () -> next.accept(input));
});
}
/**
* Adds a real time delay to the chain execution.
* Chain will abort if the delay is interrupted.
*
* @param duration duration of the delay before next task
*/
@SuppressWarnings("WeakerAccess")
public TaskChain<T> delay(final int duration, TimeUnit unit) {
//noinspection CodeBlock2Expr
return currentCallback((input, next) -> {
impl.scheduleTask(duration, unit, () -> next.accept(input));
});
}
/**
* Execute a task on the main thread, with no previous input, and a callback to return the response to.
*
* It's important you don't perform blocking operations in this method. Only use this if
* the task will be scheduling a different sync operation outside of the TaskChains scope.
*
* Usually you could achieve the same design with a blocking API by switching to an async task
* for the next task and running it there.
*
* This method would primarily be for cases where you need to use an API that ONLY provides
* a callback style API.
*
* @param task The task to execute
* @param <R> Return type that the next parameter can expect as argument type
*/
@SuppressWarnings("WeakerAccess")
public <R> TaskChain<R> syncFirstCallback(AsyncExecutingFirstTask<R> task) {
//noinspection unchecked
return add0(new TaskHolder<>(this, false, task));
}
/**
* @see #syncFirstCallback(AsyncExecutingFirstTask) but ran off main thread
* @param task The task to execute
* @param <R> Return type that the next parameter can expect as argument type
*/
@SuppressWarnings("WeakerAccess")
public <R> TaskChain<R> asyncFirstCallback(AsyncExecutingFirstTask<R> task) {
//noinspection unchecked
return add0(new TaskHolder<>(this, true, task));
}
@SuppressWarnings("WeakerAccess")
public <R> TaskChain<R> currentFirstCallback(AsyncExecutingFirstTask<R> task) {
//noinspection unchecked
return add0(new TaskHolder<>(this, null, task));
}
/**
* Execute a task on the main thread, with the last output, and a callback to return the response to.
*
* It's important you don't perform blocking operations in this method. Only use this if
* the task will be scheduling a different sync operation outside of the TaskChains scope.
*
* Usually you could achieve the same design with a blocking API by switching to an async task
* for the next task and running it there.
*
* This method would primarily be for cases where you need to use an API that ONLY provides
* a callback style API.
*
* @param task The task to execute
* @param <R> Return type that the next parameter can expect as argument type
*/
@SuppressWarnings("WeakerAccess")
public <R> TaskChain<R> syncCallback(AsyncExecutingTask<R, T> task) {
//noinspection unchecked
return add0(new TaskHolder<>(this, false, task));
}
/**
* @see #syncCallback(AsyncExecutingTask), ran on main thread but no input or output
* @param task The task to execute
*/
@SuppressWarnings("WeakerAccess")
public TaskChain<?> syncCallback(AsyncExecutingGenericTask task) {
return add0(new TaskHolder<>(this, false, task));
}
/**
* @see #syncCallback(AsyncExecutingTask) but ran off main thread
* @param task The task to execute
* @param <R> Return type that the next parameter can expect as argument type
*/
@SuppressWarnings("WeakerAccess")
public <R> TaskChain<R> asyncCallback(AsyncExecutingTask<R, T> task) {
//noinspection unchecked
return add0(new TaskHolder<>(this, true, task));
}
/**
* @see #syncCallback(AsyncExecutingTask) but ran off main thread
* @param task The task to execute
*/
@SuppressWarnings("WeakerAccess")
public TaskChain<?> asyncCallback(AsyncExecutingGenericTask task) {
return add0(new TaskHolder<>(this, true, task));
}
@SuppressWarnings("WeakerAccess")
public <R> TaskChain<R> currentCallback(AsyncExecutingTask<R, T> task) {
//noinspection unchecked
return add0(new TaskHolder<>(this, null, task));
}
@SuppressWarnings("WeakerAccess")
public TaskChain<?> currentCallback(AsyncExecutingGenericTask task) {
return add0(new TaskHolder<>(this, null, task));
}
/**
* Execute task on main thread, with no input, returning an output
* @param task The task to execute
* @param <R> Return type that the next parameter can expect as argument type
*/
@SuppressWarnings("WeakerAccess")
public <R> TaskChain<R> syncFirst(FirstTask<R> task) {
//noinspection unchecked
return add0(new TaskHolder<>(this, false, task));
}
/**
* @see #syncFirst(FirstTask) but ran off main thread
* @param task The task to execute
* @param <R> Return type that the next parameter can expect as argument type
*/
@SuppressWarnings("WeakerAccess")
public <R> TaskChain<R> asyncFirst(FirstTask<R> task) {
//noinspection unchecked
return add0(new TaskHolder<>(this, true, task));
}
@SuppressWarnings("WeakerAccess")
public <R> TaskChain<R> currentFirst(FirstTask<R> task) {
//noinspection unchecked
return add0(new TaskHolder<>(this, null, task));
}
/**
* Execute task on main thread, with the last returned input, returning an output
* @param task The task to execute
* @param <R> Return type that the next parameter can expect as argument type
*/
@SuppressWarnings("WeakerAccess")
public <R> TaskChain<R> sync(Task<R, T> task) {
//noinspection unchecked
return add0(new TaskHolder<>(this, false, task));
}
/**
* Execute task on main thread, with no input or output
* @param task The task to execute
*/
@SuppressWarnings("WeakerAccess")
public TaskChain<?> sync(GenericTask task) {
return add0(new TaskHolder<>(this, false, task));
}
/**
* @see #sync(Task) but ran off main thread
* @param task The task to execute
* @param <R> Return type that the next parameter can expect as argument type
*/
@SuppressWarnings("WeakerAccess")
public <R> TaskChain<R> async(Task<R, T> task) {
//noinspection unchecked
return add0(new TaskHolder<>(this, true, task));
}
/**
* @see #sync(GenericTask) but ran off main thread
* @param task The task to execute
*/
@SuppressWarnings("WeakerAccess")
public TaskChain<?> async(GenericTask task) {
return add0(new TaskHolder<>(this, true, task));
}
@SuppressWarnings("WeakerAccess")
public <R> TaskChain<R> current(Task<R, T> task) {
//noinspection unchecked
return add0(new TaskHolder<>(this, null, task));
}
@SuppressWarnings("WeakerAccess")
public TaskChain<?> current(GenericTask task) {
return add0(new TaskHolder<>(this, null, task));
}
/**
* Execute task on main thread, with the last output, and no furthur output
* @param task The task to execute
*/
@SuppressWarnings("WeakerAccess")
public TaskChain<?> syncLast(LastTask<T> task) {
return add0(new TaskHolder<>(this, false, task));
}
/**
* @see #syncLast(LastTask) but ran off main thread
* @param task The task to execute
*/
@SuppressWarnings("WeakerAccess")
public TaskChain<?> asyncLast(LastTask<T> task) {
return add0(new TaskHolder<>(this, true, task));
}
@SuppressWarnings("WeakerAccess")
public TaskChain<?> currentLast(LastTask<T> task) {
return add0(new TaskHolder<>(this, null, task));
}
/**
* Finished adding tasks, begins executing them.
*/
@SuppressWarnings("WeakerAccess")
public void execute() {
execute((Consumer<Boolean>) null, null);
}
/**
* Finished adding tasks, begins executing them with a done notifier
* @param done The Callback to handle when the chain has finished completion. Argument to consumer contains finish state
*/
@SuppressWarnings("WeakerAccess")
public void execute(Runnable done) {
execute((finished) -> done.run(), null);
}
/**
* Finished adding tasks, begins executing them with a done notifier and error handler
* @param done The Callback to handle when the chain has finished completion. Argument to consumer contains finish state
* @param errorHandler The Error handler to handle exceptions
*/
@SuppressWarnings("WeakerAccess")
public void execute(Runnable done, BiConsumer<Exception, Task<?, ?>> errorHandler) {
execute((finished) -> done.run(), errorHandler);
}
/**
* Finished adding tasks, with a done notifier
* @param done The Callback to handle when the chain has finished completion. Argument to consumer contains finish state
*/
@SuppressWarnings("WeakerAccess")
public void execute(Consumer<Boolean> done) {
execute(done, null);
}
/**
* Finished adding tasks, begins executing them, with an error handler
* @param errorHandler The Error handler to handle exceptions
*/
public void execute(BiConsumer<Exception, Task<?, ?>> errorHandler) {
execute((Consumer<Boolean>) null, errorHandler);
}
/**
* Finished adding tasks, begins executing them with a done notifier and error handler
* @param done The Callback to handle when the chain has finished completion. Argument to consumer contains finish state
* @param errorHandler The Error handler to handle exceptions
*/
public void execute(Consumer<Boolean> done, BiConsumer<Exception, Task<?, ?>> errorHandler) {
this.doneCallback = done;
this.errorHandler = errorHandler;
execute0();
}
// </editor-fold>
//<editor-fold desc="// Implementation Details">
void execute0() {
synchronized (this) {
if (this.executed) {
if (this.shared) {
return;
}
throw new RuntimeException("Already executed");
}
this.executed = true;
}
async = !impl.isMainThread();
nextTask();
}
void done(boolean finished) {
this.done = true;
if (this.shared) {
factory.removeSharedChain(this.sharedName);
}
if (this.doneCallback != null) {
final TaskChain<?> prev = currentChain.get();
try {
currentChain.set(this);
this.doneCallback.accept(finished);
} catch (Exception e) {
this.handleError(e, null);
} finally {
currentChain.set(prev);
}
}
}
@SuppressWarnings({"rawtypes", "WeakerAccess"})
protected TaskChain add0(TaskHolder<?,?> task) {
synchronized (this) {
if (!this.shared && this.executed) {
throw new RuntimeException("TaskChain is executing");
}
}
this.chainQueue.add(task);
return this;
}
/**
* Fires off the next task, and switches between Async/Sync as necessary.
*/
private void nextTask() {
synchronized (this) {
this.currentHolder = this.chainQueue.poll();
if (this.currentHolder == null) {
this.done = true; // to ensure its done while synchronized
}
}
if (this.currentHolder == null) {
this.previous = null;
// All Done!
this.done(true);
return;
}
Boolean isNextAsync = this.currentHolder.async;
if (isNextAsync == null || factory.shutdown) {
this.currentHolder.run();
} else if (isNextAsync) {
if (this.async) {
this.currentHolder.run();
} else {
impl.postAsync(() -> {
this.async = true;
this.currentHolder.run();
});
}
} else {
if (this.async) {
impl.postToMain(() -> {
this.async = false;
this.currentHolder.run();
});
} else {
this.currentHolder.run();
}
}
}
private void handleError(Exception e, Task<?, ?> task) {
if (errorHandler != null) {
final TaskChain<?> prev = currentChain.get();
try {
currentChain.set(this);
errorHandler.accept(e, task);
} catch (Exception e2) {
TaskChainUtil.logError("TaskChain Exception in the error handler! ");
e.printStackTrace();
} finally {
currentChain.set(prev);
}
} else {
TaskChainUtil.logError("TaskChain Exception on " + (task != null ? task.getClass().getName() : "Done Hander"));
e.printStackTrace();
}
}
// </editor-fold>
//<editor-fold desc="// TaskHolder">
/**
* Provides foundation of a task with what the previous task type should return
* to pass to this and what this task will return.
* @param <R> Return Type
* @param <A> Argument Type Expected
*/
@SuppressWarnings("AccessingNonPublicFieldOfAnotherObject")
private class TaskHolder<R, A> {
private final TaskChain<?> chain;
private final Task<R, A> task;
final Boolean async;
private boolean executed = false;
private boolean aborted = false;
private final int actionIndex;
private TaskHolder(TaskChain<?> chain, Boolean async, Task<R, A> task) {
this.actionIndex = TaskChain.this.actionIndex++;
this.task = task;
this.chain = chain;
this.async = async;
}
/**
* Called internally by Task Chain to facilitate executing the task and then the next task.
*/
private void run() {
final Object arg = this.chain.previous;
this.chain.previous = null;
TaskChain.this.currentActionIndex = this.actionIndex;
final R res;
final TaskChain<?> prevChain = currentChain.get();
try {
currentChain.set(this.chain);
if (this.task instanceof AsyncExecutingTask) {
//noinspection unchecked
((AsyncExecutingTask<R, A>) this.task).runAsync((A) arg, this::next);
} else {
//noinspection unchecked
next(this.task.run((A) arg));
}
} catch (Exception e) {
//noinspection ConstantConditions
if (e instanceof AbortChainException) {
this.abort();
return;
}
this.chain.handleError(e, this.task);
this.abort();
} finally {
if (prevChain != null) {
currentChain.set(prevChain);
} else {
currentChain.remove();
}
}
}
/**
* Abort the chain, and clear tasks for GC.
*/
private synchronized void abort() {
this.aborted = true;
this.chain.previous = null;
this.chain.chainQueue.clear();
this.chain.done(false);
}
/**
* Accepts result of previous task and executes the next
*/
private void next(Object resp) {
synchronized (this) {
if (this.aborted) {
this.chain.done(false);
return;
}
if (this.executed) {
this.chain.done(false);
throw new RuntimeException("This task has already been executed.");
}
this.executed = true;
}
this.chain.async = !TaskChain.this.impl.isMainThread(); // We don't know where the task called this from.
this.chain.previous = resp;
this.chain.nextTask();
}
}
//</editor-fold>
}
|
package hudson.model;
import hudson.FilePath;
import hudson.FilePath.FileCallable;
import hudson.remoting.VirtualChannel;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.StringTokenizer;
/**
* Has convenience methods to serve file system.
*
* @author Kohsuke Kawaguchi
*/
public abstract class DirectoryHolder extends Actionable {
/**
* Serves a file from the file system (Maps the URL to a directory in a file system.)
*
* @param icon
* The icon file name, like "folder-open.gif"
* @param serveDirIndex
* True to generate the directory index.
* False to serve "index.html"
*/
protected final void serveFile(StaplerRequest req, StaplerResponse rsp, FilePath root, String icon, boolean serveDirIndex) throws IOException, ServletException, InterruptedException {
if(req.getQueryString()!=null) {
req.setCharacterEncoding("UTF-8");
String path = req.getParameter("path");
if(path!=null) {
rsp.sendRedirect(URLEncoder.encode(path,"UTF-8"));
return;
}
}
String path = req.getRestOfPath();
if(path.length()==0)
path = "/";
if(path.indexOf("..")!=-1 || path.length()<1) {
// don't serve anything other than files in the artifacts dir
rsp.sendError(HttpServletResponse.SC_BAD_REQUEST);
return;
}
FilePath f = new FilePath(root,path.substring(1));
boolean isFingerprint=false;
if(f.getName().equals("*fingerprint*")) {
f = f.getParent();
isFingerprint = true;
}
if(!f.exists()) {
rsp.sendError(HttpServletResponse.SC_NOT_FOUND);
return;
}
if(f.isDirectory()) {
if(!req.getRequestURL().toString().endsWith("/")) {
rsp.sendRedirect2(req.getRequestURL().append('/').toString());
return;
}
if(serveDirIndex) {
req.setAttribute("it",this);
List<Path> parentPaths = buildParentPath(path);
req.setAttribute("parentPath",parentPaths);
req.setAttribute("topPath",
parentPaths.isEmpty() ? "." : repeat("../",parentPaths.size()));
req.setAttribute("files", f.act(new ChildPathBuilder()));
req.setAttribute("icon",icon);
req.setAttribute("path",path);
req.getView(this,"dir.jelly").forward(req,rsp);
return;
} else {
f = f.child("index.html");
}
}
if(isFingerprint) {
rsp.forward(Hudson.getInstance().getFingerprint(f.digest()),"/",req);
} else {
ContentInfo ci = f.act(new ContentInfo());
InputStream in = f.read();
rsp.serveFile(req, in, ci.lastModified, ci.contentLength, f.getName() );
in.close();
}
}
private static final class ContentInfo implements FileCallable<ContentInfo> {
int contentLength;
long lastModified;
public ContentInfo invoke(File f, VirtualChannel channel) throws IOException {
contentLength = (int) f.length();
lastModified = f.lastModified();
return this;
}
private static final long serialVersionUID = 1L;
}
/**
* Builds a list of {@link Path} that represents ancestors
* from a string like "/foo/bar/zot".
*/
private List<Path> buildParentPath(String pathList) {
List<Path> r = new ArrayList<Path>();
StringTokenizer tokens = new StringTokenizer(pathList, "/");
int total = tokens.countTokens();
int current=1;
while(tokens.hasMoreTokens()) {
String token = tokens.nextToken();
r.add(new Path(repeat("../",total-current),token,true,0));
current++;
}
return r;
}
private static String repeat(String s,int times) {
StringBuffer buf = new StringBuffer(s.length()*times);
for(int i=0; i<times; i++ )
buf.append(s);
return buf.toString();
}
/**
* Represents information about one file or folder.
*/
public static final class Path implements Serializable {
/**
* Relative URL to this path from the current page.
*/
private final String href;
/**
* Name of this path. Just the file name portion.
*/
private final String title;
private final boolean isFolder;
/**
* File size, or null if this is not a file.
*/
private final long size;
public Path(String href, String title, boolean isFolder, long size) {
this.href = href;
this.title = title;
this.isFolder = isFolder;
this.size = size;
}
public boolean isFolder() {
return isFolder;
}
public String getHref() {
return href;
}
public String getTitle() {
return title;
}
public String getIconName() {
return isFolder?"folder.gif":"text.gif";
}
public long getSize() {
return size;
}
private static final long serialVersionUID = 1L;
}
private static final class FileComparator implements Comparator<File> {
public int compare(File lhs, File rhs) {
// directories first, files next
int r = dirRank(lhs)-dirRank(rhs);
if(r!=0) return r;
// otherwise alphabetical
return lhs.getName().compareTo(rhs.getName());
}
private int dirRank(File f) {
if(f.isDirectory()) return 0;
else return 1;
}
}
/**
* Builds a list of list of {@link Path}. The inner
* list of {@link Path} represents one child item to be shown
* (this mechanism is used to skip empty intermediate directory.)
*/
private static final class ChildPathBuilder implements FileCallable<List<List<Path>>> {
public List<List<Path>> invoke(File cur, VirtualChannel channel) throws IOException {
List<List<Path>> r = new ArrayList<List<Path>>();
File[] files = cur.listFiles();
Arrays.sort(files,new FileComparator());
for( File f : files ) {
Path p = new Path(f.getName(),f.getName(),f.isDirectory(),f.length());
if(!f.isDirectory()) {
r.add(Collections.singletonList(p));
} else {
// find all empty intermediate directory
List<Path> l = new ArrayList<Path>();
l.add(p);
String relPath = f.getName();
while(true) {
// files that don't start with '.' qualify for 'meaningful files', nor SCM related files
File[] sub = f.listFiles(new FilenameFilter() {
public boolean accept(File dir, String name) {
return !name.startsWith(".") && !name.equals("CVS") && !name.equals(".svn");
}
});
if(sub.length!=1 || !sub[0].isDirectory())
break;
f = sub[0];
relPath += '/'+f.getName();
l.add(new Path(relPath,f.getName(),true,0));
}
r.add(l);
}
}
return r;
}
private static final long serialVersionUID = 1L;
}
}
|
package hudson.tasks;
import hudson.Launcher;
import hudson.model.Action;
import hudson.model.Build;
import hudson.model.BuildListener;
import hudson.model.Descriptor;
import hudson.model.DirectoryHolder;
import hudson.model.Project;
import hudson.model.ProminentProjectAction;
import org.apache.tools.ant.taskdefs.Copy;
import org.apache.tools.ant.types.FileSet;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
import javax.servlet.ServletException;
import java.io.File;
import java.io.IOException;
/**
* Saves Javadoc for the project and publish them.
*
* @author Kohsuke Kawaguchi
*/
public class JavadocArchiver extends AntBasedPublisher {
/**
* Path to the Javadoc directory in the workspace.
*/
private final String javadocDir;
public JavadocArchiver(String javadocDir) {
this.javadocDir = javadocDir;
}
public String getJavadocDir() {
return javadocDir;
}
/**
* Gets the directory where the Javadoc is stored for the given project.
*/
private static File getJavadocDir(Project project) {
return new File(project.getRootDir(),"javadoc");
}
public boolean perform(Build build, Launcher launcher, BuildListener listener) {
// TODO: run tar or something for better remote copy
File javadoc = new File(build.getParent().getWorkspace().getLocal(), javadocDir);
if(!javadoc.exists()) {
listener.error("The specified Javadoc directory doesn't exist: "+javadoc);
return false;
}
if(!javadoc.isDirectory()) {
listener.error("The specified Javadoc directory isn't a directory: "+javadoc);
return false;
}
listener.getLogger().println("Publishing Javadoc");
File target = getJavadocDir(build.getParent());
target.mkdirs();
Copy copyTask = new Copy();
copyTask.setProject(new org.apache.tools.ant.Project());
copyTask.setTodir(target);
FileSet src = new FileSet();
src.setDir(javadoc);
copyTask.addFileset(src);
execTask(copyTask, listener);
return true;
}
public Action getProjectAction(Project project) {
return new JavadocAction(project);
}
public Descriptor<Publisher> getDescriptor() {
return DESCRIPTOR;
}
public static final Descriptor<Publisher> DESCRIPTOR = new Descriptor<Publisher>(JavadocArchiver.class) {
public String getDisplayName() {
return "Publish Javadoc";
}
public Publisher newInstance(StaplerRequest req) {
return new JavadocArchiver(req.getParameter("javadoc_dir"));
}
};
public static final class JavadocAction extends DirectoryHolder implements ProminentProjectAction {
private final Project project;
public JavadocAction(Project project) {
this.project = project;
}
public String getUrlName() {
return "javadoc";
}
public String getDisplayName() {
return "Javadoc";
}
public String getIconFileName() {
return "help.gif";
}
public void doDynamic(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
serveFile(req, rsp, getJavadocDir(project), "help.gif", false);
}
}
}
|
package net.time4j.format;
import net.time4j.engine.AttributeKey;
import net.time4j.engine.AttributeQuery;
import net.time4j.engine.ChronoCondition;
import net.time4j.engine.ChronoElement;
import net.time4j.engine.ChronoValues;
import java.io.IOException;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
/**
* <p>Formatierschritt als Delegationsobjekt zum Parsen und Formatieren. </p>
*
* @author Meno Hochschild
* @concurrency <immutable>
*/
final class FormatStep {
private final FormatProcessor<?> processor;
private final int level;
private final int section;
private final Attributes sectionalAttrs;
private final int reserved;
private final int padLeft;
private final int padRight;
FormatStep(
FormatProcessor<?> processor,
int level,
int section,
Attributes sectionalAttrs
) {
this(processor, level, section, sectionalAttrs, 0, 0, 0);
}
private FormatStep(
FormatProcessor<?> processor,
int level,
int section,
Attributes sectionalAttrs,
int reserved,
int padLeft,
int padRight
) {
super();
if (processor == null) {
throw new NullPointerException("Missing format processor.");
} else if (level < 0) {
throw new IllegalArgumentException("Invalid level: " + level);
} else if (section < 0) {
throw new IllegalArgumentException("Invalid section: " + section);
} else if (reserved < 0) {
throw new IllegalArgumentException(
"Reserved chars must not be negative: " + reserved);
} else if (padLeft < 0) {
throw new IllegalArgumentException(
"Invalid pad-width: " + padLeft);
} else if (padRight < 0) {
throw new IllegalArgumentException(
"Invalid pad-width: " + padRight);
}
this.processor = processor;
this.level = level;
this.section = section;
this.sectionalAttrs = sectionalAttrs;
this.reserved = reserved;
this.padLeft = padLeft;
this.padRight = padRight;
}
void print(
ChronoValues formattable,
Appendable buffer,
AttributeQuery attributes,
Set<ElementPosition> positions
) throws IOException {
if (!this.isPrinting(formattable)) {
return;
}
if (
(this.padLeft == 0)
&& (this.padRight == 0)
) {
this.processor.print(
formattable,
buffer,
attributes,
positions,
this
);
return;
}
StringBuilder collector = new StringBuilder();
int offset = -1;
Set<ElementPosition> posBuf = null;
if (
(buffer instanceof CharSequence)
&& (positions != null)
) {
offset = ((CharSequence) buffer).length();
posBuf = new LinkedHashSet<ElementPosition>();
}
boolean strict = this.isStrict(attributes);
char padChar = this.getPadChar(attributes);
this.processor.print(
formattable,
collector,
attributes,
posBuf,
this
);
int len = collector.length();
int printed = len;
if (this.padLeft > 0) {
if (strict && (len > this.padLeft)) {
throw new IllegalArgumentException(this.padExceeded());
}
while (printed < this.padLeft) {
buffer.append(padChar);
printed++;
}
buffer.append(collector);
if (offset != -1) {
for (ElementPosition ep : posBuf) {
positions.add(
new ElementPosition(
ep.getElement(),
offset + ep.getStartIndex(),
offset + ep.getEndIndex()));
}
}
if (this.padRight > 0) {
if (strict && (len > this.padRight)) {
throw new IllegalArgumentException(this.padExceeded());
}
while (len < this.padRight) {
buffer.append(padChar);
len++;
}
}
} else { // padRight > 0
if (strict && (len > this.padRight)) {
throw new IllegalArgumentException(this.padExceeded());
}
buffer.append(collector);
while (printed < this.padRight) {
buffer.append(padChar);
printed++;
}
if (offset != -1) {
for (ElementPosition ep : posBuf) {
positions.add(
new ElementPosition(
ep.getElement(),
offset + ep.getStartIndex(),
offset + ep.getEndIndex()));
}
}
}
}
/**
* <p>Interpretiert den angegebenen Text. </p>
*
* @param text text to be parsed
* @param status parser information (always as new instance)
* @param attributes non-sectional control attributes
* @param parsedResult result buffer for parsed values
*/
void parse(
CharSequence text,
ParseLog status,
AttributeQuery attributes,
Map<ChronoElement<?>, Object> parsedResult
) {
if (
(this.padLeft == 0)
&& (this.padRight == 0)
) {
// Optimierung
this.doParse(text, status, attributes, parsedResult);
return;
}
boolean strict = this.isStrict(attributes);
char padChar = this.getPadChar(attributes);
int start = status.getPosition();
int endPos = text.length();
int index = start;
while (
(index < endPos)
&& (text.charAt(index) == padChar)
) {
index++;
}
int leftPadCount = index - start;
if (strict && (leftPadCount > this.padLeft)) {
status.setError(start, this.padExceeded());
return;
}
// Eigentliche Parser-Routine
status.setPosition(index);
this.doParse(text, status, attributes, parsedResult);
if (status.isError()) {
return;
}
index = status.getPosition();
int width = index - start - leftPadCount;
if (
strict
&& (this.padLeft > 0)
&& ((width + leftPadCount) != this.padLeft)
) {
status.setError(start, this.padMismatched());
return;
}
int rightPadCount = 0;
while (
(index < endPos)
&& (strict ? (width + rightPadCount < this.padRight) : true)
&& (text.charAt(index) == padChar)
) {
index++;
rightPadCount++;
}
if (
strict
&& (this.padRight > 0)
&& ((width + rightPadCount) != this.padRight)
) {
status.setError(index - rightPadCount, this.padMismatched());
return;
}
status.setPosition(index);
}
/**
* <p>Liefert die Ebene der optionalen Verarbeitung. </p>
*
* @return int
*/
int getLevel() {
return this.level;
}
/**
* <p>Identifiziert die optionale Sektion. </p>
*
* @return int
*/
int getSection() {
return this.section;
}
/**
* <p>Liegt ein fraktional formatiertes Element vor? </p>
*
* @return boolean
*/
boolean isFractional() {
return (this.processor instanceof FractionProcessor);
}
/**
* <p>Liegt ein numerisch formatiertes Element vor? </p>
*
* @return boolean
*/
boolean isNumerical() {
return this.processor.isNumerical();
}
/**
* <p>Ermittelt die Anzahl der zu reservierenden Zeichen beim Parsen. </p>
*
* @return n advance reserved chars of following format steps
*/
int getReserved() {
return this.reserved;
}
/**
* <p>Ermittelt die Delegationsinstanz. </p>
*
* @return delegate object for formatting work
*/
FormatProcessor<?> getProcessor() {
return this.processor;
}
/**
* <p>Aktualisiert diesen Formatierschritt. </p>
*
* @param element new element reference
* @return copy of this instance maybe modified
*/
FormatStep updateElement(ChronoElement<?> element) {
FormatProcessor<?> proc = update(this.processor, element);
if (this.processor == proc) {
return this;
}
return new FormatStep(
proc,
this.level,
this.section,
this.sectionalAttrs,
this.reserved,
this.padLeft,
this.padRight
);
}
/**
* <p>Rechnet die angegebene Anzahl der zu reservierenden Zeichen
* hinzu. </p>
*
* @param reserved count of chars to be reserved
* @return updated format step
*/
FormatStep reserve(int reserved) {
return new FormatStep(
this.processor,
this.level,
this.section,
this.sectionalAttrs,
this.reserved + reserved,
this.padLeft,
this.padRight
);
}
/**
* <p>Rechnet die angegebene Anzahl von Füllzeichen hinzu. </p>
*
* @param padLeft count of left-padding chars
* @param padRight count of right-padding chars
* @return updated format step
*/
FormatStep pad(
int padLeft,
int padRight
) {
return new FormatStep(
this.processor,
this.level,
this.section,
this.sectionalAttrs,
this.reserved,
this.padLeft + padLeft,
this.padRight + padRight
);
}
<A> A getAttribute(
AttributeKey<A> key,
AttributeQuery defaultAttrs,
A defaultValue
) {
AttributeQuery current = this.sectionalAttrs;
if (
(this.sectionalAttrs == null)
|| !this.sectionalAttrs.contains(key)
) {
current = defaultAttrs;
}
if (current.contains(key)) {
return current.get(key);
} else if (defaultValue == null) {
throw new IllegalArgumentException(key.name());
} else {
return defaultValue;
}
}
/**
* <p>Erstellt eine Attributabfrage. </p>
*
* @param defaultAttrs default attributes of {@code ChronoFormatter}
* @return query for retrieving attribute values
*/
AttributeQuery getQuery(final AttributeQuery defaultAttrs) {
if (this.sectionalAttrs == null) {
return defaultAttrs; // Optimierung
}
return new AttributeQuery() {
@Override
public boolean contains(AttributeKey<?> key) {
return this.getQuery(key).contains(key);
}
@Override
public <A> A get(AttributeKey<A> key) {
return this.getQuery(key).get(key);
}
@Override
public <A> A get(
AttributeKey<A> key,
A defaultValue
) {
return this.getQuery(key).get(key, defaultValue);
}
private AttributeQuery getQuery(AttributeKey<?> key) {
AttributeQuery current = FormatStep.this.sectionalAttrs;
if (!current.contains(key)) {
current = defaultAttrs;
}
return current;
}
};
}
/**
* <p>Vergleicht die internen Formatverarbeitungen und die sektionalen
* Attribute. </p>
*/
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
} else if (obj instanceof FormatStep) {
FormatStep that = (FormatStep) obj;
return (
this.processor.equals(that.processor)
&& (this.level == that.level)
&& (this.section == that.section)
&& isEqual(this.sectionalAttrs, that.sectionalAttrs)
&& (this.reserved == that.reserved)
&& (this.padLeft == that.padLeft)
&& (this.padRight == that.padRight)
);
} else {
return false;
}
}
/**
* <p>Berechnet den Hash-Code basierend auf dem internen Zustand. </p>
*/
@Override
public int hashCode() {
return (
7 * this.processor.hashCode()
+ 31 * (
(this.sectionalAttrs == null)
? 0
: this.sectionalAttrs.hashCode())
);
}
/**
* <p>Für Debugging-Zwecke. </p>
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("[processor=");
sb.append(this.processor);
sb.append(", level=");
sb.append(this.level);
sb.append(", section=");
sb.append(this.section);
if (this.sectionalAttrs != null) {
sb.append(", attributes=");
sb.append(this.sectionalAttrs);
}
sb.append(", reserved=");
sb.append(this.reserved);
sb.append(", pad-left=");
sb.append(this.padLeft);
sb.append(", pad-right=");
sb.append(this.padRight);
sb.append(']');
return sb.toString();
}
@SuppressWarnings("unchecked")
private static <V> FormatProcessor<V> update(
FormatProcessor<V> fp,
ChronoElement<?> element
) {
if (fp.getElement() == null) {
return fp;
} else if (fp.getElement().getType() != element.getType()) {
throw new IllegalArgumentException(
"Cannot change element value type: " + element.name());
}
return fp.withElement((ChronoElement<V>) element);
}
private static boolean isEqual(
Object o1, // optional
Object o2 // optional
) {
return ((o1 == null) ? (o2 == null) : o1.equals(o2));
}
private void doParse(
CharSequence text,
ParseLog status,
AttributeQuery attributes,
Map<ChronoElement<?>, Object> parsedResult
) {
int current = status.getPosition();
try {
this.processor.parse(
text,
status,
attributes,
parsedResult,
this
);
} catch (RuntimeException re) {
status.setError(current, re.getMessage());
}
}
private boolean isStrict(AttributeQuery attributes) {
return this.getAttribute(
Attributes.LENIENCY,
attributes,
Leniency.SMART
).isStrict();
}
private char getPadChar(AttributeQuery attributes) {
return this.getAttribute(
Attributes.PAD_CHAR,
attributes,
Character.valueOf(' ')
).charValue();
}
private String padExceeded() {
return "Pad width exceeded: "
+ this.getProcessor().getElement().name();
}
private String padMismatched() {
return "Pad width mismatched: "
+ this.getProcessor().getElement().name();
}
private boolean isPrinting(ChronoValues formattable) {
if (this.sectionalAttrs == null) {
return true;
}
ChronoCondition<ChronoValues> printCondition =
this.sectionalAttrs.getCondition();
return (
(printCondition == null)
|| printCondition.test(formattable)
);
}
}
|
// This software may be modified and distributed under the terms
package wyc.testing;
import static org.junit.Assert.fail;
import java.io.File;
import java.io.IOException;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import org.junit.*;
import org.junit.rules.Timeout;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
import wyc.commands.Compile;
import wyc.util.TestUtils;
import wycc.util.Pair;
/**
* Run through all valid test cases with verification enabled. Since every test
* file is valid, a successful test occurs when the compiler succeeds and, when
* executed, the compiled file produces the expected output. Note that an
* internal failure does not count as a valid pass, and indicates the test
* exposed some kind of compiler bug.
*
* @author David J. Pearce
*
*/
@RunWith(Parameterized.class)
public class AllValidVerificationTest {
@Rule
public Timeout globalTimeout = new Timeout(5, TimeUnit.SECONDS);
/**
* The directory containing the source files for each test case. Every test
* corresponds to a file in this directory.
*/
public final static String WHILEY_SRC_DIR = "tests/valid".replace('/', File.separatorChar);
/**
* Ignored tests and a reason why we ignore them.
*/
public final static Map<String, String> IGNORED = new HashMap<>();
static {
// Whiley Compiler Problems
// Bring over all the currently failing tests for the compiler. There's
// absolutely no point trying to see whether these work or not, since we
// already know they will not.
IGNORED.putAll(AllValidTest.IGNORED);
IGNORED.put("ConstrainedList_Valid_28", "#666");
IGNORED.put("IfElse_Valid_4", "#712");
IGNORED.put("Complex_Valid_4", "#712");
IGNORED.put("ListAccess_Valid_6", "712");
IGNORED.put("Record_Valid_3", "#714");
IGNORED.put("Complex_Valid_8", "#730");
IGNORED.put("Ensures_Valid_3", "#730");
IGNORED.put("ConstrainedList_Valid_22", "#731");
IGNORED.put("Assert_Valid_1", "#731");
IGNORED.put("Process_Valid_1", "#743");
IGNORED.put("Process_Valid_9", "#743");
IGNORED.put("Process_Valid_10", "#743");
IGNORED.put("Process_Valid_11", "#743");
IGNORED.put("Reference_Valid_2", "#743");
IGNORED.put("Reference_Valid_3", "#743");
IGNORED.put("Reference_Valid_6", "#743");
// Whiley Theorem Prover faults
IGNORED.put("ConstrainedList_Valid_8", "too long for Travis");
IGNORED.put("String_Valid_6", "too long for Travis");
IGNORED.put("While_Valid_30", "too long for Travis");
// Issue 2 "Verification of Remainder Operator"
IGNORED.put("ConstrainedInt_Valid_22", "WyTP
// Issue 12 "Support for Non-linear Arthmetic"
IGNORED.put("IntMul_Valid_2", "WyTP
IGNORED.put("While_Valid_27", "WyTP
IGNORED.put("While_Valid_32", "WyTP
// Issue 29 "Triggerless Quantifier Instantiation"
IGNORED.put("ConstrainedList_Valid_14", "WyTP
IGNORED.put("ConstrainedList_Valid_18", "WyTP
// Issue 36 "Support for Division Operator Feature"
IGNORED.put("Cast_Valid_5", "WyTP
IGNORED.put("IntOp_Valid_1", "WyTP
IGNORED.put("IntDiv_Valid_3", "WyTP
IGNORED.put("Lambda_Valid_3", "WyTP
IGNORED.put("Lambda_Valid_4", "WyTP
// Issue 41 "Case Split within Quantifier"
IGNORED.put("Property_Valid_4", "WyTP
IGNORED.put("Subtype_Valid_5", "WyTP
IGNORED.put("RecursiveType_Valid_19", "WyTP
// Issue 76 "Casting Record Types"
IGNORED.put("Coercion_Valid_9", "WyTP
IGNORED.put("RecordCoercion_Valid_1", "WyTP
// Issue 80 "(Non-)Empty Type"
IGNORED.put("OpenRecord_Valid_4", "WyTP
IGNORED.put("OpenRecord_Valid_9", "WyTP
// Issue 85 "NegativeArraySizeException in CoerciveSubtypeOperator"
IGNORED.put("ConstrainedRecord_Valid_9", "WyTP
IGNORED.put("TypeEquals_Valid_54", "WyTP
// Issue 86 "Handle Coefficients for CongruenceClosure"
IGNORED.put("While_Valid_25", "WyTP
// Issue 89 "Unknown Assertion Failure"
IGNORED.put("While_Valid_37", "WyTP
// Issue 102 "Support Reference Lifetimes"
IGNORED.put("Lifetime_Valid_8", "WyTP#102");
// Issue 104 "Incompleteness in CoerciveSubtypeOperator"
IGNORED.put("RecursiveType_Valid_7", "WyTP#104");
IGNORED.put("While_Valid_15", "WyTP#104");
IGNORED.put("While_Valid_20", "WyTP#104");
// Issue 107 "Limitation with ReadableRecordExtractor"
IGNORED.put("TypeEquals_Valid_30", "WyTP#107");
IGNORED.put("TypeEquals_Valid_25", "WyTP#107");
// Issue 111 "Infinite Recursive Expansion"
IGNORED.put("RecursiveType_Valid_29", "WyTP#111");
IGNORED.put("Function_Valid_18", "WyTP#111");
IGNORED.put("While_Valid_22", "WyTP#111");
// Issue 112 "More Performance Problems with Type Checking"
IGNORED.put("Complex_Valid_2", "WyTP#112");
IGNORED.put("BoolList_Valid_3", "WyTP#112");
IGNORED.put("While_Valid_2", "WyTP#112");
IGNORED.put("While_Valid_26", "WyTP#112");
// Issue 113 "Type Checking Recursive Types"
IGNORED.put("RecursiveType_Valid_2", "WyTP#113");
IGNORED.put("RecursiveType_Valid_4", "WyTP#113");
IGNORED.put("While_Valid_34", "??");
}
/**
* The directory where compiler libraries are stored. This is necessary
* since it will contain the Whiley Runtime.
*/
public final static String WYC_LIB_DIR = "lib/".replace('/', File.separatorChar);
// Test Harness
/**
* Compile a syntactically invalid test case with verification enabled. The
* expectation is that compilation should fail with an error and, hence, the
* test fails if compilation does not.
*
* @param name
* Name of the test to run. This must correspond to a whiley
* source file in the <code>WHILEY_SRC_DIR</code> directory.
* @throws IOException
*/
protected void runTest(String name) throws IOException {
File whileySrcDir = new File(WHILEY_SRC_DIR);
// this will need to turn on verification at some point.
name = WHILEY_SRC_DIR + File.separatorChar + name + ".whiley";
Pair<Compile.Result,String> p = TestUtils.compile(
whileySrcDir, // location of source directory
true, // enable verification
name); // name of test to compile
Compile.Result r = p.first();
System.out.print(p.second());
if (r != Compile.Result.SUCCESS) {
fail("Test failed to compile!");
} else if (r == Compile.Result.INTERNAL_FAILURE) {
fail("Test caused internal failure!");
}
}
// Tests
// Parameter to test case is the name of the current test.
// It will be passed to the constructor by JUnit.
private final String testName;
public AllValidVerificationTest(String testName) {
this.testName = testName;
}
// Here we enumerate all available test cases.
@Parameters(name = "{0}")
public static Collection<Object[]> data() {
return TestUtils.findTestNames(WHILEY_SRC_DIR);
}
// Skip ignored tests
@Before
public void beforeMethod() {
String ignored = IGNORED.get(this.testName);
Assume.assumeTrue("Test " + this.testName + " skipped: " + ignored, ignored == null);
}
@Test
public void validVerification() throws IOException {
if (new File("../../running_on_travis").exists()) {
System.out.println(".");
}
runTest(this.testName);
}
}
|
package xal.smf.application;
import xal.application.*;
import xal.tools.apputils.files.*;
import xal.smf.data.XMLDataManager;
import xal.smf.*;
import javax.swing.*;
import java.io.File;
import java.net.URL;
import java.util.*;
import java.util.logging.*;
/**
* AcceleratorApplication is the subclass of Application that is required for
* accelerator based applications.
* @author tap
*/
public class AcceleratorApplication extends FrameApplication {
/** file chooser for selecting an accelerator file */
private JFileChooser _acceleratorFileChooser;
/** keep track of the default accelerator folder */
private DefaultFolderAccessory _defaultFolderAccessory;
/** Creates a new instance of AcceleratorApplication */
public AcceleratorApplication(ApplicationAdaptor adaptor, URL[] urls) {
super( adaptor, urls );
}
/**
* Initialize the Application and open the documents specified by the URL array.
* Overides the inherited version to perform initializations that should occur prior to opening files.
* @param urls An array of document URLs to open.
*/
protected void setup( final URL[] urls ) {
_acceleratorFileChooser = new JFileChooser();
_defaultFolderAccessory = new DefaultFolderAccessory( this.getClass() );
_defaultFolderAccessory.applyTo( _acceleratorFileChooser );
FileFilterFactory.applyFileFilters( _acceleratorFileChooser, new String[] {"xal"} );
_acceleratorFileChooser.setMultiSelectionEnabled( false );
super.setup( urls );
}
/**
* Make an application commander
*/
protected Commander makeCommander() {
return new AcceleratorCommander( this );
}
/**
* Get the file chooser used for opening accelerator input files.
* @return The file chooser used for opening accelerator input files.
*/
public JFileChooser getAcceleratorFileChooser() {
return _acceleratorFileChooser;
}
/**
* Get the accelerator application for this session
* @return the accelerator application for this session
*/
static public AcceleratorApplication getAcceleratorApp() {
return (AcceleratorApplication)Application.getApp();
}
/**
* Handle the launching of the application by creating the application instance
* and performing application initialization.
* @param adaptor The custom application adaptor.
*/
static public void launch( final ApplicationAdaptor adaptor ) {
try {
launch( adaptor, AbstractApplicationAdaptor.getDocURLs() );
}
catch ( NullPointerException e ) {
new AcceleratorApplication( adaptor, new URL[] {} );
}
}
/**
* Handle the launching of the application by creating the application instance
* and performing application initialization.
* @param adaptor The custom application adaptor.
* @param urls The URLs of documents to open upon launching the application
*/
static public void launch( final ApplicationAdaptor adaptor, final URL[] urls ) {
new AcceleratorApplication( adaptor, urls );
}
/**
* Create and open a new empty document of the specified type.
* @param type the type of document to create.
*/
protected void newDocument( final String type ) {
final AcceleratorDocument document = (AcceleratorDocument)((ApplicationAdaptor)getAdaptor()).generateEmptyDocument( type );
// don't need to set an accelerator if the document already has one
if ( document.getAccelerator() == null ) {
final String acceleratorPath = Boolean.getBoolean( "useDefaultAccelerator" ) ? XMLDataManager.defaultPath() : System.getProperty( "useAccelerator" );
document.applySelectedAcceleratorWithDefaultPath( acceleratorPath );
final Accelerator accelerator = document.getAccelerator();
if ( accelerator != null ) {
final String sequenceID = System.getProperty( "useSequence" );
if ( sequenceID != null && sequenceID.length() > 0 ) {
document.setSelectedSequence( accelerator.findSequence( sequenceID ) );
}
}
}
final String selectedAcceleratorPath = document.getAcceleratorFilePath();
if ( selectedAcceleratorPath != null && selectedAcceleratorPath.length() > 0 ) {
_acceleratorFileChooser.setSelectedFile( new File( selectedAcceleratorPath ) );
}
produceDocument( document );
}
}
|
package transportation.Agents;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.*;
import java.util.List;
import javax.swing.Timer;
import market.Market;
import transportation.Transportation;
import transportation.TransportationPanel;
import transportation.GUIs.BusGui;
import transportation.GUIs.CarGui;
import transportation.GUIs.TruckGui;
import transportation.GUIs.WalkerGui;
import transportation.Objects.*;
import transportation.Objects.MovementTile.MovementType;
import agent.Agent;
import astar.astar.Position;
import simcity.interfaces.Person;
import simcity.mock.LoggedEvent;
import simcity.*;
import simcity.gui.trace.AlertLog;
import simcity.gui.trace.AlertTag;
public class TransportationController extends Agent implements Transportation{
TransportationPanel master;
public enum TransportationState {
REQUEST,
MOVING,
DESTINATION,
WAITINGTOSPAWN,
TIMERIDLING
};
public class Mover implements ActionListener{
public TransportationState transportationState;
public Person person;
MobileAgent mobile;
javax.swing.Timer timer;
String startingLocation;
String endingLocation;
String method;
String character;
Mover(Person person, String startingLocation, String endingLocation, String method, String character) {
this.person = person;
this.startingLocation = startingLocation;
this.endingLocation = endingLocation;
this.method = method;
this.character = character;
transportationState = TransportationState.REQUEST;
timer = new Timer(500, this);
}
public void waitingForSpawn() {
timer.start();
transportationState = TransportationState.TIMERIDLING;
}
@Override
public void actionPerformed(ActionEvent arg0) {
transportationState = TransportationState.REQUEST;
timer.stop();
stateChanged();
}
}
public List<Mover> movingObjects;
class Building {
String name;
Position walkingTile;
Position vehicleTile;
BusStop closestBusStop;
public Building(String name) {
this.name = name;
walkingTile = null;
vehicleTile = null;
closestBusStop = null;
}
public Building(String name, Position walkingTile, Position vehicleTile, BusStop closestBusStop) {
this.name = name;
this.walkingTile = walkingTile;
this.vehicleTile = vehicleTile;
this.closestBusStop = closestBusStop;
}
public void addEnteringTiles(Position walkingTile, Position vehicleTile) {
this.walkingTile = walkingTile;
this.vehicleTile = vehicleTile;
}
public void setBusStop(BusStop busStop) {
this.closestBusStop = busStop;
}
}
public Map<String, Building> directory;
MovementTile[][] grid;
public List<BusStop> busStops;
public List<BusAgent> buses;
public TruckAgent truck;
private TrafficLight trafficLight;
public TransportationController(TransportationPanel panel) {
master = panel;
movingObjects = Collections.synchronizedList(new ArrayList<Mover>());
//++++++++++++++++++++++BEGIN CREATION OF GRID++++++++++++++++++++++
grid = new MovementTile[34][30];
for(int i = 0; i < grid.length; i++) {
for(int j = 0; j< grid[0].length; j++) {
grid[i][j] = new MovementTile(this);
}
}
//Walkways
for(int i = 2; i <= 31; i++) {
grid[i][2].setMovement(true, true, true, true, MovementTile.MovementType.WALKWAY);
grid[i][3].setMovement(true, true, true, true, MovementTile.MovementType.WALKWAY);
grid[i][6].setMovement(true, true, true, true, MovementTile.MovementType.WALKWAY);
grid[i][7].setMovement(true, true, true, true, MovementTile.MovementType.WALKWAY);
grid[i][12].setMovement(true, true, true, true, MovementTile.MovementType.WALKWAY);
grid[i][13].setMovement(true, true, true, true, MovementTile.MovementType.WALKWAY);
grid[i][16].setMovement(true, true, true, true, MovementTile.MovementType.WALKWAY);
grid[i][17].setMovement(true, true, true, true, MovementTile.MovementType.WALKWAY);
grid[i][22].setMovement(true, true, true, true, MovementTile.MovementType.WALKWAY);
grid[i][23].setMovement(true, true, true, true, MovementTile.MovementType.WALKWAY);
grid[i][26].setMovement(true, true, true, true, MovementTile.MovementType.WALKWAY);
grid[i][27].setMovement(true, true, true, true, MovementTile.MovementType.WALKWAY);
}
for(int i = 4; i <= 25; i++) {
grid[2][i].setMovement(true, true, true, true, MovementTile.MovementType.WALKWAY);
grid[3][i].setMovement(true, true, true, true, MovementTile.MovementType.WALKWAY);
grid[6][i].setMovement(true, true, true, true, MovementTile.MovementType.WALKWAY);
grid[7][i].setMovement(true, true, true, true, MovementTile.MovementType.WALKWAY);
grid[14][i].setMovement(true, true, true, true, MovementTile.MovementType.WALKWAY);
grid[15][i].setMovement(true, true, true, true, MovementTile.MovementType.WALKWAY);
grid[18][i].setMovement(true, true, true, true, MovementTile.MovementType.WALKWAY);
grid[19][i].setMovement(true, true, true, true, MovementTile.MovementType.WALKWAY);
grid[26][i].setMovement(true, true, true, true, MovementTile.MovementType.WALKWAY);
grid[27][i].setMovement(true, true, true, true, MovementTile.MovementType.WALKWAY);
grid[30][i].setMovement(true, true, true, true, MovementTile.MovementType.WALKWAY);
grid[31][i].setMovement(true, true, true, true, MovementTile.MovementType.WALKWAY);
}
//Roads
for(int i = 4; i <= 29; i++) {
grid[i][4].setMovement(false, true, true, false, MovementTile.MovementType.ROAD);
grid[i][5].setMovement(true, false, false, true, MovementTile.MovementType.ROAD);
grid[i][14].setMovement(false, true, true, false, MovementTile.MovementType.ROAD);
grid[i][15].setMovement(true, false, false, true, MovementTile.MovementType.ROAD);
grid[i][24].setMovement(false, true, true, false, MovementTile.MovementType.ROAD);
grid[i][25].setMovement(true, false, false, true, MovementTile.MovementType.ROAD);
}
for(int i = 6; i <= 13; i++) {
grid[4][i].setMovement(false, true, false, true, MovementTile.MovementType.ROAD);
grid[5][i].setMovement(true, false, true, false, MovementTile.MovementType.ROAD);
grid[4][i+10].setMovement(false, true, false, true, MovementTile.MovementType.ROAD);
grid[5][i+10].setMovement(true, false, true, false, MovementTile.MovementType.ROAD);
grid[16][i].setMovement(false, true, false, true, MovementTile.MovementType.ROAD);
grid[17][i].setMovement(true, false, true, false, MovementTile.MovementType.ROAD);
grid[16][i+10].setMovement(false, true, false, true, MovementTile.MovementType.ROAD);
grid[17][i+10].setMovement(true, false, true, false, MovementTile.MovementType.ROAD);
grid[28][i].setMovement(false, true, false, true, MovementTile.MovementType.ROAD);
grid[29][i].setMovement(true, false, true, false, MovementTile.MovementType.ROAD);
grid[28][i+10].setMovement(false, true, false, true, MovementTile.MovementType.ROAD);
grid[29][i+10].setMovement(true, false, true, false, MovementTile.MovementType.ROAD);
}
//Intersections... oh joy!
grid[4][4].setMovement(false, true, false, false, MovementTile.MovementType.ROAD);
grid[5][4].setMovement(false, false, true, false, MovementTile.MovementType.ROAD);
grid[4][5].setMovement(false, true, false, false, MovementTile.MovementType.ROAD);
grid[5][5].setMovement(false, false, false, true, MovementTile.MovementType.ROAD);
grid[16][4].setMovement(false, true, true, false, MovementTile.MovementType.ROAD);
grid[17][4].setMovement(false, false, true, false, MovementTile.MovementType.ROAD);
grid[16][5].setMovement(false, true, false, true, MovementTile.MovementType.ROAD);
grid[17][5].setMovement(true, false, false, true, MovementTile.MovementType.ROAD);
grid[28][4].setMovement(false, false, true, false, MovementTile.MovementType.ROAD);
grid[29][4].setMovement(false, false, true, false, MovementTile.MovementType.ROAD);
grid[28][5].setMovement(false, true, false, false, MovementTile.MovementType.ROAD);
grid[29][5].setMovement(true, false, false, false, MovementTile.MovementType.ROAD);
grid[4][14].setMovement(false, true, false, false, MovementTile.MovementType.ROAD);
grid[5][14].setMovement(true, false, true, false, MovementTile.MovementType.ROAD);
grid[4][15].setMovement(false, true, false, true, MovementTile.MovementType.ROAD);
grid[5][15].setMovement(true, false, false, true, MovementTile.MovementType.ROAD);
grid[28][14].setMovement(false, true, true, false, MovementTile.MovementType.ROAD);
grid[29][14].setMovement(true, false, false, false, MovementTile.MovementType.ROAD);
grid[28][15].setMovement(false, true, false, true, MovementTile.MovementType.ROAD);
grid[29][15].setMovement(true, false, false, false, MovementTile.MovementType.ROAD);
grid[4][24].setMovement(false, true, false, false, MovementTile.MovementType.ROAD);
grid[5][24].setMovement(true, false, false, false, MovementTile.MovementType.ROAD);
grid[4][25].setMovement(false, false, false, true, MovementTile.MovementType.ROAD);
grid[5][25].setMovement(false, false, false, true, MovementTile.MovementType.ROAD);
grid[16][24].setMovement(false, true, true, false, MovementTile.MovementType.ROAD);
grid[17][24].setMovement(true, false, true, false, MovementTile.MovementType.ROAD);
grid[16][25].setMovement(false, false, false, true, MovementTile.MovementType.ROAD);
grid[17][25].setMovement(true, false, false, true, MovementTile.MovementType.ROAD);
grid[28][24].setMovement(false, false, true, false, MovementTile.MovementType.ROAD);
grid[29][24].setMovement(true, false, false, false, MovementTile.MovementType.ROAD);
grid[28][25].setMovement(false, false, false, true, MovementTile.MovementType.ROAD);
grid[29][25].setMovement(false, false, false, true, MovementTile.MovementType.ROAD);
//Small Driveway Esque Roads
//Houses first which are single tiles
grid[9][1].setMovement(false, true, false, false, MovementTile.MovementType.ROAD);//Tiki Hut
grid[9][4].setUp(true);
grid[32][6].setMovement(false, false, true, false, MovementTile.MovementType.ROAD);//Haunted Mansion
grid[29][6].setRight(true);
grid[1][10].setMovement(false, false, false, true, MovementTile.MovementType.ROAD);//Rabbit Hole
grid[4][10].setLeft(true);
grid[32][19].setMovement(false, false, true, false, MovementTile.MovementType.ROAD);//Pirate's Suite
grid[29][19].setRight(true);
grid[11][21].setMovement(false, true, false, false, MovementTile.MovementType.ROAD);//Space Mountain
grid[11][24].setUp(true);
grid[1][24].setMovement(false, false, false, true, MovementTile.MovementType.ROAD);//Cinderella Castle
grid[4][24].setLeft(true);
//And then others which are loops to prevent traffic jams
//North Market
grid[12][0].setMovement(false, true, false, false, MovementTile.MovementType.ROAD);
grid[13][0].setMovement(false, false, true, false, MovementTile.MovementType.ROAD);
grid[14][0].setMovement(false, false, true, false, MovementTile.MovementType.ROAD);
grid[12][1].setMovement(false, true, false, false, MovementTile.MovementType.ROAD);
grid[13][1].setMovement(false, false, false, true, MovementTile.MovementType.ROAD);
grid[14][1].setMovement(false, false, false, true, MovementTile.MovementType.ROAD);
grid[13][4].setUp(true);
//Rancho
grid[20][0].setMovement(false, true, false, false, MovementTile.MovementType.ROAD);
grid[21][0].setMovement(false, false, true, false, MovementTile.MovementType.ROAD);
grid[20][1].setMovement(false, true, false, false, MovementTile.MovementType.ROAD);
grid[21][1].setMovement(true, false, false, false, MovementTile.MovementType.ROAD);
grid[21][4].setUp(true);
//Apt
grid[24][0].setMovement(false, true, false, false, MovementTile.MovementType.ROAD);
grid[25][0].setMovement(false, false, true, false, MovementTile.MovementType.ROAD);
grid[24][1].setMovement(false, true, false, false, MovementTile.MovementType.ROAD);
grid[25][1].setMovement(true, false, false, false, MovementTile.MovementType.ROAD);
grid[25][4].setUp(true);
//Apt
grid[0][6].setMovement(false, true, false, false, MovementTile.MovementType.ROAD);
grid[1][6].setMovement(false, false, true, false, MovementTile.MovementType.ROAD);
grid[0][7].setMovement(false, false, false, true, MovementTile.MovementType.ROAD);
grid[1][7].setMovement(false, false, false, true, MovementTile.MovementType.ROAD);
grid[4][6].setLeft(true);
//Bank
grid[24][9].setMovement(false, true, false, false, MovementTile.MovementType.ROAD);
grid[25][9].setMovement(false, false, true, false, MovementTile.MovementType.ROAD);
grid[24][10].setMovement(false, true, false, false, MovementTile.MovementType.ROAD);
grid[25][10].setMovement(true, false, false, false, MovementTile.MovementType.ROAD);
grid[24][11].setMovement(false, true, false, false, MovementTile.MovementType.ROAD);
grid[25][11].setMovement(true, false, false, false, MovementTile.MovementType.ROAD);
grid[25][14].setUp(true);
//Haus
grid[32][10].setMovement(false, false, true, false, MovementTile.MovementType.ROAD);
grid[33][10].setMovement(false, false, true, false, MovementTile.MovementType.ROAD);
grid[32][11].setMovement(false, false, false, true, MovementTile.MovementType.ROAD);
grid[33][11].setMovement(true, false, false, false, MovementTile.MovementType.ROAD);
grid[29][11].setRight(true);
//Pizza and Apt
grid[10][18].setMovement(false, true, false, false, MovementTile.MovementType.ROAD);
grid[11][18].setMovement(false, false, false, true, MovementTile.MovementType.ROAD);
grid[10][19].setMovement(true, false, false, false, MovementTile.MovementType.ROAD);
grid[11][19].setMovement(true, false, false, false, MovementTile.MovementType.ROAD);
grid[10][15].setDown(true);
//Southern Market
grid[22][18].setMovement(false, true, false, false, MovementTile.MovementType.ROAD);
grid[23][18].setMovement(false, false, false, true, MovementTile.MovementType.ROAD);
grid[22][19].setMovement(true, false, false, false, MovementTile.MovementType.ROAD);
grid[23][19].setMovement(true, false, false, false, MovementTile.MovementType.ROAD);
//Apt #3 and Apt #5
grid[0][19].setMovement(false, true, false, false, MovementTile.MovementType.ROAD);
grid[1][19].setMovement(false, false, true, false, MovementTile.MovementType.ROAD);
grid[0][20].setMovement(false, false, false, true, MovementTile.MovementType.ROAD);
grid[1][20].setMovement(false, false, false, true, MovementTile.MovementType.ROAD);
grid[4][19].setLeft(true);
//Cafe
grid[24][20].setMovement(false, true, false, false, MovementTile.MovementType.ROAD);
grid[25][21].setMovement(false, false, true, false, MovementTile.MovementType.ROAD);
grid[24][20].setMovement(false, true, false, false, MovementTile.MovementType.ROAD);
grid[25][21].setMovement(true, false, false, false, MovementTile.MovementType.ROAD);
grid[25][24].setUp(true);
//Apt #6 and Apt #7
grid[32][24].setMovement(false, false, true, false, MovementTile.MovementType.ROAD);
grid[33][24].setMovement(false, false, true, false, MovementTile.MovementType.ROAD);
grid[32][25].setMovement(false, false, false, true, MovementTile.MovementType.ROAD);
grid[33][25].setMovement(true, false, false, false, MovementTile.MovementType.ROAD);
grid[29][25].setRight(true);
//Apt
grid[4][28].setMovement(false, true, false, false, MovementTile.MovementType.ROAD);
grid[5][28].setMovement(true, false, false, false, MovementTile.MovementType.ROAD);
grid[4][29].setMovement(false, false, false, true, MovementTile.MovementType.ROAD);
grid[5][29].setMovement(true, false, false, false, MovementTile.MovementType.ROAD);
grid[4][25].setDown(true);
//Apt #9 and Bayou
grid[10][28].setMovement(false, true, false, false, MovementTile.MovementType.ROAD);
grid[11][28].setMovement(true, false, false, false, MovementTile.MovementType.ROAD);
grid[10][29].setMovement(false, false, false, true, MovementTile.MovementType.ROAD);
grid[11][29].setMovement(true, false, false, false, MovementTile.MovementType.ROAD);
grid[10][25].setDown(true);
//Apt
grid[22][28].setMovement(false, true, false, false, MovementTile.MovementType.ROAD);
grid[23][28].setMovement(true, false, false, false, MovementTile.MovementType.ROAD);
grid[22][29].setMovement(false, false, false, true, MovementTile.MovementType.ROAD);
grid[23][29].setMovement(true, false, false, false, MovementTile.MovementType.ROAD);
grid[22][25].setDown(true);
//Apt
grid[28][28].setMovement(false, true, false, false, MovementTile.MovementType.ROAD);
grid[29][28].setMovement(true, false, false, false, MovementTile.MovementType.ROAD);
grid[28][29].setMovement(false, false, false, true, MovementTile.MovementType.ROAD);
grid[29][29].setMovement(true, false, false, false, MovementTile.MovementType.ROAD);
grid[28][25].setDown(true);
//Time for some CROSSWALKS
//Houses first again since they're multidirectional and only two
grid[9][2].setMovement(true, true, false, false, MovementTile.MovementType.CROSSWALK);
grid[9][3].setMovement(true, true, false, false, MovementTile.MovementType.CROSSWALK);
grid[30][6].setMovement(false, false, true, true, MovementTile.MovementType.CROSSWALK);
grid[31][6].setMovement(false, false, true, true, MovementTile.MovementType.CROSSWALK);
grid[2][10].setMovement(false, false, true, true, MovementTile.MovementType.CROSSWALK);
grid[3][10].setMovement(false, false, true, true, MovementTile.MovementType.CROSSWALK);
grid[30][19].setMovement(false, false, true, true, MovementTile.MovementType.CROSSWALK);
grid[31][19].setMovement(false, false, true, true, MovementTile.MovementType.CROSSWALK);
grid[11][22].setMovement(true, true, false, false, MovementTile.MovementType.CROSSWALK);
grid[11][23].setMovement(true, true, false, false, MovementTile.MovementType.CROSSWALK);
grid[2][24].setMovement(false, false, true, true, MovementTile.MovementType.CROSSWALK);
grid[3][24].setMovement(false, false, true, true, MovementTile.MovementType.CROSSWALK);
//Square CrossWalks
setCrossWalk(6, 4, true);
setCrossWalk(14, 4, true);
setCrossWalk(18, 4, true);
setCrossWalk(26, 4, true);
setCrossWalk(16, 6, false);
setCrossWalk(4, 12, false);
setCrossWalk(28, 12, false);
setCrossWalk(6, 14, true);
setCrossWalk(26, 14, true);
setCrossWalk(4, 16, false);
setCrossWalk(28, 16, false);
setCrossWalk(16, 22, false);
setCrossWalk(6, 24, true);
setCrossWalk(14, 24, true);
setCrossWalk(18, 24, true);
setCrossWalk(26, 24, true);
//Driveways that double as crosswalks
setCrossWalk(12, 2, false);//Northern Market
setCrossWalk(20, 2, false);//Rancho
setCrossWalk(24, 2, false);//Apt
setCrossWalk(2, 6, true);//Apt
setCrossWalk(30, 10, true);//Haus
setCrossWalk(24, 12, false);//Bank
setCrossWalk(10, 18, false);//Pizza and Apt
setCrossWalk(22, 18, false);//Southern Market
setCrossWalk(19, 2, true);//Apt #3 and Apt #5
setCrossWalk(24, 22, false);//Cafe
setCrossWalk(30, 24, true);//Apt #6 and Apt #7
setCrossWalk(4, 28, false);//Apt
setCrossWalk(10, 28, false);//Apt #9 and Bayou
setCrossWalk(22, 28, false);//Apt
setCrossWalk(28, 28, false);//Apt
//Traffic light
trafficLight = new TrafficLight(new Position(16, 14), grid);
master.addGui(trafficLight);
//GoGo Pelipper trucks
grid[18][1].setMovement(false, true, false, false, MovementTile.MovementType.FLYING);
grid[20][21].setMovement(false, true, true, false, MovementTile.MovementType.FLYING);
//grid[7][4].setMovement(false, true, true, false, MovementTile.MovementType.CROSSWALK);
//grid[11][6].setMovement(true, false, true, false, MovementTile.MovementType.CROSSWALK);
//grid[5][8].setMovement(false, false, false, true, MovementTile.MovementType.CROSSWALK);
//+++++++++++++++++++++++END CREATION OF GRID+++++++++++++++++++++++
//++++++++++++++++++++++BEGIN CREATION OF BUS STOPS++++++++++++++++++++++
busStops = new ArrayList<BusStop>();
BusStop tempBusStop = new BusStop("Bus Stop 0");//Top Left Bus Stop
tempBusStop.associateWalkTile(new Position(11, 3));
busStops.add(tempBusStop);
grid[11][4].setBusStop(busStops.get(0));
tempBusStop.addNearbyBuilding("Mickey's Market");
tempBusStop.addNearbyBuilding("Tiki Hut");
tempBusStop = new BusStop("Bus Stop 1");//Left Center Bus Stop
tempBusStop.associateWalkTile(new Position(3, 11));
busStops.add(tempBusStop);
grid[4][11].setBusStop(busStops.get(1));
tempBusStop.addNearbyBuilding("Main St Apartments
tempBusStop.addNearbyBuilding("Rabbit Hole");
// tempBusStop.addNearbyBuilding("Haunted Mansion");
tempBusStop = new BusStop("Bus Stop 2");//Left Bottom Bus
tempBusStop.associateWalkTile(new Position(3, 23));
busStops.add(tempBusStop);
grid[4][23].setBusStop(busStops.get(2));
tempBusStop.addNearbyBuilding("Main St Apartments
tempBusStop.addNearbyBuilding("Main St Apartments
tempBusStop.addNearbyBuilding("Main St Apartments
tempBusStop.addNearbyBuilding("Main St Apartments
tempBusStop.addNearbyBuilding("Pizza Port");
tempBusStop.addNearbyBuilding("Cinderella Castle");
// tempBusStop.addNearbyBuilding("Mickey's Market");
tempBusStop = new BusStop("Bus Stop 3");//Bottom Left Bus
tempBusStop.associateWalkTile(new Position(9, 26));
busStops.add(tempBusStop);
grid[9][25].setBusStop(busStops.get(3));
tempBusStop.addNearbyBuilding("Main St Apartments
tempBusStop.addNearbyBuilding("The Blue Bayou");
tempBusStop.addNearbyBuilding("Space Mountain");
tempBusStop = new BusStop("Bus Stop 4");//Bottom Right Bus
tempBusStop.associateWalkTile(new Position(24, 26));
busStops.add(tempBusStop);
grid[24][25].setBusStop(busStops.get(4));
tempBusStop.addNearbyBuilding("Main St Apartments
tempBusStop.addNearbyBuilding("Main St Apartments
tempBusStop.addNearbyBuilding("Carnation Cafe");
tempBusStop.addNearbyBuilding("Minnie's Market");
tempBusStop = new BusStop("Bus Stop 5");//Center Right Bus
tempBusStop.associateWalkTile(new Position(30, 18));
busStops.add(tempBusStop);
grid[29][18].setBusStop(busStops.get(5));
tempBusStop.addNearbyBuilding("Main St Apartments
tempBusStop.addNearbyBuilding("Main St Apartments
tempBusStop.addNearbyBuilding("Pirate's Suite");
tempBusStop = new BusStop("Bus Stop 6");//Right Top Bus
tempBusStop.associateWalkTile(new Position(30, 8));
busStops.add(tempBusStop);
grid[29][8].setBusStop(busStops.get(6));
tempBusStop.addNearbyBuilding("Pirate Bank");
tempBusStop.addNearbyBuilding("Village Haus");
tempBusStop.addNearbyBuilding("Haunted Mansion");
tempBusStop = new BusStop("Bus Stop 7");//Top Right Bus
tempBusStop.associateWalkTile(new Position(23, 3));
busStops.add(tempBusStop);
grid[23][4].setBusStop(busStops.get(7));
tempBusStop.addNearbyBuilding("Main St Apartments
tempBusStop.addNearbyBuilding("Rancho Del Zocalo");
//+++++++++++++++++++++++END CREATION OF BUS STOPS+++++++++++++++++++++++
//++++++++++++++++++++++BEGIN CREATION OF DIRECTORY++++++++++++++++++++++
directory = new HashMap<String, Building>();
Building tempBuilding = new Building("Main St Apartments #1", new Position(27, 2), new Position(25, 0), busStops.get(7));
directory.put(tempBuilding.name, tempBuilding);
tempBuilding = new Building("Main St Apartments #2", new Position(2, 4), new Position(0, 6), busStops.get(1));
directory.put(tempBuilding.name, tempBuilding);
tempBuilding = new Building("Main St Apartments #3", new Position(2, 17), new Position(0, 19), busStops.get(2));
directory.put(tempBuilding.name, tempBuilding);
tempBuilding = new Building("Main St Apartments #4", new Position(13, 17), new Position(11, 19), busStops.get(2));
directory.put(tempBuilding.name, tempBuilding);
tempBuilding = new Building("Main St Apartments #5", new Position(2, 21), new Position(0, 20), busStops.get(2));
directory.put(tempBuilding.name, tempBuilding);
tempBuilding = new Building("Main St Apartments #6", new Position(31, 22), new Position(33, 24), busStops.get(5));
directory.put(tempBuilding.name, tempBuilding);
tempBuilding = new Building("Main St Apartments #7", new Position(31, 27), new Position(33, 25), busStops.get(5));
directory.put(tempBuilding.name, tempBuilding);
tempBuilding = new Building("Main St Apartments #8", new Position(2, 27), new Position(4, 29), busStops.get(2));
directory.put(tempBuilding.name, tempBuilding);
tempBuilding = new Building("Main St Apartments #9", new Position(8, 27), new Position(10, 29), busStops.get(3));
directory.put(tempBuilding.name, tempBuilding);
tempBuilding = new Building("Main St Apartments #10", new Position(20, 27), new Position(22, 29), busStops.get(4));
directory.put(tempBuilding.name, tempBuilding);
tempBuilding = new Building("Main St Apartments #11", new Position(26, 27), new Position(28, 29), busStops.get(4));
directory.put(tempBuilding.name, tempBuilding);
tempBuilding = new Building("Haunted Mansion", new Position(31, 4), new Position(32, 6), busStops.get(6));
directory.put(tempBuilding.name, tempBuilding);
tempBuilding = new Building("Tiki Hut", new Position(7, 2), new Position(9, 1), busStops.get(0));
directory.put(tempBuilding.name, tempBuilding);
tempBuilding = new Building("Rabbit Hole", new Position(2, 12), new Position(1, 10), busStops.get(1));
directory.put(tempBuilding.name, tempBuilding);
tempBuilding = new Building("Cinderella Castle", new Position(2, 26), new Position(1, 24), busStops.get(2));
directory.put(tempBuilding.name, tempBuilding);
tempBuilding = new Building("Space Mountain", new Position(9, 22), new Position(11, 21), busStops.get(3));
directory.put(tempBuilding.name, tempBuilding);
tempBuilding = new Building("Pirate's Suite", new Position(31, 17), new Position(32, 19), busStops.get(5));
directory.put(tempBuilding.name, tempBuilding);
tempBuilding = new Building("Mickey's Market", new Position(16, 2), new Position(14, 1), busStops.get(0));
directory.put(tempBuilding.name, tempBuilding);
tempBuilding = new Building("Minnie's Market", new Position(19, 19), new Position(21, 19), busStops.get(4));
directory.put(tempBuilding.name, tempBuilding);
tempBuilding = new Building("Pirate Bank", new Position(21, 12), new Position(24, 11), busStops.get(6));
directory.put(tempBuilding.name, tempBuilding);
tempBuilding = new Building("Rancho Del Zocalo", new Position(22, 2), new Position(21, 0), busStops.get(7));
directory.put(tempBuilding.name, tempBuilding);
tempBuilding = new Building("Carnation Cafe", new Position(22, 22), new Position(24, 20), busStops.get(4));
directory.put(tempBuilding.name, tempBuilding);
tempBuilding = new Building("The Blue Bayou", new Position(13, 27), new Position(11, 29), busStops.get(4));
directory.put(tempBuilding.name, tempBuilding);
tempBuilding = new Building("Pizza Port", new Position(8, 17), new Position(10, 19), busStops.get(3));
directory.put(tempBuilding.name, tempBuilding);
tempBuilding = new Building("Village Haus", new Position(31, 9), new Position(33, 10), busStops.get(6));//hacked 33, 10
directory.put(tempBuilding.name, tempBuilding);
tempBuilding = new Building("Bus Stop 0", new Position(11, 3), new Position(11, 4), busStops.get(0));
directory.put(tempBuilding.name, tempBuilding);
tempBuilding = new Building("Bus Stop 1", new Position(3, 11), new Position(4, 11), busStops.get(1));
directory.put(tempBuilding.name, tempBuilding);
tempBuilding = new Building("Bus Stop 2", new Position(3, 23), new Position(4, 23), busStops.get(2));
directory.put(tempBuilding.name, tempBuilding);
tempBuilding = new Building("Bus Stop 3", new Position(9, 26), new Position(9, 25), busStops.get(3));
directory.put(tempBuilding.name, tempBuilding);
tempBuilding = new Building("Bus Stop 4", new Position(24, 26), new Position(24, 25), busStops.get(4));
directory.put(tempBuilding.name, tempBuilding);
tempBuilding = new Building("Bus Stop 5", new Position(30, 18), new Position(29, 18), busStops.get(5));
directory.put(tempBuilding.name, tempBuilding);
tempBuilding = new Building("Bus Stop 6", new Position(30, 8), new Position(29, 8), busStops.get(6));
directory.put(tempBuilding.name, tempBuilding);
tempBuilding = new Building("Bus Stop 7", new Position(23, 3), new Position(23, 4), busStops.get(7));
directory.put(tempBuilding.name, tempBuilding);
//+++++++++++++++++++++++END CREATION OF DIRECTORY+++++++++++++++++++++++
//Spawning Buses
buses = new ArrayList<BusAgent>();
BusAgent tempBus = new BusAgent(this, new Position(4, 4));
BusGui busGui = new BusGui(4, 4, tempBus);
if(master != null)
master.addGui(busGui);
tempBus.setGui(busGui);
tempBus.startThread();
buses.add(tempBus);
tempBus = new BusAgent(this, new Position(29, 25));
busGui = new BusGui(29, 25, tempBus);
if(master != null)
master.addGui(busGui);
tempBus.setGui(busGui);
tempBus.startThread();
buses.add(tempBus);
//Spawning Delivery Truck
truck = new TruckAgent(new Position(17, 2), this, new FlyingTraversal(grid), 18, 1);
TruckGui truckGui = new TruckGui(18, 2, truck);
if(master != null)
master.addGui(truckGui);
truck.setGui(truckGui);
truck.startThread();
if(master != null)
super.startThread();
}
private void setCrossWalk(int x, int y, boolean horizontal) {
if(horizontal) {
grid[x][y].setMovement(false, false, true, true, MovementType.CROSSWALK);
grid[x+1][y].setMovement(false, false, true, true, MovementType.CROSSWALK);
grid[x][y+1].setMovement(false, false, true, true, MovementType.CROSSWALK);
grid[x+1][y+1].setMovement(false, false, true, true, MovementType.CROSSWALK);
}
else {
grid[x][y].setMovement(true, true, false, false, MovementType.CROSSWALK);
grid[x+1][y].setMovement(true, true, false, false, MovementType.CROSSWALK);
grid[x][y+1].setMovement(true, true, false, false, MovementType.CROSSWALK);
grid[x+1][y+1].setMovement(true, true, false, false, MovementType.CROSSWALK);
}
}
//+++++++++++++++++MESSAGES+++++++++++++++++
public void msgWantToGo(String startLocation, String endLocation, Person person, String mover, String character) {
log.add(new LoggedEvent("Received transportation request from " + person.getName()));
for(Mover m : movingObjects) {
if(m.person == person && !m.method.equals("Bus"))
return;
}
System.out.println("RECEIVED REQUEST TO TRANSPORT");
movingObjects.add(new Mover(person, startLocation, endLocation, mover, character));
stateChanged();
}
public void msgArrivedAtDestination(Person person){
log.add(new LoggedEvent(person.getName() + ": Person reached destination"));
for(Mover mover : movingObjects) {
if(mover.person == person) {
mover.transportationState = TransportationState.DESTINATION;
}
}
stateChanged();
}
public void msgSendDelivery(Restaurant restaurant, Market market, String food, int quantity, int id) {
truck.msgDeliverOrder(restaurant, market, food, quantity, id);
}
public void msgSendDelivery(Person person, Market market, String food, int quantity, String location) {
truck.msgDeliverOrder(person, market, food, quantity, location);
}
//+++++++++++++++++SCHEDULER+++++++++++++++++
@Override
public boolean pickAndExecuteAnAction() {
synchronized(movingObjects) {
for(Mover mover : movingObjects) {
if(mover.transportationState == TransportationState.REQUEST) {
spawnMover(mover);
return true;
}
}
}
synchronized(movingObjects) {
for(Mover mover : movingObjects) {
if(mover.transportationState == TransportationState.DESTINATION) {
despawnMover(mover);//POTENTIAL ERROR
return true;
}
}
}
synchronized(movingObjects) {
boolean retry = false;
for(Mover mover : movingObjects) {
if(mover.transportationState == TransportationState.WAITINGTOSPAWN) {
retry = true;
retrySpawn(mover);
}
}
if(retry)
return true;
}
return false;
}
private void spawnMover(Mover mover) {
//Try to spawn mover
//TransportationTraversal aStar = new TransportationTraversal(grid);
if(mover.method.equals("Car")){
log.add(new LoggedEvent("Spawning Car"));
if(grid[directory.get(mover.startingLocation).vehicleTile.getX()][directory.get(mover.startingLocation).vehicleTile.getY()].tryAcquire()) {
CarTraversal aStar = new CarTraversal(grid);
mover.transportationState = TransportationState.MOVING;
CarAgent driver = new CarAgent(mover.person, directory.get(mover.startingLocation).vehicleTile, directory.get(mover.endingLocation).vehicleTile, this, aStar);
CarGui carGui = new CarGui(directory.get(mover.startingLocation).vehicleTile.getX(), directory.get(mover.startingLocation).vehicleTile.getY(), driver);
if(master != null)
master.addGui(carGui);
driver.setGui(carGui);
driver.startThread();
AlertLog.getInstance().logMessage(AlertTag.TRANSPORTATION, "Transportation Controller", "Spawning Car for " + mover.person.getName() + ".");
}
else {
mover.transportationState = TransportationState.WAITINGTOSPAWN;
}
}
else if(mover.method.equals("Walk")){
log.add(new LoggedEvent("Spawning Walker"));
if(grid[directory.get(mover.startingLocation).walkingTile.getX()][directory.get(mover.startingLocation).walkingTile.getY()].tryAcquire()) {
WalkerTraversal aStar = new WalkerTraversal(grid);
mover.transportationState = TransportationState.MOVING;
WalkerAgent walker = new WalkerAgent(mover.person, directory.get(mover.startingLocation).walkingTile, directory.get(mover.endingLocation).walkingTile, this, aStar);
WalkerGui walkerGui = new WalkerGui(directory.get(mover.startingLocation).walkingTile.getX(), directory.get(mover.startingLocation).walkingTile.getY(), walker);
if(master != null)
master.addGui(walkerGui);
walker.setGui(walkerGui);
walker.startThread();
AlertLog.getInstance().logMessage(AlertTag.TRANSPORTATION, "Transportation Controller", "Spawning Walker for " + mover.person.getName() + ".");
}
else {
mover.transportationState = TransportationState.WAITINGTOSPAWN;
log.add(new LoggedEvent("Failed to spawn Walker"));
}
}
else if(mover.method.equals("Bus")){
log.add(new LoggedEvent("Spawning Bus"));
//find bus stop and spawn walker to go to bus stop
mover.transportationState = TransportationState.MOVING;
if(directory.get(mover.startingLocation).closestBusStop == directory.get(mover.endingLocation).closestBusStop) {
mover.method = "Walk";
spawnMover(mover);
return;
}
if(easierToWalk(directory.get(mover.startingLocation).walkingTile, directory.get(mover.endingLocation).walkingTile, directory.get(mover.startingLocation).closestBusStop.getAssociatedTile(), directory.get(mover.endingLocation).closestBusStop.getAssociatedTile())) {
mover.method = "Walk";
spawnMover(mover);
return;
}
if(grid[directory.get(mover.startingLocation).walkingTile.getX()][directory.get(mover.startingLocation).walkingTile.getY()].tryAcquire()) {
WalkerTraversal aStar = new WalkerTraversal(grid);
WalkerAgent busWalker = new WalkerAgent(mover.person, directory.get(mover.startingLocation).walkingTile, directory.get(mover.endingLocation).walkingTile, this, aStar, directory.get(mover.startingLocation).closestBusStop, directory.get(mover.endingLocation).closestBusStop, mover.endingLocation);
WalkerGui busWalkerGui = new WalkerGui(directory.get(mover.startingLocation).walkingTile.getX(), directory.get(mover.startingLocation).walkingTile.getY(), busWalker);
if(master != null)
master.addGui(busWalkerGui);
busWalker.setGui(busWalkerGui);
busWalker.startThread();
AlertLog.getInstance().logMessage(AlertTag.TRANSPORTATION, "Transportation Controller", "Spawning Bus Walker for " + mover.person.getName() + ".");
}
else {
mover.transportationState = TransportationState.WAITINGTOSPAWN;
}
}
}
private boolean easierToWalk(Position start, Position end, Position startStop, Position endStop) {
float walkingDistance = 0.00f;
float busDistance = 0.00f;
walkingDistance += abs((start.getY() - end.getY()));
walkingDistance += abs((start.getX() - end.getX()));
busDistance += abs((start.getX() - startStop.getX()));
busDistance += abs((start.getY() - startStop.getY()));
busDistance += abs((end.getX() - endStop.getX()));
busDistance += abs((end.getY() - endStop.getY()));
//iterate through a generic bus route and find how long the bus would require
//Multiply it by 0.25 to encourage bus taking.
Queue<Position> route = new LinkedList<Position>();
createRoute(route);
while(route.peek().getX() != startStop.getX() && route.peek().getY() != startStop.getY()) {
route.add(route.poll());
}
while(route.peek().getX() != endStop.getX() && route.peek().getY() != endStop.getY()) {
route.add(route.poll());
busDistance += 0.25;
}
if(walkingDistance <= busDistance)
return true;
return false;
}
private int abs(int integer) {
if(integer < 0) {
return -integer;
}
return integer;
}
public void createRoute(Queue<Position> route) {//Hack for one route
//SPAWN BUS AT {4, 4}
for(int i = 5; i <= 25; i++) {
route.add(new Position(4, i));
}
for(int i = 5; i <= 29; i++) {
route.add(new Position(i, 25));
}
for(int i = 24; i>=4; i
route.add(new Position(29, i));
}
for(int i = 28; i >= 4; i
route.add(new Position(i, 4));
}
}
private void despawnMover(Mover mover) {
log.add(new LoggedEvent("Deleting mover"));
if(!mover.method.equals("Bus")) {
mover.person.msgReachedDestination(mover.endingLocation);
AlertLog.getInstance().logMessage(AlertTag.TRANSPORTATION, "Transportation Controller", mover.person.getName() + " reached their destination.");
}
movingObjects.remove(mover);
}
private void retrySpawn(Mover mover) {
log.add(new LoggedEvent("Resetting mover state"));
mover.waitingForSpawn();
}
public MovementTile[][] getGrid() {
return grid;
}
public void msgPayFare(Person person, float fare) {
buses.get(0).msgPayFare(person, fare);
buses.get(1).msgPayFare(person, fare);
}
}
|
package ubic.basecode.dataStructure.params;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import ubic.basecode.io.excel.SpreadSheetSchema;
/**
* Keeps track of results in the form of several key/value maps (each one can represent an experiment run), can output
* to spreadsheet or csv file
*
* @author leon
*/
public class ParamKeeper {
List<Map<String, String>> paramLines;
public ParamKeeper() {
paramLines = new LinkedList<Map<String, String>>();
}
public void addParamInstance( Map<String, String> params ) {
paramLines.add( params );
}
public void writeExcel( String filename ) throws Exception {
// get all the keys
Set<String> keySet = new HashSet<String>();
for ( Map<String, String> params : paramLines ) {
keySet.addAll( params.keySet() );
}
List<String> header = new LinkedList<String>( keySet );
// sort?
Map<String, Integer> positions = new HashMap<String, Integer>();
for ( int i = 0; i < header.size(); i++ ) {
positions.put( header.get( i ), i );
}
SpreadSheetSchema schema = new SpreadSheetSchema( positions );
ParamSpreadSheet s = new ParamSpreadSheet( filename, schema );
s.populate( paramLines );
// write file
s.save();
}
public String toCSVString() {
String result = "";
for ( Map<String, String> params : paramLines ) {
result += ParameterGrabber.paramsToLine( params ) + "\n";
}
return result;
}
}
|
package us.kbase.test.auth2.lib;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;
import static org.mockito.ArgumentMatchers.isA;
import static org.mockito.Mockito.any;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static us.kbase.test.auth2.TestCommon.set;
import static us.kbase.test.auth2.lib.AuthenticationTester.initTestMocks;
import java.time.Clock;
import java.time.Instant;
import java.util.Collections;
import java.util.Map;
import java.util.UUID;
import org.junit.Test;
import com.google.common.base.Optional;
import com.google.common.collect.ImmutableMap;
import us.kbase.auth2.cryptutils.RandomDataGenerator;
import us.kbase.auth2.lib.Authentication;
import us.kbase.auth2.lib.DisplayName;
import us.kbase.auth2.lib.LinkIdentities;
import us.kbase.auth2.lib.LinkToken;
import us.kbase.auth2.lib.UserDisabledState;
import us.kbase.auth2.lib.UserName;
import us.kbase.auth2.lib.config.AuthConfig;
import us.kbase.auth2.lib.config.AuthConfigSet;
import us.kbase.auth2.lib.config.CollectingExternalConfig;
import us.kbase.auth2.lib.config.AuthConfig.ProviderConfig;
import us.kbase.auth2.lib.config.CollectingExternalConfig.CollectingExternalConfigMapper;
import us.kbase.auth2.lib.exceptions.DisabledUserException;
import us.kbase.auth2.lib.exceptions.ErrorType;
import us.kbase.auth2.lib.exceptions.IdentityLinkedException;
import us.kbase.auth2.lib.exceptions.IdentityRetrievalException;
import us.kbase.auth2.lib.exceptions.InvalidTokenException;
import us.kbase.auth2.lib.exceptions.LinkFailedException;
import us.kbase.auth2.lib.exceptions.MissingParameterException;
import us.kbase.auth2.lib.exceptions.NoSuchIdentityProviderException;
import us.kbase.auth2.lib.exceptions.NoSuchTokenException;
import us.kbase.auth2.lib.exceptions.NoSuchUserException;
import us.kbase.auth2.lib.exceptions.UnauthorizedException;
import us.kbase.auth2.lib.identity.IdentityProvider;
import us.kbase.auth2.lib.identity.RemoteIdentity;
import us.kbase.auth2.lib.identity.RemoteIdentityDetails;
import us.kbase.auth2.lib.identity.RemoteIdentityID;
import us.kbase.auth2.lib.storage.AuthStorage;
import us.kbase.auth2.lib.storage.exceptions.AuthStorageException;
import us.kbase.auth2.lib.token.IncomingToken;
import us.kbase.auth2.lib.token.StoredToken;
import us.kbase.auth2.lib.token.TemporaryToken;
import us.kbase.auth2.lib.token.TokenType;
import us.kbase.auth2.lib.user.AuthUser;
import us.kbase.test.auth2.TestCommon;
import us.kbase.test.auth2.lib.AuthenticationTester.TestMocks;
public class AuthenticationLinkTest {
private final RemoteIdentity REMOTE = new RemoteIdentity(new RemoteIdentityID("Prov", "id1"),
new RemoteIdentityDetails("user1", "full1", "f1@g.com"));
@Test
public void linkWithTokenImmediately() throws Exception {
final IdentityProvider idp = mock(IdentityProvider.class);
when(idp.getProviderName()).thenReturn("Prov");
final TestMocks testauth = initTestMocks(set(idp));
final AuthStorage storage = testauth.storageMock;
final Authentication auth = testauth.auth;
AuthenticationTester.setConfigUpdateInterval(auth, -1);
final IncomingToken token = new IncomingToken("foobar");
final Map<String, ProviderConfig> providers = ImmutableMap.of(
"Prov", new ProviderConfig(true, false, false));
when(storage.getConfig(isA(CollectingExternalConfigMapper.class)))
.thenReturn(new AuthConfigSet<CollectingExternalConfig>(
new AuthConfig(false, providers, null),
new CollectingExternalConfig(Collections.emptyMap())));
when(storage.getToken(token.getHashedToken())).thenReturn(
StoredToken.getBuilder(TokenType.LOGIN, UUID.randomUUID(), new UserName("baz"))
.withLifeTime(Instant.now(), Instant.now()).build())
.thenReturn(null);
when(storage.getUser(new UserName("baz"))).thenReturn(AuthUser.getBuilder(
new UserName("baz"), new DisplayName("foo"), Instant.now())
.withIdentity(REMOTE).build()).thenReturn(null);
when(idp.getIdentities("authcode", true)).thenReturn(set(new RemoteIdentity(
new RemoteIdentityID("Prov", "id2"),
new RemoteIdentityDetails("user2", "full2", "f2@g.com"))))
.thenReturn(null);
final RemoteIdentity storageRemoteID = new RemoteIdentity(
new RemoteIdentityID("Prov", "id2"),
new RemoteIdentityDetails("user2", "full2", "f2@g.com"));
when(storage.getUser(storageRemoteID)).thenReturn(Optional.absent()).thenReturn(null);
final LinkToken lt = auth.link(token, "prov", "authcode");
assertThat("incorrect linktoken", lt, is(new LinkToken()));
verify(storage).link(new UserName("baz"), storageRemoteID);
}
@Test
public void linkWithTokenRaceConditionAndIDLinked() throws Exception {
final IdentityProvider idp = mock(IdentityProvider.class);
when(idp.getProviderName()).thenReturn("Prov");
final TestMocks testauth = initTestMocks(set(idp));
final AuthStorage storage = testauth.storageMock;
final RandomDataGenerator rand = testauth.randGenMock;
final Clock clock = testauth.clockMock;
final Authentication auth = testauth.auth;
AuthenticationTester.setConfigUpdateInterval(auth, -1);
final IncomingToken token = new IncomingToken("foobar");
final Map<String, ProviderConfig> providers = ImmutableMap.of(
"Prov", new ProviderConfig(true, false, false));
when(storage.getConfig(isA(CollectingExternalConfigMapper.class)))
.thenReturn(new AuthConfigSet<CollectingExternalConfig>(
new AuthConfig(false, providers, null),
new CollectingExternalConfig(Collections.emptyMap())));
when(storage.getToken(token.getHashedToken())).thenReturn(
StoredToken.getBuilder(TokenType.LOGIN, UUID.randomUUID(), new UserName("baz"))
.withLifeTime(Instant.now(), Instant.now()).build())
.thenReturn(null);
when(storage.getUser(new UserName("baz"))).thenReturn(AuthUser.getBuilder(
new UserName("baz"), new DisplayName("foo"), Instant.ofEpochMilli(20000))
.withIdentity(REMOTE).build()).thenReturn(null);
when(idp.getIdentities("authcode", true)).thenReturn(set(new RemoteIdentity(
new RemoteIdentityID("Prov", "id2"),
new RemoteIdentityDetails("user2", "full2", "f2@g.com"))))
.thenReturn(null);
final RemoteIdentity storageRemoteID = new RemoteIdentity(
new RemoteIdentityID("Prov", "id2"),
new RemoteIdentityDetails("user2", "full2", "f2@g.com"));
when(storage.getUser(storageRemoteID)).thenReturn(Optional.absent()).thenReturn(null);
doThrow(new IdentityLinkedException("foo"))
.when(storage).link(new UserName("baz"), storageRemoteID);
final UUID tokenID = UUID.randomUUID();
when(rand.randomUUID()).thenReturn(tokenID).thenReturn(null);
when(rand.getToken()).thenReturn("sometoken").thenReturn(null);
when(clock.instant()).thenReturn(Instant.ofEpochMilli(10000)).thenReturn(null);
final LinkToken lt = auth.link(token, "prov", "authcode");
assertThat("incorrect linktoken", lt, is(new LinkToken(new TemporaryToken(
tokenID, "sometoken", Instant.ofEpochMilli(10000), 10 * 60 * 1000),
new LinkIdentities(AuthUser.getBuilder(
new UserName("baz"), new DisplayName("foo"), Instant.ofEpochMilli(20000))
.withIdentity(REMOTE).build(),
"Prov"))));
verify(storage).storeIdentitiesTemporarily(new TemporaryToken(
tokenID, "sometoken", Instant.ofEpochMilli(10000), 10 * 60 * 1000)
.getHashedToken(),
Collections.emptySet());
}
@Test
public void linkWithTokenForceChoice() throws Exception {
final IdentityProvider idp = mock(IdentityProvider.class);
when(idp.getProviderName()).thenReturn("prov");
final TestMocks testauth = initTestMocks(set(idp));
final AuthStorage storage = testauth.storageMock;
final RandomDataGenerator rand = testauth.randGenMock;
final Clock clock = testauth.clockMock;
final Authentication auth = testauth.auth;
AuthenticationTester.setConfigUpdateInterval(auth, -1);
final IncomingToken token = new IncomingToken("foobar");
final Map<String, ProviderConfig> providers = ImmutableMap.of(
"prov", new ProviderConfig(true, false, true));
when(storage.getConfig(isA(CollectingExternalConfigMapper.class)))
.thenReturn(new AuthConfigSet<CollectingExternalConfig>(
new AuthConfig(false, providers, null),
new CollectingExternalConfig(Collections.emptyMap())));
when(storage.getToken(token.getHashedToken())).thenReturn(
StoredToken.getBuilder(TokenType.LOGIN, UUID.randomUUID(), new UserName("baz"))
.withLifeTime(Instant.now(), Instant.now()).build())
.thenReturn(null);
when(storage.getUser(new UserName("baz"))).thenReturn(AuthUser.getBuilder(
new UserName("baz"), new DisplayName("foo"), Instant.ofEpochMilli(20000))
.withIdentity(REMOTE).build()).thenReturn(null);
when(idp.getIdentities("authcode", true)).thenReturn(set(new RemoteIdentity(
new RemoteIdentityID("prov", "id2"),
new RemoteIdentityDetails("user2", "full2", "f2@g.com"))))
.thenReturn(null);
final RemoteIdentity storageRemoteID = new RemoteIdentity(
new RemoteIdentityID("prov", "id2"),
new RemoteIdentityDetails("user2", "full2", "f2@g.com"));
when(storage.getUser(storageRemoteID)).thenReturn(Optional.absent()).thenReturn(null);
final UUID tokenID = UUID.randomUUID();
when(rand.randomUUID()).thenReturn(tokenID).thenReturn(null);
when(rand.getToken()).thenReturn("sometoken").thenReturn(null);
when(clock.instant()).thenReturn(Instant.ofEpochMilli(10000)).thenReturn(null);
final LinkToken lt = auth.link(token, "prov", "authcode");
assertThat("incorrect linktoken", lt, is(new LinkToken(new TemporaryToken(
tokenID, "sometoken", Instant.ofEpochMilli(10000), 10 * 60 * 1000),
new LinkIdentities(AuthUser.getBuilder(
new UserName("baz"), new DisplayName("foo"), Instant.ofEpochMilli(20000))
.withIdentity(REMOTE).build(),
set(storageRemoteID)))));
verify(storage).storeIdentitiesTemporarily(new TemporaryToken(
tokenID, "sometoken", Instant.ofEpochMilli(10000), 10 * 60 * 1000)
.getHashedToken(),
set(storageRemoteID));
verify(storage, never()).link(any(), any());
}
@Test
public void linkWithTokenNoIDsDueToFilter() throws Exception {
final IdentityProvider idp = mock(IdentityProvider.class);
when(idp.getProviderName()).thenReturn("prov");
final TestMocks testauth = initTestMocks(set(idp));
final AuthStorage storage = testauth.storageMock;
final RandomDataGenerator rand = testauth.randGenMock;
final Clock clock = testauth.clockMock;
final Authentication auth = testauth.auth;
AuthenticationTester.setConfigUpdateInterval(auth, -1);
final IncomingToken token = new IncomingToken("foobar");
final Map<String, ProviderConfig> providers = ImmutableMap.of(
"prov", new ProviderConfig(true, false, false));
when(storage.getConfig(isA(CollectingExternalConfigMapper.class)))
.thenReturn(new AuthConfigSet<CollectingExternalConfig>(
new AuthConfig(false, providers, null),
new CollectingExternalConfig(Collections.emptyMap())));
when(storage.getToken(token.getHashedToken())).thenReturn(
StoredToken.getBuilder(TokenType.LOGIN, UUID.randomUUID(), new UserName("baz"))
.withLifeTime(Instant.now(), Instant.now()).build())
.thenReturn(null);
when(storage.getUser(new UserName("baz"))).thenReturn(AuthUser.getBuilder(
new UserName("baz"), new DisplayName("foo"), Instant.ofEpochMilli(20000))
.withIdentity(REMOTE).build()).thenReturn(null);
when(idp.getIdentities("authcode", true)).thenReturn(set(new RemoteIdentity(
new RemoteIdentityID("prov", "id2"),
new RemoteIdentityDetails("user2", "full2", "f2@g.com"))))
.thenReturn(null);
final RemoteIdentity storageRemoteID = new RemoteIdentity(
new RemoteIdentityID("prov", "id2"),
new RemoteIdentityDetails("user2", "full2", "f2@g.com"));
when(storage.getUser(storageRemoteID)).thenReturn(Optional.of(AuthUser.getBuilder(
new UserName("someuser"), new DisplayName("a"), Instant.now()).build()))
.thenReturn(null);
final UUID tokenID = UUID.randomUUID();
when(rand.randomUUID()).thenReturn(tokenID).thenReturn(null);
when(rand.getToken()).thenReturn("sometoken").thenReturn(null);
when(clock.instant()).thenReturn(Instant.ofEpochMilli(10000)).thenReturn(null);
final LinkToken lt = auth.link(token, "prov", "authcode");
assertThat("incorrect linktoken", lt, is(new LinkToken(new TemporaryToken(
tokenID, "sometoken", Instant.ofEpochMilli(10000), 10 * 60 * 1000),
new LinkIdentities(AuthUser.getBuilder(
new UserName("baz"), new DisplayName("foo"), Instant.ofEpochMilli(20000))
.withIdentity(REMOTE).build(),
"prov"))));
verify(storage).storeIdentitiesTemporarily(new TemporaryToken(
tokenID, "sometoken", Instant.ofEpochMilli(10000), 10 * 60 * 1000)
.getHashedToken(),
Collections.emptySet());
verify(storage, never()).link(any(), any());
}
@Test
public void linkWithTokenWith2IDs1Filtered() throws Exception {
final IdentityProvider idp = mock(IdentityProvider.class);
when(idp.getProviderName()).thenReturn("prov");
final TestMocks testauth = initTestMocks(set(idp));
final AuthStorage storage = testauth.storageMock;
final RandomDataGenerator rand = testauth.randGenMock;
final Clock clock = testauth.clockMock;
final Authentication auth = testauth.auth;
AuthenticationTester.setConfigUpdateInterval(auth, -1);
final IncomingToken token = new IncomingToken("foobar");
final Map<String, ProviderConfig> providers = ImmutableMap.of(
"prov", new ProviderConfig(true, false, false));
when(storage.getConfig(isA(CollectingExternalConfigMapper.class)))
.thenReturn(new AuthConfigSet<CollectingExternalConfig>(
new AuthConfig(false, providers, null),
new CollectingExternalConfig(Collections.emptyMap())));
when(storage.getToken(token.getHashedToken())).thenReturn(
StoredToken.getBuilder(TokenType.LOGIN, UUID.randomUUID(), new UserName("baz"))
.withLifeTime(Instant.now(), Instant.now()).build())
.thenReturn(null);
when(storage.getUser(new UserName("baz"))).thenReturn(AuthUser.getBuilder(
new UserName("baz"), new DisplayName("foo"), Instant.ofEpochMilli(20000))
.withIdentity(REMOTE).build()).thenReturn(null);
when(idp.getIdentities("authcode", true)).thenReturn(set(
new RemoteIdentity(new RemoteIdentityID("prov", "id2"),
new RemoteIdentityDetails("user2", "full2", "f2@g.com")),
new RemoteIdentity(new RemoteIdentityID("prov", "id3"),
new RemoteIdentityDetails("user3", "full3", "f3@g.com")),
new RemoteIdentity(new RemoteIdentityID("prov", "id4"),
new RemoteIdentityDetails("user4", "full4", "f4@g.com"))))
.thenReturn(null);
final RemoteIdentity storageRemoteID2 = new RemoteIdentity(
new RemoteIdentityID("prov", "id2"),
new RemoteIdentityDetails("user2", "full2", "f2@g.com"));
final RemoteIdentity storageRemoteID3 = new RemoteIdentity(
new RemoteIdentityID("prov", "id3"),
new RemoteIdentityDetails("user3", "full3", "f3@g.com"));
final RemoteIdentity storageRemoteID4 = new RemoteIdentity(
new RemoteIdentityID("prov", "id4"),
new RemoteIdentityDetails("user4", "full4", "f4@g.com"));
when(storage.getUser(storageRemoteID2)).thenReturn(Optional.of(AuthUser.getBuilder(
new UserName("someuser"), new DisplayName("a"), Instant.now()).build()))
.thenReturn(null);
when(storage.getUser(storageRemoteID3)).thenReturn(Optional.absent())
.thenReturn(null);
when(storage.getUser(storageRemoteID4)).thenReturn(Optional.absent())
.thenReturn(null);
final UUID tokenID = UUID.randomUUID();
when(rand.randomUUID()).thenReturn(tokenID).thenReturn(null);
when(rand.getToken()).thenReturn("sometoken").thenReturn(null);
when(clock.instant()).thenReturn(Instant.ofEpochMilli(10000)).thenReturn(null);
final LinkToken lt = auth.link(token, "prov", "authcode");
assertThat("incorrect linktoken", lt, is(new LinkToken(new TemporaryToken(
tokenID, "sometoken", Instant.ofEpochMilli(10000), 10 * 60 * 1000),
new LinkIdentities(AuthUser.getBuilder(
new UserName("baz"), new DisplayName("foo"), Instant.ofEpochMilli(20000))
.withIdentity(REMOTE).build(),
set(storageRemoteID3, storageRemoteID4)))));
verify(storage).storeIdentitiesTemporarily(new TemporaryToken(
tokenID, "sometoken", Instant.ofEpochMilli(10000), 10 * 60 * 1000)
.getHashedToken(),
set(storageRemoteID3, storageRemoteID4));
verify(storage, never()).link(any(), any());
}
@Test
public void linkWithTokenFailNullsAndEmpties() throws Exception {
final IdentityProvider idp = mock(IdentityProvider.class);
when(idp.getProviderName()).thenReturn("prov");
final TestMocks testauth = initTestMocks(set(idp));
final AuthStorage storage = testauth.storageMock;
final Authentication auth = testauth.auth;
AuthenticationTester.setConfigUpdateInterval(auth, -1);
final IncomingToken token = new IncomingToken("foobar");
final Map<String, ProviderConfig> providers = ImmutableMap.of(
"prov", new ProviderConfig(true, false, false));
when(storage.getConfig(isA(CollectingExternalConfigMapper.class)))
.thenReturn(new AuthConfigSet<CollectingExternalConfig>(
new AuthConfig(false, providers, null),
new CollectingExternalConfig(Collections.emptyMap())));
when(storage.getToken(token.getHashedToken())).thenReturn(
StoredToken.getBuilder(TokenType.LOGIN, UUID.randomUUID(), new UserName("baz"))
.withLifeTime(Instant.now(), Instant.now()).build());
when(storage.getUser(new UserName("baz"))).thenReturn(AuthUser.getBuilder(
new UserName("baz"), new DisplayName("foo"), Instant.ofEpochMilli(20000))
.withIdentity(REMOTE).build());
failLinkWithToken(auth, null, "prov", "foo", new NullPointerException("token"));
failLinkWithToken(auth, token, null, "foo", new NullPointerException("provider"));
failLinkWithToken(auth, token, " \t ", "foo",
new NoSuchIdentityProviderException(" \t "));
failLinkWithToken(auth, token, "prov", null,
new MissingParameterException("authorization code"));
failLinkWithToken(auth, token, "prov", " \n ",
new MissingParameterException("authorization code"));
}
@Test
public void linkWithTokenFailNoProvider() throws Exception {
final IdentityProvider idp = mock(IdentityProvider.class);
when(idp.getProviderName()).thenReturn("prov");
final Authentication auth = initTestMocks(set(idp)).auth;
final IncomingToken token = new IncomingToken("foobar");
failLinkWithToken(auth, token, "prov1", "foo",
new NoSuchIdentityProviderException("prov1"));
}
@Test
public void linkWithTokenFailNoProviderInConfig() throws Exception {
/* this case indicates a programming error, a provider should never be in the internal
* Authorization class state but not in the config in the db
*/
final IdentityProvider idp = mock(IdentityProvider.class);
when(idp.getProviderName()).thenReturn("Prov");
final TestMocks testauth = initTestMocks(set(idp));
final AuthStorage storage = testauth.storageMock;
final Authentication auth = testauth.auth;
AuthenticationTester.setConfigUpdateInterval(auth, -1);
final IncomingToken token = new IncomingToken("foobar");
final Map<String, ProviderConfig> providers = ImmutableMap.of(
"prov1", new ProviderConfig(true, false, false));
when(storage.getConfig(isA(CollectingExternalConfigMapper.class)))
.thenReturn(new AuthConfigSet<CollectingExternalConfig>(
new AuthConfig(false, providers, null),
new CollectingExternalConfig(Collections.emptyMap())));
failLinkWithToken(auth, token, "prov", "foo",
new NoSuchIdentityProviderException("Prov"));
}
@Test
public void linkWithTokenFailDisabledProvider() throws Exception {
/* this case indicates a programming error, a provider should never be in the internal
* Authorization class state but not in the config in the db
*/
final IdentityProvider idp = mock(IdentityProvider.class);
when(idp.getProviderName()).thenReturn("Prov");
final TestMocks testauth = initTestMocks(set(idp));
final AuthStorage storage = testauth.storageMock;
final Authentication auth = testauth.auth;
AuthenticationTester.setConfigUpdateInterval(auth, -1);
final IncomingToken token = new IncomingToken("foobar");
final Map<String, ProviderConfig> providers = ImmutableMap.of(
"Prov", new ProviderConfig(false, false, false));
when(storage.getConfig(isA(CollectingExternalConfigMapper.class)))
.thenReturn(new AuthConfigSet<CollectingExternalConfig>(
new AuthConfig(false, providers, null),
new CollectingExternalConfig(Collections.emptyMap())));
failLinkWithToken(auth, token, "prov", "foo",
new NoSuchIdentityProviderException("prov"));
}
@Test
public void linkWithTokenFailBadToken() throws Exception {
final IdentityProvider idp = mock(IdentityProvider.class);
when(idp.getProviderName()).thenReturn("Prov");
final TestMocks testauth = initTestMocks(set(idp));
final AuthStorage storage = testauth.storageMock;
final Authentication auth = testauth.auth;
AuthenticationTester.setConfigUpdateInterval(auth, -1);
final IncomingToken token = new IncomingToken("foobar");
final Map<String, ProviderConfig> providers = ImmutableMap.of(
"Prov", new ProviderConfig(true, false, false));
when(storage.getConfig(isA(CollectingExternalConfigMapper.class)))
.thenReturn(new AuthConfigSet<CollectingExternalConfig>(
new AuthConfig(false, providers, null),
new CollectingExternalConfig(Collections.emptyMap())));
when(storage.getToken(token.getHashedToken())).thenThrow(new NoSuchTokenException("foo"));
failLinkWithToken(auth, token, "prov", "foo", new InvalidTokenException());
}
@Test
public void linkWithTokenFailBadTokenType() throws Exception {
final IdentityProvider idp = mock(IdentityProvider.class);
when(idp.getProviderName()).thenReturn("Prov");
final TestMocks testauth = initTestMocks(set(idp));
final AuthStorage storage = testauth.storageMock;
final Authentication auth = testauth.auth;
AuthenticationTester.setConfigUpdateInterval(auth, -1);
final IncomingToken token = new IncomingToken("foobar");
final Map<String, ProviderConfig> providers = ImmutableMap.of(
"Prov", new ProviderConfig(true, false, false));
when(storage.getConfig(isA(CollectingExternalConfigMapper.class)))
.thenReturn(new AuthConfigSet<CollectingExternalConfig>(
new AuthConfig(false, providers, null),
new CollectingExternalConfig(Collections.emptyMap())));
when(storage.getToken(token.getHashedToken())).thenReturn(
StoredToken.getBuilder(TokenType.AGENT, UUID.randomUUID(), new UserName("f"))
.withLifeTime(Instant.now(), 0).build(),
StoredToken.getBuilder(TokenType.DEV, UUID.randomUUID(), new UserName("f"))
.withLifeTime(Instant.now(), 0).build(),
StoredToken.getBuilder(TokenType.SERV, UUID.randomUUID(), new UserName("f"))
.withLifeTime(Instant.now(), 0).build(),
null);
failLinkWithToken(auth, token, "prov", "foo", new UnauthorizedException(
ErrorType.UNAUTHORIZED, "Agent tokens are not allowed for this operation"));
failLinkWithToken(auth, token, "prov", "foo", new UnauthorizedException(
ErrorType.UNAUTHORIZED, "Developer tokens are not allowed for this operation"));
failLinkWithToken(auth, token, "prov", "foo", new UnauthorizedException(
ErrorType.UNAUTHORIZED, "Service tokens are not allowed for this operation"));
}
@Test
public void linkWithTokenFailNoUserForToken() throws Exception {
final IdentityProvider idp = mock(IdentityProvider.class);
when(idp.getProviderName()).thenReturn("Prov");
final TestMocks testauth = initTestMocks(set(idp));
final AuthStorage storage = testauth.storageMock;
final Authentication auth = testauth.auth;
AuthenticationTester.setConfigUpdateInterval(auth, -1);
final IncomingToken token = new IncomingToken("foobar");
final Map<String, ProviderConfig> providers = ImmutableMap.of(
"Prov", new ProviderConfig(true, false, false));
when(storage.getConfig(isA(CollectingExternalConfigMapper.class)))
.thenReturn(new AuthConfigSet<CollectingExternalConfig>(
new AuthConfig(false, providers, null),
new CollectingExternalConfig(Collections.emptyMap())));
when(storage.getToken(token.getHashedToken())).thenReturn(
StoredToken.getBuilder(TokenType.LOGIN, UUID.randomUUID(), new UserName("foo"))
.withLifeTime(Instant.now(), 0).build())
.thenReturn(null);
when(storage.getUser(new UserName("foo"))).thenThrow(new NoSuchUserException("foo"));
failLinkWithToken(auth, token, "prov", "foo", new RuntimeException(
"There seems to be an error in the storage system. Token was valid, but no user"));
}
@Test
public void linkWithTokenFailDisabledUser() throws Exception {
final IdentityProvider idp = mock(IdentityProvider.class);
when(idp.getProviderName()).thenReturn("Prov");
final TestMocks testauth = initTestMocks(set(idp));
final AuthStorage storage = testauth.storageMock;
final Authentication auth = testauth.auth;
AuthenticationTester.setConfigUpdateInterval(auth, -1);
final IncomingToken token = new IncomingToken("foobar");
final Map<String, ProviderConfig> providers = ImmutableMap.of(
"Prov", new ProviderConfig(true, false, false));
when(storage.getConfig(isA(CollectingExternalConfigMapper.class)))
.thenReturn(new AuthConfigSet<CollectingExternalConfig>(
new AuthConfig(false, providers, null),
new CollectingExternalConfig(Collections.emptyMap())));
when(storage.getToken(token.getHashedToken())).thenReturn(
StoredToken.getBuilder(TokenType.LOGIN, UUID.randomUUID(), new UserName("foo"))
.withLifeTime(Instant.now(), 0).build())
.thenReturn(null);
when(storage.getUser(new UserName("foo"))).thenReturn(AuthUser.getBuilder(
new UserName("foo"), new DisplayName("f"), Instant.now())
.withIdentity(REMOTE).withUserDisabledState(
new UserDisabledState("f", new UserName("b"), Instant.now())).build());
failLinkWithToken(auth, token, "prov", "foo", new DisabledUserException());
verify(storage).deleteTokens(new UserName("foo"));
}
@Test
public void linkWithTokenFailLocalUser() throws Exception {
final IdentityProvider idp = mock(IdentityProvider.class);
when(idp.getProviderName()).thenReturn("Prov");
final TestMocks testauth = initTestMocks(set(idp));
final AuthStorage storage = testauth.storageMock;
final Authentication auth = testauth.auth;
AuthenticationTester.setConfigUpdateInterval(auth, -1);
final IncomingToken token = new IncomingToken("foobar");
final Map<String, ProviderConfig> providers = ImmutableMap.of(
"Prov", new ProviderConfig(true, false, false));
when(storage.getConfig(isA(CollectingExternalConfigMapper.class)))
.thenReturn(new AuthConfigSet<CollectingExternalConfig>(
new AuthConfig(false, providers, null),
new CollectingExternalConfig(Collections.emptyMap())));
when(storage.getToken(token.getHashedToken())).thenReturn(
StoredToken.getBuilder(TokenType.LOGIN, UUID.randomUUID(), new UserName("foo"))
.withLifeTime(Instant.now(), 0).build())
.thenReturn(null);
when(storage.getUser(new UserName("foo"))).thenReturn(AuthUser.getBuilder(
new UserName("foo"), new DisplayName("f"), Instant.now()).build());
failLinkWithToken(auth, token, "prov", "foo",
new LinkFailedException("Cannot link identities to local accounts"));
}
@Test
public void linkWithTokenFailIDRetrievalFailed() throws Exception {
final IdentityProvider idp = mock(IdentityProvider.class);
when(idp.getProviderName()).thenReturn("Prov");
final TestMocks testauth = initTestMocks(set(idp));
final AuthStorage storage = testauth.storageMock;
final Authentication auth = testauth.auth;
AuthenticationTester.setConfigUpdateInterval(auth, -1);
final IncomingToken token = new IncomingToken("foobar");
final Map<String, ProviderConfig> providers = ImmutableMap.of(
"Prov", new ProviderConfig(true, false, false));
when(storage.getConfig(isA(CollectingExternalConfigMapper.class)))
.thenReturn(new AuthConfigSet<CollectingExternalConfig>(
new AuthConfig(false, providers, null),
new CollectingExternalConfig(Collections.emptyMap())));
when(storage.getToken(token.getHashedToken())).thenReturn(
StoredToken.getBuilder(TokenType.LOGIN, UUID.randomUUID(), new UserName("foo"))
.withLifeTime(Instant.now(), 0).build())
.thenReturn(null);
when(storage.getUser(new UserName("foo"))).thenReturn(AuthUser.getBuilder(
new UserName("foo"), new DisplayName("f"), Instant.now())
.withIdentity(REMOTE).build());
when(idp.getIdentities("foo", true)).thenThrow(new IdentityRetrievalException("oh poop"));
failLinkWithToken(auth, token, "prov", "foo", new IdentityRetrievalException("oh poop"));
}
@Test
public void linkWithTokenFailNoSuchUserOnLink() throws Exception {
/* another one that should be impossible */
final IdentityProvider idp = mock(IdentityProvider.class);
when(idp.getProviderName()).thenReturn("Prov");
final TestMocks testauth = initTestMocks(set(idp));
final AuthStorage storage = testauth.storageMock;
final Authentication auth = testauth.auth;
AuthenticationTester.setConfigUpdateInterval(auth, -1);
final IncomingToken token = new IncomingToken("foobar");
final Map<String, ProviderConfig> providers = ImmutableMap.of(
"Prov", new ProviderConfig(true, false, false));
when(storage.getConfig(isA(CollectingExternalConfigMapper.class)))
.thenReturn(new AuthConfigSet<CollectingExternalConfig>(
new AuthConfig(false, providers, null),
new CollectingExternalConfig(Collections.emptyMap())));
when(storage.getToken(token.getHashedToken())).thenReturn(
StoredToken.getBuilder(TokenType.LOGIN, UUID.randomUUID(), new UserName("baz"))
.withLifeTime(Instant.now(), Instant.now()).build())
.thenReturn(null);
when(storage.getUser(new UserName("baz"))).thenReturn(AuthUser.getBuilder(
new UserName("baz"), new DisplayName("foo"), Instant.ofEpochMilli(20000))
.withIdentity(REMOTE).build()).thenReturn(null);
when(idp.getIdentities("authcode", true)).thenReturn(set(new RemoteIdentity(
new RemoteIdentityID("Prov", "id2"),
new RemoteIdentityDetails("user2", "full2", "f2@g.com"))))
.thenReturn(null);
final RemoteIdentity storageRemoteID = new RemoteIdentity(
new RemoteIdentityID("Prov", "id2"),
new RemoteIdentityDetails("user2", "full2", "f2@g.com"));
when(storage.getUser(storageRemoteID)).thenReturn(Optional.absent()).thenReturn(null);
doThrow(new NoSuchUserException("baz"))
.when(storage).link(new UserName("baz"), storageRemoteID);
failLinkWithToken(auth, token, "prov", "authcode", new AuthStorageException(
"User unexpectedly disappeared from the database"));
}
@Test
public void linkWithTokenFailLinkFailedOnLink() throws Exception {
/* another one that should be impossible */
final IdentityProvider idp = mock(IdentityProvider.class);
when(idp.getProviderName()).thenReturn("Prov");
final TestMocks testauth = initTestMocks(set(idp));
final AuthStorage storage = testauth.storageMock;
final Authentication auth = testauth.auth;
AuthenticationTester.setConfigUpdateInterval(auth, -1);
final IncomingToken token = new IncomingToken("foobar");
final Map<String, ProviderConfig> providers = ImmutableMap.of(
"Prov", new ProviderConfig(true, false, false));
when(storage.getConfig(isA(CollectingExternalConfigMapper.class)))
.thenReturn(new AuthConfigSet<CollectingExternalConfig>(
new AuthConfig(false, providers, null),
new CollectingExternalConfig(Collections.emptyMap())));
when(storage.getToken(token.getHashedToken())).thenReturn(
StoredToken.getBuilder(TokenType.LOGIN, UUID.randomUUID(), new UserName("baz"))
.withLifeTime(Instant.now(), Instant.now()).build())
.thenReturn(null);
when(storage.getUser(new UserName("baz"))).thenReturn(AuthUser.getBuilder(
new UserName("baz"), new DisplayName("foo"), Instant.ofEpochMilli(20000))
.withIdentity(REMOTE).build()).thenReturn(null);
when(idp.getIdentities("authcode", true)).thenReturn(set(new RemoteIdentity(
new RemoteIdentityID("Prov", "id2"),
new RemoteIdentityDetails("user2", "full2", "f2@g.com"))))
.thenReturn(null);
final RemoteIdentity storageRemoteID = new RemoteIdentity(
new RemoteIdentityID("Prov", "id2"),
new RemoteIdentityDetails("user2", "full2", "f2@g.com"));
when(storage.getUser(storageRemoteID)).thenReturn(Optional.absent()).thenReturn(null);
doThrow(new LinkFailedException("doodoo"))
.when(storage).link(new UserName("baz"), storageRemoteID);
failLinkWithToken(auth, token, "prov", "authcode", new LinkFailedException("doodoo"));
}
private void failLinkWithToken(
final Authentication auth,
final IncomingToken token,
final String provider,
final String authcode,
final Exception e) {
try {
auth.link(token, provider, authcode);
fail("exception expected");
} catch (Exception got) {
TestCommon.assertExceptionCorrect(got, e);
}
}
}
|
import java.net.DatagramPacket;
import java.security.SecureRandom;
public class ID {
private static int idLengthInBytes = 16;
private static LinkedListQueue idQueue = new LinkedListQueue();
private static int maxQueueLength = 50;
private static int queueLength = 0;
private static SecureRandom secureRandom = new SecureRandom();
private static ID zeroID = ID.createZeroID();
private byte[] id;
private ID()
{
this.id = new byte[ID.getLengthInBytes()];
ID.secureRandom.nextBytes(this.id);
}
/**
* Constructs a new ID by using the input byte array as the ID.
* @param byteArray
*/
public ID (byte[] byteArray)
{
if(byteArray == null) {
throw new IllegalArgumentException("The byte array that you provided is null");
}
if(byteArray.length != idLengthInBytes)
{
throw new IllegalArgumentException("Byte array has to be exactly "+ID.idLengthInBytes+ " bytes long. You"
+ "privoded (" + byteArray.length + ")");
}
this.id = byteArray.clone();
}
public ID(DatagramPacket packet, int startingByte) {
// Check if packet is null
if(packet == null) {
throw new IllegalArgumentException("The packet that you sent is null");
}
// Check the starting byte
if(startingByte < 0) {
throw new IllegalArgumentException("The starting byte that you provided "
+ "(" + startingByte + ") is less than 0");
}
if(startingByte > packet.getData().length) {
throw new IllegalArgumentException("The starting byte that you provided "
+ "(" + startingByte + ") is greater than the length of the packet that"
+ "you sent");
}
this.id = new byte[ID.idLengthInBytes];
System.arraycopy(packet, startingByte, this.id, 0, ID.idLengthInBytes);
}
// public ID(String hexString) {
// if(hexString == null) {
/**
* Checks if the queue length is equal to 0. If so, returns an ID from the queue. If not, constructs a new ID.
* @return
* A return ID.
*/
public synchronized static ID idFactory()
{
// TODO How is this used
ID returnID;
if(ID.queueLength==0)
{
returnID = new ID();
}else{
returnID = (ID) ID.getQueue().deQueue();
ID.queueLength = ID.queueLength - 1;
}
return returnID;
}
/**
* Creates a ID consisting entirely of zeros.
* @return
* An id consisting entirely of zeros.
*/
private static ID createZeroID()
{
byte[] zeroByteArray = new byte[idLengthInBytes];
for(int i = 0; i< idLengthInBytes;i++)
{
zeroByteArray[i] = 0;
}
return new ID(zeroByteArray);
}
/**
* Generates an ID if the queue has enough space for a new one.
*/
public static synchronized void generateID()
{
// TODO fill the queue?
if(ID.queueLength<ID.maxQueueLength)
{
ID.idQueue.enQueue(new ID());
ID.queueLength++;
}
}
public String getAsHex() {
String hex = "0x";
String tmp = "";
for(byte singleByte : this.id) {
tmp = Integer.toHexString(singleByte);
if(tmp.length() < 2) {
tmp = "0" + tmp;
}
hex = hex + tmp;
}
return hex;
}
/**
* Return the length in bytes
* @return
*/
public synchronized static int getLengthInBytes() {
return ID.idLengthInBytes;
}
/**
* Basic getter for the queue containing IDs.
* @return
* A SynchronizedLinkedListQueue containing a list of IDs.
*/
public static synchronized LinkedListQueue getQueue()
{
return ID.idQueue;
}
/**
* Basic getter.
* @return
* Returns the max queue length as determined by the maxQueueLength static variable.
*/
public static synchronized int getMaxQueueLength()
{
return ID.maxQueueLength;
}
/**
* Basic getter.
* @return
* The current queue length.
*/
public synchronized static int getQueueLength() {
return ID.queueLength;
}
/**
* Basic getter.
* @return
* The zero id.
*/
public static ID getZeroID()
{
return ID.zeroID;
}
/**
* Set the length in bytes
* @param lengthInBytes
*/
public static synchronized void setLengthInBytes(int lengthInBytes) {
if(lengthInBytes < 1) {
throw new IllegalArgumentException("The length in bytes that you provided (" + lengthInBytes
+") is less than 1.");
}
ID.idLengthInBytes = lengthInBytes;
}
/**
* Set the max queue length.
* @param maxQueueLength
*/
public static synchronized void setMaxQueueLength(int maxQueueLength)
{
if(maxQueueLength < 0) {
throw new IllegalArgumentException("The max length queue that you provided (" + maxQueueLength
+") is less than 0.");
}
ID.maxQueueLength = maxQueueLength;
}
/**
* Returns the internal byte representation of this ID.
* @return
* The byte array ID.
*/
public byte[] getBytes()
{
return this.id.clone();
}
/**
* Checks to see if two ID objects have the same internal bytes.
*/
@Override
public boolean equals(Object other)
{
// TODO is this how it should be implemented
if(this == other) {
return true;
}
if(other == null || (this.getClass() != other.getClass())) {
return false;
}
// Cast and create an ID object
ID object = (ID) other;
// Check if lengths are different
if(this.id.length != object.getBytes().length) {
return false;
}
for(int i = 0; i < this.id.length; i++) {
if(this.id[i] != object.getBytes()[i]) {
return false;
}
}
return true;
}
/**
* Returns the hashCode of the toString method.
*/
@Override
public int hashCode()
{
// TODO is this right
return this.id.toString().hashCode();
}
/**
* Determines if the current ID is the zero ID.
* @return
* Boolean. True if this object is 0, false otherwise.
*/
public boolean isZero()
{
return this.equals(ID.getZeroID());
}
/**
* Converts each byte to hex, and returns the string consisting of consecutive hex characters.
*/
@Override
public String toString()
{
return this.getAsHex();
}
public boolean isRequestID() {
// TODO
return false;
}
public boolean isResourceID() {
// TODO
return false;
}
}
|
package com.artemis;
import java.util.BitSet;
import java.util.Collection;
import com.artemis.utils.Bag;
/**
* An Aspect is used by systems as a matcher against entities, to check if a
* system is interested in an entity.
* <p>
* Aspects define what sort of component types an entity must possess, or not
* possess.
* </p><p>
* This creates an aspect where an entity must possess A and B and C:<br />
* {@code Aspect.all(A.class, B.class, C.class)}
* </p><p>
* This creates an aspect where an entity must possess A and B and C, but must
* not possess U or V.<br />
* {@code Aspect.all(A.class, B.class, C.class).exclude(U.class, V.class)}
* </p><p>
* This creates an aspect where an entity must possess A and B and C, but must
* not possess U or V, but must possess one of X or Y or Z.<br />
* {@code Aspect.all(A.class, B.class, C.class).exclude(U.class, V.class).one(X.class, Y.class, Z.class)}
* </p><p>
* You can create and compose aspects in many ways:<br />
* {@code Aspect.one(X.class, Y.class, Z.class).all(A.class, B.class, C.class).exclude(U.class, V.class)}<br />
* is the same as:<br />
* {@code Aspect.all(A.class, B.class, C.class).exclude(U.class, V.class).one(X.class, Y.class, Z.class)}
* </p>
*
* @author Arni Arent
*/
public class Aspect {
/** Component bits the entity must all possess. */
private BitSet allSet;
/** Component bits the entity must not possess. */
private BitSet exclusionSet;
/** Component bits of which the entity must possess at least one. */
private BitSet oneSet;
private Aspect() {
this.allSet = new BitSet();
this.exclusionSet = new BitSet();
this.oneSet = new BitSet();
}
/**
* Get a BitSet containing bits of components the entity must all possess.
*
* @return
* the "all" BitSet
*/
public BitSet getAllSet() {
return allSet;
}
/**
* Get a BitSet containing bits of components the entity must not possess.
*
* @return
* the "exclusion" BitSet
*/
public BitSet getExclusionSet() {
return exclusionSet;
}
/**
* Get a BitSet containing bits of components of which the entity must
* possess atleast one.
*
* @return
* the "one" BitSet
*/
public BitSet getOneSet() {
return oneSet;
}
/**
* Returns whether this Aspect would accept the given Entity.
*/
public boolean isInterested(Entity e){
return isInterested(e.getComponentBits());
}
/**
* Returns whether this Aspect would accept the given set.
*/
public boolean isInterested(BitSet componentBits){
// Check if the entity possesses ALL of the components defined in the aspect.
if(!allSet.isEmpty()) {
for (int i = allSet.nextSetBit(0); i >= 0; i = allSet.nextSetBit(i+1)) {
if(!componentBits.get(i)) {
return false;
}
}
}
// If we are STILL interested,
// Check if the entity possesses ANY of the exclusion components, if it does then the system is not interested.
if(!exclusionSet.isEmpty() && exclusionSet.intersects(componentBits)) {
return false;
}
// If we are STILL interested,
// Check if the entity possesses ANY of the components in the oneSet. If so, the system is interested.
if(!oneSet.isEmpty() && !oneSet.intersects(componentBits)) {
return false;
}
return true;
}
/**
* Returns an aspect where an entity must possess all of the specified
* component types.
*
* @param types
* a required component type
*
* @return an aspect that can be matched against entities
*/
@SafeVarargs
public static final Aspect.Builder all(Class<? extends Component>... types) {
return new Builder().all(types);
}
/**
* Returns an aspect where an entity must possess all of the specified
* component types.
*
* @param types
* a required component type
*
* @return an aspect that can be matched against entities
*/
public static Aspect.Builder all(Collection<Class<? extends Component>> types) {
return new Builder().all(types);
}
/**
* Excludes all of the specified component types from the aspect.
* <p>
* A system will not be interested in an entity that possesses one of the
* specified exclusion component types.
* </p>
*
* @param types
* component type to exclude
*
* @return an aspect that can be matched against entities
*/
@SafeVarargs
public static final Aspect.Builder exclude(Class<? extends Component>... types) {
return new Builder().exclude(types);
}
/**
* Excludes all of the specified component types from the aspect.
* <p>
* A system will not be interested in an entity that possesses one of the
* specified exclusion component types.
* </p>
*
* @param types
* component type to exclude
*
* @return an aspect that can be matched against entities
*/
public static Aspect.Builder exclude(Collection<Class<? extends Component>> types) {
return new Builder().exclude(types);
}
/**
* Returns an aspect where an entity must possess one of the specified
* component types.
*
* @param types
* one of the types the entity must possess
*
* @return an aspect that can be matched against entities
*/
@SafeVarargs
public static final Aspect.Builder one(Class<? extends Component>... types) {
return new Builder().one(types);
}
/**
* Returns an aspect where an entity must possess one of the specified
* component types.
*
* @param types
* one of the types the entity must possess
*
* @return an aspect that can be matched against entities
*/
public static Aspect.Builder one(Collection<Class<? extends Component>> types) {
return new Builder().one(types);
}
/**
* Creates an aspect where an entity must possess all of the specified
* component types.
*
* @param types
* a required component type
*
* @return an aspect that can be matched against entities
* @deprecated see {@link #all(Class[])}
*/
@Deprecated
@SafeVarargs
public static final Aspect.Builder getAspectForAll(Class<? extends Component>... types) {
return all(types);
}
/**
* Creates an aspect where an entity must possess one of the specified
* component types.
*
* @param types
* one of the types the entity must possess
*
* @return an aspect that can be matched against entities
* @deprecated see {@link #one(Class[])}
*/
@Deprecated
@SafeVarargs
public static final Aspect.Builder getAspectForOne(Class<? extends Component>... types) {
return one(types);
}
/**
* Creates an aspect that matches all entities.
*
* Prior to version 0.9.0, this method returned an aspect which matched no entities.
*
* @return an empty Aspect that will reject all entities
* @deprecated extend {@link com.artemis.BaseSystem} instead of {@link com.artemis.EntitySystem} for entity-less systems.
*/
@Deprecated
public static Aspect.Builder getEmpty() {
return new Aspect.Builder();
}
public static class Builder {
private final Bag<Class<? extends Component>> allTypes;
private final Bag<Class<? extends Component>> exclusionTypes;
private final Bag<Class<? extends Component>> oneTypes;
private Builder() {
allTypes = new Bag<Class<? extends Component>>();
exclusionTypes = new Bag<Class<? extends Component>>();
oneTypes = new Bag<Class<? extends Component>>();
}
/**
* Returns an aspect where an entity must possess all of the specified
* component types.
*
* @param types
* a required component type
*
* @return an aspect that can be matched against entities
*/
public Builder all(Class<? extends Component>... types) {
for (Class<? extends Component> t : types) {
allTypes.add(t);
}
return this;
}
public Builder copy() {
Builder b = new Builder();
b.allTypes.addAll(allTypes);
b.exclusionTypes.addAll(exclusionTypes);
b.oneTypes.addAll(oneTypes);
return b;
}
/**
* Returns an aspect where an entity must possess all of the specified
* component types.
*
* @param types
* a required component type
*
* @return an aspect that can be matched against entities
*/
public Builder all(Collection<Class<? extends Component>> types) {
for (Class<? extends Component> t : types) {
allTypes.add(t);
}
return this;
}
/**
* Returns an aspect where an entity must possess one of the specified
* component types.
*
* @param types
* one of the types the entity must possess
*
* @return an aspect that can be matched against entities
*/
public Builder one(Class<? extends Component>... types) {
for (Class<? extends Component> t : types)
oneTypes.add(t);
return this;
}
/**
* Returns an aspect where an entity must possess one of the specified
* component types.
*
* @param types
* one of the types the entity must possess
*
* @return an aspect that can be matched against entities
*/
public Builder one(Collection<Class<? extends Component>> types) {
for (Class<? extends Component> t : types)
oneTypes.add(t);
return this;
}
/**
* Excludes all of the specified component types from the aspect.
* <p>
* A system will not be interested in an entity that possesses one of the
* specified exclusion component types.
* </p>
*
* @param types
* component type to exclude
*
* @return an aspect that can be matched against entities
*/
public Builder exclude(Class<? extends Component>... types) {
for (Class<? extends Component> t : types)
exclusionTypes.add(t);
return this;
}
/**
* Excludes all of the specified component types from the aspect.
* <p>
* A system will not be interested in an entity that possesses one of the
* specified exclusion component types.
* </p>
*
* @param types
* component type to exclude
*
* @return an aspect that can be matched against entities
*/
public Builder exclude(Collection<Class<? extends Component>> types) {
for (Class<? extends Component> t : types)
exclusionTypes.add(t);
return this;
}
public Aspect build(World world) {
ComponentTypeFactory tf = world.getComponentManager().typeFactory;
Aspect aspect = new Aspect();
associate(tf, allTypes, aspect.allSet);
associate(tf, exclusionTypes, aspect.exclusionSet);
associate(tf, oneTypes, aspect.oneSet);
return aspect;
}
private static void associate(ComponentTypeFactory tf, Bag<Class<? extends Component>> types, BitSet componentBits) {
for (Class<? extends Component> t : types) {
componentBits.set(tf.getIndexFor(t));
}
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Builder builder = (Builder) o;
if (!allTypes.equals(builder.allTypes))
return false;
if (!exclusionTypes.equals(builder.exclusionTypes))
return false;
if (!oneTypes.equals(builder.oneTypes))
return false;
return true;
}
@Override
public int hashCode() {
int result = allTypes.hashCode();
result = 31 * result + exclusionTypes.hashCode();
result = 31 * result + oneTypes.hashCode();
return result;
}
}
}
|
package mod._sc;
import java.io.PrintWriter;
import lib.StatusException;
import lib.TestCase;
import lib.TestEnvironment;
import lib.TestParameters;
import util.SOfficeFactory;
import com.sun.star.beans.XPropertySet;
import com.sun.star.container.XIndexAccess;
import com.sun.star.container.XNameContainer;
import com.sun.star.lang.XComponent;
import com.sun.star.lang.XMultiServiceFactory;
import com.sun.star.sheet.XSpreadsheet;
import com.sun.star.sheet.XSpreadsheetDocument;
import com.sun.star.sheet.XSpreadsheets;
import com.sun.star.uno.AnyConverter;
import com.sun.star.uno.Type;
import com.sun.star.uno.UnoRuntime;
import com.sun.star.uno.XInterface;
import ifc.sheet._XCellRangesQuery;
/**
* Test for object which is represented by service
* <code>com.sun.star.sheet.SheetCellRanges</code>. <p>
* Object implements the following interfaces :
* <ul>
* <li> <code>com::sun::star::table::CellProperties</code></li>
* <li> <code>com::sun::star::container::XNameReplace</code></li>
* <li> <code>com::sun::star::container::XNameContainer</code></li>
* <li> <code>com::sun::star::beans::XPropertySet</code></li>
* <li> <code>com::sun::star::container::XIndexAccess</code></li>
* <li> <code>com::sun::star::container::XElementAccess</code></li>
* <li> <code>com::sun::star::container::XEnumerationAccess</code></li>
* <li> <code>com::sun::star::sheet::XSheetCellRangeContainer</code></li>
* <li> <code>com::sun::star::sheet::XSheetOperation</code></li>
* <li> <code>com::sun::star::sheet::XSheetCellRanges</code></li>
* <li> <code>com::sun::star::container::XNameAccess</code></li>
* </ul>
* @see com.sun.star.sheet.SheetCellRanges
* @see com.sun.star.table.CellProperties
* @see com.sun.star.container.XNameReplace
* @see com.sun.star.container.XNameContainer
* @see com.sun.star.beans.XPropertySet
* @see com.sun.star.container.XIndexAccess
* @see com.sun.star.container.XElementAccess
* @see com.sun.star.container.XEnumerationAccess
* @see com.sun.star.sheet.XSheetCellRangeContainer
* @see com.sun.star.sheet.XSheetOperation
* @see com.sun.star.sheet.XSheetCellRanges
* @see com.sun.star.container.XNameAccess
* @see ifc.table._CellProperties
* @see ifc.container._XNameReplace
* @see ifc.container._XNameContainer
* @see ifc.beans._XPropertySet
* @see ifc.container._XIndexAccess
* @see ifc.container._XElementAccess
* @see ifc.container._XEnumerationAccess
* @see ifc.sheet._XSheetCellRangeContainer
* @see ifc.sheet._XSheetOperation
* @see ifc.sheet._XSheetCellRanges
* @see ifc.container._XNameAccess
*/
public class ScCellRangesObj extends TestCase {
static XSpreadsheetDocument xSheetDoc = null;
/**
* Creates Spreadsheet document.
*/
protected void initialize( TestParameters tParam, PrintWriter log ) {
// get a soffice factory object
SOfficeFactory SOF = SOfficeFactory.getFactory( (XMultiServiceFactory)tParam.getMSF());
try {
log.println( "creating a sheetdocument" );
xSheetDoc = SOF.createCalcDoc(null);;
} catch (com.sun.star.uno.Exception e) {
// Some exception occures.FAILED
e.printStackTrace( log );
throw new StatusException( "Couldn't create document", e );
}
}
/**
* Disposes Spreadsheet document.
*/
protected void cleanup( TestParameters tParam, PrintWriter log ) {
log.println( " disposing xSheetDoc " );
XComponent oComp =
(XComponent) UnoRuntime.queryInterface (XComponent.class, xSheetDoc);
util.DesktopTools.closeDoc(oComp);
}
/**
* Creating a Testenvironment for the interfaces to be tested.
* Creates an instance of the service
* <code>com.sun.star.sheet.SheetCellRanges</code> and fills some cells.
* Object relations created :
* <ul>
* <li> <code>'INSTANCE1', ..., 'INSTANCEN'</code> for
* {@link ifc.container._XNameReplace},
* {@link ifc.container._XNameContainer} (type of
* <code>XCellRange</code>)</li>
* <li> <code>'THRCNT'</code> for
* {@link ifc.container._XNameReplace}(the number of the running threads
* that was retrieved from the method parameter <code>Param</code>)</li>
* <li> <code>'NameReplaceIndex'</code> for
* {@link ifc.container._XNameReplace} </li>
* </ul>
* @see com.sun.star.table.XCellRange
*/
protected synchronized TestEnvironment createTestEnvironment(TestParameters Param, PrintWriter log) {
XInterface oObj = null;
Object oRange = null ;
// creation of testobject here
// first we write what we are intend to do to log file
log.println( "Creating a test environment" );
// get a soffice factory object
SOfficeFactory SOF = SOfficeFactory.getFactory( (XMultiServiceFactory)Param.getMSF() );
log.println("Getting test object ");
XComponent oComp = (XComponent)
UnoRuntime.queryInterface (XComponent.class, xSheetDoc);
oObj = (XInterface)
SOF.createInstance(oComp, "com.sun.star.sheet.SheetCellRanges");
XSpreadsheets oSheets = xSheetDoc.getSheets() ;
XIndexAccess oIndSheets = (XIndexAccess)
UnoRuntime.queryInterface (XIndexAccess.class, oSheets);
XSpreadsheet oSheet = null;
try {
oSheet = (XSpreadsheet) AnyConverter.toObject(
new Type(XSpreadsheet.class), oIndSheets.getByIndex(0));
XNameContainer oRanges = (XNameContainer)
UnoRuntime.queryInterface(XNameContainer.class, oObj);
oRange = oSheet.getCellRangeByName("C1:D4");
oRanges.insertByName("Range1", oRange);
oRange = oSheet.getCellRangeByName("E2:F5");
oRanges.insertByName("Range2", oRange);
oRange = oSheet.getCellRangeByName("G2:H3");
oRanges.insertByName("Range3", oRange);
oRange = oSheet.getCellRangeByName("I7:J8");
oRanges.insertByName("Range4", oRange);
} catch(com.sun.star.lang.WrappedTargetException e) {
e.printStackTrace(log);
throw new StatusException("Couldn't create test object", e);
} catch(com.sun.star.lang.IndexOutOfBoundsException e) {
e.printStackTrace(log);
throw new StatusException("Couldn't create test object", e);
} catch(com.sun.star.container.ElementExistException e) {
e.printStackTrace(log);
throw new StatusException("Couldn't create test object", e);
} catch(com.sun.star.lang.IllegalArgumentException e) {
e.printStackTrace(log);
throw new StatusException("Couldn't create test object", e);
}
log.println("filling some cells");
try {
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 5; j++) {
oSheet.getCellByPosition(i, j).setFormula("a");
}
}
for (int i = 0; i < 10; i++) {
for (int j = 5; j < 10; j++) {
oSheet.getCellByPosition(i, j).setValue(i + j);
}
}
} catch (com.sun.star.lang.IndexOutOfBoundsException e) {
e.printStackTrace(log);
throw new StatusException (
"Exception occurred while filling cells", e);
}
TestEnvironment tEnv = new TestEnvironment( oObj );
// NameReplaceIndex : _XNameReplace
log.println( "adding NameReplaceIndex as mod relation to environment" );
tEnv.addObjRelation("NameReplaceIndex", "0");
// INSTANCEn : _XNameContainer; _XNameReplace
log.println( "adding INSTANCEn as mod relation to environment" );
int THRCNT = 1;
if ((String)Param.get("THRCNT") != null) {
THRCNT= Integer.parseInt((String)Param.get("THRCNT"));
}
int a = 0;
int b = 0;
for (int n = 1; n < (THRCNT + 1) ; n++) {
a = n * 2;
b = a + 1;
oRange = oSheet.getCellRangeByName("A" + a + ":B" + b);
log.println(
"adding INSTANCE" + n + " as mod relation to environment" );
tEnv.addObjRelation("INSTANCE" + n, oRange);
}
XPropertySet PropSet = (XPropertySet)
UnoRuntime.queryInterface(XPropertySet.class, oObj);
tEnv.addObjRelation("PropSet",PropSet);
tEnv.addObjRelation("SHEET", oSheet);
// add expected results for the XCellRangesQuery interface test
String[]expectedResults = new String[7];
expectedResults[_XCellRangesQuery.QUERYCOLUMNDIFFERENCES] = "Sheet1.I7:J8";
expectedResults[_XCellRangesQuery.QUERYCONTENTCELLS] = "";
expectedResults[_XCellRangesQuery.QUERYEMPTYCELLS] = "";
expectedResults[_XCellRangesQuery.QUERYFORMULACELLS] = "";
expectedResults[_XCellRangesQuery.QUERYINTERSECTION] = "Sheet1.D4";
expectedResults[_XCellRangesQuery.QUERYROWDIFFERENCES] = "Sheet1.I7:J8";
expectedResults[_XCellRangesQuery.QUERYVISIBLECELLS] = "Sheet1.C2:D4"; // first range, first line invisible
tEnv.addObjRelation("XCellRangesQuery.EXPECTEDRESULTS", expectedResults);
// for XSearchable and XReplaceable interface test
tEnv.addObjRelation("SEARCHSTRING", "15");
// for XFormulaQuery interface test
tEnv.addObjRelation("EXPECTEDDEPENDENTVALUES", new int[]{4,5,1,4});
tEnv.addObjRelation("EXPECTEDPRECEDENTVALUES", new int[]{4,5,1,4});
return tEnv ;
}
} // finish class ScCellRangesObj
|
import java.util.Date;
import com.sun.star.awt.XToolkit;
import com.sun.star.beans.PropertyValue;
import com.sun.star.frame.XDesktop;
import com.sun.star.frame.XFrame;
import com.sun.star.frame.XFramesSupplier;
import com.sun.star.lang.WrappedTargetException;
import com.sun.star.lang.XComponent;
import com.sun.star.lang.XMultiComponentFactory;
import com.sun.star.lang.XMultiServiceFactory;
import com.sun.star.sheet.XSpreadsheetDocument;
import com.sun.star.text.XTextDocument;
import com.sun.star.uno.Any;
import com.sun.star.uno.UnoRuntime;
import com.sun.star.uno.XComponentContext;
import com.sun.star.uno.XNamingService;
import com.sun.star.util.XURLTransformer;
import com.sun.star.lang.Locale;
import com.sun.star.uno.XInterface;
import com.sun.star.bridge.XUnoUrlResolver;
import com.sun.star.comp.helper.Bootstrap;
import com.sun.star.container.NoSuchElementException;
import com.sun.star.container.XEnumeration;
import com.sun.star.container.XHierarchicalNameAccess;
import com.sun.star.container.XNameAccess;
import com.sun.star.util.XStringSubstitution;
import com.sun.star.frame.*;
import com.sun.star.i18n.KParseType;
import com.sun.star.i18n.ParseResult;
import com.sun.star.i18n.XCharacterClassification;
public class Desktop {
/** Creates a new instance of Desktop */
public Desktop() {
}
public static XDesktop getDesktop(XMultiServiceFactory xMSF) {
com.sun.star.uno.XInterface xInterface = null;
XDesktop xDesktop = null;
if (xMSF != null) {
try {
xInterface = (com.sun.star.uno.XInterface) xMSF.createInstance("com.sun.star.frame.Desktop");
xDesktop = (XDesktop) UnoRuntime.queryInterface(XDesktop.class, xInterface);
} catch (Exception exception) {
exception.printStackTrace(System.out);
}
} else
System.out.println("Can't create a desktop. null pointer !");
return xDesktop;
}
public static XFrame getActiveFrame(XMultiServiceFactory xMSF) {
XDesktop xDesktop = getDesktop(xMSF);
XFramesSupplier xFrameSuppl = (XFramesSupplier) UnoRuntime.queryInterface(XFramesSupplier.class, xDesktop);
XFrame xFrame = xFrameSuppl.getActiveFrame();
return xFrame;
}
public static XComponent getActiveComponent(XMultiServiceFactory _xMSF){
XFrame xFrame = getActiveFrame(_xMSF);
return (XComponent) UnoRuntime.queryInterface(XComponent.class, xFrame.getController().getModel());
}
public static XTextDocument getActiveTextDocument(XMultiServiceFactory _xMSF){
XComponent xComponent = getActiveComponent(_xMSF);
return (XTextDocument) UnoRuntime.queryInterface(XTextDocument.class, xComponent);
}
public static XSpreadsheetDocument getActiveSpreadsheetDocument(XMultiServiceFactory _xMSF){
XComponent xComponent = getActiveComponent(_xMSF);
return (XSpreadsheetDocument) UnoRuntime.queryInterface(XSpreadsheetDocument.class, xComponent);
}
public static XDispatch getDispatcher(XMultiServiceFactory xMSF, XFrame xFrame, String _stargetframe, com.sun.star.util.URL oURL) {
try {
com.sun.star.util.URL[] oURLArray = new com.sun.star.util.URL[1];
oURLArray[0] = oURL;
XDispatchProvider xDispatchProvider = (XDispatchProvider) UnoRuntime.queryInterface(XDispatchProvider.class, xFrame);
XDispatch xDispatch = xDispatchProvider.queryDispatch(oURLArray[0], _stargetframe, FrameSearchFlag.ALL); // "_self"
return xDispatch;
} catch (Exception e) {
e.printStackTrace(System.out);
}
return null;
}
public static com.sun.star.util.URL getDispatchURL(XMultiServiceFactory xMSF, String _sURL){
try {
Object oTransformer = xMSF.createInstance("com.sun.star.util.URLTransformer");
XURLTransformer xTransformer = (XURLTransformer) UnoRuntime.queryInterface(XURLTransformer.class, oTransformer);
com.sun.star.util.URL[] oURL = new com.sun.star.util.URL[1];
oURL[0] = new com.sun.star.util.URL();
oURL[0].Complete = _sURL;
xTransformer.parseStrict(oURL);
return oURL[0];
} catch (Exception e) {
e.printStackTrace(System.out);
}
return null;
}
public static void dispatchURL(XMultiServiceFactory xMSF, String sURL, XFrame xFrame, String _stargetframe) {
com.sun.star.util.URL oURL = getDispatchURL(xMSF, sURL);
XDispatch xDispatch = getDispatcher(xMSF, xFrame, _stargetframe, oURL);
dispatchURL(xDispatch, oURL);
}
public static void dispatchURL(XMultiServiceFactory xMSF, String sURL, XFrame xFrame) {
dispatchURL(xMSF, sURL, xFrame, "");
}
public static void dispatchURL(XDispatch _xDispatch, com.sun.star.util.URL oURL ) {
PropertyValue[] oArg = new PropertyValue[0];
_xDispatch.dispatch(oURL, oArg);
}
public static XMultiComponentFactory getMultiComponentFactory() throws com.sun.star.uno.Exception, RuntimeException, java.lang.Exception{
XComponentContext xcomponentcontext = Bootstrap.createInitialComponentContext(null);
// initial serviceManager
return xcomponentcontext.getServiceManager();
}
public static XMultiServiceFactory connect(String connectStr) throws com.sun.star.uno.Exception, com.sun.star.uno.RuntimeException, Exception {
XComponentContext xcomponentcontext = null;
XMultiComponentFactory xMultiComponentFactory = getMultiComponentFactory();
// create a connector, so that it can contact the office
Object xUrlResolver = xMultiComponentFactory.createInstanceWithContext("com.sun.star.bridge.UnoUrlResolver", xcomponentcontext);
XUnoUrlResolver urlResolver = (XUnoUrlResolver) UnoRuntime.queryInterface(XUnoUrlResolver.class, xUrlResolver);
Object rInitialObject = urlResolver.resolve(connectStr);
XNamingService rName = (XNamingService) UnoRuntime.queryInterface(XNamingService.class, rInitialObject);
XMultiServiceFactory xMSF = null;
if (rName != null) {
System.err.println("got the remote naming service !");
Object rXsmgr = rName.getRegisteredObject("StarOffice.ServiceManager");
xMSF = (XMultiServiceFactory) UnoRuntime.queryInterface(XMultiServiceFactory.class, rXsmgr);
}
return (xMSF);
}
public static String getIncrementSuffix(XNameAccess xElementContainer, String ElementName) {
boolean bElementexists = true;
int i = 1;
String sIncSuffix = "";
String BaseName = ElementName;
while (bElementexists == true) {
bElementexists = xElementContainer.hasByName(ElementName);
if (bElementexists == true) {
i += 1;
ElementName = BaseName + Integer.toString(i);
}
}
if (i > 1)
sIncSuffix = Integer.toString(i);
return sIncSuffix;
}
public static String getIncrementSuffix(XHierarchicalNameAccess xElementContainer, String ElementName) {
boolean bElementexists = true;
int i = 1;
String sIncSuffix = "";
String BaseName = ElementName;
while (bElementexists == true) {
bElementexists = xElementContainer.hasByHierarchicalName(ElementName);
if (bElementexists == true) {
i += 1;
ElementName = BaseName + Integer.toString(i);
}
}
if (i > 1)
sIncSuffix = Integer.toString(i);
return sIncSuffix;
}
public static int checkforfirstSpecialCharacter(XMultiServiceFactory _xMSF, String _sString, Locale _aLocale){
try {
int nStartFlags = com.sun.star.i18n.KParseTokens.ANY_LETTER_OR_NUMBER + com.sun.star.i18n.KParseTokens.ASC_UNDERSCORE;
int nContFlags = nStartFlags;
Object ocharservice = _xMSF.createInstance("com.sun.star.i18n.CharacterClassification");
XCharacterClassification xCharacterClassification = (XCharacterClassification) UnoRuntime.queryInterface(XCharacterClassification.class, ocharservice);
ParseResult aResult = xCharacterClassification.parsePredefinedToken(KParseType.IDENTNAME, _sString, 0, _aLocale, nStartFlags, "", nContFlags, " ");
return aResult.EndPos;
} catch (Exception e) {
e.printStackTrace(System.out);
return -1;
}}
public static String removeSpecialCharacters(XMultiServiceFactory _xMSF, Locale _aLocale, String _sname){
String snewname = _sname;
int i = 0;
while(i < snewname.length()){
i = Desktop.checkforfirstSpecialCharacter(_xMSF, snewname, _aLocale);
if (i < snewname.length()){
String sspecialchar = snewname.substring(i,i+1);
snewname = JavaTools.replaceSubString(snewname, "", sspecialchar);
}
}
return snewname;
}
/**
* Checks if the passed Element Name already exists in the ElementContainer. If yes it appends a
* suffix to make it unique
* @param xElementContainer
* @param sElementName
* @return a unique Name ready to be added to the container.
*/
public static String getUniqueName(XNameAccess xElementContainer, String sElementName) {
String sIncSuffix = getIncrementSuffix(xElementContainer, sElementName);
return sElementName + sIncSuffix;
}
/**
* Checks if the passed Element Name already exists in the ElementContainer. If yes it appends a
* suffix to make it unique
* @param xElementContainer
* @param sElementName
* @return a unique Name ready to be added to the container.
*/
public static String getUniqueName(XHierarchicalNameAccess xElementContainer, String sElementName) {
String sIncSuffix = getIncrementSuffix(xElementContainer, sElementName);
return sElementName + sIncSuffix;
}
/**
* Checks if the passed Element Name already exists in the list If yes it appends a
* suffix to make it unique
* @param _slist
* @param _sElementName
* @param _sSuffixSeparator
* @return a unique Name not being in the passed list.
*/
public static String getUniqueName(String[] _slist, String _sElementName, String _sSuffixSeparator) {
int a = 2;
String scompname = _sElementName;
boolean bElementexists = true;
if (_slist == null)
return _sElementName;
if (_slist.length == 0)
return _sElementName;
while (bElementexists == true) {
for (int i = 0; i < _slist.length; i++){
if (JavaTools.FieldInList(_slist, scompname) == -1)
return scompname;
}
scompname = _sElementName + _sSuffixSeparator + a++;
}
return "";
}
/**
* @deprecated use Configuration.getConfigurationRoot() with the same parameters instead
* @param xMSF
* @param KeyName
* @param bForUpdate
* @return
*/
public static XInterface getRegistryKeyContent(XMultiServiceFactory xMSF, String KeyName, boolean bForUpdate) {
try {
Object oConfigProvider;
PropertyValue[] aNodePath = new PropertyValue[1];
oConfigProvider = xMSF.createInstance("com.sun.star.configuration.ConfigurationProvider");
aNodePath[0] = new PropertyValue();
aNodePath[0].Name = "nodepath";
aNodePath[0].Value = KeyName;
XMultiServiceFactory xMSFConfig = (XMultiServiceFactory) UnoRuntime.queryInterface(XMultiServiceFactory.class, oConfigProvider);
if (bForUpdate == true)
return (XInterface) xMSFConfig.createInstanceWithArguments("com.sun.star.configuration.ConfigurationUpdateAccess", aNodePath);
else
return (XInterface) xMSFConfig.createInstanceWithArguments("com.sun.star.configuration.ConfigurationAccess", aNodePath);
} catch (Exception exception) {
exception.printStackTrace(System.out);
return null;
}
}
/**
* used to retrieve the most common paths used in the office application
* @author bc93774
*
*/
public class OfficePathRetriever {
public String TemplatePath;
public String BitmapPath;
public String UserTemplatePath;
public String WorkPath;
public OfficePathRetriever(XMultiServiceFactory xMSF) {
try {
TemplatePath = FileAccess.getOfficePath(xMSF, "Template", "share");
UserTemplatePath = FileAccess.getOfficePath(xMSF, "Template", "user");
BitmapPath = FileAccess.combinePaths(xMSF, TemplatePath, "/wizard/bitmap");
WorkPath = FileAccess.getOfficePath(xMSF, "Work", "");
} catch (NoValidPathException nopathexception) {
}
}
}
public static XStringSubstitution createStringSubstitution(XMultiServiceFactory xMSF) {
Object xPathSubst = null;
try {
xPathSubst = xMSF.createInstance("com.sun.star.util.PathSubstitution");
} catch (com.sun.star.uno.Exception e) {
e.printStackTrace();
}
if (xPathSubst != null)
return (XStringSubstitution) UnoRuntime.queryInterface(XStringSubstitution.class, xPathSubst);
else
return null;
}
/**
* This method searches (and hopefully finds...) a frame
* with a componentWindow.
* It does it in three phases:
* 1. Check if the given desktop argument has a componentWindow.
* If it is null, the myFrame argument is taken.
* 2. Go up the tree of frames and search a frame with a component window.
* 3. Get from the desktop all the components, and give the first one
* which has a frame.
* @param xMSF
* @param myFrame
* @param desktop
* @return
* @throws NoSuchElementException
* @throws WrappedTargetException
*/
public static XFrame findAFrame(XMultiServiceFactory xMSF, XFrame myFrame, XFrame desktop)
throws NoSuchElementException,
WrappedTargetException
{
if (desktop == null)
desktop = myFrame;
// we go up in the tree...
while (desktop != null && desktop.getComponentWindow() == null)
desktop = desktop.findFrame("_parent", FrameSearchFlag.PARENT);
if (desktop == null) {
for (XEnumeration e = Desktop.getDesktop(xMSF).getComponents().createEnumeration(); e.hasMoreElements();) {
Object comp = ((Any) e.nextElement()).getObject();
XModel xModel = (XModel) UnoRuntime.queryInterface(XModel.class, comp);
XFrame xFrame = xModel.getCurrentController().getFrame();
if (xFrame != null && xFrame.getComponentWindow() != null)
return xFrame;
}
}
return desktop;
}
}
|
import java.util.Deque;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map.Entry;
public class PathTreeVisitor extends PathyBaseVisitor<Void>
{
boolean debug;
HashMap<String, PathyObject> worldDict;
Deque<StackElement> stack;
private boolean checkItemNode(String id)
{
return worldDict.containsKey(id) && worldDict.get(id).getType() == PathyType.NODE;
}
private boolean checkItemAction(String id)
{
return worldDict.containsKey(id) && worldDict.get(id).getType() == PathyType.ACTION;
}
private boolean checkItemJunction(String id)
{
return worldDict.containsKey(id) && worldDict.get(id).getType() == PathyType.JUNCT;
}
private boolean checkItemLink(String id)
{
return worldDict.containsKey(id) && worldDict.get(id).getType() == PathyType.LINK;
}
private boolean checkItemEntity(String id)
{
return worldDict.containsKey(id) && worldDict.get(id).getType() == PathyType.ENTITY;
}
private HashSet<Node> getNodes()
{
HashSet<Node> set = new HashSet<Node>();
for(Entry<String, PathyObject> e: worldDict.entrySet())
{
PathyObject item = e.getValue();
if (item.getType() == PathyType.NODE)
{
set.add((Node) item);
}
}
return set;
}
private HashSet<Link> getLinks()
{
HashSet<Link> set = new HashSet<Link>();
for(Entry<String, PathyObject> e: worldDict.entrySet())
{
PathyObject item = e.getValue();
if (item.getType() == PathyType.LINK)
{
set.add((Link) item);
}
}
return set;
}
private HashSet<Entity> getEntities()
{
HashSet<Entity> set = new HashSet<Entity>();
for(Entry<String, PathyObject> e: worldDict.entrySet())
{
PathyObject item = e.getValue();
if (item.getType() == PathyType.ENTITY)
{
set.add((Entity) item);
}
}
return set;
}
private HashSet<Junction> getJunctions()
{
HashSet<Junction> set = new HashSet<Junction>();
for(Entry<String, PathyObject> e: worldDict.entrySet())
{
PathyObject item = e.getValue();
if (item.getType() == PathyType.JUNCT)
{
set.add((Junction) item);
}
}
return set;
}
private HashSet<Action> getActions()
{
HashSet<Action> set = new HashSet<Action>();
for(Entry<String, PathyObject> e: worldDict.entrySet())
{
PathyObject item = e.getValue();
if (item.getType() == PathyType.ACTION)
{
set.add((Action) item);
}
}
return set;
}
private enum ErrorType{IDCONFLICT, IDNOTVALID, ENDPOINTERR}
private String generateFeedback(ErrorType errtype, String id, String ptype, int par)
{
String ret = "";
switch(errtype)
{
case IDCONFLICT:
ret = "ERROR: \"" + id + "\" has already been used as an identifier.";
break;
case IDNOTVALID:
ret = "ERROR: \"" + id + "\" is not a valid identifier for an existing " + ptype + ". PARAM " + Integer.toString(par) + ".";
break;
case ENDPOINTERR:
ret = "ERROR: Endpoint error constructing \"" + id + "\".";
break;
}
return ret;
}
public PathTreeVisitor(HashMap<String, PathyObject> _wd)
{
super();
worldDict = _wd;
debug = true;
}
//declaration statements
public Void visitSimpleDec(PathyParser.SimpleDecContext ctx)
{
String id = ctx.idpar().getText();
//check if id already exists
if (!worldDict.containsKey(id))
{
switch(ctx.op.getType()) {
case PathyParser.NODE:
Node newNode = new Node(id);
worldDict.put(id, newNode);
break;
case PathyParser.JUNCT:
Junction newJunct = new Junction(id);
worldDict.put(id, newJunct);
break;
case PathyParser.ACT:
Action newAct = new Action(id);
worldDict.put(id, newAct);
break;
}
}
else
{
//user tried to reuse a name
throw new IllegalStateException(generateFeedback(ErrorType.IDCONFLICT,id, null, 0));
}
if (debug)
{
System.out.println(id);
System.out.println(worldDict.get(id).toString());
System.out.println();
System.out.println(worldDict);
}
return null;
}
public Void visitEntDecDef(PathyParser.EntDecDefContext ctx)
{
String id = ctx.idpar(0).getText();
String nodeid = ctx.idpar(1).getText();
//check if id already exists
if (!worldDict.containsKey(id))
{
//check if the parameter provided exists and is a node
if (checkItemNode(nodeid))
{
Node param = (Node)worldDict.get(id);
Entity newEnt = new Entity(id, param);
worldDict.put(id, newEnt);
}
else
{
throw new RuntimeException(generateFeedback(ErrorType.IDNOTVALID, nodeid, "Node", 0));
}
}
else
{
//user tried to reuse a name
throw new IllegalStateException(generateFeedback(ErrorType.IDCONFLICT,id, null, 0));
}
if (debug)
{
System.out.println(id);
System.out.println(worldDict.get(id).toString());
System.out.println();
System.out.println(worldDict);
}
return null;
}
public Void visitEntDecEnergy(PathyParser.EntDecEnergyContext ctx)
{
String id = ctx.idpar(0).getText();
String nodeid = ctx.idpar(1).getText();
int energy = Integer.parseInt(ctx.intpar().getText());
//check if id already exists
if (!worldDict.containsKey(id))
{
//check if the parameter provided exists and is a node
if (checkItemNode(nodeid))
{
Node param = (Node)worldDict.get(id);
Entity newEnt = new Entity(id, param, energy);
worldDict.put(id, newEnt);
}
else
{
throw new RuntimeException(generateFeedback(ErrorType.IDNOTVALID, nodeid, "Node", 0));
}
}
else
{
//user tried to reuse a name
throw new IllegalStateException(generateFeedback(ErrorType.IDCONFLICT, id, null, 0));
}
if (debug)
{
System.out.println(id);
System.out.println(worldDict.get(id).toString());
System.out.println();
System.out.println(worldDict);
}
return null;
}
public Void visitLinkDecDef(PathyParser.LinkDecDefContext ctx)
{
String id = ctx.idpar(0).getText();
String aid = ctx.idpar(1).getText();
String bid = ctx.idpar(2).getText();
if (!worldDict.containsKey(id))
{
PathyObject tempA;
PathyObject tempB;
boolean aNodeCheck = checkItemNode(aid);
boolean bNodeCheck = checkItemNode(bid);
boolean aJunctCheck = checkItemJunction(aid);
boolean bJunctCheck = checkItemJunction(bid);
//check if the parameters provided exist and are a nodes or junctions
//there are a few checks due to Links taking different types for the same parameter signature
if (!aNodeCheck && !aJunctCheck
&& !bNodeCheck && !bJunctCheck)
{
//Both parameters are invalid
throw new RuntimeException(generateFeedback(ErrorType.IDNOTVALID, aid, "Node or Junction", 0)
+ System.lineSeparator() + generateFeedback(ErrorType.IDNOTVALID, bid, "Node or Junction", 1));
}
if ((aNodeCheck || aJunctCheck))
{
//parameter 0 is valid
tempA = worldDict.get(aid);
}
else
{
//parameter 0 is invalid
throw new RuntimeException(generateFeedback(ErrorType.IDNOTVALID, aid, "Node or Junction", 0));
}
if ((bNodeCheck || bJunctCheck))
{
//parameter 1 is valid
tempB = worldDict.get(bid);
}
else
{
//parameter 1 is invalid
throw new RuntimeException(generateFeedback(ErrorType.IDNOTVALID, bid, "Node or Junction", 1));
}
Link newLink;
Node nodeA;
Node nodeB;
Junction junctA;
Junction junctB;
if (tempA.getType() == PathyType.NODE && tempB.getType() == PathyType.NODE)
{
nodeA = (Node)tempA;
nodeB = (Node)tempB;
newLink = new Link(id, nodeA, nodeB);
}
else if (tempA.getType() == PathyType.NODE && tempB.getType() == PathyType.JUNCT)
{
nodeA = (Node)tempA;
junctB = (Junction)tempB;
newLink = new Link(id, nodeA, junctB);
}
else if (tempA.getType() == PathyType.JUNCT && tempB.getType() == PathyType.NODE)
{
junctA = (Junction)tempA;
nodeB = (Node)tempB;
newLink = new Link(id, junctA, nodeB);
}
else if (tempA.getType() == PathyType.JUNCT && tempB.getType() == PathyType.JUNCT)
{
junctA = (Junction)tempA;
junctB = (Junction)tempB;
newLink = new Link(id, junctA, junctB);
}
else
{
throw new RuntimeException(generateFeedback(ErrorType.ENDPOINTERR,id, null, 0));
}
worldDict.put(id, newLink);
}
else
{
//user tried to reuse a name
throw new IllegalStateException(generateFeedback(ErrorType.IDCONFLICT,id, null, 0));
}
if (debug)
{
System.out.println(id);
System.out.println(worldDict.get(id).toString());
System.out.println();
System.out.println(worldDict);
}
return null;
}
public Void visitLinkDecWeight(PathyParser.LinkDecWeightContext ctx)
{
String id = ctx.idpar(0).getText();
String aid = ctx.idpar(1).getText();
String bid = ctx.idpar(2).getText();
int weight = Integer.parseInt(ctx.intpar().getText());
if (!worldDict.containsKey(id))
{
PathyObject tempA;
PathyObject tempB;
boolean aNodeCheck = checkItemNode(aid);
boolean bNodeCheck = checkItemNode(bid);
boolean aJunctCheck = checkItemJunction(aid);
boolean bJunctCheck = checkItemJunction(bid);
//check if the parameters provided exist and are a nodes or junctions
//there are a few checks due to Links taking different types for the same parameter signature
if (!aNodeCheck && !aJunctCheck
&& !bNodeCheck && !bJunctCheck)
{
//Both parameters are invalid
throw new RuntimeException(generateFeedback(ErrorType.IDNOTVALID, aid, "Node or Junction", 0)
+ System.lineSeparator() + generateFeedback(ErrorType.IDNOTVALID, bid, "Node or Junction", 1));
}
if ((aNodeCheck || aJunctCheck))
{
//parameter 0 is valid
tempA = worldDict.get(aid);
}
else
{
//parameter 0 is invalid
throw new RuntimeException(generateFeedback(ErrorType.IDNOTVALID, aid, "Node or Junction", 0));
}
if ((bNodeCheck || bJunctCheck))
{
//parameter 1 is valid
tempB = worldDict.get(bid);
}
else
{
//parameter 1 is invalid
throw new RuntimeException(generateFeedback(ErrorType.IDNOTVALID, bid, "Node or Junction", 1));
}
Link newLink;
Node nodeA;
Node nodeB;
Junction junctA;
Junction junctB;
if (tempA.getType() == PathyType.NODE && tempB.getType() == PathyType.NODE)
{
nodeA = (Node)tempA;
nodeB = (Node)tempB;
newLink = new Link(id, nodeA, nodeB, weight);
}
else if (tempA.getType() == PathyType.NODE && tempB.getType() == PathyType.JUNCT)
{
nodeA = (Node)tempA;
junctB = (Junction)tempB;
newLink = new Link(id, nodeA, junctB, weight);
}
else if (tempA.getType() == PathyType.JUNCT && tempB.getType() == PathyType.NODE)
{
junctA = (Junction)tempA;
nodeB = (Node)tempB;
newLink = new Link(id, junctA, nodeB, weight);
}
else if (tempA.getType() == PathyType.JUNCT && tempB.getType() == PathyType.JUNCT)
{
junctA = (Junction)tempA;
junctB = (Junction)tempB;
newLink = new Link(id, junctA, junctB, weight);
}
else
{
throw new RuntimeException(generateFeedback(ErrorType.ENDPOINTERR,id, null, 0));
}
worldDict.put(id, newLink);
}
else
{
//user tried to reuse a name
throw new IllegalStateException(generateFeedback(ErrorType.IDCONFLICT,id, null, 0));
}
if (debug)
{
System.out.println(id);
System.out.println(worldDict.get(id).toString());
System.out.println();
System.out.println(worldDict);
}
return null;
}
public Void visitLinkDecBoth(PathyParser.LinkDecBothContext ctx)
{
String id = ctx.idpar(0).getText();
String aid = ctx.idpar(1).getText();
String bid = ctx.idpar(2).getText();
int weight = Integer.parseInt(ctx.intpar().getText());
LinkDir dir = LinkDir.values()[Integer.parseInt(ctx.dirpar().getText())];
if (!worldDict.containsKey(id))
{
PathyObject tempA;
PathyObject tempB;
boolean aNodeCheck = checkItemNode(aid);
boolean bNodeCheck = checkItemNode(bid);
boolean aJunctCheck = checkItemJunction(aid);
boolean bJunctCheck = checkItemJunction(bid);
//check if the parameters provided exist and are a nodes or junctions
//there are a few checks due to Links taking different types for the same parameter signature
if (!aNodeCheck && !aJunctCheck
&& !bNodeCheck && !bJunctCheck)
{
//Both parameters are invalid
throw new RuntimeException(generateFeedback(ErrorType.IDNOTVALID, aid, "Node or Junction", 0)
+ System.lineSeparator() + generateFeedback(ErrorType.IDNOTVALID, bid, "Node or Junction", 1));
}
if ((aNodeCheck || aJunctCheck))
{
//parameter 0 is valid
tempA = worldDict.get(aid);
}
else
{
//parameter 0 is invalid
throw new RuntimeException(generateFeedback(ErrorType.IDNOTVALID, aid, "Node or Junction", 0));
}
if ((bNodeCheck || bJunctCheck))
{
//parameter 1 is valid
tempB = worldDict.get(bid);
}
else
{
//parameter 1 is invalid
throw new RuntimeException(generateFeedback(ErrorType.IDNOTVALID, bid, "Node or Junction", 1));
}
Link newLink;
Node nodeA;
Node nodeB;
Junction junctA;
Junction junctB;
if (tempA.getType() == PathyType.NODE && tempB.getType() == PathyType.NODE)
{
nodeA = (Node)tempA;
nodeB = (Node)tempB;
newLink = new Link(id, nodeA, nodeB, weight, dir);
}
else if (tempA.getType() == PathyType.NODE && tempB.getType() == PathyType.JUNCT)
{
nodeA = (Node)tempA;
junctB = (Junction)tempB;
newLink = new Link(id, nodeA, junctB, weight, dir);
}
else if (tempA.getType() == PathyType.JUNCT && tempB.getType() == PathyType.NODE)
{
junctA = (Junction)tempA;
nodeB = (Node)tempB;
newLink = new Link(id, junctA, nodeB, weight, dir);
}
else if (tempA.getType() == PathyType.JUNCT && tempB.getType() == PathyType.JUNCT)
{
junctA = (Junction)tempA;
junctB = (Junction)tempB;
newLink = new Link(id, junctA, junctB, weight, dir);
}
else
{
throw new RuntimeException(generateFeedback(ErrorType.ENDPOINTERR,id, null, 0));
}
worldDict.put(id, newLink);
}
else
{
//user tried to reuse a name
throw new IllegalStateException(generateFeedback(ErrorType.IDCONFLICT,id, null, 0));
}
if (debug)
{
System.out.println(id);
System.out.println(worldDict.get(id).toString());
System.out.println();
System.out.println(worldDict);
}
return null;
}
public Void visitAssignAct(PathyParser.AssignActContext ctx)
{
String aid = ctx.idpar(0).getText();
String nid = ctx.idpar(1).getText();
boolean isact = checkItemAction(aid);
boolean isnode = checkItemNode(nid);
if (!isact && !isnode)
{
throw new RuntimeException(generateFeedback(ErrorType.IDNOTVALID,aid, "Action", 0)
+ System.lineSeparator() + generateFeedback(ErrorType.IDNOTVALID,nid, "Node", 1));
}
else if (!isact)
{
throw new RuntimeException(generateFeedback(ErrorType.IDNOTVALID,aid, "Action", 0));
}
else if (!isnode)
{
throw new RuntimeException(generateFeedback(ErrorType.IDNOTVALID,nid, "Node", 1));
}
//both checked out lets add it now
Node n = (Node) worldDict.get(nid);
Action a = (Action) worldDict.get(aid);
n.addAction(a);
return null;
}
public Void visitDelItem(PathyParser.DelItemContext ctx)
{
String id = ctx.idpar().getText();
if (!worldDict.containsKey(id))
{
//Throws: if [ID] doesn't exist
throw new IllegalStateException("ERROR: \"" + id + "\" does not exist.");
}
PathyObject item = worldDict.get(id);
PathyType itemtype = item.getType();
if (itemtype == PathyType.NODE || itemtype == PathyType.JUNCT)
{
HashSet<Link> links = getLinks();
for (Link l : links)
{
if (l.getA() == item || l.getB() == item)
{
//Throws: if [ID] is a Node or Junction, and is attached to one or more Links
throw new IllegalStateException("ERROR: \"" + id + "\" is an endpoint for \"" + l.getID()
+ "\". Cannot remove \"" + id + "\" unless the Link is removed first.");
}
}
}
if (itemtype == PathyType.NODE)
{
HashSet<Entity> entities = getEntities();
for (Entity e : entities)
{
if (e.getLocation() == (Node) item)
{
//Throws: if [ID] is a Node, and an Entity is currently located at [ID]
throw new IllegalStateException("ERROR: \"" + e.getID() + "\" is the current location of \"" + id
+ "\". Cannot remove \"" + id + "\" unless the Entity is moved first.");
}
}
Node n = (Node)item;
if (!n.getActivities().isEmpty())
{
//Warning: shows a warning if [ID] is a Node, and had one or more Actions associated with it.
System.out.println("WARNING: \"" + id + "\" had Action(s) assigned to it. Some actions may not be assigned to any Nodes as a result.");
}
}
if (itemtype == PathyType.ACTION)
{
//Warning: shows a warning if [ID] is an Action, and was associated with one or more nodes.
HashSet<Node> nodes = getNodes();
boolean found = false;
for (Node n : nodes)
{
if(!n.getActivities().isEmpty())
{
if (n.removeAction((Action) item))
{
//removeAction returns true is it was removed thus was there
found = true;
}
}
}
if (found)
{
System.out.println("WARNING: \"" + id + "\" was assigned to one or more nodes. Some Nodes may not have any Actions assigned to them as a result.");
}
}
//now as the housekeeping has been taken care of we can finally delete the item.
worldDict.remove(id);
System.gc();
return null;
}
//flexi statements
public Void visitSetLink2B(PathyParser.SetLink2BContext ctx)
{
String id = ctx.idpar().getText();
if (checkItemLink(id))
{
Link l = (Link)worldDict.get(id);
switch(ctx.op.getType()) {
case PathyParser.SL2:
l.setDirection(LinkDir.TWOWAY);
break;
case PathyParser.SLB:
l.setDirection(LinkDir.BLOCKED);
break;
}
}
else
{
//parameter 0 is invalid
throw new RuntimeException(generateFeedback(ErrorType.IDNOTVALID, id, "Link", 0));
}
return null;
}
public Void visitSetVals(PathyParser.SetValsContext ctx)
{
String id = ctx.idpar().getText();
int val = Integer.parseInt(ctx.intpar().getText());
//the grammar won't catch negatives but check and fix it if it does happen.
if (val < 0)
{
val = -val;
}
switch(ctx.op.getType()) {
case PathyParser.SE:
if (checkItemEntity(id))
{
Entity e = (Entity)worldDict.get(id);
e.setEnergy(val);
}
else
{
//parameter 0 is invalid
throw new RuntimeException(generateFeedback(ErrorType.IDNOTVALID, id, "Entity", 0));
}
break;
case PathyParser.SW:
if (checkItemLink(id))
{
Link l = (Link)worldDict.get(id);
l.setWeight(val);
}
else
{
//parameter 0 is invalid
throw new RuntimeException(generateFeedback(ErrorType.IDNOTVALID, id, "Link", 0));
}
break;
}
return null;
}
public Void visitMoveEnt(PathyParser.MoveEntContext ctx)
{
String eid = ctx.idpar(0).getText();
String nid = ctx.idpar(1).getText();
boolean isentity = checkItemEntity(eid);
boolean isnode = checkItemNode(nid);
if (!isentity && !isnode)
{
throw new RuntimeException(generateFeedback(ErrorType.IDNOTVALID, eid, "Entity", 0)
+ System.lineSeparator() + generateFeedback(ErrorType.IDNOTVALID, nid, "Node", 1));
}
else if (!isentity)
{
throw new RuntimeException(generateFeedback(ErrorType.IDNOTVALID, eid, "Entity", 0));
}
else if (!isnode)
{
throw new RuntimeException(generateFeedback(ErrorType.IDNOTVALID, nid, "Node", 1));
}
//both checked out lets add it now
Node n = (Node) worldDict.get(nid);
Entity e = (Entity) worldDict.get(eid);
e.setLocation(n);
return null;
}
public Void visitSetLink1W(PathyParser.SetLink1WContext ctx)
{
String lid = ctx.idpar(0).getText();
String aid = ctx.idpar(1).getText();
String bid = ctx.idpar(2).getText();
boolean islink = checkItemEntity(lid);
boolean isA = checkItemNode(aid) || checkItemJunction(aid);
boolean isB = checkItemNode(bid) || checkItemJunction(bid);
if (!islink && !isA && !isB)
{
throw new RuntimeException(generateFeedback(ErrorType.IDNOTVALID, lid, "Link", 0)
+ System.lineSeparator() + generateFeedback(ErrorType.IDNOTVALID, aid, "Node or Junction", 1)
+ System.lineSeparator() + generateFeedback(ErrorType.IDNOTVALID, bid, "Node or Junction", 2));
}
else if (!islink && !isA)
{
throw new RuntimeException(generateFeedback(ErrorType.IDNOTVALID, lid, "Link", 0)
+ System.lineSeparator() + generateFeedback(ErrorType.IDNOTVALID, aid, "Node or Junction", 1));
}
else if (!islink && !isB)
{
throw new RuntimeException(generateFeedback(ErrorType.IDNOTVALID, lid, "Link", 0)
+ System.lineSeparator() + generateFeedback(ErrorType.IDNOTVALID, bid, "Node or Junction", 2));
}
else if (!isA && !isB)
{
throw new RuntimeException(generateFeedback(ErrorType.IDNOTVALID, aid, "Node or Junction", 1)
+ System.lineSeparator() + generateFeedback(ErrorType.IDNOTVALID, bid, "Node or Junction", 2));
}
else if (!islink)
{
throw new RuntimeException(generateFeedback(ErrorType.IDNOTVALID, lid, "Link", 0));
}
else if (!isA)
{
throw new RuntimeException(generateFeedback(ErrorType.IDNOTVALID, aid, "Node or Junction", 1));
}
else if (!isB)
{
throw new RuntimeException(generateFeedback(ErrorType.IDNOTVALID, bid, "Node or Junction", 2));
}
//two final checks - are the nodes on the Link, and are the nodes the same (just in same it slipped through)
if (aid.equals(bid))
{
throw new RuntimeException("ERROR: Both endpoints refer to the same Node or Junction");
}
Link l = (Link)worldDict.get(lid);
PathyObject a = worldDict.get(lid);
PathyObject b = worldDict.get(lid);
if (l.isEndpoint(a) && l.isEndpoint(b))
{
//all checks out lets do it now
if (a == l.getA())
{
l.setDirection(LinkDir.ATOB);
}
else
{
l.setDirection(LinkDir.BTOA);
}
}
else
{
if (!l.isEndpoint(a) && !l.isEndpoint(b))
{
//both weren't endpoints
throw new RuntimeException("ERROR: The supplied endpoints, \"" + aid + "\"and \""+ bid +"\", were not found at either end of \""+ lid +"\".");
}
else if (!l.isEndpoint(a))
{
//a wasn't an endpoint
throw new RuntimeException("ERROR: The supplied endpoint, \"" + aid + "\", was not found at either end of \""+ lid +"\". PARAM 1");
}
else
{
//b wasn't an endpoint
throw new RuntimeException("ERROR: The supplied endpoint, \"" + bid + "\", was not found at either end of \""+ lid +"\". PARAM 2");
}
}
return null;
}
public Void visitSetJunctDir(PathyParser.SetJunctDirContext ctx)
{
return null;
}
//query statements
public Void visitNoParamQuery(PathyParser.NoParamQueryContext ctx)
{
HashSet<? extends PathyObject> items = null;
switch(ctx.op.getType()) {
case PathyParser.FPN:
items = getNodes();
break;
case PathyParser.FPA:
items = getActions();
break;
case PathyParser.FPL:
items = getLinks();
break;
case PathyParser.FPJ:
items = getJunctions();
break;
case PathyParser.FPE:
items = getEntities();
break;
}
for (PathyObject i : items)
{
System.out.println(i.getID());
}
return null;
}
public Void visitOneParamQuery()
{
return null;
}
public Void visitTwoParamQuery() {
return null;
}
}
|
package ObjetoEstudiante;
import javax.swing.JOptionPane;
public class main {
public static void main(String[] args) {
int opcion=99;
Informacion[] items = new Informacion[5];
items[0] = new Informacion("0001", "KAROL CEDEO ", "MATEMATICA ", 25, 17.5);
items[1] = new Informacion("0002", "DIANA TAMAYO ", "CONTABILIDAD", 27.8, 14);
items[2] = new Informacion("0003", "KAREN ACHILIE", "QUIMICA ", 19, 7.5);
items[3] = new Informacion("0004", "TAMARA CHAVEZ", "DISEO ", 23, 15.5);
items[4] = new Informacion("0005", "XIMENA TORRES", "FISICA ", 12, 6);
while(!(opcion==4)){
opcion = Integer.parseInt(JOptionPane.showInputDialog("1: LISTA ESTUDIANTES\n2: BUSCAR ESTUDIANTES POR MATRICULA\n3: MOSTRAR ESTUDIANTES QUE APRUEBAN\n4: SALIR\n\nINGRESE SU OPCION:"));
switch(opcion){
case 1:
for(int i=0; i<items.length; i++){
items[i].show_inf();
}
break;
case 2:
System.out.println("**********************************************************************************************************");
boolean bandera = false;
String matricula = JOptionPane.showInputDialog("INGRESE MATRICULA:");
for(int i=0; i<items.length; i++){
if(matricula.equals(items[i].getMatricula())){
items[i].show_inf();
bandera = true;
}
}
if(!bandera)
JOptionPane.showMessageDialog(null, "NO EXISTE EL ALUMNO");
break;
case 3:
System.out.println("**********************************************************************************************************");
double promedio = 0;
for(int i=0; i<items.length; i++){
promedio = items[i].getNota_parciales() + items[i].getNota_examen();
if(promedio >= 30){
items[i].show_inf();
}
}
break;
case 4:
JOptionPane.showMessageDialog(null, "SE VA A CERRAR");
break;
}
}
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package sibtra.predictivo;
import sibtra.gps.Trayectoria;
import sibtra.log.LoggerArrayDoubles;
import sibtra.log.LoggerFactory;
import sibtra.util.UtilCalculos;
import Jama.Matrix;
/**
* Esta clase implementa el algoritmo de control predictivo DMC
* @author Jesus
*/
public class ControlPredictivo {
private static final double minAvancePrediccion = 2;
int horPrediccion;
/**
* Indica cuantos comandos de control futuros se quieren calcular
*/
int horControl;
/** trayectoria que debe seguir el coche */
Trayectoria ruta=null;
double landa;
double pesoError = 0.8;
Coche carroOriginal=null;
Coche carroSim=null;
/**
* Periodo de muestreo del controlador
*/
double Ts;
Matrix G;
private Matrix landaEye;
/** Almacena las orientaciones de la prediccion*/
double[] predicOrientacion;
/** Almacena las posiciones x e y de la prediccion*/
double[][] prediccionPosPorFilas;
double comandoCalculado;
double distanciaLateral;
private double[] vectorError;
private double[] orientacionesDeseadas;
private double[] respuestaEscalon;
private Coche carroEscalon;
int indMinAnt;
private double alpha = 1.05;
/** Hace las veces de ganancia proporcional al error
*
*/
private LoggerArrayDoubles logPredicOrientacion;
private LoggerArrayDoubles logPredicPosX;
private LoggerArrayDoubles logPredicPosY;
private LoggerArrayDoubles logVectorError;
private LoggerArrayDoubles logParametros;
public ControlPredictivo(Coche carroOri,Trayectoria ruta,int horPrediccion,int horControl,double landa,double Ts){
carroOriginal = carroOri;
carroSim = (Coche)carroOri.clone();
carroEscalon=(Coche)carroOriginal.clone();
this.horPrediccion = horPrediccion;
this.horControl = horControl;
this.landa = landa;
this.ruta = ruta;
this.Ts = Ts;
this.indMinAnt = -1;
// creamos todas las matrices que se usan en las iteracioner para evitar tener que
//pedir memoria cada vez
G = new Matrix(horPrediccion,horControl);
this.landaEye = Matrix.identity(horControl,horControl).times(landa);
prediccionPosPorFilas = new double[2][horPrediccion];
predicOrientacion = new double[horPrediccion];
vectorError = new double[horPrediccion];
orientacionesDeseadas = new double[horPrediccion];
respuestaEscalon = new double[horPrediccion];
logPredicOrientacion=LoggerFactory.nuevoLoggerArrayDoubles(this, "PrediccionOrientacion");
logPredicPosX=LoggerFactory.nuevoLoggerArrayDoubles(this, "PrediccionPosicionX");
logPredicPosY=LoggerFactory.nuevoLoggerArrayDoubles(this, "PrediccionPosicionY");
logVectorError=LoggerFactory.nuevoLoggerArrayDoubles(this, "VectorError");
logParametros=LoggerFactory.nuevoLoggerArrayDoubles(this, "ParametrosPredictivo");
logParametros.add(horControl,horPrediccion,landa,alpha,pesoError);
logParametros.setDescripcion("[horControl,horPrediccion,landa,alpha,pesoError]");
}
public double getPesoError() {
return pesoError;
}
public void setAlpha(double alpha2) {
alpha = alpha2;
logParametros.add(horControl,horPrediccion,landa,alpha,pesoError);
}
public void setPesoError(double pesoError2) {
pesoError = pesoError2;
logParametros.add(horControl,horPrediccion,landa,alpha,pesoError);
}
/** @return Devuelve el primer componente del vector {@link #orientacionesDeseadas} */
public double getOrientacionDeseada() {
return orientacionesDeseadas[0];
}
public int getHorControl() {
return horControl;
}
/** establece horizonte de control, recalculando {@link #G} si es necesario */
public void setHorControl(int horControl) {
logParametros.add(horControl,horPrediccion,landa,alpha,pesoError);
if (horControl==this.horControl)
return;
this.horControl = horControl;
G = new Matrix(horPrediccion,horControl);
this.landaEye = Matrix.identity(horControl,horControl).times(landa);
}
public int getHorPrediccion() {
return horPrediccion;
}
public void setHorPrediccion(int horPrediccion) {
logParametros.add(horControl,horPrediccion,landa,alpha,pesoError);
if(horPrediccion==this.horPrediccion)
return;
this.horPrediccion = horPrediccion;
prediccionPosPorFilas = new double[2][horPrediccion];
G = new Matrix(horPrediccion,horControl);
predicOrientacion = new double[horPrediccion];
vectorError = new double[horPrediccion];
orientacionesDeseadas = new double[horPrediccion];
respuestaEscalon = new double[horPrediccion];
}
public double getLanda() {
return landa;
}
public void setLanda(double landa) {
logParametros.add(horControl,horPrediccion,landa);
if(landa==this.landa)
return;
this.landa = landa;
this.landaEye = Matrix.identity(horControl,horControl).times(landa);
}
public void setRuta(Trayectoria nuevaRuta){
this.indMinAnt=-1;
this.ruta = nuevaRuta;
}
public void iniciaNavega() {
indMinAnt = -1;
}
private void calculaHorizonte(){
double metrosAvanzados = carroOriginal.getVelocidad()*Ts*horPrediccion;
double velMin = 0.1;
if (metrosAvanzados <= minAvancePrediccion){
if (carroOriginal.getVelocidad() > 0){
horPrediccion = (int)Math.ceil(minAvancePrediccion/(carroOriginal.getVelocidad()*Ts));
}else{
if (carroOriginal.getVelocidad() == 0){
//TODO ver que hacemos con el caso de que la
// velocidad sea negativa o igual a cero
//horPrediccion = (int)Math.ceil(minAvancePrediccion/(velMin*Ts));
}
else{
//caso en que la velocidad del coche es negativa
}
}
}
}
private double[] calculaPrediccion(double comando,double velocidad){
carroSim.copy(carroOriginal);
// vec_deseado(1,:) = k_dist*(pos_ref(mod(ind_min(k)+cerca,length(pos_ref))+1,:) - [carro.x,carro.y])
//+ k_ang*[cos(tita_ref(mod(ind_min(k)+cerca,length(tita_ref))+1)),sin(tita_ref(mod(ind_min(k)+cerca,length(tita_ref))+1))];
// int indMin = calculaDistMin(ruta,carroSim.getX(),carroSim.getY());
//TODO usar directamente indiceMasCercanoOptimizado ya que es la posicion actual del coche
indMinAnt = ruta.indiceMasCercanoOptimizado(carroSim.getX(),carroSim.getY(),indMinAnt);
// ruta.situaCoche(carroSim.getX(),carroSim.getY());
// indMinAnt = ruta.indiceMasCercano();
double dx=ruta.x[indMinAnt]-carroSim.getX();
double dy=ruta.y[indMinAnt]-carroSim.getY();
distanciaLateral=Math.sqrt(dx*dx+dy*dy);
double vectorDeseadoX = ruta.x[indMinAnt] - carroSim.getX() + Math.cos(ruta.rumbo[indMinAnt]);
double vectorDeseadoY = ruta.y[indMinAnt] - carroSim.getY() + Math.sin(ruta.rumbo[indMinAnt]);
orientacionesDeseadas[0] = Math.atan2(vectorDeseadoX,vectorDeseadoY);
predicOrientacion[0] = carroSim.getYaw();
vectorError[0] = orientacionesDeseadas[0] - predicOrientacion[0];
prediccionPosPorFilas[0][0] = carroSim.getX();
prediccionPosPorFilas[1][0] = carroSim.getY();
int indMin = indMinAnt;
for (int i=1; i<horPrediccion;i++ ){
carroSim.calculaEvolucion(comando,velocidad,Ts);
predicOrientacion[i] = carroSim.getYaw();
indMin = ruta.indiceMasCercanoOptimizado(carroSim.getX(),carroSim.getY(),indMin);
// indMin = calculaDistMin(ruta,carroSim.getX(),carroSim.getY());
vectorDeseadoX = ruta.x[indMin] - carroSim.getX() + Math.cos(ruta.rumbo[indMin]);
vectorDeseadoY = ruta.y[indMin] - carroSim.getY() + Math.sin(ruta.rumbo[indMin]);
orientacionesDeseadas[i] = Math.atan2(vectorDeseadoY,vectorDeseadoX);
// System.out.println("Indice minimo " + indMin);
// System.out.println("Vector x "+vectorDeseadoX+" "+ "Vector y "+vectorDeseadoY+"\n");
// System.out.println("Orientacion deseada " + orientacionesDeseadas[i] + " "
// +"prediccion de orientacion " + predicOrientacion[i]+"\n");
// coefError pesa los valores del vectorError dependiendo del valor de alpha
double coefError = Math.pow(pesoError*alpha,horPrediccion-i);
vectorError[i] = coefError*(UtilCalculos.normalizaAngulo(orientacionesDeseadas[i] - predicOrientacion[i]));
prediccionPosPorFilas[0][i] = carroSim.getX();
prediccionPosPorFilas[1][i] = carroSim.getY();
}
logPredicOrientacion.add(predicOrientacion);
logPredicPosX.add(prediccionPosPorFilas[0]);
logPredicPosY.add(prediccionPosPorFilas[1]);
logVectorError.add(vectorError);
return vectorError;
}
public double calculaComando(){
// vector_error = tita_deseado - ftita;
// vector_error = vector_error + (vector_error > pi)*(-2*pi) + (vector_error < -pi)*2*pi;
double[] vectorError = calculaPrediccion(carroOriginal.getConsignaVolante()
,carroOriginal.getVelocidad());
// M = diag(peso_tita'*vector_error);
Matrix M = new Matrix(vectorError,horPrediccion).transpose();
//M.print(1,6);
// u = inv(G'*G + landa*eye(hor_control))*G'*M;
// u_actual = u(1) + u_anterior;
calculaG();
//G.print(1,6);
Matrix Gt = G.transpose();
// Matrix GtporM = Gt.times(M.transpose());
// Matrix GtporG = Gt.times(G);
// Matrix masLandaEye = GtporG.plus(landaEye);
Matrix vectorU = Gt.times(G).plus(landaEye).inverse().times(Gt).times(M.transpose());
//vectorU.print(1,6);
comandoCalculado = vectorU.get(0,0) + carroOriginal.getConsignaVolante();
return comandoCalculado;
}
private Matrix calculaG(){
double[] escalon = calculaEscalon(carroOriginal.getVelocidad());
// for j=1:hor_control,
// cont=1;
// for i=j:hor_predic
// Gtita(i,j)=escalon_tita(cont);
// cont=cont+1;
// end
//end
for (int j=0;j<horControl;j++){
int cont = 0;
for (int i=j;i<horPrediccion;i++){
G.set(i,j,escalon[cont]);
cont++;
}
}
return G;
}
private double[] calculaEscalon(double velocidad){
// carroEscalon.copy(carroOriginal);
carroEscalon.setPostura(0,0,0,0);
carroEscalon.setEstadoA0();
for (int i=0;i<horPrediccion;i++){
carroEscalon.calculaEvolucion(Math.PI/6,velocidad, Ts);
respuestaEscalon[i] = carroEscalon.getYaw();
}
return respuestaEscalon;
}
protected void finalize() throws Throwable {
//borramos todos los loggers
LoggerFactory.borraLogger(logPredicOrientacion);
LoggerFactory.borraLogger(logPredicPosX);
LoggerFactory.borraLogger(logPredicPosY);
LoggerFactory.borraLogger(logVectorError);
LoggerFactory.borraLogger(logParametros);
super.finalize();
}
}
|
package com.parc.ccn.data.query;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.Arrays;
import java.util.Random;
import javax.xml.stream.XMLStreamException;
import com.parc.ccn.data.util.DataUtils;
import com.parc.ccn.data.util.XMLDecoder;
import com.parc.ccn.data.util.XMLEncoder;
/**
* Implement bloom filter operations
*/
public class BloomFilter extends ExcludeFilter.Filler implements Comparable<BloomFilter> {
public static final String BLOOM = "Bloom";
private int _lgBits;
private int _nHash;
/*
* I am using a short for seed internally - even though it's
* supposed to be a byte array - to get around unsigned arithmetic
* issues. Is there a better way to handle this?
*/
private short [] _seed;
private byte [] _bloom = new byte[1024];
private int _size = 0;
public BloomFilter(int size, byte [] seed) {
if (seed.length != 4)
throw new IllegalArgumentException("Bloom seed length must be 4"); // for now
_seed = new short[seed.length];
for (int i = 0; i < seed.length; i++)
_seed[i] = (short)((seed[i]) & 0xff);
_size = size;
/*
* Michael's comment: try for about m = 12*n (m = bits in Bloom filter)
*/
_lgBits = 13;
while (_lgBits > 3 && (1 << _lgBits) > size * 12)
_lgBits
/*
* Michael's comment: optimum number of hash functions is ln(2)*(m/n); use ln(2) ~= 9/13
*/
_nHash = (9 << _lgBits) / (13 * size + 1);
if (_nHash < 2)
_nHash = 2;
if (_nHash > 32)
_nHash = 32;
}
/*
* Create a seed from random values
*/
public static void createSeed(byte[] seed) {
Random rand = new Random();
rand.nextBytes(seed);
}
/**
* For decoding
*/
public BloomFilter() {}
public void insert(byte [] key) {
long s = computeSeed();
for (int i = 0; i < key.length; i++)
s = nextHash(s, key[i] + 1);
long m = (8*_bloom.length - 1) & ((1 << _lgBits) - 1);
for (int i = 0; i < _nHash; i++) {
s = nextHash(s, 0);
long h = s & m;
if ((_bloom[(int)(h >> 3)] & (1 << (h & 7))) == 0) {
_bloom[(int)(h >> 3)] |= (1 << (h & 7));
}
}
_size++;
}
/**
* Test if the bloom filter matches a particular key.
* Note - a negative result means the key was definitely not set, but a positive result only means the
* key was likely set.
* @param key
* @return
*/
public boolean match(byte [] key) {
int m = ((8*_bloom.length) - 1) & ((1 << _lgBits) - 1);
long s = computeSeed();
for (int k = 0; k < key.length; k++)
s = nextHash(s, key[k] + 1);
for (int i = 0; i < _nHash; i++) {
s = nextHash(s, 0);
long h = s & m;
if (0 == (_bloom[(int)h >> 3] & (1 << (h & 7))))
return false;
}
return true;
}
public int size() {
return _size;
}
public byte[] seed() {
byte [] outSeed = new byte[_seed.length];
for (int i = 0; i < _seed.length; i++)
outSeed[i] = (byte) _seed[i];
return outSeed;
}
private long nextHash(long s, int u) {
long k = 13; // Michael's comment: use this many bits of feedback shift output
long b = s & ((1 << k) - 1);
// Michael's comment: fsr primitive polynomial (modulo 2) x**31 + x**13 + 1
s = ((s >> k) ^ (b << (31 - k)) ^ (b << (13 - k))) + u;
return(s & 0x7FFFFFFF);
}
public void decode(XMLDecoder decoder) throws XMLStreamException {
ByteArrayInputStream bais = new ByteArrayInputStream(decoder.readBinaryElement(BLOOM));
_lgBits = bais.read();
_nHash = bais.read();
bais.skip(2); // method & reserved - ignored for now
_seed = new short[4];
for (int i = 0; i < _seed.length; i++)
_seed[i] = (byte)bais.read();
for (int i = 0; i < _seed.length; i++)
_seed[i] = (short)((_seed[i]) & 0xff);
int i = 0;
while (bais.available() > 0)
_bloom[i++] = (byte)bais.read();
}
public void encode(XMLEncoder encoder) throws XMLStreamException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
baos.write((byte)_lgBits);
baos.write((byte)_nHash);
baos.write('A'); // "method" - must be 'A' for now
baos.write(0); // "reserved" - must be 0 for now
for (int i = 0; i < _seed.length; i++)
baos.write((byte)_seed[i]);
int size = 1 << (_lgBits - 3);
for (int i = 0; i < size; i++)
baos.write(_bloom[i]);
encoder.writeElement(BLOOM, baos.toByteArray());
}
public int compareTo(BloomFilter o) {
return DataUtils.compare(_bloom, o._bloom);
}
private long computeSeed() {
long u = ((_seed[0]) << 24) |((_seed[1]) << 16) |((_seed[2]) << 8) | (_seed[3]);
return u & 0x7FFFFFFF;
}
public BloomFilter clone() throws CloneNotSupportedException {
BloomFilter result = (BloomFilter)super.clone();
result._seed = _seed.clone();
result._bloom = _bloom.clone();
return result;
}
@Override
public boolean validate() {
return true;
}
@Override
public boolean equals(Object obj) {
if (obj == null)
return false;
if (!(obj instanceof BloomFilter))
return false;
BloomFilter bl = (BloomFilter) obj;
return Arrays.equals(_bloom, bl._bloom);
}
}
|
package vg.civcraft.mc.civmodcore.itemHandling;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.logging.Level;
import java.util.Set;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.craftbukkit.v1_8_R3.inventory.CraftItemStack;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
/**
* Allows the storage and comparison of itemstacks while ignoring their maximum
* possible stack sizes. This offers various tools to compare inventories, to
* store recipe costs or to specify setupcosts. Take great care when dealing
* with itemstacks with negative amounnts, while this implementation should be
* consistent even with negative values, they create possibly unexpected
* results. For example an empty inventory/itemmap will seem to contain items
* when compared to a map containing negative values. Additionally this
* implementation allows durability "wild cards", if you specify -1 as
* durability it will count as any given durability. When working with multiple
* ItemMaps this will only work if all methods are executed on the instance
* containing items with a durability of -1.
*
*/
public class ItemMap {
private HashMap<ItemStack, Integer> items;
private int totalItems;
/**
* Empty constructor to create empty item map
*/
public ItemMap() {
items = new HashMap<ItemStack, Integer>();
totalItems = 0;
}
/**
* Constructor to create an item map based on the content of an inventory.
* The ItemMap will not be in sync with the inventory, it will only update
* if it's explicitly told to do so
*
* @param inv
* Inventory to base the item map on
*/
public ItemMap(Inventory inv) {
totalItems = 0;
update(inv);
}
/**
* Constructor to create an ItemMap based on a single ItemStack
*
* @param is
* ItemStack to start with
*/
public ItemMap(ItemStack is) {
items = new HashMap<ItemStack, Integer>();
totalItems = 0;
addItemStack(is);
}
/**
* Constructor to create an item map based on a collection of ItemStacks
*
* @param stacks
* Stacks to add to the map
*/
public ItemMap(Collection<ItemStack> stacks) {
items = new HashMap<ItemStack, Integer>();
addAll(stacks);
}
public void addItemStack(ItemStack input) {
if (input != null) {
ItemStack is = createMapConformCopy(input);
if (is == null) {
return;
}
Integer i;
if ((i = items.get(is)) != null) {
items.put(is, i + input.getAmount());
} else {
items.put(is, input.getAmount());
}
totalItems += input.getAmount();
}
}
/**
* Removes the given ItemStack from this map. Only the amount of the given
* ItemStack will be removed, not all of them. If the amount of the given
* itemstack is bigger than the existing ones in this map, not more than the
* amount in this map will be removed
*
* @param input
* ItemStack to remove
*/
public void removeItemStack(ItemStack input) {
ItemStack is = createMapConformCopy(input);
if (is == null) {
return;
}
Integer value = items.get(is);
if (value != null) {
int newVal = value - input.getAmount();
if (newVal > 0) {
items.put(is, newVal);
} else {
items.remove(is);
}
}
}
/**
* Completly removes the given itemstack of this item map, completly
* independent of its amount
*
* @param input
* ItemStack to remove
*/
public void removeItemStackCompletly(ItemStack input) {
ItemStack is = createMapConformCopy(input);
if (is != null) {
items.remove(is);
}
}
public int hashCode() {
int res = 0;
for (Entry<ItemStack, Integer> entry : items.entrySet()) {
res += entry.hashCode();
}
return res;
}
/**
* Adds all the stacks given in the collection to this map
*
* @param stacks
* Stacks to add
*/
public void addAll(Collection<ItemStack> stacks) {
for (ItemStack is : stacks) {
if (is != null) {
addItemStack(is);
}
}
}
/**
* Merges the given item map into this instance
*
* @param im
* ItemMap to merge
*/
public void merge(ItemMap im) {
for (Entry<ItemStack, Integer> entry : im.getEntrySet()) {
addItemAmount(entry.getKey(), entry.getValue());
}
}
public void update(Inventory inv) {
items = new HashMap<ItemStack, Integer>();
totalItems = 0;
for (int i = 0; i < inv.getSize(); i++) {
ItemStack is = inv.getItem(i);
if (is != null) {
addItemStack(is);
}
}
}
public void addEntrySet(Set<Entry<ItemStack, Integer>> entries) {
for (Entry<ItemStack, Integer> entry : entries) {
addItemAmount(entry.getKey(), entry.getValue());
}
}
/**
* Utility method, which has the amount of items to add as parameter.
*
* @param input
* ItemStack to sort into the map
* @param amount
* Amount associated with the given ItemStack
*/
public void addItemAmount(ItemStack input, int amount) {
ItemStack copy = createMapConformCopy(input);
if (copy == null) {
return;
}
copy.setAmount(amount);
addItemStack(copy);
}
/**
* Gets a submap of this instance which contains all stacks with the same
* material as the given one and their respective amounts
*
* @param m
* Material to search for
* @return New ItemMap with all ItemStack and their amount whose material
* matches the given one
*/
public ItemMap getStacksByMaterial(Material m) {
ItemMap result = new ItemMap();
for (ItemStack is : items.keySet()) {
if (is.getType() == m) {
result.addItemAmount(is.clone(), items.get(is));
}
}
return result;
}
public ItemMap getStacksByMaterial(ItemStack is) {
return getStacksByMaterial(is.getType());
}
/**
* Gets a submap of this instance which contains all stacks with the same
* material and durability as the given one and their respective amounts
*
* @param m
* Material to search for
* @param durability
* Durability to search for
* @return New ItemMap with all ItemStack and their amount whose material
* and durability matches the given one
*/
public ItemMap getStacksByMaterialDurability(Material m, int durability) {
ItemMap result = new ItemMap();
for (ItemStack is : items.keySet()) {
if (is.getType() == m && is.getDurability() == durability) {
result.addItemAmount(is.clone(), items.get(is));
}
}
return result;
}
public ItemMap getStacksByMaterialDurability(ItemStack is) {
return getStacksByMaterialDurability(is.getType(), is.getDurability());
}
/**
* Gets a submap of this instance which contains all stacks with the same
* material, durability and enchants as the given one and their respective
* amounts
*
* @param m
* Material to search for
* @param durability
* Durability to search for
* @param enchants
* Enchants to search for
* @return New ItemMap with all ItemStack and their amount whose material,
* durability and enchants matches the given one
*/
public ItemMap getStacksByMaterialDurabilityEnchants(Material m,
int durability, Map<Enchantment, Integer> enchants) {
ItemMap result = new ItemMap();
for (ItemStack is : items.keySet()) {
if (is.getType() == m && is.getDurability() == durability
&& is.getItemMeta() != null
&& is.getItemMeta().getEnchants().equals(enchants)) {
result.addItemAmount(is.clone(), items.get(is));
}
}
return result;
}
public ItemMap getStacksByMaterialDurabilityEnchants(ItemStack is) {
if (is.getItemMeta() != null) {
return getStacksByMaterialDurabilityEnchants(is.getType(),
(int) is.getDurability(), is.getItemMeta().getEnchants());
} else {
return getStacksByMaterialDurabilityEnchants(is.getType(),
(int) is.getDurability(),
new HashMap<Enchantment, Integer>());
}
}
/**
* Gets a submap of this instance which contains all stacks with the same
* lore as the given and their respective amount
*
* @param lore
* Lore to search for
* @return New ItemMap with all ItemStacks and their amount whose lore
* matches the given one
*/
public ItemMap getStacksByLore(List<String> lore) {
ItemMap result = new ItemMap();
for (ItemStack is : items.keySet()) {
if (is.getItemMeta() != null
&& is.getItemMeta().getLore().equals(lore)) {
result.addItemAmount(is.clone(), items.get(is));
}
}
return result;
}
/**
* Gets how many items of the given stack are in this map. Be aware that if
* a stack doesnt equal with the given one, for example because of
* mismatched NBT tags, it wont be included in the result
*
* @param is
* Exact ItemStack to search for
* @return amount of items like the given stack in this map
*/
public int getAmount(ItemStack is) {
ItemMap matSubMap = getStacksByMaterial(is);
int amount = 0;
for (Entry<ItemStack, Integer> entry : matSubMap.getEntrySet()) {
ItemStack current = entry.getKey();
if ((is.getDurability() == -1 || is.getDurability() == current
.getDurability()) && is.getItemMeta().equals(current.getItemMeta())) {
amount += entry.getValue();
}
}
return amount;
}
/**
* @return How many items are stored in this map total
*/
public int getTotalItemAmount() {
return totalItems;
}
/**
* @return How many unique items are stored in this map
*/
public int getTotalUniqueItemAmount() {
return items.keySet().size();
}
public Set<Entry<ItemStack, Integer>> getEntrySet() {
return ((HashMap<ItemStack, Integer>) items.clone()).entrySet();
}
/**
* Checks whether an inventory contains exactly what's described in this
* ItemMap
*
* @param i
* Inventory to compare
* @return True if the inventory is identical with this instance, false if
* not
*/
public boolean containedExactlyIn(Inventory i) {
ItemMap invMap = new ItemMap(i);
for (Entry<ItemStack, Integer> entry : getEntrySet()) {
if (!entry.getValue().equals(invMap.getAmount(entry.getKey()))) {
return false;
}
}
for (ItemStack is : i.getContents()) {
if (is == null) {
continue;
}
if (getStacksByMaterial(is).getTotalUniqueItemAmount() == 0) {
return false;
}
}
return true;
}
/**
* Checks whether this instance is completly contained in the given
* inventory, which means every stack in this instance is also in the given
* inventory and the amount in the given inventory is either the same or
* bigger as in this instance
*
* @param im
* inventory to check
* @return true if this instance is completly contained in the given
* inventory, false if not
*/
public boolean isContainedIn(Inventory i) {
ItemMap invMap = new ItemMap(i);
for (Entry<ItemStack, Integer> entry : getEntrySet()) {
if (entry.getValue() > invMap.getAmount(entry.getKey())) {
return false;
}
}
return true;
}
public String toString() {
String res = "";
for (ItemStack is : getItemStackRepresentation()) {
res += is.toString() + ";";
}
return res;
}
/**
* Checks how often this ItemMap is contained in the given ItemMap or how
* often this ItemMap could be removed from the given one before creating
* negative stacks
*
* @param im
* ItemMap to check
* @return How often this map is contained in the given one or
* Integer.MAX_VALUE if this instance is empty
*/
public int getMultiplesContainedIn(Inventory i) {
ItemMap invMap = new ItemMap(i);
int res = Integer.MAX_VALUE;
for (Entry<ItemStack, Integer> entry : getEntrySet()) {
int pulledAmount = invMap.getAmount(entry.getKey());
int multiples = pulledAmount / entry.getValue();
res = Math.min(res, multiples);
}
return res;
}
/**
* Multiplies the whole content of this instance by the given multiplier
*
* @param multiplier
* Multiplier to scale the amount of the contained items with
*/
public void multiplyContent(double multiplier) {
totalItems = 0;
for (Entry<ItemStack, Integer> entry : getEntrySet()) {
items.put(entry.getKey(), (int) (entry.getValue() * multiplier));
totalItems += (int) (entry.getValue() * multiplier);
}
}
/**
* Turns this item map into a list of ItemStacks, with amounts that do not
* surpass the maximum allowed stack size for each ItemStack
*
* @return List of stacksize conform ItemStacks
*/
public LinkedList<ItemStack> getItemStackRepresentation() {
LinkedList<ItemStack> result = new LinkedList<ItemStack>();
for (Entry<ItemStack, Integer> entry : getEntrySet()) {
ItemStack is = entry.getKey();
Integer amount = entry.getValue();
while (amount != 0) {
ItemStack toAdd = is.clone();
int addAmount = Math.min(amount, is.getMaxStackSize());
toAdd.setAmount(addAmount);
result.add(toAdd);
amount -= addAmount;
}
}
return result;
}
/**
* Clones this map
*/
public ItemMap clone() {
ItemMap clone = new ItemMap();
for (Entry<ItemStack, Integer> entry : getEntrySet()) {
clone.addItemAmount(entry.getKey(), entry.getValue());
}
return clone;
}
/**
* Checks whether this instance would completly fit into the given inventory
*
* @param i
* Inventory to check
* @return True if this ItemMap's item representation would completly fit in
* the inventory, false if not
*/
public boolean fitsIn(Inventory i) {
ItemMap invCopy = new ItemMap(i);
ItemMap instanceCopy = this.clone();
instanceCopy.merge(invCopy);
return instanceCopy.getItemStackRepresentation().size() <= i.getSize();
}
/**
* Instead of converting into many stacks of maximum size, this creates a
* stack with an amount of one for each entry and adds the total item amount
* and stack count as lore, which is needed to display larger ItemMaps in
* inventories
*
* @return UI representation of large ItemMap
*/
public List<ItemStack> getLoredItemCountRepresentation() {
List<ItemStack> items = new LinkedList<ItemStack>();
for (Entry<ItemStack, Integer> entry : getEntrySet()) {
ItemStack is = entry.getKey().clone();
ISUtils.addLore(is,
ChatColor.GOLD + "Total item count: " + entry.getValue());
if (entry.getValue() > entry.getKey().getType().getMaxStackSize()) {
int stacks = entry.getValue() / is.getType().getMaxStackSize();
int extra = entry.getValue() % is.getType().getMaxStackSize();
StringBuilder out = new StringBuilder(ChatColor.GOLD.toString());
if (stacks != 0) {
out.append(stacks + " stack" + (stacks == 1 ? "" : "s"));
}
if (extra != 0) {
out.append(" and " + extra);
out.append(" item" + (extra == 1 ? "" : "s"));
}
ISUtils.addLore(is, out.toString());
}
items.add(is);
}
return items;
}
/**
* Attempts to remove the content of this ItemMap from the given inventory.
* If it fails to find all the required items it will stop and return false
*
* @param i
* Inventory to remove from
* @return True if everything was successfully removed, false if not
*/
public boolean removeSafelyFrom(Inventory i) {
for (Entry<ItemStack, Integer> entry : getEntrySet()) {
int amountToRemove = entry.getValue();
ItemStack is = entry.getKey();
for (ItemStack inventoryStack : i.getContents()) {
if (inventoryStack == null) {
continue;
}
if (inventoryStack.getType() == is.getType()) {
ItemMap compareMap = new ItemMap(inventoryStack);
int removeAmount = Math.min(amountToRemove,
compareMap.getAmount(is));
if (removeAmount != 0) {
ItemStack cloneStack = inventoryStack.clone();
cloneStack.setAmount(removeAmount);
if (i.removeItem(cloneStack).values().size() != 0) {
return false;
} else {
amountToRemove -= removeAmount;
if (amountToRemove <= 0) {
break;
}
}
}
}
}
if (amountToRemove > 0) {
return false;
}
}
return true;
}
public boolean equals(Object o) {
if (o instanceof ItemMap) {
ItemMap im = (ItemMap) o;
if (im.getTotalItemAmount() == getTotalItemAmount()) {
return im.getEntrySet().equals(getEntrySet());
}
}
return false;
}
/**
* Utility to not mess with stacks directly taken from inventories
*
* @param is
* Template ItemStack
* @return Cloned ItemStack with its amount set to 1
*/
private static ItemStack createMapConformCopy(ItemStack is) {
ItemStack copy = is.clone();
copy.setAmount(1);
net.minecraft.server.v1_8_R3.ItemStack s = CraftItemStack
.asNMSCopy(copy);
if (s == null) {
Bukkit.getServer()
.getLogger()
.log(Level.SEVERE,
"Attempted to create map conform copy of "
+ copy.toString()
+ ", but couldn't because this item can't be held in inventories since Minecraft 1.8");
return null;
}
s.setRepairCost(0);
copy = CraftItemStack.asBukkitCopy(s);
return copy;
}
}
|
package se.embargo.blockade.phone;
import java.lang.reflect.Method;
import java.util.concurrent.TimeUnit;
import se.embargo.blockade.MainActivity;
import se.embargo.blockade.R;
import se.embargo.blockade.SettingsActivity;
import se.embargo.blockade.database.BlockadeRepository;
import se.embargo.blockade.database.Phonecall;
import se.embargo.core.service.AbstractService;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.media.AudioManager;
import android.os.Binder;
import android.os.IBinder;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.TaskStackBuilder;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;
public class CallService extends AbstractService {
public static final String EXTRA_EVENT = "se.embargo.blacklist.phone.CallService.event";
public static final String EXTRA_STATE_BOOT = "boot";
public static final String EXTRA_STATE_RINGING = "ringing";
public static final String EXTRA_STATE_PHONENUMBER = "phonenumber";
private static final String TAG = "CallReceiver";
private static final int NOTIFICATION_ID = 0;
/**
* Application wide preferences
*/
protected SharedPreferences _prefs;
/**
* The listener needs to be kept alive since SharedPrefernces only keeps a weak reference to it
*/
private PreferencesListener _prefsListener = new PreferencesListener();
private AudioManager _audioManager;
private TelephonyManager _telephonyManager;
private PhoneStateListener _phoneStateListener;
private Integer _prevRingerMode = null;
@Override
public void onCreate() {
super.onCreate();
_audioManager = (AudioManager)getSystemService(AUDIO_SERVICE);
_telephonyManager = (TelephonyManager)getSystemService(TELEPHONY_SERVICE);
_prefs = getSharedPreferences(SettingsActivity.PREFS_NAMESPACE, Context.MODE_PRIVATE);
_prefs.registerOnSharedPreferenceChangeListener(_prefsListener);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
if (_phoneStateListener != null) {
_telephonyManager.listen(_phoneStateListener, 0);
_phoneStateListener = null;
}
_phoneStateListener = new StateListener();
_telephonyManager.listen(_phoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);
return START_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
_prefs.unregisterOnSharedPreferenceChangeListener(_prefsListener);
if (_phoneStateListener != null) {
_telephonyManager.listen(_phoneStateListener, 0);
_phoneStateListener = null;
}
}
private class StateListener extends PhoneStateListener {
@Override
public void onCallStateChanged(int state, String incomingNumber) {
switch (state) {
case TelephonyManager.CALL_STATE_IDLE:
restoreRingerMode();
break;
case TelephonyManager.CALL_STATE_RINGING:
handleIncomingCall(incomingNumber);
break;
case TelephonyManager.CALL_STATE_OFFHOOK:
restoreRingerMode();
break;
}
}
private void restoreRingerMode() {
if (_prevRingerMode != null) {
_audioManager.setRingerMode(_prevRingerMode);
_prevRingerMode = null;
}
}
}
private boolean handleIncomingCall(String phonenumber) {
Log.i(TAG, "Incoming call from: " + phonenumber);
if (phonenumber != null && !"".equals(phonenumber)) {
return false;
}
// Check if calls should be blocked
if (!_prefs.getBoolean(SettingsActivity.PREF_PHONECALL_BLOCK_PRIVATE, SettingsActivity.PREF_PHONECALL_BLOCK_PRIVATE_DEFAULT)) {
Log.i(TAG, "Call blocking disabled by preferences");
insert(Phonecall.Action.ALLOWED);
return false;
}
// Check how many calls were attempted in the last period
if (_prefs.getBoolean(SettingsActivity.PREF_PHONECALL_ALLOW_RETRY, SettingsActivity.PREF_PHONECALL_ALLOW_RETRY_DEFAULT)) {
int attempts = getRecentAttempts();
if (attempts >= (SettingsActivity.PREF_PHONECALL_ALLOW_RETRY_NUMBER - 1)) {
Log.i(TAG, "Allowing call through after " + attempts + " attempts");
insert(Phonecall.Action.ALLOWED);
return false;
}
}
// Disconnect call
Log.i(TAG, "Blocking call from: " + phonenumber);
if (!endCall()) {
return false;
}
// Insert into database
insert(Phonecall.Action.REJECTED);
// Notify about how many calls have been blocked
if (_prefs.getBoolean(SettingsActivity.PREF_PHONECALL_NOTIFY_BLOCKED, SettingsActivity.PREF_PHONECALL_NOTIFY_BLOCKED_DEFAULT)) {
PendingIntent contentIntent = TaskStackBuilder.create(this).
addParentStack(MainActivity.class).
addNextIntent(new Intent(this, MainActivity.class)).
getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this).
setSmallIcon(R.drawable.ic_notification_phone_missed).
setContentTitle(getString(R.string.msg_blocked_call)).
setContentText(getString(R.string.msg_blocked_incoming_call)).
setContentIntent(contentIntent).
setAutoCancel(true);
NotificationManager manager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
manager.notify(NOTIFICATION_ID, builder.build());
}
return true;
}
private void insert(Phonecall.Action action) {
ContentValues phonecall = Phonecall.create("", action);
getContentResolver().insert(BlockadeRepository.PHONECALL_URI, phonecall);
}
private int getRecentAttempts() {
Cursor c = getContentResolver().query(
BlockadeRepository.PHONECALL_URI,
new String[] { "COUNT(1) calls"},
"modified >= ?", new String[] {Long.toString(System.currentTimeMillis() - TimeUnit.MINUTES.toMillis(SettingsActivity.PREF_RETRY_PERIOD_DEFAULT))},
null);
c.moveToFirst();
int result = c.getInt(0);
c.close();
return result;
}
public boolean endCall() {
if (_prevRingerMode == null) {
_prevRingerMode = _audioManager.getRingerMode();
}
_audioManager.setRingerMode(AudioManager.RINGER_MODE_SILENT);
try {
String serviceManagerName = "android.os.ServiceManager";
String serviceManagerNativeName = "android.os.ServiceManagerNative";
String telephonyName = "com.android.internal.telephony.ITelephony";
Class<?> telephonyClass = Class.forName(telephonyName);
Class<?> telephonyStubClass = telephonyClass.getClasses()[0];
Class<?> serviceManagerClass = Class.forName(serviceManagerName);
Class<?> serviceManagerNativeClass = Class.forName(serviceManagerNativeName);
Binder tmpBinder = new Binder();
tmpBinder.attachInterface(null, "fake");
Method tempInterfaceMethod = serviceManagerNativeClass.getMethod("asInterface", IBinder.class);
Object serviceManagerObject = tempInterfaceMethod.invoke(null, tmpBinder);
Method getService = serviceManagerClass.getMethod("getService", String.class);
IBinder retbinder = (IBinder)getService.invoke(serviceManagerObject, "phone");
Method serviceMethod = telephonyStubClass.getMethod("asInterface", IBinder.class);
Object telephonyObject = serviceMethod.invoke(null, retbinder);
Method telephonyEndCall = telephonyClass.getMethod("endCall");
telephonyEndCall.invoke(telephonyObject);
return true;
}
catch (Exception e) {
Log.e(TAG, "Could not connect to telephony subsystem", e);
return false;
}
}
/**
* Listens for preference changes and applies updates
*/
private class PreferencesListener implements SharedPreferences.OnSharedPreferenceChangeListener {
@Override
public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
if (SettingsActivity.PREF_PHONECALL_NOTIFY_BLOCKED.equals(key)) {
if (!prefs.getBoolean(SettingsActivity.PREF_PHONECALL_NOTIFY_BLOCKED, SettingsActivity.PREF_PHONECALL_NOTIFY_BLOCKED_DEFAULT)) {
NotificationManager manager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
manager.cancel(NOTIFICATION_ID);
}
}
}
}
}
|
package seedu.addressbook.storage;
import seedu.addressbook.data.AddressBook;
import seedu.addressbook.data.exception.IllegalValueException;
import seedu.addressbook.storage.jaxb.AdaptedAddressBook;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Reader;
import java.io.Writer;
import java.nio.file.Path;
import java.nio.file.Paths;
/**
* Represents the file used to store address book data.
*/
public class StorageFile {
/** Default file path used if the user doesn't provide the file name. */
public static final String DEFAULT_STORAGE_FILEPATH = "addressbook.xml";
/**
* Signals that the given file path does not fulfill the storage filepath constraints.
*/
public static class InvalidStorageFilePathException extends IllegalValueException {
public InvalidStorageFilePathException(String message) {
super(message);
}
}
/**
* Signals that some error has occured while trying to convert and read/write data between the application
* and the storage file.
*/
public static class StorageOperationException extends Exception {
public StorageOperationException(String message) {
super(message);
}
}
private final JAXBContext jaxbContext;
public final Path path;
/**
* @throws InvalidStorageFilePathException if the default path is invalid
*/
public StorageFile() throws InvalidStorageFilePathException {
this(DEFAULT_STORAGE_FILEPATH);
}
/**
* @throws InvalidStorageFilePathException if the given file path is invalid
*/
public StorageFile(String filePath) throws InvalidStorageFilePathException {
try {
jaxbContext = JAXBContext.newInstance(AdaptedAddressBook.class);
} catch (JAXBException jaxbe) {
throw new RuntimeException("jaxb initialisation error");
}
path = Paths.get(filePath);
if (!isValidPath(path)) {
throw new InvalidStorageFilePathException("Storage file should end with '.xml'");
}
}
/**
* Returns true if the given path is acceptable as a storage file.
* The file path is considered acceptable if it ends with '.xml'
*/
private static boolean isValidPath(Path filePath) {
return filePath.toString().endsWith(".xml");
}
/**
* Saves all data to this storage file.
*
* @throws StorageOperationException if there were errors converting and/or storing data to file.
*/
public void save(AddressBook addressBook) throws StorageOperationException {
try (final Writer fileWriter =
new BufferedWriter(new FileWriter(path.toFile()))) {
final AdaptedAddressBook toSave = new AdaptedAddressBook(addressBook);
final Marshaller marshaller = jaxbContext.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(toSave, fileWriter);
} catch (IOException ioe) {
throw new StorageOperationException("Error writing to file: " + path);
} catch (JAXBException jaxbe) {
throw new StorageOperationException("Error converting address book into storage format");
}
}
/**
* Loads data from this storage file.
*
* @throws StorageOperationException if there were errors reading and/or converting data from file.
*/
public AddressBook load() throws StorageOperationException, FileNotFoundException {
try (final Reader fileReader =
new BufferedReader(new FileReader(path.toFile()))) {
final Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
final AdaptedAddressBook loaded = (AdaptedAddressBook) unmarshaller.unmarshal(fileReader);
// manual check for missing elements
if (loaded.isAnyRequiredFieldMissing()) {
throw new StorageOperationException("File data missing some elements");
}
if (!path.toFile().exists()){
throw new FileNotFoundException("Storage file does not exist.");
}
return loaded.toModelType();
/* Note: Here, we are using an exception to create the file if it is missing. However, we should minimize
* using exceptions to facilitate normal paths of execution. If we consider the missing file as a 'normal'
* situation (i.e. not truly exceptional) we should not use an exception to handle it.
*/
// create empty file if not found
} catch (FileNotFoundException fnfe) {
final AddressBook empty = new AddressBook();
save(empty);
return empty;
// other errors
} catch (IOException ioe) {
throw new StorageOperationException("Error writing to file: " + path);
} catch (JAXBException jaxbe) {
throw new StorageOperationException("Error parsing file data format");
} catch (IllegalValueException ive) {
throw new StorageOperationException("File contains illegal data values; data type constraints not met");
}
}
public String getPath() {
return path.toString();
}
}
|
package soot.jimple.infoflow.data;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import soot.NullType;
import soot.SootMethod;
import soot.Type;
import soot.Unit;
import soot.Value;
import soot.jimple.Stmt;
import soot.jimple.infoflow.InfoflowConfiguration;
import soot.jimple.infoflow.collect.AtomicBitSet;
import soot.jimple.infoflow.collect.ConcurrentHashSet;
import soot.jimple.infoflow.solver.cfg.IInfoflowCFG.UnitContainer;
import soot.jimple.infoflow.solver.fastSolver.FastSolverLinkedNode;
import soot.jimple.internal.JimpleLocal;
import com.google.common.collect.Sets;
/**
* The abstraction class contains all information that is necessary to track the taint.
*
* @author Steven Arzt
* @author Christian Fritz
*/
public class Abstraction implements Cloneable, FastSolverLinkedNode<Abstraction, Unit> {
private static boolean flowSensitiveAliasing = true;
/**
* the access path contains the currently tainted variable or field
*/
private AccessPath accessPath;
private Abstraction predecessor = null;
private Set<Abstraction> neighbors = null;
private Stmt currentStmt = null;
private Stmt correspondingCallSite = null;
private SourceContext sourceContext = null;
// only used in path generation
private Set<SourceContextAndPath> pathCache = null;
/**
* Unit/Stmt which activates the taint when the abstraction passes it
*/
private Unit activationUnit = null;
/**
* taint is thrown by an exception (is set to false when it reaches the catch-Stmt)
*/
private boolean exceptionThrown = false;
private int hashCode = 0;
/**
* The postdominators we need to pass in order to leave the current conditional
* branch. Do not use the synchronized Stack class here to avoid deadlocks.
*/
private List<UnitContainer> postdominators = null;
private boolean isImplicit = false;
/**
* Only valid for inactive abstractions. Specifies whether an access paths
* has been cut during alias analysis.
*/
private boolean dependsOnCutAP = false;
private AtomicBitSet pathFlags = null;
public Abstraction(AccessPath sourceVal,
Stmt sourceStmt,
Object userData,
boolean exceptionThrown,
boolean isImplicit){
this(sourceVal,
new SourceContext(sourceVal, sourceStmt, userData),
exceptionThrown, isImplicit);
}
protected Abstraction(AccessPath apToTaint,
SourceContext sourceContext,
boolean exceptionThrown,
boolean isImplicit){
this.sourceContext = sourceContext;
this.accessPath = apToTaint;
this.activationUnit = null;
this.exceptionThrown = exceptionThrown;
this.neighbors = null;
this.isImplicit = isImplicit;
this.currentStmt = sourceContext == null ? null : sourceContext.getStmt();
}
/**
* Creates an abstraction as a copy of an existing abstraction,
* only exchanging the access path. -> only used by AbstractionWithPath
* @param p The access path for the new abstraction
* @param original The original abstraction to copy
*/
protected Abstraction(AccessPath p, Abstraction original){
if (original == null) {
sourceContext = null;
exceptionThrown = false;
activationUnit = null;
isImplicit = false;
}
else {
sourceContext = original.sourceContext;
exceptionThrown = original.exceptionThrown;
activationUnit = original.activationUnit;
assert activationUnit == null || flowSensitiveAliasing;
postdominators = original.postdominators == null ? null
: new ArrayList<UnitContainer>(original.postdominators);
dependsOnCutAP = original.dependsOnCutAP;
isImplicit = original.isImplicit;
}
accessPath = p;
neighbors = null;
currentStmt = null;
}
public final Abstraction deriveInactiveAbstraction(Unit activationUnit){
if (!flowSensitiveAliasing) {
assert this.isAbstractionActive();
return this;
}
// If this abstraction is already inactive, we keep it
if (!this.isAbstractionActive())
return this;
Abstraction a = deriveNewAbstractionMutable(accessPath, null);
a.postdominators = null;
a.activationUnit = activationUnit;
a.dependsOnCutAP |= a.getAccessPath().isCutOffApproximation();
return a;
}
public Abstraction deriveNewAbstraction(AccessPath p, Stmt currentStmt){
return deriveNewAbstraction(p, currentStmt, isImplicit);
}
public Abstraction deriveNewAbstraction(AccessPath p, Stmt currentStmt,
boolean isImplicit){
// If the new abstraction looks exactly like the current one, there is
// no need to create a new object
if (this.accessPath.equals(p) && this.currentStmt == currentStmt
&& this.isImplicit == isImplicit)
return this;
Abstraction abs = deriveNewAbstractionMutable(p, currentStmt);
abs.isImplicit = isImplicit;
return abs;
}
private Abstraction deriveNewAbstractionMutable(AccessPath p, Stmt currentStmt){
if (this.accessPath.equals(p) && this.currentStmt == currentStmt) {
Abstraction abs = clone();
abs.currentStmt = currentStmt;
return abs;
}
Abstraction abs = new Abstraction(p, this);
abs.predecessor = this;
abs.currentStmt = currentStmt;
if (!abs.getAccessPath().isEmpty())
abs.postdominators = null;
if (!abs.isAbstractionActive())
abs.dependsOnCutAP = abs.dependsOnCutAP || p.isCutOffApproximation();
abs.sourceContext = null;
return abs;
}
public final Abstraction deriveNewAbstraction(Value taint, boolean cutFirstField, Stmt currentStmt,
Type baseType) {
return deriveNewAbstraction(taint, cutFirstField, currentStmt, baseType, false);
}
public final Abstraction deriveNewAbstraction(Value taint, boolean cutFirstField, Stmt currentStmt,
Type baseType, boolean isArrayLength) {
assert !this.getAccessPath().isEmpty();
AccessPath newAP = accessPath.copyWithNewValue(taint, baseType, cutFirstField, true,
isArrayLength);
if (this.getAccessPath().equals(newAP) && this.currentStmt == currentStmt)
return this;
return deriveNewAbstractionMutable(newAP, currentStmt);
}
/**
* Derives a new abstraction that models the current local being thrown as
* an exception
* @param throwStmt The statement at which the exception was thrown
* @return The newly derived abstraction
*/
public final Abstraction deriveNewAbstractionOnThrow(Stmt throwStmt){
assert !this.exceptionThrown;
Abstraction abs = clone();
abs.currentStmt = throwStmt;
abs.sourceContext = null;
abs.exceptionThrown = true;
return abs;
}
/**
* Derives a new abstraction that models the current local being caught as
* an exception
* @param taint The value in which the tainted exception is stored
* @return The newly derived abstraction
*/
public final Abstraction deriveNewAbstractionOnCatch(Value taint){
assert this.exceptionThrown;
Abstraction abs = deriveNewAbstractionMutable(new AccessPath(taint, true), null);
abs.exceptionThrown = false;
return abs;
}
/**
* Gets the path of statements from the source to the current statement
* with which this abstraction is associated. If this path is ambiguous,
* a single path is selected randomly.
* @return The path from the source to the current statement
*/
public Set<SourceContextAndPath> getPaths() {
return pathCache == null ? null : Collections.unmodifiableSet(pathCache);
}
public Set<SourceContextAndPath> getOrMakePathCache() {
// We're optimistic about having a path cache. If we definitely have one,
// we return it. Otherwise, we need to lock and create one.
if (this.pathCache == null)
synchronized (this) {
if (this.pathCache == null)
this.pathCache = new ConcurrentHashSet<SourceContextAndPath>();
}
return Collections.unmodifiableSet(pathCache);
}
public boolean addPathElement(SourceContextAndPath scap) {
if (this.pathCache == null) {
synchronized (this) {
if (this.pathCache == null) {
this.pathCache = new ConcurrentHashSet<SourceContextAndPath>();
}
}
}
return this.pathCache.add(scap);
}
public void clearPathCache() {
this.pathCache = null;
}
public boolean isAbstractionActive() {
return activationUnit == null;
}
public boolean isImplicit() {
return isImplicit;
}
@Override
public String toString(){
return (isAbstractionActive()?"":"_")+accessPath.toString() + " | "+(activationUnit==null?"":activationUnit.toString()) + ">>";
}
public AccessPath getAccessPath(){
return accessPath;
}
public Unit getActivationUnit(){
return this.activationUnit;
}
public Abstraction getActiveCopy(){
assert !this.isAbstractionActive();
Abstraction a = clone();
a.sourceContext = null;
a.activationUnit = null;
return a;
}
/**
* Gets whether this value has been thrown as an exception
* @return True if this value has been thrown as an exception, otherwise
* false
*/
public boolean getExceptionThrown() {
return this.exceptionThrown;
}
public final Abstraction deriveConditionalAbstractionEnter(UnitContainer postdom,
Stmt conditionalUnit) {
assert this.isAbstractionActive();
if (postdominators != null && postdominators.contains(postdom))
return this;
Abstraction abs = deriveNewAbstractionMutable
(AccessPath.getEmptyAccessPath(), conditionalUnit);
if (abs.postdominators == null)
abs.postdominators = Collections.singletonList(postdom);
else
abs.postdominators.add(0, postdom);
return abs;
}
public final Abstraction deriveConditionalAbstractionCall(Unit conditionalCallSite) {
assert this.isAbstractionActive();
assert conditionalCallSite != null;
Abstraction abs = deriveNewAbstractionMutable
(AccessPath.getEmptyAccessPath(), (Stmt) conditionalCallSite);
// Postdominators are only kept intraprocedurally in order to not
// mess up the summary functions with caller-side information
abs.postdominators = null;
return abs;
}
public final Abstraction dropTopPostdominator() {
if (postdominators == null || postdominators.isEmpty())
return this;
Abstraction abs = clone();
abs.sourceContext = null;
abs.postdominators.remove(0);
return abs;
}
public UnitContainer getTopPostdominator() {
if (postdominators == null || postdominators.isEmpty())
return null;
return this.postdominators.get(0);
}
public boolean isTopPostdominator(Unit u) {
UnitContainer uc = getTopPostdominator();
if (uc == null)
return false;
return uc.getUnit() == u;
}
public boolean isTopPostdominator(SootMethod sm) {
UnitContainer uc = getTopPostdominator();
if (uc == null)
return false;
return uc.getMethod() == sm;
}
@Override
public Abstraction clone() {
Abstraction abs = new Abstraction(accessPath, this);
abs.predecessor = this;
abs.neighbors = null;
abs.currentStmt = null;
assert abs.equals(this);
return abs;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null || getClass() != obj.getClass())
return false;
Abstraction other = (Abstraction) obj;
// If we have already computed hash codes, we can use them for
// comparison
if (this.hashCode != 0
&& other.hashCode != 0
&& this.hashCode != other.hashCode)
return false;
if (accessPath == null) {
if (other.accessPath != null)
return false;
} else if (!accessPath.equals(other.accessPath))
return false;
return localEquals(other);
}
/**
* Checks whether this object locally equals the given object, i.e. the both
* are equal modulo the access path
* @param other The object to compare this object with
* @return True if this object is locally equal to the given one, otherwise
* false
*/
private boolean localEquals(Abstraction other) {
// deliberately ignore prevAbs
if (sourceContext == null) {
if (other.sourceContext != null)
return false;
} else if (!sourceContext.equals(other.sourceContext))
return false;
if (activationUnit == null) {
if (other.activationUnit != null)
return false;
} else if (!activationUnit.equals(other.activationUnit))
return false;
if (this.exceptionThrown != other.exceptionThrown)
return false;
if (postdominators == null) {
if (other.postdominators != null)
return false;
} else if (!postdominators.equals(other.postdominators))
return false;
if(this.dependsOnCutAP != other.dependsOnCutAP)
return false;
if(this.isImplicit != other.isImplicit)
return false;
return true;
}
@Override
public int hashCode() {
if (this.hashCode != 0)
return hashCode;
final int prime = 31;
int result = 1;
// deliberately ignore prevAbs
result = prime * result + ((sourceContext == null) ? 0 : sourceContext.hashCode());
result = prime * result + ((accessPath == null) ? 0 : accessPath.hashCode());
result = prime * result + ((activationUnit == null) ? 0 : activationUnit.hashCode());
result = prime * result + (exceptionThrown ? 1231 : 1237);
result = prime * result + ((postdominators == null) ? 0 : postdominators.hashCode());
result = prime * result + (dependsOnCutAP ? 1231 : 1237);
result = prime * result + (isImplicit ? 1231 : 1237);
this.hashCode = result;
return this.hashCode;
}
/**
* Checks whether this abstraction entails the given abstraction, i.e. this
* taint also taints everything that is tainted by the given taint.
* @param other The other taint abstraction
* @return True if this object at least taints everything that is also tainted
* by the given object
*/
public boolean entails(Abstraction other) {
if (accessPath == null) {
if (other.accessPath != null)
return false;
} else if (!accessPath.entails(other.accessPath))
return false;
return localEquals(other);
}
/**
* Gets the context of the taint, i.e. the statement and value of the source
* @return The statement and value of the source
*/
public SourceContext getSourceContext() {
return sourceContext;
}
public boolean dependsOnCutAP() {
return dependsOnCutAP;
}
@Override
public Abstraction getPredecessor() {
return this.predecessor;
}
public Set<Abstraction> getNeighbors() {
return this.neighbors;
}
public Stmt getCurrentStmt() {
return this.currentStmt;
}
@Override
public void addNeighbor(Abstraction originalAbstraction) {
// We should not register ourselves as a neighbor
if (originalAbstraction == this)
return;
// We should not add identical nodes as neighbors
if (this.predecessor == originalAbstraction.predecessor
&& this.currentStmt == originalAbstraction.currentStmt
&& this.predecessor == originalAbstraction.predecessor)
return;
synchronized (this) {
if (neighbors == null)
neighbors = Sets.newIdentityHashSet();
else if (InfoflowConfiguration.getMergeNeighbors()) {
// Check if we already have an identical neighbor
for (Abstraction nb : neighbors) {
if (nb == originalAbstraction)
return;
if (originalAbstraction.predecessor == nb.predecessor
&& originalAbstraction.currentStmt == nb.currentStmt
&& originalAbstraction.correspondingCallSite == nb.correspondingCallSite) {
return;
}
}
}
this.neighbors.add(originalAbstraction);
}
}
public void setCorrespondingCallSite(Stmt callSite) {
this.correspondingCallSite = callSite;
}
public Stmt getCorrespondingCallSite() {
return this.correspondingCallSite;
}
public static Abstraction getZeroAbstraction(boolean flowSensitiveAliasing) {
Abstraction zeroValue = new Abstraction(
new AccessPath(new JimpleLocal("zero", NullType.v()), false),
null,
false,
false);
Abstraction.flowSensitiveAliasing = flowSensitiveAliasing;
return zeroValue;
}
@Override
public void setPredecessor(Abstraction predecessor) {
this.predecessor = predecessor;
}
@Override
public void setCallingContext(Abstraction callingContext) {
}
/**
* Only use this method if you really need to fake a source context and know
* what you are doing.
* @param sourceContext The new source context
*/
public void setSourceContext(SourceContext sourceContext) {
this.sourceContext = sourceContext;
}
/**
* Registers that a worker thread with the given ID has already processed
* this abstraction
* @param id The ID of the worker thread
* @return True if the worker thread with the given ID has not been
* registered before, otherwise false
*/
public boolean registerPathFlag(int id, int maxSize) {
if (pathFlags != null && id < pathFlags.size() && pathFlags.get(id))
return false;
if (pathFlags == null) {
synchronized (this) {
if (pathFlags == null) {
// Make sure that the field is set only after the constructor
// is done and the object is fully usable
AtomicBitSet pf = new AtomicBitSet(maxSize);
pathFlags = pf;
}
}
}
return pathFlags.set(id);
}
public Abstraction injectSourceContext(SourceContext sourceContext) {
if (this.sourceContext != null && this.sourceContext.equals(sourceContext))
return this;
Abstraction abs = clone();
abs.predecessor = null;
abs.neighbors = null;
abs.sourceContext = sourceContext;
abs.currentStmt = this.currentStmt;
return abs;
}
/**
* For internal use by memory manager only. Setting a new access path will
* not update any dependent data such as cached hashes. Handle with care!
*/
void setAccessPath(AccessPath accessPath) {
this.accessPath = accessPath;
}
void setCurrentStmt(Stmt currentStmt) {
this.currentStmt = currentStmt;
}
}
|
package com.twu.biblioteca;
import org.junit.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.Is.is;
public class UserTest {
@Test
public void getUsernameReturnsUsernameString() {
String username = "user";
User user = new User(username, "pass");
assertThat(user.getUsername(), is(username));
}
@Test
public void getPasswordReturnsPasswordString() {
String password = "pass";
User user = new User("user", password);
assertThat(user.getPassword(), is(password));
}
}
|
package io.iron.test;
import io.iron.ironworker.client.entities.*;
import io.iron.ironworker.client.*;
import junit.framework.Assert;
import org.junit.Before;
import org.junit.Test;
import java.util.Properties;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.IOException;
public class IronWorkerTest {
private String queueName = "java-testing-queue";
private Client client;
@Before
public void setUp() throws Exception {
Properties prop = new Properties();
InputStream input = null;
try {
input = new FileInputStream("config.properties");
} catch(FileNotFoundException fnfe) {
System.out.println("config.properties not found");
input = new FileInputStream("../../config.properties"); //maven release hack
}
prop.load(input);
String token = prop.getProperty("token");
String projectId = prop.getProperty("project_id");
client = new Client(token, projectId);
}
@Test
public void testCreatingTask() throws IOException, APIException {
String id = client.createTask("MonoWorker101").getId();
Assert.assertTrue(id.length() > 0);
}
@Test
public void testViewingTaskInfoAfterTaskCreation() throws IOException, APIException {
TaskEntity task = client.createTask("MonoWorker101");
Assert.assertTrue(task.getId().length() > 0);
Assert.assertNull(task.getCodeId());
Assert.assertNull(task.getCodeName());
Assert.assertNull(task.getStatus());
Assert.assertNull(task.getPayload());
Assert.assertNull(task.getCreatedAt());
Assert.assertNull(task.getUpdatedAt());
}
@Test
public void testGetTaskInfo() throws IOException, APIException, InterruptedException {
String id = client.createTask("MonoWorker101").getId();
Thread.sleep(1000);
TaskEntity task = client.getTask(id);
Assert.assertTrue(task.getId().length() > 0);
Assert.assertTrue(task.getCodeId().length() > 0);
Assert.assertTrue(task.getCodeName().length() > 0);
Assert.assertTrue(task.getStatus().length() > 0);
Assert.assertTrue(task.getPayload().length() > 0);
Assert.assertNotNull(task.getCreatedAt());
Assert.assertNotNull(task.getUpdatedAt());
}
@Test
public void testTaskReloadInfo() throws IOException, APIException, InterruptedException {
TaskEntity task = client.createTask("MonoWorker101");
Thread.sleep(1000);
client.reload(task);
Assert.assertTrue(task.getId().length() > 0);
Assert.assertTrue(task.getCodeId().length() > 0);
Assert.assertTrue(task.getCodeName().length() > 0);
Assert.assertTrue(task.getStatus().length() > 0);
Assert.assertTrue(task.getPayload().length() > 0);
Assert.assertNotNull(task.getCreatedAt());
Assert.assertNotNull(task.getUpdatedAt());
}
@Test
public void testSchedulingTask() throws IOException, APIException {
String id = client.createSchedule("MonoWorker101").getId();
Assert.assertTrue(id.length() > 0);
}
@Test
public void testSchedulingInfo() throws IOException, APIException, InterruptedException {
String id = client.createSchedule("MonoWorker101").getId();
Thread.sleep(1000);
ScheduleEntity schedule = client.getSchedule(id);
Assert.assertTrue(schedule.getId().length() > 0);
Assert.assertTrue(schedule.getCodeName().length() > 0);
Assert.assertTrue(schedule.getStatus().length() > 0);
Assert.assertTrue(schedule.getPayload().length() > 0);
Assert.assertNotNull(schedule.getCreatedAt());
Assert.assertNotNull(schedule.getUpdatedAt());
}
@Test
public void testReloadSchedule() throws IOException, APIException, InterruptedException {
ScheduleEntity schedule = client.createSchedule("MonoWorker101");
Thread.sleep(1000);
client.reload(schedule);
Assert.assertTrue(schedule.getId().length() > 0);
Assert.assertTrue(schedule.getCodeName().length() > 0);
Assert.assertTrue(schedule.getStatus().length() > 0);
Assert.assertTrue(schedule.getPayload().length() > 0);
Assert.assertNotNull(schedule.getCreatedAt());
Assert.assertNotNull(schedule.getUpdatedAt());
}
}
|
package io.teknek.nibiru;
import java.io.File;
import java.io.IOException;
import io.teknek.nibiru.Server;
import io.teknek.nibiru.engine.Keyspace;
import io.teknek.nibiru.engine.SSTableTest;
import io.teknek.nibiru.engine.Val;
import io.teknek.nibiru.metadata.KeyspaceMetadata;
import io.teknek.nibiru.partitioner.NaturalPartitioner;
import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
public class ServerTest {
@Rule
public TemporaryFolder testFolder = new TemporaryFolder();
@Test
public void aTest() throws IOException, InterruptedException{
String ks = "data";
String cf = "pets";
Configuration configuration = aBasicConfiguration(testFolder);
Server s = new Server(configuration);
s.init();
s.createKeyspace(ks);
s.createColumnFamily(ks, cf);
s.getKeyspaces().get(ks).getColumnFamilies().get(cf).getColumnFamilyMetadata().setFlushNumberOfRowKeys(2);
s.put(ks, cf, "jack", "name", "bunnyjack", 1);
s.put(ks, cf, "jack", "age", "6", 1);
Val x = s.get(ks, cf, "jack", "age");
Assert.assertEquals("6", x.getValue());
s.put(ks, cf, "ziggy", "name", "ziggyrabbit", 1);
s.put(ks, cf, "ziggy", "age", "8", 1);
s.put(ks, cf, "dotty", "age", "4", 1);
Thread.sleep(2000);
Assert.assertEquals(2, s.getKeyspaces().get(ks).getColumnFamilies().get(cf).getMemtableFlusher().getFlushCount());
x = s.get(ks, cf, "jack", "age");
Assert.assertEquals("6", x.getValue());
}
@Test
public void compactionTest() throws IOException, InterruptedException{
String ks = "data";
String cf = "pets";
Configuration configuration = aBasicConfiguration(testFolder);
Server s = new Server(configuration);
s.init();
s.createKeyspace(ks);
s.createColumnFamily(ks, cf);
s.getKeyspaces().get(ks).getColumnFamilies().get(cf).getColumnFamilyMetadata().setFlushNumberOfRowKeys(2);
for (int i = 0; i < 9; i++) {
s.put(ks, cf, i+"", "age", "4", 1);
Thread.sleep(1);
}
Val x = s.get(ks, cf, "8", "age");
Thread.sleep(1000);
Assert.assertEquals(4, s.getKeyspaces().get(ks).getColumnFamilies().get(cf).getMemtableFlusher().getFlushCount());
Assert.assertEquals(1, s.getCompactionManager().getNumberOfCompactions());
Assert.assertEquals("4", x.getValue());
for (int i = 0; i < 9; i++) {
Val y = s.get(ks, cf, i+"", "age");
Assert.assertEquals("4", y.getValue());
}
}
@Test
public void commitLogTests() throws IOException, InterruptedException{
String ks = "data";
String cf = "pets";
Configuration configuration = aBasicConfiguration(testFolder);
Server s = new Server(configuration);
s.init();
s.createKeyspace(ks);
s.createColumnFamily(ks, cf);
s.getKeyspaces().get(ks).getColumnFamilies().get(cf).getColumnFamilyMetadata().setFlushNumberOfRowKeys(2);
System.out.println(s.getKeyspaces().get(ks).getKeyspaceMetadata());
for (int i = 0; i < 2; i++) {
s.put(ks, cf, i+"", "age", "4", 1);
Thread.sleep(1);
}
Val x = s.get(ks, cf, "0", "age");
Assert.assertEquals("4", x.getValue());
Thread.sleep(1000);
s.shutdown();
Thread.sleep(1000);
{
Server j = new Server(configuration);
j.init();
Assert.assertNotNull(j.getKeyspaces().get(ks).getColumnFamilies().get(cf));
Val y = j.get(ks, cf, "0", "age");
Assert.assertEquals("4", y.getValue());
}
}
public static Configuration aBasicConfiguration(TemporaryFolder testFolder){
File tempFolder = testFolder.newFolder("sstable");
File commitlog = testFolder.newFolder("commitlog");
Configuration configuration = new Configuration();
configuration.setSstableDirectory(tempFolder);
configuration.setCommitlogDirectory(commitlog);
return configuration;
}
}
|
package arez.processor;
final class Constants
{
static final String SUPPRESS_AREZ_WARNINGS_CLASSNAME = "arez.annotations.SuppressArezWarnings";
static final String ACTION_CLASSNAME = "arez.annotations.Action";
static final String COMPONENT_CLASSNAME = "arez.annotations.ArezComponent";
static final String ACT_AS_COMPONENT_CLASSNAME = "arez.annotations.ActAsComponent";
static final String OBSERVE_CLASSNAME = "arez.annotations.Observe";
static final String CASCADE_DISPOSE_CLASSNAME = "arez.annotations.CascadeDispose";
static final String COMPONENT_DEPENDENCY_CLASSNAME = "arez.annotations.ComponentDependency";
static final String REFERENCE_CLASSNAME = "arez.annotations.Reference";
static final String INVERSE_CLASSNAME = "arez.annotations.Inverse";
static final String REFERENCE_ID_CLASSNAME = "arez.annotations.ReferenceId";
static final String COMPONENT_ID_CLASSNAME = "arez.annotations.ComponentId";
static final String COMPONENT_ID_REF_CLASSNAME = "arez.annotations.ComponentIdRef";
static final String COMPONENT_NAME_REF_CLASSNAME = "arez.annotations.ComponentNameRef";
static final String COMPONENT_REF_CLASSNAME = "arez.annotations.ComponentRef";
static final String COMPONENT_STATE_REF_CLASSNAME = "arez.annotations.ComponentStateRef";
static final String COMPONENT_TYPE_NAME_REF_CLASSNAME = "arez.annotations.ComponentTypeNameRef";
static final String COMPUTABLE_VALUE_REF_CLASSNAME = "arez.annotations.ComputableValueRef";
static final String CONTEXT_REF_CLASSNAME = "arez.annotations.ContextRef";
static final String MEMOIZE_CLASSNAME = "arez.annotations.Memoize";
static final String OBSERVABLE_CLASSNAME = "arez.annotations.Observable";
static final String OBSERVABLE_VALUE_REF_CLASSNAME = "arez.annotations.ObservableValueRef";
static final String OBSERVER_REF_CLASSNAME = "arez.annotations.ObserverRef";
static final String ON_ACTIVATE_CLASSNAME = "arez.annotations.OnActivate";
static final String ON_DEACTIVATE_CLASSNAME = "arez.annotations.OnDeactivate";
static final String ON_DEPS_CHANGE_CLASSNAME = "arez.annotations.OnDepsChange";
static final String POST_CONSTRUCT_CLASSNAME = "arez.annotations.PostConstruct";
static final String POST_DISPOSE_CLASSNAME = "arez.annotations.PostDispose";
static final String PRE_DISPOSE_CLASSNAME = "arez.annotations.PreDispose";
static final String POST_INVERSE_ADD_CLASSNAME = "arez.annotations.PostInverseAdd";
static final String PRE_INVERSE_REMOVE_CLASSNAME = "arez.annotations.PreInverseRemove";
static final String COMPUTABLE_VALUE_CLASSNAME = "arez.ComputableValue";
static final String OBSERVER_CLASSNAME = "arez.Observer";
static final String DISPOSABLE_CLASSNAME = "arez.Disposable";
static final String DISPOSE_NOTIFIER_CLASSNAME = "arez.component.DisposeNotifier";
static final String EJB_POST_CONSTRUCT_CLASSNAME = "javax.annotation.PostConstruct";
static final String JAX_WS_ACTION_CLASSNAME = "javax.xml.ws.Action";
static final String INJECT_CLASSNAME = "javax.inject.Inject";
static final String SCOPE_CLASSNAME = "javax.inject.Scope";
static final String STING_INJECTOR = "sting.Injector";
static final String STING_CONTRIBUTE_TO = "sting.ContributeTo";
static final String STING_NAMED = "sting.Named";
static final String STING_EAGER = "sting.Eager";
static final String STING_TYPED = "sting.Typed";
static final String JSR_330_NAMED_CLASSNAME = "javax.inject.Named";
static final String DAGGER_MODULE_CLASSNAME = "dagger.Module";
static final String SENTINEL = "<default>";
static final String WARNING_PUBLIC_LIFECYCLE_METHOD = "Arez:PublicLifecycleMethod";
static final String WARNING_PROTECTED_LIFECYCLE_METHOD = "Arez:ProtectedLifecycleMethod";
static final String WARNING_PUBLIC_HOOK_METHOD = "Arez:PublicHookMethod";
static final String WARNING_PROTECTED_HOOK_METHOD = "Arez:ProtectedHookMethod";
static final String WARNING_PUBLIC_REF_METHOD = "Arez:PublicRefMethod";
static final String WARNING_PROTECTED_REF_METHOD = "Arez:ProtectedRefMethod";
static final String WARNING_UNMANAGED_COMPONENT_REFERENCE = "Arez:UnmanagedComponentReference";
static final String WARNING_UNNECESSARY_DEFAULT_PRIORITY = "Arez:UnnecessaryDefaultPriority";
static final String WARNING_UNNECESSARY_ALLOW_EMPTY = "Arez:UnnecessaryAllowEmpty";
static final String WARNING_UNNECESSARY_DEFAULT = "Arez:UnnecessaryDefault";
static final String WARNING_PROTECTED_CONSTRUCTOR = "Arez:ProtectedConstructor";
static final String WARNING_PUBLIC_CONSTRUCTOR = "Arez:PublicConstructor";
private Constants()
{
}
}
|
package com.mygdx.handlers;
import com.mygdx.entities.Enemy;
import com.mygdx.entities.EnemyFactory;
import com.mygdx.entities.Entity;
import com.mygdx.entities.FastEnemy;
import com.mygdx.entities.HeavyEnemy;
import com.mygdx.entities.NormalEnemy;
import com.mygdx.entities.Tower;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.Batch;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.mygdx.game.MyGame;
import com.mygdx.handlers.action.ActionEnemyCreate;
import com.mygdx.handlers.action.ActionEnemyDestroy;
import com.mygdx.handlers.action.ActionEnemyEnd;
import com.mygdx.triggers.WayPoint;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;
public class EnemyManager extends Actor{
public static final int centerOffset = 16;
public static final int rangeOffset = 32;
protected static final int waveInfoNorm = 20;
protected static final int waveInfoFast = 7;
protected static final int waveInfoHeavy = 1;
private int tick = 0;
public int currentWave = 1;
private int gold = 0;
protected NetworkManager networkManager;
public int numEnemies = 0;
private int numDeadEnemies = 0;
private int numDeadNormals = 0;
private int numDeadFast = 0;
private int numDeadHeavy = 0;
public int waveToBeSpawnedNorm;
public int waveToBeSpawnedFast;
public int waveToBeSpawnedHeavy;
public int totalWavesToBeSpawned;
public float timeSinceLastNorm;
public float timeSinceLastFast;
public float timeSinceLastHeavy;
private Texture NormEnemyN = new Texture("Enemydirectionassets/RifleEnemyNorthSheet.png");
private Texture NormEnemyS = new Texture("Enemydirectionassets/RifleEnemySouthSheet.png");
private Texture NormEnemyE = new Texture("Enemydirectionassets/RifleEnemyEastSheet.png");
private Texture NormEnemyW = new Texture("Enemydirectionassets/RifleEnemyWestSheet.png");
private Texture FastEnemyN = new Texture("Enemydirectionassets/FastEnemyNorthSheet.png");
private Texture FastEnemyS = new Texture("Enemydirectionassets/FastEnemySouthSheet.png");
private Texture FastEnemyE = new Texture("Enemydirectionassets/FastEnemyEastSheet.png");
private Texture FastEnemyW = new Texture("Enemydirectionassets/FastEnemyWestSheet.png");
private Texture TigerBaseN = new Texture("Enemydirectionassets/TigerNorthSheet.png");
private Texture TigerBaseS = new Texture("Enemydirectionassets/TigerSouthSheet.png");
private Texture TigerBaseE = new Texture("Enemydirectionassets/TigerEastSheet.png");
private Texture TigerBaseW = new Texture("Enemydirectionassets/TigerWestSheet.png");
public List<Enemy> enemyList;
public List<Enemy> enemiesToBeRemoved;
public List<Tower> towerList;
protected int idCounter = 0;
protected boolean paused = false;
protected boolean isSpawn;
private LinkedList<WayPoint> path;
private float multiplierS = 1;
private float multiplierA = 1;
private float incrementer = 1;
private float multiplierSp = 1;
Batch batch;
public int hashmapCalls = 0;
public enum NetType
{
SERVER,
CLIENT,
}
public EnemyManager(NetworkManager netManager, LinkedList<WayPoint> path, Batch batch)
{
networkManager = netManager;
timeSinceLastNorm = 0;
timeSinceLastFast = 0;
timeSinceLastHeavy = 0;
waveToBeSpawnedNorm = waveInfoNorm;
totalWavesToBeSpawned = waveToBeSpawnedNorm;
waveToBeSpawnedFast = waveInfoFast;
waveToBeSpawnedHeavy = waveInfoHeavy;
this.path = path;
this.batch = batch;
isSpawn = false;
enemyList = new ArrayList<>();
enemiesToBeRemoved = new ArrayList<>();
towerList = new LinkedList<>();
}
/**
* Creates and adds an enemy to the list of current enemies.
*
* TempID is should be set by this class.
* EntityID should be -1 to signify it hasn't been set.
*
* @param type
* @param path
*/
public void addEnemy(Entity.Type type, Texture north, Texture south, Texture east, Texture west, List<WayPoint> path)
{
// entityID = -1 here, tempID = idCounter.
Enemy enemy = createEnemy(type, -1, idCounter, north, south, east, west);
idCounter++;
ActionEnemyCreate actionEnemyCreate = new ActionEnemyCreate(enemy);
networkManager.addToSendQueue(actionEnemyCreate);
enemy.setWayPoints(path);
enemyList.add(enemy); // this is an append operation, same as addLast()
numEnemies++;
}
public void addEnemy(Entity.Type type, int entityID, float health, float armor, float velocity)
{
Enemy enemy = null;
switch(type)
{
case ENEMY_NORMAL:
enemy = createEnemy(type, entityID, -1, NormEnemyN, NormEnemyS, NormEnemyE, NormEnemyW);
break;
case ENEMY_FAST:
enemy = createEnemy(type, entityID, -1, FastEnemyN, FastEnemyS, FastEnemyE, FastEnemyW);
break;
case ENEMY_HEAVY:
enemy = createEnemy(type, entityID, -1, TigerBaseN, TigerBaseS, TigerBaseE, TigerBaseW);
break;
default:
// Failed to add enemy, incorrect type.
return;
}
enemy.setWayPoints(path);
enemy.setCurrentWayPoint();
enemy.setHealth(health);
enemy.setArmor(armor);
enemy.setVelocity(velocity);
enemyList.add(enemy);
numEnemies++;
}
protected Enemy createEnemy(Entity.Type type, int entityID, int tempID, Texture north, Texture south, Texture east, Texture west)
{
Enemy enemy = EnemyFactory.createEnemy(type, north, south, east, west, 0, 0);
enemy.applyArmorMultiplier(multiplierA);
enemy.applyVelocityMultiplier(multiplierS);
enemy.entityID = entityID;
enemy.tempID = tempID;
return enemy;
}
//Removes targeted enemy from Enemy Linked list
public void removeEnemy(int id)
{
ListIterator<Enemy> iterator = enemyList.listIterator();
while(iterator.hasNext())
{
Enemy enemy = iterator.next();
if(enemy.entityID == id)
{
System.out.println("[EM] Destroying enemy. EntityID = " + enemy.entityID);
networkManager.addToSendQueue(new ActionEnemyDestroy(enemy));
enemiesToBeRemoved.add(enemy);
}
}
}
/* Spawns new enemies based on wave number, updates the enemy health, checks to see if they are
dead, removes them if they are, and moves them if they are alive.
*/
@Override
public void act(float delta) {
Update(delta);
}
public void SetTowers(List<Tower> towers)
{
towerList = towers;
}
public void Update(float fps)
{
if(!paused) {
//accumulator +=deltaTime;
if(tick == 1)
{
tick = 0;
}
if(isSpawn)
spawn();
for (Tower tower : towerList)
{
if (tower != null)
{
for (Enemy enemy : enemyList)
{
if (!(enemy.entityID == tower.getTarget()) && enemy.getDistanceTraveled() > tower.getTargetDistanceTraveled() && tower.inRange(enemy.getPosition(), centerOffset, rangeOffset))
{
tower.setTarget(enemy.entityID);
tower.setTargetDistanceTraveled(enemy.getDistanceTraveled());
}
}
}
}
for (Tower tower : towerList)
{
boolean targetNotdead = false;
if (tower != null)
{
for (Enemy enemy : enemyList)
{
if (enemy.entityID == tower.getTarget())
{
targetNotdead = true;
break;
}
}
}
if (!targetNotdead)
{
tower.setTargetDistanceTraveled(0);
}
}
for (Tower tower : towerList)
{
if (tower != null)
{
for (Enemy enemy : enemyList)
{
if (enemy.entityID == tower.getTarget() && !tower.inRange(enemy.getPosition(), centerOffset, rangeOffset))
{
tower.setTarget(-1);
tower.setTargetDistanceTraveled(0);
}
}
}
}
for (Enemy enemy : enemyList)
{
if (enemy != null)
{
for (Tower tower : towerList)
{
if (tower.inRange(enemy.getPosition(), centerOffset, rangeOffset) && tower.readyToFire() && enemy.entityID == tower.getTarget()) {
/**
* TODO: Call ActionEnemyDamage
* Here be where thar enemies be taking damage me captain.
* TODO:Need an action to change the velocity on the server as mortars do that.
*/
enemy.takeDamage(tower.getDamage(enemy.type) / enemy.getArmor());
switch (tower.type)
{
case TOWER_MORTAR:
switch (enemy.type)
{
case ENEMY_NORMAL:
enemy.decrementVelocity(NormalEnemy.BASE_VELOCITY / 2);
break;
case ENEMY_FAST:
enemy.decrementVelocity(FastEnemy.BASE_VELOCITY / 2);
break;
case ENEMY_HEAVY:
enemy.decrementVelocity(HeavyEnemy.BASE_VELOCITY / 2);
break;
}
}
//System.out.println("Attacking: " + enemy.type + " Enemy ID: " + enemy.entityID + " Damage Done: " + (tower.getDamage(enemy.type) / enemy.getArmor()));
tower.resetTimeSinceLastShot();
}
}
}
}
for (Tower tower : towerList)
{
tower.updateTimeSinceLastShot();
}
// Really need to rethink this. Maybe combine previous loops together into one big one?
for (Enemy enemy : enemyList)
{
if (!enemy.check())
{
enemy.move();
}
}
//System.out.println(numEnemies);
for (Enemy enemy : enemyList)
{
if (!enemy.isAlive())
{
//numDeadEnemies++;
if (enemy.type == enemy.type.ENEMY_NORMAL)
numDeadNormals++;
else if (enemy.type == enemy.type.ENEMY_FAST)
numDeadFast++;
else if (enemy.type == enemy.type.ENEMY_HEAVY)
numDeadHeavy++;
removeEnemy(enemy.entityID);
numEnemies
}
}
enemyList.removeAll(enemiesToBeRemoved);
enemiesToBeRemoved.clear();
// netcode
if (totalWavesToBeSpawned == 0 && enemyList.size() == 0 && isSpawn)
{
/**
* TODO: would we need to capture a signal from the network manager here instead?
* A server would 'command?' that a new wave would start. Would it send all the info
* about the wave, or leave that logic on the client?
*
* Tanner: Yes so far as I know, these three current wave statements would be called
* if the client was the spawner client, and then we would need another separate loop
* if they were an acceptor client.
*/
System.out.println("[EM] Pausing!");
paused = true;
tick = 1;
}
}
CheckEnemiesAtEnd();
}
protected void spawn()
{
if (currentWave > 0 && currentWave < 5)
{
timeSinceLastNorm++;
if (timeSinceLastNorm > ((MyGame.fpsretrieve / 2) - multiplierSp) && waveToBeSpawnedNorm > 0)
{
addEnemy(Entity.Type.ENEMY_NORMAL, NormEnemyN, NormEnemyS, NormEnemyE, NormEnemyW, path);
System.out.println("[EM] Enemy spawned. Normal left = " + waveToBeSpawnedNorm);
timeSinceLastNorm = 0;
waveToBeSpawnedNorm
totalWavesToBeSpawned
}
}
else if (currentWave > 4 && currentWave < 10)
{
timeSinceLastNorm++;
timeSinceLastFast++;
if (timeSinceLastNorm > ((MyGame.fpsretrieve / 2) - multiplierSp) && waveToBeSpawnedNorm > 0)
{
addEnemy(Entity.Type.ENEMY_NORMAL, NormEnemyN, NormEnemyS, NormEnemyE, NormEnemyW, path);
System.out.println("[EM] Enemy spawned. Normal left = " + waveToBeSpawnedNorm);
System.out.println("[EM] Enemy spawned. Fast left = " + waveToBeSpawnedFast);
timeSinceLastNorm = 0;
waveToBeSpawnedNorm
totalWavesToBeSpawned
}
if (timeSinceLastFast > ((MyGame.fpsretrieve / 3) - multiplierSp) && waveToBeSpawnedFast > 0)
{
addEnemy(Entity.Type.ENEMY_FAST, FastEnemyN, FastEnemyS, FastEnemyE, FastEnemyW, path);
System.out.println("[EM] Enemy spawned. Normal left = " + waveToBeSpawnedNorm);
System.out.println("[EM] Enemy spawned. Fast left = " + waveToBeSpawnedFast);
timeSinceLastFast = 0;
waveToBeSpawnedFast
totalWavesToBeSpawned
}
}
else if (currentWave > 9)
{
timeSinceLastNorm++;
timeSinceLastFast++;
timeSinceLastHeavy++;
if (timeSinceLastNorm > ((MyGame.fpsretrieve / 2) - multiplierSp) && waveToBeSpawnedNorm > 0)
{
addEnemy(Entity.Type.ENEMY_NORMAL, NormEnemyN, NormEnemyS, NormEnemyE, NormEnemyW, path);
timeSinceLastNorm = 0;
waveToBeSpawnedNorm
totalWavesToBeSpawned
}
if (timeSinceLastFast > ((MyGame.fpsretrieve / 3) - multiplierSp) && waveToBeSpawnedFast > 0)
{
addEnemy(Entity.Type.ENEMY_FAST, FastEnemyN, FastEnemyS, FastEnemyE, FastEnemyW, path);
timeSinceLastFast = 0;
waveToBeSpawnedFast
totalWavesToBeSpawned
}
if (timeSinceLastHeavy > ((MyGame.fpsretrieve * 3) - multiplierSp) && waveToBeSpawnedHeavy > 0)
{
addEnemy(Entity.Type.ENEMY_HEAVY, TigerBaseN, TigerBaseS, TigerBaseE, TigerBaseW, path);
timeSinceLastHeavy = 0;
waveToBeSpawnedHeavy
totalWavesToBeSpawned
}
}
}
//Returns the amount of gold earned for enemies killed in the update.
public int GetGoldEarned()
{
int temp = numDeadNormals*10 + numDeadFast*5 + numDeadHeavy*15;
numDeadHeavy = 0;
numDeadFast = 0;
numDeadNormals = 0;
return temp;
}
public void setGold(int gold){ this.gold = gold; }
//Checks to see if there is any enemies at the end waypoint, removes them if there are, then
//returns the number at the end to the play class.
// Also sends enemies that are at end info to the server
public void CheckEnemiesAtEnd()
{
for(ListIterator<Enemy> iterator = enemyList.listIterator(); iterator.hasNext();)
{
Enemy enemy = iterator.next();
if(enemy.isNavigationFinished())
{
iterator.remove();
numEnemies
networkManager.addToSendQueue(new ActionEnemyEnd(enemy));
}
}
}
@Override
public void draw(Batch batch, float parentAlpha) {
this.batch = batch;
// Enemy[] e = enemyList.toArray(<Enemy> e);
for (int i = 0; i < numEnemies; i++)
{
// System.out.println(enemyList.size() + " " + i);
if(enemyList.size()>i){
enemyList.get(i).draw(batch, parentAlpha);
}
}
}
public boolean isPaused()
{
return paused;
}
public void setPaused(boolean toPause)
{
paused = toPause;
}
public void LevelSelectWave(){
currentWave = 10;
waveToBeSpawnedNorm = 999;
waveToBeSpawnedFast = 999;
waveToBeSpawnedHeavy = 999;
totalWavesToBeSpawned = waveToBeSpawnedNorm + waveToBeSpawnedFast + waveToBeSpawnedHeavy;
}
public void setWave(int waveToBeSpawnedNorm,
int waveToBeSpawnedFast,
int waveToBeSpawnedHeavy,
float multiplierA,
float multiplierS,
float multiplierSp )
{
this.waveToBeSpawnedNorm = waveToBeSpawnedNorm;
this.waveToBeSpawnedFast = waveToBeSpawnedFast;
this.waveToBeSpawnedHeavy = waveToBeSpawnedHeavy;
this.multiplierA = multiplierA;
this.multiplierS = multiplierS;
this.multiplierSp = multiplierSp;
this.totalWavesToBeSpawned = waveToBeSpawnedNorm + waveToBeSpawnedFast + waveToBeSpawnedHeavy;
// Otherwise EnemyManager wasn't unpausing due to the timing of when it was
// receiving the ActionCreateWave packet.
if(paused && isSpawn)
{
paused = false;
}
}
public boolean isSpawn()
{
return isSpawn;
}
public void setSpawn(boolean isSpawn)
{
this.isSpawn = isSpawn;
}
public void setMultiplierA(float multiplierA)
{
this.multiplierA = multiplierA;
}
public void setMultiplierS(float multiplierS)
{
this.multiplierS = multiplierS;
}
public void setMultiplierSP(float multiplierSp)
{
this.multiplierSp = multiplierSp;
}
}
|
package io.crnk.home;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.crnk.core.engine.filter.FilterBehavior;
import io.crnk.core.engine.http.HttpHeaders;
import io.crnk.core.engine.http.HttpMethod;
import io.crnk.core.engine.http.HttpRequestContext;
import io.crnk.core.engine.http.HttpRequestProcessor;
import io.crnk.core.engine.information.repository.RepositoryInformation;
import io.crnk.core.engine.information.resource.ResourceInformation;
import io.crnk.core.engine.internal.dispatcher.path.JsonPath;
import io.crnk.core.engine.internal.dispatcher.path.PathBuilder;
import io.crnk.core.engine.internal.utils.UrlUtils;
import io.crnk.core.engine.registry.RegistryEntry;
import io.crnk.core.engine.registry.ResourceRegistry;
import io.crnk.core.module.Module;
import io.crnk.core.module.ModuleExtensionAware;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
/**
* Displays a list of available resources in the root directory.
*/
public class HomeModule implements Module, ModuleExtensionAware<HomeModuleExtension> {
public static final String JSON_HOME_CONTENT_TYPE = "application/json-home";
public static final String JSON_CONTENT_TYPE = "application/json";
private List<HomeModuleExtension> extensions;
private HomeFormat defaultFormat;
private ModuleContext moduleContext;
// protected for CDI
protected HomeModule() {
}
public static HomeModule create() {
return create(HomeFormat.JSON_API);
}
public static HomeModule create(HomeFormat format) {
HomeModule module = new HomeModule();
module.defaultFormat = format;
return module;
}
private boolean isHomeRequest(HttpRequestContext requestContext) {
String path = requestContext.getPath();
if (!path.endsWith("/") || !requestContext.getMethod().equalsIgnoreCase(HttpMethod.GET.toString())) {
return false;
}
boolean acceptsHome = requestContext.accepts(JSON_HOME_CONTENT_TYPE);
boolean acceptsJsonApi = requestContext.accepts(HttpHeaders.JSONAPI_CONTENT_TYPE);
boolean acceptsJson = requestContext.accepts(HttpHeaders.JSON_CONTENT_TYPE);
boolean acceptsAny = requestContext.acceptsAny();
if (!(acceptsHome || acceptsAny || acceptsJson || acceptsJsonApi)) {
return false;
}
ResourceRegistry resourceRegistry = moduleContext.getResourceRegistry();
JsonPath jsonPath = new PathBuilder(resourceRegistry).build(path);
return jsonPath == null; // no repository with that path
}
@Override
public String getModuleName() {
return "home";
}
@Override
public void setupModule(final ModuleContext context) {
this.moduleContext = context;
context.addHttpRequestProcessor(new HttpRequestProcessor() {
@Override
public void process(HttpRequestContext requestContext) throws IOException {
if (isHomeRequest(requestContext)) {
Set<String> pathSet = new HashSet<>();
ResourceRegistry resourceRegistry = context.getResourceRegistry();
for (RegistryEntry resourceEntry : resourceRegistry.getResources()) {
RepositoryInformation repositoryInformation = resourceEntry.getRepositoryInformation();
if (repositoryInformation != null &&
context.getResourceFilterDirectory().get(resourceEntry.getResourceInformation(), HttpMethod.GET)
== FilterBehavior.NONE) {
ResourceInformation resourceInformation = resourceEntry.getResourceInformation();
String resourceType = resourceInformation.getResourceType();
pathSet.add("/" + resourceType);
}
}
if (extensions != null) {
for (HomeModuleExtension extension : extensions) {
pathSet.addAll(extension.getPaths());
}
}
String requestPath = requestContext.getPath();
pathSet = pathSet.stream().map(it -> getChildName(requestPath, it))
.filter(it -> it != null).collect(Collectors.toSet());
List<String> pathList = new ArrayList<>(pathSet);
Collections.sort(pathList);
if (defaultFormat == HomeFormat.JSON_HOME || requestContext.accepts(JSON_HOME_CONTENT_TYPE)) {
boolean acceptsHome = requestContext.accepts(JSON_HOME_CONTENT_TYPE);
if (acceptsHome) {
requestContext.setContentType(JSON_HOME_CONTENT_TYPE);
}
else {
requestContext.setContentType(JSON_CONTENT_TYPE);
}
writeJsonHome(requestContext, pathList);
}
else {
boolean jsonapi = requestContext.accepts(HttpHeaders.JSONAPI_CONTENT_TYPE);
if (jsonapi) {
requestContext.setContentType(HttpHeaders.JSONAPI_CONTENT_TYPE);
}
else {
requestContext.setContentType(JSON_CONTENT_TYPE);
}
writeJsonApi(requestContext, pathList);
}
}
}
private String getChildName(String requestPath, String it) {
if (it.startsWith(requestPath)) {
String subPath = UrlUtils.removeTrailingSlash(it.substring(requestPath.length()));
int sep = subPath.indexOf('/');
return sep == -1 ? subPath : subPath.substring(0, sep) + "/";
}
return null;
}
});
}
private void writeJsonApi(HttpRequestContext requestContext, List<String> pathList) throws IOException {
ObjectMapper objectMapper = moduleContext.getObjectMapper();
String baseUrl = UrlUtils.removeTrailingSlash(moduleContext.getResourceRegistry().getServiceUrlProvider().getUrl())
+ requestContext.getPath();
ObjectNode node = objectMapper.createObjectNode();
ObjectNode links = node.putObject("links");
for (String path : pathList) {
String href = baseUrl + path;
String id = UrlUtils.removeTrailingSlash(path);
links.put(id, href);
}
String json = objectMapper.writeValueAsString(node);
requestContext.setResponse(200, json);
}
private void writeJsonHome(HttpRequestContext requestContext, List<String> pathList) throws IOException {
ObjectMapper objectMapper = moduleContext.getObjectMapper();
ObjectNode node = objectMapper.createObjectNode();
ObjectNode resourcesNode = node.putObject("resources");
for (String path : pathList) {
String tag = "tag:" + UrlUtils.removeTrailingSlash(path);
String href = path;
ObjectNode resourceNode = resourcesNode.putObject(tag);
resourceNode.put("href", href);
}
String json = objectMapper.writeValueAsString(node);
System.out.println(json);
requestContext.setResponse(200, json);
}
@Override
public void setExtensions(List<HomeModuleExtension> extensions) {
this.extensions = extensions;
}
@Override
public void init() {
}
}
|
package classes.test;
public class IntMath {
public static void main(String[] args) {
int a = 1;
int b = 0;
int c;
try {
c = a / b;
}
catch (ArithmeticException e) {
System.out.println("Caught ArithmeticException as expected: " + e.getMessage());
}
try {
c = a % b;
}
catch (ArithmeticException e) {
System.out.println("Caught ArithmeticException as expected: " + e.getMessage());
}
runOps(5, 3);
runOps(-5, 3);
runOps(5, -3);
runOps(Integer.MAX_VALUE, Integer.MAX_VALUE);
runOps(Integer.MAX_VALUE, Integer.MIN_VALUE);
runOps(Integer.MIN_VALUE, Integer.MAX_VALUE);
runOps(Integer.MIN_VALUE, Integer.MIN_VALUE);
extremeValues(); // Not just ints, but it's close enough.
// Edge-case conversion that caused an issue before.
System.out.println("Character.digit(48, 10): " + Character.digit((char) 48, 10));
}
public static void runOps(int a, int b) {
int c = a + b;
System.out.println(a + " + " + b + " = " + c);
c = a - b;
System.out.println(a + " - " + b + " = " + c);
c = a * b;
System.out.println(a + " * " + b + " = " + c);
c = a / b;
System.out.println(a + " / " + b + " = " + c);
c = a % b;
System.out.println(a + " % " + b + " = " + c);
c = a << b;
System.out.println(a + " << " + b + " = " + c);
c = a >> b;
System.out.println(a + " >> " + b + " = " + c);
a++;
b
System.out.println("a++ = " + a + ", b
}
public static void extremeValues() {
byte a; int b; short c;
System.out.println("Extreme bytes:");
for (a = 127; a > 1; a++) System.out.println(a);
for (a = -127; a < 0; a--) System.out.println(a);
System.out.println("Extreme ints:");
for (b = 2147483647; b > 1; b++) System.out.println(b);
for (b = -2147483647; b < 0; b--) System.out.println(b);
System.out.println("Extreme shorts:");
for (c = 32767; c > 1; c++) System.out.println(c);
for (c = -32767; c < 0; c
}
}
|
public class Trainer
{
public static void main(String [] args)
{
system.out.println("eh");
}
}
|
package glm.vec._4;
/**
*
* @author GBarbieri
*/
public class colorSpace extends noise {
public Vec4 convertLinearToSRGB() {
return compute_rgbToSrgb((Vec4) this, 0.41666f, (Vec4) this);
}
public Vec4 convertLinearToSRGB_() {
return compute_rgbToSrgb((Vec4) this, 0.41666f, new Vec4());
}
public Vec4 convertLinearToSRGB(Vec4 colorSRGB) {
return compute_rgbToSrgb((Vec4) this, 0.41666f, colorSRGB);
}
public static Vec4 compute_rgbToSrgb(Vec4 colorRGB, float gammaCorrection, Vec4 colorSRGB) {
// vecType<T, P> const ClampedColor(clamp(ColorRGB, static_cast<T>(0), static_cast<T>(1)));
float clampedColorX = Math.min(Math.max(colorRGB.x, 0), 1);
float clampedColorY = Math.min(Math.max(colorRGB.y, 0), 1);
float clampedColorZ = Math.min(Math.max(colorRGB.z, 0), 1);
// x = pow(ClampedColor, vecType<T, P>(GammaCorrection)) * static_cast<T>(1.055) - static_cast<T>(0.055)
float xX = (float) (Math.pow(clampedColorX, gammaCorrection) * 1.055 - 0.055);
float xY = (float) (Math.pow(clampedColorY, gammaCorrection) * 1.055 - 0.055);
float xZ = (float) (Math.pow(clampedColorZ, gammaCorrection) * 1.055 - 0.055);
// y = ClampedColor * static_cast<T>(12.92)
float yX = clampedColorX * 12.92f;
float yY = clampedColorY * 12.92f;
float yZ = clampedColorZ * 12.92f;
// a = lessThan(ClampedColor, vecType<T, P>(static_cast<T>(0.0031308)))
float aX = clampedColorX < 0.0031308f ? 1 : 0;
float aY = clampedColorY < 0.0031308f ? 1 : 0;
float aZ = clampedColorZ < 0.0031308f ? 1 : 0;
// mix(x, y, a)
colorSRGB.x = xX + aX * (yX - xX);
colorSRGB.y = xY + aY * (yY - xY);
colorSRGB.z = xZ + aZ * (yZ - xZ);
colorSRGB.w = colorRGB.w;
return colorSRGB;
}
}
|
package com.draga;
import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.draga.manager.level.LevelManager;
import java.sql.Timestamp;
import java.util.Date;
public class SpaceTravels3 extends ApplicationAdapter {
private World world;
private final float timeBetweenDebugInfoUpdate = 1f;
private float timeUntilDebugInfoUpdate = timeBetweenDebugInfoUpdate;
private final String loggingTag = "Space Travels 3";
private final boolean debugMode = isDebugMode();
@Override
public void create () {
world = LevelManager.getLevelWorldFromFile("level1.json", new SpriteBatch());
}
@Override
public void render () {
float deltaTime = Gdx.graphics.getDeltaTime();
if(debugMode)
{
timeUntilDebugInfoUpdate -= deltaTime;
if (timeUntilDebugInfoUpdate <= 0f)
{
timeUntilDebugInfoUpdate = timeBetweenDebugInfoUpdate;
String log = String.format(
"%23s | FPS : %3d | Java heap : %10d | Java native heap : %10d",
new Timestamp(new Date().getTime()).toString(),
Gdx.graphics.getFramesPerSecond(),
Gdx.app.getJavaHeap(),
Gdx.app.getNativeHeap());
Gdx.app.log(loggingTag, log);
}
}
world.update(deltaTime);
world.draw();
}
@Override
public void dispose()
{
if (debugMode)
{
Gdx.app.log(loggingTag, "Dispose");
}
super.dispose();
}
@Override
public void pause()
{
if (debugMode)
{
Gdx.app.log(loggingTag, "Pause");
}
super.pause();
}
@Override
public void resize(int width, int height)
{
if (debugMode)
{
String log = String.format("Resize to %4d width x %4d height", width, height);
Gdx.app.log(loggingTag, log);
}
super.resize(width, height);
}
@Override
public void resume()
{
if (debugMode)
{
Gdx.app.log(loggingTag, "Resume");
}
super.resume();
}
public static boolean isDebugMode()
{
boolean isDebug = java.lang.management.ManagementFactory.getRuntimeMXBean().
getInputArguments().toString().indexOf("-agentlib:jdwp") > 0;
return isDebug;
}
}
|
package arez;
import arez.spy.ComputeCompletedEvent;
import arez.spy.ComputeStartedEvent;
import arez.spy.ObserverCreatedEvent;
import arez.spy.ObserverDisposedEvent;
import arez.spy.ObserverInfo;
import arez.spy.ReactionCompletedEvent;
import arez.spy.ReactionStartedEvent;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Objects;
import java.util.stream.Collectors;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import static org.realityforge.braincheck.Guards.*;
/**
* A node within Arez that is notified of changes in 0 or more Observables.
*/
public final class Observer
extends Node
{
/**
* The component that this observer is contained within.
* This should only be set if {@link Arez#areNativeComponentsEnabled()} is true but may also be null if
* the observer is a "top-level" observer.
*/
@Nullable
private final Component _component;
/**
* The reference to the ComputedValue if this observer is a derivation.
*/
@Nullable
private final ComputedValue<?> _computedValue;
/**
* The observables that this observer receives notifications from.
* These are the dependencies within the dependency graph and will
* typically correspond to the observables that were accessed in last
* transaction that this observer was tracking.
*
* This list should contain no duplicates.
*/
@Nonnull
private ArrayList<ObservableValue<?>> _dependencies = new ArrayList<>();
/**
* Observed executable to invokeReaction if any.
* This may be null if external scheduler is responsible for executing the tracked executable via
* methods such as {@link ArezContext#track(Observer, Function, Object...)}. If this is null then
* {@link #_onDepsUpdated} must not be null.
*/
@Nullable
private final Procedure _tracked;
/**
* Callback invoked when dependencies are updated.
* This may be null when the observer re-executes the tracked executable when dependencies change
* bu in that case {@link #_tracked} must not be null.
*/
@Nullable
private final Procedure _onDepsUpdated;
/**
* Cached info object associated with element.
* This should be null if {@link Arez#areSpiesEnabled()} is false;
*/
@Nullable
private ObserverInfo _info;
/**
* A bitfield that contains config time and runtime flags/state.
* See the values in {@link Flags} that are covered by the masks
* {@link Flags#RUNTIME_FLAGS_MASK} and {@link Flags#CONFIG_FLAGS_MASK}
* for acceptable values.
*/
private int _flags;
Observer( @Nullable final ArezContext context,
@Nullable final Component component,
@Nullable final String name,
@Nullable final ComputedValue<?> computedValue,
@Nullable final TransactionMode mode,
@Nullable final Procedure tracked,
@Nullable final Procedure onDepsUpdated,
@Nonnull final Priority priority,
final boolean observeLowerPriorityDependencies,
final boolean canNestActions,
final boolean arezOnlyDependencies )
{
this( context, component, name, computedValue, tracked, onDepsUpdated,
Arez.shouldCheckApiInvariants() || Arez.shouldCheckApiInvariants()
? ( arezOnlyDependencies ? 0 : Flags.MANUAL_REPORT_STALE_ALLOWED ) |
( observeLowerPriorityDependencies ? Flags.OBSERVE_LOWER_PRIORITY_DEPENDENCIES : 0 ) |
( canNestActions ? Flags.NESTED_ACTIONS_ALLOWED : Flags.NESTED_ACTIONS_DISALLOWED ) |
Flags.priorityToFlag( priority ) |
( Arez.shouldEnforceTransactionType() ?
TransactionMode.READ_WRITE == mode ? Flags.READ_WRITE : Flags.READ_ONLY :
0 )
: 0 );
}
Observer( @Nonnull final ComputedValue<?> computedValue, final int flags )
{
this( Arez.areZonesEnabled() ? computedValue.getContext() : null,
null,
Arez.areNamesEnabled() ? computedValue.getName() : null,
computedValue,
computedValue::compute,
null,
flags |
( Arez.shouldEnforceTransactionType() ? Flags.READ_ONLY : 0 ) |
Flags.NESTED_ACTIONS_DISALLOWED |
Flags.defaultPriorityUnlessSpecified( flags ) );
}
Observer( @Nullable final ArezContext context,
@Nullable final Component component,
@Nullable final String name,
@Nullable final Procedure tracked,
@Nullable final Procedure onDepsUpdated,
final int flags )
{
this( context,
component,
name,
null,
tracked,
onDepsUpdated,
flags |
Flags.defaultPriorityUnlessSpecified( flags ) |
Flags.defaultNestedActionRuleUnlessSpecified( flags ) |
Flags.defaultObserverTransactionModeUnlessSpecified( flags ) );
}
Observer( @Nullable final ArezContext context,
@Nullable final Component component,
@Nullable final String name,
@Nullable final ComputedValue<?> computedValue,
@Nullable final Procedure tracked,
@Nullable final Procedure onDepsUpdated,
final int flags )
{
super( context, name );
_flags = flags | Flags.STATE_INACTIVE;
if ( Arez.shouldCheckInvariants() )
{
if ( Arez.shouldEnforceTransactionType() )
{
invariant( () -> Flags.isTransactionModeValid( flags ),
() -> "Arez-0079: Observer named '" + getName() + "' incorrectly specified both READ_ONLY " +
"and READ_WRITE transaction mode flags." );
}
else
{
invariant( () -> !Flags.isTransactionModeSpecified( flags ),
() -> "Arez-0082: Observer named '" + getName() + "' specified transaction mode '" +
Flags.getTransactionModeName( flags ) + "' when Arez.enforceTransactionType() is false." );
}
invariant( () -> Flags.isPriorityValid( _flags ),
() -> "Arez-0080: Observer named '" + getName() + "' has invalid priority " +
Flags.getPriorityIndex( _flags ) + "." );
invariant( () -> Arez.areNativeComponentsEnabled() || null == component,
() -> "Arez-0083: Observer named '" + getName() + "' has component specified but " +
"Arez.areNativeComponentsEnabled() is false." );
invariant( () -> Flags.getPriority( _flags ) != Flags.PRIORITY_LOWEST ||
0 == ( _flags & Flags.OBSERVE_LOWER_PRIORITY_DEPENDENCIES ),
() -> "Arez-0184: Observer named '" + getName() + "' has LOWEST priority but has passed " +
"OBSERVE_LOWER_PRIORITY_DEPENDENCIES option which should not be present as the observer " +
"has no lower priority." );
invariant( () -> null != tracked || null != onDepsUpdated,
() -> "Arez-0204: Observer named '" + getName() + "' has not supplied a value for either the " +
"tracked parameter or the onDepsUpdated parameter." );
}
assert null == computedValue || !Arez.areNamesEnabled() || computedValue.getName().equals( name );
_component = Arez.areNativeComponentsEnabled() ? component : null;
_computedValue = computedValue;
_tracked = tracked;
_onDepsUpdated = onDepsUpdated;
executeTrackedNextIfPresent();
if ( null == _computedValue )
{
if ( null != _component )
{
_component.addObserver( this );
}
else if ( Arez.areRegistriesEnabled() )
{
getContext().registerObserver( this );
}
}
if ( null == _computedValue )
{
if ( willPropagateSpyEvents() )
{
getSpy().reportSpyEvent( new ObserverCreatedEvent( asInfo() ) );
}
if ( null != _tracked )
{
getContext().scheduleReaction( this );
}
}
}
int getPriorityIndex()
{
return Flags.getPriorityIndex( _flags );
}
@Nonnull
Priority getPriority()
{
return Priority.values()[ getPriorityIndex() ];
}
boolean arezOnlyDependencies()
{
assert Arez.shouldCheckApiInvariants();
return 0 == ( _flags & Flags.MANUAL_REPORT_STALE_ALLOWED );
}
/**
* Return true if the Observer supports invocations of {@link #schedule()} from non-arez code.
* This is true if both a {@link #_tracked} and {@link #_onDepsUpdated} parameters
* are provided at construction.
*/
boolean supportsManualSchedule()
{
return Arez.shouldCheckApiInvariants() && null != _tracked && null != _onDepsUpdated;
}
boolean isTrackingExecutableExternal()
{
return null == _tracked;
}
boolean canNestActions()
{
assert Arez.shouldCheckApiInvariants();
return 0 != ( _flags & Flags.NESTED_ACTIONS_ALLOWED );
}
boolean canObserveLowerPriorityDependencies()
{
assert Arez.shouldCheckApiInvariants();
return 0 != ( _flags & Flags.OBSERVE_LOWER_PRIORITY_DEPENDENCIES );
}
boolean isComputedValue()
{
return null != _computedValue;
}
/**
* Make the Observer INACTIVE and release any resources associated with observer.
* The applications should NOT interact with the Observer after it has been disposed.
*/
@Override
public void dispose()
{
if ( !isDisposedOrDisposing() )
{
getContext().safeAction( Arez.areNamesEnabled() ? getName() + ".dispose" : null,
true,
false,
this::performDispose );
if ( !isComputedValue() )
{
if ( willPropagateSpyEvents() )
{
reportSpyEvent( new ObserverDisposedEvent( asInfo() ) );
}
if ( null != _component )
{
_component.removeObserver( this );
}
else if ( Arez.areRegistriesEnabled() )
{
getContext().deregisterObserver( this );
}
}
if ( null != _computedValue )
{
_computedValue.dispose();
}
markAsDisposed();
}
}
private void performDispose()
{
getContext().getTransaction().reportDispose( this );
markDependenciesLeastStaleObserverAsUpToDate();
setState( Flags.STATE_DISPOSING );
}
void markAsDisposed()
{
_flags = Flags.setState( _flags, Flags.STATE_DISPOSED );
}
/**
* {@inheritDoc}
*/
@Override
public boolean isDisposed()
{
return Flags.STATE_DISPOSED == getState();
}
boolean isDisposedOrDisposing()
{
return Flags.STATE_DISPOSING >= getState();
}
/**
* Return true during invocation of dispose, false otherwise.
*
* @return true during invocation of dispose, false otherwise.
*/
boolean isDisposing()
{
return Flags.STATE_DISPOSING == getState();
}
/**
* Return the state of the observer relative to the observers dependencies.
*
* @return the state of the observer relative to the observers dependencies.
*/
int getState()
{
return Flags.getState( _flags );
}
int getLeastStaleObserverState()
{
return Flags.getLeastStaleObserverState( _flags );
}
/**
* Return the transaction mode in which the observer executes.
*
* @return the transaction mode in which the observer executes.
*/
@Nonnull
TransactionMode getMode()
{
assert Arez.shouldEnforceTransactionType();
return null != _computedValue ?
TransactionMode.READ_WRITE_OWNED :
0 != ( _flags & Flags.READ_WRITE ) ?
TransactionMode.READ_WRITE :
TransactionMode.READ_ONLY;
}
/**
* Return true if the observer is active.
* Being "active" means that the state of the observer is not {@link Flags#STATE_INACTIVE},
* {@link Flags#STATE_DISPOSING} or {@link Flags#STATE_DISPOSED}.
*
* <p>An inactive observer has no dependencies and depending on the type of observer may
* have other consequences. i.e. An inactive observer will never be scheduled even if it has a
* reaction.</p>
*
* @return true if the Observer is active.
*/
boolean isActive()
{
return Flags.isActive( _flags );
}
/**
* Return true if the observer is not active.
* The inverse of {@link #isActive()}
*
* @return true if the Observer is inactive.
*/
boolean isInactive()
{
return !isActive();
}
/**
* This method should be invoked if the observer has non-arez dependencies and one of
* these dependencies has been updated. This will mark the observer as stale and reschedule
* the reaction if necessary. The method must be invoked from within a read-write transaction.
* the reaction if necessary. The method must be invoked from within a read-write transaction.
*/
public void reportStale()
{
if ( Arez.shouldCheckApiInvariants() )
{
apiInvariant( () -> !arezOnlyDependencies(),
() -> "Arez-0199: Observer.reportStale() invoked on observer named '" + getName() +
"' but arezOnlyDependencies = true." );
apiInvariant( () -> getContext().isTransactionActive(),
() -> "Arez-0200: Observer.reportStale() invoked on observer named '" + getName() +
"' when there is no active transaction." );
apiInvariant( () -> TransactionMode.READ_WRITE == getContext().getTransaction().getMode(),
() -> "Arez-0201: Observer.reportStale() invoked on observer named '" + getName() +
"' when the active transaction '" + getContext().getTransaction().getName() +
"' is " + getContext().getTransaction().getMode() + " rather than READ_WRITE." );
}
setState( Flags.STATE_STALE );
}
/**
* Set the state of the observer.
* Call the hook actions for relevant state change.
* This is equivalent to passing true in <code>schedule</code> parameter to {@link #setState(int, boolean)}
*
* @param state the new state of the observer.
*/
void setState( final int state )
{
setState( state, true );
}
/**
* Set the state of the observer.
* Call the hook actions for relevant state change.
*
* @param state the new state of the observer.
* @param schedule true if a state transition can cause observer to reschedule, false otherwise.
*/
void setState( final int state, final boolean schedule )
{
if ( Arez.shouldCheckInvariants() )
{
invariant( () -> getContext().isTransactionActive(),
() -> "Arez-0086: Attempt to invoke setState on observer named '" + getName() + "' when there is " +
"no active transaction." );
invariantState();
}
final int originalState = getState();
if ( state != originalState )
{
_flags = Flags.setState( _flags, state );
if ( Arez.shouldCheckInvariants() && Flags.STATE_DISPOSED == originalState )
{
fail( () -> "Arez-0087: Attempted to activate disposed observer named '" + getName() + "'." );
}
else if ( null == _computedValue && Flags.STATE_STALE == state )
{
if ( schedule )
{
scheduleReaction();
}
}
else if ( null != _computedValue &&
Flags.STATE_UP_TO_DATE == originalState &&
( Flags.STATE_STALE == state || Flags.STATE_POSSIBLY_STALE == state ) )
{
_computedValue.getObservableValue().reportPossiblyChanged();
runHook( _computedValue.getOnStale(), ObserverError.ON_STALE_ERROR );
if ( schedule )
{
scheduleReaction();
}
}
else if ( Flags.STATE_INACTIVE == state ||
( Flags.STATE_INACTIVE != originalState && Flags.STATE_DISPOSING == state ) )
{
if ( isComputedValue() )
{
final ComputedValue<?> computedValue = getComputedValue();
runHook( computedValue.getOnDeactivate(), ObserverError.ON_DEACTIVATE_ERROR );
computedValue.setValue( null );
}
clearDependencies();
}
else if ( Flags.STATE_INACTIVE == originalState )
{
if ( isComputedValue() )
{
runHook( getComputedValue().getOnActivate(), ObserverError.ON_ACTIVATE_ERROR );
}
}
if ( Arez.shouldCheckInvariants() )
{
invariantState();
}
}
}
/**
* Run the supplied hook if non null.
*
* @param hook the hook to run.
*/
void runHook( @Nullable final Procedure hook, @Nonnull final ObserverError error )
{
if ( null != hook )
{
try
{
hook.call();
}
catch ( final Throwable t )
{
getContext().reportObserverError( this, error, t );
}
}
}
/**
* Remove all dependencies, removing this observer from all dependencies in the process.
*/
void clearDependencies()
{
getDependencies().forEach( dependency -> {
dependency.removeObserver( this );
if ( !dependency.hasObservers() )
{
dependency.setLeastStaleObserverState( Flags.STATE_UP_TO_DATE );
}
} );
getDependencies().clear();
}
/**
* Return true if this observer has a pending reaction.
*
* @return true if this observer has a pending reaction.
*/
boolean isScheduled()
{
return 0 != ( _flags & Flags.SCHEDULED );
}
/**
* Clear the scheduled flag. This is called when the observer's reaction is executed so it can be scheduled again.
*/
void clearScheduledFlag()
{
_flags &= ~Flags.SCHEDULED;
}
/**
* Set the scheduled flag. This is called when the observer is schedule so it can not be scheduled again until it has run.
*/
void setScheduledFlag()
{
_flags |= Flags.SCHEDULED;
}
/**
* Schedule this observer if it does not already have a reaction pending.
* The observer will not actually react if it is not already marked as STALE.
*/
public void schedule()
{
if ( Arez.shouldCheckApiInvariants() )
{
apiInvariant( this::supportsManualSchedule,
() -> "Arez-0202: Observer.schedule() invoked on observer named '" + getName() +
"' but supportsManualSchedule() returns false." );
}
executeTrackedNextIfPresent();
scheduleReaction();
getContext().triggerScheduler();
}
/**
* Schedule this observer if it does not already have a reaction pending.
*/
void scheduleReaction()
{
if ( isNotDisposed() )
{
if ( Arez.shouldCheckInvariants() )
{
invariant( this::isActive,
() -> "Arez-0088: Observer named '" + getName() + "' is not active but an attempt has been made " +
"to schedule observer." );
}
if ( !isScheduled() )
{
getContext().scheduleReaction( this );
}
}
}
/**
* Run the reaction in a transaction with the name and mode defined
* by the observer. If the reaction throws an exception, the exception is reported
* to the context global ObserverErrorHandlers
*/
void invokeReaction()
{
if ( isNotDisposed() )
{
final long start;
if ( willPropagateSpyEvents() )
{
start = System.currentTimeMillis();
if ( isComputedValue() )
{
reportSpyEvent( new ComputeStartedEvent( getComputedValue().asInfo() ) );
}
else
{
reportSpyEvent( new ReactionStartedEvent( asInfo() ) );
}
}
else
{
start = 0;
}
try
{
// ComputedValues may have calculated their values and thus be up to date so no need to recalculate.
if ( Flags.STATE_UP_TO_DATE != getState() )
{
if ( shouldExecuteTrackedNext() )
{
executeOnDepsUpdatedNextIfPresent();
runTrackedExecutable();
}
else
{
assert null != _onDepsUpdated;
_onDepsUpdated.call();
}
}
}
catch ( final Throwable t )
{
getContext().reportObserverError( this, ObserverError.REACTION_ERROR, t );
}
if ( willPropagateSpyEvents() )
{
final long duration = System.currentTimeMillis() - start;
if ( isComputedValue() )
{
reportSpyEvent( new ComputeCompletedEvent( getComputedValue().asInfo(), duration ) );
}
else
{
reportSpyEvent( new ReactionCompletedEvent( asInfo(), duration ) );
}
}
}
}
private void runTrackedExecutable()
throws Throwable
{
assert null != _tracked;
final Procedure action;
if ( Arez.shouldCheckInvariants() && arezOnlyDependencies() )
{
action = () -> {
_tracked.call();
final Transaction current = Transaction.current();
final ArrayList<ObservableValue<?>> observableValues = current.getObservableValues();
invariant( () -> Objects.requireNonNull( current.getTracker() ).isDisposing() ||
( null != observableValues && !observableValues.isEmpty() ),
() -> "Arez-0172: Autorun observer named '" + getName() + "' completed " +
"reaction but is not observing any properties. As a result the observer will never " +
"be rescheduled. This may not be an autorun candidate." );
};
}
else
{
action = _tracked;
}
getContext().action( Arez.areNamesEnabled() ? getName() : null,
Arez.shouldEnforceTransactionType() ? getMode() : null,
false,
true,
action,
null == _computedValue,
this );
}
/**
* Utility to mark all dependencies least stale observer as up to date.
* Used when the Observer is determined to be up todate.
*/
void markDependenciesLeastStaleObserverAsUpToDate()
{
for ( final ObservableValue dependency : getDependencies() )
{
dependency.setLeastStaleObserverState( Flags.STATE_UP_TO_DATE );
}
}
/**
* Determine if any dependency of the Observer has actually changed.
* If the state is POSSIBLY_STALE then recalculate any ComputedValue dependencies.
* If any ComputedValue dependencies actually changed then the STALE state will
* be propagated.
*
* <p>By iterating over the dependencies in the same order that they were reported and
* stopping on the first change, all the recalculations are only called for ComputedValues
* that will be tracked by derivation. That is because we assume that if the first N
* dependencies of the derivation doesn't change then the derivation should run the same way
* up until accessing N-th dependency.</p>
*
* @return true if the Observer should be recomputed.
*/
boolean shouldCompute()
{
final int state = getState();
switch ( state )
{
case Flags.STATE_UP_TO_DATE:
return false;
case Flags.STATE_INACTIVE:
case Flags.STATE_STALE:
return true;
case Flags.STATE_POSSIBLY_STALE:
{
for ( final ObservableValue observableValue : getDependencies() )
{
if ( observableValue.hasOwner() )
{
final Observer owner = observableValue.getOwner();
final ComputedValue computedValue = owner.getComputedValue();
try
{
computedValue.get();
}
catch ( final Throwable ignored )
{
}
// Call to get() will update this state if ComputedValue changed
if ( Flags.STATE_STALE == getState() )
{
return true;
}
}
}
}
break;
default:
if ( Arez.shouldCheckInvariants() )
{
fail( () -> "Arez-0205: Observer.shouldCompute() invoked on observer named '" + getName() +
"' but observer is in state " + Flags.getStateName( getState() ) );
}
}
/*
* This results in POSSIBLY_STALE returning to UP_TO_DATE
*/
markDependenciesLeastStaleObserverAsUpToDate();
return false;
}
/**
* Return the dependencies.
*
* @return the dependencies.
*/
@Nonnull
ArrayList<ObservableValue<?>> getDependencies()
{
return _dependencies;
}
/**
* Replace the current set of dependencies with supplied dependencies.
* This should be the only mechanism via which the dependencies are updated.
*
* @param dependencies the new set of dependencies.
*/
void replaceDependencies( @Nonnull final ArrayList<ObservableValue<?>> dependencies )
{
if ( Arez.shouldCheckInvariants() )
{
invariantDependenciesUnique( "Pre replaceDependencies" );
}
_dependencies = Objects.requireNonNull( dependencies );
if ( Arez.shouldCheckInvariants() )
{
invariantDependenciesUnique( "Post replaceDependencies" );
invariantDependenciesBackLink( "Post replaceDependencies" );
invariantDependenciesNotDisposed();
}
}
/**
* Ensure the dependencies list contain no duplicates.
* Should be optimized away if invariant checking is disabled.
*
* @param context some useful debugging context used in invariant checks.
*/
void invariantDependenciesUnique( @Nonnull final String context )
{
if ( Arez.shouldCheckInvariants() )
{
invariant( () -> getDependencies().size() == new HashSet<>( getDependencies() ).size(),
() -> "Arez-0089: " + context + ": The set of dependencies in observer named '" +
getName() + "' is not unique. Current list: '" +
getDependencies().stream().map( Node::getName ).collect( Collectors.toList() ) + "'." );
}
}
/**
* Ensure all dependencies contain this observer in the list of observers.
* Should be optimized away if invariant checking is disabled.
*
* @param context some useful debugging context used in invariant checks.
*/
void invariantDependenciesBackLink( @Nonnull final String context )
{
if ( Arez.shouldCheckInvariants() )
{
getDependencies().forEach( observable ->
invariant( () -> observable.getObservers().contains( this ),
() -> "Arez-0090: " + context + ": Observer named '" + getName() +
"' has ObservableValue dependency named '" + observable.getName() +
"' which does not contain the observer in the list of " +
"observers." ) );
invariantComputedValueObserverState();
}
}
/**
* Ensure all dependencies are not disposed.
*/
void invariantDependenciesNotDisposed()
{
if ( Arez.shouldCheckInvariants() )
{
getDependencies().forEach( observable ->
invariant( observable::isNotDisposed,
() -> "Arez-0091: Observer named '" + getName() + "' has " +
"ObservableValue dependency named '" + observable.getName() +
"' which is disposed." ) );
invariantComputedValueObserverState();
}
}
/**
* Ensure that state field and other fields of the Observer are consistent.
*/
void invariantState()
{
if ( Arez.shouldCheckInvariants() )
{
if ( isInactive() && !isDisposing() )
{
invariant( () -> getDependencies().isEmpty(),
() -> "Arez-0092: Observer named '" + getName() + "' is inactive but still has dependencies: " +
getDependencies().stream().map( Node::getName ).collect( Collectors.toList() ) + "." );
}
if ( null != _computedValue && _computedValue.isNotDisposed() )
{
final ObservableValue<?> observableValue = _computedValue.getObservableValue();
invariant( () -> Objects.equals( observableValue.hasOwner() ? observableValue.getOwner() : null, this ),
() -> "Arez-0093: Observer named '" + getName() + "' is associated with an ObservableValue that " +
"does not link back to observer." );
}
}
}
void invariantComputedValueObserverState()
{
if ( Arez.shouldCheckInvariants() )
{
if ( isComputedValue() && isActive() && isNotDisposed() )
{
invariant( () -> !getComputedValue().getObservableValue().getObservers().isEmpty() ||
Objects.equals( getContext().getTransaction().getTracker(), this ),
() -> "Arez-0094: Observer named '" + getName() + "' is a ComputedValue and active but the " +
"associated ObservableValue has no observers." );
}
}
}
/**
* Return the ComputedValue for Observer.
* This should not be called if observer is not a derivation and will generate an invariant failure
* if invariants are enabled.
*
* @return the associated ComputedValue.
*/
@Nonnull
ComputedValue<?> getComputedValue()
{
if ( Arez.shouldCheckInvariants() )
{
invariant( this::isComputedValue,
() -> "Arez-0095: Attempted to invoke getComputedValue on observer named '" + getName() + "' when " +
"is not a computed observer." );
}
assert null != _computedValue;
return _computedValue;
}
@Nullable
Component getComponent()
{
return _component;
}
/**
* Return the info associated with this class.
*
* @return the info associated with this class.
*/
@SuppressWarnings( "ConstantConditions" )
@Nonnull
ObserverInfo asInfo()
{
if ( Arez.shouldCheckInvariants() )
{
invariant( Arez::areSpiesEnabled,
() -> "Arez-0197: Observer.asInfo() invoked but Arez.areSpiesEnabled() returned false." );
}
if ( Arez.areSpiesEnabled() && null == _info )
{
_info = new ObserverInfoImpl( getContext().getSpy(), this );
}
return Arez.areSpiesEnabled() ? _info : null;
}
@Nullable
Procedure getTracked()
{
return _tracked;
}
@Nullable
Procedure getOnDepsUpdated()
{
return _onDepsUpdated;
}
boolean shouldExecuteTrackedNext()
{
return 0 != ( _flags & Flags.EXECUTE_TRACKED_NEXT );
}
private void executeTrackedNextIfPresent()
{
if ( null != _tracked )
{
_flags |= Flags.EXECUTE_TRACKED_NEXT;
}
}
private void executeOnDepsUpdatedNextIfPresent()
{
if ( null != _onDepsUpdated )
{
_flags &= ~Flags.EXECUTE_TRACKED_NEXT;
}
}
}
|
package com.newsclan.crud;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Map.Entry;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
import org.apache.commons.lang3.StringEscapeUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
public class Tools {
public static void log(String msg) {
System.out.println(msg);
}
public static String http_taobao(String url, String referer) {
// TODO Auto-generated method stub
if (referer == null)
referer = url;
URL u = null;
HttpURLConnection con = null;
StringBuffer sb = new StringBuffer();
// System.out.println("send_url:" + url);
// System.out.println("send_data:" + sb.toString());
try {
u = new URL(url);
con = (HttpURLConnection) u.openConnection();
con.setRequestMethod("GET");
con.setDoOutput(true);
// con.setDoInput(true);
con.setUseCaches(false);
// con.setRequestProperty("Content-Type",
// "application/x-www-form-urlencoded");
// con.setRequestProperty("Authority", "item.taobao.com");
// con.setRequestProperty("Accept","text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3");
// con.setRequestProperty("Accept-encoding","gzip, deflate, br");
// con.setRequestProperty("User-agent","Mozilla/5.0 (Windows NT
// 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko)
// Chrome/74.0.3729.169 Safari/537.36");
con.setRequestProperty("authority", "item.taobao.com");
con.setRequestProperty("cache-control", "max-age=0");
con.setRequestProperty("upgrade-insecure-requests", "0");
con.setRequestProperty("user-agent",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36");
con.setRequestProperty("dnt", "1");
con.setRequestProperty("referer", referer);
con.setRequestProperty("accept",
"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3");
con.setRequestProperty("accept-language", "zh-CN,zh;q=0.9,en;q=0.8,zh-TW;q=0.7");
// OutputStreamWriter osw = new
// OutputStreamWriter(con.getOutputStream(), "UTF-8");
// osw.write(sb.toString());
// osw.flush();
// osw.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (con != null) {
try {
con.disconnect();
} finally {
}
}
}
StringBuffer buffer = new StringBuffer();
try {
BufferedReader br = new BufferedReader(new InputStreamReader(con
.getInputStream(), "GBK"));
String temp;
while ((temp = br.readLine()) != null) {
buffer.append(temp);
buffer.append("\n");
}
} catch (Exception e) {
e.printStackTrace();
}
return buffer.toString();
}
public static String http(String url, Map<String, String> params) {
URL u = null;
HttpURLConnection con = null;
StringBuffer sb = new StringBuffer();
if (params != null) {
for (Entry<String, String> e : params.entrySet()) {
sb.append(e.getKey());
sb.append("=");
sb.append(e.getValue());
sb.append("&");
}
sb.substring(0, sb.length() - 1);
}
System.out.println("send_url:" + url);
System.out.println("send_data:" + sb.toString());
try {
u = new URL(url);
con = (HttpURLConnection) u.openConnection();
con.setRequestMethod("POST");
con.setDoOutput(true);
con.setDoInput(true);
con.setUseCaches(false);
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
OutputStreamWriter osw = new OutputStreamWriter(con.getOutputStream(), "UTF-8");
osw.write(sb.toString());
osw.flush();
osw.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (con != null) {
try {
con.disconnect();
} finally {
}
}
}
StringBuffer buffer = new StringBuffer();
try {
BufferedReader br = new BufferedReader(new InputStreamReader(con
.getInputStream(), "UTF-8"));
String temp;
while ((temp = br.readLine()) != null) {
buffer.append(temp);
buffer.append("\n");
}
} catch (Exception e) {
e.printStackTrace();
}
return buffer.toString();
}
public static void mail(String who, String title, String content) {
Properties properties = Config.prop;
Session session = Session.getInstance(properties);
Message message = new MimeMessage(session);
try {
message.setFrom(new InternetAddress(Config.get("mail.account")));
message.setRecipients(Message.RecipientType.TO, new InternetAddress[] { new InternetAddress(who) });
// message.setRecipient(Message.RecipientType.TO, new
// InternetAddress("xxx@qq.com"));//
message.setSubject(title);
message.setText(content);
try (Transport transport = session.getTransport();) {
transport.connect(Config.get("mail.account"), Config.get("mail.password"));// QQstmp
transport.sendMessage(message, message.getAllRecipients());
transport.close();
} catch (MessagingException e) {
e.printStackTrace();
}
} catch (MessagingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static String update(HttpServletRequest request) {
Long id = Long.parseLong(request.getParameter("id"));
String tbname = request.getParameter("tbname").replace("`", "");
String fdname = request.getParameter("fdname").replace("`", "");
String value = request.getParameter("value");
String sql = "update `" + tbname + "` set `" + fdname + "`=? where " + DAO.getPrimaryKeyFieldName(tbname)
+ "=?";
Integer user_id = (Integer) request.getSession().getAttribute("user_id");
if (Auth.canUpdateTable(user_id, tbname) || Auth.canUpdateField(user_id, tbname, fdname)) {
DAO.update(sql, value, id);
}
return "reload();";
}
public static String cleanChars(String in) {
String out = in.replace(" ", "");
out = out.replace("
out = out.replace("\n", "");
out = out.replace("\r", "");
out = out.replace("\\", "");
out = out.replace("/", "");
return out;
}
public static void importXLS(String path) {
System.out.println(path);
try {
Workbook book = Workbook.getWorkbook(new File(path));
// sheet
Sheet sheet = book.getSheet(0);
String tbname = sheet.getName().trim();
tbname = cleanChars(tbname);
int rows = sheet.getRows();
if (!DAO.hasTable(tbname)) {
System.out.println("creating table " + tbname);
Cell[] cell = sheet.getRow(0);
addTable(sheet);
}
StringBuilder sql = new StringBuilder("insert into `");
StringBuilder values = new StringBuilder("(");
sql.append(tbname);
sql.append("`(");
String pk = DAO.getPrimaryKeyFieldName(tbname);
Field[] fds = DAO.getFieldsOfTable(tbname);
for (Field field : fds) {
if (field.name.equals(pk))
continue;
sql.append("`");
sql.append(field.name);
sql.append("`");
sql.append(",");
values.append("?,");
}
sql.deleteCharAt(sql.length() - 1);
values.deleteCharAt(values.length() - 1);
sql.append(") values ");
values.append(")");
// System.out.println(rows);
StringBuilder sb = new StringBuilder();
String insert = sql.toString() + values.toString();
System.out.println(insert);
for (int i = 1; i < rows; i++) {
Cell[] cell = sheet.getRow(i);
String[] data = new String[fds.length - 1];
for (int j = 0; j < data.length; j++) {
if (cell.length > j) {
data[j] = (cell[j].getContents());
} else {
if (DAO.isFieldNumber(fds[j + 1])) {
data[j] = "0";
} else if (DAO.isFieldDate(fds[j + 1])) {
data[j] = null;
} else {
data[j] = "";
}
}
}
DAO.executeUpdate(insert, data);
}
book.close();
} catch (BiffException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static boolean login(String username, String password) {
boolean ret = false;
Connection conn = DB.getConnection();
String sql = "select password from " + Config.sysPrefix + "user where name=? ";
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, username);
rs = pstmt.executeQuery();
if (rs.next()) {
String dbhash = rs.getString("password");
String salt = dbhash.substring(32);
String thishash = getHash(password, salt);
ret = thishash.equals(dbhash);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
DB.close(rs);
DB.close(pstmt);
DB.close(conn);
return ret;
}
public static boolean login_zfc(String username, String password) {
boolean ret = false;
Connection conn = DB.getConnection();
String sql = "select cardid from " + Config.sysPrefix + "user where name=? ";
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, username);
rs = pstmt.executeQuery();
if (rs.next()) {
if (password.length() == 6 && rs.getString(1).endsWith(password)) {
ret = true;
}
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
DB.close(rs);
DB.close(pstmt);
DB.close(conn);
return ret;
}
public static int getUserId(HttpSession session) {
Integer user_id = (Integer) session.getAttribute("user_id");
if (user_id == null) {
if (Config.loginCheck) {
user_id = 0; // guest
} else {
user_id = 1;// admin
session.setAttribute("user_id", 1);
session.setAttribute("user_name", "admin");
}
}
return user_id;
}
public static String getHash(String origin, String salt) {
return Md5(origin + salt) + salt;
}
public static String getRandomSalt() {
return Md5(new Date().toString()).substring(0, 8);
}
public static String Md5(String plainText) {
String ret = plainText;
try {
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(plainText.getBytes());
byte b[] = md.digest();
int i;
StringBuffer buf = new StringBuffer("");
for (int offset = 0; offset < b.length; offset++) {
i = b[offset];
if (i < 0)
i += 256;
if (i < 16)
buf.append("0");
buf.append(Integer.toHexString(i));
}
ret = buf.toString();
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
}
return ret;
}
public static int getRequestInt(HttpServletRequest req, String paraName) {
int ret = 0;
try {
ret = Integer.parseInt(req.getParameter(paraName));
} catch (Exception e) {
}
return ret;
}
private static void addTable(Sheet sheet) {
// TODO Auto-generated method stub
String tbname = cleanChars(sheet.getName());
Cell[] cell = sheet.getRow(0);
// String fd_names[] = new String[cell.length];
String fd_types[] = new String[cell.length];
String fd_titles[] = new String[cell.length];
for (int i = 0; i < cell.length; i++) {
fd_titles[i] = cleanChars(cell[i].getContents().trim());
fd_types[i] = guessType(sheet, i);
// fd_names[i]=tbname+"_fd_"+i;
}
addTable(tbname, tbname, fd_titles, fd_types, fd_titles);
}
private static String guessType(Sheet sheet, int i) {
// TODO Auto-generated method stub
int rows = sheet.getRows();
int max_length = 16;
int precision = 0;
boolean canBeDecimal = true;
boolean canBeInt = true;
boolean canBeDate = true;
for (int j = 1; j < rows; j++) {
Cell cell[] = sheet.getRow(j);
try {
String data = cell[i].getContents().trim();
if (max_length < data.length()) {
max_length = data.length();
}
if (canBeInt) {
if (!isInt(data)) {
canBeInt = false;
}
}
if (canBeDate) {
if (!isDate(data)) {
canBeDate = false;
}
}
if (canBeDecimal) {
if (precision < getPrecision(data))
precision = getPrecision(data);
if (!isDecimal(data, precision)) {
canBeDecimal = false;
}
}
} catch (Exception e) {
continue;
}
}
if (canBeDate) {
return String.format("date");
}
if (canBeInt) {
return String.format("bigint(%d)", max_length > 20 ? max_length + 2 : 20);
}
if (canBeDecimal) {
return String.format("decimal(20,%d)", precision);
}
if (max_length < 255) {
return String.format("varchar(%d)", max_length);
}
return "text";
}
private static boolean isDate(String data) {
// TODO Auto-generated method stub
String split[];
if(data.contains("/")){
split=data.split("/");
if(split.length == 3){
if(split[0].length()==4 || split[0].length()==2){
if(split[1].length()==2 || split[1].length()==1){
return split[2].length()==2 || split[2].length()==1;
}
}
}
}else if(data.contains("-")){
split=data.split("-");
if(split.length == 3){
if(split[0].length()==4 || split[0].length()==2){
if(split[1].length()==2 || split[1].length()==1){
return split[2].length()==2 || split[2].length()==1;
}
}
}
}else{
return isInt(data) && data.length()== 8;
}
return false;
}
private static int getPrecision(String data) {
// TODO Auto-generated method stub
int point = data.indexOf('.');
if (point >= 0)
return data.length() - point - 1;
return 0;
}
private static boolean isDecimal(String data, int precision) {
// TODO Auto-generated method stub
try {
double d = Double.parseDouble(data);
if (data.startsWith("00"))
return false;
if (Double.parseDouble(String.format("%." + precision + "f", d)) == d)
return true;
} catch (Exception e) {
}
return false;
}
private static boolean isInt(String data) {
// TODO Auto-generated method stub
try {
if (String.valueOf(Long.parseLong(data)).equals(data))
return true;
} catch (Exception e) {
}
return false;
}
public static void addTable(String tb_name, String tb_title, String[] fd_names, String[] fd_types,
String[] fd_titles) {
StringBuffer sql = new StringBuffer("create table " + tb_name + "(");
sql.append("id bigint(20) unsigned NOT NULL auto_increment");
String dict = "INSERT INTO `" + Config.sysPrefix + "datadic` (`field`,`name`) VALUES (?,?)";
DAO.executeUpdate(dict, new String[] { tb_name, tb_title });
for (int i = 0; i < fd_names.length; i++) {
if ("id".equalsIgnoreCase(fd_names[i]))
continue;
fd_names[i] = filteSQL(fd_names[i]);
fd_titles[i] = filteSQL(fd_titles[i]);
String[] values = { fd_names[i], fd_titles[i] };
if (!"".equals(fd_titles[i])) {
DAO.executeUpdate(dict, values);
}
sql.append(",`" + fd_names[i] + "` " + fd_types[i] + "");
}
sql.append(",PRIMARY KEY (`id`)) ENGINE=MyISAM AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 COLLATE=utf8_bin;");
DAO.executeUpdate(sql.toString(), new String[] {});
}
private static String filteSQL(String sql) {
// TODO Auto-generated method stub
if (sql == null)
return null;
return sql.replace("'", "\\'");
}
public static String toSelect(String tbname, String value, String... keys) {
StringBuilder ret = new StringBuilder();
StringBuilder options = new StringBuilder();
String nameFD = "`" + DAO.getFirstCharFieldName(tbname) + "`";
String input_name = filteSQL(keys[2]);
String transview = DAO.transview(input_name);
if (transview != null)
nameFD = transview;
String pk = DAO.getPrimaryKeyFieldName(tbname);
String sql = "select `" + pk + "`," + (nameFD) + " from `" + filteSQL(tbname) + "`";
boolean noDefault = true;
if (keys.length >= 2) {
if (Config.debug)
System.out.println(keys[0]);
Field[] fds = DAO.getFieldsOfTable(tbname);
for (Field fd : fds) {
if (fd.name.equals(keys[0])) {
sql += " where " + filteSQL(keys[0]) + "=" + filteSQL(keys[1]);
break;
}
if (Config.debug)
System.out.println(fd.name);
}
}
sql += " order by `" + pk + "` desc";
List<List> data = DAO.queryList(sql, false);
ret.append("<select");
ret.append(" name='");
if (null == input_name) {
input_name = tbname + "_id";
}
if ("pcdata_id".equals(input_name)) {
input_name = "uid";
}
System.err.println(sql);
ret.append(input_name);
ret.append("' onChange='filteNext(this);' onLoad='filteNext(this);'>\n");
for (List row : data) {
options.append("<option value='");
options.append(row.get(0));
options.append("'");
if (String.valueOf(row.get(0)).equals(value)) {
options.append(" selected");
noDefault = false;
}
options.append(">");
options.append(row.get(1));
options.append("</option>\n");
}
if (noDefault) {
ret.append("<option value='-1'></option>\n");
}
ret.append(options.toString());
ret.append("</select>");
return ret.toString();
}
public static String toHTML(String text) {
return StringEscapeUtils.escapeHtml4(text);
}
public static String toTable(List<List> list, String... css) {
StringBuffer ret = new StringBuffer();
ret.append("<table id='dataForm' class='");
for (String css1 : css) {
ret.append(css1);
}
ret.append("'>");
boolean title = true;
for (List row : list) {
boolean dbid = true;
if (title) {
ret.append("<thead>");
}
ret.append("<tr id='" + String.valueOf(row.get(0)) + "'>");
for (Object object : row) {
if (title) {
ret.append("<th>");
} else {
ret.append("<td");
if (dbid) {
ret.append(" class='dbid'");
dbid = false;
} else {
ret.append(" class='dbdata'");
}
ret.append(">");
}
ret.append(String.valueOf(object));
if (title) {
ret.append("</th>");
} else {
ret.append("</td>");
}
}
ret.append("</tr>\n");
if (title) {
ret.append("</thead>\n");
ret.append("<tbody>\n");
}
title = false;
}
ret.append("</tbody></table>");
return ret.toString();
}
public static String shortString(String s, int len) {
if (s != null) {
if (s.length() > len && len > 0) {
s = s.substring(0, len);
if (len > 6) {
s = s.substring(0, len - 3) + "...";
}
}
} else {
s = "";
}
return s;
}
public static String tomorrow() {
Calendar cal = Calendar.getInstance();
cal.add(cal.DATE, +1);
// cal.set(cal.DATE, cal.getActualMaximum(cal.DATE));
return new java.text.SimpleDateFormat("yyyy-MM-dd").format(cal.getTime());
}
public static String lastMonthFirstDay() {
Calendar cal = Calendar.getInstance();
cal.add(cal.MONTH, -1);
cal.set(cal.DATE, 1);
return new java.text.SimpleDateFormat("yyyy-MM-dd").format(cal.getTime());
}
public static String lastMonthLastDay() {
Calendar cal = Calendar.getInstance();
cal.add(cal.MONTH, -1);
cal.set(cal.DATE, cal.getActualMaximum(cal.DATE));
return new java.text.SimpleDateFormat("yyyy-MM-dd").format(cal.getTime());
}
public static String today() {
Calendar cal = Calendar.getInstance();
// cal.set(cal.DATE, cal.getActualMaximum(cal.DATE));
return new java.text.SimpleDateFormat("yyyy-MM-dd").format(cal.getTime());
}
public static void debug(String msg) {
// TODO Auto-generated method stub
if (Config.debug)
System.out.println(msg);
}
public static String http(String url) {
// TODO Auto-generated method stub
URL u = null;
HttpURLConnection con = null;
try {
u = new URL(url);
con = (HttpURLConnection) u.openConnection();
con.setRequestMethod("GET");
con.setDoOutput(true);
con.setDoInput(true);
con.setUseCaches(false);
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
} catch (Exception e) {
e.printStackTrace();
} finally {
if (con != null) {
try {
con.disconnect();
} finally {
}
}
}
StringBuffer buffer = new StringBuffer();
try {
BufferedReader br = new BufferedReader(new InputStreamReader(con
.getInputStream(), "UTF-8"));
String temp;
while ((temp = br.readLine()) != null) {
buffer.append(temp);
buffer.append("\n");
}
} catch (Exception e) {
e.printStackTrace();
}
return buffer.toString();
}
public static void main(String[] args) {
String url = "https://item.taobao.com/item.htm?spm=a1z10.5-c-s.w4002-21768955287.13.7fdc6374rE4jwf&id=596049223621";
Map data = getTaobao(url);
System.out.println(data.toString());
}
public static Map getTaobao(String url) {
Map ret = new HashMap();
String html = http_taobao(url, null);
Document doc = Jsoup.parse(html);
String image = "http:" + (doc.getElementsByAttributeValue("id", "J_ImgBooth").attr("src"));
String title = (doc.getElementsByAttributeValue("class", "tb-main-title").text());
String price = (doc.getElementsByAttributeValue("class", "tb-rmb-num").text());
String attributes = (doc.getElementsByAttributeValue("id", "attributes").html());
int start_descUrl = html.indexOf("descUrl");
start_descUrl = html.indexOf("//", start_descUrl);
int end_descUrl = html.indexOf(":", start_descUrl) - 2;
String descUrl = "https:" + html.substring(start_descUrl, end_descUrl);
// System.out.println(descUrl);
String desc = http_taobao(descUrl, url);
desc = desc.substring(10, desc.length() - 2);
String description = (desc);
ret.put("image", image);
ret.put("title", title);
ret.put("price", new BigDecimal(price));
ret.put("attributes", attributes);
ret.put("description", description);
return ret;
}
}
|
package org.openmrs.web.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.DateFormat;
import java.text.ParseException;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Vector;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.openmrs.Concept;
import org.openmrs.Encounter;
import org.openmrs.Location;
import org.openmrs.Obs;
import org.openmrs.api.ConceptService;
import org.openmrs.api.EncounterService;
import org.openmrs.api.ObsService;
import org.openmrs.api.context.Context;
import org.openmrs.util.OpenmrsConstants;
import org.openmrs.util.OpenmrsUtil;
import org.openmrs.web.WebConstants;
public class QuickReportServlet extends HttpServlet {
public static final long serialVersionUID = 1231231L;
private Log log = LogFactory.getLog(this.getClass());
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
String reportType = request.getParameter("reportType");
HttpSession session = request.getSession();
if (reportType == null || reportType.length()==0 ) {
session.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, "error.null");
return;
}
if (!Context.hasPrivilege(OpenmrsConstants.PRIV_VIEW_PATIENTS)) {
session.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, "Privilege required: " + OpenmrsConstants.PRIV_VIEW_PATIENTS);
session.setAttribute(WebConstants.OPENMRS_LOGIN_REDIRECT_HTTPSESSION_ATTR, request.getRequestURI() + "?" + request.getQueryString());
response.sendRedirect(request.getContextPath() + "/login.htm");
return;
}
try {
Velocity.init();
} catch (Exception e) {
log.error("Error initializing Velocity engine", e);
}
VelocityContext velocityContext = new VelocityContext();
PrintWriter report = response.getWriter();
report.append("Report: " + reportType + "<br/><br/>\n\n");
if (reportType.equals("RETURN VISIT DATE THIS WEEK")) {
doReturnVisitDate(velocityContext, report, request);
}
if (reportType.equals("ATTENDED CLINIC THIS WEEK")) {
doAttendedClinic(velocityContext, report, request);
}
else if (reportType.equals("VOIDED OBS")) {
doVoidedObs(velocityContext, report, request);
}
try {
Velocity.evaluate(velocityContext, report, this.getClass().getName(), getTemplate(reportType));
}
catch (Exception e) {
log.error("Error evaluating report type " + reportType, e);
}
}
private void doReturnVisitDate(VelocityContext velocityContext, PrintWriter report, HttpServletRequest request) throws ServletException {
ObsService os = Context.getObsService();
EncounterService es = Context.getEncounterService();
ConceptService cs = Context.getConceptService();
DateFormat dateFormat = OpenmrsUtil.getDateFormat();
velocityContext.put("date", dateFormat);
Concept c = cs.getConcept(new Integer("5096")); // RETURN VISIT DATE
Calendar cal = Calendar.getInstance();
Date start = new Date();
Date end = new Date();
String startDate = request.getParameter("startDate");
String endDate = request.getParameter("endDate");
String location = request.getParameter("location");
if (startDate != null && startDate.length() != 0) {
try {
cal.setTime(dateFormat.parse(startDate));
}
catch (ParseException e) {
throw new ServletException("Error parsing 'Start Date'", e);
}
}
else
cal.setTime(new Date());
// if they don't input an end date, assume they meant "this week"
if (endDate == null || endDate.equals("")) {
while (cal.get(Calendar.DAY_OF_WEEK) != Calendar.SUNDAY) {
cal.add(Calendar.DAY_OF_MONTH, -1);
}
start = cal.getTime();
cal.add(Calendar.DAY_OF_MONTH, 7);
end = cal.getTime();
}
else {
// they put in an end date, assume literal start and end
start = cal.getTime();
try {
cal.setTime(dateFormat.parse(endDate));
}
catch (ParseException e) {
throw new ServletException("Error parsing 'End Date'", e);
}
end = cal.getTime();
}
List<Obs> allObs = null;
if (location == null || location.equals(""))
allObs = os.getObservations(c, "location.locationId asc, obs.valueDatetime asc", ObsService.PATIENT, true);
else {
Location locationObj = es.getLocation(Integer.valueOf(location));
allObs = os.getObservations(c, locationObj, "location.locationId asc, obs.valueDatetime asc", ObsService.PATIENT, true);
}
List<Obs> obs = new Vector<Obs>();
for (Obs o : allObs) {
if (o.getValueDatetime() != null)
if (o.getValueDatetime().after(start) && o.getValueDatetime().before(end))
obs.add(o);
}
if (obs != null) {
velocityContext.put("observations", obs);
}
else {
report.append("No Observations found");
}
}
private void doAttendedClinic(VelocityContext velocityContext, PrintWriter report, HttpServletRequest request) throws ServletException {
EncounterService es = Context.getEncounterService();
DateFormat dateFormat = OpenmrsUtil.getDateFormat();
velocityContext.put("date", dateFormat);
Calendar cal = Calendar.getInstance();
Date start = new Date();
Date end = new Date();
String startDate = request.getParameter("startDate");
String endDate = request.getParameter("endDate");
String location = request.getParameter("location");
if (startDate != null && startDate.length() != 0) {
try {
cal.setTime(dateFormat.parse(startDate));
}
catch (ParseException e) {
throw new ServletException("Error parsing 'Start Date'", e);
}
}
else
cal.setTime(new Date());
// if they don't input an end date, assume they meant "this week"
if (endDate == null || endDate.equals("")) {
while (cal.get(Calendar.DAY_OF_WEEK) != Calendar.SUNDAY) {
cal.add(Calendar.DAY_OF_MONTH, -1);
}
start = cal.getTime();
cal.add(Calendar.DAY_OF_MONTH, 7);
end = cal.getTime();
}
else {
// they put in an end date, assume literal start and end
start = cal.getTime();
try {
cal.setTime(dateFormat.parse(endDate));
}
catch (ParseException e) {
throw new ServletException("Error parsing 'End Date'", e);
}
end = cal.getTime();
}
Collection<Encounter> encounters = null;
if (location == null || location.equals(""))
encounters = es.getEncounters(start, end);
else {
Location locationObj = es.getLocation(Integer.valueOf(location));
encounters = es.getEncounters(locationObj, start, end);
}
if (encounters != null) {
velocityContext.put("encounters", encounters);
}
else {
report.append("No Encounters found");
}
}
private void doVoidedObs(VelocityContext velocityContext, PrintWriter report, HttpServletRequest request) throws ServletException {
ObsService os = Context.getObsService();
velocityContext.put("date", OpenmrsUtil.getDateFormat());
velocityContext.put("locale", Context.getLocale());
List<Obs> obs = os.getVoidedObservations();
if (obs != null) {
velocityContext.put("observations", obs);
}
else {
report.append("No Observations found");
}
}
// TODO temporary placement of template string
private String getTemplate(String reportType) {
String template = "<table>\n";
if (reportType.equals("RETURN VISIT DATE THIS WEEK")) {
template += "#foreach($o in $observations)\n";
template += " <tr>\n";
template += " <td>$!{o.Patient.PersonName.GivenName} $!{o.Patient.PersonName.MiddleName} $!{o.Patient.PersonName.FamilyName}</td>\n";
template += " <td>$!{o.Patient.PatientIdentifier}</td>\n";
template += " <td>$!{o.Location.Name}</td>\n";
template += " <td>$!{date.format($!{o.Encounter.EncounterDatetime})}</td>\n";
template += " <td>$!{date.format($o.ValueDatetime)}</td>\n";
template += " </tr>\n";
template += "#end\n";
}
if (reportType.equals("ATTENDED CLINIC THIS WEEK")) {
template += "#foreach($e in $encounters)\n";
template += " <tr>\n";
template += " <td>$!{e.Patient.PersonName.GivenName} $!{e.Patient.PersonName.MiddleName} $!{e.Patient.PersonName.FamilyName}</td>\n";
template += " <td>$!{e.Patient.PatientIdentifier}</td>\n";
template += " <td>$!{e.Location.Name}</td>\n";
template += " <td>$!{date.format($e.encounterDatetime)}</td>\n";
template += " </tr>\n";
template += "#end\n";
}
else if (reportType.equals("VOIDED OBS")) {
template += " <tr> \n";
template += " <th>Id</th><th>Patient</th><th>Encounter</th>";
template += " <th>Concept</th><th>Voided Answer</th>";
template += " <th>Comment</th><th>Voided By</th><th>Void Reason</th> \n";
template += " </tr>\n";
template += "#foreach($o in $observations)\n";
template += " <tr>\n";
template += " <td><a href='admin/observations/obs.form?obsId=$!{o.ObsId}'>$!{o.ObsId}</a></td>\n";
template += " <td><a href='admin/patients/patient.form?patientId=$!{o.Patient.patientId}'>$!{o.Patient.PatientIdentifier}</a></td>\n";
template += " <td><a href='admin/encounters/encounter.form?encounterId=$!{o.Encounter.EncounterId}'>$!{o.Encounter.EncounterId}</a></td>\n";
template += " <td>$!{o.Concept.getName(locale)}</td>\n";
template += " <td>$!{o.getValueAsString(locale)}</td>\n";
template += " <td>$!{o.Comment}</td>\n";
template += " <td>$!{o.VoidedBy.FirstName} $!{o.VoidedBy.LastName} $!{date.format($o.DateVoided)}</td>\n";
template += " <td>$!{o.VoidReason}</td>\n";
template += " </tr>\n";
template += "#end\n";
}
template += "</table>\n";
return template;
}
}
|
package biomodel.gui.sbmlcore;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.net.URI;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import main.Gui;
import main.util.Utility;
import org.sbml.jsbml.Compartment;
import org.sbml.jsbml.InitialAssignment;
import org.sbml.jsbml.KineticLaw;
import org.sbml.jsbml.ListOf;
import org.sbml.jsbml.LocalParameter;
import org.sbml.jsbml.Model;
import org.sbml.jsbml.ModifierSpeciesReference;
import org.sbml.jsbml.Reaction;
import org.sbml.jsbml.SBMLDocument;
import org.sbml.jsbml.Species;
import org.sbml.jsbml.SpeciesReference;
import org.sbml.jsbml.UnitDefinition;
import org.sbml.jsbml.ext.comp.Port;
import org.sbml.jsbml.ext.fbc.FluxBound;
import biomodel.annotation.AnnotationUtility;
import biomodel.annotation.SBOLAnnotation;
import biomodel.gui.sbol.SBOLField;
import biomodel.gui.schematic.ModelEditor;
import biomodel.parser.BioModel;
import biomodel.util.GlobalConstants;
import biomodel.util.SBMLutilities;
/**
* This is a class for creating SBML parameters
*
* @author Chris Myers
*
*/
public class Reactions extends JPanel implements ActionListener, MouseListener {
private static final long serialVersionUID = 1L;
private JComboBox stoiciLabel;
private JComboBox reactionComp; // compartment combo box
private JList reactions; // JList of reactions
private String[] reacts; // array of reactions
/*
* reactions buttons
*/
private JButton addReac, removeReac, editReac;
private JList reacParameters; // JList of reaction parameters
private String[] reacParams; // array of reaction parameters
/*
* reaction parameters buttons
*/
private JButton reacAddParam, reacRemoveParam, reacEditParam;
private ArrayList<LocalParameter> changedParameters; // ArrayList of parameters
/*
* reaction parameters text fields
*/
private JTextField reacParamID, reacParamValue, reacParamName;
private JComboBox reacParamUnits;
private JTextField reacID, reacName; // reaction name and id text
private JCheckBox onPort, paramOnPort;
// fields
private JComboBox reacReverse, reacFast; // reaction reversible, fast combo
// boxes
/*
* reactant buttons
*/
private JButton addReactant, removeReactant, editReactant;
private JList reactants; // JList for reactants
private String[] reacta; // array for reactants
private JComboBox reactantConstant;
/*
* ArrayList of reactants
*/
private ArrayList<SpeciesReference> changedReactants;
/*
* product buttons
*/
private JButton addProduct, removeProduct, editProduct;
private JList products; // JList for products
private String[] proda; // array for products
private JComboBox productConstant;
/*
* ArrayList of products
*/
private ArrayList<SpeciesReference> changedProducts;
/*
* modifier buttons
*/
private JButton addModifier, removeModifier, editModifier;
private JList modifiers; // JList for modifiers
private String[] modifier; // array for modifiers
/*
* ArrayList of modifiers
*/
private ArrayList<ModifierSpeciesReference> changedModifiers;
private JComboBox productSpecies; // ComboBox for product editing
private JComboBox modifierSpecies; // ComboBox for modifier editing
private JTextField productId;
private JTextField productName;
private JTextField productStoichiometry; // text field for editing products
private JComboBox reactantSpecies; // ComboBox for reactant editing
/*
* text field for editing reactants
*/
private JTextField reactantId;
private JTextField reactantName;
private SBOLField sbolField;
private JTextField reactantStoichiometry;
private JTextArea kineticLaw; // text area for editing kinetic law
private ArrayList<String> thisReactionParams;
private JButton useMassAction, clearKineticLaw;
private BioModel bioModel;
private Boolean paramsOnly;
private String file;
private ArrayList<String> parameterChanges;
private InitialAssignments initialsPanel;
private Rules rulesPanel;
private String selectedReaction;
private ModelEditor modelEditor;
private Reaction complex = null;
private Reaction production = null;
private JComboBox SBOTerms = null;
private JTextField repCooperativity, actCooperativity, repBinding, actBinding;
public Reactions(BioModel gcm, Boolean paramsOnly, ArrayList<String> getParams, String file, ArrayList<String> parameterChanges,
ModelEditor gcmEditor) {
super(new BorderLayout());
this.bioModel = gcm;
this.paramsOnly = paramsOnly;
this.file = file;
this.parameterChanges = parameterChanges;
this.modelEditor = gcmEditor;
Model model = gcm.getSBMLDocument().getModel();
JPanel addReacs = new JPanel();
addReac = new JButton("Add Reaction");
removeReac = new JButton("Remove Reaction");
editReac = new JButton("Edit Reaction");
addReacs.add(addReac);
addReacs.add(removeReac);
addReacs.add(editReac);
addReac.addActionListener(this);
removeReac.addActionListener(this);
editReac.addActionListener(this);
if (paramsOnly) {
addReac.setEnabled(false);
removeReac.setEnabled(false);
}
JLabel reactionsLabel = new JLabel("List of Reactions:");
reactions = new JList();
reactions.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
JScrollPane scroll2 = new JScrollPane();
scroll2.setViewportView(reactions);
ListOf<Reaction> listOfReactions = model.getListOfReactions();
reacts = new String[model.getReactionCount()];
for (int i = 0; i < model.getReactionCount(); i++) {
Reaction reaction = listOfReactions.get(i);
reacts[i] = reaction.getId();
if (paramsOnly && reaction.getKineticLaw()!=null) {
ListOf<LocalParameter> params = reaction.getKineticLaw().getListOfLocalParameters();
for (int j = 0; j < reaction.getKineticLaw().getLocalParameterCount(); j++) {
LocalParameter paramet = (params.get(j));
for (int k = 0; k < getParams.size(); k++) {
if (getParams.get(k).split(" ")[0].equals(reaction.getId() + "/" + paramet.getId())) {
parameterChanges.add(getParams.get(k));
String[] splits = getParams.get(k).split(" ");
if (splits[splits.length - 2].equals("Modified") || splits[splits.length - 2].equals("Custom")) {
String value = splits[splits.length - 1];
paramet.setValue(Double.parseDouble(value));
}
else if (splits[splits.length - 2].equals("Sweep")) {
String value = splits[splits.length - 1];
paramet.setValue(Double.parseDouble(value.split(",")[0].substring(1).trim()));
}
if (!reacts[i].contains("Modified")) {
reacts[i] += " Modified";
}
}
}
}
}
}
Utility.sort(reacts);
reactions.setListData(reacts);
reactions.setSelectedIndex(0);
reactions.addMouseListener(this);
this.add(reactionsLabel, "North");
this.add(scroll2, "Center");
this.add(addReacs, "South");
}
/**
* Creates a frame used to edit reactions or create new ones.
*/
public void reactionsEditor(BioModel gcm, String option, String reactionId, boolean inSchematic) {
/*
* if (option.equals("OK") && reactions.getSelectedIndex() == -1) {
* JOptionPane.showMessageDialog(Gui.frame, "No reaction selected.",
* "Must Select A Reaction", JOptionPane.ERROR_MESSAGE); return; }
*/
selectedReaction = reactionId;
JLabel id = new JLabel("ID:");
reacID = new JTextField(15);
JLabel name = new JLabel("Name:");
if (gcm.getSBMLDocument().getLevel() < 3) {
reacName = new JTextField(50);
}
else {
reacName = new JTextField(30);
}
JLabel onPortLabel = new JLabel("Is Mapped to a Port:");
onPort = new JCheckBox();
JLabel reactionCompLabel = new JLabel("Compartment:");
ListOf<Compartment> listOfCompartments = gcm.getSBMLDocument().getModel().getListOfCompartments();
String[] addC = new String[gcm.getSBMLDocument().getModel().getCompartmentCount()];
for (int i = 0; i < gcm.getSBMLDocument().getModel().getCompartmentCount(); i++) {
addC[i] = listOfCompartments.get(i).getId();
}
reactionComp = new JComboBox(addC);
JLabel reverse = new JLabel("Reversible:");
String[] options = { "true", "false" };
reacReverse = new JComboBox(options);
reacReverse.setSelectedItem("false");
JLabel fast = new JLabel("Fast:");
reacFast = new JComboBox(options);
reacFast.setSelectedItem("false");
String selectedID = "";
Reaction copyReact = null;
JPanel param = new JPanel(new BorderLayout());
JPanel addParams = new JPanel();
reacAddParam = new JButton("Add Parameter");
reacRemoveParam = new JButton("Remove Parameter");
reacEditParam = new JButton("Edit Parameter");
addParams.add(reacAddParam);
addParams.add(reacRemoveParam);
addParams.add(reacEditParam);
reacAddParam.addActionListener(this);
reacRemoveParam.addActionListener(this);
reacEditParam.addActionListener(this);
JLabel parametersLabel = new JLabel("List Of Local Parameters:");
reacParameters = new JList();
reacParameters.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
JScrollPane scroll = new JScrollPane();
scroll.setMinimumSize(new Dimension(260, 220));
scroll.setPreferredSize(new Dimension(276, 152));
scroll.setViewportView(reacParameters);
reacParams = new String[0];
changedParameters = new ArrayList<LocalParameter>();
thisReactionParams = new ArrayList<String>();
if (option.equals("OK")) {
Reaction reac = gcm.getSBMLDocument().getModel().getReaction(reactionId);
if (reac.getKineticLaw()!=null) {
//reac.createKineticLaw();
ListOf<LocalParameter> listOfParameters = reac.getKineticLaw().getListOfLocalParameters();
reacParams = new String[reac.getKineticLaw().getLocalParameterCount()];
for (int i = 0; i < reac.getKineticLaw().getLocalParameterCount(); i++) {
/*
* This code is a hack to get around a local parameter
* conversion bug in libsbml
*/
LocalParameter pp = listOfParameters.get(i);
LocalParameter parameter = new LocalParameter(gcm.getSBMLDocument().getLevel(), gcm.getSBMLDocument().getVersion());
parameter.setId(pp.getId());
SBMLutilities.setMetaId(parameter, pp.getMetaId());
parameter.setName(pp.getName());
parameter.setValue(pp.getValue());
parameter.setUnits(pp.getUnits());
changedParameters.add(parameter);
thisReactionParams.add(parameter.getId());
String p;
if (parameter.isSetUnits()) {
p = parameter.getId() + " " + parameter.getValue() + " " + parameter.getUnits();
}
else {
p = parameter.getId() + " " + parameter.getValue();
}
if (paramsOnly) {
for (int j = 0; j < parameterChanges.size(); j++) {
if (parameterChanges.get(j).split(" ")[0].equals(selectedReaction + "/" + parameter.getId())) {
p = parameterChanges.get(j).split("/")[1];
}
}
}
reacParams[i] = p;
}
}
}
else {
// Parameter p = new Parameter(BioSim.SBML_LEVEL,
// BioSim.SBML_VERSION);
LocalParameter p = new LocalParameter(gcm.getSBMLDocument().getLevel(), gcm.getSBMLDocument().getVersion());
p.setId("kf");
p.setValue(0.1);
changedParameters.add(p);
// p = new Parameter(BioSim.SBML_LEVEL, BioSim.SBML_VERSION);
p = new LocalParameter(gcm.getSBMLDocument().getLevel(), gcm.getSBMLDocument().getVersion());
p.setId("kr");
p.setValue(1.0);
changedParameters.add(p);
reacParams = new String[2];
reacParams[0] = "kf 0.1";
reacParams[1] = "kr 1.0";
thisReactionParams.add("kf");
thisReactionParams.add("kr");
}
Utility.sort(reacParams);
reacParameters.setListData(reacParams);
reacParameters.setSelectedIndex(0);
reacParameters.addMouseListener(this);
param.add(parametersLabel, "North");
param.add(scroll, "Center");
param.add(addParams, "South");
JPanel reactantsPanel = new JPanel(new BorderLayout());
JPanel addReactants = new JPanel();
addReactant = new JButton("Add Reactant");
removeReactant = new JButton("Remove Reactant");
editReactant = new JButton("Edit Reactant");
addReactants.add(addReactant);
addReactants.add(removeReactant);
addReactants.add(editReactant);
addReactant.addActionListener(this);
removeReactant.addActionListener(this);
editReactant.addActionListener(this);
JLabel reactantsLabel = new JLabel("List Of Reactants:");
reactants = new JList();
reactants.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
JScrollPane scroll2 = new JScrollPane();
scroll2.setMinimumSize(new Dimension(260, 220));
scroll2.setPreferredSize(new Dimension(276, 152));
scroll2.setViewportView(reactants);
reacta = new String[0];
changedReactants = new ArrayList<SpeciesReference>();
if (option.equals("OK")) {
Reaction reac = gcm.getSBMLDocument().getModel().getReaction(reactionId);
ListOf<SpeciesReference> listOfReactants = reac.getListOfReactants();
reacta = new String[reac.getReactantCount()];
for (int i = 0; i < reac.getReactantCount(); i++) {
SpeciesReference reactant = listOfReactants.get(i);
changedReactants.add(reactant);
reacta[i] = reactant.getSpecies() + " " + reactant.getStoichiometry();
}
}
Utility.sort(reacta);
reactants.setListData(reacta);
reactants.setSelectedIndex(0);
reactants.addMouseListener(this);
reactantsPanel.add(reactantsLabel, "North");
reactantsPanel.add(scroll2, "Center");
reactantsPanel.add(addReactants, "South");
JPanel productsPanel = new JPanel(new BorderLayout());
JPanel addProducts = new JPanel();
addProduct = new JButton("Add Product");
removeProduct = new JButton("Remove Product");
editProduct = new JButton("Edit Product");
addProducts.add(addProduct);
addProducts.add(removeProduct);
addProducts.add(editProduct);
addProduct.addActionListener(this);
removeProduct.addActionListener(this);
editProduct.addActionListener(this);
JLabel productsLabel = new JLabel("List Of Products:");
products = new JList();
products.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
JScrollPane scroll3 = new JScrollPane();
scroll3.setMinimumSize(new Dimension(260, 220));
scroll3.setPreferredSize(new Dimension(276, 152));
scroll3.setViewportView(products);
proda = new String[0];
changedProducts = new ArrayList<SpeciesReference>();
if (option.equals("OK")) {
Reaction reac = gcm.getSBMLDocument().getModel().getReaction(reactionId);
ListOf<SpeciesReference> listOfProducts = reac.getListOfProducts();
proda = new String[reac.getProductCount()];
for (int i = 0; i < reac.getProductCount(); i++) {
SpeciesReference product = listOfProducts.get(i);
changedProducts.add(product);
this.proda[i] = product.getSpecies() + " " + product.getStoichiometry();
}
}
Utility.sort(proda);
products.setListData(proda);
products.setSelectedIndex(0);
products.addMouseListener(this);
productsPanel.add(productsLabel, "North");
productsPanel.add(scroll3, "Center");
productsPanel.add(addProducts, "South");
JPanel modifierPanel = new JPanel(new BorderLayout());
JPanel addModifiers = new JPanel();
addModifier = new JButton("Add Modifier");
removeModifier = new JButton("Remove Modifier");
editModifier = new JButton("Edit Modifier");
addModifiers.add(addModifier);
addModifiers.add(removeModifier);
addModifiers.add(editModifier);
addModifier.addActionListener(this);
removeModifier.addActionListener(this);
editModifier.addActionListener(this);
JLabel modifiersLabel = new JLabel("List Of Modifiers:");
modifiers = new JList();
modifiers.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
JScrollPane scroll5 = new JScrollPane();
scroll5.setMinimumSize(new Dimension(260, 220));
scroll5.setPreferredSize(new Dimension(276, 152));
scroll5.setViewportView(modifiers);
modifier = new String[0];
changedModifiers = new ArrayList<ModifierSpeciesReference>();
if (option.equals("OK")) {
Reaction reac = gcm.getSBMLDocument().getModel().getReaction(reactionId);
ListOf<ModifierSpeciesReference> listOfModifiers = reac.getListOfModifiers();
modifier = new String[reac.getModifierCount()];
for (int i = 0; i < reac.getModifierCount(); i++) {
ModifierSpeciesReference modifier = listOfModifiers.get(i);
changedModifiers.add(modifier);
this.modifier[i] = modifier.getSpecies();
}
}
Utility.sort(modifier);
modifiers.setListData(modifier);
modifiers.setSelectedIndex(0);
modifiers.addMouseListener(this);
modifierPanel.add(modifiersLabel, "North");
modifierPanel.add(scroll5, "Center");
modifierPanel.add(addModifiers, "South");
JComboBox kineticFluxLabel = new JComboBox(new String[] {"Kinetic Law:","Flux Bounds:"});
kineticLaw = new JTextArea();
kineticLaw.setLineWrap(true);
kineticLaw.setWrapStyleWord(true);
useMassAction = new JButton("Use Mass Action");
clearKineticLaw = new JButton("Clear");
useMassAction.addActionListener(this);
clearKineticLaw.addActionListener(this);
JPanel kineticButtons = new JPanel();
kineticButtons.add(useMassAction);
kineticButtons.add(clearKineticLaw);
JScrollPane scroll4 = new JScrollPane();
scroll4.setMinimumSize(new Dimension(100, 100));
scroll4.setPreferredSize(new Dimension(100, 100));
scroll4.setViewportView(kineticLaw);
if (option.equals("OK")) {
if (gcm.getSBMLDocument().getModel().getReaction(reactionId).getKineticLaw()!=null) {
kineticFluxLabel.setSelectedIndex(0);
kineticLaw.setText(bioModel.removeBooleans(gcm.getSBMLDocument().getModel().getReaction(reactionId).getKineticLaw().getMath()));
} else {
kineticFluxLabel.setSelectedIndex(1);
String fluxbounds = "";
for(int i = 0; i < bioModel.getSBMLFBC().getListOfFluxBounds().size(); i++){
if(bioModel.getSBMLFBC().getListOfFluxBounds().get(i).getReaction().equals(reactionId)){
if(bioModel.getSBMLFBC().getListOfFluxBounds().get(i).getOperation().toString().equals("greaterEqual")){
fluxbounds = bioModel.getSBMLFBC().getListOfFluxBounds().get(i).getValue() + "<=" + fluxbounds;
if(!fluxbounds.contains(reactionId)){
fluxbounds += reactionId;
}
}
if(bioModel.getSBMLFBC().getListOfFluxBounds().get(i).getOperation().toString().equals("lessEqual")){
fluxbounds += "<=" + bioModel.getSBMLFBC().getListOfFluxBounds().get(i).getValue();
if(!fluxbounds.contains(reactionId)){
fluxbounds = reactionId + fluxbounds;
}
}
if(bioModel.getSBMLFBC().getListOfFluxBounds().get(i).getOperation().toString().equals("equal")){
double value = bioModel.getSBMLFBC().getListOfFluxBounds().get(i).getValue();
fluxbounds = value + "<=" + reactionId + "<=" + value;
}
}
}
kineticLaw.setText(fluxbounds);
}
}
JPanel kineticPanel = new JPanel(new BorderLayout());
kineticPanel.add(kineticFluxLabel, "North");
kineticPanel.add(scroll4, "Center");
kineticPanel.add(kineticButtons, "South");
JPanel reactionPanel = new JPanel(new BorderLayout());
if (inSchematic) {
JPanel reactionPanelNorth = new JPanel(new GridLayout(2, 1));
JPanel reactionPanelNorth1 = new JPanel();
JPanel reactionPanelNorth1b = new JPanel();
reactionPanelNorth1.add(id);
reactionPanelNorth1.add(reacID);
reactionPanelNorth1.add(name);
reactionPanelNorth1.add(reacName);
reactionPanelNorth1.add(onPortLabel);
reactionPanelNorth1.add(onPort);
if (gcm.getSBMLDocument().getLevel() > 2) {
reactionPanelNorth1b.add(reactionCompLabel);
reactionPanelNorth1b.add(reactionComp);
}
reactionPanelNorth1b.add(reverse);
reactionPanelNorth1b.add(reacReverse);
reactionPanelNorth1b.add(fast);
reactionPanelNorth1b.add(reacFast);
// Parse out SBOL annotations and add to SBOL field
if (!paramsOnly) {
// Field for annotating reaction with SBOL DNA components
Reaction reac = gcm.getSBMLDocument().getModel().getReaction(reactionId);
List<URI> sbolURIs = new LinkedList<URI>();
String sbolStrand = AnnotationUtility.parseSBOLAnnotation(reac, sbolURIs);
sbolField = new SBOLField(sbolURIs, sbolStrand, GlobalConstants.SBOL_DNA_COMPONENT, modelEditor,
2, false);
reactionPanelNorth1b.add(sbolField);
}
reactionPanelNorth.add(reactionPanelNorth1);
reactionPanelNorth.add(reactionPanelNorth1b);
reactionPanel.add(reactionPanelNorth, "North");
reactionPanel.add(param, "Center");
reactionPanel.add(kineticPanel, "South");
}
else {
JPanel reactionPanelNorth = new JPanel();
JPanel reactionPanelNorth1 = new JPanel();
JPanel reactionPanelNorth1b = new JPanel();
JPanel reactionPanelNorth2 = new JPanel();
JPanel reactionPanelCentral = new JPanel(new GridLayout(1, 3));
JPanel reactionPanelSouth = new JPanel(new GridLayout(1, 2));
reactionPanelNorth1.add(id);
reactionPanelNorth1.add(reacID);
reactionPanelNorth1.add(name);
reactionPanelNorth1.add(reacName);
if (gcm.getSBMLDocument().getLevel() > 2) {
reactionPanelNorth1.add(reactionCompLabel);
reactionPanelNorth1.add(reactionComp);
}
reactionPanelNorth1b.add(reverse);
reactionPanelNorth1b.add(reacReverse);
reactionPanelNorth1b.add(fast);
reactionPanelNorth1b.add(reacFast);
reactionPanelNorth2.add(reactionPanelNorth1);
reactionPanelNorth2.add(reactionPanelNorth1b);
reactionPanelNorth.add(reactionPanelNorth2);
reactionPanelCentral.add(reactantsPanel);
reactionPanelCentral.add(productsPanel);
reactionPanelCentral.add(modifierPanel);
reactionPanelSouth.add(param);
reactionPanelSouth.add(kineticPanel);
reactionPanel.add(reactionPanelNorth, "North");
reactionPanel.add(reactionPanelCentral, "Center");
reactionPanel.add(reactionPanelSouth, "South");
}
if (option.equals("OK")) {
Reaction reac = gcm.getSBMLDocument().getModel().getReaction(reactionId);
copyReact = reac.clone();
reacID.setText(reac.getId());
selectedID = reac.getId();
reacName.setText(reac.getName());
if (gcm.getPortByIdRef(reac.getId())!=null) {
onPort.setSelected(true);
} else {
onPort.setSelected(false);
}
if (reac.getReversible()) {
reacReverse.setSelectedItem("true");
}
else {
reacReverse.setSelectedItem("false");
}
if (reac.getFast()) {
reacFast.setSelectedItem("true");
}
else {
reacFast.setSelectedItem("false");
}
if (gcm.getSBMLDocument().getLevel() > 2) {
reactionComp.setSelectedItem(reac.getCompartment());
}
complex = null;
production = null;
if (reac.isSetSBOTerm()) {
if (BioModel.isComplexReaction(reac)) {
complex = reac;
reacID.setEnabled(false);
reacName.setEnabled(false);
onPort.setEnabled(false);
reacReverse.setEnabled(false);
reacFast.setEnabled(false);
reactionComp.setEnabled(false);
reacAddParam.setEnabled(false);
reacRemoveParam.setEnabled(false);
reacEditParam.setEnabled(false);
addProduct.setEnabled(false);
removeProduct.setEnabled(false);
editProduct.setEnabled(false);
products.removeMouseListener(this);
addModifier.setEnabled(false);
removeModifier.setEnabled(false);
editModifier.setEnabled(false);
modifiers.removeMouseListener(this);
kineticLaw.setEditable(false);
clearKineticLaw.setEnabled(false);
reacParameters.setEnabled(false);
useMassAction.setEnabled(false);
} else if (BioModel.isConstitutiveReaction(reac) || BioModel.isDegradationReaction(reac) ||
BioModel.isDiffusionReaction(reac)) {
reacID.setEnabled(false);
reacName.setEnabled(false);
onPort.setEnabled(false);
reacReverse.setEnabled(false);
reacFast.setEnabled(false);
reactionComp.setEnabled(false);
reacAddParam.setEnabled(false);
reacRemoveParam.setEnabled(false);
reacEditParam.setEnabled(false);
addReactant.setEnabled(false);
removeReactant.setEnabled(false);
editReactant.setEnabled(false);
reactants.removeMouseListener(this);
addProduct.setEnabled(false);
removeProduct.setEnabled(false);
editProduct.setEnabled(false);
products.removeMouseListener(this);
addModifier.setEnabled(false);
removeModifier.setEnabled(false);
editModifier.setEnabled(false);
modifiers.removeMouseListener(this);
kineticLaw.setEditable(false);
useMassAction.setEnabled(false);
clearKineticLaw.setEnabled(false);
reacParameters.setEnabled(false);
} else if (BioModel.isProductionReaction(reac)) {
production = reac;
reacID.setEnabled(false);
reacName.setEnabled(false);
onPort.setEnabled(false);
reacReverse.setEnabled(false);
reacFast.setEnabled(false);
reactionComp.setEnabled(false);
reacAddParam.setEnabled(false);
reacRemoveParam.setEnabled(false);
reacEditParam.setEnabled(false);
addReactant.setEnabled(false);
removeReactant.setEnabled(false);
editReactant.setEnabled(false);
reactants.removeMouseListener(this);
kineticLaw.setEditable(false);
clearKineticLaw.setEnabled(false);
reacParameters.setEnabled(false);
useMassAction.setEnabled(false);
}
}
}
else {
String NEWreactionId = "r0";
int i = 0;
while (gcm.isSIdInUse(NEWreactionId)) {
i++;
NEWreactionId = "r" + i;
}
reacID.setText(NEWreactionId);
}
if (paramsOnly) {
reacID.setEditable(false);
reacName.setEditable(false);
reacReverse.setEnabled(false);
reacFast.setEnabled(false);
reacAddParam.setEnabled(false);
reacRemoveParam.setEnabled(false);
addReactant.setEnabled(false);
removeReactant.setEnabled(false);
editReactant.setEnabled(false);
addProduct.setEnabled(false);
removeProduct.setEnabled(false);
editProduct.setEnabled(false);
addModifier.setEnabled(false);
removeModifier.setEnabled(false);
editModifier.setEnabled(false);
kineticLaw.setEditable(false);
useMassAction.setEnabled(false);
clearKineticLaw.setEnabled(false);
reactionComp.setEnabled(false);
onPort.setEnabled(false);
}
Object[] options1 = { option, "Cancel" };
int value = JOptionPane.showOptionDialog(Gui.frame, reactionPanel, "Reaction Editor", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE,
null, options1, options1[0]);
boolean error = true;
while (error && value == JOptionPane.YES_OPTION) {
String reac = reacID.getText().trim();
error = SBMLutilities.checkID(gcm.getSBMLDocument(), reac, selectedID, false);
if (!error) {
if (complex==null && production==null && kineticLaw.getText().trim().equals("")) {
JOptionPane.showMessageDialog(Gui.frame, "A reaction must have a kinetic law.", "Enter A Kinetic Law", JOptionPane.ERROR_MESSAGE);
error = true;
}
else if ((changedReactants.size() == 0) && (changedProducts.size() == 0)) {
JOptionPane.showMessageDialog(Gui.frame, "A reaction must have at least one reactant or product.", "No Reactants or Products",
JOptionPane.ERROR_MESSAGE);
error = true;
}
else if(kineticFluxLabel.getSelectedItem().equals("Kinteic Law:")){
if (complex==null && production==null && SBMLutilities.myParseFormula(kineticLaw.getText().trim()) == null) {
JOptionPane.showMessageDialog(Gui.frame, "Unable to parse kinetic law.", "Kinetic Law Error", JOptionPane.ERROR_MESSAGE);
error = true;
}
else if (complex==null && production==null){
ArrayList<String> invalidKineticVars = getInvalidVariablesInReaction(kineticLaw.getText().trim(), true, "", false);
if (invalidKineticVars.size() > 0) {
String invalid = "";
for (int i = 0; i < invalidKineticVars.size(); i++) {
if (i == invalidKineticVars.size() - 1) {
invalid += invalidKineticVars.get(i);
}
else {
invalid += invalidKineticVars.get(i) + "\n";
}
}
String message;
message = "Kinetic law contains unknown variables.\n\n" + "Unknown variables:\n" + invalid;
JTextArea messageArea = new JTextArea(message);
messageArea.setLineWrap(true);
messageArea.setWrapStyleWord(true);
messageArea.setEditable(false);
JScrollPane scrolls = new JScrollPane();
scrolls.setMinimumSize(new Dimension(300, 300));
scrolls.setPreferredSize(new Dimension(300, 300));
scrolls.setViewportView(messageArea);
JOptionPane.showMessageDialog(Gui.frame, scrolls, "Kinetic Law Error", JOptionPane.ERROR_MESSAGE);
error = true;
}
if (!error) {
error = SBMLutilities.checkNumFunctionArguments(gcm.getSBMLDocument(), SBMLutilities.myParseFormula(kineticLaw.getText().trim()));
}
}
}
else {
// TODO: see method
error = !fluxBoundisGood(kineticLaw.getText().replaceAll("\\s",""), reactionId);
}
}
if(kineticFluxLabel.getSelectedItem().equals("Kinetic Law:")){
if (!error && complex==null && production==null) {
if (SBMLutilities.returnsBoolean(bioModel.addBooleans(kineticLaw.getText().trim()), bioModel.getSBMLDocument().getModel())) {
JOptionPane.showMessageDialog(Gui.frame, "Kinetic law must evaluate to a number.", "Number Expected", JOptionPane.ERROR_MESSAGE);
error = true;
}
}
}
if (!error) {
if (option.equals("OK")) {
int index = reactions.getSelectedIndex();
String val = reactionId;
Reaction react = gcm.getSBMLDocument().getModel().getReaction(val);
ListOf remove;
long size;
if (react.getKineticLaw()==null) {
react.createKineticLaw();
}
remove = react.getKineticLaw().getListOfLocalParameters();
size = react.getKineticLaw().getLocalParameterCount();
for (int i = 0; i < size; i++) {
remove.remove(0);
}
for (int i = 0; i < changedParameters.size(); i++) {
react.getKineticLaw().addLocalParameter(changedParameters.get(i));
}
remove = react.getListOfProducts();
size = react.getProductCount();
for (int i = 0; i < size; i++) {
remove.remove(0);
}
for (int i = 0; i < changedProducts.size(); i++) {
react.addProduct(changedProducts.get(i));
}
remove = react.getListOfModifiers();
size = react.getModifierCount();
for (int i = 0; i < size; i++) {
remove.remove(0);
}
for (int i = 0; i < changedModifiers.size(); i++) {
react.addModifier(changedModifiers.get(i));
}
remove = react.getListOfReactants();
size = react.getReactantCount();
for (int i = 0; i < size; i++) {
remove.remove(0);
}
for (int i = 0; i < changedReactants.size(); i++) {
react.addReactant(changedReactants.get(i));
}
if (reacReverse.getSelectedItem().equals("true")) {
react.setReversible(true);
}
else {
react.setReversible(false);
}
if (gcm.getSBMLDocument().getLevel() > 2) {
react.setCompartment((String) reactionComp.getSelectedItem());
}
if (reacFast.getSelectedItem().equals("true")) {
react.setFast(true);
}
else {
react.setFast(false);
}
react.setId(reacID.getText().trim());
react.setName(reacName.getText().trim());
Port port = gcm.getPortByIdRef(val);
if (port!=null) {
if (onPort.isSelected()) {
port.setId(GlobalConstants.SBMLREACTION+"__"+react.getId());
port.setIdRef(react.getId());
} else {
SBMLutilities.removeFromParentAndDelete(port);
}
} else {
if (onPort.isSelected()) {
port = gcm.getSBMLCompModel().createPort();
port.setId(GlobalConstants.SBMLREACTION+"__"+react.getId());
port.setIdRef(react.getId());
}
}
if(kineticFluxLabel.getSelectedItem().equals("Kinetic Law:")){
if (complex==null && production==null) {
react.getKineticLaw().setMath(bioModel.addBooleans(kineticLaw.getText().trim()));
} else if (complex!=null) {
react.getKineticLaw().setMath(SBMLutilities.myParseFormula(BioModel.createComplexKineticLaw(complex)));
} else {
react.getKineticLaw().setMath(SBMLutilities.myParseFormula(BioModel.createProductionKineticLaw(production)));
}
error = checkKineticLawUnits(react.getKineticLaw());
int i = 0;
while (i < bioModel.getSBMLFBC().getListOfFluxBounds().size()) {
if(bioModel.getSBMLFBC().getListOfFluxBounds().get(i).getReaction().equals(reactionId)){
bioModel.getSBMLFBC().removeFluxBound(i);
} else {
i++;
}
}
}
else{
react.unsetKineticLaw();
int i = 0;
while(i < bioModel.getSBMLFBC().getListOfFluxBounds().size()){
if(bioModel.getSBMLFBC().getListOfFluxBounds().get(i).getReaction().equals(reactionId)){
bioModel.getSBMLFBC().removeFluxBound(i);
} else {
i++;
}
}
if(kineticLaw.getText().contains("<=")){
String[] userInput = kineticLaw.getText().replaceAll("\\s","").split("<=");
if (userInput.length==3) {
double greaterValue = Double.parseDouble(userInput[0]);
FluxBound fxGreater = bioModel.getSBMLFBC().createFluxBound();
fxGreater.setOperation(FluxBound.Operation.GREATER_EQUAL);
fxGreater.setValue(greaterValue);
fxGreater.setReaction(reactionId);
double lessValue = Double.parseDouble(userInput[2]);
FluxBound fxLess = bioModel.getSBMLFBC().createFluxBound();
fxLess.setOperation(FluxBound.Operation.LESS_EQUAL);
fxLess.setValue(lessValue);
fxLess.setReaction(reactionId);
}
else {
try{
double lessValue = Double.parseDouble(userInput[1]);
FluxBound fxLess = bioModel.getSBMLFBC().createFluxBound();
fxLess.setOperation(FluxBound.Operation.LESS_EQUAL);
fxLess.setValue(lessValue);
fxLess.setReaction(reactionId);
//TODO: should I add infinity?
}
catch(Exception e){
double greaterValue = Double.parseDouble(userInput[0]);
FluxBound fxGreater = bioModel.getSBMLFBC().createFluxBound();
fxGreater.setOperation(FluxBound.Operation.GREATER_EQUAL);
fxGreater.setValue(greaterValue);
fxGreater.setReaction(reactionId);
}
}
// TODO: deal with one sided bounds
}
else if(kineticLaw.getText().contains(">=")){
String[] userInput = kineticLaw.getText().replaceAll("\\s","").split(">=");
if (userInput.length==3) {
double greaterValue = Double.parseDouble(userInput[2]);
FluxBound fxGreater = bioModel.getSBMLFBC().createFluxBound();
fxGreater.setOperation(FluxBound.Operation.GREATER_EQUAL);
fxGreater.setValue(greaterValue);
fxGreater.setReaction(reactionId);
double lessValue = Double.parseDouble(userInput[0]);
FluxBound fxLess = bioModel.getSBMLFBC().createFluxBound();
fxLess.setOperation(FluxBound.Operation.LESS_EQUAL);
fxLess.setValue(lessValue);
fxLess.setReaction(reactionId);
} else {
try{
double greaterValue = Double.parseDouble(userInput[1]);
FluxBound fxGreater = bioModel.getSBMLFBC().createFluxBound();
fxGreater.setOperation(FluxBound.Operation.GREATER_EQUAL);
fxGreater.setValue(greaterValue);
fxGreater.setReaction(reactionId);
}
catch(Exception e){
double lessValue = Double.parseDouble(userInput[0]);
FluxBound fxLess = bioModel.getSBMLFBC().createFluxBound();
fxLess.setOperation(FluxBound.Operation.LESS_EQUAL);
fxLess.setValue(lessValue);
fxLess.setReaction(reactionId);
//TODO: should I add infinity?
}
}
}
else{
String[] userInput = kineticLaw.getText().replaceAll("\\s","").split("=");
FluxBound fxEqual = bioModel.getSBMLFBC().createFluxBound();
fxEqual.setOperation(FluxBound.Operation.EQUAL);
fxEqual.setReaction(reactionId);
if(userInput[0].equals(reactionId)){
fxEqual.setValue(Double.parseDouble(userInput[1]));
}
else{
fxEqual.setValue(Double.parseDouble(userInput[0]));
}
}
}
if (!error) {
error = SBMLutilities.checkCycles(gcm.getSBMLDocument());
if (error) {
JOptionPane.showMessageDialog(Gui.frame, "Cycle detected within initial assignments, assignment rules, and rate laws.",
"Cycle Detected", JOptionPane.ERROR_MESSAGE);
}
}
if (!error) {
if (index >= 0) {
if (!paramsOnly) {
reacts[index] = reac;
}
reactions.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
reacts = Utility.getList(reacts, reactions);
reactions.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
Utility.sort(reacts);
reactions.setListData(reacts);
reactions.setSelectedIndex(index);
}
}
else {
changedParameters = new ArrayList<LocalParameter>();
ListOf<LocalParameter> listOfParameters = react.getKineticLaw().getListOfLocalParameters();
for (int i = 0; i < react.getKineticLaw().getLocalParameterCount(); i++) {
LocalParameter parameter = listOfParameters.get(i);
changedParameters.add(new LocalParameter(parameter));
}
changedProducts = new ArrayList<SpeciesReference>();
ListOf<SpeciesReference> listOfProducts = react.getListOfProducts();
for (int i = 0; i < react.getProductCount(); i++) {
SpeciesReference product = listOfProducts.get(i);
changedProducts.add(product);
}
changedReactants = new ArrayList<SpeciesReference>();
ListOf<SpeciesReference> listOfReactants = react.getListOfReactants();
for (int i = 0; i < react.getReactantCount(); i++) {
SpeciesReference reactant = listOfReactants.get(i);
changedReactants.add(reactant);
}
changedModifiers = new ArrayList<ModifierSpeciesReference>();
ListOf<ModifierSpeciesReference> listOfModifiers = react.getListOfModifiers();
for (int i = 0; i < react.getModifierCount(); i++) {
ModifierSpeciesReference modifier = listOfModifiers.get(i);
changedModifiers.add(modifier);
}
}
// Handle SBOL data
if (!error && inSchematic && !paramsOnly) {
// Checks whether SBOL annotation on model needs to be deleted later when annotating rxn with SBOL
// boolean removeModelSBOLAnnotationFlag = false;
// LinkedList<URI> sbolURIs = sbolField.getSBOLURIs();
// if (sbolURIs.size() > 0 && bioModel.getElementSBOLCount() == 0
// && bioModel.getModelSBOLAnnotationFlag()) {
// Object[] sbolOptions = { "OK", "Cancel" };
// int choice = JOptionPane.showOptionDialog(null,
// "SBOL associated to model elements can't coexist with SBOL associated to model itself unless" +
// " the latter was previously generated from the former. Remove SBOL associated to model?",
// "Warning", JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE, null, sbolOptions, sbolOptions[0]);
// if (choice == JOptionPane.OK_OPTION)
// removeModelSBOLAnnotationFlag = true;
// else
// error = true;
if (!error) {
// Add SBOL annotation to reaction
if (sbolField.getSBOLURIs().size() > 0) {
SBOLAnnotation sbolAnnot = new SBOLAnnotation(react.getMetaId(), sbolField.getSBOLURIs(),
sbolField.getSBOLStrand());
AnnotationUtility.setSBOLAnnotation(react, sbolAnnot);
} else
AnnotationUtility.removeSBOLAnnotation(react);
}
}
}
else {
Reaction react = gcm.getSBMLDocument().getModel().createReaction();
int index = reactions.getSelectedIndex();
if(kineticFluxLabel.getSelectedItem().equals("Kinetic Law:")){
react.createKineticLaw();
for (int i = 0; i < changedParameters.size(); i++) {
react.getKineticLaw().addLocalParameter(changedParameters.get(i));
}
}
for (int i = 0; i < changedProducts.size(); i++) {
react.addProduct(changedProducts.get(i));
}
for (int i = 0; i < changedModifiers.size(); i++) {
react.addModifier(changedModifiers.get(i));
}
for (int i = 0; i < changedReactants.size(); i++) {
react.addReactant(changedReactants.get(i));
}
if (reacReverse.getSelectedItem().equals("true")) {
react.setReversible(true);
}
else {
react.setReversible(false);
}
if (reacFast.getSelectedItem().equals("true")) {
react.setFast(true);
}
else {
react.setFast(false);
}
if (gcm.getSBMLDocument().getLevel() > 2) {
react.setCompartment((String) reactionComp.getSelectedItem());
}
react.setId(reacID.getText().trim());
react.setName(reacName.getText().trim());
if (onPort.isSelected()) {
Port port = gcm.getSBMLCompModel().createPort();
port.setId(GlobalConstants.SBMLREACTION+"__"+react.getId());
port.setIdRef(react.getId());
}
if(kineticFluxLabel.getSelectedItem().equals("Kinetic Law:")){
if (complex==null && production==null) {
react.getKineticLaw().setMath(bioModel.addBooleans(kineticLaw.getText().trim()));
} else if (complex!=null) {
react.getKineticLaw().setMath(SBMLutilities.myParseFormula(BioModel.createComplexKineticLaw(complex)));
} else {
react.getKineticLaw().setMath(SBMLutilities.myParseFormula(BioModel.createProductionKineticLaw(production)));
}
error = checkKineticLawUnits(react.getKineticLaw());
}
else{
// TODO: needs to be copied from above
error = !fluxBoundisGood(kineticLaw.getText().replaceAll("\\s",""), reactionId);
}
if (!error) {
error = SBMLutilities.checkCycles(gcm.getSBMLDocument());
if (error) {
JOptionPane.showMessageDialog(Gui.frame, "Cycle detected within initial assignments, assignment rules, and rate laws.",
"Cycle Detected", JOptionPane.ERROR_MESSAGE);
}
}
if (!error) {
JList add = new JList();
Object[] adding = { reac };
add.setListData(adding);
add.setSelectedIndex(0);
reactions.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
adding = Utility.add(reacts, reactions, add);
reacts = new String[adding.length];
for (int i = 0; i < adding.length; i++) {
reacts[i] = (String) adding[i];
}
Utility.sort(reacts);
reactions.setListData(reacts);
reactions.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
if (gcm.getSBMLDocument().getModel().getReactionCount() == 1) {
reactions.setSelectedIndex(0);
}
else {
reactions.setSelectedIndex(index);
}
}
else {
removeTheReaction(gcm, reac);
}
}
modelEditor.setDirty(true);
gcm.makeUndoPoint();
}
if (error) {
value = JOptionPane.showOptionDialog(Gui.frame, reactionPanel, "Reaction Editor", JOptionPane.YES_NO_OPTION,
JOptionPane.PLAIN_MESSAGE, null, options1, options1[0]);
}
}
if (value == JOptionPane.NO_OPTION) {
if (option.equals("OK")) {
String reac = reactionId;
removeTheReaction(gcm, reac);
gcm.getSBMLDocument().getModel().addReaction(copyReact);
}
return;
}
}
/**
* Find invalid reaction variables in a formula
*/
private ArrayList<String> getInvalidVariablesInReaction(String formula, boolean isReaction, String arguments, boolean isFunction) {
ArrayList<String> validVars = new ArrayList<String>();
ArrayList<String> invalidVars = new ArrayList<String>();
Model model = bioModel.getSBMLDocument().getModel();
for (int i = 0; i < bioModel.getSBMLDocument().getModel().getFunctionDefinitionCount(); i++) {
validVars.add(model.getFunctionDefinition(i).getId());
}
if (isReaction) {
for (int i = 0; i < changedParameters.size(); i++) {
validVars.add(changedParameters.get(i).getId());
}
for (int i = 0; i < changedReactants.size(); i++) {
validVars.add(changedReactants.get(i).getSpecies());
validVars.add(changedReactants.get(i).getId());
}
for (int i = 0; i < changedProducts.size(); i++) {
validVars.add(changedProducts.get(i).getSpecies());
validVars.add(changedProducts.get(i).getId());
}
for (int i = 0; i < changedModifiers.size(); i++) {
validVars.add(changedModifiers.get(i).getSpecies());
}
}
else if (!isFunction) {
for (int i = 0; i < bioModel.getSBMLDocument().getModel().getSpeciesCount(); i++) {
validVars.add(model.getSpecies(i).getId());
}
}
if (isFunction) {
String[] args = arguments.split(" |\\,");
for (int i = 0; i < args.length; i++) {
validVars.add(args[i]);
}
}
else {
for (int i = 0; i < bioModel.getSBMLDocument().getModel().getCompartmentCount(); i++) {
if (bioModel.getSBMLDocument().getLevel() > 2 || (model.getCompartment(i).getSpatialDimensions() != 0)) {
validVars.add(model.getCompartment(i).getId());
}
}
for (int i = 0; i < bioModel.getSBMLDocument().getModel().getParameterCount(); i++) {
validVars.add(model.getParameter(i).getId());
}
for (int i = 0; i < bioModel.getSBMLDocument().getModel().getReactionCount(); i++) {
Reaction reaction = model.getReaction(i);
validVars.add(reaction.getId());
for (int j = 0; j < reaction.getReactantCount(); j++) {
SpeciesReference reactant = reaction.getReactant(j);
if ((reactant.isSetId()) && (!reactant.getId().equals(""))) {
validVars.add(reactant.getId());
}
}
for (int j = 0; j < reaction.getProductCount(); j++) {
SpeciesReference product = reaction.getProduct(j);
if ((product.isSetId()) && (!product.getId().equals(""))) {
validVars.add(product.getId());
}
}
}
String[] kindsL3V1 = { "ampere", "avogadro", "becquerel", "candela", "celsius", "coulomb", "dimensionless", "farad", "gram", "gray", "henry",
"hertz", "item", "joule", "katal", "kelvin", "kilogram", "litre", "lumen", "lux", "metre", "mole", "newton", "ohm", "pascal",
"radian", "second", "siemens", "sievert", "steradian", "tesla", "volt", "watt", "weber" };
for (int i = 0; i < kindsL3V1.length; i++) {
validVars.add(kindsL3V1[i]);
}
for (int i = 0; i < model.getUnitDefinitionCount(); i++) {
validVars.add(model.getUnitDefinition(i).getId());
}
}
String[] splitLaw = formula.split(" |\\(|\\)|\\,|\\*|\\+|\\/|\\-|>|=|<|\\^|%|&|\\||!");
for (int i = 0; i < splitLaw.length; i++) {
if (splitLaw[i].equals("abs") || splitLaw[i].equals("arccos") || splitLaw[i].equals("arccosh") || splitLaw[i].equals("arcsin")
|| splitLaw[i].equals("arcsinh") || splitLaw[i].equals("arctan") || splitLaw[i].equals("arctanh") || splitLaw[i].equals("arccot")
|| splitLaw[i].equals("arccoth") || splitLaw[i].equals("arccsc") || splitLaw[i].equals("arccsch") || splitLaw[i].equals("arcsec")
|| splitLaw[i].equals("arcsech") || splitLaw[i].equals("acos") || splitLaw[i].equals("acosh") || splitLaw[i].equals("asin")
|| splitLaw[i].equals("asinh") || splitLaw[i].equals("atan") || splitLaw[i].equals("atanh") || splitLaw[i].equals("acot")
|| splitLaw[i].equals("acoth") || splitLaw[i].equals("acsc") || splitLaw[i].equals("acsch") || splitLaw[i].equals("asec")
|| splitLaw[i].equals("asech") || splitLaw[i].equals("cos") || splitLaw[i].equals("cosh") || splitLaw[i].equals("cot")
|| splitLaw[i].equals("coth") || splitLaw[i].equals("csc") || splitLaw[i].equals("csch") || splitLaw[i].equals("ceil")
|| splitLaw[i].equals("factorial") || splitLaw[i].equals("exp") || splitLaw[i].equals("floor") || splitLaw[i].equals("ln")
|| splitLaw[i].equals("log") || splitLaw[i].equals("sqr") || splitLaw[i].equals("log10") || splitLaw[i].equals("pow")
|| splitLaw[i].equals("sqrt") || splitLaw[i].equals("root") || splitLaw[i].equals("piecewise") || splitLaw[i].equals("sec")
|| splitLaw[i].equals("sech") || splitLaw[i].equals("sin") || splitLaw[i].equals("sinh") || splitLaw[i].equals("tan")
|| splitLaw[i].equals("tanh") || splitLaw[i].equals("") || splitLaw[i].equals("and") || splitLaw[i].equals("or")
|| splitLaw[i].equals("xor") || splitLaw[i].equals("not") || splitLaw[i].equals("eq") || splitLaw[i].equals("geq")
|| splitLaw[i].equals("leq") || splitLaw[i].equals("gt") || splitLaw[i].equals("neq") || splitLaw[i].equals("lt")
|| splitLaw[i].equals("delay") || splitLaw[i].equals("t") || splitLaw[i].equals("time") || splitLaw[i].equals("true")
|| splitLaw[i].equals("false") || splitLaw[i].equals("pi") || splitLaw[i].equals("exponentiale")
|| ((bioModel.getSBMLDocument().getLevel() > 2) && (splitLaw[i].equals("avogadro")))) {
}
else {
String temp = splitLaw[i];
if (splitLaw[i].substring(splitLaw[i].length() - 1, splitLaw[i].length()).equals("e")) {
temp = splitLaw[i].substring(0, splitLaw[i].length() - 1);
}
try {
Double.parseDouble(temp);
}
catch (Exception e1) {
if (!validVars.contains(splitLaw[i])) {
invalidVars.add(splitLaw[i]);
}
}
}
}
return invalidVars;
}
/**
* Creates a frame used to edit reactions parameters or create new ones.
*/
private void reacParametersEditor(BioModel gcm,String option) {
if (option.equals("OK") && reacParameters.getSelectedIndex() == -1) {
JOptionPane.showMessageDialog(Gui.frame, "No parameter selected.", "Must Select A Parameter", JOptionPane.ERROR_MESSAGE);
return;
}
JPanel parametersPanel;
if (paramsOnly) {
parametersPanel = new JPanel(new GridLayout(7, 2));
}
else {
parametersPanel = new JPanel(new GridLayout(5, 2));
}
JLabel idLabel = new JLabel("ID:");
JLabel nameLabel = new JLabel("Name:");
JLabel valueLabel = new JLabel("Value:");
JLabel unitsLabel = new JLabel("Units:");
JLabel onPortLabel = new JLabel("Is Mapped to a Port:");
paramOnPort = new JCheckBox();
reacParamID = new JTextField();
reacParamName = new JTextField();
reacParamValue = new JTextField();
reacParamUnits = new JComboBox();
reacParamUnits.addItem("( none )");
Model model = bioModel.getSBMLDocument().getModel();
ListOf<UnitDefinition> listOfUnits = model.getListOfUnitDefinitions();
String[] units = new String[model.getUnitDefinitionCount()];
for (int i = 0; i < model.getUnitDefinitionCount(); i++) {
UnitDefinition unit = listOfUnits.get(i);
units[i] = unit.getId();
// GET OTHER THINGS
}
for (int i = 0; i < units.length; i++) {
if (bioModel.getSBMLDocument().getLevel() > 2
|| (!units[i].equals("substance") && !units[i].equals("volume") && !units[i].equals("area") && !units[i].equals("length") && !units[i]
.equals("time"))) {
reacParamUnits.addItem(units[i]);
}
}
String[] unitIdsL2V4 = { "substance", "volume", "area", "length", "time", "ampere", "becquerel", "candela", "celsius", "coulomb",
"dimensionless", "farad", "gram", "gray", "henry", "hertz", "item", "joule", "katal", "kelvin", "kilogram", "litre", "lumen", "lux",
"metre", "mole", "newton", "ohm", "pascal", "radian", "second", "siemens", "sievert", "steradian", "tesla", "volt", "watt", "weber" };
String[] unitIdsL3V1 = { "ampere", "avogadro", "becquerel", "candela", "celsius", "coulomb", "dimensionless", "farad", "gram", "gray",
"henry", "hertz", "item", "joule", "katal", "kelvin", "kilogram", "litre", "lumen", "lux", "metre", "mole", "newton", "ohm",
"pascal", "radian", "second", "siemens", "sievert", "steradian", "tesla", "volt", "watt", "weber" };
String[] unitIds;
if (bioModel.getSBMLDocument().getLevel() < 3) {
unitIds = unitIdsL2V4;
}
else {
unitIds = unitIdsL3V1;
}
for (int i = 0; i < unitIds.length; i++) {
reacParamUnits.addItem(unitIds[i]);
}
String[] list = { "Original", "Modified" };
String[] list1 = { "1", "2" };
final JComboBox type = new JComboBox(list);
final JTextField start = new JTextField();
final JTextField stop = new JTextField();
final JTextField step = new JTextField();
final JComboBox level = new JComboBox(list1);
final JButton sweep = new JButton("Sweep");
sweep.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Object[] options = { "Ok", "Close" };
JPanel p = new JPanel(new GridLayout(4, 2));
JLabel startLabel = new JLabel("Start:");
JLabel stopLabel = new JLabel("Stop:");
JLabel stepLabel = new JLabel("Step:");
JLabel levelLabel = new JLabel("Level:");
p.add(startLabel);
p.add(start);
p.add(stopLabel);
p.add(stop);
p.add(stepLabel);
p.add(step);
p.add(levelLabel);
p.add(level);
int i = JOptionPane.showOptionDialog(Gui.frame, p, "Sweep", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options,
options[0]);
if (i == JOptionPane.YES_OPTION) {
double startVal = 0.0;
double stopVal = 0.0;
double stepVal = 0.0;
try {
startVal = Double.parseDouble(start.getText().trim());
stopVal = Double.parseDouble(stop.getText().trim());
stepVal = Double.parseDouble(step.getText().trim());
}
catch (Exception e1) {
}
reacParamValue.setText("(" + startVal + "," + stopVal + "," + stepVal + "," + level.getSelectedItem() + ")");
}
}
});
if (paramsOnly) {
reacParamID.setEditable(false);
reacParamName.setEditable(false);
reacParamValue.setEnabled(false);
reacParamUnits.setEnabled(false);
sweep.setEnabled(false);
paramOnPort.setEnabled(false);
}
String selectedID = "";
if (option.equals("OK")) {
String v = ((String) reacParameters.getSelectedValue()).split(" ")[0];
LocalParameter paramet = null;
for (LocalParameter p : changedParameters) {
if (p.getId().equals(v)) {
paramet = p;
}
}
if (paramet==null) return;
reacParamID.setText(paramet.getId());
selectedID = paramet.getId();
reacParamName.setText(paramet.getName());
reacParamValue.setText("" + paramet.getValue());
if (paramet.isSetUnits()) {
reacParamUnits.setSelectedItem(paramet.getUnits());
}
if (gcm.getPortByMetaIdRef(paramet.getMetaId())!=null) {
paramOnPort.setSelected(true);
} else {
paramOnPort.setSelected(false);
}
if (paramsOnly && (((String) reacParameters.getSelectedValue()).contains("Modified"))
|| (((String) reacParameters.getSelectedValue()).contains("Custom"))
|| (((String) reacParameters.getSelectedValue()).contains("Sweep"))) {
type.setSelectedItem("Modified");
sweep.setEnabled(true);
reacParamValue.setText(((String) reacParameters.getSelectedValue()).split(" ")[((String) reacParameters.getSelectedValue())
.split(" ").length - 1]);
reacParamValue.setEnabled(true);
reacParamUnits.setEnabled(false);
if (reacParamValue.getText().trim().startsWith("(")) {
try {
start.setText((reacParamValue.getText().trim()).split(",")[0].substring(1).trim());
stop.setText((reacParamValue.getText().trim()).split(",")[1].trim());
step.setText((reacParamValue.getText().trim()).split(",")[2].trim());
int lev = Integer.parseInt((reacParamValue.getText().trim()).split(",")[3].replace(")", "").trim());
if (lev == 1) {
level.setSelectedIndex(0);
}
else {
level.setSelectedIndex(1);
}
}
catch (Exception e1) {
}
}
}
}
parametersPanel.add(idLabel);
parametersPanel.add(reacParamID);
parametersPanel.add(nameLabel);
parametersPanel.add(reacParamName);
if (paramsOnly) {
JLabel typeLabel = new JLabel("Type:");
type.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (!((String) type.getSelectedItem()).equals("Original")) {
sweep.setEnabled(true);
reacParamValue.setEnabled(true);
reacParamUnits.setEnabled(false);
}
else {
sweep.setEnabled(false);
reacParamValue.setEnabled(false);
reacParamUnits.setEnabled(false);
SBMLDocument d = SBMLutilities.readSBML(file);
KineticLaw KL = d.getModel().getReaction(selectedReaction).getKineticLaw();
ListOf<LocalParameter> list = KL.getListOfLocalParameters();
int number = -1;
for (int i = 0; i < KL.getLocalParameterCount(); i++) {
if (list.get(i).getId().equals(((String) reacParameters.getSelectedValue()).split(" ")[0])) {
number = i;
}
}
reacParamValue.setText(d.getModel().getReaction(selectedReaction).getKineticLaw()
.getLocalParameter(number).getValue()
+ "");
if (d.getModel().getReaction(selectedReaction).getKineticLaw().getLocalParameter(number)
.isSetUnits()) {
reacParamUnits.setSelectedItem(d.getModel().getReaction(selectedReaction)
.getKineticLaw().getLocalParameter(number).getUnits());
}
reacParamValue.setText(d.getModel().getReaction(selectedReaction).getKineticLaw().getLocalParameter(number).getValue() + "");
}
}
});
parametersPanel.add(typeLabel);
parametersPanel.add(type);
}
parametersPanel.add(valueLabel);
parametersPanel.add(reacParamValue);
if (paramsOnly) {
parametersPanel.add(new JLabel());
parametersPanel.add(sweep);
}
parametersPanel.add(unitsLabel);
parametersPanel.add(reacParamUnits);
parametersPanel.add(onPortLabel);
parametersPanel.add(paramOnPort);
Object[] options = { option, "Cancel" };
int value = JOptionPane.showOptionDialog(Gui.frame, parametersPanel, "Parameter Editor", JOptionPane.YES_NO_OPTION,
JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
boolean error = true;
while (error && value == JOptionPane.YES_OPTION) {
error = SBMLutilities.checkID(bioModel.getSBMLDocument(), reacParamID.getText().trim(), selectedID, true);
if (!error) {
if (thisReactionParams.contains(reacParamID.getText().trim()) && (!reacParamID.getText().trim().equals(selectedID))) {
JOptionPane.showMessageDialog(Gui.frame, "ID is not unique.", "ID Not Unique", JOptionPane.ERROR_MESSAGE);
error = true;
}
}
if (!error) {
double val = 0;
if (reacParamValue.getText().trim().startsWith("(") && reacParamValue.getText().trim().endsWith(")")) {
try {
Double.parseDouble((reacParamValue.getText().trim()).split(",")[0].substring(1).trim());
Double.parseDouble((reacParamValue.getText().trim()).split(",")[1].trim());
Double.parseDouble((reacParamValue.getText().trim()).split(",")[2].trim());
int lev = Integer.parseInt((reacParamValue.getText().trim()).split(",")[3].replace(")", "").trim());
if (lev != 1 && lev != 2) {
error = true;
JOptionPane.showMessageDialog(Gui.frame, "The level can only be 1 or 2.", "Error", JOptionPane.ERROR_MESSAGE);
}
}
catch (Exception e1) {
error = true;
JOptionPane.showMessageDialog(Gui.frame, "Invalid sweeping parameters.", "Error", JOptionPane.ERROR_MESSAGE);
}
}
else {
try {
val = Double.parseDouble(reacParamValue.getText().trim());
}
catch (Exception e1) {
JOptionPane
.showMessageDialog(Gui.frame, "The value must be a real number.", "Enter A Valid Value", JOptionPane.ERROR_MESSAGE);
error = true;
}
}
if (!error) {
String unit = (String) reacParamUnits.getSelectedItem();
String param = "";
if (paramsOnly && !((String) type.getSelectedItem()).equals("Original")) {
int index = reacParameters.getSelectedIndex();
String[] splits = reacParams[index].split(" ");
for (int i = 0; i < splits.length - 2; i++) {
param += splits[i] + " ";
}
if (!splits[splits.length - 2].equals("Modified") && !splits[splits.length - 2].equals("Custom")
&& !splits[splits.length - 2].equals("Sweep")) {
param += splits[splits.length - 2] + " " + splits[splits.length - 1] + " ";
}
if (reacParamValue.getText().trim().startsWith("(") && reacParamValue.getText().trim().endsWith(")")) {
double startVal = Double.parseDouble((reacParamValue.getText().trim()).split(",")[0].substring(1).trim());
double stopVal = Double.parseDouble((reacParamValue.getText().trim()).split(",")[1].trim());
double stepVal = Double.parseDouble((reacParamValue.getText().trim()).split(",")[2].trim());
int lev = Integer.parseInt((reacParamValue.getText().trim()).split(",")[3].replace(")", "").trim());
param += "Sweep (" + startVal + "," + stopVal + "," + stepVal + "," + lev + ")";
}
else {
param += "Modified " + val;
}
}
else {
if (unit.equals("( none )")) {
param = reacParamID.getText().trim() + " " + val;
}
else {
param = reacParamID.getText().trim() + " " + val + " " + unit;
}
}
if (option.equals("OK")) {
int index = reacParameters.getSelectedIndex();
String v = ((String) reacParameters.getSelectedValue()).split(" ")[0];
LocalParameter paramet = null;
for (LocalParameter p : changedParameters) {
if (p.getId().equals(v)) {
paramet = p;
}
}
if (paramet==null) return;
reacParameters.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
reacParams = Utility.getList(reacParams, reacParameters);
reacParameters.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
paramet.setId(reacParamID.getText().trim());
paramet.setName(reacParamName.getText().trim());
SBMLutilities.setMetaId(paramet, reacID.getText()+"___"+reacParamID.getText().trim());
for (int i = 0; i < thisReactionParams.size(); i++) {
if (thisReactionParams.get(i).equals(v)) {
thisReactionParams.set(i, reacParamID.getText().trim());
}
}
paramet.setValue(val);
if (unit.equals("( none )")) {
paramet.unsetUnits();
}
else {
paramet.setUnits(unit);
}
reacParams[index] = param;
Utility.sort(reacParams);
reacParameters.setListData(reacParams);
reacParameters.setSelectedIndex(index);
if (paramsOnly) {
int remove = -1;
for (int i = 0; i < parameterChanges.size(); i++) {
if (parameterChanges.get(i).split(" ")[0].equals(selectedReaction + "/" + reacParamID.getText().trim())) {
remove = i;
}
}
String reacValue = selectedReaction;
int index1 = reactions.getSelectedIndex();
if (remove != -1) {
parameterChanges.remove(remove);
reactions.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
reacts = Utility.getList(reacts, reactions);
reactions.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
reacts[index1] = reacValue.split(" ")[0];
Utility.sort(reacts);
reactions.setListData(reacts);
reactions.setSelectedIndex(index1);
}
if (!((String) type.getSelectedItem()).equals("Original")) {
parameterChanges.add(reacValue + "/" + param);
reactions.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
reacts = Utility.getList(reacts, reactions);
reactions.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
reacts[index1] = reacValue + " Modified";
Utility.sort(reacts);
reactions.setListData(reacts);
reactions.setSelectedIndex(index1);
}
}
else {
kineticLaw.setText(SBMLutilities.updateFormulaVar(kineticLaw.getText().trim(), v, reacParamID.getText().trim()));
}
Port port = gcm.getPortByMetaIdRef(paramet.getMetaId());
if (port!=null) {
if (paramOnPort.isSelected()) {
port.setId(GlobalConstants.LOCALPARAMETER+"__"+paramet.getMetaId());
port.setMetaIdRef(paramet.getMetaId());
} else {
SBMLutilities.removeFromParentAndDelete(port);
}
} else {
if (paramOnPort.isSelected()) {
port = gcm.getSBMLCompModel().createPort();
port.setId(GlobalConstants.LOCALPARAMETER+"__"+paramet.getMetaId());
port.setMetaIdRef(paramet.getMetaId());
}
}
}
else {
int index = reacParameters.getSelectedIndex();
// Parameter paramet = new Parameter(BioSim.SBML_LEVEL,
// BioSim.SBML_VERSION);
LocalParameter paramet = new LocalParameter(bioModel.getSBMLDocument().getLevel(), bioModel.getSBMLDocument().getVersion());
changedParameters.add(paramet);
paramet.setId(reacParamID.getText().trim());
paramet.setName(reacParamName.getText().trim());
SBMLutilities.setMetaId(paramet, reacID.getText()+"___"+reacParamID.getText().trim());
thisReactionParams.add(reacParamID.getText().trim());
paramet.setValue(val);
if (!unit.equals("( none )")) {
paramet.setUnits(unit);
}
if (paramOnPort.isSelected()) {
Port port = gcm.getSBMLCompModel().createPort();
port.setId(GlobalConstants.LOCALPARAMETER+"__"+paramet.getMetaId());
port.setMetaIdRef(paramet.getMetaId());
}
JList add = new JList();
Object[] adding = { param };
add.setListData(adding);
add.setSelectedIndex(0);
reacParameters.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
adding = Utility.add(reacParams, reacParameters, add);
reacParams = new String[adding.length];
for (int i = 0; i < adding.length; i++) {
reacParams[i] = (String) adding[i];
}
Utility.sort(reacParams);
reacParameters.setListData(reacParams);
reacParameters.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
try {
if (bioModel.getSBMLDocument().getModel().getReaction(selectedReaction).getKineticLaw()
.getLocalParameterCount() == 1) {
reacParameters.setSelectedIndex(0);
}
else {
reacParameters.setSelectedIndex(index);
}
}
catch (Exception e2) {
reacParameters.setSelectedIndex(0);
}
}
modelEditor.setDirty(true);
bioModel.makeUndoPoint();
}
}
if (error) {
value = JOptionPane.showOptionDialog(Gui.frame, parametersPanel, "Parameter Editor", JOptionPane.YES_NO_OPTION,
JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
}
}
if (value == JOptionPane.NO_OPTION) {
return;
}
}
private void addLocalParameter(String id,double val) {
LocalParameter paramet = new LocalParameter(bioModel.getSBMLDocument().getLevel(), bioModel.getSBMLDocument().getVersion());
changedParameters.add(paramet);
paramet.setId(id);
paramet.setName(id);
SBMLutilities.setMetaId(paramet, reacID.getText()+"___"+id);
thisReactionParams.add(id);
paramet.setValue(val);
JList add = new JList();
String param = id + " " + val;
Object[] adding = { param };
add.setListData(adding);
add.setSelectedIndex(0);
reacParameters.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
adding = Utility.add(reacParams, reacParameters, add);
reacParams = new String[adding.length];
for (int i = 0; i < adding.length; i++) {
reacParams[i] = (String) adding[i];
}
Utility.sort(reacParams);
reacParameters.setListData(reacParams);
reacParameters.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
reacParameters.setSelectedIndex(0);
modelEditor.setDirty(true);
bioModel.makeUndoPoint();
}
/**
* Creates a frame used to edit products or create new ones.
*/
public void productsEditor(BioModel gcm, String option, String selectedProductId, SpeciesReference product,
boolean inSchematic) {
JPanel productsPanel;
if (gcm.getSBMLDocument().getLevel() < 3) {
productsPanel = new JPanel(new GridLayout(4, 2));
}
else {
productsPanel = new JPanel(new GridLayout(5, 2));
}
JLabel productIdLabel = new JLabel("Id:");
JLabel productNameLabel = new JLabel("Name:");
JLabel speciesLabel = new JLabel("Species:");
Object[] stoiciOptions = { "Stoichiometry", "Stoichiometry Math" };
stoiciLabel = new JComboBox(stoiciOptions);
JLabel stoichiometryLabel = new JLabel("Stoichiometry");
JLabel constantLabel = new JLabel("Constant");
Object[] productConstantOptions = { "true", "false" };
productConstant = new JComboBox(productConstantOptions);
ListOf<Species> listOfSpecies = gcm.getSBMLDocument().getModel().getListOfSpecies();
String[] speciesList = new String[gcm.getSBMLDocument().getModel().getSpeciesCount()];
for (int i = 0; i < gcm.getSBMLDocument().getModel().getSpeciesCount(); i++) {
speciesList[i] = listOfSpecies.get(i).getId();
}
Utility.sort(speciesList);
productSpecies = new JComboBox();
if (inSchematic) {
productSpecies.setEnabled(false);
} else {
productSpecies.setEnabled(true);
}
for (int i = 0; i < speciesList.length; i++) {
Species species = gcm.getSBMLDocument().getModel().getSpecies(speciesList[i]);
if (species.getBoundaryCondition() || (!species.getConstant() && Rules.keepVarRateRule(gcm, "", speciesList[i]))) {
productSpecies.addItem(speciesList[i]);
}
}
productId = new JTextField("");
/*
* int j = 0; while (usedIDs.contains("product"+j)) { j++; }
* productId.setText("product"+j);
*/
productName = new JTextField("");
productStoichiometry = new JTextField("1");
String selectedID = "";
if (option.equals("OK")) {
String v = selectedProductId;
if (product == null || !inSchematic) {
for (SpeciesReference p : changedProducts) {
if (p.getSpecies().equals(v)) {
product = p;
}
}
}
if (product==null) return;
if (product.isSetName()) {
productName.setText(product.getName());
}
productSpecies.setSelectedItem(product.getSpecies());
productStoichiometry.setText("" + product.getStoichiometry());
if (product.isSetId()) {
selectedID = product.getId();
productId.setText(product.getId());
InitialAssignment init = bioModel.getSBMLDocument().getModel().getInitialAssignment(selectedID);
if (init!=null) {
productStoichiometry.setText("" + bioModel.removeBooleans(init.getMath()));
}
}
if (!product.getConstant()) {
productConstant.setSelectedItem("false");
}
}
if (production!=null) {
double np = bioModel.getSBMLDocument().getModel().getParameter(GlobalConstants.STOICHIOMETRY_STRING).getValue();
if (production.getKineticLaw().getLocalParameter(GlobalConstants.STOICHIOMETRY_STRING)!=null) {
np = production.getKineticLaw().getLocalParameter(GlobalConstants.STOICHIOMETRY_STRING).getValue();
}
productStoichiometry.setText(""+np);
productStoichiometry.setEnabled(false);
}
productsPanel.add(productIdLabel);
productsPanel.add(productId);
productsPanel.add(productNameLabel);
productsPanel.add(productName);
productsPanel.add(speciesLabel);
productsPanel.add(productSpecies);
if (gcm.getSBMLDocument().getLevel() < 3) {
productsPanel.add(stoiciLabel);
}
else {
productsPanel.add(stoichiometryLabel);
}
productsPanel.add(productStoichiometry);
if (gcm.getSBMLDocument().getLevel() > 2) {
productsPanel.add(constantLabel);
productsPanel.add(productConstant);
}
if (speciesList.length == 0) {
JOptionPane.showMessageDialog(Gui.frame, "There are no species availiable to be products." + "\nAdd species to this sbml file first.",
"No Species", JOptionPane.ERROR_MESSAGE);
return;
}
Object[] options = { option, "Cancel" };
int value = JOptionPane.showOptionDialog(Gui.frame, productsPanel, "Products Editor", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE,
null, options, options[0]);
boolean error = true;
while (error && value == JOptionPane.YES_OPTION) {
error = false;
String prod = "";
double val = 1.0;
if (productId.getText().trim().equals("")) {
error = SBMLutilities.variableInUse(gcm.getSBMLDocument(), selectedID, false, true, true);
}
else {
error = SBMLutilities.checkID(gcm.getSBMLDocument(), productId.getText().trim(), selectedID, false);
}
if (!error) {
if (stoiciLabel.getSelectedItem().equals("Stoichiometry")) {
InitialAssignments.removeInitialAssignment(bioModel, selectedID);
try {
val = Double.parseDouble(productStoichiometry.getText().trim());
}
catch (Exception e1) {
if (productId.getText().equals("")) {
JOptionPane.showMessageDialog(Gui.frame, "The stoichiometry must be a real number if no id is provided.", "Enter A Valid Value",
JOptionPane.ERROR_MESSAGE);
error = true;
} else {
error = InitialAssignments.addInitialAssignment(bioModel, productId.getText().trim(), productStoichiometry.getText().trim());
val = 1.0;
}
}
if (val <= 0) {
JOptionPane.showMessageDialog(Gui.frame, "The stoichiometry value must be greater than 0.", "Enter A Valid Value",
JOptionPane.ERROR_MESSAGE);
error = true;
}
prod = productSpecies.getSelectedItem() + " " + val;
}
else {
prod = productSpecies.getSelectedItem() + " " + productStoichiometry.getText().trim();
}
}
int index = -1;
if (!error) {
if (product == null || !inSchematic) {
if (option.equals("OK")) {
index = products.getSelectedIndex();
}
products.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
proda = Utility.getList(proda, products);
products.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
if (index >= 0) {
products.setSelectedIndex(index);
}
for (int i = 0; i < proda.length; i++) {
if (i != index) {
if (proda[i].split(" ")[0].equals(productSpecies.getSelectedItem())) {
error = true;
JOptionPane.showMessageDialog(Gui.frame, "Unable to add species as a product.\n"
+ "Each species can only be used as a product once.", "Species Can Only Be Used Once",
JOptionPane.ERROR_MESSAGE);
}
}
}
}
}
if (!error) {
if (stoiciLabel.getSelectedItem().equals("Stoichiometry Math")) {
if (productStoichiometry.getText().trim().equals("")) {
JOptionPane.showMessageDialog(Gui.frame, "Stoichiometry math must have formula.", "Enter Stoichiometry Formula",
JOptionPane.ERROR_MESSAGE);
error = true;
}
else if (SBMLutilities.myParseFormula(productStoichiometry.getText().trim()) == null) {
JOptionPane.showMessageDialog(Gui.frame, "Stoichiometry formula is not valid.", "Enter Valid Formula",
JOptionPane.ERROR_MESSAGE);
error = true;
}
else {
ArrayList<String> invalidVars = getInvalidVariablesInReaction(productStoichiometry.getText().trim(), true, "", false);
if (invalidVars.size() > 0) {
String invalid = "";
for (int i = 0; i < invalidVars.size(); i++) {
if (i == invalidVars.size() - 1) {
invalid += invalidVars.get(i);
}
else {
invalid += invalidVars.get(i) + "\n";
}
}
String message;
message = "Stoiciometry math contains unknown variables.\n\n" + "Unknown variables:\n" + invalid;
JTextArea messageArea = new JTextArea(message);
messageArea.setLineWrap(true);
messageArea.setWrapStyleWord(true);
messageArea.setEditable(false);
JScrollPane scrolls = new JScrollPane();
scrolls.setMinimumSize(new Dimension(300, 300));
scrolls.setPreferredSize(new Dimension(300, 300));
scrolls.setViewportView(messageArea);
JOptionPane.showMessageDialog(Gui.frame, scrolls, "Stoiciometry Math Error", JOptionPane.ERROR_MESSAGE);
error = true;
}
if (!error) {
error = SBMLutilities.checkNumFunctionArguments(gcm.getSBMLDocument(),
SBMLutilities.myParseFormula(productStoichiometry.getText().trim()));
}
if (!error) {
if (SBMLutilities.returnsBoolean(SBMLutilities.myParseFormula(productStoichiometry.getText().trim()), bioModel.getSBMLDocument().getModel())) {
JOptionPane.showMessageDialog(Gui.frame, "Stoichiometry math must evaluate to a number.", "Number Expected",
JOptionPane.ERROR_MESSAGE);
error = true;
}
}
}
}
}
if (!error && option.equals("OK") && productConstant.getSelectedItem().equals("true")) {
String id = selectedID;
error = SBMLutilities.checkConstant(gcm.getSBMLDocument(), "Product stoiciometry", id);
}
if (!error) {
if (option.equals("OK")) {
String v = selectedProductId;
SpeciesReference produ = product;
if (product == null || !inSchematic) {
for (SpeciesReference p : changedProducts) {
if (p.getSpecies().equals(v)) {
produ = p;
}
}
products.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
proda = Utility.getList(proda, products);
products.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
}
if (produ==null) return;
produ.setId(productId.getText().trim());
produ.setName(productName.getText().trim());
produ.setSpecies((String) productSpecies.getSelectedItem());
produ.setStoichiometry(val);
if (productConstant.getSelectedItem().equals("true")) {
produ.setConstant(true);
}
else {
produ.setConstant(false);
}
if (product == null || !inSchematic) {
proda[index] = prod;
Utility.sort(proda);
products.setListData(proda);
products.setSelectedIndex(index);
}
SBMLutilities.updateVarId(gcm.getSBMLDocument(), false, selectedID, productId.getText().trim());
if (product == null || !inSchematic) {
kineticLaw.setText(SBMLutilities.updateFormulaVar(kineticLaw.getText().trim(), selectedID, productId.getText().trim()));
}
}
else {
// SpeciesReference produ = new
// SpeciesReference(BioSim.SBML_LEVEL, BioSim.SBML_VERSION);
SpeciesReference produ = new SpeciesReference(gcm.getSBMLDocument().getLevel(), gcm.getSBMLDocument().getVersion());
produ.setId(productId.getText().trim());
produ.setName(productName.getText().trim());
changedProducts.add(produ);
produ.setSpecies((String) productSpecies.getSelectedItem());
produ.setStoichiometry(val);
if (productConstant.getSelectedItem().equals("true")) {
produ.setConstant(true);
}
else {
produ.setConstant(false);
}
JList add = new JList();
Object[] adding = { prod };
add.setListData(adding);
add.setSelectedIndex(0);
products.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
adding = Utility.add(proda, products, add);
proda = new String[adding.length];
for (int i = 0; i < adding.length; i++) {
proda[i] = (String) adding[i];
}
Utility.sort(proda);
products.setListData(proda);
products.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
products.setSelectedIndex(0);
}
modelEditor.setDirty(true);
gcm.makeUndoPoint();
}
if (error) {
value = JOptionPane.showOptionDialog(Gui.frame, productsPanel, "Products Editor", JOptionPane.YES_NO_OPTION,
JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
}
}
if (value == JOptionPane.NO_OPTION) {
return;
}
}
private LocalParameter getChangedParameter(String paramStr) {
for (LocalParameter r : changedParameters) {
if (r.getId().equals(paramStr)) {
return r;
}
}
return null;
}
/**
* Creates a frame used to edit modifiers or create new ones.
*/
public void modifiersEditor(String option,boolean inSchematic) {
if (option.equals("OK") && modifiers.getSelectedIndex() == -1) {
JOptionPane.showMessageDialog(Gui.frame, "No modifier selected.", "Must Select A Modifier", JOptionPane.ERROR_MESSAGE);
return;
}
JPanel modifiersPanel;
JLabel speciesLabel = new JLabel("Species:");
ListOf<Species> listOfSpecies = bioModel.getSBMLDocument().getModel().getListOfSpecies();
String[] speciesList = new String[bioModel.getSBMLDocument().getModel().getSpeciesCount()];
for (int i = 0; i < bioModel.getSBMLDocument().getModel().getSpeciesCount(); i++) {
speciesList[i] = listOfSpecies.get(i).getId();
}
Utility.sort(speciesList);
Object[] choices = speciesList;
modifierSpecies = new JComboBox(choices);
if (inSchematic) {
modifierSpecies.setEnabled(false);
} else {
modifierSpecies.setEnabled(true);
}
JLabel SBOTermsLabel = new JLabel("Type");
JLabel RepStoichiometryLabel = new JLabel("Stoichiometry of repression (nc)");
JLabel RepBindingLabel = new JLabel("Repression binding equilibrium (Kr)");
JLabel ActStoichiometryLabel = new JLabel("Stoichiometry of activation (nc)");
JLabel ActBindingLabel = new JLabel("Activation binding equilibrium (Ka)");
if (option.equals("OK")) {
String v = ((String) modifiers.getSelectedValue()).split(" ")[0];
ModifierSpeciesReference modifier = null;
for (ModifierSpeciesReference p : changedModifiers) {
if (p.getSpecies().equals(v)) {
modifier = p;
}
}
if (modifier==null) return;
modifierSpecies.setSelectedItem(modifier.getSpecies());
if (production!=null) {
if (BioModel.isPromoter(modifier)) {
String [] sboTerms = new String[1];
sboTerms[0] = "Promoter";
SBOTerms = new JComboBox(sboTerms);
SBOTerms.setSelectedItem("Promoter");
} else {
String [] sboTerms = new String[4];
sboTerms[0] = "Repression";
sboTerms[1] = "Activation";
sboTerms[2] = "Dual activity";
sboTerms[3] = "No influence";
SBOTerms = new JComboBox(sboTerms);
if (BioModel.isRepressor(modifier)) {
SBOTerms.setSelectedItem("Repression");
} else if (BioModel.isActivator(modifier)) {
SBOTerms.setSelectedItem("Activation");
} else if (BioModel.isRegulator(modifier)) {
SBOTerms.setSelectedItem("Dual activity");
} else if (BioModel.isNeutral(modifier)) {
SBOTerms.setSelectedItem("No influence");
}
}
}
} else {
String [] sboTerms = new String[4];
sboTerms[0] = "Repression";
sboTerms[1] = "Activation";
sboTerms[2] = "Dual activity";
sboTerms[3] = "No influence";
SBOTerms = new JComboBox(sboTerms);
}
if (production==null) {
modifiersPanel = new JPanel(new GridLayout(1, 2));
} else {
if (SBOTerms.getSelectedItem().equals("Promoter")) {
modifiersPanel = new JPanel(new GridLayout(2, 2));
} else {
modifiersPanel = new JPanel(new GridLayout(6, 2));
}
}
modifiersPanel.add(speciesLabel);
modifiersPanel.add(modifierSpecies);
if (production!=null) {
modifiersPanel.add(SBOTermsLabel);
modifiersPanel.add(SBOTerms);
if (SBOTerms.getSelectedItem().equals("Promoter")) {
modifierSpecies.setEnabled(false);
SBOTerms.setEnabled(false);
} else {
String selectedID = (String)modifierSpecies.getSelectedItem();
modifiersPanel.add(RepStoichiometryLabel);
repCooperativity = new JTextField();
double nc = bioModel.getSBMLDocument().getModel().getParameter(GlobalConstants.COOPERATIVITY_STRING).getValue();
repCooperativity.setText(""+nc);
LocalParameter p = getChangedParameter(GlobalConstants.COOPERATIVITY_STRING+"_"+selectedID+"_r");
if (p!=null) {
repCooperativity.setText(""+p.getValue());
}
modifiersPanel.add(repCooperativity);
modifiersPanel.add(RepBindingLabel);
repBinding = new JTextField(bioModel.getParameter(GlobalConstants.FORWARD_KREP_STRING) + "/" +
bioModel.getParameter(GlobalConstants.REVERSE_KREP_STRING));
LocalParameter kr_f = getChangedParameter(GlobalConstants.FORWARD_KREP_STRING.replace("_","_" + selectedID + "_"));
LocalParameter kr_r = getChangedParameter(GlobalConstants.REVERSE_KREP_STRING.replace("_","_" + selectedID + "_"));
if (kr_f!=null && kr_r!=null) {
repBinding.setText(""+kr_f.getValue()+"/"+kr_r.getValue());
}
modifiersPanel.add(repBinding);
modifiersPanel.add(ActStoichiometryLabel);
actCooperativity = new JTextField();
nc = bioModel.getSBMLDocument().getModel().getParameter(GlobalConstants.COOPERATIVITY_STRING).getValue();
actCooperativity.setText(""+nc);
p = getChangedParameter(GlobalConstants.COOPERATIVITY_STRING+"_"+selectedID+"_a");
if (p!=null) {
actCooperativity.setText(""+p.getValue());
}
modifiersPanel.add(actCooperativity);
modifiersPanel.add(ActBindingLabel);
actBinding = new JTextField(bioModel.getParameter(GlobalConstants.FORWARD_KACT_STRING) + "/" +
bioModel.getParameter(GlobalConstants.REVERSE_KACT_STRING));
LocalParameter ka_f = getChangedParameter(GlobalConstants.FORWARD_KACT_STRING.replace("_","_" + selectedID + "_"));
LocalParameter ka_r = getChangedParameter(GlobalConstants.REVERSE_KACT_STRING.replace("_","_" + selectedID + "_"));
if (ka_f!=null && ka_r!=null) {
actBinding.setText(""+ka_f.getValue()+"/"+ka_r.getValue());
}
modifiersPanel.add(actBinding);
}
}
if (choices.length == 0) {
JOptionPane.showMessageDialog(Gui.frame, "There are no species availiable to be modifiers." + "\nAdd species to this sbml file first.",
"No Species", JOptionPane.ERROR_MESSAGE);
return;
}
Object[] options = { option, "Cancel" };
int value = JOptionPane.showOptionDialog(Gui.frame, modifiersPanel, "Modifiers Editor", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE,
null, options, options[0]);
boolean error = true;
while (error && value == JOptionPane.YES_OPTION) {
error = false;
int index = modifiers.getSelectedIndex();
String mod = (String) modifierSpecies.getSelectedItem();
for (int i = 0; i < modifier.length; i++) {
if (i != index) {
if (modifier[i].equals(modifierSpecies.getSelectedItem())) {
error = true;
JOptionPane
.showMessageDialog(Gui.frame, "Unable to add species as a modifier.\n"
+ "Each species can only be used as a modifier once.", "Species Can Only Be Used Once",
JOptionPane.ERROR_MESSAGE);
}
}
}
double repCoop = 0.0;
double actCoop = 0.0;
double repBindf = 0.0;
double repBindr = 1.0;
double actBindf = 0.0;
double actBindr = 1.0;
if (production!=null) {
try {
repCoop = Double.parseDouble(repCooperativity.getText().trim());
}
catch (Exception e1) {
JOptionPane.showMessageDialog(Gui.frame, "The repression cooperativity must be a real number.", "Enter A Valid Value",
JOptionPane.ERROR_MESSAGE);
error = true;
}
try {
repBindf = Double.parseDouble(repBinding.getText().trim().split("/")[0]);
repBindr = Double.parseDouble(repBinding.getText().trim().split("/")[1]);
}
catch (Exception e1) {
JOptionPane.showMessageDialog(Gui.frame, "The repression binding must be a forward rate / reverse rate.", "Enter A Valid Value",
JOptionPane.ERROR_MESSAGE);
error = true;
}
try {
actCoop = Double.parseDouble(actCooperativity.getText().trim());
}
catch (Exception e1) {
JOptionPane.showMessageDialog(Gui.frame, "The activation cooperativity must be a real number.", "Enter A Valid Value",
JOptionPane.ERROR_MESSAGE);
error = true;
}
try {
actBindf = Double.parseDouble(actBinding.getText().trim().split("/")[0]);
actBindr = Double.parseDouble(actBinding.getText().trim().split("/")[1]);
}
catch (Exception e1) {
JOptionPane.showMessageDialog(Gui.frame, "The activation binding must be a forward rate / reverse rate.", "Enter A Valid Value",
JOptionPane.ERROR_MESSAGE);
error = true;
}
}
if (!error) {
if (option.equals("OK")) {
modifiers.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
modifier = Utility.getList(modifier, modifiers);
modifiers.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
modifiers.setSelectedIndex(index);
ModifierSpeciesReference modi = null;
for (ModifierSpeciesReference p : changedModifiers) {
if (p.getSpecies().equals(mod)) {
modi = p;
}
}
if (modi==null) return;
modifiers.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
modifier = Utility.getList(modifier, modifiers);
modifiers.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
modi.setSpecies((String) modifierSpecies.getSelectedItem());
if (production!=null) {
if (SBOTerms.getSelectedItem().equals("Repression")) {
modi.setSBOTerm(GlobalConstants.SBO_REPRESSION);
} else if (SBOTerms.getSelectedItem().equals("Activation")) {
modi.setSBOTerm(GlobalConstants.SBO_ACTIVATION);
} else if (SBOTerms.getSelectedItem().equals("Dual activity")) {
modi.setSBOTerm(GlobalConstants.SBO_DUAL_ACTIVITY);
} else if (SBOTerms.getSelectedItem().equals("No influence")) {
modi.setSBOTerm(GlobalConstants.SBO_NEUTRAL);
} else if (SBOTerms.getSelectedItem().equals("Promoter")) {
modi.setSBOTerm(GlobalConstants.SBO_PROMOTER_MODIFIER);
}
}
if (production!=null) {
double nc = bioModel.getSBMLDocument().getModel().getParameter(GlobalConstants.COOPERATIVITY_STRING).getValue();
String ncStr = GlobalConstants.COOPERATIVITY_STRING+"_"+mod+"_r";
LocalParameter paramet = getChangedParameter(ncStr);
if (paramet != null) {
removeLocalParameter(ncStr);
}
if (nc!=repCoop) {
addLocalParameter(ncStr,repCoop);
}
ncStr = GlobalConstants.COOPERATIVITY_STRING+"_"+mod+"_a";
paramet = getChangedParameter(ncStr);
if (paramet != null) {
removeLocalParameter(ncStr);
}
if (nc!=actCoop) {
addLocalParameter(ncStr,actCoop);
}
double bindf = bioModel.getSBMLDocument().getModel().getParameter(GlobalConstants.FORWARD_KREP_STRING).getValue();
double bindr = bioModel.getSBMLDocument().getModel().getParameter(GlobalConstants.REVERSE_KREP_STRING).getValue();
LocalParameter kr_f = getChangedParameter(GlobalConstants.FORWARD_KREP_STRING.replace("_","_" + mod + "_"));
LocalParameter kr_r = getChangedParameter(GlobalConstants.REVERSE_KREP_STRING.replace("_","_" + mod + "_"));
if (kr_f != null) {
removeLocalParameter(GlobalConstants.FORWARD_KREP_STRING.replace("_","_" + mod + "_"));
}
if (kr_r != null) {
removeLocalParameter(GlobalConstants.REVERSE_KREP_STRING.replace("_","_" + mod + "_"));
}
if (repBindf!=bindf || repBindr!=bindr) {
addLocalParameter(GlobalConstants.FORWARD_KREP_STRING.replace("_","_" + mod + "_"),repBindf);
addLocalParameter(GlobalConstants.REVERSE_KREP_STRING.replace("_","_" + mod + "_"),repBindr);
}
bindf = bioModel.getSBMLDocument().getModel().getParameter(GlobalConstants.FORWARD_KACT_STRING).getValue();
bindr = bioModel.getSBMLDocument().getModel().getParameter(GlobalConstants.REVERSE_KACT_STRING).getValue();
LocalParameter ka_f = getChangedParameter(GlobalConstants.FORWARD_KACT_STRING.replace("_","_" + mod + "_"));
LocalParameter ka_r = getChangedParameter(GlobalConstants.REVERSE_KACT_STRING.replace("_","_" + mod + "_"));
if (ka_f != null) {
removeLocalParameter(GlobalConstants.FORWARD_KACT_STRING.replace("_","_" + mod + "_"));
}
if (ka_r != null) {
removeLocalParameter(GlobalConstants.REVERSE_KACT_STRING.replace("_","_" + mod + "_"));
}
if (actBindf!=bindf || actBindr!=bindr) {
addLocalParameter(GlobalConstants.FORWARD_KACT_STRING.replace("_","_" + mod + "_"),actBindf);
addLocalParameter(GlobalConstants.REVERSE_KACT_STRING.replace("_","_" + mod + "_"),actBindr);
}
}
modifier[index] = mod;
Utility.sort(modifier);
modifiers.setListData(modifier);
modifiers.setSelectedIndex(index);
}
else {
modifiers.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
modifier = Utility.getList(modifier, modifiers);
modifiers.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
modifiers.setSelectedIndex(index);
ModifierSpeciesReference modi = new ModifierSpeciesReference(bioModel.getSBMLDocument().getLevel(), bioModel.getSBMLDocument().getVersion());
changedModifiers.add(modi);
modi.setSpecies(mod);
if (production!=null) {
if (SBOTerms.getSelectedItem().equals("Repression")) {
modi.setSBOTerm(GlobalConstants.SBO_REPRESSION);
} else if (SBOTerms.getSelectedItem().equals("Activation")) {
modi.setSBOTerm(GlobalConstants.SBO_ACTIVATION);
} else if (SBOTerms.getSelectedItem().equals("Dual activity")) {
modi.setSBOTerm(GlobalConstants.SBO_DUAL_ACTIVITY);
} else if (SBOTerms.getSelectedItem().equals("No influence")) {
modi.setSBOTerm(GlobalConstants.SBO_NEUTRAL);
} else if (SBOTerms.getSelectedItem().equals("Promoter")) {
modi.setSBOTerm(GlobalConstants.SBO_PROMOTER_MODIFIER);
}
}
if (production!=null) {
double nc = bioModel.getSBMLDocument().getModel().getParameter(GlobalConstants.COOPERATIVITY_STRING).getValue();
String ncStr = GlobalConstants.COOPERATIVITY_STRING+"_"+mod+"_r";
LocalParameter paramet = getChangedParameter(ncStr);
if (paramet != null) {
removeLocalParameter(ncStr);
}
if (nc!=repCoop) {
addLocalParameter(ncStr,repCoop);
}
ncStr = GlobalConstants.COOPERATIVITY_STRING+"_"+mod+"_a";
paramet = getChangedParameter(ncStr);
if (paramet != null) {
removeLocalParameter(ncStr);
}
if (nc!=actCoop) {
addLocalParameter(ncStr,actCoop);
}
double bindf = bioModel.getSBMLDocument().getModel().getParameter(GlobalConstants.FORWARD_KREP_STRING).getValue();
double bindr = bioModel.getSBMLDocument().getModel().getParameter(GlobalConstants.REVERSE_KREP_STRING).getValue();
LocalParameter kr_f = getChangedParameter(GlobalConstants.FORWARD_KREP_STRING.replace("_","_" + mod + "_"));
LocalParameter kr_r = getChangedParameter(GlobalConstants.REVERSE_KREP_STRING.replace("_","_" + mod + "_"));
if (kr_f != null) {
removeLocalParameter(GlobalConstants.FORWARD_KREP_STRING.replace("_","_" + mod + "_"));
}
if (kr_r != null) {
removeLocalParameter(GlobalConstants.REVERSE_KREP_STRING.replace("_","_" + mod + "_"));
}
if (repBindf!=bindf || repBindr!=bindr) {
addLocalParameter(GlobalConstants.FORWARD_KREP_STRING.replace("_","_" + mod + "_"),repBindf);
addLocalParameter(GlobalConstants.REVERSE_KREP_STRING.replace("_","_" + mod + "_"),repBindr);
}
bindf = bioModel.getSBMLDocument().getModel().getParameter(GlobalConstants.FORWARD_KACT_STRING).getValue();
bindr = bioModel.getSBMLDocument().getModel().getParameter(GlobalConstants.REVERSE_KACT_STRING).getValue();
LocalParameter ka_f = getChangedParameter(GlobalConstants.FORWARD_KACT_STRING.replace("_","_" + mod + "_"));
LocalParameter ka_r = getChangedParameter(GlobalConstants.REVERSE_KACT_STRING.replace("_","_" + mod + "_"));
if (ka_f != null) {
removeLocalParameter(GlobalConstants.FORWARD_KACT_STRING.replace("_","_" + mod + "_"));
}
if (ka_r != null) {
removeLocalParameter(GlobalConstants.REVERSE_KACT_STRING.replace("_","_" + mod + "_"));
}
if (actBindf!=bindf || actBindr!=bindr) {
addLocalParameter(GlobalConstants.FORWARD_KACT_STRING.replace("_","_" + mod + "_"),actBindf);
addLocalParameter(GlobalConstants.REVERSE_KACT_STRING.replace("_","_" + mod + "_"),actBindr);
}
}
JList add = new JList();
Object[] adding = { mod };
add.setListData(adding);
add.setSelectedIndex(0);
modifiers.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
adding = Utility.add(modifier, modifiers, add);
modifier = new String[adding.length];
for (int i = 0; i < adding.length; i++) {
modifier[i] = (String) adding[i];
}
Utility.sort(modifier);
modifiers.setListData(modifier);
modifiers.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
try {
if (bioModel.getSBMLDocument().getModel().getReaction(selectedReaction).getModifierCount() == 1) {
modifiers.setSelectedIndex(0);
}
else {
modifiers.setSelectedIndex(index);
}
}
catch (Exception e2) {
modifiers.setSelectedIndex(0);
}
}
}
modelEditor.setDirty(true);
bioModel.makeUndoPoint();
if (error) {
value = JOptionPane.showOptionDialog(Gui.frame, modifiersPanel, "Modifiers Editor", JOptionPane.YES_NO_OPTION,
JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
}
}
if (value == JOptionPane.NO_OPTION) {
return;
}
}
/**
* Creates a frame used to edit reactants or create new ones.
*/
public void reactantsEditor(BioModel gcm, String option, String selectedReactantId, SpeciesReference reactant,
boolean inSchematic) {
JPanel reactantsPanel;
if (gcm.getSBMLDocument().getLevel() < 3) {
reactantsPanel = new JPanel(new GridLayout(4, 2));
}
else {
reactantsPanel = new JPanel(new GridLayout(5, 2));
}
JLabel reactantIdLabel = new JLabel("Id:");
JLabel reactantNameLabel = new JLabel("Name:");
JLabel speciesLabel = new JLabel("Species:");
Object[] stoiciOptions = { "Stoichiometry", "Stoichiometry Math" };
stoiciLabel = new JComboBox(stoiciOptions);
JLabel stoichiometryLabel = new JLabel("Stoichiometry");
JLabel constantLabel = new JLabel("Constant");
Object[] reactantConstantOptions = { "true", "false" };
reactantConstant = new JComboBox(reactantConstantOptions);
ListOf<Species> listOfSpecies = gcm.getSBMLDocument().getModel().getListOfSpecies();
String[] speciesList = new String[gcm.getSBMLDocument().getModel().getSpeciesCount()];
for (int i = 0; i < gcm.getSBMLDocument().getModel().getSpeciesCount(); i++) {
speciesList[i] = listOfSpecies.get(i).getId();
}
Utility.sort(speciesList);
reactantSpecies = new JComboBox();
if (inSchematic) {
reactantSpecies.setEnabled(false);
} else {
reactantSpecies.setEnabled(true);
}
for (int i = 0; i < speciesList.length; i++) {
Species species = gcm.getSBMLDocument().getModel().getSpecies(speciesList[i]);
if (species.getBoundaryCondition() || (!species.getConstant() && Rules.keepVarRateRule(gcm, "", speciesList[i]))) {
reactantSpecies.addItem(speciesList[i]);
}
}
reactantId = new JTextField("");
reactantName = new JTextField("");
reactantStoichiometry = new JTextField("1");
String selectedID = "";
if (complex!=null) {
double nc = bioModel.getSBMLDocument().getModel().getParameter(GlobalConstants.COOPERATIVITY_STRING).getValue();
reactantStoichiometry.setText(""+nc);
}
if (option.equals("OK")) {
String v = selectedReactantId;
if (reactant == null) {
for (SpeciesReference r : changedReactants) {
if (r.getSpecies().equals(v)) {
reactant = r;
}
}
}
reactantSpecies.setSelectedItem(reactant.getSpecies());
if (reactant.isSetName()) {
reactantName.setText(reactant.getName());
}
reactantStoichiometry.setText("" + reactant.getStoichiometry());
if (reactant.isSetId()) {
selectedID = reactant.getId();
reactantId.setText(reactant.getId());
InitialAssignment init = bioModel.getSBMLDocument().getModel().getInitialAssignment(selectedID);
if (init!=null) {
reactantStoichiometry.setText("" + bioModel.removeBooleans(init.getMath()));
}
}
if (!reactant.getConstant()) {
reactantConstant.setSelectedItem("false");
}
if (complex!=null) {
if (complex.getKineticLaw().getLocalParameter(GlobalConstants.COOPERATIVITY_STRING+"_"+selectedID)!=null) {
double nc = complex.getKineticLaw().getLocalParameter(GlobalConstants.COOPERATIVITY_STRING+"_"+selectedID).getValue();
reactantStoichiometry.setText(""+nc);
}
}
}
reactantsPanel.add(reactantIdLabel);
reactantsPanel.add(reactantId);
reactantsPanel.add(reactantNameLabel);
reactantsPanel.add(reactantName);
reactantsPanel.add(speciesLabel);
reactantsPanel.add(reactantSpecies);
if (gcm.getSBMLDocument().getLevel() < 3) {
reactantsPanel.add(stoiciLabel);
}
else {
reactantsPanel.add(stoichiometryLabel);
}
reactantsPanel.add(reactantStoichiometry);
if (gcm.getSBMLDocument().getLevel() > 2) {
reactantsPanel.add(constantLabel);
reactantsPanel.add(reactantConstant);
}
if (speciesList.length == 0) {
JOptionPane.showMessageDialog(Gui.frame, "There are no species availiable to be reactants." + "\nAdd species to this sbml file first.",
"No Species", JOptionPane.ERROR_MESSAGE);
return;
}
Object[] options = { option, "Cancel" };
int value = JOptionPane.showOptionDialog(Gui.frame, reactantsPanel, "Reactants Editor", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE,
null, options, options[0]);
boolean error = true;
while (error && value == JOptionPane.YES_OPTION) {
error = false;
String react = "";
double val = 1.0;
if (reactantId.getText().trim().equals("")) {
error = SBMLutilities.variableInUse(gcm.getSBMLDocument(), selectedID, false, true, true);
}
else {
error = SBMLutilities.checkID(gcm.getSBMLDocument(), reactantId.getText().trim(), selectedID, false);
}
if (!error) {
if (stoiciLabel.getSelectedItem().equals("Stoichiometry")) {
InitialAssignments.removeInitialAssignment(bioModel, selectedID);
try {
val = Double.parseDouble(reactantStoichiometry.getText().trim());
}
catch (Exception e1) {
if (reactantId.getText().equals("")) {
JOptionPane.showMessageDialog(Gui.frame, "The stoichiometry must be a real number if no id is provided.", "Enter A Valid Value",
JOptionPane.ERROR_MESSAGE);
error = true;
} else {
error = InitialAssignments.addInitialAssignment(bioModel, reactantId.getText().trim(), reactantStoichiometry.getText().trim());
val = 1.0;
}
}
if (val <= 0) {
JOptionPane.showMessageDialog(Gui.frame, "The stoichiometry value must be greater than 0.", "Enter A Valid Value",
JOptionPane.ERROR_MESSAGE);
error = true;
}
react = reactantSpecies.getSelectedItem() + " " + val;
}
else {
react = reactantSpecies.getSelectedItem() + " " + reactantStoichiometry.getText().trim();
}
}
int index = -1;
if (!error) {
if (reactant == null || !inSchematic) {
if (option.equals("OK")) {
index = reactants.getSelectedIndex();
}
reactants.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
reacta = Utility.getList(reacta, reactants);
reactants.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
if (index >= 0) {
reactants.setSelectedIndex(index);
}
for (int i = 0; i < reacta.length; i++) {
if (i != index) {
if (reacta[i].split(" ")[0].equals(reactantSpecies.getSelectedItem())) {
error = true;
JOptionPane.showMessageDialog(Gui.frame, "Unable to add species as a reactant.\n"
+ "Each species can only be used as a reactant once.", "Species Can Only Be Used Once",
JOptionPane.ERROR_MESSAGE);
}
}
}
}
}
if (!error) {
if (stoiciLabel.getSelectedItem().equals("Stoichiometry Math")) {
if (reactantStoichiometry.getText().trim().equals("")) {
JOptionPane.showMessageDialog(Gui.frame, "Stoichiometry math must have formula.", "Enter Stoichiometry Formula",
JOptionPane.ERROR_MESSAGE);
error = true;
}
else if (SBMLutilities.myParseFormula(reactantStoichiometry.getText().trim()) == null) {
JOptionPane.showMessageDialog(Gui.frame, "Stoichiometry formula is not valid.", "Enter Valid Formula",
JOptionPane.ERROR_MESSAGE);
error = true;
}
else {
ArrayList<String> invalidVars = getInvalidVariablesInReaction(reactantStoichiometry.getText().trim(), true, "", false);
if (invalidVars.size() > 0) {
String invalid = "";
for (int i = 0; i < invalidVars.size(); i++) {
if (i == invalidVars.size() - 1) {
invalid += invalidVars.get(i);
}
else {
invalid += invalidVars.get(i) + "\n";
}
}
String message;
message = "Stoiciometry math contains unknown variables.\n\n" + "Unknown variables:\n" + invalid;
JTextArea messageArea = new JTextArea(message);
messageArea.setLineWrap(true);
messageArea.setWrapStyleWord(true);
messageArea.setEditable(false);
JScrollPane scrolls = new JScrollPane();
scrolls.setMinimumSize(new Dimension(300, 300));
scrolls.setPreferredSize(new Dimension(300, 300));
scrolls.setViewportView(messageArea);
JOptionPane.showMessageDialog(Gui.frame, scrolls, "Stoiciometry Math Error", JOptionPane.ERROR_MESSAGE);
error = true;
}
if (!error) {
error = SBMLutilities.checkNumFunctionArguments(gcm.getSBMLDocument(),
SBMLutilities.myParseFormula(reactantStoichiometry.getText().trim()));
}
if (!error) {
if (SBMLutilities.returnsBoolean(SBMLutilities.myParseFormula(reactantStoichiometry.getText().trim()), bioModel.getSBMLDocument().getModel())) {
JOptionPane.showMessageDialog(Gui.frame, "Stoichiometry math must evaluate to a number.", "Number Expected",
JOptionPane.ERROR_MESSAGE);
error = true;
}
}
}
}
}
if (!error && option.equals("OK") && reactantConstant.getSelectedItem().equals("true")) {
String id = selectedID;
error = SBMLutilities.checkConstant(gcm.getSBMLDocument(), "Reactant stoiciometry", id);
}
if (!error) {
if (option.equals("OK")) {
String v = selectedReactantId;
SpeciesReference reactan = reactant;
if (reactant == null || !inSchematic) {
for (SpeciesReference r : changedReactants) {
if (r.getSpecies().equals(v)) {
reactan = r;
}
}
reactants.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
reacta = Utility.getList(reacta, reactants);
reactants.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
}
if (reactan==null) return;
reactan.setId(reactantId.getText().trim());
reactan.setName(reactantName.getText().trim());
reactan.setSpecies((String) reactantSpecies.getSelectedItem());
reactan.setStoichiometry(val);
if (complex!=null) {
double nc = bioModel.getSBMLDocument().getModel().getParameter(GlobalConstants.COOPERATIVITY_STRING).getValue();
String ncStr = GlobalConstants.COOPERATIVITY_STRING+"_"+reactan.getSpecies();
LocalParameter paramet = null;
for (LocalParameter p : changedParameters) {
if (p.getId().equals(ncStr)) {
paramet = p;
}
}
if (nc==val) {
if (paramet != null) {
removeLocalParameter(ncStr);
}
} else {
if (paramet != null) {
removeLocalParameter(ncStr);
addLocalParameter(GlobalConstants.COOPERATIVITY_STRING+"_"+reactan.getSpecies(),val);
} else {
addLocalParameter(GlobalConstants.COOPERATIVITY_STRING+"_"+reactan.getSpecies(),val);
}
}
}
if (reactantConstant.getSelectedItem().equals("true")) {
reactan.setConstant(true);
}
else {
reactan.setConstant(false);
}
if (reactant == null || !inSchematic) {
reacta[index] = react;
Utility.sort(reacta);
reactants.setListData(reacta);
reactants.setSelectedIndex(index);
}
SBMLutilities.updateVarId(gcm.getSBMLDocument(), false, selectedID, reactantId.getText().trim());
if (reactant == null || !inSchematic) {
kineticLaw.setText(SBMLutilities.updateFormulaVar(kineticLaw.getText().trim(), selectedID, reactantId.getText().trim()));
}
}
else {
// SpeciesReference reactan = new
// SpeciesReference(BioSim.SBML_LEVEL, BioSim.SBML_VERSION);
SpeciesReference reactan = new SpeciesReference(gcm.getSBMLDocument().getLevel(), gcm.getSBMLDocument().getVersion());
reactan.setId(reactantId.getText().trim());
reactan.setName(reactantName.getText().trim());
reactan.setConstant(true);
changedReactants.add(reactan);
reactan.setSpecies((String) reactantSpecies.getSelectedItem());
reactan.setStoichiometry(val);
if (complex!=null) {
double nc = bioModel.getSBMLDocument().getModel().getParameter(GlobalConstants.COOPERATIVITY_STRING).getValue();
String ncStr = GlobalConstants.COOPERATIVITY_STRING+"_"+reactan.getSpecies();
LocalParameter paramet = null;
for (LocalParameter p : changedParameters) {
if (p.getId().equals(ncStr)) {
paramet = p;
}
}
if (nc==val) {
if (paramet != null) {
removeLocalParameter(ncStr);
}
} else {
if (paramet != null) {
removeLocalParameter(ncStr);
addLocalParameter(GlobalConstants.COOPERATIVITY_STRING+"_"+reactan.getSpecies(),val);
} else {
addLocalParameter(GlobalConstants.COOPERATIVITY_STRING+"_"+reactan.getSpecies(),val);
}
}
}
if (reactantConstant.getSelectedItem().equals("true")) {
reactan.setConstant(true);
}
else {
reactan.setConstant(false);
}
JList add = new JList();
Object[] adding = { react };
add.setListData(adding);
add.setSelectedIndex(0);
reactants.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
adding = Utility.add(reacta, reactants, add);
reacta = new String[adding.length];
for (int i = 0; i < adding.length; i++) {
reacta[i] = (String) adding[i];
}
Utility.sort(reacta);
reactants.setListData(reacta);
reactants.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
reactants.setSelectedIndex(0);
}
modelEditor.setDirty(true);
gcm.makeUndoPoint();
}
if (error) {
value = JOptionPane.showOptionDialog(Gui.frame, reactantsPanel, "Reactants Editor", JOptionPane.YES_NO_OPTION,
JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
}
}
if (value == JOptionPane.NO_OPTION) {
return;
}
}
/**
* Remove a reaction
*/
private void removeReaction() {
int index = reactions.getSelectedIndex();
if (index != -1) {
String selected = ((String) reactions.getSelectedValue()).split(" ")[0];
Reaction reaction = bioModel.getSBMLDocument().getModel().getReaction(selected);
if (BioModel.isProductionReaction(reaction)) {
bioModel.removePromoter(selected.replace("Production_", ""));
} else {
bioModel.removeReaction(selected);
reactions.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
reacts = (String[]) Utility.remove(reactions, reacts);
reactions.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
if (index < reactions.getModel().getSize()) {
reactions.setSelectedIndex(index);
}
else {
reactions.setSelectedIndex(index - 1);
}
}
modelEditor.setDirty(true);
bioModel.makeUndoPoint();
}
}
/**
* Remove the reaction
*/
public static void removeTheReaction(BioModel gcm, String selected) {
Reaction tempReaction = gcm.getSBMLDocument().getModel().getReaction(selected);
ListOf<Reaction> r = gcm.getSBMLDocument().getModel().getListOfReactions();
for (int i = 0; i < gcm.getSBMLDocument().getModel().getReactionCount(); i++) {
if (r.get(i).getId().equals(tempReaction.getId())) {
r.remove(i);
}
}
}
/**
* Remove a reactant from a reaction
*/
private void removeReactant() {
int index = reactants.getSelectedIndex();
if (index != -1) {
String v = ((String) reactants.getSelectedValue()).split(" ")[0];
for (int i = 0; i < changedReactants.size(); i++) {
if (changedReactants.get(i).getSpecies().equals(v) &&
!SBMLutilities.variableInUse(bioModel.getSBMLDocument(), changedReactants.get(i).getId(), false, true,true)) {
changedReactants.remove(i);
reactants.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
reacta = (String[]) Utility.remove(reactants, reacta);
reactants.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
if (index < reactants.getModel().getSize()) {
reactants.setSelectedIndex(index);
}
else {
reactants.setSelectedIndex(index - 1);
}
modelEditor.setDirty(true);
bioModel.makeUndoPoint();
}
}
}
}
/**
* Remove a product from a reaction
*/
private void removeProduct() {
int index = products.getSelectedIndex();
if (index != -1) {
String v = ((String) products.getSelectedValue()).split(" ")[0];
for (int i = 0; i < changedProducts.size(); i++) {
if (changedProducts.get(i).getSpecies().equals(v) &&
!SBMLutilities.variableInUse(bioModel.getSBMLDocument(), changedProducts.get(i).getId(), false, true, true)) {
changedProducts.remove(i);
products.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
proda = (String[]) Utility.remove(products, proda);
products.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
if (index < products.getModel().getSize()) {
products.setSelectedIndex(index);
}
else {
products.setSelectedIndex(index - 1);
}
modelEditor.setDirty(true);
bioModel.makeUndoPoint();
}
}
}
}
/**
* Remove a modifier from a reaction
*/
private void removeModifier() {
int index = modifiers.getSelectedIndex();
if (index != -1) {
String v = ((String) modifiers.getSelectedValue()).split(" ")[0];
for (int i = 0; i < changedModifiers.size(); i++) {
if (changedModifiers.get(i).getSpecies().equals(v)) {
if (!changedModifiers.get(i).isSetSBOTerm() ||
changedModifiers.get(i).getSBOTerm()!=GlobalConstants.SBO_PROMOTER_MODIFIER) {
changedModifiers.remove(i);
} else {
return;
}
}
}
modifiers.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
modifier = (String[]) Utility.remove(modifiers, modifier);
modifiers.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
if (index < modifiers.getModel().getSize()) {
modifiers.setSelectedIndex(index);
}
else {
modifiers.setSelectedIndex(index - 1);
}
modelEditor.setDirty(true);
bioModel.makeUndoPoint();
}
}
/**
* Remove a function if not in use
*/
private void useMassAction() {
String kf;
String kr;
if (changedParameters.size() == 0) {
JOptionPane.showMessageDialog(Gui.frame, "Unable to create mass action kinetic law.\n"
+ "Requires at least one local parameter.", "Unable to Create Kinetic Law",
JOptionPane.ERROR_MESSAGE);
return;
//kf = "kf";
//kr = "kr";
}
else if (changedParameters.size() == 1) {
kf = changedParameters.get(0).getId();
kr = changedParameters.get(0).getId();
}
else {
kf = changedParameters.get(0).getId();
kr = changedParameters.get(1).getId();
}
String kinetic = kf;
if (bioModel.getSBMLDocument().getLevel() > 2) {
boolean addEquil = false;
String equilExpr = "";
for (SpeciesReference s : changedReactants) {
if (s.isSetId()) {
addEquil = true;
equilExpr += s.getId();
}
else {
equilExpr += s.getStoichiometry();
}
}
if (addEquil) {
kinetic += " * pow(" + kf + "/" + kr + "," + equilExpr + "-2)";
}
}
for (SpeciesReference s : changedReactants) {
if ((bioModel.getSBMLDocument().getLevel() > 2) && (s.isSetId())) {
kinetic += " * pow(" + s.getSpecies() + ", " + s.getId() + ")";
}
else {
if (s.getStoichiometry() == 1) {
kinetic += " * " + s.getSpecies();
}
else {
kinetic += " * pow(" + s.getSpecies() + ", " + s.getStoichiometry() + ")";
}
}
}
for (ModifierSpeciesReference s : changedModifiers) {
kinetic += " * " + s.getSpecies();
}
if (reacReverse.getSelectedItem().equals("true")) {
kinetic += " - " + kr;
if (bioModel.getSBMLDocument().getLevel() > 2) {
boolean addEquil = false;
String equilExpr = "";
for (SpeciesReference s : changedProducts) {
if (s.isSetId()) {
addEquil = true;
equilExpr += s.getId();
}
else {
equilExpr += s.getStoichiometry();
}
}
if (addEquil) {
kinetic += " * pow(" + kf + "/" + kr + "," + equilExpr + "-1)";
}
}
for (SpeciesReference s : changedProducts) {
if ((bioModel.getSBMLDocument().getLevel() > 2) && (s.isSetId())) {
kinetic += " * pow(" + s.getSpecies() + ", " + s.getId() + ")";
}
else {
if (s.getStoichiometry() == 1) {
kinetic += " * " + s.getSpecies();
}
else {
kinetic += " * pow(" + s.getSpecies() + ", " + s.getStoichiometry() + ")";
}
}
}
for (ModifierSpeciesReference s : changedModifiers) {
kinetic += " * " + s.getSpecies();
}
}
kineticLaw.setText(kinetic);
modelEditor.setDirty(true);
bioModel.makeUndoPoint();
}
/**
* Remove a reaction parameter, if allowed
*/
private void reacRemoveParam() {
int index = reacParameters.getSelectedIndex();
if (index != -1) {
String v = ((String) reacParameters.getSelectedValue()).split(" ")[0];
if (reactions.getSelectedIndex() != -1) {
String kinetic = kineticLaw.getText().trim();
String[] vars = new String[0];
if (!kinetic.equals("")) {
vars = SBMLutilities.myFormulaToString(SBMLutilities.myParseFormula(kineticLaw.getText().trim())).split(" |\\(|\\)|\\,");
}
for (int j = 0; j < vars.length; j++) {
if (vars[j].equals(v)) {
JOptionPane.showMessageDialog(Gui.frame, "Cannot remove reaction parameter because it is used in the kinetic law.",
"Cannot Remove Parameter", JOptionPane.ERROR_MESSAGE);
return;
}
}
}
for (int i = 0; i < changedParameters.size(); i++) {
if (changedParameters.get(i).getId().equals(v)) {
changedParameters.remove(i);
}
}
thisReactionParams.remove(v);
reacParameters.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
reacParams = (String[]) Utility.remove(reacParameters, reacParams);
reacParameters.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
if (index < reacParameters.getModel().getSize()) {
reacParameters.setSelectedIndex(index);
}
else {
reacParameters.setSelectedIndex(index - 1);
}
modelEditor.setDirty(true);
bioModel.makeUndoPoint();
}
}
private void removeLocalParameter(String v) {
for (int i = 0; i < reacParameters.getModel().getSize(); i++) {
if (((String)reacParameters.getModel().getElementAt(i)).split(" ")[0].equals(v)) {
reacParameters.setSelectedIndex(i);
break;
}
}
for (int i = 0; i < changedParameters.size(); i++) {
if (changedParameters.get(i).getId().equals(v)) {
changedParameters.remove(i);
}
}
thisReactionParams.remove(v);
reacParameters.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
reacParams = (String[]) Utility.remove(reacParameters, reacParams);
reacParameters.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
reacParameters.setSelectedIndex(0);
modelEditor.setDirty(true);
bioModel.makeUndoPoint();
}
/**
* Check the units of a kinetic law
*/
public boolean checkKineticLawUnits(KineticLaw law) {
if (law.containsUndeclaredUnits()) {
if (Gui.getCheckUndeclared()) {
JOptionPane.showMessageDialog(Gui.frame, "Kinetic law contains literals numbers or parameters with undeclared units.\n"
+ "Therefore, it is not possible to completely verify the consistency of the units.", "Contains Undeclared Units",
JOptionPane.WARNING_MESSAGE);
}
return false;
}
else if (Gui.getCheckUnits()) {
if (SBMLutilities.checkUnitsInKineticLaw(bioModel.getSBMLDocument(), law)) {
JOptionPane.showMessageDialog(Gui.frame, "Kinetic law units should be substance / time.", "Units Do Not Match",
JOptionPane.ERROR_MESSAGE);
return true;
}
}
return false;
}
/**
* Checks the string to see if there are any errors. Retruns true if there are no errors, else returns false.
*/
public boolean fluxBoundisGood(String s, String reactionId){
if(s.contains("<=")){
String [] correctnessTest = s.split("<=");
if(correctnessTest.length == 3){
try{
Double.parseDouble(correctnessTest[0]);
}
catch(NumberFormatException e){
JOptionPane.showMessageDialog(Gui.frame, correctnessTest[0]+ " has to be a double.",
"Incorrect Element", JOptionPane.ERROR_MESSAGE);
return false;
}
try{
Double.parseDouble(correctnessTest[2]);
}
catch(NumberFormatException e){
JOptionPane.showMessageDialog(Gui.frame, correctnessTest[2] + " has to be a double.",
"Incorrect Element", JOptionPane.ERROR_MESSAGE);
return false;
}
if(Double.parseDouble(correctnessTest[0]) > Double.parseDouble(correctnessTest[2])){
JOptionPane.showMessageDialog(Gui.frame, correctnessTest[0] + " must be less than " + correctnessTest[2],
"Imbalance with Bounds", JOptionPane.ERROR_MESSAGE);
return false;
}
return true;
}
else if(correctnessTest.length == 2){
if(!correctnessTest[0].equals(reactionId) && !correctnessTest[1].equals(reactionId)){
JOptionPane.showMessageDialog(Gui.frame, "Must have "+ reactionId + " in the equation.", "No Reaction",
JOptionPane.ERROR_MESSAGE);
return false;
}
if(correctnessTest[0].equals(reactionId)){
try{
Double.parseDouble(correctnessTest[1]);
}
catch(Exception e){
if(e.equals(new NumberFormatException())){
JOptionPane.showMessageDialog(Gui.frame, correctnessTest[1] + " has to be a double.", "Incorrect Element",
JOptionPane.ERROR_MESSAGE);
return false;
}
}
}
else{
try{
Double.parseDouble(correctnessTest[0]);
}
catch(Exception e){
if(e.equals(new NumberFormatException())){
JOptionPane.showMessageDialog(Gui.frame, correctnessTest[0] + " has to be a double.", "Incorrect Element",
JOptionPane.ERROR_MESSAGE);
return false;
}
}
}
return true;
} else{
JOptionPane.showMessageDialog(Gui.frame, "Wrong number of elements.", "Bad Format",
JOptionPane.ERROR_MESSAGE);
return false;
}
}
else if(s.contains(">=")){
String [] correctnessTest = s.split(">=");
if(correctnessTest.length == 3){
try{
Double.parseDouble(correctnessTest[0]);
}
catch(NumberFormatException e){
JOptionPane.showMessageDialog(Gui.frame, correctnessTest[0]+ " has to be a double.",
"Incorrect Element", JOptionPane.ERROR_MESSAGE);
return false;
}
try{
Double.parseDouble(correctnessTest[2]);
}
catch(NumberFormatException e){
JOptionPane.showMessageDialog(Gui.frame, correctnessTest[2] + " has to be a double.",
"Incorrect Element", JOptionPane.ERROR_MESSAGE);
return false;
}
if(Double.parseDouble(correctnessTest[0]) < Double.parseDouble(correctnessTest[2])){
JOptionPane.showMessageDialog(Gui.frame, correctnessTest[0] + " must be greater than " + correctnessTest[2],
"Imbalance with Bounds", JOptionPane.ERROR_MESSAGE);
return false;
}
return true;
}
else if(correctnessTest.length == 2){
if(!correctnessTest[0].equals(reactionId) && !correctnessTest[1].equals(reactionId)){
JOptionPane.showMessageDialog(Gui.frame, "Must have "+ reactionId + " in the equation.", "No Reaction",
JOptionPane.ERROR_MESSAGE);
return false;
}
if(correctnessTest[0].equals(reactionId)){
try{
Double.parseDouble(correctnessTest[1]);
}
catch(Exception e){
if(e.equals(new NumberFormatException())){
JOptionPane.showMessageDialog(Gui.frame, correctnessTest[1] + " has to be a double.", "Incorrect Element",
JOptionPane.ERROR_MESSAGE);
return false;
}
}
}
else{
try{
Double.parseDouble(correctnessTest[0]);
}
catch(Exception e){
if(e.equals(new NumberFormatException())){
JOptionPane.showMessageDialog(Gui.frame, correctnessTest[0] + " has to be a double.", "Incorrect Element",
JOptionPane.ERROR_MESSAGE);
return false;
}
}
}
return true;
} else{
JOptionPane.showMessageDialog(Gui.frame, "Wrong number of elements.", "Bad Format",
JOptionPane.ERROR_MESSAGE);
return false;
}
}
else if(s.contains("=")){
String [] correctnessTest = s.split("=");
if(correctnessTest.length == 2){
if(!correctnessTest[0].equals(reactionId) && !correctnessTest[1].equals(reactionId)){
JOptionPane.showMessageDialog(Gui.frame, "Must have "+ reactionId + " in the equation.", "No Reaction",
JOptionPane.ERROR_MESSAGE);
return false;
}
if(correctnessTest[0].equals(reactionId)){
try{
Double.parseDouble(correctnessTest[1]);
}
catch(Exception e){
if(e.equals(new NumberFormatException())){
JOptionPane.showMessageDialog(Gui.frame, correctnessTest[1] + " has to be a double.", "Incorrect Element",
JOptionPane.ERROR_MESSAGE);
return false;
}
}
}
else{
try{
Double.parseDouble(correctnessTest[0]);
}
catch(Exception e){
if(e.equals(new NumberFormatException())){
JOptionPane.showMessageDialog(Gui.frame, correctnessTest[0] + " has to be a double.", "Incorrect Element",
JOptionPane.ERROR_MESSAGE);
return false;
}
}
}
return true;
} else{
JOptionPane.showMessageDialog(Gui.frame, "Wrong number of elements.", "Bad Format",
JOptionPane.ERROR_MESSAGE);
return false;
}
}
else{
JOptionPane.showMessageDialog(Gui.frame, "Need Operations.", "Bad Format",
JOptionPane.ERROR_MESSAGE);
return false;
}
}
// TODO: if contains >=
// split >=
// if (length == 3)
// check for double, reactionId, double
// check double1 >= double2
// else if (length == 2)
// check for (double, reactionId) OR (reactionId,double)
// else ERROR
public void setPanels(InitialAssignments initialsPanel, Rules rulesPanel) {
this.initialsPanel = initialsPanel;
this.rulesPanel = rulesPanel;
}
@Override
public void actionPerformed(ActionEvent e) {
// if the add compartment type button is clicked
// if the add species type button is clicked
// if the add compartment button is clicked
// if the add parameters button is clicked
// if the add reactions button is clicked
if (e.getSource() == addReac) {
reactionsEditor(bioModel, "Add", "", false);
}
// if the edit reactions button is clicked
else if (e.getSource() == editReac) {
if (reactions.getSelectedIndex() == -1) {
JOptionPane.showMessageDialog(Gui.frame, "No reaction selected.", "Must Select A Reaction", JOptionPane.ERROR_MESSAGE);
return;
}
reactionsEditor(bioModel, "OK", ((String) reactions.getSelectedValue()).split(" ")[0], false);
initialsPanel.refreshInitialAssignmentPanel(bioModel);
rulesPanel.refreshRulesPanel();
}
// if the remove reactions button is clicked
else if (e.getSource() == removeReac) {
removeReaction();
}
// if the add reactions parameters button is clicked
else if (e.getSource() == reacAddParam) {
reacParametersEditor(bioModel,"Add");
}
// if the edit reactions parameters button is clicked
else if (e.getSource() == reacEditParam) {
reacParametersEditor(bioModel,"OK");
}
// if the remove reactions parameters button is clicked
else if (e.getSource() == reacRemoveParam) {
reacRemoveParam();
}
// if the add reactants button is clicked
else if (e.getSource() == addReactant) {
reactantsEditor(bioModel, "Add", "", null, false);
}
// if the edit reactants button is clicked
else if (e.getSource() == editReactant) {
if (reactants.getSelectedIndex() == -1) {
JOptionPane.showMessageDialog(Gui.frame, "No reactant selected.", "Must Select A Reactant", JOptionPane.ERROR_MESSAGE);
return;
}
reactantsEditor(bioModel, "OK", ((String) reactants.getSelectedValue()).split(" ")[0], null, false);
initialsPanel.refreshInitialAssignmentPanel(bioModel);
rulesPanel.refreshRulesPanel();
}
// if the remove reactants button is clicked
else if (e.getSource() == removeReactant) {
removeReactant();
}
// if the add products button is clicked
else if (e.getSource() == addProduct) {
productsEditor(bioModel, "Add", "", null, false);
}
// if the edit products button is clicked
else if (e.getSource() == editProduct) {
if (products.getSelectedIndex() == -1) {
JOptionPane.showMessageDialog(Gui.frame, "No product selected.", "Must Select A Product", JOptionPane.ERROR_MESSAGE);
return;
}
productsEditor(bioModel, "OK", ((String) products.getSelectedValue()).split(" ")[0], null, false);
initialsPanel.refreshInitialAssignmentPanel(bioModel);
rulesPanel.refreshRulesPanel();
}
// if the remove products button is clicked
else if (e.getSource() == removeProduct) {
removeProduct();
}
// if the add modifiers button is clicked
else if (e.getSource() == addModifier) {
modifiersEditor("Add", false);
}
// if the edit modifiers button is clicked
else if (e.getSource() == editModifier) {
modifiersEditor("OK", false);
}
// if the remove modifiers button is clicked
else if (e.getSource() == removeModifier) {
removeModifier();
}
// if the clear button is clicked
else if (e.getSource() == clearKineticLaw) {
kineticLaw.setText("");
modelEditor.setDirty(true);
bioModel.makeUndoPoint();
}
// if the use mass action button is clicked
else if (e.getSource() == useMassAction) {
useMassAction();
}
}
@Override
public void mouseClicked(MouseEvent e) {
if (e.getClickCount() == 2) {
if (e.getSource() == reactions) {
if (reactions.getSelectedIndex() == -1) {
JOptionPane.showMessageDialog(Gui.frame, "No reaction selected.", "Must Select A Reaction", JOptionPane.ERROR_MESSAGE);
return;
}
reactionsEditor(bioModel, "OK", ((String) reactions.getSelectedValue()).split(" ")[0], false);
initialsPanel.refreshInitialAssignmentPanel(bioModel);
rulesPanel.refreshRulesPanel();
}
else if (e.getSource() == reacParameters) {
reacParametersEditor(bioModel,"OK");
}
else if (e.getSource() == reactants) {
if (!paramsOnly) {
if (reactants.getSelectedIndex() == -1) {
JOptionPane.showMessageDialog(Gui.frame, "No reactant selected.", "Must Select A Reactant", JOptionPane.ERROR_MESSAGE);
return;
}
reactantsEditor(bioModel, "OK", ((String) reactants.getSelectedValue()).split(" ")[0], null, false);
initialsPanel.refreshInitialAssignmentPanel(bioModel);
rulesPanel.refreshRulesPanel();
}
}
else if (e.getSource() == products) {
if (!paramsOnly) {
if (products.getSelectedIndex() == -1) {
JOptionPane.showMessageDialog(Gui.frame, "No product selected.", "Must Select A Product", JOptionPane.ERROR_MESSAGE);
return;
}
productsEditor(bioModel, "OK", ((String) products.getSelectedValue()).split(" ")[0], null, false);
initialsPanel.refreshInitialAssignmentPanel(bioModel);
rulesPanel.refreshRulesPanel();
}
}
else if (e.getSource() == modifiers) {
if (!paramsOnly) {
modifiersEditor("OK", false);
}
}
}
}
/**
* Refresh reaction panel
*/
public void refreshReactionPanel(BioModel gcm) {
String selectedReactionId = "";
if (!reactions.isSelectionEmpty()) {
selectedReactionId = ((String) reactions.getSelectedValue()).split(" ")[0];
}
this.bioModel = gcm;
Model model = gcm.getSBMLDocument().getModel();
ListOf<Reaction> listOfReactions = model.getListOfReactions();
reacts = new String[model.getReactionCount()];
for (int i = 0; i < model.getReactionCount(); i++) {
Reaction reaction = listOfReactions.get(i);
reacts[i] = reaction.getId();
if (paramsOnly) {
if (!reaction.isSetKineticLaw()) continue;
ListOf<LocalParameter> params = reaction.getKineticLaw().getListOfLocalParameters();
for (int j = 0; j < reaction.getKineticLaw().getLocalParameterCount(); j++) {
LocalParameter paramet = (params.get(j));
for (int k = 0; k < parameterChanges.size(); k++) {
if (parameterChanges.get(k).split(" ")[0].equals(reaction.getId() + "/" + paramet.getId())) {
String[] splits = parameterChanges.get(k).split(" ");
if (splits[splits.length - 2].equals("Modified") || splits[splits.length - 2].equals("Custom")) {
String value = splits[splits.length - 1];
paramet.setValue(Double.parseDouble(value));
}
else if (splits[splits.length - 2].equals("Sweep")) {
String value = splits[splits.length - 1];
paramet.setValue(Double.parseDouble(value.split(",")[0].substring(1).trim()));
}
if (!reacts[i].contains("Modified")) {
reacts[i] += " Modified";
}
}
}
}
}
}
Utility.sort(reacts);
int selected = 0;
for (int i = 0; i < reacts.length; i++) {
if (reacts[i].split(" ")[0].equals(selectedReactionId)) {
selected = i;
}
}
reactions.setListData(reacts);
reactions.setSelectedIndex(selected);
}
/**
* This method currently does nothing.
*/
@Override
public void mouseEntered(MouseEvent e) {
}
/**
* This method currently does nothing.
*/
@Override
public void mouseExited(MouseEvent e) {
}
/**
* This method currently does nothing.
*/
@Override
public void mousePressed(MouseEvent e) {
}
/**
* This method currently does nothing.
*/
@Override
public void mouseReleased(MouseEvent e) {
}
}
|
package water.fvec;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import water.*;
import water.parser.ValueString;
import water.util.Log;
import water.util.PrettyPrint;
import water.util.TwoDimTable;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.HashMap;
/** A collection of named {@link Vec}s, essentially an R-like Distributed Data Frame.
*
* <p>Frames represent a large distributed 2-D table with named columns
* ({@link Vec}s) and numbered rows. A reasonable <em>column</em> limit is
* 100K columns, but there's no hard-coded limit. There's no real <em>row</em>
* limit except memory; Frames (and Vecs) with many billions of rows are used
* routinely.
*
* <p>A Frame is a collection of named Vecs; a Vec is a collection of numbered
* {@link Chunk}s. A Frame is small, cheaply and easily manipulated, it is
* commonly passed-by-Value. It exists on one node, and <em>may</em> be
* stored in the {@link DKV}. Vecs, on the other hand, <em>must</em> be stored in the
* {@link DKV}, as they represent the shared common management state for a collection
* of distributed Chunks.
*
* <p>Multiple Frames can reference the same Vecs, although this sharing can
* make Vec lifetime management complex. Commonly temporary Frames are used
* to work with a subset of some other Frame (often during algorithm
* execution, when some columns are dropped from the modeling process). The
* temporary Frame can simply be ignored, allowing the normal GC process to
* reclaim it. Such temp Frames usually have a {@code null} key.
*
* <p>All the Vecs in a Frame belong to the same {@link Vec.VectorGroup} which
* then enforces {@link Chunk} row alignment across Vecs (or at least enforces
* a low-cost access model). Parallel and distributed execution touching all
* the data in a Frame relies on this alignment to get good performance.
*
* <p>Example: Make a Frame from a CSV file:<pre>
* File file = ...
* NFSFileVec nfs = NFSFileVec.make(file); // NFS-backed Vec, lazily read on demand
* Frame fr = water.parser.ParseDataset.parse(Key.make("myKey"),nfs._key);
* </pre>
*
* <p>Example: Find and remove the Vec called "unique_id" from the Frame,
* since modeling with a unique_id can lead to overfitting:
* <pre>
* Vec uid = fr.remove("unique_id");
* </pre>
*
* <p>Example: Move the response column to the last position:
* <pre>
* fr.add("response",fr.remove("response"));
* </pre>
*
*/
public class Frame extends Lockable<Frame> {
/** Vec names */
public String[] _names;
private boolean _lastNameBig; // Last name is "Cxxx" and has largest number
private Key<Vec>[] _keys; // Keys for the vectors
private transient Vec[] _vecs; // The Vectors (transient to avoid network traffic)
private transient Vec _col0; // First readable vec; fast access to the VectorGroup's Chunk layout
/** Creates an internal frame composed of the given Vecs and default names. The frame has no key. */
public Frame( Vec... vecs ){ this(null,vecs);}
/** Creates an internal frame composed of the given Vecs and names. The frame has no key. */
public Frame( String names[], Vec vecs[] ) { this(null,names,vecs); }
/** Creates an empty frame with given key. */
public Frame( Key key ) {
this(key,null,new Vec[0]);
}
/**
* Special constructor for data with unnamed columns (e.g. svmlight) bypassing *all* checks.
* @param key
* @param vecs
* @param noChecks
*/
public Frame( Key key, Vec vecs[], boolean noChecks) {
super(key);
assert noChecks;
_vecs = vecs;
_names = new String[vecs.length];
_keys = new Key[vecs.length];
for (int i = 0; i < vecs.length; i++) {
_names[i] = defaultColName(i);
_keys[i] = vecs[i]._key;
}
}
/** Creates a frame with given key, names and vectors. */
public Frame( Key key, String names[], Vec vecs[] ) {
super(key);
// Require all Vecs already be installed in the K/V store
for( Vec vec : vecs ) DKV.prefetch(vec._key);
for( Vec vec : vecs ) assert DKV.get(vec._key) != null;
// Always require names
if( names==null ) { // Make default names, all known to be unique
_names = new String[vecs.length];
_keys = new Key [vecs.length];
_vecs = vecs;
for( int i=0; i<vecs.length; i++ ) _names[i] = defaultColName(i);
for( int i=0; i<vecs.length; i++ ) _keys [i] = vecs[i]._key;
for( int i=0; i<vecs.length; i++ ) checkCompatible(_names[i],vecs[i]);
_lastNameBig = true;
} else {
// Make empty to dodge asserts, then "add()" them all which will check
// for compatible Vecs & names.
_names = new String[0];
_keys = new Key [0];
_vecs = new Vec [0];
add(names,vecs);
}
assert _names.length == vecs.length;
}
/** Deep copy of Vecs and Keys and Names (but not data!) to a new random Key.
* The resulting Frame does not share with the original, so the set of Vecs
* can be freely hacked without disturbing the original Frame. */
public Frame( Frame fr ) {
super( Key.make() );
_names= fr._names.clone();
_keys = fr._keys .clone();
_vecs = fr.vecs().clone();
_lastNameBig = fr._lastNameBig;
}
/** Default column name maker */
public static String defaultColName( int col ) { return "C"+(1+col); }
// Make unique names. Efficient for the special case of appending endless
// versions of "C123" style names where the next name is +1 over the prior
// name. All other names take the O(n^2) lookup.
private int pint( String name ) {
try { return Integer.valueOf(name.substring(1)); }
catch( NumberFormatException fe ) { }
return 0;
}
private String uniquify( String name ) {
String n = name;
int lastName = 0;
if( name.length() > 0 && name.charAt(0)=='C' )
lastName = pint(name);
if( _lastNameBig && _names.length > 0 ) {
String last = _names[_names.length-1];
if( !last.equals("") && last.charAt(0)=='C' && lastName == pint(last)+1 )
return name;
}
int cnt=0, again, max=0;
do {
again = cnt;
for( String s : _names ) {
if( lastName > 0 && s.charAt(0)=='C' )
max = Math.max(max,pint(s));
if( n.equals(s) )
n = name+(cnt++);
}
} while( again != cnt );
if( lastName == max+1 ) _lastNameBig = true;
return n;
}
/** Check that the vectors are all compatible. All Vecs have their content
* sharded using same number of rows per chunk, and all names are unique.
* Throw an IAE if something does not match. */
private void checkCompatible( String name, Vec vec ) {
if( vec instanceof AppendableVec ) return; // New Vectors are endlessly compatible
Vec v0 = anyVec();
if( v0 == null ) return; // No fixed-size Vecs in the Frame
// Vector group has to be the same, or else the layout has to be the same,
// or else the total length has to be small.
if( !v0.checkCompatible(vec) ) {
if(!Vec.VectorGroup.sameGroup(v0,vec))
Log.err("Unexpected incompatible vector group, " + v0.group() + " != " + vec.group());
if(!Arrays.equals(v0._espc, vec._espc))
Log.err("Unexpected incompatible espc, " + Arrays.toString(v0._espc) + " != " + Arrays.toString(vec._espc));
throw new IllegalArgumentException("Vec " + name + " is not compatible with the rest of the frame");
}
}
/** Quick compatibility check between Frames. Used by some tests for efficient equality checks. */
public boolean isCompatible( Frame fr ) {
if( numCols() != fr.numCols() ) return false;
if( numRows() != fr.numRows() ) return false;
for( int i=0; i<vecs().length; i++ )
if( !vecs()[i].checkCompatible(fr.vecs()[i]) )
return false;
return true;
}
/** Number of columns
* @return Number of columns */
public int numCols() { return _keys.length; }
/** Number of columns with categoricals expanded
* @return Number of columns with categoricals expanded into indicator columns */
public int numColsExp() { return numColsExp(true, false); }
public int numColsExp(boolean useAllFactorLevels, boolean missingBucket) {
if(_vecs == null) return 0;
int cols = 0;
for(int i = 0; i < _vecs.length; i++) {
if(_vecs[i].isEnum() && _vecs[i].domain() != null)
cols += _vecs[i].domain().length - (useAllFactorLevels ? 0 : 1) + (missingBucket ? 1 : 0);
else cols++;
}
return cols;
}
/** Number of rows
* @return Number of rows */
public long numRows() { Vec v = anyVec(); return v==null ? 0 : v.length(); }
/**
* Number of degrees of freedom (#numerical columns + sum(#categorical levels))
* @return Number of overall degrees of freedom
*/
public long degreesOfFreedom() {
long dofs = 0;
String[][] dom = domains();
for (int i=0; i<numCols(); ++i) {
if (dom[i] == null) {
dofs++;
} else {
dofs+=dom[i].length;
}
}
return dofs;
}
/** Returns the first readable vector.
* @return the first readable Vec */
public final Vec anyVec() {
Vec c0 = _col0; // single read
if( c0 != null ) return c0;
for( Vec v : vecs() )
if( v.readable() )
return (_col0 = v);
return null;
}
/** The array of column names.
* @return the array of column names */
public String[] names() { return _names; }
/** A single column name.
* @return the column name */
public String name(int i) { return _names[i]; } // TODO: saw a non-reproducible NPE here
/** The array of keys.
* @return the array of keys for each vec in the frame.
*/
public Key[] keys() { return _keys; }
/** The internal array of Vecs. For efficiency Frames contain an array of
* Vec Keys - and the Vecs themselves are lazily loaded from the {@link DKV}.
* @return the internal array of Vecs */
public final Vec[] vecs() {
Vec[] tvecs = _vecs; // read the content
return tvecs == null ? (_vecs=vecs_impl()) : tvecs;
}
public final Vec[] vecs(int [] idxs) {
Vec [] all = vecs();
Vec [] res = new Vec[idxs.length];
for(int i = 0; i < idxs.length; ++i)
res[i] = all[idxs[i]];
return res;
}
public Vec[] vecs(String[] names) {
Vec [] res = new Vec[names.length];
for(int i = 0; i < names.length; ++i)
res[i] = vec(names[i]);
return res;
}
// Compute vectors for caching
private Vec[] vecs_impl() {
// Load all Vec headers; load them all in parallel by starting prefetches
for( Key<Vec> key : _keys ) DKV.prefetch(key);
Vec [] vecs = new Vec[_keys.length];
for( int i=0; i<_keys.length; i++ ) vecs[i] = _keys[i].get();
return vecs;
}
/** Convenience to accessor for last Vec
* @return last Vec */
public Vec lastVec() { vecs(); return _vecs [_vecs.length -1]; }
/** Convenience to accessor for last Vec name
* @return last Vec name */
public String lastVecName() { return _names[_names.length-1]; }
/** Force a cache-flush and reload, assuming vec mappings were altered
* remotely, or that the _vecs array was shared and now needs to be a
* defensive copy.
* @return the new instance of the Frame's Vec[] */
public final Vec[] reloadVecs() { _vecs=null; return vecs(); }
/** Returns the Vec by given index, implemented by code: {@code vecs()[idx]}.
* @param idx idx of column
* @return this frame idx-th vector, never returns <code>null</code> */
public final Vec vec(int idx) { return vecs()[idx]; }
/** Return a Vec by name, or null if missing
* @return a Vec by name, or null if missing */
public Vec vec(String name) { int idx = find(name); return idx==-1 ? null : vecs()[idx]; }
/** Finds the column index with a matching name, or -1 if missing
* @return the column index with a matching name, or -1 if missing */
public int find( String name ) {
if( name == null ) return -1;
assert _names != null;
for( int i=0; i<_names.length; i++ )
if( name.equals(_names[i]) )
return i;
return -1;
}
/** Finds the matching column index, or -1 if missing
* @return the matching column index, or -1 if missing */
public int find( Vec vec ) {
Vec[] vecs = vecs(); //warning: side-effect
if (vec == null) return -1;
for( int i=0; i<vecs.length; i++ )
if( vec.equals(vecs[i]) )
return i;
return -1;
}
/** Finds the matching column index, or -1 if missing
* @return the matching column index, or -1 if missing */
public int find( Key key ) {
for( int i=0; i<_keys.length; i++ )
if( key.equals(_keys[i]) )
return i;
return -1;
}
/** Bulk {@link #find(String)} api
* @return An array of column indices matching the {@code names} array */
public int[] find(String[] names) {
if( names == null ) return null;
int[] res = new int[names.length];
for(int i = 0; i < names.length; ++i)
res[i] = find(names[i]);
return res;
}
/** Pair of (column name, Frame key). */
public static class VecSpecifier extends Iced {
public Key<Frame> _frame;
String _column_name;
public Vec vec() {
Value v = DKV.get(_frame);
if (null == v) return null;
Frame f = v.get();
if (null == f) return null;
return f.vec(_column_name);
}
}
/** Type for every Vec */
byte[] types() {
Vec[] vecs = vecs();
byte bs[] = new byte[vecs.length];
for( int i=0; i<vecs.length; i++ )
bs[i] = vecs[i]._type;
return bs;
}
/** All the domains for enum columns; null for non-enum columns.
* @return the domains for enum columns */
public String[][] domains() {
Vec[] vecs = vecs();
String ds[][] = new String[vecs.length][];
for( int i=0; i<vecs.length; i++ )
ds[i] = vecs[i].domain();
return ds;
}
/** All the column means.
* @return the mean of each column */
public double[] means() {
Vec[] vecs = vecs();
double[] means = new double[vecs.length];
for( int i = 0; i < vecs.length; i++ )
means[i] = vecs[i].mean();
return means;
}
/** One over the standard deviation of each column.
* @return Reciprocal the standard deviation of each column */
public double[] mults() {
Vec[] vecs = vecs();
double[] mults = new double[vecs.length];
for( int i = 0; i < vecs.length; i++ ) {
double sigma = vecs[i].sigma();
mults[i] = standardize(sigma) ? 1.0 / sigma : 1.0;
}
return mults;
}
private static boolean standardize(double sigma) {
// TODO unify handling of constant columns
return sigma > 1e-6;
}
/** The {@code Vec.byteSize} of all Vecs
* @return the {@code Vec.byteSize} of all Vecs */
public long byteSize() {
long sum=0;
Vec[] vecs = vecs();
for (Vec vec : vecs) sum += vec.byteSize();
return sum;
}
/** 64-bit checksum of the checksums of the vecs. SHA-265 checksums of the
* chunks are XORed together. Since parse always parses the same pieces of
* files into the same offsets in some chunk this checksum will be
* consistent across reparses.
* @return 64-bit Frame checksum */
@Override protected long checksum_impl() {
Vec[] vecs = vecs();
long _checksum = 0;
for( int i = 0; i < _names.length; ++i ) {
long vec_checksum = vecs[i].checksum();
_checksum ^= vec_checksum;
long tmp = (2147483647L * i);
_checksum ^= tmp;
}
_checksum *= (0xBABE + Arrays.hashCode(_names));
// TODO: include column types? Vec.checksum() should include type?
return _checksum;
}
// Add a bunch of vecs
public void add( String[] names, Vec[] vecs) {
bulkAdd(names, vecs);
}
public void add( String[] names, Vec[] vecs, int cols ) {
if (null == vecs || null == names) return;
if (cols == names.length && cols == vecs.length) {
bulkAdd(names, vecs);
} else {
for (int i = 0; i < cols; i++)
add(names[i], vecs[i]);
}
}
/** Append multiple named Vecs to the Frame. Names are forced unique, by appending a
* unique number if needed.
*/
private void bulkAdd(String[] names, Vec[] vecs) {
String[] tmpnames = names.clone();
int N = names.length;
assert(names.length == vecs.length):"names = " + Arrays.toString(names) + ", vecs len = " + vecs.length;
for (int i=0; i<N; ++i) {
vecs[i] = vecs[i] != null ? makeCompatible(new Frame(vecs[i])).anyVec() : null;
checkCompatible(tmpnames[i]=uniquify(tmpnames[i]),vecs[i]); // Throw IAE is mismatch
}
int ncols = _keys.length;
_names = Arrays.copyOf(_names, ncols+N);
_keys = Arrays.copyOf(_keys, ncols+N);
_vecs = Arrays.copyOf(_vecs, ncols+N);
for (int i=0; i<N; ++i) {
_names[ncols+i] = tmpnames[i];
_keys[ncols+i] = vecs[i]._key;
_vecs[ncols+i] = vecs[i];
}
}
/** Append a named Vec to the Frame. Names are forced unique, by appending a
* unique number if needed.
* @return the added Vec, for flow-coding */
public Vec add( String name, Vec vec ) {
vec = makeCompatible(new Frame(vec)).anyVec();
checkCompatible(name=uniquify(name),vec); // Throw IAE is mismatch
int ncols = _keys.length;
_names = Arrays.copyOf(_names,ncols+1); _names[ncols] = name;
_keys = Arrays.copyOf(_keys ,ncols+1); _keys [ncols] = vec._key;
_vecs = Arrays.copyOf(_vecs ,ncols+1); _vecs [ncols] = vec;
return vec;
}
/** Append a Frame onto this Frame. Names are forced unique, by appending
* unique numbers if needed.
* @return the expanded Frame, for flow-coding */
public Frame add( Frame fr ) { add(fr._names,fr.vecs(),fr.numCols()); return this; }
/** Insert a named column as the first column */
public Frame prepend( String name, Vec vec ) {
if( find(name) != -1 ) throw new IllegalArgumentException("Duplicate name '"+name+"' in Frame");
if( _vecs.length != 0 ) {
if( !anyVec().group().equals(vec.group()) && !Arrays.equals(anyVec()._espc,vec._espc) )
throw new IllegalArgumentException("Vector groups differs - adding vec '"+name+"' into the frame " + Arrays.toString(_names));
if( numRows() != vec.length() )
throw new IllegalArgumentException("Vector lengths differ - adding vec '"+name+"' into the frame " + Arrays.toString(_names));
}
final int len = _names != null ? _names.length : 0;
String[] _names2 = new String[len+1];
Vec[] _vecs2 = new Vec [len+1];
Key[] _keys2 = new Key [len+1];
_names2[0] = name;
_vecs2 [0] = vec ;
_keys2 [0] = vec._key;
System.arraycopy(_names, 0, _names2, 1, len);
System.arraycopy(_vecs, 0, _vecs2, 1, len);
System.arraycopy(_keys, 0, _keys2, 1, len);
_names = _names2;
_vecs = _vecs2;
_keys = _keys2;
return this;
}
/** Swap two Vecs in-place; useful for sorting columns by some criteria */
public void swap( int lo, int hi ) {
assert 0 <= lo && lo < _keys.length;
assert 0 <= hi && hi < _keys.length;
if( lo==hi ) return;
Vec vecs[] = vecs();
Vec v = vecs [lo]; vecs [lo] = vecs [hi]; vecs [hi] = v;
Key k = _keys[lo]; _keys [lo] = _keys [hi]; _keys [hi] = k;
String n=_names[lo]; _names[lo] = _names[hi]; _names[hi] = n;
}
public Frame subframe(String[] names) { return subframe(names, false, 0)[0]; }
/** Returns a new frame composed of vectors of this frame selected by given names.
* The method replaces missing vectors by a constant column filled by given value.
* @param names names of vector to compose a subframe
* @param c value to fill missing columns.
* @return two frames, the first contains subframe, the second contains newly created constant vectors or null
*/
public Frame[] subframe(String[] names, double c) { return subframe(names, true, c); }
private Frame[] subframe(String[] names, boolean replaceBy, double c){
Vec [] vecs = new Vec[names.length];
Vec [] cvecs = replaceBy ? new Vec [names.length] : null;
String[] cnames = replaceBy ? new String[names.length] : null;
int ccv = 0; // counter of constant columns
vecs(); // Preload the vecs
HashMap<String, Integer> map = new HashMap<>((int) ((names.length/0.75f)+1)); // avoid rehashing by set up initial capacity
for(int i = 0; i < _names.length; ++i) map.put(_names[i], i);
for(int i = 0; i < names.length; ++i)
if(map.containsKey(names[i])) vecs[i] = _vecs[map.get(names[i])];
else if (replaceBy) {
Log.warn("Column " + names[i] + " is missing, filling it in with " + c);
assert cnames != null;
cnames[ccv] = names[i];
vecs[i] = cvecs[ccv++] = anyVec().makeCon(c);
}
return new Frame[] { new Frame(Key.make("subframe"+Key.make().toString()), names,vecs), ccv>0 ? new Frame(Key.make("subframe"+Key.make().toString()), Arrays.copyOf(cnames, ccv), Arrays.copyOf(cvecs,ccv)) : null };
}
/** Allow rollups for all written-into vecs; used by {@link MRTask} once
* writing is complete.
* @return the original Futures, for flow-coding */
public Futures postWrite(Futures fs) {
for( Vec v : vecs() ) v.postWrite(fs);
return fs;
}
/** Actually remove/delete all Vecs from memory, not just from the Frame.
* @return the original Futures, for flow-coding */
@Override public Futures remove_impl(Futures fs) {
final Key[] keys = _keys;
if( keys.length==0 ) return fs;
final int ncs = anyVec().nChunks(); // TODO: do not call anyVec which loads all Vecs... only to delete them
_names = new String[0];
_vecs = new Vec[0];
_keys = new Key[0];
// Bulk dumb local remove - no JMM, no ordering, no safety.
new MRTask() {
@Override public void setupLocal() {
for( Key k : keys ) if( k != null ) Vec.bulk_remove(k,ncs);
}
}.doAllNodes();
return fs;
}
/** Replace one column with another. Caller must perform global update (DKV.put) on
* this updated frame.
* @return The old column, for flow-coding */
public Vec replace(int col, Vec nv) {
Vec rv = vecs()[col];
nv = ((new Frame(rv)).makeCompatible(new Frame(nv))).anyVec();
DKV.put(nv);
assert DKV.get(nv._key)!=null; // Already in DKV
assert rv.group().equals(nv.group());
_vecs[col] = nv;
_keys[col] = nv._key;
return rv;
}
/** Create a subframe from given interval of columns.
* @param startIdx index of first column (inclusive)
* @param endIdx index of the last column (exclusive)
* @return a new Frame containing specified interval of columns */
private Frame subframe(int startIdx, int endIdx) {
return new Frame(Arrays.copyOfRange(_names,startIdx,endIdx),Arrays.copyOfRange(vecs(),startIdx,endIdx));
}
/** Split this Frame; return a subframe created from the given column interval, and
* remove those columns from this Frame.
* @param startIdx index of first column (inclusive)
* @param endIdx index of the last column (exclusive)
* @return a new Frame containing specified interval of columns */
public Frame extractFrame(int startIdx, int endIdx) {
Frame f = subframe(startIdx, endIdx);
remove(startIdx, endIdx);
return f;
}
/** Removes the column with a matching name.
* @return The removed column */
public Vec remove( String name ) { return remove(find(name)); }
public Frame remove( String[] names ) {
for( String name : names )
remove(find(name));
return this;
}
/** Removes a list of columns by index; the index list must be sorted
* @return an array of the removed columns */
public Vec[] remove( int[] idxs ) {
for( int i : idxs )
if(i < 0 || i >= vecs().length)
throw new ArrayIndexOutOfBoundsException();
Arrays.sort(idxs);
Vec[] res = new Vec[idxs.length];
Vec[] rem = new Vec[_vecs.length-idxs.length];
String[] names = new String[rem.length];
Key [] keys = new Key [rem.length];
int j = 0;
int k = 0;
int l = 0;
for(int i = 0; i < _vecs.length; ++i) {
if(j < idxs.length && i == idxs[j]) {
++j;
res[k++] = _vecs[i];
} else {
rem [l] = _vecs [i];
names[l] = _names[i];
keys [l] = _keys [i];
++l;
}
}
_vecs = rem;
_names= names;
_keys = keys;
assert l == rem.length && k == idxs.length;
return res;
}
/** Removes a numbered column.
* @return the removed column */
public final Vec remove( int idx ) {
int len = _names.length;
if( idx < 0 || idx >= len ) return null;
Vec v = vecs()[idx];
System.arraycopy(_names,idx+1,_names,idx,len-idx-1);
System.arraycopy(_vecs ,idx+1,_vecs ,idx,len-idx-1);
System.arraycopy(_keys ,idx+1,_keys ,idx,len-idx-1);
_names = Arrays.copyOf(_names,len-1);
_vecs = Arrays.copyOf(_vecs ,len-1);
_keys = Arrays.copyOf(_keys ,len-1);
if( v == _col0 ) _col0 = null;
return v;
}
/** Remove given interval of columns from frame. Motivated by R intervals.
* @param startIdx - start index of column (inclusive)
* @param endIdx - end index of column (exclusive)
* @return array of removed columns */
Vec[] remove(int startIdx, int endIdx) {
int len = _names.length;
int nlen = len - (endIdx-startIdx);
String[] names = new String[nlen];
Key[] keys = new Key[nlen];
Vec[] vecs = new Vec[nlen];
vecs();
if (startIdx > 0) {
System.arraycopy(_names, 0, names, 0, startIdx);
System.arraycopy(_vecs, 0, vecs, 0, startIdx);
System.arraycopy(_keys, 0, keys, 0, startIdx);
}
nlen -= startIdx;
if (endIdx < _names.length+1) {
System.arraycopy(_names, endIdx, names, startIdx, nlen);
System.arraycopy(_vecs, endIdx, vecs, startIdx, nlen);
System.arraycopy(_keys, endIdx, keys, startIdx, nlen);
}
Vec[] vecX = Arrays.copyOfRange(_vecs,startIdx,endIdx);
_names = names;
_vecs = vecs;
_keys = keys;
_col0 = null;
return vecX;
}
/** Restructure a Frame completely */
public void restructure( String[] names, Vec[] vecs) {
restructure(names, vecs, vecs.length);
}
/** Restructure a Frame completely, but only for a specified number of columns (counting up) */
public void restructure( String[] names, Vec[] vecs, int cols) {
// Make empty to dodge asserts, then "add()" them all which will check for
// compatible Vecs & names.
_names = new String[0];
_keys = new Key [0];
_vecs = new Vec [0];
add(names,vecs,cols);
}
// Utilities to help external Frame constructors, e.g. Spark.
// Make an initial Frame & lock it for writing. Build Vec Keys.
void preparePartialFrame( String[] names ) {
// Nuke any prior frame (including freeing storage) & lock this one
if( _keys != null ) delete_and_lock(null);
else write_lock(null);
_names = names;
_keys = new Vec.VectorGroup().addVecs(names.length);
// No Vectors tho!!! These will be added *after* the import
}
// Only serialize strings, not H2O internal structures
// Make NewChunks to for holding data from e.g. Spark. Once per set of
// Chunks in a Frame, before filling them. This can be called in parallel
// for different Chunk#'s (cidx); each Chunk can be filled in parallel.
static NewChunk[] createNewChunks( String name, int cidx ) {
Frame fr = (Frame)Key.make(name).get();
NewChunk[] nchks = new NewChunk[fr.numCols()];
for( int i=0; i<nchks.length; i++ )
nchks[i] = new NewChunk(new AppendableVec(fr._keys[i]),cidx);
return nchks;
}
// Compress & DKV.put NewChunks. Once per set of Chunks in a Frame, after
// filling them. Can be called in parallel for different sets of Chunks.
static void closeNewChunks( NewChunk[] nchks ) {
Futures fs = new Futures();
for( NewChunk nchk : nchks ) nchk.close(fs);
fs.blockForPending();
}
// Build real Vecs from loose Chunks, and finalize this Frame. Called once
// after any number of [create,close]NewChunks.
// FIXME: have proper representation of column type
void finalizePartialFrame( long[] espc, String[][] domains, byte[] types ) {
// Compute elems-per-chunk.
// Roll-up elem counts, so espc[i] is the starting element# of chunk i.
int nchunk = espc.length;
long espc2[] = new long[nchunk+1]; // Shorter array
long x=0; // Total row count so far
for( int i=0; i<nchunk; i++ ) {
espc2[i] = x; // Start elem# for chunk i
x += espc[i]; // Raise total elem count
}
espc2[nchunk]=x; // Total element count in last
// For all Key/Vecs - insert Vec header
Futures fs = new Futures();
_vecs = new Vec[_keys.length];
for( int i=0; i<_keys.length; i++ ) {
// Insert Vec header
Vec vec = _vecs[i] = new Vec( _keys[i],
espc2,
domains!=null ? domains[i] : null,
types[i]);
// Here we have to save vectors since
// saving during unlock will invoke Frame vector
// refresh
DKV.put(_keys[i],vec,fs);
}
fs.blockForPending();
unlock(null);
}
static final int MAX_EQ2_COLS = 100000; // Limit of columns user is allowed to request
/** In support of R, a generic Deep Copy and Slice.
*
* <p>Semantics are a little odd, to match R's. Each dimension spec can be:<ul>
* <li><em>null</em> - all of them
* <li><em>a sorted list of negative numbers (no dups)</em> - all BUT these
* <li><em>an unordered list of positive</em> - just these, allowing dups
* </ul>
*
* <p>The numbering is 1-based; zero's are not allowed in the lists, nor are out-of-range values.
* @return the sliced Frame
*/
public Frame deepSlice( Object orows, Object ocols ) {
// ocols is either a long[] or a Frame-of-1-Vec
long[] cols;
if( ocols == null ) cols = null;
else if (ocols instanceof long[]) cols = (long[])ocols;
else if (ocols instanceof Frame) {
Frame fr = (Frame) ocols;
if (fr.numCols() != 1)
throw new IllegalArgumentException("Columns Frame must have only one column (actually has " + fr.numCols() + " columns)");
long n = fr.anyVec().length();
if (n > MAX_EQ2_COLS)
throw new IllegalArgumentException("Too many requested columns (requested " + n +", max " + MAX_EQ2_COLS + ")");
cols = new long[(int)n];
Vec v = fr.anyVec();
for (long i = 0; i < v.length(); i++)
cols[(int)i] = v.at8(i);
} else
throw new IllegalArgumentException("Columns is specified by an unsupported data type (" + ocols.getClass().getName() + ")");
// Since cols is probably short convert to a positive list.
int c2[];
if( cols==null ) {
c2 = new int[numCols()];
for( int i=0; i<c2.length; i++ ) c2[i]=i;
} else if( cols.length==0 ) {
c2 = new int[0];
} else if( cols[0] >= 0 ) {
c2 = new int[cols.length];
for( int i=0; i<cols.length; i++ )
c2[i] = (int)cols[i]; // Conversion of 1-based cols to 0-based is handled by a 1-based front-end!
} else {
c2 = new int[numCols()-cols.length];
int j=0;
for( int i=0; i<numCols(); i++ ) {
if( j >= cols.length || i < (-(1+cols[j])) ) c2[i-j] = i;
else j++;
}
}
for (int aC2 : c2)
if (aC2 >= numCols())
throw new IllegalArgumentException("Trying to select column " + (aC2 + 1) + " but only " + numCols() + " present.");
if( c2.length==0 )
throw new IllegalArgumentException("No columns selected (did you try to select column 0 instead of column 1?)");
// Do Da Slice
// orows is either a long[] or a Vec
if (numRows() == 0) {
return new MRTask() {
@Override public void map(Chunk[] chks, NewChunk[] nchks) { for (NewChunk nc : nchks) nc.addNA(); }
}.doAll(c2.length, this).outputFrame(names(c2), domains(c2));
}
if (orows == null)
return new DeepSlice(null,c2,vecs()).doAll(c2.length,this).outputFrame(names(c2),domains(c2));
else if (orows instanceof long[]) {
final long CHK_ROWS=1000000;
final long[] rows = (long[])orows;
if (this.numRows() == 0) {
return this;
}
if( rows.length==0 || rows[0] < 0 ) {
if (rows.length != 0 && rows[0] < 0) {
Vec v0 = this.anyVec().makeZero();
Vec v = new MRTask() {
@Override public void map(Chunk cs) {
for (long er : rows) {
if (er >= 0) continue;
er = Math.abs(er);
if (er < cs._start || er > (cs._len + cs._start - 1)) continue;
cs.set((int) (er - cs._start), 1);
}
}
}.doAll(v0).getResult()._fr.anyVec();
Keyed.remove(v0._key);
Frame slicedFrame = new DeepSlice(rows, c2, vecs()).doAll(c2.length, this.add("select_vec", v)).outputFrame(names(c2), domains(c2));
Keyed.remove(v._key);
Keyed.remove(this.remove(this.numCols() - 1)._key);
return slicedFrame;
} else {
return new DeepSlice(rows.length == 0 ? null : rows, c2, vecs()).doAll(c2.length, this).outputFrame(names(c2), domains(c2));
}
}
// Vec'ize the index array
Futures fs = new Futures();
AppendableVec av = new AppendableVec(Vec.newKey());
int r = 0;
int c = 0;
while (r < rows.length) {
NewChunk nc = new NewChunk(av, c);
long end = Math.min(r+CHK_ROWS, rows.length);
for (; r < end; r++) {
nc.addNum(rows[r]);
}
nc.close(c++, fs);
}
Vec c0 = av.close(fs); // c0 is the row index vec
fs.blockForPending();
Frame ff = new Frame(new String[]{"rownames"}, new Vec[]{c0});
Frame fr2 = new Slice(c2, this).doAll(c2.length,ff)
.outputFrame(names(c2), domains(c2));
Keyed.remove(c0._key);
Keyed.remove(av._key);
ff.delete();
return fr2;
}
Frame frows = (Frame)orows;
// It's a compatible Vec; use it as boolean selector.
// Build column names for the result.
Vec [] vecs = new Vec[c2.length+1];
String [] names = new String[c2.length+1];
for(int i = 0; i < c2.length; ++i){
vecs[i] = _vecs[c2[i]];
names[i] = _names[c2[i]];
}
vecs[c2.length] = frows.anyVec();
names[c2.length] = "predicate";
Frame ff = new Frame(names, vecs);
return new DeepSelect().doAll(c2.length,ff).outputFrame(names(c2),domains(c2));
}
// Slice and return in the form of new chunks.
private static class Slice extends MRTask<Slice> {
final Frame _base; // the base frame to slice from
final int[] _cols;
Slice(int[] cols, Frame base) { _cols = cols; _base = base; }
@Override public void map(Chunk[] ix, NewChunk[] ncs) {
final Vec[] vecs = new Vec[_cols.length];
final Vec anyv = _base.anyVec();
final long nrow = anyv.length();
long r = ix[0].at8(0);
int last_ci = anyv.elem2ChunkIdx(r<nrow?r:0); // memoize the last chunk index
long last_c0 = anyv._espc[last_ci]; // ... last chunk start
long last_c1 = anyv._espc[last_ci + 1]; // ... last chunk end
Chunk[] last_cs = new Chunk[vecs.length]; // ... last chunks
for (int c = 0; c < _cols.length; c++) {
vecs[c] = _base.vecs()[_cols[c]];
last_cs[c] = vecs[c].chunkForChunkIdx(last_ci);
}
for (int i = 0; i < ix[0]._len; i++) {
// select one row
r = ix[0].at8(i); // next row to select
if (r < 0) continue;
if (r >= nrow) {
for (int c = 0; c < vecs.length; c++) ncs[c].addNum(Double.NaN);
} else {
if (r < last_c0 || r >= last_c1) {
last_ci = anyv.elem2ChunkIdx(r);
last_c0 = anyv._espc[last_ci];
last_c1 = anyv._espc[last_ci + 1];
for (int c = 0; c < vecs.length; c++)
last_cs[c] = vecs[c].chunkForChunkIdx(last_ci);
}
for (int c = 0; c < vecs.length; c++)
if( vecs[c].isUUID() ) ncs[c].addUUID(last_cs[c], r);
else if( vecs[c].isString() ) ncs[c].addStr(last_cs[c],r);
else ncs[c].addNum (last_cs[c].at_abs(r));
}
}
}
}
// Convert first 100 rows to a 2-d table
@Override public String toString( ) { return toString(0,20); }
// Convert len rows starting at off to a 2-d ascii table
public String toString( long off, int len ) {
if( off > numRows() ) off = numRows();
if( off+len > numRows() ) len = (int)(numRows()-off);
String[] rowHeaders = new String[len+5];
rowHeaders[0] = "min";
rowHeaders[1] = "mean";
rowHeaders[2] = "stddev";
rowHeaders[3] = "max";
rowHeaders[4] = "missing";
for( int i=0; i<len; i++ ) rowHeaders[i+5]=""+(off+i);
final int ncols = numCols();
final Vec[] vecs = vecs();
String[] coltypes = new String[ncols];
String[][] strCells = new String[len+5][ncols];
double[][] dblCells = new double[len+5][ncols];
for( int i=0; i<ncols; i++ ) {
Vec vec = vecs[i];
dblCells[0][i] = vec.min();
dblCells[1][i] = vec.mean();
dblCells[2][i] = vec.sigma();
dblCells[3][i] = vec.max();
dblCells[4][i] = vec.naCnt();
switch( vec.get_type() ) {
case Vec.T_BAD:
coltypes[i] = "string";
for( int j=0; j<len; j++ ) { strCells[j+5][i] = null; dblCells[j+5][i] = TwoDimTable.emptyDouble; }
break;
case Vec.T_STR :
coltypes[i] = "string";
ValueString vstr = new ValueString();
for( int j=0; j<len; j++ ) { strCells[j+5][i] = vec.isNA(off+j) ? "" : vec.atStr(vstr,off+j).toString(); dblCells[j+5][i] = TwoDimTable.emptyDouble; }
break;
case Vec.T_ENUM:
coltypes[i] = "string";
for( int j=0; j<len; j++ ) { strCells[j+5][i] = vec.isNA(off+j) ? "" : vec.factor(vec.at8(off+j)); dblCells[j+5][i] = TwoDimTable.emptyDouble; }
break;
case Vec.T_TIME:
case Vec.T_TIME+1:
case Vec.T_TIME+2:
coltypes[i] = "string";
DateTimeFormatter fmt = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
for( int j=0; j<len; j++ ) { strCells[j+5][i] = fmt.print(vec.at8(off+j)); dblCells[j+5][i] = TwoDimTable.emptyDouble; }
break;
case Vec.T_NUM:
coltypes[i] = vec.isInt() ? "long" : "double";
for( int j=0; j<len; j++ ) { dblCells[j+5][i] = vec.isNA(off+j) ? TwoDimTable.emptyDouble : vec.at(off + j); strCells[j+5][i] = null; }
break;
case Vec.T_UUID:
throw H2O.unimpl();
default:
System.err.println("bad vector type during debug print: "+vec.get_type());
throw H2O.fail();
}
}
return new TwoDimTable("Frame "+_key,numRows()+" rows and "+numCols()+" cols",rowHeaders,_names,coltypes,null, "", strCells, dblCells).toString();
}
// Bulk (expensive) copy from 2nd cols into 1st cols.
// Sliced by the given cols & rows
private static class DeepSlice extends MRTask<DeepSlice> {
final int _cols[];
final long _rows[];
final byte _isInt[];
DeepSlice( long rows[], int cols[], Vec vecs[] ) {
_cols=cols;
_rows=rows;
_isInt = new byte[cols.length];
for( int i=0; i<cols.length; i++ )
_isInt[i] = (byte)(vecs[cols[i]].isInt() ? 1 : 0);
}
@Override public boolean logVerbose() { return false; }
@Override public void map( Chunk chks[], NewChunk nchks[] ) {
long rstart = chks[0]._start;
int rlen = chks[0]._len; // Total row count
int rx = 0; // Which row to in/ex-clude
int rlo = 0; // Lo/Hi for this block of rows
int rhi = rlen;
while (true) { // Still got rows to include?
if (_rows != null) { // Got a row selector?
if (rx >= _rows.length) break; // All done with row selections
long r = _rows[rx++];// Next row selector
if (r < rstart) continue;
rlo = (int) (r - rstart);
rhi = rlo + 1; // Stop at the next row
while (rx < _rows.length && (_rows[rx] - rstart) == rhi && rhi < rlen) {
rx++;
rhi++; // Grab sequential rows
}
}
// Process this next set of rows
// For all cols in the new set
for (int i = 0; i < _cols.length; i++) {
Chunk oc = chks[_cols[i]];
NewChunk nc = nchks[i];
if (_isInt[i] == 1) { // Slice on integer columns
for (int j = rlo; j < rhi; j++)
if (oc._vec.isUUID()) nc.addUUID(oc, j);
else if (oc.isNA(j)) nc.addNA();
else nc.addNum(oc.at8(j), 0);
} else if (oc._vec.isString()) {
for (int j = rlo; j < rhi; j++)
nc.addStr(oc.atStr(new ValueString(), j));
} else {// Slice on double columns
for (int j = rlo; j < rhi; j++)
nc.addNum(oc.atd(j));
}
}
rlo = rhi;
if (_rows == null) break;
}
}
}
/** Create a copy of the input Frame and return that copied Frame. All Vecs
* in this are copied in parallel. Caller mut do the DKV.put
* @param keyName Key for resulting frame. If null, no key will be given.
* @return The fresh copy of fr. */
public Frame deepCopy(String keyName) {
DoCopyFrame t = new DoCopyFrame(this.vecs()).doAll(this);
return keyName==null ? new Frame(names(),t._vecs) : new Frame(Key.make(keyName),names(),t._vecs);
}
// _vecs put into kv store already
private class DoCopyFrame extends MRTask<DoCopyFrame> {
final Vec[] _vecs;
DoCopyFrame(Vec[] vecs) {
_vecs = new Vec[vecs.length];
for(int i=0;i<vecs.length;++i)
_vecs[i] = new Vec(vecs[i].group().addVec(),vecs[i]._espc.clone(), vecs[i].domain(), vecs[i]._type);
}
@Override public void map(Chunk[] cs) {
int i=0;
for(Chunk c: cs) {
Chunk c2 = (Chunk)c.clone();
c2._vec=null;
c2._start=-1;
c2._cidx=-1;
c2._mem = c2._mem.clone();
DKV.put(_vecs[i++].chunkKey(c.cidx()), c2, _fs);
}
}
@Override public void postGlobal() { for( Vec _vec : _vecs ) DKV.put(_vec); }
}
/**
* Last column is a bit vec indicating whether or not to take the row.
*/
private static class DeepSelect extends MRTask<DeepSelect> {
@Override public void map( Chunk chks[], NewChunk nchks[] ) {
Chunk pred = chks[chks.length-1];
for(int i = 0; i < pred._len; ++i) {
if( pred.atd(i) != 0 && !pred.isNA(i) ) {
for( int j = 0; j < chks.length - 1; j++ ) {
Chunk chk = chks[j];
if( chk.isNA(i) ) nchks[j].addNA();
else if( chk instanceof C16Chunk ) nchks[j].addUUID(chk, i);
else if(chk instanceof CStrChunk) nchks[j].addStr((chk.atStr(new ValueString(), i)));
else if( chk.hasFloat() ) nchks[j].addNum(chk.atd(i));
else nchks[j].addNum(chk.at8(i),0);
}
}
}
}
}
private String[][] domains(int [] cols){
Vec[] vecs = vecs();
String[][] res = new String[cols.length][];
for(int i = 0; i < cols.length; ++i)
res[i] = vecs[cols[i]].domain();
return res;
}
private String [] names(int [] cols){
if(_names == null)return null;
String [] res = new String[cols.length];
for(int i = 0; i < cols.length; ++i)
res[i] = _names[cols[i]];
return res;
}
/** Return Frame 'f' if 'f' is compatible with 'this', else return a new
* Frame compatible with 'this' and a copy of 'f's data otherwise. Note
* that this can, in the worst case, copy all of {@code f}s' data.
* @return {@code f}'s data in a Frame that is compatible with {@code this}. */
public Frame makeCompatible( Frame f) {
// Small data frames are always "compatible"
if (anyVec() == null) // Or it is small
return f; // Then must be compatible
// Same VectorGroup is also compatible
Vec v1 = anyVec();
Vec v2 = f.anyVec();
if(v1.length() != v2.length())
throw new IllegalArgumentException("Can not make vectors of different length compatible!");
if (v2 == null || v1.checkCompatible(v2))
return f;
// Ok, here make some new Vecs with compatible layout
Key k = Key.make();
H2O.submitTask(new RebalanceDataSet(this, f, k)).join();
Frame f2 = (Frame)k.get();
DKV.remove(k);
return f2;
}
/** Convert this Frame to a CSV (in an {@link InputStream}), that optionally
* is compatible with R 3.1's recent change to read.csv()'s behavior.
* @return An InputStream containing this Frame as a CSV */
public InputStream toCSV(boolean headers, boolean hex_string) {
return new CSVStream(headers, hex_string);
}
private class CSVStream extends InputStream {
private final boolean _hex_string;
byte[] _line;
int _position;
long _row;
CSVStream(boolean headers, boolean hex_string) {
_hex_string = hex_string;
StringBuilder sb = new StringBuilder();
Vec vs[] = vecs();
if( headers ) {
sb.append('"').append(_names[0]).append('"');
for(int i = 1; i < vs.length; i++)
sb.append(',').append('"').append(_names[i]).append('"');
sb.append('\n');
}
_line = sb.toString().getBytes();
}
@Override public int available() throws IOException {
if(_position == _line.length) {
if(_row == numRows())
return 0;
StringBuilder sb = new StringBuilder();
Vec vs[] = vecs();
for( int i = 0; i < vs.length; i++ ) {
if(i > 0) sb.append(',');
if(!vs[i].isNA(_row)) {
if( vs[i].isEnum() ) sb.append('"').append(vs[i].factor(vs[i].at8(_row))).append('"');
else if( vs[i].isUUID() ) sb.append(PrettyPrint.UUID(vs[i].at16l(_row), vs[i].at16h(_row)));
else if( vs[i].isInt() ) sb.append(vs[i].at8(_row));
else if (vs[i].isString()) sb.append('"').append(vs[i].atStr(new ValueString(), _row)).append('"');
else {
double d = vs[i].at(_row);
// R 3.1 unfortunately changed the behavior of read.csv().
// (Really type.convert()).
// Numeric values with too much precision now trigger a type conversion in R 3.1 into a factor.
// See these discussions:
String s = _hex_string ? Double.toHexString(d) : Double.toString(d);
sb.append(s);
}
}
}
sb.append('\n');
_line = sb.toString().getBytes();
_position = 0;
_row++;
}
return _line.length - _position;
}
@Override public void close() throws IOException {
super.close();
_line = null;
}
@Override public int read() throws IOException {
return available() == 0 ? -1 : _line[_position++];
}
@Override public int read(byte[] b, int off, int len) throws IOException {
int n = available();
if(n > 0) {
n = Math.min(n, len);
System.arraycopy(_line, _position, b, off, n);
_position += n;
}
return n;
}
}
}
|
package MainClasses;
import java.io.File;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
/**
*
* @author Samosad
*/
public class ParseXML {
// Sorry Artem, but this is bullshit =)
// static NodeList list;
// public static void Inicialize () throws ParserConfigurationException, SAXException, IOException{
// File xmlFile = new File("Subjects.xml");
// DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
// DocumentBuilder db = dbf.newDocumentBuilder();
// Document doc = db.parse(xmlFile);
// list = doc.getElementsByTagName("Subjects");
// public static void GetSubjectInformation (){
// for (int i = 0;i<list.getLength();i++) {
// Node node = list.item(i);
public static void scanXml(List<Subject> subjectList) {
try {
File file = new File("src/MainClasses/Subjects.xml");
//File file = new File("C:/Subjects.xml");
DocumentBuilder dBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = dBuilder.parse(file);
if (doc.hasChildNodes()) {
scanNode(doc.getChildNodes(), subjectList);
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
private static void scanNode(NodeList nodeList, List<Subject> subjectList) {
Subject subj = new Subject();
for (int count = 0; count < nodeList.getLength(); count++) {
Node tempNode = nodeList.item(count);
if ("Subject".equals(tempNode.getNodeName()))
subj = new Subject();
// make sure it's element node.
if (tempNode.getNodeType() == Node.ELEMENT_NODE) {
// get node name and value
if ("subjectName".equals(tempNode.getNodeName())) {
subj.setSubjectName(tempNode.getTextContent());
}
if ("lecturerName".equals(tempNode.getNodeName())) {
subj.setLecturerName(tempNode.getTextContent());
}
if ("audience".equals(tempNode.getNodeName())) {
subj.setAudience(Integer.parseInt(tempNode.getTextContent()));
}
if ("housing".equals(tempNode.getNodeName())) {
subj.setHousing(Integer.parseInt(tempNode.getTextContent()));
}
if ("numberInTable".equals(tempNode.getNodeName())) {
subj.setNumberInTable(Integer.parseInt(tempNode.getTextContent()));
}
if ("dayOfWeek".equals(tempNode.getNodeName())) {
if ("Monday".equals(tempNode.getTextContent()))
subj.setDay(DaysOfWeek.MONDAY);
if ("Tuesday".equals(tempNode.getTextContent()))
subj.setDay(DaysOfWeek.TUESDAY);
if ("Wednesday".equals(tempNode.getTextContent()))
subj.setDay(DaysOfWeek.WEDNESDAY);
if ("Thursday".equals(tempNode.getTextContent()))
subj.setDay(DaysOfWeek.THURSDAY);
if ("Friday".equals(tempNode.getTextContent()))
subj.setDay(DaysOfWeek.FRIDAY);
if ("Saturday".equals(tempNode.getTextContent()))
subj.setDay(DaysOfWeek.SATURDEY);
}
if ("dayOfWeek".equals(tempNode.getNodeName()))
subjectList.add(subj);
if (tempNode.hasChildNodes()) {
// loop again if has child nodes
scanNode(tempNode.getChildNodes(), subjectList);
}
}
}
}
}
|
package com.flaiker.reaktio;
import com.badlogic.gdx.backends.iosrobovm.IOSApplication;
import com.badlogic.gdx.backends.iosrobovm.IOSApplicationConfiguration;
import org.robovm.apple.foundation.NSAutoreleasePool;
import org.robovm.apple.uikit.UIApplication;
public class IOSLauncher extends IOSApplication.Delegate {
@Override
protected IOSApplication createApplication() {
IOSApplicationConfiguration config = new IOSApplicationConfiguration();
config.orientationPortrait = true;
config.orientationLandscape = false;
return new IOSApplication(new Reaktio(), config);
}
public static void main(String[] argv) {
NSAutoreleasePool pool = new NSAutoreleasePool();
UIApplication.main(argv, null, IOSLauncher.class);
pool.close();
}
}
|
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class MigrateMatser implements Runnable{
private ProcessManager mManager;
private ServerSocket mServer;
public MigrateMatser(ProcessManager pm, ServerSocket s) {
mManager = pm;
mServer = s;
}
@Override
public void run() {
while(true) {
try {
Socket clientConnect = mServer.accept();
MigrateMasterService eachConnection = new MigrateMasterService(clientConnect);
Thread connectionThread = new Thread(eachConnection);
connectionThread.start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
|
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ServletsTask1 extends HttpServlet
{
private static final long serialVersionUID = -3764767856748158770L;
@Override
public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
{
res.setContentType("text/html");
PrintWriter out= res.getWriter();
out.println("<html>");
out.println("<head><title>Lab 3 Part 1</title></head>");
out.println("<body><form method=\"post\">");
out.println("<h2>Your name</h2>");
out.println("First name: <input type=\"text\" name=\"firstname\"><br>");
out.println("Last name: <input type=\"text\" name=\"lastname\">");
out.println("<h2>Programming languages you know</h2>");
out.println("<input type=\"checkbox\" name=\"java\">Java<br>");
out.println("<input type=\"checkbox\" name=\"c\">C<br>");
out.println("<input type=\"checkbox\" name=\"cpp\">C++<br>");
out.println("<input type=\"checkbox\" name=\"objc\">Objective-C<br>");
out.println("<input type=\"checkbox\" name=\"csharp\">C
out.println("<input type=\"checkbox\" name=\"php\">PHP<br>");
out.println("<input type=\"checkbox\" name=\"perl\">Perl<br>");
out.println("<input type=\"checkbox\" name=\"python\">Python<br>");
out.println("<input type=\"checkbox\" name=\"js\">JavaScript<br>");
out.println("<input type=\"checkbox\" name=\"scala\">Scala<br>");
out.println("<input type=\"checkbox\" name=\"scheme\">Scheme<br>");
out.println("<input type=\"checkbox\" name=\"prolog\">Prolog<br>");
out.println("<input type=\"checkbox\" name=\"otherlang\">Other");
out.println("<h2>Days of the week you can meet</h2>");
out.println("<input type=\"checkbox\" name=\"sun\">Sunday<br>");
out.println("<input type=\"checkbox\" name=\"mon\">Monday<br>");
out.println("<input type=\"checkbox\" name=\"tue\">Tuesday<br>");
out.println("<input type=\"checkbox\" name=\"wed\">Wednesday<br>");
out.println("<input type=\"checkbox\" name=\"thu\">Thursday<br>");
out.println("<input type=\"checkbox\" name=\"fri\">Friday<br>");
out.println("<input type=\"checkbox\" name=\"sat\">Saturday");
out.println("<h2>Your favorite color</h2>");
out.println("<input type=\"radio\" name=\"red\">Red<br>");
out.println("<input type=\"radio\" name=\"blue\">Blue<br>");
out.println("<input type=\"radio\" name=\"green\">Green<br>");
out.println("<input type=\"radio\" name=\"yellow\">Yellow<br>");
out.println("<input type=\"radio\" name=\"orange\">Orange<br>");
out.println("<input type=\"radio\" name=\"purple\">Purple<br>");
out.println("<input type=\"radio\" name=\"pink\">Pink<br>");
out.println("<input type=\"radio\" name=\"brown\">Brown<br>");
out.println("<input type=\"radio\" name=\"black\">Black<br>");
out.println("<input type=\"radio\" name=\"white\">White<br>");
out.println("<input type=\"radio\" name=\"gray\">Gray<br>");
out.println("<input type=\"radio\" name=\"othercolor\">Other");
out.println("<input type=\"submit\" value=\"Submit\">");
out.println("</form></body>");
out.println("</html>");
}
}
|
public abstract class ShipAttribute {
private String name;
private int value;
}
|
package verification.platu.stategraph;
import java.io.*;
import java.util.*;
import lpn.parser.LhpnFile;
import verification.platu.common.PlatuObj;
import verification.platu.lpn.DualHashMap;
import verification.platu.lpn.LPN;
import verification.platu.lpn.VarSet;
/**
* State
* @author Administrator
*/
public class State extends PlatuObj {
public static int[] counts = new int[15];
protected int[] marking;
protected int[] vector;
protected boolean[] tranVector; // indicator vector to record whether each transition is enabled or not.
private int hashVal = 0;
private LhpnFile lpnModel = null;
private int index;
private boolean localEnabledOnly;
protected boolean failure = false;
@Override
public String toString() {
// String ret=Arrays.toString(marking)+""+
// Arrays.toString(vector);
// return "["+ret.replace("[", "{").replace("]", "}")+"]";
return this.print();
}
public State(final LhpnFile lpn, int[] new_marking, int[] new_vector, boolean[] new_isTranEnabled) {
this.lpnModel = lpn;
this.marking = new_marking;
this.vector = new_vector;
this.tranVector = new_isTranEnabled;
if (marking == null || vector == null || tranVector == null) {
new NullPointerException().printStackTrace();
}
//Arrays.sort(this.marking);
this.index = 0;
localEnabledOnly = false;
counts[0]++;
}
public State(State other) {
if (other == null) {
new NullPointerException().printStackTrace();
}
this.lpnModel = other.lpnModel;
this.marking = new int[other.marking.length];
System.arraycopy(other.marking, 0, this.marking, 0, other.marking.length);
this.vector = new int[other.vector.length];
System.arraycopy(other.vector, 0, this.vector, 0, other.vector.length);
this.tranVector = new boolean[other.tranVector.length];
System.arraycopy(other.tranVector, 0, this.tranVector, 0, other.tranVector.length);
// this.hashVal = other.hashVal;
this.hashVal = 0;
this.index = other.index;
this.localEnabledOnly = other.localEnabledOnly;
counts[0]++;
}
// TODO: (temp) Two Unused constructors, State() and State(Object otherState)
// public State() {
// this.marking = new int[0];
// this.vector = new int[0];//EMPTY_VECTOR.clone();
// this.hashVal = 0;
// this.index = 0;
// localEnabledOnly = false;
// counts[0]++;
//static PrintStream out = System.out;
// public State(Object otherState) {
// State other = (State) otherState;
// if (other == null) {
// new NullPointerException().printStackTrace();
// this.lpnModel = other.lpnModel;
// this.marking = new int[other.marking.length];
// System.arraycopy(other.marking, 0, this.marking, 0, other.marking.length);
// // this.vector = other.getVector().clone();
// this.vector = new int[other.vector.length];
// System.arraycopy(other.vector, 0, this.vector, 0, other.vector.length);
// this.hashVal = other.hashVal;
// this.index = other.index;
// this.localEnabledOnly = other.localEnabledOnly;
// counts[0]++;
public void setLpn(final LhpnFile thisLpn) {
this.lpnModel = thisLpn;
}
public LhpnFile getLpn() {
return this.lpnModel;
}
public void setLabel(String lbl) {
}
public String getLabel() {
return null;
}
/**
* This method returns the boolean array representing the status (enabled/disabled) of each transition in an LPN.
* @return
*/
public boolean[] getTranVector() {
return tranVector;
}
public void setIndex(int newIndex) {
this.index = newIndex;
}
public int getIndex() {
return this.index;
}
public boolean hasNonLocalEnabled() {
return this.localEnabledOnly;
}
public void hasNonLocalEnabled(boolean nonLocalEnabled) {
this.localEnabledOnly = nonLocalEnabled;
}
public boolean isFailure() {
return false;// getType() != getType().NORMAL || getType() !=
// getType().TERMINAL;
}
public static long tSum = 0;
@Override
public State clone() {
counts[6]++;
State s = new State(this);
return s;
}
public String print() {
DualHashMap<String, Integer> VarIndexMap = this.lpnModel.getVarIndexMap();
String message = "Marking: [";
for (int i : marking) {
message += i + ",";
}
message += "]\n" + "Vector: [";
for (int i = 0; i < vector.length; i++) {
message += VarIndexMap.getKey(i) + "=>" + vector[i]+", ";
}
message += "]\n" + "Transition Vector: [";
for (int i = 0; i < tranVector.length; i++) {
message += tranVector[i] + ",";
}
message += "]\n";
return message;
}
@Override
public int hashCode() {
if(hashVal == 0){
final int prime = 31;
int result = 1;
result = prime * result + ((lpnModel == null) ? 0 : lpnModel.getLabel().hashCode());
result = prime * result + Arrays.hashCode(marking);
result = prime * result + Arrays.hashCode(vector);
result = prime * result + Arrays.hashCode(tranVector);
hashVal = result;
}
return hashVal;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
State other = (State) obj;
if (lpnModel == null) {
if (other.lpnModel != null)
return false;
}
else if (!lpnModel.equals(other.lpnModel))
return false;
if (!Arrays.equals(marking, other.marking))
return false;
if (!Arrays.equals(vector, other.vector))
return false;
if (!Arrays.equals(tranVector, other.tranVector))
return false;
return true;
}
public void print(DualHashMap<String, Integer> VarIndexMap) {
System.out.print("Marking: [");
for (int i : marking) {
System.out.print(i + ",");
}
System.out.println("]");
System.out.print("Vector: [");
for (int i = 0; i < vector.length; i++) {
System.out.print(VarIndexMap.getKey(i) + "=>" + vector[i]+", ");
}
System.out.println("]");
System.out.print("Transition vector: [");
for (boolean bool : tranVector) {
System.out.print(bool + ",");
}
System.out.println("]");
}
/**
* @return the marking
*/
public int[] getMarking() {
return marking;
}
public void setMarking(int[] newMarking) {
marking = newMarking;
}
/**
* @return the vector
*/
public int[] getVector() {
// new Exception("StateVector getVector(): "+s).printStackTrace();
return vector;
}
public HashMap<String, Integer> getOutVector(VarSet outputs, DualHashMap<String, Integer> VarIndexMap) {
HashMap<String, Integer> outVec = new HashMap<String, Integer>();
for(int i = 0; i < vector.length; i++) {
String var = VarIndexMap.getKey(i);
if(outputs.contains(var) == true)
outVec.put(var, vector[i]);
}
return outVec;
}
public State getLocalState() {
//VarSet lpnOutputs = this.lpnModel.getOutputs();
//VarSet lpnInternals = this.lpnModel.getInternals();
Set<String> lpnOutputs = this.lpnModel.getAllOutputs().keySet();
Set<String> lpnInternals = this.lpnModel.getAllInternals().keySet();
DualHashMap<String,Integer> varIndexMap = this.lpnModel.getVarIndexMap();
int[] outVec = new int[this.vector.length];
/*
* Create a copy of the vector of mState such that the values of inputs are set to 0
* and the values for outputs/internal variables remain the same.
*/
for(int i = 0; i < this.vector.length; i++) {
String curVar = varIndexMap.getKey(i);
if(lpnOutputs.contains(curVar) ==true || lpnInternals.contains(curVar)==true)
outVec[i] = this.vector[i];
else
outVec[i] = 0;
}
// TODO: (??) Need to create outTranVector as well?
return new State(this.lpnModel, this.marking, outVec, this.tranVector);
}
/**
* @return the enabledSet
*/
public int[] getEnabledSet() {
return null;// enabledSet;
}
public String getEnabledSetString() {
String ret = "";
// for (int i : enabledSet) {
// ret += i + ", ";
return ret;
}
/**
* Return a new state if the newVector leads to a new state from this state; otherwise return null.
* @param newVector
* @param VarIndexMap
* @return
*/
public State update(StateGraph SG,HashMap<String, Integer> newVector, DualHashMap<String, Integer> VarIndexMap) {
int[] newStateVector = new int[this.vector.length];
boolean newState = false;
for(int index = 0; index < vector.length; index++) {
String var = VarIndexMap.getKey(index);
int this_val = this.vector[index];
Integer newVal = newVector.get(var);
if(newVal != null) {
if(this_val != newVal) {
newState = true;
newStateVector[index] = newVal;
}
else
newStateVector[index] = this.vector[index];
}
else
newStateVector[index] = this.vector[index];
}
boolean[] newEnabledTranVector = SG.updateEnabledTranVector(this.getTranVector(), this.marking, newStateVector, null);
if(newState == true)
return new State(this.lpnModel, this.marking, newStateVector, newEnabledTranVector);
return null;
}
/**
* Return a new state if the newVector leads to a new state from this state; otherwise return null.
* States considered here include a vector indicating enabled/disabled state of each transition.
* @param newVector
* @param VarIndexMap
* @return
*/
public State update(HashMap<String, Integer> newVector, DualHashMap<String, Integer> VarIndexMap,
boolean[] newTranVector) {
int[] newStateVector = new int[this.vector.length];
boolean newState = false;
for(int index = 0; index < vector.length; index++) {
String var = VarIndexMap.getKey(index);
int this_val = this.vector[index];
Integer newVal = newVector.get(var);
if(newVal != null) {
if(this_val != newVal) {
newState = true;
newStateVector[index] = newVal;
}
else
newStateVector[index] = this.vector[index];
}
else
newStateVector[index] = this.vector[index];
}
if (!this.tranVector.equals(newTranVector))
newState = true;
if(newState == true)
return new State(this.lpnModel, this.marking, newStateVector, newTranVector);
return null;
}
static public void printUsageStats() {
System.out.printf("%-20s %11s\n", "State", counts[0]);
System.out.printf("\t%-20s %11s\n", "State", counts[10]);
// System.out.printf("\t%-20s %11s\n", "State", counts[11]);
// System.out.printf("\t%-20s %11s\n", "merge", counts[1]);
System.out.printf("\t%-20s %11s\n", "update", counts[2]);
// System.out.printf("\t%-20s %11s\n", "compose", counts[3]);
System.out.printf("\t%-20s %11s\n", "equals", counts[4]);
// System.out.printf("\t%-20s %11s\n", "conjunction", counts[5]);
System.out.printf("\t%-20s %11s\n", "clone", counts[6]);
System.out.printf("\t%-20s %11s\n", "hashCode", counts[7]);
// System.out.printf("\t%-20s %11s\n", "resembles", counts[8]);
// System.out.printf("\t%-20s %11s\n", "digest", counts[9]);
}
//TODO: (original) try database serialization
public File serialize(String filename) throws FileNotFoundException,
IOException {
File f = new File(filename);
ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream(f));
os.writeObject(this);
os.close();
return f;
}
public static State deserialize(String filename)
throws FileNotFoundException, IOException, ClassNotFoundException {
File f = new File(filename);
ObjectInputStream os = new ObjectInputStream(new FileInputStream(f));
State zone = (State) os.readObject();
os.close();
return zone;
}
public static State deserialize(File f) throws FileNotFoundException,
IOException, ClassNotFoundException {
ObjectInputStream os = new ObjectInputStream(new FileInputStream(f));
State zone = (State) os.readObject();
os.close();
return zone;
}
public boolean failure(){
return this.failure;
}
public void setFailure(){
this.failure = true;
}
public void print(LhpnFile lpn) {
System.out.print("Marking: [");
// for (int i : marking) {
// System.out.print(i + ",");
for (int i=0; i < marking.length; i++) {
System.out.print(lpn.getPlaceList().clone()[i] + "=" + marking[i] + ", ");
}
System.out.println("]");
System.out.print("Vector: [");
for (int i = 0; i < vector.length; i++) {
System.out.print(lpn.getVarIndexMap().getKey(i) + "=>" + vector[i]+", ");
}
System.out.println("]");
System.out.print("Transition vector: [");
for (boolean bool : tranVector) {
System.out.print(bool + ",");
}
System.out.println("]");
}
}
|
package generics;
import java.util.ArrayList;
import java.util.List;
class Being{}
class Animal extends Being{}
class Cat extends Animal{}
class TypeTransformInJava {
void testAnimals1(List<Animal> list){ }
void testAnimals2(List<? extends Animal> list){ }
void testAnimals3(List<? super Animal> list){ }
void testAnimalA(Animal animal){}
void main(){
List<Being> beings = new ArrayList<>();
List<Animal> animals = new ArrayList<>();
List<Cat> cats = new ArrayList<>();
// testAnimals1(beings);
testAnimals1(animals);
// testAnimals1(cats);
// testAnimals2(beings);
testAnimals2(animals);
testAnimals2(cats);
testAnimals3(beings);
testAnimals3(animals);
// testAnimals3(cats);
// testAnimalA(new Being());
testAnimalA(new Animal());
testAnimalA(new Cat());
}
}
|
package com.liferay.lms;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import com.liferay.counter.service.CounterLocalServiceUtil;
import com.liferay.lms.course.diploma.CourseDiploma;
import com.liferay.lms.course.diploma.CourseDiplomaRegistry;
import com.liferay.lms.learningactivity.courseeval.CourseEval;
import com.liferay.lms.learningactivity.courseeval.CourseEvalRegistry;
import com.liferay.lms.model.AsynchronousProcessAudit;
import com.liferay.lms.model.Course;
import com.liferay.lms.model.CourseCompetence;
import com.liferay.lms.model.CourseType;
import com.liferay.lms.model.CourseTypeFactory;
import com.liferay.lms.model.CourseTypeI;
import com.liferay.lms.model.LearningActivity;
import com.liferay.lms.model.LmsPrefs;
import com.liferay.lms.service.AsynchronousProcessAuditLocalServiceUtil;
import com.liferay.lms.service.CourseCompetenceLocalServiceUtil;
import com.liferay.lms.service.CourseLocalServiceUtil;
import com.liferay.lms.service.CourseTypeLocalServiceUtil;
import com.liferay.lms.service.LearningActivityLocalServiceUtil;
import com.liferay.lms.service.LmsPrefsLocalServiceUtil;
import com.liferay.lms.util.LmsConstant;
import com.liferay.portal.DuplicateGroupException;
import com.liferay.portal.kernel.exception.PortalException;
import com.liferay.portal.kernel.exception.SystemException;
import com.liferay.portal.kernel.json.JSONFactoryUtil;
import com.liferay.portal.kernel.json.JSONObject;
import com.liferay.portal.kernel.language.LanguageUtil;
import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import com.liferay.portal.kernel.messaging.Message;
import com.liferay.portal.kernel.messaging.MessageBusUtil;
import com.liferay.portal.kernel.messaging.MessageListener;
import com.liferay.portal.kernel.messaging.MessageListenerException;
import com.liferay.portal.kernel.util.StringPool;
import com.liferay.portal.kernel.util.Validator;
import com.liferay.portal.model.Group;
import com.liferay.portal.model.ResourceConstants;
import com.liferay.portal.model.ResourcePermission;
import com.liferay.portal.model.Role;
import com.liferay.portal.model.RoleConstants;
import com.liferay.portal.model.User;
import com.liferay.portal.security.auth.PrincipalThreadLocal;
import com.liferay.portal.security.permission.PermissionChecker;
import com.liferay.portal.security.permission.PermissionCheckerFactoryUtil;
import com.liferay.portal.security.permission.PermissionThreadLocal;
import com.liferay.portal.service.GroupLocalServiceUtil;
import com.liferay.portal.service.ResourcePermissionLocalServiceUtil;
import com.liferay.portal.service.RoleLocalServiceUtil;
import com.liferay.portal.service.ServiceContext;
import com.liferay.portal.service.UserGroupRoleLocalServiceUtil;
import com.liferay.portal.service.UserLocalServiceUtil;
import com.liferay.portal.theme.ThemeDisplay;
import com.liferay.portal.util.PortalUtil;
import com.liferay.portlet.announcements.model.AnnouncementsEntry;
import com.liferay.portlet.announcements.model.AnnouncementsFlagConstants;
import com.liferay.portlet.announcements.service.AnnouncementsEntryServiceUtil;
import com.liferay.portlet.announcements.service.AnnouncementsFlagLocalServiceUtil;
import com.liferay.portlet.asset.model.AssetEntry;
import com.liferay.portlet.asset.service.AssetEntryLocalServiceUtil;
import com.liferay.portlet.documentlibrary.model.DLFolderConstants;
import com.liferay.portlet.messageboards.model.MBCategory;
import com.liferay.portlet.messageboards.service.MBCategoryLocalServiceUtil;
import com.liferay.util.CourseCopyUtil;
/*import com.tls.liferaylms.mail.model.MailJob;
import com.tls.liferaylms.mail.service.MailJobLocalServiceUtil;
import com.tls.liferaylms.util.MailConstants;*/
public class CloneCourse extends CourseCopyUtil implements MessageListener {
private static Log log = LogFactoryUtil.getLog(CloneCourse.class);
static String evalclassName="com.liferay.lms.learningactivity.courseeval.PonderatedCourseEval";
long groupId;
String newCourseName;
ThemeDisplay themeDisplay;
ServiceContext serviceContext;
Date startDate;
Date endDate;
Date startExecutionDate;
Date endExecutionDate;
boolean visible;
boolean includeTeacher;
AsynchronousProcessAudit process = null;
String statusMessage ="";
boolean error= false;
boolean cloneForum;
boolean cloneDocuments;
boolean cloneModuleClassification;
boolean cloneActivityClassificationTypes;
public CloneCourse(long groupId, String newCourseName, ThemeDisplay themeDisplay, Date startDate, Date endDate, boolean cloneForum, boolean cloneDocuments,
boolean cloneModuleClassification, boolean cloneActivityClassificationTypes, ServiceContext serviceContext) {
super();
this.groupId = groupId;
this.newCourseName = newCourseName;
this.themeDisplay = themeDisplay;
this.startDate = startDate;
this.endDate = endDate;
this.cloneForum = cloneForum;
this.cloneDocuments = cloneDocuments;
this.cloneModuleClassification = cloneModuleClassification;
this.cloneActivityClassificationTypes = cloneActivityClassificationTypes;
this.serviceContext = serviceContext;
}
public CloneCourse() {
}
@Override
public void receive(Message message) throws MessageListenerException {
try {
long processId = message.getLong("asynchronousProcessAuditId");
process = AsynchronousProcessAuditLocalServiceUtil.fetchAsynchronousProcessAudit(processId);
process = AsynchronousProcessAuditLocalServiceUtil.updateProcessStatus(process, null, LmsConstant.STATUS_IN_PROGRESS, "");
statusMessage ="";
error = false;
this.groupId = message.getLong("groupId");
this.newCourseName = message.getString("newCourseName");
this.startDate = (Date)message.get("startDate");
this.endDate = (Date)message.get("endDate");
this.startExecutionDate = (Date) message.get("startExecutionDate");
this.endExecutionDate = (Date) message.get("endExecutionDate");
this.serviceContext = (ServiceContext)message.get("serviceContext");
this.themeDisplay = (ThemeDisplay)message.get("themeDisplay");
this.visible = message.getBoolean("visible");
this.includeTeacher = message.getBoolean("includeTeacher");
this.cloneForum = message.getBoolean("cloneForum");
this.cloneDocuments = message.getBoolean("cloneDocuments");
this.cloneModuleClassification = message.getBoolean("cloneModuleClassification");
this.cloneActivityClassificationTypes = message.getBoolean("cloneActivityClassificationTypes");
Role adminRole = RoleLocalServiceUtil.getRole(themeDisplay.getCompanyId(),"Administrator");
List<User> adminUsers = UserLocalServiceUtil.getRoleUsers(adminRole.getRoleId());
PrincipalThreadLocal.setName(adminUsers.get(0).getUserId());
PermissionChecker permissionChecker =PermissionCheckerFactoryUtil.create(adminUsers.get(0), true);
PermissionThreadLocal.setPermissionChecker(permissionChecker);
doCloneCourse();
} catch (Exception e) {
e.printStackTrace();
}
}
public void doCloneCourse() throws Exception {
log.debug("Course to clone\n........................." + groupId);
Group group = GroupLocalServiceUtil.fetchGroup(groupId);
Course course = CourseLocalServiceUtil.fetchByGroupCreatedId(groupId);
if(log.isDebugEnabled()){
log.debug("Course to clone\n.........................");
log.debug(" + groupId: "+groupId);
log.debug(" + course: "+course.getTitle(themeDisplay.getLocale()));
}
Date today=new Date(System.currentTimeMillis());
String courseTemplate = this.serviceContext.getRequest().getParameter("courseTemplate");
long layoutSetPrototypeId = 0;
if(courseTemplate.indexOf("&")>-1){
layoutSetPrototypeId = Long.parseLong(courseTemplate.split("&")[1]);
}else{
layoutSetPrototypeId = Long.parseLong(courseTemplate);
}
if(log.isDebugEnabled()){
log.debug(" + layoutSetPrototypeId: "+layoutSetPrototypeId);
}
try{
log.debug(" + AssetCategoryIds: "+AssetEntryLocalServiceUtil.getEntry(Course.class.getName(), course.getCourseId()).getCategoryIds().toString());
log.debug(" + AssetCategoryIds Service Context: "+serviceContext.getAssetCategoryIds());
log.debug(" + AssetTagNames: "+AssetEntryLocalServiceUtil.getEntry(Course.class.getName(), course.getCourseId()).getTagNames());
log.debug(" + AssetTagNames Service Context: "+serviceContext.getAssetTagNames());
serviceContext.setAssetCategoryIds(AssetEntryLocalServiceUtil.getEntry(Course.class.getName(), course.getCourseId()).getCategoryIds());
serviceContext.setAssetTagNames(AssetEntryLocalServiceUtil.getEntry(Course.class.getName(), course.getCourseId()).getTagNames());
AssetEntryLocalServiceUtil.validate(course.getGroupCreatedId(), Course.class.getName(), serviceContext.getAssetCategoryIds(), serviceContext.getAssetTagNames());
}catch(Exception e){
serviceContext.setAssetCategoryIds(new long[]{});
//serviceContext.setAssetTagNames(AssetEntryLocalServiceUtil.getEntry(Course.class.getName(), course.getCourseId()).getTags());
}
//Course newCourse = CourseLocalServiceUtil.addCourse(newCourseName, course.getDescription(), "", themeDisplay.getLocale() , today, startDate, endDate, serviceContext, course.getCalificationType());
//when lmsprefs has more than one lmstemplate selected the addcourse above throws an error.
int typeSite = GroupLocalServiceUtil.getGroup(course.getGroupCreatedId()).getType();
Course newCourse = null;
String summary = null;
long courseTypeId = 0;
try{
AssetEntry entry = AssetEntryLocalServiceUtil.getEntry(Course.class.getName(), course.getCourseId());
summary = entry.getSummary(themeDisplay.getLocale());
courseTypeId = entry.getClassTypeId();
newCourse = CourseLocalServiceUtil.addCourse(newCourseName, course.getDescription(themeDisplay.getLocale()),summary
, "", themeDisplay.getLocale(), today, startDate, endDate, layoutSetPrototypeId, typeSite, serviceContext, course.getCalificationType(), (int)course.getMaxusers(),true);
newCourse.setWelcome(course.getWelcome());
newCourse.setWelcomeMsg(course.getWelcomeMsg());
newCourse.setWelcomeSubject(course.getWelcomeSubject());
newCourse.setDeniedInscription(course.isDeniedInscription());
newCourse.setDeniedInscriptionSubject(course.getDeniedInscriptionSubject());
newCourse.setDeniedInscriptionMsg(course.getDeniedInscriptionMsg());
newCourse.setGoodbye(course.getGoodbye());
newCourse.setGoodbyeMsg(course.getGoodbyeMsg());
newCourse.setGoodbyeSubject(course.getGoodbyeSubject());
newCourse.setCourseEvalId(course.getCourseEvalId());
newCourse.setStartDate(startDate);
newCourse.setEndDate(endDate);
newCourse.setExecutionStartDate(startExecutionDate);
newCourse.setExecutionEndDate(endExecutionDate);
StringBuilder extraContent = new StringBuilder();
Course parentcourse = null;
try {
parentcourse = course.getParentCourse();
} catch (SystemException | PortalException e) {
log.debug("Parent course not found");
}
if(Validator.isNotNull(parentcourse) ) {
extraContent.append(LanguageUtil.get(themeDisplay.getLocale(), "course-admin.parent-course"))
.append(StringPool.COLON).append(StringPool.SPACE)
.append(course.getParentCourse().getTitle(themeDisplay.getLocale())).append("<br>");
}
extraContent.append(LanguageUtil.get(themeDisplay.getLocale(), "course.label"))
.append(StringPool.COLON).append(StringPool.SPACE)
.append(course.getTitle(themeDisplay.getLocale()));
extraContent.append("<br>").append(LanguageUtil.get(themeDisplay.getLocale(), "new-course"))
.append(StringPool.COLON).append(StringPool.SPACE)
.append(newCourse.getTitle(themeDisplay.getLocale()));
JSONObject json =JSONFactoryUtil.createJSONObject();
json.put("data", extraContent.toString());
process.setExtraContent(json.toString());
process.setClassPK(newCourse.getCourseId());
process = AsynchronousProcessAuditLocalServiceUtil.updateAsynchronousProcessAudit(process);
} catch(DuplicateGroupException e){
if(log.isDebugEnabled())e.printStackTrace();
process = AsynchronousProcessAuditLocalServiceUtil.updateProcessStatus(process, new Date(), LmsConstant.STATUS_ERROR, e.getMessage());
throw new DuplicateGroupException();
}
copyExpandos (newCourse, course, serviceContext);
List<CourseCompetence> courseCompetences= CourseCompetenceLocalServiceUtil.findBycourseId(course.getCourseId(), false);
for(CourseCompetence courseCompetence:courseCompetences)
{
long courseCompetenceId = CounterLocalServiceUtil.increment(CourseCompetence.class.getName());
CourseCompetence cc = CourseCompetenceLocalServiceUtil.createCourseCompetence(courseCompetenceId);
cc.setCourseId(newCourse.getCourseId());
cc.setCompetenceId(courseCompetence.getCompetenceId());
cc.setCachedModel(courseCompetence.getCondition());
cc.setCondition(courseCompetence.getCondition());
CourseCompetenceLocalServiceUtil.updateCourseCompetence(cc, true);
}
courseCompetences= CourseCompetenceLocalServiceUtil.findBycourseId(course.getCourseId(), true);
CourseCompetence cc=null;
for(CourseCompetence courseCompetence:courseCompetences){
long courseCompetenceId = CounterLocalServiceUtil.increment(CourseCompetence.class.getName());
cc = CourseCompetenceLocalServiceUtil.createCourseCompetence(courseCompetenceId);
cc.setCourseId(newCourse.getCourseId());
cc.setCompetenceId(courseCompetence.getCompetenceId());
cc.setCachedModel(courseCompetence.getCondition());
cc.setCondition(courseCompetence.getCondition());
CourseCompetenceLocalServiceUtil.updateCourseCompetence(cc, true);
}
Group newGroup = GroupLocalServiceUtil.getGroup(newCourse.getGroupCreatedId());
serviceContext.setScopeGroupId(newCourse.getGroupCreatedId());
newCourse.setParentCourseId(course.getParentCourseId());
Role siteMemberRole = RoleLocalServiceUtil.getRole(themeDisplay.getCompanyId(), RoleConstants.SITE_MEMBER);
newCourse.setIcon(course.getIcon());
try{
newCourse = CourseLocalServiceUtil.modCourse(newCourse, summary, courseTypeId, serviceContext, visible);
AssetEntry newEntry = AssetEntryLocalServiceUtil.getEntry(Course.class.getName(),newCourse.getCourseId());
newEntry.setVisible(visible);
newEntry.setSummary(summary);
newEntry.setClassTypeId(courseTypeId);
AssetEntryLocalServiceUtil.updateAssetEntry(newEntry);
newGroup.setName(newCourse.getTitle(themeDisplay.getLocale(), true));
newGroup.setDescription(summary);
GroupLocalServiceUtil.updateGroup(newGroup);
}catch(Exception e){
if(log.isDebugEnabled())e.printStackTrace();
error=true;
statusMessage += e.getMessage() + "\n";
}
newCourse.setUserId(themeDisplay.getUserId());
if(log.isDebugEnabled()){
log.debug("
log.debug(" + to course: "+ newCourse.getTitle(Locale.getDefault()) +", GroupCreatedId: "+newCourse.getGroupCreatedId()+", GroupId: "+newCourse.getGroupId());
}
//Update especific content of diploma (if exists)
CourseDiplomaRegistry cdr = new CourseDiplomaRegistry();
if(cdr!=null){
CourseDiploma courseDiploma = cdr.getCourseDiploma();
if(courseDiploma!=null){
String courseDiplomaError = courseDiploma.copyCourseDiploma(course.getCourseId(), newCourse.getCourseId());
log.debug("****CourseDiplomaError:"+courseDiplomaError);
if(Validator.isNotNull(courseDiplomaError)){
statusMessage += courseDiplomaError + "\n";
error = true;
}
}
}
/**
* METO AL USUARIO CREADOR DEL CURSO COMO PROFESOR
*/
if(includeTeacher){
log.debug(includeTeacher);
LmsPrefs lmsPrefs=LmsPrefsLocalServiceUtil.getLmsPrefs(themeDisplay.getCompanyId());
long teacherRoleId=RoleLocalServiceUtil.getRole(lmsPrefs.getEditorRole()).getRoleId();
UserGroupRoleLocalServiceUtil.addUserGroupRoles(new long[] { themeDisplay.getUserId() }, newCourse.getGroupCreatedId(), teacherRoleId);
if (!GroupLocalServiceUtil.hasUserGroup(themeDisplay.getUserId(), newCourse.getGroupCreatedId())) {
GroupLocalServiceUtil.addUserGroups(themeDisplay.getUserId(), new long[] { newCourse.getGroupCreatedId() });
}
}
CourseLocalServiceUtil.copyModulesAndActivities(themeDisplay.getUserId(), course, newCourse, this.cloneActivityClassificationTypes, true, serviceContext);
CourseEvalRegistry registry = new CourseEvalRegistry();
CourseEval courseEval = registry.getCourseEval(course.getCourseEvalId());
courseEval.cloneCourseEval(course, newCourse);
CourseTypeFactoryRegistry courseTypeFactoryRegistry = new CourseTypeFactoryRegistry();
AssetEntry entry=AssetEntryLocalServiceUtil.getEntry(Course.class.getName(),newCourse.getCourseId());
if(entry.getClassTypeId() > 0){
CourseType courseType = CourseTypeLocalServiceUtil.getCourseType(entry.getClassTypeId());
if(courseType.getClassNameId() > 0){
CourseTypeFactory courseTypeFactory = courseTypeFactoryRegistry.getCourseTypeFactory(courseType.getClassNameId());
if(courseTypeFactory != null){
CourseTypeI courseTypeI = courseTypeFactory.getCourseType(newCourse);
courseTypeI.copyCourse(course, serviceContext);
}
}
}
if(this.cloneForum){
//Categorias y subcategorias del foro
List<MBCategory> listCategories = MBCategoryLocalServiceUtil.getCategories(groupId);
//Si existen las categorias se clonan
if(listCategories!=null && listCategories.size()>0){
if(log.isDebugEnabled()){
log.debug("
}
long newCourseGroupId = newCourse.getGroupCreatedId();//Para asociar las categorias creadas con el nuevo curso
boolean resultCloneForo = cloneForo(newCourseGroupId, listCategories);
if(log.isDebugEnabled()){
log.debug("
}
}
}
if(this.cloneDocuments){
if(log.isDebugEnabled())
log.debug(":: Clone course :: Clone docs ::");
long newCourseGroupId = newCourse.getGroupCreatedId();
long repositoryId = DLFolderConstants.getDataRepositoryId(groupId, DLFolderConstants.DEFAULT_PARENT_FOLDER_ID);
long newRepositoryId = DLFolderConstants.getDataRepositoryId(newCourseGroupId, DLFolderConstants.DEFAULT_PARENT_FOLDER_ID);
duplicateFoldersAndFileEntriesInsideFolder(Boolean.TRUE, themeDisplay.getUserId(), typeSite, themeDisplay.getCompanyId(), DLFolderConstants.DEFAULT_PARENT_FOLDER_ID, repositoryId, newCourseGroupId, DLFolderConstants.DEFAULT_PARENT_FOLDER_ID, newRepositoryId, serviceContext);
}
//SE COPIAN LOS MAILS PROGRAMADOS
/*try {
List<MailJob> mailjobs = MailJobLocalServiceUtil.getMailJobsInGroupId(course.getGroupCreatedId(), -1, -1);
for (MailJob mj : mailjobs){
try {
log.info("mail "+mj.getGroupId());
long classpk = 0;
long referenceclasspk=0;
if (mj.getConditionClassPK()> 0){
LearningActivity act = LearningActivityLocalServiceUtil.fetchLearningActivity(mj.getConditionClassPK());
List<LearningActivity> listactivities = LearningActivityLocalServiceUtil.getLearningActivitiesOfGroupAndType(newCourse.getGroupCreatedId(), act.getTypeId());
for (LearningActivity la: listactivities){
if (act.getTitle().equals(la.getTitle())){
classpk= la.getActId();
break;
}
}
}
if (mj.getDateClassPK()> 0){
LearningActivity actref = LearningActivityLocalServiceUtil.fetchLearningActivity(mj.getDateClassPK());
List<LearningActivity> listactivities = LearningActivityLocalServiceUtil.getLearningActivitiesOfGroupAndType(newCourse.getGroupCreatedId(), actref.getTypeId());
for (LearningActivity la: listactivities){
if (actref.getTitle().equals(la.getTitle())){
classpk= la.getActId();
break;
}
}
}
MailJob mailJob = MailJobLocalServiceUtil.addMailJob(mj.getIdTemplate(), mj.getConditionClassName(), classpk, mj.getConditionStatus(), mj.getDateClassName(), referenceclasspk, mj.getDateShift(), mj.getDateToSend(), mj.getDateReferenceDate(), serviceContext);
log.info("Creado mail "+mailJob.getUuid());
JSONObject extraOrig = mj.getExtraDataJSON();
JSONObject extraData = JSONFactoryUtil.createJSONObject();
extraData.put(MailConstants.EXTRA_DATA_SEND_COPY, extraOrig.getBoolean(MailConstants.EXTRA_DATA_SEND_COPY));
extraData.put(MailConstants.EXTRA_DATA_RELATION_ARRAY, extraOrig.getJSONArray(MailConstants.EXTRA_DATA_RELATION_ARRAY));
mailJob.setExtraData(extraData.toString());
MailJobLocalServiceUtil.updateMailJob(mailJob);
} catch (PortalException e1) {
e1.printStackTrace();
log.error(e1.getMessage());
} catch (SystemException e2) {
e2.printStackTrace();
log.error(e2.getMessage());
}
}
}catch(Exception e){
log.error("NO SE PUDO COPIAR LOS EMAILS PROGRAMADOS");
}
if(log.isDebugEnabled()){
log.debug(" ENDS!");
}*/
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd kk:mm:ss");
dateFormat.setTimeZone(themeDisplay.getTimeZone());
String[] args = {newCourse.getTitle(themeDisplay.getLocale()), dateFormat.format(startDate), dateFormat.format(endDate)};
sendNotification(LanguageUtil.get(themeDisplay.getLocale(),"courseadmin.clone.confirmation.title"), LanguageUtil.format(themeDisplay.getLocale(),"courseadmin.clone.confirmation.message", args), themeDisplay.getPortalURL()+"/web/"+newGroup.getFriendlyURL(), "Avisos", 1);
Date endDate = new Date();
if(!error){
AsynchronousProcessAuditLocalServiceUtil.updateProcessStatus(process, endDate, LmsConstant.STATUS_FINISH, "asynchronous-proccess-audit.status-ok");
}else{
AsynchronousProcessAuditLocalServiceUtil.updateProcessStatus(process, endDate, LmsConstant.STATUS_ERROR, statusMessage);
}
log.debug("Enviando mensaje liferay/lms/courseClonePostAction con newCourseId "+newCourse.getCourseId() + " y originCourseId "+course.getCourseId());
Message postActionMessage=new Message();
postActionMessage.put("originCourseId", course.getCourseId());
postActionMessage.put("newCourseId", newCourse.getCourseId());
MessageBusUtil.sendMessage("liferay/lms/courseClonePostAction", postActionMessage);
}
private void sendNotification(String title, String content, String url, String type, int priority){
//ThemeDisplay themeDisplay = (ThemeDisplay) actionRequest.getAttribute(WebKeys.THEME_DISPLAY);
SimpleDateFormat formatDay = new SimpleDateFormat("dd");
formatDay.setTimeZone(themeDisplay.getTimeZone());
SimpleDateFormat formatMonth = new SimpleDateFormat("MM");
formatMonth.setTimeZone(themeDisplay.getTimeZone());
SimpleDateFormat formatYear = new SimpleDateFormat("yyyy");
formatYear.setTimeZone(themeDisplay.getTimeZone());
SimpleDateFormat formatHour = new SimpleDateFormat("HH");
formatHour.setTimeZone(themeDisplay.getTimeZone());
SimpleDateFormat formatMin = new SimpleDateFormat("mm");
formatMin.setTimeZone(themeDisplay.getTimeZone());
Date today=new Date(System.currentTimeMillis());
int displayDateDay=Integer.parseInt(formatDay.format(today));
int displayDateMonth=Integer.parseInt(formatMonth.format(today))-1;
int displayDateYear=Integer.parseInt(formatYear.format(today));
int displayDateHour=Integer.parseInt(formatHour.format(today));
int displayDateMinute=Integer.parseInt(formatMin.format(today));
int expirationDateDay=Integer.parseInt(formatDay.format(today));
int expirationDateMonth=Integer.parseInt(formatMonth.format(today))-1;
int expirationDateYear=Integer.parseInt(formatYear.format(today))+1;
int expirationDateHour=Integer.parseInt(formatHour.format(today));
int expirationDateMinute=Integer.parseInt(formatMin.format(today));
long classNameId=PortalUtil.getClassNameId(User.class.getName());
long classPK=themeDisplay.getUserId();
AnnouncementsEntry ae;
try {
ae = AnnouncementsEntryServiceUtil.addEntry(
themeDisplay.getPlid(), classNameId, classPK, title, content, url, type,
displayDateMonth, displayDateDay, displayDateYear, displayDateHour, displayDateMinute,
expirationDateMonth, expirationDateDay, expirationDateYear, expirationDateHour, expirationDateMinute,
priority, false);
AnnouncementsFlagLocalServiceUtil.addFlag(classPK,ae.getEntryId(),AnnouncementsFlagConstants.UNREAD);
} catch (PortalException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SystemException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* Clona las categorias/subcategorias/subsubcategorias... del foro
* @param newCourseGroupId: groupId del curso clonado
* @param listCategories: lista de categorias del foro del curso
*
* @return: boolean = true -> Se realiza correctamente
* boolean = false -> Se ha producido algun error durante el proceso
*/
private boolean cloneForo(long newCourseGroupId, List<MBCategory> listCategories){
boolean resultCloneForo = true;
List<MBCategory> listParentCat = new ArrayList<MBCategory>();
List<MBCategory> listSubCat = new ArrayList<MBCategory>();
long parentCategoryId = 0;
for(MBCategory category:listCategories){
if(0 == category.getParentCategoryId()) listParentCat.add(category);
else listSubCat.add(category);
}
resultCloneForo = subCategories(parentCategoryId, newCourseGroupId, listParentCat, listSubCat);
return resultCloneForo;
}
/**
*
* Funcion recursiva que clona las categorias del foro y busca si cada categoria tiene una subcategoria para
* volver a realizar la misma operacion
*
* @param parentCategoryId: Id de la categoria padre (la clonada)
* @param newCourseGroupId: Id del curso clonado
* @param listParentCat
* @param listSubCat
* @return: boolean = true -> Si se realiza el proceso correctamente
* boolean = false -> Si se produce algun error durante el proceso
*/
private boolean subCategories(long parentCategoryId, long newCourseGroupId, List<MBCategory> listParentCat, List<MBCategory> listSubCat){
if(log.isDebugEnabled()){
log.debug("
}
boolean result = true;
long newParentCategoryId;
MBCategory newCourseCategory = null;
List<MBCategory> listSubSubCat= new ArrayList<MBCategory>();
List<MBCategory> listParentSubCat= new ArrayList<MBCategory>();
for(MBCategory category:listParentCat){
newCourseCategory = createNewCategory(newCourseGroupId, category, parentCategoryId);
if (newCourseCategory==null) return false;
newParentCategoryId = newCourseCategory.getCategoryId();
if(listSubCat.size()>0) {
listParentSubCat = new ArrayList<MBCategory>();
listSubSubCat = new ArrayList<MBCategory>();
for(MBCategory subCategory:listSubCat) {
if(category.getCategoryId() == subCategory.getParentCategoryId()) listParentSubCat.add(subCategory);
else listSubSubCat.add(subCategory);
}
if(listParentSubCat.size()>0){//Si encuentro subcategorias de esta categoria vuelvo a llamar a esta misma funcion
result = subCategories(newParentCategoryId, newCourseGroupId, listParentSubCat, listSubSubCat);
if(!result) return result;
}
}
}
return result;
}
/**
*
* Crea una categoria del foro
*
* @param newCourseGroupId: Id del curso clonado
* @param category: Datos de la categoria que se quiere clonar
* @param parentCategoryId: Id de la categoria de la que depende esta categoria (parentCategoryId=0 si no depende de ninguna categoria, y si tiene
* dependencia, parentCategoryId = categoryId de la categoria de la que depende)
* @return null -> en caso de que se produzca algun error
* Objeto MBCategory creado en caso de que la operacion se realice correctamente
*/
private MBCategory createNewCategory(long newCourseGroupId, MBCategory category, long parentCategoryId) {
log.debug("
MBCategory newCourseCategory = null;
try {
newCourseCategory = MBCategoryLocalServiceUtil.createMBCategory(CounterLocalServiceUtil.increment(MBCategory.class.getName()));
newCourseCategory.setGroupId(newCourseGroupId);
newCourseCategory.setCompanyId(category.getCompanyId());
newCourseCategory.setName(category.getName());
newCourseCategory.setDescription(category.getDescription());
newCourseCategory.setCreateDate(Calendar.getInstance().getTime());
newCourseCategory.setModifiedDate(Calendar.getInstance().getTime());
newCourseCategory.setDisplayStyle(category.getDisplayStyle());
newCourseCategory.setUserId(themeDisplay.getUserId());
newCourseCategory.setUserName(themeDisplay.getUser().getFullName());
newCourseCategory.setParentCategoryId(parentCategoryId);
newCourseCategory = MBCategoryLocalServiceUtil.addMBCategory(newCourseCategory);
// Copiar permisos de la categoria antigua en la nueva
List<ResourcePermission> resourcePermissionList = new ArrayList<ResourcePermission>();
ResourcePermission rpNew = null;
long resourcePermissionId = 0;
int [] scopeIds = ResourceConstants.SCOPES;
for(int scope : scopeIds) {
resourcePermissionList = ResourcePermissionLocalServiceUtil.getResourcePermissions(category.getCompanyId(), MBCategory.class.getName(), scope, String.valueOf(category.getPrimaryKey()));
for(ResourcePermission resourcePermission : resourcePermissionList) {
resourcePermissionId = CounterLocalServiceUtil.increment(ResourcePermission.class.getName());
rpNew = ResourcePermissionLocalServiceUtil.createResourcePermission(resourcePermissionId);
rpNew.setActionIds(resourcePermission.getActionIds());
rpNew.setCompanyId(resourcePermission.getCompanyId());
rpNew.setName(resourcePermission.getName());
rpNew.setRoleId(resourcePermission.getRoleId());
rpNew.setScope(resourcePermission.getScope());
rpNew.setPrimKey(String.valueOf(newCourseCategory.getCategoryId()));
rpNew.setOwnerId(resourcePermission.getOwnerId());
rpNew = ResourcePermissionLocalServiceUtil.updateResourcePermission(rpNew);
}
}
return newCourseCategory;
} catch (SystemException e) {
log.error(e.getMessage());
return null;
}
}
}
|
package com.ibm.sk.engine;
import static com.ibm.sk.engine.World.placeObject;
import java.awt.Point;
import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import com.ibm.sk.dto.AbstractAnt;
import com.ibm.sk.dto.AbstractWarrior;
import com.ibm.sk.dto.Ant;
import com.ibm.sk.dto.Food;
import com.ibm.sk.dto.Hill;
import com.ibm.sk.dto.IAnt;
import com.ibm.sk.dto.Warrior;
import com.ibm.sk.dto.enums.Direction;
public class PopulationHandler {
private static int antcounter = 1;
public AbstractAnt breedAnt(final Hill hill) {
System.out.println("Welcome new creature of this world! From now on you belong to "
+ hill.getName() + "! But don't be affraid, you are not alone, he has other " + hill.getPopulation() + " ants.");
final Point homePosition = new Point(hill.getPosition());
final Ant ant = new Ant(antcounter++, homePosition, hill);
World.placeObject(ant);
hill.incrementPopulation(1);
return ant;
}
public static void killAnt(final IAnt ant) {
System.out.println("You shall be no more in this world! Good bye forewer dear ant " + ant.getId());
ant.getMyHill().decrementPopulation(1);
leaveFood(ant);
World.removeObject(ant.getPosition());
ant.getMyHill().getAnts().remove(ant);
}
private static void leaveFood(final IAnt ant) {
final Food remains = ant.dropFood();
if (remains != null) {
final Point here = ant.getPosition();
final List<Direction> directions = Arrays.asList(Direction.values());
Collections.shuffle(directions);
final Iterator<Direction> randomDirections = directions.iterator();
Point dropPosition = null;
do {
final Point randomDirection = randomDirections.next().getPositionChange();
dropPosition = new Point(here);
dropPosition.translate(randomDirection.x, randomDirection.y);
} while (randomDirections.hasNext() && World.getWorldObject(dropPosition) != null);
if (World.getWorldObject(dropPosition) == null) {
remains.setPosition(dropPosition);
placeObject(remains);
System.out.println("Dropped: " + remains);
}
}
}
public AbstractWarrior breedWarrior(final Hill hill) {
System.out.println("Welcome new creature of this world! From now on you belong to " + hill.getName()
+ "! But don't be affraid, you are not alone, he has other " + hill.getPopulation() + " ants.");
final Point homePosition = new Point(hill.getPosition());
final AbstractWarrior warrior = new Warrior(antcounter++, homePosition, hill);
World.placeObject(warrior);
hill.incrementPopulation(1);
return warrior;
}
}
|
package net.somethingdreadful.MAL;
import android.annotation.SuppressLint;
import android.app.FragmentManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.SearchManager;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.view.MenuItemCompat;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.SearchView;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.crashlytics.android.Crashlytics;
import com.squareup.picasso.Picasso;
import net.somethingdreadful.MAL.account.AccountService;
import net.somethingdreadful.MAL.adapters.IGFPagerAdapter;
import net.somethingdreadful.MAL.adapters.NavigationDrawerAdapter;
import net.somethingdreadful.MAL.api.MALApi;
import net.somethingdreadful.MAL.api.response.User;
import net.somethingdreadful.MAL.dialog.LogoutConfirmationDialogFragment;
import net.somethingdreadful.MAL.dialog.UpdateImageDialogFragment;
import net.somethingdreadful.MAL.dialog.UpdatePasswordDialogFragment;
import net.somethingdreadful.MAL.sql.MALSqlHelper;
import net.somethingdreadful.MAL.tasks.APIAuthenticationErrorListener;
import net.somethingdreadful.MAL.tasks.TaskJob;
import net.somethingdreadful.MAL.tasks.UserNetworkTask;
import net.somethingdreadful.MAL.tasks.UserNetworkTaskFinishedListener;
public class Home extends ActionBarActivity implements SwipeRefreshLayout.OnRefreshListener, IGFCallbackListener, APIAuthenticationErrorListener, View.OnClickListener, UserNetworkTaskFinishedListener {
IGF af;
IGF mf;
/**
* 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}.
*/
IGFPagerAdapter mIGFPagerAdapter;
/**
* The {@link ViewPager} that will host the section contents.
*/
ViewPager mViewPager;
Context context;
Menu menu;
BroadcastReceiver networkReceiver;
DrawerLayout DrawerLayout;
ListView DrawerList;
ActionBarDrawerToggle mDrawerToggle;
View mPreviousView;
ActionBar actionBar;
NavigationDrawerAdapter mNavigationDrawerAdapter;
RelativeLayout logout;
RelativeLayout settings;
RelativeLayout about;
String username;
boolean instanceExists;
boolean networkAvailable;
boolean myList = true; //tracks if the user is on 'My List' or not
boolean callbackAnimeError = false;
boolean callbackMangaError = false;
int callbackCounter = 0;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = getApplicationContext();
if (AccountService.getAccount() != null) {
actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
}
//The following is state handling code
instanceExists = savedInstanceState != null && savedInstanceState.getBoolean("instanceExists", false);
networkAvailable = savedInstanceState == null || savedInstanceState.getBoolean("networkAvailable", true);
if (savedInstanceState != null) {
myList = savedInstanceState.getBoolean("myList");
}
setContentView(R.layout.activity_home);
// Creates the adapter to return the Animu and Mango fragments
mIGFPagerAdapter = new IGFPagerAdapter(getFragmentManager());
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
DrawerLayout = (DrawerLayout) inflater.inflate(R.layout.record_home_navigationdrawer, (DrawerLayout) findViewById(R.id.drawer_layout));
DrawerLayout.setDrawerListener(new DrawerListener());
DrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, Gravity.START);
username = AccountService.getUsername();
((TextView) DrawerLayout.findViewById(R.id.name)).setText(username);
((TextView) DrawerLayout.findViewById(R.id.siteName)).setText(getString(AccountService.isMAL() ? R.string.init_hint_myanimelist : R.string.init_hint_anilist));
new UserNetworkTask(context, false, this).execute(username);
logout = (RelativeLayout) DrawerLayout.findViewById(R.id.logout);
settings = (RelativeLayout) DrawerLayout.findViewById(R.id.settings);
about = (RelativeLayout) DrawerLayout.findViewById(R.id.about);
logout.setOnClickListener(this);
settings.setOnClickListener(this);
about.setOnClickListener(this);
DrawerList = (ListView) DrawerLayout.findViewById(R.id.listview);
NavigationItems mNavigationContent = new NavigationItems(DrawerList, context);
mNavigationDrawerAdapter = new NavigationDrawerAdapter(this, mNavigationContent.ITEMS);
DrawerList.setAdapter(mNavigationDrawerAdapter);
DrawerList.setOnItemClickListener(new DrawerItemClickListener());
DrawerList.setOverScrollMode(View.OVER_SCROLL_NEVER);
mDrawerToggle = new ActionBarDrawerToggle(this, DrawerLayout, R.string.drawer_open, R.string.drawer_close);
mDrawerToggle.syncState();
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mIGFPagerAdapter);
mViewPager.setPageMargin(32);
networkReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
checkNetworkAndDisplayCrouton();
}
};
} else {
Intent firstRunInit = new Intent(this, FirstTimeInit.class);
startActivity(firstRunInit);
finish();
}
NfcHelper.disableBeam(this);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_home, menu);
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
MenuItem searchItem = menu.findItem(R.id.action_search);
SearchView searchView = (SearchView) MenuItemCompat.getActionView(searchItem);
ComponentName cn = new ComponentName(this, SearchActivity.class);
searchView.setSearchableInfo(searchManager.getSearchableInfo(cn));
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
switch (item.getItemId()) {
case R.id.listType_all:
getRecords(true, TaskJob.GETLIST, 0);
setChecked(item);
break;
case R.id.listType_inprogress:
getRecords(true, TaskJob.GETLIST, 1);
setChecked(item);
break;
case R.id.listType_completed:
getRecords(true, TaskJob.GETLIST, 2);
setChecked(item);
break;
case R.id.listType_onhold:
getRecords(true, TaskJob.GETLIST, 3);
setChecked(item);
break;
case R.id.listType_dropped:
getRecords(true, TaskJob.GETLIST, 4);
setChecked(item);
break;
case R.id.listType_planned:
getRecords(true, TaskJob.GETLIST, 5);
setChecked(item);
break;
case R.id.forceSync:
synctask(true);
break;
case R.id.menu_inverse:
if (af != null && mf != null) {
if (!AccountService.isMAL() && af.taskjob == TaskJob.GETMOSTPOPULAR) {
af.toggleAiringTime();
} else {
af.inverse();
mf.inverse();
}
}
break;
}
return super.onOptionsItemSelected(item);
}
public void getRecords(boolean clear, TaskJob task, int list) {
if (af != null && mf != null) {
af.getRecords(clear, task, list);
mf.getRecords(clear, task, list);
if (task == TaskJob.FORCESYNC)
syncNotify();
}
}
@Override
public void onResume() {
super.onResume();
checkNetworkAndDisplayCrouton();
registerReceiver(networkReceiver, new IntentFilter("android.net.conn.CONNECTIVITY_CHANGE"));
}
@SuppressLint("NewApi")
@Override
public void onPause() {
super.onPause();
if (menu != null)
menu.findItem(R.id.action_search).collapseActionView();
instanceExists = true;
unregisterReceiver(networkReceiver);
}
public void synctask(boolean clear) {
getRecords(clear, TaskJob.FORCESYNC, af.list);
}
@Override
public void onSaveInstanceState(Bundle state) {
//This is telling out future selves that we already have some things and not to do them
state.putBoolean("instanceExists", true);
state.putBoolean("networkAvailable", networkAvailable);
state.putBoolean("myList", myList);
super.onSaveInstanceState(state);
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
this.menu = menu;
if (af != null) {
//All this is handling the ticks in the switch list menu
switch (af.list) {
case 0:
setChecked(menu.findItem(R.id.listType_all));
break;
case 1:
setChecked(menu.findItem(R.id.listType_inprogress));
break;
case 2:
setChecked(menu.findItem(R.id.listType_completed));
break;
case 3:
setChecked(menu.findItem(R.id.listType_onhold));
break;
case 4:
setChecked(menu.findItem(R.id.listType_dropped));
break;
case 5:
setChecked(menu.findItem(R.id.listType_planned));
}
}
return true;
}
public void setChecked(MenuItem item) {
item.setChecked(true);
}
public void myListChanged() {
menu.findItem(R.id.menu_listType).setVisible(myList);
menu.findItem(R.id.menu_inverse).setVisible(myList || (!AccountService.isMAL() && af.taskjob == TaskJob.GETMOSTPOPULAR));
menu.findItem(R.id.forceSync).setVisible(myList && networkAvailable);
menu.findItem(R.id.action_search).setVisible(networkAvailable);
}
@SuppressLint("NewApi")
public void onLogoutConfirmed() {
if (af != null)
af.cancelNetworkTask();
if (mf != null)
mf.cancelNetworkTask();
MALSqlHelper.getHelper(context).deleteDatabase(context);
AccountService.deleteAccount();
startActivity(new Intent(this, Home.class).addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
finish();
}
private void syncNotify() {
Intent notificationIntent = new Intent(context, Home.class);
PendingIntent contentIntent = PendingIntent.getActivity(context, 1, notificationIntent, PendingIntent.FLAG_CANCEL_CURRENT);
NotificationManager nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
Notification.Builder syncNotificationBuilder = new Notification.Builder(context).setOngoing(true)
.setContentIntent(contentIntent)
.setSmallIcon(R.drawable.notification_icon)
.setContentTitle(getString(R.string.app_name))
.setContentText(getString(R.string.toast_info_SyncMessage));
Notification syncNotification;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
syncNotificationBuilder.setVisibility(Notification.VISIBILITY_PUBLIC);
}
syncNotification = syncNotificationBuilder.build();
} else {
syncNotification = syncNotificationBuilder.getNotification();
}
nm.notify(R.id.notification_sync, syncNotification);
}
private void showLogoutDialog() {
FragmentManager fm = getFragmentManager();
LogoutConfirmationDialogFragment lcdf = new LogoutConfirmationDialogFragment();
lcdf.show(fm, "fragment_LogoutConfirmationDialog");
}
public void checkNetworkAndDisplayCrouton() {
if (MALApi.isNetworkAvailable(context) && !networkAvailable) {
synctask(false);
}
networkAvailable = MALApi.isNetworkAvailable(context);
}
@Override
public void onRefresh() {
if (networkAvailable)
synctask(false);
else {
if (af != null && mf != null) {
af.toggleSwipeRefreshAnimation(false);
mf.toggleSwipeRefreshAnimation(false);
}
Toast.makeText(context, R.string.toast_error_noConnectivity, Toast.LENGTH_SHORT).show();
}
}
@Override
public void onIGFReady(IGF igf) {
igf.setUsername(AccountService.getUsername());
if (igf.listType.equals(MALApi.ListType.ANIME))
af = igf;
else
mf = igf;
// do forced sync after FirstInit
if (PrefManager.getForceSync()) {
if (af != null && mf != null) {
PrefManager.setForceSync(false);
PrefManager.commitChanges();
synctask(true);
}
} else {
if (igf.taskjob == null) {
igf.getRecords(true, TaskJob.GETLIST, PrefManager.getDefaultList());
}
}
}
@Override
public void onRecordsLoadingFinished(MALApi.ListType type, TaskJob job, boolean error, boolean resultEmpty, boolean cancelled) {
if (cancelled && !job.equals(TaskJob.FORCESYNC)) {
return;
}
callbackCounter++;
if (type.equals(MALApi.ListType.ANIME))
callbackAnimeError = error;
else
callbackMangaError = error;
if (callbackCounter >= 2) {
callbackCounter = 0;
if (job.equals(TaskJob.FORCESYNC)) {
NotificationManager nm = (NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
nm.cancel(R.id.notification_sync);
if (callbackAnimeError && callbackMangaError) // the sync failed completely
Toast.makeText(context, R.string.toast_error_SyncFailed, Toast.LENGTH_SHORT).show();
else if (callbackAnimeError || callbackMangaError) // one list failed to sync
Toast.makeText(context, callbackAnimeError ? R.string.toast_error_Anime_Sync : R.string.toast_error_Manga_Sync, Toast.LENGTH_SHORT).show();
} else {
if (callbackAnimeError && callbackMangaError) // the sync failed completely
Toast.makeText(context, R.string.toast_error_Records, Toast.LENGTH_SHORT).show();
else if (callbackAnimeError || callbackMangaError) // one list failed to sync
Toast.makeText(context, callbackAnimeError ? R.string.toast_error_Anime_Records : R.string.toast_error_Manga_Records, Toast.LENGTH_SHORT).show();
// no else here, there is nothing to be shown when everything went well
}
}
}
@Override
public void onAPIAuthenticationError(MALApi.ListType type, TaskJob job) {
// check if it is already showing
if (getFragmentManager().findFragmentByTag("fragment_updatePassword") == null) {
FragmentManager fm = getFragmentManager();
UpdatePasswordDialogFragment passwordFragment = new UpdatePasswordDialogFragment();
passwordFragment.show(fm, "fragment_updatePassword");
}
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.logout:
showLogoutDialog();
break;
case R.id.settings:
startActivity(new Intent(this, Settings.class));
break;
case R.id.about:
startActivity(new Intent(this, AboutActivity.class));
break;
case R.id.Image:
Intent Profile = new Intent(context, ProfileActivity.class);
Profile.putExtra("username", username);
startActivity(Profile);
break;
case R.id.NDimage:
UpdateImageDialogFragment lcdf = new UpdateImageDialogFragment();
lcdf.show(getFragmentManager(), "fragment_NDImage");
break;
}
DrawerLayout.closeDrawers();
}
@Override
public void onUserNetworkTaskFinished(User result) {
ImageView image = (ImageView) findViewById(R.id.Image);
ImageView image2 = (ImageView) findViewById(R.id.NDimage);
try {
Picasso.with(context)
.load(result.getProfile().getAvatarUrl())
.transform(new RoundedTransformation(result.getName()))
.into(image);
} catch (Exception e) {
Crashlytics.log(Log.ERROR, "MALX", "Home.onUserNetworkTaskFinished(): " + e.getMessage());
}
if (PrefManager.getNavigationBackground() != null)
Picasso.with(context)
.load(PrefManager.getNavigationBackground())
.into(image2);
image.setOnClickListener(this);
image2.setOnClickListener(this);
}
public class DrawerItemClickListener implements ListView.OnItemClickListener {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (!networkAvailable && position > 2) {
position = 0;
Toast.makeText(context, R.string.toast_error_noConnectivity, Toast.LENGTH_SHORT).show();
}
myList = ((position <= 3 && myList) || position == 0);
// disable swipeRefresh for other lists
if (af == null || mf == null) {
af = mIGFPagerAdapter.getIGF(0);
mf = mIGFPagerAdapter.getIGF(1);
}
af.setSwipeRefreshEnabled(myList);
mf.setSwipeRefreshEnabled(myList);
switch (position) {
case 0:
getRecords(true, TaskJob.GETLIST, af.list);
break;
case 1:
Intent Profile = new Intent(context, ProfileActivity.class);
Profile.putExtra("username", username);
startActivity(Profile);
break;
case 2:
Intent Friends = new Intent(context, net.somethingdreadful.MAL.FriendsActivity.class);
startActivity(Friends);
break;
case 3:
if (AccountService.isMAL()) {
Intent Forum = new Intent(context, ForumActivity.class);
startActivity(Forum);
} else {
Toast.makeText(context, getString(R.string.toast_info_disabled), Toast.LENGTH_SHORT).show();
}
break;
case 4:
getRecords(true, TaskJob.GETTOPRATED, af.list);
break;
case 5:
getRecords(true, TaskJob.GETMOSTPOPULAR, af.list);
break;
case 6:
getRecords(true, TaskJob.GETJUSTADDED, af.list);
break;
case 7:
getRecords(true, TaskJob.GETUPCOMING, af.list);
break;
}
myListChanged();
/*
* This part is for figuring out which item in the nav drawer is selected and highlighting it with colors.
*/
if (position != 1 && position != 2 && position != 3) {
if (mPreviousView != null)
mPreviousView.setBackgroundColor(Color.parseColor("#00000000"));
view.setBackgroundColor(Color.parseColor("#E8E8E8"));
mPreviousView = view;
}
DrawerLayout.closeDrawers();
}
}
private class DrawerListener implements DrawerLayout.DrawerListener {
@Override
public void onDrawerOpened(View drawerView) {
mDrawerToggle.onDrawerOpened(drawerView);
actionBar.setTitle(getTitle());
}
@Override
public void onDrawerClosed(View drawerView) {
mDrawerToggle.onDrawerClosed(drawerView);
actionBar.setTitle(getTitle());
}
@Override
public void onDrawerSlide(View drawerView, float slideOffset) {
mDrawerToggle.onDrawerSlide(drawerView, slideOffset);
}
@Override
public void onDrawerStateChanged(int newState) {
mDrawerToggle.onDrawerStateChanged(newState);
}
}
}
|
package com.thaiopensource.xml.dtd;
import java.util.Vector;
class Decl {
static final int REFERENCE = 0; // entity
static final int REFERENCE_END = 1;
static final int ELEMENT = 2; // params
static final int ATTLIST = 3; // params
static final int ENTITY = 4; // params
static final int NOTATION = 5; // params
static final int INCLUDE_SECTION = 6; // params + decls
static final int IGNORE_SECTION = 7; // params + value
static final int COMMENT = 8; // value
static final int PROCESSING_INSTRUCTION = 9; // value
Decl(int type) {
this.type = type;
}
int type;
Vector params;
String value;
Entity entity;
Vector decls;
public boolean equals(Object obj) {
if (obj == null || !(obj instanceof Decl))
return false;
Decl other = (Decl)obj;
if (this.type != other.type)
return false;
if (this.entity != other.entity)
return false;
if (this.value != null && !this.value.equals(other.value))
return false;
if (this.params != null) {
int n = this.params.size();
if (other.params.size() != n)
return false;
for (int i = 0; i < n; i++)
if (!this.params.elementAt(i).equals(other.params.elementAt(i)))
return false;
}
return true;
}
TopLevel createTopLevel(DtdBuilder db) {
switch (type) {
case COMMENT:
return new Comment(value);
case ELEMENT:
return createElementDecl();
case ATTLIST:
return createAttlistDecl();
case ENTITY:
return createEntityDecl(db);
case INCLUDE_SECTION:
return createIncludedSection(db);
case IGNORE_SECTION:
return createIgnoredSection();
}
return null;
}
ElementDecl createElementDecl() {
ParamStream ps = new ParamStream(params, true);
ps.advance();
String name = ps.value;
return new ElementDecl(name, Param.paramsToModelGroup(ps));
}
AttlistDecl createAttlistDecl() {
ParamStream ps = new ParamStream(params, true);
ps.advance();
String name = ps.value;
return new AttlistDecl(name, Param.paramsToAttributeGroup(ps));
}
TopLevel createEntityDecl(DtdBuilder db) {
ParamStream ps = new ParamStream(params);
ps.advance();
if (ps.type != Param.PERCENT)
return createGeneralEntityDecl(db, ps.value);
ps.advance();
String name = ps.value;
Entity entity = db.lookupParamEntity(name);
if (entity.decl == null)
entity.decl = this;
if (entity.decl != this)
return null;
switch (entity.semantic) {
case Entity.SEMANTIC_MODEL_GROUP:
entity.modelGroup = entity.toModelGroup();
return new ModelGroupDef(name, entity.modelGroup);
case Entity.SEMANTIC_ATTRIBUTE_GROUP:
entity.attributeGroup =
Param.paramsToAttributeGroup(entity.parsed);
return new AttributeGroupDef(name, entity.attributeGroup);
case Entity.SEMANTIC_DATATYPE:
entity.datatype = Param.paramsToDatatype(entity.parsed);
return new DatatypeDef(name, entity.datatype);
case Entity.SEMANTIC_ENUM_GROUP:
entity.enumGroup = Particle.particlesToEnumGroup(entity.parsed);
return new EnumGroupDef(name, entity.enumGroup);
case Entity.SEMANTIC_FLAG:
entity.flag = Param.paramsToFlag(entity.parsed);
return new FlagDef(name, entity.flag);
}
return null;
}
TopLevel createGeneralEntityDecl(DtdBuilder db, String name) {
Entity entity = db.lookupGeneralEntity(name);
if (entity.decl == null)
entity.decl = this;
if (entity.decl != this)
return null;
if (entity.text == null)
return null;
return new InternalEntityDecl(name, new String(entity.text));
}
IncludedSection createIncludedSection(DtdBuilder db) {
Flag flag = Param.paramsToFlag(params);
Vector contents = declsToTopLevel(db, decls);
TopLevel[] tem = new TopLevel[contents.size()];
for (int i = 0; i < tem.length; i++)
tem[i] = (TopLevel)contents.elementAt(i);
return new IncludedSection(flag, tem);
}
static Vector declsToTopLevel(DtdBuilder db, Vector decls) {
Vector v = new Vector();
int n = decls.size();
for (int i = 0; i < n; i++) {
TopLevel t = ((Decl)decls.elementAt(i)).createTopLevel(db);
if (t != null)
v.addElement(t);
}
return v;
}
IgnoredSection createIgnoredSection() {
return new IgnoredSection(Param.paramsToFlag(params), value);
}
}
|
package de.tobject.findbugs.io;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import javax.annotation.Nonnull;
import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import de.tobject.findbugs.FindbugsPlugin;
/**
* Input/output helper methods.
*
* @author David Hovemeyer
*/
public abstract class IO {
/**
* Write the contents of a file in the Eclipse workspace.
*
* @param file
* the file to write to
* @param output
* the FileOutput object responsible for generating the data
* @param monitor
* a progress monitor (or null if none)
* @throws CoreException
*/
public static void writeFile(IFile file, final FileOutput output, IProgressMonitor monitor) throws CoreException {
try {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
output.writeFile(bos);
ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
if (!file.exists()) {
mkdirs(file, monitor);
file.create(bis, true, monitor);
} else {
file.setContents(bis, true, false, monitor);
}
} catch (IOException e) {
IStatus status = FindbugsPlugin.createErrorStatus("Exception while " + output.getTaskDescription(), e);
throw new CoreException(status);
}
}
/**
* Recursively creates all folders needed, up to the project. Project must
* already exist.
*
* @param resource
* non null
* @param monitor
* non null
* @throws CoreException
*/
private static void mkdirs(@Nonnull IResource resource, IProgressMonitor monitor) throws CoreException {
IContainer container = resource.getParent();
if (container.getType() == IResource.FOLDER && !container.exists()) {
if(!container.getParent().exists()) {
mkdirs(container, monitor);
}
((IFolder) container).create(true, true, monitor);
}
}
/**
* Write the contents of a java.io.File
*
* @param file
* the file to write to
* @param output
* the FileOutput object responsible for generating the data
*/
public static void writeFile(final File file, final FileOutput output, final IProgressMonitor monitor) throws CoreException {
FileOutputStream fout = null;
try {
fout = new FileOutputStream(file);
BufferedOutputStream bout = new BufferedOutputStream(fout);
if (monitor != null) {
monitor.subTask("writing data to " + file.getName());
}
output.writeFile(bout);
bout.flush();
} catch (IOException e) {
IStatus status = FindbugsPlugin.createErrorStatus("Exception while " + output.getTaskDescription(), e);
throw new CoreException(status);
} finally {
closeQuietly(fout);
}
}
public static void closeQuietly(Closeable closeable) {
if (closeable != null) {
try {
closeable.close();
} catch (IOException e) {
// ignore
}
}
}
}
|
/**
* Demonstrate how to use PWM with an output pin using the MRAA library.
* If the output is connected to a led, its intensity, as perceived by the human
* eye, will vary depending on the duty cycle.
* A suitable part to use this example with in the Grove Starter Kit is the LED.
*
* Use a platform with PWM capabilities
*/
package iotdk.example;
import mraa.Platform;
import mraa.Pwm;
import mraa.Result;
import mraa.mraa;
public class PWM {
// Set true if using a Grove Pi Shield, else false
static final boolean USING_GROVE_PI_SHIELD = true;
static String unknownPlatformMessage = "This sample uses the MRAA/UPM library for I/O access, " +
"you are running it on an unrecognized platform. " +
"You may need to modify the MRAA/UPM initialization code to " +
"ensure it works properly on your platform.\n\n";
public static void main(String[] args) {
Platform platform = mraa.getPlatformType();
int pinNumber = 5;
if(platform.equals(Platform.INTEL_UP)) {
if(USING_GROVE_PI_SHIELD) {
pinNumber = pinNumber + 512; // A0 Connector (512 offset needed for the shield)
}
} else {
System.err.println(unknownPlatformMessage);
}
// create a PWM object from MRAA using pin 5
// note that not all digital pins can be used for PWM, the available ones
// are usually marked with a ~ on the board's silk screen
Pwm pwm_pin = null;
pwm_pin = new Pwm(pinNumber);
// select PWM period of 1ms
if (pwm_pin.period_ms(1) != Result.SUCCESS) {
System.err.println("Could not initalize the PMW period, exiting");
return;
}
// enable the pin for ouput
if (pwm_pin.enable(true) != Result.SUCCESS) {
System.err.println("Could not enable the pin for output, exiting");
return;
};
// PWM duty-cycle value, 0 == 0%, 1 == 100%
float duty_cycle = 0;
// loop forever increasing the PWM duty-cycle from 0% to 100%
while (true) {
// increase the duty-cycle by 1%
duty_cycle += 0.01;
// set the output duty-cycle percentage
if (pwm_pin.write(duty_cycle) != Result.SUCCESS) {
System.err.println("Could not set the duty-cycle percentage, exiting");
return;
};
try {
Thread.sleep(50);
} catch (InterruptedException e) {
System.err.println("Sleep interrupted: " + e.toString());
}
// if the duty-cycle reaches 100% start from 0% again
// a full cycle will take ~5 seconds
if (duty_cycle >= 1) {
duty_cycle = 0;
}
}
}
}
|
package com.worizon.junit.gson;
import org.junit.Test;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.worizon.jsonrpc.JsonRpcResponse;
import com.worizon.jsonrpc.gson.BooleanTypeAdapter;
import static org.junit.Assert.*;
import static org.hamcrest.CoreMatchers.*;
public class BooleanTypeAdapterTest {
class Foo{
boolean resultPri;
Boolean resultObj;
}
@Test
public void testParseTrue() throws Exception{
GsonBuilder builder = new GsonBuilder();
builder.registerTypeAdapter(Boolean.class, new BooleanTypeAdapter());
builder.registerTypeAdapter(boolean.class, new BooleanTypeAdapter());
String message = "{\"resultPri\":true,\"resultObj\":true}";
Gson gson = builder.create();
Foo b = (Foo)gson.fromJson(message, Foo.class);
assertThat(b.resultPri, is(true));
assertThat(b.resultObj, is(true));
}
@Test
public void testParseFalse() throws Exception{
GsonBuilder builder = new GsonBuilder();
builder.registerTypeAdapter(Boolean.class, new BooleanTypeAdapter());
builder.registerTypeAdapter(boolean.class, new BooleanTypeAdapter());
String message = "{\"resultPri\":false,\"resultObj\":false}";
Gson gson = builder.create();
Foo b = (Foo)gson.fromJson(message, Foo.class);
assertThat(b.resultPri, is(false));
assertThat(b.resultObj, is(false));
}
@Test
public void testParse1() throws Exception{
GsonBuilder builder = new GsonBuilder();
builder.registerTypeAdapter(Boolean.class, new BooleanTypeAdapter());
builder.registerTypeAdapter(boolean.class, new BooleanTypeAdapter());
String message = "{\"resultPri\":1,\"resultObj\":1}";
Gson gson = builder.create();
Foo b = (Foo)gson.fromJson(message, Foo.class);
assertThat(b.resultPri, is(true));
assertThat(b.resultObj, is(true));
}
@Test
public void testParse0() throws Exception{
GsonBuilder builder = new GsonBuilder();
builder.registerTypeAdapter(Boolean.class, new BooleanTypeAdapter());
builder.registerTypeAdapter(boolean.class, new BooleanTypeAdapter());
String message = "{\"resultPri\":0,\"resultObj\":0}";
Gson gson = builder.create();
Foo b = (Foo)gson.fromJson(message, Foo.class);
assertThat(b.resultPri, is(false));
assertThat(b.resultObj, is(false));
}
@Test
public void testParseWithSpaces() throws Exception{
GsonBuilder builder = new GsonBuilder();
builder.registerTypeAdapter(Boolean.class, new BooleanTypeAdapter());
builder.registerTypeAdapter(boolean.class, new BooleanTypeAdapter());
String message = "{\"resultPri\":0,\"resultObj\": 0}";
Gson gson = builder.create();
Foo b = (Foo)gson.fromJson(message, Foo.class);
assertThat(b.resultPri, is(false));
assertThat(b.resultObj, is(false));
}
@Test
public void testParseWithSpacesAndTabs() throws Exception{
GsonBuilder builder = new GsonBuilder();
builder.registerTypeAdapter(Boolean.class, new BooleanTypeAdapter());
builder.registerTypeAdapter(boolean.class, new BooleanTypeAdapter());
String message = "{ \"resultPri\" : 0, \"resultObj\" : 0}";
Gson gson = builder.create();
Foo b = (Foo)gson.fromJson(message, Foo.class);
assertThat(b.resultPri, is(false));
assertThat(b.resultObj, is(false));
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.