answer
stringlengths 17
10.2M
|
|---|
package com.brightsparklabs.asanti.validator;
import com.brightsparklabs.asanti.model.schema.constraint.AsnSchemaConstraint;
import com.brightsparklabs.asanti.model.schema.primitive.AsnPrimitiveType;
import com.brightsparklabs.asanti.model.schema.typedefinition.*;
import com.brightsparklabs.asanti.validator.builtin.*;
import com.google.common.collect.ImmutableList;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Unit tests for {@link ValidationVisitor}
*
* @author brightSPARK Labs
*/
public class ValidationVisitorTest
{
// FIXTURES
/** instance under test */
private static final ValidationVisitor instance = new ValidationVisitor();
// TESTS
@Test
public void testVisitAsnSchemaTypeDefinitionNull()
{
final BuiltinTypeValidator.Null result = instance.visit(AsnPrimitiveType.NULL);
assertNotNull(result);
}
@Test
public void testVisitAsnSchemaTypeDefinitionBitString()
{
final BitStringValidator result = instance.visit(AsnPrimitiveType.BIT_STRING);
assertNotNull(result);
}
@Test
public void testVisitAsnSchemaTypeDefinitionChoice()
{
// TODO: ASN-113
final Object result = instance.visit(AsnPrimitiveType.CHOICE);
assertEquals(BuiltinTypeValidator.NULL, result);
//assertNull(result);
}
@Test
public void testVisitAsnSchemaTypeDefinitionEnumerated()
{
// TODO: ASN-113
final Object result = instance.visit(AsnPrimitiveType.ENUMERATED);
assertEquals(BuiltinTypeValidator.NULL, result);
//assertNull(result);
}
@Test
public void testVisitAsnSchemaTypeDefinitionGeneralizedTime()
{
final GeneralizedTimeValidator result = instance.visit(AsnPrimitiveType.GENERALIZED_TIME);
assertNotNull(result);
}
@Test
public void testVisitAsnSchemaTypeDefinitionGeneralString()
{
// TODO MJF
// final GeneralStringValidator result = instance.visit(AsnPrimitiveType.GENERAL_STRING);
// assertNotNull(result);
}
@Test
public void testVisitAsnSchemaTypeDefinitionIA5String()
{
final Ia5StringValidator result = instance.visit(AsnPrimitiveType.IA5_STRING);
assertNotNull(result);
}
@Test
public void testVisitAsnSchemaTypeDefinitionInteger()
{
final IntegerValidator result = instance.visit(AsnPrimitiveType.INTEGER);
assertNotNull(result);
}
@Test
public void testVisitAsnSchemaTypeDefinitionNumericString()
{
final NumericStringValidator result = instance.visit(AsnPrimitiveType.NUMERIC_STRING);
assertNotNull(result);
}
@Test
public void testVisitAsnSchemaTypeDefinitionOctetString()
{
final OctetStringValidator result = instance.visit(AsnPrimitiveType.OCTET_STRING);
assertNotNull(result);
}
@Test
public void testVisitAsnSchemaTypeDefinitionSequence()
{
// TODO: ASN-113
final Object result = instance.visit(AsnPrimitiveType.SEQUENCE);
assertNull(result);
}
@Test
public void testVisitAsnSchemaTypeDefinitionSequenceOf()
{
assertEquals(null, instance.visit(AsnPrimitiveType.SEQUENCE_OF));
}
@Test
public void testVisitAsnSchemaTypeDefinitionSet()
{
// TODO: ASN-113
final Object result = instance.visit(AsnPrimitiveType.SET);
assertNull(result);
}
@Test
public void testVisitAsnSchemaTypeDefinitionSetOf()
{
assertEquals(null, instance.visit(AsnPrimitiveType.SET_OF));
}
@Test
public void testVisitAsnSchemaTypeDefinitionUtf8String()
{
final Utf8StringValidator result = instance.visit(AsnPrimitiveType.UTF8_STRING);
assertNotNull(result);
}
@Test
public void testVisitAsnSchemaTypeDefinitionVisibleString()
{
final VisibleStringValidator result = instance.visit(AsnPrimitiveType.VISIBLE_STRING);
assertNotNull(result);
}
}
|
package com.rarchives.ripme.tst.ripper.rippers;
import java.io.IOException;
import java.net.URL;
import com.rarchives.ripme.ripper.rippers.CheveretoRipper;
public class CheveretoRipperTest extends RippersTest {
public void testHushpix() throws IOException {
CheveretoRipper ripper = new CheveretoRipper(new URL("https://hushpix.com/album/gKcu"));
testRipper(ripper);
}
public void testTagFox() throws IOException {
CheveretoRipper ripper = new CheveretoRipper(new URL("http://tag-fox.com/album/Thjb"));
testRipper(ripper);
}
public void testgwarchives() throws IOException {
CheveretoRipper ripper = new CheveretoRipper(new URL("https://gwarchives.com/album/ns4q"));
testRipper(ripper);
}
}
|
package org.topcased.requirement.merge.process;
import java.io.IOException;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Vector;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.SubProgressMonitor;
import org.eclipse.emf.common.command.BasicCommandStack;
import org.eclipse.emf.common.command.CompoundCommand;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.common.util.TreeIterator;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.resource.ResourceSet;
import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl;
import org.eclipse.emf.ecore.util.EcoreUtil;
import org.eclipse.emf.edit.command.DeleteCommand;
import org.eclipse.emf.edit.domain.AdapterFactoryEditingDomain;
import org.eclipse.emf.edit.provider.ReflectiveItemProviderAdapterFactory;
import org.topcased.requirement.Attribute;
import org.topcased.requirement.AttributeConfiguration;
import org.topcased.requirement.AttributeLink;
import org.topcased.requirement.CurrentRequirement;
import org.topcased.requirement.HierarchicalElement;
import org.topcased.requirement.ProblemChapter;
import org.topcased.requirement.Requirement;
import org.topcased.requirement.RequirementFactory;
import org.topcased.requirement.RequirementPackage;
import org.topcased.requirement.RequirementProject;
import org.topcased.requirement.SpecialChapter;
import org.topcased.requirement.TrashChapter;
import org.topcased.requirement.UntracedChapter;
import org.topcased.requirement.UpstreamModel;
import org.topcased.requirement.core.extensions.IModelAttachmentPolicy;
import org.topcased.requirement.core.extensions.IRequirementFactoryProvider;
import org.topcased.requirement.core.extensions.ModelAttachmentPolicyManager;
import org.topcased.requirement.merge.Activator;
import org.topcased.requirement.merge.utils.Couple;
import org.topcased.requirement.util.RequirementResource;
public class Merge
{
private Map<String, Boolean> inputs;
private Vector<Couple> models;
private RequirementProject requirementProject;
private RequirementFactory factory = RequirementFactory.eINSTANCE;
private Map<EObject, HierarchicalElement> objectsCreated = new HashMap<EObject, HierarchicalElement>();
private String output;
private IProgressMonitor thisMonitor;
private ProblemChapter theProblemChapter;
private UntracedChapter theUntracedChapter;
public Merge(Map<String, Boolean> inputs, String output)
{
super();
this.inputs = inputs;
this.output = output;
models = new Vector<Couple>();
}
public void process()
{
process(new NullProgressMonitor());
}
public void process(IProgressMonitor monitor)
{
try
{
final IProgressMonitor old = monitor ;
long time = System.currentTimeMillis() ;
if (Activator.getDefault().shouldTrace())
{
Activator.getDefault().log("Start process
}
thisMonitor = monitor;
if (thisMonitor == null)
{
thisMonitor = new NullProgressMonitor();
}
if (Activator.getDefault().shouldTrace())
{
thisMonitor = new TimeProgressMonitor(time, thisMonitor);
}
thisMonitor.beginTask("Process Filter", 7);
this.getRequirementsFile();
thisMonitor.worked(1);
if (models.size() > 0)
{
this.initRequirementFile();
thisMonitor.worked(1);
this.initAttributeUpstream();
thisMonitor.worked(1);
this.mergeOtherCategory();
thisMonitor.worked(1);
this.initStructureRequirment();
thisMonitor.worked(1);
this.copyRequirement();
thisMonitor.worked(1);
this.filter();
thisMonitor.worked(1);
this.save();
if (Activator.getDefault().shouldTrace())
{
time = System.currentTimeMillis() - time ;
Activator.getDefault().log("End : " + time);
}
}
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
monitor.done();
}
}
private void filter()
{
AdapterFactoryEditingDomain domain = new AdapterFactoryEditingDomain(new ReflectiveItemProviderAdapterFactory(), new BasicCommandStack());
CompoundCommand command = new CompoundCommand();
Collection<HierarchicalElement> todeletes = new LinkedList<HierarchicalElement>();
for (HierarchicalElement h : requirementProject.getHierarchicalElement())
{
if (delete(h, domain, command))
{
todeletes.add(h);
}
}
for (HierarchicalElement h : todeletes)
{
command.append(DeleteCommand.create(domain, h));
}
domain.getCommandStack().execute(command);
}
private boolean delete(HierarchicalElement root, AdapterFactoryEditingDomain domain, CompoundCommand command)
{
boolean deleteMe = true;
Collection<HierarchicalElement> todeletes = new LinkedList<HierarchicalElement>();
if (!root.getRequirement().isEmpty())
{
deleteMe = false;
}
for (HierarchicalElement h : root.getChildren())
{
if (!(h instanceof CurrentRequirement))
{
if (delete(h, domain, command))
{
todeletes.add(h);
}
else
{
deleteMe = false;
}
}
}
if (!deleteMe)
{
for (HierarchicalElement h : todeletes)
{
command.append(DeleteCommand.create(domain, h));
}
}
return deleteMe;
}
private void save()
{
try
{
requirementProject.eResource().save(Collections.EMPTY_MAP);
}
catch (IOException e)
{
e.printStackTrace();
}
}
public void getRequirementsFile()
{
SubProgressMonitor subMonitor = new SubProgressMonitor(thisMonitor, 1);
Set<String> keys = inputs.keySet();
Iterator<String> it = keys.iterator();
subMonitor.beginTask("Get requirements", keys.size());
// for each inputs
while (it.hasNext())
{
// Get the diagram
String file = it.next();
URI uri = URI.createURI(file);
IModelAttachmentPolicy policy = ModelAttachmentPolicyManager.getInstance().getModelPolicy(uri.fileExtension());
ResourceSet resourceSetImpl = createResourceSet(policy);
EObject eobject = resourceSetImpl.getResource(uri, true).getContents().get(0);
// if (eobject instanceof Diagrams)
{
RequirementProject project = null;
// Diagrams diagram = (Diagrams) eobject;
// Get the associated requirement model
if (policy != null)
{
project = policy.getRequirementProjectFromTargetMainResource(eobject.eResource());
}
if (project != null)
{
// get the associate model
// URI uriDiagram = URI.createURI(file.substring(0, file.length() - 2));
EObject eobjectModel = getModelObject(project);
// Create a new Triplet
Couple t = new Couple(eobjectModel, project, inputs.get(file));
// Triplet t = new Triplet(eobjectModel, (Diagrams) eobject, project, inputs.get(file));
models.add(t);
}
}
subMonitor.worked(1);
}
}
protected EObject getModelObject(RequirementProject project) {
// FIXME when generic methods will exist
for (Iterator<EObject> i = EcoreUtil.getAllProperContents(project, false) ; i.hasNext() ; )
{
EObject next = i.next();
if (next instanceof HierarchicalElement) {
HierarchicalElement h = (HierarchicalElement) next;
EObject element = h.getElement();
if (element != null && element.eResource() != null)
{
Resource eResource = project.eResource();
if (eResource != null && eResource.getURI() != null && element.eResource().getURI() != null)
{
if (eResource.getURI().trimFileExtension().equals(element.eResource().getURI().trimFileExtension()))
{
return element.eResource().getContents().get(0);
}
}
}
}
}
return null;
}
public void initRequirementFile()
{
requirementProject = factory.createRequirementProject();
ResourceSet set = createResourceSet(null);
Resource r = set.createResource(URI.createURI(output));
r.getContents().add(requirementProject);
}
private ResourceSet createResourceSet(IModelAttachmentPolicy policy) {
if (policy instanceof IRequirementFactoryProvider)
{
IRequirementFactoryProvider provider = (IRequirementFactoryProvider) policy;
if (provider.provides(ResourceSet.class))
{
return provider.create(ResourceSet.class);
}
}
return new ResourceSetImpl();
}
public void initAttributeUpstream()
{
// Add upstream model
requirementProject.setUpstreamModel((UpstreamModel) EcoreUtil.copy(models.get(0).getRequirement().getUpstreamModel()));
// Add attribute configuration
requirementProject.setAttributeConfiguration((AttributeConfiguration) EcoreUtil.copy(models.get(0).getRequirement().getAttributeConfiguration()));
// Add problemChapter folder
theProblemChapter = (ProblemChapter) EcoreUtil.copy(getProblemChapter(models.get(0).getRequirement()));
theProblemChapter.getRequirement().clear();
requirementProject.getChapter().add(theProblemChapter);
// Add TrashChapter folder
TrashChapter theTrashChapter = (TrashChapter) EcoreUtil.copy(getTrashChapter(models.get(0).getRequirement()));
theTrashChapter.getRequirement().clear();
requirementProject.getChapter().add(theTrashChapter);
// Add UntracedChapter folder
theUntracedChapter = (UntracedChapter) EcoreUtil.copy(getUntracedChapter(models.get(0).getRequirement()));
theUntracedChapter.getRequirement().clear();
requirementProject.getChapter().add(theUntracedChapter);
}
private void mergeOtherCategory()
{
// For all models
for (Iterator<Couple> iterator = models.iterator(); iterator.hasNext();)
{
Couple t = (Couple) iterator.next();
// get the current requirement
RequirementProject r = t.getRequirement();
// Add problems
List<Requirement> problemChapterRequirement = getProblemChapterRequirement(r);
if (problemChapterRequirement != null)
{
for (Requirement p : problemChapterRequirement)
{
// If the problem is not present
if (!this.contains(getProblemChapterRequirement(requirementProject), p))
{
// Add the problem
if (theProblemChapter != null)
{
copyAndAdd(p, theProblemChapter);
}
}
}
}
// Add untraced
List<Requirement> untracedChapterRequirement = getUntracedChapterRequirement(r);
if (untracedChapterRequirement != null)
{
for (Requirement u : untracedChapterRequirement)
{
// If the problem is not present
if (!this.contains(getUntracedChapterRequirement(requirementProject), u))
{
// Add the problem
if (theUntracedChapter != null)
{
copyAndAdd(u, theUntracedChapter);
}
}
}
}
}
}
private boolean contains(List<Requirement> list, Requirement r)
{
boolean contain = false;
for (Requirement rCurrent : list)
{
if (EcoreUtil.equals(rCurrent, r))
{
contain = true;
}
}
return contain;
}
private void initStructureRequirment()
{
for (Iterator<Couple> iterator = models.iterator(); iterator.hasNext();)
{
Couple t = (Couple) iterator.next();
EObject model = t.getModel();
// if it is not a sub model
if (!t.isSubModel())
{
HierarchicalElement h = createHierachicalElement(model);
// Add the hierarchical element to the
// currentHierarchicalElement
requirementProject.getHierarchicalElement().add(h);
addHierarchicalElement(h, model.eContents());
}
}
}
private void addHierarchicalElement(HierarchicalElement currentHierarchicalElement, EList<EObject> list)
{
for (EObject object : list)
{
// Create a hierarchical element link to o
HierarchicalElement h = createHierachicalElement(object);
// Add the hierarchical element to the currentHierarchicalElement
currentHierarchicalElement.getChildren().add(h);
// Add all object sub element to h
if (object.eContents().size() > 0)
{
addHierarchicalElement(h, object.eContents());
}
}
}
private HierarchicalElement createHierachicalElement(EObject object)
{
HierarchicalElement h = factory.createHierarchicalElement();
h.setElement(object);
objectsCreated.put(object, h);
return h;
}
private List<Requirement> getProblemChapterRequirement(RequirementProject r)
{
ProblemChapter u = getProblemChapter(r);
if (u != null)
{
return u.getRequirement();
}
return null;
}
private ProblemChapter getProblemChapter(RequirementProject r)
{
// Get all chapter
for (SpecialChapter s : r.getChapter())
{
if (s instanceof ProblemChapter)
{
return (ProblemChapter) s;
}
}
return null;
}
private List<Requirement> getUntracedChapterRequirement(RequirementProject r)
{
UntracedChapter u = getUntracedChapter(r);
if (u != null)
{
return u.getRequirement();
}
return null;
}
private UntracedChapter getUntracedChapter(RequirementProject r)
{
// Get all chapter
for (SpecialChapter s : r.getChapter())
{
if (s instanceof UntracedChapter)
{
return (UntracedChapter) s;
}
}
return null;
}
private TrashChapter getTrashChapter(RequirementProject r)
{
// Get all chapter
for (SpecialChapter s : r.getChapter())
{
if (s instanceof TrashChapter)
{
return (TrashChapter) s;
}
}
return null;
}
private void copyRequirement()
{
for (Iterator<Couple> iterator = models.iterator(); iterator.hasNext();)
{
Couple t = (Couple) iterator.next();
addRequirements(t);
}
}
private void addRequirements(Couple t)
{
for (TreeIterator<EObject> i = t.getRequirement().eAllContents(); i.hasNext();)
{
EObject tmp = i.next();
if (tmp instanceof CurrentRequirement)
{
CurrentRequirement current = (CurrentRequirement) tmp;
if (current.eContainer() instanceof HierarchicalElement)
{
HierarchicalElement hier = (HierarchicalElement) current.eContainer();
EObject element = hier.getElement();
if (element.eIsProxy())
{
element = (EObject) hier.eGet(RequirementPackage.Literals.HIERARCHICAL_ELEMENT__ELEMENT, true);
}
if (element != null && !element.eIsProxy())
{
HierarchicalElement hierToAdd = get(hier.getElement());
if (hierToAdd != null)
{
copyAndAdd(current, hierToAdd);
}
}
}
}
}
}
private HierarchicalElement get(EObject samElement)
{
for (EObject o : objectsCreated.keySet())
{
if (EcoreUtil.equals(o, samElement))
{
return objectsCreated.get(o);
}
}
return null;
}
private void copyAndAdd(CurrentRequirement current, HierarchicalElement hierToAdd)
{
Requirement copy = (Requirement) EcoreUtil.copy(current);
hierToAdd.getRequirement().add(copy);
assignLink(copy);
}
private void copyAndAdd(Requirement current, SpecialChapter chapter)
{
Requirement copy = (Requirement) EcoreUtil.copy(current);
chapter.getRequirement().add(copy);
assignLink(copy);
}
private void assignLink(Requirement copy)
{
for (Attribute a : copy.getAttribute())
{
if (a instanceof AttributeLink)
{
AttributeLink link = (AttributeLink) a;
if (link.getValue() != null)
{
Resource resource = link.getValue().eResource();
if (RequirementResource.FILE_EXTENSION.equals(resource.getURI().fileExtension()) && resource != copy.eResource())
{
link.setValue(getEquivalent(copy.eResource(), link.getValue()));
}
}
}
}
}
private EObject getEquivalent(Resource resource, EObject value)
{
for (TreeIterator<EObject> i = resource.getAllContents(); i.hasNext();)
{
EObject tmp = i.next();
if (EcoreUtil.equals(value, tmp))
{
return tmp;
}
}
return null;
}
private class TimeProgressMonitor implements IProgressMonitor
{
private final long time;
private final IProgressMonitor old;
private int sum = 0 ;
public TimeProgressMonitor (long time, IProgressMonitor old)
{
this.time = time;
this.old = old;
}
public void worked(int work) {
old.worked(work);
sum++;
long newTime = System.currentTimeMillis() - time ;
Activator.getDefault().log("-- step : " + sum + " / " + newTime);
}
public void subTask(String name) {
old.subTask(name);
}
public void setTaskName(String name) {
old.setTaskName(name);
long newTime = System.currentTimeMillis() - time ;
Activator.getDefault().log("-- debut task : " + name + " / " + newTime);
}
public void setCanceled(boolean value) {
old.setCanceled(value);
}
public boolean isCanceled() {
return old.isCanceled();
}
public void internalWorked(double work) {
old.internalWorked(work);
}
public void done() {
old.done();
}
public void beginTask(String name, int totalWork) {
old.beginTask(name, totalWork);
long newTime = System.currentTimeMillis() - time ;
System.out.println("-- debut task : " + name + " / " + newTime);
}
}
}
|
package org.yakindu.sct.model.stext.ui;
import org.eclipse.ui.plugin.AbstractUIPlugin;
import org.eclipse.xtext.documentation.IEObjectDocumentationProvider;
import org.eclipse.xtext.ui.editor.contentassist.antlr.ParserBasedContentAssistContextFactory.StatefulFactory;
import org.eclipse.xtext.ui.editor.hover.DispatchingEObjectTextHover;
import org.eclipse.xtext.ui.editor.hover.IEObjectHover;
import org.eclipse.xtext.ui.editor.hover.IEObjectHoverProvider;
import org.yakindu.sct.model.stext.ui.contentassist.STextStatefulFactory;
import org.yakindu.sct.model.stext.ui.help.STextUserHelpDocumentationProvider;
import com.google.inject.Binder;
import com.google.inject.name.Names;
import de.itemis.utils.jface.viewers.help.CrossRefObjectTextHover;
import de.itemis.utils.jface.viewers.help.HelpHoverProvider;
/**
* Use this class to register components to be used within the IDE.
*/
public class STextUiModule extends
org.yakindu.sct.model.stext.ui.AbstractSTextUiModule {
public static final String STEXT_LANGUAGE_NAME = "org.yakindu.sct.model.stext.SText";
public STextUiModule(AbstractUIPlugin plugin) {
super(plugin);
}
public Class<? extends StatefulFactory> bindStatefulFactory() {
return STextStatefulFactory.class;
}
public Class<? extends IEObjectDocumentationProvider> bindIEObjectDocumentationProvider() {
return STextUserHelpDocumentationProvider.class;
}
public Class<? extends DispatchingEObjectTextHover> bindDispatchingEObjectTextHover() {
return CrossRefObjectTextHover.class;
}
public Class<? extends IEObjectHoverProvider> bindIEObjectHoverProvider() {
return HelpHoverProvider.class;
}
@Override
public Class<? extends IEObjectHover> bindIEObjectHover() {
return CrossRefObjectTextHover.class;
}
@Override
public void configure(Binder binder) {
super.configure(binder);
binder.bind(String.class).annotatedWith(Names.named("stylesheet"))
.toInstance("/StextHoverStyleSheet.css");
}
}
|
package org.xcolab.portlets.contests;
import com.ext.portlet.model.Contest;
import com.ext.portlet.service.ContestLocalServiceUtil;
import com.liferay.portal.kernel.exception.PortalException;
import com.liferay.portal.kernel.exception.SystemException;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.portlet.PortletRequest;
import javax.portlet.PortletResponse;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
@Controller
@RequestMapping("view")
public class ContestsController {
public ContestsController() {
}
@RequestMapping
public String showContests(PortletRequest request, PortletResponse response, Model model) throws SystemException, PortalException {
ContestPreferences contestPreferences = new ContestPreferences(request);
List<ContestWrapper> ret = new ArrayList<>();
List<Contest> contests;
if (contestPreferences.getSelectedContests().length == 0) {
contests = ContestLocalServiceUtil.findByActiveFeatured(true,true);
} else {
contests = new ArrayList<>();
for (Long contestId : contestPreferences.getSelectedContests()) {
contests.add(ContestLocalServiceUtil.getContest(contestId));
}
}
Collections.shuffle(contests);
for (Contest contest: contests) {
if(ret.size() >= contestPreferences.getFeedSize()) {
break;
}
if (contest.getContestPrivate()) {
continue;
}
ret.add(new ContestWrapper(contest));
}
model.addAttribute("contests", ret);
model.addAttribute("title", contestPreferences.getTitle());
return "showContests";
}
}
|
package io.github.classgraph.issues;
import static org.assertj.core.api.Assertions.assertThat;
import java.io.File;
import java.util.List;
import org.junit.Test;
import io.github.classgraph.ClassGraph;
public class TestGetUniqueClasspathElements {
@Test
public void testGetUniqueClasspathElements() {
final List<File> classpathElements = new ClassGraph().whitelistPackages("com.xyz").getClasspathFiles();
assertThat(classpathElements).isNotEmpty();
}
}
|
package com.opengamma.integration.tool.portfolio;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import com.opengamma.OpenGammaRuntimeException;
import com.opengamma.component.tool.AbstractTool;
import com.opengamma.financial.tool.ToolContext;
import com.opengamma.integration.copier.portfolio.PortfolioCopier;
import com.opengamma.integration.copier.portfolio.PortfolioCopierVisitor;
import com.opengamma.integration.copier.portfolio.QuietPortfolioCopierVisitor;
import com.opengamma.integration.copier.portfolio.SimplePortfolioCopier;
import com.opengamma.integration.copier.portfolio.VerbosePortfolioCopierVisitor;
import com.opengamma.integration.copier.portfolio.reader.MasterPortfolioReader;
import com.opengamma.integration.copier.portfolio.reader.PortfolioReader;
import com.opengamma.integration.copier.portfolio.rowparser.JodaBeanRowParser;
import com.opengamma.integration.copier.portfolio.writer.DummyPortfolioWriter;
import com.opengamma.integration.copier.portfolio.writer.PortfolioWriter;
import com.opengamma.integration.copier.portfolio.writer.SingleSheetSimplePortfolioWriter;
import com.opengamma.integration.copier.portfolio.writer.ZippedPortfolioWriter;
import com.opengamma.integration.copier.sheet.SheetFormat;
/**
* The portfolio saver tool
*/
public class PortfolioSaverTool extends AbstractTool {
/** File name option flag */
private static final String FILE_NAME_OPT = "f";
/** Portfolio name option flag*/
private static final String PORTFOLIO_NAME_OPT = "n";
/** Write option flag */
private static final String WRITE_OPT = "w";
/** Verbose option flag */
private static final String VERBOSE_OPT = "v";
/** Asset class flag */
private static final String SECURITY_TYPE_OPT = "s";
private static ToolContext s_context;
/**
* Main method to run the tool.
*
* @param args the arguments, not null
*/
public static void main(String[] args) { //CSIGNORE
new PortfolioSaverTool().initAndRun(args);
System.exit(0);
}
/**
* Loads the test portfolio into the position master.
*/
@Override
protected void doRun() {
s_context = getToolContext();
// Construct portfolio reader
PortfolioReader portfolioReader = constructPortfolioReader(
getCommandLine().getOptionValue(PORTFOLIO_NAME_OPT)
);
// Create portfolio writer
PortfolioWriter portfolioWriter = constructPortfolioWriter(
getCommandLine().getOptionValue(FILE_NAME_OPT),
getCommandLine().getOptionValue(SECURITY_TYPE_OPT),
getCommandLine().hasOption(WRITE_OPT)
);
// Construct portfolio copier
PortfolioCopier portfolioCopier = new SimplePortfolioCopier();
// Create visitor for verbose/quiet mode
PortfolioCopierVisitor portfolioCopierVisitor;
if (getCommandLine().hasOption(VERBOSE_OPT)) {
portfolioCopierVisitor = new VerbosePortfolioCopierVisitor();
} else {
portfolioCopierVisitor = new QuietPortfolioCopierVisitor();
}
// Call the portfolio loader with the supplied arguments
portfolioCopier.copy(portfolioReader, portfolioWriter, portfolioCopierVisitor);
// close stuff
portfolioReader.close();
portfolioWriter.close();
}
private static PortfolioWriter constructPortfolioWriter(String filename, String securityType, boolean write) {
if (write) {
// Check that the file name was specified on the command line
if (filename == null) {
throw new OpenGammaRuntimeException("File name omitted, cannot export to file");
}
if (SheetFormat.of(filename) == SheetFormat.CSV || SheetFormat.of(filename) == SheetFormat.XLS) {
// if (securityType.equalsIgnoreCase("exchangetraded")) {
// return new SingleSheetSimplePortfolioWriter(filename, new ExchangeTradedRowParser(s_context.getBloombergSecuritySource()));
// } else {
return new SingleSheetSimplePortfolioWriter(filename, JodaBeanRowParser.newJodaBeanRowParser(securityType));
} else if (SheetFormat.of(filename) == SheetFormat.ZIP) {
return new ZippedPortfolioWriter(filename);
} else {
throw new OpenGammaRuntimeException("Input filename should end in .CSV, .XLS or .ZIP");
}
} else {
// Create a dummy portfolio writer to pretty-print instead of persisting
return new DummyPortfolioWriter();
}
}
private static PortfolioReader constructPortfolioReader(String portfolioName) {
return new MasterPortfolioReader(
portfolioName, s_context.getPortfolioMaster(),
s_context.getPositionMaster(),
s_context.getSecuritySource()
);
}
@Override
protected Options createOptions(boolean contextProvided) {
Options options = super.createOptions(contextProvided);
Option filenameOption = new Option(
FILE_NAME_OPT, "filename", true, "The path to the file to create and export to (CSV, XLS or ZIP)");
filenameOption.setRequired(true);
options.addOption(filenameOption);
Option portfolioNameOption = new Option(
PORTFOLIO_NAME_OPT, "name", true, "The name of the source OpenGamma portfolio");
options.addOption(portfolioNameOption);
Option writeOption = new Option(
WRITE_OPT, "write", false,
"Actually persists the portfolio to the file if specified, otherwise pretty-prints without persisting");
options.addOption(writeOption);
Option assetClassOption = new Option(
SECURITY_TYPE_OPT, "securitytype", true,
"The security type to export (ignored if ZIP output file is specified)");
options.addOption(assetClassOption);
Option verboseOption = new Option(
VERBOSE_OPT, "verbose", false,
"Displays progress messages on the terminal");
options.addOption(verboseOption);
return options;
}
}
|
package io.jenkins.plugins.analysis.warnings;
import com.tngtech.archunit.core.domain.JavaClasses;
import com.tngtech.archunit.core.importer.ClassFileImporter;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
/**
* Defines several architecture rules for the static analysis utilities.
*
* @author Ullrich Hafner
*/
@SuppressFBWarnings("NM")
class ArchitectureRulesTest extends io.jenkins.plugins.analysis.core.testutil.ArchitectureRulesTest {
@Override
protected JavaClasses getAllClasses() {
return new ClassFileImporter().importPackages("io.jenkins.plugins.analysis.warnings");
}
}
|
package org.epics.pvmanager.formula;
import java.util.Arrays;
import java.util.List;
import org.epics.util.time.TimeDuration;
import org.epics.vtype.Alarm;
import org.epics.vtype.AlarmSeverity;
import org.epics.vtype.Time;
import org.epics.vtype.VNumber;
import org.junit.Test;
import static org.epics.vtype.ValueFactory.*;
/**
*
* @author carcassi
*/
public class NumberOperatorFunctionSetTest extends BaseTestForFormula {
private static FormulaFunctionSet set = new NumberOperatorFunctionSet();
@Test
public void sum() {
FunctionTester.findByName(set, "+")
.compareReturnValue(3.0, 1.0, 2.0)
.compareReturnValue(-1.0, 1.0, -2.0)
.compareReturnValue(null, newVDouble(1.0), null)
.compareReturnValue(null, null, newVDouble(1.0))
.highestAlarmReturned()
.latestTimeReturned();
}
@Test
public void subtract() {
FunctionTester.findBySignature(set, "-", VNumber.class, VNumber.class)
.compareReturnValue(-1.0, 1.0, 2.0)
.compareReturnValue(3.0, 1.0, -2.0)
.compareReturnValue(null, newVDouble(1.0), null)
.compareReturnValue(null, null, newVDouble(1.0))
.highestAlarmReturned()
.latestTimeReturned();
}
@Test
public void negate() {
FunctionTester.findBySignature(set, "-", VNumber.class)
.compareReturnValue(-1.0, 1.0)
.compareReturnValue(2.0, -2.0)
.compareReturnValue(null, (Object) null)
.highestAlarmReturned()
.latestTimeReturned();
}
@Test
public void multiply() {
FunctionTester.findByName(set, "*")
.compareReturnValue(10.0, 2.0, 5.0)
.compareReturnValue(-6.0, 3.0, -2.0)
.compareReturnValue(null, newVDouble(1.0), null)
.compareReturnValue(null, null, newVDouble(1.0))
.highestAlarmReturned()
.latestTimeReturned();
}
@Test
public void divide() {
FunctionTester.findByName(set, "/")
.compareReturnValue(4.0, 8.0, 2.0)
.compareReturnValue(-0.5, 1.0, -2.0)
.compareReturnValue(null, newVDouble(1.0), null)
.compareReturnValue(null, null, newVDouble(1.0))
.highestAlarmReturned()
.latestTimeReturned();
}
@Test
public void remainder() {
FunctionTester.findByName(set, "%")
.compareReturnValue(0.0, 8.0, 2.0)
.compareReturnValue(1.0, 3.0, 2.0)
.compareReturnValue(null, newVDouble(1.0), null)
.compareReturnValue(null, null, newVDouble(1.0))
.highestAlarmReturned()
.latestTimeReturned();
}
@Test
public void pow() {
FunctionTester.findByName(set, "^")
.compareReturnValue(64.0, 8.0, 2.0)
.compareReturnValue(2.0, 4.0, 0.5)
.compareReturnValue(null, newVDouble(1.0), null)
.compareReturnValue(null, null, newVDouble(1.0))
.highestAlarmReturned()
.latestTimeReturned();
}
@Test
public void lessThanOrEqual() {
FunctionTester.findByName(set, "<=")
.compareReturnValue(true, 1.0, 2.0)
.compareReturnValue(true, 2.0, 2.0)
.compareReturnValue(false, 2.0, 1.0)
.compareReturnValue(null, newVDouble(1.0), null)
.compareReturnValue(null, null, newVDouble(1.0))
.highestAlarmReturned()
.latestTimeReturned();
}
@Test
public void greaterThanOrEqual() {
FunctionTester.findByName(set, ">=")
.compareReturnValue(false, 1.0, 2.0)
.compareReturnValue(true, 2.0, 2.0)
.compareReturnValue(true, 2.0, 1.0)
.compareReturnValue(null, newVDouble(1.0), null)
.compareReturnValue(null, null, newVDouble(1.0))
.highestAlarmReturned()
.latestTimeReturned();
}
@Test
public void lessThan() {
FunctionTester.findByName(set, "<")
.compareReturnValue(true, 1.0, 2.0)
.compareReturnValue(false, 2.0, 2.0)
.compareReturnValue(false, 2.0, 1.0)
.compareReturnValue(null, newVDouble(1.0), null)
.compareReturnValue(null, null, newVDouble(1.0))
.highestAlarmReturned()
.latestTimeReturned();
}
@Test
public void greaterThan() {
FunctionTester.findByName(set, ">")
.compareReturnValue(false, 1.0, 2.0)
.compareReturnValue(false, 2.0, 2.0)
.compareReturnValue(true, 2.0, 1.0)
.compareReturnValue(null, newVDouble(1.0), null)
.compareReturnValue(null, null, newVDouble(1.0))
.highestAlarmReturned()
.latestTimeReturned();
}
@Test
public void equal() {
FunctionTester.findByName(set, "==")
.compareReturnValue(false, 1.0, 2.0)
.compareReturnValue(true, 2.0, 2.0)
.compareReturnValue(false, 2.0, 1.0)
.compareReturnValue(null, newVDouble(1.0), null)
.compareReturnValue(null, null, newVDouble(1.0))
.highestAlarmReturned()
.latestTimeReturned();
}
@Test
public void notEqual() {
FunctionTester.findByName(set, "!=")
.compareReturnValue(true, 1.0, 2.0)
.compareReturnValue(false, 2.0, 2.0)
.compareReturnValue(true, 2.0, 1.0)
.compareReturnValue(null, newVDouble(1.0), null)
.compareReturnValue(null, null, newVDouble(1.0))
.highestAlarmReturned()
.latestTimeReturned();
}
@Test
public void conditionalOr() {
FunctionTester.findByName(set, "||")
.compareReturnValue(true, true, true)
.compareReturnValue(true, true, false)
.compareReturnValue(true, false, true)
.compareReturnValue(false, false, false)
.compareReturnValue(null, true, null)
.compareReturnValue(null, null, true)
.highestAlarmReturned()
.latestTimeReturned();
}
@Test
public void conditionalAnd() {
FunctionTester.findByName(set, "&&")
.compareReturnValue(true, true, true)
.compareReturnValue(false, true, false)
.compareReturnValue(false, false, true)
.compareReturnValue(false, false, false)
.compareReturnValue(null, true, null)
.compareReturnValue(null, null, true)
.highestAlarmReturned()
.latestTimeReturned();
}
@Test
public void bitwiseXOR() {
Alarm none = alarmNone();
Alarm minor = newAlarm(AlarmSeverity.MINOR, "LOW");
Time time1 = timeNow();
Time time2 = newTime(time1.getTimestamp().plus(TimeDuration.ofMillis(100)));
FunctionTester.findByName(set, "xor")
.compareReturnValue(0b0110, 0b1100, 0b1010)
.compareReturnValue(null, 0b1100, null)
.compareReturnValue(null, null, 0b1010)
.compareReturnAlarm(none, newVNumber(1, none, timeNow(), displayNone()), newVNumber(1, none, timeNow(), displayNone()))
.compareReturnAlarm(minor, newVNumber(1, minor, timeNow(), displayNone()), newVNumber(1, none, timeNow(), displayNone()))
.compareReturnAlarm(minor, newVNumber(1, none, timeNow(), displayNone()), newVNumber(1, minor, timeNow(), displayNone()))
.compareReturnTime(time1, newVNumber(1, none, time1, displayNone()), newVNumber(1, minor, time1, displayNone()))
.compareReturnTime(time2, newVNumber(1, none, time2, displayNone()), newVNumber(1, minor, time1, displayNone()))
.compareReturnTime(time2, newVNumber(1, none, time1, displayNone()), newVNumber(1, minor, time2, displayNone()));
}
@Test
public void bitwiseOR() {
Alarm none = alarmNone();
Alarm minor = newAlarm(AlarmSeverity.MINOR, "LOW");
Time time1 = timeNow();
Time time2 = newTime(time1.getTimestamp().plus(TimeDuration.ofMillis(100)));
FunctionTester.findByName(set, "or")
.compareReturnValue(0b1110, 0b1100, 0b1010)
.compareReturnValue(null, 0b1100, null)
.compareReturnValue(null, null, 0b1010)
.compareReturnAlarm(none, newVNumber(1, none, timeNow(), displayNone()), newVNumber(1, none, timeNow(), displayNone()))
.compareReturnAlarm(minor, newVNumber(1, minor, timeNow(), displayNone()), newVNumber(1, none, timeNow(), displayNone()))
.compareReturnAlarm(minor, newVNumber(1, none, timeNow(), displayNone()), newVNumber(1, minor, timeNow(), displayNone()))
.compareReturnTime(time1, newVNumber(1, none, time1, displayNone()), newVNumber(1, minor, time1, displayNone()))
.compareReturnTime(time2, newVNumber(1, none, time2, displayNone()), newVNumber(1, minor, time1, displayNone()))
.compareReturnTime(time2, newVNumber(1, none, time1, displayNone()), newVNumber(1, minor, time2, displayNone()));
FunctionTester.findByName(set, "|")
.compareReturnValue(0b1110, 0b1100, 0b1010)
.compareReturnValue(null, 0b1100, null)
.compareReturnValue(null, null, 0b1010)
.compareReturnAlarm(none, newVNumber(1, none, timeNow(), displayNone()), newVNumber(1, none, timeNow(), displayNone()))
.compareReturnAlarm(minor, newVNumber(1, minor, timeNow(), displayNone()), newVNumber(1, none, timeNow(), displayNone()))
.compareReturnAlarm(minor, newVNumber(1, none, timeNow(), displayNone()), newVNumber(1, minor, timeNow(), displayNone()))
.compareReturnTime(time1, newVNumber(1, none, time1, displayNone()), newVNumber(1, minor, time1, displayNone()))
.compareReturnTime(time2, newVNumber(1, none, time2, displayNone()), newVNumber(1, minor, time1, displayNone()))
.compareReturnTime(time2, newVNumber(1, none, time1, displayNone()), newVNumber(1, minor, time2, displayNone()));
}
@Test
public void bitwiseAND() {
Alarm none = alarmNone();
Alarm minor = newAlarm(AlarmSeverity.MINOR, "LOW");
Time time1 = timeNow();
Time time2 = newTime(time1.getTimestamp().plus(TimeDuration.ofMillis(100)));
FunctionTester.findByName(set, "and")
.compareReturnValue(0b1000, 0b1100, 0b1010)
.compareReturnValue(null, 0b1100, null)
.compareReturnValue(null, null, 0b1010)
.compareReturnAlarm(none, newVNumber(1, none, timeNow(), displayNone()), newVNumber(1, none, timeNow(), displayNone()))
.compareReturnAlarm(minor, newVNumber(1, minor, timeNow(), displayNone()), newVNumber(1, none, timeNow(), displayNone()))
.compareReturnAlarm(minor, newVNumber(1, none, timeNow(), displayNone()), newVNumber(1, minor, timeNow(), displayNone()))
.compareReturnTime(time1, newVNumber(1, none, time1, displayNone()), newVNumber(1, minor, time1, displayNone()))
.compareReturnTime(time2, newVNumber(1, none, time2, displayNone()), newVNumber(1, minor, time1, displayNone()))
.compareReturnTime(time2, newVNumber(1, none, time1, displayNone()), newVNumber(1, minor, time2, displayNone()));
FunctionTester.findByName(set, "&")
.compareReturnValue(0b1000, 0b1100, 0b1010)
.compareReturnValue(null, 0b1100, null)
.compareReturnValue(null, null, 0b1010)
.compareReturnAlarm(none, newVNumber(1, none, timeNow(), displayNone()), newVNumber(1, none, timeNow(), displayNone()))
.compareReturnAlarm(minor, newVNumber(1, minor, timeNow(), displayNone()), newVNumber(1, none, timeNow(), displayNone()))
.compareReturnAlarm(minor, newVNumber(1, none, timeNow(), displayNone()), newVNumber(1, minor, timeNow(), displayNone()))
.compareReturnTime(time1, newVNumber(1, none, time1, displayNone()), newVNumber(1, minor, time1, displayNone()))
.compareReturnTime(time2, newVNumber(1, none, time2, displayNone()), newVNumber(1, minor, time1, displayNone()))
.compareReturnTime(time2, newVNumber(1, none, time1, displayNone()), newVNumber(1, minor, time2, displayNone()));
}
@Test
public void logicalNot() {
FunctionTester.findByName(set, "!")
.compareReturnValue(true, false)
.compareReturnValue(false, true)
.compareReturnValue(null, (Object) null)
.highestAlarmReturned()
.latestTimeReturned();
}
@Test
public void conditionalOperator() {
Alarm alarm1 = alarmNone();
Alarm alarm2 = newAlarm(AlarmSeverity.MINOR, "LOW");
Time time1 = timeNow();
Time time2 = newTime(time1.getTimestamp().plus(TimeDuration.ofMillis(100)));
FunctionTester.findByName(set, "?:")
.compareReturnValue(1, true, 1, 0)
.compareReturnValue(0, false, 1, 0)
.compareReturnValue(null, null, 1, 0)
.compareReturnValue(null, true, null, 0)
.compareReturnValue(1, true, 1, null)
.compareReturnValue(0, false, null, 0)
.compareReturnValue(null, false, 1, null)
.compareReturnAlarm(alarm1, true, alarm1, alarm2)
.compareReturnAlarm(alarm2, false, alarm1, alarm2)
.compareReturnTime(time1, true, time1, time2)
.compareReturnTime(time2, false, time1, time2);
}
@Test
public void enumIndexOfFunction(){
Alarm none = alarmNone();
List<String> labels = Arrays.asList("One", "Two", "Three");
FunctionTester.findByName(set, "indexOf")
.compareReturnValue(newVNumber(0, none, timeNow(), displayNone()), newVEnum(0, labels, none, timeNow()));
}
}
|
package org.clafer.choco.constraint;
import gnu.trove.set.TIntSet;
import gnu.trove.set.hash.TIntHashSet;
import org.chocosolver.solver.Model;
import static org.clafer.choco.constraint.ConstraintQuickTest.$;
import org.clafer.choco.constraint.ConstraintQuickTest.Check;
import org.clafer.choco.constraint.ConstraintQuickTest.Input;
import org.clafer.test.NonEmpty;
import org.clafer.test.Positive;
import static org.junit.Assert.assertTrue;
import static org.junit.Assume.assumeTrue;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.chocosolver.solver.constraints.Constraint;
import org.chocosolver.solver.variables.SetVar;
import static org.chocosolver.solver.variables.Var.*;
import org.clafer.test.NoCard;
/**
*
* @author jimmy
*/
@RunWith(ConstraintQuickTest.class)
public class TransitiveReflexiveClosureTest {
private void transitiveReflexiveClosure(TIntSet[] relation, int c, TIntSet closure) {
assertTrue(c >= 0 && c < relation.length);
closure.add(c);
relation[c].forEach(next -> {
if (closure.add(next)) {
transitiveReflexiveClosure(relation, next, closure);
}
return true;
});
}
@Input(solutions = 512)
public Object testTransitive(Model model) {
/*
* import Control.Monad
*
* powerset = filterM (const [True, False])
*
* solutions = do
* relation <- replicateM 3 $ powerset [0..2]
* return relation
*/
return $(model.setVarArray("relation", 3, ker(), env(0, 1, 2)),
model.setVarArray("closure", 3, ker(), env(0, 1, 2)));
}
@Check
public void check(TIntSet[] relation, TIntSet[] closure) {
for (int i = 0; i < relation.length; i++) {
TIntSet c = new TIntHashSet(relation.length);
transitiveReflexiveClosure(relation, i, c);
assertTrue(c.equals(closure[i]));
}
}
@Test(timeout = 300000)
public Constraint setup(
@NoCard @NonEmpty @Positive SetVar[] relation,
@NoCard @NonEmpty @Positive SetVar[] closure) {
System.out.println(System.getProperty("argLine"));
System.out.println(System.getProperties());
assumeTrue(relation.length == closure.length);
return Constraints.transitiveReflexiveClosure(relation, closure);
}
}
|
package org.sagebionetworks.web.client;
import static org.junit.Assert.*;
import static org.mockito.Matchers.*;
import static org.mockito.Mockito.*;
import static org.apache.http.HttpStatus.*;
import static org.sagebionetworks.web.shared.WebConstants.*;
import java.util.ArrayList;
import java.util.List;
import static org.sagebionetworks.web.client.SynapseJavascriptClient.*;
import static com.google.gwt.http.client.RequestBuilder.*;
import static org.sagebionetworks.client.exceptions.SynapseTooManyRequestsException.*;
import org.sagebionetworks.web.shared.exceptions.*;
import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.RequestException;
import com.google.gwt.user.client.rpc.AsyncCallback;
import org.sagebionetworks.web.shared.WikiPageKey;
import org.junit.*;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.sagebionetworks.client.exceptions.SynapseTooManyRequestsException;
import org.sagebionetworks.repo.model.EntityBundle;
import org.sagebionetworks.repo.model.EntityChildrenRequest;
import org.sagebionetworks.repo.model.FileEntity;
import org.sagebionetworks.repo.model.Folder;
import org.sagebionetworks.repo.model.Link;
import org.sagebionetworks.repo.model.ListWrapper;
import org.sagebionetworks.repo.model.ObjectType;
import org.sagebionetworks.repo.model.Preview;
import org.sagebionetworks.repo.model.Project;
import org.sagebionetworks.repo.model.RestrictableObjectType;
import org.sagebionetworks.repo.model.RestrictionInformationRequest;
import org.sagebionetworks.repo.model.Team;
import org.sagebionetworks.repo.model.UserProfile;
import org.sagebionetworks.repo.model.file.BatchFileRequest;
import org.sagebionetworks.repo.model.file.BatchFileResult;
import org.sagebionetworks.repo.model.principal.TypeFilter;
import org.sagebionetworks.repo.model.table.EntityView;
import org.sagebionetworks.repo.model.table.TableEntity;
import org.sagebionetworks.schema.adapter.JSONObjectAdapter;
import org.sagebionetworks.schema.adapter.JSONObjectAdapterException;
import org.sagebionetworks.schema.adapter.org.json.JSONObjectAdapterImpl;
import org.sagebionetworks.web.client.SynapseJavascriptFactory.OBJECT_TYPE;
import org.sagebionetworks.web.client.security.AuthenticationController;
import org.sagebionetworks.web.client.utils.Callback;
import com.google.gwt.http.client.Response;
public class SynapseJavascriptClientTest {
SynapseJavascriptClient client;
private static SynapseJavascriptFactory synapseJsFactory = new SynapseJavascriptFactory();
private static JSONObjectAdapter jsonObjectAdapter = new JSONObjectAdapterImpl();
public static final String REPO_ENDPOINT = "http://repo-endpoint/v1";
public static final String FILE_ENDPOINT = "http://file-endpoint/v1";
public static final String USER_SESSION_TOKEN = "abc123";
@Mock
RequestBuilderWrapper mockRequestBuilder;
@Mock
AuthenticationController mockAuthController;
@Mock
GlobalApplicationState mockGlobalAppState;
@Mock
GWTWrapper mockGwt;
@Captor
ArgumentCaptor<RequestCallback> requestCallbackCaptor;
@Mock
AsyncCallback mockAsyncCallback;
@Mock
Request mockRequest;
@Mock
Response mockResponse;
@Captor
ArgumentCaptor<Throwable> throwableCaptor;
@Captor
ArgumentCaptor<Callback> callbackCaptor;
@Captor
ArgumentCaptor<String> stringCaptor;
@Before
public void before() {
MockitoAnnotations.initMocks(this);
when(mockGlobalAppState.getSynapseProperty(REPO_SERVICE_URL_KEY)).thenReturn(REPO_ENDPOINT);
when(mockGlobalAppState.getSynapseProperty(FILE_SERVICE_URL_KEY)).thenReturn(FILE_ENDPOINT);
client = new SynapseJavascriptClient(
mockRequestBuilder,
mockAuthController,
jsonObjectAdapter,
mockGlobalAppState,
mockGwt,
synapseJsFactory);
}
@Test
public void testGetException() {
String reason = "error message";
assertTrue(getException(SC_UNAUTHORIZED, reason) instanceof UnauthorizedException);
assertTrue(getException(SC_FORBIDDEN, reason) instanceof ForbiddenException);
assertTrue(getException(SC_NOT_FOUND, reason) instanceof NotFoundException);
assertTrue(getException(SC_BAD_REQUEST, reason) instanceof BadRequestException);
assertTrue(getException(SC_LOCKED, reason) instanceof LockedException);
assertTrue(getException(SC_PRECONDITION_FAILED, reason) instanceof ConflictingUpdateException);
assertTrue(getException(SC_GONE, reason) instanceof BadRequestException);
assertTrue(getException(SynapseTooManyRequestsException.TOO_MANY_REQUESTS_STATUS_CODE, reason) instanceof TooManyRequestsException);
assertTrue(getException(-1, reason) instanceof UnknownErrorException);
}
@Test
public void testGetEntityBundleAnonymousSuccess() throws RequestException, JSONObjectAdapterException {
String entityId = "syn291";
int partsMask = 22;
client.getEntityBundle(entityId, partsMask, mockAsyncCallback);
//verify url and method
String url = REPO_ENDPOINT + ENTITY_URI_PATH + "/" + entityId + BUNDLE_MASK_PATH + partsMask;
verify(mockRequestBuilder).configure(GET, url);
verify(mockRequestBuilder).setHeader(ACCEPT, APPLICATION_JSON_CHARSET_UTF8);
verify(mockRequestBuilder, never()).setHeader(eq(SESSION_TOKEN_HEADER), anyString());
verify(mockRequestBuilder).sendRequest(eq((String)null), requestCallbackCaptor.capture());
RequestCallback requestCallback = requestCallbackCaptor.getValue();
EntityBundle testBundle = new EntityBundle();
JSONObjectAdapter adapter = jsonObjectAdapter.createNew();
testBundle.writeToJSONObject(adapter);
when(mockResponse.getStatusCode()).thenReturn(SC_OK);
when(mockResponse.getText()).thenReturn(adapter.toJSONString());
requestCallback.onResponseReceived(mockRequest, mockResponse);
verify(mockAsyncCallback).onSuccess(testBundle);
}
@Test
public void testGetEntityBundleForVersionLoggedInFailure() throws RequestException, JSONObjectAdapterException {
String entityId = "syn291";
int partsMask = 22;
Long versionNumber = 5L;
when(mockAuthController.isLoggedIn()).thenReturn(true);
when(mockAuthController.getCurrentUserSessionToken()).thenReturn(USER_SESSION_TOKEN);
client.getEntityBundleForVersion(entityId, versionNumber, partsMask, mockAsyncCallback);
//verify url and method
String url = REPO_ENDPOINT + ENTITY_URI_PATH + "/" + entityId + REPO_SUFFIX_VERSION + "/" + versionNumber + BUNDLE_MASK_PATH + partsMask;
verify(mockRequestBuilder).configure(GET, url);
verify(mockRequestBuilder).setHeader(ACCEPT, APPLICATION_JSON_CHARSET_UTF8);
verify(mockRequestBuilder).setHeader(SESSION_TOKEN_HEADER, USER_SESSION_TOKEN);
verify(mockRequestBuilder).sendRequest(eq((String)null), requestCallbackCaptor.capture());
RequestCallback requestCallback = requestCallbackCaptor.getValue();
when(mockResponse.getStatusCode()).thenReturn(SC_FORBIDDEN);
String statusText = "user is not allowed access";
when(mockResponse.getStatusText()).thenReturn(statusText);
requestCallback.onResponseReceived(mockRequest, mockResponse);
verify(mockAsyncCallback).onFailure(throwableCaptor.capture());
Throwable t = throwableCaptor.getValue();
assertTrue(t instanceof ForbiddenException);
assertEquals(statusText, t.getMessage());
}
@Test
public void testGetTeamWithRetry() throws RequestException, JSONObjectAdapterException {
String teamId = "9123";
client.getTeam(teamId, mockAsyncCallback);
//verify url and method
String url = REPO_ENDPOINT + TEAM + "/" + teamId;
verify(mockRequestBuilder).configure(GET, url);
verify(mockRequestBuilder).sendRequest(eq((String)null), requestCallbackCaptor.capture());
RequestCallback requestCallback = requestCallbackCaptor.getValue();
//simulate too many requests
when(mockResponse.getStatusCode()).thenReturn(TOO_MANY_REQUESTS_STATUS_CODE);
requestCallback.onResponseReceived(mockRequest, mockResponse);
//verify we'll try again later
verify(mockGwt).scheduleExecution(callbackCaptor.capture(), eq(RETRY_REQUEST_DELAY_MS));
//simulate retry
callbackCaptor.getValue().invoke();
verify(mockRequestBuilder, times(2)).sendRequest(eq((String)null), any(RequestCallback.class));
}
@Test
public void testPostRestrictionInformation() throws RequestException, JSONObjectAdapterException {
String subjectId = "syn9898782";
RestrictableObjectType type = RestrictableObjectType.ENTITY;
client.getRestrictionInformation(subjectId, type, mockAsyncCallback);
//verify url and method
String url = REPO_ENDPOINT + RESTRICTION_INFORMATION;
verify(mockRequestBuilder).configure(POST, url);
verify(mockRequestBuilder).setHeader(ACCEPT, APPLICATION_JSON_CHARSET_UTF8);
verify(mockRequestBuilder).setHeader(SynapseJavascriptClient.CONTENT_TYPE, APPLICATION_JSON_CHARSET_UTF8);
verify(mockRequestBuilder).sendRequest(stringCaptor.capture(), requestCallbackCaptor.capture());
//verify request data
String json = stringCaptor.getValue();
RestrictionInformationRequest request = new RestrictionInformationRequest(jsonObjectAdapter.createNew(json));
assertEquals(subjectId, request.getObjectId());
assertEquals(type, request.getRestrictableObjectType());
}
@Test
public void testPostEntityChildrenLoggedInWithRetry() throws RequestException, JSONObjectAdapterException {
EntityChildrenRequest entityChildrenRequest = new EntityChildrenRequest();
entityChildrenRequest.setParentId("syn982");
when(mockAuthController.isLoggedIn()).thenReturn(true);
when(mockAuthController.getCurrentUserSessionToken()).thenReturn(USER_SESSION_TOKEN);
client.getEntityChildren(entityChildrenRequest, mockAsyncCallback);
//verify url and method
String url = REPO_ENDPOINT + ENTITY_URI_PATH + CHILDREN;
verify(mockRequestBuilder).configure(POST, url);
verify(mockRequestBuilder).setHeader(ACCEPT, APPLICATION_JSON_CHARSET_UTF8);
verify(mockRequestBuilder).setHeader(SynapseJavascriptClient.CONTENT_TYPE, APPLICATION_JSON_CHARSET_UTF8);
verify(mockRequestBuilder).setHeader(SESSION_TOKEN_HEADER, USER_SESSION_TOKEN);
verify(mockRequestBuilder).sendRequest(stringCaptor.capture(), requestCallbackCaptor.capture());
String originalRequestString = stringCaptor.getValue();
// (no need to verify request object is correct, that's in another test)
RequestCallback requestCallback = requestCallbackCaptor.getValue();
//simulate too many requests
when(mockResponse.getStatusCode()).thenReturn(TOO_MANY_REQUESTS_STATUS_CODE);
requestCallback.onResponseReceived(mockRequest, mockResponse);
//verify we'll try again later
verify(mockGwt).scheduleExecution(callbackCaptor.capture(), eq(RETRY_REQUEST_DELAY_MS));
//simulate retry
callbackCaptor.getValue().invoke();
verify(mockRequestBuilder, times(2)).sendRequest(stringCaptor.capture(), any(RequestCallback.class));
//verify it retries the same request
assertEquals(originalRequestString, stringCaptor.getValue());
}
@Test
public void testGetVersionOfV2WikiPageAsV1() throws RequestException, JSONObjectAdapterException {
WikiPageKey key = new WikiPageKey();
String pageId = "222";
String ownerObjectId = "syn9834";
String ownerObjectType = ObjectType.ENTITY.name().toLowerCase();
Long versionNumber = 42L;
key.setWikiPageId(pageId);
key.setOwnerObjectId(ownerObjectId);
key.setOwnerObjectType(ownerObjectType);
client.getVersionOfV2WikiPageAsV1(key, versionNumber, mockAsyncCallback);
//verify url and method
String url = REPO_ENDPOINT + "/" + ownerObjectType + "/" + ownerObjectId + WIKI + pageId + WIKI_VERSION_PARAMETER + versionNumber;
verify(mockRequestBuilder).configure(GET, url);
}
@Test
public void testGetUserGroupHeadersByPrefix() throws RequestException, JSONObjectAdapterException {
String prefix = "hello";
when(mockGwt.encodeQueryString(anyString())).thenReturn(prefix);
TypeFilter typeFilter = TypeFilter.TEAMS_ONLY;
long limit = 10;
long offset = 0;
client.getUserGroupHeadersByPrefix(prefix, typeFilter, limit, offset, mockAsyncCallback);
//verify url and method
String url = REPO_ENDPOINT +
USER_GROUP_HEADER_PREFIX_PATH +
prefix + "&" +
LIMIT_PARAMETER + limit + "&" +
OFFSET_PARAMETER + offset +
TYPE_FILTER_PARAMETER + typeFilter.name();
verify(mockRequestBuilder).configure(GET, url);
}
@Test
public void testPostListUserProfiles() throws RequestException, JSONObjectAdapterException {
String userId1 = "32";
String userId2 = "8";
List<String> userIds = new ArrayList<>();
userIds.add(userId1);
userIds.add(userId2);
client.listUserProfiles(userIds, mockAsyncCallback);
//verify url and method
String url = REPO_ENDPOINT + USER_PROFILE_PATH;
verify(mockRequestBuilder).configure(POST, url);
verify(mockRequestBuilder).sendRequest(anyString(), requestCallbackCaptor.capture());
RequestCallback requestCallback = requestCallbackCaptor.getValue();
//we can use ListWrapper in junit (java) since it is not compiled into js.
ListWrapper<UserProfile> results = new ListWrapper<UserProfile>(UserProfile.class);
List<UserProfile> profiles = new ArrayList<UserProfile>();
UserProfile profile = new UserProfile();
profile.setOwnerId(userId1);
profiles.add(profile);
profile = new UserProfile();
profile.setOwnerId(userId2);
profiles.add(profile);
results.setList(profiles);
JSONObjectAdapter adapter = jsonObjectAdapter.createNew();
results.writeToJSONObject(adapter);
when(mockResponse.getStatusCode()).thenReturn(SC_OK);
when(mockResponse.getText()).thenReturn(adapter.toJSONString());
requestCallback.onResponseReceived(mockRequest, mockResponse);
verify(mockAsyncCallback).onSuccess(profiles);
}
@Test
public void testGetFavorites() throws RequestException, JSONObjectAdapterException {
client.getFavorites(mockAsyncCallback);
//verify url and method
String url = REPO_ENDPOINT +
FAVORITE_URI_PATH +
"?" +
OFFSET_PARAMETER + "0&" +
LIMIT_PARAMETER + "200";
verify(mockRequestBuilder).configure(GET, url);
}
@Test
public void testGetUserBundle() throws RequestException, JSONObjectAdapterException {
Long principalId = 8222L;
int mask = 23;
client.getUserBundle(principalId, mask, mockAsyncCallback);
//verify url and method
String url = REPO_ENDPOINT +
USER + "/" + principalId +
BUNDLE_MASK_PATH + mask;
verify(mockRequestBuilder).configure(GET, url);
}
@Test
public void testGetOpenMembershipInvitationCount() throws RequestException, JSONObjectAdapterException {
client.getOpenMembershipInvitationCount(mockAsyncCallback);
//verify url and method
String url = REPO_ENDPOINT +
OPEN_MEMBERSHIP_INVITATION_COUNT;
verify(mockRequestBuilder).configure(GET, url);
}
@Test
public void testGetOpenMembershipRequestCount() throws RequestException, JSONObjectAdapterException {
client.getOpenMembershipRequestCount(mockAsyncCallback);
//verify url and method
String url = REPO_ENDPOINT +
OPEN_MEMBERSHIP_REQUEST_COUNT;
verify(mockRequestBuilder).configure(GET, url);
}
@Test
public void testGetEntity() throws RequestException, JSONObjectAdapterException {
String entityId = "syn921";
client.getEntity(entityId, mockAsyncCallback);
//verify url and method
String url = REPO_ENDPOINT +
ENTITY_URI_PATH + "/" + entityId;
verify(mockRequestBuilder).configure(GET, url);
}
public void testGetForEntity() throws RequestException, JSONObjectAdapterException {
String entityId = "syn921";
Long versionNumber = 3L;
client.getEntityForVersion(entityId, versionNumber, mockAsyncCallback);
//verify url and method
String url = REPO_ENDPOINT +
ENTITY_URI_PATH + "/" + entityId +
REPO_SUFFIX_VERSION + "/" + versionNumber;
verify(mockRequestBuilder).configure(GET, url);
}
@Test
public void testGetNewEntityInstance() throws RequestException, JSONObjectAdapterException {
JSONObjectAdapter adapter = jsonObjectAdapter.createNew();
new FileEntity().writeToJSONObject(adapter);
assertTrue(synapseJsFactory.newInstance(OBJECT_TYPE.Entity, adapter) instanceof FileEntity);
adapter = jsonObjectAdapter.createNew();
new Folder().writeToJSONObject(adapter);
assertTrue(synapseJsFactory.newInstance(OBJECT_TYPE.Entity, adapter) instanceof Folder);
adapter = jsonObjectAdapter.createNew();
new EntityView().writeToJSONObject(adapter);
assertTrue(synapseJsFactory.newInstance(OBJECT_TYPE.Entity, adapter) instanceof EntityView);
adapter = jsonObjectAdapter.createNew();
new TableEntity().writeToJSONObject(adapter);
assertTrue(synapseJsFactory.newInstance(OBJECT_TYPE.Entity, adapter) instanceof TableEntity);
adapter = jsonObjectAdapter.createNew();
new Project().writeToJSONObject(adapter);
assertTrue(synapseJsFactory.newInstance(OBJECT_TYPE.Entity, adapter) instanceof Project);
adapter = jsonObjectAdapter.createNew();
new Link().writeToJSONObject(adapter);
assertTrue(synapseJsFactory.newInstance(OBJECT_TYPE.Entity, adapter) instanceof Link);
adapter = jsonObjectAdapter.createNew();
new Preview().writeToJSONObject(adapter);
assertTrue(synapseJsFactory.newInstance(OBJECT_TYPE.Entity, adapter) instanceof Preview);
}
@Test (expected=IllegalArgumentException.class)
public void testGetInvalidEntityInstance() throws RequestException, JSONObjectAdapterException {
// if using OBJECT_TYPE Entity, then json must represent a recognized subclass of Entity.
JSONObjectAdapter adapter = jsonObjectAdapter.createNew();
new Team().writeToJSONObject(adapter);
synapseJsFactory.newInstance(OBJECT_TYPE.Entity, adapter);
}
@Test
public void testGetFileHandleAndUrlBatch() throws RequestException, JSONObjectAdapterException {
BatchFileRequest fileRequest = new BatchFileRequest();
client.getFileHandleAndUrlBatch(fileRequest, mockAsyncCallback);
//verify url and method
String url = FILE_ENDPOINT + FILE_HANDLE_BATCH;
verify(mockRequestBuilder).configure(POST, url);
verify(mockRequestBuilder).sendRequest(anyString(), requestCallbackCaptor.capture());
RequestCallback requestCallback = requestCallbackCaptor.getValue();
//simulate "created" response (which is what this service returns if successful
BatchFileResult result = new BatchFileResult();
JSONObjectAdapter adapter = jsonObjectAdapter.createNew();
result.writeToJSONObject(adapter);
when(mockResponse.getStatusCode()).thenReturn(SC_CREATED);
when(mockResponse.getText()).thenReturn(adapter.toJSONString());
requestCallback.onResponseReceived(mockRequest, mockResponse);
verify(mockAsyncCallback).onSuccess(result);
}
}
|
package com.intuso.housemate.client.v1_0.real.impl.ioc;
import com.google.inject.AbstractModule;
import com.google.inject.Provides;
import com.google.inject.Scopes;
import com.google.inject.Singleton;
import com.intuso.housemate.client.v1_0.real.api.*;
import com.intuso.housemate.client.v1_0.real.impl.RealListImpl;
import com.intuso.housemate.client.v1_0.real.impl.RealRootImpl;
import com.intuso.housemate.client.v1_0.real.impl.annotations.ioc.RealAnnotationsModule;
import com.intuso.housemate.client.v1_0.real.impl.factory.ioc.RealFactoryModule;
import com.intuso.housemate.client.v1_0.real.impl.type.*;
import com.intuso.utilities.listener.ListenersFactory;
import com.intuso.utilities.log.Log;
public class RealObjectModule extends AbstractModule {
@Override
protected void configure() {
// install other required modules
install(new RealFactoryModule());
install(new RealAnnotationsModule());
bind(RealAutomation.Container.class).to(RealRootImpl.class);
bind(RealApplication.Container.class).to(RealRootImpl.class);
bind(RealDevice.Container.class).to(RealRootImpl.class);
bind(RealHardware.Container.class).to(RealRootImpl.class);
bind(RealType.Container.class).to(RealRootImpl.class);
bind(RealUser.Container.class).to(RealRootImpl.class);
// bind everything as singletons that should be
bind(ApplicationStatusType.class).in(Scopes.SINGLETON);
bind(ApplicationInstanceStatusType.class).in(Scopes.SINGLETON);
bind(BooleanType.class).in(Scopes.SINGLETON);
bind(DaysType.class).in(Scopes.SINGLETON);
bind(DoubleType.class).in(Scopes.SINGLETON);
bind(EmailType.class).in(Scopes.SINGLETON);
bind(IntegerType.class).in(Scopes.SINGLETON);
bind(StringType.class).in(Scopes.SINGLETON);
bind(TimeType.class).in(Scopes.SINGLETON);
bind(TimeUnitType.class).in(Scopes.SINGLETON);
}
@Provides
@Singleton
public RealList<RealType<?>> getTypes(Log log, ListenersFactory listenersFactory) {
return (RealList)new RealListImpl<>(log, listenersFactory, RealRootImpl.TYPES_ID, "Types", "Types");
}
}
|
package nars.inference;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import nars.core.Memory;
import nars.entity.BudgetValue;
import nars.entity.Concept;
import nars.entity.Sentence;
import nars.entity.Stamp;
import nars.entity.Task;
import nars.entity.TruthValue;
import static nars.inference.Executive.isPlanTerm;
import nars.io.Texts;
import nars.language.Conjunction;
import nars.language.Implication;
import nars.language.Interval;
import nars.language.Term;
import nars.operator.Operation;
import nars.util.graph.ImplicationGraph;
import nars.util.graph.ImplicationGraph.PostCondition;
public class GraphExecutive {
public final Memory memory;
public final ImplicationGraph implication;
final int maxConsecutiveIntervalTerms = 3;
/** controls the relative weigting of edges and vertices for particle traversals */
double conceptCostFactor = 0.5;
double edgeCostFactor = 1.0 - conceptCostFactor;
//for observation purposes, TODO enable/disable the maintenance of this
public final Map<Term,Double> accumulatedTerm = new HashMap();
public final Map<Sentence,Double> accumulatedSentence = new HashMap();
public GraphExecutive(Memory memory, Executive exec) {
super();
this.memory = memory;
this.implication = new ImplicationGraph(memory);
}
protected void accumulate(final Term t) {
accumulatedTerm.put(t, accumulatedTerm.getOrDefault(t, new Double(0)) + 1);
}
protected void accumulate(final Sentence s) {
accumulatedSentence.put(s, accumulatedTerm.getOrDefault(s, new Double(0)) + 1);
}
protected void accumulate(final Term t, final Sentence[] path) {
accumulate(t);
for (Sentence s : path)
accumulate(s);
}
/** returns maximum value */
public double fadeAccumulatedTerms(final double rate) {
double max = 0;
for (final Map.Entry<Term, Double> e : accumulatedTerm.entrySet()) {
double vv = e.getValue();
if (vv > max) max = vv;
e.setValue( vv * rate );
}
return max;
}
/** returns maximum value */
public double fadeAccumulatedSentences(double rate) {
double max = 0;
for (final Map.Entry<Sentence, Double> e : accumulatedSentence.entrySet()) {
double vv = e.getValue();
if (vv > max) max = vv;
e.setValue( vv * rate );
}
return max;
}
/** whether the Term is currently a valid goal for the implication graph to plan for */
public boolean isPlannable(final Term goal) {
PostCondition goalPostCondition = new PostCondition(goal);
/** must be in the graph and have at least one incoming edge */
if (implication.containsVertex(goalPostCondition)) {
return implication.inDegreeOf(goalPostCondition) > 0;
}
return false;
}
public class ParticlePath implements Comparable<ParticlePath> {
final public Term target;
Sentence[] bestPath;
double distance;
double score;
public ParticlePath(final Term target, final List<Sentence> path, final double distance) {
this.target = target;
addPath(path, distance);
}
public void addPath(final List<Sentence> p, final double dist) {
double newScore = 0;
for (Sentence s : p)
newScore += getSentenceRelevancy(s);
newScore /= ((double)p.size());
if ((this.bestPath == null) || (score < newScore)) {
this.bestPath = p.toArray(new Sentence[p.size()]);
this.distance = dist;
this.score = newScore;
}
}
@Override
public final int compareTo(final ParticlePath o) {
return Double.compare(o.score(), score());
}
@Override
public String toString() {
return "[" + Texts.n4((float)score()) + "|" + Texts.n4((float)distance) + "] "/*+ target */ + " <- " + Arrays.toString(bestPath);
}
/** can be used to favor the total activation, or short distnce, or combinations of other factors */
private double score() {
return score;
}
}
public class ParticleActivation {
private final ImplicationGraph graph;
/** caches sentence costs while traversing */
transient public final Map<Sentence, Double> sentenceCosts = new HashMap();
public final Map<Term, ParticlePath> termPaths = new HashMap();
TreeSet<ParticlePath> paths;
final boolean avoidCycles = true;
private int edgeDecisionPass = 0;
private int edgeDecisionFailCyclical = 0;
private int edgeDecisionFailInvalidVertex = 0;
private int edgeDecisionFailInactiveEdge = 0;
private int pathFailEmpty = 0;
private int pathFailNoOperation = 0;
private int pathsValid = 0;
private int numIterations = 0;
public ParticleActivation(ImplicationGraph graph) {
this.graph = graph;
}
public SortedSet<ParticlePath> activate(final Term source, final boolean forward, int iterations, double distance) {
//TODO cache pathways in the graph for faster traversal. must store source leading edge, destination(s) and their distances
List<Sentence> currentPath = new ArrayList();
Map<Sentence, Double> nextEdgeCost = new HashMap();
sentenceCosts.clear();
for (int i = 0; i < iterations; i++) {
numIterations++;
currentPath.clear();
double energy = distance;
Term currentVertex = source;
boolean choicesAvailable = false;
boolean operationTraversed = false;
while (energy > 0) {
Set<Sentence> graphEdges = forward ?
graph.outgoingEdgesOf(currentVertex) :
graph.incomingEdgesOf(currentVertex);
nextEdgeCost.clear();
Sentence currentSentence = null;
double totalProb = 0;
//remove edges which loop to the target goal precondition OR postcondition
for (final Sentence s : graphEdges) {
Term etarget = forward ?
getEdgeTarget(s):
getEdgeSource(s);
if ((avoidCycles) && (etarget == source)) {
edgeDecisionFailCyclical++;
continue;
}
if (!validVertex(etarget)) {
edgeDecisionFailInvalidVertex++;
continue;
}
double ew = getTraversalCost(s, etarget);
//ignore if this edge will cost more energy than allowed
if (ew > energy)
continue;
currentSentence = s;
totalProb += 1.0 / ew;
nextEdgeCost.put(currentSentence, ew);
/*if (ew >= ImplicationGraph.DEACTIVATED_EDGE_WEIGHT) {
edgeDecisionFailInactiveEdge++;
continue;
}*/
edgeDecisionPass++;
if (etarget instanceof Operation) {
operationTraversed = true;
}
}
if (nextEdgeCost.isEmpty()) {
//particle went as far as it can
break;
}
Sentence nextEdge;
if (nextEdgeCost.size() == 1) {
nextEdge = currentSentence;
}
else {
choicesAvailable = true;
nextEdge = chooseEdge(nextEdgeCost, totalProb);
}
currentPath.add(nextEdge);
energy -= nextEdgeCost.get(nextEdge);
currentVertex = forward ? getEdgeTarget(nextEdge) : getEdgeSource(nextEdge);
}
if (currentPath.isEmpty()) {
pathFailEmpty++;
continue;
}
if (!operationTraversed) {
pathFailNoOperation++;
continue;
}
ParticlePath ppath = termPaths.get(currentVertex);
if (ppath == null) {
termPaths.put(currentVertex,
ppath = new ParticlePath(source, currentPath, distance - energy));
}
else {
ppath.addPath(currentPath, distance - energy);
}
pathsValid++;
if (!choicesAvailable) {
//we've found the only path, so and we dont need to iterate any further
break;
}
}
this.paths = new TreeSet(termPaths.values());
for (ParticlePath p : this.paths) {
accumulate(p.target, p.bestPath);
//System.out.println(" " + p);
}
return this.paths;
}
/** total cost of a traversal, which includes the edge cost and the target vertex cost. any value > 1 */
public double getTraversalCost(final Sentence s, final Term target) {
Double d = sentenceCosts.get(s);
if (d!=null)
return d;
//sharpness parameter, affects how much cost is incurred for a low priority
double m = 0.1;
double conceptRelevancy;
if ((target instanceof Interval) || (target instanceof Operation))
conceptRelevancy = 1.0;
else
conceptRelevancy = getEffectivePriority(memory, target);
double sentenceRelevancy = getSentenceRelevancy(s);
double c = edgeCostFactor / (m + sentenceRelevancy) +
conceptCostFactor / (m + conceptRelevancy);
//System.out.println("s " + sentenceRelevancy + ", " + conceptRelevancy + " = " + c);
sentenceCosts.put(s, c);
return c;
}
/** choose a sentence according to a random probability
* where lower cost = higher probability. prob = 1.0 / ( 1 + cost )*/
public Sentence chooseEdge(Map<Sentence,Double> cost, double totalProb) {
Sentence nextEdge = null;
//TODO disallow edge that completes cycle back to target or traversed edge?
// probably an option to allow cycles
double r = Memory.randomNumber.nextDouble() * totalProb;
int j;
for (final Map.Entry<Sentence, Double> es : cost.entrySet()) {
nextEdge = es.getKey();
double edgeProb = 1.0 / es.getValue();
r -= edgeProb;
if (r <= 0) {
//selected the next Edge
break;
}
}
return nextEdge;
}
public String getStatus() {
return "iterations=" + numIterations +
", pathsFound=" + paths.size() +
", pathsValid=" + pathsValid +
", pathEmpty=" + pathFailEmpty +
", pathNoOperations=" + pathFailNoOperation +
", edgeDecisionPass=" + edgeDecisionPass +
", edgeDecisionFailInactiveEdge=" + edgeDecisionFailInactiveEdge +
", edgeDecisionFailInvalidVertex=" + edgeDecisionFailInvalidVertex +
", edgeDecisionFailCyclical=" + edgeDecisionFailCyclical;
}
public boolean validVertex(final Term x) {
return true;
}
//public void reset()
}
public Term getEdgeSource(final Sentence s) {
return ((Implication)s.content).getSubject();
}
public Term getEdgeTarget(final Sentence s) {
return ((Implication)s.content).getPredicate();
}
public static double getActualPriority(final Memory memory, final Term t) {
double p;
Concept c = memory.concept(t);
if ((c!=null) && (!c.beliefs.isEmpty())) {
//Sentence bestBelief = c.beliefs.get(0);
//if (bestBelief!=null)
// return c.getPriority() * bestBelief.truth.getExpectation();
return c.getPriority(); //it is not expectation cause the goal could be to make a judgement true but also false
}
//System.err.println("No Concept priority available for " + t);
//Probably an input term, so make it high priority
return 1;
}
/** between 0...1 */
public static float getActualConfidence(final Memory memory, final Term t) {
double p;
Concept c = memory.concept(t);
if ((c!=null) && (!c.beliefs.isEmpty())) {
Sentence bestBelief = c.beliefs.get(0);
if (bestBelief!=null)
return bestBelief.truth.getConfidence();
}
//System.err.println("No Concept confidence available for " + t);
//if no concept confidence is available, assume 0.5
return 0.5f;
}
/** returns 0..1.0, 1.0 being highest priority, 0 = no priority */
public static double getEffectivePriority(final Memory memory, final Term current) {
double p;
//default priority for intervals
if ((current instanceof Interval) || (current instanceof Operation))
p = 1.0f;
//get the priority for the postcondition's actual concept
else if (current instanceof PostCondition)
p = getActualPriority(memory, ((PostCondition)current).term[0]);
else
p = getActualPriority(memory, current);
return p;
}
public static float getEffectiveConfidence(final Memory memory, final Term current) {
//get the priority for the postcondition's actual concept
if (current instanceof PostCondition)
return getActualConfidence(memory, ((PostCondition)current).term[0]);
else
return getActualConfidence(memory, current);
}
/** returns (no relevancy) 0..1.0 (high relevancy) */
public double getSentenceRelevancy(final Sentence e) {
/*if (!implication.containsEdge(e))
return 0;*/
//transitions to PostCondition vertices are free or low-cost
/*
if (getEdgeTarget(e) instanceof PostCondition) {
return 1.0;
}
*/
return getEffectivePriority(memory, e.content) * e.truth.getExpectation();
}
public class ParticlePlan implements Comparable<ParticlePlan> {
public final Sentence[] path;
public final List<Term> sequence;
public final double distance;
public final double activation;
public final TruthValue truth;
public final BudgetValue budget;
private final float minConf;
// if (path.length == 0) return 0;
// float min = Float.MAX_VALUE;
// for (final Sentence s : path) {
// float c = s.truth.getConfidence();
// if (c < min)
// min = c;
// return min;
public ParticlePlan(Sentence[] path, List<Term> sequence, double activation, double distance, float minConf) {
this.path = path;
this.sequence = sequence;
this.activation = activation;
this.distance = distance;
this.minConf = minConf;
for (final Sentence s : path) {
float c = s.truth.getConfidence();
if (c < minConf) {
minConf = c;
}
}
truth = new TruthValue(1.0f, minConf);
budget = new BudgetValue(); //BudgetFunctions.forward(truth, nal);
budget.andPriority(minConf);
}
public float getMinConfidence() {
return minConf;
// if (path.length == 0) return 0;
// float min = Float.MAX_VALUE;
// for (final Sentence s : path) {
// float c = s.truth.getConfidence();
// if (c < min)
// min = c;
// return min;
}
public double score() {
return truth.getConfidence() * activation;
}
@Override
public final int compareTo(final ParticlePlan o) {
int i = Double.compare(o.score(), score());
if ((i == 0) && (o != this)) {
return -1;
}
return i;
}
@Override
public String toString() {
return sequence + "(" + score() + ";" + distance + ")";
}
}
protected void particlePredict(final Term source, final double distance, final int particles) {
ParticleActivation act = new ParticleActivation(implication);
SortedSet<ParticlePath> paths = act.activate(source, true, particles, distance);
if (!paths.isEmpty())
System.out.println(source + " predicts: " + paths);
}
public TreeSet<ParticlePlan> particlePlan(final Term target, final double distance, final int particles) {
PostCondition targetPost = new PostCondition(target);
if (!implication.containsVertex(targetPost)) {
//System.out.println(" plan for " + target + ": missing postCondition vertex");
return null;
}
ParticleActivation act = new ParticleActivation(implication) {
@Override public boolean validVertex(final Term x) {
//additional restriction on path's vertices
return !targetPost.equals(x);
}
};
SortedSet<ParticlePath> roots = act.activate(targetPost, false, particles, distance);
//System.out.println(" PATH: " + roots);
//System.out.println(" : " + act.getStatus());
if (roots == null) {
return null;
}
// System.out.println("Particle paths for " + target);
// for (ParticlePath pp : roots) {
// System.out.println(" " + pp);
TreeSet<ParticlePlan> plans = new TreeSet();
for (final ParticlePath pp : roots) {
Sentence[] path = pp.bestPath;
if (path.length == 0)
throw new RuntimeException("ParticlePath empty: " + pp);
int operations = 0;
List<Term> seq = new ArrayList(path.length);
//Calculate path back to target
Implication imp;
long accumulatedDelay = 0;
float minConf = 1.0f;
for (int i = path.length-1; i >=0; ) {
Sentence s = path[i];
Term t = s.content;
if (!(t instanceof Implication))
throw new RuntimeException("Unknown type: " + t + " in sequence generation of " + this);
imp = (Implication)t;
Term term = imp.getSubject();
i--; //next impl
if (isPlanTerm(term)) {
boolean isInterval = term instanceof Interval;
if (!isInterval) {
if (accumulatedDelay > 0) {
seq.addAll(Interval.intervalTimeSequence(
accumulatedDelay, maxConsecutiveIntervalTerms, memory) );
accumulatedDelay = 0;
}
seq.add(term);
}
else {
Interval in = (Interval)term;
long time = in.getTime(memory);
accumulatedDelay += time;
}
}
else {
float c = getEffectiveConfidence(memory, term);
if (c < minConf)
minConf = c;
//accumulate delay if the temporal rule involves time difference??
/*
if (nonIntervalAdded) {
////ignore prefix intervals
int temporal = (s.content).getTemporalOrder();
if (temporal == TemporalRules.ORDER_FORWARD) {
accumulatedDelay++;
}
}
*/
}
if (term instanceof Operation)
operations++;
}
//TODO check this prior to above loop, to avoid wasting that effort
if (operations == 0)
continue;
if (seq.isEmpty())
continue;
int lastTerm = seq.size()-1;
if (seq.get(lastTerm) instanceof Interval)
seq.remove(lastTerm);
//System.out.println(" cause: " + Arrays.toString(path));
ParticlePlan rp = new ParticlePlan(path, seq, pp.score(), pp.distance, minConf);
plans.add(rp);
}
return plans;
}
protected Task planTask(ParticlePlan plan, Concept c, Task task, Term target, char punctuation) {
TruthValue truth = plan.truth;
BudgetValue budget = plan.budget;
Sentence[] path = plan.path;
List<Term> seq = plan.sequence;
Sentence currentEdge = path[path.length-1];
Stamp stamp = Stamp.make(task.sentence.stamp, currentEdge.stamp, memory.getTime());
//add all terms to derivation chain
for(Term T : seq) {
stamp.derivationChain.add(T); //todo: if too long kick out the first n terms
}
//todo: evidental base hm
//memory.setTheNewStamp(stamp);
//memory.setCurrentTask(task);
//remove final element from path if it's equal to target
/*if (seq.get(seq.size()-1).equals(target)) {
seq.remove(seq.size()-1);
}*/
Term subj = seq.size() > 1 ?
Conjunction.make(seq.toArray(new Term[seq.size()]), TemporalRules.ORDER_FORWARD)
:
seq.get(0);
//val=TruthFunctions.abduction(val, newEvent.sentence.truth);
Term imp = Implication.make(subj, target, TemporalRules.ORDER_FORWARD);
if (imp == null) {
throw new RuntimeException("Invalid implication: " + subj + " =\\> " + target);
}
return new Task(new Sentence(imp, punctuation, truth, stamp), budget, task);
}
protected void planTask(NAL nal, ParticlePlan plan, Concept c, Task task, Term target, char punctuation) {
Task newTask = planTask(plan, c, task, target, punctuation);
if (memory.getRecorder().isActive())
memory.getRecorder().append("Plan Add", newTask.toString());
if (punctuation == '.')
nal.derivedTask(newTask, false, true, null, null);
if (punctuation == '!')
memory.executive.addTask(c, newTask);
}
protected void plan(final NAL nal, Concept c, Task task, Term target, int particles, double searchDistance, char punctuation, int maxTasks) {
if (!implication.containsVertex(target))
return;
TreeSet<ParticlePlan> plans = particlePlan(target, searchDistance, particles);
int n = 0;
for (ParticlePlan p : plans) {
planTask(nal, p, c, task, target, punctuation);
if (n++ == maxTasks)
break;
}
}
// protected void plan(Task task, Task __not_used_newEvent) {
// Term t = task.getContent();
// if (t == null) return;
// if ((t instanceof Implication) && (t.getTemporalOrder()!=TemporalRules.ORDER_NONE)) {
// //System.out.println("plan: task=" + task + " newEvent=" + __not_used_newEvent);
// Implication i = (Implication) t;
// Term target;
// //implication.add(task.sentence);
// if (i.getTemporalOrder() == TemporalRules.ORDER_FORWARD) {
// target = i.getPredicate();
// } else {
// //TODO reverse it
// target = i.getSubject();
// if (target != null) {
// System.err.println("plan: " + target);
// System.exit(1);
// ///plan(task, target, ...);
//// System.out.println("Goals");
//// for (Task t : tasks) {
//// System.out.println(t + " " + t.getParentBelief());
//// //System.out.println(getImplicationPath(t.getParentBelief()));
//// System.out.println();
// public String getImplicationPath(Sentence s) {
// Term t = s.content;
// if (t instanceof Implication) {
// return getImplicationPath(((Implication)t).getPredicate());
// else {
// return getImplicationPath(t);
// //return "";
// public String getImplicationPath(Term t) {
// KShortestPaths ksp = new KShortestPaths(implication, t, 5);
// return ksp.getPaths(t).toString();
/** TODO */
public void reset() {
}
// public boolean isActionable(final Task newEvent, Memory mem) {
// /*if(!((newEvent.isInput()) || (newEvent.getCause()!=null))) {
// return false;
// }*/
// Term newcontent = newEvent.sentence.content;
// if (newcontent instanceof Operation) {
// Term pred = ((Operation) newcontent).getPredicate();
// if (pred.equals(mem.getOperator("^want")) || pred.equals(mem.getOperator("^believe"))) {
// return false;
// plan(newEvent, (Task)null);
// return true;
// public boolean isActionable(final Task task, final Task newEvent) {
// plan(task, newEvent);
// return true;
// /*
// if (task.sentence.stamp.getOccurrenceTime() == Stamp.ETERNAL) {
// return false;
// }
//
// if (!task.sentence.isJudgment()) {
// return false;
// }
// */
//// if ((newEvent == null)
//// || (rankBelief(newEvent.sentence) < rankBelief(task.sentence))) {
//// return true;
//// /*return
//// ((shortTermMemory.isEmpty()
//// ||
//// !equalSubTermsInRespectToImageAndProduct(
//// shortTermMemory.getLast().getContent(),
//// task.getContent()))
//// );
//// */
// //return false;
// /** doesnt work yet and may not be necessary */
// @Deprecated public static class CandidateSequenceRoot implements Comparable {
// public final Term root;
// public final double distance;
// public CandidateSequenceRoot(Term root, double distance) {
// this.root = root;
// this.distance = distance;
// @Override
// public int compareTo(Object o) {
// if (o instanceof CandidateSequenceRoot) {
// CandidateSequenceRoot csr = (CandidateSequenceRoot)o;
// return Double.compare(csr.distance, distance);
// return -1;
// @Override
// public String toString() {
// return root.toString() + "|" + distance;
// @Deprecated protected List<Term> planExhaustive(Term target, double remainingDistance, List<Term> parentPath, double[] distResult) {
// if (remainingDistance <= 0)
// return Collections.EMPTY_LIST;
// ClosestFirstIterator<Term, Sentence> cfi = new ClosestFirstIterator<Term, Sentence>(new EdgeReversedGraph(implication), target, remainingDistance);
// if (parentPath == null)
// parentPath = Collections.EMPTY_LIST;
// SortedSet<CandidateSequenceRoot> roots = new TreeSet();
// while (cfi.hasNext()) {
// Term v = cfi.next();
// double length = cfi.getShortestPathLength(v);
// if (length == 0) continue;
// //dont settle for 1-edge hop from target, we need further
// if (implication.getEdgeTarget( cfi.getSpanningTreeEdge(v) ).equals(target) ) {
// //System.out.println(v + " " + cfi.getSpanningTreeEdge(v) + " ==? " + target);
// continue;
// if ((!v.equals(target)) /*&& (!parentPath.contains(v))*/) {
// //ignore intervals as roots
// if (!(v instanceof Interval))
// roots.add(new CandidateSequenceRoot(v, length));
// if (roots.isEmpty())
// return Collections.EMPTY_LIST;
// double initialRemainingDistance = remainingDistance;
// for (final CandidateSequenceRoot csroot : roots) {
// final Term root = csroot.root;
// if (root == target) continue;
// remainingDistance = initialRemainingDistance - csroot.distance;
// if (remainingDistance < 0)
// continue;
// //Calculate path back to target
// List<Term> path = new ArrayList();
// Term current = root;
// Sentence currentEdge = null;
// int operations = 0;
// while (current != target) {
// boolean isOperation = (current instanceof Operation);
// if (isOperation)
// operations++;
// //only include Operations and Intervals
// if (isOperation || (current instanceof Interval)) {
// path.add(current);
// //but if it's something else, we need to transclude it because it may indicate other necessary preconditions
// else if ((!current.equals(target))) {
// //Transclude best subpath iff vertex has other preconditions
// /*if (implication.outgoingEdgesOf(current).size() > 1) {
// //ignore a preconditon with a postcondition
// continue;
// }*/
// //TODO should the precondition branches be sorted, maybe shortest first?
// boolean goodPreconditions = true;
// Set<Sentence> preconditions = implication.incomingEdgesOf(current);
// for (Sentence s : preconditions) {
// if (!s.equals(currentEdge)) {
// //System.out.println(" precondition: " + current + " = " + s);
// Term preconditionSource = implication.getEdgeSource(s);
// if (parentPath!=null) {
// /*if (!parentPath.contains(preconditionSource))*/ {
// if (!preconditionSource.equals(target) ) {
// List<Term> preconditionPlan = null;
// try {
// double[] d = new double[1];
// preconditionPlan = planExhaustive(preconditionSource, remainingDistance, path, d);
// if (!((preconditionPlan.size() == 0) || (preconditionPlan == null))) {
// if (remainingDistance - d[0] > 0) {
// if (!preconditionPlan.contains(preconditionSource)) { path.addAll(preconditionPlan);
// if (validPlanComponent(preconditionSource))
// path.add(preconditionSource);
// remainingDistance -= d[0];
// else {
// //ignore this condition sequence because it would exceed the search distance
// System.out.println(" excess subpath: " + remainingDistance + " " + d[0] + " " + preconditionPlan);
// goodPreconditions = false;
// break;
// catch (Throwable e) {
// System.err.println(e + " " +target + " " + path + " " + preconditionSource + " " + parentPath);
// System.err.println(" " + preconditionPlan);
// new Window("Implications", new JGraphXGraphPanel(memory.executive.graph.implication)).show(500,500);
// try {
// System.in.read();
// } catch (IOException ex) {
// Logger.getLogger(GraphExecutive.class.getName()).log(Level.SEVERE, null, ex);
// if (!goodPreconditions)
// break;
// currentEdge = cfi.getSpanningTreeEdge(current);
// if (currentEdge == null) {
// //Should mean we have returned to target
// break;
// current = implication.getEdgeTarget(currentEdge);
// if (operations == 0)
// continue;
// if (path.size() < 2)
// continue;
// System.out.println(path + " " + root + " in " + roots);
// distResult[0] = initialRemainingDistance - remainingDistance;
// return path;
// return Collections.EMPTY_LIST;
}
|
package uk.co.bristlecone.voltdb.wrapgen.builder;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalToIgnoringWhiteSpace;
import static org.hamcrest.Matchers.is;
import java.util.function.Function;
import org.junit.Test;
import org.junit.runner.RunWith;
import mockit.Expectations;
import mockit.Mocked;
import mockit.integration.junit4.JMockit;
@RunWith(JMockit.class)
public class RunnerBuilderTest {
// @formatter:off
private static final String PROC_DATA_PACKAGE_NAME = "mock.package.name";
private static final String PROC_DATA_CLASS_NAME = "MockStoredProcedureName";
private static final String EXPECTED_CLASS_WITH_IDENTITY_NAMERS = ""
+ String.format("package %s;\n", PROC_DATA_PACKAGE_NAME)
+ String.format("\n")
+ String.format("import java.io.IOException;\n")
+ String.format("import java.time.Duration;\n")
+ String.format("import java.util.concurrent.CompletableFuture;\n")
+ String.format("import org.voltdb.client.Client;\n")
+ String.format("import org.voltdb.client.ClientResponse;\n")
+ String.format("import org.voltdb.client.NoConnectionsException;\n")
+ String.format("import org.voltdb.client.ProcedureCallback;\n")
+ String.format("import uk.co.bristlecone.voltdb.wrapgen.runner.VoltRunner;\n")
+ String.format("import uk.co.bristlecone.voltdb.wrapgen.runner.WrapgenUtil;\n")
+ String.format("\n")
+ String.format("/**\n")
+ String.format(" * An instance of this class can be used to run the <code>%s</code> ", PROC_DATA_CLASS_NAME)
+ String.format("VoltDB stored procedure. This stored procedure's JavaDoc is:\n")
+ String.format(" *\n")
+ String.format(" * <blockquote>null</blockquote>\n")
+ String.format(" *\n")
+ String.format(" * <strong>This class is automatically generated. Manual edits will be overwritten.</strong>\n")
+ String.format(" *\n")
+ String.format(" * @author voltdb-wrapgen\n")
+ String.format(" */\n")
+ String.format("@VoltRunner\n")
+ String.format("public class %s {\n", PROC_DATA_CLASS_NAME)
+ String.format(" CompletableFuture<ClientResponse> run(final Client client)\n")
+ String.format(" throws NoConnectionsException, IOException {\n")
+ String.format(" CompletableFuture<ClientResponse> result = new CompletableFuture<ClientResponse>();\n")
+ String.format(" ProcedureCallback handler = WrapgenUtil.getHandler(result);\n")
+ String.format(" client.callProcedure(handler, \"%s\");\n", PROC_DATA_CLASS_NAME)
+ String.format(" return result;\n")
+ String.format(" }\n")
+ String.format("\n")
+ String.format(" CompletableFuture<ClientResponse> runWithTimeout(final Client client, final Duration timeout)\n")
+ String.format(" throws NoConnectionsException, IOException {\n")
+ String.format(" CompletableFuture<ClientResponse> result = new CompletableFuture<ClientResponse>();\n")
+ String.format(" ProcedureCallback handler = WrapgenUtil.getHandler(result);\n")
+ String.format(" client.callProcedure(handler, Math.toIntExact(timeout.toMillis()), \"%s\");\n", PROC_DATA_CLASS_NAME)
+ String.format(" return result;\n")
+ String.format(" }\n")
+ String.format("}\n");
// @formatter:on
@Test
public void builderCreatesClassAsExpected(@Mocked final ProcData mockProcData) {
// @formatter:off
new Expectations() {{
mockProcData.packageName(); result = PROC_DATA_PACKAGE_NAME;
mockProcData.name(); result = PROC_DATA_CLASS_NAME;
}};
// @formatter:on
final VoltRunnerJavaSource testee = new RunnerBuilder(mockProcData, Function.identity(), Function.identity())
.build();
assertThat(testee.source(), is(equalToIgnoringWhiteSpace(EXPECTED_CLASS_WITH_IDENTITY_NAMERS)));
}
}
|
package com.hazelcast.stabilizer.tests.map;
import com.hazelcast.config.MapStoreConfig;
import com.hazelcast.core.HazelcastInstance;
import com.hazelcast.core.IMap;
import com.hazelcast.stabilizer.tests.TestContext;
import com.hazelcast.stabilizer.tests.TestRunner;
import com.hazelcast.stabilizer.tests.annotations.Run;
import com.hazelcast.stabilizer.tests.annotations.Setup;
import com.hazelcast.stabilizer.tests.annotations.Verify;
import com.hazelcast.stabilizer.tests.map.helpers.MapStoreWithCounter;
import com.hazelcast.stabilizer.tests.utils.ThreadSpawner;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import static junit.framework.Assert.assertEquals;
public class MapStoreTest {
public String basename = this.getClass().getName();
public int threadCount = 3;
public int keyCount = 10;
//check these add up to 1
public double writeProb = 0.45;
public double evictProb = 0.25;
public double removeProb = 0.15;
public double deleteProb = 0.15;
public double destroyProb = 0.5;
//check these add up to 1 (writeProb is split up into sub styles)
public double writeUsingPutProb = 0.4;
public double writeUsingPutTTLProb = 0.3;
public double writeUsingPutIfAbsent = 0.15;
public double writeUsingReplaceProb = 0.15;
private int writeDelaySeconds = 0;
private int maxExpireySeconds = 3;
private TestContext testContext;
private HazelcastInstance targetInstance;
public MapStoreTest(){}
@Setup
public void setup(TestContext testContext) throws Exception {
this.testContext = testContext;
targetInstance = testContext.getTargetInstance();
try{
MapStoreConfig mapStoreConfig = targetInstance.getConfig().getMapConfig(basename).getMapStoreConfig();
if(mapStoreConfig!=null){
writeDelaySeconds = mapStoreConfig.getWriteDelaySeconds();
}
}catch(UnsupportedOperationException e){}
}
@Run
public void run() {
ThreadSpawner spawner = new ThreadSpawner(testContext.getTestId());
for (int k = 0; k < threadCount; k++) {
spawner.spawn(new Worker());
}
spawner.awaitCompletion();
}
private class Worker implements Runnable {
private final Random random = new Random();
@Override
public void run() {
while (!testContext.isStopped()) {
final int key = random.nextInt(keyCount);
final IMap map = targetInstance.getMap(basename);
double chance = random.nextDouble();
if (chance < writeProb) {
final Object value = random.nextInt(keyCount);
chance = random.nextDouble();
if (chance < writeUsingPutProb) {
map.put(key, value);
}
if (chance < writeUsingPutTTLProb + writeUsingPutProb) {
long delay = writeDelaySeconds + random.nextInt(maxExpireySeconds);
int k = keyCount + random.nextInt(5000);
map.put(k, delay, delay,TimeUnit.SECONDS );
}
else if(chance < writeUsingPutIfAbsent + writeUsingPutTTLProb + writeUsingPutProb ){
map.putIfAbsent(key, value);
}
else if(chance < writeUsingReplaceProb + writeUsingPutIfAbsent + writeUsingPutTTLProb + writeUsingPutProb){
Object orig = map.get(key);
if ( orig !=null ){
map.replace(key, orig, value);
}
}
}else if(chance < evictProb + writeProb){
//map.evict(key);
}
else if(chance < removeProb + evictProb + writeProb){
//map.remove(key);
}
else if (chance < deleteProb + removeProb + evictProb + writeProb ){
map.delete(key);
}
else if (chance < destroyProb + deleteProb + removeProb + evictProb + writeProb ){
map.destroy();
}
}
}
}
@Verify(global = false)
public void verify() throws Exception {
try{
Thread.sleep( (writeDelaySeconds + writeDelaySeconds/2) * 1000 );
System.out.println("verify "+basename+" !!");
final IMap map = targetInstance.getMap(basename);
MapStoreWithCounter mapStore = (MapStoreWithCounter) targetInstance.getConfig().getMapConfig(basename).getMapStoreConfig().getImplementation();
System.out.println("map size =" + map.size() );
System.out.println(map.localKeySet().size() + "== " + mapStore.store.size() );
System.out.println("map local =" + map.getAll(map.localKeySet()).entrySet() );
System.out.println("map Store =" + mapStore.store.entrySet() );
for(Object k: map.localKeySet()){
assertEquals( map.get(k), mapStore.store.get(k) );
}
}catch(UnsupportedOperationException e){}
}
public static void main(String[] args) throws Throwable {
new TestRunner(new MapStoreTest()).run();
}
}
|
package org.switchyard.quickstarts.rules.interview;
import org.switchyard.component.rules.ExecuteRules;
import org.switchyard.component.rules.Rules;
@Rules(value=Interview.class, resources={"/org/switchyard/quickstarts/rules/interview/Interview.drl"})
public interface InterviewRules extends Interview {
@Override
@ExecuteRules
public void verify(Applicant applicant);
}
|
package com.malhartech.stream.kafka;
import com.malhartech.api.Sink;
import com.malhartech.dag.Stream;
import com.malhartech.dag.StreamConfiguration;
import com.malhartech.dag.StreamContext;
import com.malhartech.dag.Tuple;
import kafka.javaapi.producer.Producer;
/**
*
* @author Chetan Narsude <chetan@malhar-inc.com>
*/
public class KafkaOutputStream
implements Stream, Sink
{
@Override
public void setup(StreamConfiguration config)
{
Producer producer;
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public void setContext(StreamContext context)
{
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public void teardown()
{
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public void doSomething(Tuple t)
{
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public StreamContext getContext()
{
throw new UnsupportedOperationException("Not supported yet.");
}
public boolean hasFinished()
{
throw new UnsupportedOperationException("Not supported yet.");
}
public void activate()
{
throw new UnsupportedOperationException("Not supported yet.");
}
}
|
package net.runelite.client.plugins.wasdcamera;
import java.awt.event.KeyEvent;
import javax.inject.Inject;
import net.runelite.api.Client;
import net.runelite.api.VarClientStr;
import net.runelite.client.callback.ClientThread;
import net.runelite.client.input.KeyListener;
import net.runelite.client.input.MouseListener;
class WASDCameraListener extends MouseListener implements KeyListener
{
@Inject
private WASDCameraPlugin plugin;
@Inject
private WASDCameraConfig config;
@Inject
private Client client;
@Inject
private ClientThread clientThread;
@Override
public void keyTyped(KeyEvent e)
{
handleKey(e);
}
@Override
public void keyPressed(KeyEvent e)
{
if (!plugin.chatboxFocused())
{
return;
}
if (!plugin.isTyping())
{
if (config.up().matches(e))
{
e.setKeyCode(KeyEvent.VK_UP);
}
else if (config.down().matches(e))
{
e.setKeyCode(KeyEvent.VK_DOWN);
}
else if (config.left().matches(e))
{
e.setKeyCode(KeyEvent.VK_LEFT);
}
else if (config.right().matches(e))
{
e.setKeyCode(KeyEvent.VK_RIGHT);
}
else
{
switch (e.getKeyCode())
{
case KeyEvent.VK_ENTER:
case KeyEvent.VK_SLASH:
// refocus chatbox
clientThread.invoke(() ->
{
plugin.unlockChat();
});
break;
case KeyEvent.VK_F1:
case KeyEvent.VK_F2:
case KeyEvent.VK_F3:
case KeyEvent.VK_F4:
case KeyEvent.VK_F5:
case KeyEvent.VK_F6:
case KeyEvent.VK_F7:
case KeyEvent.VK_F8:
case KeyEvent.VK_F9:
case KeyEvent.VK_F10:
case KeyEvent.VK_F11:
case KeyEvent.VK_F12:
case KeyEvent.VK_UP:
case KeyEvent.VK_DOWN:
case KeyEvent.VK_LEFT:
case KeyEvent.VK_RIGHT:
case KeyEvent.VK_SHIFT:
case KeyEvent.VK_ESCAPE:
break;
default:
e.consume();
break;
}
}
}
else
{
switch (e.getKeyCode())
{
case KeyEvent.VK_ENTER:
clientThread.invoke(() ->
{
plugin.lockChat();
});
break;
case KeyEvent.VK_ESCAPE:
clientThread.invoke(() ->
{
client.setVar(VarClientStr.CHATBOX_TYPED_TEXT, "");
plugin.lockChat();
});
break;
}
}
}
@Override
public void keyReleased(KeyEvent e)
{
handleKey(e);
}
private void handleKey(KeyEvent e)
{
if (!plugin.chatboxFocused())
{
return;
}
if (!plugin.isTyping())
{
if (config.up().matches(e))
{
e.setKeyCode(KeyEvent.VK_UP);
}
else if (config.down().matches(e))
{
e.setKeyCode(KeyEvent.VK_DOWN);
}
else if (config.left().matches(e))
{
e.setKeyCode(KeyEvent.VK_LEFT);
}
else if (config.right().matches(e))
{
e.setKeyCode(KeyEvent.VK_RIGHT);
}
else
{
switch (e.getKeyCode())
{
case KeyEvent.VK_F1:
case KeyEvent.VK_F2:
case KeyEvent.VK_F3:
case KeyEvent.VK_F4:
case KeyEvent.VK_F5:
case KeyEvent.VK_F6:
case KeyEvent.VK_F7:
case KeyEvent.VK_F8:
case KeyEvent.VK_F9:
case KeyEvent.VK_F10:
case KeyEvent.VK_F11:
case KeyEvent.VK_F12:
case KeyEvent.VK_UP:
case KeyEvent.VK_DOWN:
case KeyEvent.VK_LEFT:
case KeyEvent.VK_RIGHT:
case KeyEvent.VK_SHIFT:
case KeyEvent.VK_ESCAPE:
break;
default:
e.consume();
break;
}
}
}
}
}
|
package com.example.bot.spring.database;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
/**
* this is to handle the unanswered questions, save them into the database and reply with a default answer
* @author jsongaf
*/
//I am doing a very stupid test, please ignore this pull request, and
//stupid test is continuing
public class UQDBEngine extends DBEngine {
/**
* class constructor
*/
public UQDBEngine() {
// TODO Auto-generated constructor stub
}
/**
* update the database table and save the question and change the status if someone answer the question
* @throws Exception if database connection fails
*/
public void updateTable() throws Exception{
Connection connection = null;
PreparedStatement stmt = null;
connection=getConnection();
stmt = connection.prepareStatement(
"update unanswered_question set sent_or_not = true where answered_or_not = true"
);
stmt.executeUpdate();
if (stmt != null) stmt.close();
if (connection != null) connection.close();
}
/**
* get the default reply from the database
* @return reply to the userse
* @throws Exception if database connection fails
*/
public String retrieveReply() throws Exception {
Connection connection = null;
PreparedStatement stmt = null;
String reply="";
connection=getConnection();
stmt = connection.prepareStatement("select * from unanswered_default_reply");
ResultSet rs=stmt.executeQuery();
while (rs.next()) {
reply=rs.getString(1);
}
if (stmt != null) stmt.close();
if (connection != null) connection.close();
return reply;
}
/**
* get the answer from the database to send it to users
* @return get the answer list
* @throws Exception if databse connection fails
*/
public ArrayList<String> answer() throws Exception{
Connection connection = null;
PreparedStatement stmt = null;
ArrayList<String> reply= new ArrayList<String>();
connection=getConnection();
stmt = connection.prepareStatement(
"select * from unanswered_question where answered_or_not = true and sent_or_not= false"
);
ResultSet rs=stmt.executeQuery();
while (rs.next()) {
String temp="";
temp+=rs.getString(1)+","+rs.getString(2)+","+rs.getString(4);
reply.add(temp);
}
if (stmt != null) stmt.close();
if (connection != null) connection.close();
updateTable();
return reply;
}
/**
* execute the query and connect to the database
* @param userId user id
* @param text user input
* @return result of the qurey
* @throws Exception if database connection is failed
*/
public String uqQuery(String userId, String text) throws Exception{
//System.out.println("Success");
Connection connection = null;
PreparedStatement stmt = null;
connection = getConnection();
//insert into the unanswered question table to store the question
stmt = connection.prepareStatement(
"insert into unanswered_question values( '"+userId+"', '"+text+"', false, '', false)"
);
stmt.executeUpdate();
if (stmt != null) stmt.close();
if (connection != null) connection.close();
return retrieveReply();
}
}
|
package org.jboss.forge.addon.scaffold.faces;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.inject.Inject;
import javax.persistence.CascadeType;
import javax.persistence.Id;
import javax.persistence.OneToOne;
import org.jboss.forge.addon.configuration.Configuration;
import org.jboss.forge.addon.dependencies.Dependency;
import org.jboss.forge.addon.dependencies.builder.DependencyBuilder;
import org.jboss.forge.addon.facets.AbstractFacet;
import org.jboss.forge.addon.facets.FacetNotFoundException;
import org.jboss.forge.addon.javaee.cdi.CDIFacet;
import org.jboss.forge.addon.javaee.cdi.CDIFacet_1_0;
import org.jboss.forge.addon.javaee.cdi.CDIFacet_1_1;
import org.jboss.forge.addon.javaee.cdi.ui.CDISetupWizard;
import org.jboss.forge.addon.javaee.ejb.EJBFacet;
import org.jboss.forge.addon.javaee.ejb.EJBFacet_3_1;
import org.jboss.forge.addon.javaee.ejb.EJBFacet_3_2;
import org.jboss.forge.addon.javaee.ejb.ui.EJBSetupWizard;
import org.jboss.forge.addon.javaee.faces.FacesFacet;
import org.jboss.forge.addon.javaee.faces.FacesFacet_2_0;
import org.jboss.forge.addon.javaee.faces.FacesFacet_2_1;
import org.jboss.forge.addon.javaee.faces.FacesFacet_2_2;
import org.jboss.forge.addon.javaee.faces.ui.FacesSetupWizard;
import org.jboss.forge.addon.javaee.jpa.JPAFacet;
import org.jboss.forge.addon.javaee.jpa.JPAFacet_2_0;
import org.jboss.forge.addon.javaee.jpa.JPAFacet_2_1;
import org.jboss.forge.addon.javaee.jpa.ui.setup.JPASetupWizard;
import org.jboss.forge.addon.javaee.servlet.ServletFacet;
import org.jboss.forge.addon.javaee.servlet.ServletFacet_3_0;
import org.jboss.forge.addon.javaee.servlet.ServletFacet_3_1;
import org.jboss.forge.addon.javaee.servlet.ui.ServletSetupWizard;
import org.jboss.forge.addon.parser.java.facets.JavaSourceFacet;
import org.jboss.forge.addon.parser.java.resources.JavaResource;
import org.jboss.forge.addon.projects.Project;
import org.jboss.forge.addon.projects.facets.DependencyFacet;
import org.jboss.forge.addon.projects.facets.WebResourcesFacet;
import org.jboss.forge.addon.resource.FileResource;
import org.jboss.forge.addon.resource.Resource;
import org.jboss.forge.addon.resource.ResourceFilter;
import org.jboss.forge.addon.scaffold.faces.freemarker.FreemarkerTemplateProcessor;
import org.jboss.forge.addon.scaffold.faces.metawidget.config.ForgeConfigReader;
import org.jboss.forge.addon.scaffold.faces.util.ScaffoldUtil;
import org.jboss.forge.addon.scaffold.spi.AccessStrategy;
import org.jboss.forge.addon.scaffold.spi.ScaffoldGenerationContext;
import org.jboss.forge.addon.scaffold.spi.ScaffoldSetupContext;
import org.jboss.forge.addon.scaffold.spi.ScaffoldProvider;
import org.jboss.forge.addon.ui.UICommand;
import org.jboss.forge.addon.ui.context.UIValidationContext;
import org.jboss.forge.parser.JavaParser;
import org.jboss.forge.parser.java.Annotation;
import org.jboss.forge.parser.java.Field;
import org.jboss.forge.parser.java.JavaClass;
import org.jboss.forge.parser.java.Member;
import org.jboss.forge.parser.java.Method;
import org.jboss.shrinkwrap.descriptor.api.javaee6.ParamValueType;
import org.jboss.shrinkwrap.descriptor.api.webapp30.WebAppDescriptor;
import org.jboss.shrinkwrap.descriptor.spi.node.Node;
import org.jboss.shrinkwrap.descriptor.spi.node.NodeDescriptor;
import org.metawidget.statically.StaticMetawidget;
import org.metawidget.statically.StaticUtils.IndentedWriter;
import org.metawidget.statically.StaticWidget;
import org.metawidget.statically.faces.StaticFacesUtils;
import org.metawidget.statically.faces.component.html.StaticHtmlMetawidget;
import org.metawidget.statically.faces.component.html.widgetbuilder.HtmlOutcomeTargetLink;
import org.metawidget.statically.faces.component.html.widgetbuilder.ReadOnlyWidgetBuilder;
import org.metawidget.statically.faces.component.html.widgetbuilder.richfaces.RichFacesWidgetBuilder;
import org.metawidget.statically.html.widgetbuilder.HtmlTag;
import org.metawidget.statically.javacode.StaticJavaMetawidget;
import org.metawidget.util.ArrayUtils;
import org.metawidget.util.CollectionUtils;
import org.metawidget.util.XmlUtils;
import org.metawidget.util.simple.StringUtils;
import org.metawidget.widgetbuilder.composite.CompositeWidgetBuilder;
import org.metawidget.widgetbuilder.composite.CompositeWidgetBuilderConfig;
import org.metawidget.widgetbuilder.iface.WidgetBuilder;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import freemarker.template.Template;
/**
* The scaffold provider for JSF 2.0
*/
public class FacesScaffoldProvider extends AbstractFacet<Project> implements ScaffoldProvider
{
private static final String JBOSS_COMMUNITY_PNG = "/resources/jboss-community.png";
private static final String TRUE_PNG = "/resources/true.png";
private static final String SEARCH_PNG = "/resources/search.png";
private static final String REMOVE_PNG = "/resources/remove.png";
private static final String FORGE_STYLE_CSS = "/resources/forge-style.css";
private static final String FORGE_LOGO_PNG = "/resources/forge-logo.png";
private static final String FAVICON_ICO = "/resources/favicon.ico";
private static final String FALSE_PNG = "/resources/false.png";
private static final String BOOTSTRAP_CSS = "/resources/bootstrap.css";
private static final String ADD_PNG = "/resources/add.png";
private static final String ERROR_XHTML = "error.xhtml";
private static final String XMLNS_PREFIX = "xmlns:";
private static final String BACKING_BEAN_TEMPLATE = "scaffold/faces/BackingBean.jv";
private static final String VIEW_UTILS_TEMPLATE = "scaffold/faces/ViewUtils.jv";
private static final String TAGLIB_TEMPLATE = "scaffold/faces/forge.taglib.xml";
private static final String VIEW_TEMPLATE = "scaffold/faces/view.xhtml";
private static final String CREATE_TEMPLATE = "scaffold/faces/create.xhtml";
private static final String SEARCH_TEMPLATE = "scaffold/faces/search.xhtml";
private static final String NAVIGATION_TEMPLATE = "scaffold/faces/pageTemplate.xhtml";
private static final String ERROR_TEMPLATE = "scaffold/faces/error.xhtml";
private static final String INDEX_TEMPLATE = "scaffold/faces/index.xhtml";
private static final String INDEX_WELCOME_TEMPLATE = "scaffold/faces/index.html";
private final Dependency richfaces3UI = DependencyBuilder.create("org.richfaces.ui:richfaces-ui");
private final Dependency richfaces3Impl = DependencyBuilder.create("org.richfaces.framework:richfaces-impl");
private final Dependency richfaces4UI = DependencyBuilder.create("org.richfaces.ui:richfaces-components-ui");
private final Dependency richfaces4Impl = DependencyBuilder.create("org.richfaces.core:richfaces-core-impl");
protected FreemarkerTemplateProcessor templateProcessor;
protected Template backingBeanTemplate;
protected int backingBeanTemplateQbeMetawidgetIndent;
protected int backingBeanTemplateRmEntityMetawidgetIndent;
protected Template viewUtilsTemplate;
protected Template taglibTemplate;
protected Template viewTemplate;
protected Map<String, String> viewTemplateNamespaces;
protected int viewTemplateEntityMetawidgetIndent;
protected Template createTemplate;
protected Map<String, String> createTemplateNamespaces;
protected int createTemplateEntityMetawidgetIndent;
protected Template searchTemplate;
protected Map<String, String> searchTemplateNamespaces;
protected int searchTemplateSearchMetawidgetIndent;
protected int searchTemplateBeanMetawidgetIndent;
protected Template navigationTemplate;
protected int navigationTemplateIndent;
protected Template errorTemplate;
protected Template indexWelcomeTemplate;
protected Template indexTemplate;
protected StaticHtmlMetawidget entityMetawidget;
protected StaticHtmlMetawidget searchMetawidget;
protected StaticHtmlMetawidget beanMetawidget;
protected StaticJavaMetawidget qbeMetawidget;
protected StaticJavaMetawidget rmEntityMetawidget;
private Configuration config;
@Inject
public FacesScaffoldProvider(final Configuration config, final FreemarkerTemplateProcessor templateProcessor)
{
this.config = config;
this.templateProcessor = templateProcessor;
}
@Override
public boolean install()
{
// TODO Auto-generated method stub
return true;
}
@Override
public boolean isInstalled()
{
// TODO Auto-generated method stub
return true;
}
@Override
public void validate(UIValidationContext context)
{
// TODO Auto-generated method stub
}
@Override
public void setFaceted(Project origin)
{
super.setFaceted(origin);
resetMetaWidgets();
}
@Override
public String getName()
{
return "Faces";
}
@Override
public String getDescription()
{
return "Scaffold a Faces project from JPA entities";
}
@Override
public List<Resource<?>> setup(Project project, ScaffoldSetupContext scaffoldContext)
{
if(this.origin == null)
{
origin = project;
}
String targetDir = scaffoldContext.getTargetDirectory();
boolean overwrite = scaffoldContext.isOverwrite();
Resource<?> template = null;
List<Resource<?>> resources = generateIndex(targetDir, template, overwrite);
setupWebXML();
return resources;
}
@Override
public List<Resource<?>> generateFrom(Project project, ScaffoldGenerationContext scaffoldContext)
{
List<Resource<?>> generatedResources = new ArrayList<Resource<?>>();
Collection<?> resources = scaffoldContext.getResources();
for (Object resource : resources)
{
JavaClass entity = (JavaClass) resource;
String targetDir = scaffoldContext.getTargetDirectory();
Resource<?> template = null;
boolean overwrite = scaffoldContext.isOverwrite();
List<Resource<?>> generatedResourcesForEntity = this.generateFromEntity(targetDir , template, entity, overwrite );
// TODO give plugins a chance to react to generated resources, use event bus?
// if (!generatedResources.isEmpty())
// generatedEvent.fire(new ScaffoldGeneratedResources(provider, prepareResources(generatedResources)));
generatedResources.addAll(generatedResourcesForEntity);
}
return generatedResources;
}
@Override
public List<Class<? extends UICommand>> getSetupFlow()
{
List<Class<? extends UICommand>> setupCommands = new ArrayList<Class<? extends UICommand>>();
// FORGE-1304 detect all facet subtypes that we support
if(!origin.hasFacet(JPAFacet_2_0.class) && !origin.hasFacet(JPAFacet_2_1.class))
{
setupCommands.add(JPASetupWizard.class);
}
if(!origin.hasFacet(CDIFacet_1_0.class) && origin.hasFacet(CDIFacet_1_1.class))
{
setupCommands.add(CDISetupWizard.class);
}
if(!origin.hasFacet(EJBFacet_3_1.class) && !origin.hasFacet(EJBFacet_3_2.class))
{
setupCommands.add(EJBSetupWizard.class);
}
if(!origin.hasFacet(ServletFacet_3_0.class) && !origin.hasFacet(ServletFacet_3_1.class))
{
//TODO: FORGE-1296. Ensure that this wizard only sets up Servlet 3.0+
setupCommands.add(ServletSetupWizard.class);
}
if(!origin.hasFacet(FacesFacet_2_0.class) && !origin.hasFacet(FacesFacet_2_1.class) && !origin.hasFacet(FacesFacet_2_2.class))
{
setupCommands.add(FacesSetupWizard.class);
}
return setupCommands;
}
@Override
public List<Class<? extends UICommand>> getGenerationFlow()
{
List<Class<? extends UICommand>> generationCommands = new ArrayList<Class<? extends UICommand>>();
generationCommands.add(ScaffoldableEntitySelectionWizard.class);
return generationCommands;
}
protected List<Resource<?>> generateIndex(String targetDir, final Resource<?> template, final boolean overwrite)
{
List<Resource<?>> result = new ArrayList<Resource<?>>();
WebResourcesFacet web = this.origin.getFacet(WebResourcesFacet.class);
// TODO: Refactor this and remove the duplication
// TODO: origin.getFacet(ServletFacet.class) returns null!!
if (this.origin.hasFacet(ServletFacet_3_0.class))
{
ServletFacet servlet = this.origin.getFacet(ServletFacet_3_0.class);
WebAppDescriptor servletConfig = (WebAppDescriptor) servlet.getConfig();
servletConfig.getOrCreateWelcomeFileList().welcomeFile("/index.html");
}
else if (this.origin.hasFacet(ServletFacet_3_1.class))
{
ServletFacet servlet = this.origin.getFacet(ServletFacet_3_1.class);
org.jboss.shrinkwrap.descriptor.api.webapp31.WebAppDescriptor servletConfig = (org.jboss.shrinkwrap.descriptor.api.webapp31.WebAppDescriptor) servlet
.getConfig();
servletConfig.getOrCreateWelcomeFileList().welcomeFile("/index.html");
}
loadTemplates();
generateTemplates(targetDir, overwrite);
HashMap<Object, Object> context = getTemplateContext(targetDir, template);
// Basic pages
result.add(ScaffoldUtil.createOrOverwrite(web.getWebResource(targetDir + "/index.html"),
this.templateProcessor.processTemplate(context, indexWelcomeTemplate), overwrite));
result.add(ScaffoldUtil.createOrOverwrite(web.getWebResource(targetDir + "/index.xhtml"),
this.templateProcessor.processTemplate(context, indexTemplate), overwrite));
result.add(ScaffoldUtil.createOrOverwrite(web.getWebResource(ERROR_XHTML),
this.templateProcessor.processTemplate(context, errorTemplate), overwrite));
// Static resources
result.add(ScaffoldUtil.createOrOverwrite(web.getWebResource(ADD_PNG),
getClass().getResourceAsStream("/scaffold/faces/add.png"), overwrite));
result.add(ScaffoldUtil.createOrOverwrite(web.getWebResource(BOOTSTRAP_CSS),
getClass().getResourceAsStream("/scaffold/faces/bootstrap.css"), overwrite));
result.add(ScaffoldUtil.createOrOverwrite(web.getWebResource(FALSE_PNG),
getClass().getResourceAsStream("/scaffold/faces/false.png"), overwrite));
result.add(ScaffoldUtil.createOrOverwrite(web.getWebResource(FAVICON_ICO),
getClass().getResourceAsStream("/scaffold/faces/favicon.ico"), overwrite));
result.add(ScaffoldUtil.createOrOverwrite(web.getWebResource(FORGE_LOGO_PNG),
getClass().getResourceAsStream("/scaffold/faces/forge-logo.png"), overwrite));
result.add(ScaffoldUtil.createOrOverwrite(web.getWebResource(FORGE_STYLE_CSS),
getClass().getResourceAsStream("/scaffold/faces/forge-style.css"), overwrite));
result.add(ScaffoldUtil.createOrOverwrite(web.getWebResource(REMOVE_PNG),
getClass().getResourceAsStream("/scaffold/faces/remove.png"), overwrite));
result.add(ScaffoldUtil.createOrOverwrite(web.getWebResource(SEARCH_PNG),
getClass().getResourceAsStream("/scaffold/faces/search.png"), overwrite));
result.add(ScaffoldUtil.createOrOverwrite(web.getWebResource(TRUE_PNG),
getClass().getResourceAsStream("/scaffold/faces/true.png"), overwrite));
result.add(ScaffoldUtil.createOrOverwrite(web.getWebResource(JBOSS_COMMUNITY_PNG),
getClass().getResourceAsStream("/scaffold/faces/jboss-community.png"), overwrite));
return result;
}
@Override
public AccessStrategy getAccessStrategy()
{
return new FacesAccessStrategy(this.origin);
}
public TemplateStrategy getTemplateStrategy()
{
return new FacesTemplateStrategy(this.origin);
}
protected List<Resource<?>> generateTemplates(String targetDir, final boolean overwrite)
{
List<Resource<?>> result = new ArrayList<Resource<?>>();
try
{
WebResourcesFacet web = this.origin.getFacet(WebResourcesFacet.class);
result.add(ScaffoldUtil.createOrOverwrite(web.getWebResource("/resources/scaffold/paginator.xhtml"),
getClass().getResourceAsStream("/scaffold/faces/paginator.xhtml"), overwrite));
result.add(generateNavigation(targetDir, overwrite));
}
catch (Exception e)
{
throw new RuntimeException("Error generating default templates", e);
}
return result;
}
protected void loadTemplates()
{
if (this.backingBeanTemplate == null)
{
this.backingBeanTemplate = this.templateProcessor.getTemplate(BACKING_BEAN_TEMPLATE);
String template = this.backingBeanTemplate.toString();
this.backingBeanTemplateQbeMetawidgetIndent = parseIndent(template, "${qbeMetawidget}");
this.backingBeanTemplateRmEntityMetawidgetIndent = parseIndent(template, "${rmEntityMetawidget}");
}
if (this.viewUtilsTemplate == null)
{
this.viewUtilsTemplate = this.templateProcessor.getTemplate(VIEW_UTILS_TEMPLATE);
}
if (this.taglibTemplate == null)
{
this.taglibTemplate = this.templateProcessor.getTemplate(TAGLIB_TEMPLATE);
}
if (this.viewTemplate == null)
{
this.viewTemplate = this.templateProcessor.getTemplate(VIEW_TEMPLATE);
String template = this.viewTemplate.toString();
this.viewTemplateNamespaces = parseNamespaces(template);
this.viewTemplateEntityMetawidgetIndent = parseIndent(template, "${metawidget}");
}
if (this.createTemplate == null)
{
this.createTemplate = this.templateProcessor.getTemplate(CREATE_TEMPLATE);
String template = this.createTemplate.toString();
this.createTemplateNamespaces = parseNamespaces(template);
this.createTemplateEntityMetawidgetIndent = parseIndent(template, "${metawidget}");
}
if (this.searchTemplate == null)
{
this.searchTemplate = this.templateProcessor.getTemplate(SEARCH_TEMPLATE);
String template = this.searchTemplate.toString();
this.searchTemplateNamespaces = parseNamespaces(template);
this.searchTemplateSearchMetawidgetIndent = parseIndent(template, "${searchMetawidget}");
this.searchTemplateBeanMetawidgetIndent = parseIndent(template, "${beanMetawidget}");
}
if (this.navigationTemplate == null)
{
this.navigationTemplate = this.templateProcessor.getTemplate(NAVIGATION_TEMPLATE);
String template = navigationTemplate.toString();
this.navigationTemplateIndent = parseIndent(template, "${navigation}");
}
if (this.errorTemplate == null)
{
this.errorTemplate = this.templateProcessor.getTemplate(ERROR_TEMPLATE);
}
if (this.indexTemplate == null)
{
this.indexTemplate = this.templateProcessor.getTemplate(INDEX_TEMPLATE);
}
if (this.indexWelcomeTemplate == null)
{
this.indexWelcomeTemplate = this.templateProcessor.getTemplate(INDEX_WELCOME_TEMPLATE);
}
}
protected HashMap<Object, Object> getTemplateContext(String targetDir, final Resource<?> template)
{
TemplateStrategy templateStrategy = getTemplateStrategy();
HashMap<Object, Object> context;
context = new HashMap<Object, Object>();
context.put("template", template);
//TODO Fix ResourceUtil first
//context.put("templatePath", templateStrategy.getReferencePath(template != null ? template : templateStrategy.getDefaultTemplate()));
context.put("templatePath", "/resources/scaffold/paginator.xhtml");
context.put("templateStrategy", templateStrategy);
context.put("targetDir", targetDir);
return context;
}
protected void setupWebXML()
{
WebResourcesFacet web = this.origin.getFacet(WebResourcesFacet.class);
// TODO: Refactor this and remove the duplication
// TODO: origin.getFacet(ServletFacet.class) returns null!!
if (this.origin.hasFacet(ServletFacet_3_0.class))
{
ServletFacet servlet = this.origin.getFacet(ServletFacet_3_0.class);
WebAppDescriptor servletConfig = (WebAppDescriptor) servlet.getConfig();
Node root = ((NodeDescriptor)servletConfig).getRootNode();
removeConflictingErrorPages(root);
// (prefer /faces/error.xhtml)
String errorLocation = getAccessStrategy().getWebPaths(web.getWebResource(ERROR_XHTML)).get(1);
servletConfig.createErrorPage().errorCode("404").location(errorLocation);
servletConfig.createErrorPage().errorCode("500").location(errorLocation);
// Use the server timezone since we accept dates in that timezone, and it makes sense to display them in the
// same
boolean found = false;
for (ParamValueType<WebAppDescriptor> contextParam : servletConfig.getAllContextParam())
{
if (contextParam.getParamName().equals("javax.faces.DATETIMECONVERTER_DEFAULT_TIMEZONE_IS_SYSTEM_TIMEZONE"))
{
found = true;
}
}
if (!found)
{
servletConfig.createContextParam()
.paramName("javax.faces.DATETIMECONVERTER_DEFAULT_TIMEZONE_IS_SYSTEM_TIMEZONE").paramValue("true");
}
servlet.saveConfig(servletConfig);
}
else if (this.origin.hasFacet(ServletFacet_3_1.class))
{
ServletFacet servlet = this.origin.getFacet(ServletFacet_3_1.class);
org.jboss.shrinkwrap.descriptor.api.webapp31.WebAppDescriptor servletConfig = (org.jboss.shrinkwrap.descriptor.api.webapp31.WebAppDescriptor) servlet
.getConfig();
// (prefer /faces/error.xhtml)
String errorLocation = getAccessStrategy().getWebPaths(web.getWebResource(ERROR_XHTML)).get(1);
servletConfig.createErrorPage().errorCode("404").location(errorLocation);
servletConfig.createErrorPage().errorCode("500").location(errorLocation);
// Use the server timezone since we accept dates in that timezone, and it makes sense to display them in the
// same
boolean found = false;
for (org.jboss.shrinkwrap.descriptor.api.javaee7.ParamValueType<org.jboss.shrinkwrap.descriptor.api.webapp31.WebAppDescriptor> contextParam : servletConfig
.getAllContextParam())
{
if (contextParam.getParamName().equals("javax.faces.DATETIMECONVERTER_DEFAULT_TIMEZONE_IS_SYSTEM_TIMEZONE"))
{
found = true;
}
}
if (!found)
{
servletConfig.createContextParam()
.paramName("javax.faces.DATETIMECONVERTER_DEFAULT_TIMEZONE_IS_SYSTEM_TIMEZONE").paramValue("true");
}
servlet.saveConfig(servletConfig);
}
}
private void removeConflictingErrorPages(Node root)
{
List<Node> nodeList = root.get("error-page");
for (Node errorPage : nodeList)
{
String errorCode = errorPage.getTextValueForPatternName("error-code");
if(errorCode.equals("404") || errorCode.equals("500"))
{
// TODO: Prompt before removing? A prompt existed in Forge 1.
root.removeChild(errorPage);
}
}
}
/**
* Generates the navigation menu based on scaffolded entities.
*/
protected Resource<?> generateNavigation(final String targetDir, final boolean overwrite)
throws IOException
{
WebResourcesFacet web = this.origin.getFacet(WebResourcesFacet.class);
HtmlTag unorderedList = new HtmlTag("ul");
ResourceFilter filter = new ResourceFilter()
{
@Override
public boolean accept(Resource<?> resource)
{
FileResource<?> file = (FileResource<?>) resource;
if (!file.isDirectory()
|| file.getName().equals("resources")
|| file.getName().equals("WEB-INF")
|| file.getName().equals("META-INF"))
{
return false;
}
return true;
}
};
for (Resource<?> resource : web.getWebResource(targetDir + "/").listResources(filter))
{
HtmlOutcomeTargetLink outcomeTargetLink = new HtmlOutcomeTargetLink();
outcomeTargetLink.putAttribute("outcome", targetDir + "/" + resource.getName() + "/search");
outcomeTargetLink.setValue(StringUtils.uncamelCase(resource.getName()));
HtmlTag listItem = new HtmlTag("li");
listItem.getChildren().add(outcomeTargetLink);
unorderedList.getChildren().add(listItem);
}
Writer writer = new IndentedWriter(new StringWriter(), this.navigationTemplateIndent);
unorderedList.write(writer);
Map<Object, Object> context = CollectionUtils.newHashMap();
context.put("appName", StringUtils.uncamelCase(this.origin.getProjectRoot().getName()));
context.put("navigation", writer.toString().trim());
context.put("targetDir", targetDir);
if (this.navigationTemplate == null)
{
loadTemplates();
}
try
{
return ScaffoldUtil.createOrOverwrite((FileResource<?>) getTemplateStrategy()
.getDefaultTemplate(),
this.templateProcessor.processTemplate(context, navigationTemplate),
overwrite);
}
finally
{
writer.close();
}
}
/**
* Parses the given XML and determines what namespaces it already declares. These are later removed from the list of
* namespaces that Metawidget introduces.
*/
protected Map<String, String> parseNamespaces(final String template)
{
Map<String, String> namespaces = CollectionUtils.newHashMap();
Document document = XmlUtils.documentFromString(template);
Element element = document.getDocumentElement();
NamedNodeMap attributes = element.getAttributes();
for (int loop = 0, length = attributes.getLength(); loop < length; loop++)
{
org.w3c.dom.Node node = attributes.item(loop);
String nodeName = node.getNodeName();
int indexOf = nodeName.indexOf(XMLNS_PREFIX);
if (indexOf == -1)
{
continue;
}
namespaces.put(nodeName.substring(indexOf + XMLNS_PREFIX.length()), node.getNodeValue());
}
return namespaces;
}
/**
* Parses the given XML and determines the indent of the given String namespaces that Metawidget introduces.
*/
protected int parseIndent(final String template, final String indentOf)
{
int indent = 0;
int indexOf = template.indexOf(indentOf);
while ((indexOf >= 0) && (template.charAt(indexOf) != '\n'))
{
if (template.charAt(indexOf) == '\t')
{
indent++;
}
indexOf
}
return indent;
}
private void resetMetaWidgets()
{
ForgeConfigReader configReader = new ForgeConfigReader(this.config, this.origin);
this.entityMetawidget = new StaticHtmlMetawidget();
this.entityMetawidget.setConfigReader(configReader);
this.entityMetawidget.setConfig("scaffold/faces/metawidget-entity.xml");
this.searchMetawidget = new StaticHtmlMetawidget();
this.searchMetawidget.setConfigReader(configReader);
this.searchMetawidget.setConfig("scaffold/faces/metawidget-search.xml");
this.beanMetawidget = new StaticHtmlMetawidget();
this.beanMetawidget.setConfigReader(configReader);
this.beanMetawidget.setConfig("scaffold/faces/metawidget-bean.xml");
this.qbeMetawidget = new StaticJavaMetawidget();
this.qbeMetawidget.setConfigReader(configReader);
this.qbeMetawidget.setConfig("scaffold/faces/metawidget-qbe.xml");
this.rmEntityMetawidget = new StaticJavaMetawidget();
this.rmEntityMetawidget.setConfigReader(configReader);
this.rmEntityMetawidget.setConfig("scaffold/faces/metawidget-remove-entity.xml");
}
private List<Resource<?>> generateFromEntity(String targetDir, final Resource<?> template, final JavaClass entity,
final boolean overwrite)
{
resetMetaWidgets();
// FORGE-460: setupRichFaces during generateFromEntity, not during setup, as generally 'richfaces setup' is called
// *after* 'scaffold setup'
// setupRichFaces();
// Track the list of resources generated
List<Resource<?>> result = new ArrayList<Resource<?>>();
try
{
JavaSourceFacet java = this.origin.getFacet(JavaSourceFacet.class);
WebResourcesFacet web = this.origin.getFacet(WebResourcesFacet.class);
loadTemplates();
Map<Object, Object> context = CollectionUtils.newHashMap();
context.put("entity", entity);
String ccEntity = StringUtils.decapitalize(entity.getName());
context.put("ccEntity", ccEntity);
context.put("rmEntity", ccEntity + "ToDelete");
setPrimaryKeyMetaData(context, entity);
// Prepare qbeMetawidget
this.qbeMetawidget.setPath(entity.getQualifiedName());
StringWriter stringWriter = new StringWriter();
this.qbeMetawidget.write(stringWriter, this.backingBeanTemplateQbeMetawidgetIndent);
context.put("qbeMetawidget", stringWriter.toString().trim());
// Prepare removeEntityMetawidget
this.rmEntityMetawidget.setPath(entity.getQualifiedName());
stringWriter = new StringWriter();
this.rmEntityMetawidget.write(stringWriter, this.backingBeanTemplateRmEntityMetawidgetIndent);
context.put("rmEntityMetawidget", stringWriter.toString().trim());
// Prepare Java imports
Set<String> qbeMetawidgetImports = this.qbeMetawidget.getImports();
Set<String> rmEntityMetawidgetImports = this.rmEntityMetawidget.getImports();
Set<String> metawidgetImports = CollectionUtils.newHashSet();
metawidgetImports.addAll(qbeMetawidgetImports);
metawidgetImports.addAll(rmEntityMetawidgetImports);
metawidgetImports.remove(entity.getQualifiedName());
context.put("metawidgetImports",
CollectionUtils.toString(metawidgetImports, ";\r\nimport ", true, false));
// Create the Backing Bean for this entity
JavaClass viewBean = JavaParser.parse(JavaClass.class, this.templateProcessor.processTemplate(context, this.backingBeanTemplate));
viewBean.setPackage(java.getBasePackage() + ".view");
result.add(ScaffoldUtil.createOrOverwrite(java.getJavaResource(viewBean), viewBean.toString(),
overwrite));
// Set new context for view generation
context = getTemplateContext(targetDir, template);
String beanName = StringUtils.decapitalize(viewBean.getName());
context.put("beanName", beanName);
context.put("ccEntity", ccEntity);
context.put("entityName", StringUtils.uncamelCase(entity.getName()));
setPrimaryKeyMetaData(context, entity);
// Prepare entityMetawidget
this.entityMetawidget.setValue(StaticFacesUtils.wrapExpression(beanName + "." + ccEntity));
this.entityMetawidget.setPath(entity.getQualifiedName());
this.entityMetawidget.setReadOnly(false);
this.entityMetawidget.setStyle(null);
// Generate create
writeEntityMetawidget(context, this.createTemplateEntityMetawidgetIndent, this.createTemplateNamespaces);
result.add(ScaffoldUtil.createOrOverwrite(
web.getWebResource(targetDir + "/" + ccEntity + "/create.xhtml"),
this.templateProcessor.processTemplate(context, this.createTemplate),
overwrite));
// Generate view
this.entityMetawidget.setReadOnly(true);
writeEntityMetawidget(context, this.viewTemplateEntityMetawidgetIndent, this.viewTemplateNamespaces);
result.add(ScaffoldUtil.createOrOverwrite(
web.getWebResource(targetDir + "/" + ccEntity + "/view.xhtml"),
this.templateProcessor.processTemplate(context, this.viewTemplate), overwrite));
// Generate search
this.searchMetawidget.setValue(StaticFacesUtils.wrapExpression(beanName + ".example"));
this.searchMetawidget.setPath(entity.getQualifiedName());
this.beanMetawidget.setValue(StaticFacesUtils.wrapExpression(beanName + ".pageItems"));
this.beanMetawidget.setPath(viewBean.getQualifiedName() + "/pageItems");
writeSearchAndBeanMetawidget(context, this.searchTemplateSearchMetawidgetIndent,
this.searchTemplateBeanMetawidgetIndent, this.searchTemplateNamespaces);
result.add(ScaffoldUtil.createOrOverwrite(
web.getWebResource(targetDir + "/" + ccEntity + "/search.xhtml"),
this.templateProcessor.processTemplate(context, this.searchTemplate), overwrite));
// Generate navigation
result.add(generateNavigation(targetDir, overwrite));
// Need ViewUtils and forge.taglib.xml for forgeview:asList
JavaClass viewUtils = JavaParser.parse(JavaClass.class, this.templateProcessor.processTemplate(context, this.viewUtilsTemplate));
viewUtils.setPackage(viewBean.getPackage());
result.add(ScaffoldUtil.createOrOverwrite(java.getJavaResource(viewUtils), viewUtils.toString(),
true));
context.put("viewPackage", viewBean.getPackage());
result.add(ScaffoldUtil.createOrOverwrite(
web.getWebResource("WEB-INF/classes/META-INF/forge.taglib.xml"),
this.templateProcessor.processTemplate(context, this.taglibTemplate), true));
createInitializers(entity);
}
catch (Exception e)
{
throw new RuntimeException("Error generating default scaffolding: " + e.getMessage(), e);
}
return result;
}
/**
* Writes the entity Metawidget and its namespaces into the given context.
*/
protected void writeEntityMetawidget(final Map<Object, Object> context, final int entityMetawidgetIndent,
final Map<String, String> existingNamespaces)
{
StringWriter stringWriter = new StringWriter();
this.entityMetawidget.write(stringWriter, entityMetawidgetIndent);
context.put("metawidget", stringWriter.toString().trim());
Map<String, String> namespaces = this.entityMetawidget.getNamespaces();
namespaces.keySet().removeAll(existingNamespaces.keySet());
context.put("metawidgetNamespaces", namespacesToString(namespaces));
}
/**
* Writes the search Metawidget, the bean Metawidget and their namespaces into the given context.
*/
protected void writeSearchAndBeanMetawidget(final Map<Object, Object> context, final int searchMetawidgetIndent,
final int beanMetawidgetIndent,
final Map<String, String> existingNamespaces)
{
StringWriter stringWriter = new StringWriter();
this.searchMetawidget.write(stringWriter, searchMetawidgetIndent);
context.put("searchMetawidget", stringWriter.toString().trim());
stringWriter = new StringWriter();
this.beanMetawidget.write(stringWriter, beanMetawidgetIndent);
context.put("beanMetawidget", stringWriter.toString().trim());
Map<String, String> namespaces = this.searchMetawidget.getNamespaces();
namespaces.putAll(this.beanMetawidget.getNamespaces());
namespaces.keySet().removeAll(existingNamespaces.keySet());
context.put("metawidgetNamespaces", namespacesToString(namespaces));
}
protected String namespacesToString(final Map<String, String> namespaces)
{
StringBuilder builder = new StringBuilder();
for (Map.Entry<String, String> entry : namespaces.entrySet())
{
// At the start, break out of the current quote. Field must be in quotes so that we're valid XML
builder.append("\"\r\n\txmlns:");
builder.append(entry.getKey());
builder.append("=\"");
builder.append(entry.getValue());
}
return builder.toString();
}
protected void createInitializers(final JavaClass entity) throws FacetNotFoundException, FileNotFoundException
{
boolean dirtyBit = false;
for (Field<JavaClass> field : entity.getFields())
{
if (field.hasAnnotation(OneToOne.class))
{
Annotation<JavaClass> oneToOne = field.getAnnotation(OneToOne.class);
if (oneToOne.getStringValue("mappedBy") == null && oneToOne.getStringValue("cascade") == null)
{
oneToOne.setEnumValue("cascade", CascadeType.ALL);
dirtyBit = true;
}
String methodName = "new" + StringUtils.capitalize(field.getName());
if (!entity.hasMethodSignature(methodName))
{
entity.addMethod().setName(methodName).setReturnTypeVoid().setPublic()
.setBody("this." + field.getName() + " = new " + field.getType() + "();");
dirtyBit = true;
}
}
}
for (Method<JavaClass> method : entity.getMethods())
{
if (method.hasAnnotation(OneToOne.class))
{
Annotation<JavaClass> oneToOne = method.getAnnotation(OneToOne.class);
if (oneToOne.getStringValue("mappedBy") == null && oneToOne.getStringValue("cascade") == null)
{
oneToOne.setEnumValue("cascade", CascadeType.ALL);
dirtyBit = true;
}
String fieldName = StringUtils.camelCase(method.getName().substring(3));
String methodName = "new" + StringUtils.capitalize(fieldName);
if (!entity.hasMethodSignature(methodName))
{
entity.addMethod().setName(methodName).setReturnTypeVoid().setPublic()
.setBody("this." + fieldName + " = new " + method.getReturnType() + "();");
dirtyBit = true;
}
}
}
if(dirtyBit)
{
this.origin.getFacet(JavaSourceFacet.class).saveJavaSource(entity);
}
}
private void setPrimaryKeyMetaData(Map<Object, Object> context, final JavaClass entity)
{
String pkName = "id";
String pkType = "Long";
String nullablePkType = "Long";
for (Member<JavaClass, ?> m : entity.getMembers())
{
if (m.hasAnnotation(Id.class))
{
if (m instanceof Field)
{
Field<?> field = (Field<?>) m;
pkName = field.getName();
pkType = field.getType();
nullablePkType = pkType;
break;
}
Method<?> method = (Method<?>) m;
pkName = method.getName().substring(3);
if (method.getName().startsWith("get"))
{
pkType = method.getReturnType();
}
else
{
pkType = method.getParameters().get(0).getType();
}
nullablePkType = pkType;
break;
}
}
if ("int".equals(pkType))
{
nullablePkType = Integer.class.getSimpleName();
}
else if ("short".equals(pkType))
{
nullablePkType = Short.class.getSimpleName();
}
else if ("byte".equals(pkType))
{
nullablePkType = Byte.class.getSimpleName();
}
else if ("long".equals(pkType))
{
nullablePkType = Long.class.getSimpleName();
}
context.put("primaryKey", pkName);
context.put("primaryKeyCC", StringUtils.capitalize(pkName));
context.put("primaryKeyType", pkType);
context.put("nullablePrimaryKeyType", nullablePkType);
}
protected void setupRichFaces()
{
if ((this.origin.getFacet(DependencyFacet.class).hasEffectiveDependency(this.richfaces3UI)
&& this.origin.getFacet(DependencyFacet.class).hasEffectiveDependency(this.richfaces3Impl))
|| (this.origin.getFacet(DependencyFacet.class).hasEffectiveDependency(this.richfaces4UI)
&& this.origin.getFacet(DependencyFacet.class).hasEffectiveDependency(this.richfaces4Impl)))
{
this.entityMetawidget
.setWidgetBuilder(insertRichFacesWidgetBuilder((CompositeWidgetBuilder<StaticWidget, StaticMetawidget>) this.entityMetawidget
.getWidgetBuilder()));
this.searchMetawidget
.setWidgetBuilder(insertRichFacesWidgetBuilder((CompositeWidgetBuilder<StaticWidget, StaticMetawidget>) this.searchMetawidget
.getWidgetBuilder()));
this.beanMetawidget
.setWidgetBuilder(insertRichFacesWidgetBuilder((CompositeWidgetBuilder<StaticWidget, StaticMetawidget>) this.beanMetawidget
.getWidgetBuilder()));
}
}
/**
* Locates a <code>ReadOnlyWidgetBuilder</code> in the list of WidgetBuilders, and inserts a
* <code>RichFacesWidgetBuilder</code> after it (unless there's a <code>RichFacesWidgetBuilder</code> in there
* already).
*/
protected <W extends StaticWidget, M extends W> CompositeWidgetBuilder<W, M> insertRichFacesWidgetBuilder(
final CompositeWidgetBuilder<W, M> compositeWidgetBuilder)
{
// Get the current WidgetBuilders...
WidgetBuilder<W, M>[] existingWidgetBuilders = compositeWidgetBuilder.getWidgetBuilders();
// ...find the ReadOnlyWidgetBuilder (if any)...
int addAt = 0;
for (int loop = 0; loop < existingWidgetBuilders.length; loop++)
{
// ...(abort if there's already a RichFacesWidgetBuilder)...
// Use an Object loop variable here to avoid a nasty Java/Generics compiler bug
Object widgetBuilder = existingWidgetBuilders[loop];
if (widgetBuilder instanceof RichFacesWidgetBuilder)
{
return compositeWidgetBuilder;
}
if (widgetBuilder instanceof ReadOnlyWidgetBuilder)
{
addAt = loop + 1;
}
}
// ...and insert our RichFacesWidgetBuilder just after it
@SuppressWarnings("unchecked")
WidgetBuilder<W, M>[] newWidgetBuilders = (WidgetBuilder<W, M>[]) ArrayUtils.addAt(existingWidgetBuilders, addAt,
new RichFacesWidgetBuilder());
return new CompositeWidgetBuilder<W, M>(
new CompositeWidgetBuilderConfig<W, M>().setWidgetBuilders(newWidgetBuilders));
}
}
|
package org.apache.mesos.elasticsearch.scheduler;
import org.apache.commons.cli.BasicParser;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.apache.log4j.Logger;
import org.apache.mesos.MesosSchedulerDriver;
import org.apache.mesos.Protos;
import org.apache.mesos.Scheduler;
import org.apache.mesos.SchedulerDriver;
import org.apache.mesos.elasticsearch.common.Binaries;
import org.apache.mesos.elasticsearch.common.Configuration;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.CountDownLatch;
import java.util.function.Predicate;
import static java.util.stream.Collectors.toList;
/**
* Scheduler for Elasticsearch.
*/
@SuppressWarnings("PMD.TooManyMethods")
public class ElasticsearchScheduler implements Scheduler, Runnable {
public static final Logger LOGGER = Logger.getLogger(ElasticsearchScheduler.class.toString());
public static final String TASK_DATE_FORMAT = "yyyyMMdd'T'HHmmss.SSS'Z'";
// As per the DCOS Service Specification, setting the failover timeout to a large value;
private static final double FAILOVER_TIMEOUT = 86400000;
Clock clock = new Clock();
Set<Task> tasks = new HashSet<>();
private CountDownLatch initialized = new CountDownLatch(1);
private int numberOfHwNodes;
private String masterUrl;
private boolean useDocker;
private String namenode;
private Protos.FrameworkID frameworkId;
public ElasticsearchScheduler(String masterUrl, int numberOfHwNodes, boolean useDocker, String namenode) {
this.masterUrl = masterUrl;
this.numberOfHwNodes = numberOfHwNodes;
this.useDocker = useDocker;
this.namenode = namenode;
}
public static void main(String[] args) {
Options options = new Options();
options.addOption("m", "masterUrl", true, "master url");
options.addOption("n", "numHardwareNodes", true, "number of hardware nodes");
options.addOption("d", "useDocker", false, "use docker to launch Elasticsearch");
options.addOption("nn", "namenode", true, "name node hostname + port");
CommandLineParser parser = new BasicParser();
try {
CommandLine cmd = parser.parse(options, args);
String masterUrl = cmd.getOptionValue("m");
String numberOfHwNodesString = cmd.getOptionValue("n");
String useDockerString = cmd.getOptionValue("d");
String nameNode = cmd.getOptionValue("nn");
if (masterUrl == null || numberOfHwNodesString == null || nameNode == null) {
printUsage(options);
return;
}
int numberOfHwNodes;
try {
numberOfHwNodes = Integer.parseInt(numberOfHwNodesString);
} catch (IllegalArgumentException e) {
printUsage(options);
return;
}
boolean useDocker = Boolean.parseBoolean(useDockerString);
LOGGER.info("Starting ElasticSearch on Mesos - [master: " + masterUrl + ", numHwNodes: " + numberOfHwNodes + "]");
final ElasticsearchScheduler scheduler = new ElasticsearchScheduler(masterUrl, numberOfHwNodes, useDocker, nameNode);
final Protos.FrameworkInfo.Builder frameworkBuilder = Protos.FrameworkInfo.newBuilder();
frameworkBuilder.setUser("jclouds");
frameworkBuilder.setName(Configuration.FRAMEWORK_NAME);
frameworkBuilder.setCheckpoint(true);
frameworkBuilder.setFailoverTimeout(FAILOVER_TIMEOUT);
final MesosSchedulerDriver driver = new MesosSchedulerDriver(scheduler, frameworkBuilder.build(), masterUrl);
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
driver.stop();
scheduler.onShutdown();
}));
Thread schedThred = new Thread(scheduler);
schedThred.start();
scheduler.waitUntilInit();
final List<String> nodes = scheduler.getTasks().stream().map(Task::getHostname).collect(toList());
LOGGER.info("ElasticSearch nodes starting on: " + nodes);
} catch (ParseException e) {
printUsage(options);
}
}
private void onShutdown() {
LOGGER.info("On shutdown...");
}
private void waitUntilInit() {
try {
initialized.await();
} catch (InterruptedException e) {
LOGGER.error("Elasticsearch framework interrupted");
}
}
private static void printUsage(Options options) {
HelpFormatter formatter = new HelpFormatter();
formatter.printHelp(Configuration.FRAMEWORK_NAME, options);
}
@Override
public void run() {
LOGGER.info("Starting up...");
SchedulerDriver driver = new MesosSchedulerDriver(this, Protos.FrameworkInfo.newBuilder().setUser("").setName(Configuration.FRAMEWORK_NAME).build(), masterUrl);
driver.run();
}
@Override
public void registered(SchedulerDriver driver, Protos.FrameworkID frameworkId, Protos.MasterInfo masterInfo) {
this.frameworkId = frameworkId;
LOGGER.info("Framework registered as " + frameworkId.getValue());
List<Protos.Resource> resources = buildResources();
Protos.Request request = Protos.Request.newBuilder()
.addAllResources(resources)
.build();
List<Protos.Request> requests = Collections.singletonList(request);
driver.requestResources(requests);
}
private static List<Protos.Resource> buildResources() {
Protos.Resource cpus = Protos.Resource.newBuilder()
.setName("cpus")
.setType(Protos.Value.Type.SCALAR)
.setScalar(Protos.Value.Scalar.newBuilder().setValue(Configuration.CPUS).build())
.build();
Protos.Resource mem = Protos.Resource.newBuilder()
.setName("mem")
.setType(Protos.Value.Type.SCALAR)
.setScalar(Protos.Value.Scalar.newBuilder().setValue(Configuration.MEM).build())
.build();
Protos.Resource disk = Protos.Resource.newBuilder()
.setName("disk")
.setType(Protos.Value.Type.SCALAR)
.setScalar(Protos.Value.Scalar.newBuilder().setValue(Configuration.DISK).build())
.build();
Protos.Value.Range clientPortRange = Protos.Value.Range.newBuilder().setBegin(Configuration.ELASTICSEARCH_CLIENT_PORT).setEnd(Configuration.ELASTICSEARCH_CLIENT_PORT).build();
Protos.Value.Range transportPortRange = Protos.Value.Range.newBuilder().setBegin(Configuration.ELASTICSEARCH_TRANSPORT_PORT).setEnd(Configuration.ELASTICSEARCH_TRANSPORT_PORT).build();
Protos.Resource ports = Protos.Resource.newBuilder()
.setName("ports")
.setType(Protos.Value.Type.RANGES)
.setRanges(Protos.Value.Ranges.newBuilder().addRange(clientPortRange).addRange(transportPortRange))
.build();
return Arrays.asList(cpus, mem, disk, ports);
}
@Override
public void reregistered(SchedulerDriver driver, Protos.MasterInfo masterInfo) {
LOGGER.info("Framework re-registered");
}
@Override
public void resourceOffers(SchedulerDriver driver, List<Protos.Offer> offers) {
List<Protos.Resource> resources = buildResources();
for (Protos.Offer offer : offers) {
if (isOfferGood(offer) && !haveEnoughNodes()) {
LOGGER.info("Accepted offer: " + offer.getHostname() + " - " + offer.toString());
String id = taskId(offer);
Protos.TaskInfo taskInfo = buildTask(resources, offer, id);
driver.launchTasks(Collections.singleton(offer.getId()), Collections.singleton(taskInfo));
tasks.add(new Task(offer.getHostname(), id));
} else {
driver.declineOffer(offer.getId());
LOGGER.info("Declined offer: " + offer.getHostname() + " - " + offer.toString());
}
}
if (haveEnoughNodes()) {
initialized.countDown();
}
}
private Protos.TaskInfo buildTask(List<Protos.Resource> resources, Protos.Offer offer, String id) {
Protos.TaskInfo.Builder taskInfoBuilder = Protos.TaskInfo.newBuilder()
.setName(Configuration.TASK_NAME)
.setTaskId(Protos.TaskID.newBuilder().setValue(id))
.setSlaveId(offer.getSlaveId())
.addAllResources(resources);
if (useDocker) {
LOGGER.info("Using Docker to start Elasticsearch cloud mesos on slaves");
Protos.ContainerInfo.Builder containerInfo = Protos.ContainerInfo.newBuilder();
Protos.ContainerInfo.DockerInfo docker = Protos.ContainerInfo.DockerInfo.newBuilder()
.setImage("mesos/elasticsearch-cloud-mesos").build();
containerInfo.setDocker(docker);
containerInfo.setType(Protos.ContainerInfo.Type.DOCKER);
taskInfoBuilder.setContainer(containerInfo);
taskInfoBuilder
.setCommand(Protos.CommandInfo.newBuilder()
.addArguments("elasticsearch")
.addArguments("--cloud.mesos.master").addArguments("http://" + masterUrl)
.addArguments("--logger.discovery").addArguments("DEBUG")
.addArguments("--discovery.type").addArguments("mesos")
.setShell(false))
.build();
} else {
LOGGER.info("NOT using Docker to start Elasticsearch cloud mesos on slaves");
Protos.ExecutorInfo executorInfo = Protos.ExecutorInfo.newBuilder()
.setExecutorId(Protos.ExecutorID.newBuilder().setValue("" + UUID.randomUUID()))
.setFrameworkId(frameworkId)
.setCommand(Protos.CommandInfo.newBuilder()
.addUris(Protos.CommandInfo.URI.newBuilder().setValue("hdfs://" + namenode + Binaries.ES_EXECUTOR_HDFS_PATH))
.addUris(Protos.CommandInfo.URI.newBuilder().setValue("hdfs://" + namenode + Binaries.ES_CLOUD_MESOS_HDFS_PATH))
.setValue("java -jar " + Binaries.ES_EXECUTOR_JAR))
.setName("" + UUID.randomUUID())
.addAllResources(resources)
.build();
taskInfoBuilder.setExecutor(executorInfo);
}
return taskInfoBuilder.build();
}
@Override
public void offerRescinded(SchedulerDriver driver, Protos.OfferID offerId) {
LOGGER.info("Offer " + offerId.getValue() + " rescinded");
}
@Override
public void statusUpdate(SchedulerDriver driver, Protos.TaskStatus status) {
LOGGER.info("Status update - Task ID: " + status.getTaskId() + ", State: " + status.getState());
}
@Override
public void frameworkMessage(SchedulerDriver driver, Protos.ExecutorID executorId, Protos.SlaveID slaveId, byte[] data) {
LOGGER.info("Framework Message - Executor: " + executorId.getValue() + ", SlaveID: " + slaveId.getValue());
}
@Override
public void disconnected(SchedulerDriver driver) {
LOGGER.warn("Disconnected");
}
@Override
public void slaveLost(SchedulerDriver driver, Protos.SlaveID slaveId) {
LOGGER.info("Slave lost: " + slaveId.getValue());
}
@Override
public void executorLost(SchedulerDriver driver, Protos.ExecutorID executorId, Protos.SlaveID slaveId, int status) {
LOGGER.info("Executor lost: " + executorId.getValue() +
"on slave " + slaveId.getValue() +
"with status " + status);
}
@Override
public void error(SchedulerDriver driver, String message) {
LOGGER.error("Error: " + message);
}
private String taskId(Protos.Offer offer) {
String date = new SimpleDateFormat(TASK_DATE_FORMAT).format(clock.now());
return String.format("elasticsearch_%s_%s", offer.getHostname(), date);
}
private boolean isOfferGood(Protos.Offer offer) {
// Don't start the same framework multiple times on the same host
return tasks.stream().map(Task::getHostname).noneMatch(Predicate.isEqual(offer.getHostname()));
}
private boolean haveEnoughNodes() {
return tasks.size() == numberOfHwNodes;
}
public Set<Task> getTasks() {
return tasks;
}
}
|
package org.openscore.content.json.actions;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import java.util.Map;
import static junit.framework.Assert.assertEquals;
public class AddJsonPropertyToObjectTest {
public static final String RETURN_RESULT = "returnResult";
final AddJsonPropertyToObject addJsonPropertyToObject = new AddJsonPropertyToObject();
@Rule
public ExpectedException exception = ExpectedException.none();
@Test
public void testExecuteSimpleAll() throws Exception {
String jsonObject = "{}";
String name = "test";
String value = "1";
final Map<String, String> result = addJsonPropertyToObject.execute(jsonObject, name, value);
assertEquals("{\"test\":1}", result.get(RETURN_RESULT));
assertEquals("0", result.get("returnCode"));
}
@Test
public void testExecuteJsonObjectBad() throws Exception {
String jsonObject = "{";
String name = "test";
String value = "1";
final Map<String, String> result = addJsonPropertyToObject.execute(jsonObject, name, value);
assertEquals("Invalid jsonObject provided! java.io.EOFException: End of input at line 1 column 2", result.get(RETURN_RESULT));
assertEquals("java.io.EOFException: End of input at line 1 column 2", result.get("exception"));
assertEquals("-1", result.get("returnCode"));
}
@Test
public void testExecuteNameBad() throws Exception {
String jsonObject = "{}";
String name = "test{\"";
String value = "1";
final Map<String, String> result = addJsonPropertyToObject.execute(jsonObject, name, value);
assertEquals("{\"test{\\\"\":1}", result.get(RETURN_RESULT));
}
@Test
public void testExecutePropertyValueBad() throws Exception {
String jsonObject = "{}";
String name = "test";
String value = "1\"{";
final Map<String, String> result = addJsonPropertyToObject.execute(jsonObject, name, value);
assertEquals("The value for the property " + name + " it is not a valid JSON object!", result.get(RETURN_RESULT));
assertEquals("com.google.gson.stream.MalformedJsonException: Use JsonReader.setLenient(true) to accept malformed JSON at line 1 column 4 path $", result.get("exception"));
}
@Test
public void testExecutePropertyValueJson() throws Exception {
String jsonObject = "{}";
String name = "test";
String value = "{\"a\":\"b\"}";
final Map<String, String> result = addJsonPropertyToObject.execute(jsonObject, name, value);
assertEquals("{\"test\":{\"a\":\"b\"}}", result.get(RETURN_RESULT));
}
@Test
public void testExecutePropertyValueArray() throws Exception {
String jsonObject = "{}";
String name = "test";
String value = "[1,2,3]";
final Map<String, String> result = addJsonPropertyToObject.execute(jsonObject, name, value);
assertEquals("{\"test\":[1,2,3]}", result.get(RETURN_RESULT));
}
@Test
public void testExecuteJsonObjectComplex() throws Exception {
String jsonObject = "{\"one\":{\"a\":\"a\",\"B\":\"B\"}, \"two\":\"two\", \"three\":[1,2,3.4]}";
String name = "test";
String value = "{\"a\":\"b\"}";
final Map<String, String> result = addJsonPropertyToObject.execute(jsonObject, name, value);
assertEquals("{\"one\":{\"a\":\"a\",\"B\":\"B\"},\"two\":\"two\",\"three\":[1,2,3.4],\"test\":{\"a\":\"b\"}}", result.get(RETURN_RESULT));
}
@Test
public void testExecuteJsonObjectComplexPropertyString() throws Exception {
String jsonObject = "{\"one\":{\"a\":\"a\",\"B\":\"B\"}, \"two\":\"two\", \"three\":[1,2,3.4]}";
String name = "test";
String value = "a";
final Map<String, String> result = addJsonPropertyToObject.execute(jsonObject, name, value);
assertEquals("{\"one\":{\"a\":\"a\",\"B\":\"B\"},\"two\":\"two\",\"three\":[1,2,3.4],\"test\":\"a\"}", result.get(RETURN_RESULT));
}
@Test
public void testExecuteJsonObjectSpecialChars() throws Exception {
String jsonObject = "{\"one\":{\"a\":\"a\",\"B\":\"B\"}, \"two\":\"two\", \"three;/?:@&=+,$\":[1,2,3.4]}";
String name = "tes;/?:@&=+,$t";
String value = "{\"a\":\"b;/?:@&=+,$\"}";
final Map<String, String> result = addJsonPropertyToObject.execute(jsonObject, name, value);
assertEquals("{\"one\":{\"a\":\"a\",\"B\":\"B\"},\"two\":\"two\",\"three;/?:@&=+,$\":[1,2,3.4],\""+
"tes;/?:@&=+,$t\":{\"a\":\"b;/?:@&=+,$\"}}", result.get(RETURN_RESULT));
}
}
|
package org.jboss.as.server.deployment.module;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.jboss.as.server.ServerLogger;
import org.jboss.as.server.deployment.AttachmentList;
import org.jboss.as.server.deployment.Attachments;
import org.jboss.as.server.deployment.DeploymentPhaseContext;
import org.jboss.as.server.deployment.DeploymentUnit;
import org.jboss.as.server.deployment.DeploymentUnitProcessingException;
import org.jboss.as.server.deployment.DeploymentUnitProcessor;
import org.jboss.as.server.deployment.DeploymentUtils;
import org.jboss.as.server.deployment.Services;
import org.jboss.as.server.moduleservice.ExtensionIndex;
import org.jboss.as.server.moduleservice.ServiceModuleLoader;
import org.jboss.modules.ModuleIdentifier;
import org.jboss.modules.ModuleLoader;
import org.jboss.modules.filter.PathFilters;
import org.jboss.msc.service.ServiceController;
import org.jboss.msc.service.ServiceName;
/**
* A processor which adds extension-list resource roots.
*
* @author <a href="mailto:david.lloyd@redhat.com">David M. Lloyd</a>
*/
public final class ModuleExtensionListProcessor implements DeploymentUnitProcessor {
public ModuleExtensionListProcessor() {
}
/** {@inheritDoc} */
public void deploy(final DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException {
final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit();
final ModuleSpecification moduleSpecification = deploymentUnit.getAttachment(Attachments.MODULE_SPECIFICATION);
final ModuleLoader moduleLoader = deploymentUnit.getAttachment(Attachments.SERVICE_MODULE_LOADER);
final ServiceController<?> controller = phaseContext.getServiceRegistry().getRequiredService(Services.JBOSS_DEPLOYMENT_EXTENSION_INDEX);
final ExtensionIndex index = (ExtensionIndex) controller.getValue();
final List<ResourceRoot> allResourceRoots = DeploymentUtils.allResourceRoots(deploymentUnit);
final Set<ServiceName> nextPhaseDeps = new HashSet<ServiceName>();
for (ResourceRoot resourceRoot : allResourceRoots) {
final AttachmentList<ExtensionListEntry> entries = resourceRoot.getAttachment(Attachments.EXTENSION_LIST_ENTRIES);
if (entries != null) {
for (ExtensionListEntry entry : entries) {
final ModuleIdentifier extension = index.findExtension(entry.getName(), entry.getSpecificationVersion(),
entry.getImplementationVersion(), entry.getImplementationVendorId());
if (extension != null) {
ModuleDependency dependency = new ModuleDependency(moduleLoader, extension, false, false, true, false);
dependency.addImportFilter(PathFilters.getMetaInfSubdirectoriesFilter(), true);
dependency.addImportFilter(PathFilters.getMetaInfFilter(), true);
moduleSpecification.addLocalDependency(dependency);
nextPhaseDeps.add(ServiceModuleLoader.moduleSpecServiceName(extension));
nextPhaseDeps.add(ServiceModuleLoader.moduleSpecServiceName(extension));
} else {
ServerLogger.DEPLOYMENT_LOGGER.cannotFindExtensionListEntry(entry, resourceRoot);
}
}
}
}
final List<AdditionalModuleSpecification> additionalModules = deploymentUnit.getAttachment(Attachments.ADDITIONAL_MODULES);
if (additionalModules != null) {
for (AdditionalModuleSpecification additionalModule : additionalModules) {
for (ResourceRoot resourceRoot : additionalModule.getResourceRoots()) {
final AttachmentList<ExtensionListEntry> entries = resourceRoot
.getAttachment(Attachments.EXTENSION_LIST_ENTRIES);
if (entries != null) {
for (ExtensionListEntry entry : entries) {
final ModuleIdentifier extension = index.findExtension(entry.getName(), entry
.getSpecificationVersion(), entry.getImplementationVersion(), entry
.getImplementationVendorId());
if (extension != null) {
moduleSpecification.addLocalDependency(new ModuleDependency(moduleLoader, extension, false, false,
true, false));
nextPhaseDeps.add(ServiceModuleLoader.moduleSpecServiceName(extension));
} else {
ServerLogger.DEPLOYMENT_LOGGER.cannotFindExtensionListEntry(entry, resourceRoot);
}
}
}
}
}
}
for (ServiceName dep : nextPhaseDeps) {
phaseContext.addToAttachmentList(Attachments.NEXT_PHASE_DEPS, dep);
}
}
/** {@inheritDoc} */
public void undeploy(final DeploymentUnit context) {
}
}
|
package org.oskari.capabilities;
import static java.util.stream.Collectors.groupingBy;
import java.sql.Timestamp;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import javax.xml.stream.XMLStreamException;
import org.json.JSONArray;
import org.json.JSONObject;
import fi.mml.map.mapwindow.service.wms.WebMapService;
import fi.nls.oskari.annotation.Oskari;
import fi.nls.oskari.domain.map.OskariLayer;
import fi.nls.oskari.log.LogFactory;
import fi.nls.oskari.log.Logger;
import fi.nls.oskari.map.geometry.ProjectionHelper;
import fi.nls.oskari.map.layer.OskariLayerService;
import fi.nls.oskari.map.layer.OskariLayerServiceIbatisImpl;
import fi.nls.oskari.map.layer.formatters.LayerJSONFormatterWMTS;
import fi.nls.oskari.service.ServiceException;
import fi.nls.oskari.service.capabilities.CapabilitiesCacheService;
import fi.nls.oskari.service.capabilities.CapabilitiesCacheServiceMybatisImpl;
import fi.nls.oskari.service.capabilities.OskariLayerCapabilities;
import fi.nls.oskari.service.capabilities.OskariLayerCapabilitiesHelper;
import fi.nls.oskari.util.JSONHelper;
import fi.nls.oskari.util.PropertyUtil;
import fi.nls.oskari.wmts.WMTSCapabilitiesParser;
import fi.nls.oskari.wmts.domain.ResourceUrl;
import fi.nls.oskari.wmts.domain.TileMatrixLink;
import fi.nls.oskari.wmts.domain.TileMatrixSet;
import fi.nls.oskari.wmts.domain.WMTSCapabilities;
import fi.nls.oskari.wmts.domain.WMTSCapabilitiesLayer;
import fi.nls.oskari.worker.ScheduledJob;
/**
* ScheludedJob that updates Capabilities of WMS and WMTS layers
* <ul>
* <li>Updates oskari_capabilities_cache rows</li>
* <li>Updates OskariLayer objects via #setCapabilities()</li>
* </ul>
* Available configuration:
* <ul>
* <li>maxAge, skip layer if its' oskari_capabilities_cache.updated is newer than (NOW() - maxAge)</li>
* </ul>
*/
@Oskari("UpdateCapabilities")
public class UpdateCapabilitiesJob extends ScheduledJob {
private static final Logger LOG = LogFactory.getLogger(UpdateCapabilitiesJob.class);
private static final String PROP_MAX_AGE = "oskari.scheduler.job.UpdateCapabilities.maxAge";
private final OskariLayerService layerService;
private final CapabilitiesCacheService capabilitiesCacheService;
private final int maxAge;
public UpdateCapabilitiesJob() {
this(new OskariLayerServiceIbatisImpl(),
new CapabilitiesCacheServiceMybatisImpl(),
PropertyUtil.getOptional(PROP_MAX_AGE, 0));
}
public UpdateCapabilitiesJob(OskariLayerService layerService,
CapabilitiesCacheService capabilitiesService, int maxAge) {
this.layerService = layerService;
this.capabilitiesCacheService = capabilitiesService;
this.maxAge = maxAge;
}
@Override
public void execute(Map<String, Object> params) {
Map<UrlTypeVersion, List<OskariLayer>> layersByUrlTypeVersion = layerService.findAll()
.stream()
.filter(l -> canUpdate(l.getType()))
.collect(groupingBy(l -> new UrlTypeVersion(l)));
long now = System.currentTimeMillis();
Timestamp oldestAllowed = maxAge > 0L ? new Timestamp(now - maxAge) : null;
for (Map.Entry<UrlTypeVersion, List<OskariLayer>> group : layersByUrlTypeVersion.entrySet()) {
UrlTypeVersion utv = group.getKey();
List<OskariLayer> layers = group.getValue();
updateCapabilitiesGroup(utv, layers, oldestAllowed);
}
}
protected static boolean canUpdate(String type) {
switch (type) {
case OskariLayer.TYPE_WMS:
case OskariLayer.TYPE_WMTS:
return true;
default:
return false;
}
}
protected void updateCapabilitiesGroup(UrlTypeVersion utv,
List<OskariLayer> layers, Timestamp oldestAllowed) {
final String url = utv.url;
final String type = utv.type;
final String version = utv.version;
final String user = layers.get(0).getUsername();
final String pass = layers.get(0).getPassword();
int[] ids = layers.stream().mapToInt(l -> l.getId()).toArray();
if (LOG.isDebugEnabled()) {
LOG.debug("Updating Capabilities for a group of layers - url:", url,
"type:", type, "version:", version, "ids:", Arrays.toString(ids));
}
final String data = getCapabilities(url, type, version, user, pass, oldestAllowed);
if (data == null || data.isEmpty()) {
return;
}
switch (type) {
case OskariLayer.TYPE_WMS:
updateWMSLayers(layers, data);
break;
case OskariLayer.TYPE_WMTS:
boolean success = updateWMTSLayers(layers, data);
if (success) {
capabilitiesCacheService.save(new OskariLayerCapabilities(url, type, version, data));
}
break;
}
}
private void updateWMSLayers(List<OskariLayer> layers, String data) {
for (OskariLayer layer : layers) {
WebMapService wms = OskariLayerCapabilitiesHelper.parseWMSCapabilities(data, layer);
if (wms == null) {
LOG.warn("Failed to parse WMS Capabilities for layerId:", layer.getId());
continue;
}
OskariLayerCapabilitiesHelper.setPropertiesFromCapabilitiesWMS(wms, layer);
layerService.update(layer);
}
}
private boolean updateWMTSLayers(List<OskariLayer> layers, String data) {
WMTSCapabilities wmts = parseWMTSCapabilities(data);
if (wmts == null) {
return false;
}
for (OskariLayer layer : layers) {
if (updateWMTS(wmts, layer)) {
layerService.update(layer);
}
}
return true;
}
private WMTSCapabilities parseWMTSCapabilities(String data) {
try {
return WMTSCapabilitiesParser.parseCapabilities(data);
} catch (XMLStreamException | IllegalArgumentException e) {
LOG.warn(e, "Failed to parse WMTS GetCapabilities");
return null;
}
}
private String getCapabilities(String url, String type, String version,
String user, String pass, Timestamp oldestAllowed) {
// If oldestAllowed is null we don't want to check cache
if (oldestAllowed != null) {
String cached = getFromCache(url, type, version, oldestAllowed);
if (cached != null && !cached.isEmpty()) {
return cached;
}
}
return getFromService(url, type, version, user, pass);
}
private String getFromCache(String url, String type, String version, Timestamp oldestAllowed) {
OskariLayerCapabilities cached = capabilitiesCacheService.find(url, type, version);
// Check if we actually found data from DB and if it's recently updated
if (cached != null) {
if (cached.getUpdated().after(oldestAllowed)) {
return cached.getData();
}
LOG.warn("Found capabilities from cache, but it was too old, url:", url,
"type:", type, "version:", version);
} else {
LOG.info("Could not find capabilities from cache, url:", url,
"type:", type, "version:", version);
}
return null;
}
private String getFromService(String url, String type, String version, String user, String pass) {
try {
return CapabilitiesCacheService.loadCapabilitiesFromService(url, type, version, user, pass);
} catch (ServiceException e) {
Throwable cause = e.getCause();
if (cause != null) {
LOG.warn(e, "Failed to get GetCapabilities - url:", url,
"type:", type, "version:", version, "cause:", cause.getMessage());
} else {
LOG.warn(e, "Failed to get GetCapabilities - url:", url,
"type:", type, "version:", version);
}
return null;
}
}
private boolean updateWMTS(WMTSCapabilities wmts, OskariLayer layer) {
int id = layer.getId();
String name = layer.getName();
WMTSCapabilitiesLayer layerCaps = wmts.getLayer(name);
if (layerCaps == null) {
// TODO: Add notification via admin notification service (once such service is built)
LOG.warn("Couldn't find layer from Capabilities! Layer id:", id, "name:", name);
return false;
}
ResourceUrl resUrl = layerCaps.getResourceUrlByType("tile");
if (resUrl == null) {
// TODO: Add notification via admin notification service (once such service is built)
LOG.warn("Couldn't find ResourceUrl of type 'tile' from GetCapabilities"
+ " layer id:", id, "name:", name);
return false;
}
JSONObject options = layer.getOptions();
JSONHelper.putValue(options, "requestEncoding", "REST");
JSONHelper.putValue(options, "format", resUrl.getFormat());
JSONHelper.putValue(options, "urlTemplate", resUrl.getTemplate());
JSONArray epsgToTileMatrixSet = new JSONArray();
Set<String> supportedCrs = new HashSet<String>();
for (TileMatrixLink link : layerCaps.getLinks()) {
TileMatrixSet tms = link.getTileMatrixSet();
String identifier = tms.getId();
String crs = tms.getCrs();
String epsg = ProjectionHelper.shortSyntaxEpsg(crs);
epsgToTileMatrixSet.put(JSONHelper.createJSONObject(epsg, identifier));
supportedCrs.add(epsg);
}
JSONObject capabilitiesJSON = new JSONObject();
if (epsgToTileMatrixSet.length() > 0) {
JSONHelper.put(capabilitiesJSON,
LayerJSONFormatterWMTS.KEY_TILEMATRIXIDS, epsgToTileMatrixSet);
}
layer.setCapabilities(capabilitiesJSON);
layer.setSupportedCRSs(supportedCrs);
return true;
}
static class UrlTypeVersion {
private final String url;
private final String type;
private final String version;
private UrlTypeVersion(OskariLayer layer) {
url = layer.getSimplifiedUrl(true);
type = layer.getType();
version = layer.getVersion();
}
@Override
public boolean equals(Object o) {
if (o == null || !(o instanceof UrlTypeVersion)) {
return false;
}
UrlTypeVersion s = (UrlTypeVersion) o;
return url.equals(s.url)
&& type.equals(s.type)
&& version.equals(s.version);
}
@Override
public int hashCode() {
return Objects.hash(url, type, version);
}
}
}
|
package com.rgi.g2t;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Set;
import java.util.TreeSet;
import javax.imageio.ImageIO;
import com.rgi.common.BoundingBox;
import com.rgi.common.CoordinateReferenceSystem;
import com.rgi.common.coordinates.AbsoluteTileCoordinate;
import com.rgi.common.coordinates.CrsCoordinate;
import com.rgi.common.tile.TileOrigin;
import com.rgi.common.tile.profile.TileProfile;
import com.rgi.common.tile.scheme.TileScheme;
import com.rgi.common.tile.store.TileStore;
import com.rgi.common.tile.store.TileStoreException;
public class SimpleFileStore implements TileStore {
private File rootFolder = null;
private final TileProfile tileProfile;
private final TileOrigin tileOrigin;
private final String imageFormat;
public SimpleFileStore(final String name, final TileProfile tileProfile, final TileOrigin tileOrigin, final String location, final String imageFormat) throws TileStoreException {
if (!"png".equalsIgnoreCase(imageFormat) && !"jpg".equalsIgnoreCase(imageFormat))
{
throw new IllegalArgumentException("Only PNG and JPG formats supported");
}
this.imageFormat = imageFormat;
this.tileProfile = tileProfile;
this.tileOrigin = tileOrigin;
String filePart = name;
if (filePart.contains(".")) {
filePart = filePart.substring(0, filePart.indexOf('.'));
}
this.rootFolder = new File(new File(location, Integer.toString(this.tileProfile.getCoordinateReferenceSystem().getIdentifier())), filePart);
if (!this.rootFolder.exists()) {
if (!this.rootFolder.mkdirs()) {
throw new TileStoreException("Unable to create folders");
}
}
}
@Override
public BoundingBox calculateBounds() throws TileStoreException {
throw new UnsupportedOperationException("Not implemented by Simple File Store");
}
@Override
public long countTiles() throws TileStoreException {
long count = 0;
final Set<Integer> zoomLevels = this.getZoomLevels();
for (final Integer z : zoomLevels) {
final File zFolder = new File(this.rootFolder, ""+z);
for (final String xName : zFolder.list()) {
final File xFolder = new File(zFolder, xName);
for (final String yName : xFolder.list()) {
try {
Integer.parseInt(yName.replaceAll("\\."+this.imageFormat, ""));
++count;
} catch (final NumberFormatException nfe) {
// do nothing
}
} // for each y
} // for each x
} // for each zoom level
return count;
}
@Override
public long calculateSize() throws TileStoreException {
long count = 0;
final Set<Integer> zoomLevels = this.getZoomLevels();
for (final Integer z : zoomLevels) {
final File zFolder = new File(this.rootFolder, ""+z);
for (final String xName : zFolder.list()) {
final File xFolder = new File(zFolder, xName);
for (final String yName : xFolder.list()) {
count += new File(yName).length();
} // for each y
} // for each x
} // for each zoom level
return count;
}
@Override
public BufferedImage getTile(final CrsCoordinate coordinate, final int zoomLevel) throws TileStoreException {
final File zoomFolder = new File(this.rootFolder, ""+zoomLevel);
if (!zoomFolder.exists()) {
if (!zoomFolder.mkdirs()) {
throw new TileStoreException("Unable to create folders");
}
}
final File xFolder = new File(zoomFolder, ""+coordinate.getX());
if (!xFolder.exists()) {
if (!xFolder.mkdirs()) {
throw new TileStoreException("Unable to create folders");
}
}
final File yFile = new File(xFolder, coordinate.getY()+".png");
BufferedImage image;
try {
image = ImageIO.read(yFile);
} catch (final IOException ioe) {
throw new TileStoreException("Unable to read tile from file", ioe);
}
return image;
}
@Override
public void addTile(final CrsCoordinate coordinate, final int zoomLevel, final BufferedImage image)
throws TileStoreException {
final File zoomFolder = new File(this.rootFolder, ""+zoomLevel);
if (!zoomFolder.exists()) {
if (!zoomFolder.mkdirs()) {
throw new TileStoreException("Unable to create folders");
}
}
final AbsoluteTileCoordinate absTileCoordinate = this.tileProfile.crsToAbsoluteTileCoordinate(coordinate, zoomLevel, this.tileOrigin);
final File xFolder = new File(zoomFolder, ""+absTileCoordinate.getX());
if (!xFolder.exists()) {
if (!xFolder.mkdirs()) {
throw new TileStoreException("Unable to create folders");
}
}
final File yFile = new File(xFolder, absTileCoordinate.getY()+"."+this.imageFormat);
try {
ImageIO.write(image, this.imageFormat, yFile);
} catch (final IOException ioe) {
throw new TileStoreException("Unable to write tile to file", ioe);
}
}
@Override
public Set<Integer> getZoomLevels() throws TileStoreException {
final Set<Integer> zoomLevels = new TreeSet<>();
final String[] files = this.rootFolder.list((dir, name) -> {
try {
Integer.parseInt(name);
} catch (final NumberFormatException nfe) {
return false;
}
return new File(name).isDirectory();
});
for (final String file : files) {
zoomLevels.add(Integer.parseInt(file));
}
return zoomLevels;
}
@Override
public CoordinateReferenceSystem getCoordinateReferenceSystem() {
return this.tileProfile.getCoordinateReferenceSystem();
}
@Override
public TileScheme getTileScheme()
{
return null; // TODO
}
}
|
package com.grandmaapp.model;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.preference.PreferenceManager;
import com.grandmaapp.model.Grandma.Requests;
import com.grandmaapp.model.Grandma.State;
/*
* handles the Request to dress brunhilde
* takes clean clothes from the storeroom if brunhilde isn't asleep
* if no clean clothes left, request won't be handled
*
*/
public class SuitUp extends Request {
public SuitUp(){
name = "Ankleiden";
}
public boolean handleRequest(Requests r) {
if (r == Requests.SUITUP) {
int cleanClothes = grandma.getStoreroom().getCleanClothes();
AlertDialog.Builder builder = new AlertDialog.Builder(grandma.getMainActivity());
builder.setTitle("");
builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
alert.dismiss();
}
});
if(realRequest || ( (grandma.getState() != State.ASLEEP) && !realRequest) ){
if (cleanClothes > 0) {
// update clothes in the storeroom
cleanClothes -= 1;
grandma.getStoreroom().setCleanClothes(cleanClothes);
// update clothes in the preferences
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(grandma.getMainActivity());
Editor editor = preferences.edit();
editor.putInt("StoreClothes", cleanClothes);
editor.commit();
builder.setMessage("Du hast Brunhilde neu eingekleidet! Sie hat noch "
+ cleanClothes + " saubere Kleidung.");
alert = builder.create();
alert.show();
return true;
} else {
builder.setMessage("Brunhilde hat keine saubere Kleidung mehr. Du musst erst waschen!");
alert = builder.create();
alert.show();
}
}
else{
builder.setMessage("Brunhilde schlft und braucht keine neue Kleidung.");
alert = builder.create();
alert.show();
}
}
return false;
}
public Requests kind(){
return Requests.SUITUP;
}
}
|
// -*- mode:java; encoding:utf-8 -*-
// vim:set fileencoding=utf-8:
// @homepage@
package example;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Objects;
import java.util.Optional;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
import java.util.stream.Stream;
import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.plaf.LayerUI;
import javax.swing.text.BadLocationException;
import javax.swing.text.DefaultHighlighter.DefaultHighlightPainter;
import javax.swing.text.Document;
import javax.swing.text.Highlighter;
import javax.swing.text.Highlighter.HighlightPainter;
import javax.swing.text.JTextComponent;
public class MainPanel extends JPanel {
private static final String[] INIT_TXT = {
"Trail: Creating a GUI with JFC/Swing",
"https://docs.oracle.com/javase/tutorial/uiswing/learn/index.html",
"Lesson: Learning Swing by Example",
"This lesson explains the concepts you need to",
" use Swing components in building a user interface.",
" First we examine the simplest Swing application you can write.",
" Then we present several progressively complicated examples of creating",
" user interfaces using components in the javax.swing package.",
" We cover several Swing components, such as buttons, labels, and text areas.",
" The handling of events is also discussed,",
" as are layout management and accessibility.",
" This lesson ends with a set of questions and exercises",
" so you can test yourself on what you've learned.",
"https://docs.oracle.com/javase/tutorial/uiswing/learn/index.html"
};
private static final Color WARNING_COLOR = new Color(0xFF_C8_C8);
private final transient HighlightPainter currentPainter = new DefaultHighlightPainter(Color.ORANGE);
private final transient HighlightPainter highlightPainter = new DefaultHighlightPainter(Color.YELLOW);
private final JTextArea textArea = new JTextArea();
private final JTextField field = new JTextField("Swing");
private final JCheckBox checkCase = new JCheckBox("Match case");
private final JCheckBox checkWord = new JCheckBox("Match whole word only");
private final PlaceholderLayerUI<JTextComponent> layerUI = new PlaceholderLayerUI<>();
protected int current;
private MainPanel() {
super(new BorderLayout());
textArea.setEditable(false);
textArea.setText(String.join("\n", INIT_TXT));
JButton prevButton = new JButton("⋀");
prevButton.setActionCommand("prev");
JButton nextButton = new JButton("⋁");
nextButton.setActionCommand("next");
HighlightHandler handler = new HighlightHandler();
field.getDocument().addDocumentListener(handler);
Stream.of(prevButton, nextButton, checkCase, checkWord).forEach(b -> {
b.setFocusable(false);
b.addActionListener(handler);
});
JPanel bp = new JPanel(new GridLayout(1, 2));
bp.add(prevButton);
bp.add(nextButton);
JPanel cp = new JPanel(new FlowLayout(FlowLayout.RIGHT));
cp.add(checkCase);
cp.add(checkWord);
JPanel sp = new JPanel(new BorderLayout(5, 5));
sp.setBorder(BorderFactory.createTitledBorder("Search"));
sp.add(new JLayer<>(field, layerUI));
sp.add(bp, BorderLayout.EAST);
sp.add(cp, BorderLayout.SOUTH);
EventQueue.invokeLater(this::changeHighlight);
add(sp, BorderLayout.NORTH);
add(new JScrollPane(textArea));
setPreferredSize(new Dimension(320, 240));
}
private static void scrollToCenter(JTextComponent tc, int pos) throws BadLocationException {
Rectangle rect = tc.modelToView(pos);
// Java 9: Rectangle rect = tc.modelToView2D(pos).getBounds();
Container c = SwingUtilities.getAncestorOfClass(JViewport.class, tc);
if (Objects.nonNull(rect) && c instanceof JViewport) {
rect.x = Math.round(rect.x - c.getWidth() / 2f);
rect.width = c.getWidth();
rect.height = Math.round(c.getHeight() / 2f);
tc.scrollRectToVisible(rect);
}
}
private Optional<Pattern> getPattern() {
String text = field.getText();
if (Objects.isNull(text) || text.isEmpty()) {
return Optional.empty();
}
String cw = checkWord.isSelected() ? "\\b" : "";
String pattern = String.format("%s%s%s", cw, text, cw);
int flags = checkCase.isSelected() ? 0 : Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE;
try {
return Optional.of(Pattern.compile(pattern, flags));
} catch (PatternSyntaxException ex) {
field.setBackground(WARNING_COLOR);
return Optional.empty();
}
}
protected final void changeHighlight() {
field.setBackground(Color.WHITE);
Highlighter highlighter = textArea.getHighlighter();
highlighter.removeAllHighlights();
Document doc = textArea.getDocument();
getPattern().ifPresent(pattern -> {
try {
Matcher matcher = pattern.matcher(doc.getText(0, doc.getLength()));
int pos = 0;
while (matcher.find(pos) && !matcher.group().isEmpty()) {
int start = matcher.start();
int end = matcher.end();
highlighter.addHighlight(start, end, highlightPainter);
pos = end;
}
} catch (BadLocationException ex) {
// should never happen
RuntimeException wrap = new StringIndexOutOfBoundsException(ex.offsetRequested());
wrap.initCause(ex);
throw wrap;
}
});
JLabel label = layerUI.hint;
Highlighter.Highlight[] array = highlighter.getHighlights();
int hits = array.length;
if (hits == 0) {
current = -1;
label.setOpaque(true);
} else {
current = (current + hits) % hits;
label.setOpaque(false);
Highlighter.Highlight hh = highlighter.getHighlights()[current];
highlighter.removeHighlight(hh);
try {
highlighter.addHighlight(hh.getStartOffset(), hh.getEndOffset(), currentPainter);
scrollToCenter(textArea, hh.getStartOffset());
} catch (BadLocationException ex) {
// should never happen
RuntimeException wrap = new StringIndexOutOfBoundsException(ex.offsetRequested());
wrap.initCause(ex);
throw wrap;
}
}
label.setText(String.format("%02d / %02d%n", current + 1, hits));
field.repaint();
}
private class HighlightHandler implements DocumentListener, ActionListener {
@Override public void changedUpdate(DocumentEvent e) {
/* not needed */
}
@Override public void insertUpdate(DocumentEvent e) {
changeHighlight();
}
@Override public void removeUpdate(DocumentEvent e) {
changeHighlight();
}
@Override public void actionPerformed(ActionEvent e) {
Object o = e.getSource();
if (o instanceof AbstractButton) {
String cmd = ((AbstractButton) o).getActionCommand();
if ("prev".equals(cmd)) {
current
} else if ("next".equals(cmd)) {
current++;
}
}
changeHighlight();
}
}
public static void main(String[] args) {
EventQueue.invokeLater(MainPanel::createAndShowGui);
}
private static void createAndShowGui() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
Toolkit.getDefaultToolkit().beep();
}
JFrame frame = new JFrame("@title@");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.getContentPane().add(new MainPanel());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
class PlaceholderLayerUI<V extends JTextComponent> extends LayerUI<V> {
public final JLabel hint = new JLabel() {
@Override public void updateUI() {
super.updateUI();
setForeground(UIManager.getColor("TextField.inactiveForeground"));
setBackground(Color.RED);
}
};
@Override public void paint(Graphics g, JComponent c) {
super.paint(g, c);
if (c instanceof JLayer) {
JTextComponent tc = (JTextComponent) ((JLayer<?>) c).getView();
if (!tc.getText().isEmpty()) {
Graphics2D g2 = (Graphics2D) g.create();
g2.setPaint(hint.getForeground());
Insets i = tc.getInsets();
Dimension d = hint.getPreferredSize();
int x = tc.getWidth() - i.right - d.width - 2;
int y = (tc.getHeight() - d.height) / 2;
SwingUtilities.paintComponent(g2, hint, tc, x, y, d.width, d.height);
g2.dispose();
}
}
}
}
|
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
public class STB_Sample {
public void testSTB(File f1, File f2) throws STBException {
try {
InputStream is = new FileInputStream(f1);
} catch (IOException ioe) {
throw new STBException();
}
try {
InputStream is = new FileInputStream(f2);
} catch (IOException ioe) {
throw new STBException();
}
}
public void testSTB2(File f1, File f2) throws STBException {
try {
InputStream is = new FileInputStream(f1);
} catch (IOException ioe) {
throw new STBException("It's broken");
}
try {
InputStream is = new FileInputStream(f2);
} catch (IOException ioe) {
throw new STBException("It's broken");
}
}
public void testSTB3(File f1, File f2) throws STBException {
try {
InputStream is = new FileInputStream(f1);
} catch (IOException ioe) {
STBException se = new STBException("It's broken");
se.initCause(ioe);
throw se;
}
try {
InputStream is = new FileInputStream(f2);
} catch (IOException ioe) {
STBException se = new STBException("It's broken");
se.initCause(ioe);
throw se;
}
}
public void fpTestMethodDeclaresThrownType(File f1, File f2) throws STBException, IOException {
try {
InputStream is = new FileInputStream(f1);
} catch (IOException ioe) {
throw new STBException();
}
try {
InputStream is = new FileInputStream(f2);
} catch (IOException ioe) {
throw new STBException();
}
}
public void fpTestDiffMessages(File f1, File f2) throws STBException {
try {
InputStream is = new FileInputStream(f1);
} catch (IOException ioe) {
throw new STBException("Couldn't open file 1");
}
try {
InputStream is = new FileInputStream(f2);
} catch (IOException ioe) {
throw new STBException("Couldn't open file 2");
}
}
public void fpTestDiffMessagesByAppending(File f1, File f2) throws STBException {
try {
InputStream is = new FileInputStream(f1);
} catch (IOException ioe) {
throw new STBException("Couldn't open file: " + f1);
}
try {
InputStream is = new FileInputStream(f2);
} catch (IOException ioe) {
throw new STBException("Couldn't open file: " + f2);
}
}
static class STBException extends Exception {
public STBException() {
}
public STBException(String message) {
super(message);
}
}
}
|
package guitests;
import static org.junit.Assert.assertTrue;
import static seedu.ezdo.commons.core.Messages.MESSAGE_INVALID_COMMAND_FORMAT;
import static seedu.ezdo.logic.commands.DoneCommand.MESSAGE_DONE_TASK_SUCCESS;
import static seedu.ezdo.logic.commands.DoneCommand.MESSAGE_UNDONE_TASK_SUCCESS;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Calendar;
import org.junit.Test;
import guitests.guihandles.TaskCardHandle;
import seedu.ezdo.commons.core.Messages;
import seedu.ezdo.commons.exceptions.IllegalValueException;
import seedu.ezdo.logic.commands.DoneCommand;
import seedu.ezdo.logic.parser.DateParser;
import seedu.ezdo.model.todo.DueDate;
import seedu.ezdo.model.todo.Recur;
import seedu.ezdo.model.todo.StartDate;
import seedu.ezdo.testutil.TaskBuilder;
import seedu.ezdo.testutil.TestTask;
import seedu.ezdo.testutil.TestUtil;
//@@author A0141010L
public class DoneCommandTest extends EzDoGuiTest {
@Test
public void done_success() {
// marks a recurring task in the list as done
TestTask[] currentList = td.getTypicalTasks();
TestTask[] doneList = td.getTypicalDoneTasks();
int targetIndex = currentList.length;
TestTask doneTask_1 = currentList[targetIndex - 1];
assertDoneSuccess(false, targetIndex, currentList, doneList);
doneList = TestUtil.addTasksToList(doneList, doneTask_1);
// reset td.george (dates taken from typical test case) and set recurrence to nil
commandBox.runCommand("edit " + targetIndex + " s/02/07/2012 04:55 " + "d/17/07/2015 22:22 " + "f/");
TestTask editedTask = new TaskBuilder(currentList[targetIndex - 1]).build();
try {
editedTask.setRecur(new Recur(""));
} catch (IllegalValueException e) {
}
currentList[targetIndex - 1] = editedTask;
//marks that non recurring task in a list as done
TestTask doneTask_2 = currentList[targetIndex - 1];
assertDoneSuccess(false, targetIndex, currentList, doneList);
doneList = TestUtil.addTasksToList(doneList, doneTask_2);
// invalid index
commandBox.runCommand("done " + currentList.length + 1);
assertResultMessage("The task index provided is invalid.");
// invalid command
commandBox.runCommand("done a");
assertResultMessage(String.format(MESSAGE_INVALID_COMMAND_FORMAT, DoneCommand.MESSAGE_USAGE));
// invalid command
commandBox.runCommand("dones 1");
assertResultMessage(Messages.MESSAGE_UNKNOWN_COMMAND);
// view done tasks
commandBox.runCommand("done");
assertTrue(taskListPanel.isListMatching(doneList));
// invalid input when viewing done task
commandBox.runCommand("done " + doneList.length);
assertResultMessage(Messages.MESSAGE_WRONG_LIST);
}
private void assertDoneSuccess(boolean usesShortCommand, int targetIndexOneIndexed, TestTask[] currentList,
TestTask[] doneList) {
TestTask taskToDone = currentList[targetIndexOneIndexed - 1]; // -1 as
// array
// uses
// zero
// indexing
ArrayList<TestTask> tasksToDone = new ArrayList<TestTask>();
tasksToDone.add(taskToDone); // old date
currentList = TestUtil.removeTaskFromList(currentList, targetIndexOneIndexed);
doneList = TestUtil.addTasksToList(doneList, taskToDone);
if (usesShortCommand) {
commandBox.runCommand("d " + targetIndexOneIndexed);
} else {
commandBox.runCommand("done " + targetIndexOneIndexed);
}
if (!taskToDone.getRecur().isRecur()) {
// confirm the task list no longer has the done task
assertTrue(taskListPanel.isListMatching(currentList));
// confirm the result message is correct
assertResultMessage(String.format(MESSAGE_DONE_TASK_SUCCESS, tasksToDone));
// confirm the new done list contains the right data
commandBox.runCommand("done");
TaskCardHandle addedCard = taskListPanel.navigateToTask(taskToDone.getName().fullName);
assertMatching(taskToDone, addedCard);
assertTrue(taskListPanel.isListMatching(doneList));
// confirm the undone list does not contain the task just marked as
// done
commandBox.runCommand("list");
assertTrue(taskListPanel.isListMatching(currentList));
} else {
TestTask recTask = updateRecTask(new TestTask(taskToDone));
currentList = TestUtil.addTasksToList(currentList, recTask);
// confirm the task list no longer has the done task
assertTrue(taskListPanel.isListMatching(currentList));
// confirm the result message is correct
assertResultMessage(String.format(MESSAGE_DONE_TASK_SUCCESS, tasksToDone));
// confirm the new done list contains the right data
commandBox.runCommand("done");
TaskCardHandle addedCard = taskListPanel.navigateToTask(taskToDone.getName().fullName);
assertMatching(tasksToDone.get(0), addedCard);
assertTrue(taskListPanel.isListMatching(doneList));
// confirm the undone list does not contain the task just marked as
// done
commandBox.runCommand("list");
assertTrue(taskListPanel.isListMatching(currentList));
}
}
private String updateDate(int type, String originalDate) {
try {
int increment = 1;
Calendar c = Calendar.getInstance();
c.setTime(DateParser.USER_OUTPUT_DATE_FORMAT.parse(originalDate));
c.add(type, increment);
return DateParser.USER_OUTPUT_DATE_FORMAT.format(c.getTime());
} catch (ParseException pe) {
// Do nothing as the date is optional
// and cannot be parsed as Date object
}
return originalDate;
}
private TestTask updateRecTask(TestTask taskToDone) {
String recurIntervalInString = taskToDone.getRecur().toString().trim();
int recurringInterval = Recur.RECUR_INTERVALS.get(recurIntervalInString);
String startDateInString = taskToDone.getStartDate().value;
String dueDateInString = taskToDone.getDueDate().value;
String newStartDate = updateDate(recurringInterval, startDateInString);
String newDueDate = updateDate(recurringInterval, dueDateInString);
try {
taskToDone.setStartDate(new StartDate(newStartDate));
taskToDone.setDueDate(new DueDate(newDueDate));
taskToDone.setRecur(new Recur(""));
} catch (IllegalValueException e) {
}
return taskToDone;
}
//@@author A0139248X
@Test
public void undone_success() {
TestTask[] currentList = td.getTypicalDoneTasks();
TestTask[] doneList = td.getTypicalTasks();
//undone a task
int targetIndex = 1;
assertUndoneSuccess(false, targetIndex, currentList, doneList);
}
@Test
public void undone_empty() {
//no tasks in done list to undone
commandBox.runCommand("done");
commandBox.runCommand("done 1");
assertResultMessage("The task index provided is invalid.");
}
private void assertUndoneSuccess(boolean usesShortCommand, int targetIndexOneIndexed, final TestTask[] currentList,
final TestTask[] doneList) {
StringBuilder sb = new StringBuilder(); // workaround to done all tasks so we can test
sb.append("done ");
for (int i = 0; i < doneList.length; i++) {
sb.append((i + 1) + " ");
}
commandBox.runCommand(sb.toString());
TestTask taskToUndone = doneList[targetIndexOneIndexed - 1]; // -1 as array uses zero indexing
ArrayList<TestTask> tasksToUndone = new ArrayList<TestTask>();
tasksToUndone.add(taskToUndone);
TestTask[] expectedRemainder = TestUtil.removeTaskFromList(doneList, targetIndexOneIndexed);
TestTask[] expectedUndone = TestUtil.addTasksToList(currentList, taskToUndone);
commandBox.runCommand("done"); // to get to done list view
if (usesShortCommand) {
commandBox.runCommand("d " + targetIndexOneIndexed);
} else {
commandBox.runCommand("done " + targetIndexOneIndexed);
}
//confirm the done list now contains all done tasks excluding the one just marked as undone
assertTrue(taskListPanel.isListMatching(expectedRemainder));
//confirm the result message is correct
assertResultMessage(String.format(MESSAGE_UNDONE_TASK_SUCCESS, tasksToUndone));
//confirm the new current list contains the right data
commandBox.runCommand("list");
TaskCardHandle addedCard = taskListPanel.navigateToTask(taskToUndone.getName().fullName);
assertMatching(taskToUndone, addedCard);
assertTrue(taskListPanel.isListMatching(expectedUndone));
//confirm the done list does not contain the task just marked as undone
commandBox.runCommand("done");
assertTrue(taskListPanel.isListMatching(expectedRemainder));
}
}
|
package guitests;
import static org.junit.Assert.assertTrue;
import static seedu.watodo.commons.core.Messages.MESSAGE_INVALID_COMMAND_FORMAT;
import org.junit.Test;
import guitests.guihandles.TaskCardHandle;
import seedu.watodo.commons.core.Messages;
import seedu.watodo.commons.exceptions.IllegalValueException;
import seedu.watodo.logic.commands.EditCommand;
import seedu.watodo.logic.parser.DateTimeParser;
import seedu.watodo.model.tag.Tag;
import seedu.watodo.model.tag.UniqueTagList;
import seedu.watodo.model.task.DateTime;
import seedu.watodo.testutil.TaskBuilder;
import seedu.watodo.testutil.TestTask;
// TODO: reduce GUI tests by transferring some tests to be covered by lower level tests.
public class EditCommandTest extends TaskManagerGuiTest {
// The list of tasks in the task list panel is expected to match this list.
// This list is updated with every successful call to assertEditSuccess().
TestTask[] expectedTasksList = td.getTypicalTasks();
//@@author A0143076J
@Test
public void edit_InvalidFormat_failure() {
String expectedMessage = String.format(MESSAGE_INVALID_COMMAND_FORMAT, EditCommand.MESSAGE_USAGE);
commandBox.runCommand("edit ");
assertResultMessage(expectedMessage);
//missing task index
commandBox.runCommand("edit p");
assertResultMessage(expectedMessage);
commandBox.runCommand("edit updated description but missing index");
assertResultMessage(expectedMessage);
//invalid task index
commandBox.runCommand("edit 0 updatedDescription");
assertResultMessage(expectedMessage);
commandBox.runCommand("edit -1 updatedDescription");
assertResultMessage(expectedMessage);
}
@Test
public void edit_noFieldsSpecified_failure() {
commandBox.runCommand("edit 1");
assertResultMessage(EditCommand.MESSAGE_NOT_EDITED);
}
@Test
public void execute_editInvalidValues_failure() {
commandBox.runCommand("edit 1 by/invalid date");
assertResultMessage(DateTime.MESSAGE_DATETIME_CONSTRAINTS);
commandBox.runCommand("edit 1 from/thurs");
assertResultMessage(DateTimeParser.MESSAGE_INVALID_DATETIME_PREFIX_COMBI);
commandBox.runCommand("edit 1
assertResultMessage(Tag.MESSAGE_TAG_CONSTRAINTS);
}
@Test
public void edit_invalidTaskIndex_failure() {
commandBox.runCommand("edit 8 meet friend for lunch");
assertResultMessage(Messages.MESSAGE_INVALID_TASK_DISPLAYED_INDEX);
}
// test to edit the first and last indexes in the task manager in accordance to boundary value analysis
@Test
public void edit_DescriptionOnly_success() throws Exception {
String detailsToEdit = "debug bugs add test cases";
int taskManagerIndex = 1;
TestTask taskToEdit = expectedTasksList[taskManagerIndex - 1];
TestTask editedTask = new TaskBuilder(taskToEdit).withDescription(detailsToEdit).build();
assertEditSuccess(taskManagerIndex, taskManagerIndex, detailsToEdit, editedTask);
detailsToEdit = "don't play play";
taskManagerIndex = 6;
taskToEdit = expectedTasksList[taskManagerIndex - 1];
editedTask = new TaskBuilder(taskToEdit).withDescription(detailsToEdit).build();
assertEditSuccess(taskManagerIndex, taskManagerIndex, detailsToEdit, editedTask);
}
//equivalence partitions for editing dates includes promoting a floating task to a deadline or event,
// changing the existing dates of a task (also include changing from event to deadline and vice versa)
// and lastly removing the current start and/or end dates of a task (deadline or event to floating)
@Test
public void execute_editDatesOnly_success() throws IllegalValueException {
//floating to deadline
String detailsToEdit = "by/ thurs 6pm";
int taskManagerIndex = 2;
TestTask taskToEdit = expectedTasksList[taskManagerIndex - 1];
TestTask editedTask = new TaskBuilder(taskToEdit).withEndDate(detailsToEdit).build();
assertEditSuccess(taskManagerIndex, taskManagerIndex, detailsToEdit, editedTask);
//floating to event
detailsToEdit = "from/5/12 to/6/12";
taskManagerIndex = 5;
taskToEdit = expectedTasksList[taskManagerIndex - 1];
editedTask = new TaskBuilder(taskToEdit).withStartDate("5/12").withEndDate("6/12").build();
assertEditSuccess(taskManagerIndex, taskManagerIndex, detailsToEdit, editedTask);
//deadline to deadline
detailsToEdit = "by/now";
taskManagerIndex = 4;
taskToEdit = expectedTasksList[taskManagerIndex - 1];
editedTask = new TaskBuilder(taskToEdit).withEndDate("now").build();
assertEditSuccess(taskManagerIndex, taskManagerIndex, detailsToEdit, editedTask);
//deadline to event
detailsToEdit = "from/3am to/7am";
taskManagerIndex = 4;
taskToEdit = expectedTasksList[taskManagerIndex - 1];
editedTask = new TaskBuilder(taskToEdit).withStartDate("3am").withEndDate("7am").build();
assertEditSuccess(taskManagerIndex, taskManagerIndex, detailsToEdit, editedTask);
//event to float
detailsToEdit = "REMOVEDATES";
taskManagerIndex = 4;
taskToEdit = expectedTasksList[taskManagerIndex - 1];
editedTask = new TaskBuilder(taskToEdit).withStartDate(null).withEndDate(null).build();
assertEditSuccess(taskManagerIndex, taskManagerIndex, detailsToEdit, editedTask);
//deadline to float
taskManagerIndex = 3;
taskToEdit = expectedTasksList[taskManagerIndex - 1];
editedTask = new TaskBuilder(taskToEdit).withEndDate(null).build();
assertEditSuccess(taskManagerIndex, taskManagerIndex, detailsToEdit, editedTask);
}
@Test
public void execute_editAddNewTag_success() throws Exception {
String detailsToEdit = "#impt";
int taskManagerIndex = 2;
TestTask taskToEdit = expectedTasksList[taskManagerIndex - 1];
UniqueTagList currTags = taskToEdit.getTags();
Tag tagToAdd = new Tag("impt");
if (currTags.contains(tagToAdd)) {
currTags.remove(tagToAdd);
} else {
currTags.add(tagToAdd);
}
TestTask editedTask = new TaskBuilder(taskToEdit).build();
editedTask.setTags(currTags);
assertEditSuccess(taskManagerIndex, taskManagerIndex, detailsToEdit, editedTask);
}
@Test
public void execute_editDeleteExistingTag_success() throws Exception {
String detailsToEdit = "#yumm";
int taskManagerIndex = 3;
TestTask taskToEdit = expectedTasksList[taskManagerIndex - 1];
UniqueTagList currTags = taskToEdit.getTags();
Tag tagToDel = new Tag("yumm");
if (currTags.contains(tagToDel)) {
currTags.remove(tagToDel);
} else {
currTags.add(tagToDel);
}
TestTask editedTask = new TaskBuilder(taskToEdit).build();
editedTask.setTags(currTags);
assertEditSuccess(taskManagerIndex, taskManagerIndex, detailsToEdit, editedTask);
}
@Test
public void edit_multipleFieldsSpecified_success() throws Exception {
String detailsToEdit = "edited task description by/next week #hello";
int taskManagerIndex = 1;
TestTask taskToEdit = expectedTasksList[taskManagerIndex - 1];
TestTask editedTask = new TaskBuilder(taskToEdit).withDescription("edited task description")
.withEndDate("next week").withTags("hello").build();
assertEditSuccess(taskManagerIndex, taskManagerIndex, detailsToEdit, editedTask);
//flexible ordering
detailsToEdit = "REMOVEDATES HEYO #lolol NO FOMO JUST YOLO #chill";
taskManagerIndex = 5;
taskToEdit = expectedTasksList[taskManagerIndex - 1];
editedTask = new TaskBuilder(taskToEdit).withDescription("HEYO NO FOMO JUST YOLO")
.withTags("lolol", "chill").build();
assertEditSuccess(taskManagerIndex, taskManagerIndex, detailsToEdit, editedTask);
}
@Test
public void edit_multipleFieldsSpecified_failure() throws Exception {
String detailsToEdit = "REMOVEDATES edited tasks description by/next week #hello";
int taskManagerIndex = 1;
commandBox.runCommand("edit " + taskManagerIndex + " " + detailsToEdit);
assertResultMessage(DateTimeParser.MESSAGE_INVALID_DATETIME_PREFIX_COMBI);
}
@Test
public void edit_findThenEdit_success() throws Exception {
commandBox.runCommand("find mug");
String detailsToEdit = "mugger muggings";
int filteredTaskListIndex = 1;
int taskManagerIndex = 2;
TestTask taskToEdit = expectedTasksList[taskManagerIndex - 1];
TestTask editedTask = new TaskBuilder(taskToEdit).withDescription(detailsToEdit).build();
assertEditSuccess(filteredTaskListIndex, taskManagerIndex, detailsToEdit, editedTask);
}
@Test
public void edit_duplicateTask_failure() {
commandBox.runCommand("edit 6 sleep? by/fri");
assertResultMessage(EditCommand.MESSAGE_DUPLICATE_TASK);
}
//@@author A0143076J-reused
/**
* Checks whether the edited task has the correct updated details.
*
* @param filteredTaskListIndex index of task to edit in filtered list
* @param taskManagerIndex index of task to edit in the task manager.
* Must refer to the same task as {@code filteredTaskListIndex}
* @param detailsToEdit details to edit the task with as input to the edit command
* @param editedTask the expected task after editing the task's details
*/
private void assertEditSuccess(int filteredTaskListIndex, int taskManagerIndex,
String detailsToEdit, TestTask editedTask) {
commandBox.runCommand("edit " + filteredTaskListIndex + " " + detailsToEdit);
// confirm the new card contains the right data
TaskCardHandle editedCard = taskListPanel.navigateToTask(editedTask.getDescription().fullDescription);
assertMatching(editedTask, editedCard);
// confirm the list now contains all previous tasks plus the task with updated details
expectedTasksList[taskManagerIndex - 1] = editedTask;
assertTrue(taskListPanel.isListMatching(expectedTasksList));
assertResultMessage(String.format(EditCommand.MESSAGE_EDIT_TASK_SUCCESS, editedTask));
}
}
|
//@@author A0142073R
package guitests;
import org.junit.Test;
import seedu.taskell.commons.core.Messages;
import seedu.taskell.commons.exceptions.IllegalValueException;
import seedu.taskell.model.task.Description;
import seedu.taskell.model.task.TaskDate;
import seedu.taskell.model.task.TaskPriority;
import seedu.taskell.model.task.TaskTime;
import seedu.taskell.testutil.TestTask;
import seedu.taskell.testutil.TestUtil;
import static org.junit.Assert.assertTrue;
import static seedu.taskell.logic.commands.EditCommand.MESSAGE_EDIT_TASK_SUCCESS;
import static seedu.taskell.logic.commands.EditCommand.MESSAGE_USAGE;
import static seedu.taskell.logic.commands.EditCommand.COMMAND_WORD;
public class EditCommandTest extends TaskManagerGuiTest {
@Test
public void edit() throws IllegalValueException {
TestTask[] currentList = td.getTypicalTasks();
int targetIndex = 1;
// edit the description of first task in the list
TestTask oldTask = currentList[targetIndex - 1];
TestTask newTask = new TestTask(new Description("make tea"), oldTask.getTaskType(), oldTask.getTaskPriority(),
oldTask.getStartTime(), oldTask.getEndTime(), oldTask.getStartDate(), oldTask.getEndDate(),
oldTask.getRecurringType(), oldTask.getTaskStatus(), oldTask.getTags());
commandBox.runCommand("edit " + targetIndex + " desc: make tea");
currentList[0] = newTask;
asserteditSuccess(targetIndex, currentList, oldTask, newTask);
// edit the description of last task in the list
targetIndex = currentList.length;
oldTask = currentList[targetIndex - 1];
newTask = new TestTask(new Description("finish software demo"), oldTask.getTaskType(),
oldTask.getTaskPriority(), oldTask.getStartTime(), oldTask.getEndTime(), oldTask.getStartDate(),
oldTask.getEndDate(), oldTask.getRecurringType(),oldTask.getTaskStatus(), oldTask.getTags());
commandBox.runCommand(COMMAND_WORD + " "+ targetIndex + " desc: finish software demo");
asserteditSuccess(targetIndex, currentList, oldTask, newTask);
// invalid index
commandBox.runCommand(COMMAND_WORD + " " + currentList.length + 1 + " desc: go shopping");
assertResultMessage(Messages.MESSAGE_INVALID_TASK_DISPLAYED_INDEX);
// invalid command
commandBox.runCommand(COMMAND_WORD);
assertResultMessage("Invalid command format! \n" + MESSAGE_USAGE);
commandBox.runCommand(COMMAND_WORD +" "+ targetIndex + " desc: finish homework " +" st: 8am "+ " desc: submit homework");
assertResultMessage("Invalid command format! \n" + MESSAGE_USAGE);
// edit the priority of first task in the list
targetIndex = 1;
oldTask = currentList[targetIndex - 1];
newTask = new TestTask(oldTask.getDescription(), oldTask.getTaskType(),
new TaskPriority(TaskPriority.DEFAULT_PRIORITY), oldTask.getStartTime(), oldTask.getEndTime(),
oldTask.getStartDate(), oldTask.getEndDate(), oldTask.getRecurringType(), oldTask.getTaskStatus(), oldTask.getTags());
commandBox.runCommand("edit " + targetIndex + " p: " + TaskPriority.DEFAULT_PRIORITY);
currentList[0] = newTask;
asserteditSuccess(targetIndex, currentList, oldTask, newTask);
// edit the priority of last task in the list
targetIndex = currentList.length;
oldTask = currentList[targetIndex - 1];
newTask = new TestTask(oldTask.getDescription(), oldTask.getTaskType(),
new TaskPriority(TaskPriority.HIGH_PRIORITY), oldTask.getStartTime(), oldTask.getEndTime(),
oldTask.getStartDate(), oldTask.getEndDate(), oldTask.getRecurringType(), oldTask.getTaskStatus(), oldTask.getTags());
commandBox.runCommand("edit " + targetIndex + " p: " + TaskPriority.HIGH_PRIORITY);
asserteditSuccess(targetIndex, currentList, oldTask, newTask);
// invalid index
commandBox.runCommand(COMMAND_WORD + " " + currentList.length + 1 + " p: " + TaskPriority.DEFAULT_PRIORITY);
assertResultMessage(Messages.MESSAGE_INVALID_TASK_DISPLAYED_INDEX);
// invalid command
commandBox.runCommand(COMMAND_WORD +" "+ targetIndex + " p:");
assertResultMessage("Invalid command format! \n" + MESSAGE_USAGE);
commandBox.runCommand(COMMAND_WORD +" "+ targetIndex + " desc: finish homework " +" p:");
assertResultMessage("Invalid command format! \n" + MESSAGE_USAGE);
// edit the start time of first task in the list
targetIndex = 1;
oldTask = currentList[targetIndex - 1];
newTask = new TestTask(oldTask.getDescription(), oldTask.getTaskType(), oldTask.getTaskPriority(),
new TaskTime(TaskTime.MIDNIGHT), oldTask.getEndTime(), oldTask.getStartDate(), oldTask.getEndDate(),
oldTask.getRecurringType(), oldTask.getTaskStatus(), oldTask.getTags());
commandBox.runCommand("edit " + targetIndex + " st: " + TaskTime.MIDNIGHT);
currentList[0] = newTask;
asserteditSuccess(targetIndex, currentList, oldTask, newTask);
// edit the start time of last task in the list
targetIndex = currentList.length;
oldTask = currentList[targetIndex - 1];
newTask = new TestTask(oldTask.getDescription(), oldTask.getTaskType(), oldTask.getTaskPriority(),
new TaskTime(TaskTime.DEFAULT_START_TIME), oldTask.getEndTime(), oldTask.getStartDate(),
oldTask.getEndDate(), oldTask.getRecurringType(), oldTask.getTaskStatus(), oldTask.getTags());
commandBox.runCommand("edit " + targetIndex + " st: " + TaskTime.DEFAULT_START_TIME);
asserteditSuccess(targetIndex, currentList, oldTask, newTask);
// invalid index
commandBox.runCommand(COMMAND_WORD + " " + currentList.length + 1 + " st: "+TaskTime.DEFAULT_START_TIME);
assertResultMessage(Messages.MESSAGE_INVALID_TASK_DISPLAYED_INDEX);
// edit the end time of first task in the list
targetIndex = 1;
oldTask = currentList[targetIndex - 1];
newTask = new TestTask(oldTask.getDescription(), oldTask.getTaskType(), oldTask.getTaskPriority(),
oldTask.getStartTime(), new TaskTime(TaskTime.DEFAULT_END_TIME), oldTask.getStartDate(),
oldTask.getEndDate(), oldTask.getRecurringType(), oldTask.getTaskStatus(), oldTask.getTags());
commandBox.runCommand("edit " + targetIndex + " et: " + TaskTime.DEFAULT_END_TIME);
currentList[0] = newTask;
asserteditSuccess(targetIndex, currentList, oldTask, newTask);
// edit the end time of last task in the list
targetIndex = currentList.length;
oldTask = currentList[targetIndex - 1];
newTask = new TestTask(oldTask.getDescription(), oldTask.getTaskType(), oldTask.getTaskPriority(),
oldTask.getStartTime(), new TaskTime(TaskTime.DEFAULT_END_TIME), oldTask.getStartDate(),
oldTask.getEndDate(), oldTask.getRecurringType(), oldTask.getTaskStatus(), oldTask.getTags());
commandBox.runCommand("edit " + targetIndex + " et: " + TaskTime.DEFAULT_END_TIME);
asserteditSuccess(targetIndex, currentList, oldTask, newTask);
// invalid index
commandBox.runCommand(COMMAND_WORD + " " + currentList.length + 1 + " et: 3pm");
assertResultMessage(Messages.MESSAGE_INVALID_TASK_DISPLAYED_INDEX);
}
@Test
public void editFew() throws IllegalValueException {
TestTask[] currentList = td.getTypicalTasks();
int targetIndex = 1;
// edit the description, start time and priority of first task in the
// list
TestTask oldTask = currentList[targetIndex - 1];
TestTask newTask = new TestTask(new Description("send emails"), oldTask.getTaskType(),
new TaskPriority(TaskPriority.DEFAULT_PRIORITY), new TaskTime("12am"), oldTask.getEndTime(),
oldTask.getStartDate(), oldTask.getEndDate(), oldTask.getRecurringType(), oldTask.getTaskStatus(), oldTask.getTags());
commandBox.runCommand("edit " + targetIndex + " desc: send emails st: 12am p: 0");
currentList[0] = newTask;
asserteditSuccess(targetIndex, currentList, oldTask, newTask);
// edit start time and end time of first task in the
// list
oldTask = currentList[targetIndex - 1];
newTask = new TestTask(oldTask.getDescription(), oldTask.getTaskType(), oldTask.getTaskPriority(),
new TaskTime(TaskTime.DEFAULT_START_TIME), new TaskTime(TaskTime.DEFAULT_END_TIME),
oldTask.getStartDate(), oldTask.getEndDate(), oldTask.getRecurringType(), oldTask.getTaskStatus(), oldTask.getTags());
commandBox.runCommand(
"edit " + targetIndex + " st: " + TaskTime.DEFAULT_START_TIME + " et: " + TaskTime.DEFAULT_END_TIME);
currentList[0] = newTask;
asserteditSuccess(targetIndex, currentList, oldTask, newTask);
}
private void asserteditSuccess(int targetIndexOneIndexed, final TestTask[] currentList, TestTask oldTask,
TestTask newTask) throws IllegalValueException {
TestTask[] current = TestUtil.replaceTaskFromList(currentList, newTask, targetIndexOneIndexed - 1);
// confirm the list now contains all previous tasks except the edited
// task
assertTrue(taskListPanel.isListMatching(current));
// confirm the result message is correct
assertResultMessage(String.format(MESSAGE_EDIT_TASK_SUCCESS, oldTask, newTask));
}
}
// @@author
|
package beaform.entities;
import java.util.List;
import javax.persistence.EntityManager;
import javax.transaction.HeuristicMixedException;
import javax.transaction.HeuristicRollbackException;
import javax.transaction.NotSupportedException;
import javax.transaction.RollbackException;
import javax.transaction.SystemException;
import javax.transaction.TransactionManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import beaform.GraphDbHandlerForJTA;
import beaform.Ingredient;
/**
* This class handles all DB access for formulas.
*
* @author steven
*
*/
public class FormulaDAO {
/**
* The logger.
*/
private static final Logger LOG = LoggerFactory.getLogger(FormulaDAO.class);
/**
* Get the ingredients of a formula.
* @param formula
* @return a list of {@link Ingredient} objects
* @throws NotSupportedException If the calling thread is already
* associated with a transaction,
* and nested transactions are not supported.
* @throws SystemException If the transaction service fails in an unexpected way.
*/
public List<Ingredient> getIngredients(Formula formula) throws NotSupportedException, SystemException {
final TransactionManager transactionMgr = GraphDbHandlerForJTA.getInstance().getTransactionManager();
transactionMgr.begin();
final EntityManager ementityManager = GraphDbHandlerForJTA.getInstance().getEntityManagerFactory().createEntityManager();
formula = (Formula) ementityManager.createNativeQuery("match (n:Formula { name:'" + formula.getName() + "' }) return n", Formula.class).getSingleResult();
final List<Ingredient> retList = formula.getIngredients();
ementityManager.flush();
ementityManager.close();
try {
transactionMgr.commit();
}
catch (SecurityException | IllegalStateException | RollbackException | HeuristicMixedException
| HeuristicRollbackException | SystemException e1)
{
LOG.error(e1.getMessage(), e1);
}
return retList;
}
/**
* Update an existing formula.
*
* @param oldName the old name of the formula
* @param name the name of the formula
* @param description the description for the formula
* @param totalAmount the total amount for the formula
* @param ingredients a list of ingredients
* @param tags a list of tags
*/
public void updateExisting(final String name, final String description, final String totalAmount, final List<Ingredient> ingredients, final List<FormulaTag> tags) {
final TransactionManager transactionMgr = GraphDbHandlerForJTA.getInstance().getTransactionManager();
try {
transactionMgr.begin();
}
catch (NotSupportedException | SystemException e1) {
LOG.error(e1.getMessage(), e1);
return;
}
final EntityManager ementityManager = GraphDbHandlerForJTA.getInstance().getEntityManagerFactory().createEntityManager();
final String query = "match (n:Formula { name:'" + name + "' }) return n";
final Formula formula = (Formula) ementityManager.createNativeQuery(query, Formula.class).getSingleResult();
formula.setDescription(description);
formula.setTotalAmount(totalAmount);
formula.clearTags();
addTags(tags, ementityManager, formula);
formula.clearIngredients();
for (final Ingredient ingredient : ingredients) {
// We should only be holding existing Formulas at this point
formula.addIngredient(ingredient.getFormula(), ingredient.getAmount());
}
ementityManager.persist(formula);
ementityManager.flush();
ementityManager.close();
try {
transactionMgr.commit();
}
catch (SecurityException | IllegalStateException | RollbackException | HeuristicMixedException
| HeuristicRollbackException | SystemException e1)
{
LOG.error(e1.getMessage(), e1);
}
}
public void addFormula(final String name, final String description, final String totalAmount, final List<Ingredient> ingredients, final List<FormulaTag> tags) {
final TransactionManager transactionMgr = GraphDbHandlerForJTA.getInstance().getTransactionManager();
try {
transactionMgr.begin();
}
catch (NotSupportedException | SystemException e1) {
LOG.error(e1.getMessage(), e1);
return;
}
final EntityManager entityManager = GraphDbHandlerForJTA.getInstance().getEntityManagerFactory().createEntityManager();
final Formula formula = new Formula();
formula.setName(name);
formula.setDescription(description);
formula.setTotalAmount(totalAmount);
addTags(tags, entityManager, formula);
for (final Ingredient ingredient : ingredients) {
// We should only be holding existing Formulas at this point
formula.addIngredient(ingredient.getFormula(), ingredient.getAmount());
}
entityManager.persist(formula);
entityManager.flush();
entityManager.close();
try {
transactionMgr.commit();
}
catch (SecurityException | IllegalStateException | RollbackException | HeuristicMixedException
| HeuristicRollbackException | SystemException e1)
{
LOG.error(e1.getMessage(), e1);
}
}
/**
* This method adds tags to a formula.
* It assumes a running transaction.
*
* @param tags A list of tags
* @param entityManager an open entity manager
* @param formula the formula to add the tags to
*/
private void addTags(final List<FormulaTag> tags, final EntityManager entityManager, final Formula formula) {
final FormulaTagDAO formulaTagDAO = new FormulaTagDAO();
for (FormulaTag tag : tags) {
// See if the tag exist in the DB, if so, use it.
FormulaTag pTag = null;
try {
pTag = formulaTagDAO.findByObject(tag);
}
catch (NotSupportedException | SystemException e1) {
LOG.error("Failed to find the tag", e1);
}
if (pTag == null) {
entityManager.persist(tag);
}
else {
tag = pTag;
}
formula.addTag(tag);
}
}
/**
* This method finds a formula in the DB based on a name.
* It assumes a transaction is already in progress.
*
* @param formula the name of the formula to look for
* @return the found {@link Formula} or null if none was found.
*/
public Formula findFormulaByName(String name) {
Formula result;
final EntityManager em = GraphDbHandlerForJTA.getInstance().getEntityManagerFactory().createEntityManager();
final String query = "match (n:Formula { name:'" + name + "' }) return n";
result = (Formula) em.createNativeQuery(query, Formula.class).getSingleResult();
if (LOG.isDebugEnabled()) {
LOG.debug("Found: " + result);
}
em.flush();
em.close();
return result;
}
}
|
package br.com.ppm.test.helper;
import org.mockito.Mockito;
import org.mockito.stubbing.Answer;
import org.mockito.stubbing.OngoingStubbing;
/**
* Just a Test Step.
*
* @param <T> the generic type
* @author pedrotoliveira
*/
public final class Step<T> implements WeExpect, StubbingWrapper<T> {
/**
* The stub.
*/
private final OngoingStubbing<T> stub;
/**
* The values.
*/
private T[] values;
/**
* Instantiates a new step.
*
* @param methodCall the method call
*/
public Step(T methodCall) {
this.stub = Mockito.when(methodCall);
}
/**
* Instantiates a new step.
*
* @param ongoingStubbing the ongoing stubbing
*/
public Step(final OngoingStubbing<T> ongoingStubbing) {
this.stub = ongoingStubbing;
}
/**
* Execute.
*/
public void execute() {
//Actually Do Nothing...
}
public void execution(Object... mocks) throws Exception {
execute();
}
@Override
public OngoingStubbing<T> thenReturn(final T value) {
return stub.thenReturn(value);
}
@Override
@SuppressWarnings("unchecked")
public OngoingStubbing<T> thenReturn(final T value, final T... values) {
return stub.thenReturn(value, this.values);
}
@Override
public OngoingStubbing<T> thenThrow(final Throwable... throwables) {
return stub.thenThrow(throwables);
}
@Override
@SuppressWarnings("unchecked")
public OngoingStubbing<T> thenThrow(final Class<? extends Throwable>... throwableClasses) {
return stub.thenThrow(throwableClasses);
}
@Override
public OngoingStubbing<T> thenCallRealMethod() {
return thenCallRealMethod();
}
@Override
public OngoingStubbing<T> thenAnswer(Answer<?> answer) {
return stub.thenAnswer(answer);
}
@Override
public OngoingStubbing<T> then(Answer<?> answer) {
return (OngoingStubbing<T>) stub.then(answer);
}
@Override
public <M> M getMock() {
return stub.getMock();
}
@Override
public <D> GivenDataAndStubbing<D, T> then() {
throw new UnsupportedOperationException("Not supported yet.");
}
}
|
package test.persistence;
import static org.junit.Assert.assertEquals;
import java.io.IOException;
import net.f4fs.fspeer.FSPeer;
import net.f4fs.persistence.DHTOperations;
import net.tomp2p.dht.PeerDHT;
import net.tomp2p.peers.Number160;
import net.tomp2p.storage.Data;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
public class DHTOperationsTest {
private static String TEST_IP = "";
private static int TEST_PORT = 4000;
private static Number160 TEST_KEY = null;
private static Data TEST_DATA = null;
private static FSPeer fsPeer = null;
private static PeerDHT peerDht = null;
private static DHTOperations dhtOperations = null;
@BeforeClass
public static void initTest()
throws Exception {
dhtOperations = new DHTOperations();
fsPeer = new FSPeer();
TEST_IP = fsPeer.findLocalIp();
fsPeer.startAsBootstrapPeer(TEST_IP, TEST_PORT);
peerDht = fsPeer.getPeerDHT();
TEST_KEY = Number160.createHash(2);
TEST_DATA = new Data("test data");
}
@AfterClass
public static void tearDown() {
fsPeer.shutdown();
}
@Test
public void getData()
throws ClassNotFoundException, IOException, InterruptedException {
dhtOperations.putData(peerDht, TEST_KEY, TEST_DATA);
Data retrievedData = dhtOperations.getData(peerDht, TEST_KEY);
assertEquals("Stored data was not equal", TEST_DATA, retrievedData);
}
@Test
public void getDataOfVersion()
throws InterruptedException {
// this should ignore the key since dhtOperations does not provide versions
dhtOperations.putData(peerDht, TEST_KEY, TEST_DATA);
Data retrievedData = dhtOperations.getDataOfVersion(peerDht, TEST_KEY, TEST_KEY);
assertEquals("Versioned data did not ignore versions", TEST_DATA, retrievedData);
}
@Test
public void putData()
throws InterruptedException {
dhtOperations.putData(peerDht, TEST_KEY, TEST_DATA);
dhtOperations.removeData(peerDht, TEST_KEY);
Data retrievedData = dhtOperations.getData(peerDht, TEST_KEY);
assertEquals("Did not remove data on DHT", null, retrievedData);
}
@Test
public void removeData()
throws InterruptedException {
dhtOperations.putData(peerDht, TEST_KEY, TEST_DATA);
Data retrievedData = dhtOperations.getData(peerDht, TEST_KEY);
assertEquals("Did not put data to DHT", TEST_DATA, retrievedData);
dhtOperations.removeData(peerDht, TEST_KEY);
retrievedData = dhtOperations.getData(peerDht, TEST_KEY);
assertEquals("Did not remove data from DHT", null, retrievedData);
}
@Test
public void removeDataOfVersion()
throws InterruptedException {
dhtOperations.putData(peerDht, TEST_KEY, TEST_DATA);
Data retrievedData = dhtOperations.getDataOfVersion(peerDht, TEST_KEY, TEST_KEY);
assertEquals("Did not put data to DHT", TEST_DATA, retrievedData);
dhtOperations.removeDataOfVersion(peerDht, TEST_KEY, TEST_KEY);
retrievedData = dhtOperations.getDataOfVersion(peerDht, TEST_KEY, TEST_KEY);
assertEquals("Did not remove data from DHT", null, retrievedData);
}
}
|
package com.bio4j.model;
import com.bio4j.angulillos.*;
import com.bio4j.angulillos.Arity.*;
public final class ENZYMEGraph<V,E> extends TypedGraph<ENZYMEGraph<V,E>,V,E> {
public ENZYMEGraph(UntypedGraph<V,E> graph) { super(graph); }
@Override
public final ENZYMEGraph<V,E> self() { return this; }
/*
## Enzymes
*/
public final class Enzyme extends Vertex<Enzyme> {
private Enzyme(V raw) { super(raw, enzyme); }
@Override public final Enzyme self() { return this; }
}
public final EnzymeType enzyme = new EnzymeType();
public final class EnzymeType extends VertexType<Enzyme> {
public final Enzyme fromRaw(V raw) { return new Enzyme(raw); }
public final ID id = new ID();
public final class ID extends Property<String> implements FromAtMostOne, ToOne {
private ID() { super(String.class); }
public final Index index = new Index();
public final class Index extends UniqueIndex<ID,String> {
private Index() { super(id); }
}
}
public final Cofactors cofactors = new Cofactors();
public final class Cofactors extends Property<String[]> implements FromAny {
private Cofactors() { super(String[].class); }
}
public final Comment comment = new Comment();
public final class Comment extends Property<String> implements FromAny {
private Comment() { super(String.class); }
}
public final Name name = new Name();
public final class Name extends Property<String> implements FromAny, ToOne {
private Name() { super(String.class); }
}
public final AlternateNames alternateNames = new AlternateNames();
public final class AlternateNames extends Property<String[]> implements FromAny {
private AlternateNames() { super(String[].class); }
}
public final CatalyticActivity catalyticActivity = new CatalyticActivity();
public final class CatalyticActivity extends Property<String[]> implements FromAny {
private CatalyticActivity() { super(String[].class); }
}
}
/*
## Enzyme classes, sub-classes, subsub-classes
*/
public final class EnzymeClass extends Vertex<EnzymeClass> {
private EnzymeClass(V raw) { super(raw, enzymeClass); }
@Override public final EnzymeClass self() { return this; }
}
public final EnzymeClassType enzymeClass = new EnzymeClassType();
public final class EnzymeClassType extends VertexType<EnzymeClass> {
public final EnzymeClass fromRaw(V raw) { return new EnzymeClass(raw); }
}
public final class EnzymeSubClass extends Vertex<EnzymeSubClass> {
private EnzymeSubClass(V raw) { super(raw, enzymeSubClass); }
@Override public final EnzymeSubClass self() { return this; }
}
public final EnzymeSubClassType enzymeSubClass = new EnzymeSubClassType();
public final class EnzymeSubClassType extends VertexType<EnzymeSubClass> {
public final EnzymeSubClass fromRaw(V raw) { return new EnzymeSubClass(raw); }
}
public final class EnzymeSubSubClass extends Vertex<EnzymeSubSubClass> {
private EnzymeSubSubClass(V raw) { super(raw, enzymeSubSubClass); }
@Override public final EnzymeSubSubClass self() { return this; }
}
public final EnzymeSubSubClassType enzymeSubSubClass = new EnzymeSubSubClassType();
public final class EnzymeSubSubClassType extends VertexType<EnzymeSubSubClass> {
public final EnzymeSubSubClass fromRaw(V raw) { return new EnzymeSubSubClass(raw); }
}
public final class SubClass extends Edge<EnzymeClass, SubClass, EnzymeSubClass> {
private SubClass(E edge) { super(edge, subClass); }
@Override
public final SubClass self() { return this; }
}
public final SubClassType subClass = new SubClassType();
public final class SubClassType extends EdgeType<EnzymeClass, SubClass, EnzymeSubClass> implements FromOne, ToAtLeastOne {
private SubClassType() { super(enzymeClass, enzymeSubClass); }
@Override
public final SubClass fromRaw(E edge) { return new SubClass(edge); }
}
public final class SubSubClass extends Edge<EnzymeSubClass, SubSubClass, EnzymeSubSubClass> {
private SubSubClass(E edge) { super(edge, subSubClass); }
@Override
public final SubSubClass self() { return this; }
}
public final SubSubClassType subSubClass = new SubSubClassType();
public final class SubSubClassType extends EdgeType<EnzymeSubClass, SubSubClass, EnzymeSubSubClass> implements FromOne, ToAtLeastOne {
private SubSubClassType() { super(enzymeSubClass, enzymeSubSubClass); }
@Override
public final SubSubClass fromRaw(E edge) { return new SubSubClass(edge); }
}
public final class Enzymes extends Edge<EnzymeSubSubClass, Enzymes, Enzyme> {
private Enzymes(E edge) { super(edge, enzymes); }
@Override
public final Enzymes self() { return this; }
}
public final EnzymesType enzymes = new EnzymesType();
public final class EnzymesType extends EdgeType<EnzymeSubSubClass, Enzymes, Enzyme> implements FromOne, ToAtLeastOne {
private EnzymesType() { super(enzymeSubSubClass, enzyme); }
@Override
public final Enzymes fromRaw(E edge) { return new Enzymes(edge); }
}
}
|
package com.box.sdk;
/**
* Thrown to indicate that an error occurred while communicating with the Box API.
*/
public class BoxAPIException extends RuntimeException {
private static final long serialVersionUID = 1L;
private final int responseCode;
private final String response;
/**
* Constructs a BoxAPIException with a specified message.
* @param message a message explaining why the exception occurred.
*/
public BoxAPIException(String message) {
super(message);
this.responseCode = 0;
this.response = null;
}
/**
* Constructs a BoxAPIException with details about the server's response.
* @param message a message explaining why the exception occurred.
* @param responseCode the response code returned by the Box server.
* @param response the response body returned by the Box server.
*/
public BoxAPIException(String message, int responseCode, String response) {
super(message);
this.responseCode = responseCode;
this.response = response;
}
/**
* Constructs a BoxAPIException that wraps another underlying exception.
* @param message a message explaining why the exception occurred.
* @param cause an underlying exception.
*/
public BoxAPIException(String message, Throwable cause) {
super(message, cause);
this.responseCode = 0;
this.response = null;
}
/**
* Constructs a BoxAPIException that wraps another underlying exception with details about the server's response.
* @param message a message explaining why the exception occurred.
* @param responseCode the response code returned by the Box server.
* @param response the response body returned by the Box server.
* @param cause an underlying exception.
*/
public BoxAPIException(String message, int responseCode, String response, Throwable cause) {
super(message, cause);
this.responseCode = responseCode;
this.response = response;
}
/**
* Gets the response code returned by the server when this exception was thrown.
* @return the response code returned by the server.
*/
public int getResponseCode() {
return this.responseCode;
}
/**
* Gets the body of the response returned by the server when this exception was thrown.
* @return the body of the response returned by the server.
*/
public String getResponse() {
return this.response;
}
}
|
package com.drugbox.Util;
import java.util.ArrayList;
import java.util.List;
public class UploadUtil {
public static boolean isImageByName(String fileName){
String ext = fileName.substring(fileName.lastIndexOf(".")+1,fileName.length());
return isImage(ext);
}
public static boolean isImage(String type){
List<String> fileTypes = new ArrayList<String>();
fileTypes.add("jpg");
fileTypes.add("jpeg");
fileTypes.add("bmp");
fileTypes.add("gif");
fileTypes.add("png");
return fileTypes.contains(type.toLowerCase());
}
}
|
package com.github.mizool;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import lombok.NonNull;
import com.github.mizool.exception.DataInconsistencyException;
import com.github.mizool.exception.ObjectNotFoundException;
import com.google.common.base.Optional;
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class Optionals
{
/**
* Used when a user directly requests or references an object, resulting in an ObjectNotFoundException if it does
* not exist.
*/
public static final <T> T unwrapUserRequestedObject(@NonNull Optional<T> wrapped, @NonNull Class<T> classOfT)
{
if (!wrapped.isPresent())
{
throw new ObjectNotFoundException(classOfT.getSimpleName() + " not found");
}
return wrapped.get();
}
/**
* Used when an object can be reasonably expected to exist, resulting in a DataInconsistencyException if it does not
* exist.
*/
public static final <T> T unwrapRequiredObject(@NonNull Optional<T> wrapped, @NonNull Class<T> classOfT)
{
if (!wrapped.isPresent())
{
throw new DataInconsistencyException(classOfT.getSimpleName() + " not found");
}
return wrapped.get();
}
}
|
package com.loomcom.symon;
import com.loomcom.symon.devices.Memory;
import com.loomcom.symon.exceptions.FifoUnderrunException;
import com.loomcom.symon.exceptions.MemoryAccessException;
import com.loomcom.symon.exceptions.MemoryRangeException;
import com.loomcom.symon.exceptions.SymonException;
import com.loomcom.symon.machines.Machine;
import com.loomcom.symon.ui.*;
import com.loomcom.symon.ui.Console;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Symon Simulator Interface and Control.
* <p/>
* This class provides a control and I/O system for the simulated 6502 system.
* It includes the simulated CPU itself, as well as 32KB of RAM, 16KB of ROM,
* and a simulated ACIA for serial I/O. The ACIA is attached to a dumb terminal
* with a basic 80x25 character display.
*/
public class Simulator {
// UI constants
private static final int DEFAULT_FONT_SIZE = 12;
private static final Font DEFAULT_FONT = new Font(Font.MONOSPACED, Font.PLAIN, DEFAULT_FONT_SIZE);
private static final int CONSOLE_BORDER_WIDTH = 10;
// Since it is very expensive to update the UI with Swing's Event Dispatch Thread, we can't afford
// to refresh the status view on every simulated clock cycle. Instead, we will only refresh the status view
// after this number of steps when running normally.
// Since we're simulating a 1MHz 6502 here, we have a 1 us delay between steps. Setting this to 20000
// should give us a status update about every 100 ms.
// TODO: Work around the event dispatch thread with custom painting code instead of relying on Swing.
private static final int MAX_STEPS_BETWEEN_UPDATES = 20000;
private final static Logger logger = Logger.getLogger(Simulator.class.getName());
// The simulated machine
private Machine machine;
// Number of CPU steps between CRT repaints.
// TODO: Dynamically refresh the value at runtime based on performance figures to reach ~ 30fps.
private long stepsBetweenCrtcRefreshes = 2500;
// A counter to keep track of the number of UI updates that have been
// requested
private int stepsSinceLastUpdate = 0;
private int stepsSinceLastCrtcRefresh = 0;
// The number of steps to run per click of the "Step" button
private int stepsPerClick = 1;
/**
* The Main Window is the primary control point for the simulator.
* It is in charge of the menu, and sub-windows. It also shows the
* CPU status at all times.
*/
private JFrame mainWindow;
/**
* The Trace Window shows the most recent 50,000 CPU states.
*/
private TraceLog traceLog;
/**
* The Memory Window shows the contents of one page of memory.
*/
private MemoryWindow memoryWindow;
private VideoWindow videoWindow;
private SimulatorMenu menuBar;
private RunLoop runLoop;
private Console console;
private StatusPanel statusPane;
private JButton runStopButton;
private JButton stepButton;
private JButton softResetButton;
private JButton hardResetButton;
private JComboBox<String> stepCountBox;
private JFileChooser fileChooser;
private PreferencesDialog preferences;
private final Object commandMonitorObject = new Object();
private MAIN_CMD command = MAIN_CMD.NONE;
public static enum MAIN_CMD {
NONE,
SELECTMACHINE
}
/**
* The list of step counts that will appear in the "Step" drop-down.
*/
private static final String[] STEPS = {"1", "5", "10", "20", "50", "100"};
public Simulator(Class machineClass) throws Exception {
this.machine = (Machine) machineClass.getConstructors()[0].newInstance();
}
/**
* Display the main simulator UI.
*/
public void createAndShowUi() throws IOException {
mainWindow = new JFrame();
mainWindow.setTitle("6502 Simulator - " + machine.getName());
mainWindow.setResizable(false);
mainWindow.getContentPane().setLayout(new BorderLayout());
// UI components used for I/O.
this.console = new com.loomcom.symon.ui.Console(80, 25, DEFAULT_FONT);
this.statusPane = new StatusPanel(machine);
console.setBorderWidth(CONSOLE_BORDER_WIDTH);
// File Chooser
fileChooser = new JFileChooser(System.getProperty("user.dir"));
preferences = new PreferencesDialog(mainWindow, true);
// Panel for Console and Buttons
JPanel consoleContainer = new JPanel();
JPanel buttonContainer = new JPanel();
consoleContainer.setLayout(new BorderLayout());
consoleContainer.setBorder(new EmptyBorder(10, 10, 10, 0));
buttonContainer.setLayout(new FlowLayout());
runStopButton = new JButton("Run");
stepButton = new JButton("Step");
softResetButton = new JButton("Soft Reset");
hardResetButton = new JButton("Hard Reset");
stepCountBox = new JComboBox<String>(STEPS);
stepCountBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
try {
JComboBox cb = (JComboBox) actionEvent.getSource();
stepsPerClick = Integer.parseInt((String) cb.getSelectedItem());
} catch (NumberFormatException ex) {
stepsPerClick = 1;
stepCountBox.setSelectedIndex(0);
}
}
});
buttonContainer.add(runStopButton);
buttonContainer.add(stepButton);
buttonContainer.add(stepCountBox);
buttonContainer.add(softResetButton);
buttonContainer.add(hardResetButton);
// Left side - console
consoleContainer.add(console, BorderLayout.CENTER);
mainWindow.getContentPane().add(consoleContainer, BorderLayout.LINE_START);
// Right side - status pane
mainWindow.getContentPane().add(statusPane, BorderLayout.LINE_END);
// Bottom - buttons.
mainWindow.getContentPane().add(buttonContainer, BorderLayout.PAGE_END);
runStopButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
if (runLoop != null && runLoop.isRunning()) {
handleStop();
} else {
handleStart();
}
}
});
stepButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
handleStep(stepsPerClick);
}
});
softResetButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
// If this was a CTRL-click, do a hard reset.
handleReset(false);
}
});
hardResetButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
// If this was a CTRL-click, do a hard reset.
handleReset(true);
}
});
// Prepare the log window
traceLog = new TraceLog();
// Prepare the memory window
memoryWindow = new MemoryWindow(machine.getBus());
// Composite Video and 6545 CRTC
if(machine.getCrtc() != null) {
videoWindow = new VideoWindow(machine.getCrtc(), 2, 2);
}
mainWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// The Menu. This comes last, because it relies on other components having
// already been initialized.
menuBar = new SimulatorMenu();
mainWindow.setJMenuBar(menuBar);
mainWindow.pack();
mainWindow.setVisible(true);
console.requestFocus();
handleReset(false);
}
public MAIN_CMD waitForCommand() {
synchronized(commandMonitorObject) {
try {
commandMonitorObject.wait();
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
return command;
}
private void handleStart() {
// Shift focus to the console.
console.requestFocus();
// Spin up the new run loop
runLoop = new RunLoop();
runLoop.start();
traceLog.simulatorDidStart();
}
private void handleStop() {
runLoop.requestStop();
runLoop.interrupt();
runLoop = null;
}
/*
* Perform a reset.
*/
private void handleReset(boolean isColdReset) {
if (runLoop != null && runLoop.isRunning()) {
runLoop.requestStop();
runLoop.interrupt();
runLoop = null;
}
try {
logger.log(Level.INFO, "Reset requested. Resetting CPU.");
// Reset CPU
machine.getCpu().reset();
// Clear the console.
console.reset();
// Reset the trace log.
traceLog.reset();
// If we're doing a cold reset, clear the memory.
if (isColdReset) {
Memory mem = machine.getRam();
if (mem != null) {
mem.fill(0);
}
}
// Update status.
SwingUtilities.invokeLater(new Runnable() {
public void run() {
// Now update the state
statusPane.updateState();
memoryWindow.updateState();
}
});
} catch (MemoryAccessException ex) {
logger.log(Level.SEVERE, "Exception during simulator reset: " + ex.getMessage());
}
}
/**
* Step the requested number of times, and immediately refresh the UI.
*/
private void handleStep(int numSteps) {
try {
for (int i = 0; i < numSteps; i++) {
step();
}
SwingUtilities.invokeLater(new Runnable() {
public void run() {
if (traceLog.isVisible()) {
traceLog.refresh();
}
statusPane.updateState();
memoryWindow.updateState();
}
});
} catch (SymonException ex) {
logger.log(Level.SEVERE, "Exception during simulator step: " + ex.getMessage());
ex.printStackTrace();
}
}
/**
* Perform a single step of the simulated system.
*/
private void step() throws MemoryAccessException {
machine.getCpu().step();
traceLog.append(machine.getCpu().getCpuState());
// Read from the ACIA and immediately update the console if there's
// output ready.
if (machine.getAcia() != null && machine.getAcia().hasTxChar()) {
// This is thread-safe
console.print(Character.toString((char) machine.getAcia().txRead()));
console.repaint();
}
// If a key has been pressed, fill the ACIA.
try {
if (machine.getAcia() != null && console.hasInput()) {
machine.getAcia().rxWrite((int) console.readInputChar());
}
} catch (FifoUnderrunException ex) {
logger.severe("Console type-ahead buffer underrun!");
}
if (videoWindow != null && stepsSinceLastCrtcRefresh++ > stepsBetweenCrtcRefreshes) {
stepsSinceLastCrtcRefresh = 0;
}
// This is a very expensive update, and we're doing it without
// a delay, so we don't want to overwhelm the Swing event processing thread
// with requests. Limit the number of ui updates that can be performed.
if (stepsSinceLastUpdate++ > MAX_STEPS_BETWEEN_UPDATES) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
// Now update the state
statusPane.updateState();
memoryWindow.updateState();
}
});
stepsSinceLastUpdate = 0;
}
}
/**
* Load a program into memory at the simulatorDidStart address.
*/
private void loadProgram(byte[] program, int startAddress) throws MemoryAccessException {
int addr = startAddress, i;
for (i = 0; i < program.length; i++) {
machine.getBus().write(addr++, program[i] & 0xff);
}
logger.log(Level.INFO, "Loaded " + i + " bytes at address 0x" +
Integer.toString(startAddress, 16));
// After loading, be sure to reset and
// Reset (but don't clear memory, naturally)
machine.getCpu().reset();
// Reset the stack program counter
machine.getCpu().setProgramCounter(preferences.getProgramStartAddress());
// Immediately update the UI.
SwingUtilities.invokeLater(new Runnable() {
public void run() {
// Now update the state
statusPane.updateState();
memoryWindow.updateState();
}
});
}
/**
* The main run thread.
*/
class RunLoop extends Thread {
private boolean isRunning = false;
public boolean isRunning() {
return isRunning;
}
public void requestStop() {
isRunning = false;
}
public void run() {
logger.log(Level.INFO, "Starting main run loop.");
isRunning = true;
SwingUtilities.invokeLater(new Runnable() {
public void run() {
// Don't allow step while the simulator is running
stepButton.setEnabled(false);
stepCountBox.setEnabled(false);
menuBar.simulatorDidStart();
// Toggle the state of the run button
runStopButton.setText("Stop");
}
});
try {
do {
step();
} while (shouldContinue());
} catch (SymonException ex) {
logger.log(Level.SEVERE, "Exception in main simulator run thread. Exiting run.");
ex.printStackTrace();
}
SwingUtilities.invokeLater(new Runnable() {
public void run() {
statusPane.updateState();
memoryWindow.updateState();
runStopButton.setText("Run");
stepButton.setEnabled(true);
stepCountBox.setEnabled(true);
if (traceLog.isVisible()) {
traceLog.refresh();
}
menuBar.simulatorDidStop();
traceLog.simulatorDidStop();
}
});
isRunning = false;
}
/**
* Returns true if the run loop should proceed to the next step.
*
* @return True if the run loop should proceed to the next step.
*/
private boolean shouldContinue() {
return isRunning && !(preferences.getHaltOnBreak() && machine.getCpu().getInstruction() == 0x00);
}
}
class LoadProgramAction extends AbstractAction {
public LoadProgramAction() {
super("Load Program...", null);
putValue(SHORT_DESCRIPTION, "Load a program into memory");
putValue(MNEMONIC_KEY, KeyEvent.VK_L);
}
public void actionPerformed(ActionEvent actionEvent) {
try {
int retVal = fileChooser.showOpenDialog(mainWindow);
if (retVal == JFileChooser.APPROVE_OPTION) {
File f = fileChooser.getSelectedFile();
if (f.canRead()) {
long fileSize = f.length();
if (fileSize > machine.getMemorySize()) {
throw new IOException("File will not fit in " +
"available memory ($" +
Integer.toString(machine.getMemorySize(), 16) +
" bytes)");
} else {
byte[] program = new byte[(int) fileSize];
int i = 0;
FileInputStream fis = new FileInputStream(f);
BufferedInputStream bis = new BufferedInputStream(fis);
DataInputStream dis = new DataInputStream(bis);
while (dis.available() != 0) {
program[i++] = dis.readByte();
}
SwingUtilities.invokeLater(new Runnable() {
public void run() {
console.reset();
}
});
// Now load the program at the starting address.
loadProgram(program, preferences.getProgramStartAddress());
// TODO: "Don't Show Again" checkbox
JOptionPane.showMessageDialog(mainWindow,
"Loaded Successfully At " +
String.format("$%04X", preferences.getProgramStartAddress()),
"OK",
JOptionPane.PLAIN_MESSAGE);
}
}
}
} catch (IOException ex) {
logger.log(Level.SEVERE, "Unable to read program file: " + ex.getMessage());
JOptionPane.showMessageDialog(mainWindow, ex.getMessage(), "Failure", JOptionPane.ERROR_MESSAGE);
} catch (MemoryAccessException ex) {
logger.log(Level.SEVERE, "Memory access error loading program: " + ex.getMessage());
JOptionPane.showMessageDialog(mainWindow, ex.getMessage(), "Failure", JOptionPane.ERROR_MESSAGE);
}
}
}
class LoadRomAction extends AbstractAction {
public LoadRomAction() {
super("Load ROM...", null);
putValue(SHORT_DESCRIPTION, "Load a ROM image");
putValue(MNEMONIC_KEY, KeyEvent.VK_R);
}
public void actionPerformed(ActionEvent actionEvent) {
try {
int retVal = fileChooser.showOpenDialog(mainWindow);
if (retVal == JFileChooser.APPROVE_OPTION) {
File romFile = fileChooser.getSelectedFile();
if (romFile.canRead()) {
long fileSize = romFile.length();
if (fileSize != machine.getRomSize()) {
throw new IOException("ROM file must be exactly " + String.valueOf(machine.getRomSize()) + " bytes.");
} else {
// Load the new ROM image
Memory rom = Memory.makeROM(machine.getRomBase(), machine.getRomBase() + machine.getRomSize() - 1, romFile);
machine.setRom(rom);
// Now, reset
machine.getCpu().reset();
logger.log(Level.INFO, "ROM File `" + romFile.getName() + "' loaded at " +
String.format("0x%04X", machine.getRomBase()));
// TODO: "Don't Show Again" checkbox
JOptionPane.showMessageDialog(mainWindow,
"Loaded Successfully At " +
String.format("$%04X", machine.getRomBase()),
"OK",
JOptionPane.PLAIN_MESSAGE);
}
}
}
} catch (IOException ex) {
logger.log(Level.SEVERE, "Unable to read ROM file: " + ex.getMessage());
JOptionPane.showMessageDialog(mainWindow, ex.getMessage(), "Failure", JOptionPane.ERROR_MESSAGE);
} catch (MemoryRangeException ex) {
logger.log(Level.SEVERE, "Memory range error while loading ROM file: " + ex.getMessage());
JOptionPane.showMessageDialog(mainWindow, ex.getMessage(), "Failure", JOptionPane.ERROR_MESSAGE);
} catch (MemoryAccessException ex) {
logger.log(Level.SEVERE, "Memory access error while loading ROM file: " + ex.getMessage());
JOptionPane.showMessageDialog(mainWindow, ex.getMessage(), "Failure", JOptionPane.ERROR_MESSAGE);
}
}
}
class ShowPrefsAction extends AbstractAction {
public ShowPrefsAction() {
super("Preferences...", null);
putValue(SHORT_DESCRIPTION, "Show Preferences Dialog");
putValue(MNEMONIC_KEY, KeyEvent.VK_P);
}
public void actionPerformed(ActionEvent actionEvent) {
preferences.getDialog().setVisible(true);
}
}
class SelectMachineAction extends AbstractAction {
public SelectMachineAction() {
super("Switch emulated machine...", null);
putValue(SHORT_DESCRIPTION, "Select the type of the machine to be emulated");
putValue(MNEMONIC_KEY, KeyEvent.VK_M);
}
public void actionPerformed(ActionEvent actionEvent) {
if(runLoop != null) {
runLoop.requestStop();
}
memoryWindow.dispose();
traceLog.dispose();
if(videoWindow != null) {
videoWindow.dispose();
}
mainWindow.dispose();
command = MAIN_CMD.SELECTMACHINE;
synchronized(commandMonitorObject) {
commandMonitorObject.notifyAll();
}
}
}
class QuitAction extends AbstractAction {
public QuitAction() {
super("Quit", null);
putValue(SHORT_DESCRIPTION, "Exit the Simulator");
putValue(MNEMONIC_KEY, KeyEvent.VK_Q);
}
public void actionPerformed(ActionEvent actionEvent) {
if (runLoop != null && runLoop.isRunning()) {
runLoop.requestStop();
runLoop.interrupt();
}
System.exit(0);
}
}
class SetFontAction extends AbstractAction {
private int size;
public SetFontAction(int size) {
super(Integer.toString(size) + " pt", null);
this.size = size;
putValue(SHORT_DESCRIPTION, "Set font to " + Integer.toString(size) + "pt.");
}
public void actionPerformed(ActionEvent actionEvent) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
console.setFont(new Font("Monospaced", Font.PLAIN, size));
mainWindow.pack();
}
});
}
}
class ToggleTraceWindowAction extends AbstractAction {
public ToggleTraceWindowAction() {
super("Trace Log", null);
putValue(SHORT_DESCRIPTION, "Show or Hide the Trace Log Window");
}
public void actionPerformed(ActionEvent actionEvent) {
synchronized (traceLog) {
if (traceLog.isVisible()) {
traceLog.setVisible(false);
} else {
traceLog.refresh();
traceLog.setVisible(true);
}
}
}
}
class ToggleMemoryWindowAction extends AbstractAction {
public ToggleMemoryWindowAction() {
super("Memory Window", null);
putValue(SHORT_DESCRIPTION, "Show or Hide the Memory Window");
}
public void actionPerformed(ActionEvent actionEvent) {
synchronized (memoryWindow) {
if (memoryWindow.isVisible()) {
memoryWindow.setVisible(false);
} else {
memoryWindow.setVisible(true);
}
}
}
}
class ToggleVideoWindowAction extends AbstractAction {
public ToggleVideoWindowAction() {
super("Video Window", null);
putValue(SHORT_DESCRIPTION, "Show or Hide the Video Window");
}
public void actionPerformed(ActionEvent actionEvent) {
synchronized (videoWindow) {
if (videoWindow.isVisible()) {
videoWindow.setVisible(false);
} else {
videoWindow.setVisible(true);
}
}
}
}
class SimulatorMenu extends JMenuBar {
// Menu Items
private JMenuItem loadProgramItem;
private JMenuItem loadRomItem;
/**
* Create a new SimulatorMenu instance.
*/
public SimulatorMenu() {
initMenu();
}
/**
* Disable menu items that should not be available during simulator execution.
*/
public void simulatorDidStart() {
loadProgramItem.setEnabled(false);
if (loadRomItem != null) {
loadRomItem.setEnabled(false);
}
}
/**
* Enable menu items that should be available while the simulator is stopped.
*/
public void simulatorDidStop() {
loadProgramItem.setEnabled(true);
if (loadRomItem != null) {
loadRomItem.setEnabled(true);
}
}
private void initMenu() {
/*
* File Menu
*/
JMenu fileMenu = new JMenu("File");
loadProgramItem = new JMenuItem(new LoadProgramAction());
fileMenu.add(loadProgramItem);
// Simple Machine does not implement a ROM, so it makes no sense to
// offer a ROM load option.
if (machine.getRom() != null) {
loadRomItem = new JMenuItem(new LoadRomAction());
fileMenu.add(loadRomItem);
}
JMenuItem prefsItem = new JMenuItem(new ShowPrefsAction());
fileMenu.add(prefsItem);
JMenuItem selectMachineItem = new JMenuItem(new SelectMachineAction());
fileMenu.add(selectMachineItem);
JMenuItem quitItem = new JMenuItem(new QuitAction());
fileMenu.add(quitItem);
add(fileMenu);
/*
* View Menu
*/
JMenu viewMenu = new JMenu("View");
JMenu fontSubMenu = new JMenu("Console Font Size");
ButtonGroup fontSizeGroup = new ButtonGroup();
makeFontSizeMenuItem(10, fontSubMenu, fontSizeGroup);
makeFontSizeMenuItem(11, fontSubMenu, fontSizeGroup);
makeFontSizeMenuItem(12, fontSubMenu, fontSizeGroup);
makeFontSizeMenuItem(13, fontSubMenu, fontSizeGroup);
makeFontSizeMenuItem(14, fontSubMenu, fontSizeGroup);
makeFontSizeMenuItem(15, fontSubMenu, fontSizeGroup);
makeFontSizeMenuItem(16, fontSubMenu, fontSizeGroup);
makeFontSizeMenuItem(17, fontSubMenu, fontSizeGroup);
makeFontSizeMenuItem(18, fontSubMenu, fontSizeGroup);
makeFontSizeMenuItem(19, fontSubMenu, fontSizeGroup);
makeFontSizeMenuItem(20, fontSubMenu, fontSizeGroup);
viewMenu.add(fontSubMenu);
final JCheckBoxMenuItem showTraceLog = new JCheckBoxMenuItem(new ToggleTraceWindowAction());
// Un-check the menu item if the user closes the window directly
traceLog.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
showTraceLog.setSelected(false);
}
});
viewMenu.add(showTraceLog);
final JCheckBoxMenuItem showMemoryTable = new JCheckBoxMenuItem(new ToggleMemoryWindowAction());
// Un-check the menu item if the user closes the window directly
memoryWindow.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
showMemoryTable.setSelected(false);
}
});
viewMenu.add(showMemoryTable);
if(videoWindow != null) {
final JCheckBoxMenuItem showVideoWindow = new JCheckBoxMenuItem(new ToggleVideoWindowAction());
videoWindow.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
showVideoWindow.setSelected(false);
}
});
viewMenu.add(showVideoWindow);
}
add(viewMenu);
}
private void makeFontSizeMenuItem(int size, JMenu fontSubMenu, ButtonGroup group) {
Action action = new SetFontAction(size);
JCheckBoxMenuItem item = new JCheckBoxMenuItem(action);
item.setSelected(size == DEFAULT_FONT_SIZE);
fontSubMenu.add(item);
group.add(item);
}
}
}
|
package org.xbill.DNS;
import java.io.*;
import java.text.*;
import java.util.*;
import org.xbill.DNS.utils.*;
/**
* A representation of a domain name.
*
* @author Brian Wellington
*/
public class Name {
private static final int LABEL_NORMAL = 0;
private static final int LABEL_COMPRESSION = 0xC0;
private static final int LABEL_EXTENDED = 0x40;
private static final int LABEL_MASK = 0xC0;
private static final int EXT_LABEL_BITSTRING = 1;
private Object [] name;
private byte labels;
private boolean qualified;
/** The root name */
public static final Name root = Name.fromStringNoValidate(".", null);
/** The maximum number of labels in a Name */
static final int MAXLABELS = 128;
/* The number of labels initially allocated. */
private static final int STARTLABELS = 4;
/* Used for printing non-printable characters */
private static DecimalFormat byteFormat = new DecimalFormat();
static {
byteFormat.setMinimumIntegerDigits(3);
}
private
Name() {
}
private final void
grow(int n) {
if (n > MAXLABELS)
throw new ArrayIndexOutOfBoundsException("name too long");
Object [] newarray = new Object[n];
System.arraycopy(name, 0, newarray, 0, labels);
name = newarray;
}
private final void
grow() {
grow(labels * 2);
}
private final void
compact() {
for (int i = labels - 1; i > 0; i
if (!(name[i] instanceof BitString) ||
!(name[i - 1] instanceof BitString))
continue;
BitString bs = (BitString) name[i];
BitString bs2 = (BitString) name[i - 1];
if (bs.nbits == 256)
continue;
int nbits = bs.nbits + bs2.nbits;
bs.join(bs2);
if (nbits <= 256) {
System.arraycopy(name, i, name, i - 1, labels - i);
labels
}
}
}
/**
* Create a new name from a string and an origin
* @param s The string to be converted
* @param origin If the name is unqualified, the origin to be appended
* @deprecated As of dnsjava 1.3.0, * replaced by <code>Name.fromString</code>.
*/
public
Name(String s, Name origin) {
Name n;
try {
n = Name.fromString(s, origin);
}
catch (TextParseException e) {
StringBuffer sb = new StringBuffer();
sb.append(s);
if (origin != null) {
sb.append(".");
sb.append(origin);
}
sb.append(": ");
sb.append(e.getMessage());
System.err.println(sb.toString());
name = null;
labels = 0;
return;
}
labels = n.labels;
name = n.name;
qualified = n.qualified;
if (!qualified) {
/*
* This isn't exactly right, but it's close.
* Partially qualified names are evil.
*/
if (Options.check("pqdn"))
qualified = false;
else
qualified = (labels > 1);
}
}
/**
* Create a new name from a string
* @param s The string to be converted
* @deprecated as of dnsjava 1.3.0, replaced by <code>Name.fromString</code>.
*/
public
Name(String s) {
this (s, null);
}
/**
* Create a new name from a string and an origin
* @param s The string to be converted
* @param origin If the name is unqualified, the origin to be appended.
* @throws TextParseException The name is invalid.
*/
public static Name
fromString(String s, Name origin) throws TextParseException {
Name name = new Name();
name.labels = 0;
name.name = new Object[1];
boolean seenBitString = false;
if (s.equals("@")) {
if (origin != null)
name.append(origin);
name.qualified = true;
return name;
} else if (s.equals(".")) {
name.qualified = true;
return name;
}
int labelstart = -1;
int pos = 0;
byte [] label = new byte[64];
boolean escaped = false;
int digits = 0;
int intval = 0;
boolean bitstring = false;
for (int i = 0; i < s.length(); i++) {
byte b = (byte) s.charAt(i);
if (escaped) {
if (pos == 0 && b == '[')
bitstring = true;
if (b >= '0' && b <= '9' && digits < 3) {
digits++;
intval *= 10 + (b - '0');
intval += (b - '0');
if (digits < 3)
continue;
b = (byte) intval;
}
else if (digits > 0 && digits < 3)
throw new TextParseException("bad escape");
if (pos >= label.length)
throw new TextParseException("label too long");
label[pos++] = b;
escaped = false;
} else if (b == '\\') {
escaped = true;
digits = 0;
intval = 0;
} else if (b == '.') {
if (labelstart == -1)
throw new TextParseException("invalid label");
byte [] newlabel = new byte[pos];
System.arraycopy(label, 0, newlabel, 0, pos);
if (name.labels == MAXLABELS)
throw new TextParseException("too many labels");
if (name.labels == name.name.length)
name.grow();
if (bitstring) {
bitstring = false;
name.name[name.labels++] =
new BitString(newlabel);
}
else
name.name[name.labels++] = newlabel;
labelstart = -1;
pos = 0;
} else {
if (labelstart == -1)
labelstart = i;
if (pos >= label.length)
throw new TextParseException("label too long");
label[pos++] = b;
}
}
if (labelstart == -1)
name.qualified = true;
else {
byte [] newlabel = new byte[pos];
System.arraycopy(label, 0, newlabel, 0, pos);
if (name.labels == MAXLABELS)
throw new TextParseException("too many labels");
if (name.labels == name.name.length)
name.grow();
if (bitstring) {
bitstring = false;
name.name[name.labels++] = new BitString(newlabel);
}
else
name.name[name.labels++] = newlabel;
}
if (!name.qualified && origin != null)
name.append(origin);
if (seenBitString)
name.compact();
return (name);
}
/*
* Convert a name from a string, knowing that it will succeed.
*/
static Name
fromStringNoValidate(String s, Name origin) {
try {
return fromString(s, origin);
}
catch (TextParseException e) {
return null;
}
}
/**
* Create a new name from DNS wire format
* @param in A stream containing the input data
*/
public
Name(DataByteInputStream in) throws IOException {
int len, start, pos, count = 0, savedpos;
Name name2;
boolean seenBitString = false;
labels = 0;
name = new Object[STARTLABELS];
start = in.getPos();
loop:
while ((len = in.readUnsignedByte()) != 0) {
count++;
switch(len & LABEL_MASK) {
case LABEL_NORMAL:
byte [] b = new byte[len];
in.read(b);
if (labels == name.length)
grow();
name[labels++] = b;
break;
case LABEL_COMPRESSION:
pos = in.readUnsignedByte();
pos += ((len & ~LABEL_MASK) << 8);
if (Options.check("verbosecompression"))
System.err.println("currently " + in.getPos() +
", pointer to " + pos);
if (pos >= in.getPos())
throw new WireParseException("bad compression");
savedpos = in.getPos();
in.setPos(pos);
if (Options.check("verbosecompression"))
System.err.println("current name '" + this +
"', seeking to " + pos);
try {
name2 = new Name(in);
}
finally {
in.setPos(savedpos);
}
if (labels + name2.labels > name.length)
grow(labels + name2.labels);
System.arraycopy(name2.name, 0, name, labels,
name2.labels);
labels += name2.labels;
break loop;
case LABEL_EXTENDED:
int type = len & ~LABEL_MASK;
switch (type) {
case EXT_LABEL_BITSTRING:
int bits = in.readUnsignedByte();
if (bits == 0)
bits = 256;
int bytes = (bits + 7) / 8;
byte [] data = new byte[bytes];
in.read(data);
if (labels == name.length)
grow();
name[labels++] = new BitString(bits, data);
seenBitString = true;
break;
default:
throw new WireParseException(
"Unknown name format");
} /* switch */
break;
} /* switch */
}
qualified = true;
if (seenBitString)
compact();
}
/**
* Create a new name by removing labels from the beginning of an existing Name
* @param d An existing Name
* @param n The number of labels to remove from the beginning in the copy
*/
/* Skips n labels and creates a new name */
public
Name(Name d, int n) {
name = new Object[d.labels - n];
labels = (byte) (d.labels - n);
System.arraycopy(d.name, n, name, 0, labels);
qualified = d.qualified;
}
/**
* Generates a new Name with the first n labels replaced by a wildcard
* @return The wildcard name
*/
public Name
wild(int n) {
Name wild = new Name(this, n - 1);
wild.name[0] = new byte[] {(byte)'*'};
return wild;
}
/**
* Generates a new Name to be used when following a DNAME.
* @return The new name, or null if the DNAME is invalid.
*/
public Name
fromDNAME(DNAMERecord dname) {
Name dnameowner = dname.getName();
Name dnametarget = dname.getTarget();
int nlabels;
int saved;
if (!subdomain(dnameowner))
return null;
saved = labels - dnameowner.labels;
nlabels = saved + dnametarget.labels;
if (nlabels > MAXLABELS)
return null;
Name newname = new Name();
newname.labels = (byte)nlabels;
newname.name = new Object[labels];
System.arraycopy(this.name, 0, newname.name, 0, saved);
System.arraycopy(dnametarget.name, 0, newname.name, saved,
dnametarget.labels);
newname.qualified = true;
newname.compact();
return newname;
}
/**
* Is this name a wildcard?
*/
public boolean
isWild() {
if (labels == 0 || (name[0] instanceof BitString))
return false;
byte [] b = (byte []) name[0];
return (b.length == 1 && b[0] == '*');
}
/**
* Is this name fully qualified?
*/
public boolean
isQualified() {
return qualified;
}
/**
* Appends the specified name to the end of the current Name
*/
public void
append(Name d) {
if (labels + d.labels > name.length)
grow(labels + d.labels);
System.arraycopy(d.name, 0, name, labels, d.labels);
labels += d.labels;
qualified = d.qualified;
compact();
}
/**
* The length
*/
public short
length() {
short total = 0;
for (int i = 0; i < labels; i++) {
if (name[i] instanceof BitString)
total += (((BitString)name[i]).bytes() + 2);
else
total += (((byte [])name[i]).length + 1);
}
return ++total;
}
/**
* The number of labels
*/
public byte
labels() {
return labels;
}
/**
* Is the current Name a subdomain of the specified name?
*/
public boolean
subdomain(Name domain) {
if (domain == null || domain.labels > labels)
return false;
Name tname = new Name(this, labels - domain.labels);
return (tname.equals(domain));
}
private String
byteString(byte [] array) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < array.length; i++) {
/* Ick. */
short b = (short)(array[i] & 0xFF);
if (b <= 0x20 || b >= 0x7f) {
sb.append('\\');
sb.append(byteFormat.format(b));
}
else if (b == '"' || b == '(' || b == ')' || b == '.' ||
b == ';' || b == '\\' || b == '@' || b == '$')
{
sb.append('\\');
sb.append((char)b);
}
else
sb.append((char)b);
}
return sb.toString();
}
/**
* Convert Name to a String
*/
public String
toString() {
StringBuffer sb = new StringBuffer();
if (labels == 0)
sb.append(".");
for (int i = 0; i < labels; i++) {
if (name[i] instanceof BitString)
sb.append(name[i]);
else
sb.append(byteString((byte [])name[i]));
if (qualified || i < labels - 1)
sb.append(".");
}
return sb.toString();
}
/**
* Convert the nth label in a Name to a String
* @param n The label to be converted to a String
*/
public String
getLabelString(int n) {
if (name[n] instanceof BitString)
return name[n].toString();
else
return byteString((byte [])name[n]);
}
/**
* Convert Name to DNS wire format
*/
public void
toWire(DataByteOutputStream out, Compression c) throws IOException {
for (int i = 0; i < labels; i++) {
Name tname;
if (i == 0)
tname = this;
else
tname = new Name(this, i);
int pos = -1;
if (c != null) {
pos = c.get(tname);
if (Options.check("verbosecompression"))
System.err.println("Looking for " + tname +
", found " + pos);
}
if (pos >= 0) {
pos |= (LABEL_MASK << 8);
out.writeShort(pos);
return;
}
else {
if (c != null) {
c.add(out.getPos(), tname);
if (Options.check("verbosecompression"))
System.err.println("Adding " + tname +
" at " +
out.getPos());
}
if (name[i] instanceof BitString) {
out.writeByte(LABEL_EXTENDED |
EXT_LABEL_BITSTRING);
out.writeByte(((BitString)name[i]).wireBits());
out.write(((BitString)name[i]).data);
}
else
out.writeString((byte []) name[i]);
}
}
out.writeByte(0);
}
/**
* Convert Name to canonical DNS wire format (all lowercase)
*/
public void
toWireCanonical(DataByteOutputStream out) throws IOException {
for (int i = 0; i < labels; i++) {
if (name[i] instanceof BitString) {
out.writeByte(LABEL_EXTENDED | EXT_LABEL_BITSTRING);
out.writeByte(((BitString)name[i]).wireBits());
out.write(((BitString)name[i]).data);
}
else
out.writeStringCanonical(new String((byte []) name[i]));
}
out.writeByte(0);
}
private static final byte
toLower(byte b) {
if (b < 'A' || b > 'Z')
return b;
else
return (byte)(b - 'A' + 'a');
}
/**
* Are these two Names equivalent?
*/
public boolean
equals(Object arg) {
if (arg == null || !(arg instanceof Name))
return false;
if (arg == this)
return true;
Name d = (Name) arg;
if (d.labels != labels)
return false;
for (int i = 0; i < labels; i++) {
if (name[i].getClass() != d.name[i].getClass())
return false;
if (name[i] instanceof BitString) {
if (!name[i].equals(d.name[i]))
return false;
}
else {
byte [] b1 = (byte []) name[i];
byte [] b2 = (byte []) d.name[i];
if (b1.length != b2.length)
return false;
for (int j = 0; j < b1.length; j++) {
if (toLower(b1[j]) != toLower(b2[j]))
return false;
}
}
}
return true;
}
/**
* Computes a hashcode based on the value
*/
public int
hashCode() {
int code = labels;
for (int i = 0; i < labels; i++) {
if (name[i] instanceof BitString) {
BitString b = (BitString) name[i];
for (int j = 0; j < b.bytes(); j++)
code += ((code << 3) + b.data[j]);
}
else {
byte [] b = (byte []) name[i];
for (int j = 0; j < b.length; j++)
code += ((code << 3) + toLower(b[j]));
}
}
return code;
}
public int
compareTo(Object o) {
Name arg = (Name) o;
int compares = labels > arg.labels ? arg.labels : labels;
for (int i = 1; i <= compares; i++) {
Object label = name[labels - i];
Object alabel = arg.name[arg.labels - i];
if (label.getClass() != alabel.getClass()) {
if (label instanceof BitString)
return (-1);
else
return (1);
}
if (label instanceof BitString) {
BitString bs = (BitString)label;
BitString abs = (BitString)alabel;
int bits = bs.nbits > abs.nbits ? abs.nbits : bs.nbits;
int n = bs.compareBits(abs, bits);
if (n != 0)
return (n);
if (bs.nbits == abs.nbits)
continue;
/*
* If label X has more bits than label Y, then the
* name with X is greater if Y is the first label
* of its name. Otherwise, the name with Y is greater.
*/
if (bs.nbits > abs.nbits)
return (i == arg.labels ? 1 : -1);
else
return (i == labels ? -1 : 1);
}
else {
byte [] b = (byte []) label;
byte [] ab = (byte []) alabel;
for (int j = 0; j < b.length && j < ab.length; j++) {
int n = toLower(b[j]) - toLower(ab[j]);
if (n != 0)
return (n);
}
if (b.length != ab.length)
return (b.length - ab.length);
}
}
return (labels - arg.labels);
}
}
|
package org.xbill.DNS;
import java.io.*;
import java.net.*;
import java.util.*;
import org.xbill.DNS.utils.*;
/**
* Transaction signature handling. This class generates and verifies
* TSIG records on messages, which provide transaction security,
* @see TSIGRecord
*
* @author Brian Wellington
*/
public class TSIG {
/**
* The domain name representing the HMAC-MD5 algorithm (the only supported
* algorithm)
*/
public static final Name HMAC = new Name("HMAC-MD5.SIG-ALG.REG.INT");
/** The default fudge value for outgoing packets. Can be overriden by the
* tsigfudge option.
*/
public static final short FUDGE = 300;
private Name name, alg;
private byte [] key;
private hmacSigner axfrSigner = null;
static {
if (Options.check("verbosehmac"))
hmacSigner.verbose = true;
}
/**
* Creates a new TSIG object, which can be used to sign or verify a message.
* @param name The name of the shared key
* @param key The shared key's data
*/
public
TSIG(String name, byte [] key) {
this.name = new Name(name);
this.alg = HMAC;
this.key = key;
}
/**
* Generates a TSIG record for a message and adds it to the message
* @param m The message
* @param old If this message is a response, the TSIG from the request
*/
public void
apply(Message m, TSIGRecord old) throws IOException {
Date timeSigned = new Date();
short fudge;
hmacSigner h = new hmacSigner(key);
if (Options.check("tsigfudge")) {
String s = Options.value("tsigfudge");
try {
fudge = Short.parseShort(s);
}
catch (NumberFormatException e) {
fudge = FUDGE;
}
}
else
fudge = FUDGE;
try {
if (old != null) {
DataByteOutputStream dbs = new DataByteOutputStream();
dbs.writeShort((short)old.getSignature().length);
h.addData(dbs.toByteArray());
h.addData(old.getSignature());
}
/* Digest the message */
h.addData(m.toWire());
DataByteOutputStream out = new DataByteOutputStream();
name.toWireCanonical(out);
out.writeShort(DClass.ANY); /* class */
out.writeInt(0); /* ttl */
alg.toWireCanonical(out);
long time = timeSigned.getTime() / 1000;
short timeHigh = (short) (time >> 32);
int timeLow = (int) (time);
out.writeShort(timeHigh);
out.writeInt(timeLow);
out.writeShort(fudge);
out.writeShort(0); /* No error */
out.writeShort(0); /* No other data */
h.addData(out.toByteArray());
}
catch (IOException e) {
return;
}
Record r = new TSIGRecord(name, DClass.ANY, 0, alg, timeSigned, fudge,
h.sign(), m.getHeader().getID(),
Rcode.NOERROR, null);
m.addRecord(r, Section.ADDITIONAL);
}
/**
* Verifies a TSIG record on an incoming message. Since this is only called
* in the context where a TSIG is expected to be present, it is an error
* if one is not present.
* @param m The message
* @param b The message in unparsed form. This is necessary since TSIG
* signs the message in wire format, and we can't recreate the exact wire
* format (with the same name compression).
* @param old If this message is a response, the TSIG from the request
*/
public boolean
verify(Message m, byte [] b, TSIGRecord old) {
TSIGRecord tsig = m.getTSIG();
hmacSigner h = new hmacSigner(key);
if (tsig == null)
return false;
if (!tsig.getName().equals(name) || !tsig.getAlgorithm().equals(alg)) {
if (Options.check("verbose"))
System.err.println("BADKEY failure");
return false;
}
long now = System.currentTimeMillis();
long then = tsig.getTimeSigned().getTime();
long fudge = tsig.getFudge();
if (Math.abs(now - then) > fudge * 1000) {
if (Options.check("verbose"))
System.err.println("BADTIME failure");
return false;
}
try {
if (old != null && tsig.getError() != Rcode.BADKEY &&
tsig.getError() != Rcode.BADSIG)
{
DataByteOutputStream dbs = new DataByteOutputStream();
dbs.writeShort((short)old.getSignature().length);
h.addData(dbs.toByteArray());
h.addData(old.getSignature());
}
m.getHeader().decCount(Section.ADDITIONAL);
byte [] header = m.getHeader().toWire();
m.getHeader().incCount(Section.ADDITIONAL);
h.addData(header);
int len = b.length - header.length;
len -= tsig.wireLength;
h.addData(b, header.length, len);
DataByteOutputStream out = new DataByteOutputStream();
tsig.getName().toWireCanonical(out);
out.writeShort(tsig.dclass);
out.writeInt(tsig.ttl);
tsig.getAlgorithm().toWireCanonical(out);
long time = tsig.getTimeSigned().getTime() / 1000;
short timeHigh = (short) (time >> 32);
int timeLow = (int) (time);
out.writeShort(timeHigh);
out.writeInt(timeLow);
out.writeShort(tsig.getFudge());
out.writeShort(tsig.getError());
if (tsig.getOther() != null) {
out.writeShort(tsig.getOther().length);
out.write(tsig.getOther());
}
else
out.writeShort(0);
h.addData(out.toByteArray());
}
catch (IOException e) {
return false;
}
if (axfrSigner != null) {
DataByteOutputStream dbs = new DataByteOutputStream();
dbs.writeShort((short)tsig.getSignature().length);
axfrSigner.addData(dbs.toByteArray());
axfrSigner.addData(tsig.getSignature());
}
if (h.verify(tsig.getSignature()))
return true;
else {
if (Options.check("verbose"))
System.err.println("BADSIG failure");
return false;
}
}
/** Prepares the TSIG object to verify an AXFR */
public void
verifyAXFRStart() {
axfrSigner = new hmacSigner(key);
}
/**
* Verifies a TSIG record on an incoming message that is part of an AXFR.
* TSIG records must be present on the first and last messages, and
* at least every 100 records in between (the last rule is not enforced).
* @param m The message
* @param b The message in unparsed form
* @param old The TSIG from the AXFR request
* @param required True if this message is required to include a TSIG.
* @param first True if this message is the first message of the AXFR
*/
public boolean
verifyAXFR(Message m, byte [] b, TSIGRecord old,
boolean required, boolean first)
{
TSIGRecord tsig = m.getTSIG();
hmacSigner h = axfrSigner;
if (first)
return verify(m, b, old);
try {
if (tsig != null)
m.getHeader().decCount(Section.ADDITIONAL);
byte [] header = m.getHeader().toWire();
if (tsig != null)
m.getHeader().incCount(Section.ADDITIONAL);
h.addData(header);
int len = b.length - header.length;
if (tsig != null)
len -= tsig.wireLength;
h.addData(b, header.length, len);
if (tsig == null) {
if (required)
return false;
else
return true;
}
if (!tsig.getName().equals(name) ||
!tsig.getAlgorithm().equals(alg))
{
if (Options.check("verbose"))
System.err.println("BADKEY failure");
return false;
}
DataByteOutputStream out = new DataByteOutputStream();
long time = tsig.getTimeSigned().getTime() / 1000;
short timeHigh = (short) (time >> 32);
int timeLow = (int) (time);
out.writeShort(timeHigh);
out.writeInt(timeLow);
out.writeShort(tsig.getFudge());
h.addData(out.toByteArray());
}
catch (IOException e) {
return false;
}
if (h.verify(tsig.getSignature()) == false) {
if (Options.check("verbose"))
System.err.println("BADSIG failure");
return false;
}
h.clear();
DataByteOutputStream dbs = new DataByteOutputStream();
dbs.writeShort((short)old.getSignature().length);
h.addData(dbs.toByteArray());
h.addData(tsig.getSignature());
return true;
}
}
|
package com.orasi.utils;
import java.net.URL;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebDriverException;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.edge.EdgeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.htmlunit.HtmlUnitDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.openqa.selenium.safari.SafariDriver;
import com.gargoylesoftware.htmlunit.WebWindow;
import com.gargoylesoftware.htmlunit.javascript.background.DefaultJavaScriptExecutor;
import com.gargoylesoftware.htmlunit.javascript.background.JavaScriptExecutor;
import com.orasi.core.by.angular.ByNG;
import com.orasi.core.by.angular.ByNG.ByNGButton;
import com.orasi.core.by.angular.ByNG.ByNGController;
import com.orasi.core.by.angular.ByNG.ByNGModel;
import com.orasi.core.by.angular.ByNG.ByNGRepeater;
import com.orasi.core.by.angular.ByNG.ByNGShow;
import com.orasi.core.by.angular.internal.ByAngular;
import com.orasi.core.interfaces.Button;
import com.orasi.core.interfaces.Checkbox;
import com.orasi.core.interfaces.Element;
import com.orasi.core.interfaces.Label;
import com.orasi.core.interfaces.Link;
import com.orasi.core.interfaces.Listbox;
import com.orasi.core.interfaces.RadioGroup;
import com.orasi.core.interfaces.Textbox;
import com.orasi.core.interfaces.Webtable;
import com.orasi.core.interfaces.impl.ButtonImpl;
import com.orasi.core.interfaces.impl.CheckboxImpl;
import com.orasi.core.interfaces.impl.ElementImpl;
import com.orasi.core.interfaces.impl.LabelImpl;
import com.orasi.core.interfaces.impl.LinkImpl;
import com.orasi.core.interfaces.impl.ListboxImpl;
import com.orasi.core.interfaces.impl.RadioGroupImpl;
import com.orasi.core.interfaces.impl.TextboxImpl;
import com.orasi.core.interfaces.impl.WebtableImpl;
public class OrasiDriver implements WebDriver, JavaScriptExecutor, TakesScreenshot {
/*
* Define fields to be used by an OrasiDriver
*/
private static final long serialVersionUID = -657563735440878909L;
private WebDriver driver;
private int currentPageTimeout = Constants.PAGE_TIMEOUT;
private int currentElementTimeout = Constants.ELEMENT_TIMEOUT;
private int currentScriptTimeout = Constants.DEFAULT_GLOBAL_DRIVER_TIMEOUT;
/**
* Constructor for OrasiDriver
* Example usage: OrasiDriver oDriver = new OrasiDriver(caps);
* @param caps - Selenium desired capabilities, used to configure the OrasiDriver
*/
public OrasiDriver(DesiredCapabilities caps) {
setDriverWithCapabilties(caps);
}
/**
* Constructor for OrasiDriver, specifically used to generate a remote WebDriver
* Example usage: OrasiDriver oDriver = new OrasiDriver(caps, url);
* @param caps - Selenium desired capabilities, used to configure the OrasiDriver
* @param url -
*/
public OrasiDriver(DesiredCapabilities caps, URL url) {
driver = new RemoteWebDriver(url, caps);
}
/**
* Method to return the current OrasiDriver
* Example usage: getDriver().getDriver();
* @return - current OrasiDriver
*/
public WebDriver getDriver() {
return driver;
}
@Override
public void get(String url) {
driver.get(url);
}
@Override
public String getCurrentUrl() {
return driver.getCurrentUrl();
}
@Override
public String getTitle() {
return driver.getTitle();
}
public void setScriptTimeout(int timeout) {
setScriptTimeout(timeout, TimeUnit.SECONDS);
}
public void setScriptTimeout(int timeout, TimeUnit timeUnit) {
this.currentScriptTimeout = timeout;
driver.manage().timeouts().setScriptTimeout(timeout, timeUnit);
}
/**
* Method to return the script timeout
* @return - script timeout
*/
public int getScriptTimeout() {
return currentScriptTimeout;
}
public void setPageTimeout(int timeout) {
setPageTimeout(timeout, TimeUnit.SECONDS);
}
public void setPageTimeout(int timeout, TimeUnit timeUnit) {
if (driver instanceof SafariDriver || driver.toString().contains("safari")) {
System.out.println("SafariDriver does not support pageLoadTimeout");
} else {
this.currentPageTimeout = timeout;
driver.manage().timeouts().pageLoadTimeout(timeout, timeUnit);
}
}
/**
* Method to return the page timeout
* @return - page timeout
*/
public int getPageTimeout() {
return currentPageTimeout;
}
public void setElementTimeout(int timeout) {
setElementTimeout(timeout, TimeUnit.SECONDS);
}
public void setElementTimeout(int timeout, TimeUnit timeUnit) {
this.currentElementTimeout = timeout;
driver.manage().timeouts().implicitlyWait(timeout, timeUnit);
}
/**
* Method to return the element timeout
* @return - element timeout
*/
public int getElementTimeout() {
return currentElementTimeout;
}
/*
* public List<Element> findElements(By by) { List<WebElement> webElements =
* driver.findElements(by); List test = webElements; List<Element> elements=
* (List<Element>)test; return elements; }
*/
@Override
public List<WebElement> findElements(By by) {
try {
return findWebElements(by);
} catch (NoSuchElementException nse) {
TestReporter.logFailure("No such Element with context " + by.toString());
throw new NoSuchElementException(nse.getMessage());
}
}
public List<WebElement> findWebElements(By by) {
try {
return driver.findElements(by);
} catch (NoSuchElementException nse) {
TestReporter.logFailure("No such WebElement with context: " + by.toString());
throw new NoSuchElementException(nse.getMessage());
}
}
@Override
public Element findElement(By by) {
try {
return new ElementImpl(driver.findElement(by), this);
} catch (NoSuchElementException nse) {
TestReporter.logFailure("No such Element with context: " + by.toString());
throw new NoSuchElementException(nse.getMessage());
}
}
public Element findElement(ByNG by) {
try {
return new ElementImpl(driver.findElement(getByNGType(by)), this);
} catch (NoSuchElementException nse) {
TestReporter.logFailure("No such Element with context: " + by.toString());
throw new NoSuchElementException(nse.getMessage());
}
}
public Textbox findTextbox(By by) {
try {
return new TextboxImpl(driver.findElement(by), this);
} catch (NoSuchElementException nse) {
TestReporter.logFailure("No such Textbox with context: " + by.toString());
throw new NoSuchElementException(nse.getMessage());
}
}
public Textbox findTextbox(ByNG by) {
try {
return new TextboxImpl(driver.findElement(getByNGType(by)), this);
} catch (NoSuchElementException nse) {
TestReporter.logFailure("No such Textbox with context: " + by.toString());
throw new NoSuchElementException(nse.getMessage());
}
}
public Button findButton(By by) {
try {
return new ButtonImpl(driver.findElement(by), this);
} catch (NoSuchElementException nse) {
TestReporter.logFailure("No such Button with context: " + by.toString());
throw new NoSuchElementException(nse.getMessage());
}
}
public Button findButton(ByNG by) {
try {
return new ButtonImpl(driver.findElement(getByNGType(by)), this);
} catch (NoSuchElementException nse) {
TestReporter.logFailure("No such Button with context: " + by.toString());
throw new NoSuchElementException(nse.getMessage());
}
}
public Checkbox findCheckbox(By by) {
try {
return new CheckboxImpl(driver.findElement(by), this);
} catch (NoSuchElementException nse) {
TestReporter.logFailure("No such Checkbox with context: " + by.toString());
throw new NoSuchElementException(nse.getMessage());
}
}
public Checkbox findCheckbox(ByNG by) {
try {
return new CheckboxImpl(driver.findElement(getByNGType(by)), this);
} catch (NoSuchElementException nse) {
TestReporter.logFailure("No such Checkbox with context: " + by.toString());
throw new NoSuchElementException(nse.getMessage());
}
}
public Label findLabel(By by) {
try {
return new LabelImpl(driver.findElement(by), this);
} catch (NoSuchElementException nse) {
TestReporter.logFailure("No such Label with context: " + by.toString());
throw new NoSuchElementException(nse.getMessage());
}
}
public Label findLabel(ByNG by) {
try {
return new LabelImpl(driver.findElement(getByNGType(by)), this);
} catch (NoSuchElementException nse) {
TestReporter.logFailure("No such Label with context: " + by.toString());
throw new NoSuchElementException(nse.getMessage());
}
}
public Link findLink(By by) {
try {
return new LinkImpl(driver.findElement(by), this);
} catch (NoSuchElementException nse) {
TestReporter.logFailure("No such Link with context: " + by.toString());
throw new NoSuchElementException(nse.getMessage());
}
}
public Link findLink(ByNG by) {
try {
return new LinkImpl(driver.findElement(getByNGType(by)), this);
} catch (NoSuchElementException nse) {
TestReporter.logFailure("No such Link with context: " + by.toString());
throw new NoSuchElementException(nse.getMessage());
}
}
public Listbox findListbox(By by) {
try {
return new ListboxImpl(driver.findElement(by), this);
} catch (NoSuchElementException nse) {
TestReporter.logFailure("No such Listbox with context: " + by.toString());
throw new NoSuchElementException(nse.getMessage());
}
}
public Listbox findListbox(ByNG by) {
try {
return new ListboxImpl(driver.findElement(getByNGType(by)), this);
} catch (NoSuchElementException nse) {
TestReporter.logFailure("No such Listbox with context: " + by.toString());
throw new NoSuchElementException(nse.getMessage());
}
}
public RadioGroup findRadioGroup(By by) {
try {
return new RadioGroupImpl(driver.findElement(by), this);
} catch (NoSuchElementException nse) {
TestReporter.logFailure("No such RadioGroup with context: " + by.toString());
throw new NoSuchElementException(nse.getMessage());
}
}
public RadioGroup findRadioGroup(ByNG by) {
try {
return new RadioGroupImpl(driver.findElement(getByNGType(by)), this);
} catch (NoSuchElementException nse) {
TestReporter.logFailure("No such RadioGroup with context: " + by.toString());
throw new NoSuchElementException(nse.getMessage());
}
}
public Webtable findWebtable(By by) {
try {
return new WebtableImpl(driver.findElement(by), this);
} catch (NoSuchElementException nse) {
TestReporter.logFailure("No such Webtable with context: " + by.toString());
throw new NoSuchElementException(nse.getMessage());
}
}
public Webtable findWebtable(ByNG by) {
try {
return new WebtableImpl(driver.findElement(getByNGType(by)), this);
} catch (NoSuchElementException nse) {
TestReporter.logFailure("No such Webtable with context: " + by.toString());
throw new NoSuchElementException(nse.getMessage());
}
}
public WebElement findWebElement(By by) {
try {
return driver.findElement(by);
} catch (NoSuchElementException nse) {
TestReporter.logFailure("No such WebElement with context: " + by.toString());
throw new NoSuchElementException(nse.getMessage());
}
}
public WebElement findWebElement(ByNG by) {
try {
return driver.findElement(getByNGType(by));
} catch (NoSuchElementException nse) {
TestReporter.logFailure("No such WebElement with context: " + by.toString());
throw new NoSuchElementException(nse.getMessage());
}
}
@Override
public String getPageSource() {
return driver.getPageSource();
}
@Override
public void close() {
driver.close();
}
@Override
public void quit() {
driver.quit();
}
@Override
public Set<String> getWindowHandles() {
return driver.getWindowHandles();
}
@Override
public String getWindowHandle() {
return driver.getWindowHandle();
}
@Override
public TargetLocator switchTo() {
return driver.switchTo();
}
@Override
public Navigation navigate() {
return driver.navigate();
}
@Override
public Options manage() {
return driver.manage();
}
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
@Override
public boolean equals(Object obj) {
return super.equals(obj);
}
@Override
protected void finalize() throws Throwable {
super.finalize();
}
@Override
public int hashCode() {
return super.hashCode();
}
@Override
public String toString() {
return super.toString();
}
public Object executeJavaScript(String script, Object... parameters) {
return ((JavascriptExecutor) driver).executeScript(script, parameters);
}
public Object executeAsyncJavaScript(String script, Object... parameters) {
return ((JavascriptExecutor) driver).executeAsyncScript(script, parameters);
}
@Override
public void run() {
((DefaultJavaScriptExecutor) driver).run();
}
@Override
public void addWindow(WebWindow newWindow) {
((DefaultJavaScriptExecutor) driver).addWindow(newWindow);
}
@Override
public void shutdown() {
((DefaultJavaScriptExecutor) driver).shutdown();
}
@Override
public int pumpEventLoop(long timeoutMillis) {
return ((DefaultJavaScriptExecutor) driver).pumpEventLoop(timeoutMillis);
}
public String getSessionId() {
return ((RemoteWebDriver) driver).getSessionId().toString();
}
private void setDriverWithCapabilties(DesiredCapabilities caps) {
switch (caps.getBrowserName().toLowerCase()) {
case "firefox":
driver = new FirefoxDriver(caps);
break;
case "internet explorer":
case "ie":
driver = new InternetExplorerDriver(caps);
break;
case "chrome":
driver = new ChromeDriver(caps);
break;
case "safari":
driver = new SafariDriver(caps);
break;
case "htmlunit":
case "html":
driver = new HtmlUnitDriver(true);
break;
case "edge":
case "microsoftedge":
driver = new EdgeDriver(caps);
break;
default:
break;
}
}
public Capabilities getDriverCapability() {
return new Capabilities();
}
@Override
public <X> X getScreenshotAs(OutputType<X> target) throws WebDriverException {
return ((TakesScreenshot) driver).getScreenshotAs(target);
}
class Capabilities {
public String browserName() {
return ((RemoteWebDriver) driver).getCapabilities().getBrowserName();
}
public String browserVersion() {
return ((RemoteWebDriver) driver).getCapabilities().getVersion();
}
public String platformOS() {
return ((RemoteWebDriver) driver).getCapabilities().getPlatform().name() + " "
+ ((RemoteWebDriver) driver).getCapabilities().getPlatform().getMajorVersion() + "."
+ ((RemoteWebDriver) driver).getCapabilities().getPlatform().getMinorVersion();
}
}
@SuppressWarnings("static-access")
private ByAngular.BaseBy getByNGType(ByNG by) {
String text = by.toString().replace("By.buttonText:", "").trim();
if (by instanceof ByNGButton)
return new ByAngular(getDriver()).buttonText(text);
if (by instanceof ByNGController)
return new ByAngular(getDriver()).controller(text);
if (by instanceof ByNGModel)
return new ByAngular(getDriver()).model(text);
if (by instanceof ByNGRepeater)
return new ByAngular(getDriver()).repeater(text);
if (by instanceof ByNGShow)
return new ByAngular(getDriver()).show(text);
return null;
}
public Page page() {
return new Page();
}
/**
* This class contains methods that hook into the PageLoaded class, allowing for compact usage with the driver
* Example usages provided with each method contained within.
* @author Waightstill W Avery
*/
public class Page {
/*
* isDomInteractive
*/
/**
* Method that determines when/if the DOM is interactive
* Example usage: getDriver().page().isDomInteractive()
* @return - boolean true if interactive, false otherwise
*/
public boolean isDomInteractive() {
return new PageLoaded(getOrasiDriver()).isDomInteractive();
}
/**
* Method that determines when/if the DOM is interactive
* Example usage: getDriver().page().isDomComplete(oDriver);
* @param oDriver - current OrasiDriver
* @return - boolean true if interactive, false otherwise
*/
public boolean isDomInteractive(OrasiDriver oDriver) {
return new PageLoaded().isDomInteractive(oDriver);
}
/**
* Method that determines when/if the DOM is interactive
* Example usage: getDriver().page().initializePage(oDriver, timeout);
* @param oDriver - current OrasiDriver
* @param timeout - user-defined timeout to allow the DOM to become interactive
* @return - boolean true if interactive, false otherwise
*/
public boolean isDomInteractive(OrasiDriver oDriver, int timeout) {
return new PageLoaded().isDomInteractive(oDriver, timeout);
}
/*
* isAngularComplete
*/
/**
* Method that determine when/if an AngularJS page is complete
* Example usage: getDriver().page().isAngularComplete();
*/
public void isAngularComplete() {
new PageLoaded(getOrasiDriver()).isAngularComplete();
}
/*
* isDomComplete
*/
/**
* Method that determines when/if the DOM is complete
* Example usage: getDriver().page().isDomComplete();
* @return - boolean true if complete, false otherwise
*/
public boolean isDomComplete() {
return new PageLoaded().isDomComplete(getOrasiDriver());
}
/**
* Method that determines when/if the DOM is complete
* Example usage: getDriver().page().isDomComplete(oDriver);
* @param oDriver - current OrasiDriver
* @return - boolean true if complete, false otherwise
*/
public boolean isDomComplete(OrasiDriver oDriver) {
return new PageLoaded(getOrasiDriver()).isDomComplete();
}
/**
* Method that determines when/if the DOM is complete
* Example usage: getDriver().page().isDomComplete(oDriver, timeout);
* @param oDriver - current OrasiDriver
* @param timeout - user-defined timeout to allow the DOM to become interactive
* @return - boolean true if complete, false otherwise
* @return
*/
public boolean isDomComplete(OrasiDriver oDriver, int timeout) {
return new PageLoaded().isDomComplete(getOrasiDriver(), timeout);
}
/*
* syncPresent
*/
/**
* Method that determines if an element is present in the DOM
* Example usage: getDriver().page().syncPresent(oDriver, element);
* @param oDriver - current OrasiDriver
* @param element - element for which to be searched
* @return - boolean true if present, false otherwise
*/
public boolean syncPresent(OrasiDriver oDriver, Element element) {
return PageLoaded.syncPresent(oDriver, element);
}
/**
* Method that determines if an element is present in the DOM
* Example usage: getDriver().page().syncPresent(oDriver, timeout, element);
* @param oDriver - current OrasiDriver
* @param timeout - amount of time to wait for the element to be present
* @param element - element for which to be searched
* @return - boolean true if present, false otherwise
*/
public boolean syncPresent(OrasiDriver oDriver, int timeout, Element element) {
return PageLoaded.syncPresent(oDriver, timeout, element);
}
/**
* Method that determines if an element is present in the DOM
* Example usage: getDriver().page().syncPresent(oDriver, timeout, returnError, element);
* @param oDriver - current OrasiDriver
* @param timeout - amount of time to wait for the element to be present
* @param returnError - boolean true if and error is to be thrown if the element is not present, false otherwise
* @param element - element for which to be searched
* @return - boolean true if present, false otherwise
*/
public boolean syncPresent(OrasiDriver oDriver, int timeout, boolean returnError, Element element) {
return PageLoaded.syncPresent(oDriver, timeout, returnError, element);
}
/*
* syncVisible
*/
/**
* Method that determines if an element is visible on the screen
* Example usage: getDriver().page().syncVisible(oDriver, element);
* @param oDriver - current OrasiDriver
* @param element - element for which to be searched
* @return - boolean true if visible, false otherwise
*/
public boolean syncVisible(OrasiDriver oDriver, Element element) {
return PageLoaded.syncVisible(oDriver, element);
}
/**
* Method that determines if an element is visible on the screen
* Example usage: getDriver().page().syncVisible(oDriver, timeout, element);
* @param oDriver - current OrasiDriver
* @param timeout - amount of time to wait for the element to be visible on the screen
* @param element - element for which to be searched
* @return - boolean true if visible, false otherwise
*/
public boolean syncVisible(OrasiDriver oDriver, int timeout, Element element) {
return PageLoaded.syncVisible(oDriver, timeout, true, element);
}
/**
* Method that determines if an element is visible on the screen
* Example usage: getDriver().page().syncVisible(oDriver, timeout, returnError, element);
* @param oDriver - current OrasiDriver
* @param timeout - amount of time to wait for the element to be visible on the screen
* @param returnError - boolean true if and error is to be thrown if the element is not visible, false otherwise
* @param element - element for which to be searched
* @return - boolean true if visible, false otherwise
*/
public boolean syncVisible(OrasiDriver oDriver, int timeout, boolean returnError, Element element) {
return PageLoaded.syncVisible(oDriver, timeout, returnError, element);
}
/*
* syncHidden
*/
/**
* Method that determines if an element is hidden on the screen
* Example usage: getDriver().page().syncHidden(oDriver, element);
* @param oDriver - current OrasiDriver
* @param element - element for which to be searched
* @return - boolean true if hidden, false otherwise
*/
public boolean syncHidden(OrasiDriver oDriver, Element element) {
return PageLoaded.syncHidden(oDriver, oDriver.getElementTimeout(), element);
}
/**
* Method that determines if an element is hidden on the screen
* Example usage: getDriver().page().syncHidden(oDriver, timeout, element);
* @param oDriver - current OrasiDriver
* @param timeout - amount of time to wait for the element to be hidden on the screen
* @param element - element for which to be searched
* @return - boolean true if hidden, false otherwise
*/
public boolean syncHidden(OrasiDriver oDriver, int timeout, Element element) {
return PageLoaded.syncHidden(oDriver, timeout, true, element);
}
/**
* Method that determines if an element is hidden on the screen
* Example usage: getDriver().page().syncHidden(oDriver, timeout, returnError, element);
* @param oDriver - current OrasiDriver
* @param timeout - amount of time to wait for the element to be hidden on the screen
* @param returnError - boolean true if and error is to be thrown if the element is not hidden, false otherwise
* @param element - element for which to be searched
* @return - boolean true if hidden, false otherwise
*/
public boolean syncHidden(OrasiDriver oDriver, int timeout, boolean returnError, Element element) {
return PageLoaded.syncHidden(oDriver, timeout, returnError, element);
}
/*
* syncEnabled
*/
/**
* Method that determines if an element is clickable
* Example usage: getDriver().page().syncEnabled(oDriver, element);
* @param oDriver - current OrasiDriver
* @param element - element for which to be searched
* @return - boolean true if clickable, false otherwise
*/
public boolean syncEnabled(OrasiDriver oDriver, Element element) {
return PageLoaded.syncEnabled(oDriver, oDriver.getElementTimeout(), element);
}
/**
* Method that determines if an element is clickable
* Example usage: getDriver().page().syncEnabled(oDriver, timeout, element);
* @param oDriver - current OrasiDriver
* @param timeout - amount of time to wait for the element to be clickable
* @param element - element for which to be searched
* @return - boolean true if clickable, false otherwise
*/
public boolean syncEnabled(OrasiDriver oDriver, int timeout, Element element) {
return PageLoaded.syncEnabled(oDriver, timeout, true, element);
}
/**
* Method that determines if an element is clickable
* Example usage: getDriver().page().syncEnabled(oDriver, timeout, returnError, element);
* @param oDriver - current OrasiDriver
* @param timeout - amount of time to wait for the element to be not clickable
* @param returnError - boolean true if and error is to be thrown if the element is not clickable, false otherwise
* @param element - element for which to be searched
* @return - boolean true if clickable, false otherwise
*/
public boolean syncEnabled(OrasiDriver oDriver, int timeout, boolean returnError, Element element) {
return syncEnabled(oDriver, timeout, returnError, element);
}
/*
* syncDisabled
*/
/**
* Method that determines if an element is not clickable
* Example usage: getDriver().page().syncDisabled(oDriver, element);
* @param oDriver - current OrasiDriver
* @param element - element for which to be searched
* @return - boolean true if not clickable, false otherwise
*/
public boolean syncDisabled(OrasiDriver oDriver, Element element) {
return PageLoaded.syncDisabled(oDriver, oDriver.getElementTimeout(), element);
}
/**
* Method that determines if an element is not clickable
* Example usage: getDriver().page().syncDisabled(oDriver, timeout, element);
* @param oDriver - current OrasiDriver
* @param timeout - amount of time to wait for the element to be not clickable
* @param element - element for which to be searched
* @return - boolean true if not clickable, false otherwise
*/
public boolean syncDisabled(OrasiDriver oDriver, int timeout, Element element) {
return PageLoaded.syncDisabled(oDriver, timeout, true, element);
}
/**
* Method that determines if an element is not clickable
* Example usage: getDriver().page().syncDisabled(oDriver, timeout, returnError, element);
* @param oDriver - current OrasiDriver
* @param timeout - amount of time to wait for the element to be not clickable
* @param returnError - boolean true if and error is to be thrown if the element is clickable, false otherwise
* @param element - element for which to be searched
* @return - boolean true if not clickable, false otherwise
*/
public boolean syncDisabled(OrasiDriver oDriver, int timeout, boolean returnError, Element element) {
return PageLoaded.syncDisabled(oDriver, timeout, returnError, element);
}
/*
* syncTextInElement
*/
/**
* Method that determines if an element contains user-defined text
* Example usage: getDriver().page().syncTextInElement(oDriver, text, element);
* @param oDriver - current OrasiDriver
* @param text - text for which to search
* @param element - element for which to be searched
* @return - boolean true if the element contains the text, false otherwise
*/
public boolean syncTextInElement(OrasiDriver oDriver, String text, Element element) {
return PageLoaded.syncTextInElement(oDriver, text, oDriver.getElementTimeout(), element);
}
/**
* Method that determines if an element contains user-defined text
* Example usage: getDriver().page().syncTextInElement(oDriver, text, timeout, element);
* @param oDriver - current OrasiDriver
* @param text - text for which to search
* @param timeout - amount of time to wait for the element to contain the text
* @param element - element for which to be searched
* @return - boolean true if the element contains the text, false otherwise
*/
public boolean syncTextInElement(OrasiDriver oDriver, String text, int timeout, Element element) {
return PageLoaded.syncTextInElement(oDriver, text, timeout, true, element);
}
/**
* Method that determines if an element contains user-defined text
* Example usage: getDriver().page().syncTextInElement(oDriver, text, timeout, returnError, element);
* @param oDriver - current OrasiDriver
* @param text - text for which to search
* @param timeout - amount of time to wait for the element to contain the text
* @param returnError - boolean true if and error is to be thrown if the element contains the text, false otherwise
* @param element - element for which to be searched
* @return - boolean true if the element contains the text, false otherwise
*/
public boolean syncTextInElement(OrasiDriver oDriver, String text, int timeout, boolean returnError,
Element element) {
return PageLoaded.syncTextInElement(oDriver, text, timeout, returnError, element);
}
/*
* initializePage
*/
/**
* Method that (re)initializes all of the elements for a given page
* class. This is useful to stave off the Selenium StaleElementException
* Example usage: getDriver().page().initializePage(clazz);
* @param clazz - page class for which to (re)initialize all elements
*/
public void initializePage(Class<?> clazz) {
PageLoaded.initializePage(clazz);
}
/**
* Method that (re)initializes all of the elements for a given page
* class. This is useful to stave off the Selenium StaleElementException
* Example usage: getDriver().page().initializePage(clazz, oDriver);
* @param clazz - page class for which to (re)initialize all elements
* @param oDriver - current OrasiDriver
*/
public void initializePage(Class<?> clazz, OrasiDriver oDriver) {
PageLoaded.initializePage(clazz, oDriver);
}
}
/**
* Method to return this OrasiDriver class
* @return - current OrasiDriver
*/
private OrasiDriver getOrasiDriver() {
return this;
}
}
|
package org.xbill.DNS;
import org.xbill.DNS.utils.*;
/**
* Constants and functions relating to DNS Types
*
* @author Brian Wellington
*/
public final class Type {
private static StringValueTable types = new StringValueTable();
/** Address */
public static final short A = 1;
/** Name server */
public static final short NS = 2;
/** Mail destination */
public static final short MD = 3;
/** Mail forwarder */
public static final short MF = 4;
/** Canonical name (alias) */
public static final short CNAME = 5;
/** Start of authority */
public static final short SOA = 6;
/** Mailbox domain name */
public static final short MB = 7;
/** Mail group member */
public static final short MG = 8;
/** Mail rename name */
public static final short MR = 9;
/** Null record */
public static final short NULL = 10;
/** Well known services */
public static final short WKS = 11;
/** Domain name pointer */
public static final short PTR = 12;
/** Host information */
public static final short HINFO = 13;
/** Mailbox information */
public static final short MINFO = 14;
/** Mail routing information */
public static final short MX = 15;
/** Text strings */
public static final short TXT = 16;
/** Responsible person */
public static final short RP = 17;
/** AFS cell database */
public static final short AFSDB = 18;
/** X_25 calling address */
public static final short X25 = 19;
/** ISDN calling address */
public static final short ISDN = 20;
/** Router */
public static final short RT = 21;
/** NSAP address */
public static final short NSAP = 22;
/** Reverse NSAP address (deprecated) */
public static final short NSAP_PTR = 23;
/** Signature */
public static final short SIG = 24;
/** Key */
public static final short KEY = 25;
/** X.400 mail mapping */
public static final short PX = 26;
/** Geographical position (withdrawn) */
public static final short GPOS = 27;
/** IPv6 address (old) */
public static final short AAAA = 28;
/** Location */
public static final short LOC = 29;
/** Next valid name in zone */
public static final short NXT = 30;
/** Endpoint identifier */
public static final short EID = 31;
/** Nimrod locator */
public static final short NIMLOC = 32;
/** Server selection */
public static final short SRV = 33;
/** ATM address */
public static final short ATMA = 34;
/** Naming authority pointer */
public static final short NAPTR = 35;
/** Key exchange */
public static final short KX = 36;
/** Certificate */
public static final short CERT = 37;
/** IPv6 address */
public static final short A6 = 38;
/** Non-terminal name redirection */
public static final short DNAME = 39;
/** Options - contains EDNS metadata */
public static final short OPT = 249;
/** Transaction signature */
public static final short TSIG = 250;
/** Incremental zone transfer */
public static final short IXFR = 251;
/** Zone transfer */
public static final short AXFR = 252;
/** Transfer mailbox records */
public static final short MAILB = 253;
/** Transfer mail agent records */
public static final short MAILA = 254;
/** Matches any type */
public static final short ANY = 255;
/** Address */
static {
types.put2(A, "A");
types.put2(NS, "NS");
types.put2(MD, "MD");
types.put2(MF, "MF");
types.put2(CNAME, "CNAME");
types.put2(SOA, "SOA");
types.put2(MB, "MB");
types.put2(MG, "MG");
types.put2(MR, "MR");
types.put2(NULL, "NULL");
types.put2(WKS, "WKS");
types.put2(PTR, "PTR");
types.put2(HINFO, "HINFO");
types.put2(MINFO, "MINFO");
types.put2(MX, "MX");
types.put2(TXT, "TXT");
types.put2(RP, "RP");
types.put2(AFSDB, "AFSDB");
types.put2(X25, "X25");
types.put2(ISDN, "ISDN");
types.put2(RT, "RT");
types.put2(NSAP, "NSAP");
types.put2(NSAP_PTR, "NSAP_PTR");
types.put2(SIG, "SIG");
types.put2(KEY, "KEY");
types.put2(PX, "PX");
types.put2(GPOS, "GPOS");
types.put2(AAAA, "AAAA");
types.put2(LOC, "LOC");
types.put2(NXT, "NXT");
types.put2(EID, "EID");
types.put2(NIMLOC, "NIMLOC");
types.put2(SRV, "SRV");
types.put2(ATMA, "ATMA");
types.put2(NAPTR, "NAPTR");
types.put2(KX, "KX");
types.put2(CERT, "CERT");
types.put2(A6, "A6");
types.put2(DNAME, "DNAME");
types.put2(OPT, "OPT");
types.put2(TSIG, "TSIG");
types.put2(IXFR, "IXFR");
types.put2(AXFR, "AXFR");
types.put2(MAILB, "MAILB");
types.put2(MAILA, "MAILA");
types.put2(ANY, "ANY");
}
private
Type() {
}
/** Converts a numeric Type into a String */
public static String
string(int i) {
String s = types.getString(i);
return (s != null) ? s : new Integer(i).toString();
}
/** Converts a String representation of an Type into its numeric value */
public static short
value(String s) {
short i = (short) types.getValue(s.toUpperCase());
if (i >= 0)
return i;
try {
return Short.parseShort(s);
}
catch (Exception e) {
return (-1);
}
}
/** Is this type valid for a record (a non-meta type)? */
public static boolean
isRR(int type) {
return (type > 0 && type < 128);
}
}
|
package com.thindeck.dynamo;
import com.amazonaws.services.dynamodbv2.model.Select;
import com.google.common.base.Function;
import com.google.common.collect.Iterables;
import com.jcabi.aspects.Immutable;
import com.jcabi.dynamo.Attributes;
import com.jcabi.dynamo.Conditions;
import com.jcabi.dynamo.Item;
import com.jcabi.dynamo.QueryValve;
import com.jcabi.dynamo.Region;
import com.thindeck.api.Repo;
import com.thindeck.api.Task;
import com.thindeck.api.Tasks;
import java.io.IOException;
import java.util.Map;
import java.util.UUID;
import lombok.EqualsAndHashCode;
import lombok.ToString;
/**
* Dynamo implementation of {@link Tasks}.
*
* @author Paul Polishchuk (ppol@yua.fm)
* @version $Id$
* @since 0.5
* @todo #406:30min Implement open method.
*/
@Immutable
@ToString
@EqualsAndHashCode
public final class DyTasks implements Tasks {
/**
* Region we're in.
*/
private final transient Region region;
/**
* Repo we're in.
*/
private final transient Repo repo;
/**
* Constructor.
* @param rgn Region
* @param rpo Repo
*/
public DyTasks(final Region rgn, final Repo rpo) {
this.region = rgn;
this.repo = rpo;
}
@Override
public Task get(final long number) {
return new DyTask(
this.region.table(DyTask.TBL)
.frame()
.through(
new QueryValve().withLimit(1)
)
.where(
new Conditions().with(
DyTask.ATTR_ID,
Conditions.equalTo(String.valueOf(number))
).with(
DyTask.ATTR_REPO_URN,
Conditions.equalTo(this.repo.name())
)
).iterator().next()
);
}
@Override
public Iterable<Task> open() {
throw new UnsupportedOperationException("#open");
}
@Override
public Iterable<Task> all() {
return Iterables.transform(
this.region.table(DyTask.TBL)
.frame()
.through(
new QueryValve().withConsistentRead(false)
.withSelect(Select.ALL_PROJECTED_ATTRIBUTES)
),
new Function<Item, Task>() {
@Override
public Task apply(final Item input) {
return new DyTask(input);
}
}
);
}
@Override
public Task add(final String command, final Map<String, String> args) {
try {
return new DyTask(
this.region.table(DyTask.TBL)
.put(new Attributes()
.with(DyTask.ATTR_ID, UUID.randomUUID())
.with(
DyTask.ATTR_REPO_URN,
this.repo.name()
)
.with(DyTask.ATTR_COMM, command)
.with(this.toAttributes(args))
)
);
} catch (final IOException ex) {
throw new IllegalStateException(ex);
}
}
/**
* Map to {@link com.jcabi.dynamo.Attributes}.
* @param map Map
* @return Attributes
*/
private Attributes toAttributes(final Map<String, String> map) {
final Attributes attributes = new Attributes();
if (map != null) {
for (final Map.Entry<String, String> entry : map.entrySet()) {
attributes.with(entry.getKey(), entry.getValue());
}
}
return attributes;
}
}
|
package org.xbill.DNS;
import java.io.*;
import java.util.*;
/**
* A DNS Zone. This encapsulates all data related to a Zone, and provides
* convenient lookup methods.
*
* @author Brian Wellington
*/
public class Zone extends NameSet {
class AXFRIterator implements Iterator {
private Iterator znames;
private Name currentName;
private Object [] current;
int count;
boolean sentFirstSOA, sentNS, sentOrigin, sentLastSOA;
AXFRIterator() {
znames = names();
}
public boolean
hasNext() {
return (!sentLastSOA);
}
public Object
next() {
if (sentLastSOA)
return null;
if (!sentFirstSOA) {
sentFirstSOA = true;
return (RRset) findExactSet(origin, Type.SOA);
}
if (!sentNS) {
sentNS = true;
return getNS();
}
if (!sentOrigin) {
if (currentName == null) {
currentName = getOrigin();
current = findExactSets(currentName);
count = 0;
}
while (count < current.length) {
RRset rrset = (RRset) current[count];
if (rrset.getType() != Type.SOA &&
rrset.getType() != Type.NS)
return current[count++];
count++;
}
current = null;
sentOrigin = true;
}
if (current != null && count < current.length)
return current[count++];
while (znames.hasNext()) {
Name currentName = (Name) znames.next();
if (currentName.equals(getOrigin()))
continue;
current = findExactSets(currentName);
count = 0;
if (count < current.length)
return current[count++];
}
sentLastSOA = true;
RRset rrset = new RRset();
rrset.addRR(getSOA());
return rrset;
}
public void
remove() {
throw new UnsupportedOperationException();
}
}
/** A primary zone */
public static final int PRIMARY = 1;
/** A secondary zone */
public static final int SECONDARY = 2;
private int type;
private Name origin;
private short dclass = DClass.IN;
private RRset NS;
private SOARecord SOA;
private boolean hasWild;
private void
validate() throws IOException {
RRset rrset = (RRset) findExactSet(origin, Type.SOA);
if (rrset == null || rrset.size() != 1)
throw new IOException(origin +
": exactly 1 SOA must be specified");
Iterator it = rrset.rrs();
SOA = (SOARecord) it.next();
NS = (RRset) findExactSet(origin, Type.NS);
if (NS == null)
throw new IOException(origin + ": no NS set specified");
}
private final void
maybeAddRecord(Record record, Cache cache, Object source) throws IOException {
int type = record.getType();
Name name = record.getName();
if (type == Type.SOA) {
if (!name.equals(origin))
throw new IOException("SOA owner " + name +
" does not match zone origin " +
origin);
else {
setOrigin(origin);
dclass = record.getDClass();
}
}
if (origin == null && type != Type.SOA)
throw new IOException("non-SOA record seen at " +
name + " with no origin set");
if (name.subdomain(origin))
addRecord(record);
else if (cache != null)
cache.addRecord(record, Credibility.GLUE, source);
}
/**
* Creates a Zone from the records in the specified master file. All
* records that do not belong in the Zone are added to the specified Cache.
* @see Cache
* @see Master
*/
public
Zone(String file, Cache cache, Name initialOrigin) throws IOException {
super(false);
Master m = new Master(file, initialOrigin);
Record record;
origin = initialOrigin;
while ((record = m.nextRecord()) != null)
maybeAddRecord(record, cache, file);
validate();
}
/**
* Creates a Zone from an array of records. All records that do not belong
* in the Zone are added to the specified Cache.
* @see Cache
* @see Master
*/
public
Zone(Record [] records, Cache cache, Name initialOrigin) throws IOException {
super(false);
origin = initialOrigin;
for (int i = 0; i < records.length; i++) {
maybeAddRecord(records[i], cache, records);
}
validate();
}
/**
* Creates a Zone from the records in the specified master file. All
* records that do not belong in the Zone are added to the specified Cache.
* @see Cache
* @see Master
*/
public
Zone(String file, Cache cache) throws IOException {
this(file, cache, null);
}
/**
* Creates a Zone by performing a zone transfer to the specified host. All
* records that do not belong in the Zone are added to the specified Cache.
* @see Cache
* @see Master
*/
public
Zone(Name zone, short dclass, String remote, Cache cache) throws IOException {
super(false);
origin = zone;
this.dclass = dclass;
type = SECONDARY;
Resolver res = new SimpleResolver(remote);
Record rec = Record.newRecord(zone, Type.AXFR, dclass);
Message query = Message.newQuery(rec);
Message response = res.send(query);
short rcode = response.getHeader().getRcode();
if (rcode != Rcode.NOERROR)
throw new IOException("AXFR failed: " + Rcode.string(rcode));
Record [] recs = response.getSectionArray(Section.ANSWER);
for (int i = 0; i < recs.length; i++) {
if (!recs[i].getName().subdomain(origin)) {
if (Options.check("verbose"))
System.err.println(recs[i].getName() +
"is not in zone " + origin);
continue;
}
addRecord(recs[i]);
}
if (cache != null) {
recs = response.getSectionArray(Section.ADDITIONAL);
for (int i = 0; i < recs.length; i++)
cache.addRecord(recs[i], Credibility.GLUE, recs);
}
validate();
}
/** Returns the Zone's origin */
public Name
getOrigin() {
return origin;
}
/** Returns the Zone origin's NS records */
public RRset
getNS() {
return NS;
}
/** Returns the Zone's SOA record */
public SOARecord
getSOA() {
return SOA;
}
/** Returns the Zone's class */
public short
getDClass() {
return dclass;
}
/**
* Looks up Records in the Zone. This follows CNAMEs and wildcards.
* @param name The name to look up
* @param type The type to look up
* @return A SetResponse object
* @see SetResponse
*/
public SetResponse
findRecords(Name name, short type) {
SetResponse zr = null;
Object o = lookup(name, type);
if (o == null) {
/* The name does not exist */
if (name.isWild() || !hasWild)
return SetResponse.ofType(SetResponse.NXDOMAIN);
int labels = name.labels() - origin.labels();
SetResponse sr;
Name tname = name;
do {
sr = findRecords(tname.wild(1), type);
if (!sr.isNXDOMAIN())
return sr;
tname = new Name(tname, 1);
} while (labels
return SetResponse.ofType(SetResponse.NXDOMAIN);
} else if (o == NXRRSET) {
/* The name exists but the type does not. */
return SetResponse.ofType(SetResponse.NXRRSET);
}
Object [] objects;
RRset rrset;
if (o instanceof RRset) {
objects = null;
rrset = (RRset) o;
}
else {
objects = (Object []) o;
rrset = (RRset) objects[0];
}
if (name.equals(rrset.getName())) {
if (type != Type.CNAME && type != Type.ANY &&
rrset.getType() == Type.CNAME)
zr = new SetResponse(SetResponse.CNAME, rrset);
else if (rrset.getType() == Type.NS &&
!name.equals(origin))
zr = new SetResponse(SetResponse.DELEGATION, rrset);
else {
zr = new SetResponse(SetResponse.SUCCESSFUL);
zr.addRRset(rrset);
if (objects != null) {
for (int i = 1; i < objects.length; i++)
zr.addRRset((RRset)objects[i]);
}
}
} else {
if (rrset.getType() == Type.CNAME)
zr = SetResponse.ofType(SetResponse.NXDOMAIN);
else if (rrset.getType() == Type.DNAME)
zr = new SetResponse(SetResponse.DNAME, rrset);
else if (rrset.getType() == Type.NS)
zr = new SetResponse(SetResponse.DELEGATION, rrset);
}
return zr;
}
/**
* Looks up Records in the zone, finding exact matches only.
* @param name The name to look up
* @param type The type to look up
* @return The matching RRset
* @see RRset
*/
public RRset
findExactMatch(Name name, short type) {
return (RRset) findExactSet(name, type);
}
/**
* Adds a record to the Zone
* @param r The record to be added
* @see Record
*/
public void
addRecord(Record r) {
Name name = r.getName();
short type = r.getRRsetType();
RRset rrset = (RRset) findExactSet (name, type);
if (rrset == null)
addSet(name, type, rrset = new RRset());
rrset.addRR(r);
}
/**
* Adds a set associated with a name/type. The data contained in the
* set is abstract.
*/
protected void
addSet(Name name, short type, TypedObject set) {
if (!hasWild && name.isWild())
hasWild = true;
super.addSet(name, type, set);
}
/**
* Removes a record from the Zone
* @param r The record to be removed
* @see Record
*/
public void
removeRecord(Record r) {
Name name = r.getName();
short type = r.getRRsetType();
RRset rrset = (RRset) findExactSet (name, type);
if (rrset != null) {
rrset.deleteRR(r);
if (rrset.size() == 0)
removeSet(name, type, rrset);
}
}
/**
* Returns an Iterator containing the RRsets of the zone that can be used
* to construct an AXFR.
*/
public Iterator
AXFR() {
return new AXFRIterator();
}
/**
* Returns the contents of a Zone in master file format.
*/
public String
toMasterFile() {
Iterator znames = names();
StringBuffer sb = new StringBuffer();
while (znames.hasNext()) {
Name name = (Name) znames.next();
Object [] sets = findExactSets(name);
for (int i = 0; i < sets.length; i++) {
RRset rrset = (RRset) sets[i];
Iterator it = rrset.rrs();
while (it.hasNext())
sb.append(it.next() + "\n");
it = rrset.sigs();
while (it.hasNext())
sb.append(it.next() + "\n");
}
}
return sb.toString();
}
}
|
package de.jformchecker;
import java.util.Map;
import de.jformchecker.criteria.Criteria;
import de.jformchecker.criteria.MaxLength;
import de.jformchecker.message.MessageSource;
import de.jformchecker.message.MinimalMessageSource;
import de.jformchecker.request.Request;
import de.jformchecker.request.SessionGet;
import de.jformchecker.request.SessionSet;
import de.jformchecker.themes.BasicFormBuilder;
import de.jformchecker.validator.DefaultValidator;
import de.jformchecker.validator.Validator;
/**
* FormChecker handles the initialisation, error- and submit status. This object
* should be stored to be accessed from the template-system.
*/
public class FormChecker {
Request req;
boolean firstRun = true;
boolean isValid = true;
FormCheckerForm form = null;
Validator validator = new DefaultValidator();
@Deprecated
String id;
int defaultMaxLenElements = 1000; // override this for each element, if you
// want longer vals!
FormCheckerConfig config;
private String formAction = "
// holds temporaryly config-infos while construction-process of fc
private GenericFormBuilder tempFormBuilder;
private MessageSource tempProperties;
public static final String SUBMIT_KEY = "submitted";
public static final String SUBMIT_VALUE_PREFIX = "FORMCHECKER_";
/**
* Deprecated: Put id into the FormcheckerForm and use build(request, form) or
* Formchecker(request)
*
* @param _id
* @param request
*/
@Deprecated
public FormChecker(String _id, Request request) {
id = _id;
req = request;
}
public FormChecker(Request request) {
req = request;
}
/**
* Deprecated: Use build(Request _req, FormCheckerForm form) and put id into the FormCheckerForm
* @param _id
* @param _req
* @param form
* @return
*/
@Deprecated
public static FormChecker build(String _id, Request _req, FormCheckerForm form) {
FormChecker fc = new FormChecker(_id, _req);
fc.id = _id;
fc.addForm(form);
return fc;
}
public static FormChecker build(Request _req, FormCheckerForm form) {
FormChecker fc = new FormChecker(_req);
fc.addForm(form);
return fc;
}
public FormChecker setProtectAgainstCSRF(SessionGet sessionGet, SessionSet sessionSet) {
if (form == null) {
throw new IllegalArgumentException("Set the FormcheckerForm BEFORE calling setAgainstCSRF");
}
form.setProtectedAgainstCSRF(true);
form.setSessionGet(sessionGet);
form.setSessionSet(sessionSet);
return this;
}
public FormChecker setConfig(FormCheckerConfig config) {
this.config = config;
return this;
}
public boolean isValid() {
return isValid;
}
public boolean isValidAndNotFirstRun() {
return isValid && !firstRun;
}
public FormCheckerForm getForm() {
return form;
}
public GenericFormBuilder getFormBuilder() {
return config.getFormBuilder();
}
public FormChecker setFormBuilder(GenericFormBuilder formBuilder) {
this.tempFormBuilder = formBuilder;
return this;
}
public FormChecker setProperties(MessageSource properties) {
this.tempProperties = properties;
return this;
}
public static String getHelpBlockId(FormCheckerElement elem) {
return "helpBlock_" + elem.getName();
}
public String getValue(String elementName) {
return form.getElement(elementName).getValue();
}
public String getSubmitTag() {
return config.getFormBuilder().getSubmittedTag(form.getId());
}
public String getLabelTag(String elementName) {
return config.getFormBuilder().getLabelForElement(form.getElement(elementName), new TagAttributes(), firstRun);
}
public String getLabelTag(String elementName, Map<String, String> map) {
return config.getFormBuilder().getLabelForElement(form.getElement(elementName), new TagAttributes(map),
firstRun);
}
public void setFormAction(String formAction) {
this.formAction = formAction;
}
private void prepareElement(FormCheckerElement element) {
element.setFormChecker(this);
// check, if maxLen is set. If not, add default-max-len
// defaultMaxLenElements;
boolean maxLenAvail = false;
for (Criterion criterion : element.getCriteria()) {
if (criterion instanceof MaxLength) {
maxLenAvail = true;
}
}
if (!maxLenAvail) {
element.getCriteria().add(Criteria.maxLength(defaultMaxLenElements));
}
}
public void addForm(FormCheckerForm form) {
this.form = form;
if (id != null) { // Internal id overrides id from form
form.setId(id);
}
}
private String getGenericForm() {
return config.getFormBuilder().generateGenericForm(formAction, form.elements, firstRun, form, req, config);
}
// TODO: is neeeded?
public String getLabelForElement(FormCheckerElement e, Map<String, String> attribs) {
return config.getFormBuilder().getLabelForElement(e, new TagAttributes(attribs), firstRun);
}
public FormChecker run() {
setupConfig();
sortTabIndexes();
checkIfFirstRun();
initForm();
// process and validate each field
for (FormCheckerElement elem : form.getElements()) {
elem.init(req, firstRun, validator);
if (!elem.isValid()) {
isValid = false;
}
}
// validate the complete form
for (FormValidator formValidator : form.getValidators()) {
formValidator.validate(form);
}
return this;
}
private void initForm() {
// init form
form.setMessageSource(this.getConfig().getProperties());
form.init();
for (FormCheckerElement element : form.getElements()) {
prepareElement(element);
}
}
/**
* set up the config-object for formchecker (handles absence of properties
* and formBuider)
*/
private void setupConfig() {
if (config == null) {
if (tempFormBuilder == null) {
tempFormBuilder = new BasicFormBuilder();
}
if (tempProperties == null) {
tempProperties = new MinimalMessageSource();
}
config = new FormCheckerConfig(tempProperties, tempFormBuilder);
}
}
// resort tab-indexes
private void sortTabIndexes() {
int tabIndex = 100;
for (FormCheckerElement elem : form.getElements()) {
elem.setTabIndex(tabIndex);
tabIndex = elem.getLastTabIndex();
tabIndex++;
}
}
private void checkIfFirstRun() {
if ((FormChecker.SUBMIT_VALUE_PREFIX + form.getId()).equals(req.getParameter(FormChecker.SUBMIT_KEY))) {
firstRun = false;
}
}
public String getCompleteForm() {
return this.getGenericForm();
}
public FormCheckerConfig getConfig() {
return config;
}
}
|
package filter.expression;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import backend.resource.*;
import filter.ParseException;
import util.Utility;
import backend.interfaces.IModel;
import filter.MetaQualifierInfo;
import filter.QualifierApplicationException;
public class Qualifier implements FilterExpression {
public static final Qualifier EMPTY = new Qualifier(QualifierType.EMPTY, "");
public static final Qualifier FALSE = new Qualifier(QualifierType.FALSE, "");
private final QualifierType type;
// Only one of these will be present at a time
private Optional<DateRange> dateRange = Optional.empty();
private Optional<String> content = Optional.empty();
private Optional<LocalDate> date = Optional.empty();
private Optional<NumberRange> numberRange = Optional.empty();
private Optional<Integer> number = Optional.empty();
private List<SortKey> sortKeys = new ArrayList<>();
// Copy constructor
public Qualifier(Qualifier other) {
this.type = other.getType();
if (other.getDateRange().isPresent()) {
this.dateRange = other.getDateRange();
} else if (other.getDate().isPresent()) {
this.date = other.getDate();
} else if (other.getContent().isPresent()) {
this.content = other.getContent();
} else if (other.getNumberRange().isPresent()) {
this.numberRange = other.getNumberRange();
} else if (other.getNumber().isPresent()) {
this.number = other.getNumber();
} else if (!other.sortKeys.isEmpty()) {
this.sortKeys = new ArrayList<>(other.sortKeys);
} else {
assert false : "Unrecognised content type! You may have forgotten to add it above";
}
}
public Qualifier(QualifierType type, String content) {
this.type = type;
this.content = Optional.of(content);
}
public Qualifier(QualifierType type, NumberRange numberRange) {
this.type = type;
this.numberRange = Optional.of(numberRange);
}
public Qualifier(QualifierType type, DateRange dateRange) {
this.type = type;
this.dateRange = Optional.of(dateRange);
}
public Qualifier(QualifierType type, LocalDate date) {
this.type = type;
this.date = Optional.of(date);
}
public Qualifier(QualifierType type, int number) {
this.type = type;
this.number = Optional.of(number);
}
public Qualifier(QualifierType type, List<SortKey> keys) {
this.type = type;
this.sortKeys = new ArrayList<>(keys);
}
public static FilterExpression replaceMilestoneAliases(IModel model, FilterExpression expr) {
List<String> repoIds = getMetaQualifierContent(expr, QualifierType.REPO).stream()
.map(String::toLowerCase)
.collect(Collectors.toList());
if (repoIds.isEmpty()) {
repoIds.add(model.getDefaultRepo().toLowerCase());
}
List<TurboMilestone> milestonesOfReposInPanel = TurboMilestone.getMilestonesOfRepos(model.getMilestones(), repoIds);
List<TurboMilestone> milestonesWithinAliasRange = getMilestonesWithinAliasRange(milestonesOfReposInPanel);
Map<Integer, TurboMilestone> milestoneAliasIndex = getMilestoneAliasIndex(milestonesWithinAliasRange);
if (milestoneAliasIndex.isEmpty()) {
return expr;
}
return expr.map(q -> {
if (Qualifier.isMilestoneQualifier(q)) {
return q.convertMilestoneAliasQualifier(milestoneAliasIndex);
} else {
return q;
}
});
}
/**
* Helper function for testing a filter expression against an issue.
* Ensures that meta-qualifiers are taken care of.
* Should always be used over isSatisfiedBy.
*/
public static boolean process(IModel model, FilterExpression expr, TurboIssue issue) {
FilterExpression exprWithNormalQualifiers = expr.filter(Qualifier::shouldNotBeStripped);
List<Qualifier> metaQualifiers = expr.find(Qualifier::isMetaQualifier);
// Preprocessing for repo qualifier
boolean containsRepoQualifier = metaQualifiers.stream()
.map(Qualifier::getType)
.collect(Collectors.toList())
.contains(QualifierType.REPO);
if (!containsRepoQualifier) {
exprWithNormalQualifiers = new Conjunction(
new Qualifier(QualifierType.REPO, model.getDefaultRepo()),
exprWithNormalQualifiers);
}
return exprWithNormalQualifiers.isSatisfiedBy(model, issue, new MetaQualifierInfo(metaQualifiers));
}
/**
* Get all milestones that can be aliased with current-[n] to current+[n]
*/
private static List<TurboMilestone> getMilestonesWithinAliasRange(List<TurboMilestone> milestonesOfReposInPanel) {
List<TurboMilestone> milestones = new ArrayList<>();
// add milestones with due date first
milestones.addAll(milestonesOfReposInPanel.stream()
.filter(ms -> ms.getDueDate().isPresent())
.collect(Collectors.toList()));
// Special case: if there is only one open milestone, it should be included regardless of whether
// it has due date or not.
// In this case, if it is not included already (the open milestone does not
// have due date), add it to the milestone list.
List<TurboMilestone> openMilestones = TurboMilestone.getOpenMilestones(milestonesOfReposInPanel);
if (openMilestones.size() == 1) {
TurboMilestone openMilestone = openMilestones.get(0);
boolean hasDueDate = openMilestone.getDueDate().isPresent();
if (!hasDueDate) {
milestones.add(openMilestone);
}
}
return milestones;
}
/**
* Returns a map where the key denotes offset from "current" milestone.
* i.e. 0 for "current" milestone, -1 for "current-1" milestone, etc.
*/
private static Map<Integer, TurboMilestone> getMilestoneAliasIndex(List<TurboMilestone> milestones) {
List<TurboMilestone> sortedMilestones = TurboMilestone.getSortedMilestonesByDueDate(milestones);
Optional<Integer> currentMilestoneIndex = getCurrentMilestoneIndex(sortedMilestones);
return IntStream
.range(0, sortedMilestones.size())
.boxed()
.collect(Collectors.toMap(
i -> i - currentMilestoneIndex.get(),
i -> sortedMilestones.get(i)));
}
private static Optional<Integer> getCurrentMilestoneIndex(List<TurboMilestone> milestones) {
if (milestones.isEmpty()) {
return Optional.empty();
}
long openMilestonesCount = milestones.stream().filter(TurboMilestone::isOpen).count();
if (openMilestonesCount == 1) {
return IntStream
.range(0, milestones.size())
.boxed()
.filter(i -> milestones.get(i).isOpen())
.findFirst();
} else {
// Look for the first milestone in the (sorted) list that is both open and ongoing.
int currentIndex = 0;
for (TurboMilestone checker : milestones) {
if (checker.isOpen() && checker.isOngoing()) {
return Optional.of(currentIndex);
}
currentIndex++;
}
// if no open and ongoing milestone, set current as one after last milestone
// - this means that no such milestone, which will return no issue
return Optional.of(milestones.size());
}
}
public static HashSet<String> getMetaQualifierContent(FilterExpression expr, QualifierType qualifierType) {
HashSet<String> contents = new HashSet<>();
List<Qualifier> panelMetaQualifiers = expr.find(Qualifier::isMetaQualifier);
panelMetaQualifiers.forEach(metaQualifier -> {
if (metaQualifier.getType().equals(qualifierType) && metaQualifier.getContent().isPresent()) {
contents.add(metaQualifier.getContent().get());
}
});
return contents;
}
private static LocalDateTime currentTime = null;
private static LocalDateTime getCurrentTime() {
if (currentTime == null) {
return LocalDateTime.now();
} else {
return currentTime;
}
}
/**
* For testing. Stubs the current time so time-related qualifiers work properly.
*/
public static void setCurrentTime(LocalDateTime dateTime) {
currentTime = dateTime;
}
@Override
public boolean isEmpty() {
return type == QualifierType.EMPTY;
}
public boolean isFalse() {
return type == QualifierType.FALSE;
}
@Override
public boolean isSatisfiedBy(IModel model, TurboIssue issue, MetaQualifierInfo info) {
assert type != null;
// The empty qualifier is satisfied by anything
if (isEmpty()) return true;
// The false qualifier is satisfied by nothing
if (isFalse()) return false;
switch (type) {
case ID:
return idSatisfies(issue);
case KEYWORD:
return keywordSatisfies(issue, info);
case TITLE:
return titleSatisfies(issue);
case DESCRIPTION:
return bodySatisfies(issue);
case MILESTONE:
return milestoneSatisfies(model, issue);
case LABEL:
return labelsSatisfy(model, issue);
case AUTHOR:
return authorSatisfies(issue);
case ASSIGNEE:
return assigneeSatisfies(model, issue);
case INVOLVES:
return involvesSatisfies(model, issue);
case TYPE:
return typeSatisfies(issue);
case STATE:
return stateSatisfies(issue);
case HAS:
return satisfiesHasConditions(issue);
case NO:
return satisfiesNoConditions(issue);
case IS:
return satisfiesIsConditions(issue);
case CREATED:
return satisfiesCreationDate(issue);
case UPDATED:
return satisfiesUpdatedHours(issue);
case REPO:
return satisfiesRepo(issue);
default:
assert false : "Missing case for " + type;
return false;
}
}
@Override
public void applyTo(TurboIssue issue, IModel model) throws QualifierApplicationException {
assert type != null && content != null;
// The empty qualifier should not be applied to anything
assert !isEmpty();
// The false qualifier should not be applied to anything
assert !isFalse();
switch (type) {
case TITLE:
case DESCRIPTION:
case KEYWORD:
throw new QualifierApplicationException("Unnecessary filter: issue text cannot be changed by dragging");
case ID:
throw new QualifierApplicationException("Unnecessary filter: id is immutable");
case CREATED:
throw new QualifierApplicationException("Unnecessary filter: cannot change issue creation date");
case HAS:
case NO:
case IS:
throw new QualifierApplicationException("Ambiguous filter: " + type);
case MILESTONE:
applyMilestone(issue, model);
break;
case LABEL:
applyLabel(issue, model);
break;
case ASSIGNEE:
applyAssignee(issue, model);
break;
case AUTHOR:
throw new QualifierApplicationException("Unnecessary filter: cannot change author of issue");
case INVOLVES:
throw new QualifierApplicationException("Ambiguous filter: cannot change users involved with issue");
case STATE:
applyState(issue);
break;
default:
assert false : "Missing case for " + type;
break;
}
}
@Override
public boolean canBeAppliedToIssue() {
return true;
}
@Override
public List<QualifierType> getQualifierTypes() {
return new ArrayList<>(Arrays.asList(type));
}
@Override
public FilterExpression filter(Predicate<Qualifier> pred) {
if (pred.test(this)) {
return new Qualifier(this);
} else {
return EMPTY;
}
}
@Override
public List<Qualifier> find(Predicate<Qualifier> pred) {
if (pred.test(this)) {
ArrayList<Qualifier> result = new ArrayList<>();
result.add(this);
return result;
} else {
return new ArrayList<>();
}
}
@Override
public FilterExpression map(Function<Qualifier, Qualifier> func) {
return func.apply(this);
}
/**
* This method is used to serialise qualifiers. Thus whatever form returned
* should be syntactically valid.
*/
@Override
public String toString() {
if (this.isEmpty()) {
return "";
} else if (content.isPresent()) {
String quotedContent = content.get();
if (quotedContent.contains(" ")) {
quotedContent = "\"" + quotedContent + "\"";
}
if (type == QualifierType.KEYWORD) {
return quotedContent;
} else {
return type + ":" + quotedContent;
}
} else if (date.isPresent()) {
return type + ":" + date.get().toString();
} else if (dateRange.isPresent()) {
return type + ":" + dateRange.get().toString();
} else if (!sortKeys.isEmpty()) {
return type + ":" + sortKeys.stream().map(SortKey::toString).collect(Collectors.joining(","));
} else if (numberRange.isPresent()) {
return type + ":" + numberRange.get().toString();
} else if (number.isPresent()) {
return type + ":" + number.get().toString();
} else {
assert false : "Should not happen";
return "";
}
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((type == null) ? 0 : type.hashCode());
result = prime * result + ((content == null) ? 0 : content.hashCode());
result = prime * result + ((date == null) ? 0 : date.hashCode());
result = prime * result + ((dateRange == null) ? 0 : dateRange.hashCode());
result = prime * result + ((number == null) ? 0 : number.hashCode());
result = prime * result + ((numberRange == null) ? 0 : numberRange.hashCode());
result = prime * result + ((sortKeys == null) ? 0 : sortKeys.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
Qualifier other = (Qualifier) obj;
return content.equals(other.content) &&
date.equals(other.date) &&
dateRange.equals(other.dateRange) &&
number.equals(other.number) &&
numberRange.equals(other.numberRange) &&
sortKeys.equals(other.sortKeys) &&
type.equals(other.type);
}
private static boolean shouldNotBeStripped(Qualifier q) {
return !shouldBeStripped(q);
}
private static boolean shouldBeStripped(Qualifier q) {
switch (q.getType()) {
case IN:
case SORT:
case COUNT:
return true;
default:
return false;
}
}
public static boolean isMetaQualifier(Qualifier q) {
switch (q.getType()) {
case SORT:
case IN:
case REPO:
case COUNT:
return true;
default:
return isUpdatedQualifier(q);
}
}
public static boolean isMilestoneQualifier(Qualifier q) {
switch (q.getType()) {
case MILESTONE:
return true;
default:
return false;
}
}
public static boolean isUpdatedQualifier(Qualifier q) {
switch (q.getType()) {
case UPDATED:
return true;
default:
return false;
}
}
public static boolean hasUpdatedQualifier(FilterExpression expr) {
return !expr.find(Qualifier::isUpdatedQualifier).isEmpty();
}
public Comparator<TurboIssue> getCompoundSortComparator(IModel model, boolean isSortableByNonSelfUpdates) {
if (sortKeys.isEmpty()) {
return (a, b) -> 0;
}
return (a, b) -> {
for (SortKey key : sortKeys) {
Comparator<TurboIssue> comparator =
getSortComparator(model, key.key, key.inverted, isSortableByNonSelfUpdates);
int result = comparator.compare(a, b);
if (result != 0) {
return result;
}
}
return 0;
};
}
public static Comparator<TurboIssue> getSortComparator(IModel model,
String key,
boolean inverted,
boolean isSortableByNonSelfUpdates) {
Comparator<TurboIssue> comparator = (a, b) -> 0;
boolean isLabelGroup = false;
switch (key) {
case "comments":
comparator = (a, b) -> a.getCommentCount() - b.getCommentCount();
break;
case "repo":
comparator = (a, b) -> a.getRepoId().compareTo(b.getRepoId());
break;
case "updated":
case "date":
comparator = (a, b) -> a.getUpdatedAt().compareTo(b.getUpdatedAt());
break;
case "nonSelfUpdate":
if (isSortableByNonSelfUpdates) {
comparator = (a, b) ->
a.getMetadata().getNonSelfUpdatedAt().compareTo(b.getMetadata().getNonSelfUpdatedAt());
} else {
comparator = (a, b) -> a.getUpdatedAt().compareTo(b.getUpdatedAt());
}
break;
case "assignee":
case "as":
comparator = (a, b) -> {
Optional<String> aAssignee = a.getAssignee();
Optional<String> bAssignee = b.getAssignee();
if (!aAssignee.isPresent() && !bAssignee.isPresent()) {
return 0;
} else if (!aAssignee.isPresent()) {
return 1;
} else if (!bAssignee.isPresent()) {
return -1;
} else {
return aAssignee.get().compareTo(bAssignee.get());
}
};
break;
case "milestone":
case "m":
comparator = (a, b) -> {
Optional<TurboMilestone> aMilestone = model.getMilestoneOfIssue(a);
Optional<TurboMilestone> bMilestone = model.getMilestoneOfIssue(b);
if (!aMilestone.isPresent() && !bMilestone.isPresent()) {
return 0;
} else if (!aMilestone.isPresent()) {
return 1;
} else if (!bMilestone.isPresent()) {
return -1;
} else {
Optional<LocalDate> aDueDate = aMilestone.get().getDueDate();
Optional<LocalDate> bDueDate = bMilestone.get().getDueDate();
if (!aDueDate.isPresent() && !bDueDate.isPresent()) {
return 0;
} else if (!aDueDate.isPresent()) {
return 1;
} else if (!bDueDate.isPresent()) {
return -1;
} else {
return -(TurboMilestone.getDueDateComparator()
.compare(aMilestone.get(), bMilestone.get()));
}
}
};
break;
case "id":
comparator = (a, b) -> a.getId() - b.getId();
break;
case "state":
case "status":
case "s":
comparator = (a, b) -> Boolean.compare(b.isOpen(), a.isOpen());
break;
default:
// Doesn't match anything; assume it's a label group
isLabelGroup = true;
break;
}
if (isLabelGroup) {
// Has a different notion of inversion
return getLabelGroupComparator(model, key, inverted);
} else {
// Use default behaviour for inverting
if (!inverted) {
return comparator;
} else {
final Comparator<TurboIssue> finalComparator = comparator;
return (a, b) -> -finalComparator.compare(a, b);
}
}
}
public static Comparator<TurboIssue> getLabelGroupComparator(IModel model, String key, boolean inverted) {
// Strip trailing ., if any
final String group = key.replaceAll("\\.$", "");
return (a, b) -> {
// Matches labels belong to the given group
Predicate<TurboLabel> sameGroup = l ->
l.getGroup().isPresent() && l.getGroup().get().equals(group);
Comparator<TurboLabel> labelComparator = (x, y) -> x.getName().compareTo(y.getName());
List<TurboLabel> aLabels = model.getLabelsOfIssue(a, sameGroup);
List<TurboLabel> bLabels = model.getLabelsOfIssue(b, sameGroup);
Collections.sort(aLabels, labelComparator);
Collections.sort(bLabels, labelComparator);
// Put empty lists at the back
if (aLabels.isEmpty() && bLabels.isEmpty()) {
return 0;
} else if (aLabels.isEmpty()) {
// a is larger
return 1;
} else if (bLabels.isEmpty()) {
// b is larger
return -1;
}
// Compare lengths
int result = !inverted
? aLabels.size() - bLabels.size()
: bLabels.size() - aLabels.size();
if (result != 0) {
return result;
}
// Lexicographic label comparison
assert aLabels.size() == bLabels.size();
for (int i = 0; i < aLabels.size(); i++) {
result = !inverted
? labelComparator.compare(aLabels.get(i), bLabels.get(i))
: labelComparator.compare(bLabels.get(i), aLabels.get(i));
if (result != 0) {
return result;
}
}
return 0;
};
}
private boolean idSatisfies(TurboIssue issue) {
if (number.isPresent()) {
return issue.getId() == number.get();
} else if (numberRange.isPresent()) {
return numberRange.get().encloses(issue.getId());
}
return false;
}
private boolean satisfiesUpdatedHours(TurboIssue issue) {
NumberRange updatedRange;
if (numberRange.isPresent()) {
updatedRange = numberRange.get();
} else if (number.isPresent()) {
updatedRange = new NumberRange(null, number.get(), true);
} else {
return false;
}
LocalDateTime dateOfUpdate = issue.getUpdatedAt();
int hoursSinceUpdate = Utility.safeLongToInt(dateOfUpdate.until(getCurrentTime(), ChronoUnit.HOURS));
return updatedRange.encloses(hoursSinceUpdate);
}
private boolean satisfiesRepo(TurboIssue issue) {
if (!content.isPresent()) return false;
return issue.getRepoId().equalsIgnoreCase(content.get());
}
private boolean satisfiesCreationDate(TurboIssue issue) {
LocalDate creationDate = issue.getCreatedAt().toLocalDate();
if (date.isPresent()) {
return creationDate.isEqual(date.get());
} else if (dateRange.isPresent()) {
return dateRange.get().encloses(creationDate);
} else {
return false;
}
}
private boolean satisfiesHasConditions(TurboIssue issue) {
if (!content.isPresent()) return false;
switch (content.get()) {
case "label":
case "labels":
return issue.getLabels().size() > 0;
case "milestone":
case "milestones":
case "m":
assert issue.getMilestone() != null;
return issue.getMilestone().isPresent();
case "assignee":
case "assignees":
case "as":
assert issue.getAssignee() != null;
return issue.getAssignee().isPresent();
default:
return false;
}
}
private boolean satisfiesNoConditions(TurboIssue issue) {
return content.isPresent() && !satisfiesHasConditions(issue);
}
private boolean satisfiesIsConditions(TurboIssue issue) {
if (!content.isPresent()) return false;
switch (content.get()) {
case "open":
case "closed":
return stateSatisfies(issue);
case "pr":
case "issue":
return typeSatisfies(issue);
case "merged":
return issue.isPullRequest() && !issue.isOpen();
case "unmerged":
return issue.isPullRequest() && issue.isOpen();
case "read":
return issue.isCurrentlyRead();
case "unread":
return !issue.isCurrentlyRead();
default:
return false;
}
}
private boolean stateSatisfies(TurboIssue issue) {
if (!content.isPresent()) return false;
String content = this.content.get().toLowerCase();
if (content.contains("open")) {
return issue.isOpen();
} else if (content.contains("closed")) {
return !issue.isOpen();
} else {
return false;
}
}
private boolean assigneeSatisfies(IModel model, TurboIssue issue) {
if (!content.isPresent()) return false;
Optional<TurboUser> assignee = model.getAssigneeOfIssue(issue);
if (!assignee.isPresent()) return false;
String content = this.content.get().toLowerCase();
String login = assignee.get().getLoginName() == null ? "" : assignee.get().getLoginName().toLowerCase();
String name = assignee.get().getRealName() == null ? "" : assignee.get().getRealName().toLowerCase();
return login.contains(content) || name.contains(content);
}
private boolean authorSatisfies(TurboIssue issue) {
if (!content.isPresent()) return false;
String creator = issue.getCreator();
return creator.toLowerCase().contains(content.get().toLowerCase());
}
private boolean involvesSatisfies(IModel model, TurboIssue issue) {
return authorSatisfies(issue) || assigneeSatisfies(model, issue);
}
public static boolean labelMatches(String input, String candidate) {
// Make use of TurboLabel constructor to parse the input, avoiding duplication
TurboLabel inputLabel = new TurboLabel("", input.toLowerCase());
TurboLabel candidateLabel = new TurboLabel("", candidate.toLowerCase());
String group = "";
if (inputLabel.hasGroup()) {
group = inputLabel.getGroup().get();
}
String labelName = inputLabel.getName();
if (candidateLabel.hasGroup()) {
if (labelName.isEmpty()) {
// Check the group
if (candidateLabel.getGroup().get().contains(group)) {
return true;
}
} else {
if (candidateLabel.getGroup().get().contains(group)
&& candidateLabel.getName().contains(labelName)) {
return true;
}
}
} else {
// Check only the label name
if (group.isEmpty() && !labelName.isEmpty() && candidateLabel.getName().contains(labelName)) {
return true;
}
}
return false;
}
private boolean labelsSatisfy(IModel model, TurboIssue issue) {
if (!content.isPresent()) return false;
// A qualifier matches an issue if the issue is associated with some subset of the
// labels that the qualifier expresses. It should only reject an issue if the issue
// does not contain any labels it expresses, and not if the issue contains some label
// it does not express.
for (TurboLabel label : model.getLabelsOfIssue(issue)) {
if (labelMatches(content.get(), label.getActualName())) {
return true;
}
}
return false;
}
private boolean milestoneSatisfies(IModel model, TurboIssue issue) {
if (!content.isPresent()) return false;
Optional<TurboMilestone> milestone = model.getMilestoneOfIssue(issue);
if (!milestone.isPresent()) return false;
String contents = content.get().toLowerCase();
String title = milestone.get().getTitle().toLowerCase();
return title.contains(contents);
}
private boolean keywordSatisfies(TurboIssue issue, MetaQualifierInfo info) {
if (info.getIn().isPresent()) {
switch (info.getIn().get()) {
case "title":
return titleSatisfies(issue);
case "body":
case "desc":
case "description":
return bodySatisfies(issue);
default:
return false;
}
} else {
return titleSatisfies(issue) || bodySatisfies(issue);
}
}
private boolean bodySatisfies(TurboIssue issue) {
if (!content.isPresent()) return false;
return issue.getDescription().toLowerCase().contains(content.get().toLowerCase());
}
private boolean titleSatisfies(TurboIssue issue) {
if (!content.isPresent()) return false;
return issue.getTitle().toLowerCase().contains(content.get().toLowerCase());
}
private boolean typeSatisfies(TurboIssue issue) {
if (!content.isPresent()) return false;
String content = this.content.get().toLowerCase();
switch (content) {
case "issue":
return !issue.isPullRequest();
case "pr":
case "pullrequest":
return issue.isPullRequest();
default:
return false;
}
}
private void applyMilestone(TurboIssue issue, IModel model) throws QualifierApplicationException {
if (!content.isPresent()) {
throw new QualifierApplicationException("Name of milestone to apply required");
}
// Find milestones containing partial title
List<TurboMilestone> milestones = model.getMilestones().stream()
.filter(m -> m.getTitle().toLowerCase().contains(content.get().toLowerCase()))
.collect(Collectors.toList());
if (milestones.isEmpty()) {
throw new QualifierApplicationException("Invalid milestone " + content.get());
} else if (milestones.size() == 1) {
issue.setMilestone(milestones.get(0));
return;
}
// Find milestones containing exact title
milestones = model.getMilestones().stream()
.filter(m -> m.getTitle().toLowerCase().equals(content.get().toLowerCase()))
.collect(Collectors.toList());
if (milestones.isEmpty()) {
throw new QualifierApplicationException("Invalid milestone " + content.get());
} else if (milestones.size() == 1) {
issue.setMilestone(milestones.get(0));
return;
}
throw new QualifierApplicationException(
"Ambiguous filter: can apply any of the following milestones: " + milestones.toString());
}
private void applyLabel(TurboIssue issue, IModel model) throws QualifierApplicationException {
if (!content.isPresent()) {
throw new QualifierApplicationException("Name of label to apply required");
}
// Find labels containing the label name
List<TurboLabel> labels = model.getLabels().stream()
.filter(l -> l.getActualName().toLowerCase().contains(content.get().toLowerCase()))
.collect(Collectors.toList());
if (labels.isEmpty()) {
throw new QualifierApplicationException("Invalid label " + content.get());
} else if (labels.size() == 1) {
issue.addLabel(labels.get(0));
return;
}
// Find labels with the exact label name
labels = model.getLabels().stream()
.filter(l -> l.getActualName().toLowerCase().equals(content.get().toLowerCase()))
.collect(Collectors.toList());
if (labels.isEmpty()) {
throw new QualifierApplicationException("Invalid label " + content.get());
} else if (labels.size() == 1) {
issue.addLabel(labels.get(0));
return;
}
throw new QualifierApplicationException(
"Ambiguous filter: can apply any of the following labels: " + labels.toString());
}
private void applyAssignee(TurboIssue issue, IModel model) throws QualifierApplicationException {
if (!content.isPresent()) {
throw new QualifierApplicationException("Name of assignee to apply required");
}
// Find assignees containing partial name
List<TurboUser> assignees = model.getUsers().stream()
.filter(c -> c.getLoginName().toLowerCase().contains(content.get().toLowerCase()))
.collect(Collectors.toList());
if (assignees.isEmpty()) {
throw new QualifierApplicationException("Invalid user " + content.get());
} else if (assignees.size() == 1) {
issue.setAssignee(assignees.get(0));
return;
}
// Find assignees containing partial name
assignees = model.getUsers().stream()
.filter(c -> c.getLoginName().toLowerCase().equals(content.get().toLowerCase()))
.collect(Collectors.toList());
if (assignees.isEmpty()) {
throw new QualifierApplicationException("Invalid user " + content.get());
} else if (assignees.size() == 1) {
issue.setAssignee(assignees.get(0));
return;
}
throw new QualifierApplicationException(
"Ambiguous filter: can apply any of the following assignees: " + assignees.toString());
}
private void applyState(TurboIssue issue) throws QualifierApplicationException {
if (!content.isPresent()) {
throw new QualifierApplicationException("State to apply required");
}
if (content.get().toLowerCase().contains("open")) {
issue.setOpen(true);
} else if (content.get().toLowerCase().contains("closed")) {
issue.setOpen(false);
} else {
throw new QualifierApplicationException("Invalid state " + content.get());
}
}
public Optional<Integer> getNumber() {
return number;
}
public Optional<NumberRange> getNumberRange() {
return numberRange;
}
public Optional<DateRange> getDateRange() {
return dateRange;
}
public Optional<String> getContent() {
return content;
}
public Optional<LocalDate> getDate() {
return date;
}
public QualifierType getType() {
return type;
}
private Qualifier convertMilestoneAliasQualifier(Map<Integer, TurboMilestone> milestoneAliasIndex) {
if (!content.isPresent()) {
return Qualifier.EMPTY;
}
String contents = content.get();
String alias = contents;
Pattern aliasPattern = Pattern.compile("(curr(?:ent)?)(?:(\\+|-)(\\d+))?$");
Matcher aliasMatcher = aliasPattern.matcher(alias);
if (!aliasMatcher.find()) {
return this;
}
int offset = 0;
if (aliasMatcher.group(2) != null && aliasMatcher.group(3) != null) {
if (aliasMatcher.group(2).equals("+")) {
offset = Integer.parseInt(aliasMatcher.group(3));
} else {
offset = -Integer.parseInt(aliasMatcher.group(3));
}
}
// if out of milestone range, don't convert alias
if (!milestoneAliasIndex.containsKey(offset)) {
return Qualifier.FALSE;
}
contents = milestoneAliasIndex.get(offset).getTitle().toLowerCase();
return new Qualifier(type, contents);
}
/**
* Determines the count value to be taken from the count qualifier. Throw a ParseException if count
* qualifier is not valid.
*
* @param issueList Issue list obtained after filtering and sorting.
* @param filterExpr The filter expression of the particular panel.
* @return The valid count value in the qualifier or the issueList.size() by default
*/
public static int determineCount(List<TurboIssue> issueList, FilterExpression filterExpr) {
List<Qualifier> countQualifiers = filterExpr.find(Qualifier::isMetaQualifier).stream()
.filter(q -> q.getType() == QualifierType.COUNT)
.collect(Collectors.toList());
if (countQualifiers.isEmpty()) {
return issueList.size();
} else if (countQualifiers.size() > 1) {
throw new ParseException("More than one count qualifier");
} else if (!countQualifiers.get(0).getNumber().isPresent()) {
throw new ParseException("Count qualifier should be a number greater than or equal to 0");
} else {
return countQualifiers.get(0).getNumber().get();
}
}
}
|
package filter.expression;
import backend.interfaces.IModel;
import backend.resource.TurboIssue;
import backend.resource.TurboLabel;
import backend.resource.TurboMilestone;
import backend.resource.TurboUser;
import filter.MetaQualifierInfo;
import filter.QualifierApplicationException;
import util.Utility;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.function.BiConsumer;
import java.util.function.Predicate;
import java.util.stream.Collectors;
public class Qualifier implements FilterExpression {
public static final String UPDATED = "updated";
public static final String REPO = "repo";
public static final String SORT = "sort";
public static final Qualifier EMPTY = new Qualifier("", "");
private final String name;
// Only one of these will be present at a time
private Optional<DateRange> dateRange = Optional.empty();
private Optional<String> content = Optional.empty();
private Optional<LocalDate> date = Optional.empty();
private Optional<NumberRange> numberRange = Optional.empty();
private Optional<Integer> number = Optional.empty();
private List<SortKey> sortKeys = new ArrayList<>();
// Copy constructor
public Qualifier(Qualifier other) {
this.name = other.getName();
if (other.getDateRange().isPresent()) {
this.dateRange = other.getDateRange();
} else if (other.getDate().isPresent()) {
this.date = other.getDate();
} else if (other.getContent().isPresent()) {
this.content = other.getContent();
} else if (other.getNumberRange().isPresent()) {
this.numberRange = other.getNumberRange();
} else if (other.getNumber().isPresent()) {
this.number = other.getNumber();
} else if (!other.sortKeys.isEmpty()) {
this.sortKeys = new ArrayList<>(other.sortKeys);
} else {
assert false : "Unrecognised content type! You may have forgotten to add it above";
}
}
public Qualifier(String name, String content) {
this.name = name;
this.content = Optional.of(content);
}
public Qualifier(String name, NumberRange numberRange) {
this.name = name;
this.numberRange = Optional.of(numberRange);
}
public Qualifier(String name, DateRange dateRange) {
this.name = name;
this.dateRange = Optional.of(dateRange);
}
public Qualifier(String name, LocalDate date) {
this.name = name;
this.date = Optional.of(date);
}
public Qualifier(String name, int number) {
this.name = name;
this.number = Optional.of(number);
}
public Qualifier(String name, List<SortKey> keys) {
this.name = name;
this.sortKeys = new ArrayList<>(keys);
}
/**
* Helper function for testing a filter expression against an issue.
* Ensures that meta-qualifiers are taken care of.
* Should always be used over isSatisfiedBy.
*/
public static boolean process(IModel model, FilterExpression expr, TurboIssue issue) {
FilterExpression exprWithNormalQualifiers = expr.filter(Qualifier::shouldNotBeStripped);
List<Qualifier> metaQualifiers = expr.find(Qualifier::isMetaQualifier);
// Preprocessing for repo qualifier
boolean containsRepoQualifier = metaQualifiers.stream()
.map(Qualifier::getName)
.collect(Collectors.toList())
.contains("repo");
if (!containsRepoQualifier) {
exprWithNormalQualifiers = new Conjunction(
new Qualifier("repo", model.getDefaultRepo()),
exprWithNormalQualifiers);
}
return exprWithNormalQualifiers.isSatisfiedBy(model, issue, new MetaQualifierInfo(metaQualifiers));
}
public static void processMetaQualifierEffects(FilterExpression expr, BiConsumer<Qualifier, MetaQualifierInfo> callback) {
List<Qualifier> qualifiers = expr.find(Qualifier::isMetaQualifier);
MetaQualifierInfo info = new MetaQualifierInfo(qualifiers);
qualifiers.forEach(q -> callback.accept(q, info));
}
private static LocalDateTime currentTime = null;
private static LocalDateTime getCurrentTime() {
if (currentTime == null) {
return LocalDateTime.now();
} else {
return currentTime;
}
}
/**
* For testing. Stubs the current time so time-related qualifiers work properly.
*/
public static void setCurrentTime(LocalDateTime dateTime) {
currentTime = dateTime;
}
public boolean isEmptyQualifier() {
return name.isEmpty() && content.isPresent() && content.get().isEmpty();
}
@Override
public boolean isSatisfiedBy(IModel model, TurboIssue issue, MetaQualifierInfo info) {
assert name != null && content != null;
// The empty qualifier is satisfied by anything
if (isEmptyQualifier()) return true;
switch (name) {
case "id":
return idSatisfies(issue);
case "keyword":
return keywordSatisfies(issue, info);
case "title":
return titleSatisfies(issue);
case "body":
return bodySatisfies(issue);
case "milestone":
return milestoneSatisfies(model, issue);
case "label":
return labelsSatisfy(model, issue);
case "author":
return authorSatisfies(issue);
case "assignee":
return assigneeSatisfies(model, issue);
case "involves":
case "user":
return involvesSatisfies(model, issue);
case "type":
return typeSatisfies(issue);
case "state":
case "status":
return stateSatisfies(issue);
case "has":
return satisfiesHasConditions(issue);
case "no":
return satisfiesNoConditions(issue);
case "is":
return satisfiesIsConditions(issue);
case "created":
return satisfiesCreationDate(issue);
case "updated":
return satisfiesUpdatedHours(issue);
case "repo":
return satisfiesRepo(issue);
default:
return false;
}
}
@Override
public void applyTo(TurboIssue issue, IModel model) throws QualifierApplicationException {
assert name != null && content != null;
// The empty qualifier should not be applied to anything
assert !isEmptyQualifier();
switch (name) {
case "title":
case "desc":
case "body":
case "keyword":
throw new QualifierApplicationException("Unnecessary filter: issue text cannot be changed by dragging");
case "id":
throw new QualifierApplicationException("Unnecessary filter: id is immutable");
case "created":
throw new QualifierApplicationException("Unnecessary filter: cannot change issue creation date");
case "has":
case "no":
case "is":
throw new QualifierApplicationException("Ambiguous filter: " + name);
case "milestone":
applyMilestone(issue, model);
break;
case "label":
applyLabel(issue, model);
break;
case "assignee":
applyAssignee(issue, model);
break;
case "author":
throw new QualifierApplicationException("Unnecessary filter: cannot change author of issue");
case "involves":
case "user":
throw new QualifierApplicationException("Ambiguous filter: cannot change users involved with issue");
case "state":
case "status":
applyState(issue);
break;
default:
break;
}
}
@Override
public boolean canBeAppliedToIssue() {
return true;
}
@Override
public List<String> getQualifierNames() {
return new ArrayList<>(Arrays.asList(name));
}
@Override
public FilterExpression filter(Predicate<Qualifier> pred) {
if (pred.test(this)) {
return new Qualifier(this);
} else {
return EMPTY;
}
}
@Override
public List<Qualifier> find(Predicate<Qualifier> pred) {
if (pred.test(this)) {
ArrayList<Qualifier> result = new ArrayList<>();
result.add(this);
return result;
} else {
return new ArrayList<>();
}
}
/**
* This method is used to serialise qualifiers. Thus whatever form returned
* should be syntactically valid.
*/
@Override
public String toString() {
if (this == EMPTY) {
return "";
} else if (content.isPresent()) {
if (name.equals("keyword")) {
return content.get();
} else {
String quotedContent = content.get();
if (quotedContent.contains(" ")) {
quotedContent = "\"" + quotedContent + "\"";
}
return name + ":" + quotedContent;
}
} else if (date.isPresent()) {
return name + ":" + date.get().toString();
} else if (dateRange.isPresent()) {
return name + ":" + dateRange.get().toString();
} else if (!sortKeys.isEmpty()) {
return name + ":" + sortKeys.toString();
} else if (numberRange.isPresent()) {
return name + ":" + numberRange.get().toString();
} else if (number.isPresent()) {
return name + ":" + number.get().toString();
} else {
assert false : "Should not happen";
return "";
}
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((content == null) ? 0 : content.hashCode());
result = prime * result + ((date == null) ? 0 : date.hashCode());
result = prime * result + ((dateRange == null) ? 0 : dateRange.hashCode());
result = prime * result + ((sortKeys == null) ? 0 : sortKeys.hashCode());
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Qualifier other = (Qualifier) obj;
if (content == null) {
if (other.content != null)
return false;
} else if (!content.equals(other.content))
return false;
if (date == null) {
if (other.date != null)
return false;
} else if (!date.equals(other.date))
return false;
if (dateRange == null) {
if (other.dateRange != null)
return false;
} else if (!dateRange.equals(other.dateRange))
return false;
if (sortKeys == null) {
if (other.sortKeys != null)
return false;
} else if (!sortKeys.equals(other.sortKeys))
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
private static boolean shouldNotBeStripped(Qualifier q) {
return !shouldBeStripped(q);
}
private static boolean shouldBeStripped(Qualifier q) {
switch (q.getName()) {
case "in":
case "sort":
return true;
default:
return false;
}
}
private static boolean isMetaQualifier(Qualifier q) {
switch (q.getName()) {
case "sort":
case "in":
case "repo":
return true;
default:
return false;
}
}
public Comparator<TurboIssue> getCompoundSortComparator() {
if (sortKeys.isEmpty()) {
return (a, b) -> 0;
}
return (a, b) -> {
for (SortKey key : sortKeys) {
Comparator<TurboIssue> comparator = getSortComparator(key.key, key.inverted);
int result = comparator.compare(a, b);
if (result != 0) {
return result;
}
}
return 0;
};
}
public static Comparator<TurboIssue> getSortComparator(String key, boolean inverted) {
Comparator<TurboIssue> comparator;
switch (key) {
case "comments":
comparator = (a, b) -> a.getCommentCount() - b.getCommentCount();
break;
case "repo":
comparator = (a, b) -> a.getRepoId().compareTo(b.getRepoId());
break;
case "updated":
comparator = (a, b) -> a.getUpdatedAt().compareTo(b.getUpdatedAt());
break;
case "id":
default:
comparator = (a, b) -> a.getId() - b.getId();
break;
}
if (!inverted) {
return comparator;
} else {
return (a, b) -> -comparator.compare(a, b);
}
}
private boolean idSatisfies(TurboIssue issue) {
return number.isPresent() && issue.getId() == number.get();
}
private boolean satisfiesUpdatedHours(TurboIssue issue) {
int hours = Utility.safeLongToInt(issue.getUpdatedAt().until(getCurrentTime(), ChronoUnit.HOURS));
if (numberRange.isPresent()) {
return numberRange.get().encloses(hours);
} else if (number.isPresent()) {
// Treat it as <
return new NumberRange(null, number.get(), true).encloses(hours);
} else {
return false;
}
}
private boolean satisfiesRepo(TurboIssue issue) {
if (!content.isPresent()) return false;
return issue.getRepoId().equals(content.get());
}
private boolean satisfiesCreationDate(TurboIssue issue) {
LocalDate creationDate = issue.getCreatedAt().toLocalDate();
if (date.isPresent()) {
return creationDate.isEqual(date.get());
} else if (dateRange.isPresent()) {
return dateRange.get().encloses(creationDate);
} else {
return false;
}
}
private boolean satisfiesHasConditions(TurboIssue issue) {
if (!content.isPresent()) return false;
switch (content.get()) {
case "label":
case "labels":
return issue.getLabels().size() > 0;
case "milestone":
case "milestones":
return issue.getMilestone() != null;
case "assignee":
case "assignees":
return issue.getAssignee() != null;
default:
return false;
}
}
private boolean satisfiesNoConditions(TurboIssue issue) {
return content.isPresent() && !satisfiesHasConditions(issue);
}
private boolean satisfiesIsConditions(TurboIssue issue) {
if (!content.isPresent()) return false;
switch (content.get()) {
case "open":
case "closed":
return stateSatisfies(issue);
case "pr":
case "issue":
return typeSatisfies(issue);
case "merged":
return issue.isPullRequest() && !issue.isOpen();
case "unmerged":
return issue.isPullRequest() && issue.isOpen();
default:
return false;
}
}
private boolean stateSatisfies(TurboIssue issue) {
if (!content.isPresent()) return false;
String content = this.content.get().toLowerCase();
if (content.contains("open")) {
return issue.isOpen();
} else if (content.contains("closed")) {
return !issue.isOpen();
} else {
return false;
}
}
private boolean assigneeSatisfies(IModel model, TurboIssue issue) {
if (!content.isPresent()) return false;
Optional<TurboUser> assignee = model.getAssigneeOfIssue(issue);
if (!assignee.isPresent()) return false;
String content = this.content.get().toLowerCase();
String login = assignee.get().getLoginName() == null ? "" : assignee.get().getLoginName().toLowerCase();
String name = assignee.get().getRealName() == null ? "" : assignee.get().getRealName().toLowerCase();
return login.contains(content) || name.contains(content);
}
private boolean authorSatisfies(TurboIssue issue) {
if (!content.isPresent()) return false;
String creator = issue.getCreator();
return creator.toLowerCase().contains(content.get().toLowerCase());
}
private boolean involvesSatisfies(IModel model, TurboIssue issue) {
return authorSatisfies(issue) || assigneeSatisfies(model, issue);
}
private boolean labelsSatisfy(IModel model, TurboIssue issue) {
if (!content.isPresent()) return false;
// Make use of TurboLabel constructor to parse the string, to avoid duplication
TurboLabel tokens = new TurboLabel("", content.get().toLowerCase());
String group = "";
if (tokens.getGroup().isPresent()) {
group = tokens.getGroup().get().toLowerCase();
}
String labelName = tokens.getName().toLowerCase();
for (TurboLabel label : model.getLabelsOfIssue(issue)) {
if (label.getGroup().isPresent()) {
// Check both
if (label.getGroup().get().toLowerCase().contains(group)
&& label.getName().toLowerCase().contains(labelName)) {
return true;
}
} else {
// Check only the label name
return label.getName().toLowerCase().contains(labelName);
}
}
return false;
}
private boolean milestoneSatisfies(IModel model, TurboIssue issue) {
if (!content.isPresent()) return false;
Optional<TurboMilestone> milestone = model.getMilestoneOfIssue(issue);
if (!milestone.isPresent()) return false;
String contents = content.get().toLowerCase();
String title = milestone.get().getTitle().toLowerCase();
return title.contains(contents);
}
private boolean keywordSatisfies(TurboIssue issue, MetaQualifierInfo info) {
if (info.getIn().isPresent()) {
switch (info.getIn().get()) {
case "title":
return titleSatisfies(issue);
case "body":
case "desc":
return bodySatisfies(issue);
default:
return false;
}
} else {
return titleSatisfies(issue) || bodySatisfies(issue);
}
}
private boolean bodySatisfies(TurboIssue issue) {
if (!content.isPresent()) return false;
return issue.getDescription().toLowerCase().contains(content.get().toLowerCase());
}
private boolean titleSatisfies(TurboIssue issue) {
if (!content.isPresent()) return false;
return issue.getTitle().toLowerCase().contains(content.get().toLowerCase());
}
private boolean typeSatisfies(TurboIssue issue) {
if (!content.isPresent()) return false;
String content = this.content.get().toLowerCase();
switch (content) {
case "issue":
return !issue.isPullRequest();
case "pr":
case "pullrequest":
return issue.isPullRequest();
default:
return false;
}
}
private void applyMilestone(TurboIssue issue, IModel model) throws QualifierApplicationException {
if (!content.isPresent()) {
throw new QualifierApplicationException("Invalid milestone " + (date.isPresent() ? date.get() : dateRange.get()));
}
// Find milestones containing the partial title
List<TurboMilestone> milestones = model.getMilestones().stream().filter(m -> m.getTitle().toLowerCase().contains(content.get().toLowerCase())).collect(Collectors.toList());
if (milestones.size() > 1) {
throw new QualifierApplicationException("Ambiguous filter: can apply any of the following milestones: " + milestones.toString());
} else {
issue.setMilestone(milestones.get(0));
}
}
private void applyLabel(TurboIssue issue, IModel model) throws QualifierApplicationException {
if (!content.isPresent()) {
throw new QualifierApplicationException("Invalid label " + (date.isPresent() ? date.get() : dateRange.get()));
}
// Find labels containing the label name
List<TurboLabel> labels = model.getLabels().stream()
.filter(l -> l.getActualName().toLowerCase().contains(content.get().toLowerCase()))
.collect(Collectors.toList());
if (labels.size() > 1) {
throw new QualifierApplicationException("Ambiguous filter: can apply any of the following labels: " + labels.toString());
} else {
issue.addLabel(labels.get(0));
}
}
private void applyAssignee(TurboIssue issue, IModel model) throws QualifierApplicationException {
if (!content.isPresent()) {
throw new QualifierApplicationException("Invalid assignee " + (date.isPresent() ? date.get() : dateRange.get()));
}
// Find assignees containing the partial title
List<TurboUser> assignees = model.getUsers().stream()
.filter(c -> c.getLoginName().toLowerCase().contains(content.get().toLowerCase()))
.collect(Collectors.toList());
if (assignees.size() > 1) {
throw new QualifierApplicationException("Ambiguous filter: can apply any of the following assignees: " + assignees.toString());
} else {
issue.setAssignee(assignees.get(0));
}
}
private void applyState(TurboIssue issue) throws QualifierApplicationException {
if (!content.isPresent()) {
throw new QualifierApplicationException("Invalid state " + (date.isPresent() ? date.get() : dateRange.get()));
}
if (content.get().toLowerCase().contains("open")) {
issue.setOpen(true);
} else if (content.get().toLowerCase().contains("closed")) {
issue.setOpen(false);
}
}
public Optional<Integer> getNumber() {
return number;
}
public Optional<NumberRange> getNumberRange() {
return numberRange;
}
public Optional<DateRange> getDateRange() {
return dateRange;
}
public Optional<String> getContent() {
return content;
}
public Optional<LocalDate> getDate() {
return date;
}
public String getName() {
return name;
}
}
|
package group7.anemone.Genetics;
import group7.anemone.Agent;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
public abstract class God<t extends GeneticObject> implements Serializable{
private static final long serialVersionUID = 4056200256851797548L;
private double bestFitness;
private double worstFitness;
private double averageFitness;
//private int noImprovementCount = 0;
// The ordered list of all species, with each represented by a member from the
// previous generation.
protected ArrayList<Species> species;
// The distances between all genes:
protected ConcurrentHashMap<Pair<AgentFitness>, Double> distances;
protected List<t> children;
// This is inside it's own method to make unittesting easier.
public double getRandom() {
return Math.random();
}
public God() {
initialiseDataStructures();
}
public God(double compatabilityThreshold) {
setCompatabilityThreshold(compatabilityThreshold);
initialiseDataStructures();
}
protected void initialiseDataStructures() {
this.species = new ArrayList<Species>();
this.distances = new ConcurrentHashMap<Pair<AgentFitness>, Double>();
}
// Method to breed the entire population without species.
protected HashMap<t, Integer> BreedPopulation(ArrayList<Agent> agents) {
resetNewGenes();
ArrayList<AgentFitness> selectedAgents = Selection(agents);
ArrayList<t> children = GenerateChildren(selectedAgents);
HashMap<t, Integer> childrenSpecies = new HashMap<t, Integer>();
for (t child : children) {
childrenSpecies.put(child, 0);
}
return childrenSpecies;
}
protected abstract void resetNewGenes();
@SuppressWarnings("unchecked")
public ArrayList<t> BreedWithSpecies(ArrayList<Agent> agents, boolean fitnessOnly) {
resetNewGenes();
if (this.species.size() == 0) {
species.add(new Species(new AgentFitness(agents.get(0)),0));
setUpInitialMarkers((t) agents.get(0).getGeneticObject());
}
countDownDistances(agents);
propagateFitnesses(agents);
shareFitnesses();
ArrayList<t> children = new ArrayList<t>();
// Breed each species
for (Species specie : species) {
ArrayList<t> speciesChildren =
breedSpecies(specie, agents.size(), fitnessOnly);
children.addAll(speciesChildren);
}
// Pre calculate the distances of new children so this is faster next round.
Runnable r = new CalcAllDistances(children);
Thread thread = new Thread(r);
thread.start();
return children;
}
protected abstract void setUpInitialMarkers(t first);
protected void countDownDistances(ArrayList<Agent> agents) {
CountDownLatch latch = new CountDownLatch(agents.size() * species.size());
// Set up threads for each distance calculation to speed this up.
for (Agent agent : agents) {
if (agent.getSpeciesId() == -1) {
AgentFitness thisAgent = new AgentFitness(agent);
for (Species specie : species) {
AgentFitness speciesRep = specie.rep;
if (!distances.containsKey(new Pair<AgentFitness>(thisAgent, speciesRep))) {
Runnable r = new CalcDistance(thisAgent, speciesRep, latch);
Thread thread = new Thread(r);
thread.start();
} else {
latch.countDown();
}
}
} else {
for (@SuppressWarnings("unused") Species specie : species) {
latch.countDown();
}
}
}
// Wait for all threads to complete:
try {
latch.await();
} catch (InterruptedException e) {
// Continue; we'll just have to calculate the distances in sequence.
}
}
protected abstract double calcDistance(AgentFitness thisAgent, AgentFitness speciesRep);
// Copy across agent's fitness from simulation to specie members.
private void propagateFitnesses(ArrayList<Agent> agents) {
for (Agent agent : agents) {
boolean speciesFound = false;
for (Species specie : species) {
for (AgentFitness member : specie.members) {
if (member.geneticRep.equals(agent.getGeneticRep())) {
member.fitness = agent.getFitness();
speciesFound = true;
break;
}
}
}
// This case could happen if the main species sorter thread was slower than the sim.
if (!speciesFound) {
AgentFitness thisAgent = new AgentFitness(agent);
sortIntoSpecies(thisAgent);
}
}
}
// Sort given AgentFitness into a species or create a new one.
private void sortIntoSpecies(AgentFitness thisAgent) {
GeneticObject geneticObj = thisAgent.geneticRep;
boolean foundSpecies = false;
for (Species specie : species) {
AgentFitness rep = specie.rep;
double dist = getDistance(thisAgent, rep);
if (dist < getCompatibilityThreshold()) {
foundSpecies = true;
specie.addMember(thisAgent);
geneticObj.setSpecies(specie.id);
break;
}
}
if (!foundSpecies) {
int newSpeciesId = species.size();
species.add(new Species(thisAgent, newSpeciesId));
geneticObj.setSpecies(newSpeciesId);
}
}
@SuppressWarnings("unchecked")
private ArrayList<t> breedSpecies(Species specie, int popSize, boolean fitnessOnly) {
children = Collections.synchronizedList(new ArrayList<t>());
if (specie.members.size() < 2) {
return new ArrayList<t>(breedOneRemaining(specie.members));
}
double summedFitness = 0;
for (AgentFitness agent : specie.members) {
summedFitness += agent.fitness;
}
int numOffspring = Math.max(
(int) getMinReproduced(),
(int) Math.ceil(summedFitness * getOffspringProportion()));
System.out.println("Generating " + numOffspring + " children for species " + specie.id + " summed fitness is " + summedFitness);
// Breed the top n! (Members is presorted :))
int i = 0;
int j = Math.min(numOffspring * 2, specie.members.size()) - 1;
while (children.size() < specie.members.size()/2 && children.size() < numOffspring) {
final AgentFitness mother = specie.members.get(i);
final AgentFitness father = specie.members.get(j);
Runnable r = new CreateOffspring(mother, father);
Thread thread = new Thread(r);
thread.start();
if (fitnessOnly) {
children.add((t) mother.geneticRep);
children.add((t) father.geneticRep);
}
i++; j
}
// If not enough children, repeat some random offspring:
i = 0;
while (children.size() < numOffspring) {
children.add(children.get(i % children.size()));
i += 1;
}
return new ArrayList<t>(children);
}
protected abstract ArrayList<t> breedOneRemaining(ArrayList<AgentFitness> members);
// Share fitnesses over species by updating AgentFitness objects (see NEAT paper)
protected void shareFitnesses() {
// For every species...
for (Species specie : species) {
// Calculate the average fitness
double fitnessTotal = 0;
for (AgentFitness member : specie.members) {
fitnessTotal += sharingFunction(member.fitness);
}
for (AgentFitness agent : specie.members) {
// Check for 0 to avoid NaNs
agent.fitness = fitnessTotal == 0 ? 0 :
(agent.fitness / Math.abs(fitnessTotal));
}
}
}
protected int sharingFunction(double distance) {
if (distance > getSharingThreshold()) {
return 0; // Seems pointless. Why not only compare with dudes from the same species,
// if all others will be made 0?!
} else {
return 1;
}
}
// Return computability distance between two networks (see NEAT speciation).
// Only calculate if not previously stored.
protected double getDistance(AgentFitness thisAgent, AgentFitness speciesRep) {
if (distances.contains(thisAgent)) {
return distances.get(thisAgent);
} else {
return calcDistance(thisAgent, speciesRep);
}
}
protected ArrayList<AgentFitness> Selection(ArrayList<Agent> agents) {
ArrayList<AgentFitness> selectedAgents = new ArrayList<AgentFitness>();
//double last_best = bestFitness;
double last_average = averageFitness;
averageFitness = 0;
for (Agent agent : agents) {
double fitness = agent.getFitness();
averageFitness += fitness;
// This number is completely arbitrary, depends on fitness function
if (fitness * getRandom() > last_average) {
selectedAgents.add(new AgentFitness(agent));
}
if (agent.getFitness() > bestFitness) {
bestFitness = agent.getFitness();
} else if (agent.getFitness() < worstFitness) {
worstFitness = agent.getFitness();
}
}
averageFitness = averageFitness / agents.size();
// Keep track of the number of generations without improvement.
/*if (last_best >= bestFitness) {
noImprovementCount++;
} else {
noImprovementCount--;
}*/
return selectedAgents;
}
protected ArrayList<t> GenerateChildren(
ArrayList<AgentFitness> selectedAgents) {
// Crossover - should select partner randomly (unless we are having genders).
ArrayList<t> children = new ArrayList<t>();
while (selectedAgents.size() > 1) {
AgentFitness mother = selectedAgents.get((int) (getRandom() * selectedAgents.size()));
selectedAgents.remove(mother);
AgentFitness father = selectedAgents.get((int) (getRandom() * selectedAgents.size()));
selectedAgents.remove(father);
children.add(crossover(father, mother));
}
ArrayList<t> mutatedChildren = new ArrayList<t>();
// Put every child through mutation process
for (t child : children) {
mutatedChildren.add(mutate(child));
}
return mutatedChildren;
}
protected ArrayList<t> createOffspring(Agent mother, Agent father) {
AgentFitness motherFitness = new AgentFitness(mother);
AgentFitness fatherFitness = new AgentFitness(father);
resetNewGenes();
ArrayList<t> children = createOffspring(motherFitness, fatherFitness);
return children;
}
protected abstract ArrayList<t> createOffspring(
AgentFitness mother, AgentFitness father);
protected t crossover(AgentFitness mother, AgentFitness father) {
// If an agent has no edges, it is definitely not dominant.
@SuppressWarnings("unchecked")
t motherGen = (t) mother.geneticRep;
@SuppressWarnings("unchecked")
t fatherGen = (t) father.geneticRep;
if (mother.fitness > father.fitness) {
return crossover(motherGen, fatherGen);
} else {
return crossover(fatherGen, motherGen);
}
}
protected abstract t crossover(t dominant, t recessive);
protected abstract t mutate(t child);
// Class used to hold an entire species.
public class Species implements Serializable {
private static final long serialVersionUID = 4956311681035778159L;
private ArrayList<AgentFitness> members;
public AgentFitness rep;
private int id;
public Species(AgentFitness rep, int id) {
this.rep = rep;
members = new ArrayList<AgentFitness>();
members.add(rep);
this.id =id;
}
private void addMember(AgentFitness newMember) {
members.add(newMember);
Collections.sort(members);
}
private void clear() {
members.clear();
members.add(rep);
}
}
// This class is used so we can easily compare agents by fitness.
// Also used to be more lightweight than Agent class.
public class AgentFitness implements Comparable<AgentFitness>, Serializable {
private static final long serialVersionUID = -8299234421823218363L;
public GeneticObject geneticRep;
public double fitness;
public AgentFitness(Agent agent) {
this.geneticRep = agent.getGeneticObject();
this.fitness = agent.getFitness();
}
public AgentFitness(t geneticObj) {
this.geneticRep = geneticObj;
this.fitness = 0;
}
public int compareTo(AgentFitness other) {
if (this.fitness < other.fitness) {
return 1;
} else if (this.fitness > other.fitness) {
return -1;
} else {
return 0;
}
}
@Override
public String toString() {
return "Genome: " + this.geneticRep + " fitness: " + this.fitness;
}
}
// Class to hold two objects together so we can map to a distance.
public static class Pair<E> {
private E first;
private E second;
public Pair(E first, E second) {
this.first = first;
this.second = second;
}
@Override
public boolean equals(Object other) {
if (!(other instanceof God.Pair<?>)) {
return false;
} else {
// We need pairs to be of the same type to compare.
@SuppressWarnings("unchecked")
Pair<E> otherPair = (Pair<E>) other;
if (this.first == otherPair.first && this.second == otherPair.second ||
this.first == otherPair.second && this.second == otherPair.first) {
return true;
} else {
return false;
}
}
}
public String toString() {
return "(" + first.toString() + ", " + second.toString() + ")";
}
}
private class CreateOffspring implements Runnable {
private AgentFitness mother;
private AgentFitness father;
public CreateOffspring(AgentFitness mother, AgentFitness father) {
this.mother = mother;
this.father = father;
}
public void run() {
children.addAll(createOffspring(mother, father));
}
}
/* Sort into species whilst the simulation is running. */
private class CalcAllDistances implements Runnable {
private List<t> agents = Collections.synchronizedList(new ArrayList<t>());
public CalcAllDistances(ArrayList<t> allChildren) {
this.agents = allChildren;
}
public synchronized void run() {
// Clear species for a new gen
for (Species specie : species) {
specie.clear();
}
// Put each agent given for reproduction into a species.
for (t agent : this.agents) {
AgentFitness thisAgent = new AgentFitness(agent);
sortIntoSpecies(thisAgent);
}
}
}
private class CalcDistance implements Runnable {
private AgentFitness thisAgent;
private AgentFitness speciesRep;
private CountDownLatch latch;
public CalcDistance(AgentFitness thisAgent, AgentFitness speciesRep, CountDownLatch latch) {
this.thisAgent = thisAgent;
this.speciesRep = speciesRep;
this.latch = latch;
}
public synchronized void run() {
calcDistance(thisAgent, speciesRep);
latch.countDown();
}
}
/* Getter methods for variables that may differ between God types.*/
public abstract double getStructuralMutationChance();
public abstract double getAddConnectionChance();
public abstract double getAddNodeChance();
public abstract double getWeightMutationChance();
public abstract double getWeightIncreaseChance();
public abstract double getParameterMutationChance();
public abstract double getParameterIncreaseChance();
public abstract double getTwinChance();
public abstract double getMatchedGeneChance();
public abstract double getOffspringProportion();
public abstract double getc1();
public abstract double getc2();
public abstract double getc3();
public abstract double getCompatibilityThreshold();
public abstract double getSharingThreshold();
public abstract double getMinReproduced();
public abstract void setCompatabilityThreshold(double compatabilityThreshold);
}
|
package jolie.typeChecker;
import jolie.lang.NativeType;
import java.io.IOException;
import java.io.Writer;
import java.util.HashSet;
public class TypeCheckerWriter {
private Writer writer;
private StringBuilder sb;
private HashSet<String> declaredConsts = new HashSet<>();
public TypeCheckerWriter(Writer writer) throws IOException {
this.writer = writer;
sb = new StringBuilder();
sb.append(
"(declare-sort Type)\n" +
"(declare-sort Term)\n" +
"\n" +
"(declare-fun hasType (Term Type) Bool)\n" +
"(declare-fun sameType (Term Term) Bool)\n" +
"(declare-fun typeOf (Term) Type)\n" +
"\n"
);
NativeType[] nativeTypes = NativeType.values();
int nativeTypesLength = nativeTypes.length;
String[] types = new String[nativeTypesLength];
for (int i = 0; i < nativeTypesLength; i++) {
NativeType type = nativeTypes[i];
// we don't need 'any' type here, but we do need 'undefined', so just replace it
if (!type.equals(NativeType.ANY)) {
types[i] = type.id();
} else {
types[i] = "undefined";
}
}
sb.append(";; Define types\n");
for (String type : types) {
sb.append("(declare-fun ").append(type).append(" () Type)\n");
}
sb.append("(declare-fun any () Type)\n"); // TODO clarify equality with other types
sb.append("\n");
sb.append(";; Ensure non-equality of types\n");
for (int i = 0; i < types.length; i++) {
for (int j = i + 1; j < types.length; j++) {
sb.append("(assert (not (= ").append(types[i]).append(" ").append(types[j]).append(")))\n");
}
sb.append("\n");
}
sb.append(";; Describe type functions behavior\n"); // TODO maybe biconitional assertions needed?
for (String type : types) {
sb.append("(assert (forall ((t Term)) (= (hasType t ").append(type).append(") (= (typeOf t) ").append(type).append("))))\n");
}
sb.append("\n");
sb.append("(assert (forall ((t1 Term) (t2 Term)) (= (sameType t1 t2) (= (typeOf t1) (typeOf t2)))))\n");
sb.append("\n");
sb.append(";; Program constraints\n");
}
protected void flush() throws IOException {
writer.write(sb.toString());
writer.write("\n(check-sat)\n");
writer.flush();
}
public void write(String s) {
sb.append(s);
}
public void writeLine() {
sb.append("\n");
}
public void writeLine(String s) {
sb.append(s);
sb.append("\n");
}
public boolean declareTermOnce(String name) {
if (!declaredConsts.contains(name)) {
writeLine("(declare-const " + name + " Term)");
declaredConsts.add(name);
return true;
}
return false;
}
}
|
package com.dooble.phonertc;
import java.util.LinkedList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import android.graphics.Point;
import android.webkit.WebView;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.PluginResult;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.webrtc.AudioSource;
import org.webrtc.DataChannel;
import org.webrtc.IceCandidate;
import org.webrtc.MediaConstraints;
import org.webrtc.MediaStream;
import org.webrtc.PeerConnection;
import org.webrtc.PeerConnectionFactory;
import org.webrtc.SdpObserver;
import org.webrtc.SessionDescription;
import org.webrtc.PeerConnection.IceConnectionState;
import org.webrtc.PeerConnection.IceGatheringState;
import org.webrtc.VideoCapturer;
import org.webrtc.VideoRenderer;
import org.webrtc.VideoRenderer.I420Frame;
import org.webrtc.VideoSource;
import org.webrtc.VideoTrack;
import android.media.AudioManager;
import android.util.Log;
public class PhoneRTCPlugin extends CordovaPlugin {
public static final String ACTION_CALL = "call";
public static final String ACTION_RECEIVE_MESSAGE = "receiveMessage";
public static final String ACTION_DISCONNECT = "disconnect";
public static final String ACTION_UPDATE_VIDEO_POSITION = "updateVideoPosition";
CallbackContext _callbackContext;
private final SDPObserver sdpObserver = new SDPObserver();
private final PCObserver pcObserver = new PCObserver();
private boolean isInitiator;
private PeerConnectionFactory factory;
private PeerConnection pc;
private MediaConstraints sdpMediaConstraints;
private LinkedList<IceCandidate> queuedRemoteCandidates ;
// Synchronize on quit[0] to avoid teardown-related crashes.
private final Boolean[] quit = new Boolean[] { false };
private AudioSource audioSource;
private VideoSource videoSource;
private VideoStreamsView localVideoView;
private VideoStreamsView remoteVideoView;
@Override
public boolean execute(String action, JSONArray args,
CallbackContext callbackContext) throws JSONException {
if (action.equals(ACTION_CALL)) {
isInitiator = args.getBoolean(0);
final String turnServerHost = args.getString(1);
final String turnUsername = args.getString(2);
final String turnPassword = args.getString(3);
final JSONObject video = (!args.isNull(4)) ? args.getJSONObject(4) : null;
_callbackContext = callbackContext;
queuedRemoteCandidates = new LinkedList<IceCandidate>();
quit[0] = false;
cordova.getThreadPool().execute(new Runnable() {
public void run() {
PluginResult result = new PluginResult(PluginResult.Status.NO_RESULT);
result.setKeepCallback(true);
_callbackContext.sendPluginResult(result);
AudioManager audioManager = ((AudioManager) cordova.getActivity().getSystemService(cordova.getActivity().AUDIO_SERVICE));
@SuppressWarnings("deprecation")
boolean isWiredHeadsetOn = audioManager.isWiredHeadsetOn();
//audioManager.setMode(isWiredHeadsetOn ? AudioManager.MODE_IN_CALL
// : AudioManager.MODE_IN_COMMUNICATION);
audioManager.setSpeakerphoneOn(!isWiredHeadsetOn);
audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC), 0);
abortUnless(PeerConnectionFactory.initializeAndroidGlobals(cordova.getActivity(), true, true),
"Failed to initializeAndroidGlobals");
final LinkedList<PeerConnection.IceServer> iceServers = new LinkedList<PeerConnection.IceServer>();
iceServers.add(new PeerConnection.IceServer(
"stun:stun.l.google.com:19302"));
iceServers.add(new PeerConnection.IceServer(
turnServerHost, turnUsername, turnPassword));
sdpMediaConstraints = new MediaConstraints();
sdpMediaConstraints.mandatory.add(new MediaConstraints.KeyValuePair(
"OfferToReceiveAudio", "true"));
sdpMediaConstraints.mandatory.add(new MediaConstraints.KeyValuePair(
"OfferToReceiveVideo", (video != null) ? "true" : "false"));
cordova.getActivity().runOnUiThread(new Runnable() {
public void run() {
factory = new PeerConnectionFactory();
MediaConstraints pcMediaConstraints = new MediaConstraints();
pcMediaConstraints.optional.add(new MediaConstraints.KeyValuePair(
"DtlsSrtpKeyAgreement", "true"));
pc = factory.createPeerConnection(iceServers, pcMediaConstraints,
pcObserver);
MediaStream lMS = factory.createLocalMediaStream("ARDAMS");
if (video != null) {
try {
localVideoView = createVideoView(video.getJSONObject("localVideo"));
remoteVideoView = createVideoView(video.getJSONObject("remoteVideo"));
VideoCapturer capturer = getVideoCapturer();
videoSource = factory.createVideoSource(capturer, new MediaConstraints());
VideoTrack videoTrack =
factory.createVideoTrack("ARDAMSv0", videoSource);
videoTrack.addRenderer(new VideoRenderer(new VideoCallbacks(
localVideoView, VideoStreamsView.Endpoint.REMOTE)));
lMS.addTrack(videoTrack);
} catch (JSONException e) {
Log.e("com.dooble.phonertc", "A JSON exception has occured while trying to add video.", e);
}
}
audioSource = factory.createAudioSource(new MediaConstraints());
lMS.addTrack(factory.createAudioTrack("ARDAMSa0", audioSource));
pc.addStream(lMS, new MediaConstraints());
if (isInitiator) {
pc.createOffer(sdpObserver, sdpMediaConstraints);
}
}
});
}
});
return true;
} else if (action.equals(ACTION_RECEIVE_MESSAGE)) {
final String message = args.getString(0);
cordova.getThreadPool().execute(new Runnable() {
public void run() {
try {
JSONObject json = new JSONObject(message);
String type = (String) json.get("type");
if (type.equals("candidate")) {
final IceCandidate candidate = new IceCandidate(
(String) json.get("id"), json.getInt("label"),
(String) json.get("candidate"));
if (queuedRemoteCandidates != null) {
queuedRemoteCandidates.add(candidate);
} else {
cordova.getActivity().runOnUiThread(new Runnable() {
public void run() {
pc.addIceCandidate(candidate);
}
});
}
} else if (type.equals("answer") || type.equals("offer")) {
final SessionDescription sdp = new SessionDescription(
SessionDescription.Type.fromCanonicalForm(type),
preferISAC((String) json.get("sdp")));
cordova.getActivity().runOnUiThread(new Runnable() {
public void run() {
pc.setRemoteDescription(sdpObserver, sdp);
}
});
} else if (type.equals("bye")) {
Log.d("com.dooble.phonertc", "Remote end hung up; dropping PeerConnection");
cordova.getActivity().runOnUiThread(new Runnable() {
public void run() {
disconnect();
}
});
} else {
//throw new RuntimeException("Unexpected message: " + message);
}
} catch (JSONException e) {
throw new RuntimeException(e);
}
}
});
return true;
} else if (action.equals(ACTION_DISCONNECT)) {
Log.e("com.dooble.phonertc", "DISCONNECT");
disconnect();
} else if (action.equals(ACTION_UPDATE_VIDEO_POSITION)) {
final JSONObject videoElements = args.getJSONObject(0);
cordova.getActivity().runOnUiThread(new Runnable() {
public void run () {
try {
if (localVideoView != null && videoElements.has("localVideo")) {
localVideoView.setLayoutParams(getLayoutParams(videoElements.getJSONObject("localVideo")));
}
if (remoteVideoView != null && videoElements.has("remoteVideo")) {
remoteVideoView.setLayoutParams(getLayoutParams(videoElements.getJSONObject("remoteVideo")));
}
} catch (JSONException e) {
throw new RuntimeException(e);
}
}
});
}
callbackContext.error("Invalid action");
return false;
}
WebView.LayoutParams getLayoutParams (JSONObject config) throws JSONException {
int devicePixelRatio = config.getInt("devicePixelRatio");
int width = config.getInt("width") * devicePixelRatio;
int height = config.getInt("height") * devicePixelRatio;
int x = config.getInt("x") * devicePixelRatio;
int y = config.getInt("y") * devicePixelRatio;
WebView.LayoutParams params = new WebView.LayoutParams(width, height, x, y);
return params;
}
VideoStreamsView createVideoView(JSONObject config) throws JSONException {
WebView.LayoutParams params = getLayoutParams(config);
Point displaySize = new Point(params.width, params.height);
VideoStreamsView view = new VideoStreamsView(cordova.getActivity(), displaySize);
webView.addView(view, params);
return view;
}
void sendMessage(JSONObject data) {
PluginResult result = new PluginResult(PluginResult.Status.OK, data);
result.setKeepCallback(true);
_callbackContext.sendPluginResult(result);
}
private String preferISAC(String sdpDescription) {
String[] lines = sdpDescription.split("\n");
int mLineIndex = -1;
String isac16kRtpMap = null;
Pattern isac16kPattern = Pattern
.compile("^a=rtpmap:(\\d+) ISAC/16000[\r]?$");
for (int i = 0; (i < lines.length)
&& (mLineIndex == -1 || isac16kRtpMap == null); ++i) {
if (lines[i].startsWith("m=audio ")) {
mLineIndex = i;
continue;
}
Matcher isac16kMatcher = isac16kPattern.matcher(lines[i]);
if (isac16kMatcher.matches()) {
isac16kRtpMap = isac16kMatcher.group(1);
continue;
}
}
if (mLineIndex == -1) {
Log.d("com.dooble.phonertc",
"No m=audio line, so can't prefer iSAC");
return sdpDescription;
}
if (isac16kRtpMap == null) {
Log.d("com.dooble.phonertc",
"No ISAC/16000 line, so can't prefer iSAC");
return sdpDescription;
}
String[] origMLineParts = lines[mLineIndex].split(" ");
StringBuilder newMLine = new StringBuilder();
int origPartIndex = 0;
// Format is: m=<media> <port> <proto> <fmt> ...
newMLine.append(origMLineParts[origPartIndex++]).append(" ");
newMLine.append(origMLineParts[origPartIndex++]).append(" ");
newMLine.append(origMLineParts[origPartIndex++]).append(" ");
newMLine.append(isac16kRtpMap).append(" ");
for (; origPartIndex < origMLineParts.length; ++origPartIndex) {
if (!origMLineParts[origPartIndex].equals(isac16kRtpMap)) {
newMLine.append(origMLineParts[origPartIndex]).append(" ");
}
}
lines[mLineIndex] = newMLine.toString();
StringBuilder newSdpDescription = new StringBuilder();
for (String line : lines) {
newSdpDescription.append(line).append("\n");
}
return newSdpDescription.toString();
}
private static void abortUnless(boolean condition, String msg) {
if (!condition) {
throw new RuntimeException(msg);
}
}
// Cycle through likely device names for the camera and return the first
// capturer that works, or crash if none do.
private VideoCapturer getVideoCapturer() {
String[] cameraFacing = { "front", "back" };
int[] cameraIndex = { 0, 1 };
int[] cameraOrientation = { 0, 90, 180, 270 };
for (String facing : cameraFacing) {
for (int index : cameraIndex) {
for (int orientation : cameraOrientation) {
String name = "Camera " + index + ", Facing " + facing +
", Orientation " + orientation;
VideoCapturer capturer = VideoCapturer.create(name);
if (capturer != null) {
// logAndToast("Using camera: " + name);
return capturer;
}
}
}
}
throw new RuntimeException("Failed to open capturer");
}
private class PCObserver implements PeerConnection.Observer {
@Override
public void onIceCandidate(final IceCandidate iceCandidate) {
PhoneRTCPlugin.this.cordova.getActivity().runOnUiThread(new Runnable() {
public void run() {
try {
JSONObject json = new JSONObject();
json.put("type", "candidate");
json.put("label", iceCandidate.sdpMLineIndex);
json.put("id", iceCandidate.sdpMid);
json.put("candidate", iceCandidate.sdp);
sendMessage(json);
} catch (JSONException e) {
// TODO Auto-generated catch bloc
e.printStackTrace();
}
}
});
}
@Override
public void onAddStream(final MediaStream stream) {
// TODO Auto-generated method stub
PhoneRTCPlugin.this.cordova.getActivity().runOnUiThread(new Runnable() {
public void run() {
if (remoteVideoView != null) {
stream.videoTracks.get(0).addRenderer(new VideoRenderer(
new VideoCallbacks(remoteVideoView, VideoStreamsView.Endpoint.REMOTE)));
}
try {
JSONObject data = new JSONObject();
data.put("type", "__answered");
sendMessage(data);
} catch (JSONException e) {
}
}
});
}
@Override
public void onDataChannel(DataChannel stream) {
// TODO Auto-generated method stub
}
@Override
public void onError() {
// TODO Auto-generated method stub
}
@Override
public void onIceConnectionChange(IceConnectionState arg0) {
// TODO Auto-generated method stub
}
@Override
public void onIceGatheringChange(IceGatheringState arg0) {
// TODO Auto-generated method stub
}
@Override
public void onRemoveStream(MediaStream arg0) {
// TODO Auto-generated method stub
}
@Override
public void onRenegotiationNeeded() {
// TODO Auto-generated method stub
}
@Override
public void onSignalingChange(
PeerConnection.SignalingState signalingState) {
}
}
private class SDPObserver implements SdpObserver {
@Override
public void onCreateSuccess(final SessionDescription origSdp) {
PhoneRTCPlugin.this.cordova.getActivity().runOnUiThread(new Runnable() {
public void run() {
SessionDescription sdp = new SessionDescription(
origSdp.type, preferISAC(origSdp.description));
try {
JSONObject json = new JSONObject();
json.put("type", sdp.type.canonicalForm());
json.put("sdp", sdp.description);
sendMessage(json);
pc.setLocalDescription(sdpObserver, sdp);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
@Override
public void onSetSuccess() {
PhoneRTCPlugin.this.cordova.getActivity().runOnUiThread(new Runnable() {
public void run() {
if (isInitiator) {
if (pc.getRemoteDescription() != null) {
// We've set our local offer and received & set the
// remote
// answer, so drain candidates.
drainRemoteCandidates();
}
} else {
if (pc.getLocalDescription() == null) {
// We just set the remote offer, time to create our
// answer.
pc.createAnswer(SDPObserver.this,
sdpMediaConstraints);
} else {
// Sent our answer and set it as local description;
// drain
// candidates.
drainRemoteCandidates();
}
}
}
});
}
@Override
public void onCreateFailure(final String error) {
PhoneRTCPlugin.this.cordova.getActivity().runOnUiThread(new Runnable() {
public void run() {
throw new RuntimeException("createSDP error: " + error);
}
});
}
@Override
public void onSetFailure(final String error) {
PhoneRTCPlugin.this.cordova.getActivity().runOnUiThread(new Runnable() {
public void run() {
//throw new RuntimeException("setSDP error: " + error);
}
});
}
private void drainRemoteCandidates() {
if (queuedRemoteCandidates == null)
return;
for (IceCandidate candidate : queuedRemoteCandidates) {
pc.addIceCandidate(candidate);
}
queuedRemoteCandidates = null;
}
}
private void disconnect() {
synchronized (quit[0]) {
if (quit[0]) {
return;
}
quit[0] = true;
if (pc != null) {
pc.dispose();
pc = null;
}
try {
JSONObject json = new JSONObject();
json.put("type", "bye");
sendMessage(json);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (factory != null) {
factory.dispose();
factory = null;
}
}
try {
JSONObject data = new JSONObject();
data.put("type", "__disconnected");
sendMessage(data);
} catch (JSONException e) {
}
}
// Implementation detail: bridge the VideoRenderer.Callbacks interface to the
// VideoStreamsView implementation.
private class VideoCallbacks implements VideoRenderer.Callbacks {
private final VideoStreamsView view;
private final VideoStreamsView.Endpoint stream;
public VideoCallbacks(
VideoStreamsView view, VideoStreamsView.Endpoint stream) {
this.view = view;
this.stream = stream;
Log.d("CordovaLog", "VideoCallbacks");
}
@Override
public void setSize(final int width, final int height) {
Log.d("setSize", width + " " + height);
view.queueEvent(new Runnable() {
public void run() {
view.setSize(stream, width, height);
}
});
}
@Override
public void renderFrame(I420Frame frame) {
view.queueFrame(stream, frame);
}
}
}
|
package app.android.simpleflashcards.ui;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import android.accounts.Account;
import android.accounts.AccountManager;
import android.accounts.AuthenticatorException;
import android.accounts.OperationCanceledException;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import app.android.simpleflashcards.R;
public class Authorizer
{
// Defined by API
private static final String SPREADSHEETS_AUTH_TOKEN_TYPE = "wise";
private static final String DOCUMENTS_LIST_AUTH_TOKEN_TYPE = "writely";
private static final String GOOGLE_ACCOUNT_TYPE = "com.google";
private static final String PREFERENCE_GOOGLE_ACCOUNT_NAME = "google_account";
private AuthTokenWaiter tokenWaiter;
private final Activity activity;
private String authType;
public static enum ServiceType {
SPREADSHEETS, DOCUMENTS_LIST
}
public Authorizer(Activity activity) {
this.activity = activity;
}
public void authorize(ServiceType serviceType, AuthTokenWaiter tokenWaiter) {
this.authType = authTypeFromServiceType(serviceType);
this.tokenWaiter = tokenWaiter;
authorize();
}
private String authTypeFromServiceType(ServiceType serviceType) {
switch (serviceType) {
case SPREADSHEETS:
return SPREADSHEETS_AUTH_TOKEN_TYPE;
case DOCUMENTS_LIST:
return DOCUMENTS_LIST_AUTH_TOKEN_TYPE;
default:
throw new RuntimeException("Unknown service type");
}
}
private void authorize() {
if (haveAccountNameInPreferences()) {
authorizeForAccount(loadAccountNameFromPreferences());
}
else {
selectAccount();
}
}
private boolean haveAccountNameInPreferences() {
String accountName = loadAccountNameFromPreferences();
return !accountName.isEmpty();
}
private String loadAccountNameFromPreferences() {
String accountName = getPreference(PREFERENCE_GOOGLE_ACCOUNT_NAME);
if (haveAccountRegistered(accountName)) {
return accountName;
}
else {
// Account name from preferences was invalid
return new String();
}
}
private boolean haveAccountRegistered(String accountName) {
return getAccountsNames().contains(accountName);
}
private void selectAccount() {
if (haveSomeAccountsRegistered()) {
constructAccountsListDialog().show();
}
else {
UserAlerter.alert(activity, activity.getString(R.string.noGoogleAccounts));
}
}
private boolean haveSomeAccountsRegistered() {
return !getAccountsNames().isEmpty();
}
private List<String> getAccountsNames() {
List<String> result = new ArrayList<String>();
AccountManager accountManager = AccountManager.get(activity.getApplicationContext());
for (Account account : accountManager.getAccountsByType(GOOGLE_ACCOUNT_TYPE)) {
result.add(account.name);
}
return result;
}
private Dialog constructAccountsListDialog() {
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(activity);
dialogBuilder.setTitle(activity.getString(R.string.chooseGoogleAccount));
final List<String> accountsNamesList = getAccountsNames();
String[] accountsNamesArray = new String[accountsNamesList.size()];
accountsNamesList.toArray(accountsNamesArray);
dialogBuilder.setItems(accountsNamesArray, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String selectedAccountName = accountsNamesList.get(which);
setPreference(PREFERENCE_GOOGLE_ACCOUNT_NAME, selectedAccountName);
authorizeForAccount(selectedAccountName);
}
});
return dialogBuilder.create();
}
private String getPreference(String key) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(activity
.getApplicationContext());
return preferences.getString(key, new String());
}
private void setPreference(String key, String value) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(activity
.getApplicationContext());
SharedPreferences.Editor preferenceEditor = preferences.edit();
preferenceEditor.putString(key, value);
preferenceEditor.commit();
}
private void authorizeForAccount(String accountName) {
new AuthorizeTask(accountName).execute();
}
private class AuthorizeTask extends AsyncTask<Void, Void, String>
{
private final Account account;
private String authToken;
public AuthorizeTask(String accountName) {
super();
this.account = accountFromName(accountName);
authToken = new String();
}
private Account accountFromName(String accountName) {
AccountManager accountManager = AccountManager.get(activity.getApplicationContext());
for (Account account : accountManager.getAccountsByType(GOOGLE_ACCOUNT_TYPE)) {
if (account.name.equals(accountName)) {
return account;
}
}
return null;
}
@Override
protected String doInBackground(Void... params) {
AccountManager accountManager = AccountManager.get(activity.getApplicationContext());
Bundle authResponse = new Bundle();
try {
authResponse = accountManager.getAuthToken(account, authType, null, activity, null,
null).getResult();
}
catch (OperationCanceledException e) {
return activity.getString(R.string.authenticationCanceled);
}
catch (AuthenticatorException e) {
return activity.getString(R.string.authenticationError);
}
catch (IOException e) {
return activity.getString(R.string.someError);
}
if (authResponse.containsKey(AccountManager.KEY_AUTHTOKEN)) {
authToken = authResponse.getString(AccountManager.KEY_AUTHTOKEN);
}
return new String();
}
@Override
protected void onPostExecute(String errorMessage) {
if (errorMessage.isEmpty()) {
tokenReceived(authToken);
}
else {
UserAlerter.alert(activity, errorMessage);
}
}
}
private void tokenReceived(String authToken) {
tokenWaiter.onTokenReceived(authToken);
}
}
|
package hello.utilities;
import java.io.File;
import java.io.IOException;
public class ProcessUtil {
public static boolean isRcloneInstalled() {
final ProcessBuilder builder = new ProcessBuilder();
builder.command("rlcone", "version");
builder.directory(new File(System.getProperty("user.home")));
Process process;
try {
process = builder.start();
process.waitFor();
final String output = new String(process.getInputStream().readAllBytes());
return output.contains("rclone");
} catch (final IOException | InterruptedException exception) {
exception.printStackTrace();
}
return false;
}
}
|
package hu.bme.mit.spaceship;
/**
* A simple spaceship with two proton torpedos and four lasers
*/
public class GT4500 implements SpaceShip {
private TorpedoStore primaryTorpedoStore;
private TorpedoStore secondaryTorpedoStore;
private boolean wasPrimaryFiredLast = false;
public GT4500() {
this.primaryTorpedoStore = new TorpedoStore(10);
this.secondaryTorpedoStore = new TorpedoStore(10);
}
public boolean fireLasers(FiringMode firingMode) {
// TODO not implemented yet
return false;
}
/**
* Tries to fire the torpedo stores of the ship.
*
* @param firingMode how many torpedo bays to fire
* SINGLE: fires only one of the bays.
* - For the first time the primary store is fired.
* - To give some cooling time to the torpedo stores, torpedo stores are fired alternating.
* - But if the store next in line is empty the ship tries to fire the other store.
* - If the fired store reports a failure, the ship does not try to fire the other one.
* ALL: tries to fire both of the torpedo stores.
*
* @return whether at least one torpedo was fired successfully
*/
@Override
public boolean fireTorpedos(FiringMode firingMode) {
boolean firingSuccess = false;
if (firingMode == SINGLE) {
if (wasPrimaryFiredLast) {
// try to fire the secondary first
if (isTorpedoStoreAvailable(secondaryTorpedoStore)) {
firingSuccess = secondaryTorpedoStore.fire(1);
wasPrimaryFiredLast = false;
}
else {
// although primary was fired last time, but the secondary is empty
// thus try to fire primary again
if (isTorpedoStoreAvailable(primaryTorpedoStore)) {
firingSuccess = primaryTorpedoStore.fire(1);
wasPrimaryFiredLast = true;
}
// if both of the stores are empty, nothing can be done, return failure
}
}
else {
// try to fire the primary first
if (isTorpedoStoreAvailable(primaryTorpedoStore)) {
firingSuccess = primaryTorpedoStore.fire(1);
wasPrimaryFiredLast = true;
}
else {
// although secondary was fired last time, but primary is empty
// thus try to fire secondary again
if (isTorpedoStoreAvailable(secondaryTorpedoStore)) {
firingSuccess = secondaryTorpedoStore.fire(1);
wasPrimaryFiredLast = false;
}
// if both of the stores are empty, nothing can be done, return failure
}
}
} else if (firingMode == ALL) {
// try to fire both of the torpedos
//TODO implement feature
if (isTorpedoStoreAvailable(primaryTorpedoStore) && isTorpedoStoreAvailable(secondaryTorpedoStore)) {
firingSuccess = (primaryTorpedoStore.fire(1) &&
secondaryTorpedoStore.fire(1));
}
}
return firingSuccess;
}
private boolean isTorpedoStoreAvailable(TorpedoStore torpedoStore) {
return !torpedoStore.isEmpty();
}
}
|
package hu.bme.mit.spaceship;
//ASDASDASDASD
//WWWWWWWWWWWWWWWWWWWWWWWW
/**
* A simple spaceship with two proton torpedos and four lasers
*/
public class GT4500 implements SpaceShip {
private TorpedoStore primaryTorpedoStore;
private TorpedoStore secondaryTorpedoStore;
private boolean wasPrimaryFiredLast = false;
public GT4500(TorpedoStore egy, TorpedoStore ket) {
this.primaryTorpedoStore = egy;//new TorpedoStore(10);
this.secondaryTorpedoStore = ket;//new TorpedoStore(10);
}
public boolean fireLasers(FiringMode firingMode) {
// TODO not implemented yet
return false;
}
/**
* Tries to fire the torpedo stores of the ship.
*
* @param firingMode how many torpedo bays to fire
* SINGLE: fires only one of the bays.
* - For the first time the primary store is fired.
* - To give some cooling time to the torpedo stores, torpedo stores are fired alternating.
* - But if the store next in line is empty the ship tries to fire the other store.
* - If the fired store reports a failure, the ship does not try to fire the other one.
* ALL: tries to fire both of the torpedo stores.
*
* @return whether at least one torpedo was fired successfully
*/
@Override
public boolean fireTorpedos(FiringMode firingMode) {
boolean firingSuccess = true;
switch (firingMode) {
case SINGLE:
if (wasPrimaryFiredLast) {
// try to fire the secondary first
if (! secondaryTorpedoStore.isEmpty()) {
firingSuccess = secondaryTorpedoStore.fire(1);
wasPrimaryFiredLast = false;
}
else {
// although primary was fired last time, but the secondary is empty
// thus try to fire primary again
if (! primaryTorpedoStore.isEmpty()) {
firingSuccess = primaryTorpedoStore.fire(1);
wasPrimaryFiredLast = true;
}
// if both of the stores are empty, nothing can be done, return failure
}
}
else {
// try to fire the primary first
if (! primaryTorpedoStore.isEmpty()) {
firingSuccess = primaryTorpedoStore.fire(1);
wasPrimaryFiredLast = true;
}
else {
// although secondary was fired last time, but primary is empty
// thus try to fire secondary again
if (! secondaryTorpedoStore.isEmpty()) {
firingSuccess = secondaryTorpedoStore.fire(1);
wasPrimaryFiredLast = false;
}
// if both of the stores are empty, nothing can be done, return failure
}
}
break;
case ALL:
// try to fire both of the torpedos
//TODO implement feature
if(!primaryTorpedoStore.isEmpty() && !secondaryTorpedoStore.isEmpty())
if(primaryTorpedoStore.fire(1))
if(secondaryTorpedoStore.fire(1))
firingSuccess = true;
break;
}
//return firingSuccess;
return firingSuccess;
}
}
|
package hu.bme.mit.spaceship;
/**
* A simple spaceship with two proton torpedos and four lasers
*/
public class GT4500 implements SpaceShip {
private TorpedoStore primaryTorpedoStore;
private TorpedoStore secondaryTorpedoStore;
private boolean wasPrimaryFiredLast = false;
public GT4500() {
this.primaryTorpedoStore = new TorpedoStore(10);
this.secondaryTorpedoStore = new TorpedoStore(10);
}
public boolean fireLasers(FiringMode firingMode) {
// TODO not implemented yet
return false;
}
/**
* Tries to fire the torpedo stores of the ship.
*
* @param firingMode how many torpedo bays to fire
* SINGLE: fires only one of the bays.
* - For the first time the primary store is fired.
* - To give some cooling time to the torpedo stores, torpedo stores are fired alternating.
* - But if the store next in line is empty the ship tries to fire the other store.
* - If the fired store reports a failure, the ship does not try to fire the other one.
* ALL: tries to fire both of the torpedo stores.
*
* @return whether at least one torpedo was fired successfully
*/
@Override
public boolean fireTorpedos(FiringMode firingMode) {
boolean firingSuccess = false;
switch (firingMode) {
case SINGLE:
if (wasPrimaryFiredLast) {
// try to fire the secondary first
if (! secondaryTorpedoStore.isEmpty()) {
firingSuccess = secondaryTorpedoStore.fire(1);
wasPrimaryFiredLast = false;
}
else {
// although primary was fired last time, but the secondary is empty
// thus try to fire primary again
if (! primaryTorpedoStore.isEmpty()) {
firingSuccess = primaryTorpedoStore.fire(1);
wasPrimaryFiredLast = true;
}
// if both of the stores are empty, nothing can be done, return failure
}
}
else {
// try to fire the primary first
if (! primaryTorpedoStore.isEmpty()) {
firingSuccess = primaryTorpedoStore.fire(1);
wasPrimaryFiredLast = true;
}
else {
// although secondary was fired last time, but primary is empty
// thus try to fire secondary again
if (! secondaryTorpedoStore.isEmpty()) {
firingSuccess = secondaryTorpedoStore.fire(1);
wasPrimaryFiredLast = false;
}
// if both of the stores are empty, nothing can be done, return failure
}
}
break;
case ALL:
// try to fire both of the torpedos
//TODO implement feature
if (! primaryTorpedoStore.isEmpty()) {
firingSuccess = primaryTorpedoStore.fire(1);
}
if (! secondaryTorpedoStore.isEmpty()) {
firingSuccess = secondaryTorpedoStore.fire(1);
}
break;
}
return firingSuccess;
}
}
|
package hudson.plugins.ec2;
import static javax.servlet.http.HttpServletResponse.SC_BAD_REQUEST;
import static javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
import com.amazonaws.ClientConfiguration;
import com.amazonaws.auth.DefaultAWSCredentialsProviderChain;
import com.cloudbees.jenkins.plugins.awscredentials.AWSCredentialsImpl;
import com.cloudbees.jenkins.plugins.awscredentials.AmazonWebServicesCredentials;
import com.cloudbees.plugins.credentials.Credentials;
import com.cloudbees.plugins.credentials.CredentialsMatchers;
import com.cloudbees.plugins.credentials.CredentialsProvider;
import com.cloudbees.plugins.credentials.CredentialsScope;
import com.cloudbees.plugins.credentials.CredentialsStore;
import com.cloudbees.plugins.credentials.SystemCredentialsProvider;
import com.cloudbees.plugins.credentials.common.StandardListBoxModel;
import com.cloudbees.plugins.credentials.domains.Domain;
import edu.umd.cs.findbugs.annotations.CheckForNull;
import edu.umd.cs.findbugs.annotations.Nullable;
import hudson.ProxyConfiguration;
import hudson.model.Computer;
import hudson.model.Descriptor;
import hudson.model.Hudson;
import hudson.model.Label;
import hudson.model.Node;
import hudson.security.ACL;
import hudson.slaves.Cloud;
import hudson.slaves.NodeProvisioner.PlannedNode;
import hudson.util.FormValidation;
import hudson.util.HttpResponses;
import hudson.util.ListBoxModel;
import hudson.util.Secret;
import hudson.util.StreamTaskListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.io.StringReader;
import java.io.StringWriter;
import java.net.InetSocketAddress;
import java.net.MalformedURLException;
import java.net.Proxy;
import java.net.URL;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.EnumSet;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.HashMap;
import java.util.UUID;
import java.util.concurrent.Callable;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;
import javax.servlet.ServletException;
import hudson.model.TaskListener;
import jenkins.model.Jenkins;
import org.apache.commons.lang.StringUtils;
import org.kohsuke.stapler.HttpResponse;
import org.kohsuke.stapler.QueryParameter;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
import com.amazonaws.AmazonClientException;
import com.amazonaws.ClientConfiguration;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.AWSCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.auth.InstanceProfileCredentialsProvider;
import com.amazonaws.internal.StaticCredentialsProvider;
import com.amazonaws.services.ec2.AmazonEC2;
import com.amazonaws.services.ec2.AmazonEC2Client;
import com.amazonaws.services.ec2.model.CreateKeyPairRequest;
import com.amazonaws.services.ec2.model.DescribeSpotInstanceRequestsRequest;
import com.amazonaws.services.ec2.model.Filter;
import com.amazonaws.services.ec2.model.Instance;
import com.amazonaws.services.ec2.model.InstanceStateName;
import com.amazonaws.services.ec2.model.InstanceType;
import com.amazonaws.services.ec2.model.KeyPair;
import com.amazonaws.services.ec2.model.KeyPairInfo;
import com.amazonaws.services.ec2.model.Reservation;
import com.amazonaws.services.ec2.model.SpotInstanceRequest;
import com.amazonaws.services.ec2.model.Tag;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.model.GeneratePresignedUrlRequest;
import hudson.ProxyConfiguration;
import hudson.model.Computer;
import hudson.model.Descriptor;
import hudson.model.Hudson;
import hudson.model.Label;
import hudson.model.Node;
import hudson.slaves.Cloud;
import hudson.slaves.NodeProvisioner.PlannedNode;
import hudson.util.FormValidation;
import hudson.util.HttpResponses;
import hudson.util.Secret;
import hudson.util.StreamTaskListener;
/**
* Hudson's view of EC2.
*
* @author Kohsuke Kawaguchi
*/
public abstract class EC2Cloud extends Cloud {
private static final Logger LOGGER = Logger.getLogger(EC2Cloud.class.getName());
public static final String DEFAULT_EC2_HOST = "us-east-1";
public static final String AWS_URL_HOST = "amazonaws.com";
public static final String EC2_SLAVE_TYPE_SPOT = "spot";
public static final String EC2_SLAVE_TYPE_DEMAND = "demand";
private static final SimpleFormatter sf = new SimpleFormatter();
private final boolean useInstanceProfileForCredentials;
/**
* Id of the {@link AmazonWebServicesCredentials} used to connect to Amazon ECS
*/
@CheckForNull
private String credentialsId;
@CheckForNull
@Deprecated
private transient String accessId;
@CheckForNull
@Deprecated
private transient Secret secretKey;
protected final EC2PrivateKey privateKey;
/**
* Upper bound on how many instances we may provision.
*/
public final int instanceCap;
private final List<? extends SlaveTemplate> templates;
private transient KeyPair usableKeyPair;
protected transient AmazonEC2 connection;
private static AWSCredentialsProvider awsCredentialsProvider;
protected EC2Cloud(String id, boolean useInstanceProfileForCredentials, String credentialsId, String privateKey,
String instanceCapStr, List<? extends SlaveTemplate> templates) {
super(id);
this.useInstanceProfileForCredentials = useInstanceProfileForCredentials;
this.credentialsId = credentialsId;
this.privateKey = new EC2PrivateKey(privateKey);
if (templates == null) {
this.templates = Collections.emptyList();
} else {
this.templates = templates;
}
if (instanceCapStr.isEmpty()) {
this.instanceCap = Integer.MAX_VALUE;
} else {
this.instanceCap = Integer.parseInt(instanceCapStr);
}
readResolve(); // set parents
}
public abstract URL getEc2EndpointUrl() throws IOException;
public abstract URL getS3EndpointUrl() throws IOException;
protected Object readResolve() {
for (SlaveTemplate t : templates)
t.parent = this;
if (this.accessId != null && credentialsId == null) {
// REPLACE this.accessId and this.secretId by a credential
SystemCredentialsProvider systemCredentialsProvider = SystemCredentialsProvider.getInstance();
// ITERATE ON EXISTING CREDS AND DON'T CREATE IF EXIST
for (Credentials credentials: systemCredentialsProvider.getCredentials()) {
if (credentials instanceof AmazonWebServicesCredentials) {
AmazonWebServicesCredentials awsCreds = (AmazonWebServicesCredentials) credentials;
AWSCredentials awsCredentials = awsCreds.getCredentials();
if (accessId.equals(awsCredentials.getAWSAccessKeyId()) &&
Secret.toString(this.secretKey).equals(awsCredentials.getAWSSecretKey())) {
this.credentialsId = awsCreds.getId();
this.accessId = null;
this.secretKey = null;
return this;
}
}
}
// CREATE
for (CredentialsStore credentialsStore: CredentialsProvider.lookupStores(Jenkins.getInstance())) {
if (credentialsStore instanceof SystemCredentialsProvider.StoreImpl) {
try {
String credsId = UUID.randomUUID().toString();
credentialsStore.addCredentials(Domain.global(), new AWSCredentialsImpl(
CredentialsScope.SYSTEM,
credsId,
this.accessId,
this.secretKey.getEncryptedValue(),
"EC2 Cloud - " + getDisplayName()));
this.credentialsId = credsId;
this.accessId = null;
this.secretKey = null;
return this;
} catch (IOException e) {
this.credentialsId = null;
LOGGER.log(Level.WARNING, "Exception converting legacy configuration to the new credentials API", e);
}
}
}
// PROBLEM, GLOBAL STORE NOT FOUND
LOGGER.log(Level.WARNING, "EC2 Plugin could not migrate credentials to the Jenkins Global Credentials Store, EC2 Plugin for cloud {0} must be manually reconfigured", getDisplayName());
}
return this;
}
public boolean isUseInstanceProfileForCredentials() {
return useInstanceProfileForCredentials;
}
public String getCredentialsId() {
return credentialsId;
}
public EC2PrivateKey getPrivateKey() {
return privateKey;
}
public String getInstanceCapStr() {
if (instanceCap == Integer.MAX_VALUE)
return "";
else
return String.valueOf(instanceCap);
}
public List<SlaveTemplate> getTemplates() {
return Collections.unmodifiableList(templates);
}
public SlaveTemplate getTemplate(String template) {
for (SlaveTemplate t : templates) {
if (t.description.equals(template)) {
return t;
}
}
return null;
}
/**
* Gets {@link SlaveTemplate} that has the matching {@link Label}.
*/
public SlaveTemplate getTemplate(Label label) {
for (SlaveTemplate t : templates) {
if (t.getMode() == Node.Mode.NORMAL) {
if (label == null || label.matches(t.getLabelSet())) {
return t;
}
} else if (t.getMode() == Node.Mode.EXCLUSIVE) {
if (label != null && label.matches(t.getLabelSet())) {
return t;
}
}
}
return null;
}
/**
* Gets the {@link KeyPairInfo} used for the launch.
*/
public synchronized KeyPair getKeyPair() throws AmazonClientException, IOException {
if (usableKeyPair == null)
usableKeyPair = privateKey.find(connect());
return usableKeyPair;
}
/**
* Debug command to attach to a running instance.
*/
public void doAttach(StaplerRequest req, StaplerResponse rsp, @QueryParameter String id)
throws ServletException, IOException, AmazonClientException {
checkPermission(PROVISION);
SlaveTemplate t = getTemplates().get(0);
StringWriter sw = new StringWriter();
StreamTaskListener listener = new StreamTaskListener(sw);
EC2AbstractSlave node = t.attach(id, listener);
Jenkins.getInstance().addNode(node);
rsp.sendRedirect2(req.getContextPath() + "/computer/" + node.getNodeName());
}
public HttpResponse doProvision(@QueryParameter String template) throws ServletException, IOException {
checkPermission(PROVISION);
if (template == null) {
throw HttpResponses.error(SC_BAD_REQUEST, "The 'template' query parameter is missing");
}
SlaveTemplate t = getTemplate(template);
if (t == null) {
throw HttpResponses.error(SC_BAD_REQUEST, "No such template: " + template);
}
try {
EC2AbstractSlave node = getNewOrExistingAvailableSlave(t, null, true);
if (node == null)
throw HttpResponses.error(SC_BAD_REQUEST, "Cloud or AMI instance cap would be exceeded for: " + template);
Jenkins.getInstance().addNode(node);
return HttpResponses.redirectViaContextPath("/computer/" + node.getNodeName());
} catch (AmazonClientException e) {
throw HttpResponses.error(SC_INTERNAL_SERVER_ERROR, e);
}
}
/**
* Counts the number of instances in EC2 that can be used with the specified image and a template. Also removes any
* nodes associated with canceled requests.
*
* @param template If left null, then all instances are counted.
*/
private int countCurrentEC2Slaves(SlaveTemplate template) throws AmazonClientException {
LOGGER.log(Level.FINE, "Counting current slaves: " + (template != null ? (" AMI: " + template.getAmi()) : " All AMIS"));
int n = 0;
Set<String> instanceIds = new HashSet<String>();
String description = template != null ? template.description : null;
for (Reservation r : connect().describeInstances().getReservations()) {
for (Instance i : r.getInstances()) {
if (isEc2ProvisionedAmiSlave(i.getTags(), description) && (template == null
|| template.getAmi().equals(i.getImageId()))) {
InstanceStateName stateName = InstanceStateName.fromValue(i.getState().getName());
if (stateName != InstanceStateName.Terminated && stateName != InstanceStateName.ShuttingDown) {
LOGGER.log(Level.FINE, "Existing instance found: " + i.getInstanceId() + " AMI: " + i.getImageId()
+ " Template: " + description);
n++;
instanceIds.add(i.getInstanceId());
}
}
}
}
List<SpotInstanceRequest> sirs = null;
List<Filter> filters = new ArrayList<Filter>();
List<String> values;
if (template != null) {
values = new ArrayList<String>();
values.add(template.getAmi());
filters.add(new Filter("launch.image-id", values));
}
values = new ArrayList<String>();
values.add(EC2Tag.TAG_NAME_JENKINS_SLAVE_TYPE);
filters.add(new Filter("tag-key", values));
DescribeSpotInstanceRequestsRequest dsir = new DescribeSpotInstanceRequestsRequest().withFilters(filters);
try {
sirs = connect().describeSpotInstanceRequests(dsir).getSpotInstanceRequests();
} catch (Exception ex) {
// Some ec2 implementations don't implement spot requests (Eucalyptus)
LOGGER.log(Level.FINEST, "Describe spot instance requests failed", ex);
}
Set<SpotInstanceRequest> sirSet = new HashSet();
if (sirs != null) {
for (SpotInstanceRequest sir : sirs) {
sirSet.add(sir);
if (sir.getState().equals("open") || sir.getState().equals("active")) {
if (sir.getInstanceId() != null && instanceIds.contains(sir.getInstanceId()))
continue;
LOGGER.log(Level.FINE, "Spot instance request found: " + sir.getSpotInstanceRequestId() + " AMI: "
+ sir.getInstanceId() + " state: " + sir.getState() + " status: " + sir.getStatus());
n++;
if (sir.getInstanceId() != null)
instanceIds.add(sir.getInstanceId());
} else {
// Canceled or otherwise dead
for (Node node : Jenkins.getInstance().getNodes()) {
try {
if (!(node instanceof EC2SpotSlave))
continue;
EC2SpotSlave ec2Slave = (EC2SpotSlave) node;
if (ec2Slave.getSpotInstanceRequestId().equals(sir.getSpotInstanceRequestId())) {
LOGGER.log(Level.INFO, "Removing dead request: " + sir.getSpotInstanceRequestId() + " AMI: "
+ sir.getInstanceId() + " state: " + sir.getState() + " status: " + sir.getStatus());
Jenkins.getInstance().removeNode(node);
break;
}
} catch (IOException e) {
LOGGER.log(Level.WARNING, "Failed to remove node for dead request: " + sir.getSpotInstanceRequestId()
+ " AMI: " + sir.getInstanceId() + " state: " + sir.getState() + " status: " + sir.getStatus(),
e);
}
}
}
}
}
// Count nodes where the spot request does not yet exist (sometimes it takes time for the request to appear
// in the EC2 API)
for (Node node : Jenkins.getInstance().getNodes()) {
if (!(node instanceof EC2SpotSlave))
continue;
EC2SpotSlave ec2Slave = (EC2SpotSlave) node;
SpotInstanceRequest sir = ec2Slave.getSpotRequest();
if (sir == null) {
LOGGER.log(Level.FINE, "Found spot node without request: " + ec2Slave.getSpotInstanceRequestId());
n++;
continue;
}
if (sirSet.contains(sir))
continue;
sirSet.add(sir);
if (sir.getState().equals("open") || sir.getState().equals("active")) {
if (template != null) {
List<Tag> instanceTags = sir.getTags();
for (Tag tag : instanceTags) {
if (StringUtils.equals(tag.getKey(), EC2Tag.TAG_NAME_JENKINS_SLAVE_TYPE) && StringUtils.equals(tag.getValue(), getSlaveTypeTagValue(EC2_SLAVE_TYPE_SPOT, template.description)) && sir.getLaunchSpecification().getImageId().equals(template.getAmi())) {
if (sir.getInstanceId() != null && instanceIds.contains(sir.getInstanceId()))
continue;
LOGGER.log(Level.FINE, "Spot instance request found (from node): " + sir.getSpotInstanceRequestId() + " AMI: "
+ sir.getInstanceId() + " state: " + sir.getState() + " status: " + sir.getStatus());
n++;
if (sir.getInstanceId() != null)
instanceIds.add(sir.getInstanceId());
}
}
}
}
}
return n;
}
private boolean isEc2ProvisionedAmiSlave(List<Tag> tags, String description) {
for (Tag tag : tags) {
if (StringUtils.equals(tag.getKey(), EC2Tag.TAG_NAME_JENKINS_SLAVE_TYPE)) {
if (description == null) {
return true;
} else if (StringUtils.equals(tag.getValue(), EC2Cloud.EC2_SLAVE_TYPE_DEMAND)
|| StringUtils.equals(tag.getValue(), EC2Cloud.EC2_SLAVE_TYPE_SPOT)) {
// To handle cases where description is null and also upgrade cases for existing slave nodes.
return true;
} else if (StringUtils.equals(tag.getValue(), getSlaveTypeTagValue(EC2Cloud.EC2_SLAVE_TYPE_DEMAND, description))
|| StringUtils.equals(tag.getValue(), getSlaveTypeTagValue(EC2Cloud.EC2_SLAVE_TYPE_SPOT, description))) {
return true;
} else {
return false;
}
}
}
return false;
}
/**
* Returns the maximum number of possible slaves that can be created.
*/
private int getPossibleNewSlavesCount(SlaveTemplate template) throws AmazonClientException {
int estimatedTotalSlaves = countCurrentEC2Slaves(null);
int estimatedAmiSlaves = countCurrentEC2Slaves(template);
int availableTotalSlaves = instanceCap - estimatedTotalSlaves;
int availableAmiSlaves = template.getInstanceCap() - estimatedAmiSlaves;
LOGGER.log(Level.FINE, "Available Total Slaves: " + availableTotalSlaves + " Available AMI slaves: " + availableAmiSlaves
+ " AMI: " + template.getAmi() + " TemplateDesc: " + template.description);
return Math.min(availableAmiSlaves, availableTotalSlaves);
}
/**
* Obtains a slave whose AMI matches the AMI of the given template, and that also has requiredLabel (if requiredLabel is non-null)
* forceCreateNew specifies that the creation of a new slave is required. Otherwise, an existing matching slave may be re-used
*/
private synchronized EC2AbstractSlave getNewOrExistingAvailableSlave(SlaveTemplate template, Label requiredLabel, boolean forceCreateNew) {
/*
* Note this is synchronized between counting the instances and then allocating the node. Once the node is
* allocated, we don't look at that instance as available for provisioning.
*/
int possibleSlavesCount = getPossibleNewSlavesCount(template);
if (possibleSlavesCount < 0) {
LOGGER.log(Level.INFO, "Cannot provision - no capacity for instances: " + possibleSlavesCount);
return null;
}
try {
EnumSet<SlaveTemplate.ProvisionOptions> provisionOptions = EnumSet.noneOf(SlaveTemplate.ProvisionOptions.class);
if (forceCreateNew)
provisionOptions = EnumSet.of(SlaveTemplate.ProvisionOptions.FORCE_CREATE);
else if (possibleSlavesCount > 0)
provisionOptions = EnumSet.of(SlaveTemplate.ProvisionOptions.ALLOW_CREATE);
return template.provision(StreamTaskListener.fromStdout(), requiredLabel, provisionOptions);
} catch (IOException e) {
LOGGER.log(Level.WARNING, "Exception during provisioning", e);
return null;
}
}
@Override
public Collection<PlannedNode> provision(Label label, int excessWorkload) {
try {
List<PlannedNode> r = new ArrayList<PlannedNode>();
final SlaveTemplate t = getTemplate(label);
LOGGER.log(Level.INFO, "Attempting to provision slave from template " + t + " needed by excess workload of " + excessWorkload + " units of label '" + label + "'");
if (label == null) {
LOGGER.log(Level.WARNING, String.format("Label is null - can't calculate how many executors slave will have. Using %s number of executors", t.getNumExecutors()));
}
while (excessWorkload > 0) {
final EC2AbstractSlave slave = getNewOrExistingAvailableSlave(t, label, false);
// Returned null if a new node could not be created
if (slave == null)
break;
LOGGER.log(Level.INFO, String.format("We have now %s computers", Jenkins.getInstance().getComputers().length));
if (t.isNode()) {
Jenkins.getInstance().addNode(slave);
LOGGER.log(Level.INFO, String.format("Added node named: %s, We have now %s computers", slave.getNodeName(), Jenkins.getInstance().getComputers().length));
r.add(new PlannedNode(t.getDisplayName(), Computer.threadPoolForRemoting.submit(new Callable<Node>() {
public Node call() throws Exception {
long startTime = System.currentTimeMillis(); // fetch starting time
while ((System.currentTimeMillis() - startTime) < slave.launchTimeout * 1000) {
return tryToCallSlave(slave, t);
}
LOGGER.log(Level.WARNING, "Expected - Instance - failed to connect within launch timeout");
return tryToCallSlave(slave, t);
}
}), t.getNumExecutors()));
}
excessWorkload -= t.getNumExecutors();
}
LOGGER.log(Level.INFO, "Attempting provision - finished, excess workload: " + excessWorkload);
return r;
} catch (AmazonClientException e) {
LOGGER.log(Level.WARNING, "Exception during provisioning", e);
return Collections.emptyList();
} catch (IOException e) {
LOGGER.log(Level.WARNING, "Exception during provisioning", e);
return Collections.emptyList();
}
}
private EC2AbstractSlave tryToCallSlave(EC2AbstractSlave slave, SlaveTemplate template) {
try {
slave.toComputer().connect(false).get();
} catch (Exception e) {
if (template.spotConfig != null) {
if(StringUtils.isNotEmpty(slave.getInstanceId()) && slave.isConnected) {
LOGGER.log(Level.INFO, String.format("Instance id: %s for node: %s is connected now.", slave.getInstanceId(), slave.getNodeName()));
return slave;
}
}
}
return slave;
}
@Override
public boolean canProvision(Label label) {
return getTemplate(label) != null;
}
private AWSCredentialsProvider createCredentialsProvider() {
return createCredentialsProvider(useInstanceProfileForCredentials, credentialsId);
}
public static String getSlaveTypeTagValue(String slaveType, String templateDescription) {
return templateDescription != null ? slaveType + "_" + templateDescription : slaveType;
}
public static AWSCredentialsProvider createCredentialsProvider(final boolean useInstanceProfileForCredentials, final String credentialsId) {
if (useInstanceProfileForCredentials) {
return new InstanceProfileCredentialsProvider();
} else if (StringUtils.isBlank(credentialsId)) {
return new DefaultAWSCredentialsProviderChain();
} else {
AmazonWebServicesCredentials credentials = getCredentials(credentialsId);
return new StaticCredentialsProvider(credentials.getCredentials());
}
}
@CheckForNull
private static AmazonWebServicesCredentials getCredentials(@Nullable String credentialsId) {
if (StringUtils.isBlank(credentialsId)) {
return null;
}
return (AmazonWebServicesCredentials) CredentialsMatchers.firstOrNull(
CredentialsProvider.lookupCredentials(AmazonWebServicesCredentials.class, Jenkins.getInstance(),
ACL.SYSTEM, Collections.EMPTY_LIST),
CredentialsMatchers.withId(credentialsId));
}
/**
* Connects to EC2 and returns {@link AmazonEC2}, which can then be used to communicate with EC2.
*/
public synchronized AmazonEC2 connect() throws AmazonClientException {
try {
if (connection == null) {
connection = connect(createCredentialsProvider(), getEc2EndpointUrl());
}
return connection;
} catch (IOException e) {
throw new AmazonClientException("Failed to retrieve the endpoint", e);
}
}
/***
* Connect to an EC2 instance.
*
* @return {@link AmazonEC2} client
*/
public synchronized static AmazonEC2 connect(AWSCredentialsProvider credentialsProvider, URL endpoint) {
awsCredentialsProvider = credentialsProvider;
ClientConfiguration config = new ClientConfiguration();
config.setMaxErrorRetry(16); // Default retry limit (3) is low and often
// cause problems. Raise it a bit.
config.setSignerOverride("AWS4SignerType");
ProxyConfiguration proxyConfig = Jenkins.getInstance().proxy;
Proxy proxy = proxyConfig == null ? Proxy.NO_PROXY : proxyConfig.createProxy(endpoint.getHost());
if (!proxy.equals(Proxy.NO_PROXY) && proxy.address() instanceof InetSocketAddress) {
InetSocketAddress address = (InetSocketAddress) proxy.address();
config.setProxyHost(address.getHostName());
config.setProxyPort(address.getPort());
if (null != proxyConfig.getUserName()) {
config.setProxyUsername(proxyConfig.getUserName());
config.setProxyPassword(proxyConfig.getPassword());
}
}
AmazonEC2 client = new AmazonEC2Client(credentialsProvider, config);
client.setEndpoint(endpoint.toString());
return client;
}
/***
* Convert a configured hostname like 'us-east-1' to a FQDN or ip address
*/
public static String convertHostName(String ec2HostName) {
if (ec2HostName == null || ec2HostName.length() == 0)
ec2HostName = DEFAULT_EC2_HOST;
if (!ec2HostName.contains("."))
ec2HostName = "ec2." + ec2HostName + "." + AWS_URL_HOST;
return ec2HostName;
}
/***
* Convert a user entered string into a port number "" -> -1 to indicate default based on SSL setting
*/
public static Integer convertPort(String ec2Port) {
if (ec2Port == null || ec2Port.length() == 0)
return -1;
return Integer.parseInt(ec2Port);
}
/**
* Computes the presigned URL for the given S3 resource.
*
* @param path String like "/bucketName/folder/folder/abc.txt" that represents the resource to request.
*/
public URL buildPresignedURL(String path) throws AmazonClientException {
AWSCredentials credentials = awsCredentialsProvider.getCredentials();
long expires = System.currentTimeMillis() + 60 * 60 * 1000;
GeneratePresignedUrlRequest request = new GeneratePresignedUrlRequest(path, credentials.getAWSSecretKey());
request.setExpiration(new Date(expires));
AmazonS3 s3 = new AmazonS3Client(credentials);
return s3.generatePresignedUrl(request);
}
/* Parse a url or return a sensible error */
public static URL checkEndPoint(String url) throws FormValidation {
try {
return new URL(url);
} catch (MalformedURLException ex) {
throw FormValidation.error("Endpoint URL is not a valid URL");
}
}
public static abstract class DescriptorImpl extends Descriptor<Cloud> {
public InstanceType[] getInstanceTypes() {
return InstanceType.values();
}
public FormValidation doCheckUseInstanceProfileForCredentials(@QueryParameter boolean value) {
if (value) {
try {
new InstanceProfileCredentialsProvider().getCredentials();
} catch (AmazonClientException e) {
return FormValidation.error(Messages.EC2Cloud_FailedToObtainCredentailsFromEC2(), e.getMessage());
}
}
return FormValidation.ok();
}
public FormValidation doCheckPrivateKey(@QueryParameter String value) throws IOException, ServletException {
boolean hasStart = false, hasEnd = false;
BufferedReader br = new BufferedReader(new StringReader(value));
String line;
while ((line = br.readLine()) != null) {
if (line.equals("
hasStart = true;
if (line.equals("
hasEnd = true;
}
if (!hasStart)
return FormValidation.error("This doesn't look like a private key at all");
if (!hasEnd)
return FormValidation
.error("The private key is missing the trailing 'END RSA PRIVATE KEY' marker. Copy&paste error?");
return FormValidation.ok();
}
protected FormValidation doTestConnection(URL ec2endpoint, boolean useInstanceProfileForCredentials, String credentialsId, String privateKey)
throws IOException, ServletException {
try {
AWSCredentialsProvider credentialsProvider = createCredentialsProvider(useInstanceProfileForCredentials, credentialsId);
AmazonEC2 ec2 = connect(credentialsProvider, ec2endpoint);
ec2.describeInstances();
if (privateKey == null)
return FormValidation.error("Private key is not specified. Click 'Generate Key' to generate one.");
if (privateKey.trim().length() > 0) {
// check if this key exists
EC2PrivateKey pk = new EC2PrivateKey(privateKey);
if (pk.find(ec2) == null)
return FormValidation
.error("The EC2 key pair private key isn't registered to this EC2 region (fingerprint is "
+ pk.getFingerprint() + ")");
}
return FormValidation.ok(Messages.EC2Cloud_Success());
} catch (AmazonClientException e) {
LOGGER.log(Level.WARNING, "Failed to check EC2 credential", e);
return FormValidation.error(e.getMessage());
}
}
public FormValidation doGenerateKey(StaplerResponse rsp, URL ec2EndpointUrl, boolean useInstanceProfileForCredentials, String credentialsId)
throws IOException, ServletException {
try {
AWSCredentialsProvider credentialsProvider = createCredentialsProvider(useInstanceProfileForCredentials, credentialsId);
AmazonEC2 ec2 = connect(credentialsProvider, ec2EndpointUrl);
List<KeyPairInfo> existingKeys = ec2.describeKeyPairs().getKeyPairs();
int n = 0;
while (true) {
boolean found = false;
for (KeyPairInfo k : existingKeys) {
if (k.getKeyName().equals("hudson-" + n))
found = true;
}
if (!found)
break;
n++;
}
CreateKeyPairRequest request = new CreateKeyPairRequest("hudson-" + n);
KeyPair key = ec2.createKeyPair(request).getKeyPair();
rsp.addHeader("script",
"findPreviousFormItem(button,'privateKey').value='" + key.getKeyMaterial().replace("\n", "\\n") + "'");
return FormValidation.ok(Messages.EC2Cloud_Success());
} catch (AmazonClientException e) {
LOGGER.log(Level.WARNING, "Failed to check EC2 credential", e);
return FormValidation.error(e.getMessage());
}
}
public ListBoxModel doFillCredentialsIdItems() {
return new StandardListBoxModel()
.withEmptySelection()
.withMatching(
CredentialsMatchers.always(),
CredentialsProvider.lookupCredentials(AmazonWebServicesCredentials.class,
Jenkins.getInstance(),
ACL.SYSTEM,
Collections.EMPTY_LIST));
}
}
public static void log(Logger logger, Level level, TaskListener listener, String message) {
log(logger, level, listener, message, null);
}
public static void log(Logger logger, Level level, TaskListener listener, String message, Throwable exception) {
logger.log(level, message, exception);
if (listener != null) {
if (exception != null)
message += " Exception: " + exception;
LogRecord lr = new LogRecord(level, message);
PrintStream printStream = listener.getLogger();
printStream.print(sf.format(lr));
}
}
}
|
package ixa.kaflib;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.Comment;
import org.jdom2.Namespace;
import org.jdom2.CDATA;
import org.jdom2.output.XMLOutputter;
import org.jdom2.output.Format;
import org.jdom2.input.SAXBuilder;
import org.jdom2.JDOMException;
import org.jdom2.xpath.XPathExpression;
import java.util.List;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Collections;
import java.util.Comparator;
import java.io.File;
import java.io.Writer;
import java.io.Reader;
import java.io.BufferedWriter;
import java.io.OutputStreamWriter;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.regex.*;
/** Reads XML files in KAF format and loads the content in a KAFDocument object, and writes the content into XML files. */
class ReadWriteManager {
/** Loads the content of a KAF file into the given KAFDocument object */
static KAFDocument load(File file) throws IOException, JDOMException, KAFNotValidException {
SAXBuilder builder = new SAXBuilder();
Document document = (Document) builder.build(file);
Element rootElem = document.getRootElement();
return DOMToKAF(document);
}
/** Loads the content of a String in KAF format into the given KAFDocument object */
static KAFDocument load(Reader stream) throws IOException, JDOMException, KAFNotValidException {
SAXBuilder builder = new SAXBuilder();
Document document = (Document) builder.build(stream);
Element rootElem = document.getRootElement();
return DOMToKAF(document);
}
/** Writes the content of a given KAFDocument to a file. */
static void save(KAFDocument kaf, String filename) {
try {
File file = new File(filename);
Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF8"));
out.write(kafToStr(kaf));
out.flush();
} catch (Exception e) {
System.out.println("Error writing to file");
}
}
/** Writes the content of a KAFDocument object to standard output. */
static void print(KAFDocument kaf) {
try {
Writer out = new BufferedWriter(new OutputStreamWriter(System.out, "UTF8"));
out.write(kafToStr(kaf));
out.flush();
} catch (Exception e) {
System.out.println(e);
}
}
/** Returns a string containing the XML content of a KAFDocument object. */
static String kafToStr(KAFDocument kaf) {
XMLOutputter out = new XMLOutputter(Format.getPrettyFormat());
Document jdom = KAFToDOM(kaf);
return out.outputString(jdom);
}
/** Loads a KAFDocument object from XML content in DOM format */
private static KAFDocument DOMToKAF(Document dom) throws KAFNotValidException {
HashMap<String, WF> wfIndex = new HashMap<String, WF>();
HashMap<String, Term> termIndex = new HashMap<String, Term>();
HashMap<String, Relational> relationalIndex = new HashMap<String, Relational>();
Element rootElem = dom.getRootElement();
String lang = getAttribute("lang", rootElem, Namespace.XML_NAMESPACE);
String kafVersion = getAttribute("version", rootElem);
KAFDocument kaf = new KAFDocument(lang, kafVersion);
List<Element> rootChildrenElems = rootElem.getChildren();
for (Element elem : rootChildrenElems) {
if (elem.getName().equals("kafHeader")) {
List<Element> lpsElems = elem.getChildren("linguisticProcessors");
for (Element lpsElem : lpsElems) {
String layer = getAttribute("layer", lpsElem);
List<Element> lpElems = lpsElem.getChildren();
for (Element lpElem : lpElems) {
String name = getAttribute("name", lpElem);
String timestamp = getOptAttribute("timestamp", lpElem);
String version = getOptAttribute("version", lpElem);
kaf.addLinguisticProcessor(layer, name, timestamp, version);
}
}
Element fileDescElem = elem.getChild("fileDesc");
if (fileDescElem != null) {
KAFDocument.FileDesc fd = kaf.createFileDesc();
String author = getOptAttribute("author", fileDescElem);
if (author != null) {
fd.author = author;
}
String title = getOptAttribute("title", fileDescElem);
if (title != null) {
fd.title = title;
}
String creationtime = getOptAttribute("creationtime", fileDescElem);
if (creationtime != null) {
fd.creationtime = creationtime;
}
String filename = getOptAttribute("filename", fileDescElem);
if (filename != null) {
fd.filename = filename;
}
String filetype = getOptAttribute("filetype", fileDescElem);
if (filetype != null) {
fd.filetype = filetype;
}
String pages = getOptAttribute("pages", fileDescElem);
if (pages != null) {
fd.pages = Integer.parseInt(pages);
}
}
Element publicElem = elem.getChild("public");
if (publicElem != null) {
String publicId = getAttribute("publicId", publicElem);
KAFDocument.Public pub = kaf.createPublic(publicId);
String uri = getOptAttribute("uri", publicElem);
if (uri != null) {
pub.uri = uri;
}
}
}
if (elem.getName().equals("raw")) {
kaf.setRawText(elem.getText());
}
if (elem.getName().equals("text")) {
List<Element> wfElems = elem.getChildren();
for (Element wfElem : wfElems) {
String wid = getAttribute("wid", wfElem);
String wForm = wfElem.getText();
String wSent = getOptAttribute("sent", wfElem);
WF newWf = kaf.newWF(wid, wForm, Integer.valueOf(wSent));
String wPara = getOptAttribute("para", wfElem);
if (wPara != null) {
newWf.setPara(Integer.valueOf(wPara));
}
String wPage = getOptAttribute("page", wfElem);
if (wPage != null) {
newWf.setPage(Integer.valueOf(wPage));
}
String wOffset = getOptAttribute("offset", wfElem);
if (wOffset != null) {
newWf.setOffset(Integer.valueOf(wOffset));
}
String wLength = getOptAttribute("length", wfElem);
if (wLength != null) {
newWf.setLength(Integer.valueOf(wLength));
}
String wXpath = getOptAttribute("xpath", wfElem);
if (wXpath != null) {
newWf.setXpath(wXpath);
}
wfIndex.put(newWf.getId(), newWf);
}
}
if (elem.getName().equals("terms")) {
List<Element> termElems = elem.getChildren();
for (Element termElem : termElems) {
String tid = getAttribute("tid", termElem);
String type = getAttribute("type", termElem);
String lemma = getAttribute("lemma", termElem);
String pos = getAttribute("pos", termElem);
Element spanElem = termElem.getChild("span");
if (spanElem == null) {
throw new IllegalStateException("Every term must contain a span element");
}
List<Element> termsWfElems = spanElem.getChildren("target");
Span<WF> span = kaf.newWFSpan();
for (Element termsWfElem : termsWfElems) {
String wfId = getAttribute("id", termsWfElem);
boolean isHead = isHead(termsWfElem);
WF wf = wfIndex.get(wfId);
if (wf == null) {
throw new KAFNotValidException("Wf " + wfId + " not found when loading term " + tid);
}
span.addTarget(wf, isHead);
}
Term newTerm = kaf.newTerm(tid, type, lemma, pos, span);
String tMorphofeat = getOptAttribute("morphofeat", termElem);
if (tMorphofeat != null) {
newTerm.setMorphofeat(tMorphofeat);
}
String tHead = getOptAttribute("head", termElem);
String termcase = getOptAttribute("case", termElem);
if (termcase != null) {
newTerm.setCase(termcase);
}
List<Element> sentimentElems = termElem.getChildren("sentiment");
if (sentimentElems.size() > 0) {
Element sentimentElem = sentimentElems.get(0);
Term.Sentiment newSentiment = kaf.newSentiment();
String sentResource = getOptAttribute("resource", sentimentElem);
if (sentResource != null) {
newSentiment.setResource(sentResource);
}
String sentPolarity = getOptAttribute("polarity", sentimentElem);
if (sentPolarity != null) {
newSentiment.setPolarity(sentPolarity);
}
String sentStrength = getOptAttribute("strength", sentimentElem);
if (sentStrength != null) {
newSentiment.setStrength(sentStrength);
}
String sentSubjectivity = getOptAttribute("subjectivity", sentimentElem);
if (sentSubjectivity != null) {
newSentiment.setSubjectivity(sentSubjectivity);
}
String sentSentimentSemanticType = getOptAttribute("sentiment_semantic_type", sentimentElem);
if (sentSentimentSemanticType != null) {
newSentiment.setSentimentSemanticType(sentSentimentSemanticType);
}
String sentSentimentModifier = getOptAttribute("sentiment_modifier", sentimentElem);
if (sentSentimentModifier != null) {
newSentiment.setSentimentModifier(sentSentimentModifier);
}
String sentSentimentMarker = getOptAttribute("sentiment_marker", sentimentElem);
if (sentSentimentMarker != null) {
newSentiment.setSentimentMarker(sentSentimentMarker);
}
String sentSentimentProductFeature = getOptAttribute("sentiment_product_feature", sentimentElem);
if (sentSentimentProductFeature != null) {
newSentiment.setSentimentProductFeature(sentSentimentProductFeature);
}
newTerm.setSentiment(newSentiment);
}
List<Element> termsComponentElems = termElem.getChildren("component");
for (Element termsComponentElem : termsComponentElems) {
String compId = getAttribute("id", termsComponentElem);
boolean isHead = ((tHead != null) && tHead.equals(compId));
String compLemma = getAttribute("lemma", termsComponentElem);
String compPos = getAttribute("pos", termsComponentElem);
Term.Component newComponent = kaf.newComponent(compId, newTerm, compLemma, compPos);
List<Element> externalReferencesElems = termsComponentElem.getChildren("externalReferences");
if (externalReferencesElems.size() > 0) {
List<ExternalRef> externalRefs = getExternalReferences(externalReferencesElems.get(0), kaf);
newComponent.addExternalRefs(externalRefs);
}
newTerm.addComponent(newComponent, isHead);
}
List<Element> externalReferencesElems = termElem.getChildren("externalReferences");
if (externalReferencesElems.size() > 0) {
List<ExternalRef> externalRefs = getExternalReferences(externalReferencesElems.get(0), kaf);
newTerm.addExternalRefs(externalRefs);
}
termIndex.put(newTerm.getId(), newTerm);
}
}
if (elem.getName().equals("deps")) {
List<Element> depElems = elem.getChildren();
for (Element depElem : depElems) {
String fromId = getAttribute("from", depElem);
String toId = getAttribute("to", depElem);
Term from = termIndex.get(fromId);
if (from == null) {
throw new KAFNotValidException("Term " + fromId + " not found when loading Dep (" + fromId + ", " + toId + ")");
}
Term to = termIndex.get(toId);
if (to == null) {
throw new KAFNotValidException("Term " + toId + " not found when loading Dep (" + fromId + ", " + toId + ")");
}
String rfunc = getAttribute("rfunc", depElem);
Dep newDep = kaf.newDep(from, to, rfunc);
String depcase = getOptAttribute("case", depElem);
if (depcase != null) {
newDep.setCase(depcase);
}
}
}
if (elem.getName().equals("chunks")) {
List<Element> chunkElems = elem.getChildren();
for (Element chunkElem : chunkElems) {
String chunkId = getAttribute("cid", chunkElem);
String headId = getAttribute("head", chunkElem);
Term chunkHead = termIndex.get(headId);
if (chunkHead == null) {
throw new KAFNotValidException("Term " + headId + " not found when loading chunk " + chunkId);
}
String chunkPhrase = getAttribute("phrase", chunkElem);
Element spanElem = chunkElem.getChild("span");
if (spanElem == null) {
throw new IllegalStateException("Every chunk must contain a span element");
}
List<Element> chunksTermElems = spanElem.getChildren("target");
Span<Term> span = kaf.newTermSpan();
for (Element chunksTermElem : chunksTermElems) {
String termId = getAttribute("id", chunksTermElem);
boolean isHead = isHead(chunksTermElem);
Term targetTerm = termIndex.get(termId);
if (targetTerm == null) {
throw new KAFNotValidException("Term " + termId + " not found when loading chunk " + chunkId);
}
span.addTarget(targetTerm, ((targetTerm == chunkHead) || isHead));
}
if (!span.hasTarget(chunkHead)) {
throw new KAFNotValidException("The head of the chunk is not in it's span.");
}
Chunk newChunk = kaf.newChunk(chunkId, chunkPhrase, span);
String chunkCase = getOptAttribute("case", chunkElem);
if (chunkCase != null) {
newChunk.setCase(chunkCase);
}
}
}
if (elem.getName().equals("entities")) {
List<Element> entityElems = elem.getChildren();
for (Element entityElem : entityElems) {
String entId = getAttribute("eid", entityElem);
String entType = getOptAttribute("type", entityElem);
List<Element> referencesElem = entityElem.getChildren("references");
if (referencesElem.size() < 1) {
throw new IllegalStateException("Every entity must contain a 'references' element");
}
List<Element> spanElems = referencesElem.get(0).getChildren();
if (spanElems.size() < 1) {
throw new IllegalStateException("Every entity must contain a 'span' element inside 'references'");
}
List<Span<Term>> references = new ArrayList<Span<Term>>();
for (Element spanElem : spanElems) {
Span<Term> span = kaf.newTermSpan();
List<Element> targetElems = spanElem.getChildren();
if (targetElems.size() < 1) {
throw new IllegalStateException("Every span in an entity must contain at least one target inside");
}
for (Element targetElem : targetElems) {
String targetTermId = getAttribute("id", targetElem);
Term targetTerm = termIndex.get(targetTermId);
if (targetTerm == null) {
throw new KAFNotValidException("Term " + targetTermId + " not found when loading entity " + entId);
}
boolean isHead = isHead(targetElem);
span.addTarget(targetTerm, isHead);
}
references.add(span);
}
Entity newEntity = kaf.newEntity(entId, references);
if (entType != null) {
newEntity.setType(entType);
}
List<Element> externalReferencesElems = entityElem.getChildren("externalReferences");
if (externalReferencesElems.size() > 0) {
List<ExternalRef> externalRefs = getExternalReferences(externalReferencesElems.get(0), kaf);
newEntity.addExternalRefs(externalRefs);
}
relationalIndex.put(newEntity.getId(), newEntity);
}
}
if (elem.getName().equals("coreferences")) {
List<Element> corefElems = elem.getChildren();
for (Element corefElem : corefElems) {
String coId = getAttribute("coid", corefElem);
List<Element> spanElems = corefElem.getChildren("span");
if (spanElems.size() < 1) {
throw new IllegalStateException("Every coref must contain a 'span' element inside 'references'");
}
List<Span<Term>> mentions = new ArrayList<Span<Term>>();
for (Element spanElem : spanElems) {
Span<Term> span = kaf.newTermSpan();
List<Element> targetElems = spanElem.getChildren();
if (targetElems.size() < 1) {
throw new IllegalStateException("Every span in an entity must contain at least one target inside");
}
for (Element targetElem : targetElems) {
String targetTermId = getAttribute("id", targetElem);
Term targetTerm = termIndex.get(targetTermId);
if (targetTerm == null) {
throw new KAFNotValidException("Term " + targetTermId + " not found when loading coref " + coId);
}
boolean isHead = isHead(targetElem);
span.addTarget(targetTerm, isHead);
}
mentions.add(span);
}
Coref newCoref = kaf.newCoref(coId, mentions);
}
}
if (elem.getName().equals("features")) {
Element propertiesElem = elem.getChild("properties");
Element categoriesElem = elem.getChild("categories");
if (propertiesElem != null) {
List<Element> propertyElems = propertiesElem.getChildren("property");
for (Element propertyElem : propertyElems) {
String pid = getAttribute("pid", propertyElem);
String lemma = getAttribute("lemma", propertyElem);
Element referencesElem = propertyElem.getChild("references");
if (referencesElem == null) {
throw new IllegalStateException("Every property must contain a 'references' element");
}
List<Element> spanElems = referencesElem.getChildren("span");
if (spanElems.size() < 1) {
throw new IllegalStateException("Every property must contain a 'span' element inside 'references'");
}
List<Span<Term>> references = new ArrayList<Span<Term>>();
for (Element spanElem : spanElems) {
Span<Term> span = kaf.newTermSpan();
List<Element> targetElems = spanElem.getChildren();
if (targetElems.size() < 1) {
throw new IllegalStateException("Every span in a property must contain at least one target inside");
}
for (Element targetElem : targetElems) {
String targetTermId = getAttribute("id", targetElem);
Term targetTerm = termIndex.get(targetTermId);
if (targetTerm == null) {
throw new KAFNotValidException("Term " + targetTermId + " not found when loading property " + pid);
}
boolean isHead = isHead(targetElem);
span.addTarget(targetTerm, isHead);
}
references.add(span);
}
Feature newProperty = kaf.newProperty(pid, lemma, references);
List<Element> externalReferencesElems = propertyElem.getChildren("externalReferences");
if (externalReferencesElems.size() > 0) {
List<ExternalRef> externalRefs = getExternalReferences(externalReferencesElems.get(0), kaf);
newProperty.addExternalRefs(externalRefs);
}
relationalIndex.put(newProperty.getId(), newProperty);
}
}
if (categoriesElem != null) {
List<Element> categoryElems = categoriesElem.getChildren("category");
for (Element categoryElem : categoryElems) {
String cid = getAttribute("cid", categoryElem);
String lemma = getAttribute("lemma", categoryElem);
Element referencesElem = categoryElem.getChild("references");
if (referencesElem == null) {
throw new IllegalStateException("Every category must contain a 'references' element");
}
List<Element> spanElems = referencesElem.getChildren("span");
if (spanElems.size() < 1) {
throw new IllegalStateException("Every category must contain a 'span' element inside 'references'");
}
List<Span<Term>> references = new ArrayList<Span<Term>>();
for (Element spanElem : spanElems) {
Span<Term> span = kaf.newTermSpan();
List<Element> targetElems = spanElem.getChildren();
if (targetElems.size() < 1) {
throw new IllegalStateException("Every span in a property must contain at least one target inside");
}
for (Element targetElem : targetElems) {
String targetTermId = getAttribute("id", targetElem);
Term targetTerm = termIndex.get(targetTermId);
if (targetTerm == null) {
throw new KAFNotValidException("Term " + targetTermId + " not found when loading category " + cid);
}
boolean isHead = isHead(targetElem);
span.addTarget(targetTerm, isHead);
}
references.add(span);
}
Feature newCategory = kaf.newCategory(cid, lemma, references);
List<Element> externalReferencesElems = categoryElem.getChildren("externalReferences");
if (externalReferencesElems.size() > 0) {
List<ExternalRef> externalRefs = getExternalReferences(externalReferencesElems.get(0), kaf);
newCategory.addExternalRefs(externalRefs);
}
relationalIndex.put(newCategory.getId(), newCategory);
}
}
}
if (elem.getName().equals("opinions")) {
List<Element> opinionElems = elem.getChildren("opinion");
for (Element opinionElem : opinionElems) {
String opinionId = getAttribute("oid", opinionElem);
Opinion opinion = kaf.newOpinion(opinionId);
Element opinionHolderElem = opinionElem.getChild("opinion_holder");
if (opinionHolderElem != null) {
Span<Term> span = kaf.newTermSpan();
Opinion.OpinionHolder opinionHolder = opinion.createOpinionHolder(span);
Element spanElem = opinionHolderElem.getChild("span");
if (spanElem != null) {
List<Element> targetElems = spanElem.getChildren("target");
for (Element targetElem : targetElems) {
String refId = getOptAttribute("id", targetElem);
boolean isHead = isHead(targetElem);
Term targetTerm = termIndex.get(refId);
if (targetTerm == null) {
throw new KAFNotValidException("Term " + refId + " not found when loading opinion " + opinionId);
}
span.addTarget(targetTerm, isHead);
}
}
}
Element opinionTargetElem = opinionElem.getChild("opinion_target");
if (opinionTargetElem != null) {
Span<Term> span = kaf.newTermSpan();
Opinion.OpinionTarget opinionTarget = opinion.createOpinionTarget(span);
Element spanElem = opinionTargetElem.getChild("span");
if (spanElem != null) {
List<Element> targetElems = spanElem.getChildren("target");
for (Element targetElem : targetElems) {
String refId = getOptAttribute("id", targetElem);
boolean isHead = isHead(targetElem);
Term targetTerm = termIndex.get(refId);
if (targetTerm == null) {
throw new KAFNotValidException("Term " + refId + " not found when loading opinion " + opinionId);
}
span.addTarget(targetTerm, isHead);
}
}
}
Element opinionExpressionElem = opinionElem.getChild("opinion_expression");
if (opinionExpressionElem != null) {
Span<Term> span = kaf.newTermSpan();
String polarity = getOptAttribute("polarity", opinionExpressionElem);
String strength = getOptAttribute("strength", opinionExpressionElem);
String subjectivity = getOptAttribute("subjectivity", opinionExpressionElem);
String sentimentSemanticType = getOptAttribute("sentiment_semantic_type", opinionExpressionElem);
String sentimentProductFeature = getOptAttribute("sentiment_product_feature", opinionExpressionElem);
Opinion.OpinionExpression opinionExpression = opinion.createOpinionExpression(span);
if (polarity != null) {
opinionExpression.setPolarity(polarity);
}
if (strength != null) {
opinionExpression.setStrength(strength);
}
if (subjectivity != null) {
opinionExpression.setSubjectivity(subjectivity);
}
if (sentimentSemanticType != null) {
opinionExpression.setSentimentSemanticType(sentimentSemanticType);
}
if (sentimentProductFeature != null) {
opinionExpression.setSentimentProductFeature(sentimentProductFeature);
}
Element spanElem = opinionExpressionElem.getChild("span");
if (spanElem != null) {
List<Element> targetElems = spanElem.getChildren("target");
for (Element targetElem : targetElems) {
String refId = getOptAttribute("id", targetElem);
boolean isHead = isHead(targetElem);
Term targetTerm = termIndex.get(refId);
if (targetTerm == null) {
throw new KAFNotValidException("Term " + refId + " not found when loading opinion " + opinionId);
}
span.addTarget(targetTerm, isHead);
}
}
}
}
}
if (elem.getName().equals("relations")) {
List<Element> relationElems = elem.getChildren("relation");
for (Element relationElem : relationElems) {
String id = getAttribute("rid", relationElem);
String fromId = getAttribute("from", relationElem);
String toId = getAttribute("to", relationElem);
String confidenceStr = getOptAttribute("confidence", relationElem);
float confidence = -1.0f;
if (confidenceStr != null) {
confidence = Float.parseFloat(confidenceStr);
}
Relational from = relationalIndex.get(fromId);
if (from == null) {
throw new KAFNotValidException("Entity/feature object " + fromId + " not found when loading relation " + id);
}
Relational to = relationalIndex.get(toId);
if (to == null) {
throw new KAFNotValidException("Entity/feature object " + toId + " not found when loading relation " + id);
}
Relation newRelation = kaf.newRelation(id, from, to);
if (confidence >= 0) {
newRelation.setConfidence(confidence);
}
}
}
if (elem.getName().equals("srl")) {
List<Element> predicateElems = elem.getChildren("predicate");
for (Element predicateElem : predicateElems) {
String id = getAttribute("prid", predicateElem);
String uri = getOptAttribute("uri", predicateElem);
Span<Term> span = kaf.newTermSpan();
Element spanElem = predicateElem.getChild("span");
if (spanElem != null) {
List<Element> targetElems = spanElem.getChildren("target");
for (Element targetElem : targetElems) {
String targetId = getAttribute("id", targetElem);
boolean isHead = isHead(targetElem);
Term targetTerm = termIndex.get(targetId);
if (targetTerm == null) {
throw new KAFNotValidException("Term object " + targetId + " not found when loading predicate " + id);
}
span.addTarget(targetTerm, isHead);
}
}
Predicate newPredicate = kaf.newPredicate(id, span);
if (uri != null) {
newPredicate.setUri(uri);
}
List<Element> roleElems = predicateElem.getChildren("role");
for (Element roleElem : roleElems) {
String rid = getAttribute("rid", roleElem);
String semRole = getAttribute("semRole", roleElem);
Span<Term> roleSpan = kaf.newTermSpan();
Element roleSpanElem = roleElem.getChild("span");
if (roleSpanElem != null) {
List<Element> targetElems = roleSpanElem.getChildren("target");
for (Element targetElem : targetElems) {
String targetId = getAttribute("id", targetElem);
boolean isHead = isHead(targetElem);
Term targetTerm = termIndex.get(targetId);
if (targetTerm == null) {
throw new KAFNotValidException("Term object " + targetId + " not found when loading role " + rid);
}
roleSpan.addTarget(targetTerm, isHead);
}
}
Predicate.Role newRole = kaf.newRole(rid, newPredicate, semRole, roleSpan);
newPredicate.addRole(newRole);
}
Span<Term> spana = kaf.newTermSpan();
Predicate.Role rolea = kaf.newRole(newPredicate, "kaka", spana);
newPredicate.addRole(rolea);
}
}
if (elem.getName().equals("constituents")) {
List<Element> treeElems = elem.getChildren("tree");
for (Element treeElem : treeElems) {
HashMap<String, TreeNode> treeNodes = new HashMap<String, TreeNode>();
HashMap<String, Boolean> rootNodes = new HashMap<String, Boolean>();
// Terminals
List<Element> terminalElems = treeElem.getChildren("t");
for (Element terminalElem : terminalElems) {
String id = getAttribute("id", terminalElem);
Element spanElem = terminalElem.getChild("span");
if (spanElem == null) {
throw new KAFNotValidException("Constituent non terminal nodes need a span");
}
Span<Term> span = loadTermSpan(spanElem, termIndex, id);
treeNodes.put(id, kaf.newTerminal(id, span));
rootNodes.put(id, true);
}
// NonTerminals
List<Element> nonTerminalElems = treeElem.getChildren("nt");
for (Element nonTerminalElem : nonTerminalElems) {
String id = getAttribute("id", nonTerminalElem);
String label = getAttribute("label", nonTerminalElem);
treeNodes.put(id, kaf.newNonTerminal(id, label));
rootNodes.put(id, true);
}
// Edges
List<Element> edgeElems = treeElem.getChildren("edge");
for (Element edgeElem : edgeElems) {
String fromId = getAttribute("from", edgeElem);
String toId = getAttribute("to", edgeElem);
String edgeId = getAttribute("id", edgeElem);
TreeNode parentNode = treeNodes.get(toId);
TreeNode childNode = treeNodes.get(fromId);
if ((parentNode == null) || (childNode == null)) {
throw new KAFNotValidException("There is a problem with the edge(" + fromId + ", " + toId + "). One of its targets doesn't exist.");
}
((NonTerminal) parentNode).addChild(childNode);
rootNodes.put(fromId, false);
childNode.setEdgeId(edgeId);
}
// Constituent objects
for (Map.Entry<String, Boolean> areRoot : rootNodes.entrySet()) {
if (areRoot.getValue()) {
TreeNode rootNode = treeNodes.get(areRoot.getKey());
kaf.newConstituent(rootNode);
}
}
}
}
}
return kaf;
}
private static Span<Term> loadTermSpan(Element spanElem, HashMap<String, Term> terms, String objId) throws KAFNotValidException {
List<Element> targetElems = spanElem.getChildren("target");
if (targetElems.size() < 1) {
throw new KAFNotValidException("A span element can not be empty");
}
Span<Term> span = KAFDocument.newTermSpan();
for (Element targetElem : targetElems) {
String targetId = getAttribute("id", targetElem);
boolean isHead = isHead(targetElem);
Term targetTerm = terms.get(targetId);
if (targetTerm == null) {
throw new KAFNotValidException("Term object " + targetId + " not found when loading object " + objId);
}
span.addTarget(targetTerm, isHead);
}
return span;
}
private static Element createTermSpanElem(Span<Term> span) {
Element spanElem = new Element("span");
for (Term term : span.getTargets()) {
Element targetElem = new Element("target");
String targetId = term.getId();
targetElem.setAttribute("id", targetId);
if (span.isHead(term)) {
targetElem.setAttribute("head", "yes");
}
spanElem.addContent(targetElem);
}
return spanElem;
}
private static List<ExternalRef> getExternalReferences(Element externalReferencesElem, KAFDocument kaf) {
List<ExternalRef> externalRefs = new ArrayList<ExternalRef>();
List<Element> externalRefElems = externalReferencesElem.getChildren();
for (Element externalRefElem : externalRefElems) {
ExternalRef externalRef = getExternalRef(externalRefElem, kaf);
externalRefs.add(externalRef);
}
return externalRefs;
}
private static ExternalRef getExternalRef(Element externalRefElem, KAFDocument kaf) {
String resource = getAttribute("resource", externalRefElem);
String references = getAttribute("reference", externalRefElem);
ExternalRef newExternalRef = kaf.newExternalRef(resource, references);
String confidence = getOptAttribute("confidence", externalRefElem);
if (confidence != null) {
newExternalRef.setConfidence(Float.valueOf(confidence));
}
List<Element> subRefElems = externalRefElem.getChildren("externalRef");
if (subRefElems.size() > 0) {
Element subRefElem = subRefElems.get(0);
ExternalRef subRef = getExternalRef(subRefElem, kaf);
newExternalRef.setExternalRef(subRef);
}
return newExternalRef;
}
private static String getAttribute(String attName, Element elem) {
String value = elem.getAttributeValue(attName);
if (value==null) {
throw new IllegalStateException(attName+" attribute must be defined for element "+elem.getName());
}
return value;
}
private static String getAttribute(String attName, Element elem, Namespace nmspace) {
String value = elem.getAttributeValue(attName, nmspace);
if (value==null) {
throw new IllegalStateException(attName+" attribute must be defined for element "+elem.getName());
}
return value;
}
private static String getOptAttribute(String attName, Element elem) {
String value = elem.getAttributeValue(attName);
if (value==null) {
return null;
}
return value;
}
private static boolean isHead(Element elem) {
String value = elem.getAttributeValue("head");
if (value == null) {
return false;
}
if (value.equals("yes")) {
return true;
}
return false;
}
private static class Edge {
String id;
String from;
String to;
boolean head;
Edge(TreeNode from, TreeNode to) {
this.id = from.getEdgeId();
this.from = from.getId();
this.to = to.getId();
this.head = from.getHead();
}
}
/** Returns the content of the given KAFDocument in a DOM document. */
private static Document KAFToDOM(KAFDocument kaf) {
AnnotationContainer annotationContainer = kaf.getAnnotationContainer();
Element root = new Element("KAF");
root.setAttribute("lang", kaf.getLang(), Namespace.XML_NAMESPACE);
root.setAttribute("version", kaf.getVersion());
Document doc = new Document(root);
Element kafHeaderElem = new Element("kafHeader");
root.addContent(kafHeaderElem);
KAFDocument.FileDesc fd = kaf.getFileDesc();
if (fd != null) {
Element fdElem = new Element("fileDesc");
if (fd.author != null) {
fdElem.setAttribute("author", fd.author);
}
if (fd.author != null) {
fdElem.setAttribute("title", fd.title);
}
if (fd.creationtime != null) {
fdElem.setAttribute("creationtime", fd.creationtime);
}
if (fd.author != null) {
fdElem.setAttribute("filename", fd.filename);
}
if (fd.author != null) {
fdElem.setAttribute("filetype", fd.filetype);
}
if (fd.author != null) {
fdElem.setAttribute("pages", Integer.toString(fd.pages));
}
kafHeaderElem.addContent(fdElem);
}
KAFDocument.Public pub = kaf.getPublic();
if (pub != null) {
Element pubElem = new Element("public");
pubElem.setAttribute("publicId", pub.publicId);
if (pub.uri != null) {
pubElem.setAttribute("uri", pub.uri);
}
kafHeaderElem.addContent(pubElem);
}
Map<String, List<KAFDocument.LinguisticProcessor>> lps = kaf.getLinguisticProcessors();
for (Map.Entry entry : lps.entrySet()) {
Element lpsElem = new Element("linguisticProcessors");
lpsElem.setAttribute("layer", (String) entry.getKey());
for (KAFDocument.LinguisticProcessor lp : (List<KAFDocument.LinguisticProcessor>) entry.getValue()) {
Element lpElem = new Element("lp");
lpElem.setAttribute("name", lp.name);
lpElem.setAttribute("timestamp", lp.timestamp);
lpElem.setAttribute("version", lp.version);
lpsElem.addContent(lpElem);
}
kafHeaderElem.addContent(lpsElem);
}
String rawText = annotationContainer.getRawText();
if (rawText.length() > 0) {
Element rawElem = new Element("raw");
CDATA cdataElem = new CDATA(rawText);
rawElem.addContent(cdataElem);
root.addContent(rawElem);
}
List<WF> text = annotationContainer.getText();
if (text.size() > 0) {
Element textElem = new Element("text");
for (WF wf : text) {
Element wfElem = new Element("wf");
wfElem.setAttribute("wid", wf.getId());
if (wf.hasSent()) {
wfElem.setAttribute("sent", Integer.toString(wf.getSent()));
}
if (wf.hasPara()) {
wfElem.setAttribute("para", Integer.toString(wf.getPara()));
}
if (wf.hasPage()) {
wfElem.setAttribute("page", Integer.toString(wf.getPage()));
}
if (wf.hasOffset()) {
wfElem.setAttribute("offset", Integer.toString(wf.getOffset()));
}
if (wf.hasLength()) {
wfElem.setAttribute("length", Integer.toString(wf.getLength()));
}
if (wf.hasXpath()) {
wfElem.setAttribute("xpath", wf.getXpath());
}
wfElem.setText(wf.getForm());
textElem.addContent(wfElem);
}
root.addContent(textElem);
}
List<Term> terms = annotationContainer.getTerms();
if (terms.size() > 0) {
Element termsElem = new Element("terms");
for (Term term : terms) {
String morphofeat;
Term.Component head;
String termcase;
Comment termComment = new Comment(term.getStr());
termsElem.addContent(termComment);
Element termElem = new Element("term");
termElem.setAttribute("tid", term.getId());
termElem.setAttribute("type", term.getType());
termElem.setAttribute("lemma", term.getLemma());
termElem.setAttribute("pos", term.getPos());
if (term.hasMorphofeat()) {
termElem.setAttribute("morphofeat", term.getMorphofeat());
}
if (term.hasHead()) {
termElem.setAttribute("head", term.getHead().getId());
}
if (term.hasCase()) {
termElem.setAttribute("case", term.getCase());
}
if (term.hasSentiment()) {
Term.Sentiment sentiment = term.getSentiment();
Element sentimentElem = new Element("sentiment");
if (sentiment.hasResource()) {
sentimentElem.setAttribute("resource", sentiment.getResource());
}
if (sentiment.hasPolarity()) {
sentimentElem.setAttribute("polarity", sentiment.getPolarity());
}
if (sentiment.hasStrength()) {
sentimentElem.setAttribute("strength", sentiment.getStrength());
}
if (sentiment.hasSubjectivity()) {
sentimentElem.setAttribute("subjectivity", sentiment.getSubjectivity());
}
if (sentiment.hasSentimentSemanticType()) {
sentimentElem.setAttribute("sentiment_semantic_type", sentiment.getSentimentSemanticType());
}
if (sentiment.hasSentimentModifier()) {
sentimentElem.setAttribute("sentiment_modifier", sentiment.getSentimentModifier());
}
if (sentiment.hasSentimentMarker()) {
sentimentElem.setAttribute("sentiment_marker", sentiment.getSentimentMarker());
}
if (sentiment.hasSentimentProductFeature()) {
sentimentElem.setAttribute("sentiment_product_feature", sentiment.getSentimentProductFeature());
}
termElem.addContent(sentimentElem);
}
Element spanElem = new Element("span");
Span<WF> span = term.getSpan();
for (WF target : term.getWFs()) {
Element targetElem = new Element("target");
targetElem.setAttribute("id", target.getId());
if (target == span.getHead()) {
targetElem.setAttribute("head", "yes");
}
spanElem.addContent(targetElem);
}
termElem.addContent(spanElem);
List<Term.Component> components = term.getComponents();
if (components.size() > 0) {
for (Term.Component component : components) {
Element componentElem = new Element("component");
componentElem.setAttribute("id", component.getId());
componentElem.setAttribute("lemma", component.getLemma());
componentElem.setAttribute("pos", component.getPos());
if (component.hasCase()) {
componentElem.setAttribute("case", component.getCase());
}
List<ExternalRef> externalReferences = component.getExternalRefs();
if (externalReferences.size() > 0) {
Element externalReferencesElem = externalReferencesToDOM(externalReferences);
componentElem.addContent(externalReferencesElem);
}
termElem.addContent(componentElem);
}
}
List<ExternalRef> externalReferences = term.getExternalRefs();
if (externalReferences.size() > 0) {
Element externalReferencesElem = externalReferencesToDOM(externalReferences);
termElem.addContent(externalReferencesElem);
}
termsElem.addContent(termElem);
}
root.addContent(termsElem);
}
List<Dep> deps = annotationContainer.getDeps();
if (deps.size() > 0) {
Element depsElem = new Element("deps");
for (Dep dep : deps) {
Comment depComment = new Comment(dep.getStr());
depsElem.addContent(depComment);
Element depElem = new Element("dep");
depElem.setAttribute("from", dep.getFrom().getId());
depElem.setAttribute("to", dep.getTo().getId());
depElem.setAttribute("rfunc", dep.getRfunc());
if (dep.hasCase()) {
depElem.setAttribute("case", dep.getCase());
}
depsElem.addContent(depElem);
}
root.addContent(depsElem);
}
List<Chunk> chunks = annotationContainer.getChunks();
if (chunks.size() > 0) {
Element chunksElem = new Element("chunks");
for (Chunk chunk : chunks) {
Comment chunkComment = new Comment(chunk.getStr());
chunksElem.addContent(chunkComment);
Element chunkElem = new Element("chunk");
chunkElem.setAttribute("cid", chunk.getId());
chunkElem.setAttribute("head", chunk.getHead().getId());
chunkElem.setAttribute("phrase", chunk.getPhrase());
if (chunk.hasCase()) {
chunkElem.setAttribute("case", chunk.getCase());
}
Element spanElem = new Element("span");
for (Term target : chunk.getTerms()) {
Element targetElem = new Element("target");
targetElem.setAttribute("id", target.getId());
spanElem.addContent(targetElem);
}
chunkElem.addContent(spanElem);
chunksElem.addContent(chunkElem);
}
root.addContent(chunksElem);
}
List<Entity> entities = annotationContainer.getEntities();
if (entities.size() > 0) {
Element entitiesElem = new Element("entities");
for (Entity entity : entities) {
Element entityElem = new Element("entity");
entityElem.setAttribute("eid", entity.getId());
entityElem.setAttribute("type", entity.getType());
Element referencesElem = new Element("references");
for (Span<Term> span : entity.getSpans()) {
Comment spanComment = new Comment(entity.getSpanStr(span));
referencesElem.addContent(spanComment);
Element spanElem = new Element("span");
for (Term term : span.getTargets()) {
Element targetElem = new Element("target");
targetElem.setAttribute("id", term.getId());
if (term == span.getHead()) {
targetElem.setAttribute("head", "yes");
}
spanElem.addContent(targetElem);
}
referencesElem.addContent(spanElem);
}
entityElem.addContent(referencesElem);
List<ExternalRef> externalReferences = entity.getExternalRefs();
if (externalReferences.size() > 0) {
Element externalReferencesElem = externalReferencesToDOM(externalReferences);
entityElem.addContent(externalReferencesElem);
}
entitiesElem.addContent(entityElem);
}
root.addContent(entitiesElem);
}
List<Coref> corefs = annotationContainer.getCorefs();
if (corefs.size() > 0) {
Element corefsElem = new Element("coreferences");
for (Coref coref : corefs) {
Element corefElem = new Element("coref");
corefElem.setAttribute("coid", coref.getId());
for (Span<Term> span : coref.getSpans()) {
Comment spanComment = new Comment(coref.getSpanStr(span));
corefElem.addContent(spanComment);
Element spanElem = new Element("span");
for (Term target : span.getTargets()) {
Element targetElem = new Element("target");
targetElem.setAttribute("id", target.getId());
if (target == span.getHead()) {
targetElem.setAttribute("head", "yes");
}
spanElem.addContent(targetElem);
}
corefElem.addContent(spanElem);
}
corefsElem.addContent(corefElem);
}
root.addContent(corefsElem);
}
Element featuresElem = new Element("features");
List<Feature> properties = annotationContainer.getProperties();
if (properties.size() > 0) {
Element propertiesElem = new Element("properties");
for (Feature property : properties) {
Element propertyElem = new Element("property");
propertyElem.setAttribute("pid", property.getId());
propertyElem.setAttribute("lemma", property.getLemma());
List<Span<Term>> references = property.getSpans();
Element referencesElem = new Element("references");
for (Span<Term> span : references) {
Comment spanComment = new Comment(property.getSpanStr(span));
referencesElem.addContent(spanComment);
Element spanElem = new Element("span");
for (Term term : span.getTargets()) {
Element targetElem = new Element("target");
targetElem.setAttribute("id", term.getId());
if (term == span.getHead()) {
targetElem.setAttribute("head", "yes");
}
spanElem.addContent(targetElem);
}
referencesElem.addContent(spanElem);
}
propertyElem.addContent(referencesElem);
propertiesElem.addContent(propertyElem);
}
featuresElem.addContent(propertiesElem);
}
List<Feature> categories = annotationContainer.getCategories();
if (categories.size() > 0) {
Element categoriesElem = new Element("categories");
for (Feature category : categories) {
Element categoryElem = new Element("category");
categoryElem.setAttribute("cid", category.getId());
categoryElem.setAttribute("lemma", category.getLemma());
List<Span<Term>> references = category.getSpans();
Element referencesElem = new Element("references");
for (Span<Term> span : references) {
Comment spanComment = new Comment(category.getSpanStr(span));
referencesElem.addContent(spanComment);
Element spanElem = new Element("span");
for (Term term : span.getTargets()) {
Element targetElem = new Element("target");
targetElem.setAttribute("id", term.getId());
if (term == span.getHead()) {
targetElem.setAttribute("head", "yes");
}
spanElem.addContent(targetElem);
}
referencesElem.addContent(spanElem);
}
categoryElem.addContent(referencesElem);
categoriesElem.addContent(categoryElem);
}
featuresElem.addContent(categoriesElem);
}
if (featuresElem.getChildren().size() > 0) {
root.addContent(featuresElem);
}
List<Opinion> opinions = annotationContainer.getOpinions();
if (opinions.size() > 0) {
Element opinionsElem = new Element("opinions");
for (Opinion opinion : opinions) {
Element opinionElem = new Element("opinion");
opinionElem.setAttribute("oid", opinion.getId());
Opinion.OpinionHolder holder = opinion.getOpinionHolder();
if (holder != null) {
Element opinionHolderElem = new Element("opinion_holder");
Comment comment = new Comment(opinion.getSpanStr(opinion.getOpinionHolder().getSpan()));
opinionHolderElem.addContent(comment);
List<Term> targets = holder.getTerms();
Span<Term> span = holder.getSpan();
if (targets.size() > 0) {
Element spanElem = new Element("span");
opinionHolderElem.addContent(spanElem);
for (Term target : targets) {
Element targetElem = new Element("target");
targetElem.setAttribute("id", target.getId());
if (target == span.getHead()) {
targetElem.setAttribute("head", "yes");
}
spanElem.addContent(targetElem);
}
}
opinionElem.addContent(opinionHolderElem);
}
Opinion.OpinionTarget opTarget = opinion.getOpinionTarget();
if (opTarget != null) {
Element opinionTargetElem = new Element("opinion_target");
Comment comment = new Comment(opinion.getSpanStr(opinion.getOpinionTarget().getSpan()));
opinionTargetElem.addContent(comment);
List<Term> targets = opTarget.getTerms();
Span<Term> span = opTarget.getSpan();
if (targets.size() > 0) {
Element spanElem = new Element("span");
opinionTargetElem.addContent(spanElem);
for (Term target : targets) {
Element targetElem = new Element("target");
targetElem.setAttribute("id", target.getId());
if (target == span.getHead()) {
targetElem.setAttribute("head", "yes");
}
spanElem.addContent(targetElem);
}
}
opinionElem.addContent(opinionTargetElem);
}
Opinion.OpinionExpression expression = opinion.getOpinionExpression();
if (expression != null) {
Element opinionExpressionElem = new Element("opinion_expression");
Comment comment = new Comment(opinion.getSpanStr(opinion.getOpinionExpression().getSpan()));
opinionExpressionElem.addContent(comment);
if (expression.hasPolarity()) {
opinionExpressionElem.setAttribute("polarity", expression.getPolarity());
}
if (expression.hasStrength()) {
opinionExpressionElem.setAttribute("strength", expression.getStrength());
}
if (expression.hasSubjectivity()) {
opinionExpressionElem.setAttribute("subjectivity", expression.getSubjectivity());
}
if (expression.hasSentimentSemanticType()) {
opinionExpressionElem.setAttribute("sentiment_semantic_type", expression.getSentimentSemanticType());
}
if (expression.hasSentimentProductFeature()) {
opinionExpressionElem.setAttribute("sentiment_product_feature", expression.getSentimentProductFeature());
}
List<Term> targets = expression.getTerms();
Span<Term> span = expression.getSpan();
if (targets.size() > 0) {
Element spanElem = new Element("span");
opinionExpressionElem.addContent(spanElem);
for (Term target : targets) {
Element targetElem = new Element("target");
targetElem.setAttribute("id", target.getId());
if (target == span.getHead()) {
targetElem.setAttribute("head", "yes");
}
spanElem.addContent(targetElem);
}
}
opinionElem.addContent(opinionExpressionElem);
}
opinionsElem.addContent(opinionElem);
}
root.addContent(opinionsElem);
}
List<Relation> relations = annotationContainer.getRelations();
if (relations.size() > 0) {
Element relationsElem = new Element("relations");
for (Relation relation : relations) {
Comment comment = new Comment(relation.getStr());
relationsElem.addContent(comment);
Element relationElem = new Element("relation");
relationElem.setAttribute("rid", relation.getId());
relationElem.setAttribute("from", relation.getFrom().getId());
relationElem.setAttribute("to", relation.getTo().getId());
if (relation.hasConfidence()) {
relationElem.setAttribute("confidence", String.valueOf(relation.getConfidence()));
}
relationsElem.addContent(relationElem);
}
root.addContent(relationsElem);
}
List<Predicate> predicates = annotationContainer.getPredicates();
if (predicates.size() > 0) {
Element predicatesElem = new Element("srl");
for (Predicate predicate : predicates) {
Comment predicateComment = new Comment(predicate.getStr());
predicatesElem.addContent(predicateComment);
Element predicateElem = new Element("predicate");
predicateElem.setAttribute("prid", predicate.getId());
if (predicate.hasUri()) {
predicateElem.setAttribute("uri", predicate.getUri());
}
Span<Term> span = predicate.getSpan();
if (span.getTargets().size() > 0) {
Comment spanComment = new Comment(predicate.getSpanStr());
Element spanElem = new Element("span");
predicateElem.addContent(spanComment);
predicateElem.addContent(spanElem);
for (Term target : span.getTargets()) {
Element targetElem = new Element("target");
targetElem.setAttribute("id", target.getId());
if (target == span.getHead()) {
targetElem.setAttribute("head", "yes");
}
spanElem.addContent(targetElem);
}
}
for (Predicate.Role role : predicate.getRoles()) {
Element roleElem = new Element("role");
roleElem.setAttribute("rid", role.getId());
roleElem.setAttribute("semRole", role.getSemRole());
Span<Term> roleSpan = role.getSpan();
if (roleSpan.getTargets().size() > 0) {
Comment spanComment = new Comment(role.getStr());
Element spanElem = new Element("span");
roleElem.addContent(spanComment);
roleElem.addContent(spanElem);
for (Term target : roleSpan.getTargets()) {
Element targetElem = new Element("target");
targetElem.setAttribute("id", target.getId());
if (target == roleSpan.getHead()) {
targetElem.setAttribute("head", "yes");
}
spanElem.addContent(targetElem);
}
}
predicateElem.addContent(roleElem);
}
predicatesElem.addContent(predicateElem);
}
root.addContent(predicatesElem);
}
List<Tree> constituents = annotationContainer.getConstituents();
if (constituents.size() > 0) {
Element constituentsElem = new Element("constituents");
for (Tree tree : constituents) {
Element treeElem = new Element("tree");
constituentsElem.addContent(treeElem);
List<NonTerminal> nonTerminals = new LinkedList<NonTerminal>();
List<Terminal> terminals = new LinkedList<Terminal>();
List<Edge> edges = new ArrayList<Edge>();
TreeNode rootNode = tree.getRoot();
extractTreeNodes(rootNode, nonTerminals, terminals, edges);
Collections.sort(nonTerminals, new Comparator<NonTerminal>() {
public int compare(NonTerminal nt1, NonTerminal nt2) {
if (cmpId(nt1.getId(), nt2.getId()) < 0) {
return -1;
} else if (nt1.getId().equals(nt2.getId())) {
return 0;
} else {
return 1;
}
}
});
Collections.sort(terminals, new Comparator<Terminal>() {
public int compare(Terminal t1, Terminal t2) {
if (cmpId(t1.getId(), t2.getId()) < 0) {
return -1;
} else if (t1.getId().equals(t2.getId())) {
return 0;
} else {
return 1;
}
}
});
Comment ntCom = new Comment("Non-terminals");
treeElem.addContent(ntCom);
for (NonTerminal node : nonTerminals) {
Element nodeElem = new Element("nt");
nodeElem.setAttribute("id", node.getId());
nodeElem.setAttribute("label", node.getLabel());
treeElem.addContent(nodeElem);
}
Comment tCom = new Comment("Terminals");
treeElem.addContent(tCom);
for (Terminal node : terminals) {
Element nodeElem = new Element("t");
nodeElem.setAttribute("id", node.getId());
nodeElem.addContent(createTermSpanElem(node.getSpan()));
// Comment
Comment tStrCom = new Comment(node.getStr());
treeElem.addContent(tStrCom);
treeElem.addContent(nodeElem);
}
Comment edgeCom = new Comment("Tree edges");
treeElem.addContent(edgeCom);
for (Edge edge : edges) {
Element edgeElem = new Element("edge");
edgeElem.setAttribute("id", edge.id);
edgeElem.setAttribute("from", edge.from);
edgeElem.setAttribute("to", edge.to);
if (edge.head) {
edgeElem.setAttribute("head", "yes");
}
treeElem.addContent(edgeElem);
}
}
root.addContent(constituentsElem);
}
return doc;
}
private static void extractTreeNodes(TreeNode node, List<NonTerminal> nonTerminals, List<Terminal> terminals, List<Edge> edges) {
if (node instanceof NonTerminal) {
nonTerminals.add((NonTerminal) node);
List<TreeNode> treeNodes = ((NonTerminal) node).getChildren();
for (TreeNode child : treeNodes) {
edges.add(new Edge(child, node));
extractTreeNodes(child, nonTerminals, terminals, edges);
}
} else {
terminals.add((Terminal) node);
}
}
private static Element externalReferencesToDOM(List<ExternalRef> externalRefs) {
Element externalReferencesElem = new Element("externalReferences");
for (ExternalRef externalRef : externalRefs) {
Element externalRefElem = externalRefToDOM(externalRef);
externalReferencesElem.addContent(externalRefElem);
}
return externalReferencesElem;
}
private static Element externalRefToDOM(ExternalRef externalRef) {
Element externalRefElem = new Element("externalRef");
externalRefElem.setAttribute("resource", externalRef.getResource());
externalRefElem.setAttribute("reference", externalRef.getReference());
if (externalRef.hasConfidence()) {
externalRefElem.setAttribute("confidence", Float.toString(externalRef.getConfidence()));
}
if (externalRef.hasExternalRef()) {
Element subExternalRefElem = externalRefToDOM(externalRef.getExternalRef());
externalRefElem.addContent(subExternalRefElem);
}
return externalRefElem;
}
private static int cmpId(String id1, String id2) {
int nbr1 = extractNumberFromId(id1);
int nbr2 = extractNumberFromId(id2);
if (nbr1 < nbr2) {
return -1;
} else if (nbr1 == nbr2) {
return 0;
} else {
return 1;
}
}
private static int extractNumberFromId(String id) {
Matcher matcher = Pattern.compile("^[a-z]*_?(\\d+)$").matcher(id);
if (!matcher.find()) {
throw new IllegalStateException("IdManager doesn't recognise the given id's (" + id + ") format. Should be [a-z]*_?[0-9]+");
}
return Integer.valueOf(matcher.group(1));
}
}
|
package java.util.stream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.StringJoiner;
import java.util.function.BiConsumer;
import java.util.function.BinaryOperator;
import java.util.function.Function;
import java.util.function.Supplier;
public final class Collectors {
private static <T> BinaryOperator<T> throwingMerger() {
return (u, v) -> {
throw new IllegalStateException(String.format("Duplicate key %s", u));
};
}
static final Set<Collector.Characteristics> CH_ID = Collections
.unmodifiableSet(Collections.singleton(Collector.Characteristics.IDENTITY_FINISH));
static final Set<Collector.Characteristics> CH_NOID = Collections.emptySet();
static class CollectorImpl<T, A, R> implements Collector<T, A, R> {
private final Supplier<A> supplier;
private final BiConsumer<A, T> accumulator;
private final BinaryOperator<A> combiner;
private final Set<Characteristics> characteristics;
private final Function<A, R> finisher;
CollectorImpl(Supplier<A> supplier, BiConsumer<A, T> accumulator, BinaryOperator<A> combiner,
Function<A, R> finisher, Set<Characteristics> characteristics) {
this.supplier = supplier;
this.accumulator = accumulator;
this.combiner = combiner;
this.finisher = finisher;
this.characteristics = characteristics;
}
CollectorImpl(Supplier<A> supplier, BiConsumer<A, T> accumulator, BinaryOperator<A> combiner,
Set<Characteristics> characteristics) {
this(supplier, accumulator, combiner, castingIdentity(), characteristics);
}
CollectorImpl(Supplier<A> supplier, BiConsumer<A, T> accumulator, BinaryOperator<A> combiner) {
this(supplier, accumulator, combiner, castingIdentity(), null);
}
@SuppressWarnings("unchecked")
private static <I, R> Function<I, R> castingIdentity() {
return i -> (R) i;
}
@Override
public BiConsumer<A, T> accumulator() {
return accumulator;
}
@Override
public Supplier<A> supplier() {
return supplier;
}
@Override
public BinaryOperator<A> combiner() {
return combiner;
}
@Override
public Function<A, R> finisher() {
return finisher;
}
@Override
public Set<Characteristics> characteristics() {
return characteristics;
}
}
public static <T> Collector<T, ?, List<T>> toList() {
return new CollectorImpl<>(() -> new ArrayList<>(), (l, i) -> l.add(i), (left, right) -> {
left.addAll(right);
return left;
});
}
public static <T> Collector<T, ?, Set<T>> toSet() {
return new CollectorImpl<>(() -> new HashSet<>(), (s, i) -> s.add(i), (left, right) -> {
left.addAll(right);
return left;
});
}
public static <T, K, U> Collector<T, ?, Map<K, U>> toMap(Function<? super T, ? extends K> keyMapper,
Function<? super T, ? extends U> valueMapper) {
return toMap(keyMapper, valueMapper, throwingMerger(), HashMap<K, U>::new);
}
public static <T, K, U> Collector<T, ?, Map<K, U>> toMap(Function<? super T, ? extends K> keyMapper,
Function<? super T, ? extends U> valueMapper, BinaryOperator<U> mergeFunction) {
return toMap(keyMapper, valueMapper, mergeFunction, HashMap<K, U>::new);
}
public static <T, K, U, M extends Map<K, U>> Collector<T, ?, M> toMap(Function<? super T, ? extends K> keyMapper,
Function<? super T, ? extends U> valueMapper, BinaryOperator<U> mergeFunction, Supplier<M> mapSupplier) {
BiConsumer<M, T> accumulator = (map, element) -> map.merge(keyMapper.apply(element), valueMapper.apply(element),
mergeFunction);
return new CollectorImpl<>(mapSupplier, accumulator, mapMerger(mergeFunction));
}
private static <K, V, M extends Map<K, V>> BinaryOperator<M> mapMerger(BinaryOperator<V> mergeFunction) {
return (m1, m2) -> {
for (Map.Entry<K, V> e : m2.entrySet())
m1.merge(e.getKey(), e.getValue(), mergeFunction);
return m1;
};
}
/**
* Returns a {@code Collector} that concatenates the input elements into a
* {@code String}, in encounter order.
*
* @return a {@code Collector} that concatenates the input elements into a
* {@code String}, in encounter order
*/
public static Collector<CharSequence, ?, String> joining() {
return new CollectorImpl<CharSequence, StringBuilder, String>(StringBuilder::new, StringBuilder::append,
(r1, r2) -> {
r1.append(r2);
return r1;
});
}
/**
* Returns a {@code Collector} that concatenates the input elements, separated
* by the specified delimiter, in encounter order.
*
* @param delimiter
* the delimiter to be used between each element
* @return A {@code Collector} which concatenates CharSequence elements,
* separated by the specified delimiter, in encounter order
*/
public static Collector<CharSequence, ?, String> joining(CharSequence delimiter) {
return joining(delimiter, "", "");
}
/**
* Returns a {@code Collector} that concatenates the input elements, separated
* by the specified delimiter, with the specified prefix and suffix, in
* encounter order.
*
* @param delimiter
* the delimiter to be used between each element
* @param prefix
* the sequence of characters to be used at the beginning of the
* joined result
* @param suffix
* the sequence of characters to be used at the end of the joined
* result
* @return A {@code Collector} which concatenates CharSequence elements,
* separated by the specified delimiter, in encounter order
*/
public static Collector<CharSequence, ?, String> joining(CharSequence delimiter, CharSequence prefix,
CharSequence suffix) {
return new CollectorImpl<>(() -> new StringJoiner(delimiter, prefix, suffix), StringJoiner::add,
StringJoiner::merge);
}
public static <T, K, A, D> Collector<T, ?, Map<K, D>> groupingBy(Function<? super T, ? extends K> classifier,
Collector<? super T, A, D> downstream) {
return groupingBy(classifier, HashMap<K, D>::new, downstream);
}
public static <T, K, D, A, M extends Map<K, D>> Collector<T, ?, M> groupingBy(
Function<? super T, ? extends K> classifier, Supplier<M> mapFactory,
Collector<? super T, A, D> downstream) {
Supplier<A> downstreamSupplier = downstream.supplier();
BiConsumer<A, ? super T> downstreamAccumulator = downstream.accumulator();
BiConsumer<Map<K, A>, T> accumulator = (m, t) -> {
K key = Objects.requireNonNull(classifier.apply(t), "element cannot be mapped to a null key");
A container = m.computeIfAbsent(key, k -> downstreamSupplier.get());
downstreamAccumulator.accept(container, t);
};
BinaryOperator<Map<K, A>> merger = Collectors.<K, A, Map<K, A>>mapMerger(downstream.combiner());
@SuppressWarnings("unchecked")
Supplier<Map<K, A>> mangledFactory = (Supplier<Map<K, A>>) mapFactory;
if (downstream.characteristics().contains(Collector.Characteristics.IDENTITY_FINISH)) {
return new CollectorImpl<>(mangledFactory, accumulator, merger, CH_ID);
} else {
@SuppressWarnings("unchecked")
Function<A, A> downstreamFinisher = (Function<A, A>) downstream.finisher();
Function<Map<K, A>, M> finisher = intermediate -> {
intermediate.replaceAll((k, v) -> downstreamFinisher.apply(v));
@SuppressWarnings("unchecked")
M castResult = (M) intermediate;
return castResult;
};
return new CollectorImpl<>(mangledFactory, accumulator, merger, finisher, CH_NOID);
}
}
public static <T, U, A, R> Collector<T, ?, R> mapping(Function<? super T, ? extends U> mapper,
Collector<? super U, A, R> downstream) {
BiConsumer<A, ? super U> downstreamAccumulator = downstream.accumulator();
return new CollectorImpl<>(downstream.supplier(), (r, t) -> downstreamAccumulator.accept(r, mapper.apply(t)),
downstream.combiner(), downstream.finisher(), downstream.characteristics());
}
public static <T> Collector<T, ?, T> reducing(T identity, BinaryOperator<T> op) {
return new CollectorImpl<>(boxSupplier(identity), (a, t) -> {
a[0] = op.apply(a[0], t);
}, (a, b) -> {
a[0] = op.apply(a[0], b[0]);
return a;
}, a -> a[0], CH_NOID);
}
public static <T, U> Collector<T, ?, U> reducing(U identity, Function<? super T, ? extends U> mapper,
BinaryOperator<U> op) {
return new CollectorImpl<>(boxSupplier(identity), (a, t) -> {
a[0] = op.apply(a[0], mapper.apply(t));
}, (a, b) -> {
a[0] = op.apply(a[0], b[0]);
return a;
}, a -> a[0], CH_NOID);
}
@SuppressWarnings("unchecked")
private static <T> Supplier<T[]> boxSupplier(T identity) {
return () -> (T[]) new Object[] { identity };
}
}
|
package log;
import log.LogListener;
import java.io.IOException;
import java.io.OutputStream;
public class OutputStreamLogListener implements LogListener {
private OutputStream outputStream;
public OutputStreamLogListener(OutputStream outputStream) {
this.outputStream = outputStream;
}
@Override
public void debug(String message) {
message = "DEBUG: " + message + System.lineSeparator();
try {
outputStream.write(message.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void info(String message) {
message = "INFO: " + message + System.lineSeparator();
try {
outputStream.write(message.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void warn(String message) {
message = "WARNING: " + message + System.lineSeparator();
try {
outputStream.write(message.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void error(String message) {
message = "ERROR: " + message + System.lineSeparator();
try {
outputStream.write(message.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void fatal(String message) {
message = "FATAL: " + message + System.lineSeparator();
try {
outputStream.write(message.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
}
}
|
package logbook.internal;
import java.beans.XMLDecoder;
import java.beans.XMLEncoder;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.PathMatcher;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.temporal.ChronoField;
import java.time.temporal.ChronoUnit;
import java.time.temporal.TemporalAccessor;
import java.time.temporal.TemporalField;
import java.time.temporal.WeekFields;
import java.util.Collections;
import java.util.EnumMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import logbook.bean.AppConfig;
import logbook.bean.BattleLog;
import logbook.internal.gui.BattleLogCollect;
import logbook.internal.log.BattleResultLogFormat;
import logbook.internal.log.LogWriter;
public class BattleLogs {
/**
*
*
* @param log
*/
public static void write(BattleLog log) {
Path dir = Paths.get(AppConfig.get().getBattleLogDir());
// yyyy-MM-dd hh:mm:ss -> yyyy-MM-dd hh-mm-ss
String name = toName(log.getTime());
Path path = dir.resolve(name);
write(path, log);
deleteExpiration(dir);
}
private static void write(Path path, BattleLog log) {
try {
Path parent = path.getParent();
if (parent != null && !Files.exists(parent)) {
Files.createDirectories(parent);
}
try (OutputStream out = new BufferedOutputStream(Files.newOutputStream(path))) {
try (XMLEncoder encoder = new XMLEncoder(out)) {
encoder.writeObject(log);
}
}
} catch (IOException e) {
LoggerHolder.LOG.warn("", e);
}
}
private static void deleteExpiration(Path dir) {
try {
ZonedDateTime exp = unitToday()
.minusDays(AppConfig.get().getBattleLogExpires())
.withZoneSameInstant(ZoneId.of("Asia/Tokyo"));
String expName = toName(Logs.DATE_FORMAT.format(exp));
PathMatcher xmlFilter = dir.getFileSystem()
.getPathMatcher("glob:*.xml");
Consumer<Path> deleteAction = p -> {
try {
Files.deleteIfExists(p);
} catch (IOException e) {
LoggerHolder.LOG.warn("", e);
}
};
try (Stream<Path> ds = Files.list(dir)) {
ds.filter(p -> xmlFilter.matches(p.getFileName()))
.filter(p -> p.getFileName().toString().compareTo(expName) < 0)
.forEach(deleteAction);
}
} catch (IOException e) {
LoggerHolder.LOG.warn("", e);
}
}
/**
*
*
* @param dateString
* @return null
*/
public static BattleLog read(String dateString) {
String name = toName(dateString);
Path dir = Paths.get(AppConfig.get().getBattleLogDir());
return read(dir.resolve(name));
}
private static BattleLog read(Path path) {
try {
if (Files.isReadable(path)) {
try (InputStream in = new BufferedInputStream(Files.newInputStream(path))) {
try (XMLDecoder decoder = new XMLDecoder(in)) {
Object obj = decoder.readObject();
if (obj instanceof BattleLog) {
return (BattleLog) obj;
}
}
}
}
} catch (IOException e) {
LoggerHolder.LOG.warn("", e);
}
return null;
}
private static String toName(String dateTimeString) {
return dateTimeString.replace(':', '-') + ".xml";
}
/**
*
*
* @return
*/
public static Map<Unit, List<SimpleBattleLog>> readSimpleLog() {
try {
Function<String, SimpleBattleLog> mapper = line -> {
try {
return new SimpleBattleLog(line);
} catch (Exception e) {
LoggerHolder.LOG.warn("", e);
}
return null;
};
Path dir = Paths.get(AppConfig.get().getReportPath());
Path path = dir.resolve(new BattleResultLogFormat().fileName());
ZonedDateTime now = unitToday();
ZonedDateTime limit = now.minusMonths(2);
if (Files.exists(path)) {
List<SimpleBattleLog> all = Files.lines(path, LogWriter.DEFAULT_CHARSET)
.skip(1)
.filter(l -> !l.isEmpty())
.map(mapper)
.filter(Objects::nonNull)
.filter(log -> log.getDate().compareTo(limit) > 0)
.collect(Collectors.toList());
EnumMap<Unit, List<SimpleBattleLog>> map = new EnumMap<>(Unit.class);
for (Unit unit : Unit.values()) {
map.put(unit, all.stream()
.filter(log -> unit.accept(log.getDate(), now))
.collect(Collectors.toList()));
}
return map;
}
} catch (Exception e) {
LoggerHolder.LOG.warn("", e);
}
return Collections.emptyMap();
}
/**
*
*
* @param logs
* @param area (null)
* @param bossOnly true
* @return
*/
public static BattleLogCollect collect(List<SimpleBattleLog> logs, String area, boolean bossOnly) {
Predicate<SimpleBattleLog> anyFilter = e -> true;
Predicate<SimpleBattleLog> areaFilter = area != null ? e -> area.equals(e.getArea()) : anyFilter;
Predicate<SimpleBattleLog> bossFilter = bossOnly ? e -> e.getBoss().indexOf("") != -1 : anyFilter;
String start;
if (bossOnly) {
start = "-";
} else {
start = Long.toString(logs.stream()
.filter(areaFilter)
.map(SimpleBattleLog::getBoss)
.filter(boss -> boss.indexOf("") != -1)
.count());
}
Map<String, Long> rank = logs.stream()
.filter(areaFilter)
.filter(bossFilter)
.map(SimpleBattleLog::getRank)
.collect(Collectors.groupingBy(s -> s, Collectors.counting()));
long s = rank.getOrDefault("S", 0L);
long a = rank.getOrDefault("A", 0L);
long b = rank.getOrDefault("B", 0L);
long c = rank.getOrDefault("C", 0L);
long d = rank.getOrDefault("D", 0L);
long win = s + a + b;
BattleLogCollect value = new BattleLogCollect();
value.setStart(start);
value.setWin(String.valueOf(win));
value.setS(String.valueOf(s));
value.setA(String.valueOf(a));
value.setB(String.valueOf(b));
value.setC(String.valueOf(c));
value.setD(String.valueOf(d));
return value;
}
private static ZonedDateTime unitToday() {
return ZonedDateTime.now(ZoneId.of("GMT+04:00"))
.truncatedTo(ChronoUnit.DAYS);
}
public static class SimpleBattleLog {
private ZonedDateTime date;
private String area;
private String cell;
private String boss;
private String rank;
private String intercept;
private String fformation;
private String eformation;
private String dispseiku;
private String ftouch;
private String etouch;
private String efleet;
private String dropType;
private String dropShip;
/**
* .csv
*
* @param line .csv
*/
public SimpleBattleLog(String line) {
String[] columns = line.split(",", -1);
// GMT+04:00
TemporalAccessor ta = Logs.DATE_FORMAT.parse(columns[0]);
ZonedDateTime date = ZonedDateTime.of(LocalDateTime.from(ta), ZoneId.of("Asia/Tokyo"))
.withZoneSameInstant(ZoneId.of("GMT+04:00"));
this.setDate(date);
this.setArea(columns[1]);
this.setCell(columns[2]);
this.setBoss(columns[3]);
this.setRank(columns[4]);
this.setIntercept(columns[5]);
this.setFformation(columns[6]);
this.setEformation(columns[7]);
this.setDispseiku(columns[8]);
this.setFtouch(columns[9]);
this.setEtouch(columns[10]);
this.setEfleet(columns[11]);
this.setDropType(columns[12]);
this.setDropShip(columns[13]);
}
/**
*
* @return
*/
public ZonedDateTime getDate() {
return this.date;
}
/**
*
* @param date
*/
public void setDate(ZonedDateTime date) {
this.date = date;
}
/**
*
* @return
*/
public String getArea() {
return this.area;
}
/**
*
* @param area
*/
public void setArea(String area) {
this.area = area;
}
/**
*
* @return
*/
public String getCell() {
return this.cell;
}
/**
*
* @param cell
*/
public void setCell(String cell) {
this.cell = cell;
}
/**
*
* @return
*/
public String getBoss() {
return this.boss;
}
/**
*
* @param boss
*/
public void setBoss(String boss) {
this.boss = boss;
}
/**
*
* @return
*/
public String getRank() {
return this.rank;
}
/**
*
* @param rank
*/
public void setRank(String rank) {
this.rank = rank;
}
/**
*
* @return
*/
public String getIntercept() {
return this.intercept;
}
/**
*
* @param intercept
*/
public void setIntercept(String intercept) {
this.intercept = intercept;
}
/**
*
* @return
*/
public String getFformation() {
return this.fformation;
}
/**
*
* @param fformation
*/
public void setFformation(String fformation) {
this.fformation = fformation;
}
/**
*
* @return
*/
public String getEformation() {
return this.eformation;
}
/**
*
* @param eformation
*/
public void setEformation(String eformation) {
this.eformation = eformation;
}
/**
*
* @return
*/
public String getDispseiku() {
return this.dispseiku;
}
/**
*
* @param dispseiku
*/
public void setDispseiku(String dispseiku) {
this.dispseiku = dispseiku;
}
/**
*
* @return
*/
public String getFtouch() {
return this.ftouch;
}
/**
*
* @param ftouch
*/
public void setFtouch(String ftouch) {
this.ftouch = ftouch;
}
/**
*
* @return
*/
public String getEtouch() {
return this.etouch;
}
/**
*
* @param etouch
*/
public void setEtouch(String etouch) {
this.etouch = etouch;
}
/**
*
* @return
*/
public String getEfleet() {
return this.efleet;
}
/**
*
* @param efleet
*/
public void setEfleet(String efleet) {
this.efleet = efleet;
}
/**
*
* @return
*/
public String getDropType() {
return this.dropType;
}
/**
*
* @param dropType
*/
public void setDropType(String dropType) {
this.dropType = dropType;
}
/**
*
* @return
*/
public String getDropShip() {
return this.dropShip;
}
/**
*
* @param dropShip
*/
public void setDropShip(String dropShip) {
this.dropShip = dropShip;
}
}
public enum Unit {
DAILY("") {
@Override
public boolean accept(ZonedDateTime target, ZonedDateTime now) {
TemporalField field = ChronoField.DAY_OF_YEAR;
return now.get(field) == target.get(field);
}
},
WEEKLY("") {
@Override
public boolean accept(ZonedDateTime target, ZonedDateTime now) {
TemporalField field = WeekFields.ISO.weekOfWeekBasedYear();
return now.get(field) == target.get(field);
}
},
MONTHLY("") {
@Override
public boolean accept(ZonedDateTime target, ZonedDateTime now) {
TemporalField field = ChronoField.MONTH_OF_YEAR;
return now.get(field) == target.get(field);
}
},
LAST_WEEK("") {
@Override
public boolean accept(ZonedDateTime target, ZonedDateTime now) {
TemporalField field = WeekFields.ISO.weekOfWeekBasedYear();
return now.minusWeeks(1).get(field) == target.get(field);
}
},
LAST_MONTH("") {
@Override
public boolean accept(ZonedDateTime target, ZonedDateTime now) {
TemporalField field = ChronoField.MONTH_OF_YEAR;
return now.minusMonths(1).get(field) == target.get(field);
}
};
private String name;
/**
*
*
* @param name
*/
Unit(String name) {
this.name = name;
}
/**
*
* @return
*/
public String getName() {
return this.name;
}
/**
*
*
* @param target (GMT+04:00)
* @param now (GMT+04:00)
* @return true
*/
public boolean accept(ZonedDateTime target, ZonedDateTime now) {
throw new UnsupportedOperationException();
}
}
private static class LoggerHolder {
private static final Logger LOG = LogManager.getLogger(BattleLogs.class);
}
}
|
package mingzuozhibi.persist;
import org.json.JSONArray;
import org.json.JSONObject;
import javax.persistence.*;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;
@Entity
public class Sakura extends BaseModel implements Comparable<Sakura> {
public static final String TOP100 = "9999-99";
private String key;
private String title;
private boolean enabled;
private LocalDateTime sakuraUpdateDate;
private List<Disc> discs = new LinkedList<>();
public Sakura() {
}
public Sakura(String key, String title) {
if (key.isEmpty()) {
this.key = TOP100;
this.title = "TOP100";
} else {
this.key = key;
this.title = Optional.ofNullable(title).orElseGet(() -> titleOfKey(key));
}
enabled = true;
}
@Column(name = "`key`", length = 100, nullable = false, unique = true)
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
@Column(length = 100, nullable = false)
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
@Column(nullable = false)
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
@Column
public LocalDateTime getSakuraUpdateDate() {
return sakuraUpdateDate;
}
public void setSakuraUpdateDate(LocalDateTime sakuraUpdateDate) {
this.sakuraUpdateDate = sakuraUpdateDate;
}
@ManyToMany
@JoinTable(name = "sakura_discs",
joinColumns = {@JoinColumn(name = "sakura_id")},
inverseJoinColumns = {@JoinColumn(name = "disc_id")})
public List<Disc> getDiscs() {
return discs;
}
public void setDiscs(List<Disc> discs) {
this.discs = discs;
}
@Transient
public boolean isTop100() {
return TOP100.equals(getKey());
}
@Transient
public static String titleOfKey(String key) {
return key.substring(0, 4) + "" + key.substring(5) + "";
}
@Override
public int compareTo(Sakura o) {
Objects.requireNonNull(o);
return Comparator.comparing(Sakura::getKey).compare(this, o);
}
private static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");
public JSONObject toJSON(boolean hasDiscs, Set<String> discColumns) {
JSONObject object = new JSONObject();
object.put("id", getId());
object.put("key", getKey());
object.put("title", getTitle());
object.put("enabled", isEnabled());
object.put("sakuraUpdateDate", Optional.ofNullable(sakuraUpdateDate)
.map(date -> date.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli())
.orElse(0L));
if (hasDiscs) {
JSONArray array = new JSONArray();
getDiscs().forEach(disc -> array.put(disc.toJSON(discColumns)));
object.put("discs", array);
}
return object;
}
}
|
package nl.mvdr.tinustris.gui;
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.paint.Color;
import javafx.scene.paint.CycleMethod;
import javafx.scene.paint.Paint;
import javafx.scene.paint.RadialGradient;
import javafx.scene.paint.Stop;
import javafx.scene.shape.Rectangle;
import javafx.scene.shape.StrokeType;
import javafx.stage.Stage;
import lombok.extern.slf4j.Slf4j;
import nl.mvdr.tinustris.engine.GameEngine;
import nl.mvdr.tinustris.engine.GameLoop;
import nl.mvdr.tinustris.engine.TinusTrisEngine;
import nl.mvdr.tinustris.input.InputController;
import nl.mvdr.tinustris.input.JInputController;
import nl.mvdr.tinustris.model.GameState;
import org.slf4j.bridge.SLF4JBridgeHandler;
import com.sun.javafx.runtime.VersionInfo;
/**
* Main class and entry point for the entire application.
*
* @author Martijn van de Rijdt
*/
// When testing the application, don't run this class directly from Eclipse. Use TinusTrisTestContext instead.
@Slf4j
public class Tinustris extends Application {
/** Width of the border around the Tetris grid and other UI components. */
private static final int BORDER_WIDTH = 10;
/** Game loop. */
private GameLoop<GridGroup> gameLoop;
/**
* Main method.
*
* @param args
* command-line parameters
*/
public static void main(String[] args) {
// JInput uses java.util.logging; redirect to slf4j.
installSlf4jBridge();
// Launch the application!
launch(args);
}
/** Installs a bridge for java.util.logging to slf4j. */
private static void installSlf4jBridge() {
// remove existing handlers attached to java.util.logging root logger
SLF4JBridgeHandler.removeHandlersForRootLogger();
// add SLF4JBridgeHandler to java.util.logging's root logger
SLF4JBridgeHandler.install();
}
/** {@inheritDoc} */
@Override
public void start(Stage stage) {
log.info("Starting application.");
logVersionInfo();
// construct the user interface
stage.setTitle("Tinustris");
GridGroup gridGroup = new GridGroup();
Group parent = new Group();
// TODO add background image: parent.getChildren().add(new ImageView("imageurl"));
parent.getChildren().add(createWindow(gridGroup));
Scene scene = new Scene(parent,
10 * GridGroup.BLOCK_SIZE + 2 * BORDER_WIDTH,
20 * GridGroup.BLOCK_SIZE + 2 * BORDER_WIDTH,
Color.WHITE);
stage.setScene(scene);
stage.show();
// Default size should also be the minimum size.
stage.setMinWidth(stage.getWidth());
stage.setMinHeight(stage.getHeight());
log.info("Stage shown.");
// setup necessary components
InputController inputController = new JInputController();
GameEngine gameEngine = new TinusTrisEngine();
GameRenderer<GridGroup> gameRenderer = createRenderer();
// start the game loop
gameLoop = new GameLoop<>(inputController, gameEngine, gameRenderer, gridGroup);
gameLoop.start();
log.info("Game loop started.");
}
/** Logs some version info. */
private void logVersionInfo() {
if (log.isInfoEnabled()) {
String version = retrieveVersion();
if (version != null) {
log.info("Application version: " + version);
} else {
log.info("pplication version unknown.");
}
log.info("Classpath: " + System.getProperty("java.class.path"));
log.info("Library path: " + System.getProperty("java.library.path"));
log.info("Java vendor: " + System.getProperty("java.vendor"));
log.info("Java version: " + System.getProperty("java.version"));
log.info("OS name: " + System.getProperty("os.name"));
log.info("OS version: " + System.getProperty("os.version"));
log.info("OS architecture: " + System.getProperty("os.arch"));
log.info("JavaFX version: " + VersionInfo.getVersion());
log.info("JavaFX runtime version: " + VersionInfo.getRuntimeVersion());
log.info("JavaFX build timestamp: " + VersionInfo.getBuildTimestamp());
}
}
/**
* Returns the version number from the jar manifest file.
*
* @return version number, or null if it cannot be determined
*/
private String retrieveVersion() {
String result;
Package p = Tinustris.class.getPackage();
if (p != null) {
result = p.getImplementationVersion();
} else {
result = null;
}
return result;
}
/**
* Creates a red-bordered window containing the given node.
*
* @param contents
* contents of the window
* @return group containing the window and the contents
*/
private Group createWindow(Node contents) {
// bounding red rectangle
Rectangle border = new Rectangle(BORDER_WIDTH, BORDER_WIDTH, 10 * GridGroup.BLOCK_SIZE,
20 * GridGroup.BLOCK_SIZE);
border.setFill(null);
Paint stroke = new RadialGradient(0,
1,
border.getX() + border.getWidth() / 2,
border.getY() + border.getHeight() / 2,
border.getHeight() / 2,
false,
CycleMethod.NO_CYCLE,
new Stop(0, Color.WHITE),
new Stop(1, Color.DARKRED));
border.setStroke(stroke);
border.setStrokeWidth(BORDER_WIDTH);
border.setStrokeType(StrokeType.OUTSIDE);
border.setArcWidth(GridGroup.ARC_SIZE);
border.setArcHeight(GridGroup.ARC_SIZE);
// black, seethrough background, to dim whatever is behind the window
Rectangle background = new Rectangle(border.getX(), border.getY(), border.getWidth(), border.getHeight());
background.setFill(Color.BLACK);
background.setOpacity(.5);
background.setArcWidth(GridGroup.ARC_SIZE);
background.setArcHeight(GridGroup.ARC_SIZE);
contents.setTranslateX(BORDER_WIDTH);
contents.setTranslateY(BORDER_WIDTH);
Group group = new Group();
group.getChildren().addAll(background, border, contents);
return group;
}
/**
* Creates the game renderer.
*
* @return renderer
*/
// If this was Java 8, this could be a lambda expression!
private GameRenderer<GridGroup> createRenderer() {
return new GameRenderer<GridGroup>() {
/** {@inheritDoc} */
@Override
public void render(GridGroup node, GameState gameState) {
node.render(gameState);
}
};
}
/** {@inheritDoc} */
@Override
public void stop() throws Exception {
log.info("Stopping the application.");
gameLoop.stop();
super.stop();
log.info("Stopped.");
}
}
|
package org.bouncycastle.tls.crypto.impl.bc;
import java.io.IOException;
import org.bouncycastle.crypto.engines.ChaCha7539Engine;
import org.bouncycastle.crypto.macs.Poly1305;
import org.bouncycastle.crypto.params.KeyParameter;
import org.bouncycastle.crypto.params.ParametersWithIV;
import org.bouncycastle.tls.AlertDescription;
import org.bouncycastle.tls.TlsFatalAlert;
import org.bouncycastle.tls.TlsUtils;
import org.bouncycastle.tls.crypto.impl.TlsAEADCipherImpl;
import org.bouncycastle.util.Arrays;
import org.bouncycastle.util.Pack;
public class BcChaCha20Poly1305 implements TlsAEADCipherImpl
{
private static final byte[] ZEROES = new byte[15];
protected final ChaCha7539Engine cipher = new ChaCha7539Engine();
protected final Poly1305 mac = new Poly1305();
protected final boolean isEncrypting;
protected int additionalDataLength;
public BcChaCha20Poly1305(boolean isEncrypting)
{
this.isEncrypting = isEncrypting;
}
public int doFinal(byte[] input, int inputOffset, int inputLength, byte[] extraInput, byte[] output,
int outputOffset) throws IOException
{
int extraInputLength = extraInput.length;
if (isEncrypting)
{
int ciphertextLength = inputLength + extraInputLength;
int outputLength = cipher.processBytes(input, inputOffset, inputLength, output, outputOffset);
if (extraInputLength > 0)
{
outputLength += cipher.processBytes(extraInput, 0, extraInputLength, output,
outputOffset + outputLength);
}
if (ciphertextLength != outputLength)
{
throw new IllegalStateException();
}
updateMAC(output, outputOffset, ciphertextLength);
byte[] lengths = new byte[16];
Pack.longToLittleEndian(additionalDataLength & 0xFFFFFFFFL, lengths, 0);
Pack.longToLittleEndian(ciphertextLength & 0xFFFFFFFFL, lengths, 8);
mac.update(lengths, 0, 16);
mac.doFinal(output, outputOffset + ciphertextLength);
return ciphertextLength + 16;
}
else
{
if (extraInputLength > 0)
{
throw new TlsFatalAlert(AlertDescription.internal_error);
}
int ciphertextLength = inputLength - 16;
updateMAC(input, inputOffset, ciphertextLength);
byte[] expectedMac = new byte[16];
Pack.longToLittleEndian(additionalDataLength & 0xFFFFFFFFL, expectedMac, 0);
Pack.longToLittleEndian(ciphertextLength & 0xFFFFFFFFL, expectedMac, 8);
mac.update(expectedMac, 0, 16);
mac.doFinal(expectedMac, 0);
boolean badMac = !TlsUtils.constantTimeAreEqual(16, expectedMac, 0, input, inputOffset + ciphertextLength);
if (badMac)
{
throw new TlsFatalAlert(AlertDescription.bad_record_mac);
}
int outputLength = cipher.processBytes(input, inputOffset, ciphertextLength, output, outputOffset);
if (ciphertextLength != outputLength)
{
throw new IllegalStateException();
}
return ciphertextLength;
}
}
public int getOutputSize(int inputLength)
{
return isEncrypting ? inputLength + 16 : inputLength - 16;
}
public void init(byte[] nonce, int macSize, byte[] additionalData) throws IOException
{
if (nonce == null || nonce.length != 12 || macSize != 16)
{
throw new TlsFatalAlert(AlertDescription.internal_error);
}
cipher.init(isEncrypting, new ParametersWithIV(null, nonce));
initMAC();
if (additionalData == null)
{
this.additionalDataLength = 0;
}
else
{
this.additionalDataLength = additionalData.length;
updateMAC(additionalData, 0, additionalData.length);
}
}
public void setKey(byte[] key, int keyOff, int keyLen) throws IOException
{
KeyParameter cipherKey = new KeyParameter(key, keyOff, keyLen);
cipher.init(isEncrypting, new ParametersWithIV(cipherKey, ZEROES, 0, 12));
}
protected void initMAC()
{
byte[] firstBlock = new byte[64];
cipher.processBytes(firstBlock, 0, 64, firstBlock, 0);
mac.init(new KeyParameter(firstBlock, 0, 32));
Arrays.fill(firstBlock, (byte)0);
}
protected void updateMAC(byte[] buf, int off, int len)
{
mac.update(buf, off, len);
int partial = len % 16;
if (partial != 0)
{
mac.update(ZEROES, 0, 16 - partial);
}
}
}
|
package to.etc.domui.server;
import org.eclipse.jdt.annotation.NonNull;
import org.eclipse.jdt.annotation.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import to.etc.domui.annotations.UIRights;
import to.etc.domui.component.meta.MetaManager;
import to.etc.domui.component.meta.PropertyMetaModel;
import to.etc.domui.component.misc.InternalParentTree;
import to.etc.domui.component.misc.MessageFlare;
import to.etc.domui.component.misc.MsgBox;
import to.etc.domui.dom.HtmlFullRenderer;
import to.etc.domui.dom.IBrowserOutput;
import to.etc.domui.dom.PrettyXmlOutputWriter;
import to.etc.domui.dom.errors.IExceptionListener;
import to.etc.domui.dom.errors.UIMessage;
import to.etc.domui.dom.html.ClickInfo;
import to.etc.domui.dom.html.IHasChangeListener;
import to.etc.domui.dom.html.NodeBase;
import to.etc.domui.dom.html.OptimalDeltaRenderer;
import to.etc.domui.dom.html.Page;
import to.etc.domui.dom.html.PagePhase;
import to.etc.domui.dom.html.UrlPage;
import to.etc.domui.login.AccessDeniedPage;
import to.etc.domui.login.ILoginDialogFactory;
import to.etc.domui.login.IUser;
import to.etc.domui.parts.IComponentJsonProvider;
import to.etc.domui.parts.IComponentUrlDataProvider;
import to.etc.domui.state.AppSession;
import to.etc.domui.state.CidPair;
import to.etc.domui.state.ConversationContext;
import to.etc.domui.state.ConversationDestroyedException;
import to.etc.domui.state.IGotoAction;
import to.etc.domui.state.INotReloadablePage;
import to.etc.domui.state.PageParameters;
import to.etc.domui.state.UIContext;
import to.etc.domui.state.UIGoto;
import to.etc.domui.state.UserLogItem;
import to.etc.domui.state.WindowSession;
import to.etc.domui.themes.ThemeManager;
import to.etc.domui.trouble.ClientDisconnectedException;
import to.etc.domui.trouble.ExpiredSessionPage;
import to.etc.domui.trouble.MsgException;
import to.etc.domui.trouble.NotLoggedInException;
import to.etc.domui.trouble.SessionInvalidException;
import to.etc.domui.trouble.ThingyNotFoundException;
import to.etc.domui.trouble.ValidationException;
import to.etc.domui.util.Constants;
import to.etc.domui.util.DomUtil;
import to.etc.domui.util.INewPageInstantiated;
import to.etc.domui.util.IRebuildOnRefresh;
import to.etc.domui.util.IRightsCheckedManually;
import to.etc.domui.util.Msgs;
import to.etc.template.JSTemplate;
import to.etc.template.JSTemplateCompiler;
import to.etc.util.DeveloperOptions;
import to.etc.util.FileTool;
import to.etc.util.IndentWriter;
import to.etc.util.StringTool;
import to.etc.util.WrappedException;
import to.etc.webapp.ProgrammerErrorException;
import to.etc.webapp.ajax.renderer.json.JSONRegistry;
import to.etc.webapp.ajax.renderer.json.JSONRenderer;
import to.etc.webapp.nls.CodeException;
import to.etc.webapp.query.QContextManager;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileReader;
import java.io.Reader;
import java.io.Writer;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import static to.etc.domui.util.DomUtil.nullChecked;
public class ApplicationRequestHandler implements IFilterRequestHandler {
static Logger LOG = LoggerFactory.getLogger(ApplicationRequestHandler.class);
@NonNull
private final DomApplication m_application;
@Nullable
private JSTemplate m_exceptionTemplate;
private static boolean m_logPerf = DeveloperOptions.getBool("domui.logtime", false);
ApplicationRequestHandler(@NonNull final DomApplication application) {
m_application = application;
}
/**
* Accept .obit, the defined DomUI extension (.ui by default) and the empty URL if a home page is set in {@link DomApplication}.
*/
private boolean accepts(@NonNull IRequestContext ctx) {
return m_application.getUrlExtension().equals(ctx.getExtension()) || ctx.getExtension().equals("obit") || (m_application.getRootPage() != null && ctx.getInputPath().length() == 0);
}
@Override
public boolean handleRequest(@NonNull final RequestContextImpl ctx) throws Exception {
if(! accepts(ctx))
return false;
ctx.getRequestResponse().setNoCache(); // All replies may not be cached at all!!
ctx.getRequestResponse().addHeader("X-UA-Compatible", "IE=edge"); // 20110329 jal Force to highest supported mode for DomUI code.
ctx.getRequestResponse().addHeader("X-XSS-Protection", "0"); // 20130124 jal Disable IE XSS filter, to prevent the idiot thing from seeing the CID as a piece of script 8-(
handleMain(ctx);
ctx.getSession().dump();
return true;
}
private void handleMain(@NonNull final RequestContextImpl ctx) throws Exception {
Class< ? extends UrlPage> runclass = decodeRunClass(ctx);
try {
runClass(ctx, runclass);
} catch(ThingyNotFoundException | ClientDisconnectedException xxxx) {
throw xxxx;
} catch(Exception x) {
renderApplicationMail(ctx, x);
//if(!m_application.isShowProblemTemplate() && !m_application.inDevelopmentMode())
// throw x;
tryRenderOopsFrame(ctx, x);
} catch(Error x) {
renderApplicationMail(ctx, x);
if(!m_application.isShowProblemTemplate() && !m_application.inDevelopmentMode())
throw x;
String s = x.getMessage();
if(s != null && s.contains("compilation") && s.contains("problem")) {
tryRenderOopsFrame(ctx, x);
} else
throw x;
}
}
/**
* In case of a (non compile) exception, check to see if mail must be sent and if yes do so.
*/
private void renderApplicationMail(@NonNull final RequestContextImpl ctx, @NonNull Throwable x) {
String s = x.getMessage();
if(s != null && s.contains("compilation") && s.contains("problem")) {
return;
}
ExceptionUtil util = new ExceptionUtil(ctx);
util.renderEmail(x);
}
/**
* Render the exception details screen.
*/
private void tryRenderOopsFrame(@NonNull final RequestContextImpl ctx, @NonNull Throwable x) throws Exception {
try {
renderOopsFrame(ctx, x);
} catch(Exception oopx) {
System.out.println("Exception while rendering exception page!!?? " + oopx);
oopx.printStackTrace();
if(x instanceof Error) {
throw (Error) x;
} else {
throw (Exception) x;
}
}
}
/**
* Decide what class to run depending on the input path.
*/
@NonNull
private Class< ? extends UrlPage> decodeRunClass(@NonNull final IRequestContext ctx) {
if(ctx.getInputPath().length() == 0) {
/*
* We need to EXECUTE the application's main class. We cannot use the .class directly
* because the reloader must be able to substitute a new version of the class when
* needed.
*/
Class< ? extends UrlPage> rootPage = m_application.getRootPage();
if(null == rootPage)
throw new ProgrammerErrorException("The DomApplication's 'getRootPage()' method returns null, and there is a request for the root of the web app... Override that method or make sure the root is handled differently.");
String txt = rootPage.getCanonicalName();
return m_application.loadPageClass(txt);
}
//-- Try to resolve as a class name,
String s = ctx.getInputPath();
int pos = s.lastIndexOf('.'); // Always strip whatever extension
if(pos != -1) {
int spos = s.lastIndexOf('/') + 1; // Try to locate path component
if(pos > spos) {
s = s.substring(spos, pos); // Last component, ex / and last extension.
//-- This should be a classname now
return m_application.loadPageClass(s);
}
}
//-- All others- cannot resolve
throw new IllegalStateException("Cannot decode URL " + ctx.getInputPath());
}
/* CODING: Initial and initial (full) page rendering. */
/**
* Intermediary impl; should later use interface impl on class to determine factory
* to use.
*/
private void runClass(@NonNull final RequestContextImpl ctx, @NonNull final Class< ? extends UrlPage> clz) throws Exception {
/*
* If this is a full render request the URL must contain a $CID... If not send a redirect after allocating a window.
*/
String action = ctx.getParameter(Constants.PARAM_UIACTION); // AJAX action request?
String cid = ctx.getParameter(Constants.PARAM_CONVERSATION_ID);
CidPair cida = cid == null ? null : CidPair.decodeLax(cid);
if(DomUtil.USERLOG.isDebugEnabled()) {
DomUtil.USERLOG.debug("\n\n\n========= DomUI request =================\nCID=" + cid + "\nAction=" + action + "\n");
}
if(!Constants.ACMD_ASYPOLL.equals(action))
// System.out.println("req: " + cid + " action " + action + ", " + ctx.getParameter(Constants.PARAM_UICOMPONENT));
logUser(ctx, cid, clz.getName(), "Incoming request on " + cid + " action=" + action);
//-- If this is an OBITUARY just mark the window as possibly gone, then exit;
if(Constants.ACMD_OBITUARY.equals(action)) {
/*
* Warning: do NOT access the WindowSession by findWindowSession: that updates the window touched
* timestamp and causes obituary timeout handling to fail.
*/
int pageTag;
try {
pageTag = Integer.parseInt(ctx.getParameter(Constants.PARAM_PAGE_TAG));
} catch(Exception x) {
throw new IllegalStateException("Missing or invalid $pt PageTAG in OBITUARY request");
}
if(cida == null)
throw new IllegalStateException("Missing $cid in OBITUARY request");
if(LOG.isDebugEnabled())
LOG.debug("OBITUARY received for " + cid + ": pageTag=" + pageTag);
ctx.getSession().internalObituaryReceived(cida.getWindowId(), pageTag);
//-- Send a silly response.
ctx.getOutputWriter("text/html", "utf-8");
// ctx.getResponse().setContentType("text/html");
// /*Writer w = */ctx.getResponse().getWriter();
return; // Obituaries get a zero response.
}
// ORDERED!!! Must be kept BELOW the OBITUARY check
WindowSession windowSession = null;
if(cida != null) {
windowSession = ctx.getSession().findWindowSession(cida.getWindowId());
}
if(windowSession == null) {
boolean nonReloadableExpiredDetected = false;
if(action != null) {
if(INotReloadablePage.class.isAssignableFrom(clz)) {
nonReloadableExpiredDetected = true;
} else {
// In auto refresh: do not send the "expired" message, but let the refresh handle this.
if(m_application.getAutoRefreshPollInterval() <= 0) {
String msg = Msgs.BUNDLE.getString(Msgs.S_EXPIRED);
generateExpired(ctx, msg);
logUser(ctx, cid, clz.getName(), msg);
} else {
String msg = "Not sending expired message because autorefresh is ON for " + cid;
LOG.info(msg);
logUser(ctx, cid, clz.getName(), msg);
}
return;
}
}
//-- We explicitly need to create a new Window and need to send a redirect back
windowSession = ctx.getSession().createWindowSession();
String newmsg = "$cid: input windowid=" + cid + " not found - created wid=" + windowSession.getWindowID();
if(LOG.isDebugEnabled())
LOG.debug(newmsg);
logUser(ctx, cid, clz.getName(), newmsg);
String conversationId = "x"; // If not reloading a saved set- use x as the default conversation id
if(m_application.inDevelopmentMode() && cida != null) {
/*
* 20130227 jal The WindowSession we did not find could have been destroyed due to a
* reloader event. In that case it's page shelve will be stored in the HttpSession or
* perhaps in a state file. Try to resurrect that page shelve as to not lose the navigation history.
*/
if(ctx.getRequestResponse() instanceof HttpServerRequestResponse) {
HttpServerRequestResponse srr = (HttpServerRequestResponse) ctx.getRequestResponse();
HttpSession hs = srr.getRequest().getSession();
if(null != hs) {
ctx.internalSetWindowSession(windowSession); // Should prevent issues when reloading
String newid = windowSession.internalAttemptReload(hs, clz, PageParameters.createFrom(ctx), cida.getWindowId());
if(newid != null)
conversationId = newid;
}
}
}
if(nonReloadableExpiredDetected) {
generateNonReloadableExpired(ctx, windowSession);
return;
}
//-- EXPERIMENTAL 20121008 jal - if the code was sent through a POST - the data can be huge so we need a workaround for the get URL.
PageParameters pp = PageParameters.createFrom(ctx);
if(ctx.getRequestResponse() instanceof HttpServerRequestResponse) {
HttpServerRequestResponse srr = (HttpServerRequestResponse) ctx.getRequestResponse();
if("post".equalsIgnoreCase(srr.getRequest().getMethod()) && pp.getDataLength() > 768) {
redirectForPost(ctx, windowSession, pp);
return;
}
}
//-- END EXPERIMENTAL
StringBuilder sb = new StringBuilder(256);
// sb.append('/');
sb.append(ctx.getRelativePath(ctx.getInputPath()));
sb.append('?');
StringTool.encodeURLEncoded(sb, Constants.PARAM_CONVERSATION_ID);
sb.append('=');
sb.append(windowSession.getWindowID());
sb.append(".").append(conversationId);
DomUtil.addUrlParameters(sb, ctx, false);
generateHttpRedirect(ctx, sb.toString(), "Your session has expired. Starting a new session.");
String expmsg = "Session " + cid + " has expired - starting a new session by redirecting to " + sb.toString();
logUser(ctx, cid, clz.getName(), expmsg);
if(DomUtil.USERLOG.isDebugEnabled())
DomUtil.USERLOG.debug(expmsg);
return;
}
if(cida == null)
throw new IllegalStateException("Cannot happen: cida is null??");
String conversationId = cida.getConversationId();
/*
* Attempt to fix etc.to bugzilla bug# 3183: IE7 sends events out of order. If an action arrives for an earlier-destroyed
* conversation just ignore it, and send an empty response to ie, hopefully causing it to die soon.
*/
if(action != null) {
if(windowSession.isConversationDestroyed(conversationId)) { // This conversation was recently destroyed?
//-- Render a null response
String msg = "Session " + cid + " was destroyed earlier- assuming this is an out-of-order event and sending empty delta back";
if(LOG.isDebugEnabled())
LOG.debug(msg);
logUser(ctx, cid, clz.getName(), msg);
System.out.println(msg);
generateEmptyDelta(ctx);
return; // jal 20121122 Must return after sending that delta or the document is invalid!!
}
}
ctx.internalSetWindowSession(windowSession);
windowSession.clearGoto();
/*
* Determine if this is an AJAX request or a normal "URL" request. If it is a non-AJAX
* request we'll always respond with a full page re-render, but we must check to see if
* the page has been requested with different parameters this time.
*/
PageParameters papa = null; // Null means: ajax request, not a full page.
if(action == null) {
papa = PageParameters.createFrom(ctx);
//-- If this request is a huge post request - get the huge post parameters.
String hpq = papa.getString(Constants.PARAM_POST_CONVERSATION_KEY, null);
if(null != hpq) {
ConversationContext coco = windowSession.findConversation(conversationId);
if(null == coco)
throw new IllegalStateException("The conversation " + conversationId + " containing POST data is missing in windowSession " + windowSession);
papa = (PageParameters) coco.getAttribute("__ORIPP");
if(null == papa)
throw new IllegalStateException("The conversation " + cid + " no (longer) has the post data??");
}
}
Page page = windowSession.tryToMakeOrGetPage(ctx, conversationId, clz, papa, action);
if(page != null) {
page.getConversation().mergePersistentParameters(ctx);
page.internalSetPhase(PagePhase.BUILD); // Tree can change at will
page.internalIncrementRequestCounter();
windowSession.internalSetLastPage(page);
if(DomUtil.USERLOG.isDebugEnabled()) {
DomUtil.USERLOG.debug("Request for page " + page + " in conversation " + cid);
}
}
/*
* If this is an AJAX request make sure the page is still the same instance (session lost trouble)
*/
if(action != null) {
String s = ctx.getParameter(Constants.PARAM_PAGE_TAG);
if(s != null) {
int pt = Integer.parseInt(s);
if(page == null || pt != page.getPageTag()) {
/*
* The page tag differs-> session has expired.
*/
if(Constants.ACMD_ASYPOLL.equals(action)) {
generateExpiredPollasy(ctx);
} else {
String msg = "Session " + cid + " expired, page will be reloaded (page tag difference) on action=" + action;
if(DomUtil.USERLOG.isDebugEnabled())
DomUtil.USERLOG.debug(msg);
logUser(ctx, cid, clz.getName(), msg);
// In auto refresh: do not send the "expired" message, but let the refresh handle this.
if(m_application.getAutoRefreshPollInterval() <= 0) {
generateExpired(ctx, Msgs.BUNDLE.getString(Msgs.S_EXPIRED));
} else {
msg = "Not sending expired message because autorefresh is ON for " + cid;
LOG.info(msg);
logUser(ctx, cid, clz.getName(), msg);
}
}
return;
}
}
}
if(page == null) {
throw new IllegalStateException("Page can not be null here. Null is already handled inside expired AJAX request handling.");
}
UIContext.internalSet(page);
/*
* Handle all out-of-bound actions: those that do not manipulate UI state.
*/
if(action != null && action.startsWith("
runComponentAction(ctx, page, action.substring(1));
return;
//-- If this is a PAGEDATA request - handle that
} else if(Constants.ACMD_PAGEDATA.equals(action)) {
runPageData(ctx, page);
return;
}
//-- All commands EXCEPT ASYPOLL have all fields, so bind them to the current component data,
List<NodeBase> pendingChangeList = Collections.emptyList();
if(!Constants.ACMD_ASYPOLL.equals(action) && action != null) {
long ts = System.nanoTime();
pendingChangeList = handleComponentInput(ctx, page); // Move all request parameters to their input field(s)
if(LOG.isDebugEnabled()) {
ts = System.nanoTime() - ts;
LOG.debug("rq: input handling took " + StringTool.strNanoTime(ts));
}
}
if(action != null) {
runAction(ctx, page, action, pendingChangeList);
return;
}
/*
* We are doing a full refresh/rebuild of a page.
*/
long ts = System.nanoTime();
try {
if(DomUtil.USERLOG.isDebugEnabled())
DomUtil.USERLOG.debug(cid + ": Full render of page " + page);
if(page.getBody() instanceof IRebuildOnRefresh) { // Must fully refresh?
page.getBody().forceRebuild(); // Cleanout state
page.setInjected(false);
QContextManager.closeSharedContexts(page.getConversation());
if(DomUtil.USERLOG.isDebugEnabled())
DomUtil.USERLOG.debug(cid + ": IForceRefresh, cleared page data for " + page);
logUser(ctx, cid, clz.getName(), "Full page render with forced refresh");
} else {
logUser(ctx, cid, clz.getName(), "Full page render");
}
if(!page.isInjected()) {
ctx.getApplication().getInjector().injectPageValues(page.getBody(), nullChecked(papa));
page.setInjected(true);
}
/*
* This is a (new) page request. We need to check rights on the page before
* it is presented. The rights check is moved here (since 2013/01/24) because
* any analysis of data-related or interface-related rights require the class
* to be instantiated.
*
* 20090415 jal Authentication checks: if the page has a "UIRights" annotation we need a logged-in
* user to check it's rights against the page's required rights.
* FIXME This is fugly. Should this use the registerExceptionHandler code? If so we need to extend it's meaning to include pre-page exception handling.
*/
if(!checkAccess(windowSession, ctx, page))
return;
m_application.internalCallPageFullRender(ctx, page);
page.getBody().onReload();
// ORDERED
page.getConversation().processDelayedResults(page);
//-- Call the 'new page added' listeners for this page, if it is still unbuilt. Fixes bug# 605
callNewPageBuiltListeners(page);
page.internalFullBuild(); // Cause full build
//-- EXPERIMENTAL Handle stored messages in session
List<UIMessage> ml = (List<UIMessage>) windowSession.getAttribute(UIGoto.SINGLESHOT_MESSAGE);
if(ml != null) {
if(ml.size() > 0) {
page.getBody().build();
for(UIMessage m : ml) {
if(DomUtil.USERLOG.isDebugEnabled())
DomUtil.USERLOG.debug(cid + ": page reload message = " + m.getMessage());
//page.getBody().addGlobalMessage(m);
MessageFlare mf = MessageFlare.display(page.getBody(), m);
mf.setTestID("SingleShotMsg");
}
}
windowSession.setAttribute(UIGoto.SINGLESHOT_MESSAGE, null);
}
page.callRequestStarted();
List<IGotoAction> al = (List<IGotoAction>) windowSession.getAttribute(UIGoto.PAGE_ACTION);
if(al != null && al.size() > 0) {
page.getBody().build();
for(IGotoAction ga : al) {
if(DomUtil.USERLOG.isDebugEnabled())
DomUtil.USERLOG.debug(cid + ": page reload action = " + ga);
ga.executeAction(page.getBody());
}
windowSession.setAttribute(UIGoto.PAGE_ACTION, null);
}
m_application.internalCallPageComplete(ctx, page);
page.getBody().internalOnBeforeRender();
page.internalDeltaBuild(); // If listeners changed the page-> rebuild those parts
// END ORDERED
//-- Start the main rendering process. Determine the browser type.
Writer w;
if(page.isRenderAsXHTML()) {
w = ctx.getOutputWriter("application/xhtml+xml; charset=UTF-8", "utf-8");
} else {
w = ctx.getOutputWriter("text/html; charset=UTF-8", "utf-8");
}
IBrowserOutput out = new PrettyXmlOutputWriter(w);
HtmlFullRenderer hr = m_application.findRendererFor(ctx.getBrowserVersion(), out);
hr.render(ctx, page);
//-- 20100408 jal If an UIGoto was done in createContent handle that
if(windowSession.handleGoto(ctx, page, false))
return;
} catch(SessionInvalidException x) {
//-- Mid-air collision between logout and some other action..
logUser(ctx, cid, clz.getName(), "Session exception: " + x);
renderUserError(ctx, "The session has been invalidated; perhaps you are logged out");
//System.err.println("domui debug: session invalidation exception");
} catch(ConversationDestroyedException x) {
logUser(ctx, cid, clz.getName(), "Conversation exception: " + x);
renderUserError(ctx, "Your conversation with the server has been destroyed. Please refresh the page.");
} catch(Exception ex) {
Exception x = WrappedException.unwrap(ex);
if(!(x instanceof ValidationException)) {
logUser(ctx, cid, clz.getName(), "Page exception: " + x);
}
//-- 20100504 jal Exception in page means it's content is invalid, so force a full rebuild
try {
page.getBody().forceRebuild();
} catch(ConversationDestroyedException xx) {
logUser(ctx, cid, clz.getName(), "Conversation exception: " + xx);
renderUserError(ctx, "Your conversation with the server has been destroyed. Please refresh the page.");
} catch(SessionInvalidException xx) {
logUser(ctx, cid, clz.getName(), "Session exception: " + x);
renderUserError(ctx, "The session has been invalidated; perhaps you have logged out in another window?");
} catch(Exception xxx) {
System.err.println("Double exception in handling full page build exception");
System.err.println("Original exception: " + x);
System.err.println("Second one on forceRebuild: " + xxx);
x.printStackTrace();
xxx.printStackTrace();
}
page.getBody().forceRebuild();
if(x instanceof NotLoggedInException) { // Better than repeating code in separate exception handlers.
String url = m_application.handleNotLoggedInException(ctx, (NotLoggedInException) x);
if(url != null) {
generateHttpRedirect(ctx, url, "You need to be logged in");
return;
}
}
IExceptionListener xl = ctx.getApplication().findExceptionListenerFor(x);
if(xl != null && xl.handleException(ctx, page, null, x)) {
if(windowSession.handleExceptionGoto(ctx, page, false)) {
AppSession aps = ctx.getSession();
if(aps.incrementExceptionCount() > 10) {
aps.clearExceptionRetryCount();
throw new IllegalStateException("Loop in exception handling in a full page (new page) render", x);
}
return;
}
}
checkFullExceptionCount(page, x); // Rethrow, but clear state if page throws up too much.
} finally {
page.callAfterRenderListeners();
page.internalClearDeltaFully();
}
//-- Full render completed: indicate that and reset the exception count
page.setFullRenderCompleted(true);
page.setPageExceptionCount(0);
ctx.getSession().clearExceptionRetryCount();
if(m_logPerf) {
ts = System.nanoTime() - ts;
System.out.println("domui: full render took " + StringTool.strNanoTime(ts));
}
//-- Start any delayed actions now.
page.getConversation().startDelayedExecution();
}
/**
* Try to render a terse error to the user.
*/
private void renderUserError(RequestContextImpl ctx, String s) {
try {
ctx.sendError(503, "It appears this session was logged out in mid-flight (" + s + ")");
} catch(Exception x) {
//-- Willfully ignore, nothing else we can do here.
}
}
private void logUser(@NonNull RequestContextImpl ctx, @Nullable String cid, @NonNull String pageName, String string) {
ctx.getSession().log(new UserLogItem(cid, pageName, null, null, string));
}
private void logUser(@NonNull RequestContextImpl ctx, @NonNull Page page, String string) {
ConversationContext conversation = page.internalGetConversation();
String cid = conversation == null ? null : conversation.getFullId();
ctx.getSession().log(new UserLogItem(cid, page.getBody().getClass().getName(), null, null, string));
}
/**
* Handle out-of-bound component requests. These are not allowed to change the tree but must return a result
* by themselves.
*/
private void runComponentAction(@NonNull RequestContextImpl ctx, @NonNull Page page, @NonNull String action) throws Exception {
m_application.internalCallPageAction(ctx, page);
page.callRequestStarted();
try {
NodeBase wcomp = null;
String wid = ctx.getParameter("webuic");
if(wid != null) {
wcomp = page.findNodeByID(wid);
}
if(wcomp == null)
return;
page.setTheCurrentNode(wcomp);
wcomp.componentHandleWebDataRequest(ctx, action);
} finally {
page.callRequestFinished();
page.setTheCurrentNode(null);
}
}
private void runPageData(@NonNull RequestContextImpl ctx, @NonNull Page page) throws Exception {
m_application.internalCallPageAction(ctx, page);
page.callRequestStarted();
NodeBase wcomp = null;
String wid = ctx.getParameter("webuic");
if(wid != null) {
wcomp = page.findNodeByID(wid);
// jal 20091120 The code below was active but is nonsense because we do not return after generateExpired!?
// if(wcomp == null) {
// generateExpired(ctx, NlsContext.getGlobalMessage(Msgs.S_BADNODE, wid));
}
if(wcomp == null)
return;
page.setTheCurrentNode(wcomp);
try {
IComponentUrlDataProvider dp = (IComponentUrlDataProvider) wcomp;
dp.provideUrlData(ctx);
} finally {
page.callRequestFinished();
page.setTheCurrentNode(null);
}
}
/**
* Call a component's JSON request handler, and render back the result.
*/
private void runPageJson(@NonNull RequestContextImpl ctx, @NonNull Page page, @Nullable NodeBase wcomp) throws Exception {
try {
if(!(wcomp instanceof IComponentJsonProvider))
throw new ProgrammerErrorException("The component " + wcomp + " must implement " + IComponentJsonProvider.class.getName() + " to be able to accept JSON data requests");
IComponentJsonProvider dp = (IComponentJsonProvider) wcomp;
PageParameters pp = PageParameters.createFromAll(ctx);
Object value = dp.provideJsonData(pp); // Let the component return something to render.
renderJsonLikeResponse(ctx, value);
} finally {
page.callRequestFinished();
page.setTheCurrentNode(null);
}
}
@NonNull
final private JSONRegistry m_jsonRegistry = new JSONRegistry();
private void renderJsonLikeResponse(@NonNull RequestContextImpl ctx, @NonNull Object value) throws Exception {
Writer w = ctx.getOutputWriter("application/javascript", "utf-8");
if(value instanceof String) {
//-- String return: we'll assume this is a javascript response by itself.
w.write((String) value);
} else {
//-- Object return: render as JSON
JSONRenderer jr = new JSONRenderer(m_jsonRegistry, new IndentWriter(w), false);
jr.render(value);
}
}
private void generateNonReloadableExpired(RequestContextImpl ctx, WindowSession cm) throws Exception {
StringBuilder sb = new StringBuilder();
sb.append(ExpiredSessionPage.class.getName()).append('.').append(DomApplication.get().getUrlExtension());
sb.append('?');
StringTool.encodeURLEncoded(sb, Constants.PARAM_CONVERSATION_ID);
sb.append('=');
sb.append(cm.getWindowID());
sb.append(".x"); // Dummy conversation ID
generateAjaxRedirect(ctx, sb.toString());
}
/**
* Fix for huge POST requests being resent as a get.
*/
private void redirectForPost(RequestContextImpl ctx, WindowSession cm, @NonNull PageParameters pp) throws Exception {
//-- Create conversation
ConversationContext cc = cm.createConversation(ConversationContext.class);
cm.acceptNewConversation(cc);
//-- Now: store the original PageParameters inside this conversation.
cc.setAttribute("__ORIPP", pp);
//-- Create an unique hash for the page parameters
String hashString = pp.calculateHashString(); // The unique hash of a page with these parameters
StringBuilder sb = new StringBuilder(256);
// sb.append('/');
sb.append(ctx.getRelativePath(ctx.getInputPath()));
sb.append('?');
StringTool.encodeURLEncoded(sb, Constants.PARAM_CONVERSATION_ID);
sb.append('=');
sb.append(cm.getWindowID());
sb.append(".");
sb.append(cc.getId());
sb.append("&");
sb.append(Constants.PARAM_POST_CONVERSATION_KEY).append("=").append(hashString);
generateHttpRedirect(ctx, sb.toString(), "Your session has expired. Starting a new session.");
}
/**
* Check if an exception is thrown every time; if so reset the page and rebuild it again.
*/
private void checkFullExceptionCount(Page page, Exception x) throws Exception {
//-- Full renderer aborted. Handle exception counting.
if(!page.isFullRenderCompleted()) { // Has the page at least once rendered OK?
//-- This page is initially unrenderable; the error is not due to state changes. Just rethrow and give up.
throw x;
}
//-- The page was initially renderable; the current problem is due to state changes. Increment the exception count and if too big clear the page before throwing up.
page.setPageExceptionCount(page.getPageExceptionCount() + 1);
if(page.getPageExceptionCount() >= 2) {
//-- Just destroy the stuff - it keeps dying on you.
page.getConversation().destroy();
throw new RuntimeException("The page keeps dying on you.. The page has been destroyed so that a new one will be allocated on the next refresh.", x);
}
//-- Just throw it now.
throw x;
}
/* CODING: Handle existing page events. */
/**
* Authentication checks: if the page has a "UIRights" annotation we need a logged-in
* user to check it's rights against the page's required rights.
*
* WARNING: Functional duplicate exists in {@link UIContext#hasRightsOn(Class)}.
*/
private boolean checkAccess(final WindowSession cm, final RequestContextImpl ctx, final Page page) throws Exception {
if(ctx.getParameter("webuia") != null)
throw new IllegalStateException("Cannot be called for an AJAX request");
UrlPage body = page.getBody(); // The actual, instantiated and injected class - which is unbuilt, though
UIRights rann = body.getClass().getAnnotation(UIRights.class); // Get class annotation
IRightsCheckedManually rcm = body instanceof IRightsCheckedManually ? (IRightsCheckedManually) body : null;
if(rann == null && rcm == null) { // Any kind of rights checking is required?
return true; // No -> allow access.
}
//-- Get user's IUser; if not present we need to log in.
IUser user = UIContext.getCurrentUser(); // Currently logged in?
if(user == null) {
redirectToLoginPage(cm, ctx);
return false;
}
//-- Start access checks, in order. First call the interface, if applicable
String failureReason = null;
try {
if(null != rcm) {
boolean allowed = rcm.isAccessAllowedBy(user); // Call interface: it explicitly allows
if(allowed)
return true;
//-- False indicates "I do not give access, but I do not deny it either". So move on to the next check.
}
if(null != rann) {
if(checkRightsAnnotation(body, rann, user)) { // Check annotation rights
return true;
}
//-- Just exit with a null failureReason - this indicates that a list of rights will be rendered.
} else
throw new CodeException(Msgs.BUNDLE, Msgs.RIGHTS_NOT_ALLOWED); // Insufficient rights - details unknown.
} catch(CodeException cx) {
failureReason = cx.getMessage();
} catch(Exception x) {
failureReason = x.toString();
}
/*
* Access not allowed: redirect to error page.
*/
ILoginDialogFactory ldf = m_application.getLoginDialogFactory();
String rurl = ldf == null ? null : ldf.getAccessDeniedURL();
if(rurl == null) {
rurl = DomApplication.get().getAccessDeniedPageClass().getName() + "." + m_application.getUrlExtension();
}
//-- Add info about the failed thingy.
StringBuilder sb = new StringBuilder(128);
sb.append(rurl);
DomUtil.addUrlParameters(sb, new PageParameters(AccessDeniedPage.PARAM_TARGET_PAGE, body.getClass().getName()), true);
//-- If we have a message use it
if(null != failureReason || rann == null) {
if(failureReason == null)
failureReason = "Empty reason - this should not happen!";
sb.append("&").append(AccessDeniedPage.PARAM_REFUSAL_MSG).append("=");
StringTool.encodeURLEncoded(sb, failureReason);
} else {
//-- All required rights
int ix = 0;
for(String r : rann.value()) {
sb.append("&r").append(ix).append("=");
ix++;
StringTool.encodeURLEncoded(sb, r);
}
}
generateHttpRedirect(ctx, sb.toString(), "Access denied");
logUser(ctx, cm.getWindowID(), page.getBody().getClass().getName(), sb.toString());
return false;
}
private void redirectToLoginPage(final WindowSession cm, final RequestContextImpl ctx) throws Exception {
//-- Create the after-login target URL.
StringBuilder sb = new StringBuilder(256);
sb.append(ctx.getRelativePath(ctx.getInputPath()));
sb.append('?');
StringTool.encodeURLEncoded(sb, Constants.PARAM_CONVERSATION_ID);
sb.append('=');
sb.append(cm.getWindowID());
sb.append(".x"); // Dummy conversation ID
DomUtil.addUrlParameters(sb, ctx, false);
//-- Obtain the URL to redirect to from a thingy factory (should this happen here?)
ILoginDialogFactory ldf = m_application.getLoginDialogFactory();
if(ldf == null)
throw NotLoggedInException.create(sb.toString()); // Force login exception.
String target = ldf.getLoginRURL(sb.toString()); // Create a RURL to move to.
if(target == null)
throw new IllegalStateException("The Login Dialog Handler=" + ldf + " returned an invalid URL for the login dialog.");
//-- Make this an absolute URL by appending the webapp path
target = ctx.getRelativePath(target);
generateHttpRedirect(ctx, target, "You need to login before accessing this function");
}
private boolean checkRightsAnnotation(@NonNull UrlPage body, @NonNull UIRights rann, @NonNull IUser user) throws Exception {
if(rann.value().length == 0) // No rights specified means -> just log in
return true;
if(StringTool.isBlank(rann.dataPath())) {
//-- No special data context - we just check plain general rights
for(String right : rann.value()) {
if(user.hasRight(right)) {
return true;
}
}
return false; // All worked, so we have access.
}
//-- We need the object specified in DataPath.
PropertyMetaModel< ? > pmm = MetaManager.getPropertyMeta(body.getClass(), rann.dataPath());
Object dataItem = pmm.getValue(body); // Get the page property.
for(String right : rann.value()) {
if(user.hasRight(right, dataItem)) {
return true;
}
}
return false;
}
/**
* Sends a redirect as a 304 MOVED command. This should be done for all full-requests.
*/
static public void generateHttpRedirect(RequestContextImpl ctx, String to, String rsn) throws Exception {
to = appendPersistedParameters(to, ctx);
IBrowserOutput out = new PrettyXmlOutputWriter(ctx.getOutputWriter("text/html; charset=UTF-8", "utf-8"));
out.writeRaw("<!DOCTYPE html PUBLIC \"-
+ "location.replace(" + StringTool.strToJavascriptString(to, true) + ");\n" + "--></script>\n" + "</head><body>" + rsn + "</body></html>\n");
}
/**
* Generate an AJAX redirect command. Should be used by all COMMAND actions.
*/
static public void generateAjaxRedirect(RequestContextImpl ctx, String url) throws Exception {
if(LOG.isInfoEnabled())
LOG.info("redirecting to " + url);
url = appendPersistedParameters(url, ctx);
IBrowserOutput out = new PrettyXmlOutputWriter(ctx.getOutputWriter("text/xml; charset=UTF-8", "utf-8"));
out.tag("redirect");
out.attr("url", url);
out.endAndCloseXmltag();
}
private static String appendPersistedParameters(String url, RequestContextImpl ctx) {
Set<String> nameSet = ctx.getApplication().getPersistentParameterSet();
if(nameSet.size() == 0)
return url;
Map<String, String> map = ctx.getPersistedParameterMap();
StringBuilder sb = new StringBuilder(url);
boolean first = ! url.contains("?");
for(Entry<String, String> entry : map.entrySet()) {
if(first) {
sb.append('?');
first = false;
} else {
sb.append('&');
}
StringTool.encodeURLEncoded(sb, entry.getKey());
sb.append('=');
StringTool.encodeURLEncoded(sb, entry.getValue());
}
return sb.toString();
}
/**
* Generates an EXPIRED message when the page here does not correspond with
* the page currently in the browser. This causes the browser to do a reload.
*/
private void generateExpired(final RequestContextImpl ctx, final String message) throws Exception {
//-- We stay on the same page. Render tree delta as response
IBrowserOutput out = new PrettyXmlOutputWriter(ctx.getOutputWriter("text/xml; charset=UTF-8", "utf-8"));
out.tag("expired");
out.endtag();
out.tag("msg");
out.endtag();
out.text(message);
out.closetag("msg");
out.closetag("expired");
}
private void generateEmptyDelta(final RequestContextImpl ctx) throws Exception {
//-- We stay on the same page. Render tree delta as response
IBrowserOutput out = new PrettyXmlOutputWriter(ctx.getOutputWriter("text/xml; charset=UTF-8", "utf-8"));
out.tag("delta");
out.endtag();
out.closetag("delta");
}
/**
* Generates an 'expiredOnPollasy' message when server receives pollasy call from expired page.
* Since pollasy calls are frequent, expired here means that user has navigated to some other page in meanwhile, and that response should be ignored by browser.
*/
private void generateExpiredPollasy(final RequestContextImpl ctx) throws Exception {
//-- We stay on the same page. Render tree delta as response
IBrowserOutput out = new PrettyXmlOutputWriter(ctx.getOutputWriter("text/xml; charset=UTF-8", "utf-8"));
out.tag("expiredOnPollasy");
out.endtag();
out.closetag("expiredOnPollasy");
}
/**
* Walk the request parameter list and bind all values that came from an input thingy
* to the appropriate Node. Nodes whose value change will leave a trail in the pending
* change list which will later be used to fire change events, if needed.
* <p>This collects a list of nodes whose input values have changed <b>and</b> that have
* an onValueChanged listener. This list will later be used to call the change handles
* on all these nodes (bug# 664).
*/
private List<NodeBase> handleComponentInput(@NonNull final IRequestContext ctx, @NonNull final Page page) throws Exception {
//-- Just walk all parameters in the input request.
List<NodeBase> changed = new ArrayList<>();
for(String name : ctx.getParameterNames()) {
String[] values = ctx.getParameters(name); // Get the value;
//-- Locate the component that the parameter is for;
if(name.startsWith("_")) {
NodeBase nb = page.findNodeByID(name); // Can we find this literally?
if(nb != null) {
//-- Try to bind this value to the component.
if(nb.acceptRequestParameter(values)) { // Make the thingy accept the parameter(s)
//-- This thing has changed.
if(nb instanceof IHasChangeListener) { // Can have a value changed thingy?
IHasChangeListener ch = (IHasChangeListener) nb;
if(ch.getOnValueChanged() != null) {
changed.add(nb);
}
}
}
}
}
}
return changed;
}
private void runAction(final RequestContextImpl ctx, final Page page, final String action, List<NodeBase> pendingChangeList) throws Exception {
// System.out.println("# action="+action);
long ts = System.nanoTime();
m_application.internalCallPageAction(ctx, page);
page.callRequestStarted();
if(!Constants.ACMD_ASYPOLL.equals(action))
page.controlToModel();
NodeBase wcomp = null;
String wid = ctx.getParameter(Constants.PARAM_UICOMPONENT);
if(wid != null) {
wcomp = page.findNodeByID(wid);
// jal 20091120 The code below was active but is nonsense because we do not return after generateExpired!?
// if(wcomp == null) {
// generateExpired(ctx, NlsContext.getGlobalMessage(Msgs.S_BADNODE, wid));
}
boolean inhibitlog = false;
page.setTheCurrentNode(wcomp);
//-- Non-delta actions
if(Constants.ACMD_PAGEJSON.equals(action)) {
try {
runPageJson(ctx, page, wcomp);
return;
} finally {
page.callRequestFinished();
}
}
try {
/*
* If we have pending changes execute them before executing any actual command. Also: be
* very sure the changed component is part of that list!! Fix for bug# 664.
*/
//-- If we are a vchange command *and* the node that changed still exists make sure it is part of the changed list.
if((Constants.ACMD_VALUE_CHANGED.equals(action) || Constants.ACMD_CLICKANDCHANGE.equals(action)) && wcomp != null) {
if(!pendingChangeList.contains(wcomp))
pendingChangeList.add(wcomp);
}
//-- Call all "changed" handlers.
for(NodeBase n : pendingChangeList) {
if(DomUtil.USERLOG.isDebugEnabled()) {
DomUtil.USERLOG.debug("valueChanged on " + DomUtil.getComponentDetails(n));
logUser(ctx, page, "valueChanged on " + DomUtil.getComponentDetails(n));
}
n.internalOnValueChanged();
}
// FIXME 20100331 jal Odd wcomp==null logic. Generalize.
if(Constants.ACMD_CLICKED.equals(action)) {
handleClicked(ctx, page, wcomp);
} else if(Constants.ACMD_CLICKANDCHANGE.equals(action)) {
if(wcomp != null && wcomp.getClicked() != null)
handleClicked(ctx, page, wcomp);
} else if(Constants.ACMD_VALUE_CHANGED.equals(action)) {
//-- Don't do anything at all - everything is done beforehand (bug #664).
} else if(Constants.ACMD_DEVTREE.equals(action)) {
handleDevelopmentShowCode(page, wcomp);
} else if(Constants.ACMD_ASYPOLL.equals(action)) {
inhibitlog = true;
//-- Async poll request..
// } else if("WEBUIDROP".equals(action)) {
// handleDrop(ctx, page, wcomp);
} else if(wcomp == null && isSafeToIgnoreUnknownNodeOnAction(action)) {
//-- Don't do anything at all - it is safe to ignore late and obsoleted events
inhibitlog = true;
} else if(wcomp == null) {
if(!action.endsWith("?"))
throw new IllegalStateException("Unknown node '" + wid + "' for action='" + action + "'");
} else {
wcomp.componentHandleWebAction(ctx, action);
}
ConversationContext conversation = page.internalGetConversation();
if(null != conversation && conversation.isValid())
page.modelToControl();
} catch(ValidationException x) {
/*
* When an action handler failed because it accessed a component which has a validation error
* we just continue - the failed validation will have posted an error message.
*/
if(LOG.isDebugEnabled())
LOG.debug("rq: ignoring validation exception " + x);
page.modelToControl();
} catch(MsgException msg) {
MsgBox.error(page.getBody(), msg.getMessage());
logUser(ctx, page, "error message: " + msg.getMessage());
page.modelToControl();
} catch(Exception ex) {
logUser(ctx, page, "Action handler exception: " + ex);
Exception x = WrappedException.unwrap(ex);
if(x instanceof NotLoggedInException) { // FIXME Fugly. Generalize this kind of exception handling somewhere.
String url = m_application.handleNotLoggedInException(ctx, (NotLoggedInException) x);
if(url != null) {
generateAjaxRedirect(ctx, url);
return;
}
}
try {
page.modelToControl();
} catch(Exception xxx) {
System.out.println("Double exception on modelToControl: " + xxx);
xxx.printStackTrace();
}
IExceptionListener xl = ctx.getApplication().findExceptionListenerFor(x);
if(xl == null) // No handler?
throw x; // Move on, nothing to see here,
if(wcomp != null && !wcomp.isAttached()) {
wcomp = page.getTheCurrentControl();
System.out.println("DEBUG: Report exception on a " + (wcomp == null ? "unknown control/node" : wcomp.getClass()));
}
if(wcomp == null || !wcomp.isAttached())
throw new IllegalStateException("INTERNAL: Cannot determine node to report exception /on/", x);
if(!xl.handleException(ctx, page, wcomp, x))
throw x;
}
page.callRequestFinished();
if(m_logPerf && !inhibitlog) {
ts = System.nanoTime() - ts;
System.out.println("domui: Action handling took " + StringTool.strNanoTime(ts));
}
if(!page.isDestroyed()) // jal 20090827 If an exception handler or whatever destroyed conversation or page exit...
page.getConversation().processDelayedResults(page);
//-- Determine the response class to render; exit if we have a redirect,
WindowSession cm = ctx.getWindowSession();
if(cm.handleGoto(ctx, page, true))
return;
//-- Call the 'new page added' listeners for this page, if it is now unbuilt due to some action calling forceRebuild() on it. Fixes bug# 605
callNewPageBuiltListeners(page);
//-- We stay on the same page. Render tree delta as response
try {
renderOptimalDelta(ctx, page, inhibitlog);
} catch(NotLoggedInException x) { // FIXME Fugly. Generalize this kind of exception handling somewhere.
String url = m_application.handleNotLoggedInException(ctx, x);
if(url != null) {
generateHttpRedirect(ctx, url, "You need to be logged in");
}
} catch(Exception x) {
logUser(ctx, page, "Delta render failed: " + x);
throw x;
}
}
/**
* Defines the actions that could arrive too late due to race conditions in client javascript, when target elements are already removed from DOM at server side.
* It is safe to just ignore such obsoleted events, rather than giving error response.
*/
private boolean isSafeToIgnoreUnknownNodeOnAction(@NonNull String action) {
return (Constants.ACMD_LOOKUP_TYPING.equals(action) || Constants.ACMD_LOOKUP_TYPING_DONE.equals(action) || Constants.ACMD_NOTIFY_CLIENT_POSITION_AND_SIZE.equals(action));
}
/**
* Called in DEVELOPMENT mode when the source code for a page is requested (double escape press). It shows
* the nodes from the entered one upto the topmost one, and when selected tries to open the source code
* by sending a command to the local Eclipse.
*/
private void handleDevelopmentShowCode(Page page, NodeBase wcomp) {
if(null == wcomp)
return;
//-- If a tree is already present ignore the click.
List<InternalParentTree> res = page.getBody().getDeepChildren(InternalParentTree.class);
if(res.size() > 0)
return;
InternalParentTree ipt = new InternalParentTree(wcomp);
page.getBody().add(0, ipt);
}
static public void renderOptimalDelta(final RequestContextImpl ctx, final Page page) throws Exception {
renderOptimalDelta(ctx, page, false);
}
static private void renderOptimalDelta(final RequestContextImpl ctx, final Page page, boolean inhibitlog) throws Exception {
// ORDERED
//-- 20100519 jal Force full rebuild before rendering, always. See bug 688.
page.getBody().internalOnBeforeRender();
page.internalDeltaBuild();
ctx.getApplication().internalCallPageComplete(ctx, page);
page.internalDeltaBuild();
// /ORDERED
IBrowserOutput out = new PrettyXmlOutputWriter(ctx.getOutputWriter("text/xml; charset=UTF-8", "utf-8"));
long ts = System.nanoTime();
// String usag = ctx.getUserAgent();
HtmlFullRenderer fullr = ctx.getApplication().findRendererFor(ctx.getBrowserVersion(), out);
OptimalDeltaRenderer dr = new OptimalDeltaRenderer(fullr, ctx, page);
dr.render();
if(m_logPerf && !inhibitlog) {
ts = System.nanoTime() - ts;
System.out.println("domui: Optimal Delta rendering using " + fullr + " took " + StringTool.strNanoTime(ts));
}
page.getConversation().startDelayedExecution();
}
/**
* Call all "new page" listeners when a page is unbuilt or new at this time.
*/
private void callNewPageBuiltListeners(final Page pg) throws Exception {
if(pg.getBody().isBuilt())
return;
pg.internalFullBuild();
for(INewPageInstantiated npi : m_application.getNewPageInstantiatedListeners())
npi.newPageBuilt(pg.getBody());
}
/**
* Called when the action is a CLICK event on some thingy. This causes the click handler for
* the object to be called.
*/
private void handleClicked(IRequestContext ctx, Page page, @Nullable NodeBase b) throws Exception {
if(b == null) {
logUser((RequestContextImpl) ctx, page, "User clicked to fast - node has disappeared");
System.out.println("User clicked too fast? Node not found. Ignoring.");
return;
}
String msg = "Clicked on " + DomUtil.getComponentDetails(b);
logUser((RequestContextImpl) ctx, page, msg);
if(DomUtil.USERLOG.isDebugEnabled()) {
DomUtil.USERLOG.debug(msg);
}
ClickInfo cli = new ClickInfo(ctx);
b.internalOnClicked(cli);
}
/* CODING: If a page failed, show a neater response. */
private void renderOopsFrame(@NonNull RequestContextImpl ctx, @NonNull Throwable x) throws Exception {
x.printStackTrace();
if(ctx.getRequestResponse() instanceof HttpServerRequestResponse) {
HttpServerRequestResponse srr = (HttpServerRequestResponse) ctx.getRequestResponse();
HttpServletResponse resp = srr.getResponse();
resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); // Fail with proper response code.
}
ThemeManager themeManager = ctx.getApplication().internalGetThemeManager();
Map<String, Object> dataMap = new HashMap<>();
dataMap.put("x", x);
dataMap.put("ctx", ctx);
dataMap.put("app", ctx.getRelativePath(""));
String sheet = themeManager.getThemedResourceRURL(ctx, "THEME/style.theme.css");
if(null == sheet)
throw new IllegalStateException("Unexpected null??");
dataMap.put("stylesheet", sheet);
String theme = themeManager.getThemedResourceRURL(ctx, "THEME/");
dataMap.put("theme", theme);
StringBuilder sb = new StringBuilder();
dumpException(sb, x);
dataMap.put("stacktrace", sb.toString());
dataMap.put("message", StringTool.htmlStringize(x.toString()));
dataMap.put("ctx", ctx);
ExceptionUtil util = new ExceptionUtil(ctx);
dataMap.put("util", util);
//util.renderEmail(x);
Writer w = ctx.getRequestResponse().getOutputWriter("text/html", "utf-8");
JSTemplate xt = getExceptionTemplate();
xt.execute(w, dataMap);
w.flush();
w.close();
}
@NonNull
public JSTemplate getExceptionTemplate() throws Exception {
JSTemplate xt = m_exceptionTemplate;
if(xt == null) {
JSTemplateCompiler jtc = new JSTemplateCompiler();
File src = new File(getClass().getResource("exceptionTemplate.html").getFile());
if(src.exists() && src.isFile()) {
Reader r = new FileReader(src);
try {
xt = jtc.compile(r, src.getAbsolutePath());
} finally {
FileTool.closeAll(r);
}
} else {
xt = jtc.compile(ApplicationRequestHandler.class, "exceptionTemplate.html", "utf-8");
}
m_exceptionTemplate = xt;
}
return xt;
}
static private void dumpException(@NonNull StringBuilder a, @NonNull Throwable x) {
Set<String> allset = new HashSet<>();
StackTraceElement[] ssear = x.getStackTrace();
for(StackTraceElement sse : ssear) {
allset.add(sse.toString());
}
dumpSingle(a, x, Collections.EMPTY_SET);
Throwable curr = x;
for(;;) {
Throwable cause = curr.getCause();
if(cause == null || cause == curr)
break;
a.append("\n\n Caused by ").append(cause.toString()).append("\n");
dumpSingle(a, cause, allset);
curr = cause;
}
}
static private void dumpSingle(@NonNull StringBuilder sb, @NonNull Throwable x, @NonNull Set<String> initset) {
//-- Try to render openable stack trace elements as links.
List<StackTraceElement> list = Arrays.asList(x.getStackTrace());
//-- Remove from the end the server stuff
int ix = findName(list, AppFilter.class.getName());
if(ix != -1) {
list = new ArrayList<>(stripFrames(list, ix + 1));
}
//-- Remove from the end all names in initset.
for(int i = list.size(); --i >= 0;) {
String str = list.get(i).toString();
if(!initset.contains(str))
break;
list.remove(i);
}
for(StackTraceElement ste : list) {
appendTraceLink(sb, ste);
}
if(x instanceof SQLException) {
SQLException sx = (SQLException) x;
while(sx.getNextException() != null) {
sx = sx.getNextException();
sb.append("SQL NextException: ");
sb.append(sx.toString());
sb.append("<br>");
}
}
}
private static int findName(@NonNull List<StackTraceElement> list, String name) {
for(int i = list.size(); --i >= 0;) {
String cn = list.get(i).getClassName();
if(name.equals(cn))
return i;
}
return -1;
}
private static List<StackTraceElement> stripFrames(@NonNull List<StackTraceElement> list, int from) {
return list.subList(0, from - 1);
}
private static void appendTraceLink(@NonNull StringBuilder sb, @NonNull StackTraceElement ste) {
sb.append(" <a class='exc-stk-l' href=\"#\" onclick=\"linkClicked('");
//-- Get name for the thingy,
String name;
if(ste.getLineNumber() <= 0)
name = ste.getClassName().replace('.', '/') + ".java@" + ste.getMethodName();
else
name = ste.getClassName().replace('.', '/') + ".java#" + ste.getLineNumber();
sb.append(name);
sb.append("')\">");
sb.append(ste.toString()).append("</a><br>");
}
}
|
package net.imagej.legacy;
import ij.Executer;
import ij.IJ;
import ij.ImageJ;
import ij.ImagePlus;
import ij.Macro;
import ij.Menus;
import ij.Prefs;
import ij.WindowManager;
import ij.gui.ImageWindow;
import ij.gui.Toolbar;
import ij.io.DirectoryChooser;
import ij.io.OpenDialog;
import ij.io.Opener;
import ij.io.SaveDialog;
import ij.macro.Interpreter;
import ij.measure.ResultsTable;
import ij.plugin.Commands;
import ij.plugin.PlugIn;
import ij.plugin.filter.PlugInFilter;
import ij.plugin.filter.PlugInFilterRunner;
import ij.plugin.frame.Recorder;
import ij.plugin.frame.RoiManager;
import java.awt.Component;
import java.awt.EventQueue;
import java.awt.Frame;
import java.awt.Image;
import java.awt.Menu;
import java.awt.MenuBar;
import java.awt.MenuItem;
import java.awt.Panel;
import java.awt.Window;
import java.awt.image.ImageProducer;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.Callable;
import javax.swing.SwingUtilities;
import net.imagej.display.ImageDisplay;
import net.imagej.patcher.LegacyHooks;
import org.scijava.AbstractContextual;
import org.scijava.Context;
import org.scijava.MenuEntry;
import org.scijava.MenuPath;
import org.scijava.event.EventHandler;
import org.scijava.log.LogService;
import org.scijava.module.ModuleInfo;
import org.scijava.platform.event.AppAboutEvent;
import org.scijava.platform.event.AppOpenFilesEvent;
import org.scijava.platform.event.AppPreferencesEvent;
import org.scijava.platform.event.AppQuitEvent;
import org.scijava.plugin.Parameter;
import org.scijava.script.ScriptService;
import org.scijava.util.ClassUtils;
/**
* A helper class to interact with ImageJ 1.x.
* <p>
* The LegacyService needs to patch ImageJ 1.x's classes before they are loaded.
* Unfortunately, this is tricky: if the LegacyService already uses those
* classes, it is a matter of luck whether we can get the patches in before
* those classes are loaded.
* </p>
* <p>
* Therefore, we put as much interaction with ImageJ 1.x as possible into this
* class and keep a reference to it in the LegacyService.
* </p>
*
* @author Johannes Schindelin
*/
public class IJ1Helper extends AbstractContextual {
/** A reference to the legacy service, just in case we need it. */
private final LegacyService legacyService;
@Parameter
private LogService log;
/** Whether we are in the process of forcibly shutting down ImageJ1. */
private boolean disposing;
public IJ1Helper(final LegacyService legacyService) {
setContext(legacyService.getContext());
this.legacyService = legacyService;
}
public void initialize() {
// initialize legacy ImageJ application
final ImageJ ij1 = IJ.getInstance();
if (getCommands() == null) {
IJ.runPlugIn("ij.IJ.init", "");
}
if (ij1 != null) {
// NB: *Always* call System.exit(0) when quitting:
// - In the case of batch mode, the JVM needs to terminate at the
// conclusion of the macro/script, regardless of the actions performed
// by that macro/script.
// - In the case of GUI mode, the JVM needs to terminate when the user
// quits the program because ImageJ1 has many plugins which do not
// properly clean up their resources. This is a vicious cycle:
// ImageJ1's main method sets exitWhenQuitting to true, which has
// historically masked the problems with these plugins. So we have
// little choice but to continue this tradition, at least with the
// legacy ImageJ1 user interface.
ij1.exitWhenQuitting(true);
// make sure that the Event Dispatch Thread's class loader is set
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
Thread.currentThread().setContextClassLoader(IJ.getClassLoader());
}
});
final LegacyImageMap imageMap = legacyService.getImageMap();
for (int i = 1; i <= WindowManager.getImageCount(); i++) {
imageMap.registerLegacyImage(WindowManager.getImage(i));
}
// set icon and title of main window (which are instantiated before the
// initializer is called)
try {
final LegacyHooks hooks =
(LegacyHooks) IJ.class.getField("_hooks").get(null);
ij1.setTitle(hooks.getAppName());
final URL iconURL = hooks.getIconURL();
if (iconURL != null) try {
final Object producer = iconURL.getContent();
final Image image = ij1.createImage((ImageProducer) producer);
ij1.setIconImage(image);
if (IJ.isMacOSX()) try {
// NB: We also need to set the dock icon
final Class<?> clazz = Class.forName("com.apple.eawt.Application");
final Object app = clazz.getMethod("getApplication").invoke(null);
clazz.getMethod("setDockIconImage", Image.class).invoke(app, image);
}
catch (final Throwable t) {
t.printStackTrace();
}
}
catch (final IOException e) {
IJ.handleException(e);
}
}
catch (final Throwable t) {
t.printStackTrace();
}
// FIXME: handle window location via LegacyUI
// This is necessary because the ImageJ 1.x window will not set its
// location if created with mode NO_SHOW, which is exactly how it is
// created right now by the legacy layer. This is a work-around by
// ensuring the preferred (e.g. saved and loaded) location is current at
// the time the IJ1Helper is initialized. Ideally we would like to handle
// positioning via the LegacyUI though, so that we can restore positions
// on secondary monitors and such.
ij1.setLocation(ij1.getPreferredLocation());
}
}
/**
* Forcibly shuts down ImageJ1, with no user interaction or opportunity to
* cancel. If ImageJ1 is not currently initialized, or if ImageJ1 is already
* in the process of quitting (i.e., {@link ij.ImageJ#quitting()} returns
* {@code true}), then this method does nothing.
*/
public synchronized void dispose() {
final ImageJ ij = IJ.getInstance();
if (ij != null && ij.quitting()) return; // IJ1 is already on its way out
disposing = true;
closeImageWindows();
disposeNonImageWindows();
if (ij != null) {
// quit legacy ImageJ on the same thread
ij.exitWhenQuitting(false); // do *not* quit the JVM!
ij.run();
}
disposing = false;
}
/** Whether we are in the process of forcibly shutting down ImageJ1. */
public boolean isDisposing() {
return disposing;
}
/** Add name aliases for ImageJ1 classes to the ScriptService. */
public void addAliases(final ScriptService scriptService) {
scriptService.addAlias(ImagePlus.class);
scriptService.addAlias(ResultsTable.class);
scriptService.addAlias(RoiManager.class);
}
public boolean isVisible() {
final ImageJ ij = IJ.getInstance();
if (ij == null) return false;
return ij.isVisible();
}
/**
* Determines whether <i>Edit>Options>Misc...>Run single instance
* listener</i> is set.
*
* @return true if <i>Run single instance listener</i> is set
*/
public boolean isRMIEnabled() {
return Prefs.runSocketListener;
}
private boolean batchMode;
void setBatchMode(final boolean batch) {
Interpreter.batchMode = batch;
batchMode = batch;
}
void invalidateInstance() {
try {
final Method cleanup = IJ.class.getDeclaredMethod("cleanup");
cleanup.setAccessible(true);
cleanup.invoke(null);
}
catch (final Throwable t) {
t.printStackTrace();
log.error(t);
}
}
/**
* Sets {@link WindowManager} {@code checkForDuplicateName} field.
*/
public void setCheckNameDuplicates(final boolean checkDuplicates) {
WindowManager.checkForDuplicateName = checkDuplicates;
}
public void setVisible(final boolean toggle) {
if (batchMode) return;
final ImageJ ij = IJ.getInstance();
if (ij != null) {
if (toggle) ij.pack();
ij.setVisible(toggle);
}
// hide/show the legacy ImagePlus instances
final LegacyImageMap imageMap = legacyService.getImageMap();
for (final ImagePlus imp : imageMap.getImagePlusInstances()) {
final ImageWindow window = imp.getWindow();
if (window != null) window.setVisible(toggle);
}
}
public void syncActiveImage(final ImageDisplay activeDisplay) {
final LegacyImageMap imageMap = legacyService.getImageMap();
final ImagePlus activeImagePlus = imageMap.lookupImagePlus(activeDisplay);
// NB - old way - caused probs with 3d Project
// WindowManager.setTempCurrentImage(activeImagePlus);
// NB - new way - test thoroughly
if (activeImagePlus == null) WindowManager.setCurrentWindow(null);
else WindowManager.setCurrentWindow(activeImagePlus.getWindow());
}
public void setKeyDown(final int keyCode) {
IJ.setKeyDown(keyCode);
}
public void setKeyUp(final int keyCode) {
IJ.setKeyUp(keyCode);
}
public boolean hasInstance() {
return IJ.getInstance() != null;
}
/** Gets the version of ImageJ 1.x. */
public String getVersion() {
// NB: We cannot hardcode a reference to ImageJ.VERSION. Java often inlines
// string constants at compile time. This means that if a different version
// of ImageJ 1.x is used at runtime, this method could return an incorrect
// value. Calling IJ.getVersion() would be more reliable, except that we
// override its behavior to return LegacyHooks#getAppVersion(). So instead,
// we resort to referencing the ImageJ#VERSION constant via reflection.
try {
final Field field = ImageJ.class.getField("VERSION");
if (field != null) {
final Object version = field.get(null);
if (version != null) return version.toString();
}
}
catch (final NoSuchFieldException exc) {
log.error(exc);
}
catch (final IllegalAccessException exc) {
log.error(exc);
}
return "Unknown";
}
public boolean isMacintosh() {
return IJ.isMacintosh();
}
public void setStatus(final String message) {
IJ.showStatus(message);
}
public void setProgress(final int val, final int max) {
IJ.showProgress(val, max);
}
public Component getToolBar() {
return Toolbar.getInstance();
}
public Panel getStatusBar() {
if (!hasInstance()) return null;
return IJ.getInstance().getStatusBar();
}
public Frame getIJ() {
if (hasInstance()) {
return IJ.getInstance();
}
return null;
}
public void setLocation(final int x, final int y) {
if (!hasInstance()) return;
IJ.getInstance().setLocation(x, y);
}
public int getX() {
if (!hasInstance()) return 0;
return IJ.getInstance().getX();
}
public int getY() {
if (!hasInstance()) return 0;
return IJ.getInstance().getY();
}
public boolean isWindowClosed(final Frame window) {
if (window instanceof ImageWindow) {
return ((ImageWindow) window).isClosed();
}
return false;
}
public boolean quitting() {
if (hasInstance()) return IJ.getInstance().quitting();
return false;
}
public int[] getIDList() {
return WindowManager.getIDList();
}
public ImagePlus getImage(final int imageID) {
return WindowManager.getImage(imageID);
}
/**
* Returns {@link ImagePlus#getTitle()} if the object is an {@link ImagePlus},
* otherwise null.
*/
public static String getTitle(final Object o) {
return o instanceof ImagePlus ? ((ImagePlus) o).getTitle() : null;
}
public ClassLoader getClassLoader() {
return IJ.getClassLoader();
}
public void showMessage(final String title, final String message) {
IJ.showMessage(title, message);
}
public boolean showMessageWithCancel(final String title,
final String message)
{
return IJ.showMessageWithCancel(title, message);
}
public String commandsName() {
return Commands.class.getName();
}
public void updateRecentMenu(final String path) {
final Menu menu = Menus.getOpenRecentMenu();
if (menu == null) return;
final int n = menu.getItemCount();
int index = -1;
for (int i = 0; i < n; i++) {
if (menu.getItem(i).getLabel().equals(path)) {
index = i;
break;
}
}
// Move to most recent
if (index > 0) {
final MenuItem item = menu.getItem(index);
menu.remove(index);
menu.insert(item, 0);
}
// not found, so replace oldest
else if (index < 0) {
final int count = menu.getItemCount();
if (count >= Menus.MAX_OPEN_RECENT_ITEMS) {
menu.remove(count - 1);
}
final MenuItem item = new MenuItem(path);
final ImageJ instance = IJ.getInstance();
if (instance != null) item.addActionListener(instance);
menu.insert(item, 0);
}
// if index was 0, already at the head so do nothing
}
/**
* Opens an image and adds the path to the <i>File>Open Recent</i> menu.
*
* @param file the image to open
*/
public static void openAndAddToRecent(final File file) {
new Opener().openAndAddToRecent(file.getAbsolutePath());
}
/**
* Records an option in ImageJ 1.x's macro recorder, <em>safely</em>.
* <p>
* Both the key and the value will be escaped to avoid problems. This behavior
* differs from direct calls to {@link Recorder#recordOption(String, String)},
* which do not escape either string.
* </p>
*
* @param key the name of the option
* @param value the value of the option
*/
public void recordOption(final String key, final String value) {
Recorder.recordOption(escape(key), escape(value));
}
/**
* Determines whether we're running inside a macro right now.
*
* @return whether we're running a macro right now.
*/
public boolean isMacro() {
return IJ.isMacro();
}
/**
* Gets a macro parameter of type <i>boolean</i>.
*
* @param label the name of the macro parameter
* @param defaultValue the default value
* @return the boolean value
*/
public boolean getMacroParameter(final String label,
final boolean defaultValue)
{
return getMacroParameter(label) != null || defaultValue;
}
/**
* Gets a macro parameter of type <i>double</i>.
*
* @param label the name of the macro parameter
* @param defaultValue the default value
* @return the double value
*/
public double getMacroParameter(final String label,
final double defaultValue)
{
final String value = Macro.getValue(getOptions(), label, null);
return value != null ? Double.parseDouble(value) : defaultValue;
}
/**
* Gets a macro parameter of type {@link String}.
*
* @param label the name of the macro parameter
* @param defaultValue the default value
* @return the value
*/
public String getMacroParameter(final String label,
final String defaultValue)
{
return Macro.getValue(getOptions(), label, defaultValue);
}
/**
* Gets a macro parameter of type {@link String}.
*
* @param label the name of the macro parameter
* @return the value, <code>null</code> if the parameter was not specified
*/
public String getMacroParameter(final String label) {
return Macro.getValue(getOptions(), label, null);
}
/** Returns the active macro {@link Interpreter}. */
public static Object getInterpreter() {
return Interpreter.getInstance();
}
/**
* Gets the value of the specified variable, from the given macro
* {@link Interpreter}.
*
* @param interpreter The macro {@link Interpreter} to query.
* @return The list of variables in {@code key\tvalue} form, as given by
* {@link Interpreter#getVariables()}.
* @throws ClassCastException if the given interpreter is not an
* {@link Interpreter}.
*/
public String[] getVariables(final Object interpreter) {
return ((Interpreter) interpreter).getVariables();
}
/**
* Gets the value of the specified variable, from the given macro
* {@link Interpreter}.
*
* @param interpreter The macro {@link Interpreter} to query.
* @param name The name of the variable to retrieve.
* @return The value of the requested variable, as either a {@link String}, a
* {@link Double} or {@code null}.
* @throws ClassCastException if the given interpreter is not an
* {@link Interpreter}.
*/
public Object getVariable(final Object interpreter, final String name) {
final Interpreter interp = (Interpreter) interpreter;
// might be a string
final String sValue = interp.getStringVariable(name);
if (sValue != null) return sValue;
// probably a number
final double nValue = interp.getVariable2(name);
if (!Double.isNaN(nValue)) return nValue;
return null;
}
/** Returns true if the object is an instance of {@link ImagePlus}. */
public boolean isImagePlus(final Object o) {
return o instanceof ImagePlus;
}
/** Returns true if the class is assignable to {@link ImagePlus}. */
public boolean isImagePlus(final Class<?> c) {
return ImagePlus.class.isAssignableFrom(c);
}
public int getImageID(final Object o) {
return ((ImagePlus) o).getID();
}
/** Gets the SciJava application context linked to the ImageJ 1.x instance. */
public static Context getLegacyContext() {
// NB: This call instantiates a Context if there is none.
// IJ.runPlugIn() will be intercepted by the legacy hooks if they are
// installed and return the current Context.
// If no legacy hooks are installed, ImageJ 1.x will instantiate the Context
// using the PluginClassLoader and the LegacyService will install the legacy
// hooks.
final Object o = IJ.runPlugIn("org.scijava.Context", "");
if (o == null) return null;
if (!(o instanceof Context)) {
throw new IllegalStateException("Unexpected type of context: " +
o.getClass().getName());
}
return (Context) o;
}
/**
* Partial replacement for ImageJ 1.x's MacAdapter.
* <p>
* ImageJ 1.x has a MacAdapter plugin that intercepts MacOSX-specific events
* and handles them. The way it does it is deprecated now, however, and
* unfortunately incompatible with the way ImageJ 2's platform service does
* it.
* </p>
* <p>
* This class implements the same functionality as the MacAdapter, but in a
* way that is compatible with the SciJava platform service.
* </p>
* <p>
* Note that the {@link AppAboutEvent}, {@link AppPreferencesEvent} and
* {@link AppQuitEvent} are handled separately, indirectly, by the
* {@link LegacyImageJApp}. See also {@link IJ1Helper#appAbout},
* {@link IJ1Helper#appPrefs} and {@link IJ1Helper#appQuit}.
* </p>
*
* @author Johannes Schindelin
*/
private static class LegacyEventDelegator extends AbstractContextual {
@Parameter(required = false)
private LegacyService legacyService;
// -- MacAdapter re-implementations --
/** @param event */
@EventHandler
private void onEvent(final AppOpenFilesEvent event) {
if (isLegacyMode()) {
final List<File> files = new ArrayList<>(event.getFiles());
for (final File file : files) {
openAndAddToRecent(file);
}
}
}
private boolean isLegacyMode() {
// We call setContext() indirectly from LegacyService#initialize,
// therefore legacyService might still be null at this point even if the
// context knows a legacy service now.
if (legacyService == null) {
final Context context = getContext();
if (context != null) {
legacyService = context.getService(LegacyService.class);
}
}
return legacyService != null && legacyService.isLegacyMode();
}
}
private static LegacyEventDelegator eventDelegator;
public static void subscribeEvents(final Context context) {
if (context == null) {
eventDelegator = null;
}
else {
eventDelegator = new LegacyEventDelegator();
eventDelegator.setContext(context);
}
}
static void run(final Class<?> c) {
IJ.resetEscape();
if (PlugIn.class.isAssignableFrom(c)) {
try {
final PlugIn plugin = (PlugIn) c.newInstance();
plugin.run("");
}
catch (final Exception e) {
throw e instanceof RuntimeException ?
(RuntimeException) e : new RuntimeException(e);
}
return;
}
if (PlugInFilter.class.isAssignableFrom(c)) {
try {
final PlugInFilter plugin = (PlugInFilter) c.newInstance();
final ImagePlus image = WindowManager.getCurrentImage();
if (image != null && image.isLocked()) {
final String msg = "The image '" +
image.getTitle() + "' appears to be locked... Unlock?";
if (!IJ.showMessageWithCancel("Unlock image?", msg)) return;
image.unlock();
}
new PlugInFilterRunner(plugin, c.getName(), "");
}
catch (final Exception e) {
throw e instanceof RuntimeException ? (RuntimeException) e
: new RuntimeException(e);
}
return;
}
throw new RuntimeException("TODO: construct class loader");
}
private boolean menuInitialized;
@SuppressWarnings("unchecked")
public Hashtable<String, String> getCommands() {
return Menus.getCommands();
}
public MenuBar getMenuBar() {
final ImageJ ij1 = hasInstance() ? IJ.getInstance() : null;
return ij1 == null ? null : ij1.getMenuBar();
}
/**
* Adds legacy-compatible scripts and commands to the ImageJ1 menu structure.
*/
public synchronized void addMenuItems() {
if (menuInitialized) return;
final Map<String, ModuleInfo> modules =
legacyService.getScriptsAndNonLegacyCommands();
final Hashtable<String, String> ij1Commands = getCommands();
final ImageJ ij1 = hasInstance() ? IJ.getInstance() : null;
final IJ1MenuWrapper wrapper = ij1 == null ? null : new IJ1MenuWrapper(ij1);
class Item implements Comparable<Item> {
private double weight;
private MenuPath path;
private String name, identifier;
private ModuleInfo info;
@Override
public int compareTo(final Item o) {
if (weight != o.weight) return Double.compare(weight, o.weight);
return compare(path, o.path);
}
public int compare(final MenuPath a, final MenuPath b) {
int i = 0;
while (i < a.size() && i < b.size()) {
final MenuEntry a2 = a.get(i), b2 = b.get(i);
int diff = Double.compare(a.get(i).getWeight(), b.get(i).getWeight());
if (diff != 0) return diff;
diff = a2.getName().compareTo(b2.getName());
if (diff != 0) return diff;
i++;
}
return 0;
}
}
final List<Item> items = new ArrayList<>();
for (final Entry<String, ModuleInfo> entry : modules.entrySet()) {
final String key = entry.getKey();
final ModuleInfo info = entry.getValue();
final MenuEntry leaf = info.getMenuPath().getLeaf();
if (leaf == null) continue;
final MenuPath path = info.getMenuPath();
final String name = leaf.getName();
final Item item = new Item();
item.weight = leaf.getWeight();
item.path = path;
item.name = name;
item.identifier = key;
item.info = info;
items.add(item);
}
// sort by menu weight, then alphabetically
Collections.sort(items);
for (final Item item : items) {
if (ij1Commands.containsKey(item.name)) {
log.info("Overriding " + item.name +
"; identifier: " + item.identifier +
"; jar: " + ClassUtils.getLocation(item.info.getDelegateClassName()));
if (wrapper != null) try {
wrapper.create(item.path, true);
}
catch (final Throwable t) {
log.error(t);
}
}
else if (wrapper != null) try {
wrapper.create(item.path, false);
}
catch (final Throwable t) {
log.error(t);
}
ij1Commands.put(item.name, item.identifier);
}
menuInitialized = true;
}
/**
* Helper class for wrapping ImageJ2 menu paths to ImageJ1 {@link Menu}
* structures, and inserting them into the proper positions of the
* {@link MenuBar}.
*/
private static class IJ1MenuWrapper {
final ImageJ ij1;
final MenuBar menuBar = Menus.getMenuBar();
final MenuCache menuCache = new MenuCache();
final Set<Menu> separators = new HashSet<>();
private IJ1MenuWrapper(final ImageJ ij1) {
this.ij1 = ij1;
}
/**
* Creates a {@link MenuItem} matching the structure of the provided path.
* Expected path structure is:
* <ul>
* <li>Level1 > Level2 > ... > Leaf entry</li>
* </ul>
* <p>
* For example, a valid path would be:
* </p>
* <ul>
* <li>Edit > Options > ImageJ2 plugins > Discombobulator</li>
* </ul>
*/
private MenuItem create(final MenuPath path, final boolean reuseExisting) {
// Find the menu structure where we can insert our command.
// NB: size - 1 is the leaf position, so we want to go to size - 2 to
// find the parent menu location
final Menu menu = getParentMenu(path, path.size() - 2);
final String label = path.getLeaf().getName();
// If we are overriding an item, find the item being overridden
if (reuseExisting) {
for (int i = 0; i < menu.getItemCount(); i++) {
final MenuItem item = menu.getItem(i);
if (label.equals(item.getLabel())) {
return item;
}
}
}
if (!separators.contains(menu)) {
if (menu.getItemCount() > 0) menu.addSeparator();
separators.add(menu);
}
// Otherwise, we are creating a new item
final MenuItem item = new MenuItem(label);
menu.insert(item, getIndex(menu, label));
item.addActionListener(ij1);
return item;
}
/**
* Helper method to look up special cases for menu weighting
*/
private int getIndex(final Menu menu, final String label) {
// Place export sub-menu after import sub-menu
if (menu.getLabel().equals("File") && label.equals("Export")) {
for (int i = 0; i < menu.getItemCount(); i++) {
final MenuItem menuItem = menu.getItem(i);
if (menuItem.getLabel().equals("Import")) return i + 1;
}
}
// TODO pass and use actual command weight from IJ2.. maybe?
// No special case: append to end of menu
return menu.getItemCount();
}
/** Recursive helper method to build the final {@link Menu} structure. */
private Menu getParentMenu(final MenuPath menuPath, final int depth) {
final MenuEntry currentItem = menuPath.get(depth);
final String currentLabel = currentItem.getName();
// Check to see if we already know the menu associated with the desired
// label/path
final Menu cached = menuCache.get(menuPath, depth);
if (cached != null) return cached;
// We are at the root of the menu, so see if we have a matching menu
if (depth == 0) {
// Special case check the help menu
if ("Help".equals(currentLabel)) {
final Menu menu = menuBar.getHelpMenu();
menuCache.put(menuPath, depth, menu);
return menu;
}
// Check the other menus of the menu bar to see if our desired label
// already exists
for (int i = 0; i < menuBar.getMenuCount(); i++) {
final Menu menu = menuBar.getMenu(i);
if (currentLabel.equals(menu.getLabel())) {
menuCache.put(menuPath, depth, menu);
return menu;
}
}
// Didn't find a match so we have to create a new menu entry
final Menu menu = new Menu(currentLabel);
menuBar.add(menu);
menuCache.put(menuPath, depth, menu);
return menu;
}
final Menu parent = getParentMenu(menuPath, depth - 1);
// Once the parent of this entry is obtained, we need to check if it
// already contains the current entry.
for (int i = 0; i < parent.getItemCount(); i++) {
final MenuItem item = parent.getItem(i);
if (currentLabel.equals(item.getLabel())) {
if (item instanceof Menu) {
// Found a menu entry that matches our desired label, so return
final Menu menu = (Menu) item;
menuCache.put(menuPath, depth, menu);
return menu;
}
// Found a match but it was an existing non-menu item, so our menu
// structure is invalid.
// TODO consider mangling the IJ2 menu name instead...
throw new IllegalArgumentException("Not a menu: " + currentLabel);
}
}
if (!separators.contains(parent)) {
if (parent.getItemCount() > 0) parent.addSeparator();
separators.add(parent);
}
// An existing entry in the parent menu was not found, so we need to
// create a new entry.
final Menu menu = new Menu(currentLabel);
parent.insert(menu, getIndex(parent, menu.getLabel()));
menuCache.put(menuPath, depth, menu);
return menu;
}
}
private static class MenuCache {
private final Map<String, Menu> map = new HashMap<>();
public void put(final MenuPath menuPath, final int depth, final Menu menu) {
map.put(key(menuPath, depth), menu);
}
public Menu get(final MenuPath menuPath, final int depth) {
return map.get(key(menuPath, depth));
}
private String key(final MenuPath menuPath, final int depth) {
final StringBuilder sb = new StringBuilder();
for (int i = 0; i <= depth; i++) {
sb.append(menuPath.get(i).getName());
sb.append("\n"); // NB: an unambiguous separator
}
return sb.toString();
}
}
private <T> T runMacroFriendly(final Callable<T> call) {
if (EventQueue.isDispatchThread()) {
throw new IllegalStateException("Cannot run macro from the EDT!");
}
final Thread thread = Thread.currentThread();
final String name = thread.getName();
try {
// to make getOptions() work
if (!name.startsWith("Run$_")) thread.setName("Run$_" + name);
// to make Macro.abort() work
if (!name.endsWith("Macro$")) thread.setName(thread.getName() + "Macro$");
return call.call();
}
catch (final RuntimeException e) {
throw e;
}
catch (final Exception e) {
throw new RuntimeException(e);
}
finally {
thread.setName(name);
// HACK: Try to null out the ij.macro.Interpreter, just in case.
try {
final Method m = Interpreter.class.getDeclaredMethod("setInstance",
Interpreter.class);
m.setAccessible(true);
m.invoke(null, new Object[] { null });
}
catch (final NoSuchMethodException | IllegalAccessException
| InvocationTargetException exc)
{
log.error(exc);
}
}
}
/**
* Evaluates the specified command.
*
* @param command the command to execute
*/
public void run(final String command) {
runMacroFriendly(new Callable<Void>() {
@Override
public Void call() throws Exception {
IJ.run(command);
return null;
}
});
}
/**
* Evaluates the specified macro.
*
* @param macro the macro to evaluate
* @return the return value
*/
public String runMacro(final String macro) {
return runMacroFriendly(new Callable<String>() {
@Override
public String call() throws Exception {
return IJ.runMacro(macro);
}
});
}
/**
* Evaluates the specified macro.
*
* @param path the macro file to evaluate
* @param arg the macro argument
* @return the return value
*/
public String runMacroFile(final String path, final String arg) {
return runMacroFriendly(new Callable<String>() {
@Override
public String call() throws Exception {
return IJ.runMacroFile(path, arg);
}
});
}
/**
* Opens an image using ImageJ 1.x.
*
* @param path the image file to open
* @return the image
*/
public Object openImage(final String path) {
return openImage(path, false);
}
/**
* Opens an image using ImageJ 1.x.
*
* @param path the image file to open
* @return the image
*/
public Object openImage(final String path, final boolean show) {
final ImagePlus imp = IJ.openImage(path);
if (show && imp != null) imp.show();
return imp;
}
/**
* Opens a path using ImageJ 1.x, bypassing the (javassisted) IJ utility
* class.
*
* @param path the image file to open
*/
public void openPathDirectly(final String path) {
new Opener().open(path);
}
/**
* Enables or disables ImageJ 1.x' debug mode.
*
* @param debug whether to show debug messages or not
*/
public void setDebugMode(final boolean debug) {
IJ.debugMode = debug;
}
/**
* Delegate exception handling to ImageJ 1.x.
*
* @param e the exception to handle
*/
public void handleException(final Throwable e) {
IJ.handleException(e);
}
/**
* Ask ImageJ 1.x whether it thinks whether the Shift key is held down.
*
* @return whether the Shift key is considered <i>down</i>
*/
public boolean shiftKeyDown() {
return IJ.shiftKeyDown();
}
/**
* Delegates to ImageJ 1.x' {@link Macro#getOptions()} function.
*
* @return the macro options, or null
*/
public String getOptions() {
final String options = Macro.getOptions();
return options == null ? "" : options;
}
/**
* Delegates to ImageJ 1.x' {@link Macro#setOptions(String)} function.
*
* @param options the macro options, or null to reset
*/
public void setOptions(final String options) {
Macro.setOptions(options);
}
/** Handles shutdown of ImageJ 1.x. */
public void appQuit() {
if (legacyService.isLegacyMode()) {
new Executer("Quit", null); // works with the CommandListener
}
}
/** Displays the About ImageJ 1.x dialog. */
public void appAbout() {
if (legacyService.isLegacyMode()) {
IJ.run("About ImageJ...");
}
}
/** Sets OpenDialog's default directory */
public void setDefaultDirectory(final File directory) {
OpenDialog.setDefaultDirectory(directory.getPath());
}
/** Uses ImageJ 1.x' OpenDialog */
public File openDialog(final String title) {
return openDialog(title, null);
}
/** Uses ImageJ 1.x' OpenDialog */
public File openDialog(final String title, final File file) {
final String defaultDir = file == null ? null : file.getParent();
final String defaultName = file == null ? null : file.getName();
final OpenDialog openDialog =
new OpenDialog(title, defaultDir, defaultName);
final String directory = openDialog.getDirectory();
// NB: As a side effect, ImageJ1 normally appends the selected
// file as a macro parameter when the getFileName() is called!
// We need to suppress that problematic behavior here; see:
final boolean recording = Recorder.record;
Recorder.record = false;
final String fileName = openDialog.getFileName();
Recorder.record = recording;
if (directory != null && fileName != null) {
return new File(directory, fileName);
}
return null;
}
/** Uses ImageJ 1.x' SaveDialog */
public File saveDialog(final String title, final File file,
final String extension)
{
// Use ImageJ1's SaveDialog.
final String defaultName, defaultExtension;
if (file == null) {
defaultName = null;
defaultExtension = extension;
}
else {
final int dotIndex = file.getName().indexOf('.');
if (dotIndex > 0) {
// split filename from extension
defaultName = file.getName().substring(0, dotIndex);
defaultExtension = extension == null ?
file.getName().substring(dotIndex) : extension;
}
else {
// file had no extension
defaultName = file.getName();
defaultExtension = extension;
}
}
final SaveDialog saveDialog =
new SaveDialog(title, defaultName, defaultExtension);
final String directory = saveDialog.getDirectory();
// NB: As a side effect, ImageJ1 normally appends the selected
// file as a macro parameter when the getFileName() is called!
// We need to suppress that problematic behavior here; see:
final boolean recording = Recorder.record;
Recorder.record = false;
final String fileName = saveDialog.getFileName();
Recorder.record = recording;
if (directory != null && fileName != null) {
return new File(directory, fileName);
}
return null;
}
/** Chooses a directory using ImageJ 1.x' directory chooser. */
public String getDirectory(final String title, final File file) {
if (file != null) {
final String defaultDir =
file.isDirectory() ? file.getPath() : file.getParent();
if (defaultDir != null) DirectoryChooser.setDefaultDirectory(defaultDir);
}
// NB: As a side effect, ImageJ1 normally appends the selected
// directory as a macro parameter when getDirectory() is called!
// We need to suppress that problematic behavior here; see:
final boolean recording = Recorder.record;
Recorder.record = false;
final String directory = new DirectoryChooser(title).getDirectory();
Recorder.record = recording;
return directory;
}
/** Handles display of the ImageJ 1.x preferences. */
public void appPrefs() {
if (legacyService.isLegacyMode()) {
IJ.error("The ImageJ preferences are in the Edit>Options menu.");
}
}
// -- Helper methods --
/** Closes all image windows on the event dispatch thread. */
private void closeImageWindows() {
// TODO: Consider using ThreadService#invoke to simplify this logic.
final Runnable run = new Runnable() {
@Override
public void run() {
// close out all image windows, without dialog prompts
while (true) {
final ImagePlus imp = WindowManager.getCurrentImage();
if (imp == null) break;
imp.changes = false;
imp.close();
}
}
};
if (EventQueue.isDispatchThread()) {
run.run();
}
else {
try {
EventQueue.invokeAndWait(run);
}
catch (final Exception e) {
// report & ignore
log.error(e);
}
}
}
private void disposeNonImageWindows() {
disposeNonImageFrames();
disposeOtherNonImageWindows();
}
/**
* Disposes all the non-image window frames, as given by
* {@link WindowManager#getNonImageWindows()}.
*/
private void disposeNonImageFrames() {
for (final Frame frame : WindowManager.getNonImageWindows()) {
frame.dispose();
}
}
/**
* Ensures <em>all</em> the non-image windows are closed.
* <p>
* This is a non-trivial problem, as
* {@link WindowManager#getNonImageWindows()} <em>only</em> returns
* {@link Frame}s. However there are non-image, non-{@link Frame} windows that
* are critical to close: for example, the
* {@link ij.plugin.frame.ContrastAdjuster} spawns a polling thread to do its
* work, which will continue to run until the {@code ContrastAdjuster} is
* explicitly closed.
* </p>
*/
private void disposeOtherNonImageWindows() {
// NB: As of v1.49b, getNonImageTitles is not restricted to Frames,
// so we can use it to iterate through the available windows.
for (final String title : WindowManager.getNonImageTitles()) {
final Window window = WindowManager.getWindow(title);
// NB: We can NOT set these windows as active and run the Commands
// plugin with argument "close", because the default behavior is to
// try closing the window as an Image. As we know these are not Images,
// that is never the right thing to do.
WindowManager.removeWindow(window);
window.dispose();
}
}
/** Escapes the given string according to the Java language specification. */
private String escape(final String s) {
// NB: It would be nice to use the StringEscapeUtils.escapeJava method of
// Apache Commons Lang, but we eschew it for now to avoid the dependency.
// escape quotes and backslashes
String escaped = s.replaceAll("([\"\\\\])", "\\\\$1");
// escape special characters
escaped = escaped.replaceAll("\b", "\\\\b");
escaped = escaped.replaceAll("\n", "\\\\n");
escaped = escaped.replaceAll("\t", "\\\\t");
escaped = escaped.replaceAll("\f", "\\\\f");
escaped = escaped.replaceAll("\r", "\\\\r");
return escaped;
}
}
|
package org.basex.core.cmd;
import static org.basex.core.Commands.*;
import static org.basex.core.Text.*;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.xml.transform.sax.SAXSource;
import org.basex.build.BuildException;
import org.basex.build.Builder;
import org.basex.build.DiskBuilder;
import org.basex.build.MemBuilder;
import org.basex.build.Parser;
import org.basex.build.xml.DirParser;
import org.basex.build.xml.SAXWrapper;
import org.basex.core.BaseXException;
import org.basex.core.CommandBuilder;
import org.basex.core.Context;
import org.basex.core.Prop;
import org.basex.core.User;
import org.basex.core.Commands.Cmd;
import org.basex.core.Commands.CmdPerm;
import org.basex.data.Data;
import org.basex.index.IndexToken.IndexType;
import org.basex.index.FTBuilder;
import org.basex.index.ValueBuilder;
import org.basex.io.BufferInput;
import org.basex.io.IO;
import org.basex.io.IOContent;
import org.basex.util.Performance;
import org.basex.util.Util;
import org.xml.sax.InputSource;
public final class CreateDB extends ACreate {
/** Optionally defined parser. */
private final Parser parser;
/**
* Default constructor.
* @param name name of database
*/
public CreateDB(final String name) {
this(name, null);
}
/**
* Constructor, specifying an input.
* @param name name of database
* @param input input file path or XML string
*/
public CreateDB(final String name, final String input) {
this(name, input, null);
}
/**
* Constructor, specifying an input.
* @param name name of database
* @param input input file path or XML string
* @param p parser reference
*/
public CreateDB(final String name, final String input, final Parser p) {
super(name, input);
parser = p;
}
@Override
protected boolean run() {
final String name = args[0];
final String input = args[1];
if(input == null) return build(Parser.emptyParser(), name);
final IO io = IO.get(input);
if(io instanceof IOContent) io.name(name + IO.XMLSUFFIX);
final Parser p = parser != null ? parser : new DirParser(io, prop);
return io.exists() ? build(p, name) : error(FILEWHICH, io);
}
/**
* Creates an empty database.
* @param name name of the database
* @param ctx database context
* @return database instance
* @throws IOException I/O exception
*/
public static Data empty(final String name, final Context ctx)
throws IOException {
return xml(Parser.emptyParser(), name, ctx);
}
/**
* Creates a database for the specified file.
* @param io input reference
* @param name name of the database
* @param ctx database context
* @return database instance
* @throws IOException I/O exception
*/
public static synchronized Data xml(final IO io, final String name,
final Context ctx) throws IOException {
if(!ctx.user.perm(User.CREATE))
throw new IOException(Util.info(PERMNO, CmdPerm.CREATE));
if(!io.exists()) throw new BuildException(FILEWHICH, io);
return xml(new DirParser(io, ctx.prop), name, ctx);
}
/**
* Creates a database for the specified file.
* @param name name of the database
* @param input input stream
* @param ctx database context
* @return info string
* @throws BaseXException database exception
*/
public static synchronized String xml(final String name,
final InputStream input, final Context ctx) throws BaseXException {
final InputStream is = input instanceof BufferedInputStream ||
input instanceof BufferInput ? input : new BufferedInputStream(input);
final SAXSource sax = new SAXSource(new InputSource(is));
return xml(name, new SAXWrapper(sax, ctx.prop), ctx);
}
/**
* Creates a database for the specified file.
* @param name name of the database
* @param parser parser
* @param ctx database context
* @return info string
* @throws BaseXException database exception
*/
public static synchronized String xml(final String name,
final Parser parser, final Context ctx) throws BaseXException {
if(!ctx.user.perm(User.CREATE))
throw new BaseXException(PERMNO, CmdPerm.CREATE);
final Performance p = new Performance();
ctx.register(true);
try {
// close open database
new Close().run(ctx);
ctx.openDB(xml(parser, name, ctx));
} catch(final IOException ex) {
throw new BaseXException(ex);
} finally {
ctx.unregister(true);
}
return Util.info(DBCREATED, name, p);
}
/**
* Creates a database instance from the specified parser.
* @param parser input parser
* @param name name of the database
* @param ctx database context
* @return database instance
* @throws IOException I/O exception
*/
public static synchronized Data xml(final Parser parser, final String name,
final Context ctx) throws IOException {
// create main memory database instance
final Prop prop = ctx.prop;
if(prop.is(Prop.MAINMEM)) return MemBuilder.build(parser, prop, name);
// database is currently locked by another process
if(ctx.pinned(name)) throw new IOException(Util.info(DBLOCKED, name));
// build database and index structures
final Builder builder = new DiskBuilder(parser, prop);
try {
final Data data = builder.build(name);
if(prop.is(Prop.TEXTINDEX)) data.setIndex(IndexType.TEXT,
new ValueBuilder(data, true).build());
if(prop.is(Prop.ATTRINDEX)) data.setIndex(IndexType.ATTRIBUTE,
new ValueBuilder(data, false).build());
if(prop.is(Prop.FTINDEX)) data.setIndex(IndexType.FULLTEXT,
FTBuilder.get(data).build());
data.close();
} finally {
try { builder.close(); } catch(final IOException exx) { Util.debug(exx); }
}
return Open.open(name, ctx);
}
/**
* Creates a main memory database for the specified parser.
* @param parser input parser
* @param ctx database context
* @return database instance
* @throws IOException I/O exception
*/
public static synchronized Data xml(final Parser parser, final Context ctx)
throws IOException {
if(!ctx.user.perm(User.CREATE))
throw new IOException(Util.info(PERMNO, CmdPerm.CREATE));
return MemBuilder.build(parser, ctx.prop);
}
/**
* Creates a main memory database from the specified input reference.
* @param io input reference
* @param ctx database context
* @return database instance
* @throws IOException I/O exception
*/
public static synchronized Data xml(final IO io, final Context ctx)
throws IOException {
if(!io.exists()) throw new BuildException(FILEWHICH, io.path());
return xml(new DirParser(io, ctx.prop), ctx);
}
/**
* Creates a main memory database from the specified SAX source.
* @param sax sax source
* @param ctx database context
* @return database instance
* @throws IOException I/O exception
*/
public static synchronized Data xml(final SAXSource sax, final Context ctx)
throws IOException {
return xml(new SAXWrapper(sax, ctx.prop) , ctx);
}
@Override
public void build(final CommandBuilder cb) {
cb.init(Cmd.CREATE + " " + CmdCreate.DB).args();
}
}
|
package org.cactoos.iterator;
import java.util.Collections;
import java.util.Iterator;
import org.cactoos.iterable.ListOf;
/**
* A few Iterators joined together.
*
* <p>There is no thread-safety guarantee.
*
* @author Yegor Bugayenko (yegor256@gmail.com)
* @version $Id$
* @param <T> Type of item
* @since 0.1
*/
public final class Joined<T> implements Iterator<T> {
/**
* Iterators.
*/
private final Iterator<Iterator<T>> iters;
/**
* Current traversal iterator
*/
private Iterator<T> current = Collections.emptyIterator();
/**
* Ctor.
* @param items Items to concatenate
*/
@SafeVarargs
public Joined(final Iterator<T>... items) {
this(new ListOf<>(items));
}
/**
* Ctor.
* @param items Items to concatenate
*/
public Joined(final Iterable<Iterator<T>> items) {
this.iters = items.iterator();
}
@Override
public boolean hasNext() {
while (!current.hasNext() && iters.hasNext()) {
current = iters.next();
}
return current.hasNext();
}
@Override
public T next() {
return current.next();
}
}
|
package org.fiteagle.api.core;
public interface IGeni {
String GENI_PROVISIONED = "geni_provisioned";
String GENI_OPERATIONAL_STATUS = "geni_operational_status";
String GENI_READY = "geni_ready";
String GENI_BEST_EFFORT = "geni_best_effort";
String GENI_END_TIME = "geni_end_time";
String GENI_API_VERSION = "geni_api_versions";
String GENI_API = "geni_api";
String GENI_TYPE = "geni_type";
String GENI_SFA = "geni_sfa";
String GENI_NAMESPACE = "namespace";
String GENI_EXTENSIONS = "extensions";
String GENI_REQUEST_VERSION = "geni_request_rspec_versions";
String GENI_REQUEST_RSPEC_SCHEMA ="http:
String GENI_AD_VERSION = "geni_ad_rspec_versions";
String GENI_AD_RSPEC_SCHEMA ="http:
String GENI_VERSION = "geni_version";
String GENI_CREDENTIAL_TYPES = "geni_credential_types";
String GENI_CODE = "geni_code";
String GENI_SLIVER_URN = "geni_sliver_urn";
String GENI_EXPIRES = "geni_expires";
String GENI_ALLOCATION_STATUS = "geni_allocation_status";
String GENI_ALLOCATED = "geni_allocated";
String GENI_RSPEC = "geni_rspec";
String GENI_SLIVERS = "geni_slivers";
String GENI_URN="geni_urn";
String GENI_ERROR = "geni_error";
String GENI_QUERY = "GENI_QUERY";
String GENI_COMPRESSED = "geni_compressed";
String GENI_AVAILABLE = "geni_available";
String GENI_VALUE = "geni_value";
String GENI_RSPEC_VERSION = "geni_rspec_version";
String GENI_NOT_ALLOCATED = "geni_not_allocated";
String GENI_UNALLOCATED = "geni_unallocated";
}
|
package org.jtrfp.trcl;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import org.apache.commons.math3.geometry.euclidean.threed.Vector3D;
import org.jtrfp.trcl.core.TR;
import org.jtrfp.trcl.core.TriangleVertex2FlatDoubleWindow;
import org.jtrfp.trcl.core.TriangleVertexWindow;
import org.jtrfp.trcl.core.WindowAnimator;
import org.jtrfp.trcl.ext.tr.GPUResourceFinalizer;
import org.jtrfp.trcl.gpu.Model;
import org.jtrfp.trcl.gpu.PortalTexture;
import org.jtrfp.trcl.gpu.Texture;
import org.jtrfp.trcl.gpu.TextureDescription;
import org.jtrfp.trcl.mem.MemoryWindow;
public class TriangleList extends PrimitiveList<Triangle> {
private Controller controller;
private int timeBetweenFramesMsec;
private int [] triangleVertexIndices;
private final boolean animateUV;
private final WindowAnimator xyzAnimator;
private TriangleVertex2FlatDoubleWindow flatTVWindow;
private volatile Vector3D cachedMinimumVertexDims,
cachedMaximumVertexDims;
private volatile Double cachedMaximumVertexValue;
public TriangleList(Triangle[][] triangles, int timeBetweenFramesMsec,
String debugName, boolean animateUV, Controller controller, TR tr, Model m) {
super(debugName, triangles, new TriangleVertexWindow(tr.gpu.get(),debugName), tr,m);
this.timeBetweenFramesMsec = timeBetweenFramesMsec;
this.animateUV = animateUV;
this.controller = controller;
if (getPrimitives().length > 1) {
this.xyzAnimator = new WindowAnimator(
getFlatTVWindow(),
this.getNumElements() * 3 * XYZXferFunc.FRONT_STRIDE_LEN,
// 3 vertices per triangle,
// XYZ+NxNyNz per vertex
getPrimitives().length, true, controller,
new XYZXferFunc(0));
getModel().addTickableAnimator(xyzAnimator);
} else if (animateUV) {
this.xyzAnimator = null;
} else {
this.xyzAnimator = null;
}
}//end constructor
private static class XYZXferFunc implements IntTransferFunction {
private final int startIndex;
public static final int BACK_STRIDE_LEN = 8;
public static final int FRONT_STRIDE_LEN = 6;
private static final byte [] STRIDE_PATTERN = new byte[]{
0,1,2,//XYZ
5,6,7//NxNyNz
};
public XYZXferFunc(int startIndex) {
this.startIndex = startIndex;
}// end constructor
@Override
public int transfer(int input) {
return startIndex + STRIDE_PATTERN[input%FRONT_STRIDE_LEN]+(input/FRONT_STRIDE_LEN)*BACK_STRIDE_LEN;
}// end transfer(...)
}// end class XYZXferFunc
private static class UVXferFunc implements IntTransferFunction {
private final int startIndex;
public static final int BACK_STRIDE_LEN=8;
private final int FRONT_STRIDE_LEN=2;
public UVXferFunc(int startIndex) {
this.startIndex = startIndex;
}// end constructor
@Override
public int transfer(int input) {
return (input / FRONT_STRIDE_LEN) * BACK_STRIDE_LEN + (input % FRONT_STRIDE_LEN) + startIndex + 3;
}// end transfer(...)
}// end class XYZXferFunc
private Controller getVertexSequencer(int timeBetweenFramesMsec, int nFrames) {
return controller;
}
private Triangle triangleAt(int frame, int tIndex) {
return getPrimitives()[frame][tIndex];
}
private void setupVertex(int vIndex, int gpuTVIndex, int triangleIndex, TextureDescription td)
throws ExecutionException, InterruptedException {
final int numFrames = getPrimitives().length;
final Triangle t = triangleAt(0, triangleIndex);
final Vector3D pos = t.getVertices()[vIndex].getPosition();
final TriangleVertexWindow vw = (TriangleVertexWindow) getMemoryWindow();
////////////////////// V E R T E X //////////////////////////////
if (numFrames == 1) {
vw.x.set(gpuTVIndex, (short) applyScale(pos.getX()));
vw.y.set(gpuTVIndex, (short) applyScale(pos.getY()));
vw.z.set(gpuTVIndex, (short) applyScale(pos.getZ()));
final Vector3D normal = t.getVertices()[vIndex].getNormal();
vw.normX.set(gpuTVIndex, (byte)(normal.getX()*127));
vw.normY.set(gpuTVIndex, (byte)(normal.getY()*127));
vw.normZ.set(gpuTVIndex, (byte)(normal.getZ()*127));
} else {
float[] xFrames = new float[numFrames];
float[] yFrames = new float[numFrames];
float[] zFrames = new float[numFrames];
float[] nxFrames = new float[numFrames];
float[] nyFrames = new float[numFrames];
float[] nzFrames = new float[numFrames];
for (int i = 0; i < numFrames; i++)
xFrames[i] = (float)applyScale(triangleAt(i, triangleIndex).getVertices()[vIndex].getPosition().getX());
xyzAnimator.addFrames(xFrames);
for (int i = 0; i < numFrames; i++)
yFrames[i] = (float)applyScale(triangleAt(i, triangleIndex).getVertices()[vIndex].getPosition().getY());
xyzAnimator.addFrames(yFrames);
for (int i = 0; i < numFrames; i++)
zFrames[i] = (float)applyScale(triangleAt(i, triangleIndex).getVertices()[vIndex].getPosition().getZ());
xyzAnimator.addFrames(zFrames);
for (int i = 0; i < numFrames; i++)
nxFrames[i] = (float)Math.rint(triangleAt(i, triangleIndex).getVertices()[vIndex].getNormal().getX()*127);
xyzAnimator.addFrames(nxFrames);
for (int i = 0; i < numFrames; i++)
nyFrames[i] = (float)Math.rint(triangleAt(i, triangleIndex).getVertices()[vIndex].getNormal().getY()*127);
xyzAnimator.addFrames(nyFrames);
for (int i = 0; i < numFrames; i++)
nzFrames[i] = (float)Math.rint(triangleAt(i, triangleIndex).getVertices()[vIndex].getNormal().getZ()*127);
xyzAnimator.addFrames(nzFrames);
}//end else(frames!=1)
//////////////// T E X T U R E ///////////////////////////
if(td==null){
System.err.println("Stack trace of triangle creation below. NullPointerException follows.");
final StackTraceElement [] elements = t.getCreationStackTrace();
if(elements == null)
throw new NullPointerException("Stack trace elements null! Did you remember to turn on Triangle.debugTriangles?");
for(StackTraceElement el:elements){
System.err.println("\tat "+el.getClassName()+"."+el.getMethodName()+"("+el.getFileName()+":"+el.getLineNumber()+")");
}//end for(stackTrace)
throw new NullPointerException("Texture for triangle in "+debugName+" intolerably null.");}
else if (td instanceof PortalTexture){
PortalTexture portalTexture = (PortalTexture)td;
portalTexture.addRelevantVertexIndex(gpuTVIndex);
portalTexture.setTriangleVertexWindow(vw);
//final int textureID = 65536-((PortalTexture)td).getPortalFramebufferNumber();
//vw.textureIDLo .set(gpuTVIndex, (byte)(textureID & 0xFF));
//vw.textureIDMid.set(gpuTVIndex, (byte)((textureID >> 8) & 0xFF));
//vw.textureIDHi .set(gpuTVIndex, (byte)((textureID >> 16) & 0xFF));
} if (td instanceof Texture ) {// Static texture
final int sideScalar = ((Texture)td).getSideLength()-1;
if (animateUV && numFrames > 1) {// Animated UV
float[] uFrames = new float[numFrames];
float[] vFrames = new float[numFrames];
final WindowAnimator uvAnimator = new WindowAnimator(
getFlatTVWindow(), 2,// UV per vertex
numFrames, false, getVertexSequencer(
timeBetweenFramesMsec, numFrames),
new UVXferFunc(gpuTVIndex * UVXferFunc.BACK_STRIDE_LEN));
getModel().addTickableAnimator(uvAnimator);
uvAnimator.setDebugName(debugName + ".uvAnimator");
for (int i = 0; i < numFrames; i++) {
uFrames[i] = (float) Math.rint(sideScalar*triangleAt(i, triangleIndex).getUV(vIndex).getX());
vFrames[i] = (float) Math.rint(sideScalar*(1-triangleAt(i, triangleIndex).getUV(vIndex).getY()));
}// end for(numFrames)
uvAnimator.addFrames(uFrames);
uvAnimator.addFrames(vFrames);
} else {// end if(animateUV)
vw.u.set(gpuTVIndex, (short) Math.rint(sideScalar * t.getUV(vIndex).getX()));
vw.v.set(gpuTVIndex, (short) Math.rint(sideScalar * (1-t.getUV(vIndex).getY())));
}// end if(!animateUV)
final int textureID = ((Texture)td).getTexturePage();
vw.textureIDLo .set(gpuTVIndex, (byte)(textureID & 0xFF));
vw.textureIDMid.set(gpuTVIndex, (byte)((textureID >> 8) & 0xFF));
vw.textureIDHi .set(gpuTVIndex, (byte)((textureID >> 16) & 0xFF));
}// end if(Texture)
if(td instanceof AnimatedTexture){//Animated texture
final AnimatedTexture at = (AnimatedTexture)td;
if (animateUV && numFrames > 1) {// Animated UV
float[] uFrames = new float[numFrames];
float[] vFrames = new float[numFrames];
final WindowAnimator uvAnimator = new WindowAnimator(
getFlatTVWindow(), 2,// UV per vertex
numFrames, false, getVertexSequencer(
timeBetweenFramesMsec, numFrames),
new UVXferFunc(gpuTVIndex * UVXferFunc.BACK_STRIDE_LEN));
getModel().addTickableAnimator(uvAnimator);
for (int i = 0; i < numFrames; i++) {
final int sideScalar = at.getFrames()[i].getSideLength()-1;
uFrames[i] = (float) Math.rint(sideScalar * triangleAt(i, triangleIndex).getUV(vIndex).getX());
vFrames[i] = (float) Math.rint(sideScalar * (1-triangleAt(i, triangleIndex).getUV(vIndex).getY()));
}// end for(numFrames)
uvAnimator.addFrames(uFrames);
uvAnimator.addFrames(vFrames);
} else {// end if(animateUV)
final int sideScalar = at.getFrames()[0].getSideLength()-1;
vw.u.set(gpuTVIndex, (short) Math.rint(sideScalar * t.getUV(vIndex).getX()));
vw.v.set(gpuTVIndex, (short) Math.rint(sideScalar * (1-t.getUV(vIndex).getY())));
}// end if(!animateUV)
final TexturePageAnimator texturePageAnimator = new TexturePageAnimator(at,vw,gpuTVIndex);
texturePageAnimator.setDebugName(debugName + ".texturePageAnimator");
getModel().addTickableAnimator(texturePageAnimator);
}//end if(animated texture)
}// end setupVertex
private void setupTriangle(final int triangleIndex, final TextureDescription textureDescription,final int [] vertexIndices) throws ExecutionException,
InterruptedException {
int tIndex = triangleIndex*3;
setupVertex(0, vertexIndices[tIndex], triangleIndex,textureDescription);
setupVertex(1, vertexIndices[tIndex+1], triangleIndex,textureDescription);
setupVertex(2, vertexIndices[tIndex+2], triangleIndex,textureDescription);
}//setupTriangle
/*
@Override
public void finalize(){
final MemoryWindow mw = getMemoryWindow();
for(int i=0; i<triangleVertexIndices.length;i++){
mw.free(triangleVertexIndices[i]);
}//end for(triangleVertexIndices)
}//end finalize()
*/
public Future<Void> uploadToGPU() {
final int nPrimitives = getNumElements();
triangleVertexIndices = new int[nPrimitives*3];
final TextureDescription [] textureDescriptions = new TextureDescription[nPrimitives];
final MemoryWindow mw = getMemoryWindow();
for (int vIndex = 0; vIndex < nPrimitives*3; vIndex++)
triangleVertexIndices[vIndex]=mw.create();
for (int tIndex = 0; tIndex < nPrimitives; tIndex++)
textureDescriptions[tIndex] = triangleAt(0, tIndex).texture;
//calculateDims();
final Future<Void> result = tr.getThreadManager().submitToGPUMemAccess(new Callable<Void>() {
@Override
public Void call() throws Exception {
for (int tIndex = 0; tIndex < nPrimitives; tIndex++) {
setupTriangle(tIndex,textureDescriptions[tIndex],triangleVertexIndices);}
finalizePrimitives();
return null;
}//end Call()
});
return result;
}// end uploadToGPU(...)
@Override
public int getElementSizeInVec4s() {
return 3;
}
@Override
public int getGPUVerticesPerElement() {
return 3;
}
@Override
public org.jtrfp.trcl.PrimitiveList.RenderStyle getRenderStyle() {
return RenderStyle.OPAQUE;
}
public Vector3D getMaximumVertexDims() {
if(cachedMaximumVertexDims!=null)
return cachedMaximumVertexDims;
throw new IllegalStateException("Primitives must first be finalized.");
}// end getMaximumVertexDims()
public Vector3D getMinimumVertexDims() {
if(cachedMinimumVertexDims!=null)
return cachedMinimumVertexDims;
throw new IllegalStateException("Primitives must first be finalized.");
}// end getMaximumVertexDims()
public double getMaximumVertexValue() {
if(cachedMaximumVertexValue!=null)
return cachedMaximumVertexValue;
throw new IllegalStateException("Primitives must first be finalized.");
}// end getMaximumVertexValue()
@Override
protected void calculateDims(){
Triangle[][] t = getPrimitives();
{double result = 0;
for (Triangle[] frame : t) {
for (Triangle tri : frame) {
for (int i = 0; i < 3; i++) {
double v;
final Vector3D pos = tri.getVertices()[i].getPosition();
v = Math.abs(pos.getX());
result = result < v ? v : result;
v = Math.abs(pos.getY());
result = result < v ? v : result;
v = Math.abs(pos.getZ());
result = result < v ? v : result;
}// end for(vertex)
}// end for(triangle)
}// end for(triangles)
cachedMaximumVertexValue=result;
}
Vector3D result = new Vector3D(Double.POSITIVE_INFINITY,
Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY);
for (Triangle[] frame : t) {
for (Triangle tri : frame) {
for (int i = 0; i < 3; i++) {
double v;
final Vector3D pos = tri.getVertices()[i].getPosition();
v = pos.getX();
result = result.getX() > v ? new Vector3D(v, result.getY(),
result.getZ()) : result;
v = pos.getY();
result = result.getY() > v ? new Vector3D(result.getX(), v,
result.getZ()) : result;
v = pos.getZ();
result = result.getZ() > v ? new Vector3D(result.getX(),
result.getY(), v) : result;
}// end for(vertex)
}// end for(triangle)
}// end for(triangles)
cachedMinimumVertexDims=result;
result = Vector3D.ZERO;
for (int index=0; index<t.length; index++) {
final Triangle []frame = t[index];
assert (frame != null):"Frame intolerably null at index "+index+".";//Verify null frame is a race condition.
for (Triangle tri : frame) {
for (int i = 0; i < 3; i++) {
double v;
final Vector3D pos = tri.getVertices()[i].getPosition();
v = pos.getX();
result = result.getX() < v ? new Vector3D(v, result.getY(),
result.getZ()) : result;
v = pos.getY();
result = result.getY() < v ? new Vector3D(result.getX(), v,
result.getZ()) : result;
v = pos.getZ();
result = result.getZ() < v ? new Vector3D(result.getX(),
result.getY(), v) : result;
}// end for(vertex)
}// end for(triangle)
}// end for(triangles)
cachedMaximumVertexDims=result;
}//calculateMaxDims()
/**
* @return the flatTVWindow
*/
private TriangleVertex2FlatDoubleWindow getFlatTVWindow() {
if (flatTVWindow == null)
flatTVWindow = new TriangleVertex2FlatDoubleWindow(
(TriangleVertexWindow) this.getMemoryWindow());
return flatTVWindow;
}
@Override
public byte getPrimitiveRenderMode() {
return PrimitiveRenderMode.RENDER_MODE_TRIANGLES;
}
@Override
public int getNumMemoryWindowIndicesPerElement() {
return 3;
}
}// end SingleTextureTriangleList
|
package org.kohsuke.github;
class Previews {
static final String ANTIOPE = "application/vnd.github.antiope-preview+json";
static final String BAPTISE = "application/vnd.github.baptiste-preview+json";
static final String CLOAK = "application/vnd.github.cloak-preview+json";
static final String FLASH = "application/vnd.github.flash-preview+json";
static final String GAMBIT = "application/vnd.github.gambit-preview+json";
static final String GROOT = "application/vnd.github.groot-preview+json";
static final String INERTIA = "application/vnd.github.inertia-preview+json";
static final String LYDIAN = "application/vnd.github.lydian-preview+json";
static final String LUKE_CAGE = "application/vnd.github.luke-cage-preview+json";
static final String MACHINE_MAN = "application/vnd.github.machine-man-preview+json";
static final String MERCY = "application/vnd.github.mercy-preview+json";
static final String NEBULA = "application/vnd.github.nebula-preview+json";
static final String SHADOW_CAT = "application/vnd.github.shadow-cat-preview+json";
static final String SQUIRREL_GIRL = "application/vnd.github.squirrel-girl-preview+json";
static final String ZZZAX = "application/vnd.github.zzzax-preview+json";
}
|
package org.lightmare.config;
import java.util.Arrays;
import java.util.HashSet;
import org.lightmare.cache.DeploymentDirectory;
/**
* Keeps keys and default values for configuration
*
* @author Levan
*
*/
public enum Config {
// Default properties
// Path where stored administrative users
ADMIN_USERS_PATH("adminUsersPath", "./config/admin/users.properties"),
// Netty server / client configuration properties for RPC calls
IP_ADDRESS("listeningIp", "0.0.0.0"),
PORT("listeningPort", "1199"), // port
BOSS_POOL("bossPoolSize", 1), // boss pool
WORKER_POOL_KEY("workerPoolSize", 3), // Worker pool
CONNECTION_TIMEOUT("timeout", 1000), // Connection timeout
// Properties for data source path and deployment path
DEMPLOYMENT_PATH("deploymentPath", new HashSet<DeploymentDirectory>(
Arrays.asList(new DeploymentDirectory("./deploy", Boolean.TRUE)))),
DATA_SOURCE_PATH("dataSourcePath", new HashSet<String>(
Arrays.asList("./ds"))), // data
// source
// path
// Properties which version of server is running remote it requires server
// client RPC infrastructure or local (embedded mode)
SERVER("server", Boolean.TRUE),
REMOTE("remote", Boolean.FALSE),
CLIENT_KEY("client", Boolean.FALSE),
// Configuration keys properties for deployment
DEPLOY_CONFIG("deployConfiguration"), // Deploy CONFIG
ADMIN_USER_PATH("adminPath"), // ADMIN user path
HOT_DEPLOYMENT("hotDeployment"), // Hot deployment
WATCH_STATUS("watchStatus"), // Watch status
LIBRARY_PATH("libraryPaths"), // Library path
// Persistence provider property keys
PERSISTENCE_CONFIG("persistenceConfig"), // Persistence config
SCAN_FOR_ENTITIES("scanForEntities"), // Scan for entities
ANNOTATED_UNIT_NAME("annotatedUnitName"), // Annotated unit
PERSISTENCE_XML_PATH("persistanceXmlPath"), // Persistence XML
PERSISTENCE_XML_FROM_JAR("persistenceXmlFromJar"), // Persistence XML from
// jar
SWAP_DATASOURCE("swapDataSource"), // Swap data source
SCAN_ARCHIVES("scanArchives"), // Scan archives
POOLED_DATA_SOURCE("pooledDataSource", Boolean.TRUE), // Pooled data source
PERSISTENCE_PROPERTIES("persistenceProperties"), // Persistence properties
// Connection pool provider property keys
POOL_CONFIG("poolConfig"), // Pool Config
POOL_PROPERTIES_PATH("poolPropertiesPath"), // Pool properties path
POOL_PROVIDER_TYPE("poolProviderType"), // Pool provider type
POOL_PROPERTIES("poolProperties"); // Pool properties
public String key;
public Object value;
private Config(String key) {
this.key = key;
}
private Config(String key, Object value) {
this(key);
this.value = value;
}
}
|
package org.sbrubbles.genericcons;
/**
* Captures and represents an open-ended list of types. This class isn't supposed to be instantiated or subclassed,
* and has no fields or methods; it's a marker class, used to indicate a list in the type declaration, like below:
* <p>
* <pre>
* Function<?, ?> f = new Function<String, C<Object, C<Number, C<String, Integer>>>>() {
* { // the no-arg constructor
* this.types = Types.fromSuperclass(this.getClass(), 1);
* }
* };
* </pre>
* <p>
* In this example, {@code C<Object, C<Number, C<String, Integer>>>>} encodes that {@code Function}'s
* second type argument is a list of types: {@code Object}, {@code Number}, {@code String} and {@code Integer}. The
* {@link Types} class provides static methods to extract the types.
* <p>
* This list-like structure, similar to Lisp's {@code cons}, is named a <i>cons type</i> (hence the {@code C}),
* but using only one letter kept the whole structure more readable.
* <p>
*
* @author Humberto Anjos
* @param <First> The first type.
* @param <Rest> The last type, or a C holding the rest of the types.
* @see Types
*/
public final class C<First, Rest> {
private C() { /* preventing instantiation */ }
}
|
package org.sbrubbles.genericcons;
import static org.sbrubbles.genericcons.Utils.nonNull;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
/**
* Captures and represents an open-ended list of types. This class isn't
* supposed to be instantiated or subclassed; it's used to build the list in
* the type declaration, like below:
*
* <pre>
* Function<?, ?> f = new Function<String, C<Object, C<Number, C<String, Integer>>>>() {
* { // the no-arg constructor
* this.types = C.extractTypesFromSuperclass(this.getClass(), 1);
* }
* };
* </pre>
*
* This list-like structure, similar to Lisp's {@code cons}, is named a <i>cons type</i> (hence the {@code C}),
* but using only one letter kept the whole structure (slightly) more readable.
*
* @author Humberto Anjos
* @param <First> The first type.
* @param <Rest> The last type, or a C holding the rest of the types.
*/
public final class C<First, Rest> {
private C() { /* preventing instantiation */ }
/**
* A helper interface for the type checking API. Instances will hold the types to be used for checking.
*
* @author Humberto Anjos
*/
public static interface TypeChecker {
boolean onVarargs(Object... objects) throws IllegalArgumentException;
boolean onIterable(Iterable<?> objects) throws IllegalArgumentException;
}
/**
* Holds an iterable of types for checking.
*/
private static class TypeCheckerImpl implements TypeChecker {
private final Iterable<? extends Type> types;
public TypeCheckerImpl(Type... types) throws IllegalArgumentException {
this(Arrays.asList(nonNull(types)));
}
public TypeCheckerImpl(Iterable<? extends Type> types) throws IllegalArgumentException {
this.types = nonNull(types);
}
@Override
public boolean onVarargs(Object... objects) throws IllegalArgumentException {
return checkIterable(types, Arrays.asList(nonNull(objects)));
}
@Override
public boolean onIterable(Iterable<?> objects) throws IllegalArgumentException {
return checkIterable(types, nonNull(objects));
}
}
public static TypeChecker check(Iterable<? extends Type> types) throws IllegalArgumentException {
return new TypeCheckerImpl(types);
}
public static TypeChecker check(Type... types) throws IllegalArgumentException {
return new TypeCheckerImpl(types);
}
public static List<? extends Type> extractTypesFromSuperclass(Class<?> baseClass, int parameterIndex)
throws IllegalArgumentException, TypeParametersNotFoundException {
if(baseClass == null)
throw new IllegalArgumentException("The base class cannot be null!");
Type superclass = baseClass.getGenericSuperclass();
if(! (superclass instanceof ParameterizedType))
throw new TypeParametersNotFoundException(baseClass);
try {
return extractTypesFromCons(((ParameterizedType) superclass).getActualTypeArguments()[parameterIndex]);
} catch (IndexOutOfBoundsException e) {
throw new TypeParametersNotFoundException(baseClass, e);
}
}
public static List<? extends Type> extractTypesFromCons(Type type)
throws IllegalArgumentException {
if(type == null)
throw new IllegalArgumentException("The type cannot be null!");
List<Type> result = new ArrayList<Type>();
// end of recursion, add it and return
if(! (type instanceof ParameterizedType)
|| ((ParameterizedType) type).getRawType() != C.class) {
result.add(type);
return result;
}
Type[] actualTypes = ((ParameterizedType) type).getActualTypeArguments();
result.add(actualTypes[0]);
result.addAll(extractTypesFromCons(actualTypes[1]));
return result;
}
private static boolean checkIterable(Iterable<? extends Type> types, Iterable<?> objects) {
assert types != null;
assert objects != null;
Iterator<?> iterator = objects.iterator();
for(Type type : types) {
if(! iterator.hasNext() // the amount of types and objects doesn't match
|| ! Utils.check(type, iterator.next()))
return false;
}
return ! iterator.hasNext(); // the amount of types and objects must match
}
}
|
package org.scijava.util;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
/**
* Utility class for creating and manipulating {@link PrimitiveArray} instances.
*
* @author Mark Hiner
*/
public final class ArrayUtils {
private ArrayUtils() {
// prevent instantiation of utility class
}
// -- ArrayUtils methods --
/**
* Converts the provided Object to a {@link Collection} implementation. If the
* object is an array type, a {@link PrimitiveArray} wrapper will be created.
*/
public static Collection<?> toCollection(final Object value) {
// If the value is null or we we have a collection, just return it
if (value == null || Collection.class.isAssignableFrom(value.getClass())) {
return (Collection<?>) value;
}
// Check for primitive array types
if (value instanceof char[]) {
return new CharArray((char[]) value);
}
if (value instanceof byte[]) {
return new ByteArray((byte[]) value);
}
if (value instanceof boolean[]) {
return new BoolArray((boolean[]) value);
}
if (value instanceof short[]) {
return new ShortArray((short[]) value);
}
if (value instanceof int[]) {
return new IntArray((int[]) value);
}
if (value instanceof long[]) {
return new LongArray((long[]) value);
}
if (value instanceof float[]) {
return new FloatArray((float[]) value);
}
if (value instanceof double[]) {
return new DoubleArray((double[]) value);
}
if (value instanceof Object[]) {
final Class<?> type = value.getClass().getComponentType();
return makeObjectArray((Object[]) value, type);
}
// This object is a neither an array nor a collection.
// So we wrap it in a list and return.
final List<Object> list = new ArrayList<Object>();
list.add(value);
return list;
}
/**
* Created a new {@link ObjectArray} instance wrapping the provided Object[],
* parameterized using the given Class instance.
*/
@SuppressWarnings("unchecked")
private static <T> ObjectArray<T> makeObjectArray(final Object[] values,
@SuppressWarnings("unused") final Class<T> type)
{
return new ObjectArray<T>((T[]) values);
}
}
|
package org.twuni.twoson;
import java.io.IOException;
import java.io.InputStream;
import java.util.Stack;
public class JSONParser {
private static enum Event {
NONE,
OBJECT,
ARRAY,
OBJECT_KEY
}
private static void burn( byte [] buffer ) {
for( int i = 0; i < buffer.length; i++ ) {
buffer[i] = 0;
}
}
private static void burn( char [] buffer ) {
for( int i = 0; i < buffer.length; i++ ) {
buffer[i] = 0;
}
}
private static boolean isDigit( char c ) {
return '0' <= c && c <= '9';
}
private final InputStream in;
private final JSONEventListener listener;
private byte [] buffer;
private int offset;
private int size;
private final Stack<Event> scope = new Stack<Event>();
public JSONParser( InputStream in, JSONEventListener listener ) {
this.in = in;
this.listener = listener;
}
private double atof( char firstDigit ) throws IOException {
double a = 0;
int e = 0;
char c = firstDigit;
boolean negative = false;
if( c == '-' ) {
negative = true;
c = nextChar();
}
while( isDigit( c ) ) {
a = a * 10 + ( c - '0' );
c = nextChar();
}
if( c == '.' ) {
c = nextChar();
while( isDigit( c ) ) {
a = a * 10 + ( c - '0' );
e
c = nextChar();
}
}
if( c == 'e' || c == 'E' ) {
int sign = 1;
int x = 0;
c = nextChar();
if( c == '+' ) {
// Valid
} else if( c == '-' ) {
sign = -1;
} else {
throw new IOException( "Invalid number format" );
}
c = nextChar();
while( isDigit( c ) ) {
x = x * 10 + c - '0';
c = nextChar();
}
e += x * sign;
}
while( e > 0 ) {
a *= 10;
e
}
while( e < 0 ) {
a *= 0.1;
e++;
}
offset
return negative ? -a : a;
}
private boolean isFinished() {
return size <= 0;
}
private char nextChar() throws IOException {
if( buffer == null ) {
buffer = new byte [64 * 1024];
size = in.read( buffer, 0, buffer.length );
}
if( offset >= size ) {
offset = 0;
size = in.read( buffer, 0, buffer.length );
}
if( isFinished() ) {
return '\0';
}
char c = (char) buffer[offset];
offset++;
return c;
}
public void read() throws IOException {
try {
scope.push( Event.NONE );
for( char c = nextChar(); c != '\0'; c = nextChar() ) {
switch( c ) {
case '{':
scope.push( Event.OBJECT );
listener.onBeginObject();
break;
case '}':
switch( scope.peek() ) {
case OBJECT:
scope.pop();
if( Event.OBJECT_KEY.equals( scope.peek() ) ) {
scope.pop();
}
listener.onEndObject();
break;
default:
throw new IllegalFormatException( c, scope.peek().toString() );
}
break;
case '[':
scope.push( Event.ARRAY );
listener.onBeginArray();
break;
case ']':
switch( scope.peek() ) {
case ARRAY:
scope.pop();
if( Event.OBJECT_KEY.equals( scope.peek() ) ) {
scope.pop();
}
listener.onEndArray();
break;
default:
throw new IllegalFormatException( c, scope.peek().toString() );
}
break;
case ',':
switch( scope.peek() ) {
case ARRAY:
case OBJECT:
break;
default:
throw new IllegalFormatException( c, scope.peek().toString() );
}
break;
case ':':
switch( scope.peek() ) {
case OBJECT_KEY:
break;
default:
throw new IllegalFormatException( c, scope.peek().toString() );
}
break;
case ' ':
case '\t':
case '\r':
case '\n':
// Ignore whitespace.
break;
case '"':
int j;
// FIXME: Read-ahead only works properly if the right anchor exists within
// the
// buffer
int skip = 0;
for( j = offset; j < buffer.length; j++ ) {
if( buffer[j] == '\\' ) {
skip++;
j++;
continue;
}
if( buffer[j] == '"' ) {
break;
}
}
char [] string = new char [j - offset - skip];
skip = 0;
for( int a = 0; a < string.length + skip; a++ ) {
if( buffer[offset + a] == '\\' ) {
skip++;
continue;
}
string[a - skip] = (char) buffer[offset + a];
}
offset = j + 1;
switch( scope.peek() ) {
case OBJECT:
listener.onObjectKey( string );
burn( string );
scope.push( Event.OBJECT_KEY );
break;
case OBJECT_KEY:
listener.onString( string );
burn( string );
scope.pop();
break;
default:
listener.onString( string );
burn( string );
break;
}
break;
case 't':
nextChar();
nextChar();
nextChar();
listener.onBoolean( true );
switch( scope.peek() ) {
case OBJECT_KEY:
scope.pop();
break;
default:
break;
}
break;
case 'f':
nextChar();
nextChar();
nextChar();
nextChar();
listener.onBoolean( false );
switch( scope.peek() ) {
case OBJECT_KEY:
scope.pop();
break;
default:
break;
}
break;
case 'n':
nextChar();
nextChar();
nextChar();
listener.onNull();
switch( scope.peek() ) {
case OBJECT_KEY:
scope.pop();
break;
default:
break;
}
break;
case '-':
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
double f = atof( c );
double d = ( f < 0 ? -1 : 1 ) * ( f - (int) f );
if( d < 0.00001 ) {
listener.onInteger( (int) f );
} else {
listener.onFloat( (float) f );
}
switch( scope.peek() ) {
case OBJECT_KEY:
scope.pop();
break;
default:
break;
}
break;
default:
throw new IllegalFormatException( c, scope.peek().toString() );
}
}
} finally {
scope.clear();
burn( buffer );
buffer = null;
}
}
}
|
package pointGroups.gui;
import java.awt.BorderLayout;
import java.awt.Color;
import java.util.ArrayList;
import java.util.Collection;
import java.util.logging.Logger;
import javax.swing.JPanel;
import pointGroups.geometry.Fundamental;
import pointGroups.geometry.Point3D;
import pointGroups.gui.event.EventDispatcher;
import pointGroups.gui.event.types.ChangeCoordinate3DPointEvent;
import pointGroups.gui.event.types.ChangeCoordinate3DPointHandler;
import pointGroups.gui.event.types.ChangeCoordinate4DPointEvent;
import pointGroups.gui.event.types.ChangeCoordinate4DPointHandler;
import pointGroups.gui.event.types.DimensionSwitchEvent;
import pointGroups.gui.event.types.DimensionSwitchHandler;
import pointGroups.gui.event.types.FundamentalResultEvent;
import pointGroups.gui.event.types.FundamentalResultHandler;
import pointGroups.gui.event.types.Schlegel3DComputeEvent;
import pointGroups.gui.event.types.Schlegel4DComputeEvent;
import pointGroups.gui.event.types.Symmetry3DChooseEvent;
import pointGroups.gui.event.types.Symmetry3DChooseHandler;
import pointGroups.gui.event.types.Symmetry4DChooseEvent;
import pointGroups.gui.event.types.Symmetry4DChooseHandler;
import pointGroups.util.LoggerFactory;
import pointGroups.util.jreality.JRealityUtility;
import pointGroups.util.polymake.FundamentalTransformer;
import de.jreality.geometry.Primitives;
import de.jreality.scene.Appearance;
import de.jreality.scene.Geometry;
import de.jreality.scene.PointSet;
import de.jreality.scene.SceneGraphComponent;
import de.jreality.scene.data.Attribute;
import de.jreality.scene.data.StorageModel;
import de.jreality.shader.DefaultGeometryShader;
import de.jreality.shader.DefaultPointShader;
import de.jreality.shader.ShaderUtility;
import de.jreality.tools.DragEventTool;
import de.jreality.tools.PointDragEvent;
import de.jreality.tools.PointDragListener;
public class PointPicker
extends JPanel
implements FundamentalResultHandler, DimensionSwitchHandler,
ChangeCoordinate3DPointHandler, ChangeCoordinate4DPointHandler,
Symmetry3DChooseHandler, Symmetry4DChooseHandler
{
private static final long serialVersionUID = -3642299900579728806L;
private final boolean responsive;
private Symmetry3DChooseEvent lastSymmetry3DChooseEvent;
private Symmetry4DChooseEvent lastSymmetry4DChooseEvent;
final protected Logger logger = LoggerFactory.getSingle(PointPicker.class);
protected final UiViewer uiViewer = new UiViewer(this) {
public final SceneGraphComponent point = new SceneGraphComponent();
public final Appearance pointAppearance = new Appearance();
public final SceneGraphComponent fundamental = new SceneGraphComponent();
public void testShow() {
Collection<Point3D> points = new ArrayList<Point3D>();
points.add(new Point3D(1, 1, 1));
points.add(new Point3D(1, 1, -1));
points.add(new Point3D(1, -1, 1));
points.add(new Point3D(-1, 1, 1));
points.add(new Point3D(1, -1, -1));
points.add(new Point3D(-1, 1, -1));
points.add(new Point3D(-1, -1, 1));
points.add(new Point3D(-1, -1, -1));
FundamentalTransformer fT = new FundamentalTransformer(points);
fT.setResultString("1 0 0 0\n&\n1 1 0 0\n1 0 0 1\n1 0 1 0\n1 0 0 0\n");
dispatcher.fireEvent(new FundamentalResultEvent(
fT.transformResultString()));
}
@Override
public void onInitialized() {
SceneGraphComponent root = getSceneRoot();
// Test for Fundamental
testShow();
// fundamental.setGeometry(Primitives.cylinder(15));
point.setGeometry(Primitives.point(new double[] { 0, 0, 0 }));
setPointAppearance(pointAppearance);
point.setAppearance(pointAppearance);
root.addChild(fundamental);
root.addChild(point);
DragEventTool dragTool = new DragEventTool();
dragTool.addPointDragListener(new PointDragListener() {
@Override
public void pointDragStart(PointDragEvent e) {
logger.finest("drag start of vertex no " + e.getIndex());
}
@Override
public void pointDragged(PointDragEvent e) {
PointSet pointSet = e.getPointSet();
double[][] points = new double[pointSet.getNumPoints()][];
pointSet.getVertexAttributes(Attribute.COORDINATES).toDoubleArrayArray(
points);
points[e.getIndex()] = e.getPosition();
pointSet.setVertexAttributes(Attribute.COORDINATES,
StorageModel.DOUBLE_ARRAY.array(3).createReadOnly(points));
/*
* for (double[] point : points) {
* System.out.printf("[%2f, %2f, %2f]\n", point[0], point[1],
* point[2]); }
*/
// TODO:
// because the point scene has only one vertex, pointSet should only
// contain one point; and therefore only the statements below should
// be sufficient for point picking.
double[] pickedPoint = e.getPosition();
if (responsive) selectPoint(pickedPoint);
}
@Override
public void pointDragEnd(PointDragEvent e) {
logger.finest("drag end of vertex no " + e.getIndex());
if (!responsive) selectPoint(e.getPosition());
}
});
point.addTool(dragTool);
}
private void setPointAppearance(Appearance ap) {
// make points a little bigger, than the default.
DefaultGeometryShader dgs;
DefaultPointShader dpts;
dgs = ShaderUtility.createDefaultGeometryShader(ap, true);
dgs.setShowPoints(true);
dpts = (DefaultPointShader) dgs.createPointShader("default");
dpts.setDiffuseColor(Color.MAGENTA);
dpts.setSpheresDraw(true);
dpts.setPointSize(0.1);
dpts.setPointRadius(0.1);
}
};
// The current Fundamental Domain
protected Fundamental fundamental;
protected boolean isSet;
protected EventDispatcher dispatcher;
protected int dim;
/**
* Creates the Point Picker, to choose a point graphically.
*
* @param responsive - true => ChangeCoordinateEvent on Drag, False => Change
* Coordinate Event on Release
*/
public PointPicker(boolean responsive) {
super();
setLayout(new BorderLayout());
/*
* JButton button3 = new JButton("VIEW"); PointPicker.this.add(button3,
* BorderLayout.PAGE_END);
*/
this.isSet = false;
this.dim = 2;
this.dispatcher = EventDispatcher.get();
this.responsive = responsive;
// Register PointPicker on Events
this.dispatcher.addHandler(FundamentalResultEvent.TYPE, this);
this.dispatcher.addHandler(DimensionSwitchEvent.TYPE, this);
this.dispatcher.addHandler(ChangeCoordinate3DPointEvent.TYPE, this);
this.dispatcher.addHandler(ChangeCoordinate4DPointEvent.TYPE, this);
this.dispatcher.addHandler(Symmetry4DChooseEvent.TYPE, this);
this.dispatcher.addHandler(Symmetry3DChooseEvent.TYPE, this);
}
public void dispose() {
uiViewer.dispose();
}
@Override
public void onSchlegelResultEvent(FundamentalResultEvent event) {
this.isSet = true;
this.fundamental = event.getResult();
// Maybe check for dimension
this.showFundamental();
}
// Maybe i need this.
@Override
public void onDimensionSwitchEvent(DimensionSwitchEvent event) {
if (event.switchedTo3D()) {
logger.fine("Point Picker switched to 2D Mode.");
this.dim = 2;
}
else if (event.switchedTo4D()) {
logger.fine("Point Picker switched to 3D Mode.");
this.dim = 3;
}
else {
this.dim = 0;
this.isSet = false;
}
}
// Method to fire coordinate Changed Event, should be executed by click inside
// the fundamental domain.
protected void selectPoint(double[] point) {
if (!isSet || (this.dim != 2 && this.dim != 3)) {
logger.info("Point was picked with no useable Fundamental Region.");
return;
}
logger.info("Selected Point (" + point[0] + "," + point[1] +
(this.dim == 3 ? "," + point[2] : "") + ")");
if (!isSet) return;
// Maybe the view is translated or smt
// point = Rotate * point - translation
// Recalculate to Unitsphere on dim+1 dimensions
// Only take the first dim components
double[] selComp = new double[this.dim];
for (int i = 0; i < this.dim; i++)
selComp[i] = point[i];
double[] resP = this.fundamental.revertPoint(selComp);
logger.fine("Point Picker calculated Point (" + resP[0] + "," + resP[1] +
"," + resP[2] + (this.dim == 3 ? "," + resP[3] : "") + ")");
// Fire Event, that the coordinate changed
if (dim == 2) {
this.dispatcher.fireEvent(new ChangeCoordinate3DPointEvent(
JRealityUtility.asPoint3D(resP), this));
// if (responsive)
this.dispatcher.fireEvent(new Schlegel3DComputeEvent(
lastSymmetry3DChooseEvent, JRealityUtility.asPoint3D(resP)));
}
else if (dim == 3) {
this.dispatcher.fireEvent(new ChangeCoordinate4DPointEvent(
JRealityUtility.asPoint4D(resP), this));
// if (responsive)
this.dispatcher.fireEvent(new Schlegel4DComputeEvent(
lastSymmetry4DChooseEvent, JRealityUtility.asPoint4D(resP)));
}
}
protected void showFundamental() {
logger.info("Showing new Fundamental Domain.");
Geometry g;
// Calculate the new fundamental
if (this.fundamental.isKnown()) {
g = JRealityUtility.generateCompleteGraph(this.fundamental.getVertices());
}
else {
if (this.dim == 2) g = Primitives.sphere(20);
else g = Primitives.sphere(20);
}
// Reset tools (3D rotation, 2D no Rotation)
logger.fine("A new Fundamental Region is shown.");
uiViewer.setGeometry(g);
}
@Override
public void
onChangeCoordinate4DPointEvent(ChangeCoordinate4DPointEvent event) {
// Calculate if the point is in the Fundamental Domain and
// show it, if possible
// For start test just show the point
// uiViewer.setGeometry(Primitives.point(new double[] { 0.5, 0.5 }));
return;
}
@Override
public void
onChangeCoordinate3DPointEvent(ChangeCoordinate3DPointEvent event) {
// Calculate if the point is in the Fundamental Domain and
// show it, if possible
// For start test just show the point
// uiViewer.setGeometry(Primitives.point(new double[] { 0.5, 0.5 }));
return;
}
@Override
public void onSymmetry4DChooseEvent(Symmetry4DChooseEvent event) {
this.lastSymmetry4DChooseEvent = event;
}
@Override
public void onSymmetry3DChooseEvent(Symmetry3DChooseEvent event) {
this.lastSymmetry3DChooseEvent = event;
}
}
|
package propertor;
import com.sun.source.util.Trees;
import com.sun.tools.javac.code.Flags;
import com.sun.tools.javac.processing.JavacProcessingEnvironment;
import com.sun.tools.javac.tree.JCTree;
import com.sun.tools.javac.tree.JCTree.JCAssign;
import com.sun.tools.javac.tree.JCTree.JCBlock;
import com.sun.tools.javac.tree.JCTree.JCClassDecl;
import com.sun.tools.javac.tree.JCTree.JCExpression;
import com.sun.tools.javac.tree.JCTree.JCExpressionStatement;
import com.sun.tools.javac.tree.JCTree.JCIdent;
import com.sun.tools.javac.tree.JCTree.JCMethodDecl;
import com.sun.tools.javac.tree.JCTree.JCModifiers;
import com.sun.tools.javac.tree.JCTree.JCPrimitiveTypeTree;
import com.sun.tools.javac.tree.JCTree.JCReturn;
import com.sun.tools.javac.tree.JCTree.JCStatement;
import com.sun.tools.javac.tree.JCTree.JCTypeParameter;
import com.sun.tools.javac.tree.JCTree.JCVariableDecl;
import com.sun.tools.javac.tree.TreeMaker;
import com.sun.tools.javac.util.List;
import com.sun.tools.javac.util.Name;
import com.sun.tools.javac.util.Name.Table;
import javax.annotation.processing.AbstractProcessor;
import javax.annotation.processing.ProcessingEnvironment;
import javax.annotation.processing.RoundEnvironment;
import javax.annotation.processing.SupportedAnnotationTypes;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.Element;
import javax.lang.model.element.TypeElement;
import java.util.ArrayList;
import java.util.Set;
import static com.sun.tools.javac.code.TypeTags.VOID;
import static com.sun.tools.javac.util.Name.fromString;
@SupportedAnnotationTypes("propertor.Property")
public class PropertyProcessor extends AbstractProcessor {
//region Fields
private TreeMaker mTreeMaker;
//endregion
//region Processor
@Override public synchronized void init(ProcessingEnvironment processingEnvironment) {
super.init(processingEnvironment);
mTreeMaker = TreeMaker.instance(((JavacProcessingEnvironment) processingEnvironment).getContext());
}
@Override public boolean process(Set<? extends TypeElement> set, RoundEnvironment roundEnvironment) {
final ArrayList<PropertyModel> propertyModels = parsePropertyAnnotations(roundEnvironment);
for (final PropertyModel propertyModel : propertyModels) {
writeGetter(propertyModel);
writeSetter(propertyModel);
}
return false;
}
@Override public SourceVersion getSupportedSourceVersion() {
return SourceVersion.latestSupported();
}
//endregion
//region Setter Getter writer
private void writeSetter(PropertyModel propertyModel) {
final Trees trees = Trees.instance(processingEnv);
final JCClassDecl classTree = (JCClassDecl) trees.getTree(propertyModel.getClassElement());
final Name methodName = getName(propertyModel.getSetterName());
for (final JCTree def : classTree.defs) {
if (def instanceof JCMethodDecl) {
JCMethodDecl methodDecl = (JCMethodDecl) def;
if (methodDecl.name.equals(methodName)) {
return;
}
}
}
long setterFlags;
switch (propertyModel.getPropertyAnnotation().setter()) {
case PUBLIC:
setterFlags = Flags.PUBLIC;
break;
case PROTECTED:
setterFlags = Flags.PROTECTED;
break;
case PRIVATE:
setterFlags = Flags.PRIVATE;
break;
default:
setterFlags = 0;
}
setterFlags = setterFlags | Flags.FINAL;
final JCModifiers modifiers = mTreeMaker.Modifiers(setterFlags);
final JCTree fieldType = propertyModel.getFieldDecl().getType();
final JCTree parameterType = fieldType instanceof JCPrimitiveTypeTree ?
wrapPrimitive((JCPrimitiveTypeTree) fieldType) : fieldType;
final JCExpression returnExpression = mTreeMaker.TypeIdent(VOID);
final JCVariableDecl paramDecl = mTreeMaker.VarDef(
mTreeMaker.Modifiers(Flags.PARAMETER),
getName(propertyModel.getPropertyName().substring(0, 1).toLowerCase() + propertyModel.getPropertyName().substring(1)),
mTreeMaker.Ident(getName(parameterType.toString())),
null);
final JCIdent paramExpression = mTreeMaker.Ident(paramDecl.name);
final JCExpression fieldIdent = mTreeMaker.Ident(propertyModel.getFieldDecl());
final JCAssign assign = mTreeMaker.Assign(fieldIdent, paramExpression);
final JCExpressionStatement exec = mTreeMaker.Exec(assign);
final JCBlock setterBody = mTreeMaker.Block(0, List.<JCStatement>nil());
setterBody.stats = setterBody.stats.append(exec);
final JCMethodDecl setter = mTreeMaker.MethodDef(modifiers, methodName, returnExpression, List.<JCTypeParameter>nil(),
List.of(paramDecl), List.<JCExpression>nil(), setterBody, null);
classTree.defs = classTree.defs.append(setter);
}
private void writeGetter(PropertyModel propertyModel) {
final Trees trees = Trees.instance(processingEnv);
final JCClassDecl classTree = (JCClassDecl) trees.getTree(propertyModel.getClassElement());
final Name methodName = getName(propertyModel.getGetterName());
for (final JCTree def : classTree.defs) {
if (def instanceof JCMethodDecl) {
JCMethodDecl methodDecl = (JCMethodDecl) def;
if (methodDecl.name.equals(methodName)) {
return;
}
}
}
long getterFlags;
switch (propertyModel.getPropertyAnnotation().getter()) {
case PUBLIC:
getterFlags = Flags.PUBLIC;
break;
case PROTECTED:
getterFlags = Flags.PROTECTED;
break;
case PRIVATE:
getterFlags = Flags.PRIVATE;
break;
default:
getterFlags = 0;
}
getterFlags = getterFlags | Flags.FINAL;
final JCBlock getterBody = mTreeMaker.Block(0, List.<JCStatement>nil());
final JCExpression expression = mTreeMaker.Ident(propertyModel.getFieldDecl());
final JCReturn returnStmt = mTreeMaker.Return(expression);
getterBody.stats = getterBody.stats.append(returnStmt);
final JCModifiers modifiers = mTreeMaker.Modifiers(getterFlags);
final JCTree fieldType = propertyModel.getFieldDecl().getType();
final JCTree returnType = fieldType instanceof JCPrimitiveTypeTree ?
wrapPrimitive((JCPrimitiveTypeTree) fieldType) : fieldType;
final JCExpression returnExpression = mTreeMaker.Ident(getName(returnType.toString()));
final JCMethodDecl getter = mTreeMaker.MethodDef(modifiers, methodName, returnExpression, List.<JCTypeParameter>nil(),
List.<JCVariableDecl>nil(), List.<JCExpression>nil(), getterBody, null);
classTree.defs = classTree.defs.append(getter);
}
//endregion
//region Helpers
private ArrayList<PropertyModel> parsePropertyAnnotations(RoundEnvironment env) {
final Set<? extends Element> propertyElements = env.getElementsAnnotatedWith(Property.class);
ArrayList<PropertyModel> propertyModels = new ArrayList<PropertyModel>(propertyElements.size());
for (final Element propertyElement : propertyElements) {
propertyModels.add(new PropertyModel(propertyElement, processingEnv));
}
return propertyModels;
}
private JCExpression generateDotExpression(String... strings) {
if (strings == null || strings.length == 0) return null;
String arg1 = strings[0];
JCExpression expression = mTreeMaker.Ident(getName(arg1));
for (int i = 1; i < strings.length; i++) {
expression = mTreeMaker.Select(expression, getName(strings[i]));
}
return expression;
}
private Name getName(String s) {
return fromString(Table.instance(((JavacProcessingEnvironment) processingEnv).getContext()), s);
}
private JCExpression wrapPrimitive(JCPrimitiveTypeTree primitiveTypeTree) {
String primitiveTypeName = primitiveTypeTree.type.tsym.getQualifiedName().toString();
String wrapperName;
if (primitiveTypeName.equalsIgnoreCase("boolean")) {
wrapperName = "Boolean";
} else if (primitiveTypeName.equalsIgnoreCase("byte")) {
wrapperName = "Byte";
} else if (primitiveTypeName.equalsIgnoreCase("char")) {
wrapperName = "Character";
} else if (primitiveTypeName.equalsIgnoreCase("double")) {
wrapperName = "Double";
} else if (primitiveTypeName.equalsIgnoreCase("float")) {
wrapperName = "Float";
} else if (primitiveTypeName.equalsIgnoreCase("int")) {
wrapperName = "Integer";
} else if (primitiveTypeName.equalsIgnoreCase("long")) {
wrapperName = "Long";
} else if (primitiveTypeName.equalsIgnoreCase("void")) {
wrapperName = "Void";
} else {
throw new IllegalArgumentException("Could not find wrapper for type " + primitiveTypeName);
}
return generateDotExpression(wrapperName);
}
//endregion
}
|
package robertbosch.utils;
import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.concurrent.TimeoutException;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.Consumer;
import com.rabbitmq.client.DefaultConsumer;
import com.rabbitmq.client.Envelope;
public class Testclass {
static int ctr=0;
public static void main(String[] args) {
System.out.println("test rabbitmq subscriber...");
subscriberabbitMQ(Integer.parseInt(args[0]));
System.out.println("done with test proto code...");
}
private static void subscriberabbitMQ(final int datapoint) {
//String subscribefile = "/Users/sahiltyagi/Desktop/subscribe.txt";
String subscribefile = "/home/etl_subsystem/subscribe.txt";
RobertBoschUtils rb = new RobertBoschUtils();
try {
final BufferedWriter subscriber = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(subscribefile)));
ConnectionFactory factory = new ConnectionFactory();
factory.setHost(RobertBoschUtils.props.getProperty("host"));
factory.setPort(Integer.parseInt(RobertBoschUtils.props.getProperty("port")));
factory.setUsername(RobertBoschUtils.props.getProperty("username"));
factory.setPassword(RobertBoschUtils.props.getProperty("password"));
factory.setVirtualHost(RobertBoschUtils.props.getProperty("virtualhost"));
Connection conn = factory.newConnection();
Channel channel = conn.createChannel();
channel.queueDeclare("sahil", false, false, false, null);
Consumer consumer = new DefaultConsumer(channel) {
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
//RabbitMQSpout.nbqueue.add(body);
String message = new String(body, "UTF-8");
System.out.println(" [x] Received '" + message + "'");
JSONParser parser = new JSONParser();
try {
Object ob = parser.parse(message);
JSONObject jsonob = (JSONObject)ob;
subscriber.write(System.currentTimeMillis() + "," + jsonob.get("msgid") + "\n");
ctr++;
if(ctr == datapoint) {
subscriber.close();
System.out.println("completed index....");
}
} catch (ParseException e) {
e.printStackTrace();
}
}
};
channel.basicConsume("sahil", true, consumer);
} catch(IOException e) {
e.printStackTrace();
} catch(TimeoutException t) {
t.printStackTrace();
}
}
}
|
package user.student;
import assignment.Assignment;
import assignment.AssignmentGrade;
import course.CurveSetting;
import course.LetterGrade;
import admin.User;
import util.GraderObject;
import java.util.Collection;
/**
* Class containing all of the information for a student's record.
*/
public abstract class StudentRecord implements GraderObject {
/**
* Student's user information
*/
User student;
/**
* Student-specific comment from the instructor.
*/
String comment;
/**
* Student's assignment grades.
*/
Collection<AssignmentGrade> grades;
/**
* Raw percentage grade of the student.
*/
double rawPercentage;
/**
* Letter grade of the student.
*/
LetterGrade letterGrade;
/**
* Accessor for the student's grade on the specified <code>Assignment</code>.
* @return grade the student received for the <code>Assignment</code>.
* <p/>
* <pre>
* pre:
* grades != null &&
* exists (int i; i >= 0 && i < grades.size();
* grades.get(i).getAssignment().equals(assignment))
* post:
* grades.contains(return) &&
* grades'.size() == grades.size()
*/
public abstract AssignmentGrade getAssignmentGrade(Assignment assignment);
/**
* Accessor for the entire <code>Collection</code> of
* <code>AssignmentGrade</code>s for the student.
* @return all <code>AssignmentGrades</code>s of this student.
* <p/>
* <pre>
* pre:
* grades != null;
* post:
* forall (AssignmentGrade ag; grades.contains(ag)
*/
public abstract Collection<AssignmentGrade> getAllAssignmentGrades();
/**
* Accessor for the personal <code>User</code> information of the student.
* @return <code>User</code> information of the student.
* <p/>
* <pre>
* pre:
* student != null
* post:
* return.equals(student)
*/
public abstract User getUserInfo();
/**
* Accessor for the comment written by the instructor about the student.
* @return comment written by the instructor.
* <p/>
* <pre>
* pre:
* student != null
* post:
* // none
*/
public abstract String getStudentComment();
/**
* Sets the comment for the student.
* @param studentComment comment for the student.
* <p/>
* <pre>
* pre:
* user != null &&
* studentComment != null
* post:
* comment' != null &&
* comment'.equals(studentComment)
*/
public abstract void setStudentComment(String studentComment);
/**
* Calculates and returns the raw percentage grade of the student.
* @return raw percentage grade.
* <p/>
* <pre>
* pre:
* user != null
* post:
* // none
*/
public abstract double getRawPercentageGrade();
/**
* Calculates and returns the letter grade of the student.
* @param curve <code>CurveSetting</code> of the course a student is in.
* @return letter grade.
* <p/>
* <pre>
* pre:
* curve != null &&
* user != null &&
* getRawPercentageGrade() >= 0
* post:
* // none
*/
public abstract LetterGrade getLetterGrade(CurveSetting curve);
}
|
package tigase.net;
import java.io.IOException;
import java.nio.channels.ClosedChannelException;
import java.nio.channels.CancelledKeyException;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;
import java.util.HashSet;
import java.util.concurrent.CompletionService;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
import tigase.annotations.TODO;
/**
* Describe class SocketReadThread here.
*
*
* Created: Mon Jan 30 12:01:17 2006
*
* @author <a href="mailto:artur.hefczyc@tigase.org">Artur Hefczyc</a>
* @version $Rev$
*/
public class SocketReadThread implements Runnable {
private static final Logger log =
Logger.getLogger("tigase.net.SocketReadThread");
public static final int DEF_MAX_THREADS_PER_CPU = 5;
private static final int MAX_EMPTY_SELECTIONS = 10;
private static SocketReadThread socketReadThread = null;
private boolean stopping = false;
private boolean wakeup_called = false;
private int empty_selections = 0;
private final ConcurrentLinkedQueue<IOService> waiting =
new ConcurrentLinkedQueue<IOService>();
private Selector clientsSel = null;
private ThreadPoolExecutor executor = null;
/**
* Variable <code>completionService</code> keeps reference to server thread pool.
* There is only one thread pool used by all server modules. Each module requiring
* separate threads for tasks processing must have access to server thread pool.
*/
private CompletionService<IOService> completionService = null;
/**
* Creates a new <code>SocketReadThread</code> instance.
*
*/
private SocketReadThread() {
try {
clientsSel = Selector.open();
int cpus = Runtime.getRuntime().availableProcessors();
int nThreads = cpus * DEF_MAX_THREADS_PER_CPU;
executor = new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>());
completionService =
new ExecutorCompletionService<IOService>(executor);
} catch (Exception e) {
log.log(Level.SEVERE, "Server I/O error, can't continue my work.", e);
stopping = true;
} // end of try-catch
new ResultsListener().start();
}
public static SocketReadThread getInstance() {
if (socketReadThread == null) {
socketReadThread = new SocketReadThread();
Thread thrd = new Thread(socketReadThread);
thrd.setName("SocketReadThread");
thrd.start();
log.fine("SocketReadThread started.");
} // end of if (acceptThread == null)
return socketReadThread;
}
public void setMaxThreadPerCPU(int threads) {
int cpus = Runtime.getRuntime().availableProcessors();
setMaxThread(threads * cpus);
}
public void setMaxThread(int threads) {
executor.setCorePoolSize(threads);
executor.setMaximumPoolSize(threads);
}
public synchronized void addSocketService(IOService s) {
waiting.offer(s);
wakeup_called = true;
clientsSel.wakeup();
}
public void removeSocketService(IOService s) {
SelectionKey key = s.getSocketChannel().keyFor(clientsSel);
if (key != null && key.attachment() == s) {
key.cancel();
} // end of if (key != null)
}
private static final int READ_ONLY = SelectionKey.OP_READ;
private static final int READ_WRITE =
SelectionKey.OP_READ | SelectionKey.OP_WRITE;
private void addAllWaiting() throws IOException {
IOService s = null;
while ((s = waiting.poll()) != null) {
final SocketChannel sc = s.getSocketChannel();
try {
int sel_key = READ_ONLY;
log.finest("ADDED OP_READ: " + s.getUniqueId());
if (s.waitingToSend()) {
sel_key = READ_WRITE;
log.finest("ADDED OP_WRITE: " + s.getUniqueId());
}
sc.register(clientsSel, sel_key, s);
} catch (Exception e) {
// Ignore such channel
log.finest("ERROR adding channel for: " + s.getUniqueId()
+ ", exception: " + e);
} // end of try-catch
} // end of for ()
}
// Implementation of java.lang.Runnable
private synchronized void recreateSelector() throws IOException {
log.finest("Recreating selector, opened channels: " + clientsSel.keys().size());
empty_selections = 0;
// Handling a bug or not a bug described in the
// last comment to this issue:
// and
// Recreating the selector and registering all channles with
// the new selector
synchronized (this) {
Selector tempSel = clientsSel;
clientsSel = Selector.open();
for (SelectionKey sk: tempSel.keys()) {
IOService serv = (IOService)sk.attachment();
sk.cancel();
if (serv.isConnected()) {
SocketChannel sc = serv.getSocketChannel();
try {
int sel_key = READ_ONLY;
log.finest("ADDED OP_READ: " + serv.getUniqueId());
if (serv.waitingToSend()) {
sel_key = READ_WRITE;
log.finest("ADDED OP_WRITE: " + serv.getUniqueId());
}
sc.register(clientsSel, sel_key, serv);
} catch (Exception e) {
// Ignore such channel
log.finest("ERROR re-adding channel for: " + serv.getUniqueId()
+ ", exception: " + e);
} // end of try-catch
} else {
try {
log.info("Forcing stopping the service: " + serv.getUniqueId());
serv.forceStop();
} catch (Exception e) { }
}
}
tempSel.close();
}
}
/**
* Describe <code>run</code> method here.
*
*/
public void run() {
while (!stopping) {
try {
wakeup_called = false;
int selectedKeys = clientsSel.select();
if((selectedKeys == 0) && !wakeup_called
&& ((++empty_selections) > MAX_EMPTY_SELECTIONS)) {
log.finest("Selected keys = 0!!! a bug again?");
recreateSelector();
} else {
empty_selections = 0;
// This is dirty but selectNow() causes concurrent modification exception
// and the selectNow() is needed because of a bug in JVM mentioned below
for (SelectionKey sk: clientsSel.selectedKeys()) {
// According to most guides we should use below code
// removing SelectionKey from iterator, however a little later
// we do cancel() on this key so removing is somehow redundant
// and causes concurrency exception if a few calls are performed
// at the same time.
//selected_keys.remove(sk);
IOService s = (IOService)sk.attachment();
try {
if (log.isLoggable(Level.FINEST)) {
StringBuilder sb = new StringBuilder("AWAKEN: " + s.getUniqueId());
if (sk.isWritable()) {
sb.append(", ready for WRITING");
}
if (sk.isReadable()) {
sb.append(", ready for READING");
}
sb.append(", readyOps() = " + sk.readyOps());
log.finest(sb.toString());
}
// Set<SelectionKey> selected_keys = clientsSel.selectedKeys();
// for (SelectionKey sk : selected_keys) {
// Handling a bug or not a bug described in the
// last comment to this issue:
// and
sk.cancel();
completionService.submit(s);
} catch (CancelledKeyException e) {
log.finest("CancelledKeyException, stopping the connection: "
+ s.getUniqueId());
try { s.forceStop(); } catch (Exception ex2) { }
}
}
}
// Clean-up cancelled keys...
clientsSel.selectNow();
addAllWaiting();
} catch (CancelledKeyException brokene) {
// According to Java API that should not happen.
// I think it happens only on the broken Java implementation
// from Apple.
log.log(Level.WARNING, "Ups, broken JDK, Apple? ", brokene);
try {
recreateSelector();
} catch (Exception e) {
log.log(Level.SEVERE, "Serious problem, can't recreate selector: ", e);
//stopping = true;
}
} catch (IOException ioe) {
// According to Java API that should not happen.
// I think it happens only on the broken Java implementation
// from Apple.
log.log(Level.WARNING, "Problem with the network connection: ", ioe);
try {
recreateSelector();
} catch (Exception e) {
log.log(Level.SEVERE, "Serious problem, can't recreate selector: ", e);
//stopping = true;
}
} catch (Exception exe) {
log.log(Level.SEVERE, "Server I/O error: ", exe);
try {
recreateSelector();
} catch (Exception e) {
log.log(Level.SEVERE, "Serious problem, can't recreate selector: ", e);
//stopping = true;
}
//stopping = true;
}
}
}
@TODO(note="ExecutionException is poorly implemented.")
protected class ResultsListener extends Thread {
public ResultsListener() {
super();
setName("SocketReadThread$ResultsListener");
}
public void run() {
for (;;) {
try {
final IOService service = completionService.take().get();
if (service.isConnected()
//&& !service.getSocketChannel().isRegistered()
) {
log.finest("COMPLETED: " + service.getUniqueId());
addSocketService(service);
} else {
log.finest("REMOVED: " + service.getUniqueId());
} // end of else
}
catch (ExecutionException e) {
log.log(Level.WARNING, "Protocol execution exception.", e);
// TODO: Do something with this
} // end of catch
catch (InterruptedException e) {
log.log(Level.WARNING, "Protocol execution interrupted.", e);
} // end of try-catch
catch (Exception e) {
log.log(Level.WARNING, "Protocol execution unknown exception.", e);
} // end of catch
} // end of for ()
}
}
} // SocketReadThread
|
package persistlayer;
import java.sql.Connection;
import java.sql.ResultSet;
public class SearchPersistImpl{
//global variables
DbAccessImpl db = new DbAccessImpl();
Connection con = db.connect();
public ResultSet getSuggestions(String searchbarContent){
ResultSet rs;
String query = "SELECT DISTINCT makes FROM cars WHERE make LIKE \'%%" + searchbarContent + "%%\' LIMIT 1";
rs = db.retrieve(con, query);
return rs;
}//getSuggestions
}//SearchImpl
|
package httpserver;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
/**
* A MethodWrapper is a wrapper for the reflect.Method class. It allows us to
* easily invoke a method based on a path without worrying about parsing out
* the variables and whatnot.
*/
class MethodWrapper {
private static final String LANG_PATH = "java.lang.";
private String path;
private Method method;
/**
* Create a MethodWrapper.
*
* Paths should come in <code>/relative/path/to/match</code>. To use a
* variable in a path, it should come in
* <code>/path/with/{VariableType}</code> form, where VariableType is a
* class inside of the `java.lang` package, and has a constructor that takes
* in a String. A better explaination is in HTTPHandler#addGET
*
* @param path Path the be matched for this method to be used.
* @param methodName Name of the method to be called.
* @param callingClass Class the method belongs to.
*
* @throws HTTPException If there is no callingClass.methodName method. If
* the wrong number of variable parameters are used in
* the path. If the variable parameters are in the
* wrong order in the path.
*
* @see HTTPHandler#addGET
*/
public MethodWrapper(String path, String methodName, Class callingClass)
throws HTTPException {
try {
// Get a list of the parameter types
List<Class> parameterTypes = new ArrayList<Class>();
String[] paths = path.split("/");
StringBuilder pathBuilder = new StringBuilder();
/* Recreate the path.
This is done so that a path may include or exclude a `/` at the end
of it. It also makes sure that non-dynamic parts of the path are
lower case'd.
*/
for (String part : paths) {
/* if, for some reason, there's something like a `//` in the path,
or if it's the first one (because of the preceeding /), part is
empty, which means we have nothing to do here.
*/
if (part.isEmpty()) {
continue;
}
if (isDynamic(part)) {
String paramClass = LANG_PATH + part.substring(1, part.length() - 1);
parameterTypes.add(Class.forName(paramClass));
}
else {
part.toLowerCase();
}
pathBuilder.append('/');
pathBuilder.append(part);
}
this.path = pathBuilder.toString();
// If the path was just a '/' it will be empty
if (this.path.isEmpty()) {
this.path = "/";
}
/* Because Class.getMethod() takes in an array of Classes, and because
List.toArray() returns an array of Objects, we need to manually
convert parameterTypes from a list to an array.
*/
Class[] paramTypes = new Class[parameterTypes.size()];
for (int i=0; i < parameterTypes.size(); i++) {
paramTypes[i] = parameterTypes.get(i);
}
method = callingClass.getMethod(methodName, paramTypes);
}
catch(ClassNotFoundException | NoSuchMethodException
| SecurityException e) {
throw new HTTPException("Could not add path.", e);
}
}
/**
* Invoke the method.
*
* @param callingClass The class the method belongs to.
* @param path The path that caused the method to be called. This is
* where variables come from.
*
* @throws HTTPException If anything bad happend in invoking the underlying
* method. Probably shouldn't happen, because the
* issues would be found first when making the
* MethodWrapper, but there's a chance they could
* happen.
*
* @see java.lang.reflect.Method#invoke
*/
public void invoke(Object callingClass, String path) throws HTTPException {
try {
// Get the parameters
String[] paths = path.split("/");
String[] methodPaths = this.path.split("/");
List<Object> params = new ArrayList<Object>();
for (int i = 0; i < methodPaths.length; i++) {
if (isDynamic(methodPaths[i])) {
Class paramClass = Class.forName(LANG_PATH
+ methodPaths[i].substring(1, methodPaths[i].length() - 1));
Constructor paramConstructor
= paramClass.getConstructor(String.class);
params.add(paramConstructor.newInstance(paths[i]));
}
}
// Method.invoke throws an exception if an empty array is passed in
if (params.isEmpty()) {
method.invoke(callingClass);
}
else {
method.invoke(callingClass, params.toArray());
}
}
catch (IllegalAccessException | IllegalArgumentException
| InvocationTargetException | SecurityException
| ClassNotFoundException | NoSuchMethodException
| InstantiationException e) {
throw new HTTPException("Could not invoke method.", e);
}
}
/**
* Determines how correct a method is from a path. The higher the number,
* the more likely the method is the correct method.
*
* Correctness is based on the similarity of the passed in path, and the
* method's path. If a path segment (the part between two slashes) matches
* this method's corresponding segment exactly, the correctness number is
* incremented by three. If the segment matches the variable type of the
* corresponding segment, the correctness number is incremented by one, and
* if the variable class can contain a decimal in it, the correctness
* number is incremented by one, again.
*
* If a zero is returned, the passed in path doesn't match this method's
* path at all.
*
* @param path The path, relative the the handler.
*
* @return A "correctness number", based on how well the passed in
* path matches this method's path.
*/
public int howCorrect(String path) {
String[] paths = path.split("/");
String[] methodPaths = this.path.split("/");
// If the paths aren't the same length, this is the wrong method
if (paths.length != methodPaths.length) {
return 0;
}
// Start at one because the paths are the same length
int count = 1;
for (int i = 0; i < paths.length && i < methodPaths.length; i++) {
if (paths[i].equals(methodPaths[i])) {
count += 3;
}
else if (isDynamic(methodPaths[i])) {
try {
Class paramClass = Class.forName(LANG_PATH +
methodPaths[i].substring(1, methodPaths[i].length() - 1));
Constructor constructor = paramClass.getConstructor(String.class);
constructor.newInstance(paths[i]);
count++;
if (!hasDecimal(paramClass)) {
count++;
}
}
catch (ClassNotFoundException | NoSuchMethodException
| SecurityException | InstantiationException
| IllegalAccessException | IllegalArgumentException
| InvocationTargetException e) {
return 0;
}
}
}
return count;
}
/**
* Checks if a class allows a decimal or not
*
* @param paramClass Class being checked
* @return If the class is a BigDecimal, Double, or Float.
*/
private boolean hasDecimal(Class<? extends Number> paramClass) {
return paramClass.equals(BigDecimal.class) ||
paramClass.equals(Double.class) ||
paramClass.equals(Float.class);
}
/**
* Checks if there is dynamic text in part of a path.
*
* @param path Part of the path you want to check for dynamic data.
* @return If the path matches the regex pattern `\{[A-Za-z0-9]{1,}\}`
*/
private boolean isDynamic(String path) {
return path.matches("\\{[A-Za-z0-9]{1,}\\}");
}
/**
* Gets the name of the Method
*
* @return the Method's name
*/
public String getName() {
return method.getName();
}
@Override
public String toString() {
return method.toString();
}
}
|
package uk.org.cinquin.mutinack;
import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;
import javax.jdo.annotations.Column;
import javax.jdo.annotations.NotPersistent;
import javax.jdo.annotations.PersistenceCapable;
import org.eclipse.jdt.annotation.NonNull;
import com.beust.jcommander.IStringConverter;
import com.beust.jcommander.JCommander;
import com.beust.jcommander.Parameter;
import com.beust.jcommander.ParameterDescription;
import com.beust.jcommander.WrappedParameter;
import com.beust.jcommander.converters.BaseConverter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import uk.org.cinquin.mutinack.misc_util.Assert;
import uk.org.cinquin.mutinack.misc_util.Handle;
import uk.org.cinquin.mutinack.statistics.PrintInStatus.OutputLevel;
@PersistenceCapable
public final class Parameters implements Serializable, Cloneable {
public void validate() {
if (ignoreFirstNBasesQ2 < ignoreFirstNBasesQ1) {
throw new IllegalArgumentException("Parameter ignoreFirstNBasesQ2 must be greater than ignoreFirstNBasesQ1");
}
final int nMaxDupArg = maxNDuplexes.size();
if (nMaxDupArg > 0 && nMaxDupArg < inputReads.size()) {
throw new IllegalArgumentException("maxNDuplexes must be specified once for each input file or not at all");
}
final OutputLevel[] d = OutputLevel.values();
if (verbosity < 0 || verbosity >= d.length) {
throw new IllegalArgumentException("Invalid verbosity " + verbosity + "; must be >= 0 and < " + d.length);
}
for (String ir: inputReads) {
if (ir.endsWith(".bai")) {
throw new IllegalArgumentException("Unexpected .bai extension in input read path " + ir);
}
}
switch(candidateQ2Criterion) {
case "1Q2Duplex":
break;
case "NQ1Duplexes":
if (minQ1Duplexes == Integer.MAX_VALUE) {
throw new IllegalArgumentException("Option minQ1Duplexes must be set for NQ1Duplexes mode");
}
break;
default:
throw new RuntimeException("Option candidateQ2Criterion must be one of 1Q2Duplex or NQ1Duplexes, not "
+ candidateQ2Criterion);
}
checkNoDuplicates();
for (String p: exploreParameters) {
String [] split = p.split(":");
if (split.length != 4 && split.length != 3 && split.length != 1) {
throw new IllegalArgumentException("exploreParameters argument should be formatted as " +
"name:min:max[:step] or name, but " + (split.length - 1) + " columns found in " + p);
}
final String paramName = split[0];
final Field f;
try {
f = Parameters.class.getDeclaredField(paramName);
} catch (NoSuchFieldException e) {
throw new RuntimeException("Unknown parameter " + paramName, e);
} catch (SecurityException e) {
throw new RuntimeException(e);
}
if (f.getAnnotation(OnlyUsedAfterDuplexGrouping.class) == null &&
f.getAnnotation(UsedAtDuplexGrouping.class) == null) {
throw new IllegalArgumentException("Parameter " + paramName + " does not explicitly support exploration");
}
if (computeRawMismatches && f.getAnnotation(ExplorationIncompatibleWithRawMismatches.class) != null) {
throw new IllegalArgumentException("Please turn computeRawMismatches off to explore " + paramName);
}
final Object value;
try {
value = f.get(this);
} catch (IllegalArgumentException | IllegalAccessException e) {
throw new RuntimeException(e);
}
if (!(value instanceof Integer) && !(value instanceof Float) && !(value instanceof Boolean)) {
throw new IllegalArgumentException("Parameter " + paramName + " is not a number or boolean");
}
}
}
private void checkNoDuplicates() {
iterateFields((field, obj) -> {
if (field.getAnnotation(NoDuplicates.class) == null || obj == null) {
return;
}
@SuppressWarnings("unchecked")
Collection<Object> col = (Collection<Object>) obj;
final Set<Object> set = new HashSet<>();
for (Object o: col) {
if (!set.add(o)) {
throw new IllegalArgumentException("Can specify each argument at most once for " + field.getName() +
" but " + o + "is specified more than once");
}
}
});
}
public static boolean isUsedAtDuplexGrouping(String key) {
try {
Field f = Parameters.class.getDeclaredField(key);
return f.getAnnotation(UsedAtDuplexGrouping.class) != null;
} catch (NoSuchFieldException e) {
throw new RuntimeException(e);
}
}
@FunctionalInterface
private static interface ThrowingFieldValueBiConsumer {
void accept(Field field, Object fieldValue) throws IllegalArgumentException, IllegalAccessException;
}
private void iterateFields(ThrowingFieldValueBiConsumer consumer) {
for (Field field: Parameters.class.getDeclaredFields()) {
try {
consumer.accept(field, field.get(this));
} catch (IllegalArgumentException | IllegalAccessException e) {
throw new RuntimeException(e);
}
}
}
@HideInToString
@JsonIgnore
public transient MutinackGroup group;
public Map<String, Object> distinctParameters = new HashMap<>();
public static final long serialVersionUID = 1L;
@JsonIgnore
private static final boolean hideInProgressParameters = true;
@JsonIgnore
private static final boolean hideAdvancedParameters = true;
@Parameter(names = {"-help", "--help"}, help = true, description = "Display this message and return")
@HideInToString
@JsonIgnore
public boolean help;
@Parameter(names = {"-version", "--version"}, help = true, description = "Display version information and return")
@HideInToString
@JsonIgnore
public boolean version;
@Parameter(names = "-noStatusMessages", description = "Do not output any status information on stderr or stdout", required = false)
@HideInToString
public boolean noStatusMessages = false;
@Parameter(names = "-skipVersionCheck", description = "Do not check whether update is available for download", required = false)
@HideInToString
@JsonIgnore
public boolean skipVersionCheck = false;
@Parameter(names = "-verbosity", description = "0: main mutation detection results only; 3: open the firehose", required = false)
public int verbosity = 0;
@Parameter(names = "-suppressStderrOutput", description = "Only partially implemented so far", required = false)
public boolean suppressStderrOutput = false;
@Parameter(names = "-runBatchName", description = "User-defined string to identify batch to which this run belongs",
required = false)
public String runBatchName = "";
@Parameter(names = "-outputToDatabaseURL", description = "Formatted e.g. as jdbc:postgresql://localhost/mutinack_test_db",
required = false)
public String outputToDatabaseURL = "jdbc:postgresql://localhost/mutinack_test_db";
@Parameter(names = "-outputToDatabaseUserName", description = "",
required = false)
public String outputToDatabaseUserName = "testuser3";
@Parameter(names = "-outputToDatabaseUserPassword", description = "",
required = false)
public @NotPersistent String outputToDatabaseUserPassword = "testpassword34";
@FilePath
@Parameter(names = "-outputJSONTo", description = "Path to which JSON-formatted output should be written",
required = false)
public @Column(length = 1_000) String outputJSONTo = "";
@Parameter(names = "-outputDuplexDetails", description = "For each reported mutation, give list of its reads and duplexes", required = false)
public boolean outputDuplexDetails = false;
@Parameter(names = "-parallelizationFactor", description = "Number of chunks into which to split each contig for parallel processing; setting this value too high can be highly counter-productive", required = false)
public int parallelizationFactor = 1;
@Parameter(names = "-contigByContigParallelization", description = "Contig-by-contig list of number of chunks into which to split contig for parallel processing; setting this value too high can be highly counter-productive; last value in the list applies to all contigs whose index falls outside of the list", required = false)
public List<Integer> contigByContigParallelization = new ArrayList<>();
@Parameter(names = "-maxThreadsPerPool", description = "Maximum number of threads per pool;" +
" for now, to avoid deadlocks this number should be kept higher than number of inputs *" +
" number of contigs * parallelization factor", required = false)
public int maxThreadsPerPool = 64;
@Parameter(names = "-maxParallelContigs", description = "JVM-wide maximum number of concurrently analyzed contigs; first call sets final value", required = false)
public int maxParallelContigs = 30;
@Parameter(names = "-terminateImmediatelyUponError", description = "If true, any error causes immediate termination of the run", required = false)
public boolean terminateImmediatelyUponError = true;
@Parameter(names = "-terminateUponOutputFileError", description = "If true, any error in writing auxiliary output files causes termination of the run", required = false)
public boolean terminateUponOutputFileError = true;
@Parameter(names = "-processingChunk", description = "Size of sliding windows used to synchronize analysis in different samples", required = false)
public int processingChunk = 160;
@FilePathList
@NoDuplicates
@Parameter(names = "-inputReads", description = "Input BAM read file, sorted and with an index; repeat as many times as there are samples", required = true)
public List<@NonNull String> inputReads = new ArrayList<>();
@Parameter(names = "-computeHashForBAMSmallerThanInGB", description = "A simple hash will be computed for all input BAM files whose size is below specified threshold (in GB)", required = false)
public float computeHashForBAMSmallerThanInGB = 0.5f;
@Parameter(names = "-lenientSamValidation",description = "Passed to Picard; seems at least sometimes necessary for" +
" alignments produced by BWA", required = false)
public boolean lenientSamValidation = true;
@FilePathList
@NoDuplicates
@Parameter(names = "-originalReadFile1", description = "Fastq-formatted raw read data", required = false, hidden = true)
public List<@NonNull String> originalReadFile1 = new ArrayList<>();
@FilePathList
@NoDuplicates
@Parameter(names = "-originalReadFile2", description = "Fastq-formatted raw read data", required = false, hidden = true)
public List<@NonNull String> originalReadFile2 = new ArrayList<>();
@Parameter(names = "-nRecordsToProcess", description = "Only process first N reads", required = false)
public long nRecordsToProcess = Long.MAX_VALUE;
@Parameter(names = "-dropReadProbability", description = "Reads will be randomly ignored with a probability given by this number")
public float dropReadProbability = 0;
@Parameter(names = "-randomizeMates", description = "Randomize first/second of pair; WARNING: this will lead to incorrect top/bottom strand grouping")
public boolean randomizeMates = false;
@UsedAtDuplexGrouping
@Parameter(names = "-randomizeStrand", description = "Randomize read mapping to top or bottom strand, preserving for each duplex" +
" the number in the top strand and the number in the bottom strand; WARNING: this will lead to incorrect mutation and disagreement detection")
public boolean randomizeStrand = false;
@FilePathList
@NoDuplicates
@Parameter(names = "-intersectAlignment", description = "List of BAM files with which alignments in inputReads must agree; each file must be sorted", required = false, hidden = hideInProgressParameters)
public List<@NonNull String> intersectAlignment = new ArrayList<>();
@Parameter(names = "-minMappingQIntersect", description = "Minimum mapping quality for reads in intersection files", required = false, hidden = hideInProgressParameters)
public List<Integer> minMappingQIntersect = new ArrayList<>();
@FilePath
@Parameter(names = "-referenceGenome", description = "Reference genome in FASTA format; index file must be present",
required = true)
public @Column(length = 1_000) String referenceGenome = "";
@Parameter(names = "-referenceGenomeShortName", description = "e.g. ce10, hg19, etc.", required = true)
public String referenceGenomeShortName = "";
@Parameter(names = "-contigNamesToProcess", description =
"Reads not mapped to any of these contigs will be ignored")
@NoDuplicates
@NonNull List<@NonNull String> contigNamesToProcess =
Arrays.asList("chrI", "chrII", "chrIII", "chrIV", "chrV", "chrX", "chrM");
{
Collections.sort(contigNamesToProcess);
}
@Parameter(names = "-startAtPosition", description = "Formatted as chrI:12,000,000 or chrI:12000000; specify up to once per contig", required = false,
converter = SwallowCommasConverter.class, listConverter = SwallowCommasConverter.class)
public List<@NonNull String> startAtPositions = new ArrayList<>();
@Parameter(names = "-stopAtPosition", description = "Formatted as chrI:12,000,000 or chrI:12000000; specify up to once per contig", required = false,
converter = SwallowCommasConverter.class, listConverter = SwallowCommasConverter.class)
public List<@NonNull String> stopAtPositions = new ArrayList<>();
@Parameter(names = "-readContigsFromFile", description = "Read contig names from reference genome file")
public boolean readContigsFromFile = false;
@Parameter(names = "-traceField", description = "Output each position at which" +
" specified statistic is incremented; formatted as sampleName:statisticName", required = false)
@NoDuplicates
public List<String> traceFields = new ArrayList<>();
@Parameter(names = "-contigStatsBinLength", description = "Length of bin to use for statistics that" +
" are broken down more finely than contig by contig", required = false)
public int contigStatsBinLength = 2_000_000;
@Parameter(names = "-reportCoverageAtAllPositions", description = "Report key coverage statistics at every position analyzed; do not use when analyzing large regions!", arity = 1)
public boolean reportCoverageAtAllPositions = false;
@Parameter(names = "-minMappingQualityQ1", description = "Reads whose mapping quality is below this" +
" threshold are discarded (best to keep this relatively low to allow non-unique mutation candidates to be identified in all samples)", required = false)
public int minMappingQualityQ1 = 20;
@Parameter(names = "-minMappingQualityQ2", description = "Reads whose mapping quality is below this" +
" threshold are not used to propose Q2 mutation candidates", required = false)
@OnlyUsedAfterDuplexGrouping
@ExplorationIncompatibleWithRawMismatches
public int minMappingQualityQ2 = 50;
@Parameter(names = "-minReadsPerStrandQ1", description = "Duplexes that have fewer reads for the" +
" original top and bottom strands are ignored when calling substitutions or indels", required = false)
@OnlyUsedAfterDuplexGrouping
public int minReadsPerStrandQ1 = 0;
@Parameter(names = "-minReadsPerStrandQ2", description = "Only duplexes that have at least this number of reads" +
" for original top and bottom strands can contribute Q2 candidates", required = false)
@OnlyUsedAfterDuplexGrouping
public int minReadsPerStrandQ2 = 3;
@Parameter(names = "-minReadsPerDuplexQ2", description = "Only duplexes that have at least this total number of reads" +
" (irrespective of whether they come from the original top and bottom strands) can contribute Q2 candidates", required = false)
@OnlyUsedAfterDuplexGrouping
public int minReadsPerDuplexQ2 = 3;
@Parameter(names = "-candidateQ2Criterion", description = "Must be one of 1Q2Duplex, NQ1Duplexes", required = false)
@OnlyUsedAfterDuplexGrouping
public String candidateQ2Criterion = "1Q2Duplex";
@Parameter(names = "-minQ1Duplexes", description = "Allow mutation candidate to be Q2 when it has at least this many Q1 duplexes", required = false, hidden = true)
@OnlyUsedAfterDuplexGrouping
public int minQ1Duplexes = Integer.MAX_VALUE;
/*@Parameter(names = "-promoteNSingleStrands", description = "Not yet functional, and probably never will be - Promote duplex that has just 1 original strand but at least this many reads to Q1", required = false, hidden = true)
public int promoteNSingleStrands = Integer.MAX_VALUE;
@Parameter(names = "-promoteFractionReads", description = "Promote candidate supported by at least this fraction of reads to Q2", required = false, hidden = hideAdvancedParameters)
public float promoteFractionReads = Float.MAX_VALUE;*/
@Parameter(names = "-minConsensusThresholdQ1", description = "Lenient value for minimum fraction of reads from the same" +
" original strand that define a consensus (must be > 0.5)", required = false)
@OnlyUsedAfterDuplexGrouping
public float minConsensusThresholdQ1 = 0.51f;
@Parameter(names = "-minConsensusThresholdQ2", description = "Strict value for minimum fraction of reads from the same" +
" original strand that define a consensus (must be > 0.5)", required = false)
@OnlyUsedAfterDuplexGrouping
public float minConsensusThresholdQ2 = 0.95f;
@Parameter(names = "-disagreementConsensusThreshold", description = "NOT YET IMPLEMENTED; Disagreements are only reported if for each strand" +
" consensus is above this threshold, in addition to being above minConsensusThresholdQ2", required = false, hidden = true)
public float disagreementConsensusThreshold = 0.0f;
@Parameter(names = "-minReadsPerStrandForDisagreement", description = "Minimal number of reads" +
" for original top and bottom strands to examine duplex for disagreement between these strands", required = false)
@OnlyUsedAfterDuplexGrouping
public int minReadsPerStrandForDisagreement = 0;
@Parameter(names = "-Q2DisagCapsMatchingMutationQuality", description = "Q2 disagreement in the same sample or in sister sample caps to Q1 the quality of matching, same-position mutations from other duplexes", required = false, arity = 1)
@OnlyUsedAfterDuplexGrouping
public boolean Q2DisagCapsMatchingMutationQuality = true;
@Parameter(names = "-computeRawMismatches", description = "Compute mismatches between raw reads and reference sequence", arity = 1, required = false)
public boolean computeRawMismatches = true;
@Parameter(names = "-topAlleleFreqReport", description = "Sites at which the top allele frequency is below this value divided by 10 are reported and marked with a % sign", required = false)
public int topAlleleFreqReport = 3;
@Parameter(names = "-minBasePhredScoreQ1", description = "Bases whose Phred quality score is below this threshold" +
" are discarded (keeping this relatively low helps identify problematic reads)", required = false)
public int minBasePhredScoreQ1 = 20;
@Parameter(names = "-minBasePhredScoreQ2", description = "Bases whose Phred quality score is below this threshold are not used to propose Q2 mutation candidates",
required = false)
@OnlyUsedAfterDuplexGrouping
@ExplorationIncompatibleWithRawMismatches
public int minBasePhredScoreQ2 = 30;
@Parameter(names = "-ignoreFirstNBasesQ1", description = "Bases that occur within this many bases of read start are discarded", required = false)
public int ignoreFirstNBasesQ1 = 4;
@Parameter(names = "-ignoreFirstNBasesQ2", description = "Bases that occur within this many bases of read start are not used to propose Q2 mutation candidates", required = false)
@OnlyUsedAfterDuplexGrouping
@ExplorationIncompatibleWithRawMismatches
public int ignoreFirstNBasesQ2 = 35;
@Parameter(names = "-ignoreLastNBases", description = "Potential mutations that occur within this many bases of read end are ignored", required = false)
public int ignoreLastNBases = 4;
@Parameter(names = "-minReadMedianPhredScore", description = "Reads whose median Phred quality score is below this threshold are discarded", required = false)
public int minReadMedianPhredScore = 0;
@Parameter(names = "-minMedianPhredQualityAtPosition", description = "Positions whose median Phred quality score is below this threshold are not used to propose Q2 mutation candidates", required = false)
@OnlyUsedAfterDuplexGrouping
public int minMedianPhredQualityAtPosition = 0;
@Parameter(names = "-maxFractionWrongPairsAtPosition", description = "Positions are not used to propose Q2 mutation candidates if the fraction of reads covering the position that have an unmapped mate or a mate that forms a wrong pair orientation (RF, Tandem) is above this threshold", required = false)
public float maxFractionWrongPairsAtPosition = 1.0f;
@Parameter(names = "-maxAverageBasesClipped", description = "Duplexes whose mean number of clipped bases is above this threshold are not used to propose Q2 mutation candidates",
required = false)
@UsedAtDuplexGrouping
@ExplorationIncompatibleWithRawMismatches
public int maxAverageBasesClipped = 15;
@Parameter(names = "-maxAverageClippingOfAllCoveringDuplexes", description = "Positions whose average covering duplex average number of clipped bases is above this threshold are not used to propose Q2 mutation candidates",
required = false)
@OnlyUsedAfterDuplexGrouping
public int maxAverageClippingOfAllCoveringDuplexes = 999;
@Parameter(names = "-maxNDuplexes", description = "Positions whose number of Q1 or Q2 duplexes is above this threshold are ignored when computing mutation rates",
required = false)
public List<Integer> maxNDuplexes = new ArrayList<>();
@Parameter(names = "-maxInsertSize", description = "Inserts above this size are not used to propose Q2 mutation candidates, and will most of the time be ignored when identifying Q1 candidates", required = false)
public int maxInsertSize = 1_000;
@Parameter(names = "-minInsertSize", description = "Inserts below this size are not used to propose Q2 mutation candidates", required = false)
public int minInsertSize = 0;
@Parameter(names = "-ignoreZeroInsertSizeReads", description = "Reads 0 or undefined insert size are thrown out at the onset (and thus cannot contribute to exclusion of mutation candidates found in multiple samples)", required = false)
public boolean ignoreZeroInsertSizeReads = false;
@Parameter(names = "-ignoreSizeOutOfRangeInserts", description = "Reads with insert size out of range are thrown out at the onset (and thus cannot contribute to exclusion of mutation candidates found in multiple samples)", required = false)
public boolean ignoreSizeOutOfRangeInserts = false;
@Parameter(names = "-ignoreTandemRFPairs", description = "Read pairs that form tandem or RF are thrown out at the onset", required = false)
public boolean ignoreTandemRFPairs = false;
@Parameter(names = "-minNumberDuplexesSisterArm", description = "Min number of duplexes in sister arm to call a candidate mutation unique; adjust this number to deal with heterozygous mutations", required = false)
@OnlyUsedAfterDuplexGrouping
public int minNumberDuplexesSisterArm = 10;
@Parameter(names = "-minQ2DuplexesToCallMutation", description = "Min number of Q2 duplexes to call mutation (condition set by minQ1Q2DuplexesToCallMutation must also be met)", required = false)
@OnlyUsedAfterDuplexGrouping
public int minQ2DuplexesToCallMutation = 1;
@Parameter(names = "-minQ1Q2DuplexesToCallMutation", description = "Min number of Q1 or Q2 duplexes to call mutation (condition set by minQ2DuplexesToCallMutation must also be met)", required = false)
@OnlyUsedAfterDuplexGrouping
public int minQ1Q2DuplexesToCallMutation = 1;
@Parameter(names = "-acceptNInBarCode", description = "If true, an N read within the barcode is" +
" considered a match", required = false)
public boolean acceptNInBarCode = true;
@Parameter(names = "-variableBarcodeLength", description = "Length of variable barcode, irrespective of whether it has been removed from the aligned sequences", required = false)
public int variableBarcodeLength = 3;
@Parameter(names = "-constantBarcode", description = "Used to only analyze reads whose constant barcode matches expected value", required = false)
public @NonNull String constantBarcode = "TCT";
@Parameter(names = "-nVariableBarcodeMismatchesAllowed", description = "Used for variable barcode matching", required = false)
public int nVariableBarcodeMismatchesAllowed = 1;
@Parameter(names = "-nConstantBarcodeMismatchesAllowed", description = "Used for constant barcode matching", required = false)
public int nConstantBarcodeMismatchesAllowed = 3;
@Parameter(names = "-alignmentPositionMismatchAllowed", description = "Reads assigned to same duplex must have alignment positions match within this tolerance (see also parameter requireMatchInAlignmentEnd)", required = false)
public int alignmentPositionMismatchAllowed = 0;
@Parameter(names = "-requireMatchInAlignmentEnd", description = "Used while grouping reads into duplexes; turn off if alignments were aggregated from sequencing runs with different read lengths", required = false)
public boolean requireMatchInAlignmentEnd = false;
@FilePathList
@NoDuplicates
@Parameter(names = "-saveFilteredReadsTo", description = "Not implemented; write raw reads that were kept for analysis to specified files", required = false, hidden = hideInProgressParameters)
public List<@NonNull String> saveFilteredReadsTo = new ArrayList<>();
@Parameter(names = "-collapseFilteredReads", description = "Only write one (randomly-chosen) read per duplex strand", required = false, hidden = false)
public boolean collapseFilteredReads = false;
@FilePathList
@NoDuplicates
@Parameter(names = "-bamReadsWithBarcodeField", description = "Unimplemented; BAM/SAM file saved from previous run with barcodes stored as attributes", required = false, hidden = hideInProgressParameters)
public List<@NonNull String> bamReadsWithBarcodeField = new ArrayList<>();
@Parameter(names = "-saveRawReadsDB", description = "Not functional at present", required = false, arity = 1, hidden = hideInProgressParameters)
public boolean saveRawReadsDB = false;
@Parameter(names = "-saveRawReadsMVDB", description = "Not functional at present", required = false, arity = 1, hidden = hideInProgressParameters)
public boolean saveRawReadsMVDB = false;
@Parameter(names = "-outputCoverageBed", description = "Output bed file that gives number of duplexes covering each position in the reference sequence;" +
" note that this is a highly-inefficient format that creates a huge file", required = false)
public boolean outputCoverageBed = false;
@Parameter(names = "-outputCoverageProto", description = "Output protobuf file that gives number of duplexes covering each position in the reference sequence",
required = false)
public boolean outputCoverageProto = false;
/**
* Output section
*/
@NoDuplicates
@Parameter(names = "-sampleName", description = "Used to name samples in output file; can be repeated as many times as there are inputReads", required = false)
List<@NonNull String> sampleNames = new ArrayList<>();
@FilePathList
@NoDuplicates
@Parameter(names = "-forceOutputAtPositionsFile", description = "Detailed information is reported for all positions listed in the file", required = false)
public List<@NonNull String> forceOutputAtPositionsFile = new ArrayList<>();
@Parameter(names = "-forceOutputAtPositions", description = "Detailed information is reported for positions given as ranges", required = false,
converter = SwallowCommasConverter.class, listConverter = SwallowCommasConverter.class)
public @NoDuplicates List<@NonNull String> forceOutputAtPositions = new ArrayList<>();
@FilePath
@Parameter(names = "-annotateMutationsInFile", description = "TODO", required = false)
public @Column(length = 1_000) String annotateMutationsInFile = null;
@FilePath
@Parameter(names = "-annotateMutationsOutputFile", description = "TODO", required = false)
public @Column(length = 1_000) String annotateMutationsOutputFile = null;
@Parameter(names = "-randomOutputRate", description = "Randomly choose genome positions at this rate to include in output", required = false)
public float randomOutputRate = 0;
@FilePath
@Parameter(names = "-outputAlignmentFile", description = "Write BAM output with duplex information provided in custom tags;" +
" note that a read may be omitted from the output, e.g. if it falls below a Q1 threshold (it is" +
" relatively rare but possible for a read to be omitted even though it counts toward coverage).", required = false)
public @Column(length = 1_000) String outputAlignmentFile = null;
@FilePath
@Parameter(names = "-discardedReadFile", description = "Write discarded reads to BAM file specified by parameter", required = false, hidden = hideInProgressParameters)
public @Column(length = 1_000) String discardedReadFile = null;
@Parameter(names = "-logReadIssuesInOutputBam", description = "Use custom fields in output BAM to give reasons why duplexes as a whole or individual bases did not reach maximum quality", required = false, arity = 1)
public boolean logReadIssuesInOutputBam = true;
@Parameter(names = "-sortOutputAlignmentFile", description = "Sort BAM file; can require a large amount of memory", required = false, arity = 1)
public boolean sortOutputAlignmentFile = false;
@Parameter(names = "-outputTopBottomDisagreementBED", description = "Output to file specified by option -topBottomDisagreementFileBaseName", required = false, arity = 1)
public boolean outputTopBottomDisagreementBED = true;
@FilePathList
@NoDuplicates
@Parameter(names = "-reportStatsForBED", description = "Report number of observations that fall within" +
" the union of regions listed by BED file whose path follows", required = false)
public List<@NonNull String> reportStatsForBED = new ArrayList<>();
@FilePathList
@NoDuplicates
@Parameter(names = "-reportStatsForNotBED", description = "Report number of observations that do *not* fall within" +
" the union of regions listed by BED file whose path follows", required = false)
public List<@NonNull String> reportStatsForNotBED = new ArrayList<>();
@FilePathList
@NoDuplicates
@Parameter(names = "-excludeRegionsInBED", description = "Positions covered by this BED file will be completely ignored in the analysis", required = false)
public List<@NonNull String> excludeRegionsInBED = new ArrayList<>();
@FilePathList
@NoDuplicates
@Parameter(names = "-repetiveRegionBED", description = "If specified, used for stats (mutant|wt)Q2CandidateQ1Q2DCoverage[Non]Repetitive", required = false)
public List<@NonNull String> repetiveRegionBED = new ArrayList<>();
@FilePath
@Parameter(names = "-bedDisagreementOrienter", description = "Gene orientation read from this file" +
" is used to orient top/bottom strand disagreements with respect to transcribed strand", required = false)
public @Column(length = 1_000) String bedDisagreementOrienter = null;
@FilePathList
@NoDuplicates
@Parameter(names = "-reportBreakdownForBED", description = "Report number of observations that fall within" +
" each of the regions defined by BED file whose path follows", required = false)
public List<@NonNull String> reportBreakdownForBED = new ArrayList<>();
@FilePathList
@NoDuplicates
@Parameter(names = "-saveBEDBreakdownTo", description = "Path for saving of BED region counts; argument " +
" list must match that given to -reportBreakdownForBED", required = false)
public List<@NonNull String> saveBEDBreakdownTo = new ArrayList<>();
@FilePath
@Parameter(names = "-bedFeatureSuppInfoFile", description = "Read genome annotation supplementary info, used in output of counter with BED feature breakdown")
public @Column(length = 1_000) String bedFeatureSuppInfoFile = null;
@FilePath
@Parameter(names = "-refSeqToOfficialGeneName", description = "Tab separated text file with RefSeq ID, tab, and official gene name and any other useful info; " +
"counts will be reported both by RefSeq ID and official gene name")
public @Column(length = 1_000) String refSeqToOfficialGeneName = null;
@FilePath
@Parameter(names = "-auxOutputFileBaseName", description = "Base name of files to which to record mutations, disagreements between top and bottom strands, etc.", required = false)
public @Column(length = 1_000) String auxOutputFileBaseName = null;
public String jsonFilePathExtraPrefix = "";
@Parameter(names = "-rnaSeq", description = "Ignore deletions and turn off checks that do not make sense for RNAseq data", required = false)
public boolean rnaSeq = false;
@Parameter(names = "-submitToServer", description = "RMI address", required = false, hidden = hideInProgressParameters)
public String submitToServer = null;
@Parameter(names = "-writePIDPath", description = "Write PID to this file when ready", required = false, hidden = hideInProgressParameters)
public String writePIDPath = null;
@Parameter(names = "-startServer", help = true, description = "RMI address", required = false, hidden = hideInProgressParameters)
public String startServer = null;
@Parameter(names = "-startWorker", help = true, description = "RMI server address", required = false, hidden = hideInProgressParameters)
public String startWorker = null;
@Parameter(names = "-timeoutSeconds", help = true, description = "If this many seconds elapse without ping from worker, worker is considered dead", required = false, hidden = hideInProgressParameters)
public int timeoutSeconds = 0;
@FilePath
@Parameter(names = "-workingDirectory", help = true, description = "Evaluate parameter file paths using specified directory as workind directory", required = false, hidden = hideAdvancedParameters)
public @Column(length = 1_000) String workingDirectory = null;
@FilePath
@Parameter(names = "-referenceOutput", description = "Path to reference output to be used for functional tests", required = false, hidden = hideAdvancedParameters)
public @Column(length = 1_000) String referenceOutput = null;
@FilePath
@Parameter(names = "-recordRunsTo", description = "Get server to output a record of all runs it processed, to be replayed for functional tests", required = false, hidden = hideAdvancedParameters)
public @Column(length = 1_000) String recordRunsTo = null;
@Parameter(names = "-runName", description = "Name of run to be used in conjunction with -recordRunsTo", required = false, hidden = hideAdvancedParameters)
public String runName = null;
@Parameter(names = "-enableCostlyAssertions", description = "Enable internal sanity checks that significantly slow down execution", required = false, arity = 1)
public boolean enableCostlyAssertions = true;
@Parameter(names = "-randomSeed", description = "TODO", required = false, hidden = hideAdvancedParameters)
public long randomSeed = new SecureRandom().nextLong();
@Parameter(names = "-keysFile", description = "Location of .jks file for RMI SSL encryption", required = false, hidden = hideAdvancedParameters)
public String keysFile = "mutinack_public_selfsigned.jks";
@Parameter(names = "-exploreParameter", description = "", required = false, hidden = true)
public @NoDuplicates List<String> exploreParameters = new ArrayList<>();
@Parameter(names = "-cartesianProductOfExploredParameters", description = "", required = false, hidden = true, arity = 1)
public boolean cartesianProductOfExploredParameters = true;
@Parameter(names = "-includeInsertionsInParamExploration", description = "", required = false, hidden = true, arity = 1)
public boolean includeInsertionsInParamExploration = false;
@Retention(RetentionPolicy.RUNTIME)
/**
* Used to mark parameters that it is not useful to print in toString method.
* @author olivier
*
*/
public @interface HideInToString {}
@Retention(RetentionPolicy.RUNTIME)
public @interface OnlyUsedAfterDuplexGrouping {}
@Retention(RetentionPolicy.RUNTIME)
public @interface ExplorationIncompatibleWithRawMismatches {}
@Retention(RetentionPolicy.RUNTIME)
public @interface UsedAtDuplexGrouping {}
@Retention(RetentionPolicy.RUNTIME)
private @interface NoDuplicates {}
@Retention(RetentionPolicy.RUNTIME)
public @interface FilePath {}
@Retention(RetentionPolicy.RUNTIME)
public @interface FilePathList {}
public void canonifyFilePaths() {
transformFilePaths(s -> {
try {
File f = new File(s);
String canonical = f.getCanonicalPath();
if (f.isDirectory()) {
return canonical + "/";
} else {
return canonical;
}
} catch (IOException e) {
throw new RuntimeException(e);
}
});
}
public void transformFilePaths(Function<String, String> transformer) {
iterateFields((field, fieldValue) -> {
if (fieldValue == null) {
return;
}
if (field.getAnnotation(FilePath.class) != null) {
Assert.isTrue(fieldValue instanceof String, "Field %s not string", field);
String path = (String) fieldValue;
String transformed = transformer.apply(path);
field.set(this, transformed);
} else if (field.getAnnotation(FilePathList.class) != null) {
Assert.isTrue(fieldValue instanceof List, "Field %s not list", field);
@SuppressWarnings("unchecked")
List<String> paths = (List<String>) fieldValue;
for (int i = 0; i < paths.size(); i++) {
String path = paths.get(i);
String transformed = transformer.apply(path);
paths.set(i, transformed);
}
}
});
}
/**
* Used to make JCommander ignore commas in genome locations.
* @author olivier
*
*/
public static class SwallowCommasConverter extends BaseConverter<String> implements IStringConverter<String> {
public SwallowCommasConverter(String optionName) {
super(optionName);
}
@Override
public String convert(String value) {
return value.replaceAll(",", "");
}
}
@HideInToString
@JsonIgnore
private static final Parameters defaultValues = new Parameters();
private static final Set<String> fieldsToIgnore = new HashSet<>();
static {
fieldsToIgnore.add("$jacocoData");
fieldsToIgnore.add("dnFieldFlags");
fieldsToIgnore.add("dnFieldTypes");
fieldsToIgnore.add("dnFieldNames");
}
@Override
public String toString() {
String defaultValuesString = "";
String nonDefaultValuesString = "";
for (Field field: Parameters.class.getDeclaredFields()) {
try {
field.setAccessible(true);
if (field.getAnnotation(HideInToString.class) != null)
continue;
if (fieldsToIgnore.contains(field.getName())) {
continue;
}
Object fieldValue = field.get(this);
Object fieldDefaultValue = field.get(defaultValues);
String stringValue;
if (fieldValue == null)
stringValue = field.getName() + " = null";
else {
Method toStringMethod = fieldValue.getClass().getMethod("toString");
toStringMethod.setAccessible(true);
stringValue = field.getName() + " = " + toStringMethod.invoke
(fieldValue);
}
final boolean fieldHasDefaultValue;
if (fieldValue == null) {
fieldHasDefaultValue = fieldDefaultValue == null;
} else {
Method equalsMethod = fieldValue.getClass().getMethod("equals", Object.class);
equalsMethod.setAccessible(true);
fieldHasDefaultValue = (Boolean) equalsMethod.invoke(fieldValue, fieldDefaultValue);
}
if (fieldHasDefaultValue) {
defaultValuesString += "Default parameter value: " + stringValue + "\n";
} else {
nonDefaultValuesString += "Non-default parameter value: " + stringValue + "\n";
}
} catch (IllegalArgumentException | IllegalAccessException |
InvocationTargetException | NoSuchMethodException | SecurityException e) {
throw new RuntimeException(e);
}
}
return "Working directory: " + System.getProperty("user.dir") + "\n" +
nonDefaultValuesString + "\n" + defaultValuesString + "\n";
}
public Object getFieldValue(String name) {
try {
Field f = Parameters.class.getDeclaredField(name);
return f.get(this);
} catch (NoSuchFieldException | SecurityException | IllegalArgumentException |
IllegalAccessException e) {
throw new RuntimeException(e);
}
}
public boolean isParameterInstanceOf(String name, Class<?> clazz) {
Field f;
try {
f = Parameters.class.getDeclaredField(name);
return clazz.isInstance(f.get(this));
} catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e) {
throw new RuntimeException(e);
}
}
public void setFieldValue(String name, Object value) {
try {
Field f = Parameters.class.getDeclaredField(name);
if (f.get(this) instanceof Integer) {
f.set(this, ((Number) value).intValue());
} else if (f.get(this) instanceof Float) {
f.set(this, ((Number) value).floatValue());
} else if (f.get(this) instanceof Boolean) {
f.set(this, value);
} else
throw new IllegalArgumentException("Field " + name + " is not Integer, Float, or Boolean");
} catch (ClassCastException e) {
throw new RuntimeException("Class of " + " value " + " does not match field " + name, e);
} catch (NoSuchFieldException | SecurityException | IllegalArgumentException |
IllegalAccessException e) {
throw new RuntimeException(e);
}
}
public static List<String> differingFields(Parameters obj1, Parameters obj2) {
List<String> result = new ArrayList<>();
for (Field field: Parameters.class.getDeclaredFields()) {
try {
if (field.getAnnotation(HideInToString.class) != null)
continue;
if (field.getName().equals("$jacocoData")) {
continue;
}
if (!Objects.equals(field.get(obj1), field.get(obj2))) {
result.add(field.getName());
}
} catch (IllegalArgumentException | IllegalAccessException | SecurityException e) {
throw new RuntimeException(e);
}
}
return result;
}
public static Set<String> differingFields(List<Parameters> list) {
Set<String> result = new HashSet<>();
for (int i = list.size() - 1; i >= 0; i
for (int j = 0; j < i; j++) {
result.addAll(differingFields(list.get(i), list.get(j)));
}
}
return result;
}
public static void getUnsortedUsage(JCommander jc, Class<?> paramClass, StringBuilder out)
throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
List<@NonNull Field> fields = Arrays.asList(paramClass.getDeclaredFields());
// Special treatment of main parameter.
ParameterDescription mainParam = jc.getMainParameter();
if (mainParam != null) {
out.append("Required parameters:\n");
out.append(" ").append(mainParam.getDescription()).append('\n');
}
@SuppressWarnings("null")
String requiredParams = fields.stream().map(f -> f.getAnnotation(Parameter.class)).
filter(a -> a != null).
filter(a -> (!a.hidden()) && a.required()).map(a -> a.names()[0]).
collect(Collectors.joining(", "));
if (! "".equals(requiredParams)) {
out.append("Required parameters: " + requiredParams + " (see explanations marked with *** below)\n");
}
out.append("Options:\n");
List<ParameterDescription> params = jc.getParameters();
final Field getWrapperParameter = ParameterDescription.class.getDeclaredField("m_wrappedParameter");
getWrapperParameter.setAccessible(true);
for (Field f: fields) {
boolean required = false;
Parameter annotation = f.getAnnotation(Parameter.class);
if (annotation != null) {
if (annotation.hidden()) {
continue;
}
if (annotation.required()) {
required = true;
}
} else {
continue;
}
int nIt = 0;
Handle<String> suffix = new Handle<>("");
outer:
while (true) {
if (nIt == 1) {
suffix.set("s");
} else if (nIt == 2) {
throw new RuntimeException("Could not find field annotation for " + f.getName());
}
nIt++;
for (ParameterDescription p: params) {
List<String> names = Arrays.asList(((WrappedParameter) getWrapperParameter.get(p)).names()).stream().map(
s -> s.substring(1) + suffix.get()).collect(Collectors.toList());
if (names.contains(f.getName())) {
out.append(p.getNames()).append('\n');
String def = (required ? "\nRequired parameter" : (p.getDefault() == null ? "" : ("\nDefault: " +
p.getDefault().toString().trim() + '.'))) + "\n";
String desc = wordWrap(p.getDescription(), 75) + def;
desc = " " + desc;
desc = desc.replaceAll("\n", "\n ") + '\n';
desc = desc.replaceAll(" Required parameter", "**** Required parameter");
out.append(desc);
break outer;
}
}
}
}
}
/**
* Copied from StackOverflow
* @param s String without pre-existing line breaks
* @param nColumns
* @return
*/
private static String wordWrap(String s, int nColumns) {
StringBuilder sb = new StringBuilder(s);
int i = 0;
while (i + nColumns < sb.length() && (i = sb.lastIndexOf(" ", i + nColumns)) != -1) {
sb.replace(i, i + 1, "\n");
}
return sb.toString();
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + (Q2DisagCapsMatchingMutationQuality ? 1231 : 1237);
result = prime * result + (acceptNInBarCode ? 1231 : 1237);
result = prime * result + alignmentPositionMismatchAllowed;
result = prime * result + ((annotateMutationsInFile == null) ? 0 : annotateMutationsInFile.hashCode());
result = prime * result + ((annotateMutationsOutputFile == null) ? 0 : annotateMutationsOutputFile.hashCode());
result = prime * result + ((auxOutputFileBaseName == null) ? 0 : auxOutputFileBaseName.hashCode());
result = prime * result + ((bamReadsWithBarcodeField == null) ? 0 : bamReadsWithBarcodeField.hashCode());
result = prime * result + ((bedDisagreementOrienter == null) ? 0 : bedDisagreementOrienter.hashCode());
result = prime * result + ((bedFeatureSuppInfoFile == null) ? 0 : bedFeatureSuppInfoFile.hashCode());
result = prime * result + ((candidateQ2Criterion == null) ? 0 : candidateQ2Criterion.hashCode());
result = prime * result + (collapseFilteredReads ? 1231 : 1237);
result = prime * result + (computeRawMismatches ? 1231 : 1237);
result = prime * result + constantBarcode.hashCode();
result = prime * result + ((contigByContigParallelization == null) ? 0 : contigByContigParallelization.hashCode());
result = prime * result + contigNamesToProcess.hashCode();
result = prime * result + contigStatsBinLength;
result = prime * result + Float.floatToIntBits(disagreementConsensusThreshold);
result = prime * result + ((discardedReadFile == null) ? 0 : discardedReadFile.hashCode());
result = prime * result + Float.floatToIntBits(dropReadProbability);
result = prime * result + (enableCostlyAssertions ? 1231 : 1237);
result = prime * result + ((excludeRegionsInBED == null) ? 0 : excludeRegionsInBED.hashCode());
result = prime * result + ((forceOutputAtPositions == null) ? 0 : forceOutputAtPositions.hashCode());
result = prime * result + ((forceOutputAtPositionsFile == null) ? 0 : forceOutputAtPositionsFile.hashCode());
result = prime * result + (help ? 1231 : 1237);
result = prime * result + ignoreFirstNBasesQ1;
result = prime * result + ignoreFirstNBasesQ2;
result = prime * result + ignoreLastNBases;
result = prime * result + (ignoreSizeOutOfRangeInserts ? 1231 : 1237);
result = prime * result + (ignoreTandemRFPairs ? 1231 : 1237);
result = prime * result + (ignoreZeroInsertSizeReads ? 1231 : 1237);
result = prime * result + ((inputReads == null) ? 0 : inputReads.hashCode());
result = prime * result + ((intersectAlignment == null) ? 0 : intersectAlignment.hashCode());
result = prime * result + ((keysFile == null) ? 0 : keysFile.hashCode());
result = prime * result + (lenientSamValidation ? 1231 : 1237);
result = prime * result + (logReadIssuesInOutputBam ? 1231 : 1237);
result = prime * result + maxAverageBasesClipped;
result = prime * result + maxAverageClippingOfAllCoveringDuplexes;
result = prime * result + Float.floatToIntBits(maxFractionWrongPairsAtPosition);
result = prime * result + maxInsertSize;
result = prime * result + ((maxNDuplexes == null) ? 0 : maxNDuplexes.hashCode());
result = prime * result + maxParallelContigs;
result = prime * result + maxThreadsPerPool;
result = prime * result + minBasePhredScoreQ1;
result = prime * result + minBasePhredScoreQ2;
result = prime * result + Float.floatToIntBits(minConsensusThresholdQ1);
result = prime * result + Float.floatToIntBits(minConsensusThresholdQ2);
result = prime * result + minInsertSize;
result = prime * result + ((minMappingQIntersect == null) ? 0 : minMappingQIntersect.hashCode());
result = prime * result + minMappingQualityQ1;
result = prime * result + minMappingQualityQ2;
result = prime * result + minMedianPhredQualityAtPosition;
result = prime * result + minNumberDuplexesSisterArm;
result = prime * result + minQ1Duplexes;
result = prime * result + minQ1Q2DuplexesToCallMutation;
result = prime * result + minQ2DuplexesToCallMutation;
result = prime * result + minReadMedianPhredScore;
result = prime * result + minReadsPerDuplexQ2;
result = prime * result + minReadsPerStrandForDisagreement;
result = prime * result + minReadsPerStrandQ1;
result = prime * result + minReadsPerStrandQ2;
result = prime * result + nConstantBarcodeMismatchesAllowed;
result = prime * result + (int) (nRecordsToProcess ^ (nRecordsToProcess >>> 32));
result = prime * result + nVariableBarcodeMismatchesAllowed;
result = prime * result + (noStatusMessages ? 1231 : 1237);
result = prime * result + ((originalReadFile1 == null) ? 0 : originalReadFile1.hashCode());
result = prime * result + ((originalReadFile2 == null) ? 0 : originalReadFile2.hashCode());
result = prime * result + ((outputAlignmentFile == null) ? 0 : outputAlignmentFile.hashCode());
result = prime * result + (outputCoverageBed ? 1231 : 1237);
result = prime * result + (outputCoverageProto ? 1231 : 1237);
result = prime * result + (outputDuplexDetails ? 1231 : 1237);
result = prime * result + ((outputJSONTo == null) ? 0 : outputJSONTo.hashCode());
result = prime * result + (outputTopBottomDisagreementBED ? 1231 : 1237);
result = prime * result + parallelizationFactor;
result = prime * result + processingChunk;
result = prime * result + Float.floatToIntBits(randomOutputRate);
result = prime * result + (int) (randomSeed ^ (randomSeed >>> 32));
result = prime * result + (randomizeMates ? 1231 : 1237);
result = prime * result + (randomizeStrand ? 1231 : 1237);
result = prime * result + (readContigsFromFile ? 1231 : 1237);
result = prime * result + ((recordRunsTo == null) ? 0 : recordRunsTo.hashCode());
result = prime * result + ((refSeqToOfficialGeneName == null) ? 0 : refSeqToOfficialGeneName.hashCode());
result = prime * result + ((referenceGenome == null) ? 0 : referenceGenome.hashCode());
result = prime * result + ((referenceOutput == null) ? 0 : referenceOutput.hashCode());
result = prime * result + ((repetiveRegionBED == null) ? 0 : repetiveRegionBED.hashCode());
result = prime * result + ((reportBreakdownForBED == null) ? 0 : reportBreakdownForBED.hashCode());
result = prime * result + (reportCoverageAtAllPositions ? 1231 : 1237);
result = prime * result + ((reportStatsForBED == null) ? 0 : reportStatsForBED.hashCode());
result = prime * result + ((reportStatsForNotBED == null) ? 0 : reportStatsForNotBED.hashCode());
result = prime * result + (requireMatchInAlignmentEnd ? 1231 : 1237);
result = prime * result + (rnaSeq ? 1231 : 1237);
result = prime * result + ((runName == null) ? 0 : runName.hashCode());
result = prime * result + ((sampleNames == null) ? 0 : sampleNames.hashCode());
result = prime * result + ((saveBEDBreakdownTo == null) ? 0 : saveBEDBreakdownTo.hashCode());
result = prime * result + ((saveFilteredReadsTo == null) ? 0 : saveFilteredReadsTo.hashCode());
result = prime * result + (saveRawReadsDB ? 1231 : 1237);
result = prime * result + (saveRawReadsMVDB ? 1231 : 1237);
result = prime * result + (skipVersionCheck ? 1231 : 1237);
result = prime * result + (sortOutputAlignmentFile ? 1231 : 1237);
result = prime * result + ((startAtPositions == null) ? 0 : startAtPositions.hashCode());
result = prime * result + ((startServer == null) ? 0 : startServer.hashCode());
result = prime * result + ((startWorker == null) ? 0 : startWorker.hashCode());
result = prime * result + ((stopAtPositions == null) ? 0 : stopAtPositions.hashCode());
result = prime * result + ((submitToServer == null) ? 0 : submitToServer.hashCode());
result = prime * result + (terminateImmediatelyUponError ? 1231 : 1237);
result = prime * result + (terminateUponOutputFileError ? 1231 : 1237);
result = prime * result + timeoutSeconds;
result = prime * result + topAlleleFreqReport;
result = prime * result + ((traceFields == null) ? 0 : traceFields.hashCode());
result = prime * result + variableBarcodeLength;
result = prime * result + verbosity;
result = prime * result + (version ? 1231 : 1237);
result = prime * result + ((workingDirectory == null) ? 0 : workingDirectory.hashCode());
return result;
}
@Override
public Parameters clone() {
try {
return (Parameters) super.clone();
} catch (CloneNotSupportedException e) {
throw new RuntimeException(e);
}
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Parameters other = (Parameters) obj;
if (Q2DisagCapsMatchingMutationQuality != other.Q2DisagCapsMatchingMutationQuality)
return false;
if (acceptNInBarCode != other.acceptNInBarCode)
return false;
if (alignmentPositionMismatchAllowed != other.alignmentPositionMismatchAllowed)
return false;
if (annotateMutationsInFile == null) {
if (other.annotateMutationsInFile != null)
return false;
} else if (!annotateMutationsInFile.equals(other.annotateMutationsInFile))
return false;
if (annotateMutationsOutputFile == null) {
if (other.annotateMutationsOutputFile != null)
return false;
} else if (!annotateMutationsOutputFile.equals(other.annotateMutationsOutputFile))
return false;
if (auxOutputFileBaseName == null) {
if (other.auxOutputFileBaseName != null)
return false;
} else if (!auxOutputFileBaseName.equals(other.auxOutputFileBaseName))
return false;
if (bamReadsWithBarcodeField == null) {
if (other.bamReadsWithBarcodeField != null)
return false;
} else if (!bamReadsWithBarcodeField.equals(other.bamReadsWithBarcodeField))
return false;
if (bedDisagreementOrienter == null) {
if (other.bedDisagreementOrienter != null)
return false;
} else if (!bedDisagreementOrienter.equals(other.bedDisagreementOrienter))
return false;
if (bedFeatureSuppInfoFile == null) {
if (other.bedFeatureSuppInfoFile != null)
return false;
} else if (!bedFeatureSuppInfoFile.equals(other.bedFeatureSuppInfoFile))
return false;
if (candidateQ2Criterion == null) {
if (other.candidateQ2Criterion != null)
return false;
} else if (!candidateQ2Criterion.equals(other.candidateQ2Criterion))
return false;
if (collapseFilteredReads != other.collapseFilteredReads)
return false;
if (computeRawMismatches != other.computeRawMismatches)
return false;
if (!constantBarcode.equals(other.constantBarcode))
return false;
if (contigByContigParallelization == null) {
if (other.contigByContigParallelization != null)
return false;
} else if (!contigByContigParallelization.equals(other.contigByContigParallelization))
return false;
if (!contigNamesToProcess.equals(other.contigNamesToProcess))
return false;
if (contigStatsBinLength != other.contigStatsBinLength)
return false;
if (Float.floatToIntBits(disagreementConsensusThreshold) != Float.floatToIntBits(
other.disagreementConsensusThreshold))
return false;
if (discardedReadFile == null) {
if (other.discardedReadFile != null)
return false;
} else if (!discardedReadFile.equals(other.discardedReadFile))
return false;
if (Float.floatToIntBits(dropReadProbability) != Float.floatToIntBits(other.dropReadProbability))
return false;
if (enableCostlyAssertions != other.enableCostlyAssertions)
return false;
if (excludeRegionsInBED == null) {
if (other.excludeRegionsInBED != null)
return false;
} else if (!excludeRegionsInBED.equals(other.excludeRegionsInBED))
return false;
if (forceOutputAtPositions == null) {
if (other.forceOutputAtPositions != null)
return false;
} else if (!forceOutputAtPositions.equals(other.forceOutputAtPositions))
return false;
if (forceOutputAtPositionsFile == null) {
if (other.forceOutputAtPositionsFile != null)
return false;
} else if (!forceOutputAtPositionsFile.equals(other.forceOutputAtPositionsFile))
return false;
if (help != other.help)
return false;
if (ignoreFirstNBasesQ1 != other.ignoreFirstNBasesQ1)
return false;
if (ignoreFirstNBasesQ2 != other.ignoreFirstNBasesQ2)
return false;
if (ignoreLastNBases != other.ignoreLastNBases)
return false;
if (ignoreSizeOutOfRangeInserts != other.ignoreSizeOutOfRangeInserts)
return false;
if (ignoreTandemRFPairs != other.ignoreTandemRFPairs)
return false;
if (ignoreZeroInsertSizeReads != other.ignoreZeroInsertSizeReads)
return false;
if (inputReads == null) {
if (other.inputReads != null)
return false;
} else if (!inputReads.equals(other.inputReads))
return false;
if (intersectAlignment == null) {
if (other.intersectAlignment != null)
return false;
} else if (!intersectAlignment.equals(other.intersectAlignment))
return false;
if (keysFile == null) {
if (other.keysFile != null)
return false;
} else if (!keysFile.equals(other.keysFile))
return false;
if (lenientSamValidation != other.lenientSamValidation)
return false;
if (logReadIssuesInOutputBam != other.logReadIssuesInOutputBam)
return false;
if (maxAverageBasesClipped != other.maxAverageBasesClipped)
return false;
if (maxAverageClippingOfAllCoveringDuplexes != other.maxAverageClippingOfAllCoveringDuplexes)
return false;
if (Float.floatToIntBits(maxFractionWrongPairsAtPosition) != Float.floatToIntBits(
other.maxFractionWrongPairsAtPosition))
return false;
if (maxInsertSize != other.maxInsertSize)
return false;
if (maxNDuplexes == null) {
if (other.maxNDuplexes != null)
return false;
} else if (!maxNDuplexes.equals(other.maxNDuplexes))
return false;
if (maxParallelContigs != other.maxParallelContigs)
return false;
if (maxThreadsPerPool != other.maxThreadsPerPool)
return false;
if (minBasePhredScoreQ1 != other.minBasePhredScoreQ1)
return false;
if (minBasePhredScoreQ2 != other.minBasePhredScoreQ2)
return false;
if (Float.floatToIntBits(minConsensusThresholdQ1) != Float.floatToIntBits(other.minConsensusThresholdQ1))
return false;
if (Float.floatToIntBits(minConsensusThresholdQ2) != Float.floatToIntBits(other.minConsensusThresholdQ2))
return false;
if (minInsertSize != other.minInsertSize)
return false;
if (minMappingQIntersect == null) {
if (other.minMappingQIntersect != null)
return false;
} else if (!minMappingQIntersect.equals(other.minMappingQIntersect))
return false;
if (minMappingQualityQ1 != other.minMappingQualityQ1)
return false;
if (minMappingQualityQ2 != other.minMappingQualityQ2)
return false;
if (minMedianPhredQualityAtPosition != other.minMedianPhredQualityAtPosition)
return false;
if (minNumberDuplexesSisterArm != other.minNumberDuplexesSisterArm)
return false;
if (minQ1Duplexes != other.minQ1Duplexes)
return false;
if (minQ1Q2DuplexesToCallMutation != other.minQ1Q2DuplexesToCallMutation)
return false;
if (minQ2DuplexesToCallMutation != other.minQ2DuplexesToCallMutation)
return false;
if (minReadMedianPhredScore != other.minReadMedianPhredScore)
return false;
if (minReadsPerDuplexQ2 != other.minReadsPerDuplexQ2)
return false;
if (minReadsPerStrandForDisagreement != other.minReadsPerStrandForDisagreement)
return false;
if (minReadsPerStrandQ1 != other.minReadsPerStrandQ1)
return false;
if (minReadsPerStrandQ2 != other.minReadsPerStrandQ2)
return false;
if (nConstantBarcodeMismatchesAllowed != other.nConstantBarcodeMismatchesAllowed)
return false;
if (nRecordsToProcess != other.nRecordsToProcess)
return false;
if (nVariableBarcodeMismatchesAllowed != other.nVariableBarcodeMismatchesAllowed)
return false;
if (noStatusMessages != other.noStatusMessages)
return false;
if (originalReadFile1 == null) {
if (other.originalReadFile1 != null)
return false;
} else if (!originalReadFile1.equals(other.originalReadFile1))
return false;
if (originalReadFile2 == null) {
if (other.originalReadFile2 != null)
return false;
} else if (!originalReadFile2.equals(other.originalReadFile2))
return false;
if (outputAlignmentFile == null) {
if (other.outputAlignmentFile != null)
return false;
} else if (!outputAlignmentFile.equals(other.outputAlignmentFile))
return false;
if (outputCoverageBed != other.outputCoverageBed)
return false;
if (outputCoverageProto != other.outputCoverageProto)
return false;
if (outputDuplexDetails != other.outputDuplexDetails)
return false;
if (outputJSONTo == null) {
if (other.outputJSONTo != null)
return false;
} else if (!outputJSONTo.equals(other.outputJSONTo))
return false;
if (outputTopBottomDisagreementBED != other.outputTopBottomDisagreementBED)
return false;
if (parallelizationFactor != other.parallelizationFactor)
return false;
if (processingChunk != other.processingChunk)
return false;
if (Float.floatToIntBits(randomOutputRate) != Float.floatToIntBits(other.randomOutputRate))
return false;
if (randomSeed != other.randomSeed)
return false;
if (randomizeMates != other.randomizeMates)
return false;
if (randomizeStrand != other.randomizeStrand)
return false;
if (readContigsFromFile != other.readContigsFromFile)
return false;
if (recordRunsTo == null) {
if (other.recordRunsTo != null)
return false;
} else if (!recordRunsTo.equals(other.recordRunsTo))
return false;
if (refSeqToOfficialGeneName == null) {
if (other.refSeqToOfficialGeneName != null)
return false;
} else if (!refSeqToOfficialGeneName.equals(other.refSeqToOfficialGeneName))
return false;
if (referenceGenome == null) {
if (other.referenceGenome != null)
return false;
} else if (!referenceGenome.equals(other.referenceGenome))
return false;
if (referenceOutput == null) {
if (other.referenceOutput != null)
return false;
} else if (!referenceOutput.equals(other.referenceOutput))
return false;
if (repetiveRegionBED == null) {
if (other.repetiveRegionBED != null)
return false;
} else if (!repetiveRegionBED.equals(other.repetiveRegionBED))
return false;
if (reportBreakdownForBED == null) {
if (other.reportBreakdownForBED != null)
return false;
} else if (!reportBreakdownForBED.equals(other.reportBreakdownForBED))
return false;
if (reportCoverageAtAllPositions != other.reportCoverageAtAllPositions)
return false;
if (reportStatsForBED == null) {
if (other.reportStatsForBED != null)
return false;
} else if (!reportStatsForBED.equals(other.reportStatsForBED))
return false;
if (reportStatsForNotBED == null) {
if (other.reportStatsForNotBED != null)
return false;
} else if (!reportStatsForNotBED.equals(other.reportStatsForNotBED))
return false;
if (requireMatchInAlignmentEnd != other.requireMatchInAlignmentEnd)
return false;
if (rnaSeq != other.rnaSeq)
return false;
if (runName == null) {
if (other.runName != null)
return false;
} else if (!runName.equals(other.runName))
return false;
if (sampleNames == null) {
if (other.sampleNames != null)
return false;
} else if (!sampleNames.equals(other.sampleNames))
return false;
if (saveBEDBreakdownTo == null) {
if (other.saveBEDBreakdownTo != null)
return false;
} else if (!saveBEDBreakdownTo.equals(other.saveBEDBreakdownTo))
return false;
if (saveFilteredReadsTo == null) {
if (other.saveFilteredReadsTo != null)
return false;
} else if (!saveFilteredReadsTo.equals(other.saveFilteredReadsTo))
return false;
if (saveRawReadsDB != other.saveRawReadsDB)
return false;
if (saveRawReadsMVDB != other.saveRawReadsMVDB)
return false;
if (skipVersionCheck != other.skipVersionCheck)
return false;
if (sortOutputAlignmentFile != other.sortOutputAlignmentFile)
return false;
if (startAtPositions == null) {
if (other.startAtPositions != null)
return false;
} else if (!startAtPositions.equals(other.startAtPositions))
return false;
if (startServer == null) {
if (other.startServer != null)
return false;
} else if (!startServer.equals(other.startServer))
return false;
if (startWorker == null) {
if (other.startWorker != null)
return false;
} else if (!startWorker.equals(other.startWorker))
return false;
if (stopAtPositions == null) {
if (other.stopAtPositions != null)
return false;
} else if (!stopAtPositions.equals(other.stopAtPositions))
return false;
if (submitToServer == null) {
if (other.submitToServer != null)
return false;
} else if (!submitToServer.equals(other.submitToServer))
return false;
if (terminateImmediatelyUponError != other.terminateImmediatelyUponError)
return false;
if (terminateUponOutputFileError != other.terminateUponOutputFileError)
return false;
if (timeoutSeconds != other.timeoutSeconds)
return false;
if (topAlleleFreqReport != other.topAlleleFreqReport)
return false;
if (traceFields == null) {
if (other.traceFields != null)
return false;
} else if (!traceFields.equals(other.traceFields))
return false;
if (variableBarcodeLength != other.variableBarcodeLength)
return false;
if (verbosity != other.verbosity)
return false;
if (version != other.version)
return false;
if (workingDirectory == null) {
if (other.workingDirectory != null)
return false;
} else if (!workingDirectory.equals(other.workingDirectory))
return false;
return true;
}
}
|
package us.kbase.genbank.test;
import us.kbase.auth.AuthService;
import us.kbase.auth.AuthToken;
import us.kbase.auth.AuthUser;
import us.kbase.common.service.Tuple11;
import us.kbase.genbank.ConvertGBK;
import us.kbase.genbank.GenometoGbk;
import us.kbase.workspace.ListObjectsParams;
import us.kbase.workspace.WorkspaceClient;
import java.io.File;
import java.net.URL;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
public class TestKBDownUp {
boolean isTest;
String[] argsPossible = {"-w", "--workspace_name", "-wu", "--workspace_service_url", "-su", "--shock_url", "-wd", "--working_directory", "--test"};
String[] argsPossibleMap = {"wsn", "wsn", "wsu", "wsu", "shocku", "shocku", "wd", "wd", "t"};
String wsname, shockurl, wsurl;
File workdir;
int skip =0;
/**
* @param args
*/
public TestKBDownUp(String[] args) {
for (int i = 0; i < args.length; i++) {
int index = Arrays.asList(argsPossible).indexOf(args[i]);
if (index > -1) {
if (argsPossibleMap[index].equals("wsn")) {
wsname = args[i + 1];
} else if (argsPossibleMap[index].equals("wsu")) {
wsurl = args[i + 1];
} else if (argsPossibleMap[index].equals("shocku")) {
shockurl = args[i + 1];
} else if (argsPossibleMap[index].equals("wd")) {
workdir = new File(args[i + 1]);
} else if (argsPossibleMap[index].equals("t")) {
if (args[i + 1].equalsIgnoreCase("Y") || args[i + 1].equalsIgnoreCase("yes")
|| args[i + 1].equalsIgnoreCase("T") || args[i + 1].equalsIgnoreCase("TRUE"))
isTest = true;
}
}
}
if (workdir == null) {
workdir = new File(Paths.get(".").toAbsolutePath().normalize().toString());
} else if (!workdir.exists()) {
workdir.mkdirs();
}
try {
WorkspaceClient wc = null;
String user = System.getProperty("test.user");
String pwd = System.getProperty("test.pwd");
String kbtok = System.getenv("KB_AUTH_TOKEN");
if (isTest) {
System.out.println("using test mode");
AuthToken at = ((AuthUser) AuthService.login(user, pwd)).getToken();
wc = new WorkspaceClient(new URL(wsurl), at);
} else {
wc = new WorkspaceClient(new URL(wsurl), new AuthToken(kbtok));
}
wc.setAuthAllowedForHttp(true);
int MAX = 30000;
for (int m = skip; m < MAX; m += 1000) {
ListObjectsParams lop = new ListObjectsParams();
List<String> lw = new ArrayList();
lw.add("KBasePublicGenomesV5");
lop.withType("KBaseGenomes.Genome").withWorkspaces(lw);
lop.withSkip((long) m);
List<Tuple11<Long, String, String, String, Long, String, Long, String, String, Long, Map<String, String>>> getobj =
wc.listObjects(lop);
System.out.println("got data for " + getobj.size() + " objects, skip " + m);
int count = 0;
for (Tuple11<Long, String, String, String, Long, String, Long, String, String, Long, Map<String, String>> t : getobj) {
System.out.println(count + "\t" + t.getE2() + "\t" + ((double) t.getE10() / (double) (1024 ^ 2)) + "M");
count++;
List<String> ar = new ArrayList();
List<String> ar2 = new ArrayList();
try {
ar.add("--workspace_name");
ar.add("KBasePublicGenomesV5");
ar.add("--workspace_service_url");
ar.add("https://kbase.us/services/ws");
ar.add("--object_name");
ar.add(t.getE2());
ar.add("--working_directory");
final String cleangenomeid = t.getE2().replace('|', '_');
ar.add(workdir.getAbsolutePath() + "/" + cleangenomeid);
if (isTest) {
ar.add("--test");
ar.add("T");
}
String[] argsgt = new String[ar.size()];
int count2 = 0;
for (Object obj : ar) {
argsgt[count2] = obj.toString();
count2++;
}
GenometoGbk gt = new GenometoGbk(wc);
gt.init(argsgt);
gt.run();
//String[] argsPossible = {"-i", "--input_directory", "-o", "--object_name", "-oc", "--contigset_object_name",
//"-w", "--workspace_name", "-wu", "--workspace_service_url", "-su", "--shock_url", "-wd", "--working_directory", "--test"};
ar2.add("--workspace_name");
ar2.add("upload_testing");
ar2.add("--workspace_service_url");
ar2.add("https://kbase.us/services/ws");
ar2.add("--input_directory");
ar2.add(workdir.getAbsolutePath() + "/" + cleangenomeid);
ar2.add("--working_directory");
ar2.add(workdir.getAbsolutePath() + "/" + cleangenomeid);
if (isTest) {
ar2.add("--test");
ar2.add("T");
}
String[] argsgt2 = new String[ar2.size()];
int count22 = 0;
for (Object obj : ar2) {
argsgt2[count22] = obj.toString();
count22++;
}
ConvertGBK cg = new ConvertGBK(wc);
cg.init(argsgt2);
try {
cg.run();
File tobermed = new File(workdir.getAbsolutePath() + "/" + cleangenomeid);
rmdir(tobermed);
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
System.out.println("Error for genome " + t.getE2());
String cmd1 = "";
int count4 = 0;
for (String s : ar) {
cmd1 += s;
if (count4 < ar.size() - 1)
cmd1 += ",";
count4++;
}
String cmd2 = "";
int count5 = 0;
for (String s : ar2) {
cmd2 += s;
if (count5 < ar2.size() - 1)
cmd2 += ",";
count5++;
}
System.out.println("Error down " + cmd1);
System.out.println("Error up " + cmd2);
e.printStackTrace();
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* @param dir
* @return
*/
public static boolean rmdir(File dir) {
if (dir.isDirectory()) {
String[] child = dir.list();
for (int i = 0; i < child.length; i++) {
boolean success = rmdir(new File(dir, child[i]));
if (!success) {
return false;
}
}
}
return dir.delete(); // The directory is empty now and can be deleted.
}
/**
* @param args
*/
public final static void main(String[] args) {
if (args.length >= 4 || args.length <= 10) {
try {
TestKBDownUp clt = new TestKBDownUp(args);
} catch (Exception e) {
e.printStackTrace();
}
} else {
System.out.println("usage: java us.kbase.genbank.test.TestKBDownUp " +
"<-w or --workspace_name ws name> " +
"<-wu or --workspace_service_url ws url> " +
"<-su or --shock_url shock url> " +
"<-wd or --working_directory> " +
"<--test>");
}
}
}
|
package client;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.OpenOption;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import javax.net.ssl.HttpsURLConnection;
import javax.swing.JFileChooser;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import org.json.JSONException;
import org.json.JSONObject;
import ssl.SSLConnection;
import ssl.SSLConnectionManager;
import ssl.SSLConnectionManagerFactory;
public class JIRAClient {
private JIRAClient(){}
private static File JIRA_CERTIFICATE_FILE = new File(System.getProperty("user.home") + "/.testmanager/.credentials/JIRA.crt");
private static File CLIENT_SECRET_FILE;
private static FileInputStream CLIENT_SECRET_INPUT;
private static BufferedReader CLIENT_SECRET_READER;
private static FileOutputStream CLIENT_SECRET_OUTPUT;
//private static BufferedReader CLIENT_SECRET = new BufferedReader(new InputStreamReader(JIRAClient.class.getResourceAsStream("/client_secret.json")));
public static String JIRA_APP_NAME = "jira";
public static final String JIRA_REST_BASE_URL = "https://" + JIRA_APP_NAME + "/jira/api/latest/";
private static String JIRA_REST_ISSUE_BASE_URL = JIRA_REST_BASE_URL + "issue/{issueID}?expand=editmeta";
public SSLConnectionManager sslConnectionManager;
static {
try {
CLIENT_SECRET_FILE = new File(JIRAClient.class.getResource("/client_secret.json").toURI());
CLIENT_SECRET_INPUT = new FileInputStream(CLIENT_SECRET_FILE);
CLIENT_SECRET_OUTPUT = new FileOutputStream(CLIENT_SECRET_FILE);
CLIENT_SECRET_READER = new BufferedReader(new InputStreamReader(CLIENT_SECRET_INPUT));
} catch (URISyntaxException | FileNotFoundException e) {
e.printStackTrace();
}
if (!SSLConnectionManagerFactory.certificateExists("JIRA")){
System.out.println("Certificate doesn't exist in keystore, attempting to add from app directory.");
}
setClientCertificate();
if(!JIRA_CERTIFICATE_FILE.exists()){
System.out.println("Certificate for JIRA is missing, request from user.");
} else {
}
if(SSLConnectionManagerFactory.getCertificate("JIRA")==null){
SSLConnectionManagerFactory.setCertificate(JIRA_CERTIFICATE_FILE, "JIRA");
}
}
private static File getCertificateFile(){
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException
| UnsupportedLookAndFeelException e) {
e.printStackTrace();
}
java.awt.FileDialog fd = new java.awt.FileDialog((java.awt.Frame) null);
fd.setAlwaysOnTop(true);
fd.setTitle("Please select the appropriate JIRA access certificate.");
fd.setDirectory("C:\\");
fd.setFile("*.crt");
fd.setVisible(true);
File file = new File(fd.getDirectory(),fd.getFile());
return file;
}
private static void setClientCertificate(){
File file = getCertificateFile();
String fileType = new StringBuilder(new StringBuilder(file.getAbsolutePath()).reverse().substring(0, 3)).reverse().toString();
if (file.exists() && file.isFile() && fileType.equals("crt")){
String line = null;
String contents = "";
try {
while((line = CLIENT_SECRET_READER.readLine()) != null){
contents += line;
}
} catch (IOException e1) {
e1.printStackTrace();
}
JSONObject json = null;
try {
json = new JSONObject(contents);
} catch (JSONException e) {
json = new JSONObject();
}
json.put("defaultDirectory", file.getAbsolutePath());
try {
CLIENT_SECRET_OUTPUT.write(json.toString().getBytes());
CLIENT_SECRET_OUTPUT.flush();
} catch (IOException e) {
e.printStackTrace();
}
} else {
System.out.println("A valid *.crt file was not selected.");
setClientCertificate();
}
}
public JIRAClient(String password){
this(System.getProperty("user.name"),password);
}
public JIRAClient(String username, String password){
this.sslConnectionManager = SSLConnectionManagerFactory.getSSLConnectionManager(password);
}
public static void setJIRAName(String jiraName){
JIRAClient.JIRA_APP_NAME = jiraName;
}
public SSLConnection getJIRAResource(String url){
return this.sslConnectionManager.getDefaultSSLConnection(url);
}
}
|
package org.voltdb.iv2;
import java.util.AbstractMap;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.function.BiConsumer;
import org.apache.zookeeper_voltpatches.CreateMode;
import org.apache.zookeeper_voltpatches.KeeperException;
import org.apache.zookeeper_voltpatches.ZooKeeper;
import org.json_voltpatches.JSONException;
import org.json_voltpatches.JSONStringer;
import org.voltcore.logging.VoltLogger;
import org.voltcore.messaging.BinaryPayloadMessage;
import org.voltcore.messaging.ForeignHost;
import org.voltcore.messaging.HostMessenger;
import org.voltcore.utils.CoreUtils;
import org.voltcore.utils.Pair;
import org.voltcore.zk.CoreZK;
import org.voltcore.zk.LeaderElector;
import org.voltcore.zk.ZKUtil;
import org.voltdb.AbstractTopology;
import org.voltdb.MailboxNodeContent;
import org.voltdb.RealVoltDB;
import org.voltdb.StatsSource;
import org.voltdb.VoltDB;
import org.voltdb.VoltTable;
import org.voltdb.VoltTable.ColumnInfo;
import org.voltdb.VoltType;
import org.voltdb.VoltZK;
import org.voltdb.VoltZK.MailboxType;
import org.voltdb.iv2.LeaderCache.LeaderCallBackInfo;
import com.google_voltpatches.common.base.Preconditions;
import com.google_voltpatches.common.collect.ArrayListMultimap;
import com.google_voltpatches.common.collect.ImmutableMap;
import com.google_voltpatches.common.collect.Lists;
import com.google_voltpatches.common.collect.Maps;
import com.google_voltpatches.common.collect.Multimap;
import com.google_voltpatches.common.collect.Multimaps;
import com.google_voltpatches.common.collect.Sets;
/**
* Cartographer provides answers to queries about the components in a cluster.
* It provides the StatsSource interface for the TOPO statistics selector, but
* can be called directly as long as the caller is careful about not calling
* from a network thread (need to avoid ZK deadlocks).
*/
public class Cartographer extends StatsSource
{
private static final VoltLogger hostLog = new VoltLogger("HOST");
private final LeaderCacheReader m_iv2Masters;
private final LeaderCacheReader m_iv2Mpi;
private final Set<Long> m_currentSPMasters = new HashSet<Long>();
private final HostMessenger m_hostMessenger;
private final ZooKeeper m_zk;
private final Set<Integer> m_allMasters = new HashSet<Integer>();
public static final String JSON_PARTITION_ID = "partitionId";
public static final String JSON_INITIATOR_HSID = "initiatorHSId";
public static final String JSON_LEADER_MIGRATION = "leaderMigration";
private final int m_configuredReplicationFactor;
//partition masters by host
private final Map<Integer, Set<Long>> m_currentMastersByHost = Maps.newTreeMap();
private final ExecutorService m_es
= CoreUtils.getCachedSingleThreadExecutor("Cartographer", 15000);
/**
* Retrieve the list of partitions in the system. Since each partition information is being populated individually
* asynchronously some partitions may throw exceptions or block when accessing data and other may not.
* <p>
* The arguments passed to {@code errorHandler} will be the zookeeper path which was being accessed at the time of
* the exception and the exception which was thrown.
*
* @param zk {@link ZooKeeper} instance to use to retrieve partition information
* @param skipMp If {@code true} the MP partition will not be included in the result
* @param errorHandler {@link BiConsumer} that will be invoked when exception is encountered
* @return {@link List} of {@link AsyncPartition}s
*/
public static List<AsyncPartition> getPartitionsAsync(ZooKeeper zk, boolean skipMp,
BiConsumer<String, Exception> errorHandler) {
List<String> partitionDirs = null;
try {
partitionDirs = zk.getChildren(VoltZK.leaders_initiators, null);
} catch (Exception e) {
errorHandler.accept(VoltZK.leaders_initiators, e);
return null;
}
// Don't fetch the values serially do it asynchronously
List<AsyncPartition> partitions = new ArrayList<>(partitionDirs.size());
for (String partitionDir : partitionDirs) {
try {
int pid = LeaderElector.getPartitionFromElectionDir(partitionDir);
if (skipMp && pid == MpInitiator.MP_INIT_PID) {
continue;
}
partitions.add(new AsyncPartition(pid, partitionDir, zk));
} catch (Exception e) {
errorHandler.accept(ZKUtil.joinZKPath(VoltZK.leaders_initiators, partitionDir), e);
return null;
}
}
return partitions;
}
// This message used to be sent by the SP or MP initiator when they accepted a promotion.
// For dev speed, we'll detect mastership changes here and construct and send this message to the
// local client interface so we can keep the CIs implementation
private void sendLeaderChangeNotify(long hsId, int partitionId, boolean migratePartitionLeader)
{
hostLog.info("[Cartographer] Sending leader change notification with new leader:" +
CoreUtils.hsIdToString(hsId) + " for partition:" + partitionId);
try {
JSONStringer stringer = new JSONStringer();
stringer.object();
stringer.keySymbolValuePair(JSON_PARTITION_ID, partitionId);
stringer.keySymbolValuePair(JSON_INITIATOR_HSID, hsId);
stringer.keySymbolValuePair(JSON_LEADER_MIGRATION, migratePartitionLeader);
stringer.endObject();
BinaryPayloadMessage bpm = new BinaryPayloadMessage(new byte[0], stringer.toString().getBytes("UTF-8"));
int hostId = m_hostMessenger.getHostId();
m_hostMessenger.send(CoreUtils.getHSIdFromHostAndSite(hostId,
HostMessenger.CLIENT_INTERFACE_SITE_ID),
bpm);
}
catch (Exception e) {
VoltDB.crashLocalVoltDB("Unable to propogate leader promotion to client interface.", true, e);
}
}
LeaderCache.Callback m_MPICallback = new LeaderCache.Callback()
{
@Override
public void run(ImmutableMap<Integer, LeaderCallBackInfo> cache) {
// Every MPI change means a new single MPI. Just do the right thing here
int pid = MpInitiator.MP_INIT_PID;
// Can be zero-length at startup
if (cache.size() > 0) {
hostLog.info("[Cartographer MP] Sending leader change notification with new leader:");
sendLeaderChangeNotify(cache.get(pid).m_HSId, pid, false);
}
}
};
LeaderCache.Callback m_SPIMasterCallback = new LeaderCache.Callback()
{
@Override
public void run(ImmutableMap<Integer, LeaderCallBackInfo> cache) {
// We know there's a 1:1 mapping between partitions and HSIds in this map.
// let's flip it
// Map<Long, Integer> hsIdToPart = new HashMap<Long, Integer>();
Set<LeaderCallBackInfo> newMasters = new HashSet<LeaderCallBackInfo>();
Set<Long> newHSIDs = Sets.newHashSet();
Map<Integer, Set<Long>> newMastersByHost = Maps.newTreeMap();
for (Entry<Integer, LeaderCallBackInfo> e : cache.entrySet()) {
LeaderCallBackInfo newMasterInfo = e.getValue();
Long hsid = newMasterInfo.m_HSId;
int partitionId = e.getKey();
newHSIDs.add(hsid);
// hsIdToPart.put(hsid, partitionId);
int hostId = CoreUtils.getHostIdFromHSId(hsid);
Set<Long> masters = newMastersByHost.get(hostId);
if (masters == null) {
masters = Sets.newHashSet();
newMastersByHost.put(hostId, masters);
}
masters.add(hsid);
if (!m_currentSPMasters.contains(hsid)) {
// we want to see items which are present in the new map but not in the old,
// these are newly promoted SPIs
newMasters.add(newMasterInfo);
// send the messages indicating promotion from here for each new master
sendLeaderChangeNotify(hsid, partitionId, newMasterInfo.m_isMigratePartitionLeaderRequested);
}
}
if (hostLog.isDebugEnabled()) {
Set<String> masters = Sets.newHashSet();
m_currentSPMasters.forEach((k) -> {
masters.add(CoreUtils.hsIdToString(k));
});
hostLog.debug("[Cartographer] SP masters:" + masters);
masters.clear();
cache.values().forEach((k) -> {
masters.add(CoreUtils.hsIdToString(k.m_HSId));
});
hostLog.debug("[Cartographer]Updated SP masters:" + masters + ". New masters:" + newMasters);
}
m_currentSPMasters.clear();
m_currentSPMasters.addAll(newHSIDs);
m_currentMastersByHost.clear();
m_currentMastersByHost.putAll(newMastersByHost);
}
};
/**
* A dummy iterator that wraps an UnmodifiableIterator<Integer> and provides the
* Iterator<Object>
*/
private static class DummyIterator implements Iterator<Object> {
private final Iterator<Integer> i;
private DummyIterator(Iterator<Integer> i) {
this.i = i;
}
@Override
public boolean hasNext() {
return i.hasNext();
}
@Override
public Object next() {
return i.next();
}
@Override
public void remove() {
i.remove();
}
}
public Cartographer(HostMessenger hostMessenger, int configuredReplicationFactor, boolean partitionDetectionEnabled) {
super(false);
m_hostMessenger = hostMessenger;
m_zk = hostMessenger.getZK();
m_iv2Masters = new LeaderCache(m_zk, "Cartographer-iv2Masters-" + hostMessenger.getHostId(),
VoltZK.iv2masters, m_SPIMasterCallback);
m_iv2Mpi = new LeaderCache(m_zk, "Cartographer-iv2Mpi-" + hostMessenger.getHostId(),
VoltZK.iv2mpi, m_MPICallback);
m_configuredReplicationFactor = configuredReplicationFactor;
try {
m_iv2Masters.start(true);
m_iv2Mpi.start(true);
} catch (Exception e) {
VoltDB.crashLocalVoltDB("Screwed", true, e);
}
}
@Override
protected void populateColumnSchema(ArrayList<ColumnInfo> columns)
{
columns.add(new ColumnInfo("Partition", VoltType.INTEGER));
columns.add(new ColumnInfo("Sites", VoltType.STRING));
columns.add(new ColumnInfo("Leader", VoltType.STRING));
}
@Override
protected Iterator<Object> getStatsRowKeyIterator(boolean interval)
{
m_allMasters.clear();
m_allMasters.addAll(m_iv2Masters.pointInTimeCache().keySet());
m_allMasters.add(MpInitiator.MP_INIT_PID);
//make a copy of the master list for the topology statistics to avoid any concurrent modification
//since the master list may be updated while the topology statistics is being built.
Set<Integer> masters = new HashSet<>();
masters.addAll(m_allMasters);
return new DummyIterator(masters.iterator());
}
@Override
protected void updateStatsRow(Object rowKey, Object[] rowValues) {
long leader;
List<Long> sites = new ArrayList<Long>();
if (rowKey.equals(MpInitiator.MP_INIT_PID)) {
leader = getHSIdForMultiPartitionInitiator();
sites.add(leader);
}
else {
//sanity check. The master list may be updated while the statistics is calculated.
Long leaderInCache = m_iv2Masters.pointInTimeCache().get(rowKey);
if (leaderInCache == null) {
return;
}
leader = leaderInCache;
sites.addAll(getReplicasForPartition((Integer)rowKey));
}
rowValues[columnNameToIndex.get("Partition")] = rowKey;
rowValues[columnNameToIndex.get("Sites")] = CoreUtils.hsIdCollectionToString(sites);
rowValues[columnNameToIndex.get("Leader")] = CoreUtils.hsIdToString(leader);
}
/**
* Convenience method: Get the HSID of the master for the specified partition ID, SP or MP
*/
public Long getHSIdForMaster(int partitionId)
{
if (partitionId == MpInitiator.MP_INIT_PID) {
return getHSIdForMultiPartitionInitiator();
}
else {
return getHSIdForSinglePartitionMaster(partitionId);
}
}
/**
* Checks whether this host is partition 0 'zero' leader
*
* @return result of the test
*/
public boolean isPartitionZeroLeader()
{
return CoreUtils.getHostIdFromHSId(m_iv2Masters.get(0)) == m_hostMessenger.getHostId();
}
/**
* Checks whether this host is partition 0 'zero' leader
*
* @return result of the test
*/
public boolean isHostIdLocal(int hostId)
{
return hostId == m_hostMessenger.getHostId();
}
/**
* Get the HSID of the single partition master for the specified partition ID
*/
public Long getHSIdForSinglePartitionMaster(int partitionId)
{
return m_iv2Masters.get(partitionId);
}
/**
* validate partition id
* @param partitionId The partition id
* @return return true if the partition id is valid
*/
public boolean hasPartition(int partitionId) {
return ((LeaderCache)m_iv2Masters).contain(partitionId);
}
// This used to be the method to get this on SiteTracker
public Long getHSIdForMultiPartitionInitiator()
{
return m_iv2Mpi.get(MpInitiator.MP_INIT_PID);
}
public long getBuddySiteForMPI(long hsid)
{
int host = CoreUtils.getHostIdFromHSId(hsid);
// We'll be lazy and get the map we'd feed to SiteTracker's
// constructor, then go looking for a matching host ID.
List<MailboxNodeContent> sitesList = getMailboxNodeContentList();
for (MailboxNodeContent site : sitesList) {
if (site.partitionId != MpInitiator.MP_INIT_PID && host == CoreUtils.getHostIdFromHSId(site.HSId)) {
return site.HSId;
}
}
throw new RuntimeException("Unable to find a buddy initiator for MPI with HSID: " +
CoreUtils.hsIdToString(hsid));
}
/**
* Returns the IDs of the partitions currently in the cluster.
* @return A list of partition IDs
*/
public static List<Integer> getPartitions(ZooKeeper zk) {
List<Integer> partitions = new ArrayList<Integer>();
try {
List<String> children = zk.getChildren(VoltZK.leaders_initiators, null);
for (String child : children) {
partitions.add(LeaderElector.getPartitionFromElectionDir(child));
}
} catch (KeeperException e) {
VoltDB.crashLocalVoltDB("Failed to get partition IDs from ZK", true, e);
} catch (InterruptedException e) {
VoltDB.crashLocalVoltDB("Failed to get partition IDs from ZK", true, e);
}
return partitions;
}
public List<Integer> getPartitions() {
return Cartographer.getPartitions(m_zk);
}
public int getPartitionCount()
{
// The list returned by getPartitions includes the MP PID. Need to remove that for the
// true partition count.
return Cartographer.getPartitions(m_zk).size() - 1;
}
private Multimap<Integer, Integer> getHostToPartitionMap() {
Multimap<Integer, Integer> hostToPartitions = ArrayListMultimap.create();
for (int pId : getPartitions()) {
if (pId == MpInitiator.MP_INIT_PID) {
continue;
}
List<Long> hsIDs = getReplicasForPartition(pId);
hsIDs.forEach(hsId -> hostToPartitions.put(CoreUtils.getHostIdFromHSId(hsId), pId));
}
return hostToPartitions;
}
/**
* Convenient method, given a hostId, return the hostId of its buddies (including itself) which both
* belong to the same partition group.
* @param hostId
* @return A set of host IDs (includes the given hostId) that both belong to the same partition group
*/
public Set<Integer> getHostIdsWithinPartitionGroup(int hostId) {
Set<Integer> hostIds = Sets.newHashSet();
Multimap<Integer, Integer> hostToPartitions = getHostToPartitionMap();
assert hostToPartitions.containsKey(hostId);
Multimap<Integer, Integer> partitionByIds = ArrayListMultimap.create();
Multimaps.invertFrom(hostToPartitions, partitionByIds);
for (int partition : hostToPartitions.asMap().get(hostId)) {
hostIds.addAll(partitionByIds.get(partition));
}
return hostIds;
}
/**
* Convenient method, given a set of partitionIds, return the hostId of their partition group buddies.
*
* @param partitions A list of partitions that to be assigned to the newly rejoined host
* @return A set of host IDs that both belong to the same partition group
*/
public Set<Integer> findPartitionGroupPeers(List<Integer> partitions) {
Set<Integer> hostIds = Sets.newHashSet();
Multimap<Integer, Integer> hostToPartitions = getHostToPartitionMap();
Multimap<Integer, Integer> partitionByIds = ArrayListMultimap.create();
Multimaps.invertFrom(hostToPartitions, partitionByIds);
for (int p : partitions) {
hostIds.addAll(partitionByIds.get(p));
}
return hostIds;
}
/**
* @return a multi map of a pair of Partition to HSIDs to all Hosts
*/
public Multimap<Integer, Entry<Integer,Long>> getHostToPartition2HSIdMap() {
Multimap<Integer, Entry<Integer,Long>> hostToHSId = ArrayListMultimap.create();
for (int pId : getPartitions()) {
if (pId == MpInitiator.MP_INIT_PID) {
continue;
}
List<Long> hsIDs = getReplicasForPartition(pId);
hsIDs.forEach(hsId -> hostToHSId.put(CoreUtils.getHostIdFromHSId(hsId), new AbstractMap.SimpleEntry<>(pId, hsId)));
}
return hostToHSId;
}
/**
* Given a partition ID, return a list of HSIDs of all the sites with copies of that partition
*/
public List<Long> getReplicasForPartition(int partition) {
String zkpath = LeaderElector.electionDirForPartition(VoltZK.leaders_initiators, partition);
List<Long> retval = new ArrayList<Long>();
try {
List<String> children = m_zk.getChildren(zkpath, null);
for (String child : children) {
retval.add(Long.valueOf(child.split("_")[0]));
}
}
catch (KeeperException.NoNodeException e) {
//Can happen when partitions are being removed
} catch (KeeperException | InterruptedException e) {
org.voltdb.VoltDB.crashLocalVoltDB("Exception getting replicas for partition: " + partition,
true, e);
}
return retval;
}
/**
* return host site id with a given host id and a partition id
* @param hostId The host id
* @param partition The partition id
* @return a site id or null if there is no such a site
*/
public Long getHSIDForPartitionHost(int hostId, int partition) {
List<Long> hsids = getReplicasForPartition(partition);
for (Long hsid : hsids) {
if (hostId == CoreUtils.getHostIdFromHSId(hsid)){
return hsid;
}
}
return null;
}
/**
* Given a set of partition IDs, return a map of partition to a list of HSIDs of all the sites with copies of each partition
*/
public Map<Integer, List<Long>> getReplicasForPartitions(Collection<Integer> partitions) {
Map<Integer, List<Long>> retval = new HashMap<Integer, List<Long>>();
List<Pair<Integer,ZKUtil.ChildrenCallback>> callbacks = new ArrayList<Pair<Integer, ZKUtil.ChildrenCallback>>();
for (Integer partition : partitions) {
String zkpath = LeaderElector.electionDirForPartition(VoltZK.leaders_initiators, partition);
ZKUtil.ChildrenCallback cb = new ZKUtil.ChildrenCallback();
callbacks.add(Pair.of(partition, cb));
m_zk.getChildren(zkpath, false, cb, null);
}
for (Pair<Integer, ZKUtil.ChildrenCallback> p : callbacks ) {
final Integer partition = p.getFirst();
try {
List<String> children = p.getSecond().get();
List<Long> sites = new ArrayList<Long>();
for (String child : children) {
sites.add(Long.valueOf(child.split("_")[0]));
}
retval.put(partition, sites);
} catch (KeeperException.NoNodeException e) {
//This can happen when a partition is being removed from the system
} catch (KeeperException ke) {
org.voltdb.VoltDB.crashLocalVoltDB("KeeperException getting replicas for partition: " + partition,
true, ke);
}
catch (InterruptedException ie) {
org.voltdb.VoltDB.crashLocalVoltDB("InterruptedException getting replicas for partition: " +
partition, true, ie);
}
}
return retval;
}
/**
* Convenience method to return the immediate count of replicas for the given partition
*/
public int getReplicaCountForPartition(int partition) {
return getReplicasForPartition(partition).size();
}
/**
* Utility method to sort the keys of a map by their value. public for testing.
*/
static public List<Integer> sortKeysByValue(Map<Integer, Integer> map)
{
List<Entry<Integer, Integer>> entries = CoreUtils.sortKeyValuePairByValue(map);
List<Integer> keys = new ArrayList<Integer>();
for (Entry<Integer, Integer> entry : entries) {
keys.add(entry.getKey());
}
return keys;
}
/**
* Given the current state of the cluster, compute the partitions which should be replicated on a single new host.
* Break this method out to be static and testable independent of ZK, JSON, other ugh.
*/
static public void computeReplacementPartitions(Map<Integer, Integer> repsPerPart, int kfactor,
int sitesPerHost, List<Integer> partitions)
{
List<Integer> partSortedByRep = sortKeysByValue(repsPerPart);
for (int i = 0; i < partSortedByRep.size(); i++) {
int leastReplicatedPart = partSortedByRep.get(i);
if (repsPerPart.get(leastReplicatedPart) < kfactor + 1) {
partitions.add(leastReplicatedPart);
if (partitions.size() == sitesPerHost) {
break;
}
}
}
}
public List<Integer> getIv2PartitionsToReplace(int kfactor, int sitesPerHost, int localHostId, Map<Integer, String> hostGroups)
throws JSONException
{
Preconditions.checkArgument(sitesPerHost != VoltDB.UNDEFINED);
List<Integer> partitionsToReplace = new ArrayList<Integer>();
Map<Integer, Integer> repsPerPart = new HashMap<Integer, Integer>();
List<Collection<Integer>> sortedHosts = AbstractTopology.sortHostIdByHGDistance(localHostId, hostGroups);
// attach partitions to each hosts
Multimap<Integer, Integer> hostToPartitions = getHostToPartitionMap();
for (Collection<Integer> subgroup : sortedHosts) {
Set<Integer> partitions = new HashSet<Integer>();
for (Integer hid : subgroup) {
partitions.addAll(hostToPartitions.get(hid));
}
hostLog.info("Computing partitions to replace. Qualified partitions: " + partitions);
// sort the partitions by replicas number
for (Integer pid : partitions) {
repsPerPart.put(pid, getReplicaCountForPartition(pid));
}
computeReplacementPartitions(repsPerPart, kfactor, sitesPerHost, partitionsToReplace);
if (partitionsToReplace.size() == sitesPerHost) {
hostLog.info("IV2 Sites will replicate the following partitions: " + partitionsToReplace);
break;
}
}
return partitionsToReplace;
}
private List<MailboxNodeContent> getMailboxNodeContentList()
{
List<MailboxNodeContent> sitesList = new ArrayList<MailboxNodeContent>();
final Set<Integer> iv2MastersKeySet = m_iv2Masters.pointInTimeCache().keySet();
Map<Integer, List<Long>> hsidsForPartMap = getReplicasForPartitions(iv2MastersKeySet);
for (Map.Entry<Integer, List<Long>> entry : hsidsForPartMap.entrySet()) {
Integer partId = entry.getKey();
List<Long> hsidsForPart = entry.getValue();
for (long hsid : hsidsForPart) {
MailboxNodeContent mnc = new MailboxNodeContent(hsid, partId);
sitesList.add(mnc);
}
}
return sitesList;
}
public Map<MailboxType, List<MailboxNodeContent>> getSiteTrackerMailboxMap()
{
HashMap<MailboxType, List<MailboxNodeContent>> result =
new HashMap<MailboxType, List<MailboxNodeContent>>();
List<MailboxNodeContent> sitesList = getMailboxNodeContentList();
result.put(MailboxType.ExecutionSite, sitesList);
return result;
}
public void shutdown() throws InterruptedException
{
m_iv2Masters.shutdown();
m_iv2Mpi.shutdown();
m_es.shutdown();
}
//Check partition replicas.
public synchronized String stopNodeIfClusterIsSafe(final Set<Integer> liveHids, final int ihid) {
try {
return m_es.submit(new Callable<String>() {
@Override
public String call() throws Exception {
if (m_configuredReplicationFactor == 0) {
//Dont die in k=0 cluster
return "Stopping individual nodes is only allowed on a K-safe cluster";
}
// check if any node still in rejoin status
try {
if (m_zk.exists(CoreZK.rejoin_node_blocker, false) != null) {
return "All rejoin nodes must be completed";
}
} catch (KeeperException.NoNodeException ignore) {} // shouldn't happen
//Otherwise we do check replicas for host
Set<Integer> otherStoppedHids = new HashSet<Integer>();
// Write the id of node to be stopped to ZK, partition detection will bypass this node.
ZKUtil.addIfMissing(m_zk, ZKUtil.joinZKPath(VoltZK.host_ids_be_stopped, Integer.toString(ihid)), CreateMode.PERSISTENT, null);
try {
List<String> children = m_zk.getChildren(VoltZK.host_ids_be_stopped, false);
for (String child : children) {
int hostId = Integer.parseInt(child);
otherStoppedHids.add(hostId);
}
otherStoppedHids.remove(ihid); /* don't count self */
} catch (KeeperException.NoNodeException ignore) {}
String reason = doPartitionsHaveReplicas(ihid, otherStoppedHids);
if (reason == null) {
// Safe to stop
m_hostMessenger.sendStopNodeNotice(ihid);
// Shutdown or send poison pill
int hid = m_hostMessenger.getHostId();
if (hid == ihid) {
//Killing myself no pill needs to be sent
VoltDB.instance().halt();
} else {
//Send poison pill with target to kill
m_hostMessenger.sendPoisonPill(ihid, "@StopNode", ForeignHost.CRASH_ME);
}
} else {
// unsafe, clear the indicator
ZKUtil.deleteRecursively(m_zk, ZKUtil.joinZKPath(VoltZK.host_ids_be_stopped, Integer.toString(ihid)));
}
return reason;
}
}).get();
} catch (InterruptedException | ExecutionException t) {
hostLog.debug("LeaderAppointer: Error in isClusterSafeIfIDie.", t);
return "Internal error: " + t.getMessage();
}
}
public String verifyPartitonLeaderMigrationForStopNode(final int ihid) {
if (m_configuredReplicationFactor == 0) {
return "Stopping individual nodes is only allowed on a K-safe cluster";
}
try {
return m_es.submit(new Callable<String>() {
@Override
public String call() throws Exception {
// Check rejoining status
try {
if (m_zk.exists(CoreZK.rejoin_node_blocker, false) != null) {
return "All rejoin nodes must be completed";
}
} catch (KeeperException.NoNodeException ignore) {}
// Check replicas
Set<Integer> otherStoppedHids = new HashSet<Integer>();
try {
List<String> children = m_zk.getChildren(VoltZK.host_ids_be_stopped, false);
for (String child : children) {
int hostId = Integer.parseInt(child);
otherStoppedHids.add(hostId);
}
} catch (KeeperException.NoNodeException ignore) {}
otherStoppedHids.remove(ihid);
if (!otherStoppedHids.isEmpty()) {
return "Cann't move partition leaders while other nodes are being shutdown.";
}
String message = doPartitionsHaveReplicas(ihid, otherStoppedHids);
if (message != null) {
return message;
}
// Partition leader distribution mast be balanced, otherwise, the migrated partition leader will
// be moved back.
if (!isPartitionLeadersBalanced()) {
return "Cann't move partition leaders since leader migration is in progress";
}
return null;
}}).get();
} catch (InterruptedException | ExecutionException t) {
return "Internal error: " + t.getMessage();
}
}
private boolean isPartitionLeadersBalanced() {
// Is partition leader migration on?
final boolean disableSpiTask = "true".equals(System.getProperty("DISABLE_MIGRATE_PARTITION_LEADER", "false"));
if (disableSpiTask) {
return true;
}
RealVoltDB db = (RealVoltDB) VoltDB.instance();
if(db.isClusterComplete()) {
Pair<Integer, Integer> pair = getPartitionLeaderMigrationTarget(db.getHostCount(),Integer.MIN_VALUE, true);
// Partition leader migration may be in progress. don't mess up
return (pair == null || pair.getFirst() == -1 ) ;
}
return true;
}
// Check if partitions on host hid will have enough replicas after losing host hid.
// If nodesBeingStopped was set, it means there are concurrent @StopNode running,
// don't count replicas on those to-be-stopped nodes.
private String doPartitionsHaveReplicas(int hid, Set<Integer> nodesBeingStopped) {
hostLog.debug("Cartographer: Reloading partition information.");
assert (!nodesBeingStopped.contains(hid));
String[] error = { null };
List<AsyncPartition> partitions = getPartitionsAsync(m_zk, false,
(d, e) -> error[0] = "Failed to read ZooKeeper node " + d + ": " + e.getMessage());
if (error[0] != null) {
return error[0];
}
//Assume that we are ksafe
for (AsyncPartition partition : partitions) {
try {
//Dont let anyone die if someone is in INITIALIZING state
if (partition.isInitializing()) {
return "StopNode is disallowed in initialization phase";
}
if (partition.getPid() == MpInitiator.MP_INIT_PID) {
continue;
}
//Get Hosts for replicas
final List<Integer> replicaHost = new ArrayList<>();
final List<Integer> replicaOnStoppingHost = new ArrayList<>();
boolean hostHasReplicas = false;
for (String replica : partition.getReplicas()) {
final String split[] = replica.split("/");
final long hsId = Long.valueOf(split[split.length - 1].split("_")[0]);
final int hostId = CoreUtils.getHostIdFromHSId(hsId);
if (hostId == hid) {
hostHasReplicas = true;
}
if (nodesBeingStopped.contains(hostId)) {
replicaOnStoppingHost.add(hostId);
}
replicaHost.add(hostId);
}
if (hostLog.isDebugEnabled()) {
hostLog.debug("Replica Host for Partition " + partition.getPid() + " " + replicaHost);
}
if (hostHasReplicas && replicaHost.size() <= 1) {
return "Cluster doesn't have enough replicas";
}
if (hostHasReplicas && !replicaOnStoppingHost.isEmpty() && replicaHost.size() <= replicaOnStoppingHost.size() + 1) {
return "Cluster doesn't have enough replicas. There are concurrent stop node requests, retry the command later";
}
} catch (InterruptedException | KeeperException | NumberFormatException e) {
return "Failed to stop node:" + e.getMessage();
}
}
return null;
}
/**
* used to calculate the partition candidate for migration
*/
private static class Host implements Comparable<Host> {
final int m_hostId;
//the master partition ids on the host
List<Integer> m_masterPartitionIDs = Lists.newArrayList();
//the replica partition ids on the host
List<Integer> m_replicaPartitionIDs = Lists.newArrayList();
public Host(int hostId) {
m_hostId = hostId;
}
@Override
public int compareTo(Host other){
int diff = (other.m_masterPartitionIDs.size() - m_masterPartitionIDs.size());
if (diff != 0) {
return diff;
}
return (m_hostId - other.m_hostId);
}
@Override
public int hashCode() {
return m_hostId;
}
@Override
public boolean equals(Object obj) {
if (obj instanceof Host) {
Host info = (Host)obj;
return m_hostId == info.m_hostId;
}
return false;
}
public void addPartition(Integer partitionId, boolean master) {
if (master) {
m_masterPartitionIDs.add(partitionId);
} else {
m_replicaPartitionIDs.add(partitionId);
}
}
public int getPartitionLeaderCount() {
return m_masterPartitionIDs.size();
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("Host:" + m_hostId);
builder.append(", master:" + m_masterPartitionIDs);
builder.append(", replica:" + m_replicaPartitionIDs);
return builder.toString();
}
}
/**
* find a partition and its target host for MigratePartitionLeader
* SPI is migrated from the host with most partition leaders to a host which has the partition replica and
* the least number of partition. if the host with @localHostId is not the host which has the most partition
* leaders, return null. Eventually the host with most partition leaders will initiate MigratePartitionLeader.
* @param hostCount The number of hosts in the cluster
* @param localHostId the host id
* @return a pair of partition id and destination host id
*/
public Pair<Integer, Integer> getPartitionLeaderMigrationTarget(int hostCount, int localHostId, boolean prepareStopNode) {
final int maxMastersPerHost = (int)Math.ceil(((double)getPartitionCount()) / hostCount);
final int minMastersPerHost = (getPartitionCount() / hostCount);
// Sort the hosts by partition leader count, descending
List<Host> hostList = getHostsByPartionMasterCount();
if (hostList == null) {
return Pair.of(-1, -1);
}
// only move SPI from the one with most partition leaders
// The local ClientInterface will pick it up and start @MigratePartitionLeader
Host srcHost = hostList.get(0);
// @MigratePartitionLeader is initiated on the host with the old leader to facilitate DR integration
// If current host does not have the most partition leaders, give it up.
// Let the host with the most partition leaders to migrate
if (srcHost.m_hostId != localHostId && !prepareStopNode) {
return null;
}
// The new host is the one with least number of partition leaders and the partition replica
for (ListIterator<Host> reverseIt = hostList.listIterator(hostList.size()); reverseIt.hasPrevious();) {
Host targetHost = reverseIt.previous();
int partitionCandidate = findNewHostForPartitionLeader(srcHost,targetHost, maxMastersPerHost, minMastersPerHost);
if (partitionCandidate > -1){
return Pair.of(partitionCandidate, targetHost.m_hostId);
}
}
// indicate that the cluster is balanced.
return Pair.of(-1, -1);
}
private List<Host> getHostsByPartionMasterCount() {
Set<Integer> liveHosts = m_hostMessenger.getLiveHostIds();
if (liveHosts.size() == 1) {
return null;
}
//collect host and partition info
Map<Integer, Host> hostsMap = Maps.newHashMap();
Set<Integer> allMasters = new HashSet<Integer>();
allMasters.addAll(m_iv2Masters.pointInTimeCache().keySet());
for (Integer partitionId : allMasters) {
int leaderHostId = CoreUtils.getHostIdFromHSId(m_iv2Masters.pointInTimeCache().get(partitionId));
//sanity check to make sure that the topology is not in the middle of leader promotion
if (!liveHosts.contains(leaderHostId)) {
return null;
}
Host leaderHost = hostsMap.get(leaderHostId);
if (leaderHost == null) {
leaderHost = new Host(leaderHostId);
hostsMap.put(leaderHostId, leaderHost);
}
List<Long> sites = getReplicasForPartition(partitionId);
for (long site : sites) {
int hostId = CoreUtils.getHostIdFromHSId(site);
if (!liveHosts.contains(hostId)) {
return null;
}
Host host = hostsMap.get(hostId);
if (host == null) {
host = new Host(hostId);
hostsMap.put(hostId, host);
}
host.addPartition(partitionId, (leaderHostId == hostId));
}
}
//Sort the hosts by partition leader count, descending
List<Host> hostList = new ArrayList<>(hostsMap.values());
Collections.sort(hostList);
return hostList;
}
private int findNewHostForPartitionLeader(Host src, Host target, int maxMastersPerHost, int minMastersPerHost) {
// cann't move onto itself
if (src.equals(target)) {
return -1;
}
// still have more leaders than max?
if (src.getPartitionLeaderCount() > maxMastersPerHost) {
for (Integer partition : src.m_masterPartitionIDs) {
if (target.m_replicaPartitionIDs.contains(partition) && target.getPartitionLeaderCount() < maxMastersPerHost) {
return partition;
}
}
} else {
if (target.getPartitionLeaderCount() >= minMastersPerHost || src.getPartitionLeaderCount() <= minMastersPerHost) {
return -1;
} else {
for (Integer partition : src.m_masterPartitionIDs) {
if (target.m_replicaPartitionIDs.contains(partition)) {
return partition;
}
}
}
}
return -1;
}
// find a new host for a partition leader on this host
public Pair<Integer, Integer> getPartitionLeaderMigrationTargetForStopNode(int localHostId) {
// Sort the hosts by partition leader count, descending
List<Host> hostList = getHostsByPartionMasterCount();
if (hostList == null) {
return Pair.of(-1, -1);
}
Host srcHost = null;
for (Host host : hostList) {
if (host.m_hostId == localHostId) {
if (!host.m_masterPartitionIDs.isEmpty()) {
srcHost = host;
}
break;
}
}
if (srcHost == null) {
return Pair.of(-1, -1);
}
// The new host is the one with least number of partition leaders and the partition replica
for (ListIterator<Host> reverseIt = hostList.listIterator(hostList.size()); reverseIt.hasPrevious();) {
Host targetHost = reverseIt.previous();
if (!targetHost.equals(srcHost)) {
for (Integer partition : srcHost.m_masterPartitionIDs) {
if (targetHost.m_replicaPartitionIDs.contains(partition)) {
return Pair.of(partition, targetHost.m_hostId);
}
}
}
}
// Indicate that all the partition leaders have been relocated.
return Pair.of(-1, -1);
}
//return the number of masters on a host
public int getMasterCount(int hostId) {
Set<Long> masters = m_currentMastersByHost.get(hostId);
if (masters == null) {
return 0;
}
return masters.size();
}
//Utility method to peek the topology
public static VoltTable peekTopology(Cartographer cart) {
ColumnInfo[] column = new ColumnInfo[3];
column[0] = new ColumnInfo("Partition", VoltType.BIGINT);
column[1] = new ColumnInfo("Sites", VoltType.STRING);
column[2] = new ColumnInfo("Leader", VoltType.STRING);
VoltTable t = new VoltTable(column);
Iterator<Object> i = cart.getStatsRowKeyIterator(false);
while (i.hasNext()) {
Object rowKey = i.next();
long leader;
List<Long> sites = new ArrayList<Long>();
if (rowKey.equals(MpInitiator.MP_INIT_PID)) {
leader = cart.getHSIdForMultiPartitionInitiator();
sites.add(leader);
} else {
leader = cart.m_iv2Masters.pointInTimeCache().get(rowKey);
sites.addAll(cart.getReplicasForPartition((Integer)rowKey));
}
t.addRow(rowKey, CoreUtils.hsIdCollectionToString(sites), CoreUtils.hsIdToString(leader));
}
return t;
}
public boolean hasPartitionMastersOnHosts(Set<Integer> hosts) {
for (Integer host : hosts) {
if (m_currentMastersByHost.containsKey(host)) {
return true;
}
}
return false;
}
/**
* Simple class to retrieve a partition data and replicas through async zookeeper callbacks
*/
public static final class AsyncPartition {
private final int m_pid;
private final String m_path;
private final ZKUtil.ByteArrayCallback m_stateCallback = new ZKUtil.ByteArrayCallback();
private final ZKUtil.ChildrenCallback m_childrenCallback = new ZKUtil.ChildrenCallback();
public AsyncPartition(String partitionDir, ZooKeeper zooKeeper) {
this(LeaderElector.getPartitionFromElectionDir(partitionDir), partitionDir, zooKeeper);
}
AsyncPartition(int pid, String partitionDir, ZooKeeper zooKeeper) {
m_pid = pid;
m_path = ZKUtil.joinZKPath(VoltZK.leaders_initiators, partitionDir);
zooKeeper.getData(m_path, false, m_stateCallback, null);
zooKeeper.getChildren(m_path, false, m_childrenCallback, null);
}
/**
* @return the pid of the partition
*/
public int getPid() {
return m_pid;
}
/**
* @return The absolute zookeeper path to the partition
*/
public String getPath() {
return m_path;
}
/**
* This call blocks until the data is populated by zookeeper or an exception occurs
*
* @return {@code true} if the state is exactly {@link LeaderElector#INITIALIZING}
* @throws InterruptedException If this thread is interrupted while waiting for data
* @throws KeeperException If there was an error retrieving the state from zookeeper
*/
public boolean isInitializing() throws InterruptedException, KeeperException {
byte[] state = m_stateCallback.get();
return state != null && state.length == 1 && state[0] == LeaderElector.INITIALIZING;
}
/**
* This call blocks until the data is populated by zookeeper or an exception occurs
*
* @return {@code true} if the state is exactly {@link LeaderElector#INITIALIZED}
* @throws InterruptedException If this thread is interrupted while waiting for data
* @throws KeeperException If there was an error retrieving the state from zookeeper
*/
public boolean isInitialized() throws InterruptedException, KeeperException {
byte[] state = m_stateCallback.get();
assert state != null && state.length == 1;
return state != null && state.length == 1 && state[0] == LeaderElector.INITIALIZED;
}
/**
* This call blocks until the data is populated by zookeeper or an exception occurs
*
* @return list of replicas for partition
* @throws InterruptedException If this thread is interrupted while waiting for data
* @throws KeeperException If there was an error retrieving the state from zookeeper
*/
public List<String> getReplicas() throws InterruptedException, KeeperException {
return m_childrenCallback.get();
}
}
}
|
package de.danielnaber.languagetool;
import java.io.IOException;
import junit.framework.TestCase;
public class ValidateXMLTest extends TestCase {
public void testPatternFile() throws IOException {
XMLValidator validator = new XMLValidator();
for (int i = 0; i < Language.LANGUAGES.length; i++) {
Language lang = Language.LANGUAGES[i];
String grammarFile = "/rules/" + lang.getShortName() + "/grammar.xml";
validator.validate(grammarFile, "/rules/rules.dtd", "rules");
}
}
public void testFalseFriendsXML() throws IOException {
XMLValidator validator = new XMLValidator();
validator.validate("/rules/false-friends.xml", "/rules/false-friends.dtd", "rules");
}
public void testDisambiguationRuleFile() throws IOException {
XMLValidator validator = new XMLValidator();
//for (int i = 0; i < Language.LANGUAGES.length; i++) {
// Language lang = Language.LANGUAGES[i];
Language lang = Language.FRENCH;
String grammarFile = "/resource/" + lang.getShortName() + "/disambiguation.xml";
validator.validate(grammarFile, "/resource/disambiguation.dtd", "rules");
}
}
|
package org.mwc.cmap.xyplot.views;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.action.IToolBarManager;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.ISelectionProvider;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.IActionBars;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IEditorReference;
import org.eclipse.ui.IMemento;
import org.eclipse.ui.IViewSite;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.part.ViewPart;
import org.mwc.cmap.core.CorePlugin;
import org.mwc.cmap.core.DataTypes.Temporal.TimeProvider;
import org.mwc.cmap.core.property_support.EditableWrapper;
import org.mwc.cmap.core.ui_support.PartMonitor;
import org.mwc.cmap.xyplot.views.providers.CrossSectionDatasetProvider;
import org.mwc.cmap.xyplot.views.providers.ICrossSectionDatasetProvider;
import org.mwc.cmap.xyplot.views.snail.ISnailPeriodChangedListener;
import org.mwc.cmap.xyplot.views.snail.SnailPeriodTracker;
import Debrief.Wrappers.ShapeWrapper;
import MWC.GUI.Editable;
import MWC.GUI.Layer;
import MWC.GUI.Layers;
import MWC.GUI.PlainWrapper;
import MWC.GUI.Plottable;
import MWC.GUI.Shapes.LineShape;
import MWC.GUI.Shapes.PlainShape;
import MWC.GenericData.HiResDate;
public class CrossSectionView extends ViewPart implements ISnailPeriodChangedListener
{
CrossSectionViewer _viewer;
/**
* listen to line annotations being selected
*/
private ISelectionChangedListener _selectionChangeListener;
/**
* Provider listening to us
*/
private ISelectionProvider _selectionProvider;
/**
* helper application to help track activation/closing of new plots
*/
private PartMonitor _partMonitor;
/**
* listen out for new times
*/
private PropertyChangeListener _timeListener;
private TimeProvider _timeProvider;
private PropertyChangeListener _lineListener = new LineChangeListener();
/**
* current line annotation being selected
*/
private LineShape _line = null;
/**
* Debrief data
*/
private Layers _myLayers;
private Layers.DataListener _myLayersListener;
private ICrossSectionDatasetProvider _datasetProvider =
new CrossSectionDatasetProvider();
/**
* store the plot information when we're reloading a plot in a fresh session
*/
private IMemento _memento = null;
/**
* Toolbar drop down for specifying time period
*/
private SnailPeriodTracker _snailMode = new SnailPeriodTracker();
@Override
public void createPartControl(final Composite parent)
{
_viewer = new CrossSectionViewer(parent);
_partMonitor = new PartMonitor(getSite().getWorkbenchWindow()
.getPartService());
listenToMyParts();
setupFiringTimeChangesToChart();
contributeToActionBars();
_selectionChangeListener = new ISelectionChangedListener()
{
@Override
public void selectionChanged(final SelectionChangedEvent event)
{
final ISelection sel = event.getSelection();
if (!(sel instanceof IStructuredSelection))
return;
final IStructuredSelection ss = (IStructuredSelection) sel;
final Object o = ss.getFirstElement();
if (o instanceof EditableWrapper)
{
// check if Line annotation is selected
final Editable eb = ((EditableWrapper) o).getEditable();
if (eb instanceof ShapeWrapper)
{
final PlainShape shape = ((ShapeWrapper) eb).getShape();
if (shape instanceof LineShape && !shape.equals(_line))
{
clearLineListener();
_line = (LineShape) shape;
_line.addPropertyListener(_lineListener);
_viewer.fillPlot(_myLayers, _line, _datasetProvider);
}
}
}
}
};
_viewer.addSelectionChangedListener(_selectionChangeListener);
_snailMode.addSnailPeriodChangedListener(this);
// have we got our data?
if (_memento != null)
{
// restore it
_viewer.restoreState(_memento);
_snailMode.setPeriod(_viewer.getPeriod());
}
}
private void contributeToActionBars()
{
final IActionBars bars = getViewSite().getActionBars();
fillLocalToolBar(bars.getToolBarManager());
}
private void fillLocalToolBar(final IToolBarManager manager)
{
manager.add(_snailMode);
}
@Override
public void init(final IViewSite site, final IMemento memento) throws PartInitException
{
super.init(site, memento);
if (memento != null)
{
_memento = memento;
}
}
private void listenToMyParts()
{
// Listen to Layers
_partMonitor.addPartListener(Layers.class, PartMonitor.ACTIVATED,
new PartMonitor.ICallback()
{
public void eventTriggered(final String type, final Object part,
final IWorkbenchPart parentPart)
{
processNewLayers(part);
}
});
_partMonitor.addPartListener(Layers.class, PartMonitor.OPENED,
new PartMonitor.ICallback()
{
public void eventTriggered(final String type, final Object part,
final IWorkbenchPart parentPart)
{
processNewLayers(part);
}
});
_partMonitor.addPartListener(Layers.class, PartMonitor.CLOSED,
new PartMonitor.ICallback()
{
public void eventTriggered(final String type, final Object part,
final IWorkbenchPart parentPart)
{
// is this our set of layers?
if (part == _myLayers)
{
clearLineListener();
// stop listening to this layer
clearLayerListener();
}
}
});
_partMonitor.addPartListener(ISelectionProvider.class,
PartMonitor.ACTIVATED, new PartMonitor.ICallback()
{
public void eventTriggered(final String type, final Object part,
final IWorkbenchPart parentPart)
{
// aah, just check it's not is
if (part != _viewer)
{
final ISelectionProvider iS = (ISelectionProvider) part;
if (!iS.equals(_selectionProvider))
{
if (part instanceof IEditorPart)
setUpTimeProvider((IEditorPart) part);
_selectionProvider = iS;
if (_selectionChangeListener != null)
{
_selectionProvider
.addSelectionChangedListener(_selectionChangeListener);
}
}
}
}
});
_partMonitor.addPartListener(ISelectionProvider.class,
PartMonitor.DEACTIVATED, new PartMonitor.ICallback()
{
public void eventTriggered(final String type, final Object part,
final IWorkbenchPart parentPart)
{
// aah, just check it's not is
if (part != _viewer)
{
if (_selectionProvider != null && _selectionChangeListener != null)
{
_selectionProvider
.removeSelectionChangedListener(_selectionChangeListener);
}
}
}
});
// ok we're all ready now. just try and see if the current part is valid
_partMonitor.fireActivePart(getSite().getWorkbenchWindow()
.getActivePage());
}
private void setupFiringTimeChangesToChart()
{
// see if we've alreay been configured
if (_timeListener != null)
return;
// get the document being edited
final IWorkbench wb = PlatformUI.getWorkbench();
final IWorkbenchWindow win = wb.getActiveWorkbenchWindow();
final IWorkbenchPage page = win.getActivePage();
IEditorPart editor = null;
// the page might not yet be open...
if (page != null)
{
editor = page.getActiveEditor();
// do we have an active editor?
if (editor == null)
{
// see if there are any editors at all open
final IEditorReference[] theEditors = page.getEditorReferences();
for (int i = 0; i < theEditors.length; i++)
{
final IEditorReference thisE = theEditors[i];
editor = thisE.getEditor(false);
// right, see if it has a time manager
final TimeProvider tp = (TimeProvider) editor
.getAdapter(TimeProvider.class);
if (tp != null)
{
final String hisId = tp.getId();
if (hisId.equals(_viewer.getPlotId()))
break;
}
}
// nope, drop out.
return;
}
}
setUpTimeProvider(editor);
}
private void setUpTimeProvider(IEditorPart editor)
{
if (editor != null)
{
// get it's time-provider interface
final TimeProvider prov = (TimeProvider) editor.getAdapter(TimeProvider.class);
if (_timeProvider != null && _timeProvider.equals(prov))
return;
if (_timeListener != null)
_timeProvider.removeListener(_timeListener,
TimeProvider.TIME_CHANGED_PROPERTY_NAME);
_timeProvider = prov;
}
else
CorePlugin.logError(Status.WARNING, "Failed to identify time provider",
null);
if (_timeProvider != null)
{
// create our listener
_timeListener = new NewTimeListener();
// add our listener to the time object
_timeProvider.addListener(_timeListener,
TimeProvider.TIME_CHANGED_PROPERTY_NAME);
_viewer.setPlotId(_timeProvider.getId());
}
}
@Override
public void setFocus()
{
//TODO:
}
void processNewLayers(final Object part)
{
// just check we're not already looking at it
if (part.equals(_myLayers))
return;
// de-register current layers before tracking the new one
clearLayerListener();
clearLineListener();
_viewer.clearPlot();
_myLayers = (Layers) part;
if (_myLayersListener == null)
{
_myLayersListener = new Layers.DataListener2()
{
public void dataModified(final Layers theData, final Layer changedLayer)
{
processReformattedLayer(theData, changedLayer);
}
public void dataExtended(final Layers theData)
{
dataExtended(theData, null, null);
}
public void dataReformatted(final Layers theData, final Layer changedLayer)
{
processReformattedLayer(theData, changedLayer);
}
public void dataExtended(final Layers theData, final Plottable newItem,
final Layer parentLayer)
{
processNewData(theData, newItem, parentLayer);
}
};
}
// right, listen for data being added
_myLayers.addDataExtendedListener(_myLayersListener);
// and listen for items being reformatted
_myLayers.addDataReformattedListener(_myLayersListener);
// and listen for items being reformatted
_myLayers.addDataModifiedListener(_myLayersListener);
// do an initial population.
processNewData(_myLayers, null, null);
}
void processReformattedLayer(final Layers theData, final Layer changedLayer)
{
_viewer.fillPlot(theData, _line, _datasetProvider);
}
@Override
public void snailPeriodChanged(final long timePeriod)
{
_viewer.fillPlot(_myLayers, _line, _datasetProvider, timePeriod);
}
void processNewData(final Layers theData, final Editable newItem,
final Layer parentLayer)
{
Display.getDefault().asyncExec(new Runnable()
{
public void run()
{
// ok, fire the change in the UI thread
_viewer.fillPlot(theData, _line, _datasetProvider);
}
});
}
/**
* stop listening to the layer, if necessary
*/
void clearLayerListener()
{
if (_myLayers != null)
{
_myLayers.removeDataExtendedListener(_myLayersListener);
_myLayersListener = null;
_myLayers = null;
}
}
void clearLineListener()
{
if (_line != null)
{
_line.removePropertyListener(_lineListener);
_lineListener = null;
_line = null;
}
}
void clearTimeListener()
{
if (_timeProvider != null)
{
_timeProvider.removeListener(_timeListener,
TimeProvider.TIME_CHANGED_PROPERTY_NAME);
_timeListener = null;
_timeProvider = null;
}
}
public void dispose()
{
super.dispose();
// make sure we close the listeners
clearLayerListener();
clearLineListener();
clearTimeListener();
if(_viewer != null)
{
_viewer.removeSelectionChangedListener(_selectionChangeListener);
}
if (_selectionProvider != null)
{
_selectionProvider.removeSelectionChangedListener(_selectionChangeListener);
_selectionProvider = null;
}
_selectionChangeListener = null;
_viewer.clearPlot();
}
@Override
public void saveState(final IMemento memento)
{
// let our parent go for it first
super.saveState(memento);
_viewer.saveState(memento);
}
protected final class LineChangeListener implements PropertyChangeListener
{
public void propertyChange(final PropertyChangeEvent event)
{
if (event.getPropertyName().equals(
PlainWrapper.LOCATION_CHANGED))
{
final Runnable nextEvent = new Runnable()
{
public void run()
{
if (event.getSource().equals(_line))
{
_viewer.fillPlot(_myLayers, _line, _datasetProvider);
}
}
};
Display.getDefault().syncExec(nextEvent);
}
}
}
protected final class NewTimeListener implements PropertyChangeListener
{
public void propertyChange(final PropertyChangeEvent event)
{
// see if it's the time or the period which
// has changed
if (event.getPropertyName().equals(
TimeProvider.TIME_CHANGED_PROPERTY_NAME))
{
// ok, use the new time
final HiResDate newDTG = (HiResDate) event.getNewValue();
final Runnable nextEvent = new Runnable()
{
public void run()
{
_viewer.newTime(newDTG);
_viewer.fillPlot(_myLayers, _line, _datasetProvider);
}
};
Display.getDefault().syncExec(nextEvent);
}
}
}
}
|
package gov.nih.nci.cananolab.service.particle.impl;
import gov.nih.nci.cananolab.domain.common.File;
import gov.nih.nci.cananolab.domain.particle.ChemicalAssociation;
import gov.nih.nci.cananolab.domain.particle.ComposingElement;
import gov.nih.nci.cananolab.domain.particle.Function;
import gov.nih.nci.cananolab.domain.particle.FunctionalizingEntity;
import gov.nih.nci.cananolab.domain.particle.NanoparticleEntity;
import gov.nih.nci.cananolab.domain.particle.NanoparticleSample;
import gov.nih.nci.cananolab.domain.particle.SampleComposition;
import gov.nih.nci.cananolab.dto.common.FileBean;
import gov.nih.nci.cananolab.dto.common.UserBean;
import gov.nih.nci.cananolab.dto.particle.composition.ChemicalAssociationBean;
import gov.nih.nci.cananolab.dto.particle.composition.ComposingElementBean;
import gov.nih.nci.cananolab.dto.particle.composition.CompositionBean;
import gov.nih.nci.cananolab.dto.particle.composition.FunctionalizingEntityBean;
import gov.nih.nci.cananolab.dto.particle.composition.NanoparticleEntityBean;
import gov.nih.nci.cananolab.exception.CaNanoLabSecurityException;
import gov.nih.nci.cananolab.exception.ParticleCompositionException;
import gov.nih.nci.cananolab.service.common.FileService;
import gov.nih.nci.cananolab.service.common.impl.FileServiceLocalImpl;
import gov.nih.nci.cananolab.service.particle.NanoparticleCompositionService;
import gov.nih.nci.cananolab.service.particle.helper.NanoparticleCompositionServiceHelper;
import gov.nih.nci.cananolab.service.security.AuthorizationService;
import gov.nih.nci.cananolab.system.applicationservice.CustomizedApplicationService;
import gov.nih.nci.cananolab.util.CaNanoLabConstants;
import gov.nih.nci.system.client.ApplicationServiceProvider;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import org.apache.log4j.Logger;
import org.hibernate.FetchMode;
import org.hibernate.criterion.CriteriaSpecification;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Property;
/**
* Local implementation of NanoparticleCompositionService.
*
* @author pansu
*
*/
public class NanoparticleCompositionServiceLocalImpl implements
NanoparticleCompositionService {
private static Logger logger = Logger
.getLogger(NanoparticleCompositionServiceLocalImpl.class);
private NanoparticleCompositionServiceHelper helper = new NanoparticleCompositionServiceHelper();
public NanoparticleCompositionServiceLocalImpl() {
}
public void saveNanoparticleEntity(NanoparticleSample particleSample,
NanoparticleEntity entity) throws ParticleCompositionException {
try {
CustomizedApplicationService appService = (CustomizedApplicationService) ApplicationServiceProvider
.getApplicationService();
if (entity.getId() != null) {
try {
NanoparticleEntity dbEntity = (NanoparticleEntity) appService
.load(NanoparticleEntity.class, entity.getId());
} catch (Exception e) {
String err = "Object doesn't exist in the database anymore. Please log in again.";
logger.error(err);
throw new ParticleCompositionException(err, e);
}
}
boolean newSampleComposition = false;
if (particleSample.getSampleComposition() == null) {
particleSample.setSampleComposition(new SampleComposition());
particleSample.getSampleComposition().setNanoparticleSample(
particleSample);
particleSample.getSampleComposition()
.setNanoparticleEntityCollection(
new HashSet<NanoparticleEntity>());
newSampleComposition = true;
}
entity.setSampleComposition(particleSample.getSampleComposition());
particleSample.getSampleComposition()
.getNanoparticleEntityCollection().add(entity);
FileService service = new FileServiceLocalImpl();
Collection<File> Files = entity.getFileCollection();
if (Files != null) {
for (File file : Files) {
service.prepareSaveFile(file);
}
}
appService.saveOrUpdate(entity);
} catch (Exception e) {
String err = "Error in saving a nanoparticle entity.";
logger.error(err, e);
throw new ParticleCompositionException(err, e);
}
}
public NanoparticleEntityBean findNanoparticleEntityById(String entityId)
throws ParticleCompositionException {
NanoparticleEntityBean entityBean = null;
try {
NanoparticleEntity entity = helper
.findNanoparticleEntityById(entityId);
if (entity != null)
entityBean = new NanoparticleEntityBean(entity);
return entityBean;
} catch (Exception e) {
String err = "Problem finding the nanoparticle entity by id: "
+ entityId;
logger.error(err, e);
throw new ParticleCompositionException(err, e);
}
}
public NanoparticleEntityBean findNanoparticleEntityById(String entityId,
String entityClassName) throws ParticleCompositionException {
return findNanoparticleEntityById(entityId);
}
public void saveFunctionalizingEntity(NanoparticleSample particleSample,
FunctionalizingEntity entity) throws ParticleCompositionException {
try {
CustomizedApplicationService appService = (CustomizedApplicationService) ApplicationServiceProvider
.getApplicationService();
if (entity.getId() != null) {
try {
FunctionalizingEntity dbEntity = (FunctionalizingEntity) appService
.load(FunctionalizingEntity.class, entity.getId());
} catch (Exception e) {
String err = "Object doesn't exist in the database anymore. Please log in again.";
logger.error(err);
throw new ParticleCompositionException(err, e);
}
}
boolean newSampleComposition = false;
if (particleSample.getSampleComposition() == null) {
particleSample.setSampleComposition(new SampleComposition());
particleSample.getSampleComposition().setNanoparticleSample(
particleSample);
particleSample.getSampleComposition()
.setFunctionalizingEntityCollection(
new HashSet<FunctionalizingEntity>());
newSampleComposition = true;
}
entity.setSampleComposition(particleSample.getSampleComposition());
particleSample.getSampleComposition()
.getFunctionalizingEntityCollection().add(entity);
FileService service = new FileServiceLocalImpl();
Collection<File> Files = entity.getFileCollection();
if (Files != null) {
for (File file : Files) {
service.prepareSaveFile(file);
}
}
appService.saveOrUpdate(entity);
} catch (Exception e) {
String err = "Problem saving the functionalizing entity.";
logger.error(err, e);
throw new ParticleCompositionException(err, e);
}
}
public void saveChemicalAssociation(NanoparticleSample particleSample,
ChemicalAssociation assoc) throws ParticleCompositionException {
try {
CustomizedApplicationService appService = (CustomizedApplicationService) ApplicationServiceProvider
.getApplicationService();
if (assoc.getId() != null) {
try {
ChemicalAssociation dbAssoc = (ChemicalAssociation) appService
.load(ChemicalAssociation.class, assoc.getId());
} catch (Exception e) {
String err = "Object doesn't exist in the database anymore. Please log in again.";
logger.error(err);
throw new ParticleCompositionException(err, e);
}
}
SampleComposition composition = particleSample
.getSampleComposition();
composition.getChemicalAssociationCollection().add(assoc);
FileService service = new FileServiceLocalImpl();
Collection<File> Files = assoc.getFileCollection();
if (Files != null) {
for (File file : Files) {
service.prepareSaveFile(file);
}
}
if (assoc.getId() == null) { // because of unidirectional
// relationship between composition
// and chemical associations
appService.saveOrUpdate(composition);
} else {
appService.saveOrUpdate(assoc);
}
} catch (Exception e) {
String err = "Problem saving the chemical assocation.";
logger.error(err, e);
throw new ParticleCompositionException(err, e);
}
}
public void saveCompositionFile(NanoparticleSample particleSample,
File file, byte[] fileData) throws ParticleCompositionException {
try {
FileService fileService = new FileServiceLocalImpl();
fileService.prepareSaveFile(file);
CustomizedApplicationService appService = (CustomizedApplicationService) ApplicationServiceProvider
.getApplicationService();
if (particleSample.getSampleComposition() == null) {
particleSample.setSampleComposition(new SampleComposition());
particleSample.getSampleComposition().setNanoparticleSample(
particleSample);
particleSample.getSampleComposition().setFileCollection(
new HashSet<File>());
}
particleSample.getSampleComposition().getFileCollection().add(file);
if (file.getId() == null) { // because of unidirectional
// relationship between composition
// and lab files
appService.saveOrUpdate(particleSample.getSampleComposition());
} else {
appService.saveOrUpdate(file);
}
// save to the file system fileData is not empty
fileService.writeFile(file, fileData);
} catch (Exception e) {
String err = "Error in saving the composition file.";
logger.error(err, e);
throw new ParticleCompositionException(err, e);
}
}
public FunctionalizingEntityBean findFunctionalizingEntityById(
String entityId) throws ParticleCompositionException {
FunctionalizingEntityBean entityBean = null;
try {
FunctionalizingEntity entity = helper
.findFunctionalizingEntityById(entityId);
if (entity != null)
entityBean = new FunctionalizingEntityBean(entity);
return entityBean;
} catch (Exception e) {
String err = "Problem finding the functionalizing entity by id: "
+ entityId;
logger.error(err, e);
throw new ParticleCompositionException(err, e);
}
}
public FunctionalizingEntityBean findFunctionalizingEntityById(
String entityId, String entityClassName)
throws ParticleCompositionException {
return findFunctionalizingEntityById(entityId);
}
public ChemicalAssociationBean findChemicalAssociationById(String assocId)
throws ParticleCompositionException {
ChemicalAssociationBean assocBean = null;
try {
ChemicalAssociation assoc = helper
.findChemicalAssocationById(assocId);
if (assoc != null)
assocBean = new ChemicalAssociationBean(assoc);
return assocBean;
} catch (Exception e) {
String err = "Problem finding the chemical association by id: "
+ assocId;
logger.error(err, e);
throw new ParticleCompositionException(err, e);
}
}
public ChemicalAssociationBean findChemicalAssociationById(
String particleId, String assocId, String assocClassName)
throws ParticleCompositionException {
return findChemicalAssociationById(assocId);
}
public void retrieveVisibility(NanoparticleEntityBean entity, UserBean user)
throws ParticleCompositionException {
try {
FileService fileService = new FileServiceLocalImpl();
for (FileBean file : entity.getFiles()) {
fileService.retrieveVisibility(file, user);
}
} catch (Exception e) {
String err = "Error setting visiblity for nanoparticle entity "
+ entity.getType();
logger.error(err, e);
throw new ParticleCompositionException(err, e);
}
}
public void retrieveVisibility(FunctionalizingEntityBean entity,
UserBean user) throws ParticleCompositionException {
try {
FileService fileService = new FileServiceLocalImpl();
for (FileBean file : entity.getFiles()) {
fileService.retrieveVisibility(file, user);
}
} catch (Exception e) {
String err = "Error setting visiblity for functionalizing entity "
+ entity.getType();
logger.error(err, e);
throw new ParticleCompositionException(err, e);
}
}
public void retrieveVisibility(ChemicalAssociationBean assoc, UserBean user)
throws ParticleCompositionException {
try {
FileService fileService = new FileServiceLocalImpl();
for (FileBean file : assoc.getFiles()) {
fileService.retrieveVisibility(file, user);
}
} catch (Exception e) {
String err = "Error setting visiblity for chemical association "
+ assoc.getType();
logger.error(err, e);
throw new ParticleCompositionException(err, e);
}
}
public void deleteNanoparticleEntity(NanoparticleEntity entity)
throws ParticleCompositionException {
try {
AuthorizationService authService = new AuthorizationService(
CaNanoLabConstants.CSM_APP_NAME);
removeNanoparticleEntityPublicVisibility(authService, entity);
CustomizedApplicationService appService = (CustomizedApplicationService) ApplicationServiceProvider
.getApplicationService();
appService.delete(entity);
} catch (Exception e) {
String err = "Error deleting nanoparticle entity " + entity.getId();
logger.error(err, e);
throw new ParticleCompositionException(err, e);
}
}
public void deleteFunctionalizingEntity(FunctionalizingEntity entity)
throws ParticleCompositionException {
try {
AuthorizationService authService = new AuthorizationService(
CaNanoLabConstants.CSM_APP_NAME);
removeFunctionalizingEntityPublicVisibility(authService, entity);
CustomizedApplicationService appService = (CustomizedApplicationService) ApplicationServiceProvider
.getApplicationService();
appService.delete(entity);
} catch (Exception e) {
String err = "Error deleting functionalizing entity "
+ entity.getId();
logger.error(err, e);
throw new ParticleCompositionException(err, e);
}
}
public void deleteChemicalAssociation(ChemicalAssociation assoc)
throws ParticleCompositionException {
try {
AuthorizationService authService = new AuthorizationService(
CaNanoLabConstants.CSM_APP_NAME);
removeChemicalAssociationPublicVisibility(authService, assoc);
CustomizedApplicationService appService = (CustomizedApplicationService) ApplicationServiceProvider
.getApplicationService();
appService.delete(assoc);
} catch (Exception e) {
String err = "Error deleting chemical association " + assoc.getId();
logger.error(err, e);
throw new ParticleCompositionException(err, e);
}
}
public void deleteCompositionFile(NanoparticleSample particleSample,
File file) throws ParticleCompositionException {
try {
CustomizedApplicationService appService = (CustomizedApplicationService) ApplicationServiceProvider
.getApplicationService();
particleSample.getSampleComposition().getFileCollection().remove(
file);
appService.saveOrUpdate(particleSample.getSampleComposition());
} catch (Exception e) {
String err = "Error deleting composition file " + file.getUri();
logger.error(err, e);
throw new ParticleCompositionException(err, e);
}
}
// check if any composing elements of the nanoparticle entity is invovled in
// the chemical association
public boolean checkChemicalAssociationBeforeDelete(
NanoparticleEntityBean entityBean) {
// need to delete chemical associations first if associated elements
// are composing elements
Collection<ChemicalAssociation> assocSet = entityBean.getDomainEntity()
.getSampleComposition().getChemicalAssociationCollection();
if (assocSet != null) {
for (ChemicalAssociation assoc : assocSet) {
if (entityBean.getDomainEntity()
.getComposingElementCollection().contains(
assoc.getAssociatedElementA())
|| entityBean.getDomainEntity()
.getComposingElementCollection().contains(
assoc.getAssociatedElementB())) {
return false;
}
}
}
return true;
}
// check if the composing element is invovled in the chemical
// association
public boolean checkChemicalAssociationBeforeDelete(
ComposingElementBean ceBean) {
if (ceBean.getDomainComposingElement().getId() != null) {
Collection<ChemicalAssociation> assocSet = ceBean
.getDomainComposingElement().getNanoparticleEntity()
.getSampleComposition().getChemicalAssociationCollection();
if (assocSet != null) {
for (ChemicalAssociation assoc : assocSet) {
if (ceBean.getDomainComposingElement().equals(
assoc.getAssociatedElementA())
|| ceBean.getDomainComposingElement().equals(
assoc.getAssociatedElementB())) {
return false;
}
}
}
}
return true;
}
// check if the composing element is invovled in the chemical
// association
public boolean checkChemicalAssociationBeforeDelete(
FunctionalizingEntityBean entityBean) {
// need to delete chemical associations first if associated elements
// are functionalizing entities
Collection<ChemicalAssociation> assocSet = entityBean.getDomainEntity()
.getSampleComposition().getChemicalAssociationCollection();
if (assocSet != null) {
for (ChemicalAssociation assoc : assocSet) {
if (entityBean.getDomainEntity().equals(
assoc.getAssociatedElementA())
|| entityBean.getDomainEntity().equals(
assoc.getAssociatedElementB())) {
return false;
}
}
}
return true;
}
public CompositionBean findCompositionByParticleSampleId(String particleId)
throws ParticleCompositionException {
try {
CustomizedApplicationService appService = (CustomizedApplicationService) ApplicationServiceProvider
.getApplicationService();
DetachedCriteria crit = DetachedCriteria
.forClass(SampleComposition.class);
crit.createAlias("nanoparticleSample", "sample");
crit.add(Property.forName("sample.id").eq(new Long(particleId)));
// fully load composition
crit.setFetchMode("nanoparticleEntityCollection", FetchMode.JOIN);
crit.setFetchMode("nanoparticleEntityCollection.fileCollection",
FetchMode.JOIN);
crit
.setFetchMode(
"nanoparticleEntityCollection.fileCollection.keywordCollection",
FetchMode.JOIN);
crit
.setFetchMode(
"nanoparticleEntityCollection.composingElementCollection",
FetchMode.JOIN);
crit
.setFetchMode(
"nanoparticleEntityCollection.composingElementCollection.inherentFunctionCollection",
FetchMode.JOIN);
crit
.setFetchMode("functionalizingEntityCollection",
FetchMode.JOIN);
crit.setFetchMode("functionalizingEntityCollection.fileCollection",
FetchMode.JOIN);
crit
.setFetchMode(
"functionalizingEntityCollection.fileCollection.keywordCollection",
FetchMode.JOIN);
crit.setFetchMode(
"functionalizingEntityCollection.functionCollection",
FetchMode.JOIN);
crit.setFetchMode("chemicalAssociationCollection", FetchMode.JOIN);
crit.setFetchMode("chemicalAssociationCollection.fileCollection",
FetchMode.JOIN);
crit.setFetchMode(
"chemicalAssociationCollection.associatedElementA",
FetchMode.JOIN);
crit.setFetchMode(
"chemicalAssociationCollection.associatedElementB",
FetchMode.JOIN);
crit.setFetchMode("fileCollection", FetchMode.JOIN);
crit.setFetchMode("fileCollection.keywordCollection",
FetchMode.JOIN);
crit
.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
List result = appService.query(crit);
CompositionBean comp = null;
if (!result.isEmpty()) {
comp = new CompositionBean((SampleComposition) result.get(0));
}
return comp;
} catch (Exception e) {
throw new ParticleCompositionException(
"Error finding composition by particle ID: " + particleId);
}
}
public void assignChemicalAssociationPublicVisibility(
AuthorizationService authService,
ChemicalAssociation chemicalAssociation)
throws CaNanoLabSecurityException {
if (chemicalAssociation != null) {
removeChemicalAssociationPublicVisibility(authService,
chemicalAssociation);
authService.assignPublicVisibility(chemicalAssociation.getId()
.toString());
// chemicalAssociation.associatedElementA
if (chemicalAssociation.getAssociatedElementA() != null) {
authService.assignPublicVisibility(chemicalAssociation
.getAssociatedElementA().getId().toString());
}
// chemicalAssociation.associatedElementB
if (chemicalAssociation.getAssociatedElementB() != null) {
authService.assignPublicVisibility(chemicalAssociation
.getAssociatedElementB().getId().toString());
}
}
}
public void assignNanoparicleEntityPublicVisibility(
AuthorizationService authService,
NanoparticleEntity nanoparticleEntity)
throws CaNanoLabSecurityException {
if (nanoparticleEntity != null) {
authService.assignPublicVisibility(nanoparticleEntity.getId()
.toString());
// nanoparticleEntityCollection.composingElementCollection,
Collection<ComposingElement> composingElementCollection = nanoparticleEntity
.getComposingElementCollection();
if (composingElementCollection != null) {
for (ComposingElement composingElement : composingElementCollection) {
if (composingElement != null) {
authService.assignPublicVisibility(composingElement
.getId().toString());
}
// composingElementCollection.inherentFucntionCollection
Collection<Function> inherentFunctionCollection = composingElement
.getInherentFunctionCollection();
if (inherentFunctionCollection != null) {
for (Function function : inherentFunctionCollection) {
if (function != null) {
authService.assignPublicVisibility(function
.getId().toString());
}
}
}
}
}
}
}
public void assignFunctionalizingEntityPublicVisibility(
AuthorizationService authService,
FunctionalizingEntity functionalizingEntity)
throws CaNanoLabSecurityException {
if (functionalizingEntity != null) {
authService.assignPublicVisibility(functionalizingEntity.getId()
.toString());
// functionalizingEntityCollection.functionCollection
Collection<Function> functionCollection = functionalizingEntity
.getFunctionCollection();
if (functionCollection != null) {
for (Function function : functionCollection) {
if (function != null) {
authService.assignPublicVisibility(function.getId()
.toString());
}
}
}
// TODO activation method
}
}
public void removeNanoparticleEntityPublicVisibility(
AuthorizationService authService,
NanoparticleEntity nanoparticleEntity)
throws CaNanoLabSecurityException {
if (nanoparticleEntity != null) {
authService
.removePublicGroup(nanoparticleEntity.getId().toString());
// nanoparticleEntityCollection.composingElementCollection,
Collection<ComposingElement> composingElementCollection = nanoparticleEntity
.getComposingElementCollection();
if (composingElementCollection != null) {
for (ComposingElement composingElement : composingElementCollection) {
if (composingElement != null) {
authService.removePublicGroup(composingElement.getId()
.toString());
}
// composingElementCollection.inherentFucntionCollection
Collection<Function> inherentFunctionCollection = composingElement
.getInherentFunctionCollection();
if (inherentFunctionCollection != null) {
for (Function function : inherentFunctionCollection) {
if (function != null) {
authService.removePublicGroup(function.getId()
.toString());
}
}
}
}
}
}
}
public void removeFunctionalizingEntityPublicVisibility(
AuthorizationService authService,
FunctionalizingEntity functionalizingEntity)
throws CaNanoLabSecurityException {
if (functionalizingEntity != null) {
authService.removePublicGroup(functionalizingEntity.getId()
.toString());
// functionalizingEntityCollection.functionCollection
Collection<Function> functionCollection = functionalizingEntity
.getFunctionCollection();
if (functionCollection != null) {
for (Function function : functionCollection) {
if (function != null) {
authService.removePublicGroup(function.getId()
.toString());
}
}
}
}
}
public void removeChemicalAssociationPublicVisibility(
AuthorizationService authService,
ChemicalAssociation chemicalAssociation)
throws CaNanoLabSecurityException {
if (chemicalAssociation != null) {
authService.removePublicGroup(chemicalAssociation.getId()
.toString());
// chemicalAssociation.associatedElementA
if (chemicalAssociation.getAssociatedElementA() != null) {
authService.removePublicGroup(chemicalAssociation
.getAssociatedElementA().getId().toString());
}
// chemicalAssociation.associatedElementB
if (chemicalAssociation.getAssociatedElementB() != null) {
authService.removePublicGroup(chemicalAssociation
.getAssociatedElementB().getId().toString());
}
}
}
public void assignPublicVisibility(AuthorizationService authService,
SampleComposition composition) throws CaNanoLabSecurityException {
// sampleComposition.nanoparticleEntityCollection,
Collection<NanoparticleEntity> nanoparticleEntityCollection = composition
.getNanoparticleEntityCollection();
if (nanoparticleEntityCollection != null) {
for (NanoparticleEntity nanoparticleEntity : nanoparticleEntityCollection) {
assignNanoparicleEntityPublicVisibility(authService,
nanoparticleEntity);
}
}
// sampleComposition.functionalizingEntityCollection,
Collection<FunctionalizingEntity> functionalizingEntityCollection = composition
.getFunctionalizingEntityCollection();
if (functionalizingEntityCollection != null) {
for (FunctionalizingEntity functionalizingEntity : functionalizingEntityCollection) {
assignFunctionalizingEntityPublicVisibility(authService,
functionalizingEntity);
}
}
// sampleComposition.chemicalAssociationCollection
Collection<ChemicalAssociation> chemicalAssociationCollection = composition
.getChemicalAssociationCollection();
if (functionalizingEntityCollection != null) {
for (ChemicalAssociation chemicalAssociation : chemicalAssociationCollection) {
assignChemicalAssociationPublicVisibility(authService,
chemicalAssociation);
}
}
}
}
|
package com.infinityraider.elementalinvocations.render.player;
import com.infinityraider.elementalinvocations.api.Element;
import com.infinityraider.elementalinvocations.api.IMagicCharge;
import com.infinityraider.elementalinvocations.api.IPotencyMap;
import com.infinityraider.elementalinvocations.reference.Constants;
import com.infinityraider.elementalinvocations.reference.Reference;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.Gui;
import net.minecraft.client.gui.ScaledResolution;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.client.renderer.VertexBuffer;
import net.minecraft.client.renderer.entity.RenderManager;
import net.minecraft.client.renderer.vertex.DefaultVertexFormats;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import org.lwjgl.opengl.GL11;
import java.util.List;
@SideOnly(Side.CLIENT)
public class MagicChargeRenderer {
private static final MagicChargeRenderer INSTANCE = new MagicChargeRenderer();
public static MagicChargeRenderer getInstance() {
return INSTANCE;
}
private static final int MAX_BLURS = 5;
private static final double RADIUS = 1.0;
private static final ResourceLocation[] CHARGE_TEXTURES;
public static ResourceLocation getTexture(Element element) {
return CHARGE_TEXTURES[element.ordinal()];
}
private MagicChargeRenderer() {}
public void renderChargesThirdPerson(List<IMagicCharge> charges) {
renderCharges(charges, RADIUS, getCurrentAngle(), 1.0F);
}
public void renderInvokeThirdPerson(List<IMagicCharge> charges, IPotencyMap potencies, int frame, int total, float partialTick) {
if(frame <= 0) {
return;
}
GlStateManager.pushMatrix();
double deltaY = (0.5*(frame + partialTick))/total;
GlStateManager.translate(0, deltaY, 0);
double radius = RADIUS*((double) total - frame + partialTick) / total;
renderCharges(charges, radius, getCurrentAngle(), 1.0F);
GlStateManager.popMatrix();
}
public void renderFadeThirdPerson(List<IMagicCharge> charges, IPotencyMap potencies, int frame, int total, float partialTick) {
if(frame <= 0) {
return;
}
float scale = (total - frame + partialTick) / total;
renderCharges(charges, RADIUS, getCurrentAngle(), scale);
}
public void renderFizzleThirdPerson(List<IMagicCharge> charges, IPotencyMap potencies, int frame, int total, float partialTick) {
if(charges == null ||charges.size() <= 0) {
return;
}
}
public void renderChargesFirstPerson(List<IMagicCharge> charges, ScaledResolution resolution) {
if (!charges.isEmpty()) {
Tessellator tessellator = Tessellator.getInstance();
VertexBuffer buffer = tessellator.getBuffer();
GlStateManager.pushMatrix();
GlStateManager.pushAttrib();
GlStateManager.enableBlend();
GlStateManager.blendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F);
int index = 0;
int row = 0;
int perRow = (resolution.getScaledWidth() / (4 * 18));
int x0 = resolution.getScaledWidth() / 2 + 103;
int y0 = resolution.getScaledHeight() - 11;
GlStateManager.enableBlend();
GlStateManager.disableLighting();
GlStateManager.blendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
GlStateManager.alphaFunc(GL11.GL_GREATER, 0.05F);
for (IMagicCharge charge : charges) {
Minecraft.getMinecraft().renderEngine.bindTexture(getTexture(charge.element()));
GlStateManager.pushMatrix();
buffer.begin(GL11.GL_QUADS, DefaultVertexFormats.POSITION_TEX);
float scale = (0.6F + (0.5F * charge.potency()) / Constants.CORE_TIERS);
float angle = (float) (360 * (System.currentTimeMillis() & 0x3FFFL) / 0x3FFFL);
int xC = x0 + index * 18;
int yC = y0 - row * 18;
GlStateManager.translate(xC, yC, 0);
GlStateManager.rotate(angle, 0, 0, 1);
double xMin = -8 * scale;
double xMax = 8 * scale;
double yMin = -8 * scale;
double yMax = 8 * scale;
buffer.pos(xMin, yMin, 0).tex(0, 0).endVertex();
buffer.pos(xMin, yMax, 0).tex(0, 1).endVertex();
buffer.pos(xMax, yMax, 0).tex(1, 1).endVertex();
buffer.pos(xMax, yMin, 0).tex(1, 0).endVertex();
tessellator.draw();
GlStateManager.popMatrix();
index = index + 1;
if (index > perRow) {
index = 0;
row = row + 1;
}
}
GlStateManager.popAttrib();
GlStateManager.popMatrix();
Minecraft.getMinecraft().renderEngine.bindTexture(Gui.ICONS);
}
}
public void renderInvokeFirstPerson(List<IMagicCharge> charges, IPotencyMap potencies, int frame, int total, float partialTick, ScaledResolution resolution) {
if(charges == null ||charges.size() <= 0) {
return;
}
}
public void renderFadeFirstPerson(List<IMagicCharge> charges, IPotencyMap potencies, int frame, int total, float partialTick, ScaledResolution resolution) {
if(charges == null ||charges.size() <= 0) {
return;
}
}
public void renderFizzleFirstPerson(List<IMagicCharge> charges, IPotencyMap potencies, int frame, int total, float partialTick, ScaledResolution resolution) {
if(charges == null ||charges.size() <= 0) {
return;
}
}
private double getCurrentAngle() {
return 360.0 * (System.currentTimeMillis() & 0x3FFFL) / ((double) 0x3FFFL);
}
private double[] calculateOrbPosition(double radius, double newAngle, int orbNumber, int totalOrbs, int blurIndex) {
int orbitNumber = orbNumber % 3;
int orbIndex = orbNumber / 3;
//calculate trajectories
double angle = (10 * (newAngle + 360 - (2.5F * blurIndex) / MAX_BLURS)) % 360;
double tilt = Math.toRadians(45);
double[] position = new double[3];
switch(orbitNumber) {
case 0:
double a = Math.toRadians(angle - 120 + (360 * orbIndex / getOrbsPerOrbit(orbitNumber, totalOrbs)));
position[0] = radius * Math.cos(a);
position[1] = 0;
position[2] = radius * Math.sin(a);
break;
case 1:
double b = Math.toRadians(-angle + 120 + (360 * orbIndex / getOrbsPerOrbit(orbitNumber, totalOrbs)));
position[0] = -radius * Math.sin(b) * Math.sin(tilt);
position[1] = radius * Math.sin(b) * Math.cos(tilt);
position[2] = radius * Math.cos(b);
break;
case 2:
double c = Math.toRadians(angle + (360 * orbIndex / getOrbsPerOrbit(orbitNumber, totalOrbs)));
position[0] = -radius * Math.sin(c) * Math.sin(-tilt);
position[1] = radius * Math.sin(c) * Math.cos(-tilt);
position[2] = radius * Math.cos(c);
break;
}
return position;
}
private int getOrbsPerOrbit(int orbitNumber, int totalOrbs) {
if(totalOrbs <= orbitNumber) {
return 0;
}
switch(orbitNumber) {
case 0: return 1 + (totalOrbs - 1) / 3;
case 1:return 1 + (totalOrbs - 2) / 3;
case 2: return totalOrbs / 3;
}
return 0;
}
private void renderCharges(List<IMagicCharge> charges, double radius, double angle, float scale) {
if(charges == null ||charges.size() <= 0) {
return;
}
GlStateManager.pushMatrix();
GlStateManager.pushAttrib();
for(int orb = 0; orb < charges.size(); orb++) {
GlStateManager.enableBlend();
GlStateManager.disableLighting();
GlStateManager.blendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
GlStateManager.alphaFunc(GL11.GL_GREATER, 0.05F);
for(int blur = 0; blur < MAX_BLURS; blur++) {
double[] position = calculateOrbPosition(radius, angle, orb, charges.size(), blur);
renderCharge(charges.get(orb), position[0], position[1], position[2], blur, scale);
}
}
GlStateManager.popAttrib();
GlStateManager.popMatrix();
}
private void renderCharge(IMagicCharge charge, double x, double y, double z, int blurIndex, float scale) {
Minecraft.getMinecraft().renderEngine.bindTexture(getTexture(charge.element()));
Tessellator tessellator = Tessellator.getInstance();
VertexBuffer buffer = tessellator.getBuffer();
GlStateManager.pushMatrix();
//configure GL settings
GlStateManager.color(1F, 1F, 1F, 0.7F*(1.0F - (blurIndex + 0.0F)/MAX_BLURS));
//translate to the orb position
GlStateManager.translate(x, y + 1, z);
//rotate so the texture always renders parallel to the screen
RenderManager renderManager = Minecraft.getMinecraft().getRenderManager();
boolean invert = Minecraft.getMinecraft().gameSettings.thirdPersonView == 2;
GlStateManager.rotate(-renderManager.playerViewY, 0, 1, 0);
GlStateManager.rotate((invert ? -1 : 1) * renderManager.playerViewX, 1, 0, 0);
float u = Constants.UNIT;
float f = scale * 0.375F*(1.0F - 0.25F*(blurIndex+0.0F)/MAX_BLURS) * (0.6F + (0.5F * charge.potency())/Constants.CORE_TIERS);
buffer.begin(GL11.GL_QUADS, DefaultVertexFormats.POSITION_TEX);
buffer.pos(-8 * f * u, 0, 0).tex(1, 1).endVertex();
buffer.pos(-8 * f * u, 16 * f * u, 0).tex(1, 0).endVertex();
buffer.pos(8 * f * u, 16 * f * u, 0).tex(0, 0).endVertex();
buffer.pos(8 * f * u, 0, 0).tex(0, 1).endVertex();
tessellator.draw();
GlStateManager.popMatrix();
}
static {
ResourceLocation[] textures = new ResourceLocation[Element.values().length];
for(Element element : Element.values()) {
textures[element.ordinal()] = new ResourceLocation(Reference.MOD_ID.toLowerCase(),
"textures/entities/player/charge_" + element.name().toLowerCase() + ".png");
}
CHARGE_TEXTURES = textures;
}
}
|
package com.jaeksoft.searchlib.crawler.file.process.fileInstances;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import jcifs.smb.ACE;
import jcifs.smb.NtlmPasswordAuthentication;
import jcifs.smb.SID;
import jcifs.smb.SmbAuthException;
import jcifs.smb.SmbException;
import jcifs.smb.SmbFile;
import jcifs.smb.SmbFileFilter;
import com.jaeksoft.searchlib.Logging;
import com.jaeksoft.searchlib.SearchLibException;
import com.jaeksoft.searchlib.crawler.file.database.FilePathItem;
import com.jaeksoft.searchlib.crawler.file.database.FileTypeEnum;
import com.jaeksoft.searchlib.crawler.file.process.FileInstanceAbstract;
import com.jaeksoft.searchlib.crawler.file.process.FileInstanceAbstract.SecurityInterface;
import com.jaeksoft.searchlib.crawler.file.process.SecurityAccess;
import com.jaeksoft.searchlib.util.LinkUtils;
import com.jaeksoft.searchlib.util.RegExpUtils;
import com.jaeksoft.searchlib.util.StringUtils;
public class SmbFileInstance extends FileInstanceAbstract implements
SecurityInterface {
static {
System.setProperty("java.protocol.handler.pkgs", "jcifs");
System.setProperty("jicfs.resolveOrder", "LMHOSTS,DNS,WINS");
}
private SmbFile smbFileStore;
public SmbFileInstance() {
smbFileStore = null;
}
protected SmbFileInstance(FilePathItem filePathItem,
SmbFileInstance parent, SmbFile smbFile) throws URISyntaxException,
SearchLibException, UnsupportedEncodingException {
init(filePathItem, parent,
LinkUtils.concatPath(parent.getPath(), smbFile.getName()));
this.smbFileStore = smbFile;
}
@Override
public URI init() throws URISyntaxException {
return new URI("smb", filePathItem.getHost(), getPath(), null);
}
protected SmbFile getSmbFile() throws MalformedURLException {
if (smbFileStore != null)
return smbFileStore;
String context = StringUtils.fastConcat("smb://", getFilePathItem()
.getHost());
if (filePathItem.isGuest()) {
smbFileStore = new SmbFile(context, getPath());
} else {
NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication(
filePathItem.getDomain(), filePathItem.getUsername(),
filePathItem.getPassword());
smbFileStore = new SmbFile(context, getPath(), auth);
}
if (Logging.isDebug)
Logging.debug("SMB Connect to (without auth) "
+ smbFileStore.getURL().toString());
return smbFileStore;
}
@Override
public FileTypeEnum getFileType() throws SearchLibException {
try {
SmbFile smbFile = getSmbFile();
if (smbFile.isDirectory())
return FileTypeEnum.directory;
if (smbFile.isFile())
return FileTypeEnum.file;
return null;
} catch (MalformedURLException e) {
throw new SearchLibException(e);
} catch (SmbException e) {
throw new SearchLibException(e);
}
}
@Override
public String getFileName() throws SearchLibException {
try {
SmbFile smbFile = getSmbFile();
if (smbFile == null)
return null;
return smbFile.getName();
} catch (MalformedURLException e) {
throw new SearchLibException(e);
}
}
protected SmbFileInstance newInstance(FilePathItem filePathItem,
SmbFileInstance parent, SmbFile smbFile) throws URISyntaxException,
SearchLibException, UnsupportedEncodingException {
return new SmbFileInstance(filePathItem, parent, smbFile);
}
private FileInstanceAbstract[] buildFileInstanceArray(SmbFile[] files)
throws URISyntaxException, SearchLibException,
UnsupportedEncodingException {
if (files == null)
return null;
FileInstanceAbstract[] fileInstances = new FileInstanceAbstract[files.length];
int i = 0;
for (SmbFile file : files)
fileInstances[i++] = newInstance(filePathItem, this, file);
return fileInstances;
}
@Override
public FileInstanceAbstract[] listFilesAndDirectories()
throws SearchLibException, UnsupportedEncodingException,
URISyntaxException {
try {
SmbFile smbFile = getSmbFile();
SmbFile[] files = smbFile
.listFiles(new SmbInstanceFileFilter(false));
return buildFileInstanceArray(files);
} catch (SmbAuthException e) {
Logging.warn(e.getMessage() + " - " + getPath(), e);
return null;
} catch (SmbException e) {
throw new SearchLibException(e);
} catch (MalformedURLException e) {
throw new SearchLibException(e);
}
}
private class SmbInstanceFileFilter implements SmbFileFilter {
private final Matcher[] exclusionMatcher;
private final boolean ignoreHiddenFiles;
private final boolean fileOnly;
private SmbInstanceFileFilter(boolean fileOnly) {
this.ignoreHiddenFiles = filePathItem.isIgnoreHiddenFiles();
this.exclusionMatcher = filePathItem.getExclusionMatchers();
this.fileOnly = fileOnly;
}
@Override
public boolean accept(SmbFile f) throws SmbException {
if (fileOnly)
if (!f.isFile())
return false;
if (ignoreHiddenFiles)
if (f.isHidden())
return false;
if (exclusionMatcher != null)
if (RegExpUtils.find(f.getPath(), exclusionMatcher))
return false;
return true;
}
}
@Override
public FileInstanceAbstract[] listFilesOnly() throws SearchLibException,
UnsupportedEncodingException, URISyntaxException {
try {
SmbFile smbFile = getSmbFile();
SmbFile[] files = smbFile
.listFiles(new SmbInstanceFileFilter(true));
return buildFileInstanceArray(files);
} catch (MalformedURLException e) {
throw new SearchLibException(e);
} catch (SmbException e) {
throw new SearchLibException(e);
}
}
@Override
public Long getLastModified() throws SearchLibException {
try {
SmbFile smbFile = getSmbFile();
return smbFile.getLastModified();
} catch (MalformedURLException e) {
throw new SearchLibException(e);
}
}
@Override
public Long getFileSize() throws SearchLibException {
try {
SmbFile smbFile = getSmbFile();
return (long) smbFile.getContentLength();
} catch (MalformedURLException e) {
throw new SearchLibException(e);
}
}
@Override
public InputStream getInputStream() throws IOException {
SmbFile smbFile = getSmbFile();
return smbFile.getInputStream();
}
public final static ACE[] getSecurity(SmbFile smbFile) throws IOException {
try {
return smbFile.getSecurity();
} catch (SmbAuthException e) {
Logging.warn(e.getMessage() + " - " + smbFile.getPath(), e);
return null;
} catch (SmbException e) {
if (e.getNtStatus() == 0xC00000BB)
return null;
throw e;
}
}
@Override
public List<SecurityAccess> getSecurity() throws IOException {
SmbFile smbFile = getSmbFile();
ACE[] aces = getSecurity(smbFile);
if (aces == null)
return null;
List<SecurityAccess> accesses = new ArrayList<SecurityAccess>();
for (ACE ace : aces) {
if ((ace.getAccessMask() & ACE.FILE_READ_DATA) == 0)
continue;
SID sid = ace.getSID();
SecurityAccess access = new SecurityAccess();
access.setId(sid.toDisplayString());
if (ace.isAllow())
access.setGrant(SecurityAccess.Grant.ALLOW);
else
access.setGrant(SecurityAccess.Grant.DENY);
switch (sid.getType()) {
case SID.SID_TYPE_USER:
access.setType(SecurityAccess.Type.USER);
break;
case SID.SID_TYPE_DOM_GRP:
case SID.SID_TYPE_DOMAIN:
case SID.SID_TYPE_ALIAS:
case SID.SID_TYPE_WKN_GRP:
access.setType(SecurityAccess.Type.GROUP);
break;
case SID.SID_TYPE_DELETED:
case SID.SID_TYPE_INVALID:
case SID.SID_TYPE_UNKNOWN:
case SID.SID_TYPE_USE_NONE:
break;
}
accesses.add(access);
}
return accesses;
}
}
|
package com.lothrazar.cyclicmagic.gui.playerworkbench;
import java.lang.ref.WeakReference;
import java.util.List;
import com.lothrazar.cyclicmagic.ModMain;
import com.lothrazar.cyclicmagic.net.PacketSyncExtendedInventory;
import com.lothrazar.cyclicmagic.util.Const;
import net.minecraft.entity.item.EntityItem;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.Container;
import net.minecraft.inventory.IInventory;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.MathHelper;
import net.minecraft.util.text.ITextComponent;
public class InventoryPlayerExtWorkbench implements IInventory {
public ItemStack[] stackList;
private Container eventHandler;
public WeakReference<EntityPlayer> player;
public boolean blockEvents = false;
public static final int IROW = 3;
public static final int ICOL = 3;
public InventoryPlayerExtWorkbench(EntityPlayer player) {
this.stackList = new ItemStack[IROW * ICOL + 4];//plus armor slots
this.player = new WeakReference<EntityPlayer>(player);
}
public Container getEventHandler() {
return eventHandler;
}
public void setEventHandler(Container eventHandler) {
this.eventHandler = eventHandler;
}
@Override
public int getSizeInventory() {
return this.stackList.length;
}
@Override
public ItemStack getStackInSlot(int s) {
return s >= this.getSizeInventory() ? null : this.stackList[s];
}
@Override
public String getName() {
return "";
}
@Override
public boolean hasCustomName() {
return false;
}
@Override
public ITextComponent getDisplayName() {
return null;
}
/**
* When some containers are closed they call this on each slot, then drop
* whatever it returns as an EntityItem - like when you close a workbench GUI.
*/
@Override
public ItemStack removeStackFromSlot(int s) {
if (this.stackList[s] != null) {
ItemStack itemstack = this.stackList[s];
this.stackList[s] = null;
return itemstack;
}
else {
return null;
}
}
/**
* Removes from an inventory slot (first arg) up to a specified number (second
* arg) of items and returns them in a new stack.
*/
@Override
public ItemStack decrStackSize(int par1, int par2) {
if (this.stackList[par1] != null) {
ItemStack itemstack;
if (this.stackList[par1].stackSize <= par2) {
itemstack = this.stackList[par1];
this.stackList[par1] = null;
if (eventHandler != null)
this.eventHandler.onCraftMatrixChanged(this);
syncSlotToClients(par1);
return itemstack;
}
else {
itemstack = this.stackList[par1].splitStack(par2);
if (this.stackList[par1].stackSize == 0) {
this.stackList[par1] = null;
}
if (eventHandler != null)
this.eventHandler.onCraftMatrixChanged(this);
syncSlotToClients(par1);
return itemstack;
}
}
else {
return null;
}
}
/**
* Sets the given item stack to the specified slot in the inventory (can be
* crafting or armor sections).
*/
@Override
public void setInventorySlotContents(int idx, ItemStack stack) {
this.stackList[idx] = stack;
syncSlotToClients(idx);
}
@Override
public int getInventoryStackLimit() {
return 64;
}
@Override
public void markDirty() {
try {
player.get().inventory.markDirty();
}
catch (Exception e) {
}
}
@Override
public boolean isUseableByPlayer(EntityPlayer par1EntityPlayer) {
return true;
}
@Override
public void openInventory(EntityPlayer player) {
}
@Override
public void closeInventory(EntityPlayer player) {
}
@Override
public boolean isItemValidForSlot(int i, ItemStack stack) {
return true;
}
@Override
public int getField(int id) {
return 0;
}
@Override
public void setField(int id, int value) {
}
@Override
public int getFieldCount() {
return 0;
}
@Override
public void clear() {
for (int i = 0; i < stackList.length; i++) {
stackList[i] = null;
}
}
public void saveNBT(EntityPlayer player) {
NBTTagCompound tags = player.getEntityData();
saveNBT(tags);
}
public void saveNBT(NBTTagCompound tags) {
NBTTagList tagList = new NBTTagList();
NBTTagCompound invSlot;
for (int i = 0; i < this.stackList.length; ++i) {
if (this.stackList[i] != null) {
invSlot = new NBTTagCompound();
invSlot.setByte("Slot", (byte) i);
this.stackList[i].writeToNBT(invSlot);
tagList.appendTag(invSlot);
}
}
tags.setTag(Const.MODID + ".Inventory", tagList);
}
public void readNBT(EntityPlayer player) {
NBTTagCompound tags = player.getEntityData();
readNBT(tags);
}
public void readNBT(NBTTagCompound tags) {
NBTTagList tagList = tags.getTagList(Const.MODID + ".Inventory", 10);
for (int i = 0; i < tagList.tagCount(); ++i) {
NBTTagCompound nbttagcompound = (NBTTagCompound) tagList.getCompoundTagAt(i);
int j = nbttagcompound.getByte("Slot") & 255;
ItemStack itemstack = ItemStack.loadItemStackFromNBT(nbttagcompound);
if (itemstack != null) {
this.stackList[j] = itemstack;
}
}
}
public void dropItems(List<EntityItem> drops, BlockPos pos) {
for (int i = 0; i < this.getSizeInventory(); ++i) {
if (this.stackList[i] != null) {
EntityItem ei = new EntityItem(player.get().worldObj, pos.getX(), pos.getY(), pos.getZ(), this.stackList[i].copy());
ei.setPickupDelay(40);
float f1 = player.get().worldObj.rand.nextFloat() * 0.5F;
float f2 = player.get().worldObj.rand.nextFloat() * (float) Math.PI * 2.0F;
ei.motionX = (double) (-MathHelper.sin(f2) * f1);
ei.motionZ = (double) (MathHelper.cos(f2) * f1);
ei.motionY = 0.20000000298023224D;
drops.add(ei);
this.stackList[i] = null;
syncSlotToClients(i);
}
}
}
// public void dropItemsAt(List<EntityItem> drops, Entity e) {
// for (int i = 0; i < this.getSizeInventory(); ++i) {
// if (this.stackList[i] != null) {
// EntityItem ei = new EntityItem(e.worldObj, e.posX, e.posY + e.getEyeHeight(), e.posZ, this.stackList[i].copy());
// ei.setPickupDelay(40);
// float f1 = e.worldObj.rand.nextFloat() * 0.5F;
// float f2 = e.worldObj.rand.nextFloat() * (float) Math.PI * 2.0F;
// ei.motionX = (double) (-MathHelper.sin(f2) * f1);
// ei.motionZ = (double) (MathHelper.cos(f2) * f1);
// ei.motionY = 0.20000000298023224D;
// drops.add(ei);
// this.stackList[i] = null;
// syncSlotToClients(i);
public void syncSlotToClients(int slot) {
try {
if (ModMain.proxy.getClientWorld() == null) {
ModMain.network.sendToAll(new PacketSyncExtendedInventory(player.get(), slot));
}
}
catch (Exception e) {
e.printStackTrace();
}
}
}
|
package gov.nih.nci.nautilus.ui;
import gov.nih.nci.nautilus.query.CompoundQuery;
import gov.nih.nci.nautilus.query.QueryCollection;
import gov.nih.nci.nautilus.resultset.DimensionalViewContainer;
import gov.nih.nci.nautilus.resultset.Resultant;
import gov.nih.nci.nautilus.resultset.ResultsContainer;
import gov.nih.nci.nautilus.resultset.ResultsetManager;
import gov.nih.nci.nautilus.resultset.copynumber.CopyNumberSingleViewResultsContainer;
import gov.nih.nci.nautilus.resultset.copynumber.CytobandResultset;
import gov.nih.nci.nautilus.resultset.copynumber.SampleCopyNumberValuesResultset;
import gov.nih.nci.nautilus.resultset.gene.DiseaseGroupResultset;
import gov.nih.nci.nautilus.resultset.gene.GeneExprResultsContainer;
import gov.nih.nci.nautilus.resultset.gene.GeneExprSingleViewResultsContainer;
import gov.nih.nci.nautilus.resultset.gene.GeneResultset;
import gov.nih.nci.nautilus.resultset.gene.ReporterResultset;
import gov.nih.nci.nautilus.resultset.gene.SampleFoldChangeValuesResultset;
import gov.nih.nci.nautilus.resultset.gene.ViewByGroupResultset;
import gov.nih.nci.nautilus.resultset.sample.SampleResultset;
import gov.nih.nci.nautilus.resultset.sample.SampleViewResultsContainer;
import gov.nih.nci.nautilus.view.ClinicalSampleView;
import gov.nih.nci.nautilus.view.CopyNumberSampleView;
import gov.nih.nci.nautilus.view.GeneExprDiseaseView;
import gov.nih.nci.nautilus.view.GeneExprSampleView;
import gov.nih.nci.nautilus.view.Viewable;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
public class CSVGenerator {
public static final DecimalFormat resultFormat = new DecimalFormat("0.0000");
public static String displayReport(QueryCollection queryCollection, boolean csv) {
StringBuffer html = new StringBuffer();
StringBuffer errors = new StringBuffer();
Resultant resultant;
try {
CompoundQuery myCompoundQuery = queryCollection.getCompoundQuery();
try {
resultant = ResultsetManager.executeCompoundQuery(myCompoundQuery);
}
catch (Throwable t) {
errors.append("Error executing the query.<Br><Br>");
//errors.append(t.getStackTrace().toString());
System.out.println("Error Executing the query");
return errors.toString();
}
if(resultant != null) {
ResultsContainer resultsContainer = resultant.getResultsContainer();
String theQuery = resultant.getAssociatedQuery().toString();
if(resultsContainer != null) {
Viewable view = resultant.getAssociatedView();
if (view instanceof GeneExprSampleView) {
html.append("Gene Expression Fold Change (Tumor/Non-tumor)\n");
html.append(geneExprSampleView(resultsContainer));
return html.toString();
}
else if (view instanceof CopyNumberSampleView) {
html.append("Copy Number Data\n");
html.append(copyNumberSampleView(resultsContainer));
return html.toString();
}
else if (view instanceof GeneExprDiseaseView) {
html.append("Mean Gene Expression Fold Change for Tumor Sub-types\n");
html.append(geneExprDiseaseView(resultsContainer));
return html.toString();
}
else if(view instanceof ClinicalSampleView){
html.append("Sample Report\n");
html.append(clinicalSampleView(resultsContainer));
return html.toString();
}
else {
errors.append("Error with report view");
return errors.toString();
}
}
else {
errors.append("No Results Found, Try a Different Query\n");
return errors.toString();
}
} //resultant != null
else {
errors.append("Resultant is NULL\n");
return errors.toString();
}
}
catch(Exception e) {
errors.append("Error Displaying the Report.\n");
return errors.toString();
}
}
public static String clinicalSampleView(ResultsContainer resultsContainer) {
boolean gLinks = false;
boolean cLinks = false;
StringBuffer sb = new StringBuffer();
SampleViewResultsContainer sampleViewContainer = null;
if(resultsContainer instanceof DimensionalViewContainer){
DimensionalViewContainer dimensionalViewContainer = (DimensionalViewContainer) resultsContainer;
if(dimensionalViewContainer.getGeneExprSingleViewContainer() != null) {
// show the geneExprHyperlinks
gLinks = true;
}
if(dimensionalViewContainer.getCopyNumberSingleViewContainer() != null) {
// show the copyNumberHyperlinks
cLinks = true;
}
sampleViewContainer = dimensionalViewContainer.getSampleViewResultsContainer();
}else if (resultsContainer instanceof SampleViewResultsContainer){
sampleViewContainer = (SampleViewResultsContainer) resultsContainer;
}
Collection samples = sampleViewContainer.getBioSpecimenResultsets();
sb.append("SAMPLE,AGE at Dx,GENDER,SURVIVAL,DISEASE");
if(gLinks)
sb.append(",GeneExp");
if(cLinks)
sb.append(",CopyNumber");
sb.append("\n");
for (Iterator sampleIterator = samples.iterator(); sampleIterator.hasNext();) {
SampleResultset sampleResultset = (SampleResultset)sampleIterator.next();
sb.append(sampleResultset.getBiospecimen().getValue().toString().substring(2)+ "," +
sampleResultset.getAgeGroup().getValue()+ "," +
sampleResultset.getGenderCode().getValue()+ "," +
sampleResultset.getSurvivalLengthRange().getValue()+ "," +
sampleResultset.getDisease().getValue());
if(gLinks)
sb.append(",G");
if(cLinks)
sb.append(",C");
sb.append("\n");
}
return sb.toString();
}
public static String geneExprDiseaseView(ResultsContainer resultsContainer) {
StringBuffer sb = new StringBuffer();
GeneExprResultsContainer geneExprDiseaseContainer = (GeneExprResultsContainer) resultsContainer;
int recordCount = 0;
if(geneExprDiseaseContainer != null) {
Collection genes = geneExprDiseaseContainer.getGeneResultsets();
Collection labels = geneExprDiseaseContainer.getGroupsLabels();
Collection sampleIds = null;
String label = null;
sb.append("Gene,Reporter");
for (Iterator labelIterator = labels.iterator(); labelIterator.hasNext();) {
label = (String) labelIterator.next();
sb.append(","+label);
}
sb.append("\n");
for (Iterator geneIterator = genes.iterator(); geneIterator.hasNext();) {
GeneResultset geneResultset = (GeneResultset)geneIterator.next();
String geneSymbol = geneResultset.getGeneSymbol().getValue().toString();
Collection reporters = geneExprDiseaseContainer.getRepoterResultsets(geneSymbol);
for (Iterator reporterIterator = reporters.iterator(); reporterIterator.hasNext();) {
recordCount += reporters.size();
ReporterResultset reporterResultset = (ReporterResultset)reporterIterator.next();
String reporterName = reporterResultset.getReporter().getValue().toString();
Collection groupTypes = geneExprDiseaseContainer.getGroupByResultsets(geneSymbol,reporterName); //reporterResultset.getGroupResultsets();
sb.append(geneSymbol+"," + reporterName);
for (Iterator labelIterator = labels.iterator(); labelIterator.hasNext();) {
label = (String) labelIterator.next();
DiseaseGroupResultset diseaseResultset = (DiseaseGroupResultset) reporterResultset.getGroupByResultset(label);
if(diseaseResultset != null){
Double ratio = (Double)diseaseResultset.getFoldChangeRatioValue().getValue();
Double pvalue = (Double)diseaseResultset.getRatioPval().getValue();
sb.append(","+resultFormat.format(ratio)+" ("+resultFormat.format(pvalue)+")");
}
else {
sb.append(",-");
}
}
sb.append("\n");
}
// add the line between genes
//sb.append("\n");
}
}
else {
sb.append("Gene Disease View container is empty");
}
return sb.toString();
}
public static String copyNumberSampleView(ResultsContainer resultsContainer) {
StringBuffer sb = new StringBuffer();
StringBuffer header = new StringBuffer();
StringBuffer sampleNames = new StringBuffer();
StringBuffer stringBuffer = new StringBuffer();
StringBuffer theLabels = new StringBuffer();
StringBuffer tempSampleNames = new StringBuffer();
int recordCount = 0;
CopyNumberSingleViewResultsContainer copyNumberContainer = null;
if(resultsContainer instanceof DimensionalViewContainer) {
DimensionalViewContainer dimensionalViewContainer = (DimensionalViewContainer) resultsContainer;
if(dimensionalViewContainer != null) {
copyNumberContainer = dimensionalViewContainer.getCopyNumberSingleViewContainer();
}
}
else if(resultsContainer instanceof CopyNumberSingleViewResultsContainer) { //for single
copyNumberContainer = (CopyNumberSingleViewResultsContainer) resultsContainer;
}
if(copyNumberContainer != null) {
Collection cytobands = copyNumberContainer.getCytobandResultsets();
Collection labels = copyNumberContainer.getGroupsLabels();
Collection sampleIds = null;
header = new StringBuffer();
sampleNames = new StringBuffer();
tempSampleNames = new StringBuffer();
stringBuffer = new StringBuffer();
sampleNames.append(" , ");
header.append("Cytoband,Reporter");
for (Iterator labelIterator = labels.iterator(); labelIterator.hasNext();) {
String label = (String) labelIterator.next();
sampleIds = copyNumberContainer.getBiospecimenLabels(label);
for (Iterator sampleIdIterator = sampleIds.iterator(); sampleIdIterator.hasNext();) {
tempSampleNames.append("," + sampleIdIterator.next().toString().substring(2));
theLabels.append(","+label);
}
}
//header.append("\n");
theLabels.append("\n");
//sb.append(header.toString());
//sb.append(sampleNames.toString());
boolean showLL = true;
boolean showAcc = true;
boolean showGenes = true;
for (Iterator cytobandIterator = cytobands.iterator(); cytobandIterator.hasNext();) {
CytobandResultset cytobandResultset = (CytobandResultset)cytobandIterator.next();
String cytoband = cytobandResultset.getCytoband().getValue().toString();
Collection reporters = copyNumberContainer.getRepoterResultsets(cytoband);
recordCount += reporters.size();
for (Iterator reporterIterator = reporters.iterator(); reporterIterator.hasNext();) {
ReporterResultset reporterResultset = (ReporterResultset)reporterIterator.next();
String reporterName = reporterResultset.getReporter().getValue().toString();
Collection groupTypes = copyNumberContainer.getGroupByResultsets(cytoband,reporterName);
stringBuffer.append(cytoband+","+reporterName);
//show 3 annotations
// HashSet geneSymbols = new HashSet(reporterResultset.getAssiciatedGeneSymbols());
Collection geneSymbols = reporterResultset.getAssiciatedGeneSymbols();
if(geneSymbols != null){
String genes = "";
for(Iterator geneIterator = geneSymbols.iterator(); geneIterator.hasNext();)
{
Object geneObj = geneIterator.next();
if(geneObj != null){
genes += geneObj.toString();
genes += " | ";
}
}
if(showGenes) {
header.append(",Gene Symbols");
sampleNames.append(", ");
showGenes = false;
}
stringBuffer.append(","+genes);
stringBuffer.deleteCharAt(stringBuffer.lastIndexOf("|"));
}
HashSet locusLinkIds = new HashSet(reporterResultset.getAssiciatedLocusLinkIDs());
if(locusLinkIds != null){
String ll = "";
for(Iterator LLIterator = locusLinkIds.iterator(); LLIterator.hasNext();)
{
Object llObj = LLIterator.next();
if(llObj!=null){
ll += llObj.toString();
ll += " | ";
}
}
if(showLL) {
header.append(",Locus Link");
sampleNames.append(", ");
showLL = false;
}
stringBuffer.append(","+ll);
stringBuffer.deleteCharAt(stringBuffer.lastIndexOf("|"));
}
HashSet accNumbers = new HashSet(reporterResultset.getAssiciatedGenBankAccessionNos());
if(accNumbers!=null) {
String acc = "";
for(Iterator accIterator = accNumbers.iterator(); accIterator.hasNext();)
{
Object accObj = accIterator.next();
if(accObj!=null){
acc += accObj.toString();
acc += " | ";
}
}
if(showAcc){
header.append(",Acc.No.");
sampleNames.append(", ");
showAcc = false;
}
stringBuffer.append(", "+acc);
stringBuffer.deleteCharAt(stringBuffer.lastIndexOf("|"));
}
//sampleNames.append("\n");
for (Iterator labelIterator = labels.iterator(); labelIterator.hasNext();) {
String label = (String) labelIterator.next();
ViewByGroupResultset groupResultset = (ViewByGroupResultset) reporterResultset.getGroupByResultset(label);
sampleIds = copyNumberContainer.getBiospecimenLabels(label);
if(groupResultset != null)
{
for (Iterator sampleIdIterator = sampleIds.iterator(); sampleIdIterator.hasNext();) {
String sampleId = (String) sampleIdIterator.next();
SampleCopyNumberValuesResultset sampleResultset2 = (SampleCopyNumberValuesResultset) groupResultset.getBioSpecimenResultset(sampleId);
if(sampleResultset2 != null){
Double ratio = (Double)sampleResultset2.getCopyNumber().getValue();
if(ratio != null)
stringBuffer.append(","+resultFormat.format(ratio));
else
stringBuffer.append(",-");
}
else
{
stringBuffer.append(",-");
}
}
}
else {
for(int s=0;s<sampleIds.size();s++)
stringBuffer.append(",-");
}
}
stringBuffer.append("\n");
}
//append the extra row here
//sb.append("\n");
}
}
else {
sb.append("Copy Number container is empty");
}
sb.append(header.toString() + theLabels.toString()); // add header
sb.append(sampleNames.toString() + tempSampleNames.toString() + "\n"); // add sample rows
sb.append(stringBuffer.toString()); // add data
return sb.toString();
}
public static String geneExprSampleView(ResultsContainer resultsContainer) {
StringBuffer sb = new StringBuffer();
StringBuffer header = new StringBuffer();
StringBuffer sampleNames = new StringBuffer();
StringBuffer tempSampleNames = new StringBuffer();
StringBuffer stringBuffer = new StringBuffer();
StringBuffer theLabels = new StringBuffer();
int recordCount = 0;
GeneExprSingleViewResultsContainer geneViewContainer = null;
if(resultsContainer instanceof DimensionalViewContainer) {
DimensionalViewContainer dimensionalViewContainer = (DimensionalViewContainer) resultsContainer;
if(dimensionalViewContainer != null) {
geneViewContainer = dimensionalViewContainer.getGeneExprSingleViewContainer();
}
}
else if(resultsContainer instanceof GeneExprSingleViewResultsContainer) { //for single
geneViewContainer = (GeneExprSingleViewResultsContainer) resultsContainer;
}
if(geneViewContainer != null) {
Collection genes = geneViewContainer.getGeneResultsets();
Collection labels = geneViewContainer.getGroupsLabels();
Collection sampleIds = null;
header = new StringBuffer();
sampleNames = new StringBuffer();
stringBuffer = new StringBuffer();
tempSampleNames = new StringBuffer();
header.append("Gene,Reporter");
sampleNames.append(" , ");
theLabels = new StringBuffer();
for (Iterator labelIterator = labels.iterator(); labelIterator.hasNext();) {
String label = (String) labelIterator.next();
sampleIds = geneViewContainer.getBiospecimenLabels(label);
//header.append(","+label);
for (Iterator sampleIdIterator = sampleIds.iterator(); sampleIdIterator.hasNext();) {
tempSampleNames.append(","+sampleIdIterator.next().toString().substring(2));
theLabels.append(","+label);
}
//header.deleteCharAt(header.lastIndexOf("\t"));
}
//sampleNames.append("\n");
theLabels.append("\n");
//sb.append(header.toString());
//sb.append(sampleNames.toString());
boolean showLL = true;
boolean showAcc = true;
for (Iterator geneIterator = genes.iterator(); geneIterator.hasNext();) {
GeneResultset geneResultset = (GeneResultset)geneIterator.next();
Collection reporters = geneResultset.getReporterResultsets();
recordCount+=reporters.size();
for (Iterator reporterIterator = reporters.iterator(); reporterIterator.hasNext();) {
ReporterResultset reporterResultset = (ReporterResultset)reporterIterator.next();
Collection groupTypes = reporterResultset.getGroupByResultsets();
String reporterName = reporterResultset.getReporter().getValue().toString();
stringBuffer.append(geneResultset.getGeneSymbol().getValueObject().toString()+","+reporterName);
if(showLL) {
header.append(",Locus Link");
sampleNames.append(", ");
showLL = false;
}
if(showAcc){
header.append(",Acc No");
sampleNames.append(", ");
showAcc = false;
}
String ll = "";
try {
HashSet locusLinkIds = new HashSet(reporterResultset.getAssiciatedLocusLinkIDs());
if(locusLinkIds != null){
System.out.println("LLs for "+reporterName+": "+locusLinkIds.size());
for(Iterator LLIterator = locusLinkIds.iterator(); LLIterator.hasNext();)
{
try {
Object llObj = LLIterator.next();
if(llObj!=null){
ll += llObj.toString();
ll += " | ";
}
}
catch(Exception e){
}
}
/*
if(showLL) {
header.append(",Locus Link");
sampleNames.append(", ");
showLL = false;
}
*/
//stringBuffer.append(","+ll);
//stringBuffer.deleteCharAt(stringBuffer.lastIndexOf("|"));
System.out.println("done with this LL");
}
else {
//stringBuffer.append(",xx");
ll = "xx";
}
}
catch(Exception e){
//stringBuffer.append(",xxx");
ll = "xxx";
}
stringBuffer.append(","+ll);
try {
stringBuffer.deleteCharAt(stringBuffer.lastIndexOf("|"));
}
catch(Exception e) {
}
// do the acc no annotation
String acc = "";
try {
HashSet accNumbers = new HashSet(reporterResultset.getAssiciatedGenBankAccessionNos());
if(accNumbers!=null) {
System.out.println("Acc nos for "+reporterName+": "+accNumbers.size());
for(Iterator accIterator = accNumbers.iterator(); accIterator.hasNext();)
{
try {
Object accObj = accIterator.next();
if(accObj!=null){
acc += accObj.toString();
acc += " | ";
}
}
catch(Exception e) {
}
}
/*
if(showAcc){
header.append(",Acc No");
sampleNames.append(", ");
showAcc = false;
}
*/
//stringBuffer.append(","+acc);
//stringBuffer.deleteCharAt(stringBuffer.lastIndexOf("|"));
System.out.println("done with this acc");
}
else {
//stringBuffer.append(",xx");
acc = "xx";
}
}
catch(Exception e) {
//stringBuffer.append(",xxx");
acc = "xxx";
}
stringBuffer.append(","+acc);
try {
stringBuffer.deleteCharAt(stringBuffer.lastIndexOf("|"));
}
catch(Exception e) {
}
//sampleNames.append("\n");
for (Iterator labelIterator = labels.iterator(); labelIterator.hasNext();) {
String label = (String) labelIterator.next();
ViewByGroupResultset groupResultset = (ViewByGroupResultset) reporterResultset.getGroupByResultset(label);
sampleIds = geneViewContainer.getBiospecimenLabels(label);
if(groupResultset != null)
{
for (Iterator sampleIdIterator = sampleIds.iterator(); sampleIdIterator.hasNext();) {
String sampleId = (String) sampleIdIterator.next();
SampleFoldChangeValuesResultset biospecimenResultset = (SampleFoldChangeValuesResultset) groupResultset.getBioSpecimenResultset(sampleId);
if(biospecimenResultset != null){
Double ratio = (Double)biospecimenResultset.getFoldChangeRatioValue().getValue();
if(ratio != null) {
try {
stringBuffer.append(","+resultFormat.format(ratio));
}
catch(Exception e){
System.out.println("cant format result");
stringBuffer.append(",x");
}
}
else
stringBuffer.append(",x ");
}
else
{
stringBuffer.append(",x ");
}
}
}
else {
for(int s=0;s<sampleIds.size();s++)
stringBuffer.append(",x ");
}
}
stringBuffer.append("\n");
}
// add the line between genes
// sb.append("\n");
}
}
else {
stringBuffer.append("Gene Container is empty<br>");
}
sb.append(header.toString() + theLabels.toString()); // add header
sb.append(sampleNames.toString() + tempSampleNames.toString() + "\n"); // add sample rows
sb.append(stringBuffer.toString()); // add data
return sb.toString();
}
}
|
package de.bmoth.backend.ltl.transformation;
import de.bmoth.parser.ast.nodes.Node;
import de.bmoth.parser.ast.nodes.ltl.LTLInfixOperatorNode;
import de.bmoth.parser.ast.nodes.ltl.LTLKeywordNode;
import de.bmoth.parser.ast.nodes.ltl.LTLNode;
import de.bmoth.parser.ast.nodes.ltl.LTLPrefixOperatorNode;
import de.bmoth.parser.ast.visitors.ASTTransformation;
import static de.bmoth.backend.ltl.LTLTransformationUtil.isOperator;
import static de.bmoth.parser.ast.nodes.ltl.LTLPrefixOperatorNode.Kind.GLOBALLY;
public class ConvertGloballyPhiToPhiWeakUntilFalse implements ASTTransformation {
@Override
public boolean canHandleNode(Node node) {
return isOperator(node, GLOBALLY);
}
@Override
public Node transformNode(Node oldNode) {
LTLPrefixOperatorNode globallyOperator = (LTLPrefixOperatorNode) oldNode;
LTLNode argument = globallyOperator.getArgument();
return new LTLInfixOperatorNode(LTLInfixOperatorNode.Kind.WEAK_UNTIL, argument, new LTLKeywordNode(LTLKeywordNode.Kind.FALSE));
}
}
|
package fi.csc.microarray.client.visualisation.methods.gbrowser.message;
import net.sf.samtools.CigarElement;
import net.sf.samtools.CigarOperator;
public class CigarItem {
private CigarElement cigarElement;
public CigarItem(CigarElement cigarElement) {
this.cigarElement = cigarElement;
}
public long getLength() {
return cigarElement.getLength();
}
public String getType() {
return cigarElement.getOperator().toString();
}
public boolean isVisible() {
return cigarElement.getOperator() == CigarOperator.M || cigarElement.getOperator() == CigarOperator.X || cigarElement.getOperator() == CigarOperator.EQ;
}
public boolean consumesReferenceBases() {
return cigarElement.getOperator().consumesReferenceBases();
}
public boolean consumesReadBases() {
return cigarElement.getOperator().consumesReadBases();
}
}
|
package gov.nasa.jpl.mbee.systemsreasoner.validation.actions;
import java.io.Serializable;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Random;
import org.apache.commons.lang.SerializationException;
import org.apache.commons.lang.SerializationUtils;
import org.eclipse.jdt.core.dom.Modifier;
import com.nomagic.magicdraw.actions.MDAction;
import com.nomagic.magicdraw.core.Application;
import com.nomagic.magicdraw.emf.ValueHolder;
import com.nomagic.magicdraw.emf.impl.BasicEStoreEList;
import com.nomagic.magicdraw.emf.impl.MDEStoreEObjectImpl;
import com.nomagic.magicdraw.emf.impl.ValueHolderImpl;
import com.nomagic.magicdraw.openapi.uml.SessionManager;
import com.nomagic.uml2.ext.jmi.helpers.StereotypesHelper;
import com.nomagic.uml2.ext.magicdraw.classes.mdkernel.Class;
import com.nomagic.uml2.ext.magicdraw.classes.mdkernel.Element;
import com.nomagic.uml2.ext.magicdraw.classes.mdkernel.Property;
import com.nomagic.uml2.ext.magicdraw.classes.mdkernel.ValueSpecification;
import com.nomagic.uml2.ext.magicdraw.mdprofiles.Stereotype;
import com.nomagic.uml2.impl.ElementsFactory;
import org.eclipse.emf.common.util.AbstractEnumerator;
import org.eclipse.emf.common.util.BasicEList;
import org.eclipse.emf.ecore.impl.BasicEObjectImpl;
public class CloneAttributeAction extends MDAction {
private static final long serialVersionUID = 1L;
private Class clazz;
private Property property;
private Property clonedProperty;
public CloneAttributeAction(final Class clazz, final Property property) {
super("CreateProperty", "Create Property", null, null);
this.clazz = clazz;
this.property = property;
}
@Override
public void actionPerformed(java.awt.event.ActionEvent e) {
SessionManager.getInstance().createSession("clone attribute");
clonedProperty = (Property) clone(property, false);
if (clonedProperty != null) {
for (final Stereotype stereotype : StereotypesHelper.getStereotypes(clonedProperty)) {
stereotype.setOwner(clonedProperty);
}
clazz.getAttribute().add(clonedProperty);
}
SessionManager.getInstance().closeSession();
}
public Field getModifiableField(final Object o, String fieldName) {
java.lang.Class clazz = o.getClass();
while (clazz != null) {
for (final Field field : clazz.getDeclaredFields()) {
if (!Modifier.isStatic(field.getModifiers()) && field.getName().equals(fieldName))
return field;
}
clazz = clazz.getSuperclass();
}
return null;
}
public List<Field> getModifiableFields(final Object o) {
final List<Field> fields = new ArrayList<Field>();
java.lang.Class clazz = o.getClass();
while (clazz != null) {
for (final Field field : clazz.getDeclaredFields()) {
if (!Modifier.isStatic(field.getModifiers()))
fields.add(field);
}
clazz = clazz.getSuperclass();
}
return fields;
}
public List<java.lang.Class> getInterfacesRecursively(final Object o) {
final List<java.lang.Class> interfaces = new ArrayList<java.lang.Class>();
java.lang.Class clazz = o.getClass();
while (clazz != null) {
for (final java.lang.Class c : o.getClass().getInterfaces()) {
interfaces.add(c);
}
clazz = clazz.getSuperclass();
}
return interfaces;
}
public <R> R clone(R r) {
return clone(r, true);
}
@SuppressWarnings("unchecked")
public <R> R clone(R r, final boolean checkForRecursion) {
if (r == null) {
return r;
}
if (checkForRecursion && r.equals(property)) {
System.out.println("Returning cloned property");
return (R) clonedProperty;
}
System.out.println("clone: " + r.getClass());
/* if (o instanceof Cloneable) {
try {
return o.clone();
} catch (CloneNotSupportedException ignored) {
//e1.printStackTrace();
}
} */ // Clone is broken for everything in MD we've tried :(
/*if (r instanceof Serializable) {
try {
return (R) SerializationUtils.clone((Serializable) r);
} catch (SerializationException se) {
//se.printStackTrace();
}
}*/
if (r instanceof Element) {
System.out.println("ELEMENT! " + r.getClass().getCanonicalName());
return (R) cloneElement((Element) r);
}
else if (r instanceof Boolean) {
return (R) new Boolean((Boolean) r);
}
else if (r instanceof String) {
return (R) new String((String) r);
}
else if (r instanceof int[]) {
return (R) Arrays.copyOf((int[]) r, ((int[]) r).length);
}
else if (r instanceof Object[]) {
final Object[] clone = new Object[((Object[]) r).length];
for (int i = 0; i < clone.length; i++) {
clone[i] = clone(((Object[]) r)[i]);
System.out.println("Object[]: " + clone[i]);
}
return (R) clone;
}
else if (r instanceof AbstractEnumerator) {
try {
Object value = r.getClass().getMethod("getValue").invoke(r);
return (R) r.getClass().getMethod("get", int.class).invoke(null, value);
} catch (ReflectiveOperationException roe) {
// Needed methods probably don't exist. I wish NoMagic implemented a common interface we could use instead. :(
roe.printStackTrace();
return r;
}
}
else if (r instanceof Map) {
return (R) cloneMap((Map<Object, Object>) r);
}
else if (r instanceof BasicEList) {
return (R) cloneBasicEList((BasicEList<Object>) r);
}
else if (r instanceof Collection) {
return (R) cloneCollection((Collection<Object>) r);
}
else {
System.out.println("UH OH! Couldn't clone!: " + r + " :: " + r.getClass());
try {
for (final Field f : getModifiableFields(r.getClass())) {
f.setAccessible(true);
System.out.println("-> " + f.getName() + "::" + f.getType().getCanonicalName());
}
for (final java.lang.Class interfacee : r.getClass().getInterfaces()) {
System.out.println("--- " + interfacee.getCanonicalName());
}
} catch (Exception roe) {
roe.printStackTrace();
}
return r;
}
}
public <R extends Element> R cloneElement(final R element) {
System.out.println("Cloning " + element + " -> " + element.getClass().getCanonicalName());
final ElementsFactory ef = Application.getInstance().getProject().getElementsFactory();
R clone = null;
try {
final Method[] createInstanceMethods = ef.getClass().getMethods();
//System.out.println("FOO" + ef.getClass().getInterfaces().length);
for (final java.lang.Class interfacee : element.getClass().getInterfaces()) {
System.out.println(interfacee.getSimpleName());
for (final Method m : createInstanceMethods) {
//System.out.println("> " + m.getName());
if (m.getName().equals("create" + interfacee.getSimpleName() + "Instance")) {
//System.out.println("GOT HERE");
clone = (R) m.invoke(ef);
break;
}
}
if (clone != null) {
break;
}
}
//clone = (R) ef.getClass().getMethod("create" + element.getClass().getName() + "Instance").invoke(null);
} catch (ReflectiveOperationException roe) {
//System.out.println("create" + element.getClass().getName() + "Instance");
roe.printStackTrace();
}
if (clone == null) {
System.out.println("Failed to clone element. Backing up to reference; potentially unsafe.");
return clone;
}
final String id = clone.getID();
final Field mHolderField = getModifiableField(element, "mHolder");
if (mHolderField != null && ValueHolder.class.isAssignableFrom(mHolderField.getType())) {
try {
mHolderField.setAccessible(true);
final ValueHolder mHolder = (ValueHolder) mHolderField.get(element);
final ValueHolder clonedMHolder = (ValueHolder) mHolderField.get(clone);
Field mIndexesField, mValuesField;
byte[] mIndexes = null;
Object[] mValues = null;
if ((mIndexesField = getModifiableField(mHolder, "mIndexes")) != null) {
mIndexesField.setAccessible(true);
mIndexes = (byte[]) mIndexesField.get(mHolder);
mIndexesField.set(clonedMHolder, clone(mIndexes));
}
if ((mValuesField = getModifiableField(mHolder, "mValues")) != null) {
//System.out.println("ASDFSDFSDFSDFSDFSDFBOO");
mValuesField.setAccessible(true);
mValues = (Object[]) mValuesField.get(mHolder);
/*if (false && element instanceof Stereotype) {
for (final Object o : mValues) {
System.out.println("STEREOTYPE: " + o + " -> " + o.getClass().getCanonicalName());
}
return (R) ef.createStereotypeInstance();
}
else {*/
final Object[] clonedMValues = clone(mValues);
//System.out.println(clonedMValues[0]);
clonedMValues[0] = id;
//System.out.println(clonedMValues[0]);
mValuesField.set(clonedMHolder, clonedMValues);
}
} catch (ReflectiveOperationException roe) {
roe.printStackTrace();
}
}
return clone;
}
public <R extends Map<Object, Object>> R cloneMap(final R map) {
R clone = null;
try {
//clone = (R) map.getClass().newInstance();
final Constructor defaultConstructor = map.getClass().getConstructor();
if (defaultConstructor == null) {
System.out.println("NO DEFAULT CONSTRUCTOR?!?!?!");
return map;
}
defaultConstructor.setAccessible(true);
clone = (R) defaultConstructor.newInstance();
for (Entry<Object, Object> entry : map.entrySet()) {
clone.put(entry.getKey(), clone(entry.getValue()));
}
//clone.putAll(map);
} catch (ReflectiveOperationException roe) {
roe.printStackTrace();
// Almost all implementations of the Map interface has a default constructor. We never expect this exception.
return map;
}
return clone;
}
public <R extends Collection<Object>> R cloneCollection(final R collection) {
R clone = null;
try {
final Constructor defaultConstructor = collection.getClass().getConstructor();
if (defaultConstructor == null) {
System.out.println("NO DEFAULT CONSTRUCTOR?!?!?!");
return collection;
}
defaultConstructor.setAccessible(true);
clone = (R) defaultConstructor.newInstance();
for (Object o : collection) {
clone.add(clone(o));
}
} catch (ReflectiveOperationException roe) {
roe.printStackTrace();
// Almost all implementations of the List interface has a default constructor. We never expect this exception.
System.out.println("DUMP CONSTRUCTORS");
for (final Constructor constructor : collection.getClass().getConstructors()) {
System.out.println("Constructor: " + constructor);
}
return collection;
}
return clone;
}
public <R extends BasicEList<Object>> BasicEList<Object> cloneBasicEList(final R bel) {
System.out.println("BESEL");
final BasicEList<Object> clone = new BasicEList<Object>();
for (Object o : bel) {
if (o != null && o.equals(property)) {
clone.add(property);
}
else {
System.out.println("BESEL " + o + " :: " + o.getClass());
clone.add(clone(o));
}
}
return clone;
}
}
|
package net.darkhax.darkutils.features.flatblocks.collision;
import net.darkhax.bookshelf.util.InventoryUtils;
import net.minecraft.block.BlockState;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityType;
import net.minecraft.entity.item.ItemEntity;
import net.minecraft.item.ItemStack;
import net.minecraft.state.properties.BlockStateProperties;
import net.minecraft.util.Direction;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import net.minecraftforge.items.IItemHandler;
public class CollisionEffectImport extends CollisionEffectPush {
private final int insertAmount;
public CollisionEffectImport(double velocity, int insertAmount) {
super(velocity);
this.insertAmount = insertAmount;
}
@Override
public void additionalEffects (BlockState state, World world, BlockPos pos, Entity entity) {
if (entity instanceof ItemEntity && !entity.world.isRemote) {
final ItemEntity itemEntity = (ItemEntity) entity;
final Direction insertSide = state.get(BlockStateProperties.HORIZONTAL_FACING);
final IItemHandler inventory = InventoryUtils.getInventory(world, pos.offset(insertSide), insertSide.getOpposite());
// Check if inventory exists and if the item can be picked up.
if (inventory != null && !itemEntity.cannotPickup() && !itemEntity.getItem().isEmpty()) {
// Create a simulated stack of what to insert.
final ItemStack pickupStack = itemEntity.getItem().copy().split(this.insertAmount);
// Iterate every valid slot of the inventory
for (int slot = 0; slot < inventory.getSlots(); slot++) {
// Check if the simulated insert stack can be accepted into the inventory.
if (inventory.isItemValid(slot, pickupStack) && inventory.insertItem(slot, pickupStack, true).getCount() != pickupStack.getCount()) {
System.out.println("Taken into slot " + slot);
// Actually split the picked up stack so it can be legitimately
// inserted.
final ItemStack actualPickupStack = itemEntity.getItem().split(this.insertAmount);
// Insert the legitimate stack.
final ItemStack remaining = inventory.insertItem(slot, actualPickupStack, false);
// If there are any leftover items, spawn them on the ground.
if (!remaining.isEmpty()) {
final ItemEntity item = new ItemEntity(EntityType.ITEM, world);
item.setItem(remaining);
item.setPosition(entity.posX, entity.posY, entity.posZ);
item.lifespan = remaining.getEntityLifespan(world);
world.addEntity(item);
}
break;
}
}
}
}
}
}
|
package org.hildan.minecraft.mining.optimizer.patterns.generated;
import org.hildan.minecraft.mining.optimizer.chunks.Sample;
import org.hildan.minecraft.mining.optimizer.chunks.Wrapping;
import org.hildan.minecraft.mining.optimizer.geometry.Position;
import org.hildan.minecraft.mining.optimizer.patterns.AbstractDiggingPattern;
import org.hildan.minecraft.mining.optimizer.patterns.Access;
import org.hildan.minecraft.mining.optimizer.patterns.generated.actions.Action;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
/**
* A pattern that can be programmatically generated.
*/
class GeneratedPattern extends AbstractDiggingPattern {
private final Map<Access, List<Action>> actionsPerAccess;
private final int width;
private final int height;
private final int length;
/**
* Creates a GeneratedPattern with the given list of actions for each given access.
*
* @param actionsPerAccess
* defines for each access, the corresponding list of actions
*/
public GeneratedPattern(Map<Access, List<Action>> actionsPerAccess, int width, int height, int length) {
this.actionsPerAccess = new HashMap<>(actionsPerAccess);
this.width = width;
this.height = height;
this.length = length;
}
@Override
public int getWidth() {
return width;
}
@Override
public int getHeight() {
return height;
}
@Override
public int getLength() {
return length;
}
@Override
public Set<Access> getAccesses(int x, int y) {
return actionsPerAccess.keySet()
.stream()
.map(a -> new Access(a.getX() + x, a.getY() + y))
.collect(Collectors.toSet());
}
@Override
protected void digInto(Sample sample, int originX, int originY, int originZ) {
for (Access access : getAccesses(originX, originY)) {
Position feetBlock = sample.getBlock(access);
sample.digBlock(feetBlock);
Position headBlock = sample.getBlockAbove(feetBlock, Wrapping.WRAP);
sample.digBlock(headBlock);
for (Action action : actionsPerAccess.get(access)) {
headBlock = action.executeOn(sample, headBlock);
}
}
}
@Override
public String toString() {
Set<Access> accesses = getAccesses(0, 0);
StringBuilder sb = new StringBuilder();
final String indent = " ";
for (Access access : accesses) {
sb.append(access).append(String.format("%n"));
for (Action action : actionsPerAccess.get(access)) {
sb.append(indent).append(action).append(String.format("%n"));
}
}
return sb.toString();
}
}
|
package org.project.openbaton.integration.test.testers;
import org.project.openbaton.catalogue.mano.descriptor.NetworkServiceDescriptor;
import org.project.openbaton.catalogue.mano.record.NetworkServiceRecord;
import org.project.openbaton.integration.test.utils.Tester;
import org.project.openbaton.sdk.api.exception.SDKException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Properties;
public class NetworkServiceRecordCreate extends Tester<NetworkServiceRecord> {
private static final String FILE_NAME = "/etc/json_file/network_service_descriptors/NetworkServiceDescriptor-with-dependencies-without-allacation.json";
private static Logger log = LoggerFactory.getLogger(NetworkServiceRecordCreate.class);
private static String path = "ns-records";
/**
* @param properties : IntegrationTest properties containing:
* nfvo-usr
* nfvo-pwd
* nfvo-ip
* nfvo-port
* @param aClass : example VimInstance.class
* @param filePath : example "/etc/json_file/vim_instances/vim-instance.json"
* @param basePath
*/
public NetworkServiceRecordCreate(Properties properties) {
super(properties, NetworkServiceRecord.class, FILE_NAME, "/ns-records");
}
@Override
protected Object doWork() throws Exception {
return create();
}
@Override
protected void handleException(Exception e) {
e.printStackTrace();
log.error("there was an exception: " + e.getMessage());
}
@Override
public NetworkServiceRecord create() throws SDKException {
NetworkServiceDescriptor nsd = (NetworkServiceDescriptor) this.param;
log.debug("Obtained param: " + param);
log.debug("Obtained id: " + nsd.getId());
NetworkServiceRecord networkServiceRecord = this.requestor.getNetworkServiceRecordAgent().create(nsd.getId());
log.debug("Created: " + networkServiceRecord);
return networkServiceRecord;
}
@Override
protected NetworkServiceRecord prepareObject() {
return null;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.