answer
stringlengths
17
10.2M
package squeek.applecore.api; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import squeek.applecore.api.food.FoodValues; import javax.annotation.Nonnull; public interface IAppleCoreAccessor { /** * Check whether or not the given ItemStack is an edible food. * * Any ItemStack that gives a return of true in * this method will also return valid FoodValues from * the {@link #getFoodValues}/{@link #getFoodValuesForPlayer} methods.<br> * <br> * This method should be preferred when doing something like * determining whether or not to show food values in an * item's tooltip, as it is more inclusive than a simple * {@code instanceof ItemFood} check. */ boolean isFood(@Nonnull ItemStack food); /** * Check if the given ItemStack can be eaten, taking into account their max hunger, and if this food item is always edible * * <br> * In particular, this method will always return {@code true} if {@link net.minecraft.util.FoodStats#getFoodLevel} {@code <} {@link #getMaxHunger} * or if this ItemStack's Item is an instance of ItemFood and has its alwaysEdible field set. * @return {@code true} if that player is able to eat this food item, {@code false} otherwise. */ boolean isFoodEdible(@Nonnull ItemStack food, @Nonnull EntityPlayer player); /** * Get player-agnostic food values. * * @return The food values, or {@link ItemStack#EMPTY} if none were found. */ FoodValues getFoodValues(@Nonnull ItemStack food); /** * Get player-specific food values. * * @return The food values, or {@link ItemStack#EMPTY} if none were found. */ FoodValues getFoodValuesForPlayer(@Nonnull ItemStack food, EntityPlayer player); /** * Get unmodified (vanilla) food values. * * @return The food values, or {@link ItemStack#EMPTY} if none were found. */ FoodValues getUnmodifiedFoodValues(@Nonnull ItemStack food); /** * @return The current exhaustion level of the {@code player}. */ float getExhaustion(EntityPlayer player); /** * @return The maximum exhaustion level of the {@code player}.<br> * <br> * Note: Maximum exhaustion refers to the amount of exhaustion that * will trigger {@link squeek.applecore.api.hunger.ExhaustionEvent.Exhausted} events; * exhaustion can exceed the maximum exhaustion value. */ float getMaxExhaustion(EntityPlayer player); /** * @return The number of ticks between health being regenerated by the {@code player}. */ int getHealthRegenTickPeriod(EntityPlayer player); /** * @return The number of ticks between starvation damage being dealt to the {@code player}. */ int getStarveDamageTickPeriod(EntityPlayer player); /** * @return The number of ticks between health being regenerated by the {@code player} when at full hunger and > 0 saturation. */ int getSaturatedHealthRegenTickPeriod(EntityPlayer player); /** * @return The maximum hunger level of the {@code player}. */ int getMaxHunger(EntityPlayer player); }
package ca.corefacility.bioinformatics.irida.ria.integration.pages.projects; import java.util.List; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; import org.openqa.selenium.support.PageFactory; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.Select; import org.openqa.selenium.support.ui.WebDriverWait; /** * Represents page found at url: /projects/{projectId}/linelist */ public class ProjectLineListPage extends ProjectPageBase { private static final String RELATIVE_URL = "/projects/{projectId}/linelist"; @FindBy(css = "#linelist th") private List<WebElement> tableHeaders; @FindBy(css = "#linelist tbody tr") private List<WebElement> tableRows; @FindBy(id = "col-vis-btn") private WebElement metadataColVisBtn; @FindBy(css = ".metadata-open .modal-content") private WebElement metadataColVisAside; @FindBy(id = "close-aside-btn") private WebElement closeAsideBtn; @FindBy(className = "bootstrap-switch-label") private List<WebElement> colVisBtns; @FindBy(id = "template-select") private WebElement templateSelect; @FindBy(id = "save-btn") private WebElement saveBtn; @FindBy(id = "template-name") private WebElement templateNameInput; @FindBy(id = "complete-save") private WebElement completeSaveBtn; public ProjectLineListPage(WebDriver driver) { super(driver); } public static ProjectLineListPage goToPage(WebDriver driver, int projectId) { get(driver, RELATIVE_URL.replace("{projectId}", String.valueOf(projectId))); return PageFactory.initElements(driver, ProjectLineListPage.class); } public int getNumberSamplesWithMetadata() { return tableRows.size(); } public int getNumberTableColumns() { return tableHeaders.size(); } public void openColumnVisibilityPanel() { WebDriverWait wait = new WebDriverWait(driver, 10); metadataColVisBtn.click(); wait.until(ExpectedConditions.visibilityOf(metadataColVisAside)); } public void closeColumnVisibilityPanel() { WebDriverWait wait = new WebDriverWait(driver, 10); closeAsideBtn.click(); wait.until(ExpectedConditions.invisibilityOfElementLocated(By.cssSelector(".modal.in-remove-active"))); } public void toggleColumn(String buttonLabel) { for (WebElement btn : colVisBtns) { if (btn.getText().equalsIgnoreCase(buttonLabel)) { btn.click(); waitForTime(300); break; } } } public void selectTemplate(String templateName) { Select select = new Select(templateSelect); select.selectByVisibleText(templateName); waitForTime(1000); } public void saveTemplate(String templateName) { saveBtn.click(); WebDriverWait wait = new WebDriverWait(driver, 10); wait.until(ExpectedConditions.visibilityOf(templateNameInput)); waitForTime(1000); templateNameInput.sendKeys(templateName); wait.until(ExpectedConditions.elementToBeClickable(completeSaveBtn)); completeSaveBtn.click(); waitForTime(2000); } }
package dr.evomodel.coalescent; import com.sun.xml.internal.rngom.digested.DDataPattern; import dr.app.beast.BeastDialog; import dr.evolution.tree.NodeRef; import dr.evolution.tree.Tree; import dr.evomodel.tree.TreeModel; import dr.evomodelxml.coalescent.GaussianProcessSkytrackLikelihoodParser; import dr.inference.model.MatrixParameter; import dr.inference.model.Parameter; import dr.inference.model.Variable; import dr.math.MathUtils; import no.uib.cipr.matrix.DenseVector; import no.uib.cipr.matrix.NotConvergedException; import no.uib.cipr.matrix.SymmTridiagEVD; import no.uib.cipr.matrix.SymmTridiagMatrix; import java.util.ArrayList; import java.util.List; /** * @author Vladimir Minin * @author Marc Suchard * @author Julia Palacios * @author Mandev */ public class GaussianProcessSkytrackLikelihood extends OldAbstractCoalescentLikelihood { protected Parameter popSizeParameter; protected Parameter groupSizeParameter; protected Parameter precisionParameter; protected Parameter lambda_boundParameter; protected Parameter lambdaParameter; protected Parameter betaParameter; // protected int GPfieldLength; protected double[] coalescentIntervals; protected double[] allintervals; protected double[] storedCoalescentIntervals; protected double[] sufficientStatistics; protected double[] allsufficient; protected double[] storedSufficientStatistics; protected double[] latentLocations; protected double[] storedlatentLocations; protected double[] latentpopSizeValues; protected double[] storedlatentpopSizeValues; protected double logFieldLikelihood; protected double storedLogFieldLikelihood; protected SymmTridiagMatrix weightMatrix; protected SymmTridiagMatrix storedWeightMatrix; protected MatrixParameter dMatrix; protected boolean rescaleByRootHeight; public GaussianProcessSkytrackLikelihood(Tree tree, Parameter popParameter, Parameter groupParameter, Parameter precParameter, Parameter lambda, Parameter beta, MatrixParameter dMatrix, /*boolean timeAwareSmoothing,*/ boolean rescaleByRootHeight, /*Parameter latentPoints,*/ Parameter lambda_bound) { this(wrapTree(tree), popParameter, groupParameter, precParameter, lambda, beta, dMatrix, rescaleByRootHeight, lambda_bound); } public GaussianProcessSkytrackLikelihood(String name) { super(name); } private static List<Tree> wrapTree(Tree tree) { List<Tree> treeList = new ArrayList<Tree>(); treeList.add(tree); return treeList; } public GaussianProcessSkytrackLikelihood(List<Tree> treeList, Parameter popParameter, Parameter groupParameter, Parameter precParameter, Parameter lambda, Parameter beta, MatrixParameter dMatrix, boolean rescaleByRootHeight, Parameter lambda_bound) { super(GaussianProcessSkytrackLikelihoodParser.SKYTRACK_LIKELIHOOD); this.popSizeParameter = popParameter; this.groupSizeParameter = groupParameter; this.precisionParameter = precParameter; this.lambdaParameter = lambda; this.betaParameter = beta; this.dMatrix = dMatrix; this.rescaleByRootHeight = rescaleByRootHeight; this.lambda_boundParameter= lambda_bound; addVariable(popSizeParameter); addVariable(precisionParameter); addVariable(lambdaParameter); addVariable(lambda_boundParameter); if (betaParameter != null) { addVariable(betaParameter); } setTree(treeList); wrapSetupIntervals(); int fieldLength = getCorrectFieldLength(); int GPfieldLength= countChangePoints(); allintervals = new double[GPfieldLength]; allsufficient=new double[GPfieldLength]; coalescentIntervals = new double[fieldLength]; storedCoalescentIntervals = new double[fieldLength]; sufficientStatistics = new double[fieldLength]; storedSufficientStatistics = new double[fieldLength]; initializationReport(); setupSufficientStatistics(); } protected void setTree(List<Tree> treeList) { if (treeList.size() != 1) { throw new RuntimeException("GP-based method only implemented for one tree"); } this.tree = treeList.get(0); this.treesSet = null; if (tree instanceof TreeModel) { addModel((TreeModel) tree); } } protected void wrapSetupIntervals() { setupIntervals(); } protected int getCorrectFieldLength() { return tree.getExternalNodeCount() - 1; } // wrapSetupIntervals(); // coalescentIntervals = new double[GPfieldLength]; // storedCoalescentIntervals = new double[GPfieldLength]; // sufficientStatistics = new double[GPfieldLength]; // storedSufficientStatistics = new double[GPfieldLength]; //// setupGPWeights(); //// System.err.println("Aqui busco:"+GPfieldLength); //// private void setupGPWeights() { //// GPsetupSufficientStatistics(); // public double calculateLogLikelihood() { // return 2.0; // // TODO Return the correct log-density // public double getLogLikelihood() { // if (!likelihoodKnown) { // logLikelihood = calculateLogLikelihood(); // likelihoodKnown = true; // return logLikelihood; //// private final Parameter latentPoints; // private final Parameter lambda_bound; public void initializationReport() { System.out.println("Creating a GP based estimation of effective population trajectories:"); System.out.println("\tPopulation sizes: " + popSizeParameter.getDimension()); System.out.println("\tIf you publish results using this model, please reference: Minin, Palacios, Suchard (XXXX), AAA"); } //// protected void setupGPWeights() { //// setupSufficientStatistics(); //// //Set up the weight Matrix //// double[] offdiag = new double[fieldLength - 1]; //// double[] diag = new double[fieldLength]; //// //First set up the offdiagonal entries; //// if (!timeAwareSmoothing) { //// for (int i = 0; i < fieldLength - 1; i++) { //// offdiag[i] = -1.0; //// } else { //// for (int i = 0; i < fieldLength - 1; i++) { //// offdiag[i] = -2.0 / (coalescentIntervals[i] + coalescentIntervals[i + 1]) * getFieldScalar(); //// //Then set up the diagonal entries; //// for (int i = 1; i < fieldLength - 1; i++) //// diag[i] = -(offdiag[i] + offdiag[i - 1]); //// //Take care of the endpoints //// diag[0] = -offdiag[0]; //// diag[fieldLength - 1] = -offdiag[fieldLength - 2]; //// weightMatrix = new SymmTridiagMatrix(diag, offdiag); //Sufficient Statistics for GP - coal+sampling // We do not consider getLineageCount == 1, we combine it with the next time // We do not need to make a difference between coalescent and sampling points //CoalescentIntervals here actually contain change points //sufficientStatistics here actually contain (k choose 2) protected void setupSufficientStatistics() { int index = 0; int index2 = 0; double length = 0; // double weight = 0; System.err.println("Prueba dimension"+coalescentIntervals.length); for (int i = 0; i < getIntervalCount(); i++) { // if (getLineageCount(i)< 2) { // length+=getInterval(i); // } else { length += getInterval(i); System.err.println("Aqui va: getInterval:"+i+" "+getInterval(i)+ "with length "+length+ " with Type"+getIntervalType(i)+" lineage count "+getLineageCount(i)); allintervals[index] = length; allsufficient[index] =getLineageCount(i)*(getLineageCount(i)-1) / 2.0; index++; if (getIntervalType(i) == CoalescentEventType.COALESCENT) { coalescentIntervals[index2] = length; sufficientStatistics[index2] = getLineageCount(i)*(getLineageCount(i)-1) / 2.0; index2++; } } System.exit(-1); } // protected int countChangePoints(){ // int countCPoints = 0; // for (int i =0; i<getIntervalCount();i++){ // if (getLineageCount(i)>1){ // countCPoints++; // return countCPoints; protected int countChangePoints(){ return getIntervalCount(); } }
package squeek.veganoption.blocks; import java.lang.reflect.Field; import net.minecraft.block.Block; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.util.ChunkCoordinates; import net.minecraft.util.DamageSource; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.event.entity.player.PlayerWakeUpEvent; import squeek.veganoption.ModInfo; import cpw.mods.fml.common.eventhandler.SubscribeEvent; import cpw.mods.fml.relauncher.ReflectionHelper; public class BlockBedStraw extends BlockBedGeneric { public static final DamageSource itchyDamageSource = new DamageSource(ModInfo.MODID + ".itchyBed"); public static final int ITCH_DAMAGE = 1; public static final Field playerSleepingField = ReflectionHelper.findField(EntityPlayer.class, "sleeping", "field_71083_bS", "bA"); public BlockBedStraw() { super(); MinecraftForge.EVENT_BUS.register(this); } @SubscribeEvent public void onWakeUp(PlayerWakeUpEvent event) { // this flag combination should only be set when the sleep was successful // and the server is waking all sleeping players boolean wokenByWakeAllPlayers = event.setSpawn && !event.updateWorld; if (!wokenByWakeAllPlayers) return; ChunkCoordinates chunkcoordinates = event.entityPlayer.playerLocation; if (chunkcoordinates == null) return; Block block = event.entityPlayer.worldObj.getBlock(chunkcoordinates.posX, chunkcoordinates.posY, chunkcoordinates.posZ); if (block != this) return; // The player's sleeping bool must be set to false before calling // attackEntityFrom; otherwise, an infinite loop would be created due to // the wakeUpPlayer call in attackEntityFrom try { playerSleepingField.setBoolean(event.entityPlayer, false); event.entityPlayer.attackEntityFrom(itchyDamageSource, ITCH_DAMAGE); } catch (Exception e) { e.printStackTrace(); } } }
package org.buddycloud.channelserver.packetprocessor.iq.namespace.pubsub.set; import java.util.ArrayList; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import junit.framework.Assert; import org.buddycloud.channelserver.Configuration; import org.buddycloud.channelserver.channel.ChannelManager; import org.buddycloud.channelserver.packetHandler.iq.IQTestHandler; import org.buddycloud.channelserver.pubsub.affiliation.Affiliations; import org.buddycloud.channelserver.pubsub.event.Event; import org.buddycloud.channelserver.pubsub.model.NodeMembership; import org.buddycloud.channelserver.pubsub.model.NodeSubscription; import org.buddycloud.channelserver.pubsub.model.impl.NodeMembershipImpl; import org.buddycloud.channelserver.pubsub.model.impl.NodeSubscriptionImpl; import org.buddycloud.channelserver.pubsub.subscription.Subscriptions; import org.buddycloud.channelserver.utils.node.item.payload.Buddycloud; import org.dom4j.Element; import org.dom4j.tree.BaseElement; import org.junit.Before; import org.junit.Test; import org.mockito.ArgumentCaptor; import org.mockito.Mockito; import org.xmpp.packet.IQ; import org.xmpp.packet.JID; import org.xmpp.packet.Message; import org.xmpp.packet.Packet; import org.xmpp.packet.PacketError; import org.xmpp.resultsetmanagement.ResultSet; import org.xmpp.resultsetmanagement.ResultSetImpl; public class UnsubscribeSetTest extends IQTestHandler { private IQ request; private UnsubscribeSet unsubscribe; private Element element; private BlockingQueue<Packet> queue = new LinkedBlockingQueue<Packet>(); private String node = "/user/pamela@denmark.lit/posts"; private JID jid = new JID("juliet@shakespeare.lit"); private ChannelManager channelManager; private NodeMembership membership; @Before public void setUp() throws Exception { channelManager = Mockito.mock(ChannelManager.class); Configuration.getInstance().putProperty(Configuration.CONFIGURATION_LOCAL_DOMAIN_CHECKER, Boolean.TRUE.toString()); Mockito.when(channelManager.nodeExists(Mockito.anyString())).thenReturn(true); Mockito.when(channelManager.isEphemeralNode(Mockito.anyString())).thenReturn(false); queue = new LinkedBlockingQueue<Packet>(); unsubscribe = new UnsubscribeSet(queue, channelManager); request = readStanzaAsIq("/iq/pubsub/unsubscribe/request.stanza"); unsubscribe.setServerDomain("shakespeare.lit"); element = new BaseElement("unsubscribe"); element.addAttribute("node", node); unsubscribe.setChannelManager(channelManager); membership = new NodeMembershipImpl(node, jid, Subscriptions.subscribed, Affiliations.publisher, null); Mockito.when(channelManager.getNodeMembership(Mockito.anyString(), Mockito.any(JID.class))) .thenReturn(membership); ResultSet<NodeSubscription> listeners = new ResultSetImpl<NodeSubscription>(new ArrayList<NodeSubscription>()); Mockito.when(channelManager.getNodeSubscriptionListeners(node)).thenReturn(listeners); Mockito.when(channelManager.getNodeOwners(Mockito.anyString())) .thenReturn(new ArrayList<JID>()); } @Test public void missingNodeAttributeReturnsError() throws Exception { IQ badRequest = request.createCopy(); badRequest.getChildElement().element("unsubscribe").attribute("node").detach(); unsubscribe.process(element, jid, badRequest, null); Assert.assertEquals(1, queue.size()); IQ response = (IQ) queue.poll(); Assert.assertEquals(IQ.Type.error, response.getType()); Assert.assertEquals(badRequest.getFrom(), response.getTo()); PacketError error = response.getError(); Assert.assertEquals(PacketError.Condition.bad_request, error.getCondition()); Assert.assertEquals(PacketError.Type.modify, error.getType()); Assert.assertEquals(UnsubscribeSet.NODE_ID_REQUIRED, error.getApplicationConditionName()); } @Test public void emptyNodeAttributeReturnsError() throws Exception { IQ badRequest = request.createCopy(); badRequest.getChildElement().element("unsubscribe").attribute("node").detach(); badRequest.getChildElement().element("unsubscribe").addAttribute("node", ""); unsubscribe.process(element, jid, badRequest, null); Assert.assertEquals(1, queue.size()); IQ response = (IQ) queue.poll(); Assert.assertEquals(IQ.Type.error, response.getType()); Assert.assertEquals(badRequest.getFrom(), response.getTo()); PacketError error = response.getError(); Assert.assertEquals(PacketError.Condition.bad_request, error.getCondition()); Assert.assertEquals(PacketError.Type.modify, error.getType()); Assert.assertEquals(UnsubscribeSet.NODE_ID_REQUIRED, error.getApplicationConditionName()); } @Test public void makesRemoteRequest() throws Exception { Configuration.getInstance().remove(Configuration.CONFIGURATION_LOCAL_DOMAIN_CHECKER); unsubscribe.process(element, jid, request, null); Assert.assertEquals(1, queue.size()); String domain = new JID( request.getChildElement().element("unsubscribe").attributeValue("node").split("/")[2]) .getDomain(); IQ response = (IQ) queue.poll(); Assert.assertEquals(IQ.Type.set, response.getType()); Assert.assertEquals(domain, response.getTo().toString()); Element actor = response.getChildElement().element("actor"); Assert.assertNotNull(actor); Assert.assertEquals(Buddycloud.NS, actor.getNamespaceURI()); Assert.assertEquals(request.getFrom().toBareJID(), actor.getText()); } @Test public void canNotUnsubscribeAnotherUser() throws Exception { IQ badRequest = request.createCopy(); badRequest.getChildElement().element("unsubscribe").attribute("jid").detach(); badRequest.getChildElement().element("unsubscribe").addAttribute("jid", "romeo@montague.lit"); unsubscribe.process(element, jid, badRequest, null); Assert.assertEquals(1, queue.size()); IQ response = (IQ) queue.poll(); Assert.assertEquals(IQ.Type.error, response.getType()); Assert.assertEquals(badRequest.getFrom(), response.getTo()); PacketError error = response.getError(); Assert.assertEquals(PacketError.Condition.not_authorized, error.getCondition()); Assert.assertEquals(PacketError.Type.auth, error.getType()); } @Test public void notExistingNodeRetunsError() throws Exception { Mockito.when(channelManager.nodeExists(Mockito.anyString())).thenReturn(false); unsubscribe.process(element, jid, request, null); Assert.assertEquals(1, queue.size()); IQ response = (IQ) queue.poll(); Assert.assertEquals(IQ.Type.error, response.getType()); Assert.assertEquals(request.getFrom(), response.getTo()); PacketError error = response.getError(); Assert.assertEquals(PacketError.Condition.item_not_found, error.getCondition()); Assert.assertEquals(PacketError.Type.cancel, error.getType()); } @Test public void nonMatchingSubscriptionToSenderReturnsError() throws Exception { membership = new NodeMembershipImpl(node, new JID("juliet@capulet.lit"), Subscriptions.subscribed, Affiliations.owner, null); Mockito.when(channelManager.getNodeMembership(Mockito.anyString(), Mockito.any(JID.class))) .thenReturn(membership); unsubscribe.process(element, jid, request, null); Assert.assertEquals(1, queue.size()); IQ response = (IQ) queue.poll(); Assert.assertEquals(IQ.Type.error, response.getType()); Assert.assertEquals(request.getFrom(), response.getTo()); PacketError error = response.getError(); Assert.assertEquals(PacketError.Condition.forbidden, error.getCondition()); Assert.assertEquals(PacketError.Type.auth, error.getType()); Assert.assertEquals(Buddycloud.NS, error.getElement().element(UnsubscribeSet.CAN_NOT_UNSUBSCRIBE_ANOTHER_USER) .getNamespaceURI()); Assert.assertEquals(UnsubscribeSet.CAN_NOT_UNSUBSCRIBE_ANOTHER_USER, error.getApplicationConditionName()); } @Test public void canNotUnsubscribeAsOnlyNodeOwner() throws Exception { membership = new NodeMembershipImpl(node, jid, Subscriptions.subscribed, Affiliations.owner, null); Mockito.when(channelManager.getNodeMembership(Mockito.anyString(), Mockito.any(JID.class))) .thenReturn(membership); ArrayList<JID> owners = new ArrayList<JID>(); owners.add(jid); Mockito.when(channelManager.getNodeOwners(Mockito.anyString())).thenReturn(owners); unsubscribe.process(element, jid, request, null); Assert.assertEquals(1, queue.size()); IQ response = (IQ) queue.poll(); Assert.assertEquals(IQ.Type.error, response.getType()); PacketError error = response.getError(); Assert.assertNotNull(error); Assert.assertEquals(PacketError.Type.cancel, error.getType()); Assert.assertEquals(PacketError.Condition.not_allowed, error.getCondition()); Assert.assertEquals(UnsubscribeSet.MUST_HAVE_ONE_OWNER, error.getApplicationConditionName()); Assert.assertEquals(Buddycloud.NS, error.getApplicationConditionNamespaceURI()); } @Test public void unsubscribesTheUser() throws Exception { ArgumentCaptor<NodeSubscriptionImpl> argument = ArgumentCaptor.forClass(NodeSubscriptionImpl.class); unsubscribe.process(element, jid, request, null); Mockito.verify(channelManager, Mockito.times(1)).addUserSubscription(argument.capture()); IQ response = (IQ) queue.poll(); Assert.assertEquals(IQ.Type.result, response.getType()); Assert.assertEquals(node, argument.getValue().getNodeId()); Assert.assertEquals(request.getFrom().toBareJID(), argument.getValue().getUser().toString()); Assert.assertEquals(Subscriptions.none, argument.getValue().getSubscription()); } @Test public void updatesUserAffiliationToNone() throws Exception { unsubscribe.process(element, jid, request, null); Mockito.verify(channelManager, Mockito.times(1)).setUserAffiliation(Mockito.eq(node), Mockito.eq(jid), Mockito.eq(Affiliations.none)); IQ response = (IQ) queue.poll(); Assert.assertEquals(IQ.Type.result, response.getType()); } @Test public void doesNotUpdateAffiliationIfOutcast() throws Exception { membership = new NodeMembershipImpl(node, jid, Subscriptions.subscribed, Affiliations.outcast, null); Mockito.when(channelManager.getNodeMembership(Mockito.anyString(), Mockito.any(JID.class))) .thenReturn(membership); Mockito.when(channelManager.getNodeOwners(Mockito.anyString())) .thenReturn(new ArrayList<JID>()); unsubscribe.process(element, jid, request, null); Mockito.verify(channelManager, Mockito.times(0)).setUserAffiliation(Mockito.eq(node), Mockito.eq(jid), Mockito.eq(Affiliations.none)); IQ response = (IQ) queue.poll(); Assert.assertEquals(IQ.Type.result, response.getType()); } @Test public void sendsExpectedNotifications() throws Exception { JID listener = new JID("channels.example.com"); ArrayList<NodeSubscription> listeners = new ArrayList<NodeSubscription>(); listeners.add(new NodeSubscriptionImpl(node, jid, listener, Subscriptions.subscribed, null)); ResultSet<NodeSubscription> nodeListeners = new ResultSetImpl<NodeSubscription>(listeners); Mockito.when(channelManager.getNodeSubscriptionListeners(node)).thenReturn(nodeListeners); unsubscribe.process(element, jid, request, null); Assert.assertEquals(4, queue.size()); IQ response = (IQ) queue.poll(); Assert.assertEquals(IQ.Type.result, response.getType()); Message notification = (Message) queue.poll(); Assert.assertEquals(jid, notification.getTo()); Assert.assertEquals(Message.Type.headline, notification.getType()); Element event = notification.getElement().element("event"); Assert.assertEquals(Event.NAMESPACE, event.getNamespaceURI()); Element subscription = event.element("subscription"); Assert.assertEquals(node, subscription.attributeValue("node")); Assert.assertEquals(jid.toBareJID(), subscription.attributeValue("jid")); Assert.assertEquals(Subscriptions.none.toString(), subscription.attributeValue("subscription")); } @Test public void acceptsUnubscribeElement() throws Exception { Assert.assertTrue(unsubscribe.accept(new BaseElement("unsubscribe"))); } @Test public void rejectsNotUnsubscribeElement() throws Exception { Assert.assertFalse(unsubscribe.accept(new BaseElement("not-unsubscribe"))); } @Test public void doesNotDeleteEphemeralNodeIfThereAreSubscribers() throws Exception { Mockito.when(channelManager.isEphemeralNode(Mockito.anyString())).thenReturn(true); ArrayList<NodeMembership> members = new ArrayList<NodeMembership>(); members.add(new NodeMembershipImpl(node, jid, Subscriptions.subscribed, Affiliations.member, null)); Mockito.when(channelManager.getNodeMemberships(Mockito.eq(node))).thenReturn( new ResultSetImpl<NodeMembership>(members)); unsubscribe.process(element, jid, request, null); Mockito.verify(channelManager, Mockito.times(0)).deleteNode(Mockito.eq(node)); } @Test public void deletesEphemeralNodeIfThereAreNoSubscribers() throws Exception { Mockito.when(channelManager.isEphemeralNode(Mockito.anyString())).thenReturn(true); Mockito.when(channelManager.getNodeMemberships(Mockito.eq(node))).thenReturn( new ResultSetImpl<NodeMembership>(new ArrayList<NodeMembership>())); unsubscribe.process(element, jid, request, null); Mockito.verify(channelManager, Mockito.times(1)).deleteNode(Mockito.eq(node)); } }
package org.arquillian.smart.testing.surefire.provider; import java.io.File; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.Enumeration; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.logging.Level; import java.util.regex.Pattern; import org.arquillian.smart.testing.Logger; import static java.lang.Thread.currentThread; /** * Loads library versions from given classloader. */ public class LoaderVersionExtractor { public static final MavenLibrary LIBRARY_SUREFIRE_API = new MavenLibrary("org.apache.maven.surefire", "surefire-api"); public static final MavenLibrary LIBRARY_JUNIT = new MavenLibrary("junit", "junit"); public static final MavenLibrary LIBRARY_TEST_NG = new MavenLibrary("org.testng", "testng"); private static final Logger logger = Logger.getLogger(LoaderVersionExtractor.class); private static Map<ClassLoader, Map<MavenLibrary, String>> loaderWithLibraryVersions = new HashMap<>(); private static List<MavenLibrary> initLibraries = new ArrayList<>(); static { initLibraries.add(LIBRARY_SUREFIRE_API); initLibraries.add(LIBRARY_JUNIT); initLibraries.add(LIBRARY_TEST_NG); } public static String getSurefireApiVersion() { return getVersionFromClassLoader(LIBRARY_SUREFIRE_API, currentThread().getContextClassLoader()); } public static String getJunitVersion() { return getVersionFromClassLoader(LIBRARY_JUNIT, currentThread().getContextClassLoader()); } public static String getTestNgVersion() { return getVersionFromClassLoader(LIBRARY_TEST_NG, currentThread().getContextClassLoader()); } /** * In the given classloader finds manifest file on a path matching the given groupId and artifactId; * when the file is matched, then it retrieves and returns a version. * * @param mavenLibrary * Maven library to find * @param loader * The classloader the library should be in * * @return Version retrieved from the matched path */ public static String getVersionFromClassLoader(MavenLibrary mavenLibrary, ClassLoader loader) { if (loaderWithLibraryVersions.get(loader) != null) { if (!initLibraries.contains(mavenLibrary)) { List<MavenLibrary> wrappedLibrary = Arrays.asList(mavenLibrary); Map<MavenLibrary, String> implTitleWithVersion = getTitleWithVersion(wrappedLibrary, loader); loaderWithLibraryVersions.put(loader, implTitleWithVersion); } } else { Map<MavenLibrary, String> implTitleWithVersion = getTitleWithVersion(initLibraries, loader); loaderWithLibraryVersions.put(loader, implTitleWithVersion); } return loaderWithLibraryVersions.get(loader).get(mavenLibrary); } private static Map<MavenLibrary, String> getTitleWithVersion(List<MavenLibrary> libraries, ClassLoader classLoader) { Map<MavenLibrary, String> implTitleWithVersion = new HashMap<>(); ArrayList<MavenLibrary> librariesToFind = new ArrayList<>(libraries); try { Enumeration<URL> manifests = classLoader.getResources("META-INF/MANIFEST.MF"); while (manifests.hasMoreElements()) { String manifestURL = manifests.nextElement().toString(); Optional<MavenLibrary> matched = librariesToFind.parallelStream() .filter(library -> manifestURL.matches(library.getRegex())) .findFirst(); matched.ifPresent(mavenLibrary -> { MavenLibrary matchedLibrary = mavenLibrary; String startWithVersion = manifestURL.replaceAll(matchedLibrary.getLeadingRegex(), ""); String version = startWithVersion.substring(0, startWithVersion.indexOf(File.separator)); implTitleWithVersion.put(matchedLibrary, version); librariesToFind.remove(matchedLibrary); }); } } catch (Exception e) { logger.log(Level.WARNING, "Exception {0} occurred while resolving manifest files", e.getMessage()); } return implTitleWithVersion; } static class MavenLibrary { private final String groupId; private final String artifactId; MavenLibrary(String groupId, String artifactId) { this.groupId = groupId; this.artifactId = artifactId; } String getRegex() { return Pattern.compile(getLeadingString() + ".*" + File.separator + artifactId + "-.*\\.jar.*").pattern(); } String getLeadingRegex() { return Pattern.compile(getLeadingString()).pattern(); } private String getLeadingString() { return ".*" + File.separator + groupId.replaceAll("\\.", File.separator) + File.separator + artifactId + File.separator; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; final MavenLibrary that = (MavenLibrary) o; if (groupId != null ? !groupId.equals(that.groupId) : that.groupId != null) return false; if (artifactId != null ? !artifactId.equals(that.artifactId) : that.artifactId != null) return false; return true; } @Override public int hashCode() { int result = groupId != null ? groupId.hashCode() : 0; result = 31 * result + (artifactId != null ? artifactId.hashCode() : 0); return result; } } }
package org.reasm.commons.parseerrors; import java.util.Objects; import javax.annotation.Nonnull; import javax.annotation.concurrent.Immutable; import org.reasm.commons.source.BlockDirective; import org.reasm.source.ParseError; @Immutable public class UnclosedBlockParseError extends ParseError { @Nonnull private final BlockDirective startingBlockDirective; /** * Initializes a new UnclosedBlockParseError. * * @param startingBlockDirective * the starting directive of the block that was not closed */ public UnclosedBlockParseError(@Nonnull BlockDirective startingBlockDirective) { super("Block starting with \"" + Objects.requireNonNull(startingBlockDirective, "startingBlockDirective").getMnemonic() + "\" is not closed"); this.startingBlockDirective = startingBlockDirective; } /** * Gets the starting directive of the block that was not closed. * * @return the starting directive */ @Nonnull public final BlockDirective getStartingBlockDirective() { return this.startingBlockDirective; } }
package com.opengamma.math.statistics.estimation; import static org.junit.Assert.assertEquals; import org.junit.Test; import cern.jet.random.engine.MersenneTwister64; import com.opengamma.math.statistics.distribution.LaplaceDistribution; import com.opengamma.math.statistics.distribution.ProbabilityDistribution; public class LaplaceDistributionMaximumLikelihoodEstimatorTest { private static final DistributionParameterEstimator<Double> ESTIMATOR = new LaplaceDistributionMaximumLikelihoodEstimator(); @Test(expected = IllegalArgumentException.class) public void testNull() { ESTIMATOR.evaluate((double[]) null); } @Test(expected = IllegalArgumentException.class) public void testEmpty() { ESTIMATOR.evaluate(new double[0]); } @Test public void test() { final double mu = 0.367; final double b = 1.4; final ProbabilityDistribution<Double> distribution = new LaplaceDistribution(mu, b, new MersenneTwister64(MersenneTwister64.DEFAULT_SEED)); final int n = 500000; final double[] x = new double[n]; for (int i = 0; i < n; i++) { x[i] = distribution.nextRandom(); } final LaplaceDistribution result = (LaplaceDistribution) ESTIMATOR.evaluate(x); final double eps = 1e-2; assertEquals(1, result.getB() / b, eps); assertEquals(1, result.getMu() / mu, eps); } }
package org.jboss.as.test.integration.domain.mixed; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.BLOCKING; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.CORE_SERVICE; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.EXTENSION; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.HOST; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.INCLUDE_ALIASES; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.INCLUDE_RUNTIME; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.INTERFACE; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.MANAGEMENT_CLIENT_CONTENT; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.NAMESPACES; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP_ADDR; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.PROFILE; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.PROXIES; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.READ_RESOURCE_OPERATION; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.RECURSIVE; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.RESTART; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SCHEMA_LOCATIONS; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SERVER_CONFIG; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SERVER_GROUP; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SOCKET_BINDING_GROUP; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SUBSYSTEM; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SYSTEM_PROPERTY; import static org.jboss.as.test.integration.domain.management.util.DomainTestSupport.validateResponse; import static org.junit.Assert.assertEquals; import java.net.URL; import java.net.URLConnection; import java.util.HashSet; import java.util.List; import java.util.Set; import org.jboss.as.controller.PathAddress; import org.jboss.as.controller.PathElement; import org.jboss.as.controller.client.helpers.domain.DomainClient; import org.jboss.as.controller.operations.common.Util; import org.jboss.as.model.test.ModelTestUtils; import org.jboss.as.security.Constants; import org.jboss.as.security.SecurityExtension; import org.jboss.as.test.integration.domain.management.util.DomainTestSupport; import org.jboss.as.test.integration.domain.management.util.DomainTestUtils; import org.jboss.as.test.integration.domain.mixed.Version.AsVersion; import org.jboss.as.test.integration.domain.mixed.util.MixedDomainTestSupport; import org.jboss.as.test.shared.TestSuiteEnvironment; import org.jboss.dmr.ModelNode; import org.jboss.dmr.Property; import org.junit.AfterClass; import org.junit.Assert; import org.junit.Before; import org.junit.FixMethodOrder; import org.junit.Test; import org.junit.runners.MethodSorters; import org.xnio.IoUtils; /** * * @author <a href="kabir.khan@jboss.com">Kabir Khan</a> */ @FixMethodOrder(MethodSorters.NAME_ASCENDING) public abstract class SimpleMixedDomainTest { MixedDomainTestSupport support; Version.AsVersion version; @Before public void init() throws Exception { support = MixedDomainTestSuite.getSupport(this.getClass()); version = MixedDomainTestSuite.getVersion(this.getClass()); } @AfterClass public synchronized static void afterClass() { MixedDomainTestSuite.afterClass(); } @Test public void test1ServerRunning() throws Exception { URLConnection connection = new URL("http://" + TestSuiteEnvironment.formatPossibleIpv6Address(DomainTestSupport.slaveAddress) + ":8080").openConnection(); connection.connect(); } @Test public void test2Versioning() throws Exception { DomainClient masterClient = support.getDomainMasterLifecycleUtil().createDomainClient(); ModelNode masterModel; try { masterModel = readDomainModelForVersions(masterClient); } finally { IoUtils.safeClose(masterClient); } DomainClient slaveClient = support.getDomainSlaveLifecycleUtil().createDomainClient(); ModelNode slaveModel; try { slaveModel = readDomainModelForVersions(slaveClient); } finally { IoUtils.safeClose(slaveClient); } cleanupKnownDifferencesInModelsForVersioningCheck(masterModel, slaveModel); //The version fields should be the same assertEquals(masterModel, slaveModel); } @Test public void test9SecurityTransformers() throws Exception { final DomainClient masterClient = support.getDomainMasterLifecycleUtil().createDomainClient(); final DomainClient slaveClient = support.getDomainSlaveLifecycleUtil().createDomainClient(); try { PathAddress subsystem = PathAddress.pathAddress(PathElement.pathElement(PROFILE, getProfile()), PathElement.pathElement(SUBSYSTEM, SecurityExtension.SUBSYSTEM_NAME)); PathAddress webPolicy = subsystem.append(Constants.SECURITY_DOMAIN, "jboss-web-policy").append(Constants.AUTHORIZATION, Constants.CLASSIC); ModelNode options = new ModelNode(); options.add("a", "b"); ModelNode op = Util.getWriteAttributeOperation(webPolicy.append(Constants.POLICY_MODULE, "Delegating"), Constants.MODULE_OPTIONS, options); DomainTestUtils.executeForResult(op, masterClient); //TODO check the resources //System.out.println(DomainTestUtils.executeForResult(Util.createOperation(READ_RESOURCE_OPERATION, address), modelControllerClient)); PathAddress jaspi = subsystem.append(Constants.SECURITY_DOMAIN, "jaspi-test").append(Constants.AUTHENTICATION, Constants.JASPI); PathAddress jaspiLoginStack = jaspi.append(Constants.LOGIN_MODULE_STACK, "lm-stack"); op = Util.createAddOperation(jaspiLoginStack.append(Constants.LOGIN_MODULE, "test2")); op.get(Constants.CODE).set("UserRoles"); op.get(Constants.FLAG).set("required"); op.get(Constants.MODULE).set("test-jaspi"); DomainTestUtils.executeForResult(op, masterClient); op = Util.createAddOperation(jaspi.append(Constants.AUTH_MODULE, "Delegating")); op.get(Constants.CODE).set("Delegating"); op.get(Constants.LOGIN_MODULE_STACK_REF).set("lm-stack"); op.get(Constants.FLAG).set("optional"); DomainTestUtils.executeForResult(op, masterClient); op = new ModelNode(); op.get(OP).set(READ_RESOURCE_OPERATION); op.get(OP_ADDR).set(jaspi.toModelNode()); op.get(INCLUDE_ALIASES).set(false); op.get(RECURSIVE).set(true); ModelNode masterResource = DomainTestUtils.executeForResult(op, masterClient); ModelNode slaveResource = DomainTestUtils.executeForResult(op, slaveClient); //TODO only check this for 7.1.x if (version == Version.AsVersion.AS_7_1_2_FINAL || version == Version.AsVersion.AS_7_1_3_FINAL) { ModelNode masterModules = masterResource.get(Constants.AUTH_MODULE); Assert.assertFalse(slaveResource.hasDefined(Constants.AUTH_MODULE)); List<ModelNode> slaveModules = slaveResource.get(Constants.AUTH_MODULES).asList(); Assert.assertEquals(masterModules.keys().size(), slaveModules.size()); Set<ModelNode> masterSet = getAllChildren(masterModules); Assert.assertTrue(slaveModules.containsAll(masterSet)); masterModules = masterResource.get(Constants.LOGIN_MODULE_STACK, "lm-stack", Constants.LOGIN_MODULE); Assert.assertFalse(slaveResource.get(Constants.LOGIN_MODULE_STACK, "lm-stack").hasDefined(Constants.LOGIN_MODULE)); slaveModules = slaveResource.get(Constants.LOGIN_MODULE_STACK, "lm-stack", Constants.LOGIN_MODULES).asList(); Assert.assertEquals(masterModules.keys().size(), slaveModules.size()); masterSet = getAllChildren(masterModules); Assert.assertTrue(slaveModules.containsAll(masterSet)); } else { ModelTestUtils.compare(masterResource, slaveResource, true); } } finally { try { //The server will be in restart-required mode, so restart it to get rid of the changes PathAddress serverAddress = PathAddress.pathAddress(HOST, "slave").append(SERVER_CONFIG, "server-one"); ModelNode op = Util.createOperation(RESTART, PathAddress.pathAddress(serverAddress)); op.get(BLOCKING).set(true); Assert.assertEquals("STARTED", validateResponse(slaveClient.execute(op), true).asString()); } finally { IoUtils.safeClose(slaveClient); IoUtils.safeClose(masterClient); } } } private Set<ModelNode> getAllChildren(ModelNode modules) { HashSet<ModelNode> set = new HashSet<ModelNode>(); for (Property prop : modules.asPropertyList()) { set.add(prop.getValue()); } return set; } private void cleanupKnownDifferencesInModelsForVersioningCheck(ModelNode masterModel, ModelNode slaveModel) { //First get rid of any undefined crap cleanUndefinedNodes(masterModel); cleanUndefinedNodes(slaveModel); if (version == AsVersion.AS_7_1_2_FINAL || version == AsVersion.AS_7_1_3_FINAL) { if (masterModel.hasDefined(NAMESPACES) && masterModel.get(NAMESPACES).asList().isEmpty()) { if (!slaveModel.hasDefined(NAMESPACES)) { masterModel.remove(NAMESPACES); } } if (masterModel.hasDefined(SCHEMA_LOCATIONS) && masterModel.get(SCHEMA_LOCATIONS).asList().isEmpty()) { if (!slaveModel.hasDefined(SCHEMA_LOCATIONS)) { masterModel.remove(SCHEMA_LOCATIONS); } } } } private void cleanUndefinedNodes(ModelNode model) { Set<String> removals = new HashSet<String>(); for (String key : model.keys()) { if (!model.hasDefined(key)) { removals.add(key); } } for (String key : removals) { model.remove(key); } } private ModelNode readDomainModelForVersions(DomainClient domainClient) throws Exception { ModelNode op = new ModelNode(); op.get(OP).set(READ_RESOURCE_OPERATION); op.get(OP_ADDR).setEmptyList(); op.get(RECURSIVE).set(true); op.get(INCLUDE_RUNTIME).set(false); op.get(PROXIES).set(false); ModelNode model = DomainTestUtils.executeForResult(op, domainClient); model.remove(EXTENSION); model.remove(HOST); model.remove(INTERFACE); model.remove(MANAGEMENT_CLIENT_CONTENT); model.remove(PROFILE); model.remove(SERVER_GROUP); model.remove(SOCKET_BINDING_GROUP); model.remove(SYSTEM_PROPERTY); model.remove(CORE_SERVICE); return model; } protected abstract String getProfile(); }
package org.search.nibrs.validation; import java.time.LocalDateTime; import java.time.ZoneId; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.function.Function; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.search.nibrs.model.GroupAIncidentReport; final class ArresteeRuleViolationExemplarFactory { private static final ArresteeRuleViolationExemplarFactory INSTANCE = new ArresteeRuleViolationExemplarFactory(); @SuppressWarnings("unused") private static final Logger LOG = LogManager.getLogger(ArresteeRuleViolationExemplarFactory.class); private Map<Integer, Function<GroupAIncidentReport, List<GroupAIncidentReport>>> groupATweakerMap; private ArresteeRuleViolationExemplarFactory() { groupATweakerMap = new HashMap<Integer, Function<GroupAIncidentReport, List<GroupAIncidentReport>>>(); populateGroupAExemplarMap(); } /** * Get an instance of the factory. * * @return the instance */ public static final ArresteeRuleViolationExemplarFactory getInstance() { return INSTANCE; } Map<Integer, Function<GroupAIncidentReport, List<GroupAIncidentReport>>> getGroupATweakerMap() { return groupATweakerMap; } private void populateGroupAExemplarMap() { groupATweakerMap.put(601, incident -> { // The referenced data element in a Group A Incident AbstractReport // Segment 6 is mandatory & must be present. List<GroupAIncidentReport> incidents = new ArrayList<GroupAIncidentReport>(); GroupAIncidentReport copy = new GroupAIncidentReport(incident); copy.setYearOfTape(null); GroupAIncidentReport copy2 = new GroupAIncidentReport(copy); copy2.setMonthOfTape(null); GroupAIncidentReport copy3 = new GroupAIncidentReport(copy); copy3.setOri(null); GroupAIncidentReport copy4 = new GroupAIncidentReport(copy); copy4.setIncidentNumber(null); GroupAIncidentReport copy5 = new GroupAIncidentReport(copy); copy5.getArrestees().get(0).setArresteeSequenceNumber(null); GroupAIncidentReport copy6 = new GroupAIncidentReport(copy); copy6.getArrestees().get(0).setArrestTransactionNumber(null); incidents.add(copy); incidents.add(copy2); incidents.add(copy3); incidents.add(copy4); incidents.add(copy5); incidents.add(copy6); return incidents; }); groupATweakerMap.put(617, incident -> { //(Arrest Transaction Number) Must contain a valid character combination of the following: //AZ (capital letters only) //Hyphen //Example: 11-123-SC is valid, but 11+123*SC is not valid List<GroupAIncidentReport> incidents = new ArrayList<GroupAIncidentReport>(); GroupAIncidentReport copy = new GroupAIncidentReport(incident); copy.getArrestees().get(0).setArrestTransactionNumber("11+123*SC"); incidents.add(copy); return incidents; }); groupATweakerMap.put(665, incident -> { //(Arrest Date) cannot be earlier than Data Element 3 (Incident Date/Hour). //A person cannot be arrested before the incident occurred. List<GroupAIncidentReport> incidents = new ArrayList<GroupAIncidentReport>(); GroupAIncidentReport copy = new GroupAIncidentReport(incident); copy.getArrestees().get(0).setArrestDate(Date.from(LocalDateTime.of(2016, 4, 12, 10, 7, 46).atZone(ZoneId.systemDefault()).toInstant())); incidents.add(copy); return incidents; }); } }
package org.jfree.chart.renderer.category; import java.awt.Font; import java.awt.Graphics2D; import java.awt.Paint; import java.awt.Shape; import java.awt.Stroke; import java.awt.geom.Rectangle2D; import org.jfree.chart.LegendItem; import org.jfree.chart.LegendItemSource; import org.jfree.chart.axis.CategoryAxis; import org.jfree.chart.axis.ValueAxis; import org.jfree.chart.event.RendererChangeEvent; import org.jfree.chart.event.RendererChangeListener; import org.jfree.chart.labels.CategoryItemLabelGenerator; import org.jfree.chart.labels.CategoryToolTipGenerator; import org.jfree.chart.labels.ItemLabelPosition; import org.jfree.chart.plot.CategoryMarker; import org.jfree.chart.plot.CategoryPlot; import org.jfree.chart.plot.Marker; import org.jfree.chart.plot.PlotRenderingInfo; import org.jfree.chart.ui.RectangleEdge; import org.jfree.chart.urls.CategoryURLGenerator; import org.jfree.data.Range; import org.jfree.data.category.CategoryDataset; /** * A plug-in object that is used by the {@link CategoryPlot} class to display * individual data items from a {@link CategoryDataset}. * <p> * This interface defines the methods that must be provided by all renderers. * If you are implementing a custom renderer, you should consider extending the * {@link AbstractCategoryItemRenderer} class. * <p> * Most renderer attributes are defined using a two layer approach. When * looking up an attribute (for example, the outline paint) the renderer first * checks to see if there is a setting that applies to a specific series * that the renderer draws. If there is, that setting is used, but if it is * {@code null} the renderer looks up the default setting. Some attributes * allow the base setting to be {@code null}, while other attributes enforce * non-{@code null} values. */ public interface CategoryItemRenderer extends LegendItemSource { /** * Returns the number of passes through the dataset required by the * renderer. Usually this will be one, but some renderers may use * a second or third pass to overlay items on top of things that were * drawn in an earlier pass. * * @return The pass count. */ public int getPassCount(); /** * Returns the plot that the renderer has been assigned to (where * {@code null} indicates that the renderer is not currently assigned * to a plot). * * @return The plot (possibly {@code null}). * * @see #setPlot(CategoryPlot) */ public CategoryPlot getPlot(); /** * Sets the plot that the renderer has been assigned to. This method is * usually called by the {@link CategoryPlot}, in normal usage you * shouldn't need to call this method directly. * * @param plot the plot ({@code null} not permitted). * * @see #getPlot() */ public void setPlot(CategoryPlot plot); /** * Adds a change listener. * * @param listener the listener. * * @see #removeChangeListener(RendererChangeListener) */ public void addChangeListener(RendererChangeListener listener); /** * Removes a change listener. * * @param listener the listener. * * @see #addChangeListener(RendererChangeListener) */ public void removeChangeListener(RendererChangeListener listener); /** * Returns the range of values the renderer requires to display all the * items from the specified dataset. * * @param dataset the dataset ({@code null} permitted). * * @return The range (or {@code null} if the dataset is * {@code null} or empty). */ public Range findRangeBounds(CategoryDataset dataset); /** * Initialises the renderer. This method will be called before the first * item is rendered, giving the renderer an opportunity to initialise any * state information it wants to maintain. The renderer can do nothing if * it chooses. * * @param g2 the graphics device. * @param dataArea the area inside the axes. * @param plot the plot. * @param rendererIndex the renderer index. * @param info collects chart rendering information for return to caller. * * @return A state object (maintains state information relevant to one * chart drawing). */ public CategoryItemRendererState initialise(Graphics2D g2, Rectangle2D dataArea, CategoryPlot plot, int rendererIndex, PlotRenderingInfo info); /** * Returns a boolean that indicates whether or not the specified item * should be drawn (this is typically used to hide an entire series). * * @param series the series index. * @param item the item index. * * @return A boolean. */ public boolean getItemVisible(int series, int item); /** * Returns a boolean that indicates whether or not the specified series * should be drawn (this is typically used to hide an entire series). * * @param series the series index. * * @return A boolean. */ public boolean isSeriesVisible(int series); /** * Returns the flag that controls whether a series is visible. * * @param series the series index (zero-based). * * @return The flag (possibly {@code null}). * * @see #setSeriesVisible(int, Boolean) */ public Boolean getSeriesVisible(int series); /** * Sets the flag that controls whether a series is visible and sends a * {@link RendererChangeEvent} to all registered listeners. * * @param series the series index (zero-based). * @param visible the flag ({@code null} permitted). * * @see #getSeriesVisible(int) */ public void setSeriesVisible(int series, Boolean visible); /** * Sets the flag that controls whether a series is visible and, if * requested, sends a {@link RendererChangeEvent} to all registered * listeners. * * @param series the series index. * @param visible the flag ({@code null} permitted). * @param notify notify listeners? * * @see #getSeriesVisible(int) */ public void setSeriesVisible(int series, Boolean visible, boolean notify); /** * Returns the default visibility for all series. * * @return The default visibility. * * @see #setDefaultSeriesVisible(boolean) */ public boolean getDefaultSeriesVisible(); /** * Sets the default visibility and sends a {@link RendererChangeEvent} to all * registered listeners. * * @param visible the flag. * * @see #getDefaultSeriesVisible() */ public void setDefaultSeriesVisible(boolean visible); /** * Sets the default visibility and, if requested, sends * a {@link RendererChangeEvent} to all registered listeners. * * @param visible the visibility. * @param notify notify listeners? * * @see #getDefaultSeriesVisible() */ public void setDefaultSeriesVisible(boolean visible, boolean notify); // SERIES VISIBLE IN LEGEND (not yet respected by all renderers) /** * Returns {@code true} if the series should be shown in the legend, * and {@code false} otherwise. * * @param series the series index. * * @return A boolean. */ public boolean isSeriesVisibleInLegend(int series); /** * Returns the flag that controls whether a series is visible in the * legend. This method returns only the "per series" settings - to * incorporate the override and base settings as well, you need to use the * {@link #isSeriesVisibleInLegend(int)} method. * * @param series the series index (zero-based). * * @return The flag (possibly {@code null}). * * @see #setSeriesVisibleInLegend(int, Boolean) */ public Boolean getSeriesVisibleInLegend(int series); /** * Sets the flag that controls whether a series is visible in the legend * and sends a {@link RendererChangeEvent} to all registered listeners. * * @param series the series index (zero-based). * @param visible the flag ({@code null} permitted). * * @see #getSeriesVisibleInLegend(int) */ public void setSeriesVisibleInLegend(int series, Boolean visible); /** * Sets the flag that controls whether a series is visible in the legend * and, if requested, sends a {@link RendererChangeEvent} to all registered * listeners. * * @param series the series index. * @param visible the flag ({@code null} permitted). * @param notify notify listeners? * * @see #getSeriesVisibleInLegend(int) */ public void setSeriesVisibleInLegend(int series, Boolean visible, boolean notify); /** * Returns the default visibility in the legend for all series. * * @return The default visibility. * * @see #setDefaultSeriesVisibleInLegend(boolean) */ public boolean getDefaultSeriesVisibleInLegend(); /** * Sets the default visibility in the legend and sends a * {@link RendererChangeEvent} to all registered listeners. * * @param visible the flag. * * @see #getDefaultSeriesVisibleInLegend() */ public void setDefaultSeriesVisibleInLegend(boolean visible); /** * Sets the default visibility in the legend and, if requested, sends * a {@link RendererChangeEvent} to all registered listeners. * * @param visible the visibility. * @param notify notify listeners? * * @see #getDefaultSeriesVisibleInLegend() */ public void setDefaultSeriesVisibleInLegend(boolean visible, boolean notify); //// PAINT ///////////////////////////////////////////////////////////////// /** * Returns the paint used to fill data items as they are drawn. * * @param row the row (or series) index (zero-based). * @param column the column (or category) index (zero-based). * * @return The paint (never {@code null}). */ public Paint getItemPaint(int row, int column); /** * Returns the paint used to fill an item drawn by the renderer. * * @param series the series index (zero-based). * * @return The paint (possibly {@code null}). * * @see #setSeriesPaint(int, Paint) */ public Paint getSeriesPaint(int series); /** * Sets the paint used for a series and sends a {@link RendererChangeEvent} * to all registered listeners. * * @param series the series index (zero-based). * @param paint the paint ({@code null} permitted). * * @see #getSeriesPaint(int) */ public void setSeriesPaint(int series, Paint paint); public void setSeriesPaint(int series, Paint paint, boolean notify); /** * Returns the default paint. * * @return The default paint (never {@code null}). * * @see #setDefaultPaint(Paint) */ public Paint getDefaultPaint(); /** * Sets the default paint and sends a {@link RendererChangeEvent} to all * registered listeners. * * @param paint the paint ({@code null} not permitted). * * @see #getDefaultPaint() */ public void setDefaultPaint(Paint paint); public void setDefaultPaint(Paint paint, boolean notify); //// FILL PAINT ///////////////////////////////////////////////////////// /** * Returns the paint used to fill data items as they are drawn. * * @param row the row (or series) index (zero-based). * @param column the column (or category) index (zero-based). * * @return The paint (never {@code null}). */ public Paint getItemFillPaint(int row, int column); /** * Returns the paint used to fill an item drawn by the renderer. * * @param series the series (zero-based index). * * @return The paint (possibly {@code null}). * * @see #setSeriesFillPaint(int, Paint) */ public Paint getSeriesFillPaint(int series); /** * Sets the paint used for a series outline and sends a * {@link RendererChangeEvent} to all registered listeners. * * @param series the series index (zero-based). * @param paint the paint ({@code null} permitted). * * @see #getSeriesFillPaint(int) */ public void setSeriesFillPaint(int series, Paint paint); /** * Returns the default outline paint. * * @return The paint (never {@code null}). * * @see #setDefaultFillPaint(Paint) */ public Paint getDefaultFillPaint(); /** * Sets the default outline paint and sends a {@link RendererChangeEvent} to * all registered listeners. * * @param paint the paint ({@code null} not permitted). * * @see #getDefaultFillPaint() */ public void setDefaultFillPaint(Paint paint); //// OUTLINE PAINT ///////////////////////////////////////////////////////// /** * Returns the paint used to outline data items as they are drawn. * * @param row the row (or series) index (zero-based). * @param column the column (or category) index (zero-based). * * @return The paint (never {@code null}). */ public Paint getItemOutlinePaint(int row, int column); /** * Returns the paint used to outline an item drawn by the renderer. * * @param series the series (zero-based index). * * @return The paint (possibly {@code null}). * * @see #setSeriesOutlinePaint(int, Paint) */ public Paint getSeriesOutlinePaint(int series); /** * Sets the paint used for a series outline and sends a * {@link RendererChangeEvent} to all registered listeners. * * @param series the series index (zero-based). * @param paint the paint ({@code null} permitted). * * @see #getSeriesOutlinePaint(int) */ public void setSeriesOutlinePaint(int series, Paint paint); public void setSeriesOutlinePaint(int series, Paint paint, boolean notify); /** * Returns the default outline paint. * * @return The paint (never {@code null}). * * @see #setDefaultOutlinePaint(Paint) */ public Paint getDefaultOutlinePaint(); /** * Sets the default outline paint and sends a {@link RendererChangeEvent} to * all registered listeners. * * @param paint the paint ({@code null} not permitted). * * @see #getDefaultOutlinePaint() */ public void setDefaultOutlinePaint(Paint paint); public void setDefaultOutlinePaint(Paint paint, boolean notify); //// STROKE //////////////////////////////////////////////////////////////// /** * Returns the stroke used to draw data items. * * @param row the row (or series) index (zero-based). * @param column the column (or category) index (zero-based). * * @return The stroke (never {@code null}). */ public Stroke getItemStroke(int row, int column); /** * Returns the stroke used to draw the items in a series. * * @param series the series (zero-based index). * * @return The stroke (never {@code null}). * * @see #setSeriesStroke(int, Stroke) */ public Stroke getSeriesStroke(int series); /** * Sets the stroke used for a series and sends a * {@link RendererChangeEvent} to all registered listeners. * * @param series the series index (zero-based). * @param stroke the stroke ({@code null} permitted). * * @see #getSeriesStroke(int) */ public void setSeriesStroke(int series, Stroke stroke); public void setSeriesStroke(int series, Stroke stroke, boolean notify); /** * Returns the default stroke. * * @return The default stroke (never {@code null}). * * @see #setDefaultStroke(Stroke) */ public Stroke getDefaultStroke(); /** * Sets the default stroke and sends a {@link RendererChangeEvent} to all * registered listeners. * * @param stroke the stroke ({@code null} not permitted). * * @see #getDefaultStroke() */ public void setDefaultStroke(Stroke stroke); public void setDefaultStroke(Stroke stroke, boolean notify); //// OUTLINE STROKE //////////////////////////////////////////////////////// /** * Returns the stroke used to outline data items. * <p> * The default implementation passes control to the * lookupSeriesOutlineStroke method. You can override this method if you * require different behaviour. * * @param row the row (or series) index (zero-based). * @param column the column (or category) index (zero-based). * * @return The stroke (never {@code null}). */ public Stroke getItemOutlineStroke(int row, int column); /** * Returns the stroke used to outline the items in a series. * * @param series the series (zero-based index). * * @return The stroke (possibly {@code null}). * * @see #setSeriesOutlineStroke(int, Stroke) */ public Stroke getSeriesOutlineStroke(int series); /** * Sets the outline stroke used for a series and sends a * {@link RendererChangeEvent} to all registered listeners. * * @param series the series index (zero-based). * @param stroke the stroke ({@code null} permitted). * * @see #getSeriesOutlineStroke(int) */ public void setSeriesOutlineStroke(int series, Stroke stroke); public void setSeriesOutlineStroke(int series, Stroke stroke, boolean notify); /** * Returns the default outline stroke. * * @return The stroke (never {@code null}). * * @see #setDefaultOutlineStroke(Stroke) */ public Stroke getDefaultOutlineStroke(); /** * Sets the default outline stroke and sends a {@link RendererChangeEvent} to * all registered listeners. * * @param stroke the stroke ({@code null} not permitted). * * @see #getDefaultOutlineStroke() */ public void setDefaultOutlineStroke(Stroke stroke); public void setDefaultOutlineStroke(Stroke stroke, boolean notify); //// SHAPE ///////////////////////////////////////////////////////////////// /** * Returns a shape used to represent a data item. * * @param row the row (or series) index (zero-based). * @param column the column (or category) index (zero-based). * * @return The shape (never {@code null}). */ public Shape getItemShape(int row, int column); /** * Returns a shape used to represent the items in a series. * * @param series the series (zero-based index). * * @return The shape (possibly {@code null}). * * @see #setSeriesShape(int, Shape) */ public Shape getSeriesShape(int series); /** * Sets the shape used for a series and sends a {@link RendererChangeEvent} * to all registered listeners. * * @param series the series index (zero-based). * @param shape the shape ({@code null} permitted). * * @see #getSeriesShape(int) */ public void setSeriesShape(int series, Shape shape); public void setSeriesShape(int series, Shape shape, boolean notify); /** * Returns the default shape. * * @return The shape (never {@code null}). * * @see #setDefaultShape(Shape) */ public Shape getDefaultShape(); /** * Sets the default shape and sends a {@link RendererChangeEvent} to all * registered listeners. * * @param shape the shape ({@code null} not permitted). * * @see #getDefaultShape() */ public void setDefaultShape(Shape shape); public void setDefaultShape(Shape shape, boolean notify); // ITEM LABELS VISIBLE /** * Returns {@code true} if an item label is visible, and * {@code false} otherwise. * * @param row the row index (zero-based). * @param column the column index (zero-based). * * @return A boolean. */ public boolean isItemLabelVisible(int row, int column); /** * Returns {@code true} if the item labels for a series are visible, * and {@code false} otherwise. * * @param series the series index (zero-based). * * @return A boolean. * * @see #setSeriesItemLabelsVisible(int, Boolean) */ public boolean isSeriesItemLabelsVisible(int series); /** * Sets a flag that controls the visibility of the item labels for a series. * * @param series the series index (zero-based). * @param visible the flag. * * @see #isSeriesItemLabelsVisible(int) */ public void setSeriesItemLabelsVisible(int series, boolean visible); /** * Sets a flag that controls the visibility of the item labels for a series. * * @param series the series index (zero-based). * @param visible the flag ({@code null} permitted). * * @see #isSeriesItemLabelsVisible(int) */ public void setSeriesItemLabelsVisible(int series, Boolean visible); /** * Sets the visibility of item labels for a series and, if requested, sends * a {@link RendererChangeEvent} to all registered listeners. * * @param series the series index (zero-based). * @param visible the visible flag. * @param notify a flag that controls whether or not listeners are * notified. * * @see #isSeriesItemLabelsVisible(int) */ public void setSeriesItemLabelsVisible(int series, Boolean visible, boolean notify); /** * Returns the default setting for item label visibility. A {@code null} * result should be interpreted as equivalent to {@code Boolean.FALSE} * (this is an error in the API design, the return value should have been * a boolean primitive). * * @return A flag (possibly {@code null}). * * @see #setDefaultItemLabelsVisible(boolean) */ public boolean getDefaultItemLabelsVisible(); /** * Sets the default flag that controls whether or not item labels are visible * and sends a {@link RendererChangeEvent} to all registered listeners. * * @param visible the flag. * * @see #getDefaultItemLabelsVisible() */ public void setDefaultItemLabelsVisible(boolean visible); /** * Sets the default visibility for item labels and, if requested, sends a * {@link RendererChangeEvent} to all registered listeners. * * @param visible the visibility flag. * @param notify a flag that controls whether or not listeners are * notified. * * @see #getDefaultItemLabelsVisible() */ public void setDefaultItemLabelsVisible(boolean visible, boolean notify); // ITEM LABEL GENERATOR /** * Returns the item label generator for the specified data item. * * @param series the series index (zero-based). * @param item the item index (zero-based). * * @return The generator (possibly {@code null}). */ public CategoryItemLabelGenerator getItemLabelGenerator(int series, int item); /** * Returns the item label generator for a series. * * @param series the series index (zero-based). * * @return The label generator (possibly {@code null}). * * @see #setSeriesItemLabelGenerator(int, CategoryItemLabelGenerator) */ public CategoryItemLabelGenerator getSeriesItemLabelGenerator(int series); /** * Sets the item label generator for a series and sends a * {@link RendererChangeEvent} to all registered listeners. * * @param series the series index (zero-based). * @param generator the generator. * * @see #getSeriesItemLabelGenerator(int) */ public void setSeriesItemLabelGenerator(int series, CategoryItemLabelGenerator generator); public void setSeriesItemLabelGenerator(int series, CategoryItemLabelGenerator generator, boolean notify); /** * Returns the default item label generator. * * @return The generator (possibly {@code null}). * * @see #setDefaultItemLabelGenerator(CategoryItemLabelGenerator) */ public CategoryItemLabelGenerator getDefaultItemLabelGenerator(); /** * Sets the default item label generator and sends a * {@link RendererChangeEvent} to all registered listeners. * * @param generator the generator ({@code null} permitted). * * @see #getDefaultItemLabelGenerator() */ public void setDefaultItemLabelGenerator(CategoryItemLabelGenerator generator); public void setDefaultItemLabelGenerator(CategoryItemLabelGenerator generator, boolean notify); // TOOL TIP GENERATOR /** * Returns the tool tip generator that should be used for the specified * item. This method looks up the generator using the "three-layer" * approach outlined in the general description of this interface. * * @param row the row index (zero-based). * @param column the column index (zero-based). * * @return The generator (possibly {@code null}). */ public CategoryToolTipGenerator getToolTipGenerator(int row, int column); /** * Returns the tool tip generator for the specified series (a "layer 1" * generator). * * @param series the series index (zero-based). * * @return The tool tip generator (possibly {@code null}). * * @see #setSeriesToolTipGenerator(int, CategoryToolTipGenerator) */ public CategoryToolTipGenerator getSeriesToolTipGenerator(int series); /** * Sets the tool tip generator for a series and sends a * {@link org.jfree.chart.event.RendererChangeEvent} to all registered * listeners. * * @param series the series index (zero-based). * @param generator the generator ({@code null} permitted). * * @see #getSeriesToolTipGenerator(int) */ public void setSeriesToolTipGenerator(int series, CategoryToolTipGenerator generator); public void setSeriesToolTipGenerator(int series, CategoryToolTipGenerator generator, boolean notify); /** * Returns the default tool tip generator (the "layer 2" generator). * * @return The tool tip generator (possibly {@code null}). * * @see #setDefaultToolTipGenerator(CategoryToolTipGenerator) */ public CategoryToolTipGenerator getDefaultToolTipGenerator(); /** * Sets the default tool tip generator and sends a * {@link org.jfree.chart.event.RendererChangeEvent} to all registered * listeners. * * @param generator the generator ({@code null} permitted). * * @see #getDefaultToolTipGenerator() */ public void setDefaultToolTipGenerator(CategoryToolTipGenerator generator); public void setDefaultToolTipGenerator(CategoryToolTipGenerator generator, boolean notify); //// ITEM LABEL FONT ////////////////////////////////////////////////////// /** * Returns the font for an item label. * * @param row the row index (zero-based). * @param column the column index (zero-based). * * @return The font (never {@code null}). */ public Font getItemLabelFont(int row, int column); /** * Returns the font for all the item labels in a series. * * @param series the series index (zero-based). * * @return The font (possibly {@code null}). * * @see #setSeriesItemLabelFont(int, Font) */ public Font getSeriesItemLabelFont(int series); /** * Sets the item label font for a series and sends a * {@link RendererChangeEvent} to all registered listeners. * * @param series the series index (zero-based). * @param font the font ({@code null} permitted). * * @see #getSeriesItemLabelFont(int) */ public void setSeriesItemLabelFont(int series, Font font); public void setSeriesItemLabelFont(int series, Font font, boolean notify); /** * Returns the default item label font (this is used when no other font * setting is available). * * @return The font (never {@code null}). * * @see #setDefaultItemLabelFont(Font) */ public Font getDefaultItemLabelFont(); /** * Sets the default item label font and sends a {@link RendererChangeEvent} * to all registered listeners. * * @param font the font ({@code null} not permitted). * * @see #getDefaultItemLabelFont() */ public void setDefaultItemLabelFont(Font font); public void setDefaultItemLabelFont(Font font, boolean notify); //// ITEM LABEL PAINT ///////////////////////////////////////////////////// /** * Returns the paint used to draw an item label. * * @param row the row index (zero based). * @param column the column index (zero based). * * @return The paint (never {@code null}). */ public Paint getItemLabelPaint(int row, int column); /** * Returns the paint used to draw the item labels for a series. * * @param series the series index (zero based). * * @return The paint (possibly {@code null}). * * @see #setSeriesItemLabelPaint(int, Paint) */ public Paint getSeriesItemLabelPaint(int series); /** * Sets the item label paint for a series and sends a * {@link RendererChangeEvent} to all registered listeners. * * @param series the series (zero based index). * @param paint the paint ({@code null} permitted). * * @see #getSeriesItemLabelPaint(int) */ public void setSeriesItemLabelPaint(int series, Paint paint); public void setSeriesItemLabelPaint(int series, Paint paint, boolean notify); /** * Returns the default item label paint. * * @return The paint (never {@code null}). * * @see #setDefaultItemLabelPaint(Paint) */ public Paint getDefaultItemLabelPaint(); /** * Sets the default item label paint and sends a {@link RendererChangeEvent} * to all registered listeners. * * @param paint the paint ({@code null} not permitted). * * @see #getDefaultItemLabelPaint() */ public void setDefaultItemLabelPaint(Paint paint); public void setDefaultItemLabelPaint(Paint paint, boolean notify); // POSITIVE ITEM LABEL POSITION... /** * Returns the item label position for positive values. * * @param row the row index (zero-based). * @param column the column index (zero-based). * * @return The item label position (never {@code null}). */ public ItemLabelPosition getPositiveItemLabelPosition(int row, int column); /** * Returns the item label position for all positive values in a series. * * @param series the series index (zero-based). * * @return The item label position. * * @see #setSeriesPositiveItemLabelPosition(int, ItemLabelPosition) */ public ItemLabelPosition getSeriesPositiveItemLabelPosition(int series); /** * Sets the item label position for all positive values in a series and * sends a {@link RendererChangeEvent} to all registered listeners. * * @param series the series index (zero-based). * @param position the position ({@code null} permitted). * * @see #getSeriesPositiveItemLabelPosition(int) */ public void setSeriesPositiveItemLabelPosition(int series, ItemLabelPosition position); /** * Sets the item label position for all positive values in a series and (if * requested) sends a {@link RendererChangeEvent} to all registered * listeners. * * @param series the series index (zero-based). * @param position the position ({@code null} permitted). * @param notify notify registered listeners? * * @see #getSeriesPositiveItemLabelPosition(int) */ public void setSeriesPositiveItemLabelPosition(int series, ItemLabelPosition position, boolean notify); /** * Returns the default positive item label position. * * @return The position. * * @see #setDefaultPositiveItemLabelPosition(ItemLabelPosition) */ public ItemLabelPosition getDefaultPositiveItemLabelPosition(); /** * Sets the default positive item label position. * * @param position the position. * * @see #getDefaultPositiveItemLabelPosition() */ public void setDefaultPositiveItemLabelPosition(ItemLabelPosition position); /** * Sets the default positive item label position and, if requested, sends a * {@link RendererChangeEvent} to all registered listeners. * * @param position the position. * @param notify notify registered listeners? * * @see #getDefaultPositiveItemLabelPosition() */ public void setDefaultPositiveItemLabelPosition(ItemLabelPosition position, boolean notify); // NEGATIVE ITEM LABEL POSITION... /** * Returns the item label position for negative values. This method can be * overridden to provide customisation of the item label position for * individual data items. * * @param row the row index (zero-based). * @param column the column (zero-based). * * @return The item label position. */ public ItemLabelPosition getNegativeItemLabelPosition(int row, int column); /** * Returns the item label position for all negative values in a series. * * @param series the series index (zero-based). * * @return The item label position. * * @see #setSeriesNegativeItemLabelPosition(int, ItemLabelPosition) */ public ItemLabelPosition getSeriesNegativeItemLabelPosition(int series); /** * Sets the item label position for negative values in a series and sends a * {@link RendererChangeEvent} to all registered listeners. * * @param series the series index (zero-based). * @param position the position ({@code null} permitted). * * @see #getSeriesNegativeItemLabelPosition(int) */ public void setSeriesNegativeItemLabelPosition(int series, ItemLabelPosition position); /** * Sets the item label position for negative values in a series and (if * requested) sends a {@link RendererChangeEvent} to all registered * listeners. * * @param series the series index (zero-based). * @param position the position ({@code null} permitted). * @param notify notify registered listeners? * * @see #getSeriesNegativeItemLabelPosition(int) */ public void setSeriesNegativeItemLabelPosition(int series, ItemLabelPosition position, boolean notify); /** * Returns the default item label position for negative values. * * @return The position. * * @see #setDefaultNegativeItemLabelPosition(ItemLabelPosition) */ public ItemLabelPosition getDefaultNegativeItemLabelPosition(); /** * Sets the default item label position for negative values and sends a * {@link RendererChangeEvent} to all registered listeners. * * @param position the position. * * @see #getDefaultNegativeItemLabelPosition() */ public void setDefaultNegativeItemLabelPosition(ItemLabelPosition position); /** * Sets the default negative item label position and, if requested, sends a * {@link RendererChangeEvent} to all registered listeners. * * @param position the position. * @param notify notify registered listeners? * * @see #getDefaultNegativeItemLabelPosition() */ public void setDefaultNegativeItemLabelPosition(ItemLabelPosition position, boolean notify); // CREATE ENTITIES public boolean getItemCreateEntity(int series, int item); public Boolean getSeriesCreateEntities(int series); public void setSeriesCreateEntities(int series, Boolean create); public void setSeriesCreateEntities(int series, Boolean create, boolean notify); public boolean getDefaultCreateEntities(); public void setDefaultCreateEntities(boolean create); public void setDefaultCreateEntities(boolean create, boolean notify); // ITEM URL GENERATOR /** * Returns the URL generator for an item. * * @param series the series index (zero-based). * @param item the item index (zero-based). * * @return The item URL generator. */ public CategoryURLGenerator getItemURLGenerator(int series, int item); /** * Returns the item URL generator for a series. * * @param series the series index (zero-based). * * @return The URL generator. * * @see #setSeriesItemURLGenerator(int, CategoryURLGenerator) */ public CategoryURLGenerator getSeriesItemURLGenerator(int series); /** * Sets the item URL generator for a series. * * @param series the series index (zero-based). * @param generator the generator. * * @see #getSeriesItemURLGenerator(int) */ public void setSeriesItemURLGenerator(int series, CategoryURLGenerator generator); public void setSeriesItemURLGenerator(int series, CategoryURLGenerator generator, boolean notify); /** * Returns the default item URL generator. * * @return The item URL generator (possibly {@code null}). * * @see #setDefaultItemURLGenerator(CategoryURLGenerator) */ public CategoryURLGenerator getDefaultItemURLGenerator(); /** * Sets the default item URL generator and sends a {@link RendererChangeEvent} * to all registered listeners. * * @param generator the item URL generator ({@code null} permitted). * * @see #getDefaultItemURLGenerator() */ public void setDefaultItemURLGenerator(CategoryURLGenerator generator); public void setDefaultItemURLGenerator(CategoryURLGenerator generator, boolean notify); /** * Returns a legend item for a series. This method can return * {@code null}, in which case the series will have no entry in the * legend. * * @param datasetIndex the dataset index (zero-based). * @param series the series (zero-based index). * * @return The legend item (possibly {@code null}). */ public LegendItem getLegendItem(int datasetIndex, int series); /** * Draws a background for the data area. * * @param g2 the graphics device. * @param plot the plot. * @param dataArea the data area. */ public void drawBackground(Graphics2D g2, CategoryPlot plot, Rectangle2D dataArea); /** * Draws an outline for the data area. * * @param g2 the graphics device. * @param plot the plot. * @param dataArea the data area. */ public void drawOutline(Graphics2D g2, CategoryPlot plot, Rectangle2D dataArea); /** * Draws a single data item. * * @param g2 the graphics device. * @param state state information for one chart. * @param dataArea the data plot area. * @param plot the plot. * @param domainAxis the domain axis. * @param rangeAxis the range axis. * @param dataset the data. * @param row the row index (zero-based). * @param column the column index (zero-based). * @param pass the pass index. */ public void drawItem(Graphics2D g2, CategoryItemRendererState state, Rectangle2D dataArea, CategoryPlot plot, CategoryAxis domainAxis, ValueAxis rangeAxis, CategoryDataset dataset, int row, int column, int pass); /** * Draws a grid line against the domain axis. * * @param g2 the graphics device. * @param plot the plot. * @param dataArea the area for plotting data. * @param value the value. */ public void drawDomainGridline(Graphics2D g2, CategoryPlot plot, Rectangle2D dataArea, double value); /** * Draws a grid line against the range axis. * * @param g2 the graphics device. * @param plot the plot. * @param axis the value axis. * @param dataArea the area for plotting data. * @param value the value. * @param paint the paint ({@code null} not permitted). * @param stroke the line stroke ({@code null} not permitted). */ public void drawRangeLine(Graphics2D g2, CategoryPlot plot, ValueAxis axis, Rectangle2D dataArea, double value, Paint paint, Stroke stroke); /** * Draws a line (or some other marker) to indicate a particular category on * the domain axis. * * @param g2 the graphics device. * @param plot the plot. * @param axis the category axis. * @param marker the marker. * @param dataArea the area for plotting data. * * @see #drawRangeMarker(Graphics2D, CategoryPlot, ValueAxis, Marker, * Rectangle2D) */ public void drawDomainMarker(Graphics2D g2, CategoryPlot plot, CategoryAxis axis, CategoryMarker marker, Rectangle2D dataArea); /** * Draws a line (or some other marker) to indicate a particular value on * the range axis. * * @param g2 the graphics device. * @param plot the plot. * @param axis the value axis. * @param marker the marker. * @param dataArea the area for plotting data. * * @see #drawDomainMarker(Graphics2D, CategoryPlot, CategoryAxis, * CategoryMarker, Rectangle2D) */ public void drawRangeMarker(Graphics2D g2, CategoryPlot plot, ValueAxis axis, Marker marker, Rectangle2D dataArea); /** * Returns the Java2D coordinate for the middle of the specified data item. * * @param rowKey the row key. * @param columnKey the column key. * @param dataset the dataset. * @param axis the axis. * @param area the data area. * @param edge the edge along which the axis lies. * * @return The Java2D coordinate for the middle of the item. * * @since 1.0.11 */ public double getItemMiddle(Comparable rowKey, Comparable columnKey, CategoryDataset dataset, CategoryAxis axis, Rectangle2D area, RectangleEdge edge); }
package cz.habarta.typescript.generator.parser; import cz.habarta.typescript.generator.JaxrsApplicationScanner; import cz.habarta.typescript.generator.Settings; import cz.habarta.typescript.generator.util.Parameter; import cz.habarta.typescript.generator.util.Predicate; import cz.habarta.typescript.generator.util.Utils; import java.lang.annotation.Annotation; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.*; import javax.ws.rs.ApplicationPath; import javax.ws.rs.CookieParam; import javax.ws.rs.FormParam; import javax.ws.rs.HeaderParam; import javax.ws.rs.HttpMethod; import javax.ws.rs.MatrixParam; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.QueryParam; import javax.ws.rs.core.Application; import javax.ws.rs.core.Context; import javax.ws.rs.core.GenericEntity; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.core.Response; import javax.ws.rs.core.StreamingOutput; public class JaxrsApplicationParser { private final Settings settings; private final Predicate<String> isClassNameExcluded; private final Set<String> defaultExcludes; private final JaxrsApplicationModel model; public JaxrsApplicationParser(Settings settings) { this.settings = settings; this.isClassNameExcluded = settings.getExcludeFilter(); this.defaultExcludes = new LinkedHashSet<>(getDefaultExcludedClassNames()); this.model = new JaxrsApplicationModel(); } public JaxrsApplicationModel getModel() { return model; } public static class Result { public List<SourceType<Type>> discoveredTypes; public Result() { discoveredTypes = new ArrayList<>(); } public Result(List<SourceType<Type>> discoveredTypes) { this.discoveredTypes = discoveredTypes; } } public Result tryParse(SourceType<?> sourceType) { if (!(sourceType.type instanceof Class<?>)) { return null; } final Class<?> cls = (Class<?>) sourceType.type; // application if (Application.class.isAssignableFrom(cls)) { final ApplicationPath applicationPathAnnotation = cls.getAnnotation(ApplicationPath.class); if (applicationPathAnnotation != null) { model.setApplicationPath(applicationPathAnnotation.value()); } model.setApplicationName(cls.getSimpleName()); final List<SourceType<Type>> discoveredTypes = JaxrsApplicationScanner.scanJaxrsApplication(cls, isClassNameExcluded); return new Result(discoveredTypes); } // resource final Path path = cls.getAnnotation(Path.class); if (path != null) { System.out.println("Parsing JAX-RS resource: " + cls.getName()); final Result result = new Result(); parseResource(result, new ResourceContext(cls, path.value()), cls); return result; } return null; } private void parseResource(Result result, ResourceContext context, Class<?> resourceClass) { // subContext final Map<String, Type> pathParamTypes = new LinkedHashMap<>(); for (Field field : resourceClass.getDeclaredFields()) { final PathParam pathParamAnnotation = field.getAnnotation(PathParam.class); if (pathParamAnnotation != null) { pathParamTypes.put(pathParamAnnotation.value(), field.getType()); } } final ResourceContext subContext = context.subPathParamTypes(pathParamTypes); // parse resource methods final List<Method> methods = Arrays.asList(resourceClass.getMethods()); Collections.sort(methods, new Comparator<Method>() { @Override public int compare(Method o1, Method o2) { final int nameDiff = o1.getName().compareToIgnoreCase(o2.getName()); if (nameDiff != 0) { return nameDiff; } final int parameterTypesDiff = Arrays.asList(o1.getParameterTypes()).toString().compareTo(Arrays.asList(o2.getParameterTypes()).toString()); if (parameterTypesDiff != 0) { return parameterTypesDiff; } return 0; } }); for (Method method : methods) { parseResourceMethod(result, subContext, resourceClass, method); } } private void parseResourceMethod(Result result, ResourceContext context, Class<?> resourceClass, Method method) { final Path pathAnnotation = method.getAnnotation(Path.class); // subContext context = context.subPath(pathAnnotation); final Map<String, Type> pathParamTypes = new LinkedHashMap<>(); final List<Parameter> methodParameters = Parameter.ofMethod(method); for (Parameter parameter : methodParameters) { final PathParam pathParamAnnotation = parameter.getAnnotation(PathParam.class); if (pathParamAnnotation != null) { pathParamTypes.put(pathParamAnnotation.value(), parameter.getParameterizedType()); } } context = context.subPathParamTypes(pathParamTypes); // JAX-RS specification - 3.3 Resource Methods final HttpMethod httpMethod = getHttpMethod(method); if (httpMethod != null) { // swagger final SwaggerOperation swaggerOperation = settings.ignoreSwaggerAnnotations ? new SwaggerOperation() : Swagger.parseSwaggerAnnotations(method); if (swaggerOperation.possibleResponses != null) { for (SwaggerResponse response : swaggerOperation.possibleResponses) { if (response.responseType != null) { foundType(result, response.responseType, resourceClass, method.getName()); } } } if (swaggerOperation.hidden) { return; } // path parameters final List<MethodParameterModel> pathParams = new ArrayList<>(); final PathTemplate pathTemplate = PathTemplate.parse(context.path); for (PathTemplate.Part part : pathTemplate.getParts()) { if (part instanceof PathTemplate.Parameter) { final PathTemplate.Parameter parameter = (PathTemplate.Parameter) part; final Type type = context.pathParamTypes.get(parameter.getName()); pathParams.add(new MethodParameterModel(parameter.getName(), type != null ? type : String.class)); } } // query parameters final List<MethodParameterModel> queryParams = new ArrayList<>(); final List<Parameter> params = Parameter.ofMethod(method); for (Parameter param : params) { final QueryParam queryParamAnnotation = param.getAnnotation(QueryParam.class); if (queryParamAnnotation != null) { queryParams.add(new MethodParameterModel(queryParamAnnotation.value(), param.getParameterizedType())); } } // JAX-RS specification - 3.3.2.1 Entity Parameters final MethodParameterModel entityParameter = getEntityParameter(method); if (entityParameter != null) { foundType(result, entityParameter.getType(), resourceClass, method.getName()); } // JAX-RS specification - 3.3.3 Return Type final Class<?> returnType = method.getReturnType(); final Type genericReturnType = method.getGenericReturnType(); final Type modelReturnType; if (returnType == void.class) { modelReturnType = returnType; } else if (returnType == Response.class) { if (swaggerOperation.responseType != null) { modelReturnType = swaggerOperation.responseType; foundType(result, modelReturnType, resourceClass, method.getName()); } else { modelReturnType = Object.class; } } else if (genericReturnType instanceof ParameterizedType && returnType == GenericEntity.class) { final ParameterizedType parameterizedReturnType = (ParameterizedType) genericReturnType; modelReturnType = parameterizedReturnType.getActualTypeArguments()[0]; foundType(result, modelReturnType, resourceClass, method.getName()); } else { modelReturnType = genericReturnType; foundType(result, modelReturnType, resourceClass, method.getName()); } // comments final List<String> comments = Swagger.getOperationComments(swaggerOperation); // create method model.getMethods().add(new JaxrsMethodModel(resourceClass, method.getName(), modelReturnType, context.rootResource, httpMethod.value(), context.path, pathParams, queryParams, entityParameter, comments)); } // JAX-RS specification - 3.4.1 Sub Resources if (pathAnnotation != null && httpMethod == null) { parseResource(result, context, method.getReturnType()); } } private void foundType(Result result, Type type, Class<?> usedInClass, String usedInMember) { if (!isExcluded(type)) { result.discoveredTypes.add(new SourceType<>(type, usedInClass, usedInMember)); } } private boolean isExcluded(Type type) { final Class<?> cls = Utils.getRawClassOrNull(type); if (cls == null) { return false; } if (isClassNameExcluded != null && isClassNameExcluded.test(cls.getName())) { return true; } if (defaultExcludes.contains(cls.getName())) { return true; } for (Class<?> standardEntityClass : getStandardEntityClasses()) { if (standardEntityClass.isAssignableFrom(cls)) { return true; } } return false; } private static HttpMethod getHttpMethod(Method method) { for (Annotation annotation : method.getAnnotations()) { final HttpMethod httpMethodAnnotation = annotation.annotationType().getAnnotation(HttpMethod.class); if (httpMethodAnnotation != null) { return httpMethodAnnotation; } } return null; } private static MethodParameterModel getEntityParameter(Method method) { final List<Parameter> parameters = Parameter.ofMethod(method); for (Parameter parameter : parameters) { if (!hasAnyAnnotation(parameter, Arrays.asList( MatrixParam.class, QueryParam.class, PathParam.class, CookieParam.class, HeaderParam.class, Context.class, FormParam.class ))) { return new MethodParameterModel(parameter.getName(), parameter.getParameterizedType()); } } return null; } private static boolean hasAnyAnnotation(Parameter parameter, List<Class<? extends Annotation>> annotationClasses) { for (Class<? extends Annotation> annotationClass : annotationClasses) { for (Annotation parameterAnnotation : parameter.getAnnotations()) { if (annotationClass.isInstance(parameterAnnotation)) { return true; } } } return false; } public static List<Class<?>> getStandardEntityClasses() { // JAX-RS specification - 4.2.4 Standard Entity Providers return Arrays.asList( byte[].class, java.lang.String.class, java.io.InputStream.class, java.io.Reader.class, java.io.File.class, javax.activation.DataSource.class, javax.xml.transform.Source.class, javax.xml.bind.JAXBElement.class, MultivaluedMap.class, StreamingOutput.class, java.lang.Boolean.class, java.lang.Character.class, java.lang.Number.class, long.class, int.class, short.class, byte.class, double.class, float.class, boolean.class, char.class); } private static List<String> getDefaultExcludedClassNames() { return Arrays.asList( "org.glassfish.jersey.media.multipart.FormDataBodyPart" ); } private static class ResourceContext { public final Class<?> rootResource; public final String path; public final Map<String, Type> pathParamTypes; public ResourceContext(Class<?> rootResource, String path) { this(rootResource, path, new LinkedHashMap<String, Type>()); } private ResourceContext(Class<?> rootResource, String path, Map<String, Type> pathParamTypes) { this.rootResource = rootResource; this.path = path; this.pathParamTypes = pathParamTypes; } ResourceContext subPath(Path pathAnnotation) { final String subPath = pathAnnotation != null ? pathAnnotation.value() : null; return new ResourceContext(rootResource, Utils.joinPath(path, subPath), pathParamTypes); } ResourceContext subPathParamTypes(Map<String, Type> subPathParamTypes) { final Map<String, Type> newPathParamTypes = new LinkedHashMap<>(); newPathParamTypes.putAll(pathParamTypes); if (subPathParamTypes != null) { newPathParamTypes.putAll(subPathParamTypes); } return new ResourceContext(rootResource, path, newPathParamTypes); } } }
package io.vertx.ext.web.api.contract.openapi3; import io.vertx.core.Handler; import io.vertx.core.http.HttpClientOptions; import io.vertx.core.http.HttpMethod; import io.vertx.core.http.HttpServerOptions; import io.vertx.ext.web.Router; import io.vertx.ext.web.RoutingContext; import io.vertx.ext.web.WebTestWithWebClientBase; import io.vertx.ext.web.api.contract.RouterFactoryException; import io.vertx.ext.web.api.validation.ValidationException; import org.junit.Test; import java.util.concurrent.CountDownLatch; /** * @author Francesco Guardiani @slinkydeveloper */ public class OpenAPI3RouterFactoryTest extends WebTestWithWebClientBase { public Handler<RoutingContext> generateFailureHandler(boolean expected) { return routingContext -> { Throwable failure = routingContext.failure(); if (failure instanceof ValidationException) { if (!expected) { failure.printStackTrace(); } routingContext.response().setStatusCode(400).setStatusMessage("failure:" + ((ValidationException) failure) .type().name()).end(); } else { failure.printStackTrace(); routingContext.response().setStatusCode(500).setStatusMessage("unknownfailure:" + failure.toString()).end(); } }; } private void startServer(Router router) throws Exception { server = vertx.createHttpServer(new HttpServerOptions().setPort(8080).setHost("localhost")); CountDownLatch latch = new CountDownLatch(1); server.requestHandler(router::accept).listen(onSuccess(res -> { latch.countDown(); })); awaitLatch(latch); } private void stopServer() throws Exception { if (server != null) { CountDownLatch latch = new CountDownLatch(1); server.close((asyncResult) -> { assertTrue(asyncResult.succeeded()); latch.countDown(); }); awaitLatch(latch); } } @Override public void setUp() throws Exception { super.setUp(); stopServer(); // Have to stop default server of WebTestBase client = vertx.createHttpClient(new HttpClientOptions().setDefaultPort(8080)); } @Override public void tearDown() throws Exception { if (client != null) { try { client.close(); } catch (IllegalStateException e) { } } super.tearDown(); } @Test public void loadPetStoreAndTestSomething() throws Exception { CountDownLatch latch = new CountDownLatch(1); final Router[] router = {null}; OpenAPI3RouterFactory.createRouterFactoryFromFile(this.vertx, "src/test/resources/swaggers/testSpec.yaml", openAPI3RouterFactoryAsyncResult -> { assertTrue(openAPI3RouterFactoryAsyncResult.succeeded()); OpenAPI3RouterFactory routerFactory = openAPI3RouterFactoryAsyncResult.result(); routerFactory.mountOperationsWithoutHandlers(true); routerFactory.addHandlerByOperationId("listPets", routingContext -> { routingContext.response().setStatusMessage("path mounted!").end(); }); routerFactory.addFailureHandlerByOperationId("listPets", generateFailureHandler(false)); routerFactory.addHandler(HttpMethod.POST, "/pets", routingContext -> { routingContext.response().setStatusMessage("path mounted!").end(); }); routerFactory.addFailureHandler(HttpMethod.POST, "/pets", generateFailureHandler(false)); //Test if router generation throw error if no handler is set for security validation boolean throwed = false; try { router[0] = routerFactory.getRouter(); } catch (RouterFactoryException e) { throwed = true; } assertTrue("RouterFactoryException not thrown", throwed); // Add security handler routerFactory.addSecurityHandler("api_key", routingContext -> routingContext.next()); router[0] = routerFactory.getRouter(); latch.countDown(); }); awaitLatch(latch); router[0].route().failureHandler((routingContext -> { if (routingContext.statusCode() == 501) routingContext.response().setStatusCode(501).setStatusMessage("not implemented").end(); })); startServer(router[0]); testRequest(HttpMethod.GET, "/pets", 200, "path mounted!"); testRequest(HttpMethod.POST, "/pets", 200, "path mounted!"); testRequest(HttpMethod.GET, "/pets/3", 501, "Not Implemented"); stopServer(); } @Test public void loadSpecFromURL() throws Exception { CountDownLatch latch = new CountDownLatch(1); OpenAPI3RouterFactory.createRouterFactoryFromURL(this.vertx, "https://raw.githubusercontent.com/OAI/OpenAPI-Specification/master/examples/v3.0/petstore.yaml", openAPI3RouterFactoryAsyncResult -> { assertFalse(openAPI3RouterFactoryAsyncResult.failed()); latch.countDown(); }); awaitLatch(latch); } }
package org.archive.wayback.archivalurl; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.net.URL; import java.util.Properties; import javax.servlet.ServletException; import junit.framework.TestCase; import org.archive.wayback.core.WaybackRequest; import org.archive.wayback.replay.JSPExecutor; import org.archive.wayback.replay.html.ReplayParseContext; import org.archive.wayback.replay.html.StringTransformer; import org.archive.wayback.util.htmllex.ContextAwareLexer; import org.htmlparser.Node; import org.htmlparser.Tag; import org.htmlparser.lexer.Lexer; import org.htmlparser.lexer.Page; /** * test {@link FastArchivalUrlReplayParseEventHandler}. * also covers {@link StandardAttributeRewriter}. * */ public class FastArchivalUrlReplayParseEventHandlerTest extends TestCase { FastArchivalUrlReplayParseEventHandler delegator; JSPExecutor jspExec = null; @Override protected void setUp() throws Exception { delegator = new FastArchivalUrlReplayParseEventHandler(); delegator.setEndJsp(null); delegator.setJspInsertPath(null); delegator.init(); } public void testAnchorHrefAbsolute() throws Exception { final String input = "<html>" + "<a href=\"/foo.html\">foo</a>" + "</html>"; final String expected = "<html>" + "<a href=\"http: "foo</a></html>"; assertEquals(expected, doEndToEnd(input)); } public void testAnchorHrefRelative() throws Exception { final String input = "<html>" + "<a href=\"foo.html\">foo</a>" + "</html>"; final String expected = "<html>" + "<a href=\"http: "</html>"; assertEquals(expected, doEndToEnd(input)); } public void testAnchorHrefAbsoluteInJavascript() throws Exception { final String input = "<html>" + "<a href=\"javascript:doWin('http: "</html>"; final String expected = "<html>" + "<a href=\"javascript:doWin('http: "</html>"; assertEquals(expected, doEndToEnd(input)); } public void testStyleElementBackgroundUrl() throws Exception { final String input = "<html>" + "<head>" + "<style type=\"text/css\">" + "#head{" + "background:transparent url(/images/logo.jpg);" + "}" + "</style>" + "</head>" + "</html>"; final String expected = "<html>" + "<head>" + "<style type=\"text/css\">" + "#head{" + "background:transparent url(http: "}" + "</style>" + "</head>" + "</html>"; assertEquals(expected, doEndToEnd(input)); } /** * HTML entities in &lt;STYLE> element are not unescaped. * (although this is an unlikely scenario) * @throws Exception */ public void testStyleElementBackgroundUrlNoUnescape() throws Exception { final String input = "<html>" + "<head>" + "<style type=\"text/css\">" + "#head{" + "background-image:url(/genbg?a=2&amp;b=1);" + "}" + "</style>" + "</head>" + "</html>"; final String expected = "<html>" + "<head>" + "<style type=\"text/css\">" + "#head{" + "background-image:url(http://replay.archive.org/2001im_" + "/http: "}" + "</style>" + "</head>" + "</html>"; assertEquals(expected, doEndToEnd(input)); } public void testStyleElementImportUrl() throws Exception { final String input = "<html>" + "<head>" + "<style type=\"text/css\">" + "@import \"style1.css\";\n" + "@import \'style2.css\';\n" + "@import 'http://archive.org/common.css';\n" + "}" + "</style>" + "</head>" + "</html>"; final String expected = "<html>" + "<head>" + "<style type=\"text/css\">" + "@import \"http: "@import 'http: "@import 'http: "}" + "</style>" + "</head>" + "</html>"; assertEquals(expected, doEndToEnd(input)); } public void testStyleElementFontfaceSrcUrl() throws Exception { // font data is not an image technically, but it'd require more elaborate // pattern match to differentiate a context of url function. use im_ for // font data for now. final String input = "<html>" + "<head>" + "<style type=\"text/css\">" + "@font-face {" + "font-family: 'TestFont" + "src: local('TestFont')" + "src: url(/fonts/TestFont.otf)" + "}" + "</style>" + "</head>" + "</html>"; final String expected = "<html>" + "<head>" + "<style type=\"text/css\">" + "@font-face {" + "font-family: 'TestFont" + "src: local('TestFont')" + "src: url(http: "}" + "</style>" + "</head>" + "</html>"; assertEquals(expected, doEndToEnd(input)); } public void testHTMLEntityInURL() throws Exception { // note "&amp;amp" - it should appear in translated URL as it does in the original. final String input = "<html>" + "<body>" + "<iframe src=\"https://example.com/player/?url=https%3A//api.example.com/" + "tracks/135768597%3Ftoken%3Dsss&amp;amp;auto_play=false&bare=1\"></iframe>" + "</body>" + "</html>"; final String expected = "<html>" + "<body>" + "<iframe src=\"http: + "tracks/135768597%3Ftoken%3Dsss&amp;amp;auto_play=false&amp;bare=1\"></iframe>" + "</body>" + "</html>"; assertEquals(expected, doEndToEnd(input)); } /** * test of {@code unescapeAttributeValue } == {@code false} case. * bare "{@code &}" is unchanged. * @throws Exception */ public void testUnescapeAttributeValuesFalse() throws Exception { // disable unescaping HTML entities in attribute value. ((StandardAttributeRewriter)delegator.getAttributeRewriter()).setUnescapeAttributeValues(false); // note "&amp;amp" - it should appear in translated URL as it does in the original. final String input = "<html>" + "<body>" + "<iframe src=\"https://example.com/player/?url=https%3A//api.example.com/" + "tracks/135768597%3Ftoken%3Dsss&amp;amp;auto_play=false&intact=1\"></iframe>" + "</body>" + "</html>"; final String expected = "<html>" + "<body>" + "<iframe src=\"http: + "tracks/135768597%3Ftoken%3Dsss&amp;amp;auto_play=false&intact=1\"></iframe>" + "</body>" + "</html>"; assertEquals(expected, doEndToEnd(input)); } public void testLinkElement() throws Exception { final String input = "<html>" + "<head>" + " <link rel=\"stylesheet\" href=\"basic.css?v=1.0&amp;l=en\">" + " <link rel=\"shortcut icon\" href=\"icon.png?v=1.0&amp;rg=en\">" + "</head>" + "<body>" + "</body>"; final String expected = "<html>" + "<head>" + " <link rel=\"stylesheet\" href=\"http: " <link rel=\"shortcut icon\" href=\"http: "</head>" + "<body>" + "</body>"; assertEquals(expected, doEndToEnd(input)); } public void testStyleAttribute() throws Exception { final String input = "<html>" + "<body>" + "<div style=\"background-image:url(genbg?a=1&amp;b=2);\">" + "blah" + "</div>" + "</body>" + "</html>"; final String expected = "<html>" + "<body>" + "<div style=\"background-image:url(http: "blah" + "</div>" + "</body>" + "</html>"; assertEquals(expected, doEndToEnd(input)); } /** * test of rewriting SCRIPT tag. * Also covered is a feature for disabling script by returning {@code null} from * {@code jsBlockTrans} (This feature may be removed/redesigned at any time). * @throws Exception */ public void testDisableScriptElement() throws Exception { delegator.setJsBlockTrans(new StringTransformer() { @Override public String transform(ReplayParseContext context, String input) { if (input.equals("dropthis.js")) return null; else return input; } }); final String input = "<html>" + "<head>" + "<script src=\"rewrite.js\"></script>" + "<script src=\"dropthis.js\"></script>" + "</head>" + "<body>" + "</body>" + "</html>"; final String expected = "<html>" + "<head>" + "<script src=\"http: "<script src=\"\"></script>" + "</head>" + "<body>" + "</body>" + "</html>"; assertEquals(expected, doEndToEnd(input)); } /** * URL rewrite takes {@code BASE} element into account. * @throws Exception */ public void testBase() throws Exception { final String input = "<html>" + "<base href='http://othersite.com/'>" + "<body>" + "<a href='nextpage.html'>next page</a>" + "<base href='http://anothersite.com/'>" + "</body>" + "</html>"; final String expected = "<html>" + "<base href='http: "<body>" + "<a href='http: "<base href='http: "</body>" + "</html>"; assertEquals(expected, doEndToEnd(input)); } /** * test of additional attribute rewrite rules for {@link StandardAttributeRewriter}. * additional rules takes precedence over default one, if they are of the same specificity. * @throws Exception */ public void testAdditionalAttributeRewriteRules() throws Exception { // adding custom rewrite rules through backdoor... Properties rules = new Properties(); rules.setProperty("SPAN.DATA-URI.type", "an"); rules.setProperty("A[ROLE=logo.download].HREF.type", "im"); rules.setProperty("LINK[TYPE=text/javascript].HREF.type", "js"); ((StandardAttributeRewriter)delegator.getAttributeRewriter()).loadRulesFromProperties(rules); final String input = "<html>" + "<head>" + "<link rel='stylesheet' type='text/javascript' href='styles.js'>" + "</head>" + "<body>" + "<span data-uri='http://datasource.example.com/data1'></span>" + "<a href='logo.png' role='logo.download'>download logo</a>" + "</body>" + "</html>"; final String expected = "<html>" + "<head>" + "<link rel='stylesheet' type='text/javascript' href='http: "</head>" + "<body>" + "<span data-uri='http: "<a href='http: "</body>" + "</html>"; assertEquals(expected, doEndToEnd(input)); } /** * test of {@link StandardAttributeRewriter#setDefaultRulesDisabled(boolean)} * @throws Exception */ public void testDisableDefaultRules() throws Exception { // use local instance for modifying defaultRulesDisabled property. StandardAttributeRewriter rewriter = new StandardAttributeRewriter(); rewriter.setDefaultRulesDisabled(true); Properties rules = new Properties(); rules.setProperty("A[REWRITE=TRUE].HREF.type", "an"); rewriter.setConfigProperties(rules); rewriter.init(); delegator.setAttributeRewriter(rewriter); final String input ="<html>" + "<body>" + "<a href=\"ignore.html\">ignore this</a>" + "<a href=\"rewrite.html\" rewrite=\"true\">rewrite this</a>" + "</body>" + "</html>"; final String expected ="<html>" + "<body>" + "<a href=\"ignore.html\">ignore this</a>" + "<a href=\"http: "</body>" + "</html>"; assertEquals(expected, doEndToEnd(input)); } /** * JSPExecutor patched to return predictable text without * actually running JSP. */ protected static class TestJSPExecutor extends JSPExecutor { public TestJSPExecutor() { // we cannot pass null WaybackRequest to JSPExecutor constructor, // because it accesses WaybackRequst.isAjaxRequest() method. super(null, null, null, stubWaybackRequest(), null, null, null); } @Override public String jspToString(String jspPath) throws ServletException, IOException { return "[[[JSP-INSERT:" + jspPath + "]]]"; } private static WaybackRequest stubWaybackRequest() { WaybackRequest wbRequest = new WaybackRequest(); // make sure ajaxRequest is false (true disables JSP inserts) // it's false by default currently, but just in case (paranoia). wbRequest.setAjaxRequest(false); return wbRequest; } } /** * Servers often return non-HTML resource with {@code Content-Type: text/html}. * Inserting HTML annotation to non-HTML resource can break its replay. * Therefore, don't insert {@code EndJsp} if resource does not appear to be * HTML. * @throws Exception */ public void testNoEndJspForNonHTML() throws Exception { delegator.setEndJsp("end.jsp"); jspExec = new TestJSPExecutor(); final String input = "{\"a\": 1}"; final String expected = "{\"a\": 1}"; String output = doEndToEnd(input); System.out.println(output); assertEquals(expected, output); } /** * JSP inserts: well formed case. * @throws Exception */ public void testInserts() throws Exception { delegator.setHeadInsertJsp("head.jsp"); delegator.setJspInsertPath("body-insert.jsp"); jspExec = new TestJSPExecutor(); final String input = "<html>" + "<head>" + "<title>BarBar</title>" + "<script src=\"a.js\"></script>" + "<link rel=\"stylesheet\" type=\"text/css\" href=\"style.css\">" + "</head>" + "<body>" + "<p align=\"center\">" + "<img src=\"map.gif\">" + "</p>" + "</body>" + "</html>"; final String expected = "<html>" + "<head>" + "[[[JSP-INSERT:head.jsp]]]" + "<title>BarBar</title>" + "<script src=\"http: "<link rel=\"stylesheet\" type=\"text/css\" href=\"http: "</head>" + "<body>" + "[[[JSP-INSERT:body-insert.jsp]]]" + "<p align=\"center\">" + "<img src=\"http: "</p>" + "</body>" + "</html>"; String output = doEndToEnd(input); System.out.println(output); assertEquals(expected, output); } /** * Pathological case: * Missing HEAD tag. head-insert shall be inserted just before * the first open tag (excluding !DOCTYPE and HTML). * @throws Exception */ public void testMissingHeadTag() throws Exception { delegator.setHeadInsertJsp("head.jsp"); delegator.setJspInsertPath("body.jsp"); jspExec = new TestJSPExecutor(); final String input = "<html>" + "<title>BarBar</title>" + "<body>" + "Content" + "</body>" + "</html>"; final String expected = "<html>" + "[[[JSP-INSERT:head.jsp]]]" + "<title>BarBar</title>" + "<body>" + "[[[JSP-INSERT:body.jsp]]]" + "Content" + "</body>" + "</html>"; String output = doEndToEnd(input); assertEquals(expected, output); } public void testMissingBodyTag() throws Exception { delegator.setHeadInsertJsp("head.jsp"); delegator.setJspInsertPath("body-insert.jsp"); jspExec = new TestJSPExecutor(); final String input = "<html>" + "<head>" + "<title>BarBar</title>" + "<script src=\"a.js\"></script>" + "</head>" + "<p align=\"center\">" + "<img src=\"map.gif\">" + "</p>" + "</body>" + "</html>"; final String expected = "<html>" + "<head>" + "[[[JSP-INSERT:head.jsp]]]" + "<title>BarBar</title>" + "<script src=\"http: "</head>" + "[[[JSP-INSERT:body-insert.jsp]]]" + "<p align=\"center\">" + "<img src=\"http: "</p>" + "</body>" + "</html>"; String output = doEndToEnd(input); System.out.println(output); assertEquals(expected, output); } /** * Pathological case: * Content has {@code <HEAD>} but missing {@code </HEAD>} and {@code BODY}. * @throws Exception */ public void testMissingHeadCloseTag() throws Exception { delegator.setHeadInsertJsp("head.jsp"); delegator.setJspInsertPath("body-insert.jsp"); jspExec = new TestJSPExecutor(); final String input = "<html>" + "<head>" + "<title>BarBar</title>" + "<script src=\"a.js\"></script>" + "<body>" + "<p align=\"center\">" + "<img src=\"map.gif\">" + "</p>" + "</body>" + "</html>"; final String expected = "<html>" + "<head>" + "[[[JSP-INSERT:head.jsp]]]" + "<title>BarBar</title>" + "<script src=\"http: "</head>" + "<body>" + "[[[JSP-INSERT:body-insert.jsp]]]" + "<p align=\"center\">" + "<img src=\"http: "</p>" + "</body>" + "</html>"; String output = doEndToEnd(input); System.out.println(output); assertEquals(expected, output); } /** * Pathological case: * both HEAD and BODY tags are missing. There are some in-HEAD tags. * @throws Exception */ public void testMissingHeadAndBodyTag() throws Exception { delegator.setHeadInsertJsp("head.jsp"); delegator.setJspInsertPath("body-insert.jsp"); jspExec = new TestJSPExecutor(); final String input = "<title>BarBar</title>" + "<script src=\"a.js\"></script>" + "<p align=\"center\">" + "<img src=\"map.gif\">" + "</p>"; final String expected = "[[[JSP-INSERT:head.jsp]]]" + "<title>BarBar</title>" + "<script src=\"http: "[[[JSP-INSERT:body-insert.jsp]]]" + "<p align=\"center\">" + "<img src=\"http: "</p>"; String output = doEndToEnd(input); System.out.println(output); assertEquals(expected, output); } /** * Pathological case: * both HEAD and BODY tags are missing. There are some in-HEAD tags. * @throws Exception */ public void testMissingHeadAndBodyTagStartsWithContentTag() throws Exception { delegator.setHeadInsertJsp("head.jsp"); delegator.setJspInsertPath("body-insert.jsp"); jspExec = new TestJSPExecutor(); final String input = "<p align=\"center\">" + "<img src=\"map.gif\">" + "</p>"; final String expected = "[[[JSP-INSERT:head.jsp]]]" + "[[[JSP-INSERT:body-insert.jsp]]]" + "<p align=\"center\">" + "<img src=\"http: "</p>"; String output = doEndToEnd(input); System.out.println(output); assertEquals(expected, output); } /** * Pathological case: * Content-producing tag appearing before BODY tag. * body-insert is inserted before the tag, not after the BODY tag. * @throws Exception */ public void testNonHeadTagBeforeBodyTag() throws Exception { delegator.setHeadInsertJsp("head.jsp"); delegator.setJspInsertPath("body-insert.jsp"); jspExec = new TestJSPExecutor(); final String input = "<html>" + "<title>BarBar</title>" + "<script src=\"a.js\"></script>" + "<div>TEXT</div>" + "<body>" + "<p align=\"center\">" + "<img src=\"map.gif\">" + "</p>" + "</body>" + "</html>"; final String expected = "<html>" + "[[[JSP-INSERT:head.jsp]]]" + "<title>BarBar</title>" + "<script src=\"http: "[[[JSP-INSERT:body-insert.jsp]]]" + "<div>TEXT</div>" + "<body>" + "<p align=\"center\">" + "<img src=\"http: "</p>" + "</body>" + "</html>"; String output = doEndToEnd(input); System.out.println(output); assertEquals(expected, output); } /** * pathological case of two HEAD tags. * head-insert shall be inserted after the first HEAD tag. * @throws Exception */ public void testExtraHeadTag() throws Exception { delegator.setHeadInsertJsp("head.jsp"); jspExec = new TestJSPExecutor(); final String input = "<html>" + "<head>" + "<head>" + "<title>BarBar</title>" + "</head>" + "Content" + "</html>"; final String expected = "<html>" + "<head>" + "[[[JSP-INSERT:head.jsp]]]" + "<head>" + "<title>BarBar</title>" + "</head>" + "Content" + "</html>"; String output = doEndToEnd(input); assertEquals(expected, output); } public String doEndToEnd(String input) throws Exception { final String baseUrl = "http: final String timestamp = "2001"; final String outputCharset = "UTF-8"; final String charSet = "UTF-8"; ByteArrayInputStream bais = new ByteArrayInputStream(input.getBytes(charSet)); ArchivalUrlResultURIConverter uriConverter = new ArchivalUrlResultURIConverter(); uriConverter.setReplayURIPrefix("http://replay.archive.org/"); ArchivalUrlContextResultURIConverterFactory fact = new ArchivalUrlContextResultURIConverterFactory( (ArchivalUrlResultURIConverter) uriConverter); // The URL of the page, for resolving in-page relative URLs: URL url = new URL(baseUrl); // To make sure we get the length, we have to buffer it all up... ByteArrayOutputStream baos = new ByteArrayOutputStream(); // set up the context: ReplayParseContext context = new ReplayParseContext(fact, url, timestamp); context.setOutputCharset(outputCharset); context.setOutputStream(baos); // jspExec is null for attribute rewrite tests. context.setJspExec(jspExec); // and finally, parse, using the special lexer that knows how to // handle javascript blocks containing unescaped HTML entities: Page lexPage = new Page(bais,charSet); Lexer lexer = new Lexer(lexPage); Lexer.STRICT_REMARKS = false; ContextAwareLexer lex = new ContextAwareLexer(lexer, context); Node node; while ((node = lex.nextNode()) != null) { delegator.handleNode(context, node); } delegator.handleParseComplete(context); // At this point, baos contains the utf-8 encoded bytes of our result: return new String(baos.toByteArray(),outputCharset); } /** * test expected behavior of htmlparser. * <p>htmlparser does neither unescape HTML entities found in text, nor * escape special characters in Node.toHtml(). We have a workaround based on this * behavior. If this expectation breaks, we need to modify our code.</p> * @throws Exception */ public void testHtmlParser() throws Exception { final String html = "<html>" + "<body>" + "<a href=\"http://example.com/api?a=1&amp;b=2&c=3&#34;\">anchor</a>" + "</body>" + "</html>"; byte[] bytes = html.getBytes(); ByteArrayInputStream bais = new ByteArrayInputStream(bytes); Page page = new Page(bais, "UTF-8"); Lexer lexer = new Lexer(page); Node node; while ((node = lexer.nextNode()) != null) { if (node instanceof Tag) { Tag tag = (Tag)node; if (tag.getTagName().equalsIgnoreCase("A") && !tag.isEndTag()) { assertEquals("href", "http://example.com/api?a=1&amp;b=2&c=3&#34;", tag.getAttribute("HREF")); String htmlout = tag.toHtml(); assertEquals("toHtml output", "<a href=\"http://example.com/api?a=1&amp;b=2&c=3&#34;\">", htmlout); } } } } }
package za.org.grassroot.services.job; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; import java.text.SimpleDateFormat; import java.util.Date; import java.util.logging.Logger; @Component public class ScheduledTasks { private Logger log = Logger.getLogger(getClass().getCanonicalName()); private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss"); @Scheduled(fixedRate = 60000) public void reportCurrentTime() { //log.info("The time is now " + dateFormat.format(new Date())); } }
package water.bindings.proxies.retrofit; import water.bindings.pojos.*; import water.bindings.proxies.*; import com.google.gson.*; import retrofit2.*; import retrofit2.http.*; import retrofit2.converter.gson.GsonConverterFactory; import retrofit2.Call; import java.io.IOException; import java.lang.reflect.Type; import java.util.List; import java.util.ArrayList; public class GBM_Example { /** * Keys get sent as Strings and returned as objects also containing the type and URL, * so they need a custom GSON serializer. */ private static class KeySerializer implements JsonSerializer<KeyV3> { public JsonElement serialize(KeyV3 key, Type typeOfKey, JsonSerializationContext context) { return new JsonPrimitive(key.name); } } public static JobV3 poll(Retrofit retrofit, String job_id) { Jobs jobsService = retrofit.create(Jobs.class); Response<JobsV3> jobs_response = null; int retries = 3; JobsV3 jobs = null; do { try { jobs_response = jobsService.fetch(job_id).execute(); } catch (IOException e) { System.err.println("Caught exception: " + e); } if (! jobs_response.isSuccessful()) if (retries continue; else throw new RuntimeException("/3/Jobs/{job_id} failed 3 times."); jobs = jobs_response.body(); if (null == jobs.jobs || jobs.jobs.length != 1) throw new RuntimeException("Failed to find Job: " + job_id); if (! "RUNNING".equals(jobs.jobs[0].status)) try { Thread.sleep(100); } catch (InterruptedException e) {} // wait 100mS } while ("RUNNING".equals(jobs.jobs[0].status)); return jobs.jobs[0]; } public static void gbm_example_flow() { GsonBuilder builder = new GsonBuilder(); builder.registerTypeAdapter(KeyV3.class, new KeySerializer()); // builder.registerTypeAdapter(ColSpecifierV3.class, new ColSpecifierSerializer()); Gson gson = builder.create(); Retrofit retrofit = new Retrofit.Builder() .baseUrl("http://localhost:54321/") // note trailing slash for Retrofit 2 .addConverterFactory(GsonConverterFactory.create(gson)) .build(); ImportFiles importService = retrofit.create(ImportFiles.class); ParseSetup parseSetupService = retrofit.create(ParseSetup.class); Parse parseService = retrofit.create(Parse.class); Frames framesService = retrofit.create(Frames.class); Models modelsService = retrofit.create(Models.class); ModelBuilders modelBuildersService = retrofit.create(ModelBuilders.class); Predictions predictionsService = retrofit.create(Predictions.class); JobV3 job = null; try { // STEP 1: import raw file ImportFilesV3 importBody = importService.importFiles("http://s3.amazonaws.com/h2o-public-test-data/smalldata/flow_examples/arrhythmia.csv.gz", null).execute().body(); System.out.println("import: " + importBody); // STEP 2: parse setup ParseSetupV3 parseSetupBody = parseSetupService.guessSetup(importBody.destination_frames, ApiParseTypeValuesProvider.GUESS, (byte)',', false, -1, null, null, null, null, 0, 0, 0, null ).execute().body(); System.out.println("parseSetupBody: " + parseSetupBody); // STEP 3: parse into columnar Frame List<String> source_frames = new ArrayList<>(); for (FrameKeyV3 frame : parseSetupBody.source_frames) source_frames.add(frame.name); ParseV3 parseBody = parseService.parse("arrhythmia.hex", source_frames.toArray(new String[0]), parseSetupBody.parse_type, parseSetupBody.separator, parseSetupBody.single_quotes, parseSetupBody.check_header, parseSetupBody.number_columns, parseSetupBody.column_names, parseSetupBody.column_types, null, // domains parseSetupBody.na_strings, parseSetupBody.chunk_size, true, true, null).execute().body(); System.out.println("parseBody: " + parseBody); // STEP 5: Train the model (NOTE: step 4 is polling, which we don't require because we specified blocking for the parse above) GBMParametersV3 gbm_parms = new GBMParametersV3(); FrameKeyV3 training_frame = new FrameKeyV3(); training_frame.name = "arrhythmia.hex"; gbm_parms.training_frame = training_frame; ColSpecifierV3 response_column = new ColSpecifierV3(); response_column.column_name = "C1"; gbm_parms.response_column = response_column; System.out.println("About to train GBM. . ."); GBMV3 gbmBody = (GBMV3)ModelBuilders.Helper.train_gbm(modelBuildersService, gbm_parms).execute().body(); System.out.println("gbmBody: " + gbmBody); // STEP 6: poll for completion job = gbmBody.job; if (null == job || null == job.key) throw new RuntimeException("train_gbm returned a bad Job: " + job); job = poll(retrofit, job.key.name); System.out.println("GBM build done."); // STEP 7: fetch the model // TODO: Retrofit seems to be only deserializing the base class. What to do? KeyV3 model_key = job.dest; ModelsV3 models = modelsService.fetch(model_key.name).execute().body(); System.out.println("models: " + models); // GBMModelV3 model = (GBMModelV3)models.models[0]; // System.out.println("new GBM model: " + model); System.out.println("new GBM model: " + models.models[0]); // STEP 8: predict! ModelMetricsListSchemaV3 predictions = predictionsService.predict(model_key.name, training_frame.name, "predictions", false, false, -1, false, false, false, false, -1, null).execute().body(); System.out.println("predictions: " + predictions); } catch (IOException e) { System.err.println("Caught exception: " + e); } } public static void main (String[] args) { gbm_example_flow(); } }
package org.callistasoftware.netcare.core.spi.impl; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Collections; import java.util.Date; import java.util.List; import org.callistasoftware.netcare.core.api.ActivityComment; import org.callistasoftware.netcare.core.api.ActivityDefinition; import org.callistasoftware.netcare.core.api.ActivityReport; import org.callistasoftware.netcare.core.api.ApiUtil; import org.callistasoftware.netcare.core.api.CareGiverBaseView; import org.callistasoftware.netcare.core.api.CareUnit; import org.callistasoftware.netcare.core.api.DayTime; import org.callistasoftware.netcare.core.api.HealthPlan; import org.callistasoftware.netcare.core.api.MeasurementDefinition; import org.callistasoftware.netcare.core.api.Option; import org.callistasoftware.netcare.core.api.PatientBaseView; import org.callistasoftware.netcare.core.api.PatientEvent; import org.callistasoftware.netcare.core.api.ScheduledActivity; import org.callistasoftware.netcare.core.api.ServiceResult; import org.callistasoftware.netcare.core.api.UserBaseView; import org.callistasoftware.netcare.core.api.Value; import org.callistasoftware.netcare.core.api.impl.ActivityCommentImpl; import org.callistasoftware.netcare.core.api.impl.ActivityDefintionImpl; import org.callistasoftware.netcare.core.api.impl.HealthPlanImpl; import org.callistasoftware.netcare.core.api.impl.PatientEventImpl; import org.callistasoftware.netcare.core.api.impl.ScheduledActivityImpl; import org.callistasoftware.netcare.core.api.impl.ServiceResultImpl; import org.callistasoftware.netcare.core.api.messages.EntityDeletedMessage; import org.callistasoftware.netcare.core.api.messages.EntityNotFoundMessage; import org.callistasoftware.netcare.core.api.messages.GenericSuccessMessage; import org.callistasoftware.netcare.core.api.messages.ListEntitiesMessage; import org.callistasoftware.netcare.core.api.statistics.ActivityCount; import org.callistasoftware.netcare.core.api.statistics.HealthPlanStatistics; import org.callistasoftware.netcare.core.api.statistics.MeasuredValue; import org.callistasoftware.netcare.core.api.statistics.ReportedActivity; import org.callistasoftware.netcare.core.api.statistics.ReportedValue; import org.callistasoftware.netcare.core.api.util.DateUtil; import org.callistasoftware.netcare.core.repository.ActivityCommentRepository; import org.callistasoftware.netcare.core.repository.ActivityDefinitionRepository; import org.callistasoftware.netcare.core.repository.ActivityTypeRepository; import org.callistasoftware.netcare.core.repository.CareGiverRepository; import org.callistasoftware.netcare.core.repository.CareUnitRepository; import org.callistasoftware.netcare.core.repository.HealthPlanRepository; import org.callistasoftware.netcare.core.repository.PatientRepository; import org.callistasoftware.netcare.core.repository.ScheduledActivityRepository; import org.callistasoftware.netcare.core.spi.HealthPlanService; import org.callistasoftware.netcare.model.entity.ActivityCommentEntity; import org.callistasoftware.netcare.model.entity.ActivityDefinitionEntity; import org.callistasoftware.netcare.model.entity.ActivityTypeEntity; import org.callistasoftware.netcare.model.entity.CareGiverEntity; import org.callistasoftware.netcare.model.entity.CareUnitEntity; import org.callistasoftware.netcare.model.entity.DurationUnit; import org.callistasoftware.netcare.model.entity.EntityUtil; import org.callistasoftware.netcare.model.entity.Frequency; import org.callistasoftware.netcare.model.entity.FrequencyDay; import org.callistasoftware.netcare.model.entity.FrequencyTime; import org.callistasoftware.netcare.model.entity.HealthPlanEntity; import org.callistasoftware.netcare.model.entity.MeasurementDefinitionEntity; import org.callistasoftware.netcare.model.entity.MeasurementEntity; import org.callistasoftware.netcare.model.entity.MeasurementTypeEntity; import org.callistasoftware.netcare.model.entity.MeasurementValueType; import org.callistasoftware.netcare.model.entity.PatientEntity; import org.callistasoftware.netcare.model.entity.ScheduledActivityEntity; import org.callistasoftware.netcare.model.entity.ScheduledActivityStatus; import org.callistasoftware.netcare.model.entity.UserEntity; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.i18n.LocaleContextHolder; import org.springframework.data.domain.Sort; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; /** * Implementation of service defintion * * @author Marcus Krantz [marcus.krantz@callistaenterprise.se] * */ @Service @Transactional public class HealthPlanServiceImpl extends ServiceSupport implements HealthPlanService { /** * Days back when fetching patient plan (schema). */ public static int SCHEMA_HISTORY_DAYS = 7; /** * Days forward when fetching patient plan (schema). */ public static int SCHEMA_FUTURE_DAYS = (2*SCHEMA_HISTORY_DAYS); /** * Always get full weeks when fetching patient plan (schema), and weeks starts on Mondays. */ public static int SCHEMA_DAY_ALIGN = Calendar.MONDAY; /** * CSV End of Line */ public static String CSV_EOL = "\r\n"; @org.springframework.beans.factory.annotation.Value("#{application['csv.delimiter']}") private String CSV_SEP; private static final Logger log = LoggerFactory.getLogger(HealthPlanServiceImpl.class); @Autowired private HealthPlanRepository repo; @Autowired private ActivityTypeRepository activityTypeRepository; @Autowired private CareGiverRepository careGiverRepository; @Autowired private CareUnitRepository careUnitRepository; @Autowired private PatientRepository patientRepository; @Autowired private ActivityDefinitionRepository activityDefintionRepository; @Autowired private ScheduledActivityRepository scheduledActivityRepository; @Autowired private ActivityCommentRepository commentRepository; @Override public ServiceResult<HealthPlan[]> loadHealthPlansForPatient(Long patientId) { final PatientEntity forPatient = patientRepository.findOne(patientId); final List<HealthPlanEntity> entities = this.repo.findByForPatient(forPatient); final HealthPlan[] dtos = new HealthPlan[entities.size()]; int count = 0; for (final HealthPlanEntity ent : entities) { final HealthPlanImpl dto = HealthPlanImpl.newFromEntity(ent, LocaleContextHolder.getLocale()); dtos[count++] = dto; } return ServiceResultImpl.createSuccessResult(dtos, new ListEntitiesMessage(HealthPlanEntity.class, dtos.length)); } public ServiceResult<ScheduledActivity[]> getActivitiesForPatient(PatientBaseView patient) { Calendar c = Calendar.getInstance(); c.setFirstDayOfWeek(1); c.add(Calendar.DATE, -(SCHEMA_HISTORY_DAYS)); c.set(Calendar.DAY_OF_WEEK, SCHEMA_DAY_ALIGN); Date startDate = ApiUtil.dayBegin(c).getTime(); c.add(Calendar.DATE, SCHEMA_HISTORY_DAYS + SCHEMA_FUTURE_DAYS); Date endDate = ApiUtil.dayEnd(c).getTime(); PatientEntity forPatient = patientRepository.findOne(patient.getId()); List<ScheduledActivityEntity> entities = scheduledActivityRepository.findByPatientAndScheduledTimeBetween(forPatient, startDate, endDate); Collections.sort(entities); ScheduledActivity[] arr = ScheduledActivityImpl.newFromEntities(entities); return ServiceResultImpl.createSuccessResult(arr, new GenericSuccessMessage()); } @Override public ServiceResult<HealthPlan> createNewHealthPlan(final HealthPlan o, final CareGiverBaseView careGiver, final Long patientId) { log.info("Creating new ordination {}", o.getName()); final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); try { final Date start = sdf.parse(o.getStartDate()); final DurationUnit du = DurationUnit.valueOf(o.getDurationUnit().getCode()); final CareGiverEntity cg = this.careGiverRepository.findByHsaId(careGiver.getHsaId()); final PatientEntity patient = this.patientRepository.findOne(patientId); final HealthPlanEntity newEntity = HealthPlanEntity.newEntity(cg, patient, o.getName(), start, o.getDuration(), du); final HealthPlanEntity saved = this.repo.save(newEntity); final HealthPlan dto = HealthPlanImpl.newFromEntity(saved, null); return ServiceResultImpl.createSuccessResult(dto, new GenericSuccessMessage()); } catch (ParseException e1) { throw new IllegalArgumentException("Could not parse date.", e1); } } @Override public ServiceResult<HealthPlan> deleteHealthPlan(Long healthPlanId) { log.info("Deleting health plan {}", healthPlanId); final HealthPlanEntity hp = this.repo.findOne(healthPlanId); if (hp == null) { return ServiceResultImpl.createFailedResult(new EntityNotFoundMessage(HealthPlanEntity.class, healthPlanId)); } this.verifyWriteAccess(hp); this.repo.delete(healthPlanId); return ServiceResultImpl.createSuccessResult(null, new GenericSuccessMessage()); } @Override public ServiceResult<HealthPlan> loadHealthPlan(Long healthPlanId) { final HealthPlanEntity entity = this.repo.findOne(healthPlanId); if (entity == null) { return ServiceResultImpl.createFailedResult(new EntityNotFoundMessage(HealthPlanEntity.class, healthPlanId)); } this.verifyReadAccess(entity); final HealthPlan dto = HealthPlanImpl.newFromEntity(entity, LocaleContextHolder.getLocale()); return ServiceResultImpl.createSuccessResult(dto, new GenericSuccessMessage()); } @Override public ServiceResult<HealthPlan> addActvitiyToHealthPlan( final Long healthPlanId, final ActivityDefinition dto, final UserBaseView user) { log.info("Adding activity defintion to existing ordination with id {}", healthPlanId); final HealthPlanEntity entity = this.repo.findOne(healthPlanId); if (entity == null) { return ServiceResultImpl.createFailedResult(new EntityNotFoundMessage(HealthPlanEntity.class, healthPlanId)); } this.verifyWriteAccess(entity); log.debug("Health plan entity found and resolved."); final ActivityTypeEntity typeEntity = this.activityTypeRepository.findOne(dto.getType().getId()); if (typeEntity == null) { return ServiceResultImpl.createFailedResult(new EntityNotFoundMessage(ActivityTypeEntity.class, dto.getType().getId())); } log.debug("Activity type entity found and resolved"); /* * Create the day frequency based on what the user * selected. */ log.debug("Processing the day and time frequence..."); final Frequency frequency = new Frequency(); frequency.setWeekFrequency(dto.getActivityRepeat()); for (final DayTime dt : dto.getDayTimes()) { FrequencyDay fd = FrequencyDay.newFrequencyDay(ApiUtil.toIntDay(dt.getDay())); for (String time : dt.getTimes()) { fd.addTime(FrequencyTime.unmarshal(time)); } frequency.addDay(fd); } log.debug("Frequency: {}", Frequency.marshal(frequency)); final UserEntity userEntity = user.isCareGiver() ? careGiverRepository.findOne(user.getId()) : patientRepository.findOne(user.getId()); final ActivityDefinitionEntity newEntity = ActivityDefinitionEntity.newEntity(entity, typeEntity, frequency, userEntity); log.debug("Setting public definition to {}", dto.isPublicDefinition()); newEntity.setPublicDefinition(dto.isPublicDefinition()); /* * Process measurement defintions */ for (final MeasurementDefinitionEntity mde : newEntity.getMeasurementDefinitions()) { for (final MeasurementDefinition md : dto.getGoalValues()) { if (mde.getMeasurementType().getId().equals(md.getMeasurementType().getId())) { log.debug("Processing measure value {} for activity type {}", mde.getMeasurementType().getName(), mde.getMeasurementType().getActivityType().getName()); switch (mde.getMeasurementType().getValueType()) { case INTERVAL: log.debug("Setting values for measure defintion: {}-{}", md.getMinTarget(), md.getMaxTarget()); mde.setMaxTarget(md.getMaxTarget()); mde.setMinTarget(md.getMinTarget()); break; case SINGLE_VALUE: log.debug("Setting values for measure defintion: {}", md.getTarget()); mde.setTarget(md.getTarget()); break; } } } } if (dto.getStartDate() != null) { newEntity.setStartDate(ApiUtil.parseDate(dto.getStartDate())); } ActivityDefinitionEntity savedEntity = activityDefintionRepository.save(newEntity); log.debug("Activity defintion saved."); scheduleActivities(savedEntity); final HealthPlanEntity savedOrdination = this.repo.save(entity); log.debug("Health plan saved"); log.debug("Creating result. Success!"); final HealthPlan result = HealthPlanImpl.newFromEntity(savedOrdination, LocaleContextHolder.getLocale()); return ServiceResultImpl.createSuccessResult(result, new GenericSuccessMessage()); } @Override public void scheduleActivities(ActivityDefinitionEntity activityDefinition) { scheduledActivityRepository.save(activityDefinition.scheduleActivities()); } @Override public ServiceResult<ActivityDefinition[]> loadActivitiesForHealthPlan( Long healthPlanId) { log.info("Loading health plan activities for health plan {}", healthPlanId); final HealthPlanEntity entity = this.repo.findOne(healthPlanId); if (entity == null) { return ServiceResultImpl.createFailedResult(new EntityNotFoundMessage(HealthPlanEntity.class, healthPlanId)); } this.verifyReadAccess(entity); log.debug("Found {} health plan activities for health plan {}", entity.getActivityDefinitions().size(), healthPlanId); return ServiceResultImpl.createSuccessResult(ActivityDefintionImpl.newFromEntities(entity.getActivityDefinitions()), new ListEntitiesMessage(ActivityDefinitionEntity.class, entity.getActivityDefinitions().size())); } @Override public ServiceResult<ScheduledActivity> reportReady( Long scheduledActivityId, ActivityReport report) { log.info("Report done for scheduled activity {}", scheduledActivityId); ScheduledActivityEntity entity = scheduledActivityRepository.findOne(scheduledActivityId); entity.setReportedTime(new Date()); entity.setStatus(report.isRejected() ? ScheduledActivityStatus.REJECTED : ScheduledActivityStatus.OPEN); entity.setNote(report.getNote()); entity.setPerceivedSense(report.getSense()); for (Value value : report.getValues()) { entity.lookupMeasurement(value.getSeqno()).setReportedValue(value.getValue()); } Date d = ApiUtil.parseDateTime(report.getActualDate(), report.getActualTime()); entity.setActualTime(d); entity = scheduledActivityRepository.save(entity); log.debug("Reported time for activity is: {}", entity.getReportedTime()); return ServiceResultImpl.createSuccessResult(ScheduledActivityImpl.newFromEntity(entity), new GenericSuccessMessage()); } @Override public ServiceResult<ScheduledActivity[]> loadLatestReportedForAllPatients(final CareUnit careUnit) { log.info("Loading latest reported activities for all patients belonging to care unit {}", careUnit.getHsaId()); final CareUnitEntity entity = this.careUnitRepository.findByHsaId(careUnit.getHsaId()); if (entity == null) { ServiceResultImpl.createFailedResult(new EntityNotFoundMessage(CareUnitEntity.class, -1L)); } this.verifyReadAccess(entity); final List<ScheduledActivityEntity> activities = this.scheduledActivityRepository.findByCareUnit(entity.getHsaId()); return ServiceResultImpl.createSuccessResult(ScheduledActivityImpl.newFromEntities(activities), new ListEntitiesMessage(ScheduledActivityEntity.class, activities.size())); } @Override public ServiceResult<ActivityDefinition[]> getPlannedActivitiesForPatient( PatientBaseView patient) { PatientEntity forPatient = patientRepository.findOne(patient.getId()); Date now = new Date(); List<ActivityDefinitionEntity> defs = activityDefintionRepository.findByPatientAndNow(forPatient, now); ActivityDefinition[] arr = ActivityDefintionImpl.newFromEntities(defs); return ServiceResultImpl.createSuccessResult(arr,new GenericSuccessMessage()); } @Override public ServiceResult<PatientEvent> getActualEventsForPatient(PatientBaseView patientView) { PatientEntity patient = patientRepository.findOne(patientView.getId()); Calendar cal = Calendar.getInstance(); Date today = ApiUtil.dayBegin(cal).getTime(); cal.add(Calendar.DATE, -(SCHEMA_HISTORY_DAYS)); cal.set(Calendar.DAY_OF_WEEK, SCHEMA_DAY_ALIGN); Date start = ApiUtil.dayBegin(cal).getTime(); cal.setTime(today); Date end = ApiUtil.dayEnd(cal).getTime(); final List<ScheduledActivityEntity> activities = scheduledActivityRepository.findByPatientAndScheduledTimeBetween(patient, start, end); int num = 0; int due = 0; for (ScheduledActivityEntity sc : activities) { if (sc.getReportedTime() == null) { if (sc.getScheduledTime().compareTo(today) < 0) { due++; } else { num++; } } } PatientEvent event = PatientEventImpl.newPatientEvent(num, due); ServiceResult<PatientEvent> sr; sr = ServiceResultImpl.createSuccessResult(event, new GenericSuccessMessage()); return sr; } public ServiceResult<ScheduledActivity[]> getScheduledActivitiesForHealthPlan( Long healthPlanId) { log.info("Get scheduled activities for health plan {}", healthPlanId); final HealthPlanEntity ad = this.repo.findOne(healthPlanId); if (ad == null) { return ServiceResultImpl.createFailedResult(new EntityNotFoundMessage(HealthPlanEntity.class, healthPlanId)); } this.verifyReadAccess(ad); final List<ScheduledActivityEntity> entities = this.scheduledActivityRepository.findScheduledActivitiesForHealthPlan(healthPlanId); log.debug("Found {} scheduled activities", entities.size()); return ServiceResultImpl.createSuccessResult(ScheduledActivityImpl.newFromEntities(entities), new ListEntitiesMessage(ScheduledActivityEntity.class, entities.size())); } @Override public ServiceResult<HealthPlanStatistics> getStatisticsForHealthPlan( Long healthPlanId) { log.info("Getting statistics for health plans..."); final HealthPlanStatistics stats = new HealthPlanStatistics(); final HealthPlanEntity healthPlan = this.repo.findOne(healthPlanId); if (healthPlan == null) { return ServiceResultImpl.createFailedResult(new EntityNotFoundMessage(HealthPlanEntity.class, healthPlanId)); } this.verifyReadAccess(healthPlan); log.debug("Calculating health plan overview..."); final ScheduledActivity[] activities = this.getScheduledActivitiesForHealthPlan(healthPlanId).getData(); final List<ActivityCount> activityCount = new ArrayList<ActivityCount>(); actLoop: for(final ScheduledActivity ac : activities) { if (!ac.getDefinition().isPublicDefinition() && this.getCurrentUser().isCareGiver()) { log.debug("Skip activity because the care giver was not allowed to see it."); continue actLoop; } final String name = ac.getDefinition().getType().getName(); final ActivityCount act = new ActivityCount(name); final ActivityCount existing = this.findActivityCount(name, activityCount); if (existing == null) { log.debug("Activity count not in list. Adding {}", act.getName()); activityCount.add(act); } this.findActivityCount(name, activityCount).increaseCount(); } stats.setActivities(activityCount); log.debug("Health plan overview calculated."); /* * Get all reported activities */ log.debug("Calculating reported activities..."); final List<ScheduledActivityEntity> ents = this.scheduledActivityRepository.findReportedActivitiesForHealthPlan( healthPlanId , healthPlan.getStartDate() , new Date() , new Sort(Sort.Direction.ASC, "scheduledTime")); final List<MeasuredValue> measuredValues = new ArrayList<MeasuredValue>(); for (final ScheduledActivityEntity e : ents) { if (!e.getActivityDefinitionEntity().isPublicDefinition() && this.getCurrentUser().isCareGiver()) { log.debug("Skip activity because the care giver was not allowed to see it."); continue; } final ReportedActivity ra = new ReportedActivity(); ra.setName(e.getActivityDefinitionEntity().getActivityType().getName()); ra.setNote(e.getNote()); ra.setReportedAt(DateUtil.toDateTime(e.getReportedTime())); ra.setLabel(DateUtil.toDateTime(e.getScheduledTime())); final List<MeasurementEntity> measurements = e.getMeasurements(); for (final MeasurementEntity m : measurements) { final String measurementName = m.getMeasurementDefinition().getMeasurementType().getName(); MeasuredValue mv = this.findMeasuredValue(measurementName, measuredValues); if (mv == null) { mv = new MeasuredValue(); mv.setName(e.getActivityDefinitionEntity().getActivityType().getName()); mv.setValueType(new Option(measurementName, null)); mv.setUnit(new Option(m.getMeasurementDefinition().getMeasurementType().getUnit().name(), LocaleContextHolder.getLocale())); mv.setInterval(m.getMeasurementDefinition().getMeasurementType().getValueType().equals(MeasurementValueType.INTERVAL)); measuredValues.add(mv); } final ReportedValue rv = new ReportedValue(); switch (m.getMeasurementDefinition().getMeasurementType().getValueType()) { case INTERVAL: rv.setMaxTargetValue((float) m.getMaxTarget()); rv.setMinTargetValue((float) m.getMinTarget()); break; case SINGLE_VALUE: rv.setTargetValue((float) m.getTarget()); break; } rv.setReportedValue((float) m.getReportedValue()); rv.setReportedAt(DateUtil.toDateTime(e.getScheduledTime())); mv.getReportedValues().add(rv); } ra.setMeasures(measuredValues); } stats.setMeasuredValues(measuredValues); return ServiceResultImpl.createSuccessResult(stats, new GenericSuccessMessage()); } private MeasuredValue findMeasuredValue(final String measurementName, final List<MeasuredValue> list) { for (final MeasuredValue mv : list) { if (mv.getValueType().getCode().equals(measurementName)) { return mv; } } return null; } private ActivityCount findActivityCount(final String name, final List<ActivityCount> list) { for (final ActivityCount a : list) { if (a.getName().equals(name)) { return a; } } return null; } @Override public ServiceResult<ActivityDefinition> deleteActivity( Long activityDefinitionId) { log.info("Deleteing activity definition {}", activityDefinitionId); final ActivityDefinitionEntity ent = this.activityDefintionRepository.findOne(activityDefinitionId); if (ent == null) { log.warn("The activity definition {} could not be found.", activityDefinitionId); return ServiceResultImpl.createFailedResult(new EntityNotFoundMessage(ActivityDefinitionEntity.class, activityDefinitionId)); } this.verifyWriteAccess(ent); ent.setRemovedFlag(true); log.debug("Activity definition with id {} marked as rmeoved", activityDefinitionId); this.activityDefintionRepository.save(ent); return ServiceResultImpl.createSuccessResult(ActivityDefintionImpl.newFromEntity(ent), new EntityDeletedMessage(ActivityDefinitionEntity.class, activityDefinitionId)); } @Override public String getICalendarEvents(PatientBaseView patient) { PatientEntity forPatient = patientRepository.findOne(patient.getId()); Date now = new Date(); List<ActivityDefinitionEntity> defs = activityDefintionRepository.findByPatientAndNow(forPatient, now); final String calPattern = "BEGIN:VCALENDAR\r\n" + "VERSION:2.0\r\n" + "PRODID:-//Callista Enterprise//NONSGML NetCare//EN\r\n" + "%s" + "END:VCALENDAR\r\n"; final String eventPattern = "BEGIN:VEVENT\r\n" + "UID:%s@%s.%d\r\n" + "DTSTAMP;TZID=Europe/Stockholm:%s\r\n" + "DTSTART;TZID=Europe/Stockholm:%s\r\n" + "DURATION:%s\r\n" + "SUMMARY:%s\r\n" + "TRANSP:TRANSPARENT\r\n" + "CLASS:CONFIDENTIAL\r\n" + "CATEGORIES:FYSIK,PERSONLIGT,PLAN,HÄLSA\r\n" + "%s" + "END:VEVENT\r\n"; StringBuffer events = new StringBuffer(); for (ActivityDefinitionEntity ad : defs) { String stamp = EntityUtil.formatCalTime(ad.getCreatedTime()); String summary = ad.getActivityType().getName(); Frequency fr = ad.getFrequency(); String duration = toICalDuration(ad); for (FrequencyDay day : fr.getDays()) { StringBuffer rrule = new StringBuffer(); String wday = toICalDay(day); if (fr.getWeekFrequency() > 0) { rrule.append("RRULE:FREQ=WEEKLY"); rrule.append(";INTERVAL=").append(ad.getFrequency().getWeekFrequency()); rrule.append(";WKST=MO"); rrule.append(";BYDAY=").append(wday); rrule.append(";UNTIL=").append(EntityUtil.formatCalTime(ad.getHealthPlan().getEndDate())); rrule.append("\r\n"); } int timeIndex = 0; for (FrequencyTime time : day.getTimes()) { Calendar cal = Calendar.getInstance(); cal.setTime(ad.getStartDate()); cal.set(Calendar.HOUR, time.getHour()); cal.set(Calendar.MINUTE, time.getMinute()); String start = EntityUtil.formatCalTime(cal.getTime()); events.append(String.format(eventPattern, ad.getUUID(), wday, timeIndex++, stamp, start, duration, summary, rrule.toString())); } } } String r = String.format(calPattern, events.toString()); return r; } /** * Converts amount and units into minutes. <p> * * Steps are converted into slow walking, and meter into slow jog. <p> * * Minutes are rounded to half-hour precision. * * @param the activity deftinion. * @return the ical duration. */ private static String toICalDuration(ActivityDefinitionEntity ad) { int minutes = 30; for (MeasurementDefinitionEntity md : ad.getMeasurementDefinitions()) { int target = md.getMeasurementType().getValueType().equals(MeasurementValueType.INTERVAL) ? md.getMaxTarget() : md.getTarget(); switch (md.getMeasurementType().getUnit()) { case STEP: minutes = Math.max(target / 50, minutes); break; case METER: minutes = Math.max(target / 80, minutes); break; case MINUTE: minutes = Math.max(target, minutes); break; } } String dur = "PT"; if (minutes > 60) { int hours = minutes / 60; dur += (hours + "H"); minutes = (minutes % 60); } minutes = (minutes < 30) ? 30 : 60; dur += (minutes + "M"); return dur; } private static String toICalDay(FrequencyDay day) { switch (day.getDay()) { case Calendar.MONDAY: return "MO"; case Calendar.TUESDAY: return "TU"; case Calendar.WEDNESDAY: return "WE"; case Calendar.THURSDAY: return "TH"; case Calendar.FRIDAY: return "FR"; case Calendar.SATURDAY: return "SA"; case Calendar.SUNDAY: return "SU"; } throw new IllegalArgumentException("Invalid day: " + day.getDay()); } @Override public ServiceResult<ScheduledActivity> commentOnPerformedActivity( Long activityId, String comment) { final ScheduledActivityEntity ent = this.scheduledActivityRepository.findOne(activityId); if (ent == null) { return ServiceResultImpl.createFailedResult(new EntityNotFoundMessage(ScheduledActivityEntity.class, activityId)); } this.verifyWriteAccess(ent); final UserEntity user = this.getCurrentUser(); if (user.isCareGiver()) { final CareGiverEntity cg = (CareGiverEntity) user; ent.getComments().add(ActivityCommentEntity.newEntity(comment, cg, ent)); return ServiceResultImpl.createSuccessResult(ScheduledActivityImpl.newFromEntity(ent), new GenericSuccessMessage()); } else { throw new SecurityException("A patient is not allow to comment his own activity"); } } @Override public ServiceResult<ActivityComment[]> loadCommentsForPatient() { final PatientEntity patient = this.getPatient(); final List<ActivityCommentEntity> entities = this.commentRepository.findCommentsForPatient(patient); return ServiceResultImpl.createSuccessResult(ActivityCommentImpl.newFromEntities(entities), new ListEntitiesMessage(ActivityCommentEntity.class, entities.size())); } @Override public ServiceResult<ActivityComment> replyToComment(Long comment, final String reply) { final ActivityCommentEntity ent = this.commentRepository.findOne(comment); if (ent == null) { return ServiceResultImpl.createFailedResult(new EntityNotFoundMessage(ActivityCommentEntity.class, comment)); } this.verifyWriteAccess(getPatient()); ent.setReply(reply); ent.setRepliedAt(new Date()); return ServiceResultImpl.createSuccessResult(ActivityCommentImpl.newFromEntity(ent), new GenericSuccessMessage()); } @Override public ServiceResult<ActivityComment[]> loadRepliesForCareGiver() { final CareGiverEntity cg = this.getCareGiver(); log.info("Loading replies for care giver {}", cg.getName()); final List<ActivityCommentEntity> comments = this.commentRepository.findRepliesForCareGiver(cg); return ServiceResultImpl.createSuccessResult(ActivityCommentImpl.newFromEntities(comments), new ListEntitiesMessage(ActivityCommentEntity.class, comments.size())); } @Override public ServiceResult<ActivityComment> deleteComment(Long commentId) { final UserEntity user = this.getCurrentUser(); log.info("Care giver {} is deleting comment {}", user.getId(), commentId); final ActivityCommentEntity ent = this.commentRepository.findOne(commentId); if (ent == null) { return ServiceResultImpl.createFailedResult(new EntityNotFoundMessage(ActivityCommentEntity.class, commentId)); } this.verifyWriteAccess(ent); this.commentRepository.delete(ent); return ServiceResultImpl.createSuccessResult(null, new GenericSuccessMessage()); } @Override public ServiceResult<ScheduledActivity> loadScheduledActivity(Long activity) { final ScheduledActivityEntity sae = this.scheduledActivityRepository.findOne(activity); if (sae == null) { return ServiceResultImpl.createFailedResult(new EntityNotFoundMessage(ScheduledActivityEntity.class, activity)); } this.verifyReadAccess(sae); return ServiceResultImpl.createSuccessResult(ScheduledActivityImpl.newFromEntity(sae), new GenericSuccessMessage()); } private static String quotedString(String s) { return String.format("\"%s\"", s); } // FIXME: Requires single activity definitions @Override public String getPlanReports(Long activityDeifntionId, PatientBaseView patient) { ActivityDefinitionEntity entity = activityDefintionRepository.findOne(activityDeifntionId); List<ScheduledActivityEntity> list = entity.getScheduledActivities(); StringBuffer hb = new StringBuffer(); hb.append("Aktivitet"); hb.append(CSV_SEP).append("Planerad datum"); hb.append(CSV_SEP).append("Planerad tid"); hb.append(CSV_SEP).append("Utförd datum"); hb.append(CSV_SEP).append("Utförd tid"); hb.append(CSV_SEP).append("Känsla"); hb.append(CSV_SEP).append("Kommentar"); StringBuffer sb = new StringBuffer(); boolean first = true; for (ScheduledActivityEntity sc : list) { if (sc.getReportedTime() == null) { continue; } sb.append(quotedString(sc.getActivityDefinitionEntity().getActivityType().getName())); sb.append(CSV_SEP).append(ApiUtil.formatDate(sc.getScheduledTime())); sb.append(CSV_SEP).append(ApiUtil.formatTime(sc.getScheduledTime())); sb.append(CSV_SEP).append(sc.getActualTime() != null ? ApiUtil.formatDate(sc.getActualTime()) : ""); sb.append(CSV_SEP).append(sc.getActualTime() != null ? ApiUtil.formatTime(sc.getActualTime()) : ""); sb.append(CSV_SEP).append(sc.getPerceivedSense()); sb.append(CSV_SEP).append(quotedString(sc.getNote())); for (MeasurementEntity me : sc.getMeasurements()) { MeasurementTypeEntity type = me.getMeasurementDefinition().getMeasurementType(); String name = type.getName(); if (first) { Option unit = new Option(type.getUnit().name(), LocaleContextHolder.getLocale()); hb.append(CSV_SEP).append(quotedString(name + " [" + unit.getValue() + "]")); if (type.getValueType().equals(MeasurementValueType.INTERVAL)) { hb.append(CSV_SEP).append(quotedString(name + " - min")); hb.append(CSV_SEP).append(quotedString(name + " - max")); } else { hb.append(CSV_SEP).append(quotedString(name + " - mål")); } } sb.append(CSV_SEP).append(me.getReportedValue()); if (type.getValueType().equals(MeasurementValueType.INTERVAL)) { sb.append(CSV_SEP).append(me.getMinTarget()); sb.append(CSV_SEP).append(me.getMaxTarget()); } else { sb.append(CSV_SEP).append(me.getTarget()); } } sb.append(CSV_EOL); first = false; } hb.append(CSV_EOL); return hb.append(sb).toString(); } }
package org.fao.fenix.commons.msd.dto.full; import com.fasterxml.jackson.annotation.JsonProperty; import org.fao.fenix.commons.annotations.Description; import org.fao.fenix.commons.annotations.Label; import org.fao.fenix.commons.msd.dto.JSONEntity; import javax.persistence.Embedded; import java.io.Serializable; public class SeProjectionParameters extends JSONEntity implements Serializable { @JsonProperty @Label(en="Zone") @Description(en= "Unique identifier for 100,000-meter grid zone.") private Integer zone; @JsonProperty @Label(en="Standard parallel") @Description(en= "Line of constant latitude where the projection surface intersects the earth.") private Double standardParallel; @JsonProperty @Label(en="Longitude of central meridian") @Description(en= "Line of longitude at the center of a map projection generally used as the basis for constructing the projection.") private Double longitudeOfCentralMeridian; @JsonProperty @Label(en="Latitude of projection origin") @Description(en= "Latitude chosen as the origin of the coordinates for a map projection.") private Double latitudeOfProjectionOrigin; @JsonProperty @Label(en="False easting") @Description(en= "Value added to all 'x' values to the coordinates for a map projection. It is expressed in the unit of measure identi ed in Planar Coordinate Unit.") private Double falseEasting; @JsonProperty @Label(en="False northing") @Description(en= "Value added to all 'y' values to the coordinates for a map projection. This value frequently is assigned to eliminate negative numbers. It is expressed in the unit of measure identified in Planar Coordinates Units.") private Double falseNorthing; @JsonProperty @Label(en="Unit of measure of false easting/northing") @Description(en= "Unit of the falseEasting and falseNorthing.") private OjMeasure falseEastingNorthingUnits; @JsonProperty @Label(en="Scale factor at the equator") @Description(en= "Ratio between the distance on earth and the corresponding map distance, along the equator.") private Double scaleFactorAtEquator; @JsonProperty @Label(en="Height of view point above the Earth (m)") @Description(en= "Height of viewpoint above the Earth expressed in meters.") private Double heightOfProspectivePointAboveSurface; @JsonProperty @Label(en="Longitude of projection centre") @Description(en= "Longitude of the point of projection for azimuthal projections.") private Double longitudeOfProjectionCenter; @JsonProperty @Label(en="Latitude of projection center") @Description(en= "Latitude of the point of projection for azimuthal projections.") private Double latitudeOfProjectionCenter; @JsonProperty @Label(en="Scale factor at center line") @Description(en= "Ratio between distance on earth and the corresponding map distance, along the center line.") private Double scaleFactorAtCenterLine; @JsonProperty @Label(en="Straight vertical longitude from pole") @Description(en= "Longitude to be oriented straight up from the North Pole.") private Double straightVerticalLongitudeFromPole; @JsonProperty @Label(en="Scale factor at projection origin") @Description(en= "Multiplier for reducing a distance obtained from a map by computation or scaling to the actual distance at the projection origin.") private Double scaleFactorAtProjectionOrigin; @JsonProperty @Label(en="Oblique Line Azimuth") @Description(en= "Method used to describe the line along which an oblique Mercator map projection is centred using the map projection origin and an azimuth.") private SeObliqueLineAzimuth seObliqueLineAzimuth; @JsonProperty @Label(en="Oblique Line Point") @Description(en= "Method used to describe the line along which an oblique mercator map projection is centred using two points near the limit of the mapped region that define the centre line.") private SeObliqueLinePoint seObliqueLinePoint; public Integer getZone() { return zone; } public void setZone(Integer zone) { this.zone = zone; } public Double getStandardParallel() { return standardParallel; } public void setStandardParallel(Double standardParallel) { this.standardParallel = standardParallel; } public Double getLongitudeOfCentralMeridian() { return longitudeOfCentralMeridian; } public void setLongitudeOfCentralMeridian(Double longitudeOfCentralMeridian) { this.longitudeOfCentralMeridian = longitudeOfCentralMeridian; } public Double getLatitudeOfProjectionOrigin() { return latitudeOfProjectionOrigin; } public void setLatitudeOfProjectionOrigin(Double latitudeOfProjectionOrigin) { this.latitudeOfProjectionOrigin = latitudeOfProjectionOrigin; } public Double getFalseEasting() { return falseEasting; } public void setFalseEasting(Double falseEasting) { this.falseEasting = falseEasting; } public Double getFalseNorthing() { return falseNorthing; } public void setFalseNorthing(Double falseNorthing) { this.falseNorthing = falseNorthing; } public OjMeasure getFalseEastingNorthingUnits() { return falseEastingNorthingUnits; } @Embedded public void setFalseEastingNorthingUnits(OjMeasure falseEastingNorthingUnits) { this.falseEastingNorthingUnits = falseEastingNorthingUnits; } public Double getScaleFactorAtEquator() { return scaleFactorAtEquator; } public void setScaleFactorAtEquator(Double scaleFactorAtEquator) { this.scaleFactorAtEquator = scaleFactorAtEquator; } public Double getHeightOfProspectivePointAboveSurface() { return heightOfProspectivePointAboveSurface; } public void setHeightOfProspectivePointAboveSurface(Double heightOfProspectivePointAboveSurface) { this.heightOfProspectivePointAboveSurface = heightOfProspectivePointAboveSurface; } public Double getLongitudeOfProjectionCenter() { return longitudeOfProjectionCenter; } public void setLongitudeOfProjectionCenter(Double longitudeOfProjectionCenter) { this.longitudeOfProjectionCenter = longitudeOfProjectionCenter; } public Double getLatitudeOfProjectionCenter() { return latitudeOfProjectionCenter; } public void setLatitudeOfProjectionCenter(Double latitudeOfProjectionCenter) { this.latitudeOfProjectionCenter = latitudeOfProjectionCenter; } public Double getScaleFactorAtCenterLine() { return scaleFactorAtCenterLine; } public void setScaleFactorAtCenterLine(Double scaleFactorAtCenterLine) { this.scaleFactorAtCenterLine = scaleFactorAtCenterLine; } public Double getStraightVerticalLongitudeFromPole() { return straightVerticalLongitudeFromPole; } public void setStraightVerticalLongitudeFromPole(Double straightVerticalLongitudeFromPole) { this.straightVerticalLongitudeFromPole = straightVerticalLongitudeFromPole; } public Double getScaleFactorAtProjectionOrigin() { return scaleFactorAtProjectionOrigin; } public void setScaleFactorAtProjectionOrigin(Double scaleFactorAtProjectionOrigin) { this.scaleFactorAtProjectionOrigin = scaleFactorAtProjectionOrigin; } public SeObliqueLineAzimuth getSeObliqueLineAzimuth() { return seObliqueLineAzimuth; } @Embedded public void setSeObliqueLineAzimuth(SeObliqueLineAzimuth seObliqueLineAzimuth) { this.seObliqueLineAzimuth = seObliqueLineAzimuth; } public SeObliqueLinePoint getSeObliqueLinePoint() { return seObliqueLinePoint; } @Embedded public void setSeObliqueLinePoint(SeObliqueLinePoint seObliqueLinePoint) { this.seObliqueLinePoint = seObliqueLinePoint; } }
package org.jkiss.dbeaver.model.impl.jdbc.cache; import org.jkiss.code.NotNull; import org.jkiss.code.Nullable; import org.jkiss.dbeaver.DBException; import org.jkiss.dbeaver.Log; import org.jkiss.dbeaver.model.DBConstants; import org.jkiss.dbeaver.model.DBPDataSource; import org.jkiss.dbeaver.model.DBUtils; import org.jkiss.dbeaver.model.exec.jdbc.JDBCResultSet; import org.jkiss.dbeaver.model.exec.jdbc.JDBCSession; import org.jkiss.dbeaver.model.exec.jdbc.JDBCStatement; import org.jkiss.dbeaver.model.impl.AbstractObjectCache; import org.jkiss.dbeaver.model.impl.jdbc.JDBCUtils; import org.jkiss.dbeaver.model.runtime.DBRProgressMonitor; import org.jkiss.dbeaver.model.struct.DBSObject; import org.jkiss.utils.CommonUtils; import java.sql.ResultSet; import java.sql.SQLException; import java.util.*; /** * Composite objects cache. * Each composite object consists from several rows. * Each row object refers to some other DB objects. * Each composite object belongs to some parent object (table usually) and it's name is unique within it's parent. * Each row object name is unique within main object. * * Examples: table index, constraint. */ public abstract class JDBCCompositeCache< OWNER extends DBSObject, PARENT extends DBSObject, OBJECT extends DBSObject, ROW_REF extends DBSObject> extends AbstractObjectCache<OWNER, OBJECT> { protected static final Log log = Log.getLog(JDBCCompositeCache.class); public static final String DEFAULT_OBJECT_NAME = "#DBOBJ"; private final JDBCStructCache<OWNER,?,?> parentCache; private final Class<PARENT> parentType; private final Object parentColumnName; private final Object objectColumnName; private final Map<PARENT, List<OBJECT>> objectCache = new IdentityHashMap<>(); protected JDBCCompositeCache( JDBCStructCache<OWNER,?,?> parentCache, Class<PARENT> parentType, Object parentColumnName, Object objectColumnName) { this.parentCache = parentCache; this.parentType = parentType; this.parentColumnName = parentColumnName; this.objectColumnName = objectColumnName; } abstract protected JDBCStatement prepareObjectsStatement(JDBCSession session, OWNER owner, PARENT forParent) throws SQLException; @Nullable abstract protected OBJECT fetchObject(JDBCSession session, OWNER owner, PARENT parent, String childName, ResultSet resultSet) throws SQLException, DBException; @Nullable abstract protected ROW_REF fetchObjectRow(JDBCSession session, PARENT parent, OBJECT forObject, ResultSet resultSet) throws SQLException, DBException; protected PARENT getParent(OBJECT object) { return (PARENT) object.getParentObject(); } abstract protected void cacheChildren(OBJECT object, List<ROW_REF> children); @NotNull @Override public Collection<OBJECT> getAllObjects(@NotNull DBRProgressMonitor monitor, @Nullable OWNER owner) throws DBException { return getObjects(monitor, owner, null); } public Collection<OBJECT> getObjects(DBRProgressMonitor monitor, OWNER owner, PARENT forParent) throws DBException { loadObjects(monitor, owner, forParent); return getCachedObjects(forParent); } public Collection<OBJECT> getCachedObjects(PARENT forParent) { if (forParent == null) { return getCachedObjects(); } else { synchronized (objectCache) { return objectCache.get(forParent); } } } @Override public OBJECT getObject(@NotNull DBRProgressMonitor monitor, @Nullable OWNER owner, @NotNull String objectName) throws DBException { loadObjects(monitor, owner, null); return getCachedObject(objectName); } public OBJECT getObject(DBRProgressMonitor monitor, OWNER owner, PARENT forParent, String objectName) throws DBException { loadObjects(monitor, owner, forParent); if (forParent == null) { return getCachedObject(objectName); } else { synchronized (objectCache) { return DBUtils.findObject(objectCache.get(forParent), objectName); } } } @Override public void cacheObject(@NotNull OBJECT object) { super.cacheObject(object); synchronized (objectCache) { List<OBJECT> objects = objectCache.get(getParent(object)); if (!CommonUtils.isEmpty(objects)) { objects.add(object); } } } @Override public void removeObject(@NotNull OBJECT object) { super.removeObject(object); objectCache.remove(getParent(object)); } public void clearObjectCache(PARENT forParent) { if (forParent == null) { super.clearCache(); } else { objectCache.remove(forParent); } } @Override public void clearCache() { synchronized (objectCache) { this.objectCache.clear(); super.clearCache(); } } private class ObjectInfo { final OBJECT object; final List<ROW_REF> rows = new ArrayList<>(); public boolean broken; public ObjectInfo(OBJECT object) { this.object = object; } } protected void loadObjects(DBRProgressMonitor monitor, OWNER owner, PARENT forParent) throws DBException { synchronized (objectCache) { if ((forParent == null && isCached()) || (forParent != null && (!forParent.isPersisted() || objectCache.containsKey(forParent)))) { return; } } // Load tables and columns first if (forParent == null) { parentCache.loadObjects(monitor, owner); parentCache.loadChildren(monitor, owner, null); } Map<PARENT, Map<String, ObjectInfo>> parentObjectMap = new LinkedHashMap<>(); // Load index columns DBPDataSource dataSource = owner.getDataSource(); assert (dataSource != null); try (JDBCSession session = DBUtils.openMetaSession(monitor, dataSource, "Load composite objects")) { JDBCStatement dbStat = prepareObjectsStatement(session, owner, forParent); dbStat.setFetchSize(DBConstants.METADATA_FETCH_SIZE); try { dbStat.executeStatement(); JDBCResultSet dbResult = dbStat.getResultSet(); if (dbResult != null) try { while (dbResult.next()) { if (monitor.isCanceled()) { break; } String parentName = parentColumnName instanceof Number ? JDBCUtils.safeGetString(dbResult, ((Number)parentColumnName).intValue()) : JDBCUtils.safeGetString(dbResult, parentColumnName.toString()); String objectName = objectColumnName instanceof Number ? JDBCUtils.safeGetString(dbResult, ((Number)objectColumnName).intValue()) : JDBCUtils.safeGetString(dbResult, objectColumnName.toString()); if (CommonUtils.isEmpty(objectName)) { // Use default name objectName = getDefaultObjectName(parentName); } if (forParent == null && CommonUtils.isEmpty(parentName)) { // No parent - can't evaluate it log.debug("Empty parent name in " + this); continue; } PARENT parent = forParent; if (parent == null) { parent = parentCache.getObject(monitor, owner, parentName, parentType); if (parent == null) { log.debug("Object '" + objectName + "' owner '" + parentName + "' not found"); continue; } } synchronized (objectCache) { if (objectCache.containsKey(parent)) { // Already cached continue; } } // Add to map Map<String, ObjectInfo> objectMap = parentObjectMap.get(parent); if (objectMap == null) { objectMap = new TreeMap<>(); parentObjectMap.put(parent, objectMap); } ObjectInfo objectInfo = objectMap.get(objectName); if (objectInfo == null) { OBJECT object = fetchObject(session, owner, parent, objectName, dbResult); if (object == null) { // Can't fetch object continue; } objectName = object.getName(); objectInfo = new ObjectInfo(object); objectMap.put(objectName, objectInfo); } ROW_REF rowRef = fetchObjectRow(session, parent, objectInfo.object, dbResult); if (rowRef == null) { // At least one of rows is broken. // So entire object is broken, let's just skip it. objectInfo.broken = true; break; } objectInfo.rows.add(rowRef); } } finally { dbResult.close(); } } finally { dbStat.close(); } } catch (SQLException ex) { throw new DBException(ex, dataSource); } if (monitor.isCanceled()) { return; } // Fill global cache synchronized (this) { synchronized (objectCache) { if (forParent != null || !parentObjectMap.isEmpty()) { if (forParent == null) { // Cache global object list List<OBJECT> globalCache = new ArrayList<>(); for (Map<String, ObjectInfo> objMap : parentObjectMap.values()) { if (objMap != null) { for (ObjectInfo info : objMap.values()) { if (!info.broken) { globalCache.add(info.object); } } } } // Save precached objects in global cache for (List<OBJECT> objects : objectCache.values()) { globalCache.addAll(objects); } // Add precached objects to global cache too this.setCache(globalCache); this.invalidateObjects(monitor, owner, new CacheIterator()); } } // Cache data in individual objects only if we have read something or have certain parent object // Otherwise we assume that this function is not supported for mass data reading // All objects are read. Now assign them to parents for (Map.Entry<PARENT, Map<String, ObjectInfo>> colEntry : parentObjectMap.entrySet()) { if (colEntry.getValue() == null || objectCache.containsKey(colEntry.getKey())) { // Do not overwrite this object's cache continue; } Collection<ObjectInfo> objectInfos = colEntry.getValue().values(); ArrayList<OBJECT> objects = new ArrayList<>(objectInfos.size()); for (ObjectInfo objectInfo : objectInfos) { if (!objectInfo.broken) { cacheChildren(objectInfo.object, objectInfo.rows); objects.add(objectInfo.object); } } objectCache.put(colEntry.getKey(), objects); } // Now set empty object list for other parents if (forParent == null) { for (PARENT tmpParent : parentCache.getTypedObjects(monitor, owner, parentType)) { if (!parentObjectMap.containsKey(tmpParent) && !objectCache.containsKey(tmpParent)) { objectCache.put(tmpParent, new ArrayList<OBJECT>()); } } } else if (!parentObjectMap.containsKey(forParent) && !objectCache.containsKey(forParent)) { objectCache.put(forParent, new ArrayList<OBJECT>()); } } } } protected String getDefaultObjectName(String parentName) { return parentName == null ? DEFAULT_OBJECT_NAME : parentName.toUpperCase() + "_" + DEFAULT_OBJECT_NAME; } }
package org.devgateway.ocds.persistence.mongo.repository; import org.devgateway.ocds.persistence.mongo.Organization; import org.devgateway.ocds.persistence.mongo.Organization.OrganizationType; import org.springframework.data.mongodb.repository.Query; /** * @author mpostelnicu * */ public interface OrganizationRepository extends GenericOrganizationRepository<Organization> { @Query(value = "{$and: [ { $or: [ {'_id' : ?0 }, " + "{'name': ?0 } ] } , { 'types': ?1 } ]}") Organization findByIdOrNameAndTypes(String idName, OrganizationType type); @Query(value = "{ $or: [ {'_id' : ?0 }, " + "{'name': ?0} ] }") Organization findByIdOrName(String idName); @Query(value = "{$and: [ { $or: [ {'_id' : ?0 }, " + "{'additionalIdentifiers.identifier._id': ?0} ] }, { 'types': ?1 } ] }") Organization findByAllIdsAndType(String id, OrganizationType type); }
package uk.ac.ebi.atlas.experimentpage.baseline.download; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import uk.ac.ebi.atlas.experimentpage.context.BaselineRequestContextBuilder; import uk.ac.ebi.atlas.model.baseline.BaselineExperiment; import uk.ac.ebi.atlas.web.BaselineRequestPreferences; import uk.ac.ebi.atlas.web.FilterFactorsConverter; import uk.ac.ebi.atlas.web.controllers.ExperimentDispatcher; import uk.ac.ebi.atlas.web.controllers.ResourceNotFoundException; import javax.inject.Inject; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.validation.Valid; import java.io.IOException; import java.text.MessageFormat; @Controller @Scope("request") public class ProteomicsBaselineExperimentDownloadController extends BaselineExperimentDownloadController { private final String TYPE_PROTEOMICS_BASELINE = "type=PROTEOMICS_BASELINE"; @Inject public ProteomicsBaselineExperimentDownloadController(BaselineRequestContextBuilder requestContextBuilder, FilterFactorsConverter filterFactorsConverter, ProteomicsBaselineProfilesWriter proteomicsBaselineProfilesWriter) { super(requestContextBuilder, filterFactorsConverter, proteomicsBaselineProfilesWriter); } @RequestMapping(value = "/experiments/{experimentAccession}.tsv", params = TYPE_PROTEOMICS_BASELINE) public void downloadGeneProfiles(HttpServletRequest request , @ModelAttribute("preferences") @Valid BaselineRequestPreferences preferences , HttpServletResponse response) throws IOException { geneProfilesHandler(request, preferences, response); } @RequestMapping(value = "/experiments/{experimentAccession}/{experimentAccession}-atlasExperimentSummary.Rdata", params = TYPE_PROTEOMICS_BASELINE) public String downloadRdataURL(HttpServletRequest request) throws IOException { throw new ResourceNotFoundException(""); } }
package org.vrjuggler.vrjconfig.customeditors.display_window; import java.awt.BorderLayout; import java.awt.Component; import java.awt.Container; import java.awt.Dimension; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import javax.swing.*; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import org.vrjuggler.jccl.config.*; import org.vrjuggler.vrjconfig.commoneditors.KeyboardEditorPanel; public class SimKeyboardEditorPanel extends JPanel implements EditorConstants { private static Map sSimDevProxyTypeMap; private static Map sSimDevEditorMap; static { sSimDevProxyTypeMap = new HashMap(); sSimDevProxyTypeMap.put(SIM_ANALOG_DEVICE_TYPE, ANALOG_PROXY_TYPE); sSimDevProxyTypeMap.put(SIM_DIGITAL_DEVICE_TYPE, DIGITAL_PROXY_TYPE); sSimDevProxyTypeMap.put(SIM_POS_DEVICE_TYPE, POSITION_PROXY_TYPE); sSimDevEditorMap = new HashMap(); } public SimKeyboardEditorPanel() { mDeviceList.setModel(new DefaultListModel()); ConfigBroker broker = new ConfigBrokerProxy(); ConfigDefinitionRepository def_repos = broker.getRepository(); for ( Iterator i = sSimDevProxyTypeMap.keySet().iterator(); i.hasNext(); ) { String dev_type = (String) i.next(); String proxy_type = (String) sSimDevProxyTypeMap.get(dev_type); mSimDevProxyDefMap.put(def_repos.get(dev_type), def_repos.get(proxy_type)); } try { jbInit(); } catch (Exception ex) { ex.printStackTrace(); } } /** * Sets up the configuration information for this panel. This is primarily * a convenience method intended to eliminate the need for the caller to * invoke the methods setConfig(ConfigContext,ConfigElement) and * setDataSourceName(String) in succession. In general, this should only * be invoked once for a given instance of this class. At the moment, the * implementation of this method expects to be invoked only once. * * @param ctx the config context that will be used by this * panel * @param kbdElt the keyboard/mouse device config element that * serves as the basis for what this panel edits * @param dataSourceName the name of the data source that will be used * by this panel for adding new config elements * and removing existing config elements * * @see #setConfig(ConfigContext, ConfigElement) * @see #setDataSourceName(String) */ public void setConfig(ConfigContext ctx, ConfigElement kbdElt, String dataSourceName) { setConfig(ctx, kbdElt); setDataSourceName(dataSourceName); } /** * Sets up the configuration information for this panel. In general, this * should only be invoked once for a given instance of this class. At * the moment, the implementation of this method expects to be invoked only * once. * * @param ctx the config context that will be used by this panel * @param kbdElt the keyboard/mouse device config element that serves * as the basis for what this panel edits */ public void setConfig(ConfigContext ctx, ConfigElement kbdElt) { mContext = ctx; // If the ConfigElement reference we are given is null, then there is // nothing for this panel to do. if ( kbdElt == null ) { mRemoveSimDeviceButton.setEnabled(false); } // If the given ConfigElement reference is not null, then we will not // allow a new keyboard/mouse device config element to be created. // The amount of looping that happens in here is insane... else { if ( ! kbdElt.getDefinition().getToken().equals(KEYBOARD_MOUSE_TYPE) ) { throw new IllegalArgumentException("Element named '" + kbdElt.getName() + "' is not of type " + KEYBOARD_MOUSE_TYPE); } keyboardDeviceElement = kbdElt; ConfigBroker broker = new ConfigBrokerProxy(); List elements = broker.getElements(ctx); String proxy_type = KEYBOARD_MOUSE_PROXY_TYPE; String proxy_ptr_prop = KEYBOARD_MOUSE_PROXY_PTR_PROPERTY; List sim_dev_elts = new ArrayList(); java.util.Set sim_dev_types = sSimDevProxyTypeMap.keySet(); // Pull out all the config elements that are simulated devices // that we handle. for ( Iterator i = elements.iterator(); i.hasNext(); ) { ConfigElement elt = (ConfigElement) i.next(); if ( sim_dev_types.contains(elt.getDefinition().getToken()) ) { sim_dev_elts.add(elt); } } // Search through all the elements in this context looking for // simulated devices that make use of kbdElt for keyboard/mouse // input. // System.out.println("Looking for pointers to " + kbdElt.getName()); for ( Iterator i = elements.iterator(); i.hasNext(); ) { ConfigElement proxy_elt = (ConfigElement) i.next(); // If the current config element is a keyboard proxy, then we // need to see if it points at kbdElt first. if ( proxy_elt.getDefinition().getToken().equals(proxy_type) ) { ConfigElementPointer kbd_ptr = (ConfigElementPointer) proxy_elt.getProperty(DEVICE_PROPERTY, 0); // If keyboard proxy refers to the element kbdElt, then we will // search for config elements for simulated devices that refer // to that proxy. // System.out.println("Proxy: " + proxy_elt.getName()); // System.out.println("\tPointing at " + kbd_ptr.getTarget()); if ( kbd_ptr != null && kbd_ptr.getTarget() != null && kbd_ptr.getTarget().equals(kbdElt.getName()) ) { keyboardProxyElement = proxy_elt; // Loop over all the simulated device config elements we // know about looking for those that refer to the keyboard // proxy proxy_elt. for ( Iterator j = sim_dev_elts.iterator(); j.hasNext(); ) { ConfigElement sim_elt = (ConfigElement) j.next(); ConfigElementPointer proxy_ptr = (ConfigElementPointer) sim_elt.getProperty(proxy_ptr_prop, 0); // If proxy_ptr refers to proxy_elt, then we have found // a simulated device config element that gets its input // from kbdElt. We need to create a holder for sim_elt // and ad it to the list model for mDeviceList. // System.out.println("\tSim Device: " + sim_elt.getName()); // System.out.println("\tPointing at " + // proxy_ptr.getTarget()); if ( proxy_ptr != null && proxy_ptr.getTarget() != null && proxy_ptr.getTarget().equals(proxy_elt.getName()) ) { // System.out.println("\t\tMatched " + // proxy_elt.getName()); SimDeviceConfig def_cfg = new SimDeviceConfig(ctx, sim_elt); DefaultListModel model = (DefaultListModel) mDeviceList.getModel(); model.addElement(def_cfg); } } } } } } } /** * Updates the name of the data source being used by this panel for * adding and removing config elements. This may be invoked at any time. * * @param dataSourceName the name of the data source that will be used * by this panel for adding new config elements * and removing existing config elements */ public void setDataSourceName(String dataSourceName) { mDataSourceName = dataSourceName; } public ConfigElement getKeyboardDeviceElement() { return keyboardDeviceElement; } private void jbInit() throws Exception { this.setLayout(mMainLayout); mDevicePanel.setLayout(mDevicePanelLayout); mDeviceSplitPane.setOneTouchExpandable(false); mDeviceSplitPane.setOrientation(JSplitPane.VERTICAL_SPLIT); mDeviceSplitPane.setResizeWeight(1.0); mAddSimDeviceButton.setText("Create Sim Device"); mAddSimDeviceButton.setToolTipText("Create a new simulator device configuration"); mAddSimDeviceButton.addActionListener( new SimKeyboardEditorPanel_mAddSimDeviceButton_actionAdapter(this) ); mRemoveSimDeviceButton.setEnabled(false); mRemoveSimDeviceButton.setText("Remove Sim Device"); mRemoveSimDeviceButton.setToolTipText("Remove the selected simulator device configuration"); mRemoveSimDeviceButton.addActionListener( new SimKeyboardEditorPanel_mRemoveSimDeviceButton_actionAdapter(this) ); mAddSimDeviceButton.setAlignmentX(0.5f); mRemoveSimDeviceButton.setAlignmentX(0.5f); mDeviceButtonPanel.add(mAddSimDeviceButton); mDeviceButtonPanel.add(mRemoveSimDeviceButton); mDeviceList.addListSelectionListener( new SimKeyboardEditorPanel_mDeviceList_listSelectionAdapter(this) ); mDeviceList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); mDevicePanel.add(mDeviceButtonPanel, BorderLayout.NORTH); mDevicePanel.add(mDeviceScrollPane, BorderLayout.CENTER); mKeyboardEditor.setMinimumSize(new Dimension(500, 225)); mKeyboardEditor.setPreferredSize(new Dimension(500, 225)); mDeviceSplitPane.add(mEmptyEditor, JSplitPane.LEFT); mDeviceSplitPane.add(mKeyboardEditor, JSplitPane.RIGHT); this.add(mMainSplitPane, BorderLayout.CENTER); mMainSplitPane.add(mDevicePanel, JSplitPane.LEFT); mMainSplitPane.add(mDeviceSplitPane, JSplitPane.RIGHT); mDeviceScrollPane.getViewport().add(mDeviceList); } private ConfigContext mContext = null; private ConfigElement keyboardDeviceElement = null; private ConfigElement keyboardProxyElement = null; private Map mSimDevProxyDefMap = new HashMap(); private String mDataSourceName = null; private Map mSimEditorCache = new HashMap(); private SimDeviceEditor mCurSimEditor = null; private KeyboardEditorPanel mKeyboardEditor = new KeyboardEditorPanel(); private JPanel mEmptyEditor = new JPanel(); private JSplitPane mMainSplitPane = new JSplitPane(); private BorderLayout mMainLayout = new BorderLayout(); private JPanel mDevicePanel = new JPanel(); private BorderLayout mDevicePanelLayout = new BorderLayout(); private Box mDeviceButtonPanel = new Box(BoxLayout.Y_AXIS); private JButton mAddSimDeviceButton = new JButton(); private JButton mRemoveSimDeviceButton = new JButton(); private JScrollPane mDeviceScrollPane = new JScrollPane(); private JList mDeviceList = new JList(); private JSplitPane mDeviceSplitPane = new JSplitPane(); void mAddSimDeviceButton_actionPerformed(ActionEvent event) { if ( keyboardDeviceElement == null ) { ConfigBrokerProxy broker = new ConfigBrokerProxy(); ConfigDefinition kbd_def = broker.getRepository().get(KEYBOARD_MOUSE_TYPE); ConfigElementFactory factory = new ConfigElementFactory(broker.getRepository().getAllLatest()); // Create the new KEYBOARD_MOUSE_TYPE config element. We won't bother // to ask the user for a name since they probably won't care anyway. keyboardDeviceElement = factory.createUnique(kbd_def, mContext); // Create a proxy to the new KEYBOARD_MOUSE_TYPE config element. ConfigDefinition kbd_proxy_def = broker.getRepository().get(KEYBOARD_MOUSE_PROXY_TYPE); keyboardProxyElement = factory.create(keyboardDeviceElement.getName() + " Proxy", kbd_proxy_def); keyboardProxyElement.setProperty(DEVICE_PROPERTY, 0, keyboardDeviceElement.getName()); // Add the newly created config elements to the data source that the // user selected. broker.add(mContext, keyboardDeviceElement, mDataSourceName); broker.add(mContext, keyboardProxyElement, mDataSourceName); } Container parent = (Container) SwingUtilities.getAncestorOfClass(Container.class, this); // Instead of having SimDeviceCreateDialog have yet another resource // chooser, it will use the same data source that is currently in use // for this panel. As far as the user is concerned, this should make // sense. Furthermore, the device to be created will need to reference // keyboardProxyElement, so it would generally be best to have all those // config elements in the same file. SimDeviceCreateDialog dlg = new SimDeviceCreateDialog(parent, mContext, keyboardProxyElement, mSimDevProxyDefMap, mDataSourceName); SimDeviceConfig sim_dev_cfg = dlg.showDialog(); if ( sim_dev_cfg != null ) { DefaultListModel model = (DefaultListModel) mDeviceList.getModel(); model.addElement(sim_dev_cfg); } } void mRemoveSimDeviceButton_actionPerformed(ActionEvent event) { SimDeviceConfig sim_dev_cfg = (SimDeviceConfig) mDeviceList.getSelectedValue(); ConfigElement dev_elt = sim_dev_cfg.getDevice(); if ( mCurSimEditor != null ) { mDeviceSplitPane.remove(mCurSimEditor.getEditor()); } mDeviceSplitPane.add(mEmptyEditor, JSplitPane.LEFT); mCurSimEditor = null; mDeviceSplitPane.revalidate(); mDeviceSplitPane.repaint(); mDeviceList.clearSelection(); ((DefaultListModel) mDeviceList.getModel()).removeElement(sim_dev_cfg); ConfigBroker broker = new ConfigBrokerProxy(); List aliases = sim_dev_cfg.getAliases(); for ( Iterator i = aliases.iterator(); i.hasNext(); ) { broker.remove(mContext, (ConfigElement) i.next()); } List proxies = sim_dev_cfg.getProxies(); for ( Iterator i = proxies.iterator(); i.hasNext(); ) { broker.remove(mContext, (ConfigElement) i.next()); } broker.remove(mContext, sim_dev_cfg.getDevice()); } void mDeviceList_valueChanged(ListSelectionEvent listSelectionEvent) { if ( mCurSimEditor != null ) { mCurSimEditor.setKeyboardEditorPanel(null); mDeviceSplitPane.remove(mCurSimEditor.getEditor()); mDeviceSplitPane.add(mEmptyEditor, JSplitPane.LEFT); mCurSimEditor = null; } Object selection = mDeviceList.getSelectedValue(); if ( selection != null ) { SimDeviceConfig sim_dev_cfg = (SimDeviceConfig) selection; ConfigElement dev_elt = sim_dev_cfg.getDevice(); Object cached_editor = mSimEditorCache.get(dev_elt); if ( cached_editor != null ) { mCurSimEditor = (SimDeviceEditor) cached_editor; mCurSimEditor.setKeyboardEditorPanel(mKeyboardEditor); mDeviceSplitPane.remove(mEmptyEditor); mDeviceSplitPane.add(mCurSimEditor.getEditor(), JSplitPane.LEFT); } else { // Look up the editor for this config element's type. Object value = sSimDevEditorMap.get(dev_elt.getDefinition().getToken()); if ( value != null ) { Class editor_class = (Class) value; try { mCurSimEditor = (SimDeviceEditor) editor_class.newInstance(); mCurSimEditor.setKeyboardEditorPanel(mKeyboardEditor); mCurSimEditor.setConfig(mContext, dev_elt); mDeviceSplitPane.remove(mEmptyEditor); mDeviceSplitPane.add(mCurSimEditor.getEditor(), JSplitPane.LEFT); mSimEditorCache.put(dev_elt, mCurSimEditor); } catch (Exception ex) { ex.printStackTrace(); } } else { /* No editor! */ ; } } } mRemoveSimDeviceButton.setEnabled(selection != null); } private class SimDeviceRenderer extends JLabel implements ListCellRenderer { public SimDeviceRenderer() { setOpaque(true); setHorizontalAlignment(LEFT); setVerticalAlignment(CENTER); } public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { if ( isSelected ) { setBackground(list.getSelectionBackground()); setForeground(list.getSelectionForeground()); } else { setBackground(list.getBackground()); setForeground(list.getForeground()); } setFont(list.getFont()); setText(value.toString()); return this; } } } class SimKeyboardEditorPanel_mAddSimDeviceButton_actionAdapter implements ActionListener { private SimKeyboardEditorPanel adaptee; SimKeyboardEditorPanel_mAddSimDeviceButton_actionAdapter(SimKeyboardEditorPanel adaptee) { this.adaptee = adaptee; } public void actionPerformed(ActionEvent actionEvent) { adaptee.mAddSimDeviceButton_actionPerformed(actionEvent); } } class SimKeyboardEditorPanel_mRemoveSimDeviceButton_actionAdapter implements ActionListener { private SimKeyboardEditorPanel adaptee; SimKeyboardEditorPanel_mRemoveSimDeviceButton_actionAdapter(SimKeyboardEditorPanel adaptee) { this.adaptee = adaptee; } public void actionPerformed(ActionEvent actionEvent) { adaptee.mRemoveSimDeviceButton_actionPerformed(actionEvent); } } class SimKeyboardEditorPanel_mDeviceList_listSelectionAdapter implements ListSelectionListener { private SimKeyboardEditorPanel adaptee; SimKeyboardEditorPanel_mDeviceList_listSelectionAdapter(SimKeyboardEditorPanel adaptee) { this.adaptee = adaptee; } public void valueChanged(ListSelectionEvent listSelectionEvent) { adaptee.mDeviceList_valueChanged(listSelectionEvent); } }
package fi.evident.dalesbred; import fi.evident.dalesbred.connection.DataSourceConnectionProvider; import fi.evident.dalesbred.connection.DriverManagerConnectionProvider; import fi.evident.dalesbred.dialects.Dialect; import fi.evident.dalesbred.instantiation.InstantiatorRegistry; import fi.evident.dalesbred.results.*; import fi.evident.dalesbred.support.proxy.TransactionalProxyFactory; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.inject.Inject; import javax.inject.Provider; import javax.naming.InitialContext; import javax.naming.NamingException; import javax.sql.DataSource; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.List; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; import static fi.evident.dalesbred.Propagation.*; import static fi.evident.dalesbred.SqlQuery.query; import static fi.evident.dalesbred.utils.Require.requireNonNull; /** * The main abstraction of the library: represents a connection to database and provides a way to * execute callbacks in transactions. */ public final class Database { /** Provides us with connections whenever we need one */ private final Provider<Connection> connectionProvider; /** The current active transaction of this thread, or null */ private final ThreadLocal<DatabaseTransaction> activeTransaction = new ThreadLocal<DatabaseTransaction>(); /** Logger in which we log actions */ private final Logger log = Logger.getLogger(getClass().getName()); /** The isolation level to use for transactions that have not specified an explicit level. Null for default. */ @Nullable private Isolation defaultIsolation = null; /** Default propagation for new transactions */ private boolean allowImplicitTransactions = true; /** The dialect that the database uses */ private final Dialect dialect; /** Instantiators */ private final InstantiatorRegistry instantiatorRegistry; /** * Returns a new Database that uses given {@link DataSource} to retrieve connections. */ @NotNull public static Database forDataSource(@NotNull DataSource dataSource) { return new Database(new DataSourceConnectionProvider(dataSource)); } /** * Returns a new Database that uses {@link DataSource} with given JNDI-name. */ @NotNull public static Database forJndiDataSource(@NotNull String jndiName) { try { InitialContext ctx = new InitialContext(); DataSource dataSource = (DataSource) ctx.lookup(jndiName); if (dataSource != null) return forDataSource(dataSource); else throw new DatabaseException("Could not find DataSource '" + jndiName + "'"); } catch (NamingException e) { throw new DatabaseException("Error when looking up DataSource '" + jndiName + "': " + e, e); } } /** * Returns a new Database that uses given connection options to open connection. The database * uses {@link DriverManagerConnectionProvider} so it performs no connection pooling. * * @see DriverManagerConnectionProvider */ @NotNull public static Database forUrlAndCredentials(@NotNull String url, String username, String password) { return new Database(new DriverManagerConnectionProvider(url, username, password)); } /** * Constructs a new Database that uses given connection-provider and auto-detects the dialect to use. */ @Inject public Database(@NotNull Provider<Connection> connectionProvider) { this(connectionProvider, Dialect.detect(connectionProvider)); } /** * Constructs a new Database that uses given connection-provider and dialect. */ public Database(@NotNull Provider<Connection> connectionProvider, @NotNull Dialect dialect) { this.connectionProvider = requireNonNull(connectionProvider); this.dialect = requireNonNull(dialect); this.instantiatorRegistry = new InstantiatorRegistry(dialect); } /** * Executes a block of code within a context of a transaction, using {@link Propagation#REQUIRED} propagation. */ public <T> T withTransaction(@NotNull TransactionCallback<T> callback) { return withTransaction(REQUIRED, defaultIsolation, callback); } /** * Executes a block of code with given propagation and configuration default isolation. */ public <T> T withTransaction(@NotNull Propagation propagation, @NotNull TransactionCallback<T> callback) { return withTransaction(propagation, defaultIsolation, callback); } /** * Executes a block of code with given propagation and isolation. */ public <T> T withTransaction(@NotNull Propagation propagation, @Nullable Isolation isolation, @NotNull TransactionCallback<T> callback) { DatabaseTransaction existingTransaction = activeTransaction.get(); if (existingTransaction != null) { if (propagation == REQUIRES_NEW) return withSuspendedTransaction(isolation, callback); else if (propagation == NESTED) return existingTransaction.nested(callback); else return existingTransaction.join(callback); } else { if (propagation == MANDATORY) throw new NoActiveTransactionException("Transaction propagation was MANDATORY, but there was no existing transaction."); DatabaseTransaction newTransaction = new DatabaseTransaction(connectionProvider, dialect, isolation); try { activeTransaction.set(newTransaction); return newTransaction.execute(callback); } finally { activeTransaction.set(null); newTransaction.close(); } } } /** * Returns true if and only if the current thread has an active transaction for this database. */ public boolean hasActiveTransaction() { return activeTransaction.get() != null; } private <T> T withSuspendedTransaction(@Nullable Isolation isolation, @NotNull TransactionCallback<T> callback) { DatabaseTransaction suspended = activeTransaction.get(); try { activeTransaction.set(null); return withTransaction(REQUIRED, isolation, callback); } finally { activeTransaction.set(suspended); } } private <T> T withCurrentTransaction(@NotNull TransactionCallback<T> callback) { if (allowImplicitTransactions) { return withTransaction(callback); } else { DatabaseTransaction transaction = activeTransaction.get(); if (transaction != null) return transaction.join(callback); else throw new NoActiveTransactionException("Tried to perform database operation without active transaction. Database accesses should be bracketed with Database.withTransaction(...) or implicit transactions should be enabled."); } } /** * Executes a query and processes the results with given {@link ResultSetProcessor}. * All other findXXX-methods are just convenience methods for this one. */ public <T> T executeQuery(@NotNull final ResultSetProcessor<T> processor, @NotNull final SqlQuery query) { return withCurrentTransaction(new TransactionCallback<T>() { @Override public T execute(TransactionContext tx) throws SQLException { logQuery(query); PreparedStatement ps = tx.getConnection().prepareStatement(query.sql); try { bindArguments(ps, query.args); return processResults(ps.executeQuery(), processor); } finally { ps.close(); } } }); } public <T> T executeQuery(@NotNull ResultSetProcessor<T> processor, @NotNull @SQL String sql, Object... args) { return executeQuery(processor, query(sql, args)); } /** * Executes a query and processes each row of the result with given {@link RowMapper} * to produce a list of results. */ @NotNull public <T> List<T> findAll(@NotNull RowMapper<T> rowMapper, @NotNull SqlQuery query) { return executeQuery(new ListWithRowMapperResultSetProcessor<T>(rowMapper), query); } @NotNull public <T> List<T> findAll(@NotNull RowMapper<T> rowMapper, @NotNull @SQL String sql, Object... args) { return findAll(rowMapper, query(sql, args)); } /** * Executes a query and converts the results to instances of given class using default mechanisms. */ @NotNull public <T> List<T> findAll(@NotNull Class<T> cl, @NotNull SqlQuery query) { return executeQuery(resultProcessorForClass(cl), query); } /** * Executes a query and converts the results to instances of given class using default mechanisms. */ @NotNull public <T> List<T> findAll(@NotNull Class<T> cl, @NotNull @SQL String sql, Object... args) { return findAll(cl, query(sql, args)); } /** * Finds a unique result from database, using given {@link RowMapper} to convert the row. * * @throws NonUniqueResultException if there are no rows or multiple rows */ public <T> T findUnique(@NotNull RowMapper<T> mapper, @NotNull SqlQuery query) { return unique(findAll(mapper, query)); } public <T> T findUnique(@NotNull RowMapper<T> mapper, @NotNull @SQL String sql, Object... args) { return findUnique(mapper, query(sql, args)); } /** * Finds a unique result from database, converting the database row to given class using default mechanisms. * * @throws NonUniqueResultException if there are no rows or multiple rows */ public <T> T findUnique(@NotNull Class<T> cl, @NotNull SqlQuery query) { return unique(findAll(cl, query)); } public <T> T findUnique(@NotNull Class<T> cl, @NotNull @SQL String sql, Object... args) { return findUnique(cl, query(sql, args)); } /** * Find a unique result from database, using given {@link RowMapper} to convert row. Returns null if * there are no results. * * @throws NonUniqueResultException if there are multiple result rows */ @Nullable public <T> T findUniqueOrNull(@NotNull RowMapper<T> rowMapper, @NotNull SqlQuery query) { return uniqueOrNull(findAll(rowMapper, query)); } @Nullable public <T> T findUniqueOrNull(@NotNull RowMapper<T> rowMapper, @NotNull @SQL String sql, Object... args) { return findUniqueOrNull(rowMapper, query(sql, args)); } /** * Finds a unique result from database, converting the database row to given class using default mechanisms. * Returns null if there are no results. * * @throws NonUniqueResultException if there are multiple result rows */ @Nullable public <T> T findUniqueOrNull(@NotNull Class<T> cl, @NotNull SqlQuery query) { return uniqueOrNull(findAll(cl, query)); } public <T> T findUniqueOrNull(@NotNull Class<T> cl, @NotNull @SQL String sql, Object... args) { return findUniqueOrNull(cl, query(sql, args)); } /** * A convenience method for retrieving a single non-null integer. */ public int findUniqueInt(@NotNull SqlQuery query) { Integer value = findUnique(Integer.class, query); if (value != null) return value; else throw new UnexpectedResultException("database returned null instead of int"); } /** * A convenience method for retrieving a single non-null integer. */ public int findUniqueInt(@NotNull @SQL String sql, Object... args) { return findUniqueInt(query(sql, args)); } /** * A convenience method for retrieving a single non-null long. */ public long findUniqueLong(@NotNull SqlQuery query) { Long value = findUnique(Long.class, query); if (value != null) return value; else throw new UnexpectedResultException("database returned null instead of long"); } /** * A convenience method for retrieving a single non-null integer. */ public long findUniqueLong(@NotNull @SQL String sql, Object... args) { return findUniqueLong(query(sql, args)); } @NotNull public <K,V> Map<K, V> findMap(@NotNull final Class<K> keyType, @NotNull final Class<V> valueType, @NotNull SqlQuery query) { return executeQuery(new MapResultSetProcessor<K, V>(keyType, valueType, instantiatorRegistry), query); } @NotNull public <K,V> Map<K, V> findMap(@NotNull Class<K> keyType, @NotNull Class<V> valueType, @NotNull @SQL String sql, Object... args) { return findMap(keyType, valueType, query(sql, args)); } /** * Executes a query and creates a {@link ResultTable} from the results. */ @NotNull public ResultTable findTable(@NotNull SqlQuery query) { return executeQuery(new ResultTableResultSetProcessor(), query); } @NotNull public ResultTable findTable(@NotNull @SQL String sql, Object... args) { return findTable(query(sql, args)); } /** * Executes an update against the database and returns the amount of affected rows. */ public int update(@NotNull final SqlQuery query) { return withCurrentTransaction(new TransactionCallback<Integer>() { @Override public Integer execute(TransactionContext tx) throws SQLException { logQuery(query); PreparedStatement ps = tx.getConnection().prepareStatement(query.sql); try { bindArguments(ps, query.args); return ps.executeUpdate(); } finally { ps.close(); } } }); } /** * Executes an update against the database and returns the amount of affected rows. */ public int update(@NotNull @SQL String sql, Object... args) { return update(query(sql, args)); } private void logQuery(@NotNull SqlQuery query) { if (log.isLoggable(Level.FINE)) log.fine("executing query " + query); } private void bindArguments(@NotNull PreparedStatement ps, @NotNull List<?> args) throws SQLException { InstantiatorRegistry instantiatorRegistry = this.instantiatorRegistry; int i = 1; for (Object arg : args) ps.setObject(i++, instantiatorRegistry.valueToDatabase(arg)); } @Nullable private static <T> T uniqueOrNull(@NotNull List<T> items) { switch (items.size()) { case 0: return null; case 1: return items.get(0); default: throw new NonUniqueResultException(items.size()); } } private static <T> T unique(@NotNull List<T> items) { if (items.size() == 1) return items.get(0); else throw new NonUniqueResultException(items.size()); } @NotNull private <T> ResultSetProcessor<List<T>> resultProcessorForClass(@NotNull Class<T> cl) { return new ReflectionResultSetProcessor<T>(cl, instantiatorRegistry); } private static <T> T processResults(@NotNull ResultSet resultSet, @NotNull ResultSetProcessor<T> processor) throws SQLException { try { return processor.process(resultSet); } finally { resultSet.close(); } } /** * Returns a transactional proxy for given object. */ @NotNull public <T> T createTransactionalProxyFor(@NotNull Class<T> iface, @NotNull T target) { return TransactionalProxyFactory.createTransactionalProxyFor(this, iface, target); } /** * Returns the used transaction isolation level, or null for default level. */ @Nullable public Isolation getDefaultIsolation() { return defaultIsolation; } /** * Sets the transaction isolation level to use, or null for default level */ public void setDefaultIsolation(@Nullable Isolation isolation) { this.defaultIsolation = isolation; } public boolean isAllowImplicitTransactions() { return allowImplicitTransactions; } /** * If flag is set to true (by default it's false) queries without active transaction will * not throw exception but will start a fresh transaction. */ public void setAllowImplicitTransactions(boolean allowImplicitTransactions) { this.allowImplicitTransactions = allowImplicitTransactions; } @Override @NotNull public String toString() { return "Database [dialect=" + dialect + ", allowImplicitTransactions=" + allowImplicitTransactions + ", defaultIsolation=" + defaultIsolation + "]"; } }
package alma.COUNTER.CounterConsumerImpl; import java.util.logging.Logger; import alma.ACS.ComponentStates; import alma.ACSErrTypeCommon.CouldntPerformActionEx; import alma.ACSErrTypeCommon.wrappers.AcsJCouldntPerformActionEx; import alma.COUNTER.CounterConsumerOperations; import alma.COUNTER.OnOffStates; import alma.COUNTER.statusBlockEvent; import alma.acs.component.ComponentLifecycle; import alma.acs.component.ComponentLifecycleException; import alma.acs.container.ContainerServices; import alma.acs.nc.AcsEventSubscriber; import alma.acs.util.StopWatch; import alma.acsnc.EventDescription; import alma.maciErrType.wrappers.AcsJComponentCleanUpEx; /** * CounterConsumer is a simple class that connects to the "counter" * notification channel, receives events, and then disconnects from the channel. * @author eallaert */ public class CounterConsumerImpl implements ComponentLifecycle, CounterConsumerOperations, AcsEventSubscriber.Callback<statusBlockEvent> { public static final String PROP_ASSERTION_MESSAGE = "CounterConsumerAssert"; private ContainerServices m_containerServices; private Logger m_logger; private volatile AcsEventSubscriber<statusBlockEvent> subscriber; /** * Total number of events that have been consumed. */ private volatile int eventCount = 0; volatile boolean contFlag = true; // Implementation of ComponentLifecycle @Override public void initialize(ContainerServices containerServices) throws ComponentLifecycleException { m_containerServices = containerServices; m_logger = m_containerServices.getLogger(); m_logger.info("initialize() called..."); } @Override public void execute() { m_logger.info("execute() called..."); } @Override public void cleanUp() throws AcsJComponentCleanUpEx { if (subscriber != null) { m_logger.info("cleanUp() called, disconnecting from channel " + alma.COUNTER.CHANNELNAME_COUNTER.value); StopWatch sw = new StopWatch(); try { subscriber.disconnect(); subscriber = null; } catch (Exception ex) { throw new AcsJComponentCleanUpEx(ex); } long disconnectTimeMillis = sw.getLapTimeMillis(); if (disconnectTimeMillis > 600) { m_logger.info("Suspiciously slow NC disconnect in " + disconnectTimeMillis + " ms."); } } else { m_logger.info("cleanUp() called..., nothing to clean up."); } } @Override public void aboutToAbort() { try { cleanUp(); } catch (AcsJComponentCleanUpEx ex) { ex.printStackTrace(); } // m_logger.info("managed to abort..."); System.out.println("CounterConsumer component managed to abort... you should know this even if the logger did not flush correctly!"); } /** * NC receiver method. */ @Override public void receive(statusBlockEvent someParam, EventDescription eventDescrip) { // Know how many events this instance has received. eventCount++; if (contFlag) { OnOffStates onOff = someParam.onOff; // float onOff = someParam.onOff; String myString = someParam.myString; int counter1 = someParam.counter1; int counter2 = someParam.counter2; int counter3 = someParam.counter3; boolean lastFlag = someParam.flipFlop; float period = someParam.period; // if (!lastFlag) { if (onOff == OnOffStates.ON && !lastFlag) { // m_logger.info("Counter now " + counter1 + " (max " + counter2 + "), flag will flip at " + counter3); // System.out.println("Counter now " + counter1 + " (max " + counter2 + "), flag will flip at " + // counter3); } else { m_logger.info(myString + " received, counter is now " + counter1); System.out.println(myString + " received, counter is now " + counter1); // allow waitTillDone() to return so that this component can be released by the client. contFlag = false; } } } @Override public Class<statusBlockEvent> getEventType() { return statusBlockEvent.class; } // Implementation of ACSComponent @Override public ComponentStates componentState() { return m_containerServices.getComponentStateManager().getCurrentState(); } @Override public String name() { return m_containerServices.getName(); } // Implementation of CounterConsumerOperations /** * @throws CouldntPerformActionEx * @see alma.COUNTER.CounterConsumerOperations#getBlocks() */ @Override public void getBlocks() throws CouldntPerformActionEx { try { subscriber = m_containerServices.createNotificationChannelSubscriber(alma.COUNTER.CHANNELNAME_COUNTER.value, statusBlockEvent.class); //Subscribe to an event type. subscriber.addSubscription(this); //After consumerReady() is invoked, receive(...) is invoked //by the notification channel. That is, we have no control over when //that method is called. subscriber.startReceivingEvents(); m_logger.info("CounterConsumer is ready to receive 'status' events."); } catch (Exception ex) { if (subscriber != null) { try { subscriber.disconnect(); } catch (Exception ex3) { // too bad, but we forward rather the original ex } } AcsJCouldntPerformActionEx ex2 = new AcsJCouldntPerformActionEx(); ex2.setProperty(PROP_ASSERTION_MESSAGE, "failed to connect as an event consumer to channel " + alma.COUNTER.CHANNELNAME_COUNTER.value); throw ex2.toCouldntPerformActionEx(); } return; } /** * @throws CouldntPerformActionEx * @see alma.COUNTER.CounterConsumerOperations#waitTillDone() */ @Override public int waitTillDone() throws CouldntPerformActionEx { if (subscriber == null) { AcsJCouldntPerformActionEx ex = new AcsJCouldntPerformActionEx(); ex.setProperty(PROP_ASSERTION_MESSAGE, "Consumer didn't even start yet"); throw ex.toCouldntPerformActionEx(); } while (contFlag) { try { m_logger.info("CounterConsumer received " + eventCount + " blocks so far ... will sleep 1000 ms more."); Thread.sleep(1000); } catch (Exception e) { } } return eventCount; } }
package de.naoth.rc.dialogs.multiagentconfiguration; import de.naoth.rc.core.dialog.AbstractJFXDialog; import de.naoth.rc.core.dialog.DialogPlugin; import de.naoth.rc.core.dialog.RCDialog; import de.naoth.rc.dialogs.multiagentconfiguration.ui.AgentTab; import de.naoth.rc.dialogs.multiagentconfiguration.ui.AgentTabGlobal; import java.awt.SplashScreen; import java.io.IOException; import java.net.URL; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; import javafx.application.Application; import static javafx.application.Application.launch; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.control.CheckBoxTreeItem; import javafx.scene.control.Tab; import javafx.scene.control.TabPane; import javafx.scene.control.TextField; import javafx.scene.control.ToggleButton; import javafx.scene.image.Image; import javafx.scene.input.KeyCode; import javafx.scene.input.KeyCodeCombination; import javafx.scene.input.KeyCombination; import javafx.stage.Stage; import net.xeoh.plugins.base.annotations.PluginImplementation; /** * * @author Philipp Strobel <philippstrobel@posteo.de> */ public class MultiAgentConfigurationFx extends AbstractJFXDialog { @RCDialog(category = RCDialog.Category.Tools, name = "MultiAgentConfigurationFx") @PluginImplementation public static class Plugin extends DialogPlugin<MultiAgentConfigurationFx> {} @FXML private ToggleButton btn_connect; @FXML private TextField field_ip; @FXML private TextField field_ip_end; @FXML private TextField field_port_start; @FXML private TextField field_port_end; @FXML private TabPane tabpane; private final AgentTabGlobal allTab = new AgentTabGlobal(); @Override protected boolean isSelfController() { return true; } @Override public URL getFXMLRessource() { return getClass().getResource("MultiAgentConfigurationFx.fxml"); } @Override public void afterInit() { // TODO field_ip.disableProperty().bind(btn_connect.selectedProperty()); field_ip_end.disableProperty().bind(btn_connect.selectedProperty()); field_port_start.disableProperty().bind(btn_connect.selectedProperty()); field_port_end.disableProperty().bind(btn_connect.selectedProperty()); btn_connect.selectedProperty().addListener((ov, t, t1) -> { if(t1) { connecting(); allTab.setDisable(false); } else { disconnecting(); allTab.setDisable(true); } }); allTab.setDisable(true); tabpane.getTabs().add(allTab); tabpane.setTabClosingPolicy(TabPane.TabClosingPolicy.UNAVAILABLE); } @Override public Map<KeyCombination, Runnable> getGlobalShortcuts() { HashMap<KeyCombination, Runnable> shortcuts = new HashMap<KeyCombination, Runnable>(); shortcuts.put(new KeyCodeCombination(KeyCode.C, KeyCombination.CONTROL_DOWN, KeyCombination.SHIFT_DOWN), () -> { connect(); }); shortcuts.put(new KeyCodeCombination(KeyCode.D, KeyCombination.ALT_DOWN, KeyCombination.SHIFT_DOWN), () -> { disconnect(); }); return shortcuts; } @FXML public void connect() { btn_connect.selectedProperty().set(true); } private void connecting() { List<String> ip_parts = Arrays.asList(field_ip.getText().trim().split("\\.", -1)); String ip_range = field_ip_end.getText().trim().equals("0") ? ip_parts.get(3) : field_ip_end.getText().trim(); int port_start = Integer.parseInt(field_port_start.getText().trim()); int port_end = Integer.parseInt(field_port_end.getText().trim()); if(ip_range.compareTo(ip_parts.get(3)) < 0 || port_end < port_start) { // TODO: indicate invalid values!? btn_connect.setSelected(false); return; } for (int i = Integer.parseInt(ip_parts.get(3)); i <= Integer.parseInt(ip_range); i++) { String ip = ip_parts.get(0) + "." + ip_parts.get(1) + "." + ip_parts.get(2) + "." + i; for (int port = port_start; port <= port_end; port++) { System.out.println(ip + ":" + port); // System.out.println(tabpane.getTabs()); AgentTab tab = new AgentTab(ip, port); tab.connectDivider(allTab); tab.connectAgentList(allTab); tab.connectButtons(allTab); tabpane.getTabs().add(tab); } } } public void disconnect() { btn_connect.setSelected(false); } private void disconnecting() { // remove all, except the first ("all") tabs while (tabpane.getTabs().size() > 1) { Tab t = tabpane.getTabs().get(tabpane.getTabs().size()-1); if(t instanceof Tab) { ((AgentTab)t).requestClose(); } } System.out.println("disconnect: " + tabpane.getTabs()); } /** * Start method for the standalone MultiAgentConfigurationFx application. * * @param args */ public static void main(String[] args) { launch(MultiAgentConfigurationFxMain.class, args); } /** * The standalone MultiAgentConfigurationFx application class. */ public static class MultiAgentConfigurationFxMain extends Application { @Override public void start(Stage stage) throws Exception { try { FXMLLoader loader = new FXMLLoader(MultiAgentConfigurationFxMain.class.getResource("MultiAgentConfigurationFx.fxml")); MultiAgentConfigurationFx controller = new MultiAgentConfigurationFx(); loader.setController(controller); Parent root = loader.load(); controller.afterInit(); Scene scene = new Scene(root); stage.setScene(scene); stage.setMaximized(true); stage.getIcons().add(new Image(MultiAgentConfigurationFxMain.class.getResourceAsStream("/de/naoth/rc/res/nao-nice.png"))); stage.setTitle("MultiAgentConfigurationFx"); stage.show(); stage.setOnCloseRequest((e) -> { System.exit(0); }); SplashScreen.getSplashScreen().close(); } catch (IOException ex) { Logger.getLogger(MultiAgentConfigurationFxMain.class.getName()).log(Level.SEVERE, null, ex); } } } }
package be.ibridge.kettle.cluster; import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.Authenticator; import java.net.MalformedURLException; import java.net.PasswordAuthentication; import java.net.URL; import java.net.URLConnection; import java.util.List; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.HttpMethod; import org.apache.commons.httpclient.UsernamePasswordCredentials; import org.apache.commons.httpclient.auth.AuthScope; import org.apache.commons.httpclient.methods.ByteArrayRequestEntity; import org.apache.commons.httpclient.methods.GetMethod; import org.apache.commons.httpclient.methods.PutMethod; import org.apache.commons.httpclient.methods.RequestEntity; import org.w3c.dom.Node; import be.ibridge.kettle.core.ChangedFlag; import be.ibridge.kettle.core.Const; import be.ibridge.kettle.core.Encr; import be.ibridge.kettle.core.LogWriter; import be.ibridge.kettle.core.Row; import be.ibridge.kettle.core.SharedObjectInterface; import be.ibridge.kettle.core.XMLHandler; import be.ibridge.kettle.core.exception.KettleDatabaseException; import be.ibridge.kettle.core.util.StringUtil; import be.ibridge.kettle.repository.Repository; import be.ibridge.kettle.www.GetStatusServlet; import be.ibridge.kettle.www.GetTransStatusServlet; import be.ibridge.kettle.www.SlaveServerStatus; import be.ibridge.kettle.www.SlaveServerTransStatus; import be.ibridge.kettle.www.StartTransServlet; import be.ibridge.kettle.www.StopTransServlet; import be.ibridge.kettle.www.WebResult; public class SlaveServer extends ChangedFlag implements Cloneable, SharedObjectInterface { public static final String XML_TAG = "slaveserver"; private static LogWriter log = LogWriter.getInstance(); private String name; private String hostname; private String port; private String username; private String password; private String proxyHostname; private String proxyPort; private String nonProxyHosts; private boolean master; private boolean shared; private long id; public SlaveServer() { id=-1L; } public SlaveServer(String name, String hostname, String port, String username, String password) { this(name, hostname, port, username, password, null, null, null, false); } public SlaveServer(String name, String hostname, String port, String username, String password, String proxyHostname, String proxyPort, String nonProxyHosts, boolean master) { this(); this.name = name; this.hostname = hostname; this.port = port; this.username = username; this.password = password; this.proxyHostname = proxyHostname; this.proxyPort = proxyPort; this.nonProxyHosts = nonProxyHosts; this.master = master; } public SlaveServer(Node slaveNode) { this(); this.name = XMLHandler.getTagValue(slaveNode, "name"); this.hostname = XMLHandler.getTagValue(slaveNode, "hostname"); this.port = XMLHandler.getTagValue(slaveNode, "port"); this.username = XMLHandler.getTagValue(slaveNode, "username"); this.password = Encr.decryptPasswordOptionallyEncrypted( XMLHandler.getTagValue(slaveNode, "password") ); this.proxyHostname = XMLHandler.getTagValue(slaveNode, "proxy_hostname"); this.proxyPort = XMLHandler.getTagValue(slaveNode, "proxy_port"); this.nonProxyHosts = XMLHandler.getTagValue(slaveNode, "non_proxy_hosts"); this.master = "Y".equalsIgnoreCase( XMLHandler.getTagValue(slaveNode, "master") ); } public String getXML() { StringBuffer xml = new StringBuffer(); xml.append("<"+XML_TAG+">"); xml.append(XMLHandler.addTagValue("name", name, false)); xml.append(XMLHandler.addTagValue("hostname", hostname, false)); xml.append(XMLHandler.addTagValue("port", port, false)); xml.append(XMLHandler.addTagValue("username", username, false)); xml.append(XMLHandler.addTagValue("password", Encr.encryptPasswordIfNotUsingVariables(password), false)); xml.append(XMLHandler.addTagValue("proxy_hostname", proxyHostname, false)); xml.append(XMLHandler.addTagValue("proxy_port", proxyPort, false)); xml.append(XMLHandler.addTagValue("non_proxy_hosts", nonProxyHosts, false)); xml.append(XMLHandler.addTagValue("master", master, false)); xml.append("</"+XML_TAG+">"); return xml.toString(); } public void saveRep(Repository rep) throws KettleDatabaseException { saveRep(rep, -1L, false); } public void saveRep(Repository rep, long id_transformation, boolean isUsedByTransformation) throws KettleDatabaseException { setId(rep.getSlaveID(name)); if (getId()<0) { setId(rep.insertSlave(this)); } else { rep.updateSlave(this); } // Save the trans-slave relationship too. if (id_transformation>=0 && isUsedByTransformation) rep.insertTransformationSlave(id_transformation, getId()); } public SlaveServer(Repository rep, long id_slave_server) throws KettleDatabaseException { this(); setId(id_slave_server); Row row = rep.getSlaveServer(id_slave_server); if (row==null) { throw new KettleDatabaseException("Internal repository error: slave server with id "+id_slave_server+" could not be found!"); } name = row.getString("NAME", null); hostname = row.getString("HOST_NAME", null); port = row.getString("PORT", null); username = row.getString("USERNAME", null); password = row.getString("PASSWORD", null); proxyHostname = row.getString("PROXY_HOST_NAME", null); proxyPort = row.getString("PROXY_PORT", null); nonProxyHosts = row.getString("NON_PROXY_HOSTS", null); master = row.getBoolean("MASTER", false); } public Object clone() { SlaveServer slaveServer = new SlaveServer(); slaveServer.replaceMeta(this); return slaveServer; } public void replaceMeta(SlaveServer slaveServer) { this.name = slaveServer.name; this.hostname = slaveServer.hostname; this.port = slaveServer.port; this.username = slaveServer.username; this.password = slaveServer.password; this.proxyHostname = slaveServer.proxyHostname; this.proxyPort = slaveServer.proxyPort; this.nonProxyHosts = slaveServer.nonProxyHosts; this.master = slaveServer.master; this.id = slaveServer.id; this.shared = slaveServer.shared; this.setChanged(true); } public String toString() { return name; } public String getServerAndPort() { String realHostname = StringUtil.environmentSubstitute(hostname); if (!Const.isEmpty(realHostname)) return realHostname+getPortSpecification(); return "Slave Server"; } public boolean equals(Object obj) { SlaveServer slave = (SlaveServer) obj; return name.equalsIgnoreCase(slave.getName()); } public int hashCode() { return name.hashCode(); } public String getHostname() { return hostname; } public void setHostname(String urlString) { this.hostname = urlString; } /** * @return the password */ public String getPassword() { return password; } /** * @param password the password to set */ public void setPassword(String password) { this.password = password; } /** * @return the username */ public String getUsername() { return username; } /** * @param username the username to set */ public void setUsername(String username) { this.username = username; } /** * @return the nonProxyHosts */ public String getNonProxyHosts() { return nonProxyHosts; } /** * @param nonProxyHosts the nonProxyHosts to set */ public void setNonProxyHosts(String nonProxyHosts) { this.nonProxyHosts = nonProxyHosts; } /** * @return the proxyHostname */ public String getProxyHostname() { return proxyHostname; } /** * @param proxyHostname the proxyHostname to set */ public void setProxyHostname(String proxyHostname) { this.proxyHostname = proxyHostname; } /** * @return the proxyPort */ public String getProxyPort() { return proxyPort; } /** * @param proxyPort the proxyPort to set */ public void setProxyPort(String proxyPort) { this.proxyPort = proxyPort; } public String getPortSpecification() { String realPort = StringUtil.environmentSubstitute(port); String portSpec = ":"+realPort; if (Const.isEmpty(realPort) || port.equals("80")) { portSpec=""; } return portSpec; } public String constructUrl(String serviceAndArguments) { String realHostname = StringUtil.environmentSubstitute(hostname); String retval = "http://"+realHostname+getPortSpecification()+serviceAndArguments; retval = Const.replace(retval, " ", "%20"); return retval; } /** * @return the port */ public String getPort() { return port; } /** * @param port the port to set */ public void setPort(String port) { this.port = port; } public String sendXML(String xml, String service) throws Exception { // The content byte[] content = xml.getBytes(Const.XML_ENCODING); // Prepare HTTP put String urlString = constructUrl(service); System.out.println("Connecting to: "+urlString); PutMethod put = new PutMethod(urlString); // Request content will be retrieved directly from the input stream RequestEntity entity = new ByteArrayRequestEntity(content); put.setRequestEntity(entity); put.setDoAuthentication(true); // post.setContentChunked(true); // Get HTTP client HttpClient client = new HttpClient(); addCredentials(client); // Execute request try { int result = client.executeMethod(put); // The status code log.logDebug(toString(), "Response status code: " + result); // the response InputStream inputStream = new BufferedInputStream(put.getResponseBodyAsStream(), 1000); StringBuffer bodyBuffer = new StringBuffer(); int c; while ( (c=inputStream.read())!=-1) bodyBuffer.append((char)c); inputStream.close(); String bodyTmp = bodyBuffer.toString(); switch(result) { case 401: // Security problem: authentication required String message = "Authentication failed"+Const.DOSCR+Const.DOSCR+bodyTmp; WebResult webResult = new WebResult(WebResult.STRING_ERROR, message); bodyBuffer.setLength(0); bodyBuffer.append(webResult.getXML()); break; } String body = bodyBuffer.toString(); // String body = post.getResponseBodyAsString(); log.logDebug(toString(), "Response body: "+body); return body; } finally { // Release current connection to the connection pool once you are done put.releaseConnection(); log.logDetailed(toString(), "Sent XML to service ["+service+"] on host ["+hostname+"]"); } } private void addCredentials(HttpClient client) { client.getState().setCredentials ( new AuthScope(hostname, Const.toInt(StringUtil.environmentSubstitute(port), 80), "Kettle"), new UsernamePasswordCredentials(username, password) ); } /** * @return the master */ public boolean isMaster() { return master; } /** * @param master the master to set */ public void setMaster(boolean master) { this.master = master; } public String execService(String service) throws Exception { // Prepare HTTP get HttpClient client = new HttpClient(); addCredentials(client); HttpMethod method = new GetMethod(constructUrl(service)); // Execute request try { int result = client.executeMethod(method); // The status code log.logDebug(toString(), "Response status code: " + result); // the response InputStream inputStream = new BufferedInputStream(method.getResponseBodyAsStream()); StringBuffer bodyBuffer = new StringBuffer(); int c; while ( (c=inputStream.read())!=-1) { bodyBuffer.append((char)c); } inputStream.close(); String body = bodyBuffer.toString(); log.logDetailed(toString(), "Finished reading "+bodyBuffer.length()+" bytes from server."); log.logDebug(toString(), "Response body: "+body); return body; } finally { // Release current connection to the connection pool once you are done method.releaseConnection(); log.logDetailed(toString(), "Executed service ["+service+"] on host ["+hostname+"]"); } } /** * Contact the server and get back the reply as a string * @return the requested information * @throws Exception in case something goes awry */ public String getContentFromServer(String service) throws Exception { LogWriter log = LogWriter.getInstance(); String urlToUse = constructUrl(service); URL server; StringBuffer result = new StringBuffer(); try { String beforeProxyHost = System.getProperty("http.proxyHost"); String beforeProxyPort = System.getProperty("http.proxyPort"); String beforeNonProxyHosts = System.getProperty("http.nonProxyHosts"); BufferedReader input = null; try { log.logBasic(toString(), "Connecting to URL: "+urlToUse); if (proxyHostname!=null) { System.setProperty("http.proxyHost", proxyHostname); System.setProperty("http.proxyPort", proxyPort); if (nonProxyHosts!=null) System.setProperty("http.nonProxyHosts", nonProxyHosts); } if (username!=null && username.length()>0) { Authenticator.setDefault(new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password!=null ? password.toCharArray() : new char[] {} ); } } ); } // Get a stream for the specified URL server = new URL(urlToUse); URLConnection connection = server.openConnection(); log.logDetailed(toString(), "Start reading reply from webserver."); // Read the result from the server... InputStream inputStream = new BufferedInputStream(connection.getInputStream(), 1000); input = new BufferedReader(new InputStreamReader( inputStream )); long bytesRead = 0L; String line; while ( (line=input.readLine())!=null ) { result.append(line).append(Const.CR); bytesRead+=line.length(); } log.logBasic(toString(), "Finished reading "+bytesRead+" bytes as a response from the webserver"); } catch(MalformedURLException e) { log.logError(toString(), "The specified URL is not valid ["+urlToUse+"] : "+e.getMessage()); log.logError(toString(), Const.getStackTracker(e)); } catch(IOException e) { log.logError(toString(), "I was unable to save the HTTP result to file because of a I/O error: "+e.getMessage()); log.logError(toString(), Const.getStackTracker(e)); } catch(Exception e) { log.logError(toString(), "Error getting file from HTTP : "+e.getMessage()); log.logError(toString(), Const.getStackTracker(e)); } finally { // Close it all try { if (input!=null) input.close(); } catch(Exception e) { log.logError(toString(), "Unable to close streams : "+e.getMessage()); log.logError(toString(), Const.getStackTracker(e)); } } // Set the proxy settings back as they were on the system! System.setProperty("http.proxyHost", Const.NVL(beforeProxyHost, "")); System.setProperty("http.proxyPort", Const.NVL(beforeProxyPort, "")); System.setProperty("http.nonProxyHosts", Const.NVL(beforeNonProxyHosts, "")); // Get the result back... return result.toString(); } catch(Exception e) { throw new Exception("Unable to contact URL ["+urlToUse+"] to get the security reference information.", e); } } public SlaveServerStatus getStatus() throws Exception { String xml = execService(GetStatusServlet.CONTEXT_PATH+"?xml=Y"); return SlaveServerStatus.fromXML(xml); } public SlaveServerTransStatus getTransStatus(String transName) throws Exception { String xml = execService(GetTransStatusServlet.CONTEXT_PATH+"?name="+transName+"&xml=Y"); return SlaveServerTransStatus.fromXML(xml); } public WebResult stopTransformation(String transName) throws Exception { String xml = execService(StopTransServlet.CONTEXT_PATH+"?name="+transName+"&xml=Y"); return WebResult.fromXMLString(xml); } public WebResult startTransformation(String transName) throws Exception { String xml = execService(StartTransServlet.CONTEXT_PATH+"?name="+transName+"&xml=Y"); return WebResult.fromXMLString(xml); } public static SlaveServer findSlaveServer(List slaveServers, String name) { for (int i=0;i<slaveServers.size();i++) { SlaveServer slaveServer = (SlaveServer) slaveServers.get(i); if (slaveServer.getName()!=null && slaveServer.getName().equalsIgnoreCase(name)) return slaveServer; } return null; } public static String[] getSlaveServerNames(List slaveServers) { String[] names = new String[slaveServers.size()]; for (int i=0;i<slaveServers.size();i++) { SlaveServer slaveServer = (SlaveServer) slaveServers.get(i); names[i] = slaveServer.getName(); } return names; } public String getName() { return name; } public void setName(String name) { this.name = name; } public boolean isShared() { return shared; } public void setShared(boolean shared) { this.shared = shared; } public long getId() { return id; } public void setId(long id) { this.id = id; } }
package it.alfrescoinaction.lab.awsi.repository; import it.alfrescoinaction.lab.awsi.domain.Downloadable; import it.alfrescoinaction.lab.awsi.domain.RenditionDownloadable; import it.alfrescoinaction.lab.awsi.domain.SearchFilterItem; import it.alfrescoinaction.lab.awsi.domain.SearchFilters; import it.alfrescoinaction.lab.awsi.exceptions.InvalidParameterException; import it.alfrescoinaction.lab.awsi.exceptions.ObjectNotFoundException; import it.alfrescoinaction.lab.awsi.exceptions.PageNotFoundException; import org.apache.chemistry.opencmis.client.api.*; import org.apache.chemistry.opencmis.client.runtime.util.EmptyItemIterable; import org.apache.chemistry.opencmis.commons.exceptions.CmisInvalidArgumentException; import org.apache.chemistry.opencmis.commons.exceptions.CmisObjectNotFoundException; import org.apache.chemistry.opencmis.commons.exceptions.CmisRuntimeException; import org.apache.chemistry.opencmis.commons.impl.jaxb.CmisException; import org.apache.http.HttpEntity; import org.apache.http.auth.AuthScope; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.client.CredentialsProvider; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.utils.URIBuilder; import org.apache.http.impl.client.BasicCredentialsProvider; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.util.EntityUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.DefaultResourceLoader; import org.springframework.core.io.Resource; import org.springframework.stereotype.Repository; import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.regex.Pattern; @Repository public class AlfrescoCmisRepository implements CmisRepository { @Autowired private RemoteConnection connection; @Value("${alfresco.serverProtocol}") private String alfrescoServerProtocol; @Value("${alfresco.serverUrl}") private String alfrescoServer; @Value("${alfresco.serviceEntryPoint}") private String alfrescoServiceEntryPoint; @Value("${alfresco.sites}") private String alfrescoSites; @Value("${alfresco.doclib}") private String alfrescoDocumentLibrary; @Value("${alfresco.search.type}") private String searchType; @Value("${alfresco.username}") private String username; @Value("${alfresco.password}") private String password; private String siteId; private String alfrescoDocLibPath; @Override public ItemIterable<CmisObject> getCategories() { Session session = connection.getSession(); CmisObject obj = session.getObjectByPath(alfrescoDocLibPath); // procceed only if the node is a folder if (obj.getBaseTypeId().value().equals("cmis:folder")){ Folder folder = (Folder)obj; OperationContext oc = session.createOperationContext(); oc.setRenditionFilterString("*"); ItemIterable<CmisObject> children = folder.getChildren(oc); return children; } else { throw new PageNotFoundException("Home folder not found: " + alfrescoDocLibPath); } } @Override public Folder getFolderById(String id) throws PageNotFoundException { Session session = connection.getSession(); if (id.equals("home")) { OperationContext oc = session.createOperationContext(); oc.setRenditionFilterString("*"); id = session.getObjectByPath(alfrescoDocLibPath, oc).getId(); } CmisObject obj; try { obj = session.getObject(id); } catch(CmisObjectNotFoundException e) { throw new PageNotFoundException(id); } // procceed only if the node is a folder if (obj.getBaseTypeId().value().equals("cmis:folder")){ Folder folder = (Folder)obj; return folder; } else { throw new PageNotFoundException("Folder not found: " + id); } } /** * * @param realtivePath: in the form F1/F2/F3 (no initial /) * @return * @throws PageNotFoundException */ @Override public String getFolderIdByRelativePath(String realtivePath) throws PageNotFoundException { Session session = connection.getSession(); // delete initial / String fullPath = alfrescoDocLibPath; if (realtivePath.startsWith("/")) { fullPath += realtivePath; } else { fullPath += "/" + realtivePath; } CmisObject obj = session.getObjectByPath(fullPath); // procceed only if the node is a folder if (obj.getBaseTypeId().value().equals("cmis:folder")){ return obj.getId(); } else { throw new PageNotFoundException("Folder not found: " + fullPath); } } @Override public Document getDocumentById(String id) throws PageNotFoundException { Session session = connection.getSession(); CmisObject obj; try { OperationContext oc = session.createOperationContext(); oc.setRenditionFilterString("*"); obj = session.getObject(id,oc); } catch (CmisObjectNotFoundException e){ throw new PageNotFoundException("Document not found: " + id); } if (obj.getBaseTypeId().value().equals("cmis:document") || obj.getBaseTypeId().value().equals("D:cm:thumbnail")){ Document doc = (Document)obj; return doc; } else { throw new PageNotFoundException("Document not found: " + id); } } @Override public ItemIterable<QueryResult> getSubFolders(Folder folder) { String queryTemplate = "SELECT F.* FROM cmis:folder F WHERE IN_FOLDER('%s')"; String query = String.format(queryTemplate,folder.getId()); Session session = connection.getSession(); OperationContext oc = session.createOperationContext(); oc.setRenditionFilterString("*"); ItemIterable<QueryResult> children = session.query(query, false, oc); return children; } @Override public ItemIterable<QueryResult> getSubDocuments(Folder folder, Map<String,String> filters) { String query = "SELECT D.* FROM cmis:document D WHERE IN_FOLDER('" + folder.getId() + "') "; Session session = connection.getSession(); OperationContext oc = session.createOperationContext(); oc.setRenditionFilterString("*"); ItemIterable<QueryResult> children = session.query(query, false, oc); return children; } @Override public ItemIterable<QueryResult> search(String folderId, SearchFilters filters) { String queryFilters = ""; String queryFilterTemplateTEXT = "AND %s LIKE '%s' "; String queryFilterTemplateDATEFROM = "AND %s >= TIMESTAMP '%sT00:00:00.000+00:00' "; String queryFilterTemplateDATETO = "AND %s <= TIMESTAMP '%sT00:00:00.000+00:00' "; String queryFilterTemplateDATE = "AND %s = TIMESTAMP '%sT00:00:00.000+00:00' "; String queryFilterTemplateNUM = "AND %s = %d"; String queryFilterTemplateNUM_MIN = "AND %s >= %d"; String queryFilterTemplateNUM_MAX = "AND %s <= %d"; String queryFilterTemplateFULLTEXT = "AND CONTAINS('\\'%s\\'')"; List <SearchFilterItem> filterItems = filters.getFilterItems(); for (SearchFilterItem filter : filterItems) { if (!filter.getContent().isEmpty()) { switch (filter.getType()) { case "TEXT": { queryFilters += String.format(queryFilterTemplateTEXT, filter.getId(), filter.getContent()); break; } case "%TEXT": { queryFilters += String.format(queryFilterTemplateTEXT, filter.getId(), "%" + filter.getContent()); break; } case "TEXT%": { queryFilters += String.format(queryFilterTemplateTEXT, filter.getId(), filter.getContent() + "%"); break; } case "%TEXT%": { queryFilters += String.format(queryFilterTemplateTEXT, filter.getId(), "%" + filter.getContent() + "%"); break; } case "DATE": { queryFilters += String.format(queryFilterTemplateDATE, filter.getId(), filter.getContent()); break; } case "DATE_FROM": { String formattedDate = this.getFormattedDate (filter.getContent(), filter.getType()); if (!formattedDate.isEmpty()) { queryFilters += String.format(queryFilterTemplateDATEFROM, filter.getId(), formattedDate); } break; } case "DATE_TO": { String formattedDate = this.getFormattedDate (filter.getContent(), filter.getType()); if (!formattedDate.isEmpty()) { queryFilters += String.format(queryFilterTemplateDATETO, filter.getId(), formattedDate); } break; } // always the last item case "FULLTEXT": { queryFilters += String.format(queryFilterTemplateFULLTEXT, filter.getContent()); } } } } // check if at least 1 field is valid (otherwise all the repository will be searched) if (queryFilters.isEmpty()) { return new EmptyItemIterable<>(); } String [] typeParts = searchType.split("\\|"); String typeName = typeParts[1] != null?typeParts[1]:"cmis:document"; String queryTemplate = "SELECT * FROM %s WHERE IN_TREE('workspace://SpacesStore/%s') %s AND cmis:name <> '.*'"; String query = String.format(queryTemplate, typeName, folderId, queryFilters); Session session = connection.getSession(); OperationContext oc = session.createOperationContext(); oc.setRenditionFilterString("*"); ItemIterable<QueryResult> children; try { children = session.query(query, false, oc); // if the query is invalid, the following row throws an exception children.getTotalNumItems(); } catch (Exception e) { children = new EmptyItemIterable<>(); } return children; } @Override public boolean isHomePage(String path) { return alfrescoDocLibPath.equals(path); } @Override public Map<String,String> getSiteInfo() { Session session = connection.getSession(); CmisObject cmiso = session.getObjectByPath(alfrescoSites + "/" + siteId); Map<String,String> siteInfo = new HashMap<>(2); siteInfo.put("name",cmiso.getProperty("cm:title").getValue().toString()); siteInfo.put("description",cmiso.getProperty("cm:description").getValue().toString()); return siteInfo; } public Downloadable getRendition(String type, String objectId, String name) throws ObjectNotFoundException { // I'm not using cmis because it doesn't trigger the thumbnail generetion process // The rest service generate the thumbnauk or eventually return the default placeholder CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password)); try (CloseableHttpClient httpclient = HttpClientBuilder.create().setDefaultCredentialsProvider(credentialsProvider).build()) { String alfrescoServerUrl = alfrescoServer; String requestPath = alfrescoServiceEntryPoint + "/api/node/workspace/SpacesStore/" + objectId + "/content/thumbnails/" + type; URI uri = new URIBuilder() .setScheme("http") .setHost(alfrescoServerUrl) .setPath(requestPath) .setParameter("c", "force") .setParameter("ph", "true") .build(); HttpGet httpget = new HttpGet(uri); try (CloseableHttpResponse response = httpclient.execute(httpget)) { HttpEntity entity = response.getEntity(); RenditionDownloadable rend; //TODO replace magic number if (entity.getContentLength() < 1024*1024 || entity.getContentLength() > 0) { byte[] buffer = EntityUtils.toByteArray(entity); // byte[] buffer = new byte[((Long)entity.getContentLength()).intValue()]; // entity.getContent().read(buffer); String mimetype = entity.getContentType().getValue(); rend = new RenditionDownloadable(name, buffer, entity.getContentLength(), mimetype); return rend; } else { httpget.abort(); throw new Exception("Content 0 or too large "); } } } catch (Exception e) { //TODO manage exception throw new ObjectNotFoundException(e.getMessage()); } } public String getAlfrescoDocLibPath() { return alfrescoDocLibPath; } @Override public void setSite(String siteId) { this.siteId = siteId; this.alfrescoDocLibPath = "/" + alfrescoSites + "/" + siteId + "/" + alfrescoDocumentLibrary; } private String getFormattedDate(String date, String type) { String formattedDate = ""; if (date.length() == 4) { // it's only the year if ("DATE_TO".equals(type)){ formattedDate = date + "-12-31"; } else { formattedDate = date + "-01-01"; } } else if (date.length() == 10) { String [] datePart = date.split("\\-"); if (datePart.length == 3) { formattedDate = datePart[2]+"-"+datePart[1]+"-"+datePart[0]; } } return formattedDate; } private boolean validateInput(String input, String type) { switch (type) { case "DATE": { //^(\d\d?-\d\d?-[1-2]\d{3})$|^([1-2]\d{3})$ Pattern p = Pattern.compile(""); } } return false; } }
package be.ibridge.kettle.core; import java.util.ArrayList; import java.util.Hashtable; import java.util.List; import java.util.Map; /** * This class is a container for "Local" enrvironment variables. * This is a singleton. We are going to launch jobs using a customer classloader. * This will make the variables inside it local. * * @author Matt */ public class LocalVariables { ThreadLocal local; private static LocalVariables localVariables; private Map map; /** * Create a new KettleVariables variable map in the local variables map for the specified thread. * @param localThread The local thread to attach to * @param parentThread The parent thread, null if there is no parent thread. The initial value of the variables will be taken from the variables that are attached to this thread. * @param sameNamespace true if you want to use the same namespace as the parent (if any) or false if you want to use a new namespace, create a new KettleVariables object. */ public KettleVariables createKettleVariables(String localThread, String parentThread, boolean sameNamespace) { if (localThread.equals("Thread[Thread-1,5,main]")) { new Exception().printStackTrace(); } if (parentThread!=null && parentThread.equals(localThread)) { throw new RuntimeException("local thread can't be the same as the parent thread!"); } // See if the thread already has an entry in the map KettleVariables vars = new KettleVariables(localThread, parentThread); // Copy the initial values from the parent thread if it is specified if (parentThread!=null) { KettleVariables initialValue = getKettleVariables(parentThread); if (initialValue!=null) { if (sameNamespace) { vars = new KettleVariables(localThread, parentThread); vars.setProperties(initialValue.getProperties()); } else { vars.putAll(initialValue.getProperties()); } } else { throw new RuntimeException("No parent Kettle Variables found for thread ["+parentThread+"], local thread is ["+localThread+"]"); } } // Before we add this, for debugging, just see if we're not overwriting anything. // Overwriting is a big No-No KettleVariables checkVars = (KettleVariables) map.get(localThread); if (checkVars!=null) { // throw new RuntimeException("There are already variables in the local variables map for ["+localThread+"]"); } // Put this one in the map, attached to the local thread map.put(localThread, vars); return vars; } public LocalVariables() { map = new Hashtable(); } public static final LocalVariables getInstance() { if (localVariables==null) // Not the first time we call this, see if we have properties for this thread { // System.out.println("Init of new local variables object"); localVariables = new LocalVariables(); } return localVariables; } public Map getMap() { return map; } public static final KettleVariables getKettleVariables() { return getInstance().getVariables(Thread.currentThread().getName()); } public static final KettleVariables getKettleVariables(String thread) { return getInstance().getVariables(thread); } /** * Find the KettleVariables in the map, attached to the specified Thread. * This is not singleton stuff, we return null in case we don't have anything attached to the current thread. * That makes it easier to find the "missing links" * @param localThread The thread to look for * @return The KettleVariables attached to the specified thread. */ private KettleVariables getVariables(String localThread) { KettleVariables kettleVariables = (KettleVariables) map.get(localThread); return kettleVariables; } public void removeKettleVariables(String thread) { if (thread==null) return; removeKettleVariables(thread, 1); } /** * Remove all KettleVariables objects in the map, including the one for this thread, but also the ones with this thread as parent, etc. * @param thread the grand-parent thread to look for to remove */ private void removeKettleVariables(String thread, int level) { LogWriter log = LogWriter.getInstance(); List children = getKettleVariablesWithParent(thread); for (int i=0;i<children.size();i++) { String child = (String)children.get(i); removeKettleVariables(child, level+1); } // See if it was in there in the first place... if (map.get(thread)==null) { // We should not ever arrive here... log.logError("LocalVariables!!!!!!!", "The variables you are trying to remove, do not exist for thread ["+thread+"]"); log.logError("LocalVariables!!!!!!!", "Please report this error to the Kettle developers."); } else { map.remove(thread); } } private List getKettleVariablesWithParent(String parentThread) { List children = new ArrayList(); List values = new ArrayList(map.values()); for (int i=0;i<values.size();i++) { KettleVariables kv = (KettleVariables)values.get(i); if (kv.getParentThread()!=null && kv.getParentThread().equals(parentThread)) { if (kv.getLocalThread().equals(parentThread)) { System.out.println("---> !!!! This should not happen! Thread ["+parentThread+"] is linked to itself!"); } else { children.add(kv.getLocalThread()); } } } return children; } }
package beast.app.treeannotator; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.io.PrintStream; import java.util.ArrayList; import java.util.Arrays; import java.util.BitSet; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.SortedSet; import javax.swing.JFrame; import beast.app.BEASTVersion; import beast.app.beauti.BeautiDoc; import beast.app.tools.LogCombiner; import beast.app.util.Arguments; import beast.core.util.Log; import beast.evolution.alignment.TaxonSet; import beast.evolution.tree.Node; import beast.evolution.tree.Tree; import beast.evolution.tree.TreeUtils; import beast.math.statistic.DiscreteStatistics; import beast.util.CollectionUtils; import beast.util.HeapSort; import beast.util.NexusParser; import beast.util.TreeParser; import jam.console.ConsoleApplication; //import org.rosuda.JRI.REXP; //import org.rosuda.JRI.RVector; //import org.rosuda.JRI.Rengine; /** * @author Alexei Drummond * @author Andrew Rambaut * * TreeAnnotator ported from BEAST 1 */ public class TreeAnnotator { private final static BEASTVersion version = new BEASTVersion(); private final static boolean USE_R = false; private static boolean forceIntegerToDiscrete = false; private boolean SAmode = false; abstract class TreeSet { abstract boolean hasNext(); abstract Tree next() throws IOException; abstract void reset() throws IOException; } class FastTreeSet extends TreeSet { int current = 0; Tree [] trees; public FastTreeSet(String inputFileName, int burninPercentage) throws IOException { progressStream.println("0 25 50 75 100"); progressStream.println("| TreeSetParser parser = new TreeSetParser(burninPercentage, false); Node [] roots = parser.parseFile(inputFileName); trees = new Tree[roots.length]; int i = 0; for (Node root : roots) { trees[i++] = new Tree(root); } } @Override boolean hasNext() { return current < trees.length; } @Override Tree next() { return trees[current++]; } @Override void reset() { current = 0; } } class MemoryFriendlyTreeSet extends TreeSet { // Tree [] trees; int current = 0; int lineNr; public Map<String, String> translationMap = null; public List<String> taxa; int burninCount = 0; int totalTrees = 0; boolean isNexus = true; BufferedReader fin; String inputFileName; // label count origin for NEXUS trees int origin = -1; MemoryFriendlyTreeSet(String inputFileName, int burninPercentage) throws IOException { this.inputFileName = inputFileName; init(burninPercentage); progressStream.println("Processing " + (totalTrees - burninCount) + " trees from file" + (burninPercentage > 0 ? " after ignoring first " + burninPercentage + "% = " + burninCount + " trees." : ".")); } /** determine number of trees in the file, * and number of trees to skip as burnin * @throws IOException * @throws FileNotFoundException **/ private void init(int burninPercentage) throws IOException { fin = new BufferedReader(new FileReader(new File(inputFileName))); if (!fin.ready()) { throw new IOException("File appears empty"); } String str = nextLine(); if (!str.toUpperCase().trim().startsWith("#NEXUS")) { // the file contains a list of Newick trees instead of a list in Nexus format isNexus = false; if (str.trim().length() > 0) { totalTrees = 1; } } while (fin.ready()) { str = nextLine(); if (isNexus) { if (str.trim().toLowerCase().startsWith("tree ")) { totalTrees++; } } else if (str.trim().length() > 0) { totalTrees++; } } fin.close(); burninCount = Math.max(0, (burninPercentage * totalTrees)/100); } @Override void reset() throws FileNotFoundException { current = 0; fin = new BufferedReader(new FileReader(new File(inputFileName))); lineNr = 0; try { while (fin.ready()) { final String str = nextLine(); if (str == null) { return; } final String lower = str.toLowerCase(); if (lower.matches("^\\s*begin\\s+trees;\\s*$")) { parseTreesBlock(); return; } } } catch (Exception e) { e.printStackTrace(); throw new RuntimeException("Around line " + lineNr + "\n" + e.getMessage()); } } // parseFile /** * read next line from Nexus file that is not a comment and not empty * @throws IOException * */ String nextLine() throws IOException { String str = readLine(); if (str == null) { return null; } if (str.contains("[")) { final int start = str.indexOf('['); int end = str.indexOf(']', start); while (end < 0) { str += readLine(); end = str.indexOf(']', start); } str = str.substring(0, start) + str.substring(end + 1); if (str.matches("^\\s*$")) { return nextLine(); } } if (str.matches("^\\s*$")) { return nextLine(); } return str; } /** * read line from nexus file * */ String readLine() throws IOException { if (!fin.ready()) { return null; } lineNr++; return fin.readLine(); } private void parseTreesBlock() throws IOException { // read to first non-empty line within trees block String str = fin.readLine().trim(); while (str.equals("")) { str = fin.readLine().trim(); } // if first non-empty line is "translate" then parse translate block if (str.toLowerCase().contains("translate")) { translationMap = parseTranslateBlock(); origin = getIndexedTranslationMapOrigin(translationMap); if (origin != -1) { taxa = getIndexedTranslationMap(translationMap, origin); } } // we got to the end of the translate block // read bunrinCount trees current = 0; while (current < burninCount && fin.ready()) { str = nextLine(); if (str.toLowerCase().startsWith("tree ")) { current++; } } } private List<String> getIndexedTranslationMap(final Map<String, String> translationMap, final int origin) { //System.out.println("translation map size = " + translationMap.size()); final String[] taxa = new String[translationMap.size()]; for (final String key : translationMap.keySet()) { taxa[Integer.parseInt(key) - origin] = translationMap.get(key); } return Arrays.asList(taxa); } /** * @param translationMap * @return minimum key value if keys are a contiguous set of integers starting from zero or one, -1 otherwise */ private int getIndexedTranslationMapOrigin(final Map<String, String> translationMap) { final SortedSet<Integer> indices = new java.util.TreeSet<>(); int count = 0; for (final String key : translationMap.keySet()) { final int index = Integer.parseInt(key); indices.add(index); count += 1; } if ((indices.last() - indices.first() == count - 1) && (indices.first() == 0 || indices.first() == 1)) { return indices.first(); } return -1; } /** * @return a map of taxa translations, keys are generally integer node number starting from 1 * whereas values are generally descriptive strings. * @throws IOException */ private Map<String, String> parseTranslateBlock() throws IOException { final Map<String, String> translationMap = new HashMap<>(); String line = readLine(); final StringBuilder translateBlock = new StringBuilder(); while (line != null && !line.trim().toLowerCase().equals(";")) { translateBlock.append(line.trim()); line = readLine(); } final String[] taxaTranslations = translateBlock.toString().split(","); for (final String taxaTranslation : taxaTranslations) { final String[] translation = taxaTranslation.split("[\t ]+"); if (translation.length == 2) { translationMap.put(translation[0], translation[1]); // System.out.println(translation[0] + " -> " + translation[1]); } else { Log.err.println("Ignoring translation:" + Arrays.toString(translation)); } } return translationMap; } @Override boolean hasNext() { return current < totalTrees; } @Override Tree next() throws IOException { String str = nextLine(); if (!isNexus) { TreeParser treeParser; if (origin != -1) { treeParser = new TreeParser(taxa, str, origin, false); } else { try { treeParser = new TreeParser(taxa, str, 0, false); } catch (ArrayIndexOutOfBoundsException e) { treeParser = new TreeParser(taxa, str, 1, false); } } return treeParser; } // read trees from NEXUS file if (str.toLowerCase().startsWith("tree ")) { current++; final int i = str.indexOf('('); if (i > 0) { str = str.substring(i); } TreeParser treeParser; if (origin != -1) { treeParser = new TreeParser(taxa, str, origin, false); } else { try { treeParser = new TreeParser(taxa, str, 0, false); } catch (ArrayIndexOutOfBoundsException e) { treeParser = new TreeParser(taxa, str, 1, false); } } if (translationMap != null) treeParser.translateLeafIds(translationMap); return treeParser; } return null; } } TreeSet treeSet; enum Target { MAX_CLADE_CREDIBILITY("Maximum clade credibility tree"), MAX_SUM_CLADE_CREDIBILITY("Maximum sum of clade credibilities"), USER_TARGET_TREE("User target tree"); String desc; Target(String s) { desc = s; } @Override public String toString() { return desc; } } enum HeightsSummary { CA_HEIGHTS("Common Ancestor heights"), MEDIAN_HEIGHTS("Median heights"), MEAN_HEIGHTS("Mean heights"), KEEP_HEIGHTS("Keep target heights"); String desc; HeightsSummary(String s) { desc = s; } @Override public String toString() { return desc; } } // Messages to stderr, output to stdout private static PrintStream progressStream = Log.err; // private final String location1Attribute = "longLat1"; // private final String location2Attribute = "longLat2"; // private final String locationOutputAttribute = "location"; public TreeAnnotator() { } public TreeAnnotator(final int burninPercentage, boolean lowMemory, // allowSingleChild was defunct (always set to false), now replaced by flag to say how much HeightsSummary heightsOption, double posteriorLimit, double hpd2D, Target targetOption, String targetTreeFileName, String inputFileName, String outputFileName ) throws IOException { this.posteriorLimit = posteriorLimit; this.hpd2D = hpd2D; attributeNames.add("height"); attributeNames.add("length"); CladeSystem cladeSystem = new CladeSystem(); totalTrees = 10000; totalTreesUsed = 0; //progressStream.println("Reading trees (bar assumes 10,000 trees)..."); int stepSize = Math.max(totalTrees / 60, 1); try { if (lowMemory) { treeSet = new MemoryFriendlyTreeSet(inputFileName, burninPercentage); } else { treeSet = new FastTreeSet(inputFileName, burninPercentage); } } catch (Exception e) { e.printStackTrace(); Log.err.println("Error Parsing Input Tree: " + e.getMessage()); return; } if (targetOption != Target.USER_TARGET_TREE) { try { treeSet.reset(); while (treeSet.hasNext()) { Tree tree = treeSet.next(); tree.getLeafNodeCount(); if (tree.getDirectAncestorNodeCount() > 0 && !SAmode) { SAmode = true; Log.err.println("A tree with a sampled ancestor is found. Turning on\n the sampled ancestor " + "summary analysis."); if (heightsOption == HeightsSummary.CA_HEIGHTS) { throw new RuntimeException("The common ancestor height is not \n available for trees with sampled " + "ancestors. Please choose \n another height summary option"); } } cladeSystem.add(tree, false); totalTreesUsed++; } totalTrees = totalTreesUsed * 100 / (100-Math.max(burninPercentage, 0)); } catch (Exception e) { Log.err.println(e.getMessage()); return; } progressStream.println(); progressStream.println(); if (totalTrees < 1) { Log.err.println("No trees"); return; } if (totalTreesUsed <= 1) { if (burninPercentage > 0) { Log.err.println("No trees to use: burnin too high"); return; } } cladeSystem.calculateCladeCredibilities(totalTreesUsed); progressStream.println("Total trees have " + totalTrees + ", where " + totalTreesUsed + " are used."); // if (burninPercentage > 0) { // progressStream.println("Ignoring first " + burninPercentage + "% trees."); progressStream.println("Total unique clades: " + cladeSystem.getCladeMap().keySet().size()); progressStream.println(); } Tree targetTree = null; switch (targetOption) { case USER_TARGET_TREE: { if (targetTreeFileName != null) { progressStream.println("Reading user specified target tree, " + targetTreeFileName); String tree = BeautiDoc.load(targetTreeFileName); if (tree.startsWith("#NEXUS")) { NexusParser parser2 = new NexusParser(); parser2.parseFile(new File(targetTreeFileName)); targetTree = parser2.trees.get(0); } else { try { TreeParser parser2 = new TreeParser(); parser2.initByName("IsLabelledNewick", true, "newick", tree); targetTree = parser2; } catch (Exception e) { Log.err.println("Error Parsing Target Tree: " + e.getMessage()); return; } } } else { Log.err.println("No user target tree specified."); return; } break; } case MAX_CLADE_CREDIBILITY: { progressStream.println("Finding maximum credibility tree..."); targetTree = summarizeTrees(cladeSystem, false).copy(); break; } case MAX_SUM_CLADE_CREDIBILITY: { progressStream.println("Finding maximum sum clade credibility tree..."); targetTree = summarizeTrees(cladeSystem, true).copy(); break; } } progressStream.println("Collecting node information..."); progressStream.println("0 25 50 75 100"); progressStream.println("| stepSize = Math.max(totalTrees / 60, 1); int reported = 0; // this call increments the clade counts and it shouldn't // this is remedied with removeClades call after while loop below cladeSystem = new CladeSystem(targetTree); totalTreesUsed = 0; try { int counter = 0; treeSet.reset(); while (treeSet.hasNext()) { Tree tree = treeSet.next(); if (counter == 0) { setupAttributes(tree); } cladeSystem.collectAttributes(tree, attributeNames); if (counter > 0 && counter % stepSize == 0 && reported < 61) { progressStream.print("*"); progressStream.flush(); reported++; } totalTreesUsed++; counter++; } cladeSystem.removeClades(targetTree.getRoot(), true); //progressStream.println("totalTreesUsed=" + totalTreesUsed); cladeSystem.calculateCladeCredibilities(totalTreesUsed); } catch (Exception e) { Log.err.println("Error Parsing Input Tree: " + e.getMessage()); return; } progressStream.println(); progressStream.println(); progressStream.println("Annotating target tree..."); try { annotateTree(cladeSystem, targetTree.getRoot(), null, heightsOption); if( heightsOption == HeightsSummary.CA_HEIGHTS ) { setTreeHeightsByCA(targetTree); } } catch (Exception e) { e.printStackTrace(); Log.err.println("Error to annotate tree: " + e.getMessage() + "\nPlease check the tree log file format."); return; } progressStream.println("Writing annotated tree...."); processMetaData(targetTree.getRoot()); try { final PrintStream stream = outputFileName != null ? new PrintStream(new FileOutputStream(outputFileName)) : System.out; targetTree.init(stream); stream.println(); stream.print("tree TREE1 = "); int[] dummy = new int[1]; String newick = targetTree.getRoot().toSortedNewick(dummy, true); stream.print(newick); stream.println(";"); // stream.println(targetTree.getRoot().toShortNewick(false)); // stream.println(); targetTree.close(stream); stream.println(); } catch (Exception e) { Log.err.println("Error to write annotated tree file: " + e.getMessage()); return; } } private void processMetaData(Node node) { for (Node child : node.getChildren()) { processMetaData(child); } Set<String> metaDataNames = node.getMetaDataNames(); if (metaDataNames != null) { String metadata = ""; for (String name : metaDataNames) { Object value = node.getMetaData(name); metadata += name + "="; if (value instanceof Object[]) { Object [] values = (Object[]) value; metadata += "{"; for (int i = 0; i < values.length; i++) { metadata += values[i].toString(); if (i < values.length - 1) { metadata += ","; } } metadata += "}"; } else { metadata += value.toString(); } metadata += ","; } metadata = metadata.substring(0, metadata.length() - 1); node.metaDataString = metadata; } } private void setupAttributes(Tree tree) { for (int i = 0; i < tree.getNodeCount(); i++) { Node node = tree.getNode(i); Set<String> iter = node.getMetaDataNames(); if (iter != null) { for (String name : iter) { attributeNames.add(name); } } } for (TreeAnnotationPlugin beastObject : beastObjects) { Set<String> claimed = beastObject.setAttributeNames(attributeNames); attributeNames.removeAll(claimed); } } private Tree summarizeTrees(CladeSystem cladeSystem, boolean useSumCladeCredibility) throws IOException { Tree bestTree = null; double bestScore = Double.NEGATIVE_INFINITY; progressStream.println("Analyzing " + totalTreesUsed + " trees..."); progressStream.println("0 25 50 75 100"); progressStream.println("| int stepSize = Math.max(totalTrees / 60, 1); int reported = 0; int counter = 0; treeSet.reset(); while (treeSet.hasNext()) { Tree tree = treeSet.next(); double score = scoreTree(tree, cladeSystem, useSumCladeCredibility); if (score > bestScore) { bestTree = tree; bestScore = score; } if (counter > 0 && counter % stepSize == 0 && reported < 61) { progressStream.print("*"); progressStream.flush(); reported++; } counter++; } progressStream.println(); progressStream.println(); if (useSumCladeCredibility) { progressStream.println("Highest Sum Clade Credibility: " + bestScore); } else { progressStream.println("Highest Log Clade Credibility: " + bestScore); } return bestTree; } public double scoreTree(Tree tree, CladeSystem cladeSystem, boolean useSumCladeCredibility) { if (useSumCladeCredibility) { return cladeSystem.getSumCladeCredibility(tree.getRoot(), null); } else { return cladeSystem.getLogCladeCredibility(tree.getRoot(), null); } } private void annotateTree(CladeSystem cladeSystem, Node node, BitSet bits, HeightsSummary heightsOption) { BitSet bits2 = new BitSet(); if (node.isLeaf()) { int index = cladeSystem.getTaxonIndex(node); bits2.set(2*index); annotateNode(cladeSystem, node, bits2, true, heightsOption); } else { for (int i = 0; i < node.getChildCount(); i++) { Node node1 = node.getChild(i); annotateTree(cladeSystem, node1, bits2, heightsOption); } for (int i=1; i<bits2.length(); i=i+2) { bits2.set(i, false); } if (node.isFake()) { int index = cladeSystem.getTaxonIndex(node.getDirectAncestorChild()); bits2.set(2 * index + 1); } annotateNode(cladeSystem, node, bits2, false, heightsOption); } if (bits != null) { bits.or(bits2); } } private void annotateNode(CladeSystem cladeSystem, Node node, BitSet bits, boolean isTip, HeightsSummary heightsOption) { CladeSystem.Clade clade = cladeSystem.cladeMap.get(bits); assert clade != null : "Clade missing?"; boolean filter = false; if (!isTip) { final double posterior = clade.getCredibility(); node.setMetaData("posterior", posterior); if (posterior < posteriorLimit) { filter = true; } } int i = 0; for (String attributeName : attributeNames) { if (clade.attributeValues != null && clade.attributeValues.size() > 0) { double[] values = new double[clade.attributeValues.size()]; HashMap<Object, Integer> hashMap = new HashMap<>(); Object[] v = clade.attributeValues.get(0); if (v[i] != null) { final boolean isHeight = attributeName.equals("height"); boolean isBoolean = v[i] instanceof Boolean; boolean isDiscrete = v[i] instanceof String; if (forceIntegerToDiscrete && v[i] instanceof Integer) isDiscrete = true; double minValue = Double.MAX_VALUE; double maxValue = -Double.MAX_VALUE; final boolean isArray = v[i] instanceof Object[]; boolean isDoubleArray = isArray && ((Object[]) v[i])[0] instanceof Double; // This is Java, friends - first value type does not imply all. if (isDoubleArray) { for (Object n : (Object[]) v[i]) { if (!(n instanceof Double)) { isDoubleArray = false; break; } } } // todo Handle other types of arrays double[][] valuesArray = null; double[] minValueArray = null; double[] maxValueArray = null; int lenArray = 0; if (isDoubleArray) { lenArray = ((Object[]) v[i]).length; valuesArray = new double[lenArray][clade.attributeValues.size()]; minValueArray = new double[lenArray]; maxValueArray = new double[lenArray]; for (int k = 0; k < lenArray; k++) { minValueArray[k] = Double.MAX_VALUE; maxValueArray[k] = -Double.MAX_VALUE; } } for (int j = 0; j < clade.attributeValues.size(); j++) { Object value = clade.attributeValues.get(j)[i]; if (isDiscrete) { final Object s = value; if (hashMap.containsKey(s)) { hashMap.put(s, hashMap.get(s) + 1); } else { hashMap.put(s, 1); } } else if (isBoolean) { values[j] = (((Boolean) value) ? 1.0 : 0.0); } else if (isDoubleArray) { // Forcing to Double[] causes a cast exception. MAS try { Object[] array = (Object[]) value; for (int k = 0; k < lenArray; k++) { valuesArray[k][j] = ((Double) array[k]); if (valuesArray[k][j] < minValueArray[k]) minValueArray[k] = valuesArray[k][j]; if (valuesArray[k][j] > maxValueArray[k]) maxValueArray[k] = valuesArray[k][j]; } } catch (Exception e) { // ignore } } else { // Ignore other (unknown) types if (value instanceof Number) { values[j] = ((Number) value).doubleValue(); if (values[j] < minValue) minValue = values[j]; if (values[j] > maxValue) maxValue = values[j]; } } } if (isHeight) { if (heightsOption == HeightsSummary.MEAN_HEIGHTS) { final double mean = DiscreteStatistics.mean(values); if (node.isDirectAncestor()) { node.getParent().setHeight(mean); } if (node.isFake()) { node.getDirectAncestorChild().setHeight(mean); } node.setHeight(mean); } else if (heightsOption == HeightsSummary.MEDIAN_HEIGHTS) { final double median = DiscreteStatistics.median(values); if (node.isDirectAncestor()) { node.getParent().setHeight(median); } if (node.isFake()) { node.getDirectAncestorChild().setHeight(median); } node.setHeight(median); } else { // keep the existing height } } if (!filter) { boolean processed = false; for (TreeAnnotationPlugin beastObject : beastObjects) { if (beastObject.handleAttribute(node, attributeName, values)) { processed = true; } } if (!processed) { if (!isDiscrete) { if (!isDoubleArray) annotateMeanAttribute(node, attributeName, values); else { for (int k = 0; k < lenArray; k++) { annotateMeanAttribute(node, attributeName + (k + 1), valuesArray[k]); } } } else { annotateModeAttribute(node, attributeName, hashMap); annotateFrequencyAttribute(node, attributeName, hashMap); } if (!isBoolean && minValue < maxValue && !isDiscrete && !isDoubleArray) { // Basically, if it is a boolean (0, 1) then we don't need the distribution information // Likewise if it doesn't vary. annotateMedianAttribute(node, attributeName + "_median", values); annotateHPDAttribute(node, attributeName + "_95%_HPD", 0.95, values); annotateRangeAttribute(node, attributeName + "_range", values); } if (isDoubleArray) { String name = attributeName; // todo // if (name.equals(location1Attribute)) { // name = locationOutputAttribute; boolean want2d = processBivariateAttributes && lenArray == 2; if (name.equals("dmv")) { // terrible hack want2d = false; } for (int k = 0; k < lenArray; k++) { if (minValueArray[k] < maxValueArray[k]) { annotateMedianAttribute(node, name + (k + 1) + "_median", valuesArray[k]); annotateRangeAttribute(node, name + (k + 1) + "_range", valuesArray[k]); if (!want2d) annotateHPDAttribute(node, name + (k + 1) + "_95%_HPD", 0.95, valuesArray[k]); } } // 2D contours if (want2d) { boolean variationInFirst = (minValueArray[0] < maxValueArray[0]); boolean variationInSecond = (minValueArray[1] < maxValueArray[1]); if (variationInFirst && !variationInSecond) annotateHPDAttribute(node, name + "1" + "_95%_HPD", 0.95, valuesArray[0]); if (variationInSecond && !variationInFirst) annotateHPDAttribute(node, name + "2" + "_95%_HPD", 0.95, valuesArray[1]); if (variationInFirst && variationInSecond) annotate2DHPDAttribute(node, name, "_" + (int) (100 * hpd2D) + "%HPD", hpd2D, valuesArray); } } } } } } i++; } } private void annotateMeanAttribute(Node node, String label, double[] values) { double mean = DiscreteStatistics.mean(values); node.setMetaData(label, mean); } private void annotateMedianAttribute(Node node, String label, double[] values) { double median = DiscreteStatistics.median(values); node.setMetaData(label, median); } private void annotateModeAttribute(Node node, String label, HashMap<Object, Integer> values) { Object mode = null; int maxCount = 0; int totalCount = 0; int countInMode = 1; for (Object key : values.keySet()) { int thisCount = values.get(key); if (thisCount == maxCount) { // I hope this is the intention mode = mode.toString().concat("+" + key); countInMode++; } else if (thisCount > maxCount) { mode = key; maxCount = thisCount; countInMode = 1; } totalCount += thisCount; } double freq = (double) maxCount / (double) totalCount * countInMode; node.setMetaData(label, mode); node.setMetaData(label + ".prob", freq); } private void annotateFrequencyAttribute(Node node, String label, HashMap<Object, Integer> values) { double totalCount = 0; Set<?> keySet = values.keySet(); int length = keySet.size(); String[] name = new String[length]; Double[] freq = new Double[length]; int index = 0; for (Object key : values.keySet()) { name[index] = key.toString(); freq[index] = new Double(values.get(key)); totalCount += freq[index]; index++; } for (int i = 0; i < length; i++) freq[i] /= totalCount; node.setMetaData(label + ".set", name); node.setMetaData(label + ".set.prob", freq); } private void annotateRangeAttribute(Node node, String label, double[] values) { double min = DiscreteStatistics.min(values); double max = DiscreteStatistics.max(values); node.setMetaData(label, new Object[]{min, max}); } private void annotateHPDAttribute(Node node, String label, double hpd, double[] values) { int[] indices = new int[values.length]; HeapSort.sort(values, indices); double minRange = Double.MAX_VALUE; int hpdIndex = 0; int diff = (int) Math.round(hpd * values.length); for (int i = 0; i <= (values.length - diff); i++) { double minValue = values[indices[i]]; double maxValue = values[indices[i + diff - 1]]; double range = Math.abs(maxValue - minValue); if (range < minRange) { minRange = range; hpdIndex = i; } } double lower = values[indices[hpdIndex]]; double upper = values[indices[hpdIndex + diff - 1]]; node.setMetaData(label, new Object[]{lower, upper}); } // todo Move rEngine to outer class; create once. // Rengine rEngine = null; // private final String[] rArgs = {"--no-save"}; // private final String[] rBootCommands = { // "library(MASS)", // "makeContour = function(var1, var2, prob=0.95, n=50, h=c(1,1)) {" + // "post1 = kde2d(var1, var2, n = n, h=h); " + // This had h=h in argument // "dx = diff(post1$x[1:2]); " + // "dy = diff(post1$y[1:2]); " + // "sz = sort(post1$z); " + // "c1 = cumsum(sz) * dx * dy; " + // "levels = sapply(prob, function(x) { approx(c1, sz, xout = 1 - x)$y }); " + // "line = contourLines(post1$x, post1$y, post1$z, level = levels); " + // "return(line) }" // private String makeRString(double[] values) { // StringBuffer sb = new StringBuffer("c("); // sb.append(values[0]); // for (int i = 1; i < values.length; i++) { // sb.append(","); // sb.append(values[i]); // sb.append(")"); // return sb.toString(); public static final String CORDINATE = "cordinates"; // private String formattedLocation(double loc1, double loc2) { // return formattedLocation(loc1) + "," + formattedLocation(loc2); private String formattedLocation(double x) { return String.format("%5.2f", x); } private void annotate2DHPDAttribute(Node node, String preLabel, String postLabel, double hpd, double[][] values) { if (USE_R) { // Uses R-Java interface, and the HPD routines from 'emdbook' and 'coda' // int N = 50; // if (rEngine == null) { // if (!Rengine.versionCheck()) { // throw new RuntimeException("JRI library version mismatch"); // rEngine = new Rengine(rArgs, false, null); // if (!rEngine.waitForR()) { // throw new RuntimeException("Cannot load R"); // for (String command : rBootCommands) { // rEngine.eval(command); // // todo Need a good method to pick grid size // REXP x = rEngine.eval("makeContour(" + // makeRString(values[0]) + "," + // makeRString(values[1]) + "," + // hpd + "," + // RVector contourList = x.asVector(); // int numberContours = contourList.size(); // if (numberContours > 1) { // Log.err.println("Warning: a node has a disjoint " + 100 * hpd + "% HPD region. This may be an artifact!"); // Log.err.println("Try decreasing the enclosed mass or increasing the number of samples."); // node.setMetaData(preLabel + postLabel + "_modality", numberContours); // StringBuffer output = new StringBuffer(); // for (int i = 0; i < numberContours; i++) { // output.append("\n<" + CORDINATE + ">\n"); // RVector oneContour = contourList.at(i).asVector(); // double[] xList = oneContour.at(1).asDoubleArray(); // double[] yList = oneContour.at(2).asDoubleArray(); // StringBuffer xString = new StringBuffer("{"); // StringBuffer yString = new StringBuffer("{"); // for (int k = 0; k < xList.length; k++) { // xString.append(formattedLocation(xList[k])).append(","); // yString.append(formattedLocation(yList[k])).append(","); // xString.append(formattedLocation(xList[0])).append("}"); // yString.append(formattedLocation(yList[0])).append("}"); // node.setMetaData(preLabel + "1" + postLabel + "_" + (i + 1), xString); // node.setMetaData(preLabel + "2" + postLabel + "_" + (i + 1), yString); } else { // do not use R // KernelDensityEstimator2D kde = new KernelDensityEstimator2D(values[0], values[1], N); //ContourMaker kde = new ContourWithSynder(values[0], values[1], N); boolean bandwidthLimit = false; ContourMaker kde = new ContourWithSynder(values[0], values[1], bandwidthLimit); ContourPath[] paths = kde.getContourPaths(hpd); node.setMetaData(preLabel + postLabel + "_modality", paths.length); if (paths.length > 1) { Log.err.println("Warning: a node has a disjoint " + 100 * hpd + "% HPD region. This may be an artifact!"); Log.err.println("Try decreasing the enclosed mass or increasing the number of samples."); } StringBuffer output = new StringBuffer(); int i = 0; for (ContourPath p : paths) { output.append("\n<" + CORDINATE + ">\n"); double[] xList = p.getAllX(); double[] yList = p.getAllY(); StringBuffer xString = new StringBuffer("{"); StringBuffer yString = new StringBuffer("{"); for (int k = 0; k < xList.length; k++) { xString.append(formattedLocation(xList[k])).append(","); yString.append(formattedLocation(yList[k])).append(","); } xString.append(formattedLocation(xList[0])).append("}"); yString.append(formattedLocation(yList[0])).append("}"); node.setMetaData(preLabel + "1" + postLabel + "_" + (i + 1), xString); node.setMetaData(preLabel + "2" + postLabel + "_" + (i + 1), yString); i++; } } } int totalTrees = 0; int totalTreesUsed = 0; double posteriorLimit = 0.0; double hpd2D = 0.80; private final List<TreeAnnotationPlugin> beastObjects = new ArrayList<>(); Set<String> attributeNames = new HashSet<>(); TaxonSet taxa = null; static boolean processBivariateAttributes = false; // static { // try { // System.loadLibrary("jri"); // processBivariateAttributes = true; // Log.err.println("JRI loaded. Will process bivariate attributes"); // } catch (UnsatisfiedLinkError e) { // Log.err.print("JRI not available. "); // if (!USE_R) { // processBivariateAttributes = true; // Log.err.println("Using Java bivariate attributes"); // } else { // Log.err.println("Will not process bivariate attributes"); public static void printTitle() { progressStream.println(); centreLine("TreeAnnotator " + version.getVersionString() + ", " + version.getDateString(), 60); centreLine("MCMC Output analysis", 60); centreLine("by", 60); centreLine("Andrew Rambaut and Alexei J. Drummond", 60); progressStream.println(); centreLine("Institute of Evolutionary Biology", 60); centreLine("University of Edinburgh", 60); centreLine("a.rambaut@ed.ac.uk", 60); progressStream.println(); centreLine("Department of Computer Science", 60); centreLine("University of Auckland", 60); centreLine("alexei@cs.auckland.ac.nz", 60); progressStream.println(); progressStream.println(); } public static void centreLine(String line, int pageWidth) { int n = pageWidth - line.length(); int n1 = n / 2; for (int i = 0; i < n1; i++) { progressStream.print(" "); } progressStream.println(line); } public static void printUsage(Arguments arguments) { arguments.printUsage("treeannotator", "<input-file-name> [<output-file-name>]"); progressStream.println(); progressStream.println(" Example: treeannotator test.trees out.txt"); progressStream.println(" Example: treeannotator -burnin 10 -heights mean test.trees out.txt"); progressStream.println(" Example: treeannotator -burnin 20 -target map.tree test.trees out.txt"); progressStream.println(); } //Main method public static void main(String[] args) throws IOException { // There is a major issue with languages that use the comma as a decimal separator. // To ensure compatibility between programs in the package, enforce the US locale. Locale.setDefault(Locale.US); String targetTreeFileName = null; String inputFileName = null; String outputFileName = null; if (args.length == 0) { System.setProperty("com.apple.macos.useScreenMenuBar", "true"); System.setProperty("apple.laf.useScreenMenuBar", "true"); System.setProperty("apple.awt.showGrowBox", "true"); java.net.URL url = LogCombiner.class.getResource("/images/utility.png"); javax.swing.Icon icon = null; if (url != null) { icon = new javax.swing.ImageIcon(url); } final String versionString = version.getVersionString(); String nameString = "TreeAnnotator " + versionString; String aboutString = "<html><center><p>" + versionString + ", " + version.getDateString() + "</p>" + "<p>by<br>" + "Andrew Rambaut and Alexei J. Drummond</p>" + "<p>Institute of Evolutionary Biology, University of Edinburgh<br>" + "<a href=\"mailto:a.rambaut@ed.ac.uk\">a.rambaut@ed.ac.uk</a></p>" + "<p>Department of Computer Science, University of Auckland<br>" + "<a href=\"mailto:alexei@cs.auckland.ac.nz\">alexei@cs.auckland.ac.nz</a></p>" + "<p>Part of the BEAST package:<br>" + "<a href=\"http: "</center></html>"; new ConsoleApplication(nameString, aboutString, icon, true); // The ConsoleApplication will have overridden System.out so set progressStream // to capture the output to the window: progressStream = System.out; printTitle(); TreeAnnotatorDialog dialog = new TreeAnnotatorDialog(new JFrame()); if (!dialog.showDialog("TreeAnnotator " + versionString)) { return; } int burninPercentage = dialog.getBurninPercentage(); if (burninPercentage < 0) { Log.warning.println("burnin percentage is " + burninPercentage + " but should be non-negative. Setting it to zero"); burninPercentage = 0; } if (burninPercentage >= 100) { Log.err.println("burnin percentage is " + burninPercentage + " but should be less than 100."); return; } double posteriorLimit = dialog.getPosteriorLimit(); double hpd2D = 0.80; Target targetOption = dialog.getTargetOption(); HeightsSummary heightsOption = dialog.getHeightsOption(); targetTreeFileName = dialog.getTargetFileName(); if (targetOption == Target.USER_TARGET_TREE && targetTreeFileName == null) { Log.err.println("No target file specified"); return; } inputFileName = dialog.getInputFileName(); if (inputFileName == null) { Log.err.println("No input file specified"); return; } outputFileName = dialog.getOutputFileName(); if (outputFileName == null) { Log.err.println("No output file specified"); return; } boolean lowMem = dialog.useLowMem(); try { new TreeAnnotator(burninPercentage, lowMem, heightsOption, posteriorLimit, hpd2D, targetOption, targetTreeFileName, inputFileName, outputFileName); } catch (Exception ex) { Log.err.println("Exception: " + ex.getMessage()); } progressStream.println("Finished - Quit program to exit."); while (true) { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } printTitle(); Arguments arguments = new Arguments( new Arguments.Option[]{ //new Arguments.StringOption("target", new String[] { "maxclade", "maxtree" }, false, "an option of 'maxclade' or 'maxtree'"), new Arguments.StringOption("heights", new String[]{"keep", "median", "mean", "ca"}, false, "an option of 'keep' (default), 'median', 'mean' or 'ca'"), new Arguments.IntegerOption("burnin", 0, 99, "the percentage of states to be considered as 'burn-in'"), // allow -b as burnin option, just like other apps new Arguments.IntegerOption("b", 0, 99, "the percentage of states to be considered as 'burn-in'"), new Arguments.RealOption("limit", "the minimum posterior probability for a node to be annotated"), new Arguments.StringOption("target", "target_file_name", "specifies a user target tree to be annotated"), new Arguments.Option("help", "option to print this message"), new Arguments.Option("forceDiscrete", "forces integer traits to be treated as discrete traits."), new Arguments.Option("lowMem", "use less memory, which is a bit slower."), new Arguments.RealOption("hpd2D", "the HPD interval to be used for the bivariate traits") }); try { arguments.parseArguments(args); } catch (Arguments.ArgumentException ae) { progressStream.println(ae); printUsage(arguments); System.exit(1); } if (arguments.hasOption("forceDiscrete")) { Log.info.println(" Forcing integer traits to be treated as discrete traits."); forceIntegerToDiscrete = true; } if (arguments.hasOption("help")) { printUsage(arguments); System.exit(0); } boolean lowMem = false; if (arguments.hasOption("lowMem")) { lowMem = true; } HeightsSummary heights = HeightsSummary.CA_HEIGHTS; if (arguments.hasOption("heights")) { String value = arguments.getStringOption("heights"); if (value.equalsIgnoreCase("mean")) { heights = HeightsSummary.MEAN_HEIGHTS; } else if (value.equalsIgnoreCase("median")) { heights = HeightsSummary.MEDIAN_HEIGHTS; } else if (value.equalsIgnoreCase("ca")) { heights = HeightsSummary.CA_HEIGHTS; Log.info.println("Please cite: Heled and Bouckaert: Looking for trees in the forest:\n" + "summary tree from posterior samples. BMC Evolutionary Biology 2013 13:221."); } } int burnin = -1; if (arguments.hasOption("burnin")) { burnin = arguments.getIntegerOption("burnin"); } else if (arguments.hasOption("b")) { burnin = arguments.getIntegerOption("b"); } if (burnin >= 100) { Log.err.println("burnin percentage is " + burnin + " but should be less than 100."); System.exit(1); } double posteriorLimit = 0.0; if (arguments.hasOption("limit")) { posteriorLimit = arguments.getRealOption("limit"); } double hpd2D = 0.80; if (arguments.hasOption("hpd2D")) { hpd2D = arguments.getRealOption("hpd2D"); if (hpd2D <= 0 || hpd2D >=1) { Log.err.println("hpd2D is a fraction and should be in between 0.0 and 1.0."); System.exit(1); } processBivariateAttributes = true; } Target target = Target.MAX_CLADE_CREDIBILITY; if (arguments.hasOption("target")) { target = Target.USER_TARGET_TREE; targetTreeFileName = arguments.getStringOption("target"); } final String[] args2 = arguments.getLeftoverArguments(); switch (args2.length) { case 2: outputFileName = args2[1]; // fall to case 1: inputFileName = args2[0]; break; default: { Log.err.println("Unknown option: " + args2[2]); Log.err.println(); printUsage(arguments); System.exit(1); } } try { new TreeAnnotator(burnin, lowMem, heights, posteriorLimit, hpd2D, target, targetTreeFileName, inputFileName, outputFileName); } catch (IOException e) { throw e; } catch (Exception e) { e.printStackTrace(); } System.exit(0); } /** * @author Andrew Rambaut * @version $Id$ */ //TODO code review: it seems not necessary public static interface TreeAnnotationPlugin { Set<String> setAttributeNames(Set<String> attributeNames); boolean handleAttribute(Node node, String attributeName, double[] values); } boolean setTreeHeightsByCA(Tree targetTree) throws IOException { progressStream.println("Setting node heights..."); progressStream.println("0 25 50 75 100"); progressStream.println("| int reportStepSize = totalTrees / 60; if (reportStepSize < 1) reportStepSize = 1; int reported = 0; // this call increments the clade counts and it shouldn't // this is remedied with removeClades call after while loop below CladeSystem cladeSystem = new CladeSystem(targetTree); final int clades = cladeSystem.getCladeMap().size(); // allocate posterior tree nodes order once int[] postOrderList = new int[clades]; BitSet[] ctarget = new BitSet[clades]; BitSet[] ctree = new BitSet[clades]; for (int k = 0; k < clades; ++k) { ctarget[k] = new BitSet(); ctree[k] = new BitSet(); } cladeSystem.getTreeCladeCodes(targetTree, ctarget); // temp collecting heights inside loop allocated once double[] hs = new double[clades]; // heights total sum from posterior trees double[] ths = new double[clades]; totalTreesUsed = 0; int counter = 0; treeSet.reset(); while (treeSet.hasNext()) { Tree tree = treeSet.next(); TreeUtils.preOrderTraversalList(tree, postOrderList); cladeSystem.getTreeCladeCodes(tree, ctree); for (int k = 0; k < clades; ++k) { int j = postOrderList[k]; for (int i = 0; i < clades; ++i) { if( CollectionUtils.isSubSet(ctarget[i], ctree[j]) ) { hs[i] = tree.getNode(j).getHeight(); } } } for (int k = 0; k < clades; ++k) { ths[k] += hs[k]; } totalTreesUsed += 1; if (counter > 0 && counter % reportStepSize == 0 && reported < 61) { progressStream.print("*"); progressStream.flush(); reported++; } counter++; } targetTree.initAndValidate(); cladeSystem.removeClades(targetTree.getRoot(), true); for (int k = 0; k < clades; ++k) { ths[k] /= totalTreesUsed; final Node node = targetTree.getNode(k); node.setHeight(ths[k]); } progressStream.println(); progressStream.println(); return true; } }
package ca.nmsasaki.silenttouch; import java.text.DateFormat; import java.util.Calendar; import android.app.AlarmManager; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.app.Service; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.media.AudioManager; import android.os.IBinder; import android.util.Log; import android.widget.Toast; public class WidgetService extends Service { // when testing minimum is 2 minutes because I round seconds down to 00 to // timer expires on minute change //private static final long SILENT_DURATION_MILLISECONDS = 2 * 60 * 1000; public static final long SILENT_DURATION_MILLISECONDS = 30 * 60 * 1000; private static final String TAG = "SilentTouch"; private static final int MY_NOTIFICATION_ID = 1; // private static final String INTENT_ACTION_WIDGET_CLICK = "ca.nmsasaki.silenttouch.INTENT_ACTION_WIDGET_CLICK"; private static final String PREF_NAME = "ca.nmsasaki.silenttouch.prefs"; private static final String PREF_NAME_ALARM_EXPIRE = "ca.nmsasaki.silenttouch.prefs.alarm_expire"; private static final String PREF_NAME_ORIGINAL_RINGER_MODE = "ca.nmsasaki.silenttouch.prefs.orig_ringer_mode"; private static final String INTENT_ACTION_NOTIFICATION_CANCEL_CLICK = "ca.nmsasaki.silenttouch.INTENT_ACTION_NOTIFICATION_CANCEL_CLICK"; private static final String INTENT_ACTION_TIMER_EXPIRED = "ca.nmsasaki.silenttouch.INTENT_ACTION_TIMER_EXPIRED"; // TODO: remove static mToast // mToast is used to cancel an existing toast if user clicks on widget in succession // seems to work find and should be ok if this state gets cleaned up by android private static Toast mToast = null; private int mOriginalRingerMode = AudioManager.RINGER_MODE_NORMAL; private long mAlarmExpireTime = 0; private boolean mPrefsUpdated = false; @Override public void onStart(Intent intent, int startId) { Log.i(TAG, "WidgetService::onStart - enter"); final String curIntentAction = intent.getAction(); final Context context = getApplicationContext(); SharedPreferences prefs = readPrefs(context); if (curIntentAction == WidgetProvider.INTENT_ACTION_WIDGET_CLICK) { UserClickedWidget(context); } else if (curIntentAction == INTENT_ACTION_TIMER_EXPIRED) { TimerExpired(context); } else if (intent.getAction() == INTENT_ACTION_NOTIFICATION_CANCEL_CLICK) { UserClickedCancel(context); } writePrefs(prefs); Log.i(TAG, "WidgetService::onStart - exit"); stopSelf(); } /** * @param prefs * * if preferences were updated, then write to storage */ private void writePrefs(SharedPreferences prefs) { if (isPrefsUpdated()) { Editor editor = prefs.edit(); editor.putInt(PREF_NAME_ORIGINAL_RINGER_MODE, getOriginalRingerMode()); editor.putLong(PREF_NAME_ALARM_EXPIRE, getAlarmExpireTime()); editor.commit(); } } /** * @param context * @return SharedPreferences populated with app state */ private SharedPreferences readPrefs(final Context context) { SharedPreferences prefs = context.getSharedPreferences(PREF_NAME, MODE_PRIVATE); setOriginalRingerMode(prefs.getInt(PREF_NAME_ORIGINAL_RINGER_MODE, AudioManager.RINGER_MODE_NORMAL)); setAlarmExpireTime(prefs.getLong(PREF_NAME_ALARM_EXPIRE, 0)); return prefs; } @Override public IBinder onBind(Intent intent) { Log.i(TAG, "WigetService::onBind()"); return null; } @Override public void onDestroy() { Log.i(TAG, "WidgetService::onDestroy - exit"); } /** * @param context * @return * * 1. Restore Ringer Mode * 2. Cancel Timer * 3. Clear Notification */ private void UserClickedCancel(Context context) { Log.i(TAG, "INTENT_ACTION_NOTIFICATION_CANCEL_CLICK - enter"); // User canceled the mode manually from notifications // Restore previous RingerMode AudioManager audioMgr = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE); final int curAudioMode = audioMgr.getRingerMode(); final String curModeString = RingerMode_intToString(curAudioMode); Log.i(TAG, "AudioMode=" + curModeString); if (curAudioMode == AudioManager.RINGER_MODE_SILENT) { audioMgr.setRingerMode(getOriginalRingerMode()); Log.i(TAG, String.format("AudioMode=%d", getOriginalRingerMode())); } // cancel timer AlarmManager alarmMgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); PendingIntent alarmIntent = createAlarmIntent(context); alarmMgr.cancel(alarmIntent); // clear notification NotificationManager notiMgr = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); notiMgr.cancel(MY_NOTIFICATION_ID); // set AlarmExpire to 0 to show that there is no more timer setAlarmExpireTime(0); Log.i(TAG, "INTENT_ACTION_NOTIFICATION_CANCEL_CLICK - exit"); } /** * @param context * @return * 1. Restore Ringer Mode * 2. Build Notification */ private void TimerExpired(Context context) { Log.i(TAG, "INTENT_ACTION_TIMER_EXPIRED - enter"); // Timer expired - restore previous notification type // enable previous ringerMode AudioManager audioMgr = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE); final int curAudioMode = audioMgr.getRingerMode(); final String curModeString = RingerMode_intToString(curAudioMode); Log.i(TAG, "AudioMode=" + curModeString); if (curAudioMode == AudioManager.RINGER_MODE_SILENT) { Log.i(TAG, String.format("before AudioMode=%d", getOriginalRingerMode())); audioMgr.setRingerMode(getOriginalRingerMode()); Log.i(TAG, String.format("after AudioMode=%d", getOriginalRingerMode())); } // Build notification to say timer expired final long alarmExpired = System.currentTimeMillis(); final String dateStringLog = DateFormat.getTimeInstance(DateFormat.LONG).format(alarmExpired); Log.i(TAG, "onReceive Actual expireTime:" + dateStringLog); final String notiTitle = context.getString(R.string.notification_title); String notiContentText = context.getString(R.string.notification_OFF_timer); final String dateStringUser = DateFormat.getTimeInstance(DateFormat.SHORT).format(alarmExpired); notiContentText = String.format(notiContentText, dateStringUser); // Define the Notification's expanded message and Intent: Notification.Builder notiBuilder = new Notification.Builder(context) .setSmallIcon(R.drawable.ic_notify).setContentTitle(notiTitle) .setContentText(notiContentText); // Pass the Notification to the NotificationManager: NotificationManager notiMgr = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); notiMgr.notify(MY_NOTIFICATION_ID, notiBuilder.build()); // set AlarmExpire to 0 to show that there is no more timer setAlarmExpireTime(0); Log.i(TAG, "INTENT_ACTION_TIMER_EXPIRED - exit"); } /** * @param context * @return * * 1. Set New Timer or Update Timer * 2. Set RingerMode * 3. Create Toast * 4. Build Notification */ private void UserClickedWidget(Context context) { // User clicked on widget // Perform actions before notifying user // this will expose performance delays and show bugs Log.i(TAG, "INTENT_ACTION_WIDGET_CLICK - enter"); // check current ringermode AudioManager audioMgr = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE); final int curAudioMode = audioMgr.getRingerMode(); final String curModeString = RingerMode_intToString(curAudioMode); Log.i(TAG, "AudioMode=" + curModeString); // set timer to re-enable original ringer mode AlarmManager alarmMgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); if (getAlarmExpireTime() == 0) { // record current state // set time for silence to expire setAlarmExpireTime(System.currentTimeMillis() + SILENT_DURATION_MILLISECONDS); // set ringer mode to restore here // if the ringer mode is silent already, then set restore mode to normal // (otherwise, why did they click on widget... assume they want it to expire) if (curAudioMode == AudioManager.RINGER_MODE_SILENT) { setOriginalRingerMode(AudioManager.RINGER_MODE_NORMAL); } else { setOriginalRingerMode(curAudioMode); } } else { // set time for silence to expire based on previous value setAlarmExpireTime(getAlarmExpireTime() + SILENT_DURATION_MILLISECONDS); } PendingIntent alarmIntent = createAlarmIntent(context); setAlarmExpireTime(truncateSeconds(getAlarmExpireTime())); alarmMgr.set(AlarmManager.RTC_WAKEUP, getAlarmExpireTime(), alarmIntent); final String dateStringLog = DateFormat.getTimeInstance(DateFormat.LONG).format(getAlarmExpireTime()); Log.i(TAG, "onReceive Set expireTime=" + dateStringLog); // set ringer mode after alarm is set // to ensure mode will become re-enabled if (curAudioMode != AudioManager.RINGER_MODE_SILENT) { audioMgr.setRingerMode(AudioManager.RINGER_MODE_SILENT); Log.i(TAG, "AudioMode=RINGER_MODE_SILENT"); } // Create toast to alert user String toastText = context.getString(R.string.toast_ON); final String dateStringUser = DateFormat.getTimeInstance(DateFormat.SHORT).format( getAlarmExpireTime()); toastText = String.format(toastText, dateStringUser); if (mToast != null) { mToast.cancel(); } mToast = Toast.makeText(context, toastText, Toast.LENGTH_LONG); mToast.show(); // Build notification // notification strings final String notiTitle = context.getString(R.string.notification_title); final String notiCancel = context.getString(R.string.notification_ON_cancel); String notiContentText = context.getString(R.string.notification_ON_content); notiContentText = String.format(notiContentText, dateStringUser); // Pending intent to be fired when notification is clicked Intent notiIntent = new Intent(context, WidgetProvider.class); notiIntent.setAction(INTENT_ACTION_NOTIFICATION_CANCEL_CLICK); PendingIntent cancelPendingIntent = PendingIntent.getBroadcast(context, 0, notiIntent, 0); // TODO: find actual vibrate icon - cannot find official vibrate icon // use regular notification icon int iconId = android.R.drawable.ic_lock_silent_mode_off; // if (mRingerMode == AudioManager.RINGER_MODE_VIBRATE) { // iconId = android.R.drawable.; // Define the Notification's expanded message and Intent: Notification.Builder notiBuilder = new Notification.Builder(context) .setSmallIcon(R.drawable.ic_notify).setContentTitle(notiTitle) .setContentText(notiContentText).addAction(iconId, notiCancel, cancelPendingIntent); // Pass the Notification to the NotificationManager: NotificationManager notMgr = (NotificationManager) context .getSystemService(Context.NOTIFICATION_SERVICE); notMgr.notify(MY_NOTIFICATION_ID, notiBuilder.build()); Log.i(TAG, "INTENT_ACTION_WIDGET_CLICK - exit"); } /** * @param context * @return PendingIntent for AlarmManager */ private PendingIntent createAlarmIntent(Context context) { Intent intentAlarmReceiver = new Intent(context, WidgetProvider.class); intentAlarmReceiver.setAction(INTENT_ACTION_TIMER_EXPIRED); return PendingIntent.getBroadcast(context, 0, intentAlarmReceiver, 0); } /** * @param timeInMilliseconds * @return equivalent time in Milliseconds rounded down to nearest minute */ public static long truncateSeconds(long timeInMilliseconds) { long returnValue = 0; Calendar calendar = Calendar.getInstance(); calendar.setTimeInMillis(timeInMilliseconds); calendar.set(Calendar.SECOND, 0); returnValue = calendar.getTimeInMillis(); return returnValue; } /** * @param curAudioMode from AudioManager.RINGER_MODE_XXXX * @return String version of curAudioMode * if the ringer mode is unknown, include int value for reference debugging */ public static String RingerMode_intToString(int curAudioMode) { String returnString = "UNKNOWN_MODE"; switch (curAudioMode) { case AudioManager.RINGER_MODE_SILENT: returnString = "0-RINGER_MODE_SILENT"; break; case AudioManager.RINGER_MODE_VIBRATE: returnString = "1-RINGER_MODE_VIBRATE"; break; case AudioManager.RINGER_MODE_NORMAL: returnString = "2-RINGER_MODE_NORMAL"; break; default: // Integer intObj = curAudioMode; // returnString = intObj.toString() + "-UNKNOWN_MODE"; returnString = curAudioMode + "-UNKNOWN_MODE"; // returnString = (String) returnString.toCharArray(); break; } return returnString; } private int getOriginalRingerMode() { return mOriginalRingerMode; } private void setOriginalRingerMode(int mOriginalRingerMode) { this.mOriginalRingerMode = mOriginalRingerMode; this.setPrefsUpdated(true); } private long getAlarmExpireTime() { return mAlarmExpireTime; } private void setAlarmExpireTime(long mAlarmExpireTime) { this.mAlarmExpireTime = mAlarmExpireTime; this.setPrefsUpdated(true); } private boolean isPrefsUpdated() { return mPrefsUpdated; } private void setPrefsUpdated(boolean mPrefsUpdated) { this.mPrefsUpdated = mPrefsUpdated; } }
package de.ptb.epics.eve.data.tests.internal; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import javax.xml.parsers.ParserConfigurationException; import org.apache.log4j.Logger; import org.apache.log4j.xml.DOMConfigurator; import org.xml.sax.SAXException; import de.ptb.epics.eve.data.measuringstation.IMeasuringStation; import de.ptb.epics.eve.data.measuringstation.processors.MeasuringStationLoader; import de.ptb.epics.eve.data.scandescription.Chain; import de.ptb.epics.eve.data.scandescription.ScanDescription; import de.ptb.epics.eve.data.scandescription.ScanModule; /** * <code>Configurator</code> contains the configuration of the tests used. * * @author Marcus Michalsky * @since 0.4.1 */ public class Configurator { private static Logger logger = Logger.getLogger(Configurator.class.getName()); private static boolean configured = false; /** * Returns all available * {@link de.ptb.epics.eve.data.measuringstation.IMeasuringStation}s. * * @return all available * {@link de.ptb.epics.eve.data.measuringstation.IMeasuringStation}s */ public static List<IMeasuringStation> getMeasuringStations() { List<IMeasuringStation> stations = new ArrayList<IMeasuringStation>(); final MeasuringStationLoader measuringStationLoader = new MeasuringStationLoader(Configurator.getSchemaFile()); File bigref = new File("xml/bigref.xml"); File euvr = new File("xml/euvr.xml"); File kmc = new File("xml/kmc.xml"); File newref = new File("xml/newref.xml"); File nrfa = new File("xml/nrfa.xml"); File pgm = new File("xml/pgm.xml"); File qnim = new File("xml/qnim.xml"); File rfa = new File("xml/rfa.xml"); File sx700 = new File("xml/sx700.xml"); File test = new File("xml/test.xml"); File trfa = new File("xml/trfa.xml"); try { measuringStationLoader.load(bigref); stations.add(measuringStationLoader.getMeasuringStation()); measuringStationLoader.load(euvr); stations.add(measuringStationLoader.getMeasuringStation()); measuringStationLoader.load(kmc); stations.add(measuringStationLoader.getMeasuringStation()); measuringStationLoader.load(newref); stations.add(measuringStationLoader.getMeasuringStation()); measuringStationLoader.load(nrfa); stations.add(measuringStationLoader.getMeasuringStation()); measuringStationLoader.load(pgm); stations.add(measuringStationLoader.getMeasuringStation()); measuringStationLoader.load(qnim); stations.add(measuringStationLoader.getMeasuringStation()); measuringStationLoader.load(rfa); stations.add(measuringStationLoader.getMeasuringStation()); measuringStationLoader.load(sx700); stations.add(measuringStationLoader.getMeasuringStation()); measuringStationLoader.load(test); stations.add(measuringStationLoader.getMeasuringStation()); measuringStationLoader.load(trfa); stations.add(measuringStationLoader.getMeasuringStation()); } catch (ParserConfigurationException e) { logger.error(e.getMessage(), e); } catch (SAXException e) { logger.error(e.getMessage(), e); } catch (IOException e) { logger.error(e.getMessage(), e); } return stations; } /** * Returns a {@link de.ptb.epics.eve.data.scandescription.ScanDescription} * containing one {@link de.ptb.epics.eve.data.scandescription.Chain} and * one {@link de.ptb.epics.eve.data.scandescription.ScanModule}. * * @param ims the {@link de.ptb.epics.eve.data.measuringstation.MeasuringStation} * @return a scan description containing one chain and one scan module */ public static ScanDescription getBasicScanDescription(IMeasuringStation ims) { ScanDescription sd = new ScanDescription(ims); Chain ch = new Chain(1); ScanModule sm = new ScanModule(1); ch.add(sm); sd.add(ch); return sd; } /** * Loads the Log4j configuration. */ public static void configureLogging() { if(!configured) { DOMConfigurator.configure("log4j-conf.xml"); configured = true; } } /** * Returns the schema file. * * @return the schema file */ public static File getSchemaFile() { return new File("../org.csstudio.eve.resources/cfg/schema.xsd"); } }
package com.KST.eCommerce; import java.io.IOException; import java.net.URL; import java.util.ArrayList; import java.util.ResourceBundle; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.fxml.Initializable; import javafx.scene.Node; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.input.MouseEvent; import javafx.scene.layout.AnchorPane; import javafx.scene.layout.Pane; import javafx.stage.Stage; /** * * @author Ken */ public class EcommerceGUIController implements Initializable { @FXML private Button btnStore; @FXML private Button btnCart; @FXML private Button btnLogin; @FXML private AnchorPane itemList; @FXML private void viewHandler(ActionEvent event) throws IOException { Stage stage = (Stage) ((Node) event.getSource()).getScene().getWindow(); Parent root = null; if (event.getSource() == btnStore) { root = FXMLLoader.load(getClass().getResource("views/viewHome.fxml")); } else if (event.getSource() == btnCart) { root = FXMLLoader.load(getClass().getResource("views/viewCart.fxml")); } else if (event.getSource() == btnLogin) { root = FXMLLoader.load(getClass().getResource("views/viewLogin.fxml")); } if (root != null) { stage.setScene(new Scene(root)); stage.show(); } } private void loadItems() { EcommerceGUIController reference = this; AnchorPane itemContainer; Label itemTitle; Label itemDescription; Label itemPrice; Button addToCart; Session session = EcommerceGUI.platform.getSession(); ArrayList<Item> items = EcommerceGUI.platform.listItems(); double x = 20; double y = 20; for (Item i : items) { itemContainer = new AnchorPane(); itemContainer.setStyle("-fx-background-color:" + EcommerceGUI.BACKGROUND); itemContainer.setMinWidth(520); itemContainer.setMinHeight(120); itemContainer.setLayoutX(x); itemContainer.setLayoutY(y); y += 140; itemTitle = new Label(i.getTitle()); itemTitle.setStyle("-fx-text-fill:" + EcommerceGUI.FOREGROUND + ";-fx-padding:10;-fx-font-size:16;-fx-font-weight:bold"); itemTitle.setMinWidth(410); itemTitle.setMinHeight(45); itemTitle.setLayoutX(10); itemTitle.setLayoutY(10); itemDescription = new Label(i.getDescription()); itemDescription.setStyle("-fx-text-fill:" + EcommerceGUI.FOREGROUND + ";-fx-padding:10;-fx-alignment:TOP-LEFT"); itemDescription.setMinWidth(410); itemDescription.setMinHeight(60); itemDescription.setLayoutX(10); itemDescription.setLayoutY(50); itemPrice = new Label(String.format("$%.2f", i.getPrice())); itemPrice.setStyle("-fx-text-fill:" + EcommerceGUI.FOREGROUND + ";-fx-padding:10;-fx-font-size:16;-fx-font-weight:bold;-fx-alignment:CENTER-RIGHT"); itemPrice.setMinWidth(90); itemPrice.setMinHeight(45); itemPrice.setLayoutX(420); itemPrice.setLayoutY(10); addToCart = new Button("Add To Cart"); addToCart.setMinWidth(80); addToCart.setMinHeight(40); addToCart.setLayoutX(430); addToCart.setLayoutY(70); addToCart.setOnMouseClicked((EventHandler) new EventHandler<MouseEvent>() { @Override public void handle(MouseEvent t) { session.addToCart(i); if (btnCart != null) { btnCart.setText("Cart: " + session.getCartSize()); } } }); itemContainer.getChildren().add(itemTitle); itemContainer.getChildren().add(itemDescription); itemContainer.getChildren().add(itemPrice); itemContainer.getChildren().add(addToCart); itemList.getChildren().add(itemContainer); } Pane spacer = new Pane(); spacer.setMinHeight(20); spacer.setMinWidth(450); spacer.setLayoutX(0); spacer.setLayoutY(y - 20); itemList.getChildren().add(spacer); } @Override public void initialize(URL url, ResourceBundle rb) { if (btnCart != null) { btnCart.setText("Cart: " + EcommerceGUI.platform.getSession().getCartSize()); } if (itemList != null) { loadItems(); } } }
package com.backendless.persistence; import java.util.ArrayList; import java.util.List; public class QueryOptions { private List<String> sortBy = new ArrayList<String>(); private List<String> related = new ArrayList<String>(); private Integer relationsDepth; public QueryOptions() { } public QueryOptions( String sortBy ) { addSortByOption( sortBy ); } public void setSortBy( List<String> sortBy ) { this.sortBy = sortBy; } public void setRelated( List<String> related ) { this.related = related; } public void addSortByOption( String sortBy ) { if( sortBy == null || sortBy.equals( "" ) ) return; if( this.sortBy == null ) this.sortBy = new ArrayList<String>(); this.sortBy.add( sortBy ); } public void addRelated( String related ) { if( related == null || related.equals( "" ) ) return; if( this.related == null ) this.related = new ArrayList<String>(); this.related.add( related ); } public List<String> getSortBy() { if( sortBy == null ) return sortBy = new ArrayList<String>(); return new ArrayList<String>( sortBy ); } public List<String> getRelated() { if( related == null ) return related = new ArrayList<String>(); return new ArrayList<String>( related ); } public QueryOptions newInstance() { QueryOptions result = new QueryOptions(); result.setSortBy( sortBy ); result.setRelated( related ); result.setRelationsDepth( relationsDepth ); return result; } public void setRelationsDepth ( Integer relationsDepth ) { this.relationsDepth = relationsDepth; } public Integer getRelationsDepth() { return relationsDepth; } }
package com.haxademic.sketch.render; import com.haxademic.core.app.P; import com.haxademic.core.app.PAppletHax; import com.haxademic.core.constants.AppSettings; import com.haxademic.core.draw.context.OpenGLUtil; import com.haxademic.core.draw.image.TiledTexture; import com.haxademic.core.draw.shapes.PShapeUtil; import com.haxademic.core.draw.shapes.TextToPShape; import com.haxademic.core.file.FileUtil; import com.haxademic.core.math.easing.Penner; import processing.core.PGraphics; import processing.core.PImage; import processing.core.PShape; public class DeathMachine extends PAppletHax { public static void main(String args[]) { PAppletHax.main(Thread.currentThread().getStackTrace()[1].getClassName()); } protected PShape skullMesh; protected PShape gunMesh; protected PImage img; // protected PImage flag; protected PGraphics gunTexture; protected TiledTexture gunTilingTexture; protected TextToPShape textToPShape; protected PShape textAmerica; protected PShape textThe; protected PShape textIndefensible; protected float _frames = 900; protected void overridePropsFile() { p.appConfig.setProperty( AppSettings.WIDTH, 1280 ); p.appConfig.setProperty( AppSettings.HEIGHT, 720 ); p.appConfig.setProperty( AppSettings.FILLS_SCREEN, false ); p.appConfig.setProperty( AppSettings.RENDERING_MOVIE, false ); p.appConfig.setProperty( AppSettings.RENDERING_MOVIE_START_FRAME, 1 ); p.appConfig.setProperty( AppSettings.RENDERING_MOVIE_STOP_FRAME, (int)_frames ); } public void setup() { super.setup(); } protected void firstFrameSetup() { P.println("America the Indefensible"); // load texture // flag = p.loadImage(FileUtil.getFile("images/usa.png")); img = p.loadImage(FileUtil.getFile("images/las-vegas-victims-nbcnews.png")); gunTexture = p.createGraphics(img.width * 3, img.width * 3, P.P3D); gunTexture.smooth(8); gunTilingTexture = new TiledTexture(img); // build obj PShape and scale to window skullMesh = p.loadShape( FileUtil.getFile("models/skull-realistic.obj")); gunMesh = p.loadShape( FileUtil.getFile("models/m4a1.obj")); normalizeMesh(skullMesh, p.height * 0.03f, null); normalizeMesh(gunMesh, p.height, gunTexture); // build texts float textDepth = 14f; textToPShape = new TextToPShape(); String fontFile = FileUtil.getFile("fonts/AvantGarde-Book.ttf"); textAmerica = textToPShape.stringToShape3d("AMERICA", textDepth, fontFile); PShapeUtil.scaleShapeToHeight(textAmerica, p.height * 0.068f); textThe = textToPShape.stringToShape3d("THE", textDepth, fontFile); PShapeUtil.scaleShapeToHeight(textThe, p.height * 0.05f); textIndefensible = textToPShape.stringToShape3d("INDEFENSIBLE", textDepth, fontFile); PShapeUtil.scaleShapeToHeight(textIndefensible, p.height * 0.055f); // smooth more // OpenGLUtil.setTextureQualityHigh(p.g); } protected void normalizeMesh(PShape s, float extent, PImage texture) { PShapeUtil.scaleShapeToExtent(s, extent); // add UV coordinates to OBJ float modelExtent = PShapeUtil.getShapeMaxExtent(s); if(texture != null) PShapeUtil.addTextureUVToShape(s, texture, modelExtent, false); } public void setBetterLights( PGraphics p ) { // setup lighting props p.ambient(127); p.lightSpecular(230, 230, 230); p.directionalLight(200, 200, 200, -0.0f, -0.0f, 1); p.directionalLight(200, 200, 200, 0.0f, 0.0f, -1); p.specular(p.color(200)); p.shininess(5.0f); } public void drawApp() { p.pushMatrix(); if(p.frameCount == 1) firstFrameSetup(); background(0); p.ortho(); setBetterLights(p.g); // mouse control // float xmouse = P.map(P.p.mouseX, 0, p.width, -800f, 800f); // float ymouse = P.map(P.p.mouseY, 0, p.height, -800f, 800f); // P.p.debugView.addValue("xmouse", xmouse); // P.p.debugView.addValue("ymouse", ymouse); // loop progress float loopFrames = p.frameCount % _frames; float percentComplete = loopFrames / _frames; // percentComplete = 0.75f; // percentComplete = Penner.easeInOutCirc(percentComplete % 1f, 0, 1, 1); // float cameraPercent = Penner.easeInOutCirc((0.75f + percentComplete) % 1f, 0, 1, 1); float radsComplete = percentComplete * P.TWO_PI; // float cameraPercentRadsComplete = cameraPercent * P.TWO_PI; // rotate scene float starXOffset = (p.width/7f + p.width/7f * P.sin(P.PI - radsComplete)); float starYOffset = (p.height/12f + p.width/12f * P.sin(P.PI - radsComplete)); p.translate(p.width * 0.49f - starXOffset, p.height * 0.49f - starYOffset, -p.width * 0.6f); p.rotateY(0.35f - P.HALF_PI + 0.25f * P.sin(-0.4f + radsComplete)); p.scale(0.7f + 2.2f + 2.2f * P.sin(radsComplete)); // update gun texture gunTexture.beginDraw(); gunTexture.background(180); gunTexture.translate(gunTexture.width/2, gunTexture.height/2); gunTilingTexture.update(); // gunTilingTexture.setRotation(p.frameCount * 0.001f); gunTilingTexture.setOffset(percentComplete, percentComplete); float tileScale = 1.0f + 0.5f * P.sin(radsComplete); gunTilingTexture.setSize(tileScale, -tileScale); gunTilingTexture.drawCentered(gunTexture, gunTexture.width, gunTexture.height); gunTexture.endDraw(); // draw gun p.rotateZ(P.PI - 0.7f + (0.2f + 0.2f * P.sin(radsComplete))); // p.rotateZ(ymouse); p.rotateX(0.4f - (0.3f + 0.3f * P.sin(radsComplete))); // p.rotateX(xmouse); p.pushMatrix(); p.noStroke(); PShapeUtil.drawTriangles(p.g, gunMesh, gunTexture, 1f); // img p.popMatrix(); // draw skull p.pushMatrix(); float yOffset = -24; float zOffset = -49; p.translate(-3000f - 3500f/2f * percentComplete, yOffset, zOffset); // float curZ = 0; for (int i = 0; i < 9000f; i+=70f) { p.pushMatrix(); p.translate(i, 0, 0); p.rotateY(-P.HALF_PI); p.shape(skullMesh); p.popMatrix(); } // p.rotateZ(P.PI); // p.rotateY(P.HALF_PI); p.popMatrix(); // PShapeUtil.drawTrianglesWithTexture(p.g, skullMesh, gunTexture, 0.2f); // img // draw text // AMERICA p.pushMatrix(); p.rotateZ(P.PI); p.rotateY(P.HALF_PI); p.translate(-209, -302, 0); // p.translate(xmouse , ymouse, 0); p.fill(255); textAmerica.disableStyle(); p.shape(textAmerica); // PShapeUtil.drawTriangles(p.g, textAmerica, flag, 1); p.popMatrix(); // THE p.pushMatrix(); p.rotateZ(P.PI); p.rotateY(P.HALF_PI); p.translate(-259, 51, 0); // p.translate(yOffsetAM ,zOffsetAM, 0); textThe.disableStyle(); p.fill(255); p.shape(textThe); p.popMatrix(); // INDEFENSIBLE p.pushMatrix(); p.rotateZ(P.PI); p.rotateY(P.HALF_PI); p.translate(337, 302, 0); // p.translate(yOffsetAM ,zOffsetAM, 0); textIndefensible.disableStyle(); p.fill(255); p.shape(textIndefensible); p.popMatrix(); p.popMatrix(); } }
package com.hp.hpl.jena.graph.query; import com.hp.hpl.jena.graph.*; import com.hp.hpl.jena.util.iterator.*; /** A PatternStage is a Stage that handles some bunch of related patterns; those patterns are encoded as Triples. @author hedgehog */ public class PatternStage extends Stage { protected Graph graph; protected Pattern [] compiled; public PatternStage( Graph graph, Mapping map, Triple [] triples ) { this.graph = graph; this.compiled = compile( map, triples ); } protected Pattern [] compile( Mapping map, Triple [] triples ) { return compile( compiler, map, triples ); } protected Pattern [] compile( PatternCompiler pc, Mapping map, Triple [] source ) { return PatternStageCompiler.compile( pc, map, source ); } private static final PatternCompiler compiler = new PatternStageCompiler(); public Pipe deliver( final Pipe result ) { final Pipe stream = previous.deliver( new BufferPipe() ); new Thread() { public void run() { PatternStage.this.run( stream, result ); } } .start(); return result; } protected void run( Pipe source, Pipe sink ) { while (stillOpen && source.hasNext()) nest( sink, source.get(), 0 ); sink.close(); } protected void nest( Pipe sink, Domain current, int index ) { if (index == compiled.length) sink.put( current.copy() ); else { Pattern p = compiled[index]; ClosableIterator it = graph.find( p.asTripleMatch( current ) ); while (stillOpen && it.hasNext()) if (p.match( current, (Triple) it.next())) nest( sink, current, index + 1 ); it.close(); } } }
package com.io7m.jsycamore.components; import java.util.Set; import javax.annotation.Nonnull; import com.io7m.jaux.Constraints.ConstraintError; import com.io7m.jcanephora.GLException; import com.io7m.jcanephora.GLInterface; import com.io7m.jsycamore.Component; import com.io7m.jsycamore.ComponentAlignment; import com.io7m.jsycamore.ComponentLimits; import com.io7m.jsycamore.DrawPrimitives; import com.io7m.jsycamore.GUIContext; import com.io7m.jsycamore.GUIException; import com.io7m.jsycamore.Theme; import com.io7m.jsycamore.Triangle; import com.io7m.jsycamore.Window; import com.io7m.jsycamore.geometry.ParentRelative; import com.io7m.jsycamore.geometry.Point; import com.io7m.jsycamore.geometry.PointConstants; import com.io7m.jsycamore.geometry.PointReadable; import com.io7m.jsycamore.geometry.ScreenRelative; import com.io7m.jtensors.VectorI2I; import com.io7m.jtensors.VectorM2I; import com.io7m.jtensors.VectorReadable2I; import com.io7m.jtensors.VectorReadable3F; public final class Scrollable extends Component { private final class ScrollBarHorizontal extends Component { private final class ButtonLeft extends AbstractRepeatingButton { public ButtonLeft( final @Nonnull ScrollBarHorizontal parent, final @Nonnull PointReadable<ParentRelative> position, final @Nonnull VectorReadable2I size) throws ConstraintError { super(parent, position, size); } @Override public void buttonListenerOnClick( final @Nonnull Component button) { // Unused. } @SuppressWarnings("synthetic-access") @Override public void buttonRenderPost( final @Nonnull GUIContext context) throws ConstraintError, GUIException { try { final DrawPrimitives draw = context.contextGetDrawPrimitives(); draw.renderTriangleFill( context, Scrollable.triangle_left0, this.buttonGetCurrentEdgeColor()); draw.renderTriangleFill( context, Scrollable.triangle_left1, this.buttonGetCurrentEdgeColor()); } catch (final GLException e) { throw new GUIException(e); } } @Override public void buttonRenderPre( final @Nonnull GUIContext context) throws ConstraintError, GUIException { // Unused. } @Override public void resourceDelete( final @Nonnull GLInterface gl) throws ConstraintError, GLException { // Unused. } @Override public boolean resourceIsDeleted() { return true; } @Override public String toString() { final StringBuilder builder = new StringBuilder(); builder.append("[ButtonLeft "); builder.append(this.componentGetID()); builder.append("]"); return builder.toString(); } } private final class ButtonRight extends AbstractRepeatingButton { public ButtonRight( final @Nonnull ScrollBarHorizontal parent, final @Nonnull PointReadable<ParentRelative> position, final @Nonnull VectorReadable2I size) throws ConstraintError { super(parent, position, size); } @Override public void buttonListenerOnClick( final @Nonnull Component button) throws ConstraintError { // final Set<Component> children = // Scrollable.this.content.componentGetChildren(); // final Point<ParentRelative> pos = new Point<ParentRelative>(); // for (final Component child : children) { // final PointReadable<ParentRelative> cpos = // child.componentGetPositionParentRelative(); // pos.setXI(cpos.getXI() - 1); // pos.setYI(cpos.getYI()); // child.componentSetPositionParentRelative(pos); } @SuppressWarnings("synthetic-access") @Override public void buttonRenderPost( final @Nonnull GUIContext context) throws ConstraintError, GUIException { try { final DrawPrimitives draw = context.contextGetDrawPrimitives(); draw.renderTriangleFill( context, Scrollable.triangle_right0, this.buttonGetCurrentEdgeColor()); draw.renderTriangleFill( context, Scrollable.triangle_right1, this.buttonGetCurrentEdgeColor()); } catch (final GLException e) { throw new GUIException(e); } } @Override public void buttonRenderPre( final @Nonnull GUIContext context) throws ConstraintError, GUIException { // Unused. } @Override public void resourceDelete( final @Nonnull GLInterface gl) throws ConstraintError, GLException { // Unused. } @Override public boolean resourceIsDeleted() { return true; } @Override public String toString() { final StringBuilder builder = new StringBuilder(); builder.append("[ButtonRight "); builder.append(this.componentGetID()); builder.append("]"); return builder.toString(); } } private final class Thumb extends AbstractDragButton { private final class Ridges extends AbstractContainer { public Ridges( final @Nonnull Component parent, final @Nonnull PointReadable<ParentRelative> position, final @Nonnull VectorReadable2I size) throws ConstraintError { super(parent, position, size); } @Override public void componentRenderPostDescendants( final GUIContext context) throws ConstraintError, GUIException { // Unused. } @SuppressWarnings("synthetic-access") @Override public void componentRenderPreDescendants( final @Nonnull GUIContext context) throws ConstraintError, GUIException { try { final DrawPrimitives draw = context.contextGetDrawPrimitives(); final VectorReadable3F color = Thumb.this.buttonGetCurrentEdgeColor(); draw.renderLine( context, Scrollable.H_THUMB_LINE0_POINT_0, Scrollable.H_THUMB_LINE0_POINT_1, color); draw.renderLine( context, Scrollable.H_THUMB_LINE1_POINT_0, Scrollable.H_THUMB_LINE1_POINT_1, color); draw.renderLine( context, Scrollable.H_THUMB_LINE2_POINT_0, Scrollable.H_THUMB_LINE2_POINT_1, color); } catch (final GLException e) { throw new GUIException(e); } } @Override public String toString() { final StringBuilder builder = new StringBuilder(); builder.append("[Ridges "); builder.append(this.componentGetID()); builder.append("]"); return builder.toString(); } } private final @Nonnull Ridges ridges; public Thumb( final @Nonnull Component parent, final @Nonnull PointReadable<ParentRelative> position, final @Nonnull VectorReadable2I size) throws ConstraintError { super(parent, position, size); this.ridges = new Ridges( this, PointConstants.PARENT_ORIGIN, Scrollable.SCROLLBAR_BUTTON_SIZE); } @Override public void buttonListenerOnClick( final @Nonnull Component button) throws GUIException, ConstraintError { // Unused. } @Override public void buttonRenderPost( final @Nonnull GUIContext context) throws ConstraintError, GUIException { // Unused. } @Override public void buttonRenderPre( final @Nonnull GUIContext context) throws ConstraintError, GUIException { ComponentAlignment.setPositionContainerCenter(this.ridges); } private void doDrag() throws ConstraintError { this.doDragUpdateThumbPosition(); } private void doDragUpdateThumbPosition() throws ConstraintError { final PointReadable<ScreenRelative> delta = this.dragGetDeltaFromInitial(); final Point<ParentRelative> component_start = this.dragGetComponentInitial(); final Point<ParentRelative> new_pos = new Point<ParentRelative>(); new_pos.setXI(component_start.getXI() + delta.getXI()); new_pos.setYI(0); this.componentSetPositionParentRelative(new_pos); } @Override public void dragListenerOnDrag( final @Nonnull GUIContext context, final @Nonnull PointReadable<ScreenRelative> start, final @Nonnull PointReadable<ScreenRelative> current, final @Nonnull Component initial) throws ConstraintError, GUIException { this.doDrag(); } @Override public void dragListenerOnRelease( final @Nonnull GUIContext context, final @Nonnull PointReadable<ScreenRelative> start, final @Nonnull PointReadable<ScreenRelative> current, final @Nonnull Component initial, final @Nonnull Component actual) throws ConstraintError, GUIException { this.doDrag(); } @Override public void dragListenerOnStart( final @Nonnull GUIContext context, final @Nonnull PointReadable<ScreenRelative> start, final @Nonnull Component initial) throws ConstraintError, GUIException { // Unused. } @Override public void resourceDelete( final @Nonnull GLInterface gl) throws ConstraintError, GLException { // Unused. } @Override public boolean resourceIsDeleted() { return true; } @Override public String toString() { final StringBuilder builder = new StringBuilder(); builder.append("[Thumb "); builder.append(this.componentGetID()); builder.append("]"); return builder.toString(); } } private final class Trough extends AbstractContainer { public Trough( final @Nonnull Component parent, final @Nonnull PointReadable<ParentRelative> position, final @Nonnull VectorReadable2I size) throws ConstraintError { super(parent, position, size); } @Override public void componentRenderPostDescendants( final GUIContext context) throws ConstraintError, GUIException { // Unused. } @Override public void componentRenderPreDescendants( final GUIContext context) throws ConstraintError, GUIException { try { final DrawPrimitives draw = context.contextGetDrawPrimitives(); final Theme theme = context.contextGetTheme(); final VectorReadable2I size = this.componentGetSize(); final Window window = this.componentGetWindow(); assert window != null; VectorReadable3F fill_color = null; VectorReadable3F edge_color = null; final int edge_width = 1; if (window.windowIsFocused()) { if (this.componentIsEnabled()) { fill_color = theme.getFocusedComponentBackgroundColor(); edge_color = theme.getFocusedComponentEdgeColor(); } else { fill_color = theme.getFocusedComponentDisabledBackgroundColor(); edge_color = theme.getFocusedComponentDisabledEdgeColor(); } } else { if (this.componentIsEnabled()) { fill_color = theme.getUnfocusedComponentBackgroundColor(); edge_color = theme.getUnfocusedComponentEdgeColor(); } else { fill_color = theme.getUnfocusedComponentDisabledBackgroundColor(); edge_color = theme.getUnfocusedComponentDisabledEdgeColor(); } } assert fill_color != null; assert edge_color != null; draw.renderRectangleFill(context, size, fill_color); draw.renderRectangleEdge(context, size, edge_width, edge_color); } catch (final GLException e) { throw new GUIException(e); } } } private final @Nonnull ButtonLeft button_left; private final @Nonnull ButtonRight button_right; private final @Nonnull Trough trough; private final @Nonnull Thumb thumb; public ScrollBarHorizontal( final @Nonnull GUIContext context, final @Nonnull Component component, final @Nonnull PointReadable<ParentRelative> position, final @Nonnull VectorReadable2I size) throws ConstraintError { super(component, position, size); this.button_left = new ButtonLeft( this, PointConstants.PARENT_ORIGIN, Scrollable.SCROLLBAR_BUTTON_SIZE); this.button_right = new ButtonRight( this, PointConstants.PARENT_ORIGIN, Scrollable.SCROLLBAR_BUTTON_SIZE); final int trough_w = this.componentGetWidth() - (Scrollable.SCROLLBAR_BUTTON_SIZE.getXI() * 2); final int trough_h = Scrollable.SCROLLBAR_BUTTON_SIZE.getYI(); this.trough = new Trough(this, PointConstants.PARENT_ORIGIN, new VectorI2I( trough_w, trough_h)); this.thumb = new Thumb( this.trough, PointConstants.PARENT_ORIGIN, Scrollable.SCROLLBAR_BUTTON_SIZE); this.thumb.componentSetMinimumWidth( context, Scrollable.SCROLLBAR_BUTTON_SIZE.getXI()); ComponentLimits.setMaximumXYContainer(ScrollBarHorizontal.this.thumb); this.button_right .componentSetWidthResizeBehavior(ParentResizeBehavior.BEHAVIOR_MOVE); this.trough .componentSetWidthResizeBehavior(ParentResizeBehavior.BEHAVIOR_RESIZE); ComponentAlignment.setPositionContainerTopLeft(this.button_left, 0); ComponentAlignment.setPositionRelativeRightOfSameY( this.trough, 0, this.button_left); ComponentAlignment.setPositionRelativeRightOfSameY( this.button_right, 0, this.trough); } @Override public void componentRenderPostDescendants( final @Nonnull GUIContext context) throws ConstraintError, GUIException { // Unused. } @Override public void componentRenderPreDescendants( final @Nonnull GUIContext context) throws ConstraintError, GUIException { // Unused. } int getTroughWidth() { return this.trough.componentGetWidth(); } @Override public void resourceDelete( final @Nonnull GLInterface gl) throws ConstraintError, GLException { // Unused. } @Override public boolean resourceIsDeleted() { return true; } void setThumbWidth( final @Nonnull GUIContext context, final int width) throws ConstraintError { this.thumb.componentSetSize(context, new VectorI2I( width, Scrollable.SCROLLBAR_BUTTON_SIZE.getYI())); ComponentLimits.setMaximumXYContainer(this.thumb); } @Override public String toString() { final StringBuilder builder = new StringBuilder(); builder.append("[ScrollBarHorizontal "); builder.append(this.componentGetID()); builder.append("]"); return builder.toString(); } } private final class ScrollBarVertical extends Component { private final class ButtonDown extends AbstractRepeatingButton { public ButtonDown( final @Nonnull ScrollBarVertical parent, final @Nonnull PointReadable<ParentRelative> position, final @Nonnull VectorReadable2I size) throws ConstraintError { super(parent, position, size); } @Override public void buttonListenerOnClick( final @Nonnull Component button) { // Unused. } @SuppressWarnings("synthetic-access") @Override public void buttonRenderPost( final @Nonnull GUIContext context) throws ConstraintError, GUIException { try { final DrawPrimitives draw = context.contextGetDrawPrimitives(); draw.renderTriangleFill( context, Scrollable.triangle_down0, this.buttonGetCurrentEdgeColor()); draw.renderTriangleFill( context, Scrollable.triangle_down1, this.buttonGetCurrentEdgeColor()); } catch (final GLException e) { throw new GUIException(e); } } @Override public void buttonRenderPre( final @Nonnull GUIContext context) throws ConstraintError, GUIException { // Unused. } @Override public void resourceDelete( final @Nonnull GLInterface gl) throws ConstraintError, GLException { // Unused. } @Override public boolean resourceIsDeleted() { return true; } @Override public String toString() { final StringBuilder builder = new StringBuilder(); builder.append("[ButtonRight "); builder.append(this.componentGetID()); builder.append("]"); return builder.toString(); } } private final class ButtonUp extends AbstractRepeatingButton { public ButtonUp( final @Nonnull ScrollBarVertical parent, final @Nonnull PointReadable<ParentRelative> position, final @Nonnull VectorReadable2I size) throws ConstraintError { super(parent, position, size); } @Override public void buttonListenerOnClick( final @Nonnull Component button) { // Unused. } @SuppressWarnings("synthetic-access") @Override public void buttonRenderPost( final @Nonnull GUIContext context) throws ConstraintError, GUIException { try { final DrawPrimitives draw = context.contextGetDrawPrimitives(); draw.renderTriangleFill( context, Scrollable.triangle_up0, this.buttonGetCurrentEdgeColor()); draw.renderTriangleFill( context, Scrollable.triangle_up1, this.buttonGetCurrentEdgeColor()); } catch (final GLException e) { throw new GUIException(e); } } @Override public void buttonRenderPre( final @Nonnull GUIContext context) throws ConstraintError, GUIException { // Unused. } @Override public void resourceDelete( final @Nonnull GLInterface gl) throws ConstraintError, GLException { // Unused. } @Override public boolean resourceIsDeleted() { return true; } @Override public String toString() { final StringBuilder builder = new StringBuilder(); builder.append("[ButtonUp "); builder.append(this.componentGetID()); builder.append("]"); return builder.toString(); } } private final class Thumb extends AbstractDragButton { private final class Ridges extends AbstractContainer { public Ridges( final @Nonnull Component parent, final @Nonnull PointReadable<ParentRelative> position, final @Nonnull VectorReadable2I size) throws ConstraintError { super(parent, position, size); } @Override public void componentRenderPostDescendants( final GUIContext context) throws ConstraintError, GUIException { // Unused. } @SuppressWarnings("synthetic-access") @Override public void componentRenderPreDescendants( final @Nonnull GUIContext context) throws ConstraintError, GUIException { try { final DrawPrimitives draw = context.contextGetDrawPrimitives(); final VectorReadable3F color = Thumb.this.buttonGetCurrentEdgeColor(); draw.renderLine( context, Scrollable.V_THUMB_LINE0_POINT_0, Scrollable.V_THUMB_LINE0_POINT_1, color); draw.renderLine( context, Scrollable.V_THUMB_LINE1_POINT_0, Scrollable.V_THUMB_LINE1_POINT_1, color); draw.renderLine( context, Scrollable.V_THUMB_LINE2_POINT_0, Scrollable.V_THUMB_LINE2_POINT_1, color); } catch (final GLException e) { throw new GUIException(e); } } @Override public String toString() { final StringBuilder builder = new StringBuilder(); builder.append("[Ridges "); builder.append(this.componentGetID()); builder.append("]"); return builder.toString(); } } private final Ridges ridges; public Thumb( final @Nonnull Component parent, final @Nonnull PointReadable<ParentRelative> position, final @Nonnull VectorReadable2I size) throws ConstraintError { super(parent, position, size); this.ridges = new Ridges( this, PointConstants.PARENT_ORIGIN, Scrollable.SCROLLBAR_BUTTON_SIZE); } @Override public void buttonListenerOnClick( final @Nonnull Component button) throws GUIException, ConstraintError { // Unused. } @Override public void buttonRenderPost( final @Nonnull GUIContext context) throws ConstraintError, GUIException { // Unused. } @Override public void buttonRenderPre( final @Nonnull GUIContext context) throws ConstraintError, GUIException { ComponentAlignment.setPositionContainerCenter(this.ridges); } private void doDrag() throws ConstraintError { final Point<ParentRelative> component_start = this.dragGetComponentInitial(); final PointReadable<ScreenRelative> delta = this.dragGetDeltaFromInitial(); final Point<ParentRelative> new_pos = new Point<ParentRelative>(); new_pos.setXI(0); new_pos.setYI(component_start.getYI() + delta.getYI()); this.componentSetPositionParentRelative(new_pos); } @Override public void dragListenerOnDrag( final @Nonnull GUIContext context, final @Nonnull PointReadable<ScreenRelative> start, final @Nonnull PointReadable<ScreenRelative> current, final @Nonnull Component initial) throws ConstraintError, GUIException { this.doDrag(); } @Override public void dragListenerOnRelease( final @Nonnull GUIContext context, final @Nonnull PointReadable<ScreenRelative> start, final @Nonnull PointReadable<ScreenRelative> current, final @Nonnull Component initial, final @Nonnull Component actual) throws ConstraintError, GUIException { this.doDrag(); } @Override public void dragListenerOnStart( final @Nonnull GUIContext context, final @Nonnull PointReadable<ScreenRelative> start, final @Nonnull Component initial) throws ConstraintError, GUIException { // Unused. } @Override public void resourceDelete( final @Nonnull GLInterface gl) throws ConstraintError, GLException { // Unused. } @Override public boolean resourceIsDeleted() { return true; } @Override public String toString() { final StringBuilder builder = new StringBuilder(); builder.append("[Thumb "); builder.append(this.componentGetID()); builder.append("]"); return builder.toString(); } } private final class Trough extends AbstractContainer { public Trough( final @Nonnull Component parent, final @Nonnull PointReadable<ParentRelative> position, final @Nonnull VectorReadable2I size) throws ConstraintError { super(parent, position, size); } @Override public void componentRenderPostDescendants( final GUIContext context) throws ConstraintError, GUIException { // Unused. } @Override public void componentRenderPreDescendants( final GUIContext context) throws ConstraintError, GUIException { try { final DrawPrimitives draw = context.contextGetDrawPrimitives(); final Theme theme = context.contextGetTheme(); final VectorReadable2I size = this.componentGetSize(); final Window window = this.componentGetWindow(); assert window != null; VectorReadable3F fill_color = null; VectorReadable3F edge_color = null; final int edge_width = 1; if (window.windowIsFocused()) { if (this.componentIsEnabled()) { fill_color = theme.getFocusedComponentBackgroundColor(); edge_color = theme.getFocusedComponentEdgeColor(); } else { fill_color = theme.getFocusedComponentDisabledBackgroundColor(); edge_color = theme.getFocusedComponentDisabledEdgeColor(); } } else { if (this.componentIsEnabled()) { fill_color = theme.getUnfocusedComponentBackgroundColor(); edge_color = theme.getUnfocusedComponentEdgeColor(); } else { fill_color = theme.getUnfocusedComponentDisabledBackgroundColor(); edge_color = theme.getUnfocusedComponentDisabledEdgeColor(); } } assert fill_color != null; assert edge_color != null; draw.renderRectangleFill(context, size, fill_color); draw.renderRectangleEdge(context, size, edge_width, edge_color); } catch (final GLException e) { throw new GUIException(e); } } } private final @Nonnull ButtonUp button_up; private final @Nonnull ButtonDown button_down; private final @Nonnull Trough trough; private final @Nonnull Thumb thumb; public ScrollBarVertical( final @Nonnull GUIContext context, final @Nonnull Component component, final @Nonnull PointReadable<ParentRelative> position, final @Nonnull VectorReadable2I size) throws ConstraintError { super(component, position, size); this.button_up = new ButtonUp( this, PointConstants.PARENT_ORIGIN, Scrollable.SCROLLBAR_BUTTON_SIZE); this.button_down = new ButtonDown( this, PointConstants.PARENT_ORIGIN, Scrollable.SCROLLBAR_BUTTON_SIZE); final int trough_h = this.componentGetHeight() - (Scrollable.SCROLLBAR_BUTTON_SIZE.getYI() * 2); final int trough_w = Scrollable.SCROLLBAR_BUTTON_SIZE.getXI(); this.trough = new Trough(this, PointConstants.PARENT_ORIGIN, new VectorI2I( trough_w, trough_h)); this.thumb = new Thumb( this.trough, PointConstants.PARENT_ORIGIN, Scrollable.SCROLLBAR_BUTTON_SIZE); this.thumb.componentSetMinimumHeight( context, Scrollable.SCROLLBAR_BUTTON_SIZE.getYI()); ComponentLimits.setMaximumXYContainer(this.thumb); this.button_down .componentSetHeightResizeBehavior(ParentResizeBehavior.BEHAVIOR_MOVE); this.trough .componentSetHeightResizeBehavior(ParentResizeBehavior.BEHAVIOR_RESIZE); ComponentAlignment.setPositionContainerTopLeft(this.button_up, 0); ComponentAlignment.setPositionRelativeBelowSameX( this.trough, 0, this.button_up); ComponentAlignment.setPositionRelativeBelowSameX( this.button_down, 0, this.trough); } @Override public void componentRenderPostDescendants( final @Nonnull GUIContext context) throws ConstraintError, GUIException { // Unused. } @Override public void componentRenderPreDescendants( final @Nonnull GUIContext context) throws ConstraintError, GUIException { // Unused. } public int getTroughHeight() { return this.trough.componentGetHeight(); } @Override public void resourceDelete( final @Nonnull GLInterface gl) throws ConstraintError, GLException { // TODO Auto-generated method stub } @Override public boolean resourceIsDeleted() { // TODO Auto-generated method stub return false; } public void setThumbHeight( final GUIContext context, final int height) throws ConstraintError { this.thumb.componentSetSize(context, new VectorI2I( Scrollable.SCROLLBAR_BUTTON_SIZE.getXI(), height)); ComponentLimits.setMaximumXYContainer(this.thumb); } @Override public String toString() { final StringBuilder builder = new StringBuilder(); builder.append("[ScrollBarVertical "); builder.append(this.componentGetID()); builder.append("]"); return builder.toString(); } } private static final @Nonnull Triangle triangle_left0; private static final @Nonnull Triangle triangle_left1; private static final @Nonnull Triangle triangle_right0; private static final @Nonnull Triangle triangle_right1; private static final @Nonnull Triangle triangle_down0; private static final @Nonnull Triangle triangle_down1; private static final @Nonnull Triangle triangle_up0; private static final @Nonnull Triangle triangle_up1; private static final @Nonnull VectorI2I H_THUMB_LINE0_POINT_0; private static final @Nonnull VectorI2I H_THUMB_LINE1_POINT_0; private static final @Nonnull VectorI2I H_THUMB_LINE1_POINT_1; private static final @Nonnull VectorI2I H_THUMB_LINE2_POINT_0; private static final @Nonnull VectorI2I H_THUMB_LINE2_POINT_1; private static final @Nonnull VectorI2I H_THUMB_LINE0_POINT_1; private static final @Nonnull VectorI2I V_THUMB_LINE0_POINT_0; private static final @Nonnull VectorI2I V_THUMB_LINE1_POINT_0; private static final @Nonnull VectorI2I V_THUMB_LINE1_POINT_1; private static final @Nonnull VectorI2I V_THUMB_LINE2_POINT_0; private static final @Nonnull VectorI2I V_THUMB_LINE2_POINT_1; private static final @Nonnull VectorI2I V_THUMB_LINE0_POINT_1; static { { H_SCROLLBAR_WIDTH = 14; V_SCROLLBAR_HEIGHT = 14; SCROLLBAR_BUTTON_SIZE = new VectorI2I( Scrollable.H_SCROLLBAR_WIDTH, Scrollable.V_SCROLLBAR_HEIGHT); } { H_THUMB_LINE0_POINT_0 = new VectorI2I(4, 4); H_THUMB_LINE0_POINT_1 = new VectorI2I(4, Scrollable.V_SCROLLBAR_HEIGHT - 4); H_THUMB_LINE1_POINT_0 = new VectorI2I(Scrollable.H_SCROLLBAR_WIDTH / 2, 4); H_THUMB_LINE1_POINT_1 = new VectorI2I( Scrollable.H_SCROLLBAR_WIDTH / 2, Scrollable.V_SCROLLBAR_HEIGHT - 4); H_THUMB_LINE2_POINT_0 = new VectorI2I(Scrollable.H_SCROLLBAR_WIDTH - 4, 4); H_THUMB_LINE2_POINT_1 = new VectorI2I( Scrollable.H_SCROLLBAR_WIDTH - 4, Scrollable.V_SCROLLBAR_HEIGHT - 4); } { V_THUMB_LINE0_POINT_0 = new VectorI2I(4, 4); V_THUMB_LINE0_POINT_1 = new VectorI2I(Scrollable.H_SCROLLBAR_WIDTH - 4, 4); V_THUMB_LINE1_POINT_0 = new VectorI2I(4, Scrollable.V_SCROLLBAR_HEIGHT / 2); V_THUMB_LINE1_POINT_1 = new VectorI2I( Scrollable.H_SCROLLBAR_WIDTH - 4, Scrollable.V_SCROLLBAR_HEIGHT / 2); V_THUMB_LINE2_POINT_0 = new VectorI2I(4, Scrollable.V_SCROLLBAR_HEIGHT - 4); V_THUMB_LINE2_POINT_1 = new VectorI2I( Scrollable.H_SCROLLBAR_WIDTH - 4, Scrollable.V_SCROLLBAR_HEIGHT - 4); } { final int x_off = 5; final int y_off = 3; final VectorI2I tl0p0 = new VectorI2I(0 + x_off, 4 + y_off); final VectorI2I tl0p1 = new VectorI2I(3 + x_off, 4 + y_off); final VectorI2I tl0p2 = new VectorI2I(3 + x_off, 0 + y_off); triangle_left0 = new Triangle(tl0p0, tl0p1, tl0p2); final VectorI2I tl1p0 = new VectorI2I(0 + x_off, 3 + y_off); final VectorI2I tl1p1 = new VectorI2I(3 + x_off, 7 + y_off); final VectorI2I tl1p2 = new VectorI2I(3 + x_off, 3 + y_off); triangle_left1 = new Triangle(tl1p0, tl1p1, tl1p2); } { final int x_off = 6; final int y_off = 3; final VectorI2I tr0p0 = new VectorI2I(0 + x_off, 0 + y_off); final VectorI2I tr0p1 = new VectorI2I(0 + x_off, 4 + y_off); final VectorI2I tr0p2 = new VectorI2I(4 + x_off, 4 + y_off); triangle_right0 = new Triangle(tr0p0, tr0p1, tr0p2); final VectorI2I tr1p0 = new VectorI2I(0 + x_off, 3 + y_off); final VectorI2I tr1p1 = new VectorI2I(0 + x_off, 7 + y_off); final VectorI2I tr1p2 = new VectorI2I(4 + x_off, 3 + y_off); triangle_right1 = new Triangle(tr1p0, tr1p1, tr1p2); } { final int x_off = 3; final int y_off = 6; final VectorI2I td0p0 = new VectorI2I(0 + x_off, 0 + y_off); final VectorI2I td0p1 = new VectorI2I(4 + x_off, 3 + y_off); final VectorI2I td0p2 = new VectorI2I(4 + x_off, 0 + y_off); triangle_down0 = new Triangle(td0p0, td0p1, td0p2); final VectorI2I td1p0 = new VectorI2I(3 + x_off, 0 + y_off); final VectorI2I td1p1 = new VectorI2I(3 + x_off, 3 + y_off); final VectorI2I td1p2 = new VectorI2I(7 + x_off, 0 + y_off); triangle_down1 = new Triangle(td1p0, td1p1, td1p2); } { final int x_off = 3; final int y_off = 5; final VectorI2I tu0p0 = new VectorI2I(0 + x_off, 3 + y_off); final VectorI2I tu0p1 = new VectorI2I(4 + x_off, 3 + y_off); final VectorI2I tu0p2 = new VectorI2I(4 + x_off, 0 + y_off); triangle_up0 = new Triangle(tu0p0, tu0p1, tu0p2); final VectorI2I tu1p0 = new VectorI2I(3 + x_off, 3 + y_off); final VectorI2I tu1p1 = new VectorI2I(7 + x_off, 3 + y_off); final VectorI2I tu1p2 = new VectorI2I(3 + x_off, 0 + y_off); triangle_up1 = new Triangle(tu1p0, tu1p1, tu1p2); } } private final @Nonnull AbstractContainer content; private final @Nonnull ScrollBarHorizontal scroll_h; private final @Nonnull ScrollBarVertical scroll_v; private final @Nonnull VectorM2I minimum_child = new VectorM2I(); private final @Nonnull VectorM2I maximum_child = new VectorM2I(); private final @Nonnull VectorM2I span_children = new VectorM2I(); private final @Nonnull VectorM2I span_trough = new VectorM2I(); private final @Nonnull VectorM2I span_pane = new VectorM2I(); static final int H_SCROLLBAR_WIDTH; static final int V_SCROLLBAR_HEIGHT; static final @Nonnull VectorReadable2I SCROLLBAR_BUTTON_SIZE; public Scrollable( final @Nonnull GUIContext context, final @Nonnull Component parent, final @Nonnull AbstractContainer content) throws ConstraintError { super(parent, content.componentGetPositionParentRelative(), content .componentGetSize()); { /* * Take ownership of content area. Resize it and position. */ final VectorM2I content_size = new VectorM2I(content.componentGetSize()); content_size.y -= Scrollable.H_SCROLLBAR_WIDTH; content_size.x -= Scrollable.V_SCROLLBAR_HEIGHT; this.content = content; if (this.content.componentHasParent()) { this.content.componentDetachFromParent(); } this.content.componentAttachToParent(this); this.content .componentSetPositionParentRelative(PointConstants.PARENT_ORIGIN); this.content.componentSetSize(context, content_size); this.content .componentSetHeightResizeBehavior(ParentResizeBehavior.BEHAVIOR_RESIZE); this.content .componentSetWidthResizeBehavior(ParentResizeBehavior.BEHAVIOR_RESIZE); } { /* * Initialize horizontal scrollbar. */ final VectorM2I scroll_h_size = new VectorM2I(); scroll_h_size.x = this.componentGetWidth(); scroll_h_size.x -= Scrollable.H_SCROLLBAR_WIDTH; scroll_h_size.y = Scrollable.V_SCROLLBAR_HEIGHT; this.scroll_h = new ScrollBarHorizontal( context, this, PointConstants.PARENT_ORIGIN, scroll_h_size); this.scroll_h .componentSetWidthResizeBehavior(ParentResizeBehavior.BEHAVIOR_RESIZE); this.scroll_h .componentSetHeightResizeBehavior(ParentResizeBehavior.BEHAVIOR_MOVE); ComponentAlignment.setPositionRelativeBelowSameX( this.scroll_h, -1, content); } { /* * Initialize vertical scrollbar. */ final VectorM2I scroll_v_size = new VectorM2I(); scroll_v_size.x = Scrollable.H_SCROLLBAR_WIDTH; scroll_v_size.y = this.componentGetHeight(); scroll_v_size.y -= Scrollable.V_SCROLLBAR_HEIGHT; this.scroll_v = new ScrollBarVertical( context, this, PointConstants.PARENT_ORIGIN, scroll_v_size); this.scroll_v .componentSetWidthResizeBehavior(ParentResizeBehavior.BEHAVIOR_MOVE); this.scroll_v .componentSetHeightResizeBehavior(ParentResizeBehavior.BEHAVIOR_RESIZE); ComponentAlignment.setPositionRelativeRightOfSameY( this.scroll_v, -1, content); } } @Override public void componentRenderPostDescendants( final @Nonnull GUIContext context) throws ConstraintError, GUIException { // Unused. } @Override public void componentRenderPreDescendants( final @Nonnull GUIContext context) throws ConstraintError, GUIException { this.reconfigureScrollbars(context); } /** * Determine the current "spans": the difference between the left edge of * the leftmost child and the right edge of the rightmost child, the * difference between the top edge of the top child and the bottom edge of * the bottom child, etc... */ private void reconfigureCalculateSpans() { final Set<Component> children = this.content.componentGetChildren(); this.minimum_child.x = Integer.MAX_VALUE; this.minimum_child.y = Integer.MAX_VALUE; this.maximum_child.x = Integer.MIN_VALUE; this.maximum_child.y = Integer.MIN_VALUE; for (final Component child : children) { final PointReadable<ParentRelative> pos = child.componentGetPositionParentRelative(); this.minimum_child.x = Math.min(this.minimum_child.x, pos.getXI()); this.maximum_child.x = Math.max( this.maximum_child.x, pos.getXI() + child.componentGetWidth()); this.minimum_child.y = Math.min(this.minimum_child.y, pos.getYI()); this.maximum_child.y = Math.max( this.maximum_child.y, pos.getYI() + child.componentGetHeight()); } assert this.maximum_child.x >= this.minimum_child.x; assert this.maximum_child.y >= this.minimum_child.y; this.span_children.x = this.maximum_child.x - this.minimum_child.x; this.span_children.y = this.maximum_child.y - this.minimum_child.y; this.span_trough.x = this.scroll_h.getTroughWidth(); this.span_trough.y = this.scroll_v.getTroughHeight(); this.span_pane.x = this.content.componentGetWidth(); this.span_pane.y = this.content.componentGetHeight(); } /** * The height of the scrollbar thumb is equal to the proportion of the * "child span" to the "pane span", multiplied by the height of the trough. * In other words, if 50% of the child span is contained within the current * pane span, the thumb height will be 50% of the height of the scrollbar * trough. */ private int reconfigureGetThumbHeight() { final double proportion = (double) this.span_pane.y / (double) this.span_children.y; return (int) (this.span_trough.y * proportion); } /** * The width of the scrollbar thumb is equal to the proportion of the * "child span" to the "pane span", multiplied by the width of the trough. * In other words, if 50% of the child span is contained within the current * pane span, the thumb width will be 50% of the width of the scrollbar * trough. */ private int reconfigureGetThumbWidth() { final double proportion = (double) this.span_pane.x / (double) this.span_children.x; return (int) (this.span_trough.x * proportion); } /** * Activate/deactive the horizontal and vertical scrollbars based on whether * or not the contents of the managed pane are within view. Resize the * scrollbar thumbs based on how much of the pane is visible. */ private void reconfigureScrollbars( final @Nonnull GUIContext context) throws ConstraintError { this.reconfigureCalculateSpans(); if (this.reconfigureShouldScrollX()) { final int thumb_width = this.reconfigureGetThumbWidth(); this.scroll_h.setThumbWidth(context, thumb_width); this.scroll_h.componentSetEnabled(true); } else { this.scroll_h.setThumbWidth(context, this.scroll_h.getTroughWidth()); this.scroll_h.componentSetEnabled(false); } if (this.reconfigureShouldScrollY()) { final int thumb_height = this.reconfigureGetThumbHeight(); this.scroll_v.setThumbHeight(context, thumb_height); this.scroll_v.componentSetEnabled(true); } else { this.scroll_v.setThumbHeight(context, this.scroll_v.getTroughHeight()); this.scroll_v.componentSetEnabled(false); } } /** * If the rightmost edge of the rightmost child is greater than the * rightmost edge of the current span, or if the leftmost edge of the * leftmost child is less than 0, the pane should scroll horizontally. */ private boolean reconfigureShouldScrollX() { return (this.minimum_child.x < 0) || (this.maximum_child.x > this.span_pane.x); } /** * If the bottom edge of the bottom child is greater than the bottom edge of * the current span, or if the top edge of the top child is less than 0, the * pane should scroll vertically. */ private boolean reconfigureShouldScrollY() { return (this.minimum_child.y < 0) || (this.maximum_child.y > this.span_pane.y); } @Override public void resourceDelete( final @Nonnull GLInterface gl) throws ConstraintError, GLException { // Unused. } @Override public boolean resourceIsDeleted() { return true; } @Override public String toString() { final StringBuilder builder = new StringBuilder(); builder.append("[Scrollable "); builder.append(this.componentGetID()); builder.append("]"); return builder.toString(); } }
package com.jcwhatever.pvs.api.arena; import com.jcwhatever.nucleus.regions.IRegion; import com.jcwhatever.nucleus.regions.RegionPriorityInfo; import com.jcwhatever.nucleus.regions.RestorableRegion; import com.jcwhatever.nucleus.regions.file.IRegionFileFactory; import com.jcwhatever.nucleus.regions.file.basic.BasicFileFactory; import com.jcwhatever.nucleus.regions.options.EnterRegionReason; import com.jcwhatever.nucleus.regions.options.LeaveRegionReason; import com.jcwhatever.nucleus.regions.options.RegionEventPriority; import com.jcwhatever.nucleus.storage.IDataNode; import com.jcwhatever.nucleus.utils.MetaKey; import com.jcwhatever.pvs.api.PVStarAPI; import com.jcwhatever.pvs.api.arena.mixins.IArenaOwned; import com.jcwhatever.pvs.api.events.region.ArenaRegionDefinedEvent; import com.jcwhatever.pvs.api.events.region.ArenaRegionPreRestoreEvent; import com.jcwhatever.pvs.api.events.region.ArenaRegionPreSaveEvent; import com.jcwhatever.pvs.api.events.region.ArenaRegionRestoredEvent; import com.jcwhatever.pvs.api.events.region.ArenaRegionSavedEvent; import com.jcwhatever.pvs.api.events.region.PlayerEnterArenaRegionEvent; import com.jcwhatever.pvs.api.events.region.PlayerLeaveArenaRegionEvent; import org.bukkit.Location; import org.bukkit.entity.Player; /** * A region that represents the bounds of an arena. */ @RegionPriorityInfo(enter = RegionEventPriority.HIGH, leave = RegionEventPriority.LOW) public class ArenaRegion extends RestorableRegion implements IArenaOwned { public static final MetaKey<ArenaRegion> ARENA_REGION_KEY = new MetaKey<ArenaRegion>(ArenaRegion.class); private final IArena _arena; private final FileFactory _fileFactory = new FileFactory(); /** * Constructor. * * @param arena The owning arena. * @param dataNode The regions data node. */ public ArenaRegion(IArena arena, IDataNode dataNode) { super(PVStarAPI.getPlugin(), arena.getId().toString(), dataNode); _arena = arena; getMeta().setKey(ARENA_REGION_KEY, this); setEventListener(true); } @Override public IArena getArena() { return _arena; } @Override public IRegionFileFactory getFileFactory() { return _fileFactory; } @Override protected void onCoordsChanged(Location p1, Location p2) { super.onCoordsChanged(p1, p2); ArenaRegionDefinedEvent event = new ArenaRegionDefinedEvent(getArena()); getArena().getEventManager().call(this, event); } /** * Determine if {@link #onPlayerEnter} can be called. * * @param player The player entering the region. * * @return True to allow calling {@link #onPlayerEnter}. */ @Override protected boolean canDoPlayerEnter(Player player, EnterRegionReason reason) { return getArena().getSettings().isEnabled() && PVStarAPI.getPlugin().isEnabled(); } /** * Called when a player enters the region. * * @param p The player entering the region. */ @Override protected void onPlayerEnter(Player p, EnterRegionReason reason) { final IArenaPlayer player = PVStarAPI.getArenaPlayer(p); _arena.getEventManager().call(this, new PlayerEnterArenaRegionEvent(_arena, player, reason)); } /** * Determine if {@link #onPlayerLeave} can be called. * * @param player The player leaving the region. * * @return True to allow calling {@link #onPlayerLeave}. */ @Override protected boolean canDoPlayerLeave(Player player, LeaveRegionReason reason) { return getArena().getSettings().isEnabled() && PVStarAPI.getPlugin().isEnabled(); } /** * Called when a player leaves the region. * * @param p The player leaving the region. */ @Override protected void onPlayerLeave(Player p, LeaveRegionReason reason) { IArenaPlayer player = PVStarAPI.getArenaPlayer(p); _arena.getEventManager().call(this, new PlayerLeaveArenaRegionEvent(_arena, player, reason)); } /** * Called when the arena region is saved to disk. */ @Override protected void onPreSave() { getArena().setBusy(); _arena.getEventManager().call(this, new ArenaRegionPreSaveEvent(_arena)); } /** * Called when the arena region save operation is completed. */ @Override protected void onSaveComplete() { getArena().setIdle(); _arena.getEventManager().call(this, new ArenaRegionSavedEvent(_arena)); } /** * Called when the arena region is restored from disk. */ @Override protected void onPreRestore() { getArena().setBusy(); _arena.getEventManager().call(this, new ArenaRegionPreRestoreEvent(_arena)); } /** * Called when the arena region restore operation is complete. */ @Override protected void onRestoreComplete() { getArena().setIdle(); _arena.getEventManager().call(this, new ArenaRegionRestoredEvent(_arena)); } private class FileFactory extends BasicFileFactory { @Override public String getFilename(IRegion region) { return "arena." + _arena.getId(); } } }
package com.jwetherell.algorithms; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Random; import com.jwetherell.algorithms.data_structures.BinarySearchTree; import com.jwetherell.algorithms.data_structures.BinaryHeap; import com.jwetherell.algorithms.data_structures.BinaryHeap.TYPE; import com.jwetherell.algorithms.data_structures.Graph.Edge; import com.jwetherell.algorithms.data_structures.Graph.Vertex; import com.jwetherell.algorithms.data_structures.Graph; import com.jwetherell.algorithms.data_structures.HashMap; import com.jwetherell.algorithms.data_structures.LinkedList; import com.jwetherell.algorithms.data_structures.Queue; import com.jwetherell.algorithms.data_structures.Stack; import com.jwetherell.algorithms.graph.Dijkstra; import com.jwetherell.algorithms.graph.Dijkstra.CostPathPair; public class DataStructures { private static final int SIZE = 1000; private static int[] unsorted = null; public static void main(String[] args) { Random random = new Random(); System.out.print("Array="); unsorted = new int[SIZE]; int i=0; System.out.print("array="); while (i<unsorted.length) { int j = random.nextInt(unsorted.length*10); unsorted[i++] = j; System.out.print(j+","); } System.out.println(); System.out.println(); { // Linked List System.out.println("Linked List."); LinkedList list = new LinkedList(unsorted); System.out.println(list.toString()); int index = 0; int next = unsorted[index]; System.out.println("Removing the head of the List "+next); list.remove(next); System.out.println(list.toString()); index = unsorted.length-1; next = unsorted[index]; System.out.println("Removing the tail of the List "+next); list.remove(next); System.out.println(list.toString()); next = random.nextInt(unsorted.length*100); System.out.println("Adding a new node "+next); list.add(next); System.out.println(list.toString()); index = random.nextInt(unsorted.length); next = unsorted[index]; System.out.println("Removing a previously added node "+next); list.remove(next); System.out.println(list.toString()); /* while (list.getSize()>0) { int headValue = list.getHeadValue(); list.remove(headValue); System.out.println("Removed the head "+headValue+" from the list."); System.out.println(list.toString()); } */ System.out.println(); } { // Stack System.out.println("Stack."); Stack stack = new Stack(unsorted); System.out.println(stack.toString()); int next = random.nextInt(unsorted.length*100); System.out.println("Pushing a new node onto the Stack "+next); stack.push(next); System.out.println(stack.toString()); int node = stack.pop(); System.out.println("Popped "+node+" from the Stack."); System.out.println(stack.toString()); /* int size = stack.getSize(); for (int j=0; j<size; j++) { int node = stack.pop(); System.out.println("Popped "+node+" from the Stack."); System.out.println(stack.toString()); } */ System.out.println(); } { // Queue System.out.println("Queue."); Queue queue = new Queue(unsorted); System.out.println(queue.toString()); int next = random.nextInt(unsorted.length*100); System.out.println("Pushing a new node onto the Queue "+next); queue.enqueue(next); System.out.println(queue.toString()); /* int size = queue.getSize(); for (int j=0; j<size; j++) { int node = queue.dequeue(); System.out.println("Dequeued "+node+" from the Queue."); System.out.println(queue.toString()); } */ System.out.println(); } { // HashMap System.out.println("Hash Map."); HashMap hash = new HashMap(unsorted); System.out.println(hash.toString()); int next = random.nextInt(unsorted.length*100); System.out.println("Putting a new node into the HashMap "+next); hash.put(next,next); System.out.println(hash.toString()); hash.remove(next); System.out.println("Removed key="+next+" from the HashMap."); System.out.println(hash.toString()); /* for (int j=0; j<unsorted.length; j++) { int key = unsorted[j]; hash.remove(key); System.out.println("Removed key="+key+" from the HashMap."); System.out.println(hash.toString()); } */ System.out.println(); } { // BINARY SEARCH TREE System.out.println("Binary search tree."); BinarySearchTree bst = new BinarySearchTree(unsorted); System.out.println(bst.toString()); // Add random node int next = random.nextInt(unsorted.length*100); System.out.println("Adding a new node "+next); bst.add(next); System.out.println(bst.toString()); // Remove a previously added node next = random.nextInt(unsorted.length); System.out.println("Removing a previously added node "+unsorted[next]); bst.remove(unsorted[next]); System.out.println(bst.toString()); System.out.println(); } { // MIN-HEAP System.out.println("Min-Heap."); BinaryHeap minHeap = new BinaryHeap(unsorted); System.out.println(minHeap.toString()); int next = minHeap.getRootValue(); System.out.println("Removing the root "+next); minHeap.remove(next); System.out.println(minHeap.toString()); next = random.nextInt(unsorted.length*100); System.out.println("Adding a new node "+next); minHeap.add(next); System.out.println(minHeap.toString()); int index = random.nextInt(unsorted.length); next = unsorted[index]; System.out.println("Adding a previously added node "+next); minHeap.add(next); System.out.println(minHeap.toString()); index = random.nextInt(unsorted.length); next = unsorted[index]; System.out.println("Removing a previously added node "+next); minHeap.remove(next); System.out.println(minHeap.toString()); System.out.println(); } { // MAX-HEAP System.out.println("Max-Heap."); BinaryHeap maxHeap = new BinaryHeap(unsorted,TYPE.MAX); System.out.println(maxHeap.toString()); int next = maxHeap.getRootValue(); System.out.println("Removing the root "+next); maxHeap.remove(next); System.out.println(maxHeap.toString()); next = random.nextInt(unsorted.length*100); System.out.println("Adding a new node "+next); maxHeap.add(next); System.out.println(maxHeap.toString()); int index = random.nextInt(unsorted.length); next = unsorted[index]; System.out.println("Adding a previously added node "+next); maxHeap.add(next); System.out.println(maxHeap.toString()); index = random.nextInt(unsorted.length); next = unsorted[index]; System.out.println("Removing a previously added node "+next); maxHeap.remove(next); System.out.println(maxHeap.toString()); System.out.println(); } { // UNDIRECTED GRAPH System.out.println("Undirected Graph."); List<Vertex> verticies = new ArrayList<Vertex>(); Graph.Vertex v1 = new Graph.Vertex(1); verticies.add(v1); Graph.Vertex v2 = new Graph.Vertex(2); verticies.add(v2); Graph.Vertex v3 = new Graph.Vertex(3); verticies.add(v3); Graph.Vertex v4 = new Graph.Vertex(4); verticies.add(v4); Graph.Vertex v5 = new Graph.Vertex(5); verticies.add(v5); Graph.Vertex v6 = new Graph.Vertex(6); verticies.add(v6); List<Edge> edges = new ArrayList<Edge>(); Graph.Edge e1_2 = new Graph.Edge(7, v1, v2); edges.add(e1_2); Graph.Edge e1_3 = new Graph.Edge(9, v1, v3); edges.add(e1_3); Graph.Edge e1_6 = new Graph.Edge(14, v1, v6); edges.add(e1_6); Graph.Edge e2_3 = new Graph.Edge(10, v2, v3); edges.add(e2_3); Graph.Edge e2_4 = new Graph.Edge(15, v2, v4); edges.add(e2_4); Graph.Edge e3_4 = new Graph.Edge(11, v3, v4); edges.add(e3_4); Graph.Edge e3_6 = new Graph.Edge(2, v3, v6); edges.add(e3_6); Graph.Edge e5_6 = new Graph.Edge(9, v5, v6); edges.add(e5_6); Graph.Edge e4_5 = new Graph.Edge(6, v4, v5); edges.add(e4_5); Graph undirected = new Graph(verticies,edges); System.out.println(undirected.toString()); Graph.Vertex start = v1; System.out.println("Dijstra's shortest paths of the undirected graph from "+start.getValue()); Map<Graph.Vertex, CostPathPair> map = Dijkstra.getShortestPaths(undirected, start); System.out.println(getPathMapString(map)); Graph.Vertex end = v5; System.out.println("Dijstra's shortest path of the undirected graph from "+start.getValue()+" to "+end.getValue()); Dijkstra.CostPathPair pair = Dijkstra.getShortestPath(undirected, start, end); if (pair!=null) System.out.println(pair.toString()); else System.out.println("No path from "+start.getValue()+" to "+end.getValue()); System.out.println(); } { // DIRECTED GRAPH System.out.println("Directed Graph."); List<Vertex> verticies = new ArrayList<Vertex>(); Graph.Vertex v1 = new Graph.Vertex(1); verticies.add(v1); Graph.Vertex v2 = new Graph.Vertex(2); verticies.add(v2); Graph.Vertex v3 = new Graph.Vertex(3); verticies.add(v3); Graph.Vertex v4 = new Graph.Vertex(4); verticies.add(v4); Graph.Vertex v5 = new Graph.Vertex(5); verticies.add(v5); Graph.Vertex v6 = new Graph.Vertex(6); verticies.add(v6); Graph.Vertex v7 = new Graph.Vertex(7); verticies.add(v7); List<Edge> edges = new ArrayList<Edge>(); Graph.Edge e1_2 = new Graph.Edge(7, v1, v2); edges.add(e1_2); Graph.Edge e1_3 = new Graph.Edge(9, v1, v3); edges.add(e1_3); Graph.Edge e1_6 = new Graph.Edge(14, v1, v6); edges.add(e1_6); Graph.Edge e2_3 = new Graph.Edge(10, v2, v3); edges.add(e2_3); Graph.Edge e2_4 = new Graph.Edge(15, v2, v4); edges.add(e2_4); Graph.Edge e3_4 = new Graph.Edge(11, v3, v4); edges.add(e3_4); Graph.Edge e3_6 = new Graph.Edge(2, v3, v6); edges.add(e3_6); Graph.Edge e6_5 = new Graph.Edge(9, v6, v5); edges.add(e6_5); Graph.Edge e4_5 = new Graph.Edge(6, v4, v5); edges.add(e4_5); Graph.Edge e4_7 = new Graph.Edge(16, v4, v7); edges.add(e4_7); Graph directed = new Graph(Graph.TYPE.DIRECTED,verticies,edges); System.out.println(directed.toString()); Graph.Vertex start = v1; System.out.println("Dijstra's shortest paths of the directed graph from "+start.getValue()); Map<Graph.Vertex, CostPathPair> map = Dijkstra.getShortestPaths(directed, start); System.out.println(getPathMapString(map)); Graph.Vertex end = v5; System.out.println("Dijstra's shortest path of the directed graph from "+start.getValue()+" to "+end.getValue()); Dijkstra.CostPathPair pair = Dijkstra.getShortestPath(directed, start, end); if (pair!=null) System.out.println(pair.toString()); else System.out.println("No path from "+start.getValue()+" to "+end.getValue()); System.out.println(); } } private static final String getPathMapString(Map<Graph.Vertex, CostPathPair> map) { StringBuilder builder = new StringBuilder(); for (Graph.Vertex v : map.keySet()) { CostPathPair pair = map.get(v); builder.append("to vertex=").append(v.getValue()).append("\n"); builder.append(pair.toString()).append("\n"); } return builder.toString(); } }
package main; import java.awt.Color; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Random; import algorithms.AStar; import algorithms.Anya; import algorithms.BasicThetaStar; import algorithms.JumpPointSearch; import algorithms.StrictVisibilityGraphAlgorithm; import algorithms.StrictVisibilityGraphAlgorithmV2; import algorithms.datatypes.Point; import algorithms.datatypes.SnapshotItem; import algorithms.sparsevgs.LineOfSightScanner; import algorithms.sparsevgs.SparseVisibilityGraph; import algorithms.strictthetastar.RecursiveStrictThetaStar; import algorithms.strictthetastar.StrictThetaStar; import algorithms.visibilitygraph.VisibilityGraph; import draw.DrawCanvas; import draw.GridLineSet; import draw.GridObjects; import draw.GridPointSet; import grid.GridAndGoals; import grid.GridGraph; import grid.ReachableNodes; import grid.StartGoalPoints; import main.graphgeneration.DefaultGenerator; import main.utility.Utility; import uiandio.FileIO; import uiandio.GraphImporter; public class Experiment { public static void run() { // testVisibilityGraphSize(); // testAbilityToFindGoal(); // findStrictThetaStarIssues(); // findUpperBound(); // testAlgorithmOptimality(); //testAgainstReferenceAlgorithm(); //countTautPaths(); // other(); testLOSScan(); } /** * Custom code for experiments. */ public static void other() { // This is how to generate test data for the grid. (Use the VisibilityGraph algorithm to generate optimal path lengths) // ArrayList<Point> points = ReachableNodes.computeReachable(gridGraph, 5, 5); // System.out.println(points.size()); // generateRandomTestDataAndPrint(gridGraph); //This is how to conduct a running time / path length test for tha algorithm: // TestResult test1 = testAlgorithm(gridGraph, sx, sy, ex, ey, 1, 1); // System.out.println(test1); // TestResult test2 = testAlgorithm(gridGraph, sx, sy, ex, ey, 30, 25); // System.out.println(test2); } /** * Generates and prints out random test data for the gridGraph in question. <br> * Note: the algorithm used is the one specified in the algoFunction. * Use setDefaultAlgoFunction to choose the algorithm. * @param gridGraph the grid to test. */ private static void generateRandomTestDataAndPrint(GridGraph gridGraph) { AlgoFunction algo = AnyAnglePathfinding.setDefaultAlgoFunction(); ArrayList<Point> points = ReachableNodes.computeReachable(gridGraph, 5, 5); LinkedList<Integer> startX = new LinkedList<>(); LinkedList<Integer> startY = new LinkedList<>(); LinkedList<Integer> endX = new LinkedList<>(); LinkedList<Integer> endY = new LinkedList<>(); LinkedList<Double> length = new LinkedList<>(); int size = points.size(); System.out.println("Points: " + size); for (int i=0; i<100; i++) { Random random = new Random(); int first = random.nextInt(size); int last = random.nextInt(size-1); if (last == first) last = size-1; // prevent first and last from being the same Point s = points.get(first); Point f = points.get(last); int[][] path = Utility.generatePath(algo, gridGraph, s.x, s.y, f.x, f.y); if (path.length >= 2) { double len = Utility.computePathLength(gridGraph, path); startX.offer(s.x); startY.offer(s.y); endX.offer(f.x); endY.offer(f.y); length.offer(len); } if (i%10 == 0) System.out.println("Computed: " + i); } System.out.println(startX); System.out.println(startY); System.out.println(endX); System.out.println(endY); System.out.println(length); } /** * Returns true iff there is a path from the start to the end. Uses the current algorithm to check.<br> * Use setDefaultAlgoFunction to choose the algorithm. */ private static boolean hasSolution(AlgoFunction algo, GridGraph gridGraph, StartGoalPoints p) { int[][] path = Utility.generatePath(algo, gridGraph, p.sx, p.sy, p.ex, p.ey); return path.length > 1; } private static void testLOSScan() { GridAndGoals gridAndGoals = AnyAnglePathfinding.loadMaze(); GridGraph gridGraph = gridAndGoals.gridGraph; ArrayList<GridObjects> gridObjectsList = new ArrayList<>(); GridLineSet gridLineSet = new GridLineSet();; GridPointSet gridPointSet = new GridPointSet(); int dx, dy; Random rand = new Random(); { int sx = rand.nextInt(gridGraph.sizeX+1); int sy = rand.nextInt(gridGraph.sizeY+1); sx = gridAndGoals.startGoalPoints.sx; sy = gridAndGoals.startGoalPoints.sy; sx = 24; sy = 24; dx = -1; dy = 2; LineOfSightScanner losScanner = new LineOfSightScanner(gridGraph); try { // Expected running time: 500x500, blocked ratio 25 ==> 0.07ms to 0.1ms per iteration. int iterations = 30000; long start = System.nanoTime(); for (int i=0;i<iterations;++i) { //losScanner.computeAllVisibleTautSuccessors(rand.nextInt(gridGraph.sizeX+1), rand.nextInt(gridGraph.sizeY+1)); //losScanner.clearSnapshots(); } long end = System.nanoTime(); double totalTime = (end-start)/1000000.; // convert to milliseconds System.out.println("Total Time: " + totalTime); System.out.println("Per iteration time: " + (totalTime/iterations)); //losScanner.computeAllVisibleTwoWayTautSuccessors(sx, sy); losScanner.computeAllVisibleSuccessors(sx, sy); //losScanner.computeAllVisibleTautSuccessors(sx, sy); //losScanner.computeAllVisibleIncrementalTautSuccessors(sx, sy, dx, dy); } catch (Exception e) { e.printStackTrace(); } for (int i=0;i<losScanner.nSuccessors;++i) { int x = losScanner.successorsX[i]; int y = losScanner.successorsY[i]; gridLineSet.addLine(sx, sy, x,y, Color.GREEN); gridPointSet.addPoint(x, y, Color.RED); } //gridLineSet = generateRandomTestLines(gridGraph, 10); gridPointSet.addPoint(sx, sy, Color.BLUE); gridObjectsList.add(new GridObjects(gridLineSet, gridPointSet)); for (List<SnapshotItem> l : LineOfSightScanner.snapshotList) { gridObjectsList.add(GridObjects.create(l)); } } DrawCanvas drawCanvas = new DrawCanvas(gridGraph, gridLineSet); Visualisation.setupMainFrame(drawCanvas, gridObjectsList); } /** * Generates random lines on the map. Used to test whether the line-of-sight * algorithm is correct. Returns a gridLineSet containing all the test lines. */ private static GridLineSet generateRandomTestLines(GridGraph gridGraph, int amount) { GridLineSet gridLineSet = new GridLineSet(); Random rand = new Random(); for (int i=0; i<amount; i++) { int x1 = rand.nextInt(gridGraph.sizeX); int y1 = rand.nextInt(gridGraph.sizeY); int x2 = rand.nextInt(gridGraph.sizeX); int y2 = rand.nextInt(gridGraph.sizeY); Experiment.testAndAddLine(x1,y1,x2,y2,gridGraph,gridLineSet); } return gridLineSet; } /** * Tests a set of coordinates for line-of-sight. Adds a green line to the * gridLineSet if there is line-of-sight between (x1,y1) and (x2,y2). * Adds a red line otherwise. */ private static void testAndAddLine(int x1, int y1, int x2, int y2, GridGraph gridGraph, GridLineSet gridLineSet) { if (gridGraph.lineOfSight(x1, y1, x2, y2)) { gridLineSet.addLine(x1, y1, x2, y2, Color.GREEN); } else { gridLineSet.addLine(x1, y1, x2, y2, Color.RED); } } private static void testAgainstReferenceAlgorithm() { AnyAnglePathfinding.setDefaultAlgoFunction(); AlgoFunction currentAlgo = AnyAnglePathfinding.setDefaultAlgoFunction(); AlgoFunction referenceAlgo = AStar::new; Random seedRand = new Random(3); int initial = seedRand.nextInt(); for (int i=0; i<500000; i++) { int sizeX = seedRand.nextInt(70) + 10; int sizeY = seedRand.nextInt(70) + 10; int seed = i+initial; int ratio = seedRand.nextInt(40) + 5; int max = (sizeX+1)*(sizeY+1); int p1 = seedRand.nextInt(max); int p2 = seedRand.nextInt(max-1); if (p2 == p1) { p2 = max-1; } int sx = p1%(sizeX+1); int sy = p1/(sizeX+1); int ex = p2%(sizeX+1); int ey = p2/(sizeX+1); GridGraph gridGraph = DefaultGenerator.generateSeededGraphOnlyOld(seed, sizeX, sizeY, ratio); int[][] path = Utility.generatePath(referenceAlgo, gridGraph, sx, sy, ex, ey); double referencePathLength = Utility.computePathLength(gridGraph, path); boolean referenceValid = (referencePathLength > 0.00001f); path = Utility.generatePath(currentAlgo, gridGraph, sx, sy, ex, ey); double algoPathLength = Utility.computePathLength(gridGraph, path); boolean algoValid = (referencePathLength > 0.00001f); if (referenceValid != algoValid) { System.out.println("============"); System.out.println("Validity Discrepancy Discovered!"); System.out.println("Seed = " + seed +" , Ratio = " + ratio + " , Size: x=" + sizeX + " y=" + sizeY); System.out.println("Start = " + sx + "," + sy + " End = " + ex + "," + ey); System.out.println("Reference: " + referenceValid + " , Current: " + algoValid); System.out.println("============"); throw new UnsupportedOperationException("DISCREPANCY!!"); } else { if (Math.abs(algoPathLength - referencePathLength) > 0.0001) { System.out.println("============"); System.out.println("Path Length Discrepancy Discovered!"); System.out.println("Seed = " + seed +" , Ratio = " + ratio + " , Size: x=" + sizeX + " y=" + sizeY); System.out.println("Start = " + sx + "," + sy + " End = " + ex + "," + ey); System.out.println("Reference: " + referencePathLength + " , Current: " + algoPathLength); System.out.println("============"); throw new UnsupportedOperationException("DISCREPANCY!!"); } if (i%1000 == 0) System.out.println("OK: Seed = " + seed +" , Ratio = " + ratio + " , Size: x=" + sizeX + " y=" + sizeY); } } } /** * Tests random generated maps of various sizes and obstacle densities for * the size of the visibility graphs.<br> * The results are output to the file VisibilityGraphSizes.txt. */ private static void testVisibilityGraphSize() { FileIO fileIO = FileIO.csv(AnyAnglePathfinding.PATH_ANALYSISDATA + "VisibilityGraphSizes.csv"); Random seedGenerator = new Random(9191); fileIO.writeRow("Seed", "Size", "UnblockedRatio", "%Blocked", "VG Vertices", "VG Edges (Directed)", "SVG Vertices", "SVG Edges (Directed)"); for (int i=0; i<50; i++) { int currentSize = 10 + i*10; for (int r=0; r<3; r++) { int currentRatio = (r == 0 ? 7 : (r == 1 ? 15 : 50)); int currentSeed = seedGenerator.nextInt(); GridGraph gridGraph = DefaultGenerator.generateSeededGraphOnly(currentSeed, currentSize, currentSize, currentRatio, 0, 0, currentSize, currentSize); String seedString = currentSeed + ""; String sizeString = currentSize + ""; String ratioString = currentRatio + ""; String perBlockedString = gridGraph.getPercentageBlocked()*100f + ""; VisibilityGraph vGraph = new VisibilityGraph(gridGraph, 0, 0, currentSize, currentSize); vGraph.initialise(); String verticesString = vGraph.size() + ""; String edgesString = vGraph.computeSumDegrees() + ""; SparseVisibilityGraph svGraph = new SparseVisibilityGraph(gridGraph); svGraph.initialise(0, 0, currentSize, currentSize); String sverticesString = svGraph.size() + ""; String sedgesString = svGraph.computeSumDegrees() + ""; fileIO.writeRow(seedString, sizeString, ratioString, perBlockedString, verticesString, edgesString, sverticesString, sedgesString); fileIO.flush(); } } fileIO.close(); } private static void findUpperBound() { System.out.println("Strict Theta Star"); AlgoFunction testAlgo = (gridGraph, sx, sy, ex, ey) -> new RecursiveStrictThetaStar(gridGraph, sx, sy, ex, ey); AlgoFunction optimalAlgo = (gridGraph, sx, sy, ex, ey) -> new StrictVisibilityGraphAlgorithm(gridGraph, sx, sy, ex, ey); double upperBound = 1.5; double maxRatio = 1; int wins = 0; int ties = 0; Random seedRand = new Random(-2814121L); long initial = seedRand.nextLong(); for (int i=0; i>=0; i++) { int sizeX = seedRand.nextInt(30 + (int)(Math.sqrt(i))) + 1; int sizeY = seedRand.nextInt(10 + (int)(Math.sqrt(i))) + 1; sizeX = seedRand.nextInt(50) + 1; sizeY = seedRand.nextInt(30) + 1; long seed = i+initial; int ratio = seedRand.nextInt(60) + 1; int max = (sizeX+1)*(sizeY+1); int p1 = seedRand.nextInt(max); int p2 = seedRand.nextInt(max-1); if (p2 == p1) { p2 = max-1; } int sx = p1%(sizeX+1); int sy = p1/(sizeX+1); int ex = p2%(sizeX+1); int ey = p2/(sizeX+1); //GridGraph gridGraph = DefaultGenerator.generateSeededGraphOnly(seed, sizeX, sizeY, ratio); GridGraph gridGraph = DefaultGenerator.generateSeededTrueRandomGraphOnly(seed, sizeX, sizeY, ratio); //gridGraph = GraphImporter.importGraphFromFile("custommaze4.txt"); //sx = 0; sy=0;ex=10+i;ey=2; //if (ex > 22) break; int[][] path = Utility.generatePath(testAlgo, gridGraph, sx, sy, ex, ey); double testPathLength = Utility.computePathLength(gridGraph, path); path = Utility.generatePath(optimalAlgo, gridGraph, sx, sy, ex, ey); double optimalPathLength = Utility.computePathLength(gridGraph, path); if (testPathLength > optimalPathLength*upperBound) { System.out.println("============"); System.out.println("Discrepancy Discovered!"); System.out.println("Seed = " + seed +" , Ratio = " + ratio + " , Size: x=" + sizeX + " y=" + sizeY); System.out.println("Start = " + sx + "," + sy + " End = " + ex + "," + ey); System.out.println("Test: " + testPathLength + " , Optimal: " + optimalPathLength); System.out.println("Ratio: " + (testPathLength/optimalPathLength)); System.out.println("============"); System.out.println("WINS: " + wins + ", TIES: " + ties); throw new UnsupportedOperationException("DISCREPANCY!!"); } else { //System.out.println("OK: Seed = " + seed +" , Ratio = " + ratio + " , Size: x=" + sizeX + " y=" + sizeY); double lengthRatio = (double)testPathLength/optimalPathLength; if (lengthRatio > maxRatio) { //System.out.println("OK: Seed = " + seed +" , Ratio = " + ratio + " , Size: x=" + sizeX + " y=" + sizeY); System.out.println("Seed = " + seed +" , Ratio = " + ratio + " , Size: x=" + sizeX + " y=" + sizeY); System.out.println("Start = " + sx + "," + sy + " End = " + ex + "," + ey); System.out.println("Test: " + testPathLength + " , Optimal: " + optimalPathLength); System.out.println("Ratio: " + (testPathLength/optimalPathLength)); maxRatio = lengthRatio; System.out.println(maxRatio); } } } //System.out.println(maxRatio); } private static void findStrictThetaStarIssues() { AlgoFunction basicThetaStar = (gridGraph, sx, sy, ex, ey) -> new BasicThetaStar(gridGraph, sx, sy, ex, ey);; AlgoFunction strictThetaStar = (gridGraph, sx, sy, ex, ey) -> new StrictThetaStar(gridGraph, sx, sy, ex, ey); // AlgoFunction basicThetaStar = (gridGraph, sx, sy, ex, ey) -> RecursiveStrictThetaStar.setBuffer(gridGraph, sx, sy, ex, ey, 0.4f); // AlgoFunction strictThetaStar = (gridGraph, sx, sy, ex, ey) -> RecursiveStrictThetaStar.setBuffer(gridGraph, sx, sy, ex, ey, 0.2f); // AlgoFunction basicThetaStar = AnyAngleSubgoalGraphsAlgorithm::new; // AlgoFunction strictThetaStar = RecursiveStrictAnyAngleSubgoalGraphsAlgorithm::new; double sumBasic = 0; double sumStrict = 0; int wins = 0; int ties = 0; int losses = 0; Random seedRand = new Random(-4418533); int initial = seedRand.nextInt(); for (int i=0; i<500000; i++) { int sizeX = seedRand.nextInt(60) + 8; int sizeY = seedRand.nextInt(60) + 8; int seed = i+initial; int ratio = seedRand.nextInt(40) + 5; int max = (sizeX+1)*(sizeY+1); int p1 = seedRand.nextInt(max); int p2 = seedRand.nextInt(max-1); if (p2 == p1) { p2 = max-1; } int sx = p1%(sizeX+1); int sy = p1/(sizeX+1); int ex = p2%(sizeX+1); int ey = p2/(sizeX+1); GridGraph gridGraph = DefaultGenerator.generateSeededGraphOnly(seed, sizeX, sizeY, ratio); int[][] path = Utility.generatePath(basicThetaStar, gridGraph, sx, sy, ex, ey); double basicPathLength = Utility.computePathLength(gridGraph, path); path = Utility.generatePath(strictThetaStar, gridGraph, sx, sy, ex, ey); double strictPathLength = Utility.computePathLength(gridGraph, path); sumBasic += basicPathLength; sumStrict += strictPathLength; if (basicPathLength < strictPathLength-0.01f) { losses += 1; System.out.println("============"); System.out.println("Discrepancy Discovered!"); System.out.println("Seed = " + seed +" , Ratio = " + ratio + " , Size: x=" + sizeX + " y=" + sizeY); System.out.println("Start = " + sx + "," + sy + " End = " + ex + "," + ey); System.out.println("Basic: " + basicPathLength + " , Strict: " + strictPathLength); System.out.println("============"); System.out.println("WINS: " + wins + ", TIES: " + ties + ", LOSSES: " + losses); System.out.println("BASIC: " + sumBasic + ", STRICT: " + sumStrict); System.out.println("Result: " + (sumBasic - sumStrict)/ (wins+losses+ties)); //throw new UnsupportedOperationException("DISCREPANCY!!"); } else { //System.out.println("OK: Seed = " + seed +" , Ratio = " + ratio + " , Size: x=" + sizeX + " y=" + sizeY); if (strictPathLength < basicPathLength - 0.01f) { wins += 1; } else { ties += 1; } } } } private static void testAlgorithmOptimality() { //AlgoFunction rVGA = (gridGraph, sx, sy, ex, ey) -> new RestrictedVisibilityGraphAlgorithm(gridGraph, sx, sy, ex, ey); //AlgoFunction rVGA = (gridGraph, sx, sy, ex, ey) -> new VisibilityGraphAlgorithm(gridGraph, sx, sy, ex, ey); //AlgoFunction rVGA = (gridGraph, sx, sy, ex, ey) -> new StrictVisibilityGraphAlgorithm(gridGraph, sx, sy, ex, ey); AlgoFunction testAlgo = Anya::new; AlgoFunction refAlgo = StrictVisibilityGraphAlgorithmV2::new; //AlgoFunction VGA = (gridGraph, sx, sy, ex, ey) -> VisibilityGraphAlgorithm.graphReuseNoHeuristic(gridGraph, sx, sy, ex, ey); //printSeed = false; // keep this commented out. Random seedRand = new Random(-2059321351); int initial = seedRand.nextInt(); for (int i=0; i<50000000; i++) { int sizeX = seedRand.nextInt(300) + 10; int sizeY = seedRand.nextInt(300) + 10; int seed = i+initial; int ratio = seedRand.nextInt(50) + 10; int max = (sizeX+1)*(sizeY+1); int p1 = seedRand.nextInt(max); int p2 = seedRand.nextInt(max-1); if (p2 == p1) { p2 = max-1; } int sx = p1%(sizeX+1); int sy = p1/(sizeX+1); int ex = p2%(sizeX+1); int ey = p2/(sizeX+1); double restPathLength = 0, normalPathLength = 0; try { GridGraph gridGraph = DefaultGenerator.generateSeededGraphOnly(seed, sizeX, sizeY, ratio); //for (int iii=0;iii<100;++iii) Utility.generatePath(testAlgo, gridGraph, seedRand.nextInt(sizeX+1),seedRand.nextInt(sizeY+1),seedRand.nextInt(sizeX+1),seedRand.nextInt(sizeY+1)); int[][] path = Utility.generatePath(testAlgo, gridGraph, sx, sy, ex, ey); path = Utility.removeDuplicatesInPath(path); restPathLength = Utility.computePathLength(gridGraph, path); path = Utility.generatePath(refAlgo, gridGraph, sx, sy, ex, ey); path = Utility.removeDuplicatesInPath(path); normalPathLength = Utility.computePathLength(gridGraph, path); }catch (Exception e) { e.printStackTrace(); System.out.println("EXCEPTION OCCURRED!"); System.out.println("Seed = " + seed +" , Ratio = " + ratio + " , Size: x=" + sizeX + " y=" + sizeY); System.out.println("Start = " + sx + "," + sy + " End = " + ex + "," + ey); throw new UnsupportedOperationException("DISCREPANCY!!"); } if (Math.abs(restPathLength - normalPathLength) > 0.000001f) { System.out.println("============"); System.out.println("Discrepancy Discovered!"); System.out.println("Seed = " + seed +" , Ratio = " + ratio + " , Size: x=" + sizeX + " y=" + sizeY); System.out.println("Start = " + sx + "," + sy + " End = " + ex + "," + ey); System.out.println("Actual: " + restPathLength + " , Expected: " + normalPathLength); System.out.println(restPathLength / normalPathLength); System.out.println("============"); throw new UnsupportedOperationException("DISCREPANCY!!"); } else { if (i%10000 == 9999) { System.out.println("Count: " + (i+1)); System.out.println("OK: Seed = " + seed +" , Ratio = " + ratio + " , Size: x=" + sizeX + " y=" + sizeY); System.out.println("Actual: " + restPathLength + " , Expected: " + normalPathLength); } } } } private static boolean testTautness(GridGraph gridGraph, AlgoFunction algo, int sx, int sy, int ex, int ey) { int[][] path = Utility.generatePath(algo, gridGraph, sx, sy, ex, ey); path = Utility.removeDuplicatesInPath(path); return Utility.isPathTaut(gridGraph, path); } private static boolean hasSolution(GridGraph gridGraph, AlgoFunction algo, int sx, int sy, int ex, int ey) { int[][] path = Utility.generatePath(algo, gridGraph, sx, sy, ex, ey); return path.length > 1; } private static void countTautPaths() { int nTaut1=0;int nTaut2=0; int nTaut3=0; AlgoFunction hasPathChecker = JumpPointSearch::new; AlgoFunction algo3 = BasicThetaStar::new; AlgoFunction algo2 = StrictThetaStar::new; AlgoFunction algo1 = RecursiveStrictThetaStar::new; //printSeed = false; // keep this commented out. int pathsPerGraph = 100; int nIterations = 100000; int nPaths = 0; String[] maps = { "obst10_random512-10-0", "obst10_random512-10-1", "obst10_random512-10-2", "obst10_random512-10-3", "obst10_random512-10-4", "obst10_random512-10-5", "obst10_random512-10-6", "obst10_random512-10-7", "obst10_random512-10-8", "obst10_random512-10-9", "obst40_random512-40-0", "obst40_random512-40-1", "obst40_random512-40-2", "obst40_random512-40-3", "obst40_random512-40-4", "obst40_random512-40-5", "obst40_random512-40-6", "obst40_random512-40-7", "obst40_random512-40-8", "obst40_random512-40-9" }; nIterations = maps.length; System.out.println(maps.length); Random seedRand = new Random(-14); int initial = seedRand.nextInt(); for (int i=0;i<nIterations;++i) { String map = maps[i]; System.out.println("Map: " + map); GridGraph gridGraph = GraphImporter.loadStoredMaze(map); int sizeX = gridGraph.sizeX; int sizeY = gridGraph.sizeY; /*int sizeX = seedRand.nextInt(20) + 300; int sizeY = seedRand.nextInt(20) + 300; int seed = i+initial; int ratio = seedRand.nextInt(30) + 5; GridGraph gridGraph = DefaultGenerator.generateSeededGraphOnly(seed, sizeX, sizeY, ratio); System.out.println("Ratio: " + ratio);*/ for (int j=0;j<pathsPerGraph;++j) { int max = (sizeX+1)*(sizeY+1); int p1 = seedRand.nextInt(max); int p2 = seedRand.nextInt(max-1); if (p2 == p1) { p2 = max-1; } int sx = p1%(sizeX+1); int sy = p1/(sizeX+1); int ex = p2%(sizeX+1); int ey = p2/(sizeX+1); if (hasSolution(gridGraph, hasPathChecker, sx, sy, ex, ey)) { if (testTautness(gridGraph, algo1, sx,sy,ex,ey)) nTaut1++; if (testTautness(gridGraph, algo2, sx,sy,ex,ey)) nTaut2++; if (testTautness(gridGraph, algo3, sx,sy,ex,ey)) nTaut3++; nPaths++; } else { j } } System.out.println("Total = " + nPaths); System.out.println("1: " + ((float)nTaut1/nPaths)); System.out.println("2: " + ((float)nTaut2/nPaths)); System.out.println("3: " + ((float)nTaut3/nPaths)); } } }
package com.kapouta.katools; import java.util.Vector; import javax.microedition.khronos.egl.EGLConfig; import javax.microedition.khronos.opengles.GL10; import android.opengl.GLSurfaceView.Renderer; import android.view.MotionEvent; import android.view.View; import android.view.View.OnTouchListener; public abstract class KTouchQueuedRenderer implements Renderer, OnTouchListener { public static final int MODE_TWO_POINTERS_DOWN = 0; public static final int MODE_WAIT_POINTER_DOWN = 1; Vector<MotionEventData> events = null; private int mode; public KTouchQueuedRenderer() { events = new Vector<MotionEventData>(); } @Override public synchronized void onDrawFrame(GL10 gl) { if (events.size() > 0) { MotionEventData curr_event = events.remove(0); // System.out.println(curr_event); switch (curr_event.action) { case MotionEvent.ACTION_DOWN: this.onTouchDown(gl, curr_event.x1, curr_event.y1); break; case MotionEvent.ACTION_MOVE: // only one finger if (curr_event.count == 1) this.onTouchMove(gl, curr_event.x1, curr_event.y1); else // two or more (only ready for two) this.onDualTouchMove(gl, curr_event.x1, curr_event.y1, curr_event.x2, curr_event.y2); break; case MotionEvent.ACTION_UP: this.onTouchUp(gl, curr_event.x1, curr_event.y1); break; case MotionEvent.ACTION_POINTER_1_DOWN: this.onTouchUp(gl, curr_event.x2, curr_event.y2); this.onDualTouchDown(gl, curr_event.x1, curr_event.y1, curr_event.x2, curr_event.y2); break; case MotionEvent.ACTION_POINTER_2_DOWN: this.onTouchUp(gl, curr_event.x1, curr_event.y1); this.onDualTouchDown(gl, curr_event.x1, curr_event.y1, curr_event.x2, curr_event.y2); break; case MotionEvent.ACTION_POINTER_1_UP: this.onDualTouchUp(gl, curr_event.x1, curr_event.y1, curr_event.x2, curr_event.y2); this.onTouchDown(gl, curr_event.x2, curr_event.y2); break; case MotionEvent.ACTION_POINTER_2_UP: this.onDualTouchUp(gl, curr_event.x1, curr_event.y1, curr_event.x2, curr_event.y2); this.onTouchDown(gl, curr_event.x1, curr_event.y1); break; default: System.out.println("Unknown: " + curr_event); } } } @Override public void onSurfaceChanged(GL10 arg0, int arg1, int arg2) { } @Override public void onSurfaceCreated(GL10 arg0, EGLConfig arg1) { } public void onTouchDown(GL10 gl, float x, float y) { System.out.println("One DOWN ( " + x + " , " + y + " )"); } public void onTouchMove(GL10 gl, float x, float y) { System.out.println("One MOVE ( " + x + " , " + y + " )"); } public void onTouchUp(GL10 gl, float x, float y) { System.out.println("One UP ( " + x + " , " + y + " )"); } public void onDualTouchDown(GL10 gl, float x1, float y1, float x2, float y2) { System.out.println("Two DOWN ( " + x1 + " , " + y1 + " ; " + x2 + " , " + y2 + " ) "); } public void onDualTouchMove(GL10 gl, float x1, float y1, float x2, float y2) { System.out.println("Two MOVE ( " + x1 + " , " + y1 + " ; " + x2 + " , " + y2 + " ) "); } public void onDualTouchUp(GL10 gl, float x1, float y1, float x2, float y2) { System.out.println("Two UP ( " + x1 + " , " + y1 + " ; " + x2 + " , " + y2 + " ) "); } @Override public boolean onTouch(View view, MotionEvent event) { // by discarding MVOE events, this condition ensures that the event // queue does not grow crazy when the user is moving around a lot. if (MotionEvent.ACTION_MOVE != event.getAction() || events.size() == 0) events.add(new MotionEventData(event)); return true; } protected class MotionEventData { float x1, y1, x2, y2; int action; int count; public MotionEventData(MotionEvent event) { int pid0 = event.getPointerId(0); int pid1 = event.getPointerId(1); x1 = event.getX(pid0); y1 = event.getY(pid0); if (event.getPointerCount() > 0) { x2 = event.getX(pid1); y2 = event.getY(pid1); } count = event.getPointerCount(); action = event.getAction(); } public String toString() { return "A[" + action + "] P1( " + x1 + " , " + y1 + " ) P2 " + x2 + " , " + y2 + " )"; } } }
import java.util.List; public class taco { public static void main(String[] args) { int amount = 8; List<Integer> numbers = generateNumbers(amount); loop(numbers); } public static boolean isSorted(List<Integer> numbers){ for (Integer number : numbers){ if (number > numbers.get(number+1)) { return false; } } return true; } public static void loop(List<Integer> numbers){ int count = 0; while (!isSorted(numbers)){ //TODO } } public static void sort(List<Integer> numbers){ //TODO } public static List<Integer> generateNumbers(int amount){ //TODO return null; } }
package com.opencms.workplace; import com.opencms.file.*; import com.opencms.core.*; import com.opencms.util.*; import com.opencms.template.*; import org.w3c.dom.*; import org.xml.sax.*; import javax.servlet.http.*; import java.util.*; import java.io.*; public class CmsNewResourcePage extends CmsWorkplaceDefault implements I_CmsWpConstants, I_CmsConstants { /** Definition of the class */ private final static String C_CLASSNAME="com.opencms.template.CmsXmlTemplate"; private static final String C_DEFAULTBODY = "<?xml version=\"1.0\"?>\n<XMLTEMPLATE>\n<TEMPLATE/>\n</XMLTEMPLATE>"; /** * Indicates if the results of this class are cacheable. * * @param cms A_CmsObject Object for accessing system resources * @param templateFile Filename of the template file * @param elementName Element name of this template in our parent template. * @param parameters Hashtable with all template class parameters. * @param templateSelector template section that should be processed. * @return <EM>true</EM> if cacheable, <EM>false</EM> otherwise. */ public boolean isCacheable(A_CmsObject cms, String templateFile, String elementName, Hashtable parameters, String templateSelector) { return false; } /** * Overwrites the getContent method of the CmsWorkplaceDefault.<br> * Gets the content of the new resource page template and processed the data input. * @param cms The CmsObject. * @param templateFile The new page template file * @param elementName not used * @param parameters Parameters of the request and the template. * @param templateSelector Selector of the template tag to be displayed. * @return Bytearry containing the processed data of the template. * @exception Throws CmsException if something goes wrong. */ public byte[] getContent(A_CmsObject cms, String templateFile, String elementName, Hashtable parameters, String templateSelector) throws CmsException { // the template to be displayed String template=null; // TODO: check, if this is neede: String type=null; byte[] content=new byte[0]; CmsFile contentFile=null; HttpSession session= ((HttpServletRequest)cms.getRequestContext().getRequest().getOriginalRequest()).getSession(true); //get the current filelist String currentFilelist=(String)session.getValue(C_PARA_FILELIST); if (currentFilelist==null) { currentFilelist=cms.rootFolder().getAbsolutePath(); } // get request parameters String newFile=(String)parameters.get(C_PARA_NEWFILE); String title=(String)parameters.get(C_PARA_TITLE); // TODO: check, if this is neede: String flags=(String)parameters.get(C_PARA_FLAGS); String templatefile=(String)parameters.get(C_PARA_TEMPLATE); String navtitle=(String)parameters.get(C_PARA_NAVTITLE); String navpos=(String)parameters.get(C_PARA_NAVPOS); // get the current phase of this wizard String step=cms.getRequestContext().getRequest().getParameter("step"); if (step != null) { if (step.equals("1")) { //check if the fielname has a file extension if (newFile.indexOf(".")==-1) { newFile+=".html"; } try { // create the content for the page file content=createPagefile(C_CLASSNAME, templatefile, C_CONTENTBODYPATH+currentFilelist.substring(1,currentFilelist.length())+newFile); // check if the nescessary folders for the content files are existing. // if not, create the missing folders. checkFolders(cms,currentFilelist); // create the page file CmsFile file=cms.createFile(currentFilelist,newFile,content,"page"); cms.lockResource(file.getAbsolutePath()); cms.writeMetainformation(file.getAbsolutePath(),C_METAINFO_TITLE,title); // now create the page content file try { contentFile=cms.readFile(C_CONTENTBODYPATH+currentFilelist.substring(1,currentFilelist.length()),newFile); } catch (CmsException e) { if (contentFile == null) { contentFile=cms.createFile(C_CONTENTBODYPATH+currentFilelist.substring(1,currentFilelist.length()),newFile,C_DEFAULTBODY.getBytes(),"plain"); } } // set the flags for the content file to internal use, the content // should not be loaded cms.lockResource(contentFile.getAbsolutePath()); cms.chmod(contentFile.getAbsolutePath(), contentFile.getAccessFlags()+C_ACCESS_INTERNAL_READ); // now check if navigation informations have to be added to the new page. if (navtitle != null) { cms.writeMetainformation(file.getAbsolutePath(),C_METAINFO_NAVTITLE,navtitle); // update the navposition. if (navpos != null) { updateNavPos(cms,file,navpos); } } } catch (CmsException ex) { throw new CmsException("Error while creating new Page"+ex.getMessage(),ex.getType(),ex); } // TODO: ErrorHandling // now return to filelist try { cms.getRequestContext().getResponse().sendCmsRedirect( getConfigFile(cms).getWorkplaceActionPath()+C_WP_EXPLORER_FILELIST); } catch (Exception e) { throw new CmsException("Redirect fails :"+ getConfigFile(cms).getWorkplaceActionPath()+C_WP_EXPLORER_FILELIST,CmsException.C_UNKNOWN_EXCEPTION,e); } } } else { session.removeValue(C_PARA_FILE); } // get the document to display CmsXmlWpTemplateFile xmlTemplateDocument = new CmsXmlWpTemplateFile(cms,templateFile); // process the selected template return startProcessing(cms,xmlTemplateDocument,"",parameters,template); } /** * Create the pagefile for this new page. * @classname The name of the class used by this page. * @template The name of the template (content) used by this page. * @return Bytearray containgin the XML code for the pagefile. */ private byte[] createPagefile(String classname, String template, String contenttemplate) throws CmsException{ byte[] xmlContent= null; try { I_CmsXmlParser parser = A_CmsXmlContent.getXmlParser(); Document docXml = parser.createEmptyDocument("page"); Element firstElement = docXml.getDocumentElement(); // add element CLASS Element elClass= docXml.createElement("CLASS"); firstElement.appendChild(elClass); Node noClass = docXml.createTextNode(classname); elClass.appendChild(noClass); // add element MASTERTEMPLATE Element elTempl= docXml.createElement("MASTERTEMPLATE"); firstElement.appendChild(elTempl); Node noTempl = docXml.createTextNode(template); elTempl.appendChild(noTempl); //add element ELEMENTDEF Element elEldef=docXml.createElement("ELEMENTDEF"); elEldef.setAttribute("name","body"); firstElement.appendChild(elEldef); //add element ELEMENTDEF.CLASS Element elElClass= docXml.createElement("CLASS"); elEldef.appendChild(elElClass); Node noElClass = docXml.createTextNode(classname); elElClass.appendChild(noElClass); //add element ELEMENTDEF.TEMPLATE Element elElTempl= docXml.createElement("TEMPLATE"); elEldef.appendChild(elElTempl); Node noElTempl = docXml.createTextNode(contenttemplate); elElTempl.appendChild(noElTempl); // generate the output StringWriter writer = new StringWriter(); parser.getXmlText(docXml,writer); xmlContent = writer.toString().getBytes(); } catch (Exception e) { throw new CmsException(e.getMessage(),CmsException.C_UNKNOWN_EXCEPTION,e); } return xmlContent; } /** * Gets the templates displayed in the template select box. * @param cms The CmsObject. * @param lang The langauge definitions. * @param names The names of the new rescources. * @param values The links that are connected with each resource. * @param parameters Hashtable of parameters (not used yet). * @returns The vectors names and values are filled with the information found in the * workplace.ini. * @exception Throws CmsException if something goes wrong. */ public Integer getTemplates(A_CmsObject cms, CmsXmlLanguageFile lang, Vector names, Vector values, Hashtable parameters) throws CmsException { Vector files=cms.getFilesInFolder(C_CONTENTTEMPLATEPATH); Enumeration enum=files.elements(); while (enum.hasMoreElements()) { CmsFile file =(CmsFile)enum.nextElement(); if (file.getState() != C_STATE_DELETED) { String nicename=cms.readMetainformation(file.getAbsolutePath(),C_METAINFO_TITLE); if (nicename == null) { nicename=file.getName(); } names.addElement(nicename); values.addElement(file.getAbsolutePath()); } } return new Integer(0); } /** * This method checks if all nescessary folders are exisitng in the content body * folder and creates the missing ones. <br> * All page contents files are stored in the content body folder in a mirrored directory * structure of the OpenCms filesystem. Therefor it is nescessary to create the * missing folders when a new page document is createg. * @param cms The CmsObject * @param path The path in the CmsFilesystem where the new page should be created. * @exception CmsException if something goes wrong. */ private void checkFolders(A_CmsObject cms, String path) throws CmsException { String completePath=C_CONTENTBODYPATH; StringTokenizer t=new StringTokenizer(path,"/"); // check if all folders are there while (t.hasMoreTokens()) { String foldername=t.nextToken(); try { // try to read the folder. if this fails, an exception is thrown cms.readFolder(completePath+foldername+"/"); } catch (CmsException e) { // the folder could not be read, so create it. cms.createFolder(completePath,foldername); } completePath+=foldername+"/"; } } /** * Gets the files displayed in the navigation select box. * @param cms The CmsObject. * @param lang The langauge definitions. * @param names The names of the new rescources. * @param values The links that are connected with each resource. * @param parameters Hashtable of parameters (not used yet). * @returns The vectors names and values are filled with data for building the navigation. * @exception Throws CmsException if something goes wrong. */ public Integer getNavPos(A_CmsObject cms, CmsXmlLanguageFile lang, Vector names, Vector values, Hashtable parameters) throws CmsException { // get the nav information Hashtable storage = getNavData(cms); if (storage.size() >0) { String[] nicenames=(String[])storage.get("NICENAMES"); int count=((Integer)storage.get("COUNT")).intValue(); // finally fill the result vectors for (int i=0;i<=count;i++) { names.addElement(nicenames[i]); values.addElement(nicenames[i]); } } else { values=new Vector(); } return new Integer(values.size()-1); } /** * Updates the navigation position of all resources in the actual folder. * @param cms The CmsObject. * @param newfile The new file added to the nav. * @param navpos The file after which the new entry is sorted. */ private void updateNavPos(A_CmsObject cms, CmsFile newfile, String newpos) throws CmsException { float newPos=0; // get the nav information Hashtable storage = getNavData(cms); if (storage.size() >0 ) { String[] nicenames=(String[])storage.get("NICENAMES"); String[] positions=(String[])storage.get("POSITIONS"); int count=((Integer)storage.get("COUNT")).intValue(); // now find the file after which the new file is sorted int pos=0; for (int i=0;i<nicenames.length;i++) { if (newpos.equals((String)nicenames[i])) { pos=i; } } if (pos < count) { float low=new Float(positions[pos]).floatValue(); float high=new Float(positions[pos+1]).floatValue(); newPos= (high+low)/2; } else { newPos= new Float(positions[pos]).floatValue()+1; } } else { newPos=1; } cms.writeMetainformation(newfile.getAbsolutePath(),C_METAINFO_NAVPOS,new Float(newPos).toString()); } /** * Sorts a set of three String arrays containing navigation information depending on * their navigation positions. * @param cms Cms Object for accessign files. * @param filenames Array of filenames * @param nicenames Array of well formed navigation names * @param positions Array of navpostions */ private void sort(A_CmsObject cms, String[] filenames, String[] nicenames, String[] positions,int max){ // Sorting algorithm // This method uses an bubble sort, so replace this with something more // efficient for (int i=max-1;i>1;i for (int j=1;j<i;j++) { float a=new Float(positions[j]).floatValue(); float b=new Float(positions[j+1]).floatValue(); if (a > b) { String tempfilename= filenames[j]; String tempnicename = nicenames[j]; String tempposition = positions[j]; filenames[j]=filenames[j+1]; nicenames[j]=nicenames[j+1]; positions[j]=positions[j+1]; filenames[j+1]=tempfilename; nicenames[j+1]=tempnicename; positions[j+1]=tempposition; } } } } /** * Gets all required navigation information from the files and subfolders of a folder. * A file list of all files and folder is created, for all those resources, the navigation * metainformation is read. The list is sorted by their navigation position. * @param cms The CmsObject. * @return Hashtable including three arrays of strings containing the filenames, * nicenames and navigation positions. * @exception Throws CmsException if something goes wrong. */ private Hashtable getNavData(A_CmsObject cms) throws CmsException { HttpSession session= ((HttpServletRequest)cms.getRequestContext().getRequest().getOriginalRequest()).getSession(true); CmsXmlLanguageFile lang= new CmsXmlLanguageFile(cms); String[] filenames; String[] nicenames; String[] positions; Hashtable storage=new Hashtable(); CmsFolder folder=null; CmsFile file=null; String nicename=null; String currentFilelist=null; int count=1; float max=0; // get the current folder currentFilelist=(String)session.getValue(C_PARA_FILELIST); if (currentFilelist==null) { currentFilelist=cms.rootFolder().getAbsolutePath(); } // get all files and folders in the current filelist. Vector files=cms.getFilesInFolder(currentFilelist); Vector folders=cms.getSubFolders(currentFilelist); // combine folder and file vector Vector filefolders=new Vector(); Enumeration enum=folders.elements(); while (enum.hasMoreElements()) { folder=(CmsFolder)enum.nextElement(); filefolders.addElement(folder); } enum=files.elements(); while (enum.hasMoreElements()) { file=(CmsFile)enum.nextElement(); filefolders.addElement(file); } if (filefolders.size()>0) { // Create some arrays to store filename, nicename and position for the // nav in there. The dimension of this arrays is set to the number of // found files and folders plus two more entrys for the first and last // element. filenames=new String[filefolders.size()+2]; nicenames=new String[filefolders.size()+2]; positions=new String[filefolders.size()+2]; //now check files and folders that are not deleted and include navigation // information enum=filefolders.elements(); while (enum.hasMoreElements()) { CmsResource res =(CmsResource)enum.nextElement(); // check if the resource is not marked as deleted if (res.getState() != C_STATE_DELETED) { String navpos= cms.readMetainformation(res.getAbsolutePath(),C_METAINFO_NAVPOS); // check if there is a navpos for this file/folder if (navpos!= null) { nicename=cms.readMetainformation(res.getAbsolutePath(),C_METAINFO_NAVTITLE); if (nicename == null) { nicename=res.getName(); } // add this file/folder to the storage. filenames[count]=res.getAbsolutePath(); nicenames[count]=nicename; positions[count]=navpos; if (new Float(navpos).floatValue() > max) { max = new Float(navpos).floatValue(); } count++; } } } } else { filenames=new String[2]; nicenames=new String[2]; positions=new String[2]; } // now add the first and last value filenames[0]="FIRSTENTRY"; nicenames[0]=lang.getDataValue("input.firstelement"); positions[0]="0"; filenames[count]="LASTENTRY"; nicenames[count]=lang.getDataValue("input.lastelement"); positions[count]=new Float(max+1).toString(); // finally sort the nav information. sort(cms,filenames,nicenames,positions,count); // put all arrays into a hashtable to return them to the calling method. storage.put("FILENAMES",filenames); storage.put("NICENAMES",nicenames); storage.put("POSITIONS",positions); storage.put("COUNT",new Integer(count)); return storage; } }
package com.pmovil.codenameone.nativeshare; import com.codename1.io.FileSystemStorage; import com.codename1.io.Log; import com.codename1.io.services.ImageDownloadService; import com.codename1.system.NativeLookup; import com.codename1.ui.events.ActionEvent; import com.codename1.ui.events.ActionListener; import org.bouncycastle.crypto.digests.MD5Digest; /** * Allows native sharing text and image directly to Facebook or Twitter * * Curretly supported in Android and iOS * * @author Fabricio */ public class Share { public static final int FACEBOOK = 1; public static final int TWITTER = 2; private static NativeShare peer; private Share() { } public static Share getInstance() throws RuntimeException { if (peer == null) { peer = (NativeShare)NativeLookup.create(NativeShare.class); if ( peer == null ) { throw new RuntimeException("Native share is not implemented yet in this platform."); } } if ( !peer.isSupported() ){ throw new RuntimeException("Native share is not supported in this platform."); } Share dialog = new Share(); return dialog; } public void show(final String text, String image, final String mimeType, final int services) { show(text, image, mimeType, services, null); } public void show(final String text, String image, final String mimeType, final int services, final ActionListener callback) { if (image != null && image.toLowerCase().startsWith("http")) { try { final String basename = image.substring(image.lastIndexOf("/")); String extension; if (basename.indexOf('.') >= 0) { extension = basename.substring(basename.lastIndexOf(".")); } else if (mimeType != null) { extension = "." + mimeType.substring(mimeType.lastIndexOf("/") + 1); } else { extension = ".jpg"; } final String file = FileSystemStorage.getInstance().getAppHomePath() + "share_" + md5(image) + extension; Log.p("Fetching " + image + " to " + file); ImageDownloadService.createImageToFileSystem(image, new ActionListener() { public void actionPerformed(ActionEvent evt) { Log.p(file + " fetched"); peer.show(text, file, mimeType != null ? mimeType : "image/jpg" , services); if (callback != null) { callback.actionPerformed(new ActionEvent(file)); } // delete after share ? } }, file); } catch (IndexOutOfBoundsException ex) { if (callback != null) { callback.actionPerformed(new ActionEvent("failed")); } } } else { peer.show(text, image, mimeType, services); if (callback != null) { callback.actionPerformed(new ActionEvent(image)); } } } public boolean isServiceSupported(int service) { return peer.isServiceSupported(service); } private static String md5(String text) { MD5Digest digest = new MD5Digest(); byte[] data = text.getBytes(); digest.update(data, 0, data.length); byte[] md5 = new byte[digest.getDigestSize()]; digest.doFinal(md5, 0); return bytesToHex(md5); } final protected static char[] hexArray = "0123456789ABCDEF".toCharArray(); private static String bytesToHex(byte[] bytes) { char[] hexChars = new char[bytes.length * 2]; for (int j = 0; j < bytes.length; j++) { int v = bytes[j] & 0xFF; hexChars[j * 2] = hexArray[v >>> 4]; hexChars[j * 2 + 1] = hexArray[v & 0x0F]; } return new String(hexChars); } }
package com.intellij.pom; /** * @author peter */ public interface PomNamedTarget extends PomTarget { PomNamedTarget[] EMPTY_ARRAY = new PomNamedTarget[0]; String getName(); }
package matlab; import java.io.IOException; import java.io.StringReader; import java.util.ArrayList; import java.util.List; import matlab.ExtractionParser.Terminals; import beaver.Scanner; import beaver.Symbol; public class CommandFormatter { private final List<Symbol> originalSymbols; private final List<Symbol> rescannedSymbols; private final List<Symbol> formattedSymbols; private int numArgs; private CommandFormatter(List<Symbol> originalSymbols) throws CommandException { this.originalSymbols = originalSymbols; this.rescannedSymbols = new ArrayList<Symbol>(); this.formattedSymbols = new ArrayList<Symbol>(); this.numArgs = 0; } public static List<Symbol> format(List<Symbol> originalSymbols) throws CommandException { if(originalSymbols == null) { return null; } originalSymbols = new ArrayList<Symbol>(originalSymbols); if(isNotCmd(originalSymbols)) { return originalSymbols; } CommandFormatter cf = new CommandFormatter(originalSymbols); cf.rescan(); cf.format(); return cf.formattedSymbols; } private void rescan() throws CommandException { StringBuffer textBuf = new StringBuffer(); for(Symbol sym : originalSymbols) { textBuf.append(sym.value); } CommandScanner scanner = new CommandScanner(new StringReader(textBuf.toString())); int basePos = originalSymbols.get(0).getStart(); int baseLine = Symbol.getLine(basePos); int baseCol = Symbol.getColumn(basePos); scanner.setBasePosition(baseLine, baseCol); while(true) { Symbol curr = null; try { curr = scanner.nextToken(); } catch (Scanner.Exception e) { throw new CommandException(e.line, e.column, e.getMessage()); } catch (IOException e) { //can't happen - using a StringReader e.printStackTrace(); throw new RuntimeException(e); } if(curr.getId() == ExtractionParser.Terminals.EOF) { break; } if(!isFiller(curr)) { numArgs++; } rescannedSymbols.add(curr); } } //TODO-AC: track position changes private void format() { formattedSymbols.add(new Symbol("(")); //TODO-AC: id? int i = 0; for(Symbol sym : rescannedSymbols) { formattedSymbols.add(sym); if(!isFiller(sym)) { if(i < numArgs - 1) { formattedSymbols.add(new Symbol(Terminals.COMMA, ",")); } i++; } } formattedSymbols.add(new Symbol(")"));//TODO-AC: id? } private static boolean isFiller(Symbol sym) { short type = sym.getId(); return type == Terminals.OTHER_WHITESPACE || type == Terminals.ELLIPSIS_COMMENT; } private static boolean isNotCmd(List<Symbol> originalSymbols) { //no args => not a command if(originalSymbols == null || originalSymbols.isEmpty()) { return true; } //transpose => no args => not a command switch(originalSymbols.get(0).getId()) { case Terminals.MTRANSPOSE: case Terminals.ARRAYTRANSPOSE: return true; } Symbol firstNonWhitespace = null; for(Symbol sym : originalSymbols) { if(!isFiller(sym)) { if(firstNonWhitespace == null) { firstNonWhitespace = sym; switch(sym.getId()) { //paren or assign => definitely not a command case Terminals.PARENTHESIZED: case Terminals.ASSIGN: return true; //operator => command iff nothing important follows case Terminals.LT: case Terminals.GT: case Terminals.LE: case Terminals.GE: case Terminals.EQ: case Terminals.NE: case Terminals.AND: case Terminals.OR: case Terminals.SHORTAND: case Terminals.SHORTOR: case Terminals.COLON: case Terminals.MTIMES: case Terminals.ETIMES: case Terminals.MDIV: case Terminals.EDIV: case Terminals.MLDIV: case Terminals.ELDIV: case Terminals.PLUS: case Terminals.MINUS: case Terminals.MPOW: case Terminals.EPOW: case Terminals.DOT: break; //otherwise => definitely a command default: return false; } } else { return true; } } } return false; } }
package com.winitzki.prototyping.androjoin; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; 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.Set; import java.util.UUID; import java.util.concurrent.Semaphore; import android.os.AsyncTask; import android.os.Handler; import android.os.Looper; public class AJoin { private Reaction[] definedReactions; private int joinID = 0; private static int globalJoinCount = 0; private Map<String,List<M_A>> availableMolecules; private Set<String> knownMoleculeNames; private boolean decideOnUIThread; private static Handler uiHandler = new Handler(Looper.getMainLooper()); public AJoin(boolean uiThread) { joinID = ++globalJoinCount; decideOnUIThread = uiThread; } // name of asynchronous molecule public static abstract class M_A { protected String moleculeName; protected AJoin ownerJoin; protected Object value; public String getName() { return moleculeName; } abstract protected Class<?> getValueClass(); public M_A(String name) { assign(name, null); value = null; // a non-null owner join has to be assigned if this molecule were to be injected } public M_A() { assign(UUID.randomUUID().toString(), null); value = null; } private M_A makeCopy(Object value) { try { M_A newCopy = this.getClass().newInstance(); newCopy.assign(this.moleculeName, this.ownerJoin); newCopy.value = value; return newCopy; } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } return null; } protected void assign(String name, AJoin join) { moleculeName = name; ownerJoin = join; } protected void putInternal(Object value) { ownerJoin.inject(makeCopy(value)); } public String toString() { String joinIdString = ""; if (ownerJoin != null) joinIdString = "[j=" + ownerJoin.joinID + "]"; return moleculeName + "(" + value.toString() + ")" + joinIdString; } } // name of synchronous molecule public static abstract class M_S extends M_A { protected Object resultValue = null; protected Semaphore semaphore = null; public M_S(String name) { super(name); // a non-null owner join has to be assigned if this molecule were to be injected } public M_S() { super(); } private M_S makeCopy(Object value) { return (M_S)super.makeCopy(value); } public M_S reply(final Object value) { resultValue = value; return this; } protected Object putSyncInternal(Object value) { M_S newCopy = makeCopy(value); newCopy.initializeSemaphore(); return ownerJoin.injectSyncAndReturnValue(newCopy); } private void initializeSemaphore() { semaphore = new Semaphore(0, true); semaphore.drainPermits(); // documentation does not say how many "permits" I need to set initially. So let's drain them. } } public static class M_int extends M_A { public M_int(String name) { super(name); } public M_int() { super(); } public void put(int value) { putInternal((Integer)value); } @Override protected Class<?> getValueClass() { return int.class; } } public static class M_empty extends M_A { public M_empty(String name) { super(name); } public M_empty() { super(); } public void put() { putInternal(null); } @Override protected Class<?> getValueClass() { return null; } } public static class M_empty_int extends M_S { public M_empty_int(String name) { super(name); } public M_empty_int() { super(); } public int put() { return (int)(Integer)putSyncInternal(null); } @Override protected Class<?> getValueClass() { return null; } } public static class M_float_int extends M_S { public M_float_int(String name) { super(name); } public M_float_int() { super(); } public int put(float value) { return (int)(Integer)putSyncInternal((Float)value); } @Override protected Class<?> getValueClass() { return float.class; } } public abstract static class ReactionBody { private List<M_A> inputMolecules; private boolean scheduleOnUIThread; private M_A findMoleculeById(M_A m) { for (M_A inM : inputMolecules) { if (inM.getName().equals(m.getName())) return m; } return null; } private ReactionBody makeCopy(boolean scheduleOnUIThread) { ReactionBody newCopy = null; try { newCopy = this.getClass().newInstance(); newCopy.scheduleOnUIThread = scheduleOnUIThread; } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } return newCopy; } public static Method findMethod(Class<?> instanceClass, String name) { for (Method m : instanceClass.getDeclaredMethods()) { if (m.getName().equals(name)) { return m; } } return null; } private void runReactionBody() { // input molecules must be already assigned at this point! final ReactionBody instance = this; final Class<?> instanceClass = this.getClass(); runOnUIThread(scheduleOnUIThread, new Runnable() { @Override public void run() { // introspect the types of all arguments of the overloaded "run" function. Method runMethod = findMethod(instanceClass, "run"); Class<?>[] paramClasses = runMethod.getParameterTypes(); // find the corresponding molecule values from the provided input molecules, using their known types, in the declared order. // construct the actual typed arguments for the reaction block, and execute "run" with these arguments. Object[] params = new Object[paramClasses.length]; int paramNumber = -1; boolean paramError = false; for (M_A m : inputMolecules) { if (m.getValueClass() != null) { paramNumber++; if (paramNumber < paramClasses.length && m.getValueClass().equals(paramClasses[paramNumber])) { params[paramNumber] = m.value; } else { // error! mismatched types or number of parameters. paramError = true; } } } if (paramNumber != paramClasses.length) { // error! too few parameters in the run() method of reaction body paramError = true; } if (!paramError) { try { runMethod.invoke(instance, params); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } } } }); } protected void to(M_S m) { // the result value is already set on the molecule object m. M_S ms = (M_S)findMoleculeById(m); Object resultValue = m.resultValue; m.resultValue = null; ms.resultValue = resultValue; ms.semaphore.release(); // need to use the reaction context in order to obtain the actual molecule instance to be replied to; "m" is not necessarily the right instance. // this is done using some private value from this instance of ReactionBody that will be set when the reaction is run. (We need a new instance of the reaction, too!) // then we need to set the result value on that instance, and also set it to null on "m" just in case // and raise the semaphore on the instance. } } /// this class is used only as a container for values specified by the user public static class Reaction { private M_A[] nominalInputMolecules; private ReactionBody reactionBody; private boolean scheduleOnUIThread; public Reaction(M_A[] nominalInputs, ReactionBody body, boolean uiThread) { nominalInputMolecules = nominalInputs; reactionBody = body; scheduleOnUIThread = uiThread; } } /** * Convenience function, to circumvent Java syntax restrictions * */ public static M_A[] consume(M_A... m_As) { return m_As; } private boolean isMoleculeKnown(M_A m) { return knownMoleculeNames != null && knownMoleculeNames.contains(m.getName()); } private void inject(M_A fullM) { if (!isMoleculeKnown(fullM)) return; injectAndStartReactions(fullM); } private Object injectSyncAndReturnValue(M_S fullM) { if (!isMoleculeKnown(fullM)) return null; injectAndStartReactions(fullM); try { fullM.semaphore.acquire(); } catch (InterruptedException e) { e.printStackTrace(); } fullM.semaphore = null; return fullM.resultValue; } private static void runOnUIThread(boolean uiThread, final Runnable runnable) { if (uiThread) { if (Looper.myLooper() == Looper.getMainLooper()) { runnable.run(); } else { uiHandler.post(runnable); } } else { runInBackground(runnable); } } private static void runInBackground(final Runnable runnable) { if (runnable != null){ new AsyncTask<Void, Void, Void>() { @Override protected Void doInBackground(Void... params) { runnable.run(); return null; } }; } } private void injectAndStartReactions(final M_A fullM) { runOnUIThread(decideOnUIThread, new Runnable() { @Override public void run() { internalInjectAndStartReactions(fullM); } }); } private void internalInjectAndStartReactions(M_A fullM) { List<M_A> presentMolecules = availableMolecules.get(fullM.getName()); if (presentMolecules == null) { presentMolecules = new ArrayList<AJoin.M_A>(); availableMolecules.put(fullM.getName(), presentMolecules); } presentMolecules.add(fullM); decideAndRunPossibleReactions(); } private void decideAndRunPossibleReactions() { ReactionBody foundReaction = null; while( (foundReaction = findAnyReaction()) != null ) { foundReaction.runReactionBody(); } } private ReactionBody findAnyReaction() { List<Reaction> reactions = Arrays.asList(definedReactions); Collections.shuffle(reactions); for (Reaction r : reactions) { List<M_A> availableInput = moleculesAvailable(r.nominalInputMolecules); if (availableInput != null) { ReactionBody newBody = r.reactionBody.makeCopy(r.scheduleOnUIThread); newBody.inputMolecules = availableInput; return newBody; } } return null; } /*NSMutableArray *affectedMoleculeList = [NSMutableArray arrayWithCapacity:moleculeNames.count]; for (NSString *moleculeClass in moleculeNames) { NSMutableArray *presentMolecules = [self.availableMoleculeNames objectForKey:moleculeClass]; if ([presentMolecules count] > 0) { [presentMolecules shuffle]; // important to remove a randomly chosen object! so, first we shuffle, id chosenMolecule = [presentMolecules lastObject]; // then we select the last object. [molecules addObject:chosenMolecule]; [affectedMoleculeList addObject:presentMolecules]; // affectedMoleculeList is the list of arrays from which we have selected last elements. Each of these arrays needs to be trimmed (the last element removed), but only if we finally succeed in finding all required molecules. Otherwise, nothing should be removed from any lists. } else { // did not find this molecule, but reaction requires it - nothing to do now. return nil; } } if (moleculeNames.count != molecules.count) return nil; // if we are here, we have found all input molecules required for the reaction! // now we need to remove them from the molecule arrays; note that affectedMoleculeInstances is a pointer to an array inside the dictionary self.availableMoleculeNames. for (NSMutableArray *affectedMoleculeInstances in affectedMoleculeList) { [affectedMoleculeInstances removeLastObject]; // now that the array was shuffled, we know that we need to remove the last object. } return [NSArray arrayWithArray:molecules];*/ private List<M_A> moleculesAvailable(M_A[] nominalInputMolecules) { List<M_A> molecules = new ArrayList<AJoin.M_A>(); List<List<M_A>> affectedMoleculeList = new ArrayList<List<AJoin.M_A>>(); for (M_A m : nominalInputMolecules) { List<M_A> presentMolecules = availableMolecules.get(m.getName()); if (presentMolecules != null && presentMolecules.size() > 0) { Collections.shuffle(presentMolecules); molecules.add(presentMolecules.get(0)); affectedMoleculeList.add(presentMolecules); } else { return null; } } if (molecules.size() != nominalInputMolecules.length) { return null; } for (List<M_A> l : affectedMoleculeList) { l.remove(0); } return molecules; } /** * Convenience functions, to circumvent Java syntax restrictions * */ public static Reaction reaction(M_A[] nominalInputs, ReactionBody body) { return new Reaction(nominalInputs, body, false); } public static Reaction reactionUI(M_A[] nominalInputs, ReactionBody body) { return new Reaction(nominalInputs, body, true); } /** * Define a new set of reactions, using input molecule objects that are already defined but not yet bound to a join definition. * */ public static void define(Reaction... reactions) { defineInternal(false, reactions); } public static void defineUI(Reaction... reactions) { defineInternal(true, reactions); } private static void defineInternal(boolean uiThread, Reaction... reactions) { AJoin join = new AJoin(uiThread); join.definedReactions = reactions; join.initializeReactionsAndMolecules(); // this will assign the join instance to the given input molecules. } private void initializeReactionsAndMolecules() { knownMoleculeNames = new HashSet<String>(); availableMolecules = new HashMap<String, List<M_A>>(); for (Reaction r : definedReactions) { for (M_A m : r.nominalInputMolecules) { m.ownerJoin = this; knownMoleculeNames.add(m.getName()); } } } }
package com.hbb20; import android.content.Context; import android.content.res.TypedArray; import android.graphics.PorterDuff; import android.graphics.Typeface; import android.os.Build; import android.telephony.PhoneNumberFormattingTextWatcher; import android.telephony.PhoneNumberUtils; import android.telephony.TelephonyManager; import android.text.Editable; import android.text.TextWatcher; import android.util.AttributeSet; import android.util.DisplayMetrics; import android.util.Log; import android.util.TypedValue; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.widget.EditText; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; import com.google.i18n.phonenumbers.NumberParseException; import com.google.i18n.phonenumbers.PhoneNumberUtil; import com.google.i18n.phonenumbers.Phonenumber; import java.util.ArrayList; import java.util.List; import java.util.Locale; public class CountryCodePicker extends RelativeLayout { static String TAG = "CCP"; static String BUNDLE_SELECTED_CODE = "selectedCode"; static int LIB_DEFAULT_COUNTRY_CODE = 91; private static int TEXT_GRAVITY_LEFT = -1, TEXT_GRAVITY_RIGHT = 1, TEXT_GRAVITY_CENTER = 0; private static String ANDROID_NAME_SPACE = "http://schemas.android.com/apk/res/android"; int defaultCountryCode; String defaultCountryNameCode; Context context; View holderView; LayoutInflater mInflater; TextView textView_selectedCountry; EditText editText_registeredCarrierNumber; RelativeLayout holder; ImageView imageViewArrow; ImageView imageViewFlag; LinearLayout linearFlagBorder; LinearLayout linearFlagHolder; Country selectedCountry; Country defaultCountry; RelativeLayout relativeClickConsumer; CountryCodePicker codePicker; TextGravity currentTextGravity; boolean showNameCode = false; boolean showPhoneCode = true; boolean ccpDialogShowPhoneCode = true; boolean showFlag = true; boolean showFullName = false; boolean showFastScroller; boolean searchAllowed = true; int contentColor; int borderFlagColor; List<Country> preferredCountries; int ccpTextgGravity = TEXT_GRAVITY_CENTER; //this will be "AU,IN,US" String countryPreference; int fastScrollerBubbleColor = 0; List<Country> customMasterCountriesList; //this will be "AU,IN,US" String customMasterCountries; Language customDefaultLanguage = Language.ENGLISH; Language languageToApply = Language.ENGLISH; boolean dialogKeyboardAutoPopup = true; boolean ccpClickable = true; boolean autoDetectLanguageEnabled, autoDetectCountryEnabled, numberAutoFormattingEnabled; String xmlWidth = "notSet"; TextWatcher validityTextWatcher; PhoneNumberFormattingTextWatcher textWatcher; boolean reportedValidity; private OnCountryChangeListener onCountryChangeListener; private PhoneNumberValidityChangeListener phoneNumberValidityChangeListener; private int fastScrollerHandleColor; private int dialogBackgroundColor, dialogTextColor, dialogSearchEditTextTintColor; private int fastScrollerBubbleTextAppearance; View.OnClickListener countryCodeHolderClickListener = new View.OnClickListener() { @Override public void onClick(View v) { if (isCcpClickable()) { CountryCodeDialog.openCountryCodeDialog(codePicker); } } }; public CountryCodePicker(Context context) { super(context); this.context = context; init(null); } public CountryCodePicker(Context context, AttributeSet attrs) { super(context, attrs); this.context = context; init(attrs); } public CountryCodePicker(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); this.context = context; init(attrs); } private boolean isNumberAutoFormattingEnabled() { return numberAutoFormattingEnabled; } /** * This will set boolean for numberAutoFormattingEnabled and refresh formattingTextWatcher * * @param numberAutoFormattingEnabled */ public void setNumberAutoFormattingEnabled(boolean numberAutoFormattingEnabled) { this.numberAutoFormattingEnabled = numberAutoFormattingEnabled; if (editText_registeredCarrierNumber != null) { updateFormattingTextWatcher(); } } private void init(AttributeSet attrs) { mInflater = LayoutInflater.from(context); xmlWidth = attrs.getAttributeValue(ANDROID_NAME_SPACE, "layout_width"); Log.d(TAG, "init:xmlWidth " + xmlWidth); removeAllViewsInLayout(); //at run time, match parent value returns LayoutParams.MATCH_PARENT ("-1"), for some android xml preview it returns "fill_parent" if (xmlWidth != null && (xmlWidth.equals(LayoutParams.MATCH_PARENT + "") || xmlWidth.equals(LayoutParams.FILL_PARENT + "") || xmlWidth.equals("fill_parent") || xmlWidth.equals("match_parent"))) { holderView = mInflater.inflate(R.layout.layout_full_width_code_picker, this, true); } else { holderView = mInflater.inflate(R.layout.layout_code_picker, this, true); } textView_selectedCountry = (TextView) holderView.findViewById(R.id.textView_selectedCountry); holder = (RelativeLayout) holderView.findViewById(R.id.countryCodeHolder); imageViewArrow = (ImageView) holderView.findViewById(R.id.imageView_arrow); imageViewFlag = (ImageView) holderView.findViewById(R.id.image_flag); linearFlagHolder = (LinearLayout) holderView.findViewById(R.id.linear_flag_holder); linearFlagBorder = (LinearLayout) holderView.findViewById(R.id.linear_flag_border); relativeClickConsumer = (RelativeLayout) holderView.findViewById(R.id.rlClickConsumer); codePicker = this; applyCustomProperty(attrs); relativeClickConsumer.setOnClickListener(countryCodeHolderClickListener); } private void applyCustomProperty(AttributeSet attrs) { // Log.d(TAG, "Applying custom property"); TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.CountryCodePicker, 0, 0); //default country code try { //hide nameCode. If someone wants only phone code to avoid name collision for same country phone code. showNameCode = a.getBoolean(R.styleable.CountryCodePicker_ccp_showNameCode, true); //show phone code. showPhoneCode = a.getBoolean(R.styleable.CountryCodePicker_ccp_showPhoneCode, true); //show phone code on dialog ccpDialogShowPhoneCode = a.getBoolean(R.styleable.CountryCodePicker_ccpDialog_showPhoneCode, showPhoneCode); //show full name showFullName = a.getBoolean(R.styleable.CountryCodePicker_ccp_showFullName, false); //show fast scroller showFastScroller = a.getBoolean(R.styleable.CountryCodePicker_ccpDialog_showFastScroller, true); //bubble color fastScrollerBubbleColor = a.getColor(R.styleable.CountryCodePicker_ccpDialog_fastScroller_bubbleColor, 0); //scroller handle color fastScrollerHandleColor = a.getColor(R.styleable.CountryCodePicker_ccpDialog_fastScroller_handleColor, 0); //scroller text appearance fastScrollerBubbleTextAppearance = a.getResourceId(R.styleable.CountryCodePicker_ccpDialog_fastScroller_bubbleTextAppearance, 0); //auto detect language autoDetectLanguageEnabled = a.getBoolean(R.styleable.CountryCodePicker_ccp_autoDetectLanguage, false); //auto detect county autoDetectCountryEnabled = a.getBoolean(R.styleable.CountryCodePicker_ccp_autoDetectCountry, true); //show flag showFlag(a.getBoolean(R.styleable.CountryCodePicker_ccp_showFlag, true)); //number auto formatting numberAutoFormattingEnabled = a.getBoolean(R.styleable.CountryCodePicker_ccp_autoFormatNumber, true); //autopop keyboard setDialogKeyboardAutoPopup(a.getBoolean(R.styleable.CountryCodePicker_ccpDialog_keyboardAutoPopup, true)); //if custom default language is specified, then set it as custom int attrLanguage = 3; //for english if (a.hasValue(R.styleable.CountryCodePicker_ccp_defaultLanguage)) { attrLanguage = a.getInt(R.styleable.CountryCodePicker_ccp_defaultLanguage, 1); } customDefaultLanguage = getLanguageEnum(attrLanguage); updateLanguageToApply(); //custom master list customMasterCountries = a.getString(R.styleable.CountryCodePicker_ccp_customMasterCountries); refreshCustomMasterList(); //preference countryPreference = a.getString(R.styleable.CountryCodePicker_ccp_countryPreference); refreshPreferredCountries(); //text gravity if (a.hasValue(R.styleable.CountryCodePicker_ccp_textGravity)) { ccpTextgGravity = a.getInt(R.styleable.CountryCodePicker_ccp_textGravity, TEXT_GRAVITY_RIGHT); } applyTextGravity(ccpTextgGravity); //default country defaultCountryNameCode = a.getString(R.styleable.CountryCodePicker_ccp_defaultNameCode); boolean setUsingNameCode = false; if (defaultCountryNameCode != null && defaultCountryNameCode.length() != 0) { if (Country.getCountryForNameCodeFromLibraryMasterList(getContext(), getLanguageToApply(), defaultCountryNameCode) != null) { setUsingNameCode = true; setDefaultCountry(Country.getCountryForNameCodeFromLibraryMasterList(getContext(), getLanguageToApply(), defaultCountryNameCode)); setSelectedCountry(defaultCountry); } } //if default country is not set using name code. if (!setUsingNameCode) { int defaultCountryCode = a.getInteger(R.styleable.CountryCodePicker_ccp_defaultPhoneCode, -1); //if invalid country is set using xml, it will be replaced with LIB_DEFAULT_COUNTRY_CODE if (Country.getCountryForCode(getContext(), getLanguageToApply(), preferredCountries, defaultCountryCode) == null) { defaultCountryCode = LIB_DEFAULT_COUNTRY_CODE; } setDefaultCountryUsingPhoneCode(defaultCountryCode); setSelectedCountry(defaultCountry); } //set auto detected country if (isAutoDetectCountryEnabled()) { selectCountryFromSimInfo(); } //content color int contentColor; if (isInEditMode()) { contentColor = a.getColor(R.styleable.CountryCodePicker_ccp_contentColor, 0); } else { contentColor = a.getColor(R.styleable.CountryCodePicker_ccp_contentColor, context.getResources().getColor(R.color.defaultContentColor)); } if (contentColor != 0) { setContentColor(contentColor); } // flag border color int borderFlagColor; if (isInEditMode()) { borderFlagColor = a.getColor(R.styleable.CountryCodePicker_ccp_flagBorderColor, 0); } else { borderFlagColor = a.getColor(R.styleable.CountryCodePicker_ccp_flagBorderColor, context.getResources().getColor(R.color.defaultBorderFlagColor)); } if (borderFlagColor != 0) { setFlagBorderColor(borderFlagColor); } //dialog colors setDialogBackgroundColor(a.getColor(R.styleable.CountryCodePicker_ccpDialog_backgroundColor, 0)); setDialogTextColor(a.getColor(R.styleable.CountryCodePicker_ccpDialog_textColor, 0)); setDialogSearchEditTextTintColor(a.getColor(R.styleable.CountryCodePicker_ccpDialog_searchEditTextTint, 0)); //text size int textSize = a.getDimensionPixelSize(R.styleable.CountryCodePicker_ccp_textSize, 0); if (textSize > 0) { textView_selectedCountry.setTextSize(TypedValue.COMPLEX_UNIT_PX, textSize); setFlagSize(textSize); setArrowSize(textSize); } else { //no textsize specified DisplayMetrics dm = context.getResources().getDisplayMetrics(); int defaultSize = Math.round(18 * (dm.xdpi / DisplayMetrics.DENSITY_DEFAULT)); setTextSize(defaultSize); } //if arrow size is explicitly defined int arrowSize = a.getDimensionPixelSize(R.styleable.CountryCodePicker_ccp_arrowSize, 0); if (arrowSize > 0) { setArrowSize(arrowSize); } searchAllowed = a.getBoolean(R.styleable.CountryCodePicker_ccpDialog_allowSearch, true); setCcpClickable(a.getBoolean(R.styleable.CountryCodePicker_ccp_clickable, true)); } catch (Exception e) { textView_selectedCountry.setText(e.getMessage()); } finally { a.recycle(); } Log.d(TAG, "end:xmlWidth " + xmlWidth); } boolean isCcpDialogShowPhoneCode() { return ccpDialogShowPhoneCode; } /** * To show/hide phone code from country selection dialog * @param ccpDialogShowPhoneCode */ public void setCcpDialogShowPhoneCode(boolean ccpDialogShowPhoneCode) { this.ccpDialogShowPhoneCode = ccpDialogShowPhoneCode; } boolean isShowPhoneCode() { return showPhoneCode; } /** * To show/hide phone code from ccp view * * @param showPhoneCode */ public void setShowPhoneCode(boolean showPhoneCode) { this.showPhoneCode = showPhoneCode; setSelectedCountry(selectedCountry); } int getFastScrollerBubbleTextAppearance() { return fastScrollerBubbleTextAppearance; } /** * This sets text appearance for fast scroller index character * * @param fastScrollerBubbleTextAppearance should be reference id of textappereance style. i.e. R.style.myBubbleTextAppearance */ public void setFastScrollerBubbleTextAppearance(int fastScrollerBubbleTextAppearance) { this.fastScrollerBubbleTextAppearance = fastScrollerBubbleTextAppearance; } int getFastScrollerHandleColor() { return fastScrollerHandleColor; } /** * This should be the color for fast scroller handle. * * @param fastScrollerHandleColor */ public void setFastScrollerHandleColor(int fastScrollerHandleColor) { this.fastScrollerHandleColor = fastScrollerHandleColor; } int getFastScrollerBubbleColor() { return fastScrollerBubbleColor; } /** * Sets bubble color for fast scroller * * @param fastScrollerBubbleColor */ public void setFastScrollerBubbleColor(int fastScrollerBubbleColor) { this.fastScrollerBubbleColor = fastScrollerBubbleColor; } TextGravity getCurrentTextGravity() { return currentTextGravity; } /** * When width is set "match_parent", this gravity will set placement of text (Between flag and down arrow). * * @param textGravity expected placement */ public void setCurrentTextGravity(TextGravity textGravity) { this.currentTextGravity = textGravity; applyTextGravity(textGravity.enumIndex); } private void applyTextGravity(int enumIndex) { if (enumIndex == TextGravity.LEFT.enumIndex) { textView_selectedCountry.setGravity(Gravity.LEFT); } else if (enumIndex == TextGravity.CENTER.enumIndex) { textView_selectedCountry.setGravity(Gravity.CENTER); } else { textView_selectedCountry.setGravity(Gravity.RIGHT); } } /** * which language to show is decided based on * autoDetectLanguage flag * if autoDetectLanguage is true, then it should check language based on locale, if no language is found based on locale, customDefault language will returned * else autoDetectLanguage is false, then customDefaultLanguage will be returned. * * @return */ private void updateLanguageToApply() { //when in edit mode, it will return default language only if (isInEditMode()) { if (customDefaultLanguage != null) { languageToApply = customDefaultLanguage; } else { languageToApply = Language.ENGLISH; } } else { if (isAutoDetectLanguageEnabled()) { Language localeBasedLanguage = getCCPLanguageFromLocale(); if (localeBasedLanguage == null) { //if no language is found from locale if (getCustomDefaultLanguage() != null) { //and custom language is defined languageToApply = getCustomDefaultLanguage(); } else { languageToApply = Language.ENGLISH; } } else { languageToApply = localeBasedLanguage; } } else { if (getCustomDefaultLanguage() != null) { languageToApply = customDefaultLanguage; } else { languageToApply = Language.ENGLISH; //library default } } } Log.d(TAG, "updateLanguageToApply: " + languageToApply); } private Language getCCPLanguageFromLocale() { Locale currentLocale = context.getResources().getConfiguration().locale; Log.d(TAG, "getCCPLanguageFromLocale: current locale language" + currentLocale.getLanguage()); for (Language language : Language.values()) { if (language.getCode().equalsIgnoreCase(currentLocale.getLanguage())) { return language; } } return null; } private Country getDefaultCountry() { return defaultCountry; } private void setDefaultCountry(Country defaultCountry) { this.defaultCountry = defaultCountry; // Log.d(TAG, "Setting default country:" + defaultCountry.logString()); } private TextView getTextView_selectedCountry() { return textView_selectedCountry; } private void setTextView_selectedCountry(TextView textView_selectedCountry) { this.textView_selectedCountry = textView_selectedCountry; } private Country getSelectedCountry() { return selectedCountry; } void setSelectedCountry(Country selectedCountry) { //as soon as country is selected, textView should be updated if (selectedCountry == null) { selectedCountry = Country.getCountryForCode(getContext(), getLanguageToApply(), preferredCountries, defaultCountryCode); } this.selectedCountry = selectedCountry; String displayText = ""; // add full name to if required if (showFullName) { displayText = displayText + selectedCountry.getName(); } // adds name code if required if (showNameCode) { if (showFullName) { displayText += " (" + selectedCountry.getNameCode().toUpperCase() + ")"; } else { displayText += " " + selectedCountry.getNameCode().toUpperCase(); } } // hide phone code if required if (showPhoneCode) { if (displayText.length() > 0) { displayText += " "; } displayText += "+" + selectedCountry.getPhoneCode(); } textView_selectedCountry.setText(displayText); //avoid blank state of ccp if (showFlag == false && displayText.length() == 0) { displayText += "+" + selectedCountry.getPhoneCode(); textView_selectedCountry.setText(displayText); } if (onCountryChangeListener != null) { onCountryChangeListener.onCountrySelected(); } imageViewFlag.setImageResource(selectedCountry.getFlagID()); // Log.d(TAG, "Setting selected country:" + selectedCountry.logString()); updateFormattingTextWatcher(); //notify to registered validity listener if (editText_registeredCarrierNumber != null && phoneNumberValidityChangeListener != null) { reportedValidity = isValidFullNumber(); phoneNumberValidityChangeListener.onValidityChanged(reportedValidity); } } Language getLanguageToApply() { if (languageToApply == null) { updateLanguageToApply(); } return languageToApply; } void setLanguageToApply(Language languageToApply) { this.languageToApply = languageToApply; } private void updateFormattingTextWatcher() { if (getEditText_registeredCarrierNumber() != null && selectedCountry != null) { String enteredValue = getEditText_registeredCarrierNumber().getText().toString(); String digitsValue = PhoneNumberUtil.normalizeDigitsOnly(enteredValue); editText_registeredCarrierNumber.removeTextChangedListener(textWatcher); if (numberAutoFormattingEnabled) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { textWatcher = new PhoneNumberFormattingTextWatcher(selectedCountry.getNameCode()); } else { textWatcher = new PhoneNumberFormattingTextWatcher(); } editText_registeredCarrierNumber.addTextChangedListener(textWatcher); } //text watcher stops working when it finds non digit character in previous phone code. This will reset its function editText_registeredCarrierNumber.setText(""); editText_registeredCarrierNumber.setText(digitsValue); editText_registeredCarrierNumber.setSelection(editText_registeredCarrierNumber.getText().length()); } } Language getCustomDefaultLanguage() { return customDefaultLanguage; } private void setCustomDefaultLanguage(Language customDefaultLanguage) { this.customDefaultLanguage = customDefaultLanguage; updateLanguageToApply(); setSelectedCountry(Country.getCountryForNameCodeFromLibraryMasterList(context, getLanguageToApply(), selectedCountry.getNameCode())); } private View getHolderView() { return holderView; } private void setHolderView(View holderView) { this.holderView = holderView; } private RelativeLayout getHolder() { return holder; } private void setHolder(RelativeLayout holder) { this.holder = holder; } boolean isAutoDetectLanguageEnabled() { return autoDetectLanguageEnabled; } boolean isAutoDetectCountryEnabled() { return autoDetectCountryEnabled; } boolean isDialogKeyboardAutoPopup() { return dialogKeyboardAutoPopup; } /** * By default, keyboard pops up every time ccp is clicked and selection dialog is opened. * * @param dialogKeyboardAutoPopup true: to open keyboard automatically when selection dialog is opened * false: to avoid auto pop of keyboard */ public void setDialogKeyboardAutoPopup(boolean dialogKeyboardAutoPopup) { this.dialogKeyboardAutoPopup = dialogKeyboardAutoPopup; } boolean isShowFastScroller() { return showFastScroller; } /** * Set visibility of fast scroller. * * @param showFastScroller */ public void setShowFastScroller(boolean showFastScroller) { this.showFastScroller = showFastScroller; } EditText getEditText_registeredCarrierNumber() { return editText_registeredCarrierNumber; } /** * this will register editText and will apply required text watchers * * @param editText_registeredCarrierNumber */ void setEditText_registeredCarrierNumber(EditText editText_registeredCarrierNumber) { this.editText_registeredCarrierNumber = editText_registeredCarrierNumber; PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance(); updateFormattingTextWatcher(); updateValidityTextWatcher(); } /** * This function will * - remove existing, if any, validityTextWatcher * - prepare new validityTextWatcher * - attach validityTextWatcher * - do initial reporting to watcher */ private void updateValidityTextWatcher() { try { editText_registeredCarrierNumber.removeTextChangedListener(validityTextWatcher); } catch (Exception e) { e.printStackTrace(); } //initial REPORTING reportedValidity = isValidFullNumber(); if (phoneNumberValidityChangeListener != null) { phoneNumberValidityChangeListener.onValidityChanged(reportedValidity); } validityTextWatcher = new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } @Override public void afterTextChanged(Editable s) { if (phoneNumberValidityChangeListener != null) { boolean currentValidity; currentValidity = isValidFullNumber(); if (currentValidity != reportedValidity) { reportedValidity = currentValidity; phoneNumberValidityChangeListener.onValidityChanged(reportedValidity); } } } }; editText_registeredCarrierNumber.addTextChangedListener(validityTextWatcher); } private LayoutInflater getmInflater() { return mInflater; } private OnClickListener getCountryCodeHolderClickListener() { return countryCodeHolderClickListener; } int getDialogBackgroundColor() { return dialogBackgroundColor; } /** * This will be color of dialog background * * @param dialogBackgroundColor */ public void setDialogBackgroundColor(int dialogBackgroundColor) { this.dialogBackgroundColor = dialogBackgroundColor; } int getDialogSearchEditTextTintColor() { return dialogSearchEditTextTintColor; } /** * If device is running above or equal LOLLIPOP version, this will change tint of search edittext background. * * @param dialogSearchEditTextTintColor */ public void setDialogSearchEditTextTintColor(int dialogSearchEditTextTintColor) { this.dialogSearchEditTextTintColor = dialogSearchEditTextTintColor; } int getDialogTextColor() { return dialogTextColor; } /** * This color will be applied to * Title of dialog * Name of country * Phone code of country * "X" button to clear query * preferred country divider if preferred countries defined (semi transparent) * * @param dialogTextColor */ public void setDialogTextColor(int dialogTextColor) { this.dialogTextColor = dialogTextColor; } /** * Publicly available functions from library */ /** * this will load preferredCountries based on countryPreference */ void refreshPreferredCountries() { if (countryPreference == null || countryPreference.length() == 0) { preferredCountries = null; } else { List<Country> localCountryList = new ArrayList<>(); for (String nameCode : countryPreference.split(",")) { Country country = Country.getCountryForNameCodeFromCustomMasterList(getContext(), customMasterCountriesList, getLanguageToApply(), nameCode); if (country != null) { if (!isAlreadyInList(country, localCountryList)) { //to avoid duplicate entry of country localCountryList.add(country); } } } if (localCountryList.size() == 0) { preferredCountries = null; } else { preferredCountries = localCountryList; } } if (preferredCountries != null) { // Log.d("preference list", preferredCountries.size() + " countries"); for (Country country : preferredCountries) { country.log(); } } else { // Log.d("preference list", " has no country"); } } /** * this will load preferredCountries based on countryPreference */ void refreshCustomMasterList() { if (customMasterCountries == null || customMasterCountries.length() == 0) { customMasterCountriesList = null; } else { List<Country> localCountryList = new ArrayList<>(); for (String nameCode : customMasterCountries.split(",")) { Country country = Country.getCountryForNameCodeFromLibraryMasterList(getContext(), getLanguageToApply(), nameCode); if (country != null) { if (!isAlreadyInList(country, localCountryList)) { //to avoid duplicate entry of country localCountryList.add(country); } } } if (localCountryList.size() == 0) { customMasterCountriesList = null; } else { customMasterCountriesList = localCountryList; } } if (customMasterCountriesList != null) { // Log.d("custom master list:", customMasterCountriesList.size() + " countries"); for (Country country : customMasterCountriesList) { country.log(); } } else { // Log.d("custom master list", " has no country"); } } List<Country> getCustomMasterCountriesList() { return customMasterCountriesList; } /** * @param customMasterCountriesList is list of countries that we need as custom master list */ void setCustomMasterCountriesList(List<Country> customMasterCountriesList) { this.customMasterCountriesList = customMasterCountriesList; } /** * @return comma separated custom master countries' name code. i.e "gb,us,nz,in,pk" */ String getCustomMasterCountries() { return customMasterCountries; } /** * To provide definite set of countries when selection dialog is opened. * Only custom master countries, if defined, will be there is selection dialog to select from. * To set any country in preference, it must be included in custom master countries, if defined * When not defined or null or blank is set, it will use library's default master list * Custom master list will only limit the visibility of irrelevant country from selection dialog. But all other functions like setCountryForCodeName() or setFullNumber() will consider all the countries. * * @param customMasterCountries is country name codes separated by comma. e.g. "us,in,nz" * if null or "" , will remove custom countries and library default will be used. */ public void setCustomMasterCountries(String customMasterCountries) { this.customMasterCountries = customMasterCountries; } /** * @return true if ccp is enabled for click */ boolean isCcpClickable() { return ccpClickable; } /** * Allow click and open dialog * * @param ccpClickable */ public void setCcpClickable(boolean ccpClickable) { this.ccpClickable = ccpClickable; if (!ccpClickable) { relativeClickConsumer.setOnClickListener(null); relativeClickConsumer.setClickable(false); relativeClickConsumer.setEnabled(false); } else { relativeClickConsumer.setOnClickListener(countryCodeHolderClickListener); relativeClickConsumer.setClickable(true); relativeClickConsumer.setEnabled(true); } } /** * This will match name code of all countries of list against the country's name code. * * @param country * @param countryList list of countries against which country will be checked. * @return if country name code is found in list, returns true else return false */ private boolean isAlreadyInList(Country country, List<Country> countryList) { if (country != null && countryList != null) { for (Country iterationCountry : countryList) { if (iterationCountry.getNameCode().equalsIgnoreCase(country.getNameCode())) { return true; } } } return false; } /** * This function removes possible country code from fullNumber and set rest of the number as carrier number. * * @param fullNumber combination of country code and carrier number. * @param country selected country in CCP to detect country code part. */ private String detectCarrierNumber(String fullNumber, Country country) { String carrierNumber; if (country == null || fullNumber == null) { carrierNumber = fullNumber; } else { int indexOfCode = fullNumber.indexOf(country.getPhoneCode()); if (indexOfCode == -1) { carrierNumber = fullNumber; } else { carrierNumber = fullNumber.substring(indexOfCode + country.getPhoneCode().length()); } } return carrierNumber; } /** * Related to selected country */ //add entry here private Language getLanguageEnum(int index) { if (index < Language.values().length) { return Language.values()[index]; } else { return Language.ENGLISH; } } String getDialogTitle() { return Country.getDialogTitle(context, getLanguageToApply()); } String getSearchHintText() { return Country.getSearchHintMessage(context, getLanguageToApply()); } /** * @return translated text for "No Results Found" message. */ String getNoResultFoundText() { return Country.getNoResultFoundAckMessage(context, getLanguageToApply()); } /** * This method is not encouraged because this might set some other country which have same country code as of yours. e.g 1 is common for US and canada. * If you are trying to set US ( and countryPreference is not set) and you pass 1 as @param defaultCountryCode, it will set canada (prior in list due to alphabetical order) * Rather use @function setDefaultCountryUsingNameCode("us"); or setDefaultCountryUsingNameCode("US"); * <p> * Default country code defines your default country. * Whenever invalid / improper number is found in setCountryForPhoneCode() / setFullNumber(), it CCP will set to default country. * This function will not set default country as selected in CCP. To set default country in CCP call resetToDefaultCountry() right after this call. * If invalid defaultCountryCode is applied, it won't be changed. * * @param defaultCountryCode code of your default country * if you want to set IN +91(India) as default country, defaultCountryCode = 91 * if you want to set JP +81(Japan) as default country, defaultCountryCode = 81 */ @Deprecated public void setDefaultCountryUsingPhoneCode(int defaultCountryCode) { Country defaultCountry = Country.getCountryForCode(getContext(), getLanguageToApply(), preferredCountries, defaultCountryCode); //xml stores data in string format, but want to allow only numeric value to country code to user. if (defaultCountry == null) { //if no correct country is found // Log.d(TAG, "No country for code " + defaultCountryCode + " is found"); } else { //if correct country is found, set the country this.defaultCountryCode = defaultCountryCode; setDefaultCountry(defaultCountry); } } /** * Default country name code defines your default country. * Whenever invalid / improper name code is found in setCountryForNameCode(), CCP will set to default country. * This function will not set default country as selected in CCP. To set default country in CCP call resetToDefaultCountry() right after this call. * If invalid defaultCountryCode is applied, it won't be changed. * * @param defaultCountryNameCode code of your default country * if you want to set IN +91(India) as default country, defaultCountryCode = "IN" or "in" * if you want to set JP +81(Japan) as default country, defaultCountryCode = "JP" or "jp" */ public void setDefaultCountryUsingNameCode(String defaultCountryNameCode) { Country defaultCountry = Country.getCountryForNameCodeFromLibraryMasterList(getContext(), getLanguageToApply(), defaultCountryNameCode); //xml stores data in string format, but want to allow only numeric value to country code to user. if (defaultCountry == null) { //if no correct country is found // Log.d(TAG, "No country for nameCode " + defaultCountryNameCode + " is found"); } else { //if correct country is found, set the country this.defaultCountryNameCode = defaultCountry.getNameCode(); setDefaultCountry(defaultCountry); } } /** * @return: Country Code of default country * i.e if default country is IN +91(India) returns: "91" * if default country is JP +81(Japan) returns: "81" */ public String getDefaultCountryCode() { return defaultCountry.phoneCode; } /** * * To get code of default country as Integer. * * @return integer value of default country code in CCP * i.e if default country is IN +91(India) returns: 91 * if default country is JP +81(Japan) returns: 81 */ public int getDefaultCountryCodeAsInt() { int code = 0; try { code = Integer.parseInt(getDefaultCountryCode()); } catch (Exception e) { e.printStackTrace(); } return code; } /** * To get code of default country with prefix "+". * * @return String value of default country code in CCP with prefix "+" * i.e if default country is IN +91(India) returns: "+91" * if default country is JP +81(Japan) returns: "+81" */ public String getDefaultCountryCodeWithPlus() { return "+" + getDefaultCountryCode(); } /** * To get name of default country. * * @return String value of country name, default in CCP * i.e if default country is IN +91(India) returns: "India" * if default country is JP +81(Japan) returns: "Japan" */ public String getDefaultCountryName() { return getDefaultCountry().name; } /** * To get name code of default country. * * @return String value of country name, default in CCP * i.e if default country is IN +91(India) returns: "IN" * if default country is JP +81(Japan) returns: "JP" */ public String getDefaultCountryNameCode() { return getDefaultCountry().nameCode.toUpperCase(); } /** * reset the default country as selected country. */ public void resetToDefaultCountry() { setSelectedCountry(defaultCountry); } /** * To get code of selected country. * * @return String value of selected country code in CCP * i.e if selected country is IN +91(India) returns: "91" * if selected country is JP +81(Japan) returns: "81" */ public String getSelectedCountryCode() { return getSelectedCountry().phoneCode; } /** * To get code of selected country with prefix "+". * * @return String value of selected country code in CCP with prefix "+" * i.e if selected country is IN +91(India) returns: "+91" * if selected country is JP +81(Japan) returns: "+81" */ public String getSelectedCountryCodeWithPlus() { return "+" + getSelectedCountryCode(); } /** * * To get code of selected country as Integer. * * @return integer value of selected country code in CCP * i.e if selected country is IN +91(India) returns: 91 * if selected country is JP +81(Japan) returns: 81 */ public int getSelectedCountryCodeAsInt() { int code = 0; try { code = Integer.parseInt(getSelectedCountryCode()); } catch (Exception e) { e.printStackTrace(); } return code; } /** * To get name of selected country. * * @return String value of country name, selected in CCP * i.e if selected country is IN +91(India) returns: "India" * if selected country is JP +81(Japan) returns: "Japan" */ public String getSelectedCountryName() { return getSelectedCountry().name; } /** * To get name code of selected country. * * @return String value of country name, selected in CCP * i.e if selected country is IN +91(India) returns: "IN" * if selected country is JP +81(Japan) returns: "JP" */ public String getSelectedCountryNameCode() { return getSelectedCountry().nameCode.toUpperCase(); } /** * This will set country with @param countryCode as country code, in CCP * * @param countryCode a valid country code. * If you want to set IN +91(India), countryCode= 91 * If you want to set JP +81(Japan), countryCode= 81 */ public void setCountryForPhoneCode(int countryCode) { Country country = Country.getCountryForCode(getContext(), getLanguageToApply(), preferredCountries, countryCode); //xml stores data in string format, but want to allow only numeric value to country code to user. if (country == null) { if (defaultCountry == null) { defaultCountry = Country.getCountryForCode(getContext(), getLanguageToApply(), preferredCountries, defaultCountryCode); } setSelectedCountry(defaultCountry); } else { setSelectedCountry(country); } } /** * This will set country with @param countryNameCode as country name code, in CCP * * @param countryNameCode a valid country name code. * If you want to set IN +91(India), countryCode= IN * If you want to set JP +81(Japan), countryCode= JP */ public void setCountryForNameCode(String countryNameCode) { Country country = Country.getCountryForNameCodeFromLibraryMasterList(getContext(), getLanguageToApply(), countryNameCode); //xml stores data in string format, but want to allow only numeric value to country code to user. if (country == null) { if (defaultCountry == null) { defaultCountry = Country.getCountryForCode(getContext(), getLanguageToApply(), preferredCountries, defaultCountryCode); } setSelectedCountry(defaultCountry); } else { setSelectedCountry(country); } } /** * All functions that work with fullNumber need an editText to write and read carrier number of full number. * An editText for carrier number must be registered in order to use functions like setFullNumber() and getFullNumber(). * * @param editTextCarrierNumber - an editText where user types carrier number ( the part of full number other than country code). */ public void registerCarrierNumberEditText(EditText editTextCarrierNumber) { setEditText_registeredCarrierNumber(editTextCarrierNumber); } /** * This function combines selected country code from CCP and carrier number from @param editTextCarrierNumber * * @return Full number is countryCode + carrierNumber i.e countryCode= 91 and carrier number= 8866667722, this will return "918866667722" */ public String getFullNumber() { String fullNumber; if (editText_registeredCarrierNumber != null) { fullNumber = getSelectedCountry().getPhoneCode() + editText_registeredCarrierNumber.getText().toString(); fullNumber = PhoneNumberUtil.normalizeDigitsOnly(fullNumber); } else { fullNumber = getSelectedCountry().getPhoneCode(); Log.w(TAG, "EditText for carrier number is not registered. Register it using registerCarrierNumberEditText() before getFullNumber() or setFullNumber()."); } return fullNumber; } /** * Separate out country code and carrier number from fullNumber. * Sets country of separated country code in CCP and carrier number as text of editTextCarrierNumber * If no valid country code is found from full number, CCP will be set to default country code and full number will be set as carrier number to editTextCarrierNumber. * * @param fullNumber is combination of country code and carrier number, (country_code+carrier_number) for example if country is India (+91) and carrier/mobile number is 8866667722 then full number will be 9188666667722 or +918866667722. "+" in starting of number is optional. */ public void setFullNumber(String fullNumber) { Country country = Country.getCountryForNumber(getContext(), getLanguageToApply(), preferredCountries, fullNumber); setSelectedCountry(country); String carrierNumber = detectCarrierNumber(fullNumber, country); if (getEditText_registeredCarrierNumber() != null) { getEditText_registeredCarrierNumber().setText(carrierNumber); } else { Log.w(TAG, "EditText for carrier number is not registered. Register it using registerCarrierNumberEditText() before getFullNumber() or setFullNumber()."); } } /** * This function combines selected country code from CCP and carrier number from @param editTextCarrierNumber * This will return formatted number. * * @return Full number is countryCode + carrierNumber i.e countryCode= 91 and carrier number= 8866667722, this will return "918866667722" */ public String getFormattedFullNumber() { String formattedFullNumber; Phonenumber.PhoneNumber phoneNumber; if (editText_registeredCarrierNumber != null) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { formattedFullNumber = PhoneNumberUtils.formatNumber(getFullNumberWithPlus(), getSelectedCountryCode()); } else { formattedFullNumber = PhoneNumberUtils.formatNumber(getFullNumberWithPlus()); } } else { formattedFullNumber = getSelectedCountry().getPhoneCode(); Log.w(TAG, "EditText for carrier number is not registered. Register it using registerCarrierNumberEditText() before getFullNumber() or setFullNumber()."); } return formattedFullNumber; } /** * This function combines selected country code from CCP and carrier number from @param editTextCarrierNumber and prefix "+" * * @return Full number is countryCode + carrierNumber i.e countryCode= 91 and carrier number= 8866667722, this will return "+918866667722" */ public String getFullNumberWithPlus() { String fullNumber = "+" + getFullNumber(); return fullNumber; } /** * @return content color of CCP's text and small downward arrow. */ public int getContentColor() { return contentColor; } /** * Sets text and small down arrow color of CCP. * * @param contentColor color to apply to text and down arrow */ public void setContentColor(int contentColor) { this.contentColor = contentColor; textView_selectedCountry.setTextColor(this.contentColor); imageViewArrow.setColorFilter(this.contentColor, PorterDuff.Mode.SRC_IN); } /** * Sets flag border color of CCP. * * @param borderFlagColor color to apply to flag border */ public void setFlagBorderColor(int borderFlagColor) { this.borderFlagColor = borderFlagColor; linearFlagBorder.setBackgroundColor(this.borderFlagColor); } /** * Modifies size of text in side CCP view. * * @param textSize size of text in pixels */ public void setTextSize(int textSize) { if (textSize > 0) { textView_selectedCountry.setTextSize(TypedValue.COMPLEX_UNIT_PX, textSize); setArrowSize(textSize); setFlagSize(textSize); } } /** * Modifies size of downArrow in CCP view * * @param arrowSize size in pixels */ public void setArrowSize(int arrowSize) { if (arrowSize > 0) { LayoutParams params = (LayoutParams) imageViewArrow.getLayoutParams(); params.width = arrowSize; params.height = arrowSize; imageViewArrow.setLayoutParams(params); } } /** * If nameCode of country in CCP view is not required use this to show/hide country name code of ccp view. * * @param showNameCode true will show country name code in ccp view, it will result " (IN) +91 " * false will remove country name code from ccp view, it will result " +91 " */ public void showNameCode(boolean showNameCode) { this.showNameCode = showNameCode; setSelectedCountry(selectedCountry); } /** * This will set preferred countries using their name code. Prior preferred countries will be replaced by these countries. * Preferred countries will be at top of country selection box. * If more than one countries have same country code, country in preferred list will have higher priory than others. e.g. Canada and US have +1 as their country code. If "us" is set as preferred country then US will be selected whenever setCountryForPhoneCode(1); or setFullNumber("+1xxxxxxxxx"); is called. * * @param countryPreference is country name codes separated by comma. e.g. "us,in,nz" */ public void setCountryPreference(String countryPreference) { this.countryPreference = countryPreference; } /** * Language will be applied to country select dialog * If autoDetectCountry is true, ccp will try to detect language from locale. * Detected language is supported If no language is detected or detected language is not supported by ccp, it will set default language as set. * * @param language */ public void changeDefaultLanguage(Language language) { setCustomDefaultLanguage(language); } /** * To change font of ccp views * * @param typeFace */ public void setTypeFace(Typeface typeFace) { try { textView_selectedCountry.setTypeface(typeFace); } catch (Exception e) { e.printStackTrace(); } } /** * To change font of ccp views along with style. * * @param typeFace * @param style */ public void setTypeFace(Typeface typeFace, int style) { try { textView_selectedCountry.setTypeface(typeFace, style); } catch (Exception e) { e.printStackTrace(); } } /** * To get call back on country selection a onCountryChangeListener must be registered. * * @param onCountryChangeListener */ public void setOnCountryChangeListener(OnCountryChangeListener onCountryChangeListener) { this.onCountryChangeListener = onCountryChangeListener; } /** * Modifies size of flag in CCP view * * @param flagSize size in pixels */ public void setFlagSize(int flagSize) { imageViewFlag.getLayoutParams().height = flagSize; imageViewFlag.requestLayout(); } public void showFlag(boolean showFlag) { this.showFlag = showFlag; if (showFlag) { linearFlagHolder.setVisibility(VISIBLE); } else { linearFlagHolder.setVisibility(GONE); } } public void showFullName(boolean showFullName) { this.showFullName = showFullName; setSelectedCountry(selectedCountry); } /** * SelectionDialogSearch is the facility to search through the list of country while selecting. * * @return true if search is set allowed */ public boolean isSearchAllowed() { return searchAllowed; } /** * SelectionDialogSearch is the facility to search through the list of country while selecting. * * @param searchAllowed true will allow search and false will hide search box */ public void setSearchAllowed(boolean searchAllowed) { this.searchAllowed = searchAllowed; } /** * Sets validity change listener. * First call back will be sent right away. * * @param phoneNumberValidityChangeListener */ public void setPhoneNumberValidityChangeListener(PhoneNumberValidityChangeListener phoneNumberValidityChangeListener) { this.phoneNumberValidityChangeListener = phoneNumberValidityChangeListener; if (editText_registeredCarrierNumber != null) { reportedValidity = isValidFullNumber(); phoneNumberValidityChangeListener.onValidityChanged(reportedValidity); } } /** * This function will check the validity of entered number. * It will use PhoneNumberUtil to check validity * * @return true if entered carrier number is valid else false */ public boolean isValidFullNumber() { try { if (getEditText_registeredCarrierNumber() != null && getEditText_registeredCarrierNumber().getText().length() != 0) { Phonenumber.PhoneNumber phoneNumber = PhoneNumberUtil.getInstance().parse("+" + selectedCountry.getPhoneCode() + getEditText_registeredCarrierNumber().getText().toString(), selectedCountry.getNameCode()); return PhoneNumberUtil.getInstance().isValidNumber(phoneNumber); } else if (getEditText_registeredCarrierNumber() == null) { Toast.makeText(context, "No editText for Carrier number found.", Toast.LENGTH_SHORT).show(); return false; } else { return false; } } catch (NumberParseException e) { // when number could not be parsed, its not valid return false; } } /** * loads current country in ccp using telephony manager */ public void selectCountryFromSimInfo() { try { TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); String currentCountryISO = telephonyManager.getSimCountryIso(); setSelectedCountry(Country.getCountryForNameCodeFromLibraryMasterList(getContext(), getLanguageToApply(), currentCountryISO)); } catch (Exception e) { Log.w(TAG, "applyCustomProperty: could not set country from sim"); } } /** * Update every time new language is supported #languageSupport */ //add an entry for your language in attrs.xml's <attr name="language" format="enum"> enum. //add here so that language can be set programmatically public enum Language { ARABIC("ar"), BENGALI("bn"), CHINESE_SIMPLIFIED("zh"), ENGLISH("en"), FRENCH("fr"), GERMAN("de"), GUJARATI("gu"), HINDI("hi"), JAPANESE("ja"), INDONESIA("in"), PORTUGUESE("pt"), RUSSIAN("ru"), SPANISH("es"), HEBREW("iw"), CHINESE_TRADITIONAL("zh"), KOREAN("ko"), UKRAINIAN("ua"); String code; Language(String code) { this.code = code; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } } /** * When width is "match_parent", this gravity will decide the placement of text. */ public enum TextGravity { LEFT(-1), CENTER(0), RIGHT(1); int enumIndex; TextGravity(int i) { enumIndex = i; } } /** * interface to set change listener */ public interface OnCountryChangeListener { void onCountrySelected(); } /** * Interface to check phone number validity change listener */ public interface PhoneNumberValidityChangeListener { void onValidityChanged(boolean isValidNumber); } }
package ucar.nc2.iosp.nids; import ucar.ma2.*; import ucar.nc2.*; import ucar.nc2.iosp.AbstractIOServiceProvider; import ucar.nc2.units.DateUnit; import java.io.*; import java.util.*; import java.util.zip.DataFormatException; import java.util.zip.Inflater; import java.nio.ByteBuffer; /** * IOServiceProvider implementation abstract base class to read/write "version 3" netcdf files. * AKA "file format version 1" files. * <p/> * see concrete class */ public class Nidsiosp extends AbstractIOServiceProvider { protected boolean readonly; private ucar.nc2.NetcdfFile ncfile; private ucar.unidata.io.RandomAccessFile myRaf; // private Nidsheader.Vinfo myInfo; protected Nidsheader headerParser; private static int pcode; final static int Z_DEFLATED = 8; final static int DEF_WBITS = 15; // used for writing protected int fileUsed = 0; // how much of the file is written to ? protected int recStart = 0; // where the record data starts protected boolean debug = false, debugSize = false, debugSPIO = false; protected boolean showHeaderBytes = false; /** * Read nested structure data * @param v2 * @param section * @return output data * @throws java.io.IOException * @throws ucar.ma2.InvalidRangeException */ public ucar.ma2.Array readNestedData(ucar.nc2.Variable v2, Section section) throws java.io.IOException, ucar.ma2.InvalidRangeException { Variable vp = v2.getParentStructure(); Object data; Array outputData; List<Range> ranges = section.getRanges(); Nidsheader.Vinfo vinfo = (Nidsheader.Vinfo) vp.getSPobject(); byte[] vdata = headerParser.getUncompData((int) vinfo.doff, 0); ByteBuffer bos = ByteBuffer.wrap(vdata); if (vp.getName().startsWith("VADWindSpeed")) { return readNestedWindBarbData(vp.getShortName(), v2.getShortName(), bos, vinfo, ranges); } else if (vp.getName().startsWith("unlinkedVectorStruct")) { return readNestedDataUnlinkVector(vp.getShortName(), v2.getShortName(), bos, vinfo, ranges); } else if (vp.getName().equals("linkedVectorStruct")) { return readNestedLinkedVectorData(vp.getShortName(), v2.getShortName(), bos, vinfo, ranges); } else if (vp.getName().startsWith("textStruct")) { return readNestedTextStringData(vp.getShortName(), v2.getShortName(), bos, vinfo, ranges); } else if (vp.getName().startsWith("VectorArrow")) { return readNestedVectorArrowData(vp.getShortName(), v2.getShortName(), bos, vinfo, ranges); } else if (vp.getName().startsWith("circleStruct")) { return readNestedCircleStructData(vp.getShortName(), v2.getShortName(), bos, vinfo, ranges); } else { throw new UnsupportedOperationException("Unknown nested variable "+v2.getName()); } // return null; } /** * checking the file * @param raf * @return the valid of file checking */ public boolean isValidFile(ucar.unidata.io.RandomAccessFile raf) { Nidsheader localHeader = new Nidsheader(); return (localHeader.isValidFile(raf)); } /** * Open the file and read the header part * @param raf * @param file * @param cancelTask * @throws IOException */ public void open(ucar.unidata.io.RandomAccessFile raf, ucar.nc2.NetcdfFile file, ucar.nc2.util.CancelTask cancelTask) throws IOException { ncfile = file; myRaf = raf; headerParser = new Nidsheader(); headerParser.read(myRaf, ncfile); //myInfo = headerParser.getVarInfo(); pcode = headerParser.pcode; ncfile.finish(); } /** * Read the data for each variable passed in * @param v2 * @param section * @return output data * @throws IOException * @throws InvalidRangeException */ public Array readData(Variable v2, Section section) throws IOException, InvalidRangeException { // subset Object data; Array outputData; byte[] vdata; Nidsheader.Vinfo vinfo; ByteBuffer bos; List<Range> ranges = section.getRanges(); vinfo = (Nidsheader.Vinfo) v2.getSPobject(); /* if (vinfo.isZlibed ) vdata = readCompData(vinfo.hoff, vinfo.doff); else vdata = readUCompData(vinfo.hoff, vinfo.doff); ByteBuffer bos = ByteBuffer.wrap(vdata); */ vdata = headerParser.getUncompData((int) vinfo.doff, 0); bos = ByteBuffer.wrap(vdata); if (v2.getName().equals("azimuth")) { data = readRadialDataAzi(bos, vinfo); outputData = Array.factory(v2.getDataType().getPrimitiveClassType(), v2.getShape(), data); } else if (v2.getName().equals("gate")) { data = readRadialDataGate(vinfo); outputData = Array.factory(v2.getDataType().getPrimitiveClassType(), v2.getShape(), data); } else if (v2.getName().equals("elevation")) { data = readRadialDataEle(bos, vinfo); outputData = Array.factory(v2.getDataType().getPrimitiveClassType(), v2.getShape(), data); } else if (v2.getName().equals("latitude")) { double lat = ncfile.findGlobalAttribute("RadarLatitude").getNumericValue().doubleValue(); data = readRadialDataLatLonAlt(lat, vinfo); outputData = Array.factory(v2.getDataType().getPrimitiveClassType(), v2.getShape(), data); } else if (v2.getName().equals("longitude")) { double lon = ncfile.findGlobalAttribute("RadarLongitude").getNumericValue().doubleValue(); data = readRadialDataLatLonAlt(lon, vinfo); outputData = Array.factory(v2.getDataType().getPrimitiveClassType(), v2.getShape(), data); } else if (v2.getName().equals("altitude")) { double alt = ncfile.findGlobalAttribute("RadarAltitude").getNumericValue().doubleValue(); data = readRadialDataLatLonAlt(alt, vinfo); outputData = Array.factory(v2.getDataType().getPrimitiveClassType(), v2.getShape(), data); } else if (v2.getName().equals("distance")) { data = readDistance(vinfo); outputData = Array.factory(v2.getDataType().getPrimitiveClassType(), v2.getShape(), data); } else if (v2.getName().equals("rays_time")) { String rt = ncfile.findGlobalAttribute("DateCreated").getStringValue(); java.util.Date pDate = DateUnit.getStandardOrISO(rt); double lt = pDate.getTime(); double[] dd = new double[vinfo.yt]; for (int radial = 0; radial < vinfo.yt; radial++) { dd[radial] = (float) lt; } outputData = Array.factory(v2.getDataType().getPrimitiveClassType(), v2.getShape(), dd); } else if (v2.getName().startsWith("EchoTop") || v2.getName().startsWith("VertLiquid") || v2.getName().startsWith("BaseReflectivityComp") || v2.getName().startsWith("LayerCompReflect")) { data = readOneArrayData(bos, vinfo, v2.getName()); outputData = Array.factory(v2.getDataType().getPrimitiveClassType(), v2.getShape(), data); } else if (v2.getName().startsWith("PrecipArray")) { data = readOneArrayData1(bos, vinfo); outputData = Array.factory(v2.getDataType().getPrimitiveClassType(), v2.getShape(), data); } else if ( v2.getName().startsWith("Precip") && !vinfo.isRadial) { data = readOneArrayData(bos, vinfo, v2.getName()); outputData = Array.factory(v2.getDataType().getPrimitiveClassType(), v2.getShape(), data); } else if (v2.getName().equals("unlinkedVectorStruct")) { return readUnlinkedVectorData(v2.getName(), bos, vinfo); // JOHN outputData = Array.factory( v2.getDataType().getPrimitiveClassType(), v2.getShape(), data); } else if (v2.getName().equals("linkedVectorStruct")) { return readLinkedVectorData(v2.getName(), bos, vinfo); } else if (v2.getName().startsWith("textStruct")) { return readTextStringData(v2.getName(), bos, vinfo); // JOHN outputData = Array.factory( v2.getDataType().getPrimitiveClassType(), v2.getShape(), data); } else if (v2.getName().startsWith("VADWindSpeed")) { return readWindBarbData(v2.getName(), bos, vinfo, null); // JOHN outputData = Array.factory( v2.getDataType().getPrimitiveClassType(), v2.getShape(), data); } else if (v2.getName().startsWith("VectorArrow")) { return readVectorArrowData(v2.getName(), bos, vinfo); // JOHN outputData = Array.factory( v2.getDataType().getPrimitiveClassType(), v2.getShape(), data); } else if (v2.getName().startsWith("TabMessagePage")) { data = readTabAlphaNumData(bos, vinfo); outputData = Array.factory(v2.getDataType().getPrimitiveClassType(), v2.getShape(), data); } else if (v2.getName().startsWith("circleStruct")) { return readCircleStructData(v2.getName(), bos, vinfo); } else if (v2.getName().startsWith("hail") || v2.getName().startsWith("TVS")) { return readGraphicSymbolData(v2.getName(), bos, vinfo); } else { data = readOneScanData(bos, vinfo, v2.getName()); outputData = Array.factory(v2.getDataType().getPrimitiveClassType(), v2.getShape(), data); } return( outputData.sectionNoReduce( ranges).copy()); //return outputData; } /** * Read nested graphic symbolic structure data * * @param name Variable name, * @param m Structure mumber name, * @param bos data buffer, * @param vinfo variable info, * @param section variable section * @return the array of member variable data */ public Array readNestedGraphicSymbolData(String name, StructureMembers.Member m, ByteBuffer bos, Nidsheader.Vinfo vinfo, java.util.List section) throws IOException, InvalidRangeException { int[] pos = vinfo.pos; int size = pos.length; Structure pdata = (Structure) ncfile.findVariable(name); ArrayStructure ma = readCircleStructData(name, bos, vinfo); short[] pa = new short[size]; for (int i = 0; i < size; i++) { pa[i] = ma.getScalarShort(i, m); } Array ay = Array.factory(short.class, pdata.getShape(), pa); return ay.sectionNoReduce(section); } /** * Read graphic sysmbol structure data * * @param name Variable name * @param bos data buffer, * @param vinfo variable info, * @return the arraystructure of graphic symbol data */ public ArrayStructure readGraphicSymbolData(String name, ByteBuffer bos, Nidsheader.Vinfo vinfo) throws IOException, InvalidRangeException { int[] pos = vinfo.pos; int[] sizes = vinfo.len; int size = pos.length; Structure pdata = (Structure) ncfile.findVariable(name); StructureMembers members = pdata.makeStructureMembers(); members.findMember("x_start").setDataParam(0); members.findMember("y_start").setDataParam(2); return new MyArrayStructureBBpos(members, new int[]{size}, bos, pos, sizes); /* int[] pos = vinfo.pos; int[] dlen = vinfo.len; int size = pos.length; int vlen = 0; for(int i=0; i< size ; i++ ){ vlen = vlen + dlen[i]; } Structure pdata = (Structure) ncfile.findVariable( name); StructureMembers members = pdata.makeStructureMembers(); members.findMember("x_start"); members.findMember("y_start"); // return new ArrayStructureBBpos(members, new int[] {size}, bos, pos ); short istart; short jstart; ArrayStructureW asw = new ArrayStructureW(members, new int[] {vlen}); int ii = 0; for (int i=0; i< size; i++) { bos.position( pos[i] ); for( int j = 0; j < dlen[i]; j++ ) { StructureDataW sdata = new StructureDataW(asw.getStructureMembers()); Iterator memberIter = sdata.getMembers().iterator(); ArrayShort.D0 sArray ; istart = bos.getShort(); jstart = bos.getShort(); sArray = new ArrayShort.D0(); sArray.set( istart ); sdata.setMemberData( (StructureMembers.Member) memberIter.next(), sArray); sArray = new ArrayShort.D0(); sArray.set( jstart ); sdata.setMemberData((StructureMembers.Member) memberIter.next(), sArray); asw.setStructureData(sdata, ii); ii++; } } //end of for loop return asw; */ } /** * Read nested structure data * * @param name Variable name, * @param memberName mumber name, * @param bos data buffer, * @param vinfo variable info, * @param section variable section * @return the array of member variable data */ public Array readNestedLinkedVectorData(String name, String memberName, ByteBuffer bos, Nidsheader.Vinfo vinfo, java.util.List section) throws IOException, InvalidRangeException { Structure pdata = (Structure) ncfile.findVariable(name); ArrayStructure ma = readLinkedVectorData(name, bos, vinfo); int size = (int) pdata.getSize(); StructureMembers members = ma.getStructureMembers(); StructureMembers.Member m = members.findMember(memberName); short[] pa = new short[size]; for (int i = 0; i < size; i++) { pa[i] = ma.getScalarShort(i, m); } Array ay = Array.factory(short.class, pdata.getShape(), pa); return ay.sectionNoReduce(section); } /** * Read linked vector sturcture data * * @param name Variable name, * @param bos data buffer, * @param vinfo variable info, * @return the arraystructure of linked vector data */ public ArrayStructure readLinkedVectorData(String name, ByteBuffer bos, Nidsheader.Vinfo vinfo) throws IOException, InvalidRangeException { int[] pos = vinfo.pos; int[] dlen = vinfo.len; bos.position(0); int size = pos.length; int vlen = 0; for (int i = 0; i < size; i++) { vlen = vlen + dlen[i]; } Structure pdata = (Structure) ncfile.findVariable(name); StructureMembers members = pdata.makeStructureMembers(); // Structure pdata = new Structure(ncfile, null, null,"unlinkedVector" ); short istart; short jstart; short iend; short jend; short sValue = 0; int ii = 0; short[][] sArray = new short[5][vlen]; for (int i = 0; i < size; i++) { bos.position(pos[i]); if (vinfo.code == 9) { sValue = bos.getShort(); } istart = bos.getShort(); jstart = bos.getShort(); for (int j = 0; j < dlen[i]; j++) { iend = bos.getShort(); jend = bos.getShort(); if (vinfo.code == 9) { sArray[0][ii] = sValue; } sArray[1][ii] = istart; sArray[2][ii] = jstart; sArray[3][ii] = iend; sArray[4][ii] = jend; ii++; } } //end of for loop of read data ArrayStructureMA asma = new ArrayStructureMA(members, new int[]{vlen}); Array data; // these are the offsets into the record data = Array.factory(short.class, new int[]{vlen}, sArray[0]); StructureMembers.Member m = members.findMember("sValue"); if (m != null) m.setDataArray(data); data = Array.factory(short.class, new int[]{vlen}, sArray[1]); m = members.findMember("x_start"); m.setDataArray(data); data = Array.factory(short.class, new int[]{vlen}, sArray[2]); m = members.findMember("y_start"); m.setDataArray(data); data = Array.factory(short.class, new int[]{vlen}, sArray[3]); m = members.findMember("x_end"); m.setDataArray(data); data = Array.factory(short.class, new int[]{vlen}, sArray[4]); m = members.findMember("y_end"); m.setDataArray(data); return asma; } /** * Read nested data * * @param name Variable name, * @param memberName Structure mumber name, * @param bos Data buffer, * @param vinfo variable info, * @param section variable section * @return the array of member variable data */ public Array readNestedCircleStructData(String name, String memberName, ByteBuffer bos, Nidsheader.Vinfo vinfo, java.util.List section) throws IOException, InvalidRangeException { Structure pdata = (Structure) ncfile.findVariable(name); ArrayStructure ma = readCircleStructData(name, bos, vinfo); int size = (int) pdata.getSize(); StructureMembers members = ma.getStructureMembers(); StructureMembers.Member m = members.findMember(memberName); short[] pa = new short[size]; for (int i = 0; i < size; i++) { pa[i] = ma.getScalarShort(i, m); } Array ay = Array.factory(short.class, pdata.getShape(), pa); return ay.sectionNoReduce(section); } /** * Read data * * @param name Variable name, * @param bos Data buffer, * @param vinfo variable info, * @return the arraystructure of circle struct data */ public ArrayStructure readCircleStructData(String name, ByteBuffer bos, Nidsheader.Vinfo vinfo) throws IOException, InvalidRangeException { int[] pos = vinfo.pos; int size = pos.length; Structure pdata = (Structure) ncfile.findVariable(name); int recsize = pos[1] - pos[0]; // each record must be all the same size for (int i = 1; i < size; i++) { int r = pos[i] - pos[i - 1]; if (r != recsize) System.out.println(" PROBLEM at " + i + " == " + r); } StructureMembers members = pdata.makeStructureMembers(); members.findMember("x_center").setDataParam(0); members.findMember("y_center").setDataParam(2); members.findMember("radius").setDataParam(4); members.setStructureSize(recsize); return new ArrayStructureBBpos(members, new int[]{size}, bos, pos); } /** * Read data * * @param bos Data buffer, * @param vinfo variable info, * @return the array of tab data */ public Object readTabAlphaNumData(ByteBuffer bos, Nidsheader.Vinfo vinfo) throws IOException, InvalidRangeException { int plen = vinfo.xt; int tablen = vinfo.yt; String[] pdata = new String[plen]; bos.position(0); int llen; int ipage = 0; int icnt = 4; StringBuilder sbuf = new StringBuilder(); while (ipage < plen && (tablen > 128 + icnt)) { llen = bos.getShort(); if (llen == -1) { pdata[ipage] = new String(sbuf); sbuf = new StringBuilder(); ipage++; icnt = icnt + 2; continue; } byte[] b = new byte[llen]; bos.get(b); String sl = new String(b) + "\n"; sbuf.append(sl); icnt = icnt + llen + 2; } return pdata; } /** * Read one scan radar data * * @param bos Data buffer * @param vinfo variable info * @return the data object of scan data */ // all the work is here, so can be called recursively public Object readOneScanData(ByteBuffer bos, Nidsheader.Vinfo vinfo, String vName) throws IOException, InvalidRangeException { int doff = 0; int npixel = vinfo.yt * vinfo.xt; byte[] odata = new byte[vinfo.xt]; byte[] pdata = new byte[npixel]; bos.position(0); for (int radial = 0; radial < vinfo.yt; radial++) { //bos.get(b2, 0, 2); //int test = getInt(b2, 0, 2); int runLen = bos.getShort(); // getInt(vdata, doff, 2 ); doff += 2; if (vinfo.isRadial) { int radialAngle = bos.getShort(); doff += 2; int radialAngleD = bos.getShort(); doff += 2; } byte[] rdata = null; byte[] bdata = null; if(vinfo.xt != runLen) { rdata = new byte[runLen * 2]; bos.get(rdata, 0, runLen * 2); doff += runLen * 2; bdata = readOneBeamData(rdata, runLen, vinfo.xt, vinfo.level); } else { rdata = new byte[runLen]; bos.get(rdata, 0, runLen); doff += runLen ; // sdata = readOneBeamShortData(rdata, runLen, vinfo.xt, vinfo.level); bdata = rdata; } if (vinfo.x0 > 0) { for (int i = 0; i < vinfo.x0; i++) { odata[i] = 0; } } System.arraycopy(bdata, 0, odata, vinfo.x0, bdata.length); // copy into odata System.arraycopy(odata, 0, pdata, vinfo.xt * radial, vinfo.xt); } //end of for loop int offset = 0; if (vName.endsWith("_RAW")) { return pdata; } else if (vName.startsWith("BaseReflectivity")) { int[] levels = vinfo.len; int iscale = vinfo.code; float[] fdata = new float[npixel]; for (int i = 0; i < npixel; i++) { int ival = levels[unsignedByteToInt(pdata[i])]; if (ival > -9997 && ival != -9866 ) fdata[i] = (float) ival / (float) iscale + (float) offset; else fdata[i] = Float.NaN; } return fdata; } else if (vName.startsWith("DigitalHybridReflectivity")) { int[] levels = vinfo.len; int iscale = vinfo.code; float[] fdata = new float[npixel]; for (int i = 0; i < npixel; i++) { int ival = levels[unsignedByteToInt(pdata[i])]; if (ival != levels[0] && ival != levels[1]) fdata[i] = (float) ival / (float) iscale + (float) offset; else fdata[i] = Float.NaN; } return fdata; } else if (vName.startsWith("RadialVelocity")|| vName.startsWith("SpectrumWidth") ) { int[] levels = vinfo.len; int iscale = vinfo.code; float[] fdata = new float[npixel]; for (int i = 0; i < npixel; i++) { int ival = levels[convertunsignedByte2Short(pdata[i])]; if (ival > -9996 && ival != -9866) fdata[i] = (float) ival / (float) iscale + (float) offset; else fdata[i] = Float.NaN; } return fdata; } else if (vName.startsWith("StormMeanVelocity")) { int[] levels = vinfo.len; int iscale = vinfo.code; float[] fdata = new float[npixel]; for (int i = 0; i < npixel; i++) { int ival = levels[pdata[i]]; if (ival > -9996) fdata[i] = (float) ival / (float) iscale + (float) offset; else fdata[i] = Float.NaN; } return fdata; } else if (vName.startsWith("Precip") || vName.startsWith("DigitalPrecip")) { int[] levels = vinfo.len; int iscale = vinfo.code; float[] fdata = new float[npixel]; for (int i = 0; i < npixel; i++) { int ival; if(pdata[i] < 0) ival = -9997; else ival = levels[pdata[i]]; if (ival > -9996) fdata[i] = ((float) ival / (float) iscale + (float) offset); else fdata[i] = Float.NaN; //100 * ival; } return fdata; } /*else if(vName.endsWith( "_Brightness" )){ float ratio = 256.0f/vinfo.level; float [] fdata = new float[npixel]; for ( int i = 0; i < vinfo.yt * vinfo.xt; i++ ) { fdata[i] = pdata[i] * ratio; } return fdata; } else if ( vName.endsWith( "_VIP" )) { int [] levels = vinfo.len; int iscale = vinfo.code; int [] dvip ={ 0, 30, 40, 45, 50, 55 }; float [] fdata = new float[npixel]; for (int i = 0; i < npixel; i++ ) { float dbz = levels[pdata[i]] / iscale + offset; for (int j = 0; j <= 5; j++ ) { if ( dbz > dvip[j] ) fdata[i] = j + 1; } } return fdata; } */ return null; } /** * read one radial beam data * @param ddata * @param rLen * @param xt * @param level * @return one beam data array * @throws IOException * @throws InvalidRangeException */ public byte[] readOneBeamData(byte[] ddata, int rLen, int xt, int level) throws IOException, InvalidRangeException { int run; byte[] bdata = new byte[xt]; int nbin = 0; int total = 0; for (run = 0; run < rLen * 2; run++) { int drun = convertunsignedByte2Short(ddata[run]) >> 4; byte dcode1 = (byte) (convertunsignedByte2Short(ddata[run]) & 0Xf); for (int i = 0; i < drun; i++) { bdata[nbin++] = dcode1; total++; } } if (total < xt) { for (run = total; run < xt; run++) { bdata[run] = 0; } } return bdata; } /** * read one radial beam data * @param ddata * @param rLen * @param xt * @param level * @return one beam data array * @throws IOException * @throws InvalidRangeException */ public short[] readOneBeamShortData(byte[] ddata, int rLen, int xt, int level) throws IOException, InvalidRangeException { int run; short[] sdata = new short[xt]; int total = 0; for (run = 0; run < rLen ; run++) { short dcode1 = convertunsignedByte2Short(ddata[run]); sdata[run] = dcode1; total++; } if (total < xt) { for (run = total; run < xt; run++) { sdata[run] = 0; } } return sdata; } /** * Read nested data * * @param name Variable name, * @param memberName Structure mumber name, * @param bos Data buffer, * @param vinfo variable info, * @param section variable section * @return the array of member variable data */ public Array readNestedWindBarbData(String name, String memberName, ByteBuffer bos, Nidsheader.Vinfo vinfo, java.util.List section) throws IOException, InvalidRangeException { Structure pdata = (Structure) ncfile.findVariable(name); ArrayStructure ma = readWindBarbData(name, bos, vinfo, null); int size = (int) pdata.getSize(); StructureMembers members = ma.getStructureMembers(); StructureMembers.Member m = members.findMember(memberName); short[] pa = new short[size]; for (int i = 0; i < size; i++) { pa[i] = ma.getScalarShort(i, m); } Array ay = Array.factory(short.class, pdata.getShape(), pa); return ay.sectionNoReduce(section); //return asbb; } /** * Read data * * @param name Variable name, * @param bos Data buffer, * @param vinfo variable info, * @return the arraystructure of wind barb data */ public ArrayStructure readWindBarbData(String name, ByteBuffer bos, Nidsheader.Vinfo vinfo, List sList) throws IOException, InvalidRangeException { int[] pos = vinfo.pos; int size = pos.length; Structure pdata = (Structure) ncfile.findVariable(name); int recsize; if (size > 1) { recsize = pos[1] - pos[0]; // each record must be all the same size for (int i = 1; i < size; i++) { int r = pos[i] - pos[i - 1]; if (r != recsize) System.out.println(" PROBLEM at " + i + " == " + r); } } else recsize = 1; StructureMembers members = pdata.makeStructureMembers(); members.findMember("value").setDataParam(0); // these are the offsets into the record members.findMember("x_start").setDataParam(2); members.findMember("y_start").setDataParam(4); members.findMember("direction").setDataParam(6); members.findMember("speed").setDataParam(8); members.setStructureSize(recsize); ArrayStructure ay = new ArrayStructureBBpos(members, new int[]{size}, bos, pos); return (sList != null) ? (ArrayStructure) ay.sectionNoReduce(sList) : ay; // return new ArrayStructureBBpos( members, new int[] { size}, bos, pos); //return asbb; } /** * Read nested data * * @param name Variable name, * @param memberName Structure mumber name, * @param bos Data buffer, * @param vinfo variable info, * @param section variable section * @return the array of member variable data */ public Array readNestedVectorArrowData(String name, String memberName, ByteBuffer bos, Nidsheader.Vinfo vinfo, java.util.List section) throws IOException, InvalidRangeException { Structure pdata = (Structure) ncfile.findVariable(name); ArrayStructure ma = readVectorArrowData(name, bos, vinfo); int size = (int) pdata.getSize(); StructureMembers members = ma.getStructureMembers(); StructureMembers.Member m = members.findMember(memberName); short[] pa = new short[size]; for (int i = 0; i < size; i++) { pa[i] = ma.getScalarShort(i, m); } Array ay = Array.factory(short.class, pdata.getShape(), pa); return ay.sectionNoReduce(section); } /** * Read data * * @param name Variable name, * @param bos Data buffer, * @param vinfo variable info, * @return the arraystructure of vector arrow data */ public ArrayStructure readVectorArrowData(String name, ByteBuffer bos, Nidsheader.Vinfo vinfo) throws IOException, InvalidRangeException { int[] pos = vinfo.pos; int size = pos.length; /* short istart = 0; short jstart = 0; short direction = 0; short arrowvalue = 0; short arrowHeadValue = 0; */ Structure pdata = (Structure) ncfile.findVariable(name); int recsize = pos[1] - pos[0]; // each record must be all the same size for (int i = 1; i < size; i++) { int r = pos[i] - pos[i - 1]; if (r != recsize) System.out.println(" PROBLEM at " + i + " == " + r); } StructureMembers members = pdata.makeStructureMembers(); members.findMember("x_start").setDataParam(0); members.findMember("y_start").setDataParam(2); members.findMember("direction").setDataParam(4); members.findMember("arrowLength").setDataParam(6); members.findMember("arrowHeadLength").setDataParam(8); members.setStructureSize(recsize); return new ArrayStructureBBpos(members, new int[]{size}, bos, pos); /* Structure pdata = new Structure(ncfile, null, null,"vectorArrow" ); Variable ii0 = new Variable(ncfile, null, pdata, "x_start"); ii0.setDimensions((String)null); ii0.setDataType(DataType.SHORT); pdata.addMemberVariable(ii0); Variable ii1 = new Variable(ncfile, null, pdata, "y_start"); ii1.setDimensions((String)null); ii1.setDataType(DataType.SHORT); pdata.addMemberVariable(ii1); Variable direct = new Variable(ncfile, null, pdata, "direction"); direct.setDimensions((String)null); direct.setDataType(DataType.SHORT); pdata.addMemberVariable(direct); Variable speed = new Variable(ncfile, null, pdata, "arrowLength"); speed.setDimensions((String)null); speed.setDataType(DataType.SHORT); pdata.addMemberVariable(speed); Variable v = new Variable(ncfile, null, null, "arrowHeadLength"); v.setDataType(DataType.SHORT); v.setDimensions((String)null); pdata.addMemberVariable(v); StructureMembers members = pdata.makeStructureMembers(); ArrayStructureW asw = new ArrayStructureW(members, new int[] {size}); for (int i=0; i< size; i++) { bos.position( pos[i]); istart = bos.getShort(); jstart = bos.getShort(); direction = bos.getShort(); arrowvalue = bos.getShort(); arrowHeadValue = bos.getShort(); ArrayStructureW.StructureDataW sdata = asw.new StructureDataW(); Iterator memberIter = sdata.getMembers().iterator(); ArrayObject.D0 sArray = new ArrayObject.D0(Short.class); sArray.set(new Short(istart)); sdata.setMemberData( (StructureMembers.Member) memberIter.next(), sArray); sArray = new ArrayObject.D0(Short.class); sArray.set(new Short(jstart)); sdata.setMemberData( (StructureMembers.Member) memberIter.next(), sArray); sArray = new ArrayObject.D0(String.class); sArray.set(new Short(direction)); sdata.setMemberData( (StructureMembers.Member) memberIter.next(), sArray); sArray = new ArrayObject.D0(Short.class); sArray.set(new Short(arrowvalue)); sdata.setMemberData( (StructureMembers.Member) memberIter.next(), sArray); sArray = new ArrayObject.D0(String.class); sArray.set(new Short(arrowHeadValue)); sdata.setMemberData( (StructureMembers.Member) memberIter.next(), sArray); asw.setStructureData(sdata, i); } //end of for loop */ // return asw; } /** * Read nested data * * @param name Variable name, * @param memberName Structure mumber name, * @param bos Data buffer, * @param vinfo variable info, * @param section variable section * @return the array of member variable data */ public Array readNestedTextStringData(String name, String memberName, ByteBuffer bos, Nidsheader.Vinfo vinfo, java.util.List section) throws IOException, InvalidRangeException { Structure pdata = (Structure) ncfile.findVariable(name); ArrayStructure ma = readTextStringData(name, bos, vinfo); int size = (int) pdata.getSize(); StructureMembers members = ma.getStructureMembers(); StructureMembers.Member m = members.findMember(memberName); Array ay; short[] pa = new short[size]; String[] ps = new String[size]; if (m.getName().equalsIgnoreCase("testString")) { for (int i = 0; i < size; i++) { ps[i] = ma.getScalarString(i, m); } ay = Array.factory(String.class, pdata.getShape(), ps); } else { for (int i = 0; i < size; i++) { pa[i] = ma.getScalarShort(i, m); } ay = Array.factory(short.class, pdata.getShape(), pa); } return ay.sectionNoReduce(section); } /** * Read data * * @param name Variable name, * @param bos Data buffer, * @param vinfo variable info * @return the arraystructure of text string data */ public ArrayStructure readTextStringData(String name, ByteBuffer bos, Nidsheader.Vinfo vinfo) throws IOException, InvalidRangeException { int[] pos = vinfo.pos; int[] sizes = vinfo.len; int size = pos.length; Structure pdata = (Structure) ncfile.findVariable(name); StructureMembers members = pdata.makeStructureMembers(); if (vinfo.code == 8) { members.findMember("strValue").setDataParam(0); members.findMember("x_start").setDataParam(2); members.findMember("y_start").setDataParam(4); members.findMember("textString").setDataParam(6); } else { members.findMember("x_start").setDataParam(0); members.findMember("y_start").setDataParam(2); members.findMember("textString").setDataParam(4); } return new MyArrayStructureBBpos(members, new int[]{size}, bos, pos, sizes); //StructureData[] outdata = new StructureData[size]; // Structure pdata = new Structure(ncfile, null, null,"textdata" ); /* short istart = 0; short jstart = 0; short sValue = 0; Variable ii0 = new Variable(ncfile, null, pdata, "x_start"); ii0.setDimensions((String)null); ii0.setDataType(DataType.SHORT); pdata.addMemberVariable(ii0); Variable ii1 = new Variable(ncfile, null, pdata, "y_start"); ii1.setDimensions((String)null); ii1.setDataType(DataType.SHORT); pdata.addMemberVariable(ii1); Variable jj0 = new Variable(ncfile, null, pdata, "textString"); jj0.setDimensions((String)null); jj0.setDataType(DataType.STRING); pdata.addMemberVariable(jj0); if(vinfo.code == 8){ Variable v = new Variable(ncfile, null, null, "strValue"); v.setDataType(DataType.SHORT); v.setDimensions((String)null); pdata.addMemberVariable(v); } StructureMembers members = pdata.makeStructureMembers(); ArrayStructureW asw = new ArrayStructureW(members, new int[] {size}); for (int i=0; i< size; i++) { bos.position( pos[i] - 2); //re read the length of block int strLen = bos.getShort(); if(vinfo.code == 8) { strLen = strLen - 6; sValue = bos.getShort(); } else { strLen = strLen - 4; } byte[] bb = new byte[strLen]; ArrayStructureW.StructureDataW sdata = asw.new StructureDataW(); Iterator memberIter = sdata.getMembers().iterator(); ArrayObject.D0 sArray = new ArrayObject.D0(Short.class); istart = bos.getShort(); jstart = bos.getShort(); bos.get(bb); String tstring = new String(bb); sArray.set(new Short(istart)); sdata.setMemberData( (StructureMembers.Member) memberIter.next(), sArray); sArray = new ArrayObject.D0(Short.class); sArray.set(new Short(jstart)); sdata.setMemberData( (StructureMembers.Member) memberIter.next(), sArray); sArray = new ArrayObject.D0(String.class); sArray.set(new String(tstring)); sdata.setMemberData( (StructureMembers.Member) memberIter.next(), sArray); if(vinfo.code == 8) { sArray = new ArrayObject.D0(Short.class); sArray.set(new Short(sValue)); sdata.setMemberData( (StructureMembers.Member) memberIter.next(), sArray); } asw.setStructureData(sdata, i); } //end of for loop */ //return asw; } private class MyArrayStructureBBpos extends ArrayStructureBBpos { int[] size; MyArrayStructureBBpos(StructureMembers members, int[] shape, ByteBuffer bbuffer, int[] positions, int[] size) { super(members, shape, bbuffer, positions); this.size = size; } /** * convert structure member into a string * @param recnum * @param m * @return */ public String getScalarString(int recnum, StructureMembers.Member m) { if ((m.getDataType() == DataType.CHAR) || (m.getDataType() == DataType.STRING)) { int offset = calcOffsetSetOrder(recnum, m); int count = size[recnum]; byte[] pa = new byte[count]; int i; for (i = 0; i < count; i++) { pa[i] = bbuffer.get(offset + i); if (0 == pa[i]) break; } return new String(pa, 0, i); } throw new IllegalArgumentException("Type is " + m.getDataType() + ", must be String or char"); } } /** * Read nested data * * @param name Variable name, * @param memberName Structure mumber name, * @param bos Data buffer, * @param vinfo variable info, * @param section variable section * @return the array of member variable data */ public Array readNestedDataUnlinkVector(String name, String memberName, ByteBuffer bos, Nidsheader.Vinfo vinfo, java.util.List section) throws java.io.IOException, ucar.ma2.InvalidRangeException { Structure pdata = (Structure) ncfile.findVariable(name); ArrayStructure ma = readUnlinkedVectorData(name, bos, vinfo); int size = (int) pdata.getSize(); StructureMembers members = ma.getStructureMembers(); StructureMembers.Member m = members.findMember(memberName); short[] pa = new short[size]; for (int i = 0; i < size; i++) { pa[i] = ma.getScalarShort(i, m); } Array ay = Array.factory(short.class, pdata.getShape(), pa); return ay.sectionNoReduce(section); } /** * Read data * * @param name Variable name, * @param bos Data buffer, * @param vinfo variable info, * @return the arraystructure of unlinked vector data */ public ArrayStructure readUnlinkedVectorData(String name, ByteBuffer bos, Nidsheader.Vinfo vinfo) throws IOException, InvalidRangeException { int[] pos = vinfo.pos; int[] dlen = vinfo.len; bos.position(0); int size = pos.length; int vlen = 0; for (int i = 0; i < size; i++) { vlen = vlen + dlen[i]; } Structure pdata = (Structure) ncfile.findVariable(name); StructureMembers members = pdata.makeStructureMembers(); // Structure pdata = new Structure(ncfile, null, null,"unlinkedVector" ); short istart; short jstart; short iend; short jend; short vlevel; ArrayStructureMA asma = new ArrayStructureMA(members, new int[]{vlen}); int ii = 0; short[][] sArray = new short[5][vlen]; for (int i = 0; i < size; i++) { bos.position(pos[i]); vlevel = bos.getShort(); for (int j = 0; j < dlen[i]; j++) { istart = bos.getShort(); jstart = bos.getShort(); iend = bos.getShort(); jend = bos.getShort(); sArray[0][ii] = vlevel; sArray[1][ii] = istart; sArray[2][ii] = jstart; sArray[3][ii] = iend; sArray[4][ii] = jend; ii++; } } //end of for loop Array data; // these are the offsets into the record data = Array.factory(short.class, new int[]{vlen}, sArray[0]); StructureMembers.Member m = members.findMember("iValue"); m.setDataArray(data); data = Array.factory(short.class, new int[]{vlen}, sArray[1]); m = members.findMember("x_start"); m.setDataArray(data); data = Array.factory(short.class, new int[]{vlen}, sArray[2]); m = members.findMember("y_start"); m.setDataArray(data); data = Array.factory(short.class, new int[]{vlen}, sArray[3]); m = members.findMember("x_end"); m.setDataArray(data); data = Array.factory(short.class, new int[]{vlen}, sArray[4]); m = members.findMember("y_end"); m.setDataArray(data); return asma; } // all the work is here, so can be called recursively public Object readOneArrayData(ByteBuffer bos, Nidsheader.Vinfo vinfo, String vName) throws IOException, InvalidRangeException { int doff = 0; int offset = 0; //byte[] odata = new byte[ vinfo.xt]; byte[] pdata = new byte[vinfo.yt * vinfo.xt]; byte[] b2 = new byte[2]; int npixel = vinfo.yt * vinfo.xt; //int t = 0; bos.position(0); for (int radial = 0; radial < vinfo.yt; radial++) { bos.get(b2); int runLen = getUInt(b2, 0, 2); //bos.getShort(); // getInt(vdata, doff, 2 ); doff += 2; byte[] rdata = new byte[runLen]; int tmpp = bos.remaining(); bos.get(rdata, 0, runLen); doff += runLen; byte[] bdata = readOneRowData(rdata, runLen, vinfo.xt); // copy into odata System.arraycopy(bdata, 0, pdata, vinfo.xt * radial, vinfo.xt); } //end of for loop if (vName.endsWith("_RAW")) { return pdata; } else if (vName.equals("EchoTop") || vName.equals("VertLiquid") || vName.startsWith("Precip")) { int[] levels = vinfo.len; int iscale = vinfo.code; float[] fdata = new float[npixel]; for (int i = 0; i < npixel; i++) { int ival = levels[pdata[i]]; if (ival > -9996) fdata[i] = (float) ival / (float) iscale + (float) offset; else fdata[i] = Float.NaN; } return fdata; } else if (vName.startsWith("BaseReflectivityComp") || vName.startsWith("LayerCompReflect")) { int[] levels = vinfo.len; int iscale = vinfo.code; float[] fdata = new float[npixel]; for (int i = 0; i < npixel; i++) { int ival = levels[pdata[i]]; if (ival > -9997) fdata[i] = (float) ival / (float) iscale + (float) offset; else fdata[i] = Float.NaN; } return fdata; } return null; } /** * Read data * * @param bos is data buffer * @param vinfo is variable info * @return the data object */ public Object readOneArrayData1(ByteBuffer bos, Nidsheader.Vinfo vinfo) throws IOException, InvalidRangeException { int doff = 0; //byte[] odata = new byte[ vinfo.xt]; byte[] pdata = new byte[vinfo.yt * vinfo.xt]; //byte[] b2 = new byte[2]; //int t = 0; bos.position(0); for (int row = 0; row < vinfo.yt; row++) { int runLen = bos.getShort(); // getInt(vdata, doff, 2 ); doff += 2; byte[] rdata = new byte[runLen]; int tmpp = bos.remaining(); bos.get(rdata, 0, runLen); doff += runLen; byte[] bdata; if (vinfo.code == 17) { bdata = readOneRowData1(rdata, runLen, vinfo.xt); } else { bdata = readOneRowData(rdata, runLen, vinfo.xt); } // copy into odata System.arraycopy(bdata, 0, pdata, vinfo.xt * row, vinfo.xt); } //end of for loop return pdata; } /** * Read data from encoded values and run len into regular data array * * @param ddata is encoded data values * @return the data array of row data */ public byte[] readOneRowData1(byte[] ddata, int rLen, int xt) throws IOException, InvalidRangeException { int run; byte[] bdata = new byte[xt]; int nbin = 0; int total = 0; for (run = 0; run < rLen / 2; run++) { int drun = convertunsignedByte2Short(ddata[run]); run++; byte dcode1 = (byte) (convertunsignedByte2Short(ddata[run])); for (int i = 0; i < drun; i++) { bdata[nbin++] = dcode1; total++; } } if (total < xt) { for (run = total; run < xt; run++) { bdata[run] = 0; } } return bdata; } /** * Read data from encoded values and run len into regular data array * * @param ddata is encoded data values * @return the data array of row data */ public byte[] readOneRowData(byte[] ddata, int rLen, int xt) throws IOException, InvalidRangeException { int run; byte[] bdata = new byte[xt]; int nbin = 0; int total = 0; for (run = 0; run < rLen; run++) { int drun = convertunsignedByte2Short(ddata[run]) >> 4; byte dcode1 = (byte) (convertunsignedByte2Short(ddata[run]) & 0Xf); for (int i = 0; i < drun; i++) { bdata[nbin++] = dcode1; total++; } } if (total < xt) { for (run = total; run < xt; run++) { bdata[run] = 0; } } return bdata; } /** * read radail elevation array * @param bos * @param vinfo * @return data elevation array * @throws IOException * @throws InvalidRangeException */ public Object readRadialDataEle(ByteBuffer bos, Nidsheader.Vinfo vinfo) throws IOException, InvalidRangeException { float[] elvdata = new float[vinfo.yt]; float elvAngle = vinfo.y0 * 0.1f; //Float ra = new Float(elvAngle); for (int radial = 0; radial < vinfo.yt; radial++) { elvdata[radial] = elvAngle; } //end of for loop return elvdata; } /** * read radial data * @param t * @param vinfo * @return data output * @throws IOException * @throws InvalidRangeException */ public Object readRadialDataLatLonAlt(double t, Nidsheader.Vinfo vinfo) throws IOException, InvalidRangeException { float[] vdata = new float[vinfo.yt]; for (int radial = 0; radial < vinfo.yt; radial++) { vdata[radial] = (float) t; } //end of for loop return vdata; } public Object readRadialDataAzi(ByteBuffer bos, Nidsheader.Vinfo vinfo) throws IOException, InvalidRangeException { int doff = 0; float[] azidata = new float[vinfo.yt]; for (int radial = 0; radial < vinfo.yt; radial++) { int runLen = bos.getShort(); // getInt(vdata, doff, 2 ); doff += 2; float radialAngle = (float) bos.getShort() / 10.0f; doff += 2; int radialAngleD = bos.getShort(); doff += 2; if(vinfo.xt != runLen) doff += runLen * 2; else doff += runLen; bos.position(doff); Float ra = new Float(radialAngle); azidata[radial] = ra.floatValue(); } //end of for loop return azidata; } public Object readDistance(Nidsheader.Vinfo vinfo) throws IOException, InvalidRangeException { //int doff = 0; int[] data = new int[vinfo.yt * vinfo.xt]; for (int row = 0; row < vinfo.yt; row++) { for (int col = 0; col < vinfo.xt; col++) { int i = row * vinfo.yt + col; data[i] = col + vinfo.x0; //data[i] = val; } } //end of for loop return data; } public Object readRadialDataGate(Nidsheader.Vinfo vinfo) throws IOException, InvalidRangeException { //int doff = 0; float[] gatedata = new float[vinfo.xt]; double ddg = Nidsheader.code_reslookup(pcode); float sc = vinfo.y0 * 1.0f; for (int rad = 0; rad < vinfo.xt; rad++) { gatedata[rad] = (vinfo.x0 + rad) * sc * (float)ddg; } //end of for loop return gatedata; } // for the compressed data read all out into a array and then parse into requested // This routine reads compressed image data for Level III formatted file. // We referenced McIDAS GetNexrLine function public byte[] readCompData1(byte[] uncomp, long hoff, long doff) throws IOException { int off; byte b1, b2; b1 = uncomp[0]; b2 = uncomp[1]; off = 2 * (((b1 & 63) << 8) + b2); /* eat WMO and PIL */ for (int i = 0; i < 2; i++) { while ((off < uncomp.length) && (uncomp[off] != '\n')) off++; off++; } byte[] data = new byte[(int) (uncomp.length - off - doff)]; //byte[] hedata = new byte[(int)doff]; // System.arraycopy(uncomp, off, hedata, 0, (int)doff); System.arraycopy(uncomp, off + (int) doff, data, 0, uncomp.length - off - (int) doff); return data; } /** * Read compressed data * * @param hoff header offset * @param doff data offset * @return the array of data */ public byte[] readCompData(long hoff, long doff) throws IOException { int numin; /* # input bytes processed */ long pos = 0; long len = myRaf.length(); myRaf.seek(pos); numin = (int) (len - hoff); // Read in the contents of the NEXRAD Level III product header // nids header process byte[] b = new byte[(int) len]; myRaf.readFully(b); /* a new copy of buff with only compressed bytes */ // byte[] comp = new byte[numin - 4]; // System.arraycopy( b, (int)hoff, comp, 0, numin -4 ); // decompress the bytes Inflater inf = new Inflater(false); int resultLength; int result = 0; //byte[] inflateData = null; byte[] tmp; int uncompLen = 24500; /* length of decompress space */ byte[] uncomp = new byte[uncompLen]; inf.setInput(b, (int) hoff, numin - 4); int limit = 20000; while (inf.getRemaining() > 0) { try { resultLength = inf.inflate(uncomp, result, 4000); } catch (DataFormatException ex) { System.out.println("ERROR on inflation " + ex.getMessage()); ex.printStackTrace(); throw new IOException(ex.getMessage()); } result = result + resultLength; if (result > limit) { // when uncomp data larger then limit, the uncomp need to increase size tmp = new byte[result]; System.arraycopy(uncomp, 0, tmp, 0, result); uncompLen = uncompLen + 10000; uncomp = new byte[uncompLen]; System.arraycopy(tmp, 0, uncomp, 0, result); } if (resultLength == 0) { int tt = inf.getRemaining(); byte[] b2 = new byte[2]; System.arraycopy(b, (int) hoff + numin - 4 - tt, b2, 0, 2); if (headerParser.isZlibHed(b2) == 0) { System.arraycopy(b, (int) hoff + numin - 4 - tt, uncomp, result, tt); result = result + tt; break; } inf.reset(); inf.setInput(b, (int) hoff + numin - 4 - tt, tt); } } /* while ( inf.getRemaining() > 0) { try{ resultLength = inf.inflate(uncomp); } catch (DataFormatException ex) { System.out.println("ERROR on inflation"); ex.printStackTrace(); } if(resultLength > 0 ) { result = result + resultLength; inflateData = new byte[result]; if(tmp != null) { System.arraycopy(tmp, 0, inflateData, 0, tmp.length); System.arraycopy(uncomp, 0, inflateData, tmp.length, resultLength); } else { System.arraycopy(uncomp, 0, inflateData, 0, resultLength); } tmp = new byte[result]; System.arraycopy(inflateData, 0, tmp, 0, result); uncomp = new byte[(int)uncompLen]; } else { int tt = inf.getRemaining(); byte [] b2 = new byte[2]; System.arraycopy(b,(int)hoff+numin-4-tt, b2, 0, 2); if( headerParser.isZlibHed( b2 ) == 0 ) { result = result + tt; inflateData = new byte[result]; System.arraycopy(tmp, 0, inflateData, 0, tmp.length); System.arraycopy(b, (int)hoff+numin-4-tt, inflateData, tmp.length, tt); break; } inf.reset(); inf.setInput(b, (int)hoff+numin-4-tt, tt); } } */ inf.end(); int off; byte b1, b2; b1 = uncomp[0]; b2 = uncomp[1]; off = 2 * (((b1 & 63) << 8) + b2); /* eat WMO and PIL */ for (int i = 0; i < 2; i++) { while ((off < result) && (uncomp[off] != '\n')) off++; off++; } byte[] data = new byte[(int) (result - off - doff)]; //byte[] hedata = new byte[(int)doff]; // System.arraycopy(uncomp, off, hedata, 0, (int)doff); System.arraycopy(uncomp, off + (int) doff, data, 0, result - off - (int) doff); return data; } /** * Read uncompressed data * * @param hoff header offset * @param doff data offset * @return the array of data */ public byte[] readUCompData(long hoff, long doff) throws IOException { int numin; long pos = 0; long len = myRaf.length(); myRaf.seek(pos); numin = (int) (len - hoff); // Read in the contents of the NEXRAD Level III product header // nids header process byte[] b = new byte[(int) len]; myRaf.readFully(b); /* a new copy of buff with only compressed bytes */ byte[] ucomp = new byte[numin - 4]; System.arraycopy(b, (int) hoff, ucomp, 0, numin - 4); byte[] data = new byte[(int) (ucomp.length - doff)]; System.arraycopy(ucomp, (int) doff, data, 0, ucomp.length - (int) doff); return data; } /* ** Name: IsZlibed ** ** Purpose: Check a two-byte sequence to see if it indicates the start of ** a zlib-compressed buffer ** ** Parameters: ** buf - buffer containing at least two bytes ** ** Returns: ** SUCCESS 1 ** FAILURE 0 ** */ int issZlibed(byte[] buf) { if ((buf[0] & 0xf) == Z_DEFLATED) { if ((buf[0] >> 4) + 8 <= DEF_WBITS) { if ((((buf[0] << 8) + (buf[1])) % 31) == 0) { return 1; } } } return 0; } int getUInt(byte[] b, int offset, int num) { int base = 1; int i; int word = 0; int bv[] = new int[num]; for (i = 0; i < num; i++) { bv[i] = convertunsignedByte2Short(b[offset + i]); } /* ** Calculate the integer value of the byte sequence */ for (i = num - 1; i >= 0; i word += base * bv[i]; base *= 256; } return word; } int getInt(byte[] b, int offset, int num) { int base = 1; int i; int word = 0; int bv[] = new int[num]; for (i = 0; i < num; i++) { bv[i] = convertunsignedByte2Short(b[offset + i]); } if (bv[0] > 127) { bv[0] -= 128; base = -1; } /* ** Calculate the integer value of the byte sequence */ for (i = num - 1; i >= 0; i word += base * bv[i]; base *= 256; } return word; } public short convertunsignedByte2Short(byte b) { return (short) ((b < 0) ? (short) b + 256 : (short) b); } public static int unsignedByteToInt(byte b) { return (int) b & 0xFF; } protected boolean fill; protected HashMap dimHash = new HashMap(50); public void flush() throws java.io.IOException { myRaf.flush(); } public void close() throws java.io.IOException { myRaf.close(); } public static void main(String args[]) throws Exception, IOException, InstantiationException, IllegalAccessException { String fileIn = "/home/yuanho/NIDS/N0R_20041102_2111"; //String fileIn = "c:/data/image/Nids/n0r_20041013_1852"; ucar.nc2.NetcdfFile.registerIOProvider(ucar.nc2.iosp.nids.Nidsiosp.class); ucar.nc2.NetcdfFile ncf = ucar.nc2.NetcdfFile.open(fileIn); //List alist = ncf.getGlobalAttributes(); ucar.nc2.Variable v = ncf.findVariable("BaseReflectivity"); int[] origin = {0, 0}; int[] shape = {300, 36}; ArrayByte data = (ArrayByte) v.read(origin, shape); ncf.close(); } }
package org.bitrepository.integrityclient; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.Properties; import org.bitrepository.common.settings.Settings; import org.bitrepository.common.settings.SettingsProvider; import org.bitrepository.common.settings.XMLFileSettingsLoader; import org.bitrepository.protocol.security.BasicMessageAuthenticator; import org.bitrepository.protocol.security.BasicMessageSigner; import org.bitrepository.protocol.security.BasicOperationAuthorizor; import org.bitrepository.protocol.security.BasicSecurityManager; import org.bitrepository.protocol.security.MessageAuthenticator; import org.bitrepository.protocol.security.MessageSigner; import org.bitrepository.protocol.security.OperationAuthorizor; import org.bitrepository.protocol.security.PermissionStore; import org.bitrepository.protocol.security.SecurityManager; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class IntegrityServiceFactory { private Logger log = LoggerFactory.getLogger(IntegrityServiceFactory.class); private static String confDir; private static IntegrityService integrityService; private static String privateKeyFile; private static MessageAuthenticator authenticator; private static MessageSigner signer; private static OperationAuthorizor authorizer; private static PermissionStore permissionStore; private static SecurityManager securityManager; /** Default collection settings identifier (used to build the path the collection and referencesettings */ private static final String DEFAULT_COLLECTION_ID = "bitrepository-devel"; /** The properties file holding implementation specifics for the alarm service. */ private static final String CONFIGFILE = "integrity.properties"; /** Property key to tell where to locate the path and filename to the private key file. */ private static final String PRIVATE_KEY_FILE = "org.bitrepository.integrity-service.privateKeyFile"; /** The time of one week.*/ private static final long DEFAULT_MAX_TIME_SINCE_UPDATE = 604800000; /** * Private constructor, use static getInstance method to get instance. */ private IntegrityServiceFactory() { //Empty constructor } /** * Set the configuration directory. * Should only be run at initialization time. */ public synchronized static void init(String configurationDir) { confDir = configurationDir; } /** * Factory method to get a singleton instance of BasicClient * @return The BasicClient instance or a null in case of trouble. */ public synchronized static IntegrityService getIntegrityService() { if(integrityService == null) { if(confDir == null) { throw new RuntimeException("No configuration dir has been set!"); } SettingsProvider settingsLoader = new SettingsProvider(new XMLFileSettingsLoader(confDir)); Settings settings = settingsLoader.getSettings(DEFAULT_COLLECTION_ID); long timeSinceLastChecksumUpdate = DEFAULT_MAX_TIME_SINCE_UPDATE; long timeSinceLastFileIDsUpdate = DEFAULT_MAX_TIME_SINCE_UPDATE; try { loadProperties(); permissionStore = new PermissionStore(); authenticator = new BasicMessageAuthenticator(permissionStore); signer = new BasicMessageSigner(); authorizer = new BasicOperationAuthorizor(permissionStore); securityManager = new BasicSecurityManager(settings.getCollectionSettings(), privateKeyFile, authenticator, signer, authorizer, permissionStore); SimpleIntegrityService simpleIntegrityService = new SimpleIntegrityService(settings, securityManager); integrityService = new IntegrityService(simpleIntegrityService, settings); simpleIntegrityService.startChecksumIntegrityCheck(timeSinceLastChecksumUpdate, settings.getReferenceSettings().getIntegrityServiceSettings().getSchedulerInterval()); for(String pillarId : settings.getCollectionSettings().getClientSettings().getPillarIDs()) { simpleIntegrityService.startAllFileIDsIntegrityCheckFromPillar(pillarId, timeSinceLastFileIDsUpdate); } } catch (Exception e) { throw new RuntimeException(e); } } return integrityService; } private static void loadProperties() throws IOException { Properties properties = new Properties(); String propertiesFile = confDir + "/" + CONFIGFILE; BufferedReader propertiesReader = new BufferedReader(new FileReader(propertiesFile)); properties.load(propertiesReader); privateKeyFile = properties.getProperty(PRIVATE_KEY_FILE); } }
package ilg.gnumcueclipse.debug.gdbjtag.datamodel; import java.math.BigInteger; import java.util.LinkedList; import java.util.List; import ilg.gnumcueclipse.packs.core.tree.Leaf; import ilg.gnumcueclipse.packs.core.tree.Node; /** * As per SVD 1.1, <i>"A cluster describes a sequence of registers within a * peripheral. A cluster has an base offset relative to the base address of the * peripheral. All registers within a cluster specify their address offset * relative to the cluster base address. Register and cluster sections can occur * in an arbitrary order."</i> */ public class SvdClusterDMNode extends SvdDMNode { public SvdClusterDMNode(Leaf node) { super(node); } @Override public void dispose() { super.dispose(); } @Override protected SvdObjectDMNode[] prepareChildren(Leaf node) { if (node == null || !node.hasChildren()) { return null; } // System.out.println("prepareChildren(" + node.getName() + List<SvdObjectDMNode> list = new LinkedList<SvdObjectDMNode>(); for (Leaf child : ((Node) node).getChildren()) { // Keep only <register> and <cluster> nodes if (child.isType("register")) { list.add(new SvdRegisterDMNode(child)); } else if (child.isType("cluster")) { list.add(new SvdClusterDMNode(child)); } } if (getNode().getPackType() == Node.PACK_TYPE_XPACK) { Leaf group = ((Node) node).findChild("registers"); if (group != null && group.hasChildren()) { for (Leaf child : ((Node) group).getChildren()) { // Keep only <register> and <cluster> nodes if (child.isType("register")) { list.add(new SvdRegisterDMNode(child)); } else if (child.isType("cluster")) { list.add(new SvdClusterDMNode(child)); } } } Leaf clusters = ((Node) node).findChild("clusters"); if (clusters != null && clusters.hasChildren()) { for (Leaf child : ((Node) clusters).getChildren()) { if (child.isType("cluster")) { list.add(new SvdClusterDMNode(child)); } } } } SvdObjectDMNode[] array = list.toArray(new SvdObjectDMNode[list.size()]); // Preserve apparition order. return array; } @Override public BigInteger getBigAddressOffset() { String str = getNode().getProperty("addressOffset"); if (!str.isEmpty()) { return SvdUtils.parseScaledNonNegativeBigInteger(str); } else { return BigInteger.ZERO; } } @Override public BigInteger getBigRepeatIncrement() { BigInteger bigRepeatIncrement = getBigArrayAddressIncrement(); if (bigRepeatIncrement != BigInteger.ZERO) { return bigRepeatIncrement; } return null; } }
package org.openhab.model.core.internal; import java.io.IOException; import java.io.InputStream; import java.util.Collections; import java.util.HashMap; import java.util.Map; import org.eclipse.core.runtime.ListenerList; 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.xtext.resource.SynchronizedXtextResourceSet; import org.eclipse.xtext.resource.XtextResource; import org.eclipse.xtext.resource.XtextResourceSet; import org.openhab.model.core.EventType; import org.openhab.model.core.ModelRepository; import org.openhab.model.core.ModelRepositoryChangeListener; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.base.Function; import com.google.common.base.Predicate; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; public class ModelRepositoryImpl implements ModelRepository { private static final Logger logger = LoggerFactory.getLogger(ModelRepositoryImpl.class); private final ResourceSet resourceSet; private final ListenerList listeners = new ListenerList(); public ModelRepositoryImpl() { XtextResourceSet xtextResourceSet = new SynchronizedXtextResourceSet(); xtextResourceSet.addLoadOption(XtextResource.OPTION_RESOLVE_ALL, Boolean.TRUE); this.resourceSet = xtextResourceSet; // don't use XMI as a default Resource.Factory.Registry.INSTANCE.getExtensionToFactoryMap().remove("*"); } public EObject getModel(String name) { Resource resource = getResource(name); if(resource!=null) { if(resource.getContents().size()>0) { return resource.getContents().get(0); } else { logger.warn("Configuration model '{}' is either empty or cannot be parsed correctly!", name); resourceSet.getResources().remove(resource); return null; } } else { logger.warn("Configuration model '{}' can not be found", name); return null; } } public boolean addOrRefreshModel(String name, InputStream inputStream) { Resource resource = getResource(name); if(resource==null) { synchronized(resourceSet) { resource = getResource(name); if(resource==null) { // seems to be a new file resource = resourceSet.createResource(URI.createURI(name)); if(resource!=null) { try { Map<String, String> options = new HashMap<String, String>(); options.put(XtextResource.OPTION_ENCODING, "UTF-8"); resource.load(inputStream, options); notifyListeners(name, EventType.ADDED); return true; } catch (IOException e) { logger.warn("Configuration model '" + name + "' cannot be parsed correctly!", e); resourceSet.getResources().remove(resource); } } } } } else { synchronized(resourceSet) { resource.unload(); try { resource.load(inputStream, Collections.EMPTY_MAP); notifyListeners(name, EventType.MODIFIED); return true; } catch (IOException e) { logger.warn("Configuration model '" + name + "' cannot be parsed correctly!", e); resourceSet.getResources().remove(resource); } } } return false; } public boolean removeModel(String name) { Resource resource = getResource(name); if(resource!=null) { synchronized(resourceSet) { // do not physically delete it, but remove it from the resource set resourceSet.getResources().remove(resource); notifyListeners(name, EventType.REMOVED); return true; } } else { return false; } } public Iterable<String> getAllModelNamesOfType(final String modelType) { synchronized(resourceSet) { Iterable<Resource> matchingResources = Iterables.filter(resourceSet.getResources(), new Predicate<Resource>() { public boolean apply(Resource input) { if(input!=null && input.getURI().lastSegment().contains(".") && input.isLoaded()) { return modelType.equalsIgnoreCase(input.getURI().fileExtension()); } else { return false; } }}); return Lists.newArrayList(Iterables.transform(matchingResources, new Function<Resource, String>() { public String apply(Resource from) { return from.getURI().path(); }})); } } public void addModelRepositoryChangeListener( ModelRepositoryChangeListener listener) { listeners.add(listener); } public void removeModelRepositoryChangeListener( ModelRepositoryChangeListener listener) { listeners.remove(listener); } private Resource getResource(String name) { return resourceSet.getResource(URI.createURI(name), false); } private void notifyListeners(String name, EventType type) { for(Object listener : listeners.getListeners()) { ModelRepositoryChangeListener changeListener = (ModelRepositoryChangeListener) listener; changeListener.modelChanged(name, type); } } }
package org.eclipse.birt.chart.reportitem; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.eclipse.birt.chart.log.ILogger; import org.eclipse.birt.chart.log.Logger; import org.eclipse.birt.chart.model.Chart; import org.eclipse.birt.chart.model.ChartWithAxes; import org.eclipse.birt.chart.model.ChartWithoutAxes; import org.eclipse.birt.chart.model.attribute.DataType; import org.eclipse.birt.chart.model.attribute.GroupingUnitType; import org.eclipse.birt.chart.model.component.Axis; import org.eclipse.birt.chart.model.data.Query; import org.eclipse.birt.chart.model.data.SeriesDefinition; import org.eclipse.birt.chart.model.data.SeriesGrouping; import org.eclipse.birt.chart.reportitem.i18n.Messages; import org.eclipse.birt.core.data.ExpressionUtil; import org.eclipse.birt.core.exception.BirtException; import org.eclipse.birt.data.engine.api.IBaseExpression; import org.eclipse.birt.data.engine.api.IBaseQueryDefinition; import org.eclipse.birt.data.engine.api.IBinding; import org.eclipse.birt.data.engine.api.IDataQueryDefinition; import org.eclipse.birt.data.engine.api.IFilterDefinition; import org.eclipse.birt.data.engine.api.IInputParameterBinding; import org.eclipse.birt.data.engine.api.querydefn.BaseQueryDefinition; import org.eclipse.birt.data.engine.api.querydefn.Binding; import org.eclipse.birt.data.engine.api.querydefn.ConditionalExpression; import org.eclipse.birt.data.engine.api.querydefn.FilterDefinition; import org.eclipse.birt.data.engine.api.querydefn.GroupDefinition; import org.eclipse.birt.data.engine.api.querydefn.InputParameterBinding; import org.eclipse.birt.data.engine.api.querydefn.QueryDefinition; import org.eclipse.birt.data.engine.api.querydefn.ScriptExpression; import org.eclipse.birt.data.engine.api.querydefn.SortDefinition; import org.eclipse.birt.data.engine.api.querydefn.SubqueryDefinition; import org.eclipse.birt.data.engine.core.DataException; import org.eclipse.birt.data.engine.olap.api.query.ICubeQueryDefinition; import org.eclipse.birt.report.engine.adapter.ModelDteApiAdapter; import org.eclipse.birt.report.engine.api.EngineException; import org.eclipse.birt.report.engine.extension.ReportItemQueryBase; import org.eclipse.birt.report.engine.i18n.MessageConstants; import org.eclipse.birt.report.model.api.AggregationArgumentHandle; import org.eclipse.birt.report.model.api.ComputedColumnHandle; import org.eclipse.birt.report.model.api.DataSetHandle; import org.eclipse.birt.report.model.api.ExtendedItemHandle; import org.eclipse.birt.report.model.api.FilterConditionHandle; import org.eclipse.birt.report.model.api.ModuleUtil; import org.eclipse.birt.report.model.api.ParamBindingHandle; import org.eclipse.birt.report.model.api.ReportItemHandle; import org.eclipse.birt.report.model.api.StructureFactory; import org.eclipse.birt.report.model.api.activity.SemanticException; import org.eclipse.birt.report.model.api.elements.DesignChoiceConstants; import org.eclipse.birt.report.model.api.elements.structures.ComputedColumn; import org.eclipse.birt.report.model.api.extension.ExtendedElementException; import org.eclipse.birt.report.model.api.extension.IReportItem; import org.eclipse.emf.common.util.EList; /** * Customized query implementation for Chart. */ public final class ChartReportItemQueryImpl extends ReportItemQueryBase { private Chart cm = null; private ExtendedItemHandle eih = null; private static ILogger logger = Logger.getLogger( "org.eclipse.birt.chart.reportitem/trace" ); //$NON-NLS-1$ /* * (non-Javadoc) * * @see org.eclipse.birt.report.engine.extension.IReportItemQuery#setModelObject(org.eclipse.birt.report.model.api.ExtendedItemHandle) */ public void setModelObject( ExtendedItemHandle eih ) { IReportItem item; try { item = eih.getReportItem( ); if ( item == null ) { try { eih.loadExtendedElement( ); } catch ( ExtendedElementException eeex ) { logger.log( eeex ); } item = eih.getReportItem( ); if ( item == null ) { logger.log( ILogger.ERROR, Messages.getString( "ChartReportItemQueryImpl.log.UnableToLocate" ) ); //$NON-NLS-1$ return; } } } catch ( ExtendedElementException e ) { logger.log( ILogger.ERROR, Messages.getString( "ChartReportItemQueryImpl.log.UnableToLocate" ) ); //$NON-NLS-1$ return; } cm = (Chart) ( (ChartReportItemImpl) item ).getProperty( "chart.instance" ); //$NON-NLS-1$ this.eih = eih; } public IDataQueryDefinition[] createReportQueries( IDataQueryDefinition parent ) throws BirtException { logger.log( ILogger.INFORMATION, Messages.getString( "ChartReportItemQueryImpl.log.getReportQueries.start" ) ); //$NON-NLS-1$ IDataQueryDefinition idqd = createQuery( eih, parent ); logger.log( ILogger.INFORMATION, Messages.getString( "ChartReportItemQueryImpl.log.getReportQueries.end" ) ); //$NON-NLS-1$ return new IDataQueryDefinition[]{ idqd }; } IDataQueryDefinition createQuery( ExtendedItemHandle handle, IDataQueryDefinition parent ) throws BirtException { if ( handle.getDataSet( ) != null || parent instanceof IBaseQueryDefinition ) { return createBaseQuery( handle, parent ); } else if ( handle.getCube( ) != null || parent instanceof ICubeQueryDefinition ) { return ChartCubeQueryHelper.createCubeQuery( handle, cm, parent ); } return null; } IDataQueryDefinition createBaseQuery( ExtendedItemHandle handle, IDataQueryDefinition parent ) { BaseQueryDefinition parentQuery = null; if ( parent instanceof BaseQueryDefinition ) { parentQuery = (BaseQueryDefinition) parent; } DataSetHandle dsHandle = handle.getDataSet( ); if ( dsHandle == null ) { // dataset reference error String dsName = (String) handle.getProperty( ReportItemHandle.DATA_SET_PROP ); if ( dsName != null && dsName.length( ) > 0 ) { logger.log( new EngineException( MessageConstants.UNDEFINED_DATASET_ERROR, dsName ) ); } // we has data set name defined, so test if we have column // binding here. if ( parent instanceof ICubeQueryDefinition ) { return null; // return createSubQuery(item, null); } if ( ChartReportItemUtil.canScaleShared( handle, cm ) ) { // Add min/max binding to parent query since it's global min/max addMinMaxBinding( ChartReportItemUtil.getBindingHolder( handle ), parentQuery ); } // we have column binding, create a sub query. return createSubQuery( handle, parentQuery ); } // The report item has a data set definition, must create a query for QueryDefinition query = new QueryDefinition( parentQuery ); query.setDataSetName( dsHandle.getQualifiedName( ) ); // bind the query with parameters query.getInputParamBindings( ) .addAll( createParamBindings( handle.paramBindingsIterator( ) ) ); Iterator iter = handle.columnBindingsIterator( ); while ( iter.hasNext( ) ) { ComputedColumnHandle binding = (ComputedColumnHandle) iter.next( ); addColumBinding( query, binding ); } addSortAndFilter( handle, query ); try { new ChartBaseQueryHelper( cm, handle, query ).generateGroupBindings( ); } catch ( DataException e ) { logger.log( e ); } return query; } private void addMinMaxBinding( ReportItemHandle handle, BaseQueryDefinition query ) { // Add min/max bindings for the query expression in first value // series, so share the scale later try { String queryExp = getExpressionOfValueSeries( ); ComputedColumn ccMin = StructureFactory.newComputedColumn( handle, ChartReportItemUtil.QUERY_MIN ); ccMin.setAggregateFunction( DesignChoiceConstants.AGGREGATION_FUNCTION_MIN ); ccMin.setExpression( queryExp ); addColumBinding( query, handle.addColumnBinding( ccMin, false ) ); ComputedColumn ccMax = StructureFactory.newComputedColumn( handle, ChartReportItemUtil.QUERY_MAX ); ccMax.setAggregateFunction( DesignChoiceConstants.AGGREGATION_FUNCTION_MAX ); ccMax.setExpression( queryExp ); addColumBinding( query, handle.addColumnBinding( ccMax, false ) ); } catch ( SemanticException e ) { logger.log( e ); } } private String getExpressionOfValueSeries( ) { SeriesDefinition ySd; if ( cm instanceof ChartWithAxes ) { Axis yAxis = (Axis) ( (Axis) ( (ChartWithAxes) cm ).getAxes( ) .get( 0 ) ).getAssociatedAxes( ).get( 0 ); ySd = (SeriesDefinition) yAxis.getSeriesDefinitions( ).get( 0 ); } else { ySd = (SeriesDefinition) ( (SeriesDefinition) ( (ChartWithoutAxes) cm ).getSeriesDefinitions( ) .get( 0 ) ).getSeriesDefinitions( ).get( 0 ); } Query query = (Query) ySd.getDesignTimeSeries( ) .getDataDefinition( ) .get( 0 ); return query.getDefinition( ); } protected BaseQueryDefinition createSubQuery( ExtendedItemHandle handle, BaseQueryDefinition parentQuery ) { BaseQueryDefinition query = null; // sub query must be defined in a transform if ( parentQuery == null ) { // no parent query exits, so create a empty query for it. query = new QueryDefinition( null ); } else { // create a sub query query = new SubqueryDefinition( "chart_subquery", parentQuery ); //$NON-NLS-1$ parentQuery.getSubqueries( ).add( query ); } Iterator iter = handle.columnBindingsIterator( ); while ( iter.hasNext( ) ) { ComputedColumnHandle binding = (ComputedColumnHandle) iter.next( ); addColumBinding( query, binding ); } addSortAndFilter( handle, query ); return query; } private void addSortAndFilter( ExtendedItemHandle handle, BaseQueryDefinition query ) { query.getFilters( ).addAll( createFilters( handle.filtersIterator( ) ) ); } /** * create a filter array given a filter condition handle iterator * * @param iter * the iterator * @return filter array */ private ArrayList createFilters( Iterator iter ) { ArrayList filters = new ArrayList( ); if ( iter != null ) { while ( iter.hasNext( ) ) { FilterConditionHandle filterHandle = (FilterConditionHandle) iter.next( ); IFilterDefinition filter = createFilter( filterHandle ); filters.add( filter ); } } return filters; } /** * create one Filter given a filter condition handle * * @param handle * a filter condition handle * @return the filter */ private IFilterDefinition createFilter( FilterConditionHandle handle ) { String filterExpr = handle.getExpr( ); if ( filterExpr == null || filterExpr.length( ) == 0 ) return null; // no filter defined // converts to DtE exprFilter if there is no operator String filterOpr = handle.getOperator( ); if ( filterOpr == null || filterOpr.length( ) == 0 ) return new FilterDefinition( new ScriptExpression( filterExpr ) ); /* * has operator defined, try to convert filter condition to * operator/operand style column filter with 0 to 2 operands */ String column = filterExpr; int dteOpr = ModelDteApiAdapter.toDteFilterOperator( filterOpr ); if ( ModuleUtil.isListFilterValue( handle ) ) { List operand1List = handle.getValue1List( ); return new FilterDefinition( new ConditionalExpression( column, dteOpr, operand1List ) ); } String operand1 = handle.getValue1( ); String operand2 = handle.getValue2( ); return new FilterDefinition( new ConditionalExpression( column, dteOpr, operand1, operand2 ) ); } protected void addColumBinding( IBaseQueryDefinition transfer, ComputedColumnHandle columnBinding ) { String name = columnBinding.getName( ); String expr = columnBinding.getExpression( ); String type = columnBinding.getDataType( ); int dbType = ModelDteApiAdapter.toDteDataType( type ); IBaseExpression dbExpr = new ScriptExpression( expr, dbType ); if ( columnBinding.getAggregateOn( ) != null ) { dbExpr.setGroupName( columnBinding.getAggregateOn( ) ); } IBinding binding = new Binding( name, dbExpr ); try { if ( columnBinding.getAggregateOn( ) != null ) binding.addAggregateOn( columnBinding.getAggregateOn( ) ); if ( columnBinding.getAggregateFunction( ) != null ) { binding.setAggrFunction( columnBinding.getAggregateFunction( ) ); } String filter = columnBinding.getFilterExpression( ); if ( filter != null ) { binding.setFilter( new ScriptExpression( filter ) ); } Iterator arguments = columnBinding.argumentsIterator( ); if ( arguments != null ) { while ( arguments.hasNext( ) ) { AggregationArgumentHandle argumentHandle = (AggregationArgumentHandle) arguments.next( ); String argument = argumentHandle.getValue( ); if ( argument != null ) { binding.addArgument( new ScriptExpression( argument ) ); } } } transfer.addBinding( binding ); } catch ( DataException ex ) { logger.log( ex ); } } /** * create input parameter bindings * * @param iter * parameter bindings iterator * @return a list of input parameter bindings */ protected List createParamBindings( Iterator iter ) { ArrayList list = new ArrayList( ); if ( iter != null ) { while ( iter.hasNext( ) ) { ParamBindingHandle modelParamBinding = (ParamBindingHandle) iter.next( ); IInputParameterBinding binding = createParamBinding( modelParamBinding ); if ( binding != null ) { list.add( binding ); } } } return list; } /** * create input parameter binding * * @param handle * @return */ protected IInputParameterBinding createParamBinding( ParamBindingHandle handle ) { if ( handle.getExpression( ) == null ) return null; // no expression is bound ScriptExpression expr = new ScriptExpression( handle.getExpression( ) ); // model provides binding by name only return new InputParameterBinding( handle.getParamName( ), expr ); } /** * Get valid sort expression from series definition. * * @param sd * @return */ private String getValidSortExpr( SeriesDefinition sd ) { if ( !sd.isSetSorting( ) ) { return null; } String sortExpr = null; if ( sd.getSortKey( ) != null && sd.getSortKey( ).getDefinition( ) != null ) { sortExpr = sd.getSortKey( ).getDefinition( ); } else { sortExpr = ( (Query) sd.getDesignTimeSeries( ) .getDataDefinition( ) .get( 0 ) ).getDefinition( ); } if ( "".equals( sortExpr ) ) //$NON-NLS-1$ { sortExpr = null; } return sortExpr; } /** * The class is responsible to add group bindings of chart on query * definition. * * @since BIRT 2.3 */ class ChartBaseQueryHelper { /** The handle of report item handle. */ private ExtendedItemHandle fReportItemHandle; /** * The handle of <code>QueryDefinition</code> which is the container * to contains created group bindings. */ private QueryDefinition fQueryDefinition; /** Current chart handle. */ private Chart fChart; /** * Constructor of the class. * * @param chart * @param handle * @param query */ public ChartBaseQueryHelper( Chart chart, ExtendedItemHandle handle, QueryDefinition query ) { fChart = chart; fReportItemHandle = handle; fQueryDefinition = query; } /** * Generate grouping bindings and add into query definition. * * @throws DataException */ private void generateGroupBindings( ) throws DataException { // 1. Get first base and orthogonal series definition to get // grouping definition. SeriesDefinition baseSD = null; SeriesDefinition orthSD = null; Object[] orthAxisArray = null; if ( fChart instanceof ChartWithAxes ) { ChartWithAxes cwa = (ChartWithAxes) fChart; baseSD = (SeriesDefinition) cwa.getBaseAxes( )[0].getSeriesDefinitions( ) .get( 0 ); orthAxisArray = cwa.getOrthogonalAxes( cwa.getBaseAxes( )[0], true ); orthSD = (SeriesDefinition) ( (Axis) orthAxisArray[0] ).getSeriesDefinitions( ) .get( 0 ); } else if ( fChart instanceof ChartWithoutAxes ) { ChartWithoutAxes cwoa = (ChartWithoutAxes) fChart; baseSD = (SeriesDefinition) cwoa.getSeriesDefinitions( ) .get( 0 ); orthSD = (SeriesDefinition) baseSD.getSeriesDefinitions( ) .get( 0 ); } // 2. Add grouping. // 2.1 Add Y optional grouping. GroupDefinition yGroupingDefinition = createOrthogonalGroupingDefinition( orthSD ); if ( yGroupingDefinition != null ) { fQueryDefinition.addGroup( yGroupingDefinition ); // If the SortKey of Y grouping isn't Y grouping expression, add // new // sort definition on the group. // If base grouping is set, the value series should be // aggregate. if ( ChartReportItemUtil.isBaseGroupingDefined( baseSD ) && orthSD.isSetSorting( ) && orthSD.getSortKey( ) != null ) { String sortKey = orthSD.getSortKey( ).getDefinition( ); String yGroupingExpr = orthSD.getQuery( ).getDefinition( ); // Add additional sort on the grouping. if ( sortKey != null && !yGroupingExpr.equals( sortKey ) ) { // If the SortKey does't equal Y grouping expression, we // must create new sort definition and calculate // aggregate on the grouping and sort by the SortKey. String name = StructureFactory.newComputedColumn( fReportItemHandle, sortKey.replaceAll( "\"", "" ) ) //$NON-NLS-1$ //$NON-NLS-2$ .getName( ); Binding binding = new Binding( name ); fQueryDefinition.addBinding( binding ); binding.setExpression( new ScriptExpression( sortKey ) ); binding.setDataType( org.eclipse.birt.core.data.DataType.ANY_TYPE ); binding.addAggregateOn( yGroupingDefinition.getName( ) ); String aggFunc = getAggFunExpr( sortKey, baseSD, orthAxisArray ); binding.setAggrFunction( ChartReportItemUtil.convertToDtEAggFunction( aggFunc ) ); SortDefinition sortDefinition = new SortDefinition( ); sortDefinition.setColumn( binding.getBindingName( ) ); sortDefinition.setExpression( ExpressionUtil.createRowExpression( binding.getBindingName( ) ) ); sortDefinition.setSortDirection( ChartReportItemUtil.convertToDtESortDirection( orthSD.getSorting( ) ) ); yGroupingDefinition.addSort( sortDefinition ); } } } // 2.2 Add base grouping. GroupDefinition baseGroupDefinition = createBaseGroupingDefinition( baseSD ); if ( baseGroupDefinition != null ) { fQueryDefinition.addGroup( baseGroupDefinition ); } // 3. Add binding for value series aggregate. GroupDefinition innerGroupDef = null; if ( fQueryDefinition.getGroups( ) != null && fQueryDefinition.getGroups( ).size( ) > 0 ) { innerGroupDef = (GroupDefinition) fQueryDefinition.getGroups( ) .get( fQueryDefinition.getGroups( ).size( ) - 1 ); } Map valueExprMap = new HashMap( ); // If it has base grouping, the value series should be aggregate. if ( ChartReportItemUtil.isBaseGroupingDefined( baseSD ) ) { if ( fChart instanceof ChartWithAxes ) { for ( int i = 0; i < orthAxisArray.length; i++ ) { addValueSeriesAggregateBindingForGrouping( fReportItemHandle, fQueryDefinition, ( (Axis) orthAxisArray[i] ).getSeriesDefinitions( ), innerGroupDef, valueExprMap, baseSD ); } } else if ( fChart instanceof ChartWithoutAxes ) { addValueSeriesAggregateBindingForGrouping( fReportItemHandle, fQueryDefinition, baseSD.getSeriesDefinitions( ), innerGroupDef, valueExprMap, baseSD ); } } // 4. Binding sort on base series. String baseSortExpr = getValidSortExpr( baseSD ); if ( baseSD.isSetSorting( ) && baseSortExpr != null ) { if ( ChartReportItemUtil.isBaseGroupingDefined( baseSD ) ) { // If base series set group, add sort on group definition. String baseExpr = ( (Query) baseSD.getDesignTimeSeries( ) .getDataDefinition( ) .get( 0 ) ).getDefinition( ); if ( baseExpr.equals( getValidSortExpr( baseSD ) ) ) { baseGroupDefinition.setSortDirection( ChartReportItemUtil.convertToDtESortDirection( baseSD.getSorting( ) ) ); } else { SortDefinition sd = new SortDefinition( ); sd.setSortDirection( ChartReportItemUtil.convertToDtESortDirection( baseSD.getSorting( ) ) ); String newValueSeriesExpr = (String) valueExprMap.get( baseSortExpr ); if ( newValueSeriesExpr != null ) { // Use new expression instead of old. baseSD.getSortKey( ) .setDefinition( newValueSeriesExpr ); sd.setExpression( newValueSeriesExpr ); } else { sd.setExpression( baseSortExpr ); } baseGroupDefinition.addSort( sd ); } } else { // If base series doesn't set group, directly add sort on // query definition. SortDefinition sd = new SortDefinition( ); sd.setExpression( baseSortExpr ); sd.setSortDirection( ChartReportItemUtil.convertToDtESortDirection( baseSD.getSorting( ) ) ); fQueryDefinition.addSort( sd ); } } } /** * Create Y grouping definition. * * @param orthSD * @return */ private GroupDefinition createOrthogonalGroupingDefinition( SeriesDefinition orthSD ) { if ( ChartReportItemUtil.isYGroupingDefined( orthSD ) ) { DataType dataType = null; GroupingUnitType groupUnit = null; double groupIntervalRange = 0; // Default value is 0. String yGroupExpr = orthSD.getQuery( ).getDefinition( ); if ( orthSD.getGrouping( ) != null && orthSD.getGrouping( ).isEnabled( ) ) { dataType = orthSD.getGrouping( ).getGroupType( ); groupUnit = orthSD.getGrouping( ).getGroupingUnit( ); groupIntervalRange = orthSD.getGrouping( ) .getGroupingInterval( ); } GroupDefinition yGroupDefinition = new GroupDefinition( yGroupExpr ); yGroupDefinition.setKeyExpression( yGroupExpr ); yGroupDefinition.setInterval( ChartReportItemUtil.convertToDtEGroupUnit( dataType, groupUnit, groupIntervalRange ) ); yGroupDefinition.setIntervalRange( ChartReportItemUtil.convertToDtEIntervalRange( dataType, groupIntervalRange ) ); if ( orthSD.isSetSorting( ) ) { yGroupDefinition.setSortDirection( ChartReportItemUtil.convertToDtESortDirection( orthSD.getSorting( ) ) ); } return yGroupDefinition; } return null; } /** * Create base grouping definition. * * @param baseSD * @return */ private GroupDefinition createBaseGroupingDefinition( SeriesDefinition baseSD ) { DataType dataType; GroupingUnitType groupUnit; double groupIntervalRange; if ( ChartReportItemUtil.isBaseGroupingDefined( baseSD ) ) { dataType = baseSD.getGrouping( ).getGroupType( ); groupUnit = baseSD.getGrouping( ).getGroupingUnit( ); groupIntervalRange = baseSD.getGrouping( ) .getGroupingInterval( ); if ( groupIntervalRange < 0 ) { groupIntervalRange = 0; } String baseExpr = ( (Query) baseSD.getDesignTimeSeries( ) .getDataDefinition( ) .get( 0 ) ).getDefinition( ); GroupDefinition baseGroupDefinition = new GroupDefinition( baseExpr ); baseGroupDefinition.setKeyExpression( baseExpr ); baseGroupDefinition.setInterval( ChartReportItemUtil.convertToDtEGroupUnit( dataType, groupUnit, groupIntervalRange ) ); baseGroupDefinition.setIntervalRange( ChartReportItemUtil.convertToDtEIntervalRange( dataType, groupIntervalRange ) ); return baseGroupDefinition; } return null; } /** * Add aggregate bindings of value series for grouping case. * * @param handle * @param query * @param seriesDefinitions * @param innerGroupDef * @param valueExprMap * @param baseSD * @throws DataException */ private void addValueSeriesAggregateBindingForGrouping( ExtendedItemHandle handle, QueryDefinition query, EList seriesDefinitions, GroupDefinition innerGroupDef, Map valueExprMap, SeriesDefinition baseSD ) throws DataException { for ( Iterator iter = seriesDefinitions.iterator( ); iter.hasNext( ); ) { SeriesDefinition orthSD = (SeriesDefinition) iter.next( ); String expr = ( (Query) orthSD.getDesignTimeSeries( ) .getDataDefinition( ) .get( 0 ) ).getDefinition( ); if ( expr != null && !"".equals( expr ) ) //$NON-NLS-1$ { // Get a unique name. String name = StructureFactory.newComputedColumn( handle, expr.replaceAll( "\"", "" ) ) //$NON-NLS-1$ //$NON-NLS-2$ .getName( ); Binding colBinding = new Binding( name ); colBinding.setDataType( org.eclipse.birt.core.data.DataType.ANY_TYPE ); colBinding.setExpression( new ScriptExpression( expr ) ); if ( innerGroupDef != null ) { colBinding.addAggregateOn( innerGroupDef.getName( ) ); colBinding.setAggrFunction( ChartReportItemUtil.convertToDtEAggFunction( getAggFunExpr( orthSD, baseSD ) ) ); } String newExpr = ExpressionUtil.createJSRowExpression( name ); ( (Query) orthSD.getDesignTimeSeries( ) .getDataDefinition( ) .get( 0 ) ).setDefinition( newExpr ); query.addBinding( colBinding ); valueExprMap.put( expr, newExpr ); } } } /** * Returns aggregation function expression. * * @param orthSD * @param baseSD * @return */ private String getAggFunExpr( SeriesDefinition orthSD, SeriesDefinition baseSD ) { String strBaseAggExp = null; if ( baseSD.getGrouping( ) != null && baseSD.getGrouping( ).isSetEnabled( ) && baseSD.getGrouping( ).isEnabled( ) ) { strBaseAggExp = baseSD.getGrouping( ).getAggregateExpression( ); } return getAggFunExpr( orthSD, strBaseAggExp ); } /** * Returns aggregation function expression. * * @param orthSD * @param baseAggExp * @return */ private String getAggFunExpr( SeriesDefinition orthSD, String baseAggExp ) { String strOrthoAgg = null; SeriesGrouping grouping = orthSD.getGrouping( ); // Only if base series has enabled grouping if ( baseAggExp != null ) { if ( grouping != null && grouping.isSetEnabled( ) && grouping.isEnabled( ) ) { // Set own group strOrthoAgg = grouping.getAggregateExpression( ); } else { // Set base group strOrthoAgg = baseAggExp; } } return strOrthoAgg; } /** * Get aggregation function string of sort key related with value * series. * * @param sortKey * @param baseSD * @param orthAxisArray * @return */ private String getAggFunExpr( String sortKey, SeriesDefinition baseSD, Object[] orthAxisArray ) { String baseAggFunExpr = null; if ( baseSD.getGrouping( ) != null && baseSD.getGrouping( ).isSetEnabled( ) && baseSD.getGrouping( ).isEnabled( ) ) { baseAggFunExpr = baseSD.getGrouping( ).getAggregateExpression( ); } String aggFunction = null; if ( fChart instanceof ChartWithAxes ) { for ( int i = 0; i < orthAxisArray.length; i++ ) { EList sds = ( (Axis) orthAxisArray[i] ).getSeriesDefinitions( ); for ( Iterator iter = sds.iterator( ); iter.hasNext( ); ) { SeriesDefinition sd = (SeriesDefinition) iter.next( ); if ( sd.getDesignTimeSeries( ).getDataDefinition( ) != null && sd.getDesignTimeSeries( ) .getDataDefinition( ) .get( 0 ) != null ) { Query q = (Query) sd.getDesignTimeSeries( ) .getDataDefinition( ) .get( 0 ); if ( sortKey.equals( q.getDefinition( ) ) ) { aggFunction = getAggFunExpr( sd, baseAggFunExpr ); break; } } } } } else if ( fChart instanceof ChartWithoutAxes ) { for ( Iterator iter = baseSD.getSeriesDefinitions( ).iterator( ); iter.hasNext( ); ) { SeriesDefinition sd = (SeriesDefinition) iter.next( ); if ( sd.getDesignTimeSeries( ).getDataDefinition( ) != null && sd.getDesignTimeSeries( ) .getDataDefinition( ) .get( 0 ) != null ) { Query q = (Query) sd.getDesignTimeSeries( ) .getDataDefinition( ) .get( 0 ); if ( sortKey.equals( q.getDefinition( ) ) ) ; { aggFunction = sd.getGrouping( ) .getAggregateExpression( ); break; } } } } if( aggFunction == null ) { return baseAggFunExpr; } return aggFunction; } } // End of class ChartGroupBindingManager. }
package org.eclipse.birt.chart.reportitem; import org.eclipse.birt.chart.model.Chart; import org.eclipse.birt.chart.model.util.ChartValueUpdater; import org.eclipse.birt.report.model.api.DesignElementHandle; import org.eclipse.birt.report.model.api.elements.structures.FormatValue; /** * This class process extra styles to chart. * * @since 2.6.2 */ public class ChartStyleProcessorProxy { /** The chart's report item handle. */ protected DesignElementHandle handle; private FormatInfo categoryFormat = null; protected ChartValueUpdater chartValueUpdater; /** * Constructor. */ public ChartStyleProcessorProxy() { chartValueUpdater = new ChartValueUpdater( ); } /** * Sets chart's report handle. * * @param handle */ public void setHandle( DesignElementHandle handle ) { this.handle = handle; } /** * Applies extra styles onto chart. * * @param cm */ public void processDataSetStyle( Chart cm ) { // No code here, just return return; } /** * Sets format info of chart's category. * * @param formatInfo */ protected void setCategoryFormat( FormatInfo formatInfo ) { this.categoryFormat = formatInfo; } /** * Returns format info of chart's category. * * @return object of format info. */ public FormatInfo getCategoryFormat( ) { return this.categoryFormat; } /** * The class stores format information. */ public static class FormatInfo { public FormatValue formatValue = null; public String dataType = null; } /** * Updates chart values. * * @param cm * @param formatDefault * indicates if it force to use default values to update chart * model. */ public void updateChart( Chart cm, boolean forceDefault ) { chartValueUpdater.update( cm, null ); } /** * Indicates if chart need to inherit basic styles from container. * * @return true if it needs to inherit styles. */ public boolean needInheritingStyles( ) { return true; } /** * Sets an instance of ChartValueUpdater. * * @param valueUpdater */ public void setChartValueUpdater( ChartValueUpdater valueUpdater ) { this.chartValueUpdater = valueUpdater; } }
package org.chromium.chrome.browser.sync; import android.app.Activity; import android.app.FragmentTransaction; import android.os.Bundle; import android.preference.CheckBoxPreference; import android.preference.Preference; import android.preference.SwitchPreference; import android.preference.TwoStatePreference; import android.test.suitebuilder.annotation.SmallTest; import org.chromium.base.ThreadUtils; import org.chromium.base.test.util.Feature; import org.chromium.chrome.browser.sync.ui.SyncCustomizationFragment; import org.chromium.chrome.shell.R; import org.chromium.chrome.test.util.browser.sync.SyncTestUtil; import org.chromium.sync.AndroidSyncSettings; import org.chromium.sync.internal_api.pub.base.ModelType; import java.util.Collection; import java.util.EnumSet; import java.util.HashMap; import java.util.Map; import java.util.Set; /** * Tests for SyncCustomizationFragment. */ public class SyncCustomizationFragmentTest extends SyncTestBase { private static final String TAG = "SyncCustomizationFragmentTest"; private static final String TEST_ACCOUNT = "test@gmail.com"; /** * Maps ModelTypes to their UI element IDs. */ private static final Map<ModelType, String> UI_DATATYPES; static { UI_DATATYPES = new HashMap<ModelType, String>(); UI_DATATYPES.put(ModelType.AUTOFILL, SyncCustomizationFragment.PREFERENCE_SYNC_AUTOFILL); UI_DATATYPES.put(ModelType.BOOKMARK, SyncCustomizationFragment.PREFERENCE_SYNC_BOOKMARKS); UI_DATATYPES.put(ModelType.TYPED_URL, SyncCustomizationFragment.PREFERENCE_SYNC_OMNIBOX); UI_DATATYPES.put(ModelType.PASSWORD, SyncCustomizationFragment.PREFERENCE_SYNC_PASSWORDS); UI_DATATYPES.put(ModelType.PROXY_TABS, SyncCustomizationFragment.PREFERENCE_SYNC_RECENT_TABS); } private Activity mActivity; private AndroidSyncSettings mAndroidSyncSettings; @Override protected void setUp() throws Exception { super.setUp(); mAndroidSyncSettings = AndroidSyncSettings.get(mContext); mActivity = getActivity(); } @SmallTest @Feature({"Sync"}) public void testSyncSwitch() throws Exception { setupTestAccountAndSignInToSync(CLIENT_ID); startSync(); SyncCustomizationFragment fragment = startSyncCustomizationFragment(); final SwitchPreference syncSwitch = getSyncSwitch(fragment); assertTrue(syncSwitch.isChecked()); assertTrue(mAndroidSyncSettings.isChromeSyncEnabled()); togglePreference(syncSwitch); assertFalse(syncSwitch.isChecked()); assertFalse(mAndroidSyncSettings.isChromeSyncEnabled()); togglePreference(syncSwitch); assertTrue(syncSwitch.isChecked()); assertTrue(mAndroidSyncSettings.isChromeSyncEnabled()); } @SmallTest @Feature({"Sync"}) public void testOpeningSettingsDoesntEnableSync() throws Exception { setupTestAccountAndSignInToSync(CLIENT_ID); stopSync(); SyncCustomizationFragment fragment = startSyncCustomizationFragment(); closeFragment(fragment); assertFalse(mAndroidSyncSettings.isChromeSyncEnabled()); } @SmallTest @Feature({"Sync"}) public void testDefaultControlStatesWithSyncOffThenOn() throws Exception { setupTestAccountAndSignInToSync(CLIENT_ID); stopSync(); SyncCustomizationFragment fragment = startSyncCustomizationFragment(); assertDefaultSyncOffState(fragment); togglePreference(getSyncSwitch(fragment)); waitForSyncInitialized(); assertDefaultSyncOnState(fragment); } @SmallTest @Feature({"Sync"}) public void testDefaultControlStatesWithSyncOnThenOff() throws Exception { setupTestAccountAndSignInToSync(CLIENT_ID); startSync(); SyncCustomizationFragment fragment = startSyncCustomizationFragment(); assertDefaultSyncOnState(fragment); togglePreference(getSyncSwitch(fragment)); assertDefaultSyncOffState(fragment); } @SmallTest @Feature({"Sync"}) public void testSyncEverythingAndDataTypes() throws Exception { setupTestAccountAndSignInToSync(CLIENT_ID); startSync(); SyncCustomizationFragment fragment = startSyncCustomizationFragment(); SwitchPreference syncEverything = getSyncEverything(fragment); Collection<CheckBoxPreference> dataTypes = getDataTypes(fragment).values(); assertDefaultSyncOnState(fragment); togglePreference(syncEverything); for (CheckBoxPreference dataType : dataTypes) { assertTrue(dataType.isChecked()); assertTrue(dataType.isEnabled()); } // If all data types are unchecked, sync should turn off. for (CheckBoxPreference dataType : dataTypes) { togglePreference(dataType); } getInstrumentation().waitForIdleSync(); assertDefaultSyncOffState(fragment); assertFalse(mAndroidSyncSettings.isChromeSyncEnabled()); } @SmallTest @Feature({"Sync"}) public void testSettingDataTypes() throws Exception { setupTestAccountAndSignInToSync(CLIENT_ID); startSync(); SyncCustomizationFragment fragment = startSyncCustomizationFragment(); SwitchPreference syncEverything = getSyncEverything(fragment); Map<ModelType, CheckBoxPreference> dataTypes = getDataTypes(fragment); assertDefaultSyncOnState(fragment); togglePreference(syncEverything); for (CheckBoxPreference dataType : dataTypes.values()) { assertTrue(dataType.isChecked()); assertTrue(dataType.isEnabled()); } Set<ModelType> expectedTypes = EnumSet.copyOf(dataTypes.keySet()); assertDataTypesAre(expectedTypes); togglePreference(dataTypes.get(ModelType.AUTOFILL)); togglePreference(dataTypes.get(ModelType.PASSWORD)); // Nothing should have changed before the fragment closes. assertDataTypesAre(expectedTypes); closeFragment(fragment); expectedTypes.remove(ModelType.AUTOFILL); expectedTypes.remove(ModelType.PASSWORD); assertDataTypesAre(expectedTypes); } private SyncCustomizationFragment startSyncCustomizationFragment() { SyncCustomizationFragment fragment = new SyncCustomizationFragment(); Bundle args = new Bundle(); args.putString(SyncCustomizationFragment.ARGUMENT_ACCOUNT, SyncTestUtil.DEFAULT_TEST_ACCOUNT); fragment.setArguments(args); FragmentTransaction transaction = mActivity.getFragmentManager().beginTransaction(); transaction.add(R.id.content_container, fragment, TAG); transaction.commit(); getInstrumentation().waitForIdleSync(); return fragment; } private void closeFragment(SyncCustomizationFragment fragment) { FragmentTransaction transaction = mActivity.getFragmentManager().beginTransaction(); transaction.remove(fragment); transaction.commit(); getInstrumentation().waitForIdleSync(); } private SwitchPreference getSyncSwitch(SyncCustomizationFragment fragment) { return (SwitchPreference) fragment.findPreference( SyncCustomizationFragment.PREF_SYNC_SWITCH); } private SwitchPreference getSyncEverything(SyncCustomizationFragment fragment) { return (SwitchPreference) fragment.findPreference( SyncCustomizationFragment.PREFERENCE_SYNC_EVERYTHING); } private Map<ModelType, CheckBoxPreference> getDataTypes(SyncCustomizationFragment fragment) { Map<ModelType, CheckBoxPreference> dataTypes = new HashMap<ModelType, CheckBoxPreference>(); for (ModelType modelType : UI_DATATYPES.keySet()) { String prefId = UI_DATATYPES.get(modelType); dataTypes.put(modelType, (CheckBoxPreference) fragment.findPreference(prefId)); } return dataTypes; } private Preference getEncryption(SyncCustomizationFragment fragment) { return (Preference) fragment.findPreference( SyncCustomizationFragment.PREFERENCE_ENCRYPTION); } private Preference getManageData(SyncCustomizationFragment fragment) { return (Preference) fragment.findPreference( SyncCustomizationFragment.PREFERENCE_SYNC_MANAGE_DATA); } private void assertDefaultSyncOnState(SyncCustomizationFragment fragment) { assertTrue("The sync switch should be on.", getSyncSwitch(fragment).isChecked()); assertTrue("The sync switch should be enabled.", getSyncSwitch(fragment).isEnabled()); SwitchPreference syncEverything = getSyncEverything(fragment); assertTrue("The sync everything switch should be on.", syncEverything.isChecked()); assertTrue("The sync everything switch should be enabled.", syncEverything.isEnabled()); for (CheckBoxPreference dataType : getDataTypes(fragment).values()) { String key = dataType.getKey(); assertTrue("Data type " + key + " should be checked.", dataType.isChecked()); assertFalse("Data type " + key + " should be disabled.", dataType.isEnabled()); } assertTrue("The encryption button should be enabled.", getEncryption(fragment).isEnabled()); assertTrue("The manage sync data button should be always enabled.", getManageData(fragment).isEnabled()); } private void assertDefaultSyncOffState(SyncCustomizationFragment fragment) { assertFalse("The sync switch should be off.", getSyncSwitch(fragment).isChecked()); assertTrue("The sync switch should be enabled.", getSyncSwitch(fragment).isEnabled()); SwitchPreference syncEverything = getSyncEverything(fragment); assertTrue("The sync everything switch should be on.", syncEverything.isChecked()); assertFalse("The sync everything switch should be disabled.", syncEverything.isEnabled()); for (CheckBoxPreference dataType : getDataTypes(fragment).values()) { String key = dataType.getKey(); assertTrue("Data type " + key + " should be checked.", dataType.isChecked()); assertFalse("Data type " + key + " should be disabled.", dataType.isEnabled()); } assertFalse("The encryption button should be disabled.", getEncryption(fragment).isEnabled()); assertTrue("The manage sync data button should be always enabled.", getManageData(fragment).isEnabled()); } private void assertDataTypesAre(final Set<ModelType> enabledDataTypes) { final Set<ModelType> disabledDataTypes = EnumSet.copyOf(UI_DATATYPES.keySet()); disabledDataTypes.removeAll(enabledDataTypes); ThreadUtils.runOnUiThreadBlocking(new Runnable() { @Override public void run() { Set<ModelType> actualDataTypes = mProfileSyncService.getPreferredDataTypes(); assertTrue(actualDataTypes.containsAll(enabledDataTypes)); // There is no Set.containsNone(), sadly. for (ModelType disabledDataType : disabledDataTypes) { assertFalse(actualDataTypes.contains(disabledDataType)); } } }); } private void togglePreference(final TwoStatePreference pref) { ThreadUtils.runOnUiThreadBlocking(new Runnable() { @Override public void run() { boolean newValue = !pref.isChecked(); pref.getOnPreferenceChangeListener().onPreferenceChange( pref, Boolean.valueOf(newValue)); pref.setChecked(newValue); } }); getInstrumentation().waitForIdleSync(); } }
package com.vogella.eclipse.languagetool.spellchecker; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.util.List; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IMarker; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.IRegion; import org.eclipse.ui.IEditorInput; import org.eclipse.ui.IFileEditorInput; import org.eclipse.ui.IWorkbench; import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.actions.WorkspaceModifyOperation; import org.eclipse.ui.texteditor.spelling.ISpellingEngine; import org.eclipse.ui.texteditor.spelling.ISpellingProblemCollector; import org.eclipse.ui.texteditor.spelling.SpellingContext; import org.languagetool.JLanguageTool; import org.languagetool.Language; import org.languagetool.language.AmericanEnglish; import org.languagetool.markup.AnnotatedTextBuilder; import org.languagetool.rules.RuleMatch; import org.languagetool.tokenizers.en.EnglishWordTokenizer; public class Engine implements ISpellingEngine { @Override public void check(IDocument document, IRegion[] regions, SpellingContext context, ISpellingProblemCollector collector, IProgressMonitor monitor) { JLanguageTool.setDataBroker(new EclipseRessourceDataBroker()); JLanguageTool langTool = new JLanguageTool(new AmericanEnglish()); Language language = langTool.getLanguage(); if (language == null) { return; } for (IRegion region : regions) { AnnotatedTextBuilder textBuilder = new AnnotatedTextBuilder(); List<RuleMatch> matches; try { populateBuilder(textBuilder, document.get(region.getOffset(), region.getLength())); matches = langTool.check(textBuilder.build()); processMatches(collector, matches); } catch (IOException | BadLocationException e) { e.printStackTrace(); } } } private void processMatches(ISpellingProblemCollector collector, List<RuleMatch> matches) { WorkspaceModifyOperation workspaceRunnable = new WorkspaceModifyOperation() { @Override protected void execute(IProgressMonitor monitor) throws CoreException, InvocationTargetException, InterruptedException { for (RuleMatch match : matches) { collector.accept(new LTSpellingProblem(match)); addMarker(match); } } }; try { workspaceRunnable.run(null); } catch (InvocationTargetException | InterruptedException e) { e.printStackTrace(); } } private void addMarker(RuleMatch match) { IWorkbench workbench = PlatformUI.getWorkbench(); workbench.getDisplay().syncExec(new Runnable() { @Override public void run() { IWorkbenchWindow activeWorkbenchWindow = workbench.getActiveWorkbenchWindow(); IEditorInput currentEditorInput = activeWorkbenchWindow.getActivePage().getActiveEditor() .getEditorInput(); IFile file = null; if (currentEditorInput instanceof IFileEditorInput) { file = ((IFileEditorInput) currentEditorInput).getFile(); if (file != null) { IMarker marker = null; try { marker = file.createMarker(IMarker.PROBLEM); marker.setAttribute(IMarker.SEVERITY, IMarker.SEVERITY_ERROR); marker.setAttribute(IMarker.MESSAGE, match.getMessage()); marker.setAttribute(IMarker.CHAR_START, match.getFromPos()); marker.setAttribute(IMarker.CHAR_END, match.getToPos()); } catch (CoreException e) { e.printStackTrace(); } } } } }); } private static void populateBuilder(AnnotatedTextBuilder builder, String lines) { EnglishWordTokenizer wordTokenizer = new EnglishWordTokenizer() { @Override public String getTokenizingCharacters() { return super.getTokenizingCharacters() + "_"; } }; List<String> tokens = wordTokenizer.tokenize(lines); // String[] splittedList = // lines.split("(?<=\\s|\\||\\s\\_|\\[)|(?=\\_\\s|\\])"); for (String singleWord : tokens) { if (isMarkup(singleWord)) { builder.addMarkup(singleWord); continue; } builder.addText(singleWord); } } private static boolean isMarkup(String line) { if (line.startsWith("image::")) { return true; } if (line.startsWith("menu:")) { return true; } if (line.contains("_")) { return true; } if (line.contains("`")) { return true; } if (line.startsWith("|")) { return true; } if (line.startsWith("btn:")) { return true; } if (line.startsWith("include::")) { return true; } if (line.startsWith(" return true; } return false; } }
package com.nobodyiam.spring.cloud.in.action.config.server; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.cloud.config.server.EnableConfigServer; @EnableConfigServer @SpringBootApplication public class ConfigServerApplication { public static void main(String[] args) { new SpringApplicationBuilder(ConfigServerApplication.class) .run(args); } }
package ca.qc.bergeron.marcantoine.crammeur.librairy.utils; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.math.BigDecimal; import java.util.Collection; import java.util.Iterator; import java.util.LinkedList; import java.util.NoSuchElementException; import ca.qc.bergeron.marcantoine.crammeur.librairy.models.i.Data; import ca.qc.bergeron.marcantoine.crammeur.librairy.utils.i.DataCollectionIterator; import ca.qc.bergeron.marcantoine.crammeur.librairy.utils.i.DataListIterator; public final class DataLongListIterator<T extends Data<Long>> extends ca.qc.bergeron.marcantoine.crammeur.librairy.utils.DataListIterator<T, Long> { protected final LinkedList<LinkedList<T>>[] values = new LinkedList[2]; protected transient volatile long mIndex = NULL_INDEX; protected transient volatile long mSize = 0L; private DataLongListIterator(@NotNull LinkedList<LinkedList<T>> pListOne, @NotNull LinkedList<LinkedList<T>> pListTwo) { values[0] = pListOne; values[1] = pListTwo; for (LinkedList<LinkedList<T>> lla : values) { Parallel.For(lla, new Parallel.Operation<LinkedList<T>>() { @Override public void perform(LinkedList<T> pParameter) { synchronized (DataLongListIterator.this) { mSize+=pParameter.size(); } } @Override public boolean follow() { return true; } }); } } public DataLongListIterator() { values[0] = new LinkedList<LinkedList<T>>(); values[1] = new LinkedList<LinkedList<T>>(); } @Override protected void finalize() throws Throwable { super.finalize(); values[0] = null; values[1] = null; mIndex = NULL_INDEX; mSize = 0L; } @Override @NotNull public final Long size() { return mSize; } @Override public final boolean isEmpty() { return mSize == 0; } @Override @NotNull public final Long indexOfKey(@Nullable final Long pKey) { final long[] result = new long[1]; result[0] = NULL_INDEX; Parallel.Operation<T> operation = new Parallel.Operation<T>() { boolean follow = true; long index = NULL_INDEX; @Override public void perform(T pParameter) { if (pParameter != null && ((pKey == null && pParameter.getId() == null) || (pKey != null && pKey.equals(pParameter.getId())))) { synchronized (this) { index++; follow = false; } synchronized (result) { result[0] = index; } } else { synchronized (this) { index++; } } } @Override public boolean follow() { return follow; } }; for (Collection<T> collection : this.allCollections()) { Parallel.For(collection, operation); if (result[0] != NULL_INDEX) { break; } } return result[0]; } @NotNull @Override public final Long lastIndexOfKey(@Nullable final Long pKey) { final long[] result = new long[1]; result[0] = NULL_INDEX; Parallel.Operation<T> operation = new Parallel.Operation<T>() { long index = NULL_INDEX; @Override public void perform(T pParameter) { synchronized (this) { index++; } if (pParameter != null) { boolean equals; if (pKey == null) { equals = pParameter.getId() == null; } else { equals = pKey.equals(pParameter.getId()); } if (equals) { synchronized (result) { result[0] = index; } } } } @Override public boolean follow() { return true; } }; for (Collection<T> collection : this.allCollections()) { Parallel.For(collection, operation); } return result[0]; } @Override public final int currentCollectionIndex() { return this.collectionIndexOf(mIndex); } @Override public final boolean hasNext() { return mIndex + 1 < mSize; } @Nullable @Override public final T next() { if (hasNext()) { mIndex++; return actual(); } else throw new NoSuchElementException(); } @Override public final boolean hasPrevious() { return (mIndex != NULL_INDEX) && mIndex - 1 != NULL_INDEX; } @Nullable @Override public final T previous() { if (hasPrevious()) { mIndex return actual(); } else throw new NoSuchElementException(); } @Nullable protected final T actual() { if (mIndex != -1 && mIndex < Long.MAX_VALUE) { final int arrayIndex = (int) (mIndex / ((long) MAX_COLLECTION_INDEX * MAX_COLLECTION_INDEX)); final int listIndex = (arrayIndex == 1) ? BigDecimal.valueOf(((mIndex / ((long) MAX_COLLECTION_INDEX + 1)) + 1)).divide(BigDecimal.valueOf(2), BigDecimal.ROUND_HALF_UP).add(BigDecimal.ONE.negate()).multiply(BigDecimal.valueOf(2)).intValue() : (int) (mIndex / ((long) MAX_COLLECTION_INDEX + 1)); return values[arrayIndex].get(listIndex).get(collectionIndexOf(mIndex)); } else throw new IndexOutOfBoundsException(String.valueOf(mIndex)); } @Override public final int collectionIndexOf(@NotNull Long pIndex) { return (int) (pIndex % Integer.MAX_VALUE); } @Override @NotNull public final LinkedList<T> currentCollection() { final int arrayIndex = (int) (mIndex / (((long) MAX_COLLECTION_INDEX + 1) * ((long) MAX_COLLECTION_INDEX + 1))); final int listIndex = (arrayIndex == 1) ? (int) ((mIndex % (((long) MAX_COLLECTION_INDEX + 1) * ((long) MAX_COLLECTION_INDEX + 1))) / ((long) MAX_COLLECTION_INDEX + 1)) : (int) (mIndex / ((long) MAX_COLLECTION_INDEX + 1)); return new LinkedList<>(values[arrayIndex].get(listIndex)); } @Override @NotNull public final Iterable<Collection<T>> allCollections() { return new Iterable<Collection<T>>() { @NotNull @Override public Iterator<Collection<T>> iterator() { return new Iterator<Collection<T>>() { private LinkedList<LinkedList<T>>[] values = DataLongListIterator.this.values; private transient volatile long mIndex = NULL_INDEX; private transient volatile long mSize = values[0].size() + values[1].size(); @Override public boolean hasNext() { return mIndex + 1 < mSize; } @Override public Collection<T> next() { if (mIndex + 1 < Integer.MAX_VALUE) { return values[0].get((int) (++mIndex)); } else { return values[1].get((int) ((++mIndex) % Integer.MAX_VALUE)); } } @Override public void remove() { if (mIndex == NULL_INDEX) throw new IllegalStateException(String.valueOf(NULL_INDEX)); if (mIndex < Integer.MAX_VALUE) { values[0].remove((int) mIndex); } else { values[1].remove((int) (mIndex % Integer.MAX_VALUE)); } mIndex } }; } }; } @Override @NotNull public final LinkedList<T> collectionOf(@NotNull Long pIndex) { final int arrayIndex = (int) (mIndex / (((long) MAX_COLLECTION_INDEX + 1) * ((long) MAX_COLLECTION_INDEX + 1))); final int listIndex = (arrayIndex == 1) ? (int) ((mIndex % (((long) MAX_COLLECTION_INDEX + 1) * ((long) MAX_COLLECTION_INDEX + 1))) / ((long) MAX_COLLECTION_INDEX + 1)) : (int) (mIndex / ((long) MAX_COLLECTION_INDEX + 1)); return new LinkedList<>(values[arrayIndex].get(listIndex)); } @Override public final int nextIndex() { if (mIndex + 1 != Long.MAX_VALUE && mIndex + 1 < mSize) { return collectionIndexOf(mIndex + 1); } else { return collectionIndexOf(mSize); } } @Override public final int previousIndex() { if (mIndex - 1 >= MIN_INDEX && mIndex != NULL_INDEX) { return collectionIndexOf(mIndex - 1); } else { return NULL_INDEX; } } @Override public final void remove() { if (mIndex == NULL_INDEX) throw new IllegalStateException(String.valueOf(NULL_INDEX)); final int arrayIndex = (int) (mIndex / (((long) MAX_COLLECTION_INDEX + 1) * ((long) MAX_COLLECTION_INDEX + 1))); final int listIndex = (arrayIndex == 1) ? (int) ((mIndex % (((long) MAX_COLLECTION_INDEX + 1) * ((long) MAX_COLLECTION_INDEX + 1))) / ((long) MAX_COLLECTION_INDEX + 1)) : (int) (mIndex / ((long) MAX_COLLECTION_INDEX + 1)); values[arrayIndex].get(listIndex).remove(this.currentCollectionIndex()); mIndex } @Override public final void set(@Nullable T t) { if (mIndex == NULL_INDEX) throw new IllegalStateException(String.valueOf(NULL_INDEX)); final int arrayIndex = (int) (mIndex / (((long) MAX_COLLECTION_INDEX + 1) * ((long) MAX_COLLECTION_INDEX + 1))); final int listIndex = (arrayIndex == 1) ? (int) ((mIndex % (((long) MAX_COLLECTION_INDEX + 1) * ((long) MAX_COLLECTION_INDEX + 1))) / ((long) MAX_COLLECTION_INDEX + 1)) : (int) (mIndex / ((long) MAX_COLLECTION_INDEX + 1)); values[arrayIndex].get(listIndex).set(this.currentCollectionIndex(), t); } @Override public final void add(@Nullable T pData) { long index; if (mIndex == NULL_INDEX) index = mIndex + 1; else index = mIndex; final int arrayIndex = (int) (index / (((long) MAX_COLLECTION_INDEX + 1) * ((long) MAX_COLLECTION_INDEX + 1))); final int listIndex = (arrayIndex == 1) ? (int) ((index % (((long) MAX_COLLECTION_INDEX + 1) * ((long) MAX_COLLECTION_INDEX + 1))) / ((long) MAX_COLLECTION_INDEX + 1)) : (int) (index / ((long) MAX_COLLECTION_INDEX + 1)); if (values[arrayIndex].isEmpty() || (listIndex > 0 && values[arrayIndex].get(listIndex - 1).size() == Integer.MAX_VALUE)) { values[arrayIndex].add(new LinkedList<T>()); } values[arrayIndex].get(values[arrayIndex].size() - 1).add(collectionIndexOf(index),pData); mSize++; } @Override public boolean addAtEnd(@Nullable T pData) { final int arrayIndex = (int) ((mSize - 1) / (((long) MAX_COLLECTION_INDEX + 1) * ((long) MAX_COLLECTION_INDEX + 1))); final int listIndex = (arrayIndex == 1) ? (int) (((mSize - 1) % (((long) MAX_COLLECTION_INDEX + 1) * ((long) MAX_COLLECTION_INDEX + 1))) / ((long) MAX_COLLECTION_INDEX + 1)) : (int) ((mSize - 1) / ((long) MAX_COLLECTION_INDEX + 1)); if (values[arrayIndex].isEmpty() || (listIndex > 0 && values[arrayIndex].get(listIndex - 1).size() == Integer.MAX_VALUE)) { values[arrayIndex].add(new LinkedList<T>()); } boolean exception = false; try { return values[arrayIndex].get(values[arrayIndex].size() - 1).add(pData); } catch (Throwable t) { t.printStackTrace(); exception = true; throw t; } finally { if (!exception) mSize++; } } @Override public final boolean remove(@Nullable final T pData) { final long[] index = new long[1]; index[0] = NULL_INDEX; final boolean[] result = new boolean[1]; Parallel.Operation<T> operation = new Parallel.Operation<T>() { boolean follow = true; @Override public void perform(final T pParameter) { synchronized (index) { index[0]++; } synchronized (result) { result[0] = (pData == pParameter || (pData != null && pData.equals(pParameter))); } synchronized (this) { follow = !result[0]; } } @Override public boolean follow() { return follow; } }; for (final LinkedList<LinkedList<T>> lla : values) { LinkedList<T> list = null; for (final LinkedList<T> linkedList : lla) { Parallel.For(linkedList, operation); if (result[0]) { list = linkedList; break; } } if (list != null) { result[0] = list.remove(pData); if (result[0]) { if (index[0] != NULL_INDEX && index[0] <= mIndex) { mIndex } mSize } } if (result[0]) break; } return result[0]; } @Override public final <E extends T> boolean retainAll(@NotNull DataCollectionIterator<E, Long> pDataCollectionIterator) { final boolean[] result = new boolean[1]; result[0] = true; final DataLongListIterator<T> retain = new DataLongListIterator<T>(); for (Collection<E> collection : pDataCollectionIterator.allCollections()) { Parallel.For(collection, new Parallel.Operation<E>() { @Override public void perform(E pParameter) { retain.addAtEnd(pParameter); } @Override public boolean follow() { return true; } }); } final DataLongListIterator<T> delete = new DataLongListIterator<>(); for (Collection<T> collection : this.allCollections()) { Parallel.For(collection, new Parallel.Operation<T>() { @Override public void perform(T pParameter) { if (!retain.contains(pParameter)) { delete.addAtEnd(pParameter); } } @Override public boolean follow() { return true; } }); } for (Collection<T> collection : delete.allCollections()) { Parallel.For(collection, new Parallel.Operation<T>() { boolean follow = true; @Override public void perform(T pParameter) { synchronized (result) { result[0] = DataLongListIterator.this.remove(pParameter); } synchronized (this) { follow = result[0]; } } @Override public boolean follow() { return follow; } }); } return result[0]; } @Override public final void clear() { values[0].clear(); values[1].clear(); mIndex = NULL_INDEX; mSize = 0L; } @Override public final Iterator<T> iterator() { return new DataLongListIterator<T>(values[0], values[1]); } @Override public final <E extends T> void addAll(@NotNull final Long pIndex, @NotNull DataListIterator<E, Long> pDataListIterator) { Parallel.Operation<E> operation = new Parallel.Operation<E>() { long index = pIndex; @Override public void perform(E pParameter) { final int arrayIndex = (int) (index / (((long) MAX_COLLECTION_INDEX + 1) * ((long) MAX_COLLECTION_INDEX + 1))); final int listIndex = (arrayIndex == 1) ? (int) ((index % (((long) MAX_COLLECTION_INDEX + 1) * ((long) MAX_COLLECTION_INDEX + 1))) / ((long) MAX_COLLECTION_INDEX + 1)) : (int) (index / ((long) MAX_COLLECTION_INDEX + 1)); synchronized (values) { values[arrayIndex].get(listIndex).add(collectionIndexOf(index), pParameter); } synchronized (this) { index++; } } @Override public boolean follow() { return true; } }; for (Collection<E> collection : pDataListIterator.allCollections()) { Parallel.For(collection, operation); } } @Override @Nullable public final T get(@NotNull Long pIndex) { if (pIndex > mSize - 1) throw new IndexOutOfBoundsException(String.valueOf(pIndex)); final int arrayIndex = (int) (pIndex / (((long) MAX_COLLECTION_INDEX + 1) * ((long) MAX_COLLECTION_INDEX + 1))); final int listIndex = (arrayIndex == 1) ? (int) ((pIndex % (((long) MAX_COLLECTION_INDEX + 1) * ((long) MAX_COLLECTION_INDEX + 1))) / ((long) MAX_COLLECTION_INDEX + 1)) : (int) (pIndex / ((long) MAX_COLLECTION_INDEX + 1)); //if (values[arrayIndex].get(listIndex) == null) return null; return values[arrayIndex].get(listIndex).get(collectionIndexOf(pIndex)); } @Override @Nullable public final T set(@NotNull Long pIndex, @Nullable T pData) { if (pIndex > mSize - 1) throw new IndexOutOfBoundsException(String.valueOf(pIndex)); final int arrayIndex = (int) (pIndex / (((long) MAX_COLLECTION_INDEX + 1) * ((long) MAX_COLLECTION_INDEX + 1))); final int listIndex = (arrayIndex == 1) ? (int) ((pIndex % (((long) MAX_COLLECTION_INDEX + 1) * ((long) MAX_COLLECTION_INDEX + 1))) / ((long) MAX_COLLECTION_INDEX + 1)) : (int) (pIndex / ((long) MAX_COLLECTION_INDEX + 1)); //if (values[arrayIndex].get(listIndex) == null) return null; return values[arrayIndex].get(listIndex).set(collectionIndexOf(pIndex), pData); } @Override public final void add(@NotNull final Long pIndex, @Nullable final T pData) { final int arrayIndex = (int) (pIndex / (((long) MAX_COLLECTION_INDEX + 1) * ((long) MAX_COLLECTION_INDEX + 1))); final int listIndex = (arrayIndex == 1) ? (int) ((pIndex % (((long) MAX_COLLECTION_INDEX + 1) * ((long) MAX_COLLECTION_INDEX + 1))) / ((long) MAX_COLLECTION_INDEX + 1)) : (int) (pIndex / ((long) MAX_COLLECTION_INDEX + 1)); if (values[arrayIndex].get(listIndex) != null) { values[arrayIndex].get(listIndex).add(collectionIndexOf(pIndex), pData); } else { values[arrayIndex].add(listIndex, new LinkedList<T>() {{ add(collectionIndexOf(pIndex), pData); }}); } if (pIndex <= this.mIndex) this.mIndex++; } @Override @NotNull public final Long indexOf(@Nullable final T pData) { final long[] result = new long[1]; result[0] = NULL_INDEX; Parallel.Operation<T> operation = new Parallel.Operation<T>() { long index = NULL_INDEX; boolean follow = true; @Override public void perform(T pParameter) { if ((pData == pParameter) || (pData != null && pData.equals(pParameter))) { synchronized (this) { index++; follow = false; } synchronized (result) { result[0] = index; } } else { synchronized (this) { index++; } } } @Override public boolean follow() { return follow; } }; for (Collection<T> collection : this.allCollections()) { Parallel.For(collection, operation); } return result[0]; } @Override @NotNull public final Long lastIndexOf(@Nullable final T pData) { final long[] result = new long[1]; result[0] = NULL_INDEX; Parallel.Operation<T> operation = new Parallel.Operation<T>() { long index = NULL_INDEX; @Override public void perform(T pParameter) { synchronized (this) { index++; } if ((pData == pParameter) || (pData != null && pData.equals(pParameter))) { synchronized (result) { result[0] = index; } } } @Override public boolean follow() { return true; } }; for (Collection<T> collection : this.allCollections()) { Parallel.For(collection, operation); } return result[0]; } @NotNull @Override public final DataListIterator<T, Long> listIterator() { return new DataLongListIterator<>(values[0], values[1]); } @NotNull @Override public final DataListIterator<T, Long> listIterator(@NotNull final Long pIndex) { final DataListIterator<T, Long> result = new DataLongListIterator<>(); Parallel.Operation<T> operation = new Parallel.Operation<T>() { long index = NULL_INDEX; @Override public void perform(T pParameter) { synchronized (this) { index++; } if (index >= pIndex) { synchronized (result) { result.addAtEnd(pParameter); } } } @Override public boolean follow() { return true; } }; for (Collection<T> collection : this.allCollections()) { Parallel.For(collection, operation); } return result; } @NotNull @Override public final DataListIterator<T, Long> subDataListIterator(@NotNull final Long pIndex1, @NotNull final Long pIndex2) { final DataListIterator<T, Long> result = new DataLongListIterator<>(); Parallel.Operation<T> operation = new Parallel.Operation<T>() { long index = NULL_INDEX; boolean follow = true; @Override public void perform(T pParameter) { synchronized (this) { index++; } if (index >= pIndex1 && index < pIndex2) { synchronized (result) { result.addAtEnd(pParameter); } } else if (index >= pIndex2) { synchronized (this) { follow = false; } } } @Override public boolean follow() { return follow; } }; for (Collection<T> collection : this.allCollections()) { Parallel.For(collection, operation); } return result; } }
package org.eclipse.birt.report.data.oda.jdbc; import java.io.File; import java.io.FileFilter; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.security.CodeSource; import java.security.PermissionCollection; import java.sql.Connection; import java.sql.Driver; import java.sql.DriverManager; import java.sql.DriverPropertyInfo; import java.sql.SQLException; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Hashtable; import java.util.Map; import java.util.Properties; import java.util.logging.Level; import java.util.logging.Logger; import org.eclipse.birt.core.framework.URLClassLoader; import org.eclipse.birt.report.data.oda.i18n.JdbcResourceHandle; import org.eclipse.birt.report.data.oda.i18n.ResourceConstants; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IConfigurationElement; import org.eclipse.core.runtime.IExtension; import org.eclipse.core.runtime.IExtensionPoint; import org.eclipse.core.runtime.IExtensionRegistry; import org.eclipse.core.runtime.Platform; import org.eclipse.datatools.connectivity.oda.IDriver; import org.eclipse.datatools.connectivity.oda.OdaException; import org.eclipse.datatools.connectivity.oda.util.manifest.ExtensionManifest; import org.eclipse.datatools.connectivity.oda.util.manifest.ManifestExplorer; import org.eclipse.datatools.connectivity.services.PluginResourceLocator; import com.ibm.icu.util.ULocale; /** * Utility classs that manages the JDBC drivers available to this bridge driver. * Deals with dynamic discovery of JDBC drivers and some annoying class loader * issues. * This class is not to be instantiated by the user. Use the getInstance() method * to obtain an instance */ public class JDBCDriverManager { private static final int MAX_WORD_LENGTH = 20; private static final int MAX_MSG_LENGTH = 300; public static final String JDBC_USER_PROP_NAME = "user"; //$NON-NLS-1$ public static final String JDBC_PASSWORD_PROP_NAME = "password"; //$NON-NLS-1$ private static final String INVALID_AUTH_SQL_STATE = "28000"; // X/Open SQL State //$NON-NLS-1$ private static final String EMPTY_STRING = ""; //$NON-NLS-1$ // Driver classes that we have registered with JDBC DriverManager private HashMap<String, Driver> registeredDrivers = new HashMap<String, Driver>(); private Hashtable<String, Driver> testedDrivers = new Hashtable<String, Driver>(); // A HashMap of JDBC driver instances private Hashtable<String, Driver> cachedJdbcDrivers = new Hashtable<String, Driver>(); // A HashMap of driverinfo extensions which provides IConnectionFactory implementation // Map is from driverClass (String) to either IConfigurationElement or IConnectionFactory private HashMap driverExtensions = null; private boolean loadedDriver = false; private DriverClassLoader extraDriverLoader = null; //The resource handle. private JdbcResourceHandle resourceHandle = new JdbcResourceHandle(ULocale .getDefault()); private static JDBCDriverManager instance; private static Logger logger = Logger.getLogger( JDBCDriverManager.class.getName() ); private JDBCDriverManager() { logger.logp( java.util.logging.Level.FINE, JDBCDriverManager.class.getName( ), "JDBCDriverManager", //$NON-NLS-1$ "JDBCDriverManager starts up" ); //$NON-NLS-1$ } public synchronized static JDBCDriverManager getInstance() { if ( instance == null ) instance = new JDBCDriverManager(); return instance; } public Driver getDriverInstance( Class driver, boolean refreshDriver ) throws OdaException { String driverName = driver.getName( ); Driver drv = getDriverInstance( driverName ); if ( refreshDriver || drv == null ) { Driver instance = null; try { instance = new WrappedDriver( (Driver) driver.newInstance( ), driverName ); } catch ( Exception e ) { throw new OdaException( e ); } cachedJdbcDrivers.put( driverName, instance ); return instance; } else { return drv; } } private Driver getDriverInstance( String driverName ) { return cachedJdbcDrivers.get( driverName ); } /** * Release all the resources */ public void close() { if( this.extraDriverLoader != null ) { this.extraDriverLoader.close(); this.extraDriverLoader = null; } synchronized( registeredDrivers ) { this.registeredDrivers.clear( ); } this.cachedJdbcDrivers.clear( ); this.testedDrivers.clear( ); } /** * Gets a JDBC connection * @param driverClass Class name of JDBC driver * @param url Connection URL * @param connectionProperties Properties for establising connection * @return new JDBC Connection * @throws SQLException */ public Connection getConnection( String driverClass, String url, Properties connectionProperties, Collection<String> driverClassPath ) throws SQLException, OdaException { validateConnectionProperties( driverClass, url, null ); if ( logger.isLoggable( Level.FINEST ) ) { logger.fine( "Request JDBC Connection: driverClass=" //$NON-NLS-1$ + ( driverClass == null ? EMPTY_STRING : driverClass ) + "; URL=" //$NON-NLS-1$ + LogUtil.encryptURL( url ) ); } return doConnect( driverClass, url, null, connectionProperties, driverClassPath ); } /** * Gets a JDBC connection * @param driverClass Class name of JDBC driver * @param url Connection URL * @param user connection user name * @param password connection password * @return new JDBC connection * @throws SQLException */ public Connection getConnection( String driverClass, String url, String user, String password, Collection<String> driverClassPath ) throws SQLException, OdaException { return getConnection( driverClass, url, user, password, driverClassPath, null ); } public Connection getConnection( String driverClass, String url, String user, String password, Collection<String> driverClassPath, Properties props ) throws SQLException, OdaException { validateConnectionProperties( driverClass, url, null ); if ( logger.isLoggable( Level.FINEST ) ) logger.fine( "Request JDBC Connection: driverClass=" //$NON-NLS-1$ + ( driverClass == null ? EMPTY_STRING : driverClass ) + "; URL=" //$NON-NLS-1$ + LogUtil.encryptURL( url ) + "; user=" //$NON-NLS-1$ + ( ( user == null ) ? EMPTY_STRING : user ) ); // Construct a Properties list with user/password properties props = addUserAuthenticationProperties( props, user, password ); return doConnect( driverClass, url, null, props, driverClassPath ); } /** * Gets a JDBC connection from the specified JNDI data source URL, or * if not available, directly from the specified driver and JDBC driver url. * @param driverClass the class name of JDBC driver * @param url JDBC connection URL * @param jndiNameUrl the JNDI name to look up a Data Source name service; * may be null or empty * @param connectionProperties properties for establising connection * @return a JDBC connection * @throws SQLException * @throws OdaException */ public Connection getConnection( String driverClass, String url, String jndiNameUrl, Properties connectionProperties, Collection<String> driverClassPath ) throws SQLException, OdaException { validateConnectionProperties( driverClass, url, jndiNameUrl ); if ( logger.isLoggable( Level.FINEST ) ) logger.fine( "Request JDBC Connection: driverClass=" + driverClass + //$NON-NLS-1$ "; URL=" + LogUtil.encryptURL( url )+ //$NON-NLS-1$ "; JNDI name URL=" + jndiNameUrl ); //$NON-NLS-1$ return doConnect( driverClass, url, jndiNameUrl, connectionProperties, driverClassPath ); } /** * Implementation of getConnection() methods. Gets connection from either java.sql.DriverManager, * or from IConnectionFactory defined in the extension */ private Connection doConnect( String driverClass, String url, String jndiNameUrl, Properties connectionProperties, Collection<String> driverClassPath ) throws SQLException, OdaException { // JNDI should take priority when getting connection.If JNDI Data Source // URL is defined, try use name service to get connection Connection jndiDSConnection = getJndiDSConnection( driverClass, jndiNameUrl, connectionProperties ); if ( jndiDSConnection != null ) // successful return jndiDSConnection; // done IConnectionFactory factory = getDriverConnectionFactory (driverClass); Exception connFactoryEx = null; if ( factory != null ) { // Use connection factory for connection if ( logger.isLoggable( Level.FINER )) logger.finer( "Calling IConnectionFactory.getConnection. driverClass=" + driverClass + //$NON-NLS-1$ ", URL=" + LogUtil.encryptURL( url ) ); //$NON-NLS-1$ try { Connection cn = factory.getConnection( driverClass, url, connectionProperties ); return cn; } catch( Exception ex ) { // if it was an invalid authorization specification, i.e. not a driver issue, // go ahead and throw the exception if ( ex instanceof SQLException && INVALID_AUTH_SQL_STATE.equals( ((SQLException)ex).getSQLState() )) throw (SQLException) ex; connFactoryEx = ex; // track the caught exception } } // no driverinfo extension for driverClass connectionFactory // no JNDI Data Source URL defined, or // not able to get a JNDI data source connection, // use the JDBC DriverManager instead to get a JDBC connection try { loadAndRegisterDriver( driverClass, driverClassPath ); } catch( OdaException loadDriverEx ) { // no appropriate JDBC driver available, // throw the original exception thrown by IConnectionFactory, if exists if( connFactoryEx != null ) { if ( connFactoryEx instanceof SQLException ) throw (SQLException)connFactoryEx; throw new OdaException( connFactoryEx ); } throw loadDriverEx; } if ( logger.isLoggable( Level.FINER )) logger.finer( "Calling DriverManager to connect; URL=" + LogUtil.encryptURL( url ) ); //$NON-NLS-1$ try { Driver driver = DriverManager.getDriver( url ); if( driver != null ) return driver.connect( url, connectionProperties ); } catch ( SQLException e1 ) { // first try to identify if it was due to invalid authorization spec. if( INVALID_AUTH_SQL_STATE.equals( e1.getSQLState() )) throw e1; } try { return DriverManager.getConnection( url, connectionProperties ); } catch ( SQLException e ) { try { //Important! Don't Change me. see 46956. DriverClassLoader dl = new DriverClassLoader( driverClassPath, Thread.currentThread().getContextClassLoader() ); Class dc = dl.loadClass( driverClass ); if( dc!= null ) return ((Driver)dc.newInstance()).connect(url, connectionProperties); throw new JDBCException(ResourceConstants.CONN_GET_ERROR, null, truncate(e.getLocalizedMessage())); } catch (Exception e1) { throw new JDBCException(ResourceConstants.CONN_GET_ERROR, null, truncate(e.getLocalizedMessage())); } } } /** * * @param message * @return */ private String truncate( String message ) { if ( message == null ) return null; if ( message.length( ) > MAX_MSG_LENGTH ) { int maxLength = MAX_MSG_LENGTH + MAX_WORD_LENGTH; if ( maxLength > message.length( ) ) { maxLength = message.length( ); } boolean findBoundary = false; int i = MAX_MSG_LENGTH; for ( ; !findBoundary && i < maxLength; i++ ) { char c = message.charAt( i ); switch ( c ) { case ' ' : findBoundary = true; break; case '\t': findBoundary = true; break; case '.' : findBoundary = true; break; case ',' : findBoundary = true; break; case ':' : findBoundary = true; break; case ';' : findBoundary = true; break; } } message = message.substring( 0, i ) + " ..."; //$NON-NLS-1$ } return message; } /** * Obtain a JDBC connection from a Data Source connection factory * via the specified JNDI name service. * May return null if no JNDI Name URL is specified, or not able to obtain * a connection from the JNDI name service. */ private Connection getJndiDSConnection( String driverClass, String jndiNameUrl, Properties connectionProperties ) { if ( jndiNameUrl == null || jndiNameUrl.length() == 0 ) return null; // no JNDI Data Source URL defined if ( logger.isLoggable( Level.FINER )) logger.finer( "Calling getJndiDSConnection: JNDI name URL=" + jndiNameUrl ); //$NON-NLS-1$ IConnectionFactory factory = new JndiDataSource(); Connection jndiDSConnection = null; try { jndiDSConnection = factory.getConnection( driverClass, jndiNameUrl, connectionProperties ); } catch( SQLException e ) { // log and ignore exception if ( logger.isLoggable( Level.FINE )) logger.info( "getJndiDSConnection: Unable to get JNDI data source connection; " + e.toString() ); //$NON-NLS-1$ } return jndiDSConnection; } /** * Adds the specified user name and password to the * specified collection as Jdbc driver properties. * Creates a new collection if none is specified. */ static Properties addUserAuthenticationProperties( Properties connProps, String user, String password ) { if ( connProps == null ) connProps = new Properties( ); if ( user != null ) connProps.setProperty( JDBC_USER_PROP_NAME, user ); if ( password != null ) connProps.setProperty( JDBC_PASSWORD_PROP_NAME, password ); return connProps; } /** * Validate the driver class name, URL & Jndi properties. * * @param url * @param jndiNameUrl */ private void validateConnectionProperties( String driverClass, String url, String jndiNameUrl ) { if ( isBlank( jndiNameUrl) && isBlank( driverClass ) ) throw new NullPointerException( this.resourceHandle.getMessage( ResourceConstants.EMPTYDRIVERCLASS ) ); if ( isBlank( url ) && isBlank( jndiNameUrl ) ) throw new NullPointerException( this.resourceHandle.getMessage( ResourceConstants.MISSEDURLANDJNDI ) ); } /** * * @param url * @return */ private boolean isBlank(String url) { return url == null || url.trim().toString().length() == 0; } public IDriver getDriver( String extensionId ) throws OdaException { IDriver driver = null; try { ExtensionManifest ex = ManifestExplorer.getInstance( ).getExtensionManifest( extensionId ); if( ex!= null && ex.getDataSourceElement().getAttribute( "driverClass" )!= null ) driver = (IDriver) ex.getDataSourceElement( ).createExecutableExtension( "driverClass" ); } catch ( Exception e) { //Ignore exception as we can still continue with the OdaJdbcDriver. if ( logger.isLoggable( Level.FINER )) logger.finer( "Failed to load driver from extension:" + extensionId ); } if( driver == null ) driver = new OdaJdbcDriver(); return driver; } /** * Searches extension registry for connection factory defined for driverClass. Returns an * instance of the factory if there is a connection factory for the driver class. Returns null * otherwise. */ public IConnectionFactory getDriverConnectionFactory( String driverClass ) throws OdaException { loadDriverExtensions(); IConnectionFactory factory = null; Object driverInfo = null; synchronized ( driverExtensions ) { if ( driverClass != null ) driverInfo = driverExtensions.get( driverClass ); if ( driverInfo != null ) { // Driver has own connection factory; use it if ( driverInfo instanceof IConfigurationElement ) { // connectionFactory not yet created; do it now String factoryClass = ( (IConfigurationElement) driverInfo ).getAttribute( OdaJdbcDriver.Constants.DRIVER_INFO_ATTR_CONNFACTORY ); try { factory = (IConnectionFactory) ( (IConfigurationElement) driverInfo ).createExecutableExtension( OdaJdbcDriver.Constants.DRIVER_INFO_ATTR_CONNFACTORY ); logger.fine( "Created connection factory class " //$NON-NLS-1$ + factoryClass + " for driverClass " //$NON-NLS-1$ + driverClass ); } catch ( CoreException e ) { JDBCException ex = new JDBCException( ResourceConstants.CANNOT_INSTANTIATE_FACTORY, null, new Object[]{ factoryClass, driverClass } ); logger.log( Level.WARNING, "Failed to instantiate connection factory for driverClass " //$NON-NLS-1$ + driverClass, ex ); throw ex; } assert ( factory != null ); // Cache factory instance driverExtensions.put( driverClass, factory ); } else { // connectionFactory already created assert driverInfo instanceof IConnectionFactory; factory = (IConnectionFactory) driverInfo; } } } return factory; } private void loadDriverExtensions() { if ( loadedDriver ) // Already loaded return; synchronized( this ) { if( loadedDriver ) return; // First time: load all driverinfo extensions driverExtensions = new HashMap(); IExtensionRegistry extReg = Platform.getExtensionRegistry(); /* * getConfigurationElementsFor is not working for server Platform. * I have to work around this by walking the extension list IConfigurationElement[] configElems = extReg.getConfigurationElementsFor( OdaJdbcDriver.Constants.DRIVER_INFO_EXTENSION ); */ IExtensionPoint extPoint = extReg.getExtensionPoint( OdaJdbcDriver.Constants.DRIVER_INFO_EXTENSION ); if ( extPoint == null ) return; IExtension[] exts = extPoint.getExtensions(); if ( exts == null ) return; for ( int e = 0; e < exts.length; e++) { IConfigurationElement[] configElems = exts[e].getConfigurationElements(); if ( configElems == null ) continue; for ( int i = 0; i < configElems.length; i++ ) { if ( configElems[i].getName().equals( OdaJdbcDriver.Constants.DRIVER_INFO_ELEM_JDBCDRIVER) ) { String driverClass = configElems[i].getAttribute( OdaJdbcDriver.Constants.DRIVER_INFO_ATTR_DRIVERCLASS ); String connectionFactory = configElems[i].getAttribute( OdaJdbcDriver.Constants.DRIVER_INFO_ATTR_CONNFACTORY ); logger.info("Found JDBC driverinfo extension: driverClass=" + driverClass + //$NON-NLS-1$ ", connectionFactory=" + connectionFactory ); //$NON-NLS-1$ if ( driverClass != null && driverClass.length() > 0 && connectionFactory != null && connectionFactory.length() > 0 ) { // This driver class has its own connection factory; cache it // Note that the instantiation of the connection factory can wait // until we actually need it driverExtensions.put( driverClass, configElems[i] ); } } } } loadedDriver = true; } } /** * The method which test whether the give connection properties can be used * to create a connection * * @param driverClassName * the name of driver class * @param connectionString * the connection URL * @param userId * the user id * @param password * the pass word * @return boolean whether could the connection being created * @throws OdaException */ public boolean testConnection( String driverClassName, String connectionString, String userId, String password ) throws OdaException { return testConnection( driverClassName, connectionString, null, userId, password ); } public boolean testConnection( String driverClassName, String connectionString, String userId, String password, Properties props ) throws OdaException { return testConnection( driverClassName, connectionString, null, userId, password, props ); } /** * Tests whether the given connection properties can be used to obtain a connection. * @param driverClassName the name of driver class * @param connectionString the JDBC driver connection URL * @param jndiNameUrl the JNDI name to look up a Data Source name service; * may be null or empty * @param userId the login user id * @param password the login password * @return true if the the specified properties are valid to obtain a connection; * false otherwise * @throws OdaException */ public boolean testConnection( String driverClassName, String connectionString, String jndiNameUrl, String userId, String password ) throws OdaException { return testConnection( driverClassName, connectionString, jndiNameUrl, userId, password, new Properties( ) ); } public boolean testConnection( String driverClassName, String connectionString, String jndiNameUrl, String userId, String password, Properties props ) throws OdaException { boolean canConnect = false; try { // If connection is provided by driverInfo extension, use it to create connection if ( getDriverConnectionFactory( driverClassName ) != null ) { tryCreateConnection( driverClassName, connectionString, userId, password, props ); return true; } // no driverinfo extension for driverClass connectionFactory // if JNDI Data Source URL is defined, try use name service to get connection if ( jndiNameUrl != null ) { Connection jndiDSConnection = getJndiDSConnection( driverClassName, jndiNameUrl, addUserAuthenticationProperties( null, userId, password ) ); if ( jndiDSConnection != null ) // test connection successful { closeConnection( jndiDSConnection ); return true; } else if ( connectionString != null && connectionString.trim( ).length( ) > 0 ) { return testConnection( driverClassName, connectionString, userId, password ); } else { throw new JDBCException( ResourceConstants.CANNOT_PARSE_JNDI, null ); } } // no JNDI Data Source URL defined, or // not able to get a JNDI data source connection, // use the JDBC DriverManager instead to get a JDBC connection loadAndRegisterDriver( driverClassName, null ); // If the connections built upon the given driver has been tested // once, // it will be add to cachedDrivers hashmap so that next time we can // directly // test the connection using specific driver rather than iterate all // available // drivers in DriverManager if ( testedDrivers.get( driverClassName ) == null ) { Driver driver = (Driver) getRegisteredDriver( driverClassName ); // The driver might be a wrapped driver. The toString() // method // of a wrapped driver is overriden // so that the name of driver being wrapped is returned. if ( isExpectedDriver( driver, driverClassName ) ) { if ( driver.acceptsURL( connectionString ) ) { testedDrivers.put( driverClassName, driver ); // if connection can be built then the test // connection // succeed. Otherwise Exception would be thrown. The // source // of the exception is tryCreateConnection( driverClassName, connectionString, userId, password, props ); canConnect = true; } } // If the test url can be accepted by DriverManager (because the // driver which can pass // that url has been registered.) but a connection // cannot be built using driver whose name is given, throw a // exception. if ( !canConnect ) throw new JDBCException( ResourceConstants.CANNOT_PARSE_URL, null ); } else { if ( ( (Driver) this.testedDrivers.get( driverClassName ) ).acceptsURL( connectionString ) ) { tryCreateConnection( driverClassName, connectionString, userId, password, props ); canConnect = true; } } } catch ( SQLException e ) { throw new JDBCException( ResourceConstants.TEST_CONNECTION_FAIL, e ); } catch( RuntimeException e ) { OdaException ex = new OdaException( e.getLocalizedMessage( ) ); ex.initCause( e ); throw ex; } // If the given url cannot be parsed. if ( canConnect == false ) throw new JDBCException( ResourceConstants.NO_SUITABLE_DRIVER, null ); return true; } private void closeConnection( Connection conn ) { if ( conn == null ) return; // nothing to close try { conn.close(); } catch( SQLException e ) { /* ok to ignore */ } } private boolean isExpectedDriver( Driver driver, String className ) { String actual; if ( driver instanceof WrappedDriver ) actual = driver.toString(); else actual = driver.getClass( ).getName( ); return isExpectedDriverClass( actual, className); } private boolean isExpectedDriverClass( String actual, String expected) { // Normally, a driver class registers itself with DriverManager // when it is loaded. However, at least one driver (Derby Embedded) // registers a different driver class with DriverManager (Driver30) than the // documented driver class (EmbeddedDriver). We have to relaxed // the rules here to determin if driver is registered by className. // As long as driver's class and className has same package name // we consider them compatible. // Not a perfect solution but so far works with drivers we've tested String actualPkg = actual.substring(0, actual.lastIndexOf('.') ); String expectedPkg = expected.substring(0, expected.lastIndexOf('.') ); return actualPkg.equals( expectedPkg ); } /** * Try to create a connection based on given connection properties. * @param driverClassName * @param connectionString * @param userId * @param password * @throws SQLException * @throws OdaException */ private void tryCreateConnection( String driverClassName, String connectionString, String userId, String password, Properties props ) throws SQLException, OdaException { Connection testConn = this.getConnection( driverClassName, connectionString, userId, password, null, props ); assert ( testConn != null ); closeConnection( testConn ); } /** * Look for the Driver from drivers directory if it not in plugin class path * * @param className * @return Driver instance * @throws OdaException */ private Driver findDriver( String className, Collection<String> driverClassPath, boolean refresh ) throws OdaException { Class driverClass = null; try { driverClass = Class.forName( className ); // Driver class in class path logger.info( "Loaded JDBC driver class in class path: " + className ); //$NON-NLS-1$ } catch ( ClassNotFoundException e ) { if ( logger.isLoggable( Level.FINE ) ) { logger.info( "Driver class not in class path: " //$NON-NLS-1$ + className + ". Trying to locate driver in drivers directory" ); //$NON-NLS-1$ } // Driver not in plugin class path; find it in drivers directory driverClass = loadExtraDriver( className, true, refresh, driverClassPath ); // if driver class still cannot be found, if ( driverClass == null ) { ClassLoader loader = Thread.currentThread( ).getContextClassLoader( ); if ( loader != null ) { try { driverClass = Class.forName( className, true, loader ); } catch ( ClassNotFoundException e1 ) { driverClass = null; } } } } if ( driverClass == null ) { logger.warning( "Failed to load JDBC driver class: " + className ); //$NON-NLS-1$ throw new JDBCException( ResourceConstants.CANNOT_LOAD_DRIVER, null, className ); } Driver driver = null; try { driver = this.getDriverInstance( driverClass, refresh ); } catch ( Exception e ) { logger.log( Level.WARNING, "Failed to create new instance of JDBC driver:" + className, e); //$NON-NLS-1$ throw new JDBCException( ResourceConstants.CANNOT_INSTANTIATE_DRIVER, null, className ); } return driver; } /** * Deregister the driver by the given class name from DriverManager * * @param className * @return true if deregister the driver successfully * @throws OdaException */ public boolean deregisterDriver( String className ) throws OdaException { if ( className == null || className.length() == 0) // no driver class; assume class already deregistered return false; Driver driver = getRegisteredDriver( className ); if ( driver == null ) return false; if ( driver != null ) { try { if (logger.isLoggable(Level.FINER)) logger.finer("Registering with DriverManager: wrapped driver for " + className ); //$NON-NLS-1$ synchronized( registeredDrivers ) { registeredDrivers.remove( className ); DriverManager.deregisterDriver( driver ); } cachedJdbcDrivers.remove( className ); testedDrivers.remove( className ); } catch ( SQLException e) { // This shouldn't happen logger.log( Level.WARNING, "Failed to deRegister wrapped driver instance.", e); //$NON-NLS-1$ } } return true; } public void loadAndRegisterDriver( String className, Collection<String> driverClassPath ) throws OdaException { if ( className == null || className.length() == 0) // no driver class; assume class already loaded return; if ( isDriverRegistered( className ) ) return; if ( logger.isLoggable( Level.FINEST )) { logger.info( "Loading JDBC driver class: " + className ); //$NON-NLS-1$ } try { loadAndRegisterDriver( className, driverClassPath, false ); } catch ( JDBCException ex ) { // Try a refresh load. loadAndRegisterDriver( className, driverClassPath, true ); } } private boolean isDriverRegistered( String className ) { synchronized( registeredDrivers ) { return registeredDrivers.containsKey( className ); } } private Driver getRegisteredDriver( String className ) { synchronized( registeredDrivers ) { return registeredDrivers.get( className ); } } private void loadAndRegisterDriver( String className, Collection<String> driverClassPath, boolean refreshClassLoader ) throws OdaException { Driver driver = findDriver( className, driverClassPath, refreshClassLoader ); registerDriver( driver, className ); } /** * If driver is found in the drivers directory, its class is not accessible * in this class's ClassLoader. DriverManager will not allow this class to create * connections using such driver. To solve the problem, we create a wrapper Driver in * our class loader, and register it with DriverManager * * @param className * @param driverClassPath * @param refreshClassLoader * @throws OdaException */ private void registerDriver( Driver driver, String className ) { assert driver != null; try { if (logger.isLoggable(Level.FINER)) logger.finer("Registering with DriverManager: wrapped driver for " + className ); //$NON-NLS-1$ synchronized ( registeredDrivers ) { DriverManager.registerDriver( driver ); registeredDrivers.put( className, driver ); } } catch ( SQLException e ) { // This shouldn't happen logger.log( Level.WARNING, "Failed to register wrapped driver instance from DriverManager.", e); //$NON-NLS-1$ } } /** * Search driver in the "drivers" directory and load it if found * @param className * @return * @throws OdaException * @throws DriverException * @throws OdaException */ private Class loadExtraDriver(String className, boolean refreshUrlsWhenFail, boolean refreshClassLoader, Collection<String> driverClassPath) throws OdaException { assert className != null; if ( extraDriverLoader == null || refreshClassLoader ) { if( extraDriverLoader!= null ) { synchronized( registeredDrivers ) { for ( Map.Entry<String, Driver> e : registeredDrivers.entrySet( ) ) { try { DriverManager.deregisterDriver( e.getValue( ) ); } catch ( SQLException ignore ) { logger.log( Level.WARNING, "Failed to deregister wrapped driver instance from DriverManager.", ignore ); //$NON-NLS-1$ } } registeredDrivers.clear( ); testedDrivers.clear( ); cachedJdbcDrivers.clear( ); extraDriverLoader.close( ); } } extraDriverLoader = new DriverClassLoader( driverClassPath, null ); } try { return Class.forName( className, true, extraDriverLoader ); } catch ( ClassNotFoundException e ) { logger.log( Level.SEVERE, "DriverClassLoader failed to load class: " + className, e ); //$NON-NLS-1$ logger.log( Level.SEVERE, "refreshUrlsWhenFail: " + refreshUrlsWhenFail); //$NON-NLS-1$ logger.log( Level.SEVERE, "driverClassPath: " + driverClassPath); //$NON-NLS-1$ StringBuffer sb = new StringBuffer(); for (URL url : extraDriverLoader.getURLs( )) { sb.append( "[" ).append( url ).append( "]" ); //$NON-NLS-1$ //$NON-NLS-2$ } logger.log( Level.SEVERE, "Registered URLs: " + sb.toString( ) ); //$NON-NLS-1$ //re-scan the driver directory. This re-scan is added for users would potentially //set their own jdbc drivers, which would be copied to driver directory as well if( refreshUrlsWhenFail && extraDriverLoader.refreshURLs() ) { // New driver found; try loading again return loadExtraDriver( className, false, false, driverClassPath ); } // no new driver found; give up logger.log( Level.FINER, "Driver class not found in drivers directory: " + className ); //$NON-NLS-1$ return null; } } private static class DriverClassLoader extends URLClassLoader { private HashSet fileSet = new HashSet(); private Collection<String> driverClassPath; public DriverClassLoader( Collection<String> driverClassPath, ClassLoader parent ) throws OdaException { super( new URL[0], parent != null ? parent:DriverClassLoader.class.getClassLoader() ); logger.entering( DriverClassLoader.class.getName(), "constructor()" ); //$NON-NLS-1$ this.driverClassPath = driverClassPath; refreshURLs(); } protected PermissionCollection getPermissions( CodeSource codesource ) { return this.getClass( ).getProtectionDomain( ).getPermissions( ); } /** * Refresh the URL list of DriverClassLoader * @return if the refreshURL is different than the former one then return true otherwise * return false * @throws OdaException */ public boolean refreshURLs() throws OdaException { boolean foundNewUnderSpecifiedDIR = refreshFileURLsUnderSpecifiedDIR( ); boolean foundNewUnderDefaultDIR = refreshFileURLsUnderDefaultDIR( ); return foundNewUnderSpecifiedDIR || foundNewUnderDefaultDIR; } private boolean refreshFileURLsUnderSpecifiedDIR( ) throws OdaException { boolean hasNewDriver = false; if ( driverClassPath != null && driverClassPath.size( ) > 0 ) { for ( String classPath : driverClassPath ) { if ( refreshFileURL( classPath ) ) { hasNewDriver = true; } } } return hasNewDriver; } private boolean refreshFileURL( String classPath ) { File driverClassFile = new File( classPath ); if ( !driverClassFile.exists( ) ) { return false; } boolean hasNewDriver = false; try { this.addURL( driverClassFile.toURI( ).toURL( ) ); } catch ( MalformedURLException ex ) { } if ( driverClassFile.isDirectory( ) ) { File[] driverFiles = driverClassFile .listFiles( new FileFilter( ) { public boolean accept( File pathname ) { if ( pathname.isFile( ) && OdaJdbcDriver.isDriverFile( pathname .getName( ) ) ) { return true; } return false; } } ); for ( File driverFile : driverFiles ) { String fileName = driverFile.getName( ); if ( !fileSet.contains( fileName ) ) { fileSet.add( fileName ); try { hasNewDriver = true; URL driverUrl = driverFile.toURI( ).toURL( ); addURL( driverUrl ); logger.info( "JDBCDriverManager: found JAR file " //$NON-NLS-1$ + fileName + ". URL=" + driverUrl ); //$NON-NLS-1$ } catch ( MalformedURLException ex ) { } } } } return hasNewDriver; } private boolean refreshFileURLsUnderDefaultDIR( ) throws OdaException { try { URL url = PluginResourceLocator.getPluginEntry( "org.eclipse.birt.report.data.oda.jdbc", //$NON-NLS-1$ OdaJdbcDriver.Constants.DRIVER_DIRECTORY ); if ( url != null ) { url = PluginResourceLocator.resolve( url ); if ( url != null ) { if ( "file".equals( url.getProtocol( ) ) ) { String driverFolder = url.getFile( ); return refreshFileURL( driverFolder ); } } } return false; } catch ( IOException ex ) { throw new OdaException( ex ); } } } // The classloader of a driver (jtds driver, etc.) is // "java.net.FactoryURLClassLoader", whose parent is // "sun.misc.Launcher$AppClassLoader". // The classloader of class Connection (the caller of // DriverManager.getConnection(url, props)) is // "sun.misc.Launcher$AppClassLoader". As the classes loaded by a child // classloader are always not visible to its parent classloader, // DriverManager.getConnection(url, props), called by class Connection, actually // has no access to driver classes, which are loaded by // "java.net.FactoryURLClassLoader". The invoking of this method would return a // "no suitable driver" exception. // On the other hand, if we use class WrappedDriver to wrap drivers. The DriverExt // class is loaded by "sun.misc.Launcher$AppClassLoader", which is same as the // classloader of Connection class. So DriverExt class is visible to // DriverManager.getConnection(url, props). And the invoking of the very method // would success. private static class WrappedDriver implements Driver { private Driver driver; private String driverClass; WrappedDriver( Driver d, String driverClass ) { logger.entering( WrappedDriver.class.getName(), "WrappedDriver", driverClass ); //$NON-NLS-1$ this.driver = d; this.driverClass = driverClass; } /* * @see java.sql.Driver#acceptsURL(java.lang.String) */ public boolean acceptsURL( String u ) throws SQLException { boolean res = this.driver.acceptsURL( u ); if ( logger.isLoggable( Level.FINER )) logger.log( Level.FINER, "WrappedDriver(" + driverClass + //$NON-NLS-1$ ").acceptsURL(" + LogUtil.encryptURL( u )+ ")returns: " + res); //$NON-NLS-1$//$NON-NLS-2$ return res; } /* * @see java.sql.Driver#connect(java.lang.String, java.util.Properties) */ public java.sql.Connection connect( String u, Properties p ) throws SQLException { logger.entering( WrappedDriver.class.getName() + ":" + driverClass, //$NON-NLS-1$ "connect", LogUtil.encryptURL( u ) ); //$NON-NLS-1$ try { return this.driver.connect( u, p ); } catch ( RuntimeException e ) { throw new SQLException( e.getMessage( ) ); } } /* * @see java.sql.Driver#getMajorVersion() */ public int getMajorVersion( ) { return this.driver.getMajorVersion( ); } /* * @see java.sql.Driver#getMinorVersion() */ public int getMinorVersion( ) { return this.driver.getMinorVersion( ); } /* * @see java.sql.Driver#getPropertyInfo(java.lang.String, java.util.Properties) */ public DriverPropertyInfo[] getPropertyInfo( String u, Properties p ) throws SQLException { return this.driver.getPropertyInfo( u, p ); } /* * @see java.sql.Driver#jdbcCompliant() */ public boolean jdbcCompliant( ) { return this.driver.jdbcCompliant( ); } /* * @see java.lang.Object#toString() */ public String toString( ) { return driverClass; } } }
package hu.elte.txtuml.export.plantuml.seqdiag; import org.eclipse.jdt.core.dom.ASTNode; import org.eclipse.jdt.core.dom.Expression; import org.eclipse.jdt.core.dom.MethodInvocation; import hu.elte.txtuml.export.plantuml.generator.PlantUmlCompiler; /** * Exporter implementation, which is responsible for exporting the message * sending from the SequenceDiagrams ({@code Sequence.send()} and * {@code Sequence.fromActor()}) */ public class SequenceExporter extends MethodInvocationExporter { public SequenceExporter(final PlantUmlCompiler compiler) { super(compiler); } @Override public boolean validElement(ASTNode curElement) { if (super.validElement(curElement)) { String fullName = ExporterUtils.getFullyQualifiedName((MethodInvocation) curElement); return fullName.equals("hu.elte.txtuml.api.model.seqdiag.Sequence.send") || fullName.equals("hu.elte.txtuml.api.model.seqdiag.Sequence.fromActor"); } return false; } @Override public boolean preNext(MethodInvocation curElement) { // Sequence.fromActor call if (curElement.arguments().size() == 2) { Expression target = (Expression) curElement.arguments().get(1); String targetName = target.toString(); compiler.activateLifeline(targetName); return true; } // Sequence.send call Expression sender = (Expression) curElement.arguments().get(0); String senderName = sender.toString(); Expression target = (Expression) curElement.arguments().get(2); String targetName = target.toString(); Expression signal = (Expression) curElement.arguments().get(1); String signalExpr = signal.resolveTypeBinding().getQualifiedName(); compiler.println(senderName + "->" + targetName + " : " + signalExpr); compiler.activateLifeline(senderName); compiler.activateLifeline(targetName); return true; } @Override public void afterNext(MethodInvocation curElement) { } }
package pl.edu.icm.coansys.disambiguation.author.pig; import java.io.IOException; import java.util.LinkedList; import java.util.List; import java.util.Map; import org.apache.pig.EvalFunc; import org.apache.pig.data.DataType; import org.apache.pig.data.Tuple; import org.apache.pig.data.TupleFactory; import org.apache.pig.impl.logicalLayer.FrontendException; import org.apache.pig.impl.logicalLayer.schema.Schema; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import pl.edu.icm.coansys.disambiguation.author.features.disambiguators.DisambiguatorFactory; import pl.edu.icm.coansys.disambiguation.features.Disambiguator; import pl.edu.icm.coansys.disambiguation.features.FeatureInfo; /** * Flow (constructor and exec method) similar to ExhaustiveAND * * @author pdendek * */ public class SvmMaxValPairsCreator extends EvalFunc<Tuple> { private static final Logger logger = LoggerFactory.getLogger(SvmMaxValPairsCreator.class); @Override public Schema outputSchema(Schema p_input) { try { return Schema.generateNestedSchema(DataType.TUPLE); } catch (FrontendException e) { logger.error("Error in creating output schema:", e); throw new IllegalStateException(e); } } private PigDisambiguator[] features; private FeatureInfo[] featureInfos; public SvmMaxValPairsCreator(String featureDescription){ List<FeatureInfo> FIwithEmpties = FeatureInfo.parseFeatureInfoString(featureDescription); List<FeatureInfo> FIFinall = new LinkedList<FeatureInfo>(); List<PigDisambiguator> FeaturesFinall = new LinkedList<PigDisambiguator>(); DisambiguatorFactory ff = new DisambiguatorFactory(); Disambiguator d; //separate features which are fully described and able to use for ( FeatureInfo fi : FIwithEmpties ){ if ( fi.getDisambiguatorName().equals("") ) continue; if ( fi.getFeatureExtractorName().equals("") ) continue; d = ff.create(fi); if ( d == null ) continue; FIFinall.add( fi ); FeaturesFinall.add( new PigDisambiguator( d ) ); } this.featureInfos = FIFinall.toArray( new FeatureInfo[ FIFinall.size() ] ); this.features = FeaturesFinall.toArray( new PigDisambiguator[ FIFinall.size() ] ); } @SuppressWarnings("unchecked") @Override public Tuple exec(Tuple tuple) throws IOException { String c1 = (String) tuple.get(0);//cId1 //tuple.get(1);//sname Map<String, Object> m1 = (Map<String, Object>) tuple.get(2);//map1 String c2 = (String) tuple.get(3);//cId2 //tuple.get(4);//sname Map<String, Object> m2 = (Map<String, Object>) tuple.get(5);//map2 int[] a = new int[features.length+2]; for ( int d = 0; d < features.length; d++ ){ Object oA = m1.get( featureInfos[d].getFeatureExtractorName() ); Object oB = m2.get( featureInfos[d].getFeatureExtractorName() ); if ( oA == null || oB == null ) a[d]=0; a[d] = (int)features[d].calculateAffinity( oA, oB ); } if(a[a.length-1]==0){ a[a.length-1]=-1; } Tuple t = TupleFactory.getInstance().newTuple(); t.append(c1); t.append(c2); for(int e : a){ t.append(e); } return t; } }
package com.xpn.xwiki.it.selenium; import com.xpn.xwiki.it.selenium.framework.AbstractXWikiTestCase; import com.xpn.xwiki.it.selenium.framework.AlbatrossSkinExecutor; import com.xpn.xwiki.it.selenium.framework.XWikiTestSuite; import junit.framework.Test; /** * Verify the Users, Groups and Rights Management features of XWiki. * * @version $Id: $ */ public class UsersGroupsRightsManagementTest extends AbstractXWikiTestCase { public static Test suite() { XWikiTestSuite suite = new XWikiTestSuite("Verify the Users, Groups and Rights Management features of XWiki"); suite.addTestSuite(UsersGroupsRightsManagementTest.class, AlbatrossSkinExecutor.class); return suite; } protected void setUp() throws Exception { super.setUp(); loginAsAdmin(); } /** * <ul> * <li>Validate group creation.</li> * <li>Validate groups administration print "0" members for empty group.</li> * <li>Validate group deletion.</li> * <li>Validate rights automatically cleaned from deleted groups.</li> * </ul> */ public void testCreateAndDeleteGroup() { clickLinkWithText("Administration"); clickLinkWithText("Groups"); clickLinkWithText("Add new group", false); // Wait for lightbox getSelenium().waitForCondition("selenium.page().bodyText().indexOf('Create new group') != -1;", "2000"); setFieldValue("newgroupi", "NewGroup"); getSelenium().click("//input[@value='Create group']"); getSelenium().waitForPageToLoad("10000"); // Validate that group has been created. assertTextPresent("NewGroup"); // Validate XWIKI-1903: New UI - Empty group shows 1 member. assertEquals("Group NewGroup which is empty print more than 0 members", "0", getSelenium().getText("//tbody/tr[td/a=\"NewGroup\"]/td[2]")); // Give "view" global right to NewGroup on wiki clickLinkWithText("Global Rights"); getSelenium().click("uorg"); getSelenium().click("//tbody/tr[td/a=\"NewGroup\"]/td[2]/img"); // Give "comment" right to NewGroup on Main.WebHome page open("/xwiki/bin/view/Main/WebHome"); clickLinkWithText("Page access rights"); getSelenium().click("uorg"); getSelenium().click("//tbody/tr[td/a=\"NewGroup\"]/td[3]/img"); // Delete the newly created group and see if rights are cleaned // FIXME : find a way to delete user using groups administration. See // #testCreateAndDeleteUser() for more. open("/xwiki/bin/view/XWiki/NewGroup"); clickDeletePage(); clickLinkWithLocator("//input[@value='yes']"); // Validate XWIKI-2304: When a user or a group is removed it's not removed from rights // objects open("/xwiki/bin/edit/XWiki/XWikiPreferences?editor=object"); assertTextNotPresent("NewGroup"); open("/xwiki/bin/edit/Main/WebHome?editor=object"); assertTextNotPresent("NewGroup"); } /** * Validate that administration show error when trying to create an existing group. */ public void testCreateAnExistingGroup() { clickLinkWithText("Administration"); clickLinkWithText("Groups"); clickLinkWithText("Add new group", false); // Wait for lightbox getSelenium().waitForCondition("selenium.page().bodyText().indexOf('Create new group') != -1;", "2000"); setFieldValue("newgroupi", "Admin"); getSelenium().click("//input[@value='Create group']"); getSelenium().setSpeed("1000"); assertEquals( "Admin cannot be used for the group name, as another document with this name already exists.", this.getSelenium().getAlert()); } /** * <ul> * <li>Validate user creation.</li> * <li>Validate user deletion.</li> * <li>Validate groups automatically cleaned from deleted users.</li> * </ul> */ public void testCreateAndDeleteUser() { // Create the new user clickLinkWithText("Administration"); clickLinkWithText("Users"); clickLinkWithText("Add new user", false); // Wait for lightbox getSelenium().waitForCondition("selenium.page().bodyText().indexOf('Registration') != -1;", "2000"); setFieldValue("register_first_name", "New"); setFieldValue("register_last_name", "User"); setFieldValue("xwikiname", "NewUser"); setFieldValue("register_password", "NewUser"); setFieldValue("register2_password", "NewUser"); setFieldValue("register_email", "new.user@xwiki.org"); getSelenium().click("//input[@value='Save']"); waitPage(); // Verify that the user is present in the table assertTextPresent("NewUser"); // Verify that new users are automatically added to the XWikiAllGroup group. open("/xwiki/bin/view/XWiki/XWikiAllGroup"); assertTextPresent("XWiki.NewUser"); // Delete the newly created user and see if groups are cleaned // FIXME: this is the code that should be use to delete a user but I can't makes it works // (the popup does not show up) // clickLinkWithText("Administration"); // clickLinkWithText("Users"); // getSelenium().chooseOkOnNextConfirmation(); // open("/xwiki/bin/admin/XWiki/XWikiUsers?editor=users&space=XWiki"); // getSelenium().click("//tbody/tr[td/a=\"NewUser\"]/td/img[@title='Delete']"); // FIXME: find a way to delete user using users administration. See previous commented // code. open("/xwiki/bin/view/XWiki/NewUser"); clickDeletePage(); clickLinkWithLocator("//input[@value='yes']"); // Verify that when a user is removed he's removed from the groups he belongs to. open("/xwiki/bin/view/XWiki/XWikiAllGroup"); assertTextNotPresent("XWiki.NewUser"); } }
package org.apache.mesos.elasticsearch.executor.elasticsearch; import com.jayway.awaitility.Awaitility; import com.mashape.unirest.http.Unirest; import com.mashape.unirest.http.exceptions.UnirestException; import org.apache.log4j.Logger; import org.apache.mesos.elasticsearch.common.cli.ElasticsearchCLIParameter; import org.apache.mesos.elasticsearch.executor.Configuration; import org.apache.mesos.elasticsearch.executor.model.PortsModel; import org.elasticsearch.action.ActionFuture; import org.elasticsearch.action.admin.cluster.state.ClusterStateRequest; import org.elasticsearch.action.admin.cluster.state.ClusterStateResponse; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.node.Node; import org.elasticsearch.node.NodeBuilder; import org.junit.Test; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.function.Consumer; import static org.junit.Assert.*; import static org.mockito.Mockito.*; /** * Tests that ES node can be launched using provided settings. */ @SuppressWarnings({"PMD.TooManyMethods"}) public class ElasticsearchLauncherTest { private static final Logger LOG = Logger.getLogger(ElasticsearchLauncherTest.class); public static final String PATH_HOME = "path.home"; public static final String GITHUB_YML_URL = "https://raw.githubusercontent.com/mesos/elasticsearch/master/executor/src/main/resources/elasticsearch.yml"; @Test(expected = NullPointerException.class) public void shouldExceptionIfNullSettings() { new ElasticsearchLauncher(null); } @Test public void shouldLaunchWithDefaultSettings() throws InterruptedException, UnirestException, ExecutionException { Settings.Builder settings = Settings.builder() .put("node.local", true) .put("path.data", ".") .put(PATH_HOME, "."); ElasticsearchLauncher elasticsearchLauncher = new ElasticsearchLauncher(settings); safeStartAndShutdownNode(elasticsearchLauncher, nodeConsumer(9200)); } @Test public void shouldShutdownNode() { Node node = NodeBuilder.nodeBuilder().settings(Settings.settingsBuilder().put(PATH_HOME, ".").build()).node(); node.close(); assertTrue(node.isClosed()); } @Test public void shouldLaunchWithRunTimeSettings() throws InterruptedException, ExecutionException, UnirestException { Settings.Builder settings = Settings.builder() .put("node.local", true) .put("path.data", ".") .put(PATH_HOME, "."); ElasticsearchLauncher elasticsearchLauncher = new ElasticsearchLauncher(settings); Integer port = 1234; elasticsearchLauncher.addRuntimeSettings(clientPortSetting(port)); safeStartAndShutdownNode(elasticsearchLauncher, nodeConsumer(port)); } @Test public void shouldBeAbleToAddRunTimeSettings() { // Given settings Settings.Builder settings = mock(Settings.Builder.class); Launcher launcher = new ElasticsearchLauncher(settings); // When add runtime Settings.Builder runtimeSettings = spy(clientPortSetting(1234)); launcher.addRuntimeSettings(runtimeSettings); // Ensure settings are updated verify(settings, times(1)).put(runtimeSettings.build()); } @Test public void shouldBeAbleToLoadSettingsFromResources() { Configuration configuration = new Configuration(new String[]{""}); Settings.Builder esSettings = configuration.getDefaultESSettings(); assertNotNull(esSettings); } @Test public void shouldBeAbleToOverrideDefaults() { Configuration configuration = new Configuration(new String[]{""}); Settings.Builder esSettings = configuration.getDefaultESSettings(); assertNotNull(esSettings); String value = esSettings.get(PATH_HOME); assertFalse(value.isEmpty()); final String testValue = "test"; esSettings.put(PATH_HOME, testValue); assertEquals(testValue, esSettings.get(PATH_HOME)); } @Test public void shouldBeAbleToLoadSettingsFromFile() throws IOException { // Create temp file Path tempFile = Files.createTempFile("elasticsearchTest", ".yml"); Settings.Builder esSettings; try { Configuration configuration = new Configuration(new String[]{ElasticsearchCLIParameter.ELASTICSEARCH_SETTINGS_LOCATION, tempFile.toString()}); esSettings = configuration.getUserESSettings(); } finally { Files.delete(tempFile); } assertNotNull(esSettings); } @Test public void shouldLoadSettingsFromURL() { Configuration configuration = new Configuration(new String[]{ElasticsearchCLIParameter.ELASTICSEARCH_SETTINGS_LOCATION, GITHUB_YML_URL}); assertNotNull(configuration.getUserESSettings()); } private Settings.Builder clientPortSetting(Integer http) { return Settings.settingsBuilder().put(PortsModel.HTTP_PORT_KEY, http); } public Consumer<Node> nodeConsumer(Integer port) throws InterruptedException, ExecutionException, UnirestException { return node -> { try { debugNodeInfo(node); assertStarted(port); } catch (InterruptedException | ExecutionException | UnirestException e) { e.printStackTrace(); } }; } public void safeStartAndShutdownNode(ElasticsearchLauncher launcher, Consumer<Node> function) throws InterruptedException { Node node = launcher.launch(); try { function.accept(node); } finally { if (node != null) { node.close(); Awaitility.await().pollInterval(1L, TimeUnit.SECONDS).atMost(30L, TimeUnit.SECONDS).until(node::isClosed); assertTrue("Node did not close properly. Check ps -ax for rouge elasticsearch processes.", node.isClosed()); } } } public void debugNodeInfo(Node node) throws InterruptedException, ExecutionException { node.settings().getAsMap().forEach((s, s2) -> LOG.debug(s + " = " + s2)); LOG.debug(node.isClosed()); ActionFuture<ClusterStateResponse> state = node.client().admin().cluster().state(new ClusterStateRequest()); LOG.debug(state.get().getState().prettyPrint()); } public void assertStarted(Integer port) throws UnirestException { waitForStart(port); LOG.debug(Unirest.get("http://127.0.0.1:" + port).asString().getBody()); assertEquals(200, Unirest.get("http://127.0.0.1:" + port).asJson().getStatus()); } public void waitForStart(Integer port) { Awaitility.await().pollInterval(1L, TimeUnit.SECONDS).atMost(30L, TimeUnit.SECONDS).until(() -> { try { return Unirest.get("http://127.0.0.1:" + port).asJson().getStatus() == 200; } catch (UnirestException e) { return false; } }); } }
package de.roamingthings.expenses.ui.expense.controller; import de.roamingthings.expenses.business.expense.domain.RecurringExpense; import de.roamingthings.expenses.business.expense.service.RecurringExpenseService; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.*; import javax.validation.Valid; import java.time.LocalDate; /** * @author Alexander Sparkowsky [info@roamingthings.de] * @version 2017/04/15 */ @Controller @RequestMapping("/recurring_expenses") public class RecurringExpenseController { private RecurringExpenseService recurringExpenseService; public RecurringExpenseController(RecurringExpenseService recurringExpenseService) { this.recurringExpenseService = recurringExpenseService; } @RequestMapping(method = RequestMethod.GET) public String listRecurringExpenses(Model model) { final Iterable<RecurringExpense> recurringExpenseList = recurringExpenseService.findAllRecurringExpenseSummaries(); model.addAttribute("recurringExpenseList", recurringExpenseList); return "recurring_expenses/list"; } @RequestMapping(method = RequestMethod.POST) public String updateRecurringExpenses(@Valid @ModelAttribute RecurringExpense formExpenseModel, BindingResult bindingResult) { if (bindingResult.hasErrors()) { return "recurring_expenses/recurring_expenses_form"; } if (formExpenseModel.getId() != null) { final RecurringExpense currentRecurringExpense = recurringExpenseService.findRecurringExpense(formExpenseModel.getId()); currentRecurringExpense.setDescription(formExpenseModel.getDescription()); currentRecurringExpense.setLabel(formExpenseModel.getLabel()); currentRecurringExpense.setNextDueDate(formExpenseModel.getNextDueDate()); currentRecurringExpense.setRecurrencePeriod(formExpenseModel.getRecurrencePeriod()); currentRecurringExpense.setExpenseType(formExpenseModel.getExpenseType()); currentRecurringExpense.setAmount(formExpenseModel.getAmount()); currentRecurringExpense.setCurrency(formExpenseModel.getCurrency()); currentRecurringExpense.setCreditorName(formExpenseModel.getCreditorName()); currentRecurringExpense.setNote(formExpenseModel.getNote()); recurringExpenseService.save(currentRecurringExpense); } else { recurringExpenseService.save(formExpenseModel); } return "redirect:recurring_expenses"; } @RequestMapping(path = "/details/{id}", method = RequestMethod.GET) public String editRecurringExpenses(@PathVariable Long id, Model model) { final RecurringExpense recurringExpense = recurringExpenseService.findRecurringExpense(id); model.addAttribute("recurringExpense", recurringExpense); return "recurring_expenses/recurring_expenses_form"; } @RequestMapping(path = "/new", method = RequestMethod.GET) public String newRecurringExpenses(Model model) { final RecurringExpense recurringExpense = new RecurringExpense(); recurringExpense.setNextDueDate(LocalDate.now()); model.addAttribute("recurringExpense", recurringExpense); return "recurring_expenses/recurring_expenses_form"; } }
package net.openid.consumer; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.HttpStatus; import org.apache.commons.httpclient.cookie.CookiePolicy; import org.apache.commons.httpclient.methods.PostMethod; import org.apache.commons.httpclient.methods.StringRequestEntity; import org.apache.log4j.Logger; import net.openid.message.*; import net.openid.association.Association; import net.openid.association.DiffieHellmanSession; import net.openid.association.AssociationException; import net.openid.association.AssociationSessionType; import net.openid.discovery.Identifier; import net.openid.discovery.Discovery; import net.openid.discovery.DiscoveryException; import net.openid.discovery.DiscoveryInformation; import net.openid.server.NonceGenerator; import net.openid.server.IncrementalNonceGenerator; import net.openid.server.RealmVerifier; import net.openid.OpenIDException; import javax.crypto.spec.DHParameterSpec; import java.net.*; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.*; /** * Manages OpenID communications with an OpenID Provider (Server). * <p> * The Consumer site needs to have the same instance of this class throughout * the lifecycle of a OpenID authentication session. * * @author Marius Scurtescu, Johnny Bufu */ public class ConsumerManager { private static Logger _log = Logger.getLogger(ConsumerManager.class); private static final boolean DEBUG = _log.isDebugEnabled(); /** * Discovery process manager. */ private Discovery _discovery = new Discovery(); /** * Store for keeping track of the established associations. */ private ConsumerAssociationStore _associations = new InMemoryConsumerAssociationStore(); /** * Consumer-side nonce generator, needed for compatibility with OpenID 1.1. */ private NonceGenerator _consumerNonceGenerator = new IncrementalNonceGenerator(); /** * Private association used for signing consumer nonces when operating in * compatibility (v1.x) mode. */ private Association _privateAssociation; /** * Verifier for the nonces in authentication responses; * prevents replay attacks. */ private NonceVerifier _nonceVerifier = new InMemoryNonceVerifier(60); /** * Handles HTTP calls to the Server / OpenID Provider. */ private HttpClient _httpClient; /** * Maximum number of attmpts for establishing an association. */ private int _maxAssocAttempts = 4; /** * Flag for enabling or disabling stateless mode. */ private boolean _allowStateless = true; /** * The lowest encryption level session accepted for association sessions. */ private AssociationSessionType _minAssocSessEnc = AssociationSessionType.NO_ENCRYPTION_SHA1MAC; /** * The preferred association session type; will be attempted first. */ private AssociationSessionType _prefAssocSessEnc; /** * Flag for allowing / disallowing no-encryption association session * over plain HTTP. */ private boolean _allowNoEncHttpSess = false; /** * Parameters (modulus and generator) for the Diffie-Hellman sessions. */ DHParameterSpec _dhParams = DiffieHellmanSession.getDefaultParameter(); /** * Timeout (in seconds) for keeping track of failed association attempts. * Default 5 minutes. */ private int _failedAssocExpire = 300; /** * Flag for generating checkid_immediate authentication requests. */ private boolean _immediateAuth = false; /** * Used to perform verify realms against return_to URLs. */ private RealmVerifier _realmVerifier; /** * Connect timeout for HTTP calls in miliseconds. Default 10s */ private int _connectTimeout = 10000; /** * Socket (read) timeout for HTTP calls in miliseconds. Default 10s. */ private int _socketTimeout = 10000; /** * Maximum number of redirects to be followed. Default 0. */ private int _maxRedirects = 0; /** * Instantiates a ConsumerManager with default settings. */ public ConsumerManager() throws ConsumerException { _httpClient = new HttpClient(); // global httpclient configuration parameters _httpClient.getParams().setParameter( "http.protocol.allow-circular-redirects", Boolean.FALSE); _httpClient.getParams().setParameter( "http.protocol.cookie-policy", CookiePolicy.IGNORE_COOKIES); _realmVerifier = new RealmVerifier(); if (Association.isHmacSha256Supported()) _prefAssocSessEnc = AssociationSessionType.DH_SHA256; else _prefAssocSessEnc = AssociationSessionType.DH_SHA1; try { // initialize the private association for compat consumer nonces _privateAssociation = Association.generate( getPrefAssocSessEnc().getAssociationType(), "", 0); } catch (AssociationException e) { throw new ConsumerException( "Cannot initialize private association, " + "needed for consumer nonces."); } } /** * Returns discovery process manager. * * @return discovery process manager. */ public Discovery getDiscovery() { return _discovery; } /** * Sets discovery process manager. * * @param discovery discovery process manager. */ public void setDiscovery(Discovery discovery) { _discovery = discovery; } /** * Gets the association store that holds established associations with * OpenID providers. * * @see ConsumerAssociationStore */ public ConsumerAssociationStore getAssociations() { return _associations; } /** * Configures the ConsumerAssociationStore that will be used to store the * associations established with OpenID providers. * * @param associations ConsumerAssociationStore implementation * @see ConsumerAssociationStore */ public void setAssociations(ConsumerAssociationStore associations) { this._associations = associations; } /** * Gets the NonceVerifier implementation used to keep track of the nonces * that have been seen in authentication response messages. * * @see NonceVerifier */ public NonceVerifier getNonceVerifier() { return _nonceVerifier; } /** * Configures the NonceVerifier that will be used to keep track of the * nonces in the authentication response messages. * * @param nonceVerifier NonceVerifier implementation * @see NonceVerifier */ public void setNonceVerifier(NonceVerifier nonceVerifier) { this._nonceVerifier = nonceVerifier; } /** * Sets the Diffie-Hellman base parameters that will be used for encoding * the MAC key exchange. * <p> * If not provided the default set specified by the Diffie-Hellman algorithm * will be used. * * @param dhParams Object encapsulating modulus and generator numbers * @see DHParameterSpec DiffieHellmanSession */ public void setDHParams(DHParameterSpec dhParams) { this._dhParams = dhParams; } /** * Gets the Diffie-Hellman base parameters (modulus and generator). * * @see DHParameterSpec DiffieHellmanSession */ public DHParameterSpec getDHParams() { return _dhParams; } /** * Maximum number of attempts (HTTP calls) the RP is willing to make * for trying to establish an association with the IdP. * * Default: 4; * 0 = don't use associations * * Associations and stateless mode cannot be both disabled at the same time. */ public void setMaxAssocAttempts(int maxAssocAttempts) throws ConsumerException { if (maxAssocAttempts > 0 || _allowStateless) this._maxAssocAttempts = maxAssocAttempts; else throw new IllegalArgumentException( "Associations and stateless mode " + "cannot be both disabled at the same time."); if (_maxAssocAttempts == 0) _log.info("Associations disabled."); } /** * Gets the value configured for the maximum number of association attempts * that will be performed for a given OpenID provider. * <p> * If an association cannot be established after this number of attempts the * ConsumerManager will fallback to stateless mode, provided the * #allowStateless preference is enabled. * <p> * See also: {@link #allowStateless(boolean)} {@link #statelessAllowed()} */ public int getMaxAssocAttempts() { return _maxAssocAttempts; } /** * Flag used to enable / disable the use of stateless mode. * <p> * Default: enabled. * <p> * Associations and stateless mode cannot be both disabled at the same time. */ public void allowStateless(boolean useStateless) { if (_allowStateless || _maxAssocAttempts > 0) this._allowStateless = useStateless; else throw new IllegalArgumentException( "Associations and stateless mode " + "cannot be both disabled at the same time."); } /** * Returns true if the ConsumerManager is configured to fallback to * stateless mode when failing to associate with an OpenID Provider. */ public boolean statelessAllowed() { return _allowStateless; } /** * Configures the minimum level of encryption accepted for association * sessions. * <p> * Default: no-encryption session, SHA1 MAC association. * <p> * See also: {@link #allowStateless(boolean)} */ public void setMinAssocSessEnc(AssociationSessionType minAssocSessEnc) { this._minAssocSessEnc = minAssocSessEnc; } /** * Gets the minimum level of encryption that will be accepted for * association sessions. * <p> * Default: no-encryption session, SHA1 MAC association * <p> * See also: {@link #setAllowNoEncHttp(boolean)} */ public AssociationSessionType getMinAssocSessEnc() { return _minAssocSessEnc; } /** * Sets the preferred encryption type for the association sessions. * <p> * Default: DH-SHA256 */ public void setPrefAssocSessEnc(AssociationSessionType prefAssocSessEnc) { this._prefAssocSessEnc = prefAssocSessEnc; } /** * Gets the preferred encryption type for the association sessions. */ public AssociationSessionType getPrefAssocSessEnc() { return _prefAssocSessEnc; } /** * Flag that determines whether no-encryption association sessions are * allowed through plain HTTP. * <p> * Default: false (require HTTPS for no-encryption association sessions). * <p> * OpenID specification strongly RECOMMENDEDS AGAINST the use of * "no-encryption" sessions on a public network; this is vulnerable to * eavesdropping attacks. */ public void setAllowNoEncHttp(boolean allowNoEncHttp) { this._allowNoEncHttpSess = allowNoEncHttp; } /** * Returns true if no-encryption association sessions will be allowed to be * established over plain HTTP. */ public boolean getAllowNoEncHttp() { return _allowNoEncHttpSess; } /** * Sets the expiration timeout (in seconds) for keeping track of failed * association attempts. * <p> * If an association cannot be establish with an IdP, subsequesnt * authentication request to that IdP will not try to establish an * association within the timeout period configured here. * <p> * Default: 300s * 0 = disabled (attempt to establish an association with every * authentication request) * * @param _failedAssocExpire time in seconds to remember failed * association attempts */ public void setFailedAssocExpire(int _failedAssocExpire) { this._failedAssocExpire = _failedAssocExpire; } /** * Gets the timeout (in seconds) configured for keeping track of failed * association attempts. * <p> * See also: {@link #setFailedAssocExpire(int)} */ public int getFailedAssocExpire() { return _failedAssocExpire; } /** * Configures the authentication request mode: * checkid_immediate (true) or checkid_setup (false). * <p> * Default: false / checkid_setup */ public void setImmediateAuth(boolean _immediateAuth) { this._immediateAuth = _immediateAuth; } /** * Returns true if the ConsumerManager is configured to attempt * checkid_immediate authentication requests. * <p> * Default: false */ public boolean isImmediateAuth() { return _immediateAuth; } /** * Gets the RealmVerifier used to verify realms against return_to URLs. */ public RealmVerifier getRealmVerifier() { return _realmVerifier; } /** * Sets the RealmVerifier used to verify realms against return_to URLs. */ public void setRealmVerifier(RealmVerifier realmVerifier) { this._realmVerifier = realmVerifier; } /** * Gets the max age (in seconds) configured for keeping track of nonces. * <p> * Nonces older than the max age will be removed from the store and * authentication responses will be considered failures. */ public long getMaxNonceAge() { return _nonceVerifier.getMaxAge(); } /** * Does discover on an identifier. It delegates the call to its * discovery manager. * * @return A List of {@link DiscoveryInformation} objects. * The list could be empty if no discovery information can * be retrieved. * * @throws DiscoveryException if the discovery process runs into errors. */ public List discover(String identifier) throws DiscoveryException { return _discovery.discover(identifier); } /** * Configures a private association for signing consumer nonces. * <p> * Consumer nonces are needed to prevent replay attacks in compatibility * mode, because OpenID 1.x Providers to not attach nonces to * authentication responses. * <p> * One way for the Consumer to know that a consumer nonce in an * authentication response was indeed issued by itself (and thus prevent * denial of service attacks), is by signing them. * * @param assoc The association to be used for signing consumer nonces; * signing can be deactivated by setting this to null. * Signing is enabled by default. */ public void setPrivateAssociation(Association assoc) throws ConsumerException { if (assoc == null) throw new ConsumerException( "Cannot set null private association, " + "needed for consumer nonces."); _privateAssociation = assoc; } /** * Gets the private association used for signing consumer nonces. * * @see #setPrivateAssociation(net.openid.association.Association) */ public Association getPrivateAssociation() { return _privateAssociation; } /** * Makes a HTTP call to the specified URL with the parameters specified * in the Message. * * @param url URL endpoint for the HTTP call * @param request Message containing the parameters * @param response ParameterList that will hold the parameters received in * the HTTP response * @return the status code of the HTTP call */ private int call(String url, Message request, ParameterList response) throws MessageException { // custom httpclient configuration _httpClient.getParams().setParameter( "http.protocol.max-redirects", new Integer(_maxRedirects)); _httpClient.getParams().setSoTimeout(_socketTimeout); _httpClient.getHttpConnectionManager() .getParams().setConnectionTimeout(_connectTimeout); int responseCode = -1; try { // build the post message with the parameters from the request PostMethod post = new PostMethod(url); // can't follow redirects on a POST (w/o user intervention) //post.setFollowRedirects(true); post.setRequestEntity(new StringRequestEntity( request.wwwFormEncoding(), "application/x-www-form-urlencoded", "UTF-8")); // place the http call to the IdP if (DEBUG) _log.debug("Performing HTTP POST on " + url); responseCode = _httpClient.executeMethod(post); String postResponse = post.getResponseBodyAsString(); response.copyOf(ParameterList.createFromKeyValueForm(postResponse)); if (DEBUG) _log.debug("Retrived response:" + postResponse); } catch (IOException e) { _log.error("Error talking to " + url + " response code: " + responseCode, e); } return responseCode; } /** * Tries to establish an association with on of the service endpoints in * the list of DiscoveryInformation. * <p> * Iterates over the items in the discoveries parameter a maximum of * #_maxAssocAttempts times trying to esablish an association. * * @param discoveries The DiscoveryInformation list obtained by * performing dicovery on the User-supplied OpenID * identifier. Should be ordered by the priority * of the service endpoints. * @return The DiscoveryInformation instance with which * an association was established, or the one * with the highest priority if association failed. * * @see Discovery#discover(net.openid.discovery.Identifier) */ public DiscoveryInformation associate(List discoveries) { DiscoveryInformation discovered; Association assoc; int attemptsLeft = _maxAssocAttempts; Iterator itr = discoveries.iterator(); while (itr.hasNext() && attemptsLeft > 0) { discovered = (DiscoveryInformation) itr.next(); attemptsLeft -= associate(discovered, attemptsLeft); // check if an association was established assoc = _associations.load(discovered.getIdpEndpoint().toString()); if ( assoc != null && ! Association.FAILED_ASSOC_HANDLE.equals(assoc.getHandle())) return discovered; } if (discoveries.size() > 0) { // no association established, return the first service endpoint DiscoveryInformation d0 = (DiscoveryInformation) discoveries.get(0); _log.warn("Association failed; using first entry: " + d0.getIdpEndpoint()); return d0; } else { _log.error("Association attempt, but no discovey endpoints provided."); return null; } } /** * Tries to establish an association with the OpenID Provider. * <p> * The resulting association information will be kept on storage for later * use at verification stage. * * @param discovered DiscoveryInformation obtained during the discovery * @return The number of association attempts performed. */ private int associate(DiscoveryInformation discovered, int maxAttempts) { if (_maxAssocAttempts == 0) return 0; // associations disabled URL idpUrl = discovered.getIdpEndpoint(); String idpEndpoint = idpUrl.toString(); _log.info("Trying to associate with " + idpEndpoint + " attempts left: " + maxAttempts); // check if there's an already established association Association a = _associations.load(idpEndpoint); if (a != null && a.getHandle() != null) { _log.info("Found an existing association."); return 0; } String handle = Association.FAILED_ASSOC_HANDLE; // build a list of association types, with the preferred one at the end LinkedHashMap requests = new LinkedHashMap(); if (discovered.isVersion2()) { requests.put(AssociationSessionType.NO_ENCRYPTION_SHA1MAC, null); requests.put(AssociationSessionType.NO_ENCRYPTION_SHA256MAC, null); requests.put(AssociationSessionType.DH_SHA1, null); requests.put(AssociationSessionType.DH_SHA256, null); } else { requests.put(AssociationSessionType.NO_ENCRYPTION_COMPAT_SHA1MAC, null); requests.put(AssociationSessionType.DH_COMPAT_SHA1, null); } if (_prefAssocSessEnc.isVersion2() == discovered.isVersion2()) requests.put(_prefAssocSessEnc, null); // build a stack of Association Request objects // and keep only the allowed by the configured preferences // the most-desirable entry is always at the top of the stack Stack reqStack = new Stack(); Iterator iter = requests.keySet().iterator(); while(iter.hasNext()) { AssociationSessionType type = (AssociationSessionType) iter.next(); // create the appropriate Association Request AssociationRequest newReq = createAssociationRequest(type, idpUrl); if (newReq != null) reqStack.push(newReq); } // perform the association attempts int attemptsLeft = maxAttempts; LinkedHashMap alreadyTried = new LinkedHashMap(); while (attemptsLeft > 0 && ! reqStack.empty()) { try { attemptsLeft AssociationRequest assocReq = (AssociationRequest) reqStack.pop(); if (DEBUG) _log.debug("Trying association type: " + assocReq.getType()); // was this association / session type attempted already? if (alreadyTried.keySet().contains(assocReq.getType())) { if (DEBUG) _log.debug("Already tried."); continue; } // mark the current request type as already tried alreadyTried.put(assocReq.getType(), null); ParameterList respParams = new ParameterList(); int status = call(idpEndpoint, assocReq, respParams); // process the response if (status == HttpStatus.SC_OK) // success response { AssociationResponse assocResp; assocResp = AssociationResponse .createAssociationResponse(respParams); // valid association response Association assoc = assocResp.getAssociation(assocReq.getDHSess()); handle = assoc.getHandle(); AssociationSessionType respType = assocResp.getType(); if ( respType.equals(assocReq.getType()) || // v1 IdPs may return a success no-encryption resp ( ! discovered.isVersion2() && respType.getHAlgorithm() == null && createAssociationRequest(respType,idpUrl) != null)) { // store the association and do no try alternatives _associations.save(idpEndpoint, assoc); _log.info("Associated with " + discovered.getIdpEndpoint() + " handle: " + assoc.getHandle()); break; } else _log.info("Discarding, not matching consumer criteria"); } else if (status == HttpStatus.SC_BAD_REQUEST) // error response { _log.info("Association attempt failed."); // retrieve fallback sess/assoc/encryption params set by IdP // and queue a new attempt AssociationError assocErr = AssociationError.createAssociationError(respParams); AssociationSessionType idpType = AssociationSessionType.create( assocErr.getSessionType(), assocErr.getAssocType()); if (alreadyTried.keySet().contains(idpType)) continue; // create the appropriate Association Request AssociationRequest newReq = createAssociationRequest(idpType, idpUrl); if (newReq != null) { if (DEBUG) _log.debug("Retrieved association type " + "from the association error: " + newReq.getType()); reqStack.push(newReq); } } } catch (OpenIDException e) { _log.error("Error encountered during association attempt.", e); } } // store IdPs with which an association could not be established // so that association attempts are not performed with each auth request if (Association.FAILED_ASSOC_HANDLE.equals(handle) && _failedAssocExpire > 0) _associations.save(idpEndpoint, Association.getFailedAssociation(_failedAssocExpire)); return maxAttempts - attemptsLeft; } /** * Constructs an Association Request message of the specified session and * association type, taking into account the user preferences (encryption * level, default Diffie-Hellman parameters). * * @param type The type of the association (session and association) * @param idpUrl The IdP for which the association request is created * @return An AssociationRequest message ready to be sent back * to the OpenID Provider, or null if an association * of the requested type cannot be built. */ private AssociationRequest createAssociationRequest( AssociationSessionType type, URL idpUrl) { try { if (_minAssocSessEnc.isBetter(type)) return null; AssociationRequest assocReq = null; DiffieHellmanSession dhSess; if (type.getHAlgorithm() != null) // DH session { dhSess = DiffieHellmanSession.create(type, _dhParams); if (DiffieHellmanSession.isDhSupported(type) && Association.isHmacSupported(type.getAssociationType())) assocReq = AssociationRequest.createAssociationRequest(type, dhSess); } else // no-enc session { if ((_allowNoEncHttpSess || idpUrl.getProtocol().equals("https")) && Association.isHmacSupported(type.getAssociationType())) assocReq = AssociationRequest.createAssociationRequest(type); } return assocReq; } catch (OpenIDException e) { _log.error("Error trying to create association request.", e); return null; } } /** * Builds a authentication request message for the user specified in the * discovery information provided as a parameter. * <p> * If the discoveries parameter contains more than one entry, it will * iterate over them trying to establish an association. If an association * cannot be established, the first entry is used with stateless mode. * * @see #associate(java.util.List) * @param discoveries The DiscoveryInformation list obtained by * performing dicovery on the User-supplied OpenID * identifier. Should be ordered by the priority * of the service endpoints. * @param returnToUrl The URL on the Consumer site where the OpenID * Provider will return the user after generating * the authentication response. <br> * Null if the Consumer does not with to for the * End User to be returned to it (something else * useful will have been performed via an * extension). <br> * Must not be null in OpenID 1.x compatibility * mode. * @return Authentication request message to be sent to the * OpenID Provider. */ public AuthRequest authenticate(List discoveries, String returnToUrl) throws ConsumerException, MessageException { return authenticate(discoveries, returnToUrl, returnToUrl); } /** * Builds a authentication request message for the user specified in the * discovery information provided as a parameter. * <p> * If the discoveries parameter contains more than one entry, it will * iterate over them trying to establish an association. If an association * cannot be established, the first entry is used with stateless mode. * * @see #associate(java.util.List) * @param discoveries The DiscoveryInformation list obtained by * performing dicovery on the User-supplied OpenID * identifier. Should be ordered by the priority * of the service endpoints. * @param returnToUrl The URL on the Consumer site where the OpenID * Provider will return the user after generating * the authentication response. <br> * Null if the Consumer does not with to for the * End User to be returned to it (something else * useful will have been performed via an * extension). <br> * Must not be null in OpenID 1.x compatibility * mode. * @param realm The URL pattern that will be presented to the * user when he/she will be asked to authorize the * authentication transaction. Must be a super-set * of the @returnToUrl. * @return Authentication request message to be sent to the * OpenID Provider. */ public AuthRequest authenticate(List discoveries, String returnToUrl, String realm) throws ConsumerException, MessageException { // try to associate with one OP in the discovered list DiscoveryInformation discovered = associate(discoveries); return authenticate(discovered, returnToUrl, realm); } /** * Builds a authentication request message for the user specified in the * discovery information provided as a parameter. * * @param discovered A DiscoveryInformation endpoint from the list * obtained by performing dicovery on the * User-supplied OpenID identifier. * @param returnToUrl The URL on the Consumer site where the OpenID * Provider will return the user after generating * the authentication response. <br> * Null if the Consumer does not with to for the * End User to be returned to it (something else * useful will have been performed via an * extension). <br> * Must not be null in OpenID 1.x compatibility * mode. * @return Authentication request message to be sent to the * OpenID Provider. */ public AuthRequest authenticate(DiscoveryInformation discovered, String returnToUrl) throws MessageException, ConsumerException { return authenticate(discovered, returnToUrl, returnToUrl); } /** * Builds a authentication request message for the user specified in the * discovery information provided as a parameter. * * @param discovered A DiscoveryInformation endpoint from the list * obtained by performing dicovery on the * User-supplied OpenID identifier. * @param returnToUrl The URL on the Consumer site where the OpenID * Provider will return the user after generating * the authentication response. <br> * Null if the Consumer does not with to for the * End User to be returned to it (something else * useful will have been performed via an * extension). <br> * Must not be null in OpenID 1.x compatibility * mode. * @param realm The URL pattern that will be presented to the * user when he/she will be asked to authorize the * authentication transaction. Must be a super-set * of the @returnToUrl. * @return Authentication request message to be sent to the * OpenID Provider. */ public AuthRequest authenticate(DiscoveryInformation discovered, String returnToUrl, String realm) throws MessageException, ConsumerException { if (discovered == null) throw new ConsumerException("Authentication cannot continue: " + "no discovery information provided."); associate(discovered, _maxAssocAttempts); Association assoc = _associations.load(discovered.getIdpEndpoint().toString()); String handle = assoc != null ? assoc.getHandle() : Association.FAILED_ASSOC_HANDLE; // get the Claimed ID String claimedId; if (discovered.hasClaimedIdentifier()) claimedId = discovered.getClaimedIdentifier().getIdentifier(); else claimedId = AuthRequest.SELECT_ID; // set the Delegate ID (aka OP-specific identifier) String delegate = claimedId; if (discovered.hasDelegateIdentifier()) delegate = discovered.getDelegateIdentifier(); // stateless mode disabled ? if ( !_allowStateless && Association.FAILED_ASSOC_HANDLE.equals(handle)) throw new ConsumerException("Authentication cannot be performed: " + "no association available and stateless mode is disabled"); _log.info("Creating authentication request for" + " OP-endpoint: " + discovered.getIdpEndpoint() + " claimedID: " + claimedId + " OP-specific ID: " + delegate); AuthRequest authReq = AuthRequest.createAuthRequest(claimedId, delegate, ! discovered.isVersion2(), returnToUrl, handle, realm, _realmVerifier); authReq.setOPEndpoint(discovered.getIdpEndpoint()); if (! discovered.isVersion2()) authReq.setReturnTo(insertConsumerNonce(authReq.getReturnTo())); // ignore the immediate flag for OP-directed identifier selection if (! AuthRequest.SELECT_ID.equals(claimedId)) authReq.setImmediate(_immediateAuth); if (! authReq.isValid()) throw new MessageException("Invalid AuthRequest: " + authReq.wwwFormEncoding()); return authReq; } /** * Performs verification on the Authentication Response (assertion) * received from the OpenID Provider. * <p> * Three verification steps are performed: * <ul> * <li> nonce: the same assertion will not be accepted more * than once * <li> signatures: verifies that the message was indeed sent * by the OpenID Provider that was contacted * earlier after discovery * <li> discovered information: the information contained in the assertion * matches the one obtained during the * discovery (the OpenID Provider is * authoritative for the claimed identifier; * the received assertion is not meaningful * otherwise * </ul> * * @param receivingUrl The URL where the Consumer (Relying Party) has * accepted the incoming message. * @param response ParameterList of the authentication response * being verified. * @param discovered Previously discovered information (which can * therefore be trusted) obtained during the discovery * phase; this should be stored and retrieved by the RP * in the user's session. * * @return A VerificationResult, containing a verified * identifier; the verified identifier is null if * the verification failed). */ public VerificationResult verify(String receivingUrl, ParameterList response, DiscoveryInformation discovered) throws MessageException, DiscoveryException, AssociationException { VerificationResult result = new VerificationResult(); _log.info("Verifying authentication response..."); // non-immediate negative response if ( "cancel".equals(response.getParameterValue("openid.mode")) ) { result.setAuthResponse(AuthFailure.createAuthFailure(response)); _log.info("Received auth failure."); return result; } // immediate negative response if ( "setup_needed".equals(response.getParameterValue("openid.mode")) || ("id_res".equals(response.getParameterValue("openid.mode")) && response.hasParameter("openid.user_setup_url") ) ) { AuthImmediateFailure fail = AuthImmediateFailure.createAuthImmediateFailure(response); result.setAuthResponse(fail); result.setIdpSetupUrl(fail.getUserSetupUrl()); _log.info("Received auth immediate failure."); return result; } AuthSuccess authResp = AuthSuccess.createAuthSuccess(response); _log.info("Received positive auth response."); if (!authResp.isValid()) throw new MessageException("Invalid Authentication Response: " + authResp.wwwFormEncoding()); result.setAuthResponse(authResp); // [1/4] return_to verification if (! verifyReturnTo(receivingUrl, authResp)) { result.setStatusMsg("Return_To URL verification failed."); _log.error("Return_To URL verification failed."); return result; } // [2/4] : discovered info verification discovered = verifyDiscovered(authResp, discovered); if (discovered == null || ! discovered.hasClaimedIdentifier()) { result.setStatusMsg("Discovered information verification failed."); _log.error("Discovered information verification failed."); return result; } // [3/4] : nonce verification if (! verifyNonce(authResp, discovered)) { result.setStatusMsg("Nonce verificaton failed."); _log.error("Nonce verificaton failed."); return result; } // [4/4] : signature verification if (verifySignature(authResp, discovered)) { // mark verification success _log.info("Verification succeeded."); result.setVerifiedId(discovered.getClaimedIdentifier()); } else { result.setStatusMsg("Signature verification failed."); _log.error("Signature verification failed."); } return result; } /** * Verifies that the URL where the Consumer (Relying Party) received the * authentication response matches the value of the "openid.return_to" * parameter in the authentication response. * * @param receivingUrl The URL where the Consumer received the * authentication response. * @param response The authentication response. * @return True if the two URLs match, false otherwise. */ public boolean verifyReturnTo(String receivingUrl, AuthSuccess response) { if (DEBUG) _log.debug("Verifying return URL; receiving: " + receivingUrl + "\nmessage: " + response.getReturnTo()); URL receiving; URL returnTo; try { receiving = new URL(receivingUrl); returnTo = new URL(response.getReturnTo()); } catch (MalformedURLException e) { _log.error("Invalid return URL.", e); return false; } // [1/2] schema, authority (includes port) and path // deal manually with the trailing slash in the path StringBuffer receivingPath = new StringBuffer(receiving.getPath()); if ( receivingPath.length() > 0 && receivingPath.charAt(receivingPath.length() -1) != '/') receivingPath.append('/'); StringBuffer returnToPath = new StringBuffer(returnTo.getPath()); if ( returnToPath.length() > 0 && returnToPath.charAt(returnToPath.length() -1) != '/') returnToPath.append('/'); if ( ! receiving.getProtocol().equals(returnTo.getProtocol()) || ! receiving.getAuthority().equals(returnTo.getAuthority()) || ! receivingPath.toString().equals(returnToPath.toString()) ) { if (DEBUG) _log.debug("Return URL schema, authority or " + "path verification failed."); return false; } // [2/2] query parameters try { Map returnToParams = extractQueryParams(returnTo); Map receivingParams = extractQueryParams(receiving); if (returnToParams == null) return true; if (receivingParams == null) { if (DEBUG) _log.debug("Return URL query parameters verification failed."); return false; } Iterator iter = returnToParams.keySet().iterator(); while (iter.hasNext()) { String key = (String) iter.next(); List receivingValues = (List) receivingParams.get(key); List returnToValues = (List) returnToParams.get(key); if ( receivingValues == null || receivingValues.size() != returnToValues.size() || ! receivingValues.containsAll( returnToValues ) ) { if (DEBUG) _log.debug("Return URL query parameters verification failed."); return false; } } } catch (UnsupportedEncodingException e) { _log.error("Error verifying return URL query parameters.", e); return false; } return true; } /** * Returns a Map(key, List(values)) with the URL's query params, or null if * the URL doesn't have a query string. */ public Map extractQueryParams(URL url) throws UnsupportedEncodingException { if (url.getQuery() == null) return null; Map paramsMap = new HashMap(); List paramList = Arrays.asList(url.getQuery().split("&")); Iterator iter = paramList.iterator(); while (iter.hasNext()) { String keyValue = (String) iter.next(); int equalPos = keyValue.indexOf("="); String key = equalPos > -1 ? URLDecoder.decode(keyValue.substring(0, equalPos), "UTF-8") : URLDecoder.decode(keyValue, "UTF-8"); String value; if (equalPos <= -1) value = null; else if (equalPos + 1 > keyValue.length()) value = ""; else value = URLDecoder.decode(keyValue.substring(equalPos + 1), "UTF-8"); List existingValues = (List) paramsMap.get(key); if (existingValues == null) { List newValues = new ArrayList(); newValues.add(value); paramsMap.put(key, newValues); } else existingValues.add(value); } return paramsMap; } /** * Verifies the nonce in an authentication response. * * @param authResp The authentication response containing the nonce * to be verified. * @param discovered The discovery information associated with the * authentication transaction. * @return True if the nonce is valid, false otherwise. */ public boolean verifyNonce(AuthSuccess authResp, DiscoveryInformation discovered) { String nonce = authResp.getNonce(); if (nonce == null) // compatibility mode nonce = extractConsumerNonce(authResp.getReturnTo()); if (nonce == null) return false; // using the same nonce verifier for both server and consumer nonces return (NonceVerifier.OK == _nonceVerifier.seen( discovered.getIdpEndpoint().toString(), nonce)); } /** * Inserts a consumer-side nonce as a custom parameter in the return_to * parameter of the authentication request. * <p> * Needed for preventing replay attack when running compatibility mode. * OpenID 1.1 OpenID Providers do not generate nonces in authentication * responses. * * @param returnTo The return_to URL to which a custom nonce * parameter will be added. * @return The return_to URL containing the nonce. */ public String insertConsumerNonce(String returnTo) { String nonce = _consumerNonceGenerator.next(); returnTo += (returnTo.indexOf('?') != -1) ? '&' : '?'; try { returnTo += "openid.rpnonce=" + URLEncoder.encode(nonce, "UTF-8"); returnTo += "&openid.rpsig=" + URLEncoder.encode(_privateAssociation.sign(returnTo), "UTF-8"); _log.info("Inserted consumer nonce."); if (DEBUG) _log.debug("return_to:" + returnTo); } catch (Exception e) { _log.error("Error inserting consumre nonce.", e); return null; } return returnTo; } /** * Extracts the consumer-side nonce from the return_to parameter in * authentication response from a OpenID 1.1 Provider. * * @param returnTo return_to URL from the authentication response * @return The nonce found in the return_to URL, or null if * it wasn't found. */ public String extractConsumerNonce(String returnTo) { if (DEBUG) _log.debug("Extracting consumer nonce..."); String nonce = null; String signature = null; URL returnToUrl; try { returnToUrl = new URL(returnTo); } catch (MalformedURLException e) { _log.error("Invalid return_to: " + returnTo, e); return null; } String query = returnToUrl.getQuery(); String[] params = query.split("&"); for (int i=0; i < params.length; i++) { String keyVal[] = params[i].split("=", 2); try { if (keyVal.length == 2 && "openid.rpnonce".equals(keyVal[0])) { nonce = URLDecoder.decode(keyVal[1], "UTF-8"); if (DEBUG) _log.debug("Extracted consumer nonce: " + nonce); } if (keyVal.length == 2 && "openid.rpsig".equals(keyVal[0])) { signature = URLDecoder.decode(keyVal[1], "UTF-8"); if (DEBUG) _log.debug("Extracted consumer nonce signature: " + signature); } } catch (UnsupportedEncodingException e) { _log.error("Error extracting consumer nonce / signarure.", e); return null; } } // check the signature if (signature == null) { _log.error("Null consumer nonce signature."); return null; } String signed = returnTo.substring(0, returnTo.indexOf("&openid.rpsig=")); if (DEBUG) _log.debug("Consumer signed text: " + signed); try { if (_privateAssociation.verifySignature(signed, signature)) { _log.info("Consumer nonce signature verified."); return nonce; } else { _log.error("Consumer nonce signature failed."); return null; } } catch (AssociationException e) { _log.error("Error verifying consumer nonce signature.", e); return null; } } /** * Verifies the dicovery information matches the data received in a * authentication response from an OpenID Provider. * * @param authResp The authentication response to be verified. * @param discovered The discovery information obtained earlier during * the discovery stage, associated with the * identifier(s) in the request. May be null for * OpenID 2.0; must not be null for OpenID 1.x. * @return The discovery information associated with the * claimed identifier, that can be used further in * the verification process. Null if the discovery * on the claimed identifier does not match the data * in the assertion. */ private DiscoveryInformation verifyDiscovered(AuthSuccess authResp, DiscoveryInformation discovered) throws DiscoveryException { if (authResp == null || authResp.getIdentity() == null) { _log.info("Assertion is not about an identifier"); return null; } if (authResp.isVersion2()) return verifyDiscovered2(authResp, discovered); else return verifyDiscovered1(authResp, discovered); } /** * Verifies the discovered information associated with a OpenID 1.x * response. * * @param authResp The authentication response to be verified. * @param discovered The discovery information obtained earlier during * the discovery stage, associated with the * identifier(s) in the request. Must not be null, * and must contain a claimed identifier. * @return The discovery information associated with the * claimed identifier, that can be used further in * the verification process. Null if the discovery * on the claimed identifier does not match the data * in the assertion. */ private DiscoveryInformation verifyDiscovered1(AuthSuccess authResp, DiscoveryInformation discovered) throws DiscoveryException { if (authResp == null || authResp.isVersion2() || authResp.getIdentity() == null || discovered == null || discovered.getClaimedIdentifier() == null || discovered.isVersion2()) { if (DEBUG) _log.debug("Discovered information doesn't match " + "auth response / version"); return null; } // asserted identifier in the AuthResponse String assertId = authResp.getIdentity(); // claimed identifier Identifier claimedId = discovered.getClaimedIdentifier(); if (DEBUG) _log.debug("Verifying discovered information for OpenID1 assertion " + "about ClaimedID: " + claimedId.getIdentifier()); // OP-specific ID String opSpecific = discovered.hasDelegateIdentifier() ? discovered.getDelegateIdentifier() : claimedId.getIdentifier(); // does the asserted ID match the OP-specific ID from the discovery? if ( opSpecific.equals(assertId) ) return discovered; // success // discovered info verification failed if (DEBUG) _log.debug("Identifier in the assertion doesn't match " + "the one in the discovered information."); return null; } /** * Verifies the discovered information associated with a OpenID 2.0 * response. * * @param authResp The authentication response to be verified. * @param discovered The discovery information obtained earlier during * the discovery stage, associated with the * identifier(s) in the request. May be null, * in which case discovery will be performed on * the claimed identifier in the response. * @return The discovery information associated with the * claimed identifier, that can be used further in * the verification process. Null if the discovery * on the claimed identifier does not match the data * in the assertion. */ private DiscoveryInformation verifyDiscovered2(AuthSuccess authResp, DiscoveryInformation discovered) throws DiscoveryException { if (authResp == null || ! authResp.isVersion2() || authResp.getIdentity() == null || authResp.getClaimed() == null) { if (DEBUG) _log.debug("Discovered information doesn't match " + "auth response / version"); return null; } // asserted identifier in the AuthResponse String assertId = authResp.getIdentity(); // claimed identifier in the AuthResponse Identifier respClaimed = Discovery.parseIdentifier(authResp.getClaimed()); // the OP endpoint sent in the response String respEndpoint = authResp.getOpEndpoint(); if (DEBUG) _log.debug("Verifying discovered information for OpenID2 assertion " + "about ClaimedID: " + respClaimed.getIdentifier()); // was the claimed identifier in the assertion previously discovered? if (discovered != null && discovered.hasClaimedIdentifier() && discovered.getClaimedIdentifier().equals(respClaimed) ) { // OP-endpoint, OP-specific ID and protocol version must match String opSpecific = discovered.hasDelegateIdentifier() ? discovered.getDelegateIdentifier() : discovered.getClaimedIdentifier().getIdentifier(); if ( opSpecific.equals(assertId) && discovered.isVersion2() && discovered.getIdpEndpoint().equals(respEndpoint)) { if (DEBUG) _log.debug( "ClaimedID in the assertion was previously discovered: " + respClaimed); return discovered; } } // stateless, bare response, or the user changed the ID at the OP DiscoveryInformation firstServiceMatch = null; // perform discovery on the claim identifier in the assertion if(DEBUG) _log.debug( "Performing discovery on the ClaimedID in the assertion: " + respClaimed); List discoveries = _discovery.discover(respClaimed); // find the newly discovered service endpoint that matches the assertion // - OP endpoint, OP-specific ID and protocol version must match // - prefer (first = highest priority) endpoint with an association if (DEBUG) _log.debug("Looking for a service element to match " + "the ClaimedID and OP endpoint in the assertion..."); Iterator iter = discoveries.iterator(); while (iter.hasNext()) { DiscoveryInformation service = (DiscoveryInformation) iter.next(); if (DiscoveryInformation.OPENID2_OP.equals(service.getVersion())) continue; String opSpecific = service.hasDelegateIdentifier() ? service.getDelegateIdentifier() : service.getClaimedIdentifier().getIdentifier(); if ( ! opSpecific.equals(assertId) || ! service.isVersion2() || ! service.getIdpEndpoint().equals(respEndpoint) ) continue; // keep the first endpoint that matches if (firstServiceMatch == null) { if (DEBUG) _log.debug("Found matching service: " + service); firstServiceMatch = service; } Association assoc = _associations.load( service.getIdpEndpoint().toString(), authResp.getHandle()); // don't look further if there is an association with this endpoint if (assoc != null) { if (DEBUG) _log.debug("Found existing association, " + "not looking for another service endpoint."); return service; } } if (firstServiceMatch == null) _log.error("No service element found to match " + "the ClaimedID / OP-endpoint in the assertion."); return firstServiceMatch; } /** * Verifies the signature in a authentication response message. * * @param authResp Authentication response to be verified. * @param discovered The discovery information obtained earlier during * the discovery stage. * @return True if the verification succeeded, false otherwise. */ private boolean verifySignature(AuthSuccess authResp, DiscoveryInformation discovered) throws AssociationException, MessageException { if (discovered == null || authResp == null) { _log.error("Can't verify signature: " + "null assertion or discovered information."); return false; } String handle = authResp.getHandle(); URL idp = discovered.getIdpEndpoint(); Association assoc = _associations.load(idp.toString(), handle); if (assoc != null) // association available, local verification { _log.info("Found association: " + assoc.getHandle() + " verifying signature locally..."); String text = authResp.getSignedText(); String signature = authResp.getSignature(); if (assoc.verifySignature(text, signature)) return true; } else // no association, verify with the IdP { _log.info("No association found, " + "contacting the OP for direct verification..."); VerifyRequest vrfy = VerifyRequest.createVerifyRequest(authResp); ParameterList responseParams = new ParameterList(); int respCode = call(idp.toString(), vrfy, responseParams); if (HttpStatus.SC_OK == respCode) { VerifyResponse vrfyResp = VerifyResponse.createVerifyResponse(responseParams); if (vrfyResp.isValid() & vrfyResp.isSignatureVerified()) { // process the optional invalidate_handle first String invalidateHandle = vrfyResp.getInvalidateHandle(); if (invalidateHandle != null) _associations.remove(idp.toString(), invalidateHandle); return true; } else _log.error("OP: " + idp + " says the signature is invalid."); } else { // todo: handle direct verification error responses _log.error("Received verification error response."); } } return false; } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package net.sf.jaer.util; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.PrintStream; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JFileChooser; import net.sf.jaer.Description; public class FilterIndexPrinter { private static final int DIVIDE_INTO_NUM_FILES = 1; // if pages are too long, sf.net allura wiki barfs private static final int MAX_DESC_LENGTH = 1000; private static Logger log=Logger.getLogger("FilterIndexPrinter"); public static void main(final String[] args) throws IOException { final List<String> classList = SubclassFinder.findSubclassesOf("net.sf.jaer.eventprocessing.EventFilter2D"); // Remove duplicates. final HashSet<String> h = new HashSet<String>(classList); classList.clear(); classList.addAll(h); class Filter implements Comparable<Filter> { final String fullName; final String shortName; Filter(final String longName) { fullName = longName; final int point = longName.lastIndexOf("."); shortName = longName.substring(point + 1, longName.length()); } @Override public int compareTo(final Filter o) { return shortName.compareToIgnoreCase(o.shortName); } } final List<Filter> filterList = new ArrayList<Filter>(); for (final String c : classList) { filterList.add(new Filter(c)); } Collections.sort(filterList); /** Get file to save into */ final JFileChooser fileChooser = new JFileChooser("."); final int status = fileChooser.showOpenDialog(null); File selectedFile = null; if (status == JFileChooser.APPROVE_OPTION) { selectedFile = fileChooser.getSelectedFile(); // System.out.println(selectedFile.getParent()); // System.out.println(selectedFile.getName()); } else if (status == JFileChooser.CANCEL_OPTION) { // System.out.println(JFileChooser.CANCEL_OPTION); } if (selectedFile == null) { return; } FileOutputStream fout = null; final FileOutputStream foutAlpha[] = new FileOutputStream[FilterIndexPrinter.DIVIDE_INTO_NUM_FILES]; try { fout = new FileOutputStream(selectedFile.getAbsolutePath()); for (int i = 0; i < foutAlpha.length; i++) { foutAlpha[i] = new FileOutputStream(selectedFile.getAbsolutePath() + "_" + (i + 1)); } } catch (final FileNotFoundException ex) { Logger.getLogger(FilterIndexPrinter.class.getName()).log(Level.SEVERE, null, ex); return; } // Print the file. log.info("Printing index to file "+selectedFile.getAbsolutePath()); final PrintStream ps = new PrintStream(fout); final PrintStream psAlpha[] = new PrintStream[FilterIndexPrinter.DIVIDE_INTO_NUM_FILES]; for (int i = 0; i < foutAlpha.length; i++) { psAlpha[i] = new PrintStream(foutAlpha[i]); } ps.println("# List of Event-Processing Filters"); ps.println(); ps.println("Click on a sub-list for more info on the contained filters."); ps.println("The various lists are sorted alphabetically by filter name."); ps.println(); final int printPerFile = filterList.size() / FilterIndexPrinter.DIVIDE_INTO_NUM_FILES; PrintStream psCurrentFile = null; String firstInList = null; String lastInList = null; for (int i = 0, j = 0; i < filterList.size(); i++) { final Filter f = filterList.get(i); if (((i % printPerFile) == 0) && (j < (FilterIndexPrinter.DIVIDE_INTO_NUM_FILES))) { // Switch to next file. psCurrentFile = psAlpha[j++]; // Add new list link to main index. firstInList = f.shortName; if (j == FilterIndexPrinter.DIVIDE_INTO_NUM_FILES) { lastInList = filterList.get(filterList.size() - 1).shortName; } else { lastInList = filterList.get((i + printPerFile) - 1).shortName; } ps.println("[List of Filters from " + firstInList + " to " + lastInList + "](" + "FilterIndex_" + j + ")"); // Print header. psCurrentFile.println("# List of Event-Processing Filters " + j+"/"+DIVIDE_INTO_NUM_FILES); psCurrentFile.println(); psCurrentFile.println("Click on a filter for more info."); psCurrentFile.println(); psCurrentFile.println("|Filter Name|Description|Package|"); psCurrentFile.println("| } Description des = null; try { final Class<?> c = Class.forName(f.fullName); if (c.isAnnotationPresent(Description.class)) { des = c.getAnnotation(Description.class); } } catch (final SecurityException ex) { Logger.getLogger(FilterIndexPrinter.class.getName()).log(Level.SEVERE, null, ex); } catch (final ClassNotFoundException ex) { Logger.getLogger(FilterIndexPrinter.class.getName()).log(Level.SEVERE, null, ex); } String description; if (des == null) { description = " "; } else { description = des.value(); final int descriptionLength = description.length(); description = description.substring(0, (descriptionLength > FilterIndexPrinter.MAX_DESC_LENGTH) ? (FilterIndexPrinter.MAX_DESC_LENGTH - 1) : (descriptionLength - 1)); // Add open continuation marker. if (descriptionLength > FilterIndexPrinter.MAX_DESC_LENGTH) { description = description + " ..."; } } psCurrentFile.println("|[" + f.shortName + "](filt." + f.fullName + ")|" + description + "|" + f.fullName.substring(0, f.fullName.length() - f.shortName.length() - 1) + "|"); } ps.println(); ps.println("Run the class net.sf.jaer.util.FilterIndexPrinter to regenerate the lists. Save the lists to a name, e.g. filterlist. \nThe result will be a base file filterlist. Then copy the contents of filterlist here, and copy the contents of filterlist_1 to the index of filters, page 1, filterlist_2 to index of filters, page 2, etc."); ps.close(); for (final PrintStream p : psAlpha) { p.close(); } fout.close(); for (final FileOutputStream f : foutAlpha) { f.close(); } log.info("Done"); System.exit(0); } }
package net.wigle.wigleandroid; import static android.location.LocationManager.GPS_PROVIDER; import static android.location.LocationManager.NETWORK_PROVIDER; import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; import java.io.IOException; import java.io.PrintStream; import java.text.DecimalFormat; import java.text.NumberFormat; import java.util.Comparator; import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.Set; import java.util.concurrent.atomic.AtomicBoolean; import org.andnav.osm.util.GeoPoint; import android.app.Activity; import android.content.BroadcastReceiver; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.ServiceConnection; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.content.res.Resources; import android.graphics.Color; import android.location.GpsSatellite; import android.location.GpsStatus; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.location.GpsStatus.Listener; import android.media.AudioManager; import android.media.MediaPlayer; import android.media.MediaPlayer.OnErrorListener; import android.net.Uri; import android.net.wifi.ScanResult; import android.net.wifi.WifiManager; import android.net.wifi.WifiManager.WifiLock; import android.os.Bundle; import android.os.Environment; import android.os.Handler; import android.os.IBinder; import android.provider.Settings; import android.util.Log; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.view.View.OnClickListener; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; public final class WigleAndroid extends Activity { // state. anything added here should be added to the retain copy-construction private ArrayAdapter<Network> listAdapter; private Set<String> runNetworks; private GpsStatus gpsStatus; private Location location; private Location networkLocation; private Handler wifiTimer; private DatabaseHelper dbHelper; private ServiceConnection serviceConnection; private AtomicBoolean finishing; private String savedStats; private long prevNewNetCount; private Long satCountLowTime; // set these times to avoid NPE in locationOK() seen by <DooMMasteR> private Long lastLocationTime = 0L; private Long lastNetworkLocationTime = 0L; private MediaPlayer soundPop; private MediaPlayer soundNewPop; private WifiLock wifiLock; // created every time, even after retain private Listener gpsStatusListener; private LocationListener locationListener; private BroadcastReceiver wifiReceiver; private NumberFormat numberFormat1; private NumberFormat numberFormat8; private TTS tts; private AudioManager audioManager; private long previousTalkTime = System.currentTimeMillis(); private boolean inEmulator; public static final String FILE_POST_URL = "https://wigle.net/gps/gps/main/confirmfile/"; private static final String LOG_TAG = "wigle"; private static final int MENU_SETTINGS = 10; private static final int MENU_EXIT = 11; private static final int MENU_MAP = 12; public static final String ENCODING = "ISO8859_1"; private static final long GPS_TIMEOUT = 15000L; private static final long NET_LOC_TIMEOUT = 60000L; // color by signal strength public static final int COLOR_1 = Color.rgb( 70, 170, 0); public static final int COLOR_2 = Color.rgb(170, 170, 0); public static final int COLOR_3 = Color.rgb(170, 95, 30); public static final int COLOR_4 = Color.rgb(180, 60, 40); public static final int COLOR_5 = Color.rgb(180, 45, 70); // preferences static final String SHARED_PREFS = "WiglePrefs"; static final String PREF_USERNAME = "username"; static final String PREF_PASSWORD = "password"; static final String PREF_SHOW_CURRENT = "showCurrent"; static final String PREF_BE_ANONYMOUS = "beAnonymous"; static final String PREF_DB_MARKER = "dbMarker"; static final String PREF_SCAN_PERIOD = "scanPeriod"; static final String PREF_FOUND_SOUND = "foundSound"; static final String PREF_SPEECH_PERIOD = "speechPeriod"; static final String PREF_SPEECH_GPS = "speechGPS"; static final String PREF_MUTED = "muted"; static final String PREF_WIFI_WAS_OFF = "wifiWasOff"; static final long DEFAULT_SPEECH_PERIOD = 60L; static final String ANONYMOUS = "anonymous"; private static final String WIFI_LOCK_NAME = "wigleWifiLock"; //static final String THREAD_DEATH_MESSAGE = "threadDeathMessage"; /** XXX: switch to using the service */ public static class LameStatic { public Location location; public String savedStats; public ConcurrentLinkedHashMap<GeoPoint,Integer> trail = new ConcurrentLinkedHashMap<GeoPoint,Integer>( 512 ); } public static final LameStatic lameStatic = new LameStatic(); // cache private static final ThreadLocal<CacheMap<String,Network>> networkCache = new ThreadLocal<CacheMap<String,Network>>() { protected CacheMap<String,Network> initialValue() { return new CacheMap<String,Network>( 16, 64 ); } }; private static final Comparator<Network> signalCompare = new Comparator<Network>() { public int compare( Network a, Network b ) { return b.getLevel() - a.getLevel(); } }; /** Called when the activity is first created. */ @Override public void onCreate( final Bundle savedInstanceState ) { super.onCreate( savedInstanceState ); setContentView( R.layout.main ); final String id = Settings.Secure.getString( getContentResolver(), Settings.Secure.ANDROID_ID ); inEmulator = id == null; info( "id: '" + id + "' inEmulator: " + inEmulator ); // Thread.setDefaultUncaughtExceptionHandler( new Thread.UncaughtExceptionHandler(){ // public void uncaughtException( Thread thread, Throwable throwable ) { // String error = "Thread: " + thread + " throwable: " + throwable; // WigleAndroid.error( error ); // throwable.printStackTrace(); // WigleAndroid.writeError( thread, throwable ); // // throw new RuntimeException( error, throwable ); // WigleAndroid.this.finish(); // System.exit( -1 ); final Object stored = getLastNonConfigurationInstance(); if ( stored != null && stored instanceof WigleAndroid ) { // pry an orientation change, which calls destroy, but we set this in onRetainNonConfigurationInstance final WigleAndroid retained = (WigleAndroid) stored; this.listAdapter = retained.listAdapter; this.runNetworks = retained.runNetworks; this.gpsStatus = retained.gpsStatus; this.location = retained.location; this.wifiTimer = retained.wifiTimer; this.dbHelper = retained.dbHelper; this.serviceConnection = retained.serviceConnection; this.finishing = retained.finishing; this.savedStats = retained.savedStats; this.prevNewNetCount = retained.prevNewNetCount; this.soundPop = retained.soundPop; this.soundNewPop = retained.soundNewPop; this.wifiLock = retained.wifiLock; final TextView tv = (TextView) findViewById( R.id.stats ); tv.setText( savedStats ); } else { runNetworks = new HashSet<String>(); finishing = new AtomicBoolean( false ); } numberFormat1 = NumberFormat.getNumberInstance( Locale.US ); if ( numberFormat1 instanceof DecimalFormat ) { ((DecimalFormat) numberFormat1).setMaximumFractionDigits( 1 ); } numberFormat8 = NumberFormat.getNumberInstance( Locale.US ); if ( numberFormat8 instanceof DecimalFormat ) { ((DecimalFormat) numberFormat8).setMaximumFractionDigits( 8 ); } setupService(); setupDatabase(); setupMaxidDebug(); setupUploadButton(); setupList(); setupSound(); setupWifi(); setupLocation(); } @Override public Object onRetainNonConfigurationInstance() { // return this whole class to copy data from return this; } @Override public void onPause() { info( "paused. networks: " + runNetworks.size() ); super.onPause(); } @Override public void onResume() { info( "resumed. networks: " + runNetworks.size() ); super.onResume(); } @Override public void onStart() { info( "start. networks: " + runNetworks.size() ); super.onStart(); } @Override public void onStop() { info( "stop. networks: " + runNetworks.size() ); super.onStop(); } @Override public void onRestart() { info( "restart. networks: " + runNetworks.size() ); super.onRestart(); } @Override public void onDestroy() { info( "destroy. networks: " + runNetworks.size() ); try { this.unregisterReceiver( wifiReceiver ); } catch ( final IllegalArgumentException ex ) { info( "wifiReceiver not registered: " + ex ); } // stop the service, so when we die it's both stopped and unbound and will die final Intent serviceIntent = new Intent( this, WigleService.class ); this.stopService( serviceIntent ); try { this.unbindService( serviceConnection ); } catch ( final IllegalArgumentException ex ) { info( "serviceConnection not registered: " + ex ); } if ( wifiLock != null && wifiLock.isHeld() ) { wifiLock.release(); } // clean up. if ( soundPop != null ) { soundPop.release(); } if ( soundNewPop != null ) { soundNewPop.release(); } super.onDestroy(); } @Override public void finish() { info( "finish. networks: " + runNetworks.size() ); finishing.set( true ); // close the db. not in destroy, because it'll still write after that. dbHelper.close(); final LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); if ( gpsStatusListener != null ) { locationManager.removeGpsStatusListener( gpsStatusListener ); } if ( locationListener != null ) { locationManager.removeUpdates( locationListener ); } try { this.unregisterReceiver( wifiReceiver ); } catch ( final IllegalArgumentException ex ) { info( "wifiReceiver not registered: " + ex ); } // stop the service, so when we die it's both stopped and unbound and will die final Intent serviceIntent = new Intent( this, WigleService.class ); this.stopService( serviceIntent ); try { this.unbindService( serviceConnection ); } catch ( final IllegalArgumentException ex ) { info( "serviceConnection not registered: " + ex ); } // release the lock before turning wifi off if ( wifiLock != null && wifiLock.isHeld() ) { wifiLock.release(); } final SharedPreferences prefs = this.getSharedPreferences( SHARED_PREFS, 0 ); final boolean wifiWasOff = prefs.getBoolean( PREF_WIFI_WAS_OFF, false ); // don't call on emulator, it crashes it if ( wifiWasOff && ! inEmulator ) { // well turn it of now that we're done final WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE); info( "turning back off wifi" ); wifiManager.setWifiEnabled( false ); } if ( tts != null ) { tts.shutdown(); } super.finish(); } /* Creates the menu items */ @Override public boolean onCreateOptionsMenu( final Menu menu ) { MenuItem item = menu.add(0, MENU_EXIT, 0, "Exit"); item.setIcon( android.R.drawable.ic_menu_close_clear_cancel ); item = menu.add(0, MENU_SETTINGS, 0, "Settings"); item.setIcon( android.R.drawable.ic_menu_preferences ); item = menu.add(0, MENU_MAP, 0, "Map"); item.setIcon( android.R.drawable.ic_menu_mapmode ); return true; } /* Handles item selections */ @Override public boolean onOptionsItemSelected( final MenuItem item ) { switch ( item.getItemId() ) { case MENU_SETTINGS: { info("start settings activity"); final Intent intent = new Intent( this, SettingsActivity.class ); this.startActivity( intent ); return true; } case MENU_MAP: { info("start map activity"); final Intent intent = new Intent( this, MappingActivity.class ); this.startActivity( intent ); return true; } case MENU_EXIT: // stop the service, so when we die it's both stopped and unbound and will die final Intent serviceIntent = new Intent( this, WigleService.class ); this.stopService( serviceIntent ); // call over to finish finish(); // actually kill //System.exit( 0 ); return true; } return false; } private void setupDatabase() { // could be set by nonconfig retain if ( dbHelper == null ) { dbHelper = new DatabaseHelper( this ); dbHelper.open(); dbHelper.start(); } dbHelper.checkDB(); } private void setupList() { final LayoutInflater mInflater = (LayoutInflater) getSystemService( Context.LAYOUT_INFLATER_SERVICE ); // may have been set by nonconfig retain if ( listAdapter == null ) { listAdapter = new ArrayAdapter<Network>( this, R.layout.row ) { // @Override // public boolean areAllItemsEnabled() { // return false; // @Override // public boolean isEnabled( int position ) { // return false; @Override public View getView( final int position, final View convertView, final ViewGroup parent ) { // long start = System.currentTimeMillis(); View row; if ( null == convertView ) { row = mInflater.inflate( R.layout.row, null ); } else { row = convertView; } final Network network = getItem(position); // info( "listing net: " + network.getBssid() ); final ImageView ico = (ImageView) row.findViewById( R.id.wepicon ); switch ( network.getCrypto() ) { case Network.CRYPTO_WEP: ico.setImageResource( R.drawable.wep_ico ); break; case Network.CRYPTO_WPA: ico.setImageResource( R.drawable.wpa_ico ); break; case Network.CRYPTO_NONE: ico.setImageResource( R.drawable.no_ico ); break; default: throw new IllegalArgumentException( "unhanded crypto: " + network.getCrypto() + " in network: " + network ); } TextView tv = (TextView) row.findViewById( R.id.ssid ); tv.setText( network.getSsid() ); tv = (TextView) row.findViewById( R.id.level_string ); int level = network.getLevel(); if ( level <= -90 ) { tv.setTextColor( COLOR_5 ); } else if ( level <= -80 ) { tv.setTextColor( COLOR_4 ); } else if ( level <= -70 ) { tv.setTextColor( COLOR_3 ); } else if ( level <= -60 ) { tv.setTextColor( COLOR_2 ); } else { tv.setTextColor( COLOR_1 ); } tv.setText( Integer.toString( level ) ); tv = (TextView) row.findViewById( R.id.detail ); String det = network.getDetail(); tv.setText( det ); // status( position + " view done. ms: " + (System.currentTimeMillis() - start ) ); return row; } }; } final ListView listView = (ListView) findViewById( R.id.ListView01 ); listView.setAdapter( listAdapter ); } private void setupWifi() { // warn about turning off network notification final String notifOn = Settings.Secure.getString(getContentResolver(), Settings.Secure.WIFI_NETWORKS_AVAILABLE_NOTIFICATION_ON ); if ( notifOn != null && "1".equals( notifOn ) ) { Toast.makeText( this, "For best results, unset \"Network notification\" in" + " \"Wireless & networks\"->\"Wi-Fi settings\"", Toast.LENGTH_LONG ).show(); } final WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE); final SharedPreferences prefs = this.getSharedPreferences( SHARED_PREFS, 0 ); final Editor edit = prefs.edit(); if ( ! wifiManager.isWifiEnabled() ) { // save so we can turn it back off when we exit edit.putBoolean( PREF_WIFI_WAS_OFF, true ); // just turn it on, but not in emulator cuz it crashes it if ( ! inEmulator ) { wifiManager.setWifiEnabled( true ); } } else { edit.putBoolean( PREF_WIFI_WAS_OFF, false ); } edit.commit(); // wifi scan listener wifiReceiver = new BroadcastReceiver(){ public void onReceive( final Context context, final Intent intent ){ final long start = System.currentTimeMillis(); final List<ScanResult> results = wifiManager.getScanResults(); // return can be null! final long period = prefs.getLong( PREF_SCAN_PERIOD, 1000L ); if ( period < 1000L ) { // under a second is hard to hit, treat as "continuous", so request scan in here wifiManager.startScan(); } final boolean showCurrent = prefs.getBoolean( PREF_SHOW_CURRENT, true ); if ( showCurrent ) { listAdapter.clear(); } final int preQueueSize = dbHelper.getQueueSize(); final CacheMap<String,Network> networkCache = getNetworkCache(); boolean somethingAdded = false; int resultSize = 0; int newForRun = 0; // can be null on shutdown if ( results != null ) { resultSize = results.size(); for ( ScanResult result : results ) { Network network = networkCache.get( result.BSSID ); if ( network == null ) { network = new Network( result ); networkCache.put( network.getBssid(), network ); } else { // cache hit, just set the level network.setLevel( result.level ); } final boolean added = runNetworks.add( result.BSSID ); if ( added ) { newForRun++; } somethingAdded |= added; // if we're showing current, or this was just added, put on the list if ( showCurrent || added ) { listAdapter.add( network ); // load test // for ( int i = 0; i< 10; i++) { // listAdapter.add( network ); } else { // not showing current, and not a new thing, go find the network and update the level // this is O(n), ohwell, that's why showCurrent is the default config. for ( int index = 0; index < listAdapter.getCount(); index++ ) { final Network testNet = listAdapter.getItem(index); if ( testNet.getBssid().equals( network.getBssid() ) ) { testNet.setLevel( result.level ); } } } if ( location != null && dbHelper != null ) { dbHelper.addObservation( network, location ); } } } // check if there are more "New" nets final long newNetCount = dbHelper.getNewNetworkCount(); final boolean newNet = newNetCount > prevNewNetCount; prevNewNetCount = newNetCount; final boolean play = prefs.getBoolean( PREF_FOUND_SOUND, true ); if ( play && ! isMuted() ) { if ( newNet ) { if ( soundNewPop != null && ! soundNewPop.isPlaying() ) { // play sound on something new soundNewPop.start(); } else { info( "soundNewPop is playing or null" ); } } else if ( somethingAdded ) { if ( soundPop != null && ! soundPop.isPlaying() ) { // play sound on something new soundPop.start(); } else { info( "soundPop is playing or null" ); } } } // sort by signal strength listAdapter.sort( signalCompare ); // update stat final TextView tv = (TextView) findViewById( R.id.stats ); final StringBuilder builder = new StringBuilder( 40 ); builder.append( "Run: " ).append( runNetworks.size() ); builder.append( " New: " ).append( newNetCount ); builder.append( " DB: " ).append( dbHelper.getNetworkCount() ); builder.append( " Locs: " ).append( dbHelper.getLocationCount() ); savedStats = builder.toString(); tv.setText( savedStats ); // set the statics for the map WigleAndroid.lameStatic.savedStats = savedStats; if ( newForRun > 0 && location != null ) { final GeoPoint geoPoint = new GeoPoint( location ); Integer points = lameStatic.trail.get( geoPoint ); if ( points == null ) { points = newForRun; } else { points += newForRun; } lameStatic.trail.put( geoPoint, points ); } // info( savedStats ); // notify listAdapter.notifyDataSetChanged(); final long now = System.currentTimeMillis(); status( resultSize + " scanned in " + (now - start) + "ms. DB Queue: " + preQueueSize ); final long speechPeriod = prefs.getLong( PREF_SPEECH_PERIOD, DEFAULT_SPEECH_PERIOD ); if ( speechPeriod != 0 && now - previousTalkTime > speechPeriod * 1000L ) { String gps = ""; if ( location == null ) { gps = ", no gps fix"; } speak("run " + runNetworks.size() + ", new " + newNetCount + gps ); previousTalkTime = now; } } }; // register final IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction( WifiManager.SCAN_RESULTS_AVAILABLE_ACTION ); this.registerReceiver( wifiReceiver, intentFilter ); if ( wifiLock == null ) { // lock the radio on wifiLock = wifiManager.createWifiLock( WifiManager.WIFI_MODE_SCAN_ONLY, WIFI_LOCK_NAME ); wifiLock.acquire(); } // might not be null on a nonconfig retain if ( wifiTimer == null ) { wifiTimer = new Handler(); final Runnable mUpdateTimeTask = new Runnable() { public void run() { // make sure the app isn't trying to finish if ( ! finishing.get() ) { // info( "timer start scan" ); wifiManager.startScan(); final long period = prefs.getLong( PREF_SCAN_PERIOD, 1000L); // info("wifitimer: " + period ); wifiTimer.postDelayed( this, period ); } else { info( "finishing timer" ); } } }; wifiTimer.removeCallbacks( mUpdateTimeTask ); wifiTimer.postDelayed( mUpdateTimeTask, 100 ); // starts scan, sends event when done final boolean scanOK = wifiManager.startScan(); info( "startup finished. wifi scanOK: " + scanOK ); } } private void speak( final String string ) { if ( ! isMuted() && tts != null ) { tts.speak( string ); } } private void setupLocation() { // set on UI if we already have one updateLocationData( (Location) null ); final LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); if ( ! locationManager.isProviderEnabled( GPS_PROVIDER ) ) { Toast.makeText( this, "Please turn on GPS", Toast.LENGTH_SHORT ).show(); final Intent myIntent = new Intent( Settings.ACTION_SECURITY_SETTINGS ); startActivity(myIntent); } // emulator crashes if you ask this if ( ! inEmulator && ! locationManager.isProviderEnabled( NETWORK_PROVIDER ) ) { Toast.makeText( this, "For best results, set \"Use wireless networks\" in \"Location & security\"", Toast.LENGTH_LONG ).show(); } gpsStatusListener = new Listener(){ public void onGpsStatusChanged( final int event ) { updateLocationData( (Location) null ); } }; locationManager.addGpsStatusListener( gpsStatusListener ); final List<String> providers = locationManager.getAllProviders(); locationListener = new LocationListener(){ public void onLocationChanged( final Location newLocation ) { updateLocationData( newLocation ); } public void onProviderDisabled( final String provider ) {} public void onProviderEnabled( final String provider ) {} public void onStatusChanged( final String provider, final int status, final Bundle extras ) {} }; for ( String provider : providers ) { info( "provider: " + provider ); locationManager.requestLocationUpdates( provider, 1000L, 0, locationListener ); } } /** newLocation can be null */ private void updateLocationData( final Location newLocation ) { final LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); // see if we have new data gpsStatus = locationManager.getGpsStatus( gpsStatus ); final int satCount = getSatCount(); boolean newOK = newLocation != null; final boolean locOK = locationOK( location, satCount ); final long now = System.currentTimeMillis(); if ( newOK ) { if ( NETWORK_PROVIDER.equals( newLocation.getProvider() ) ) { // save for later, in case we lose gps networkLocation = newLocation; lastNetworkLocationTime = now; } else { lastLocationTime = now; // make sure there's enough sats on this new gps location newOK = locationOK( newLocation, satCount ); } } final boolean netLocOK = locationOK( networkLocation, satCount ); boolean wasProviderChange = false; if ( ! locOK ) { if ( newOK ) { wasProviderChange = true; if ( location != null && ! location.getProvider().equals( newLocation.getProvider() ) ) { wasProviderChange = false; } location = newLocation; } else if ( netLocOK ) { location = networkLocation; wasProviderChange = true; } else if ( location != null ) { // transition to null info( "nulling location: " + location ); location = null; wasProviderChange = true; } } else if ( newOK && GPS_PROVIDER.equals( newLocation.getProvider() ) ) { if ( NETWORK_PROVIDER.equals( location.getProvider() ) ) { // this is an upgrade from network to gps wasProviderChange = true; } location = newLocation; } else if ( newOK && NETWORK_PROVIDER.equals( newLocation.getProvider() ) ) { if ( NETWORK_PROVIDER.equals( location.getProvider() ) ) { // just a new network provided location over an old one location = newLocation; } } // for maps. so lame! lameStatic.location = location; if ( wasProviderChange ) { info( "wasProviderChange: run: " + this.runNetworks.size() + " satCount: " + satCount + " newOK: " + newOK + " locOK: " + locOK + " netLocOK: " + netLocOK + " wasProviderChange: " + wasProviderChange + (newOK ? " newProvider: " + newLocation.getProvider() : "") + (locOK ? " locProvider: " + location.getProvider() : "") + " newLocation: " + newLocation ); } if ( wasProviderChange ) { final String announce = location == null ? "Lost Location" : "Now have location from \"" + location.getProvider() + "\""; Toast.makeText( this, announce, Toast.LENGTH_SHORT ).show(); final SharedPreferences prefs = this.getSharedPreferences( SHARED_PREFS, 0 ); final boolean speechGPS = prefs.getBoolean( PREF_SPEECH_GPS, true ); if ( speechGPS ) { // no quotes or the voice pauses final String speakAnnounce = location == null ? "Lost Location" : "Now have location from " + location.getProvider() + "."; speak( speakAnnounce ); } } // update the UI setLocationUI(); } private boolean locationOK( final Location location, final int satCount ) { boolean retval = false; final long now = System.currentTimeMillis(); if ( location == null ) { // bad! } else if ( GPS_PROVIDER.equals( location.getProvider() ) ) { if ( satCount < 3 ) { if ( satCountLowTime == null ) { satCountLowTime = now; } } else { // plenty of sats satCountLowTime = null; } boolean gpsLost = satCountLowTime != null && (now - satCountLowTime) > GPS_TIMEOUT; gpsLost |= now - lastLocationTime > GPS_TIMEOUT; retval = ! gpsLost; } else if ( NETWORK_PROVIDER.equals( location.getProvider() ) ) { boolean gpsLost = now - lastNetworkLocationTime > NET_LOC_TIMEOUT; retval = ! gpsLost; } return retval; } private int getSatCount() { int satCount = 0; if ( gpsStatus != null ) { for ( GpsSatellite sat : gpsStatus.getSatellites() ) { if ( sat.usedInFix() ) { satCount++; } } } return satCount; } private void setLocationUI() { if ( gpsStatus != null ) { final int satCount = getSatCount(); final TextView tv = (TextView) this.findViewById( R.id.LocationTextView06 ); tv.setText( "Sats: " + satCount ); } TextView tv = (TextView) this.findViewById( R.id.LocationTextView01 ); tv.setText( "Lat: " + (location == null ? " (Waiting for GPS sync..)" : numberFormat8.format( location.getLatitude() ) ) ); tv = (TextView) this.findViewById( R.id.LocationTextView02 ); tv.setText( "Lon: " + (location == null ? "" : numberFormat8.format( location.getLongitude() ) ) ); tv = (TextView) this.findViewById( R.id.LocationTextView03 ); tv.setText( "Speed: " + (location == null ? "" : numberFormat1.format( location.getSpeed() * 2.23693629f ) + "mph" ) ); tv = (TextView) this.findViewById( R.id.LocationTextView04 ); tv.setText( location == null ? "" : ("+/- " + numberFormat1.format( location.getAccuracy() ) + "m") ); tv = (TextView) this.findViewById( R.id.LocationTextView05 ); tv.setText( location == null ? "" : ("Alt: " + numberFormat1.format( location.getAltitude() ) + "m") ); } private void setupUploadButton() { final Button button = (Button) findViewById( R.id.upload_button ); button.setOnClickListener( new OnClickListener() { public void onClick( final View view ) { uploadFile( WigleAndroid.this, dbHelper ); } }); } private void setupService() { final Intent serviceIntent = new Intent( this, WigleService.class ); // could be set by nonconfig retain if ( serviceConnection == null ) { final ComponentName compName = startService( serviceIntent ); if ( compName == null ) { WigleAndroid.error( "startService() failed!" ); } else { WigleAndroid.info( "service started ok: " + compName ); } serviceConnection = new ServiceConnection(){ public void onServiceConnected( final ComponentName name, final IBinder iBinder ) { WigleAndroid.info( name + " service connected" ); } public void onServiceDisconnected( final ComponentName name ) { WigleAndroid.info( name + " service disconnected" ); } }; } int flags = 0; this.bindService( serviceIntent, serviceConnection, flags ); } private void setupSound() { // could have been retained if ( soundPop == null ) { soundPop = createMediaPlayer( R.raw.pop ); } if ( soundNewPop == null ) { soundNewPop = createMediaPlayer( R.raw.newpop ); } audioManager = (AudioManager) this.getSystemService(Context.AUDIO_SERVICE); // make volume change "media" this.setVolumeControlStream( AudioManager.STREAM_MUSIC ); if ( TTS.hasTTS() ) { tts = new TTS( this ); } final Button mute = (Button) this.findViewById(R.id.mute); final SharedPreferences prefs = this.getSharedPreferences(SHARED_PREFS, 0); final boolean muted = prefs.getBoolean(PREF_MUTED, false); if ( muted ) { mute.setText("Play"); } mute.setOnClickListener(new OnClickListener(){ public void onClick( final View buttonView ) { boolean muted = prefs.getBoolean(PREF_MUTED, false); muted = ! muted; Editor editor = prefs.edit(); editor.putBoolean( PREF_MUTED, muted ); editor.commit(); if ( muted ) { mute.setText("Play"); } else { mute.setText("Mute"); } } }); } /** * create a mediaplayer for a given raw resource id. * @param soundId the R.raw. id for a given sound * @return the mediaplayer for soundId or null if it could not be created. */ private MediaPlayer createMediaPlayer( final int soundId ) { final MediaPlayer sound = createMp( this, soundId ); if ( sound == null ) { info( "sound null from media player" ); return null; } // try to figure out why sounds stops after a while sound.setOnErrorListener( new OnErrorListener() { public boolean onError( final MediaPlayer mp, final int what, final int extra ) { String whatString = null; switch ( what ) { case MediaPlayer.MEDIA_ERROR_UNKNOWN: whatString = "error unknown"; break; case MediaPlayer.MEDIA_ERROR_SERVER_DIED: whatString = "server died"; break; default: whatString = "not defined"; } info( "media player error \"" + whatString + "\" what: " + what + " extra: " + extra + " mp: " + mp ); return false; } } ); return sound; } /** * externalize the file from a given resource id (if it dosen't already exist), write to our dir if there is one. * @param context the context to use * @param resid the resource id * @param name the file name to write out * @return the uri of a file containing resid's resource */ private static Uri resToFile( final Context context, final int resid, final String name ) throws IOException { // throw it in our bag of fun. String openString = name; final boolean hasSD = hasSD(); if ( hasSD ) { final String filepath = Environment.getExternalStorageDirectory().getCanonicalPath() + "/wiglewifi/"; final File path = new File( filepath ); path.mkdirs(); openString = filepath + name; } final File f = new File( openString ); // see if it exists already if ( ! f.exists() ) { info("causing "+f.getCanonicalPath()+" to be made"); // make it happen: f.createNewFile(); InputStream is = null; FileOutputStream fos = null; try { is = context.getResources().openRawResource( resid ); if ( hasSD ) { fos = new FileOutputStream( f ); } else { // XXX: should this be using openString instead? baroo? fos = context.openFileOutput( name, Context.MODE_WORLD_READABLE ); } final byte[] buff = new byte[ 1024 ]; int rv = -1; while( ( rv = is.read( buff ) ) > -1 ) { fos.write( buff, 0, rv ); } } finally { if ( fos != null ) { fos.close(); } if ( is != null ) { is.close(); } } } return Uri.fromFile( f ); } /** * create a media player (trying several paths if available) * @param context the context to use * @param resid the resource to use * @return the media player for resid (or null if it wasn't creatable) */ private static MediaPlayer createMp( final Context context, final int resid ) { try { MediaPlayer mp = MediaPlayer.create( context, resid ); // this can fail for many reasons, but android 1.6 on archos5 definitely hates creating from resource if ( mp == null ) { Uri sounduri; // XXX: find a better way? baroo. if ( resid == R.raw.pop ) { sounduri = resToFile( context, resid, "pop.wav" ); } else if ( resid == R.raw.newpop ) { sounduri = resToFile( context, resid, "newpop.wav" ); } else { info( "unknown raw sound id:"+resid ); return null; } mp = MediaPlayer.create( context, sounduri ); // may still end up null } return mp; } catch (IOException ex) { error("ioe create failed:", ex); // fall through } catch (IllegalArgumentException ex) { error("iae create failed:", ex); // fall through } catch (SecurityException ex) { error("se create failed:", ex); // fall through } catch ( Resources.NotFoundException ex ) { error("rnfe create failed("+resid+"):", ex ); } return null; } @SuppressWarnings("unused") private boolean isRingerOn() { boolean retval = false; if ( audioManager != null ) { retval = audioManager.getRingerMode() == AudioManager.RINGER_MODE_NORMAL; } return retval; } private boolean isMuted() { boolean retval = this.getSharedPreferences(SHARED_PREFS, 0).getBoolean(PREF_MUTED, false); // info( "ismuted: " + retval ); return retval; } private static void uploadFile( final Context context, final DatabaseHelper dbHelper ){ info( "upload file" ); final FileUploaderTask task = new FileUploaderTask( context, dbHelper ); task.start(); } private void status( String status ) { // info( status ); final TextView tv = (TextView) findViewById( R.id.status ); tv.setText( status ); } public static void sleep( final long sleep ) { try { Thread.sleep( sleep ); } catch ( final InterruptedException ex ) { // no worries } } public static void info( final String value ) { Log.i( LOG_TAG, Thread.currentThread().getName() + "] " + value ); } public static void error( final String value ) { Log.e( LOG_TAG, Thread.currentThread().getName() + "] " + value ); } public static void error( final String value, final Throwable t ) { Log.e( LOG_TAG, Thread.currentThread().getName() + "] " + value, t ); } /** * get the per-thread network LRU cache * @return per-thread network cache */ public static CacheMap<String,Network> getNetworkCache() { return networkCache.get(); } public static void writeError( final Thread thread, final Throwable throwable ) { try { final String error = "Thread: " + thread + " throwable: " + throwable; error( error ); if ( hasSD() ) { File file = new File( Environment.getExternalStorageDirectory().getCanonicalPath() + "/wiglewifi/" ); file.mkdirs(); file = new File(Environment.getExternalStorageDirectory().getCanonicalPath() + "/wiglewifi/errorstack_" + System.currentTimeMillis() + ".txt" ); if ( ! file.exists() ) { file.createNewFile(); } final FileOutputStream fos = new FileOutputStream( file ); fos.write( error.getBytes( ENCODING ) ); throwable.printStackTrace( new PrintStream( fos ) ); fos.close(); } } catch ( final Exception ex ) { error( "error logging error: " + ex ); ex.printStackTrace(); } } public static boolean hasSD() { File sdCard = null; try { sdCard = new File( Environment.getExternalStorageDirectory().getCanonicalPath() + "/" ); } catch ( final IOException ex ) { // ohwell } return sdCard != null && sdCard.exists() && sdCard.isDirectory() && sdCard.canRead() && sdCard.canWrite(); } private void setupMaxidDebug() { final SharedPreferences prefs = WigleAndroid.this.getSharedPreferences( SHARED_PREFS, 0 ); final long maxid = prefs.getLong( PREF_DB_MARKER, -1L ); if ( maxid == -1L ) { // load up the local value dbHelper.getLocationCountFromDB(); final long loccount = dbHelper.getLocationCount(); if ( loccount > 0 ) { // there is no preference set, yet there are locations, this is likely // a developer testing a new install on an old db, so set the pref. info( "setting db marker to: " + loccount ); final Editor edit = prefs.edit(); edit.putLong( PREF_DB_MARKER, loccount ); edit.commit(); } } } }
package burlap.behavior.singleagent; import burlap.behavior.policy.Policy; import burlap.behavior.policy.RandomPolicy; import burlap.datastructures.AlphanumericSorting; import burlap.domain.singleagent.gridworld.GridWorldDomain; import burlap.oomdp.auxiliary.common.NullTermination; import burlap.oomdp.core.Domain; import burlap.oomdp.core.State; import burlap.oomdp.singleagent.Action; import burlap.oomdp.singleagent.GroundedAction; import burlap.oomdp.singleagent.common.NullAction; import burlap.oomdp.singleagent.common.NullRewardFunction; import org.yaml.snakeyaml.Yaml; import org.yaml.snakeyaml.constructor.AbstractConstruct; import org.yaml.snakeyaml.constructor.Constructor; import org.yaml.snakeyaml.nodes.Node; import org.yaml.snakeyaml.nodes.ScalarNode; import org.yaml.snakeyaml.nodes.Tag; import org.yaml.snakeyaml.representer.Represent; import org.yaml.snakeyaml.representer.Representer; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.FilenameFilter; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Scanner; public class EpisodeAnalysis { /** * The sequence of states observed */ public List<State> stateSequence; /** * The sequence of actions taken */ public List<GroundedAction> actionSequence; /** * The sequence of rewards received. Note the reward stored at index i is the reward received at time step i+1. */ public List<Double> rewardSequence; /** * Creates a new EpisodeAnalysis object. Before recording transitions, the {@link #initializeEpisideWithInitialState(State)} method * should be called to set the initial state of the episode. */ public EpisodeAnalysis(){ this.initializeDatastructures(); } /** * Initializes a new EpisodeAnalysis object with the initial state in which the episode started. * @param initialState the initial state of the episode */ public EpisodeAnalysis(State initialState){ this.initializeEpisideWithInitialState(initialState); } /** * Initializes this object with the initial state in which the episode started. * @param initialState the initial state of the episode */ public void initializeEpisideWithInitialState(State initialState){ this.initializeDatastructures(); this.stateSequence.add(initialState); } protected void initializeDatastructures(){ stateSequence = new ArrayList<State>(); actionSequence = new ArrayList<GroundedAction>(); rewardSequence = new ArrayList<Double>(); } /** * Adds a state to the state sequence. In general, it is recommended that {@link #initializeEpisideWithInitialState(State)} method * along with subsequent calls to the {@link #recordTransitionTo(GroundedAction, State, double)} method is used instead, but this * method can be used to manually add a state. * @param s the state to add */ public void addState(State s){ stateSequence.add(s); } /** * Adds a GroundedAction to the action sequence. In general, it is recommended that {@link #initializeEpisideWithInitialState(State)} method * along with subsequent calls to the {@link #recordTransitionTo(GroundedAction, State, double)} method is used instead, but this * method can be used to manually add a GroundedAction. * @param ga the GroundedAction to add */ public void addAction(GroundedAction ga){ actionSequence.add(ga); } /** * Adds a reward to the reward sequence. In general, it is recommended that {@link #initializeEpisideWithInitialState(State)} method * along with subsequent calls to the {@link #recordTransitionTo(GroundedAction, State, double)} method is used instead, but this * method can be used to manually add a reward. * @param r the reward to add */ public void addReward(double r){ rewardSequence.add(r); } /** * Records an transition event where the agent applied the usingAction argument in the last * state in this object's state sequence, received reward r, and transitioned to state next. * @param next the next state to which the agent transitioned * @param usingAction the action the agent used that caused the transition * @param r the reward the agent received for this transition. */ @Deprecated public void recordTransitionTo(State next, GroundedAction usingAction, double r){ stateSequence.add(next); actionSequence.add(usingAction); rewardSequence.add(r); } /** * Records an transition event where the agent applied the usingAction action in the last * state in this object's state sequence, transitioned to state nextState, and received reward r,. * @param usingAction the action the agent used that caused the transition * @param nextState the next state to which the agent transitioned * @param r the reward the agent received for this transition. */ public void recordTransitionTo(GroundedAction usingAction, State nextState, double r){ stateSequence.add(nextState); actionSequence.add(usingAction); rewardSequence.add(r); } /** * Returns the state observed at time step t. t=0 refers to the initial state. * @param t the time step of the episode * @return the state at time step t */ public State getState(int t){ return stateSequence.get(t); } /** * Returns the action taken in the state at time step t. t=0 refers to the action taken in the initial state. * @param t the time step of the episode * @return the action taken at time step t */ public GroundedAction getAction(int t){ return actionSequence.get(t); } /** * Returns the reward received at timestep t. Note that the fist received reward will be at time step 1, which is the reward received * after taking the first action in the initial state. * @param t the time step of the episode * @return the ith reward received in this episode */ public double getReward(int t){ if(t == 0){ throw new RuntimeException("Cannot return the reward received at time step 0; the first received reward occurs after the initial state at time step 1"); } if(t > rewardSequence.size()){ throw new RuntimeException("There are only " + this.rewardSequence.size() + " rewards recorded; cannot return the reward for time step " + t); } return rewardSequence.get(t-1); } /** * Returns the number of time steps in this episode, which is equivalent to the number of states. * @return the number of time steps in this episode */ public int numTimeSteps(){ return stateSequence.size(); //state sequence will always have the most because of initial state and terminal state } /** * Returns the maximimum time step index in this episode which is the {@link #numTimeSteps()}-1. * @return the maximum time step index in this episode */ public int maxTimeStep(){ return this.stateSequence.size()-1; } /** * Will return the discounted return received from the first state in the episode to the last state in the episode. * @param discountFactor the discount factor to compute the discounted return; should be on [0, 1] * @return the discounted return of the episode */ public double getDiscountedReturn(double discountFactor){ double discount = 1.; double sum = 0.; for(double r : rewardSequence){ sum += discount*r; discount *= discountFactor; } return sum; } /** * This method will append execution results in e to this object's results. Note that it is assumed that the initial state in e * is the last state recorded in this object. This method is useful for appending the results of an option's execution * to a episode. * @param e the execution results to append to this episode. */ public void appendAndMergeEpisodeAnalysis(EpisodeAnalysis e){ for(int i = 0; i < e.numTimeSteps()-1; i++){ this.recordTransitionTo(e.getAction(i), e.getState(i+1), e.getReward(i+1)); } } /** * Returns a string representing the actions taken in this episode. Actions are separated * by ';' characters. * @return a string representing the actions taken in this episode */ public String getActionSequenceString(){ return this.getActionSequenceString("; "); } /** * Returns a string representing the actions taken in this episode. Actions are separated * by the provided delimiter string. * @param delimiter the delimiter to separate actions in the string. * @return a string representing the actions taken in this episode */ public String getActionSequenceString(String delimiter){ StringBuilder buf = new StringBuilder(); boolean first = true; for(GroundedAction ga : actionSequence){ if(!first){ buf.append(delimiter); } buf.append(ga.toString()); first = false; } return buf.toString(); } /** * Takes a {@link java.util.List} of {@link burlap.behavior.singleagent.EpisodeAnalysis} objects and writes them to a directory. * The format of the file names will be "baseFileName{index}.episode" where {index} represents the index of the * episode in the list. States must be serializable. * @param episodes the list of episodes to write to disk * @param directoryPath the directory path in which the episodes will be written * @param baseFileName the base file name to use for the episode files */ public static void writeEpisodesToDisk(List<EpisodeAnalysis> episodes, String directoryPath, String baseFileName){ if(!directoryPath.endsWith("/")){ directoryPath += "/"; } for(int i = 0; i < episodes.size(); i++){ EpisodeAnalysis ea = episodes.get(i); ea.writeToFile(directoryPath + baseFileName + i); } } /** * Writes this episode to a file. If the the directory for the specified file path do not exist, then they will be created. * If the file extension is not ".episode" will automatically be added. States must be serializable. * @param path the path to the file in which to write this episode. */ public void writeToFile(String path){ if(!path.endsWith(".episode")){ path = path + ".episode"; } File f = (new File(path)).getParentFile(); if(f != null){ f.mkdirs(); } try{ String str = this.serialize(); BufferedWriter out = new BufferedWriter(new FileWriter(path)); out.write(str); out.close(); }catch(Exception e){ System.out.println(e); } } /** * Takes a path to a directory containing .episode files and reads them all into a {@link java.util.List} * of {@link burlap.behavior.singleagent.EpisodeAnalysis} objects. * @param directoryPath the path to the directory containing the episode files * @param d the domain to which the episode states and actions belong * @return a {@link java.util.List} of {@link burlap.behavior.singleagent.EpisodeAnalysis} objects. */ public static List<EpisodeAnalysis> parseFilesIntoEAList(String directoryPath, Domain d){ if(!directoryPath.endsWith("/")){ directoryPath = directoryPath + "/"; } File dir = new File(directoryPath); final String ext = ".episode"; FilenameFilter filter = new FilenameFilter() { public boolean accept(File dir, String name) { if(name.endsWith(ext)){ return true; } return false; } }; String[] children = dir.list(filter); Arrays.sort(children, new AlphanumericSorting()); List<EpisodeAnalysis> eas = new ArrayList<EpisodeAnalysis>(children.length); for(int i = 0; i < children.length; i++){ String episodeFile = directoryPath + children[i]; EpisodeAnalysis ea = parseFileIntoEA(episodeFile, d); eas.add(ea); } return eas; } /** * Reads an episode that was written to a file and turns into an EpisodeAnalysis object. * @param path the path to the episode file. * @param d the domain to which the states and actions belong * @return an EpisodeAnalysis object. */ public static EpisodeAnalysis parseFileIntoEA(String path, Domain d){ //read whole file into string first String fcont = null; try{ fcont = new Scanner(new File(path)).useDelimiter("\\Z").next(); }catch(Exception E){ System.out.println(E); } return parseEpisode(d, fcont); } public String serialize(){ Yaml yaml = new Yaml(new EpisodeAnalysisYamlRepresenter()); String yamlOut = yaml.dump(this); return yamlOut; } private class EpisodeAnalysisYamlRepresenter extends Representer{ public EpisodeAnalysisYamlRepresenter() { super(); for(GroundedAction ga : actionSequence){ this.representers.put(ga.getClass(), new ActionYamlRepresent()); } } private class ActionYamlRepresent implements Represent{ @Override public Node representData(Object o) { return representScalar(new Tag("!action"), o.toString()); } } } public static EpisodeAnalysis parseEpisode(Domain domain, String episodeString){ Yaml yaml = new Yaml(new EpisodeAnalysisConstructor(domain)); EpisodeAnalysis ea = (EpisodeAnalysis)yaml.load(episodeString); return ea; } private static class EpisodeAnalysisConstructor extends Constructor{ Domain domain; public EpisodeAnalysisConstructor(Domain domain) { this.domain = domain; yamlConstructors.put(new Tag("!action"), new ActionConstruct()); } private class ActionConstruct extends AbstractConstruct{ @Override public Object construct(Node node) { String val = (String) constructScalar((ScalarNode)node); GroundedAction ga = getGAFromSpaceDelimGAString(domain, val); return ga; } } } private static GroundedAction getGAFromSpaceDelimGAString(Domain d, String str){ //handle option annotated grounded actions if(str.startsWith("*")){ String [] annotatedParts = str.split(" GroundedAction primitivePart = getGAFromSpaceDelimGAString(d, annotatedParts[1]); String annotation = annotatedParts[0].substring(1); Policy.GroundedAnnotatedAction ga = new Policy.GroundedAnnotatedAction(annotation, primitivePart); return ga; } else { String[] scomps = str.split(" "); Action a = d.getAction(scomps[0]); if(a == null) { //the domain does not have a reference, so create a null action in its place a = new NullAction(scomps[0]); } String[] params = new String[scomps.length - 1]; for(int i = 1; i < scomps.length; i++) { params[i - 1] = scomps[i]; } GroundedAction ga = a.getAssociatedGroundedAction(); ga.initParamsWithStringRep(params); return ga; } } public static void main(String[] args) { GridWorldDomain gwd = new GridWorldDomain(11, 11); Domain domain = gwd.generateDomain(); State s = GridWorldDomain.getOneAgentNoLocationState(domain, 1, 3); Policy p = new RandomPolicy(domain); EpisodeAnalysis ea = p.evaluateBehavior(s, new NullRewardFunction(), new NullTermination(), 30); String yamlOut = ea.serialize(); System.out.println(yamlOut); System.out.println("\n\n"); EpisodeAnalysis read = EpisodeAnalysis.parseEpisode(domain, yamlOut); System.out.println(read.getActionSequenceString()); System.out.println(read.getState(0).toString()); System.out.println(read.actionSequence.size()); System.out.println(read.stateSequence.size()); } }
package com.akjava.gwt.poseeditor.client; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import com.akjava.bvh.client.BVH; import com.akjava.bvh.client.BVHNode; import com.akjava.bvh.client.BVHParser; import com.akjava.bvh.client.BVHParser.ParserListener; import com.akjava.bvh.client.gwt.BoxData; import com.akjava.bvh.client.gwt.BoxDataParser; import com.akjava.bvh.client.threejs.AnimationBoneConverter; import com.akjava.bvh.client.threejs.AnimationDataConverter; import com.akjava.bvh.client.threejs.BVHConverter; import com.akjava.bvh.client.BVHWriter; import com.akjava.bvh.client.BVHMotion; import com.akjava.gwt.html5.client.HTML5InputRange; import com.akjava.gwt.html5.client.HTML5InputRange.HTML5InputRangeListener; import com.akjava.gwt.html5.client.extra.HTML5Builder; import com.akjava.gwt.poseeditor.client.resources.Bundles; import com.akjava.gwt.three.client.THREE; import com.akjava.gwt.three.client.core.Geometry; import com.akjava.gwt.three.client.core.Intersect; import com.akjava.gwt.three.client.core.Matrix4; import com.akjava.gwt.three.client.core.Object3D; import com.akjava.gwt.three.client.core.Projector; import com.akjava.gwt.three.client.core.Quaternion; import com.akjava.gwt.three.client.core.Vector3; import com.akjava.gwt.three.client.core.Vector4; import com.akjava.gwt.three.client.core.Vertex; import com.akjava.gwt.three.client.extras.GeometryUtils; import com.akjava.gwt.three.client.extras.ImageUtils; import com.akjava.gwt.three.client.extras.loaders.JSONLoader; import com.akjava.gwt.three.client.extras.loaders.JSONLoader.LoadHandler; import com.akjava.gwt.three.client.gwt.GWTGeometryUtils; import com.akjava.gwt.three.client.gwt.GWTThreeUtils; import com.akjava.gwt.three.client.gwt.SimpleDemoEntryPoint; import com.akjava.gwt.three.client.gwt.ThreeLog; import com.akjava.gwt.three.client.gwt.animation.AnimationBone; import com.akjava.gwt.three.client.gwt.animation.AnimationBonesData; import com.akjava.gwt.three.client.gwt.animation.AnimationData; import com.akjava.gwt.three.client.gwt.animation.AnimationHierarchyItem; import com.akjava.gwt.three.client.gwt.animation.AnimationKey; import com.akjava.gwt.three.client.gwt.animation.BoneLimit; import com.akjava.gwt.three.client.gwt.animation.NameAndVector3; import com.akjava.gwt.three.client.gwt.animation.WeightBuilder; import com.akjava.gwt.three.client.gwt.animation.ik.CDDIK; import com.akjava.gwt.three.client.gwt.animation.ik.IKData; import com.akjava.gwt.three.client.lights.Light; import com.akjava.gwt.three.client.materials.Material; import com.akjava.gwt.three.client.objects.Mesh; import com.akjava.gwt.three.client.renderers.WebGLRenderer; import com.google.gwt.core.client.JsArray; import com.google.gwt.event.dom.client.ChangeEvent; import com.google.gwt.event.dom.client.ChangeHandler; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.event.dom.client.MouseDownEvent; import com.google.gwt.event.dom.client.MouseMoveEvent; import com.google.gwt.event.dom.client.MouseOutEvent; import com.google.gwt.event.dom.client.MouseUpEvent; import com.google.gwt.event.dom.client.MouseUpHandler; import com.google.gwt.event.dom.client.MouseWheelEvent; import com.google.gwt.http.client.Request; import com.google.gwt.http.client.RequestBuilder; import com.google.gwt.http.client.RequestCallback; import com.google.gwt.http.client.RequestException; import com.google.gwt.http.client.Response; import com.google.gwt.http.client.URL; import com.google.gwt.user.client.Window; import com.google.gwt.user.client.ui.Button; import com.google.gwt.user.client.ui.CheckBox; import com.google.gwt.user.client.ui.HorizontalPanel; import com.google.gwt.user.client.ui.Label; import com.google.gwt.user.client.ui.ListBox; import com.google.gwt.user.client.ui.Panel; import com.google.gwt.user.client.ui.PopupPanel; import com.google.gwt.user.client.ui.VerticalPanel; /** * Entry point classes define <code>onModuleLoad()</code>. */ public class PoseEditor extends SimpleDemoEntryPoint{ private BVH bvh; protected JsArray<AnimationBone> bones; private AnimationData animationData; @Override protected void beforeUpdate(WebGLRenderer renderer) { if(root!=null){ root.setPosition(positionXRange.getValue(), positionYRange.getValue(), positionZRange.getValue()); root.getRotation().set(Math.toRadians(rotationRange.getValue()),Math.toRadians(rotationYRange.getValue()),Math.toRadians(rotationZRange.getValue())); } } @Override public void resized(int width, int height) { super.resized(width, height); leftBottom(bottomPanel); } private Map<String,BoxData> boxDatas; @Override protected void initializeOthers(WebGLRenderer renderer) { canvas.setClearColorHex(0x333333); scene.add(THREE.AmbientLight(0xffffff)); Light pointLight = THREE.DirectionalLight(0xffffff,1); pointLight.setPosition(0, 10, 300); scene.add(pointLight); Light pointLight2 = THREE.DirectionalLight(0xffffff,1);//for fix back side dark problem pointLight2.setPosition(0, 10, -300); //scene.add(pointLight2); root=THREE.Object3D(); scene.add(root); Geometry geo=THREE.PlaneGeometry(100, 100,10,10); Mesh mesh=THREE.Mesh(geo, THREE.MeshBasicMaterial().color(0xaaaaaa).wireFrame().build()); mesh.setRotation(Math.toRadians(-90), 0, 0); root.add(mesh); Mesh xline=GWTGeometryUtils.createLineMesh(THREE.Vector3(-50, 0, 0.001), THREE.Vector3(50, 0, 0.001), 0x880000,3); //root.add(xline); Mesh zline=GWTGeometryUtils.createLineMesh(THREE.Vector3(0, 0, -50), THREE.Vector3(0, 0, 50), 0x008800,3); //root.add(zline); selectionMesh=THREE.Mesh(THREE.CubeGeometry(2, 2, 2), THREE.MeshBasicMaterial().color(0x00ff00).wireFrame(true).build()); root.add(selectionMesh); selectionMesh.setVisible(false); //line flicked think something boxDatas=new BoxDataParser().parse(Bundles.INSTANCE.boxsize().getText()); loadBVH("14_01.bvh"); IKData ikdata1=new IKData(); //ikdata1.setTargetPos(THREE.Vector3(0, 20, 0)); ikdata1.setLastBoneName("Head"); ikdata1.setBones(new String[]{"Neck1","Neck","Spine","LowerBack"}); //ikdata1.setBones(new String[]{"Neck1","Neck","Spine1","Spine","LowerBack"}); ikdata1.setIteration(9); ikdatas.add(ikdata1); IKData ikdata0=new IKData(); //ikdata0.setTargetPos(THREE.Vector3(-10, 5, 0)); ikdata0.setLastBoneName("RightHand"); ikdata0.setBones(new String[]{"RightForeArm","RightArm","RightShoulder"}); ikdata0.setIteration(7); ikdatas.add(ikdata0); IKData ikdata=new IKData(); //ikdata.setTargetPos(THREE.Vector3(0, -10, 0)); ikdata.setLastBoneName("RightFoot"); ikdata.setBones(new String[]{"RightLeg","RightUpLeg"}); ikdata.setIteration(5); ikdatas.add(ikdata); IKData ikdata2=new IKData(); //ikdata0.setTargetPos(THREE.Vector3(-10, 5, 0)); ikdata2.setLastBoneName("LeftHand"); ikdata2.setBones(new String[]{"LeftForeArm","LeftArm","LeftShoulder"}); ikdata2.setIteration(7); ikdatas.add(ikdata2); IKData ikdata3=new IKData(); //ikdata.setTargetPos(THREE.Vector3(0, -10, 0)); ikdata3.setLastBoneName("LeftFoot"); ikdata3.setBones(new String[]{"LeftLeg","LeftUpLeg"}); ikdata3.setIteration(5); ikdatas.add(ikdata3); //updateIkLabels(); //calcurate by bvh 80_* /* boneLimits.put("RightForeArm",BoneLimit.createBoneLimit(-118, 0, 0, 60, -170, 0)); boneLimits.put("RightArm",BoneLimit.createBoneLimit(-180, 180, -60, 91, -180, 180)); boneLimits.put("RightShoulder",BoneLimit.createBoneLimit(0, 0, 0, 0,0, 0)); boneLimits.put("LeftForeArm",BoneLimit.createBoneLimit(-40, 10, -170, 0, 0, 0)); boneLimits.put("LeftArm",BoneLimit.createBoneLimit(-80, 60, -91, 40, -120, 50)); boneLimits.put("LeftShoulder",BoneLimit.createBoneLimit(-15, 25, -20, 20,-10, 10)); boneLimits.put("RightLeg",BoneLimit.createBoneLimit(0, 160, 0, 0, 0, 20)); boneLimits.put("RightUpLeg",BoneLimit.createBoneLimit(-85, 91, -35, 5, -80, 40)); boneLimits.put("LeftLeg",BoneLimit.createBoneLimit(0, 160, 0, 0, -20, 0)); boneLimits.put("LeftUpLeg",BoneLimit.createBoneLimit(-85, 91, -5, 35, -40, 80)); boneLimits.put("LowerBack",BoneLimit.createBoneLimit(-30, 30, -60, 60, -30, 30)); boneLimits.put("Spine",BoneLimit.createBoneLimit(-30, 30, -40, 40, -40, 40)); //boneLimits.put("Spine1",BoneLimit.createBoneLimit(-30, 30, -30, 30, -30, 30)); boneLimits.put("Neck",BoneLimit.createBoneLimit(-45, 45, -45, 45, -45, 45)); boneLimits.put("Neck1",BoneLimit.createBoneLimit(-15, 15, -15, 15, -15, 15)); */ //manual boneLimits.put("RightForeArm",BoneLimit.createBoneLimit(-40, 10, 0, 170, 0, 0)); boneLimits.put("RightArm",BoneLimit.createBoneLimit(-80, 60, -40, 91, -50, 120)); boneLimits.put("RightShoulder",BoneLimit.createBoneLimit(-15, 25, -20, 20,-10, 10)); boneLimits.put("LeftForeArm",BoneLimit.createBoneLimit(-40, 10, -170, 0, 0, 0)); boneLimits.put("LeftArm",BoneLimit.createBoneLimit(-80, 60, -91, 40, -120, 50)); boneLimits.put("LeftShoulder",BoneLimit.createBoneLimit(-15, 25, -20, 20,-10, 10)); //straight only //boneLimits.put("RightLeg",BoneLimit.createBoneLimit(0, 160, 0, 0, 8, 8)); //boneLimits.put("RightUpLeg",BoneLimit.createBoneLimit(-85, 91, 0, 0, 20, 20)); boneLimits.put("RightLeg",BoneLimit.createBoneLimit(0, 160, 0, 0, 0, 40)); boneLimits.put("RightUpLeg",BoneLimit.createBoneLimit(-85, 91, -35, 5, -80, 40)); boneLimits.put("LeftLeg",BoneLimit.createBoneLimit(0, 160, 0, 0, -40, 0)); boneLimits.put("LeftUpLeg",BoneLimit.createBoneLimit(-85, 91, -5, 35, -40, 80)); boneLimits.put("LowerBack",BoneLimit.createBoneLimit(-30, 30, -60, 60, -30, 30)); boneLimits.put("Spine",BoneLimit.createBoneLimit(-30, 30, -40, 40, -40, 40)); //boneLimits.put("Spine1",BoneLimit.createBoneLimit(-30, 30, -30, 30, -30, 30)); boneLimits.put("Neck",BoneLimit.createBoneLimit(-45, 45, -45, 45, -45, 45)); boneLimits.put("Neck1",BoneLimit.createBoneLimit(-15, 15, -15, 15, -15, 15)); } Map<String,BoneLimit> boneLimits=new HashMap<String,BoneLimit>(); private void updateIkLabels(){ //log(""+boneNamesBox); boneNamesBox.clear(); if(currentSelectionName!=null){ for(int i=0;i<getCurrentIkData().getBones().size();i++){ boneNamesBox.addItem(getCurrentIkData().getBones().get(i)); } boneNamesBox.setSelectedIndex(0); }else if(selectedBone!=null){ boneNamesBox.addItem(selectedBone); boneNamesBox.setSelectedIndex(0); } } int ikdataIndex=1; List<IKData> ikdatas=new ArrayList<IKData>(); private String currentSelectionName; Mesh selectionMesh; final Projector projector=THREE.Projector(); @Override public void onMouseClick(ClickEvent event) { //not work correctly on zoom //Vector3 pos=GWTUtils.toWebGLXY(event.getX(), event.getY(), camera, screenWidth, screenHeight); // targetPos.setX(pos.getX()); //targetPos.setY(pos.getY()); //doCDDIk(); //doPoseIkk(0); } private boolean isSelectedIk(){ return currentSelectionName!=null; } private void switchSelection(String name){ currentSelectionName=name; currentMatrixs=AnimationBonesData.cloneMatrix(ab.getBonesMatrixs()); if(currentSelectionName!=null){ List<List<NameAndVector3>> result=createBases(getCurrentIkData()); //log("switchd:"+result.size()); List<NameAndVector3> tmp=result.get(result.size()-1); for(NameAndVector3 value:tmp){ // log(value.getName()+":"+ThreeLog.get(value.getVector3())); } if(nearMatrix!=null){ nearMatrix.clear(); }else{ nearMatrix=new ArrayList<List<Matrix4>>(); } for(List<NameAndVector3> nv:result){ List<Matrix4> bm=AnimationBonesData.cloneMatrix(currentMatrixs); applyMatrix(bm, nv); //deb for(String bname:getCurrentIkData().getBones()){ Matrix4 mx=bm.get(ab.getBoneIndex(bname)); //log(bname+":"+ThreeLog.get(GWTThreeUtils.toDegreeAngle(mx))); } nearMatrix.add(bm); } }else{ log("null selected"); } updateIkLabels(); } public List<List<NameAndVector3>> createBases(IKData data){ int angle=45; if(data.getLastBoneName().equals("RightFoot")){ angle=40; } List<List<NameAndVector3>> all=new ArrayList(); List<List<NameAndVector3>> result=new ArrayList(); for(int i=0;i<data.getBones().size();i++){ String name=data.getBones().get(i); List<NameAndVector3> patterns=createBases(name,angle); //90 //60 is slow all.add(patterns); //log(name+"-size:"+patterns.size()); } //log(data.getLastBoneName()+"-joint-size:"+all.size()); doAdd(all,result,data.getBones(),0,null,2); return result; } private void doAdd(List<List<NameAndVector3>> all, List<List<NameAndVector3>> result, List<String> boneNames, int index,List<NameAndVector3> tmp,int depth) { if(index>=boneNames.size() || index==depth){ result.add(tmp); return; } if(index==0){ tmp=new ArrayList<NameAndVector3>(); } for(NameAndVector3 child:all.get(index)){ //copied List<NameAndVector3> list=new ArrayList<NameAndVector3>(); for(int i=0;i<tmp.size();i++){ list.add(tmp.get(i)); } list.add(child); doAdd(all,result,boneNames,index+1,list,2); } } private List<NameAndVector3> createBases(String name,int step){ List<NameAndVector3> patterns=new ArrayList<NameAndVector3>(); BoneLimit limit=boneLimits.get(name); for(int x=-180;x<=180;x+=step){ for(int y=-180;y<=180;y+=step){ for(int z=-180;z<=180;z+=step){ boolean pass=true; if(limit!=null){ if(limit.getMinXDegit()>x || limit.getMaxXDegit()<x){ pass=false; } if(limit.getMinYDegit()>y || limit.getMaxYDegit()<y){ pass=false; } if(limit.getMinZDegit()>z || limit.getMaxZDegit()<z){ pass=false; } } if(x==180||x==-180 || y==180||y==-180||z==180||z==-180){ pass=false;//same as 0 } if(pass){ // log(name+" pass:"+x+","+y+","+z); NameAndVector3 nvec=new NameAndVector3(name, Math.toRadians(x),Math.toRadians(y),Math.toRadians(z)); patterns.add(nvec); }else{ } } } } if(patterns.size()==0){ patterns.add(new NameAndVector3(name,0,0,0));//empty not allowd } return patterns; } @Override public void onMouseDown(MouseDownEvent event) { mouseDown=true; mouseDownX=event.getX(); mouseDownY=event.getY(); log("mouse-click:"+event.getX()+"x"+event.getY()); JsArray<Intersect> intersects=projector.gwtPickIntersects(event.getX(), event.getY(), screenWidth, screenHeight, camera,scene); log("intersects-length:"+intersects.length()); for(int i=0;i<intersects.length();i++){ Intersect sect=intersects.get(i); Object3D target=sect.getObject(); if(!target.getName().isEmpty()){ if(target.getName().startsWith("ik:")){ String bname=target.getName().substring(3); for(int j=0;j<ikdatas.size();j++){ if(ikdatas.get(j).getLastBoneName().equals(bname)){ ikdataIndex=j; selectionMesh.setVisible(true); selectionMesh.setPosition(target.getPosition()); if(!bname.equals(currentSelectionName)){ switchSelection(bname); } selectedBone=null; return;//ik selected } } }else{ //maybe bone or root log(target.getName()); selectedBone=target.getName(); selectionMesh.setVisible(true); selectionMesh.setPosition(target.getPosition()); switchSelection(null); return; } } } selectedBone=null; selectionMesh.setVisible(false); switchSelection(null); } private String selectedBone; @Override public void onMouseUp(MouseUpEvent event) { mouseDown=false; } @Override public void onMouseOut(MouseOutEvent event) { mouseDown=false; } @Override public void onMouseMove(MouseMoveEvent event) { if(mouseDown){ if(isSelectedIk()){ double diffX=event.getX()-mouseDownX; double diffY=event.getY()-mouseDownY; mouseDownX=event.getX(); mouseDownY=event.getY(); diffX*=0.1; diffY*=-0.1; getCurrentIkData().getTargetPos().incrementX(diffX); getCurrentIkData().getTargetPos().incrementY(diffY); doPoseIkk(0,event.isShiftKeyDown()); }else if(isSelectedBone()){ int diffX=event.getX()-mouseDownX; int diffY=event.getY()-mouseDownY; mouseDownX=event.getX(); mouseDownY=event.getY(); rotationBoneRange.setValue(rotationBoneRange.getValue()+diffY); rotationBoneYRange.setValue(rotationBoneYRange.getValue()+diffX); rangeToBone(); } else{//global int diffX=event.getX()-mouseDownX; int diffY=event.getY()-mouseDownY; mouseDownX=event.getX(); mouseDownY=event.getY(); rotationRange.setValue(rotationRange.getValue()+diffY); rotationYRange.setValue(rotationYRange.getValue()+diffX); } } } private boolean isSelectedBone(){ return selectedBone!=null; } private IKData getCurrentIkData(){ return ikdatas.get(ikdataIndex); } @Override public void onMouseWheel(MouseWheelEvent event) { if(isSelectedIk()){ if(event.isAltKeyDown()){//swapped }else{ onMouseWheelWithShiftKey(event.getDeltaY(),event.isShiftKeyDown()); } }else{ //TODO make class long t=System.currentTimeMillis(); if(mouseLast+100>t){ tmpZoom*=2; }else{ tmpZoom=defaultZoom; } //GWT.log("wheel:"+event.getDeltaY()); int tmp=cameraZ+event.getDeltaY()*tmpZoom; tmp=Math.max(minCamera, tmp); tmp=Math.min(4000, tmp); cameraZ=tmp; mouseLast=t; } } public void onMouseWheelWithShiftKey(int deltaY,boolean shift){ double dy=deltaY*0.2; getCurrentIkData().getTargetPos().incrementZ(dy); doPoseIkk(0,shift); } private HTML5InputRange positionXRange; private HTML5InputRange positionYRange; private HTML5InputRange positionZRange; private HTML5InputRange frameRange; private HTML5InputRange rotationRange; private HTML5InputRange rotationYRange; private HTML5InputRange rotationZRange; private HTML5InputRange rotationBoneRange; private HTML5InputRange rotationBoneYRange; private HTML5InputRange rotationBoneZRange; private PopupPanel bottomPanel; private HTML5InputRange currentFrameRange; private Label currentFrameLabel; @Override public void createControl(Panel parent) { HorizontalPanel h1=new HorizontalPanel(); rotationRange = new HTML5InputRange(-180,180,0); parent.add(HTML5Builder.createRangeLabel("X-Rotate:", rotationRange)); parent.add(h1); h1.add(rotationRange); Button reset=new Button("Reset"); reset.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { rotationRange.setValue(0); } }); h1.add(reset); HorizontalPanel h2=new HorizontalPanel(); rotationYRange = new HTML5InputRange(-180,180,0); parent.add(HTML5Builder.createRangeLabel("Y-Rotate:", rotationYRange)); parent.add(h2); h2.add(rotationYRange); Button reset2=new Button("Reset"); reset2.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { rotationYRange.setValue(0); } }); h2.add(reset2); HorizontalPanel h3=new HorizontalPanel(); rotationZRange = new HTML5InputRange(-180,180,0); parent.add(HTML5Builder.createRangeLabel("Z-Rotate:", rotationZRange)); parent.add(h3); h3.add(rotationZRange); Button reset3=new Button("Reset"); reset3.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { rotationZRange.setValue(0); } }); h3.add(reset3); HorizontalPanel h4=new HorizontalPanel(); positionXRange = new HTML5InputRange(-50,50,0); parent.add(HTML5Builder.createRangeLabel("X-Position:", positionXRange)); parent.add(h4); h4.add(positionXRange); Button reset4=new Button("Reset"); reset4.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { positionXRange.setValue(0); } }); h4.add(reset4); HorizontalPanel h5=new HorizontalPanel(); positionYRange = new HTML5InputRange(-50,50,0); parent.add(HTML5Builder.createRangeLabel("Y-Position:", positionYRange)); parent.add(h5); h5.add(positionYRange); Button reset5=new Button("Reset"); reset5.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { positionYRange.setValue(0); } }); h5.add(reset5); HorizontalPanel h6=new HorizontalPanel(); positionZRange = new HTML5InputRange(-50,50,0); parent.add(HTML5Builder.createRangeLabel("Z-Position:", positionZRange)); parent.add(h6); h6.add(positionZRange); Button reset6=new Button("Reset"); reset6.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { positionZRange.setValue(0); } }); h6.add(reset6); transparentCheck = new CheckBox(); parent.add(transparentCheck); transparentCheck.setText("transparent"); transparentCheck.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { updateMaterial(); } }); transparentCheck.setValue(true); basicMaterialCheck = new CheckBox(); parent.add(basicMaterialCheck); basicMaterialCheck.setText("BasicMaterial"); basicMaterialCheck.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { updateMaterial(); } }); //dont need now HorizontalPanel frames=new HorizontalPanel(); frameRange = new HTML5InputRange(0,1,0); parent.add(HTML5Builder.createRangeLabel("Frame:", frameRange)); //parent.add(frames); frames.add(frameRange); frameRange.addListener(new HTML5InputRangeListener() { @Override public void changed(int newValue) { doPose(frameRange.getValue()); } }); parent.add(new Label("Bone")); boneNamesBox = new ListBox(); boneNamesBox.addChangeHandler(new ChangeHandler() { @Override public void onChange(ChangeEvent event) { updateBoneRanges(); } }); parent.add(boneNamesBox); HorizontalPanel h1b=new HorizontalPanel(); rotationBoneRange = new HTML5InputRange(-180,180,0); parent.add(HTML5Builder.createRangeLabel("X-Rotate:", rotationBoneRange)); parent.add(h1b); h1b.add(rotationBoneRange); Button resetB1=new Button("Reset"); resetB1.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { rotationBoneRange.setValue(0); rangeToBone(); } }); h1b.add(resetB1); rotationBoneRange.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { rangeToBone(); } }); HorizontalPanel h2b=new HorizontalPanel(); rotationBoneYRange = new HTML5InputRange(-180,180,0); parent.add(HTML5Builder.createRangeLabel("Y-Rotate:", rotationBoneYRange)); parent.add(h2b); h2b.add(rotationBoneYRange); Button reset2b=new Button("Reset"); reset2b.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { rotationBoneYRange.setValue(0); rangeToBone(); } }); h2b.add(reset2b); rotationBoneYRange.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { rangeToBone(); } }); HorizontalPanel h3b=new HorizontalPanel(); rotationBoneZRange = new HTML5InputRange(-180,180,0); parent.add(HTML5Builder.createRangeLabel("Z-Rotate:", rotationBoneZRange)); parent.add(h3b); h3b.add(rotationBoneZRange); Button reset3b=new Button("Reset"); reset3b.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { rotationBoneZRange.setValue(0); rangeToBone(); } }); h3b.add(reset3b); rotationBoneZRange.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { rangeToBone(); } }); updateMaterial(); positionYRange.setValue(-14);//for test updateIkLabels(); createBottomPanel(); showControl(); } private void createBottomPanel(){ bottomPanel = new PopupPanel(); bottomPanel.setVisible(true); bottomPanel.setSize("650px", "40px"); VerticalPanel main=new VerticalPanel(); bottomPanel.add(main); bottomPanel.show(); //upper HorizontalPanel upperPanel=new HorizontalPanel(); upperPanel.setVerticalAlignment(HorizontalPanel.ALIGN_MIDDLE); main.add(upperPanel); Button snap=new Button("Snap"); upperPanel.add(snap); snap.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { List<Matrix4> matrixs=AnimationBonesData.cloneMatrix(ab.getBonesMatrixs()); List<Vector3> targets=new ArrayList<Vector3>(); for(IKData ikdata:ikdatas){ targets.add(ikdata.getTargetPos().clone()); } PoseFrameData ps=new PoseFrameData(matrixs, targets); poseFrameDatas.add(ps); updatePoseIndex(poseFrameDatas.size()-1); } }); Button remove=new Button("Remove"); upperPanel.add(remove); remove.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { poseFrameDatas.remove(poseFrameDataIndex); updatePoseIndex(poseFrameDataIndex-1); } }); Button export=new Button("Export"); upperPanel.add(export); export.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { doExport(); } }); HorizontalPanel pPanel=new HorizontalPanel(); main.add(pPanel); pPanel.setVerticalAlignment(HorizontalPanel.ALIGN_MIDDLE); currentFrameRange = new HTML5InputRange(0,0,0); currentFrameRange.setWidth("420px"); pPanel.add(currentFrameRange); currentFrameRange.addMouseUpHandler(new MouseUpHandler() { @Override public void onMouseUp(MouseUpEvent event) { updatePoseIndex(currentFrameRange.getValue()); } }); currentFrameLabel = new Label(); pPanel.add(currentFrameLabel); super.leftBottom(bottomPanel); } protected void doExport() { BVH exportBVH=new BVH(); BVHConverter converter=new BVHConverter(); BVHNode node=converter.convertBVHNode(bones); exportBVH.setHiearchy(node); converter.setChannels(node,0,"XYZ"); //TODO support other order BVHMotion motion=new BVHMotion(); motion.setFrameTime(1); log("size:"+poseFrameDatas.size()); for(PoseFrameData pose:poseFrameDatas){ double[] values=converter.matrixsToMotion(pose.getMatrixs(),BVHConverter.ROOT_POSITION_ROTATE_ONLY,"XYZ"); motion.add(values); } motion.setFrames(motion.getMotions().size()); exportBVH.setMotion(motion); //log("frames:"+exportBVH.getFrames()); BVHWriter writer=new BVHWriter(); String bvhText=writer.writeToString(exportBVH); log(bvhText); exportTextChrome(bvhText); } public native final void exportTextChrome(String text)/*-{ win = $wnd.open("", "win") win.document.body.innerText =""+text+""; }-*/; private int poseFrameDataIndex=0; private List<PoseFrameData> poseFrameDatas=new ArrayList<PoseFrameData>(); private void updatePoseIndex(int index){ if(index==-1){ currentFrameRange.setMax(0); currentFrameRange.setValue(0); currentFrameLabel.setText(""); }else{ //poseIndex=index; currentFrameRange.setMax(poseFrameDatas.size()-1); currentFrameRange.setValue(index); currentFrameLabel.setText((index+1)+"/"+poseFrameDatas.size()); selectFrameData(index); } } private void selectFrameData(int index) { poseFrameDataIndex=index; PoseFrameData ps=poseFrameDatas.get(index); //update for(int i=0;i<ikdatas.size();i++){ Vector3 vec=ps.getTargetPositions().get(i); ikdatas.get(i).getTargetPos().set(vec.getX(), vec.getY(), vec.getZ()); } currentMatrixs=AnimationBonesData.cloneMatrix(ps.getMatrixs()); ab.setBonesMatrixs(currentMatrixs); switchSelection(getCurrentIkData().getLastBoneName()); doPoseByMatrix(ab); updateBoneRanges(); } private void rangeToBone(){ String name=boneNamesBox.getItemText(boneNamesBox.getSelectedIndex()); int index=ab.getBoneIndex(name); //Matrix4 mx=ab.getBoneMatrix(name); Vector3 angles=THREE.Vector3(Math.toRadians(rotationBoneRange.getValue()), Math.toRadians(rotationBoneYRange.getValue()) , Math.toRadians(rotationBoneZRange.getValue())); //log("set-angle:"+ThreeLog.get(GWTThreeUtils.radiantToDegree(angles))); //mx.setRotationFromEuler(angles, "XYZ"); Vector3 pos=GWTThreeUtils.toPositionVec(ab.getBoneMatrix(index)); //log("pos:"+ThreeLog.get(pos)); Matrix4 posMx=GWTThreeUtils.translateToMatrix4(pos); Matrix4 rotMx=GWTThreeUtils.rotationToMatrix4(angles); rotMx.multiply(posMx,rotMx); //log("bone-pos:"+ThreeLog.get(bones.get(index).getPos())); Vector3 changed=GWTThreeUtils.toDegreeAngle(rotMx); //log("seted-angle:"+ThreeLog.get(changed)); ab.setBoneMatrix(index, rotMx); doPoseByMatrix(ab); } private void updateBoneRanges(){ String name=boneNamesBox.getItemText(boneNamesBox.getSelectedIndex()); int boneIndex=ab.getBoneIndex(name); Quaternion q=GWTThreeUtils.jsArrayToQuaternion(bones.get(boneIndex).getRotq()); //log("bone:"+ThreeLog.get(GWTThreeUtils.radiantToDegree(GWTThreeUtils.rotationToVector3(q)))); Vector3 angles=GWTThreeUtils.toDegreeAngle(ab.getBoneMatrix(name)); //log("update-bone:"+ThreeLog.get(angles)); int x=(int) angles.getX(); if(x==180|| x==-180){ x=0; } rotationBoneRange.setValue(x); int y=(int) angles.getY(); if(y==180|| y==-180){ y=0; } rotationBoneYRange.setValue(y); int z=(int) angles.getZ(); if(z==180|| z==-180){ z=0; } rotationBoneZRange.setValue(z); } private Material bodyMaterial; protected void updateMaterial() { Material material=null; boolean transparent=transparentCheck.getValue(); double opacity=1; if(transparent){ opacity=0.75; } if(basicMaterialCheck.getValue()){ material=THREE.MeshBasicMaterial().map(ImageUtils.loadTexture("men3smart_texture2.png")).transparent(transparent).opacity(opacity).build(); }else{ material=THREE.MeshLambertMaterial().map(ImageUtils.loadTexture("men3smart_texture2.png")).transparent(transparent).opacity(opacity).build(); } bodyMaterial=material; if(bodyMesh!=null){ bodyMesh.setMaterial(material); } } private void loadBVH(String path){ RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, URL.encode(path)); try { builder.sendRequest(null, new RequestCallback() { @Override public void onResponseReceived(Request request, Response response) { String bvhText=response.getText(); parseBVH(bvhText); } @Override public void onError(Request request, Throwable exception) { Window.alert("load faild:"); } }); } catch (RequestException e) { log(e.getMessage()); e.printStackTrace(); } } private Geometry baseGeometry; protected void parseBVH(String bvhText) { final BVHParser parser=new BVHParser(); parser.parseAsync(bvhText, new ParserListener() { @Override public void onFaild(String message) { log(message); } @Override public void onSuccess(BVH bv) { bvh=bv; AnimationBoneConverter converter=new AnimationBoneConverter(); bones = converter.convertJsonBone(bvh); AnimationDataConverter dataConverter=new AnimationDataConverter(); dataConverter.setSkipFirst(false); animationData = dataConverter.convertJsonAnimation(bones,bvh); frameRange.setMax(animationData.getHierarchy().get(0).getKeys().length()); JSONLoader loader=THREE.JSONLoader(); loader.load("men3tmp.js", new LoadHandler() { @Override public void loaded(Geometry geometry) { baseGeometry=geometry; doPose(0); } }); } }); } public static class MatrixAndVector3{ public MatrixAndVector3(){} private Vector3 position; public Vector3 getPosition() { return position; } public void setPosition(Vector3 position) { this.position = position; } private Vector3 absolutePosition; public Vector3 getAbsolutePosition() { return absolutePosition; } public void setAbsolutePosition(Vector3 absolutePosition) { this.absolutePosition = absolutePosition; } public Matrix4 getMatrix() { return matrix; } public void setMatrix(Matrix4 matrix) { this.matrix = matrix; } private Matrix4 matrix; } private List<MatrixAndVector3> boneMatrix; /* private Vector3 calculateBonedPos(Vector3 pos,AnimationBone bone,int animationIndex){ } */ public static List<MatrixAndVector3> boneToBoneMatrix(JsArray<AnimationBone> bones,AnimationData animationData,int index){ List<MatrixAndVector3> boneMatrix=new ArrayList<MatrixAndVector3>(); //analyze bone matrix for(int i=0;i<bones.length();i++){ AnimationBone bone=bones.get(i); AnimationHierarchyItem item=animationData.getHierarchy().get(i); AnimationKey motion=item.getKeys().get(index); //log(bone.getName()); Matrix4 mx=THREE.Matrix4(); Vector3 motionPos=AnimationBone.jsArrayToVector3(motion.getPos()); //seems same as bone // LogUtils.log(motionPos); mx.setTranslation(motionPos.getX(), motionPos.getY(), motionPos.getZ()); Matrix4 mx2=THREE.Matrix4(); mx2.setRotationFromQuaternion(motion.getRot()); mx.multiplySelf(mx2); /* Vector3 tmpRot=THREE.Vector3(); tmpRot.setRotationFromMatrix(mx); Vector3 tmpPos=THREE.Vector3(); tmpPos.setPositionFromMatrix(mx); */ //LogUtils.log(tmpPos.getX()+","+tmpPos.getY()+","+tmpPos.getZ()); //LogUtils.log(Math.toDegrees(tmpRot.)) MatrixAndVector3 mv=new MatrixAndVector3(); Vector3 bpos=AnimationBone.jsArrayToVector3(bone.getPos()); mv.setPosition(bpos);//not effected self matrix mv.setMatrix(mx); if(bone.getParent()!=-1){ MatrixAndVector3 parentMv=boneMatrix.get(bone.getParent()); Vector3 apos=bpos.clone(); apos.addSelf(parentMv.getAbsolutePosition()); mv.setAbsolutePosition(apos); }else{ //root mv.setAbsolutePosition(bpos.clone()); } boneMatrix.add(mv); } return boneMatrix; } private List<List<Integer>> bonePath; public static List<List<Integer>> boneToPath(JsArray<AnimationBone> bones){ List<List<Integer>> data=new ArrayList<List<Integer>>(); for(int i=0;i<bones.length();i++){ List<Integer> path=new ArrayList<Integer>(); AnimationBone bone=bones.get(i); path.add(i); data.add(path); while(bone.getParent()!=-1){ //path.add(bone.getParent()); path.add(0,bone.getParent()); bone=bones.get(bone.getParent()); } } return data; } private JsArray<Vector4> bodyIndices; private JsArray<Vector4> bodyWeight; Mesh bodyMesh; Object3D root; Object3D bone3D; private CheckBox transparentCheck; private CheckBox basicMaterialCheck; private void doPose(int index){ for(int i=0;i<bones.length();i++){ log(bones.get(i).getName()); } initializeBodyMesh(); initializeAnimationData(index,false); //stepCDDIk(); doPoseByMatrix(ab); updateBoneRanges(); /* * trying to fix leg problem Vector3 rootOffset=GWTThreeUtils.jsArrayToVector3(animationData.getHierarchy().get(0).getKeys().get(index).getPos()); //initial pose is base for motions baseGeometry=GeometryUtils.clone(bodyMesh.getGeometry()); for(int i=0;i<baseGeometry.vertices().length();i++){ Vertex vertex=baseGeometry.vertices().get(i); vertex.getPosition().subSelf(rootOffset); } */ } AnimationBonesData ab; List<Matrix4> baseMatrixs; private void applyMatrix(List<Matrix4> matrix,List<NameAndVector3> samples){ for(NameAndVector3 nv:samples){ int boneIndex=ab.getBoneIndex(nv.getName()); Matrix4 translates=GWTThreeUtils.translateToMatrix4(GWTThreeUtils.toPositionVec(ab.getBoneMatrix(boneIndex))); Matrix4 newMatrix=GWTThreeUtils.rotationToMatrix4(nv.getVector3()); newMatrix.multiply(translates,newMatrix); //log("apply-matrix"); matrix.set(boneIndex, newMatrix); } } List<List<Matrix4>> nearMatrix; private void initializeBodyMesh(){ //initializeBodyMesh if(bodyMesh==null){//initial bodyIndices = (JsArray<Vector4>) JsArray.createArray(); bodyWeight = (JsArray<Vector4>) JsArray.createArray(); WeightBuilder.autoWeight(baseGeometry, bones, WeightBuilder.MODE_NearParentAndChildren, bodyIndices, bodyWeight); }else{ root.remove(bodyMesh); } } List<Matrix4> currentMatrixs; private void initializeAnimationData(int index,boolean resetMatrix){ //initialize AnimationBone if(ab==null){ baseMatrixs=AnimationBonesData.boneToMatrix(bones, animationData, index); ab=new AnimationBonesData(bones,AnimationBonesData.cloneMatrix(baseMatrixs) ); } //TODO make automatic //this is find base matrix ,because sometime cdd-ik faild from some position //nearMatrix=new ArrayList<List<Matrix4>>(); //nearMatrix.add(AnimationBonesData.cloneMatrix(baseMatrixs)); /* * for foot List<NameAndVector3> sample=new ArrayList<NameAndVector3>(); sample.add(new NameAndVector3("RightLeg", GWTThreeUtils.degreeToRagiant(THREE.Vector3(90, 0, 0)), 0)); sample.add(new NameAndVector3("RightUpLeg", GWTThreeUtils.degreeToRagiant(THREE.Vector3(-90, 0, 0)), 0)); List<Matrix4> bm=AnimationBonesData.cloneMatrix(baseMatrixs); applyMatrix(bm, sample); nearMatrix.add(bm); List<NameAndVector3> sample1=new ArrayList<NameAndVector3>(); sample1.add(new NameAndVector3("RightLeg", GWTThreeUtils.degreeToRagiant(THREE.Vector3(0, 0, 0)), 0)); sample1.add(new NameAndVector3("RightUpLeg", GWTThreeUtils.degreeToRagiant(THREE.Vector3(0, 0, 45)), 0)); List<Matrix4> bm1=AnimationBonesData.cloneMatrix(baseMatrixs); applyMatrix(bm1, sample); //ab.setBonesMatrixs(findStartMatrix("RightFoot",getCurrentIkData().getTargetPos()));// */ if(currentMatrixs!=null && resetMatrix){ if(nearMatrix!=null){ //need bone limit ab.setBonesMatrixs(AnimationBonesData.cloneMatrix(findStartMatrix(getCurrentIkData().getLastBoneName(),getCurrentIkData().getTargetPos()))); }else{ ab.setBonesMatrixs(AnimationBonesData.cloneMatrix(currentMatrixs)); } //TODO only need }else{ } } private void stepCDDIk(){ //do CDDIK //doCDDIk(); Vector3 tmp1=null,tmp2=null; currentIkJointIndex=0; for(int i=0;i<getCurrentIkData().getIteration();i++){ String targetBoneName=getCurrentIkData().getBones().get(currentIkJointIndex); int boneIndex=ab.getBoneIndex(targetBoneName); Vector3 lastJointPos=ab.getPosition(getCurrentIkData().getLastBoneName()); //Vector3 jointPos=ab.getParentPosition(targetName); Vector3 jointPos=ab.getPosition(targetBoneName); Matrix4 jointRot=ab.getBoneMatrix(targetBoneName); Vector3 beforeAngles=GWTThreeUtils.radiantToDegree(GWTThreeUtils.rotationToVector3(jointRot)); String beforeAngleValue=ThreeLog.get(beforeAngles); Matrix4 newMatrix=cddIk.doStep(lastJointPos, jointPos, jointRot, getCurrentIkData().getTargetPos()); if(newMatrix==null){//invalid value continue; } //limit per angles Vector3 angles=GWTThreeUtils.rotationToVector3(newMatrix); int perLimit=1; Vector3 diffAngles=GWTThreeUtils.radiantToDegree(angles).subSelf(beforeAngles); if(Math.abs(diffAngles.getX())>perLimit){ double diff=perLimit; if(diffAngles.getX()<0){ diff*=-1; } diffAngles.setX(diff); } if(Math.abs(diffAngles.getY())>perLimit){ double diff=perLimit; if(diffAngles.getY()<0){ diff*=-1; } diffAngles.setY(diff); } if(Math.abs(diffAngles.getZ())>perLimit){ double diff=perLimit; if(diffAngles.getZ()<0){ diff*=-1; } diffAngles.setZ(diff); } beforeAngles.addSelf(diffAngles); angles=GWTThreeUtils.degreeToRagiant(beforeAngles); //log("before:"+beforeAngleValue+" after:"+ThreeLog.get(beforeAngles)); Matrix4 translates=GWTThreeUtils.translateToMatrix4(GWTThreeUtils.toPositionVec(newMatrix)); //limit max BoneLimit blimit=boneLimits.get(targetBoneName); //log(targetBoneName); //log("before-limit:"+ThreeLog.get(GWTThreeUtils.radiantToDegree(angles))); if(blimit!=null){ blimit.apply(angles); } //invalid ignore if("NaN".equals(""+angles.getX())){ continue; } if("NaN".equals(""+angles.getY())){ continue; } if("NaN".equals(""+angles.getZ())){ continue; } //log("after-limit:"+ThreeLog.get(GWTThreeUtils.radiantToDegree(angles))); newMatrix=GWTThreeUtils.rotationToMatrix4(angles); newMatrix.multiply(translates,newMatrix); ab.setBoneMatrix(boneIndex, newMatrix); //log(targetName+":"+ThreeLog.getAngle(jointRot)+",new"+ThreeLog.getAngle(newMatrix)); //log("parentPos,"+ThreeLog.get(jointPos)+",lastPos,"+ThreeLog.get(lastJointPos)); currentIkJointIndex++; if(currentIkJointIndex>=getCurrentIkData().getBones().size()){ currentIkJointIndex=0; } tmp1=lastJointPos; tmp2=jointPos; } } private void doPoseIkk(int index,boolean resetMatrix){ initializeBodyMesh(); initializeAnimationData(index,resetMatrix); stepCDDIk(); doPoseByMatrix(ab); updateBoneRanges(); } private List<Matrix4> findStartMatrix(String boneName,Vector3 targetPos) { List<Matrix4> retMatrix=nearMatrix.get(0); ab.setBonesMatrixs(retMatrix); Vector3 tpos=ab.getPosition(boneName); double minlength=targetPos.clone().subSelf(tpos).length(); for(int i=1;i<nearMatrix.size();i++){ List<Matrix4> mxs=nearMatrix.get(i); ab.setBonesMatrixs(mxs);//TODO change Vector3 tmpPos=ab.getPosition(boneName); double tmpLength=targetPos.clone().subSelf(tmpPos).length(); if(tmpLength<minlength){ minlength=tmpLength; retMatrix=mxs; } } for(String name:getCurrentIkData().getBones()){ Matrix4 mx=retMatrix.get(ab.getBoneIndex(name)); // log(name+":"+ThreeLog.get(GWTThreeUtils.rotationToVector3(mx))); // log(name+":"+ThreeLog.get(GWTThreeUtils.toDegreeAngle(mx))); } return retMatrix; } /* private void doCDDIk(){ String targetName=getCurrentIkData().getBones().get(currentIkJointIndex); int boneIndex=ab.getBoneIndex(targetName); Vector3 lastJointPos=ab.getPosition("RightFoot"); Vector3 jointPos=ab.getParentPosition(targetName); Matrix4 jointRot=ab.getBoneMatrix(targetName); Matrix4 newMatrix=cddIk.doStep(lastJointPos, jointPos, jointRot, getCurrentIkData().getTargetPos()); ab.setBoneMatrix(boneIndex, newMatrix); //log(targetName+":"+ThreeLog.getAngle(jointRot)+",new"+ThreeLog.getAngle(newMatrix)); //log("parentPos,"+ThreeLog.get(jointPos)+",lastPos,"+ThreeLog.get(lastJointPos)); currentIkJointIndex++; if(currentIkJointIndex>=getCurrentIkData().getBones().size()){ currentIkJointIndex=0; } doPoseByMatrix(ab); } */ CDDIK cddIk=new CDDIK(); int currentIkJointIndex=0; //private String[] ikTestNames={"RightLeg","RightUpLeg"}; //Vector3 targetPos=THREE.Vector3(-10, -3, 0); private ListBox boneNamesBox; private void doPoseByMatrix(AnimationBonesData animationBonesData){ List<Matrix4> boneMatrix=animationBonesData.getBonesMatrixs(); bonePath=boneToPath(bones); if(bone3D!=null){ root.remove(bone3D); } bone3D=THREE.Object3D(); root.add(bone3D); //selection //test ikk Mesh cddIk0=THREE.Mesh(THREE.CubeGeometry(.5, .5, .5),THREE.MeshLambertMaterial().color(0x00ff00).build()); cddIk0.setPosition(getCurrentIkData().getTargetPos()); bone3D.add(cddIk0); List<Matrix4> moveMatrix=new ArrayList<Matrix4>(); List<Vector3> bonePositions=new ArrayList<Vector3>(); for(int i=0;i<bones.length();i++){ Matrix4 mv=boneMatrix.get(i); double bsize=.5; if(i==0){ bsize=1; } Mesh mesh=THREE.Mesh(THREE.CubeGeometry(bsize,bsize, bsize),THREE.MeshLambertMaterial().color(0xff0000).build()); bone3D.add(mesh); Vector3 pos=THREE.Vector3(); pos.setPositionFromMatrix(boneMatrix.get(i)); Vector3 rot=GWTThreeUtils.rotationToVector3(GWTThreeUtils.jsArrayToQuaternion(bones.get(i).getRotq())); List<Integer> path=bonePath.get(i); String boneName=bones.get(i).getName(); //log(boneName); mesh.setName(boneName); Matrix4 matrix=THREE.Matrix4(); for(int j=0;j<path.size()-1;j++){//last is boneself // log(""+path.get(j)); Matrix4 mx=boneMatrix.get(path.get(j)); matrix.multiply(matrix, mx); } matrix.multiplyVector3(pos); matrix.multiply(matrix, boneMatrix.get(path.get(path.size()-1)));//last one moveMatrix.add(matrix); if(bones.get(i).getParent()!=-1){ Vector3 ppos=bonePositions.get(bones.get(i).getParent()); //pos.addSelf(ppos); //log(boneName+":"+ThreeLog.get(pos)+","+ThreeLog.get(ppos)); Mesh line=GWTGeometryUtils.createLineMesh(pos, ppos, 0xffffff); bone3D.add(line); //cylinder /* better bone faild Vector3 halfPos=pos.clone().subSelf(ppos).multiplyScalar(0.5).addSelf(ppos); Mesh boneMesh=THREE.Mesh(THREE.CylinderGeometry(.1,.1,.2,6), THREE.MeshLambertMaterial().color(0xffffff).build()); boneMesh.setPosition(halfPos); boneMesh.setName(boneName); bone3D.add(boneMesh); BoxData data=boxDatas.get(boneName); if(data!=null){ boneMesh.setScale(data.getScaleX(), data.getScaleY(), data.getScaleZ()); boneMesh.getRotation().setZ(Math.toRadians(data.getRotateZ())); } */ for(IKData ik:ikdatas){ if(ik.getLastBoneName().equals(boneName)){ Mesh ikMesh=targetMeshs.get(boneName); if(ikMesh==null){//at first call this from non-ik stepped. //log("xxx"); //initial Vector3 ikpos=pos.clone().subSelf(ppos).multiplyScalar(2).addSelf(ppos); //ikpos=pos.clone(); ikMesh=THREE.Mesh(THREE.CubeGeometry(1, 1, 1),THREE.MeshLambertMaterial().color(0x00ff00).build()); ikMesh.setPosition(ikpos); ikMesh.setName("ik:"+boneName); // log(boneName+":"+ThreeLog.get(ikpos)); //log(ThreeLog.get(pos)); ik.getTargetPos().set(ikpos.getX(), ikpos.getY(), ikpos.getZ()); targetMeshs.put(boneName, ikMesh); }else{ ikMesh.getParent().remove(ikMesh); } bone3D.add(ikMesh); ikMesh.setPosition(ik.getTargetPos()); Mesh ikline=GWTGeometryUtils.createLineMesh(pos, ik.getTargetPos(), 0xffffff); bone3D.add(ikline); } } } mesh.setRotation(rot); mesh.setPosition(pos); bonePositions.add(pos); } //Geometry geo=GeometryUtils.clone(baseGeometry); //Geometry geo=bodyMesh.getGeometry(); Geometry geo=GeometryUtils.clone(baseGeometry); for(int i=0;i<baseGeometry.vertices().length();i++){ Vertex baseVertex=baseGeometry.vertices().get(i); Vector3 vertexPosition=baseVertex.getPosition().clone(); Vertex targetVertex=geo.vertices().get(i); int boneIndex1=(int) bodyIndices.get(i).getX(); int boneIndex2=(int) bodyIndices.get(i).getY(); String name=animationBonesData.getBoneName(boneIndex1); /* * if(name.equals("RightLeg")){//test parent base Vector3 parentPos=animationBonesData.getBaseParentBonePosition(boneIndex1); Matrix4 tmpMatrix=GWTThreeUtils.rotationToMatrix4(GWTThreeUtils.degreeToRagiant(THREE.Vector3(0, 0, 20))); vertexPosition.subSelf(parentPos); tmpMatrix.multiplyVector3(vertexPosition); vertexPosition.addSelf(parentPos); boneIndex2=boneIndex1; //dont work without this }*/ Vector3 bonePos=animationBonesData.getBaseBonePosition(boneIndex1); Vector3 relatePos=bonePos.clone(); relatePos.sub(vertexPosition,bonePos); //double length=relatePos.length(); moveMatrix.get(boneIndex1).multiplyVector3(relatePos); /* if(name.equals("RightLeg")){ Vector3 parentPos=animationBonesData.getParentPosition(boneIndex1); relatePos.subSelf(parentPos); Matrix4 tmpMatrix2=GWTThreeUtils.rotationToMatrix4(GWTThreeUtils.degreeToRagiant(THREE.Vector3(0, 0, -20))); tmpMatrix2.multiplyVector3(relatePos); relatePos.addSelf(parentPos); }*/ //relatePos.addSelf(bonePos); if(boneIndex2!=boneIndex1){ Vector3 bonePos2=animationBonesData.getBaseBonePosition(boneIndex2); Vector3 relatePos2=bonePos2.clone(); relatePos2.sub(baseVertex.getPosition(),bonePos2); double length2=relatePos2.length(); moveMatrix.get(boneIndex2).multiplyVector3(relatePos2); //scalar weight relatePos.multiplyScalar(bodyWeight.get(i).getX()); relatePos2.multiplyScalar(bodyWeight.get(i).getY()); relatePos.addSelf(relatePos2); //keep distance1 faild /* if(length<1){ //length2 Vector3 abpos=THREE.Vector3(); abpos.sub(relatePos, bonePositions.get(boneIndex1)); double scar=abpos.length()/length; abpos.multiplyScalar(scar); abpos.addSelf(bonePositions.get(boneIndex1)); relatePos.set(abpos.getX(), abpos.getY(), abpos.getZ()); }*/ if(length2<1){ Vector3 abpos=THREE.Vector3(); abpos.sub(relatePos, bonePositions.get(boneIndex2)); double scar=abpos.length()/length2; abpos.multiplyScalar(scar); abpos.addSelf(bonePositions.get(boneIndex2)); relatePos.set(abpos.getX(), abpos.getY(), abpos.getZ()); } /* Vector3 diff=THREE.Vector3(); diff.sub(relatePos2, relatePos); diff.multiplyScalar(bodyWeight.get(i).getY()); relatePos.addSelf(diff); */ }else{ if(name.equals("RightLeg")){ // Matrix4 tmpMatrix2=GWTThreeUtils.rotationToMatrix4(GWTThreeUtils.degreeToRagiant(THREE.Vector3(0, 0, -20))); // tmpMatrix2.multiplyVector3(relatePos); } } targetVertex.getPosition().set(relatePos.getX(), relatePos.getY(), relatePos.getZ()); } geo.computeFaceNormals(); geo.computeVertexNormals(); //Material material=THREE.MeshLambertMaterial().map(ImageUtils.loadTexture("men3smart_texture.png")).build(); if(bodyMesh==null){//initial bodyIndices = (JsArray<Vector4>) JsArray.createArray(); bodyWeight = (JsArray<Vector4>) JsArray.createArray(); WeightBuilder.autoWeight(baseGeometry, bones, 2, bodyIndices, bodyWeight); }else{ root.remove(bodyMesh); } bodyMesh=THREE.Mesh(geo, bodyMaterial); root.add(bodyMesh); //selection //selectionMesh=THREE.Mesh(THREE.CubeGeometry(2, 2, 2), THREE.MeshBasicMaterial().color(0x00ff00).wireFrame(true).build()); if(isSelectedIk()){ selectionMesh.setPosition(getCurrentIkData().getTargetPos()); } //bone3D.add(selectionMesh); //selectionMesh.setVisible(false); /* geo.setDynamic(true); geo.setDirtyVertices(true); geo.computeBoundingSphere(); */ //bodyMesh.setGeometry(geo); //bodyMesh.gwtBoundingSphere(); //geo.computeTangents(); /* geo.setDynamic(true); geo.setDirtyVertices(true); geo.computeFaceNormals(); geo.computeVertexNormals(); geo.computeTangents(); */ } private Map<String,Mesh> targetMeshs=new HashMap<String,Mesh>(); /** * @deprecated */ private void doPose(List<MatrixAndVector3> boneMatrix){ bonePath=boneToPath(bones); if(bone3D!=null){ root.remove(bone3D); } bone3D=THREE.Object3D(); root.add(bone3D); //test ikk Mesh cddIk0=THREE.Mesh(THREE.CubeGeometry(.5, .5, .5),THREE.MeshLambertMaterial().color(0x00ff00).build()); cddIk0.setPosition(getCurrentIkData().getTargetPos()); bone3D.add(cddIk0); List<Matrix4> moveMatrix=new ArrayList<Matrix4>(); List<Vector3> bonePositions=new ArrayList<Vector3>(); for(int i=0;i<bones.length();i++){ MatrixAndVector3 mv=boneMatrix.get(i); Mesh mesh=THREE.Mesh(THREE.CubeGeometry(.2, .2, .2),THREE.MeshLambertMaterial().color(0xff0000).build()); bone3D.add(mesh); Vector3 pos=mv.getPosition().clone(); List<Integer> path=bonePath.get(i); String boneName=bones.get(i).getName(); //log(boneName); Matrix4 tmpmx=boneMatrix.get(path.get(path.size()-1)).getMatrix(); Vector3 tmpp=THREE.Vector3(); tmpp.setPositionFromMatrix(tmpmx); //log(pos.getX()+","+pos.getY()+","+pos.getZ()+":"+tmpp.getX()+","+tmpp.getY()+","+tmpp.getZ()); Matrix4 matrix=THREE.Matrix4(); for(int j=0;j<path.size()-1;j++){//last is boneself // log(""+path.get(j)); Matrix4 mx=boneMatrix.get(path.get(j)).getMatrix(); matrix.multiply(matrix, mx); } matrix.multiplyVector3(pos); matrix.multiply(matrix, boneMatrix.get(path.get(path.size()-1)).getMatrix());//last one moveMatrix.add(matrix); if(bones.get(i).getParent()!=-1){ Vector3 ppos=bonePositions.get(bones.get(i).getParent()); //pos.addSelf(ppos); Mesh line=GWTGeometryUtils.createLineMesh(pos, ppos, 0xffffff); bone3D.add(line); }else{ //root action Matrix4 mx=boneMatrix.get(0).getMatrix(); mx.multiplyVector3(pos); } mesh.setPosition(pos); bonePositions.add(pos); } //Geometry geo=GeometryUtils.clone(baseGeometry); //Geometry geo=bodyMesh.getGeometry(); Geometry geo=GeometryUtils.clone(baseGeometry); for(int i=0;i<baseGeometry.vertices().length();i++){ Vertex baseVertex=baseGeometry.vertices().get(i); Vertex targetVertex=geo.vertices().get(i); int boneIndex1=(int) bodyIndices.get(i).getX(); int boneIndex2=(int) bodyIndices.get(i).getY(); Vector3 bonePos=boneMatrix.get(boneIndex1).getAbsolutePosition(); Vector3 relatePos=bonePos.clone(); relatePos.sub(baseVertex.getPosition(),bonePos); double length=relatePos.length(); moveMatrix.get(boneIndex1).multiplyVector3(relatePos); //relatePos.addSelf(bonePos); if(boneIndex2!=boneIndex1){ Vector3 bonePos2=boneMatrix.get(boneIndex2).getAbsolutePosition(); Vector3 relatePos2=bonePos2.clone(); relatePos2.sub(baseVertex.getPosition(),bonePos2); double length2=relatePos2.length(); moveMatrix.get(boneIndex2).multiplyVector3(relatePos2); //scalar weight relatePos.multiplyScalar(bodyWeight.get(i).getX()); relatePos2.multiplyScalar(bodyWeight.get(i).getY()); relatePos.addSelf(relatePos2); //keep distance1 faild /* if(length<1){ //length2 Vector3 abpos=THREE.Vector3(); abpos.sub(relatePos, bonePositions.get(boneIndex1)); double scar=abpos.length()/length; abpos.multiplyScalar(scar); abpos.addSelf(bonePositions.get(boneIndex1)); relatePos.set(abpos.getX(), abpos.getY(), abpos.getZ()); }*/ if(length2<1){ Vector3 abpos=THREE.Vector3(); abpos.sub(relatePos, bonePositions.get(boneIndex2)); double scar=abpos.length()/length2; abpos.multiplyScalar(scar); abpos.addSelf(bonePositions.get(boneIndex2)); relatePos.set(abpos.getX(), abpos.getY(), abpos.getZ()); } /* Vector3 diff=THREE.Vector3(); diff.sub(relatePos2, relatePos); diff.multiplyScalar(bodyWeight.get(i).getY()); relatePos.addSelf(diff); */ } targetVertex.getPosition().set(relatePos.getX(), relatePos.getY(), relatePos.getZ()); } geo.computeFaceNormals(); geo.computeVertexNormals(); //Material material=THREE.MeshLambertMaterial().map(ImageUtils.loadTexture("men3smart_texture.png")).build(); bodyMesh=THREE.Mesh(geo, bodyMaterial); root.add(bodyMesh); /* geo.setDynamic(true); geo.setDirtyVertices(true); geo.computeBoundingSphere(); */ //bodyMesh.setGeometry(geo); //bodyMesh.gwtBoundingSphere(); //geo.computeTangents(); /* geo.setDynamic(true); geo.setDirtyVertices(true); geo.computeFaceNormals(); geo.computeVertexNormals(); geo.computeTangents(); */ } }
package com.bkahlert.nebula.widgets.browser; import java.io.File; import java.io.FileOutputStream; import java.net.URI; import java.util.ArrayList; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.Future; import java.util.concurrent.atomic.AtomicReference; import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; import org.apache.log4j.Logger; import org.eclipse.swt.SWT; import org.eclipse.swt.SWTException; import org.eclipse.swt.browser.BrowserFunction; import org.eclipse.swt.browser.LocationAdapter; import org.eclipse.swt.browser.LocationEvent; import org.eclipse.swt.browser.ProgressAdapter; import org.eclipse.swt.browser.ProgressEvent; import org.eclipse.swt.browser.ProgressListener; import org.eclipse.swt.events.DisposeEvent; import org.eclipse.swt.events.DisposeListener; import org.eclipse.swt.events.FocusEvent; import org.eclipse.swt.events.FocusListener; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.graphics.Rectangle; import org.eclipse.swt.layout.FillLayout; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.Listener; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.contexts.IContextActivation; import org.eclipse.ui.contexts.IContextService; import org.eclipse.ui.swt.IFocusService; import com.bkahlert.nebula.utils.CompletedFuture; import com.bkahlert.nebula.utils.EventDelegator; import com.bkahlert.nebula.utils.ExecUtils; import com.bkahlert.nebula.utils.IConverter; import com.bkahlert.nebula.utils.SWTUtils; import com.bkahlert.nebula.utils.colors.RGB; import com.bkahlert.nebula.widgets.browser.extended.html.Element; import com.bkahlert.nebula.widgets.browser.extended.html.IAnker; import com.bkahlert.nebula.widgets.browser.extended.html.IElement; import com.bkahlert.nebula.widgets.browser.listener.IAnkerListener; import com.bkahlert.nebula.widgets.browser.listener.IDropListener; import com.bkahlert.nebula.widgets.browser.listener.IFocusListener; import com.bkahlert.nebula.widgets.browser.listener.IMouseListener; import com.bkahlert.nebula.widgets.browser.runner.BrowserScriptRunner; import com.bkahlert.nebula.widgets.browser.runner.BrowserScriptRunner.BrowserStatus; public class Browser extends Composite implements IBrowser { private static IFocusService FOCUS_SERVICE = null; private static IContextService CONTEXT_SERVICE = null; static { try { FOCUS_SERVICE = (IFocusService) PlatformUI.getWorkbench() .getService(IFocusService.class); CONTEXT_SERVICE = (IContextService) PlatformUI.getWorkbench() .getService(IContextService.class); } catch (NoClassDefFoundError e) { } } private static Logger LOGGER = Logger.getLogger(Browser.class); private static final int STYLES = SWT.INHERIT_FORCE; public static final String FOCUS_ID = "com.bkahlert.nebula.browser"; private org.eclipse.swt.browser.Browser browser; private BrowserScriptRunner browserScriptRunner; private boolean initWithSystemBackgroundColor; private boolean textSelectionsDisabled = false; private boolean settingUri = false; private boolean allowLocationChange = false; private Rectangle cachedContentBounds = null; private final List<IAnkerListener> ankerListeners = new ArrayList<IAnkerListener>(); private final List<IMouseListener> mouseListeners = new ArrayList<IMouseListener>(); private final List<IFocusListener> focusListeners = new ArrayList<IFocusListener>(); private final List<IDropListener> dropListeners = new ArrayList<IDropListener>(); /** * Constructs a new {@link Browser} with the given styles. * * @param parent * @param style * if {@link SWT#INHERIT_FORCE}) is set the loaded page's * background is replaced by the inherited background color */ public Browser(Composite parent, int style) { super(parent, style | SWT.EMBEDDED & ~STYLES); this.setLayout(new FillLayout()); this.initWithSystemBackgroundColor = (style & SWT.INHERIT_FORCE) != 0; this.browser = new org.eclipse.swt.browser.Browser(this, SWT.NONE); this.browser.setVisible(false); this.browserScriptRunner = new BrowserScriptRunner(this.browser) { @Override public void scriptAboutToBeSentToBrowser(String script) { Browser.this.scriptAboutToBeSentToBrowser(script); } @Override public void scriptReturnValueReceived(Object returnValue) { Browser.this.scriptReturnValueReceived(returnValue); } }; new BrowserFunction(this.browser, "__mouseenter") { @Override public Object function(Object[] arguments) { if (arguments.length == 1 && arguments[0] instanceof String) { Browser.this.fireAnkerHover((String) arguments[0], true); } return null; } }; new BrowserFunction(this.browser, "__mouseleave") { @Override public Object function(Object[] arguments) { if (arguments.length == 1 && arguments[0] instanceof String) { Browser.this.fireAnkerHover((String) arguments[0], false); } return null; } }; new BrowserFunction(this.browser, "__mousemove") { @Override public Object function(Object[] arguments) { if (arguments.length == 2 && (arguments[0] == null || arguments[0] instanceof Double) && (arguments[1] == null || arguments[1] instanceof Double)) { Browser.this.fireMouseMove((Double) arguments[0], (Double) arguments[1]); } return null; } }; new BrowserFunction(this.browser, "__mousedown") { @Override public Object function(Object[] arguments) { if (arguments.length == 2 && (arguments[0] == null || arguments[0] instanceof Double) && (arguments[1] == null || arguments[1] instanceof Double)) { Browser.this.fireMouseDown((Double) arguments[0], (Double) arguments[1]); } return null; } }; new BrowserFunction(this.browser, "__mouseup") { @Override public Object function(Object[] arguments) { if (arguments.length == 2 && (arguments[0] == null || arguments[0] instanceof Double) && (arguments[1] == null || arguments[1] instanceof Double)) { Browser.this.fireMouseUp((Double) arguments[0], (Double) arguments[1]); } return null; } }; new BrowserFunction(this.browser, "__click") { @Override public Object function(Object[] arguments) { if (arguments.length == 1 && arguments[0] instanceof String) { Browser.this.fireAnkerClicked((String) arguments[0]); } return null; } }; new BrowserFunction(this.browser, "__focusgained") { @Override public Object function(Object[] arguments) { if (arguments.length == 1 && arguments[0] instanceof String) { final IElement element = new Element((String) arguments[0]); Browser.this.fireFocusGained(element); } return null; } }; new BrowserFunction(this.browser, "__focuslost") { @Override public Object function(Object[] arguments) { if (arguments.length == 1 && arguments[0] instanceof String) { final IElement element = new Element((String) arguments[0]); Browser.this.fireFocusLost(element); } return null; } }; new BrowserFunction(this.browser, "__resize") { @Override public Object function(Object[] arguments) { if (arguments.length == 4 && (arguments[0] == null || arguments[0] instanceof Double) && (arguments[1] == null || arguments[1] instanceof Double) && (arguments[2] == null || arguments[2] instanceof Double) && (arguments[3] == null || arguments[3] instanceof Double)) { Browser.this.cachedContentBounds = new Rectangle( arguments[0] != null ? (int) Math.round((Double) arguments[0]) : 0, arguments[1] != null ? (int) Math .round((Double) arguments[1]) : 0, arguments[2] != null ? (int) Math .round((Double) arguments[2]) : Integer.MAX_VALUE, arguments[3] != null ? (int) Math .round((Double) arguments[3]) : Integer.MAX_VALUE); } return null; } }; new BrowserFunction(this.browser, "__drop") { @Override public Object function(Object[] arguments) { if (arguments.length == 3 && arguments[0] instanceof Double && arguments[1] instanceof Double && arguments[2] instanceof String) { long offsetX = Math.round((Double) arguments[0]); long offsetY = Math.round((Double) arguments[1]); String data = (String) arguments[2]; Browser.this.fireDrop(offsetX, offsetY, data); } return null; } }; // needed so paste action can be overwritten // @see if (FOCUS_SERVICE != null) { FOCUS_SERVICE.addFocusTracker(this.browser, FOCUS_ID); } this.browser.addDisposeListener(new DisposeListener() { @Override public void widgetDisposed(DisposeEvent e) { if (FOCUS_SERVICE != null) { FOCUS_SERVICE.removeFocusTracker(Browser.this.browser); } } }); this.browser.addLocationListener(new LocationAdapter() { @Override public void changing(LocationEvent event) { if (!Browser.this.settingUri) { event.doit = Browser.this.allowLocationChange || Browser.this.browserScriptRunner .getBrowserStatus() == BrowserStatus.LOADING; } } // TODO call injectAnkerCode after a page has loaded a user clicked // on (or do all the same steps on first page load on all // consecutive loads) }); this.browser.addFocusListener(new FocusListener() { private IContextActivation activation = null; @Override public void focusGained(FocusEvent e) { if (CONTEXT_SERVICE != null) { this.activation = CONTEXT_SERVICE .activateContext("com.bkahlert.ui.browser"); } } @Override public void focusLost(FocusEvent e) { if (CONTEXT_SERVICE != null) { CONTEXT_SERVICE.deactivateContext(this.activation); } } }); this.addDisposeListener(new DisposeListener() { @Override public void widgetDisposed(DisposeEvent e) { synchronized (Browser.this.monitor) { if (Browser.this.browserScriptRunner.getBrowserStatus() == BrowserStatus.LOADING) { Browser.this.browserScriptRunner .setBrowserStatus(BrowserStatus.CANCELLED); } Browser.this.browserScriptRunner.dispose(); Browser.this.monitor.notifyAll(); } } }); } private boolean eventCatchScriptInjected = false; /** * Injects the code needed for {@link #addAnkerListener(IAnkerListener)}, * {@link #addFokusListener(IFocusListener)} and * {@link #addDropListener(IFocusListener)} to work. * <p> * The JavaScript remembers a successful injection in case to consecutive * calls are made. * <p> * As soon as a successful injection has been registered, * {@link #eventCatchScriptInjected} is set so no unnecessary further * injection is made. */ private void injectEventCatchScript() { if (this.eventCatchScriptInjected) { return; } File events = BrowserUtils.getFile(Browser.class, "events.js"); try { Browser.this.runImmediately(events); } catch (Exception e) { LOGGER.error("Could not inject events catch script in " + Browser.this.getClass().getSimpleName(), e); } File dnd = BrowserUtils.getFile(Browser.class, "dnd.js"); try { Browser.this.runImmediately(dnd); } catch (Exception e) { LOGGER.error("Could not inject drop catch script in " + Browser.this.getClass().getSimpleName(), e); } Browser.this.eventCatchScriptInjected = true; } /** * This method waits for the {@link Browser} to complete loading. * <p> * It has been observed that the * {@link ProgressListener#completed(ProgressEvent)} fires to early. This * method uses JavaScript to reliably detect the completed state. * * @param pageLoadCheckExpression */ private void waitAndComplete(String pageLoadCheckExpression) { if (Browser.this.browser == null || Browser.this.browser.isDisposed()) { return; } if (Browser.this.browserScriptRunner.getBrowserStatus() != BrowserStatus.LOADING) { if (Browser.this.browserScriptRunner.getBrowserStatus() != BrowserStatus.CANCELLED) { LOGGER.error("State Error: " + Browser.this.browserScriptRunner.getBrowserStatus()); } return; } String completedCallbackFunctionName = BrowserUtils .createRandomFunctionName(); String completedCheckScript = "(function() { " + "function test() { if(document.readyState == 'complete'" + (pageLoadCheckExpression != null ? " && (" + pageLoadCheckExpression + ")" : "") + ") { " + completedCallbackFunctionName + "(); } else { window.setTimeout(test, 50); } } " + "test(); })()"; final AtomicReference<BrowserFunction> completedCallback = new AtomicReference<BrowserFunction>(); completedCallback.set(new BrowserFunction(this.browser, completedCallbackFunctionName) { @Override public Object function(Object[] arguments) { Browser.this.complete(); completedCallback.get().dispose(); return null; } }); try { this.runImmediately(completedCheckScript, IConverter.CONVERTER_VOID); } catch (Exception e) { LOGGER.error( "An error occurred while checking the page load state", e); synchronized (Browser.this.monitor) { Browser.this.monitor.notifyAll(); } } } /** * This method is called by {@link #waitAndComplete(String)} and post * processes the loaded page. * <ol> * <li>calls {@link #beforeCompletion(String)}</li> * <li>injects necessary scripts</li> * <li>runs the scheduled user scripts</li> * </ol> */ private void complete() { final String uri = Browser.this.browser.getUrl(); if (this.initWithSystemBackgroundColor) { this.setBackground(SWTUtils.getEffectiveBackground(Browser.this)); } if (this.textSelectionsDisabled) { try { this.injectCssImmediately("* { -webkit-touch-callout: none; -webkit-user-select: none; -khtml-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; }"); } catch (Exception e) { LOGGER.error(e); } } final Future<Void> finished = Browser.this.beforeCompletion(uri); ExecUtils.nonUISyncExec(Browser.class, "Progress Check for " + uri, new Runnable() { @Override public void run() { try { if (finished != null) { finished.get(); } } catch (Exception e) { LOGGER.error(e); } Browser.this.injectEventCatchScript(); ExecUtils.asyncExec(new Runnable() { @Override public void run() { if (!Browser.this.browser.isDisposed()) { Browser.this.browser.setVisible(true); } } }); synchronized (Browser.this.monitor) { if (Browser.this.browserScriptRunner .getBrowserStatus() != BrowserStatus.CANCELLED) { Browser.this.browserScriptRunner .setBrowserStatus(BrowserStatus.LOADED); } Browser.this.monitor.notifyAll(); } } }); } @Override public Future<Boolean> open(final String uri, final Integer timeout, final String pageLoadCheckExpression) { if (this.browser.isDisposed()) { throw new SWTException(SWT.ERROR_WIDGET_DISPOSED); } Browser.this.browserScriptRunner .setBrowserStatus(BrowserStatus.LOADING); this.browser.addProgressListener(new ProgressAdapter() { @Override public void completed(ProgressEvent event) { Browser.this.waitAndComplete(pageLoadCheckExpression); } }); return ExecUtils.nonUIAsyncExec(Browser.class, "Opening " + uri, new Callable<Boolean>() { @Override public Boolean call() throws Exception { // stops waiting after timeout Future<Void> timeoutMonitor = null; if (timeout != null && timeout > 0) { timeoutMonitor = ExecUtils.nonUIAsyncExec( Browser.class, "Timeout Watcher for " + uri, new Runnable() { @Override public void run() { synchronized (Browser.this.monitor) { if (Browser.this.browserScriptRunner .getBrowserStatus() != BrowserStatus.LOADED) { Browser.this.browserScriptRunner .setBrowserStatus(BrowserStatus.CANCELLED); } Browser.this.monitor .notifyAll(); } } }, timeout); } else { LOGGER.warn("timeout must be greater or equal 0. Ignoring timeout."); } Browser.this.beforeLoad(uri); ExecUtils.syncExec(new Runnable() { @Override public void run() { Browser.this.settingUri = true; if (!Browser.this.browser.isDisposed()) { Browser.this.browser.setUrl(uri.toString()); } Browser.this.settingUri = false; } }); Browser.this.afterLoad(uri); synchronized (Browser.this.monitor) { if (Browser.this.browserScriptRunner .getBrowserStatus() == BrowserStatus.LOADING) { LOGGER.debug("Waiting for " + uri + " to be loaded (Thread: " + Thread.currentThread() + "; status: " + Browser.this.browserScriptRunner .getBrowserStatus() + ")"); Browser.this.monitor.wait(); // notified by progresslistener or by timeout } if (timeoutMonitor != null) { timeoutMonitor.cancel(true); } switch (Browser.this.browserScriptRunner .getBrowserStatus()) { case LOADED: LOGGER.debug("Successfully loaded " + uri); break; case CANCELLED: if (!Browser.this.browser.isDisposed()) { LOGGER.warn("Aborted loading " + uri + " due to timeout"); } break; default: throw new RuntimeException( "Implementation error"); } return Browser.this.browserScriptRunner .getBrowserStatus() == BrowserStatus.LOADED; } } }); } @Override public Future<Boolean> open(String address, Integer timeout) { return this.open(address, timeout, null); } @Override public Future<Boolean> open(URI uri, Integer timeout) { return this.open(uri.toString(), timeout, null); } @Override public Future<Boolean> open(URI uri, Integer timeout, String pageLoadCheckExpression) { return this.open(uri.toString(), timeout, pageLoadCheckExpression); } @Override public Future<Boolean> openBlank() { try { File empty = File.createTempFile("blank", ".html"); FileUtils.writeStringToFile(empty, "<html><head></head><body></body></html>", "UTF-8"); return this.open(new URI("file://" + empty.getAbsolutePath()), 60000); } catch (Exception e) { return new CompletedFuture<Boolean>(false, e); } } @Override public void setAllowLocationChange(boolean allow) { this.allowLocationChange = allow; } @Override public void beforeLoad(String uri) { } @Override public void afterLoad(String uri) { } @Override public Future<Void> beforeCompletion(String uri) { return null; } @Override public void addListener(int eventType, Listener listener) { // evtl. falsche Mauskoordinaten zu verhindern und so ein Fehlverhalten // im InformationControl vorzeugen if (EventDelegator.mustDelegate(eventType, this)) { this.browser.addListener(eventType, listener); } else { super.addListener(eventType, listener); } } /** * Deactivate browser's native context/popup menu. Doing so allows the * definition of menus in an inheriting composite via setMenu. */ public void deactivateNativeMenu() { this.browser.addListener(SWT.MenuDetect, new Listener() { @Override public void handleEvent(Event event) { event.doit = false; } }); } public void deactivateTextSelections() { this.textSelectionsDisabled = true; } @Override public org.eclipse.swt.browser.Browser getBrowser() { return this.browser; } public boolean isLoadingCompleted() { return this.browserScriptRunner.getBrowserStatus() == BrowserStatus.LOADED; } private final Object monitor = new Object(); @Override public Future<Boolean> inject(URI script) { return this.browserScriptRunner.inject(script); } @Override public Future<Boolean> run(final File script) { return this.browserScriptRunner.run(script); } @Override public Future<Boolean> run(final URI script) { return this.browserScriptRunner.run(script); } @Override public Future<Object> run(final String script) { return this.browserScriptRunner.run(script); } @Override public <DEST> Future<DEST> run(final String script, final IConverter<Object, DEST> converter) { return this.browserScriptRunner.run(script, converter); } @Override public <DEST> DEST runImmediately(String script, IConverter<Object, DEST> converter) throws Exception { return this.browserScriptRunner.runImmediately(script, converter); } @Override public void runImmediately(File script) throws Exception { this.browserScriptRunner.runImmediately(script); } @Override public void scriptAboutToBeSentToBrowser(String script) { return; } @Override public void scriptReturnValueReceived(Object returnValue) { return; } @Override public Future<Void> injectJsFile(File file) { return this .run("var script=document.createElement(\"script\"); script.type=\"text/javascript\"; script.src=\"" + "file: + file + "\"; document.getElementsByTagName(\"head\")[0].appendChild(script);", IConverter.CONVERTER_VOID); } @Override public Future<Void> injectCssFile(URI uri) { return this .run("if(document.createStyleSheet){document.createStyleSheet(\"" + uri.toString() + "\")}else{ var link=document.createElement(\"link\"); link.rel=\"stylesheet\"; link.type=\"text/css\"; link.href=\"" + uri.toString() + "\"; document.getElementsByTagName(\"head\")[0].appendChild(link); }", IConverter.CONVERTER_VOID); } private static String createCssInjectionScript(String css) { return "(function(){var style=document.createElement(\"style\");style.appendChild(document.createTextNode(\"" + css + "\"));(document.getElementsByTagName(\"head\")[0]||document.documentElement).appendChild(style)})()"; } @Override public Future<Void> injectCss(String css) { return this.run(createCssInjectionScript(css), IConverter.CONVERTER_VOID); } @Override public void injectCssImmediately(String css) throws Exception { this.runImmediately(createCssInjectionScript(css), IConverter.CONVERTER_VOID); } @Override public void addAnkerListener(IAnkerListener ankerListener) { this.ankerListeners.add(ankerListener); } @Override public void removeAnkerListener(IAnkerListener ankerListener) { this.ankerListeners.remove(ankerListener); } @Override public void addMouseListener(IMouseListener mouseListener) { this.mouseListeners.add(mouseListener); } @Override public void removeMouseListener(IMouseListener mouseListener) { this.mouseListeners.remove(mouseListener); } /** * * @param string * @param mouseEnter * true if mouseenter; false otherwise */ protected void fireAnkerHover(String html, boolean mouseEnter) { IAnker anker = BrowserUtils.extractAnker(html); for (IAnkerListener ankerListener : Browser.this.ankerListeners) { ankerListener.ankerHovered(anker, mouseEnter); } } /** * * @param x * @param y */ protected void fireMouseMove(double x, double y) { for (IMouseListener mouseListener : Browser.this.mouseListeners) { mouseListener.mouseMove(x, y); } } /** * * @param x * @param y */ protected void fireMouseDown(double x, double y) { for (IMouseListener mouseListener : Browser.this.mouseListeners) { mouseListener.mouseDown(x, y); } } /** * * @param x * @param y */ protected void fireMouseUp(double x, double y) { for (IMouseListener mouseListener : Browser.this.mouseListeners) { mouseListener.mouseUp(x, y); } } /** * * @param string */ protected void fireAnkerClicked(String html) { IAnker anker = BrowserUtils.extractAnker(html); for (IAnkerListener ankerListener : Browser.this.ankerListeners) { ankerListener.ankerClicked(anker); } } @Override public void addFocusListener(IFocusListener focusListener) { this.focusListeners.add(focusListener); } @Override public void removeFocusListener(IFocusListener focusListener) { this.focusListeners.remove(focusListener); } synchronized protected void fireFocusGained(IElement element) { for (IFocusListener focusListener : this.focusListeners) { focusListener.focusGained(element); } } synchronized protected void fireFocusLost(IElement element) { for (IFocusListener focusListener : this.focusListeners) { focusListener.focusLost(element); } } @Override public void addDropListener(IDropListener dropListener) { this.dropListeners.add(dropListener); } @Override public void removeDropListener(IDropListener dropListener) { this.dropListeners.remove(dropListener); } synchronized protected void fireDrop(long offsetX, long offsetY, String data) { for (IDropListener dropListener : this.dropListeners) { dropListener.drop(offsetX, offsetY, data); } } @Override public Future<Boolean> containsElementWithID(String id) { return this.run("return document.getElementById('" + id + "') != null", IConverter.CONVERTER_BOOLEAN); } @Override public Future<Boolean> containsElementsWithName(String name) { return this.run("return document.getElementsByName('" + name + "').length > 0", IConverter.CONVERTER_BOOLEAN); } private String escape(String html) { return html.replace("\n", "<br>").replace("& .replace("\r", "").replace("\"", "\\\"").replace("'", "\\'"); } @Override public Future<Void> setBodyHtml(String html) { return this.run("document.body.innerHTML = ('" + this.escape(html) + "');", IConverter.CONVERTER_VOID); } @Override public Future<String> getBodyHtml() { return this.run("return document.body.innerHTML", IConverter.CONVERTER_STRING); } @Override public Future<String> getHtml() { return this.run("return document.documentElement.outerHTML", IConverter.CONVERTER_STRING); } @Override public void setBackground(Color color) { super.setBackground(color); String hex = color != null ? new RGB(color.getRGB()).toHexString() : "transparent"; try { this.injectCssImmediately("html, body { background-color: " + hex + "; }"); } catch (Exception e) { LOGGER.error("Error setting background color to " + color, e); } } @Override public Future<Void> pasteHtmlAtCaret(String html) { String escapedHtml = this.escape(html); try { File js = File.createTempFile("paste", ".js"); FileUtils .write(js, "if(['input','textarea'].indexOf(document.activeElement.tagName.toLowerCase()) != -1) { document.activeElement.value = '"); FileOutputStream outStream = new FileOutputStream(js, true); IOUtils.copy(IOUtils.toInputStream(escapedHtml), outStream); IOUtils.copy( IOUtils.toInputStream("';} else { var t,n;if(window.getSelection){t=window.getSelection();if(t.getRangeAt&&t.rangeCount){n=t.getRangeAt(0);n.deleteContents();var r=document.createElement(\"div\");r.innerHTML='"), outStream); IOUtils.copy(IOUtils.toInputStream(escapedHtml), outStream); IOUtils.copy( IOUtils.toInputStream("';var i=document.createDocumentFragment(),s,o;while(s=r.firstChild){o=i.appendChild(s)}n.insertNode(i);if(o){n=n.cloneRange();n.setStartAfter(o);n.collapse(true);t.removeAllRanges();t.addRange(n)}}}else if(document.selection&&document.selection.type!=\"Control\"){document.selection.createRange().pasteHTML('"), outStream); IOUtils.copy(IOUtils.toInputStream(escapedHtml + "')}}"), outStream); return this.injectJsFile(js); } catch (Exception e) { return new CompletedFuture<Void>(null, e); } } @Override public Point computeSize(int wHint, int hHint, boolean changed) { try { this.browser .execute("if (window[\"__notifySize\"] && typeof window[\"__notifySize\"]) window[\"__notifySize\"]();"); } catch (Exception e) { LOGGER.error("Error computing size for " + Browser.class.getSimpleName()); } Rectangle bounds = this.cachedContentBounds; if (bounds == null) { return super.computeSize(wHint, hHint, changed); } return new Point(bounds.x + bounds.width, bounds.y + bounds.height); } }
package com.bkahlert.nebula.widgets.browser; import java.io.File; import java.io.FileOutputStream; import java.net.URI; import java.util.ArrayList; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.Future; import java.util.concurrent.atomic.AtomicReference; import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; import org.apache.log4j.Logger; import org.eclipse.swt.SWT; import org.eclipse.swt.SWTException; import org.eclipse.swt.browser.BrowserFunction; import org.eclipse.swt.browser.LocationAdapter; import org.eclipse.swt.browser.LocationEvent; import org.eclipse.swt.browser.ProgressAdapter; import org.eclipse.swt.browser.ProgressEvent; import org.eclipse.swt.browser.ProgressListener; import org.eclipse.swt.events.DisposeEvent; import org.eclipse.swt.events.DisposeListener; import org.eclipse.swt.events.FocusEvent; import org.eclipse.swt.events.FocusListener; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.graphics.Rectangle; import org.eclipse.swt.layout.FillLayout; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.Listener; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.contexts.IContextActivation; import org.eclipse.ui.contexts.IContextService; import org.eclipse.ui.swt.IFocusService; import com.bkahlert.nebula.utils.CompletedFuture; import com.bkahlert.nebula.utils.EventDelegator; import com.bkahlert.nebula.utils.ExecUtils; import com.bkahlert.nebula.utils.IConverter; import com.bkahlert.nebula.utils.SWTUtils; import com.bkahlert.nebula.utils.colors.RGB; import com.bkahlert.nebula.widgets.browser.extended.html.Element; import com.bkahlert.nebula.widgets.browser.extended.html.IAnker; import com.bkahlert.nebula.widgets.browser.extended.html.IElement; import com.bkahlert.nebula.widgets.browser.listener.IAnkerListener; import com.bkahlert.nebula.widgets.browser.listener.IDropListener; import com.bkahlert.nebula.widgets.browser.listener.IFocusListener; import com.bkahlert.nebula.widgets.browser.listener.IMouseListener; import com.bkahlert.nebula.widgets.browser.runner.BrowserScriptRunner; import com.bkahlert.nebula.widgets.browser.runner.BrowserScriptRunner.BrowserStatus; public class Browser extends Composite implements IBrowser { private static IFocusService FOCUS_SERVICE = null; private static IContextService CONTEXT_SERVICE = null; static { try { FOCUS_SERVICE = (IFocusService) PlatformUI.getWorkbench() .getService(IFocusService.class); CONTEXT_SERVICE = (IContextService) PlatformUI.getWorkbench() .getService(IContextService.class); } catch (NoClassDefFoundError e) { } } private static Logger LOGGER = Logger.getLogger(Browser.class); private static final int STYLES = SWT.INHERIT_FORCE; public static final String FOCUS_ID = "com.bkahlert.nebula.browser"; private org.eclipse.swt.browser.Browser browser; private BrowserScriptRunner browserScriptRunner; private boolean initWithSystemBackgroundColor; private boolean textSelectionsDisabled = false; private boolean settingUri = false; private boolean allowLocationChange = false; private Rectangle cachedContentBounds = null; private final List<IAnkerListener> ankerListeners = new ArrayList<IAnkerListener>(); private final List<IMouseListener> mouseListeners = new ArrayList<IMouseListener>(); private final List<IFocusListener> focusListeners = new ArrayList<IFocusListener>(); private final List<IDropListener> dropListeners = new ArrayList<IDropListener>(); /** * Constructs a new {@link Browser} with the given styles. * * @param parent * @param style * if {@link SWT#INHERIT_FORCE}) is set the loaded page's * background is replaced by the inherited background color */ public Browser(Composite parent, int style) { super(parent, style | SWT.EMBEDDED & ~STYLES); this.setLayout(new FillLayout()); this.initWithSystemBackgroundColor = (style & SWT.INHERIT_FORCE) != 0; this.browser = new org.eclipse.swt.browser.Browser(this, SWT.NONE); this.browser.setVisible(false); this.browserScriptRunner = new BrowserScriptRunner(this.browser) { @Override public void scriptAboutToBeSentToBrowser(String script) { Browser.this.scriptAboutToBeSentToBrowser(script); } @Override public void scriptReturnValueReceived(Object returnValue) { Browser.this.scriptReturnValueReceived(returnValue); } }; new BrowserFunction(this.browser, "__mouseenter") { @Override public Object function(Object[] arguments) { if (arguments.length == 1 && arguments[0] instanceof String) { Browser.this.fireAnkerHover((String) arguments[0], true); } return null; } }; new BrowserFunction(this.browser, "__mouseleave") { @Override public Object function(Object[] arguments) { if (arguments.length == 1 && arguments[0] instanceof String) { Browser.this.fireAnkerHover((String) arguments[0], false); } return null; } }; new BrowserFunction(this.browser, "__mousemove") { @Override public Object function(Object[] arguments) { if (arguments.length == 2 && (arguments[0] == null || arguments[0] instanceof Double) && (arguments[1] == null || arguments[1] instanceof Double)) { Browser.this.fireMouseMove((Double) arguments[0], (Double) arguments[1]); } return null; } }; new BrowserFunction(this.browser, "__mousedown") { @Override public Object function(Object[] arguments) { if (arguments.length == 2 && (arguments[0] == null || arguments[0] instanceof Double) && (arguments[1] == null || arguments[1] instanceof Double)) { Browser.this.fireMouseDown((Double) arguments[0], (Double) arguments[1]); } return null; } }; new BrowserFunction(this.browser, "__mouseup") { @Override public Object function(Object[] arguments) { if (arguments.length == 2 && (arguments[0] == null || arguments[0] instanceof Double) && (arguments[1] == null || arguments[1] instanceof Double)) { Browser.this.fireMouseUp((Double) arguments[0], (Double) arguments[1]); } return null; } }; new BrowserFunction(this.browser, "__click") { @Override public Object function(Object[] arguments) { if (arguments.length == 1 && arguments[0] instanceof String) { Browser.this.fireAnkerClicked((String) arguments[0]); } return null; } }; new BrowserFunction(this.browser, "__focusgained") { @Override public Object function(Object[] arguments) { if (arguments.length == 1 && arguments[0] instanceof String) { final IElement element = new Element((String) arguments[0]); Browser.this.fireFocusGained(element); } return null; } }; new BrowserFunction(this.browser, "__focuslost") { @Override public Object function(Object[] arguments) { if (arguments.length == 1 && arguments[0] instanceof String) { final IElement element = new Element((String) arguments[0]); Browser.this.fireFocusLost(element); } return null; } }; new BrowserFunction(this.browser, "__resize") { @Override public Object function(Object[] arguments) { if (arguments.length == 4 && (arguments[0] == null || arguments[0] instanceof Double) && (arguments[1] == null || arguments[1] instanceof Double) && (arguments[2] == null || arguments[2] instanceof Double) && (arguments[3] == null || arguments[3] instanceof Double)) { Browser.this.cachedContentBounds = new Rectangle( arguments[0] != null ? (int) Math.round((Double) arguments[0]) : 0, arguments[1] != null ? (int) Math .round((Double) arguments[1]) : 0, arguments[2] != null ? (int) Math .round((Double) arguments[2]) : Integer.MAX_VALUE, arguments[3] != null ? (int) Math .round((Double) arguments[3]) : Integer.MAX_VALUE); } return null; } }; new BrowserFunction(this.browser, "__drop") { @Override public Object function(Object[] arguments) { if (arguments.length == 3 && arguments[0] instanceof Double && arguments[1] instanceof Double && arguments[2] instanceof String) { long offsetX = Math.round((Double) arguments[0]); long offsetY = Math.round((Double) arguments[1]); String data = (String) arguments[2]; Browser.this.fireDrop(offsetX, offsetY, data); } return null; } }; // needed so paste action can be overwritten // @see if (FOCUS_SERVICE != null) { FOCUS_SERVICE.addFocusTracker(this.browser, FOCUS_ID); } this.browser.addDisposeListener(new DisposeListener() { @Override public void widgetDisposed(DisposeEvent e) { if (FOCUS_SERVICE != null) { FOCUS_SERVICE.removeFocusTracker(Browser.this.browser); } } }); this.browser.addLocationListener(new LocationAdapter() { @Override public void changing(LocationEvent event) { if (!Browser.this.settingUri) { event.doit = Browser.this.allowLocationChange || Browser.this.browserScriptRunner .getBrowserStatus() == BrowserStatus.LOADING; } } // TODO call injectAnkerCode after a page has loaded a user clicked // on (or do all the same steps on first page load on all // consecutive loads) }); this.browser.addFocusListener(new FocusListener() { private IContextActivation activation = null; @Override public void focusGained(FocusEvent e) { if (CONTEXT_SERVICE != null) { this.activation = CONTEXT_SERVICE .activateContext("com.bkahlert.ui.browser"); } } @Override public void focusLost(FocusEvent e) { if (CONTEXT_SERVICE != null) { CONTEXT_SERVICE.deactivateContext(this.activation); } } }); this.addDisposeListener(new DisposeListener() { @Override public void widgetDisposed(DisposeEvent e) { synchronized (Browser.this.monitor) { if (Browser.this.browserScriptRunner.getBrowserStatus() == BrowserStatus.LOADING) { Browser.this.browserScriptRunner .setBrowserStatus(BrowserStatus.CANCELLED); } Browser.this.browserScriptRunner.dispose(); Browser.this.monitor.notifyAll(); } } }); } private boolean eventCatchScriptInjected = false; /** * Injects the code needed for {@link #addAnkerListener(IAnkerListener)}, * {@link #addFokusListener(IFocusListener)} and * {@link #addDropListener(IFocusListener)} to work. * <p> * The JavaScript remembers a successful injection in case to consecutive * calls are made. * <p> * As soon as a successful injection has been registered, * {@link #eventCatchScriptInjected} is set so no unnecessary further * injection is made. */ private void injectEventCatchScript() { if (this.eventCatchScriptInjected) { return; } File events = BrowserUtils.getFile(Browser.class, "events.js"); try { Browser.this.runImmediately(events); } catch (Exception e) { LOGGER.error("Could not inject events catch script in " + Browser.this.getClass().getSimpleName(), e); } File dnd = BrowserUtils.getFile(Browser.class, "dnd.js"); try { Browser.this.runImmediately(dnd); } catch (Exception e) { LOGGER.error("Could not inject drop catch script in " + Browser.this.getClass().getSimpleName(), e); } Browser.this.eventCatchScriptInjected = true; } /** * This method waits for the {@link Browser} to complete loading. * <p> * It has been observed that the * {@link ProgressListener#completed(ProgressEvent)} fires to early. This * method uses JavaScript to reliably detect the completed state. * * @param pageLoadCheckExpression */ private void waitAndComplete(String pageLoadCheckExpression) { if (Browser.this.browser == null || Browser.this.browser.isDisposed()) { return; } if (Browser.this.browserScriptRunner.getBrowserStatus() != BrowserStatus.LOADING) { if (Browser.this.browserScriptRunner.getBrowserStatus() != BrowserStatus.CANCELLED) { LOGGER.error("State Error: " + Browser.this.browserScriptRunner.getBrowserStatus()); } return; } String completedCallbackFunctionName = BrowserUtils .createRandomFunctionName(); String completedCheckScript = "(function() { " + "function test() { if(document.readyState == 'complete'" + (pageLoadCheckExpression != null ? " && (" + pageLoadCheckExpression + ")" : "") + ") { " + completedCallbackFunctionName + "(); } else { window.setTimeout(test, 50); } } " + "test(); })()"; final AtomicReference<BrowserFunction> completedCallback = new AtomicReference<BrowserFunction>(); completedCallback.set(new BrowserFunction(this.browser, completedCallbackFunctionName) { @Override public Object function(Object[] arguments) { Browser.this.complete(); completedCallback.get().dispose(); return null; } }); try { this.runImmediately(completedCheckScript, IConverter.CONVERTER_VOID); } catch (Exception e) { LOGGER.error( "An error occurred while checking the page load state", e); synchronized (Browser.this.monitor) { Browser.this.monitor.notifyAll(); } } } /** * This method is called by {@link #waitAndComplete(String)} and post * processes the loaded page. * <ol> * <li>calls {@link #beforeCompletion(String)}</li> * <li>injects necessary scripts</li> * <li>runs the scheduled user scripts</li> * </ol> */ private void complete() { final String uri = Browser.this.browser.getUrl(); if (this.initWithSystemBackgroundColor) { this.setBackground(SWTUtils.getEffectiveBackground(Browser.this)); } if (this.textSelectionsDisabled) { try { this.injectCssImmediately("* { -webkit-touch-callout: none; -webkit-user-select: none; -khtml-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; }"); } catch (Exception e) { LOGGER.error(e); } } final Future<Void> finished = Browser.this.beforeCompletion(uri); ExecUtils.nonUISyncExec(Browser.class, "Progress Check for " + uri, new Runnable() { @Override public void run() { try { if (finished != null) { finished.get(); } } catch (Exception e) { LOGGER.error(e); } Browser.this.injectEventCatchScript(); ExecUtils.asyncExec(new Runnable() { @Override public void run() { Browser.this.browser.setVisible(true); } }); synchronized (Browser.this.monitor) { if (Browser.this.browserScriptRunner .getBrowserStatus() != BrowserStatus.CANCELLED) { Browser.this.browserScriptRunner .setBrowserStatus(BrowserStatus.LOADED); } Browser.this.monitor.notifyAll(); } } }); } @Override public Future<Boolean> open(final String uri, final Integer timeout, final String pageLoadCheckExpression) { if (this.browser.isDisposed()) { throw new SWTException(SWT.ERROR_WIDGET_DISPOSED); } Browser.this.browserScriptRunner .setBrowserStatus(BrowserStatus.LOADING); this.browser.addProgressListener(new ProgressAdapter() { @Override public void completed(ProgressEvent event) { Browser.this.waitAndComplete(pageLoadCheckExpression); } }); return ExecUtils.nonUIAsyncExec(Browser.class, "Opening " + uri, new Callable<Boolean>() { @Override public Boolean call() throws Exception { // stops waiting after timeout Future<Void> timeoutMonitor = null; if (timeout != null && timeout > 0) { timeoutMonitor = ExecUtils.nonUIAsyncExec( Browser.class, "Timeout Watcher for " + uri, new Runnable() { @Override public void run() { synchronized (Browser.this.monitor) { if (Browser.this.browserScriptRunner .getBrowserStatus() != BrowserStatus.LOADED) { Browser.this.browserScriptRunner .setBrowserStatus(BrowserStatus.CANCELLED); } Browser.this.monitor .notifyAll(); } } }, timeout); } else { LOGGER.warn("timeout must be greater or equal 0. Ignoring timeout."); } Browser.this.beforeLoad(uri); ExecUtils.syncExec(new Runnable() { @Override public void run() { Browser.this.settingUri = true; Browser.this.browser.setUrl(uri.toString()); Browser.this.settingUri = false; } }); Browser.this.afterLoad(uri); synchronized (Browser.this.monitor) { if (Browser.this.browserScriptRunner .getBrowserStatus() == BrowserStatus.LOADING) { LOGGER.debug("Waiting for " + uri + " to be loaded (Thread: " + Thread.currentThread() + "; status: " + Browser.this.browserScriptRunner .getBrowserStatus() + ")"); Browser.this.monitor.wait(); // notified by progresslistener or by timeout } if (timeoutMonitor != null) { timeoutMonitor.cancel(true); } switch (Browser.this.browserScriptRunner .getBrowserStatus()) { case LOADED: LOGGER.debug("Successfully loaded " + uri); break; case CANCELLED: if (!Browser.this.browser.isDisposed()) { LOGGER.warn("Aborted loading " + uri + " due to timeout"); } break; default: throw new RuntimeException( "Implementation error"); } return Browser.this.browserScriptRunner .getBrowserStatus() == BrowserStatus.LOADED; } } }); } @Override public Future<Boolean> open(String address, Integer timeout) { return this.open(address, timeout, null); } @Override public Future<Boolean> open(URI uri, Integer timeout) { return this.open(uri.toString(), timeout, null); } @Override public Future<Boolean> open(URI uri, Integer timeout, String pageLoadCheckExpression) { return this.open(uri.toString(), timeout, pageLoadCheckExpression); } @Override public Future<Boolean> openBlank() { try { File empty = File.createTempFile("blank", ".html"); FileUtils.writeStringToFile(empty, "<html><head></head><body></body></html>", "UTF-8"); return this.open(new URI("file://" + empty.getAbsolutePath()), 60000); } catch (Exception e) { return new CompletedFuture<Boolean>(false, e); } } @Override public void setAllowLocationChange(boolean allow) { this.allowLocationChange = allow; } @Override public void beforeLoad(String uri) { } @Override public void afterLoad(String uri) { } @Override public Future<Void> beforeCompletion(String uri) { return null; } @Override public void addListener(int eventType, Listener listener) { // evtl. falsche Mauskoordinaten zu verhindern und so ein Fehlverhalten // im InformationControl vorzeugen if (EventDelegator.mustDelegate(eventType, this)) { this.browser.addListener(eventType, listener); } else { super.addListener(eventType, listener); } } /** * Deactivate browser's native context/popup menu. Doing so allows the * definition of menus in an inheriting composite via setMenu. */ public void deactivateNativeMenu() { this.browser.addListener(SWT.MenuDetect, new Listener() { @Override public void handleEvent(Event event) { event.doit = false; } }); } public void deactivateTextSelections() { this.textSelectionsDisabled = true; } @Override public org.eclipse.swt.browser.Browser getBrowser() { return this.browser; } public boolean isLoadingCompleted() { return this.browserScriptRunner.getBrowserStatus() == BrowserStatus.LOADED; } private final Object monitor = new Object(); @Override public Future<Boolean> inject(URI script) { return this.browserScriptRunner.inject(script); } @Override public Future<Boolean> run(final File script) { return this.browserScriptRunner.run(script); } @Override public Future<Boolean> run(final URI script) { return this.browserScriptRunner.run(script); } @Override public Future<Object> run(final String script) { return this.browserScriptRunner.run(script); } @Override public <DEST> Future<DEST> run(final String script, final IConverter<Object, DEST> converter) { return this.browserScriptRunner.run(script, converter); } @Override public <DEST> DEST runImmediately(String script, IConverter<Object, DEST> converter) throws Exception { return this.browserScriptRunner.runImmediately(script, converter); } @Override public void runImmediately(File script) throws Exception { this.browserScriptRunner.runImmediately(script); } @Override public void scriptAboutToBeSentToBrowser(String script) { return; } @Override public void scriptReturnValueReceived(Object returnValue) { return; } @Override public Future<Void> injectJsFile(File file) { return this .run("var script=document.createElement(\"script\"); script.type=\"text/javascript\"; script.src=\"" + "file: + file + "\"; document.getElementsByTagName(\"head\")[0].appendChild(script);", IConverter.CONVERTER_VOID); } @Override public Future<Void> injectCssFile(URI uri) { return this .run("if(document.createStyleSheet){document.createStyleSheet(\"" + uri.toString() + "\")}else{ var link=document.createElement(\"link\"); link.rel=\"stylesheet\"; link.type=\"text/css\"; link.href=\"" + uri.toString() + "\"; document.getElementsByTagName(\"head\")[0].appendChild(link); }", IConverter.CONVERTER_VOID); } private static String createCssInjectionScript(String css) { return "(function(){var style=document.createElement(\"style\");style.appendChild(document.createTextNode(\"" + css + "\"));(document.getElementsByTagName(\"head\")[0]||document.documentElement).appendChild(style)})()"; } @Override public Future<Void> injectCss(String css) { return this.run(createCssInjectionScript(css), IConverter.CONVERTER_VOID); } @Override public void injectCssImmediately(String css) throws Exception { this.runImmediately(createCssInjectionScript(css), IConverter.CONVERTER_VOID); } @Override public void addAnkerListener(IAnkerListener ankerListener) { this.ankerListeners.add(ankerListener); } @Override public void removeAnkerListener(IAnkerListener ankerListener) { this.ankerListeners.remove(ankerListener); } @Override public void addMouseListener(IMouseListener mouseListener) { this.mouseListeners.add(mouseListener); } @Override public void removeMouseListener(IMouseListener mouseListener) { this.mouseListeners.remove(mouseListener); } /** * * @param string * @param mouseEnter * true if mouseenter; false otherwise */ protected void fireAnkerHover(String html, boolean mouseEnter) { IAnker anker = BrowserUtils.extractAnker(html); for (IAnkerListener ankerListener : Browser.this.ankerListeners) { ankerListener.ankerHovered(anker, mouseEnter); } } /** * * @param x * @param y */ protected void fireMouseMove(double x, double y) { for (IMouseListener mouseListener : Browser.this.mouseListeners) { mouseListener.mouseMove(x, y); } } /** * * @param x * @param y */ protected void fireMouseDown(double x, double y) { for (IMouseListener mouseListener : Browser.this.mouseListeners) { mouseListener.mouseDown(x, y); } } /** * * @param x * @param y */ protected void fireMouseUp(double x, double y) { for (IMouseListener mouseListener : Browser.this.mouseListeners) { mouseListener.mouseUp(x, y); } } /** * * @param string */ protected void fireAnkerClicked(String html) { IAnker anker = BrowserUtils.extractAnker(html); for (IAnkerListener ankerListener : Browser.this.ankerListeners) { ankerListener.ankerClicked(anker); } } @Override public void addFocusListener(IFocusListener focusListener) { this.focusListeners.add(focusListener); } @Override public void removeFocusListener(IFocusListener focusListener) { this.focusListeners.remove(focusListener); } synchronized protected void fireFocusGained(IElement element) { for (IFocusListener focusListener : this.focusListeners) { focusListener.focusGained(element); } } synchronized protected void fireFocusLost(IElement element) { for (IFocusListener focusListener : this.focusListeners) { focusListener.focusLost(element); } } @Override public void addDropListener(IDropListener dropListener) { this.dropListeners.add(dropListener); } @Override public void removeDropListener(IDropListener dropListener) { this.dropListeners.remove(dropListener); } synchronized protected void fireDrop(long offsetX, long offsetY, String data) { for (IDropListener dropListener : this.dropListeners) { dropListener.drop(offsetX, offsetY, data); } } @Override public Future<Boolean> containsElementWithID(String id) { return this.run("return document.getElementById('" + id + "') != null", IConverter.CONVERTER_BOOLEAN); } @Override public Future<Boolean> containsElementsWithName(String name) { return this.run("return document.getElementsByName('" + name + "').length > 0", IConverter.CONVERTER_BOOLEAN); } private String escape(String html) { return html.replace("\n", "<br>").replace("& .replace("\r", "").replace("\"", "\\\"").replace("'", "\\'"); } @Override public Future<Void> setBodyHtml(String html) { return this.run("document.body.innerHTML = ('" + this.escape(html) + "');", IConverter.CONVERTER_VOID); } @Override public Future<String> getBodyHtml() { return this.run("return document.body.innerHTML", IConverter.CONVERTER_STRING); } @Override public Future<String> getHtml() { return this.run("return document.documentElement.outerHTML", IConverter.CONVERTER_STRING); } @Override public void setBackground(Color color) { super.setBackground(color); String hex = color != null ? new RGB(color.getRGB()).toHexString() : "transparent"; try { this.injectCssImmediately("html, body { background-color: " + hex + "; }"); } catch (Exception e) { LOGGER.error("Error setting background color to " + color, e); } } @Override public Future<Void> pasteHtmlAtCaret(String html) { String escapedHtml = this.escape(html); try { File js = File.createTempFile("paste", ".js"); FileUtils .write(js, "if(['input','textarea'].indexOf(document.activeElement.tagName.toLowerCase()) != -1) { document.activeElement.value = '"); FileOutputStream outStream = new FileOutputStream(js, true); IOUtils.copy(IOUtils.toInputStream(escapedHtml), outStream); IOUtils.copy( IOUtils.toInputStream("';} else { var t,n;if(window.getSelection){t=window.getSelection();if(t.getRangeAt&&t.rangeCount){n=t.getRangeAt(0);n.deleteContents();var r=document.createElement(\"div\");r.innerHTML='"), outStream); IOUtils.copy(IOUtils.toInputStream(escapedHtml), outStream); IOUtils.copy( IOUtils.toInputStream("';var i=document.createDocumentFragment(),s,o;while(s=r.firstChild){o=i.appendChild(s)}n.insertNode(i);if(o){n=n.cloneRange();n.setStartAfter(o);n.collapse(true);t.removeAllRanges();t.addRange(n)}}}else if(document.selection&&document.selection.type!=\"Control\"){document.selection.createRange().pasteHTML('"), outStream); IOUtils.copy(IOUtils.toInputStream(escapedHtml + "')}}"), outStream); return this.injectJsFile(js); } catch (Exception e) { return new CompletedFuture<Void>(null, e); } } @Override public Point computeSize(int wHint, int hHint, boolean changed) { try { this.browser .execute("if (window[\"__notifySize\"] && typeof window[\"__notifySize\"]) window[\"__notifySize\"]();"); } catch (Exception e) { LOGGER.error("Error computing size for " + Browser.class.getSimpleName()); } Rectangle bounds = this.cachedContentBounds; if (bounds == null) { return super.computeSize(wHint, hHint, changed); } return new Point(bounds.x + bounds.width, bounds.y + bounds.height); } }
package eu.nimble.core.infrastructure.identity.clients; import feign.Retryer; import feign.hystrix.HystrixFeign; import feign.jackson.JacksonDecoder; import feign.jackson.JacksonEncoder; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.cloud.netflix.feign.support.SpringMvcContract; import org.springframework.context.annotation.PropertySource; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.List; @Service @PropertySource("classpath:bootstrap.yml") public class IndexingClientController { private IndexingClient nimbleIndexClient; private IndexingClient federatedIndexClient; private List<IndexingClient> clients; @Value("${nimble.indexing.url}") private String nimbleIndexUrl; @Value("${federated-index-enabled}") private boolean federatedIndexEnabled; @Value("${nimble.indexing.federated-index-url}") private String federatedIndexUrl; @Autowired IndexingClientFallback indexingFallback; public IndexingClientController() { } public IndexingClient getNimbleIndexClient() { if (nimbleIndexClient == null) { nimbleIndexClient = createIndexingClient(nimbleIndexUrl); } return nimbleIndexClient; } public IndexingClient getFederatedIndexClient() { if (federatedIndexEnabled && federatedIndexClient == null) { federatedIndexClient = createIndexingClient(federatedIndexUrl); } return federatedIndexClient; } public List<IndexingClient> getClients() { if (clients == null) { clients = new ArrayList<IndexingClient>(); clients.add(getNimbleIndexClient()); if (federatedIndexEnabled) { clients.add(getFederatedIndexClient()); } } return clients; } private IndexingClient createIndexingClient(String url) { return HystrixFeign.builder().contract(new SpringMvcContract()) .encoder(new JacksonEncoder()) .decoder(new JacksonDecoder()) .retryer(new Retryer.Default(1,100,3)) .target(IndexingClient.class, url, indexingFallback); } }
package eu.nimble.core.infrastructure.identity.system; import com.fasterxml.jackson.core.JsonProcessingException; import com.mashape.unirest.http.HttpResponse; import com.mashape.unirest.http.JsonNode; import com.mashape.unirest.http.Unirest; import com.mashape.unirest.http.exceptions.UnirestException; import eu.nimble.core.infrastructure.identity.clients.IndexingClient; import eu.nimble.core.infrastructure.identity.clients.IndexingClientController; import eu.nimble.core.infrastructure.identity.entity.NegotiationSettings; import eu.nimble.core.infrastructure.identity.entity.UaaUser; import eu.nimble.core.infrastructure.identity.entity.dto.CompanySettings; import eu.nimble.core.infrastructure.identity.repository.*; import eu.nimble.core.infrastructure.identity.service.AdminService; import eu.nimble.core.infrastructure.identity.service.CertificateService; import eu.nimble.core.infrastructure.identity.service.IdentityService; import eu.nimble.core.infrastructure.identity.utils.*; import eu.nimble.service.model.ubl.commonaggregatecomponents.*; import eu.nimble.service.model.ubl.commonbasiccomponents.BinaryObjectType; import eu.nimble.service.model.ubl.commonbasiccomponents.CodeType; import eu.nimble.utility.JsonSerializationUtility; import eu.nimble.utility.persistence.binary.BinaryContentService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiParam; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.io.ByteArrayResource; import org.springframework.core.io.Resource; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import java.io.IOException; import java.math.BigInteger; import java.util.ArrayList; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; import static eu.nimble.core.infrastructure.identity.uaa.OAuthClient.Role.*; import static eu.nimble.core.infrastructure.identity.utils.UblAdapter.*; import static eu.nimble.service.model.ubl.extension.QualityIndicatorParameter.*; import static eu.nimble.utility.HttpResponseUtil.createResponseEntityAndLog; @RestController @RequestMapping("/company-settings") @SuppressWarnings({"SpringJavaAutowiredFieldsWarningInspection", "FieldCanBeLocal"}) @Api(value = "company-settings", description = "API for handling settings of companies.") public class CompanySettingsController { private final Long MAX_IMAGE_SIZE = 10 * 1024L * 1024L; // in bytes private static final Logger logger = LoggerFactory.getLogger(CompanySettingsController.class); @Autowired private PartyRepository partyRepository; @Autowired private QualifyingPartyRepository qualifyingPartyRepository; @Autowired private CertificateRepository certificateRepository; @Autowired private DocumentReferenceRepository documentReferenceRepository; @Autowired private NegotiationSettingsRepository negotiationSettingsRepository; @Autowired private IdentityService identityService; @Autowired private CertificateService certificateService; private BinaryContentService binaryContentService = new BinaryContentService(); @Autowired private IndexingClientController indexingController; @Autowired private AdminService adminService; @ApiOperation(value = "Retrieve company settings", response = CompanySettings.class) @RequestMapping(value = "/{companyID}", produces = {"application/json"}, method = RequestMethod.GET) ResponseEntity<CompanySettings> getSettings( @ApiParam(value = "Id of company to retrieve settings from.", required = true) @PathVariable Long companyID) { // search relevant parties PartyType company = partyRepository.findByHjid(companyID).stream().findFirst().orElseThrow(ControllerUtils.CompanyNotFoundException::new); Optional<QualifyingPartyType> qualifyingPartyOptional = qualifyingPartyRepository.findByParty(company).stream().findFirst(); logger.debug("Returning requested settings for party with Id {}", company.getHjid()); // pre fetch image metadata without binaries enrichImageMetadata(company); CompanySettings settings = UblAdapter.adaptCompanySettings(company, qualifyingPartyOptional.orElse(null)); return new ResponseEntity<>(settings, HttpStatus.OK); } @ApiOperation(value = "Change company settings", response = CompanySettings.class) @RequestMapping(value = "/{companyID}", consumes = {"application/json"}, method = RequestMethod.PUT) ResponseEntity<?> setSettings( @RequestHeader(value = "Authorization") String bearer, @ApiParam(value = "Id of company to change settings from.", required = true) @PathVariable Long companyID, @ApiParam(value = "Settings to update.", required = true) @RequestBody CompanySettings newSettings)throws IOException{ if (identityService.hasAnyRole(bearer,COMPANY_ADMIN,LEGAL_REPRESENTATIVE, PLATFORM_MANAGER, INITIAL_REPRESENTATIVE, PUBLISHER) == false) return new ResponseEntity<>("Only legal representatives, company admin or platform managers are allowed add images", HttpStatus.FORBIDDEN); PartyType existingCompany = partyRepository.findByHjid(companyID).stream().findFirst().orElseThrow(ControllerUtils.CompanyNotFoundException::new); logger.debug("Changing settings for party with Id {}", existingCompany.getHjid()); existingCompany = UblAdapter.adaptCompanySettings(newSettings, null, existingCompany); Optional<QualifyingPartyType> qualifyingPartyOptional = qualifyingPartyRepository.findByParty(existingCompany).stream().findFirst(); QualifyingPartyType qualifyingParty = UblAdapter.adaptQualifyingParty(newSettings, existingCompany, qualifyingPartyOptional.orElse(null)); qualifyingPartyRepository.save(qualifyingParty); // set preferred product categories List<CodeType> preferredProductCategories = UblAdapter.adaptProductCategories(newSettings.getPreferredProductCategories()); existingCompany.getPreferredItemClassificationCode().clear(); existingCompany.getPreferredItemClassificationCode().addAll(preferredProductCategories); // set recently used product categories List<CodeType> recentlyUsedProductCategories = UblAdapter.adaptProductCategories(newSettings.getRecentlyUsedProductCategories()); existingCompany.getMostRecentItemsClassificationCode().clear(); existingCompany.getMostRecentItemsClassificationCode().addAll(recentlyUsedProductCategories); partyRepository.save(existingCompany); eu.nimble.service.model.solr.party.PartyType indexedParty = indexingController.getNimbleIndexClient().getParty(existingCompany.getHjid().toString(),bearer); //indexing the new company in the indexing service eu.nimble.service.model.solr.party.PartyType party = DataModelUtils.toIndexParty(existingCompany,qualifyingParty); if (indexedParty != null && indexedParty.getVerified()) { party.setVerified(true); } List<IndexingClient> indexingClients = indexingController.getClients(); for(IndexingClient indexingClient : indexingClients){ indexingClient.setParty(party,bearer); } newSettings = adaptCompanySettings(existingCompany, qualifyingParty); return new ResponseEntity<>(newSettings, HttpStatus.ACCEPTED); } @ApiOperation(value = "Upload company image") @RequestMapping(value = "/{companyID}/image", produces = {"application/json"}, method = RequestMethod.POST) public ResponseEntity<?> uploadImage( @RequestHeader(value = "Authorization") String bearer, @ApiParam(value = "Id of company", required = true) @PathVariable Long companyID, @RequestParam(value = "isLogo", defaultValue = "false") String isLogo, @RequestParam(value = "file") MultipartFile imageFile) throws IOException { if (identityService.hasAnyRole(bearer,COMPANY_ADMIN,LEGAL_REPRESENTATIVE, PLATFORM_MANAGER, INITIAL_REPRESENTATIVE) == false) return new ResponseEntity<>("Only legal representatives, company admin or platform managers are allowed add images", HttpStatus.FORBIDDEN); if (imageFile.getSize() > MAX_IMAGE_SIZE) throw new ControllerUtils.FileTooLargeException(); PartyType company = getCompanySecure(companyID, bearer); logger.info("Storing image for company with ID " + UblAdapter.adaptPartyIdentifier(company)); Boolean logoFlag = "true".equals(isLogo); // scale image byte[] scaledImage = ImageUtils.scaleImage(imageFile.getBytes(), false, imageFile.getContentType()); // store the original object in separate database BinaryObjectType binaryObject = new BinaryObjectType(); binaryObject.setValue(scaledImage); binaryObject.setMimeCode(imageFile.getContentType()); binaryObject.setFileName(imageFile.getOriginalFilename()); binaryObject = binaryContentService.createContent(binaryObject); binaryObject.setValue(null); // reset value so it is not stored in database DocumentReferenceType imageDocument = UblAdapter.adaptCompanyPhoto(binaryObject, logoFlag); documentReferenceRepository.save(imageDocument); company.getDocumentReference().add(imageDocument); partyRepository.save(company); imageDocument.setID(imageDocument.getHjid().toString()); imageDocument.getAttachment().getEmbeddedDocumentBinaryObject().setUri(null); // reset uri (images are handled differently) //indexing logo image uri for the existing party eu.nimble.service.model.solr.party.PartyType indexParty = indexingController.getNimbleIndexClient().getParty(company.getHjid().toString(),bearer); indexParty.setLogoId(imageDocument.getID()); List<IndexingClient> indexingClients = indexingController.getClients(); for(IndexingClient indexingClient : indexingClients){ indexingClient.setParty(indexParty,bearer); } return ResponseEntity.ok(imageDocument); } @ApiOperation(value = "Download company image") @RequestMapping(value = "/image/{imageId}", produces = {"application/json"}, method = RequestMethod.GET) public ResponseEntity<Resource> downloadImage( @ApiParam(value = "Id of company to retrieve settings from.", required = true) @PathVariable Long imageId) { // collect image resource DocumentReferenceType imageDocument = documentReferenceRepository.findOne(imageId); if (imageDocument == null) throw new ControllerUtils.DocumentNotFoundException(); String uri = imageDocument.getAttachment().getEmbeddedDocumentBinaryObject().getUri(); BinaryObjectType imageObject = binaryContentService.retrieveContent(uri); Resource imageResource = new ByteArrayResource(imageObject.getValue()); logger.info("Downloading image with Id " + imageId); return ResponseEntity.ok() .contentType(MediaType.parseMediaType(imageObject.getMimeCode())) .body(imageResource); } @ApiOperation(value = "Delete company image") @RequestMapping(value = "/{companyID}/image/{imageId}", produces = {"application/json"}, method = RequestMethod.DELETE) public ResponseEntity<?> deleteImage( @RequestHeader(value = "Authorization") String bearer, @ApiParam(value = "Id of company owning the image", required = true) @PathVariable Long companyID, @ApiParam(value = "Id of image to delete", required = true) @PathVariable Long imageId) throws IOException { if (identityService.hasAnyRole(bearer, COMPANY_ADMIN,LEGAL_REPRESENTATIVE, PLATFORM_MANAGER, INITIAL_REPRESENTATIVE) == false) return new ResponseEntity<>("Only legal representatives or platform managers are allowed to delete images", HttpStatus.FORBIDDEN); logger.info("Deleting image with Id " + imageId); PartyType company = getCompanySecure(companyID, bearer); if (company.getDocumentReference().stream().anyMatch(dr -> imageId.equals(dr.getHjid())) == false) throw new ControllerUtils.DocumentNotFoundException("No associated document found."); if (documentReferenceRepository.exists(imageId) == false) throw new ControllerUtils.DocumentNotFoundException("No document for Id found."); // delete binary content DocumentReferenceType imageDocument = documentReferenceRepository.findOne(imageId); String uri = imageDocument.getAttachment().getEmbeddedDocumentBinaryObject().getUri(); binaryContentService.deleteContentIdentity(uri); // delete document of company documentReferenceRepository.delete(imageDocument); // remove from list in party Optional<DocumentReferenceType> toDelete = company.getDocumentReference().stream() .filter(dr -> imageId.equals(dr.getHjid())) .findFirst(); if (toDelete.isPresent()) { company.getDocumentReference().remove(toDelete.get()); partyRepository.save(company); } //removing logo image id from the indexed the party eu.nimble.service.model.solr.party.PartyType indexParty = indexingController.getNimbleIndexClient().getParty(company.getHjid().toString(),bearer); indexParty.setLogoId(""); List<IndexingClient> indexingClients = indexingController.getClients(); for(IndexingClient indexingClient : indexingClients){ indexingClient.setParty(indexParty,bearer); } return ResponseEntity.ok().build(); } @ApiOperation(value = "Certificate upload") @PostMapping("/{companyID}/certificate") public ResponseEntity<?> uploadCertificate( @RequestHeader(value = "Authorization") String bearer, @ApiParam(value = "Id of company owning the certificate", required = true) @PathVariable Long companyID, @RequestParam("file") MultipartFile certFile, @RequestParam("name") String name, @RequestParam("description") String description, @RequestParam("type") String type, @RequestParam("langId") String languageId, @RequestParam("certID") String certID ) throws IOException { if (identityService.hasAnyRole(bearer, LEGAL_REPRESENTATIVE, PLATFORM_MANAGER, INITIAL_REPRESENTATIVE) == false) return new ResponseEntity<>("Only legal representatives or platform managers are allowed to upload certificates", HttpStatus.FORBIDDEN); PartyType company = getCompanySecure(companyID, bearer); if(!certID.equals("null")){ Long certId = Long.parseLong(certID); // delete binary content CertificateType certificate = certificateRepository.findOne(certId); String uri = certificate.getDocumentReference().get(0).getAttachment().getEmbeddedDocumentBinaryObject().getUri(); binaryContentService.deleteContentIdentity(uri); // delete certificate certificateRepository.delete(certificate); // update list of certificates Optional<CertificateType> toDelete = company.getCertificate().stream() .filter(c -> c.getHjid() != null) .filter(c -> c.getHjid().equals(certId)) .findFirst(); if (toDelete.isPresent()) { company.getCertificate().remove(toDelete.get()); partyRepository.save(company); } } BinaryObjectType certificateBinary = new BinaryObjectType(); certificateBinary.setValue(certFile.getBytes()); certificateBinary.setFileName(certFile.getOriginalFilename()); certificateBinary.setMimeCode(certFile.getContentType()); certificateBinary.setLanguageID(languageId); certificateBinary = binaryContentService.createContent(certificateBinary); certificateBinary.setValue(null); // reset value so it is not stored in database // create new certificate CertificateType certificate = UblAdapter.adaptCertificate(certificateBinary, name, type, description); // update and store company company.getCertificate().add(certificate); partyRepository.save(company); return ResponseEntity.ok(certificate); } @ApiOperation(value = "Certificate download") @RequestMapping(value = "/certificate/{certificateId}", method = RequestMethod.GET) ResponseEntity<?> downloadCertificate(@ApiParam(value = "Id of certificate.", required = true) @PathVariable Long certificateId) { CertificateType certificateType = certificateService.queryCertificate(certificateId); if (certificateType == null) return ResponseEntity.notFound().build(); String uri = certificateType.getDocumentReference().get(0).getAttachment().getEmbeddedDocumentBinaryObject().getUri(); BinaryObjectType certFile = binaryContentService.retrieveContent(uri); Resource certResource = new ByteArrayResource(certFile.getValue()); return ResponseEntity.ok() .contentType(MediaType.parseMediaType(certFile.getMimeCode())) .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + certFile.getFileName() + "\"") .body(certResource); } @ApiOperation(value = "Certificate download") @RequestMapping(value = "/certificate/{certificateId}/object", method = RequestMethod.GET) ResponseEntity<CertificateType> downloadCertificateObject(@ApiParam(value = "Id of certificate.", required = true) @PathVariable Long certificateId) { CertificateType certificateType = certificateService.queryCertificate(certificateId); if (certificateType == null) return ResponseEntity.status(HttpStatus.NOT_FOUND).body(null); return ResponseEntity.ok().body(certificateType); } @ApiOperation(value = "Certificate deletion") @RequestMapping(value = "/{companyID}/certificate/{certificateId}", method = RequestMethod.DELETE) ResponseEntity<?> deleteCertificate( @RequestHeader(value = "Authorization") String bearer, @ApiParam(value = "Id of company owning the certificate", required = true) @PathVariable Long companyID, @ApiParam(value = "Id of certificate.", required = true) @PathVariable Long certificateId) throws IOException { if (identityService.hasAnyRole(bearer, LEGAL_REPRESENTATIVE, PLATFORM_MANAGER) == false) return new ResponseEntity<>("Only legal representatives or platform managers are allowed to delete images", HttpStatus.FORBIDDEN); PartyType company = getCompanySecure(companyID, bearer); if (certificateRepository.exists(certificateId) == false) throw new ControllerUtils.DocumentNotFoundException("No certificate for Id found."); // delete binary content CertificateType certificate = certificateRepository.findOne(certificateId); String uri = certificate.getDocumentReference().get(0).getAttachment().getEmbeddedDocumentBinaryObject().getUri(); binaryContentService.deleteContentIdentity(uri); // delete certificate certificateRepository.delete(certificate); // update list of certificates Optional<CertificateType> toDelete = company.getCertificate().stream() .filter(c -> c.getHjid() != null) .filter(c -> c.getHjid().equals(certificateId)) .findFirst(); if (toDelete.isPresent()) { company.getCertificate().remove(toDelete.get()); partyRepository.save(company); } return ResponseEntity.ok().build(); } @ApiOperation(value = "Update negotiation settings") @RequestMapping(value = "/{companyID}/negotiation", method = RequestMethod.PUT) ResponseEntity<?> updateNegotiationSettings( @RequestHeader(value = "Authorization") String bearer, @ApiParam(value = "Id of company owning the certificate", required = true) @PathVariable Long companyID, @ApiParam(value = "Settings to update.", required = true) @RequestBody NegotiationSettings newSettings) throws IOException { if (identityService.hasAnyRole(bearer, LEGAL_REPRESENTATIVE, PLATFORM_MANAGER) == false) return new ResponseEntity<>("Only legal representatives or platform managers are allowed to update settings", HttpStatus.FORBIDDEN); PartyType company = getCompanySecure(companyID, bearer); // update settings NegotiationSettings existingSettings = findOrCreateNegotiationSettings(company); existingSettings.update(newSettings); existingSettings = negotiationSettingsRepository.save(existingSettings); logger.info("Updated negotiation settings {} for company {}", existingSettings.getId(), UblAdapter.adaptPartyIdentifier(company)); // //indexing the updated company in the indexing service // eu.nimble.service.model.solr.party.PartyType party = DataModelUtils.toIndexParty(company); // indexingClient.setParty(party); return ResponseEntity.ok().build(); } @ApiOperation(value = "Get negotiation settings", response = NegotiationSettings.class) @RequestMapping(value = "/{companyID}/negotiation/", method = RequestMethod.GET, produces = "application/json") ResponseEntity<?> getNegotiationSettings( @ApiParam(value = "Id of company to retrieve settings from.", required = true) @PathVariable Long companyID) { PartyType company = partyRepository.findByHjid(companyID).stream().findFirst().orElseThrow(ControllerUtils.CompanyNotFoundException::new); NegotiationSettings negotiationSettings = findOrCreateNegotiationSettings(company); try { String serializedNegotiationSettings = JsonSerializationUtility.getObjectMapper().writeValueAsString(negotiationSettings); logger.info("Fetched negotiation settings {} for company {}", negotiationSettings.getId(), UblAdapter.adaptPartyIdentifier(company)); return new ResponseEntity<>(serializedNegotiationSettings, HttpStatus.OK); } catch (JsonProcessingException e) { return createResponseEntityAndLog(String.format("Serialization error for negotiation settings: %s for company %s", negotiationSettings.getId(),UblAdapter.adaptPartyIdentifier(company)), e, HttpStatus.INTERNAL_SERVER_ERROR); } } @ApiOperation(value = "", notes = "Get profile completeness of company.", response = PartyType.class) @RequestMapping(value = "/{companyID}/completeness", produces = {"application/json"}, method = RequestMethod.GET) ResponseEntity<?> getProfileCompleteness( @ApiParam(value = "Id of party to retrieve profile completeness.", required = true) @PathVariable Long companyID ) { // search relevant parties PartyType company = partyRepository.findByHjid(companyID).stream().findFirst().orElseThrow(ControllerUtils.CompanyNotFoundException::new); QualifyingPartyType qualifyingParty = qualifyingPartyRepository.findByParty(company).stream().findFirst().orElse(null); NegotiationSettings negotiationSettings = negotiationSettingsRepository.findByCompany(company).stream().findFirst().orElse(null); CompanySettings companySettings = UblAdapter.adaptCompanySettings(company, qualifyingParty); // compute completeness factors Double detailsCompleteness = IdentityService.computeDetailsCompleteness(companySettings.getDetails()) * 3; Double descriptionCompleteness = IdentityService.computeDescriptionCompleteness(companySettings.getDescription()) * 2; Double deliveryAddressCompleteness = IdentityService.computeDeliveryAddressCompleteness(company) * 2; Double certificateCompleteness = IdentityService.computeCertificateCompleteness(company) * 1.5; Double tradeCompleteness = IdentityService.computeTradeCompleteness(negotiationSettings); Double nonMandatoryDataCompleteness = IdentityService.computeAdditionalDataCompleteness(company, companySettings.getTradeDetails(), companySettings.getDescription()) * 1.5; Double overallCompleteness = (detailsCompleteness + descriptionCompleteness + certificateCompleteness + deliveryAddressCompleteness+ nonMandatoryDataCompleteness) / 10.0; List<QualityIndicatorType> qualityIndicators = new ArrayList<>(); qualityIndicators.add(UblAdapter.adaptQualityIndicator(PROFILE_COMPLETENESS, overallCompleteness)); qualityIndicators.add(UblAdapter.adaptQualityIndicator(COMPLETENESS_OF_COMPANY_GENERAL_DETAILS, detailsCompleteness)); qualityIndicators.add(UblAdapter.adaptQualityIndicator(COMPLETENESS_OF_COMPANY_DESCRIPTION, descriptionCompleteness)); qualityIndicators.add(UblAdapter.adaptQualityIndicator(COMPLETENESS_OF_COMPANY_CERTIFICATE_DETAILS, certificateCompleteness)); qualityIndicators.add(UblAdapter.adaptQualityIndicator(COMPLETENESS_OF_COMPANY_TRADE_DETAILS, tradeCompleteness)); PartyType completenessParty = new PartyType(); completenessParty.setQualityIndicator(qualityIndicators); UblUtils.setID(completenessParty, UblAdapter.adaptPartyIdentifier(company)); logger.debug("Returning completeness of party with Id {0}", company.getHjid()); return new ResponseEntity<>(completenessParty, HttpStatus.OK); } private NegotiationSettings findOrCreateNegotiationSettings(PartyType company) { NegotiationSettings negotiationSettings = negotiationSettingsRepository.findByCompany(company).stream().findFirst().orElse(null); if (negotiationSettings == null) { negotiationSettings = new NegotiationSettings(); negotiationSettings.setCompany(company); negotiationSettings = negotiationSettingsRepository.save(negotiationSettings); } return negotiationSettings; } private PartyType getCompanySecure(Long companyID, String bearer) throws IOException { PartyType company = partyRepository.findByHjid(companyID).stream().findFirst().orElseThrow(ControllerUtils.CompanyNotFoundException::new); UaaUser user = identityService.getUserfromBearer(bearer); PartyType companyFromBearer = identityService.getCompanyOfUser(user).orElseThrow(ControllerUtils.CompanyNotFoundException::new); if( identityService.hasAnyRole(bearer, PLATFORM_MANAGER) == false && companyFromBearer.getHjid().equals(companyID) == false) throw new ControllerUtils.UnauthorisedAccess(); return company; } @RequestMapping(value = "/vat/{vat}", produces = {"application/json"}, method = RequestMethod.GET) ResponseEntity<?> getVatInfo(@PathVariable String vat) throws UnirestException { logger.debug("Querying VAT info for " + vat); HttpResponse<JsonNode> response = Unirest.get("https://taxapi.io/api/v1/vat?vat_number=" + vat).asJson(); return new ResponseEntity<>(response.getBody().toString(), HttpStatus.OK); } /** * admin endpoint to reindex all valid parties in indexing service (for platform manager/admin purposes only) * @return 200 OK * @throws UnirestException */ @RequestMapping(value = "/reindexParties", produces = {"application/json"}, method = RequestMethod.GET) ResponseEntity<?> reindexAllCompanies(@RequestHeader(value = "Authorization") String bearer) throws IOException{ if (identityService.hasAnyRole(bearer, PLATFORM_MANAGER) == false) return new ResponseEntity<>("Only platform managers are allowed to reindex all companies", HttpStatus.FORBIDDEN); logger.debug("indexing all companies. "); //adding verified and unverified companies with valid userRoles List<PartyType> verifiedCompanies = adminService.queryCompanies(AdminService.CompanyState.VERIFIED); List<PartyType> unVerifiedCompanies = adminService.queryCompanies(AdminService.CompanyState.UNVERIFIED); for (PartyType party : verifiedCompanies) { Optional<QualifyingPartyType> qualifyingPartyTypeOptional = qualifyingPartyRepository.findByParty(party).stream().findFirst(); if(qualifyingPartyTypeOptional.isPresent()){ QualifyingPartyType qualifyingPartyType = qualifyingPartyTypeOptional.get(); eu.nimble.service.model.solr.party.PartyType newParty = DataModelUtils.toIndexParty(party,qualifyingPartyType); newParty.setVerified(true); logger.info("Indexing verified party from database to index : " + newParty.getId() + " legalName : " + newParty.getLegalName()); List<IndexingClient> indexingClients = indexingController.getClients(); for(IndexingClient indexingClient : indexingClients) { indexingClient.setParty(newParty,bearer); } } } for (PartyType party : unVerifiedCompanies) { Optional<QualifyingPartyType> qualifyingPartyTypeOptional = qualifyingPartyRepository.findByParty(party).stream().findFirst(); if(qualifyingPartyTypeOptional.isPresent()){ QualifyingPartyType qualifyingPartyType = qualifyingPartyTypeOptional.get(); eu.nimble.service.model.solr.party.PartyType newParty = DataModelUtils.toIndexParty(party,qualifyingPartyType); logger.info("Indexing unverified party from database to index : " + newParty.getId() + " legalName : " + newParty.getLegalName()); List<IndexingClient> indexingClients = indexingController.getClients(); for (IndexingClient indexingClient : indexingClients) { indexingClient.setParty(newParty, bearer); } } } return new ResponseEntity<>("Completed indexing all companies", HttpStatus.OK); } private void enrichImageMetadata(PartyType party) { // fetch only identifiers of images in order to avoid fetch of entire binary files List<DocumentReferenceType> imageDocuments = party.getDocumentReference().stream() .filter(d -> DOCUMENT_TYPE_COMPANY_LOGO.equals(d.getDocumentType()) || DOCUMENT_TYPE_COMPANY_PHOTO.equals(d.getDocumentType())) .collect(Collectors.toList()); party.getDocumentReference().removeAll(imageDocuments); List<DocumentReferenceType> logos = partyRepository.findDocumentIds(party.getHjid(), DOCUMENT_TYPE_COMPANY_LOGO).stream() .map(id -> shallowDocumentReference(id, DOCUMENT_TYPE_COMPANY_LOGO)) .collect(Collectors.toList()); party.getDocumentReference().addAll(logos); List<DocumentReferenceType> images = partyRepository.findDocumentIds(party.getHjid(), DOCUMENT_TYPE_COMPANY_PHOTO).stream() .map(id -> shallowDocumentReference(id, DOCUMENT_TYPE_COMPANY_PHOTO)) .collect(Collectors.toList()); party.getDocumentReference().addAll(images); } private static DocumentReferenceType shallowDocumentReference(BigInteger identifier, String documentType) { DocumentReferenceType documentReference = new DocumentReferenceType(); documentReference.setID(identifier.toString()); documentReference.setHjid(identifier.longValue()); documentReference.setDocumentType(documentType); return documentReference; } }
package com.mutinycraft.irc.impl; import org.bukkit.entity.Player; import org.bukkit.event.*; import org.bukkit.event.player.*; import com.massivecraft.factions.P; import com.mutinycraft.irc.*; import com.mutinycraft.irc.plugin.Plugin; public class DefaultChatHandler extends IRCListener implements Listener { public DefaultChatHandler(IRC irc, Plugin plugin) { super(irc, plugin); } @Override public void onMessage(String sender, String channel, String message) { if(!getIRC().getGameRelay("msg")) return; String pcmd = message.substring( getIRC().getCommandPrefix().length()).toLowerCase(); if(pcmd.startsWith("list") || pcmd.startsWith("who") || pcmd.startsWith("players")) return; String msg = getIRC().getGameMessage("msg") .replace("%user%", sender) .replace("%channel%", channel) .replace("%msg%", getIRC().toGameColor(message)); getIRC().sendGameMessage(msg); } @Override public void onAction(String sender, String recipient, String action) { if(!getIRC().getGameRelay("me")) return; String msg = getIRC().getGameMessage("me") .replace("%user%", sender) .replace("%channel%", recipient) .replace("%action%", getIRC().toGameColor(action.trim())); getIRC().sendGameMessage(msg); } @Override public void onNick(String oldNick, String newNick) { if(!getIRC().getGameRelay("nick")) return; String msg = getIRC().getGameMessage("nick") .replace("%oldnick%", oldNick) .replace("%newnick%", newNick); getIRC().sendGameMessage(msg); } @Override public void onKick(String channel, String user, String kicker) { if(!getIRC().getGameRelay("kick")) return; String msg = getIRC().getGameMessage("kick") .replace("%user%", user) .replace("%kicker%", kicker) .replace("%channel%", channel); getIRC().sendGameMessage(msg); } @Override public void onJoin(String user, String login, String host, String channel) { if(!getIRC().getGameRelay("join") || user.equalsIgnoreCase(getIRC().getNick())) return; String msg = getIRC().getGameMessage("join") .replace("%user%", user) .replace("%channel%", channel); getIRC().sendGameMessage(msg); } @Override public void onPart(String user, String channel) { if(!getIRC().getGameRelay("part") || user.equalsIgnoreCase(getIRC().getNick())) return; String msg = getIRC().getGameMessage("part") .replace("%user%", user) .replace("%channel%", channel); getIRC().sendGameMessage(msg); } @Override public void onQuit(String user, String reason) { onPart(user, ""); } @Override public void onModeChanged(String channel, String user, String modes) { if(!getIRC().getGameRelay("modes") || !getIRC().isChannel(channel)) return; String msg = getIRC().getGameMessage("modes") .replace("%user%", user) .replace("%channel%", channel) .replace("%mode%", modes); getIRC().sendGameMessage(msg); } @EventHandler public void onGameMessage(AsyncPlayerChatEvent event) { if(!getIRC().getIrcRelay("msg") || event.isCancelled()) return; Player p = event.getPlayer(); if(getPlugin().isFactionsEnabled() && P.p.isPlayerFactionChatting(p)) return; String message = event.getMessage(); getIRC().sendIrcMessage(p, message); } @EventHandler public void onGameMe(PlayerCommandPreprocessEvent event) { if(!getIRC().getIrcRelay("me")) return; if(getPlugin().isFactionsEnabled() && P.p.isPlayerFactionChatting(event.getPlayer())) return; String cmd = event.getMessage().trim(); String[] split = cmd.split(" "); if(split.length > 1 && (split[0].equalsIgnoreCase("/me") || split[0].equalsIgnoreCase("/mchatme"))) { String m = getIRC().formatGameMessage(event.getPlayer(), "me"); String message = cmd.substring(cmd.indexOf(" ") + 1); String p = m.replace("%action%", message); getIRC().sendIrcMessage(p); } } @EventHandler public void onGameJoin(PlayerJoinEvent event) { if(!getIRC().getIrcRelay("join")) return; String msg = getIRC().formatGameMessage(event.getPlayer(), "join"); getIRC().sendIrcMessage(msg); } @EventHandler public void onGameQuit(PlayerQuitEvent event) { if(!getIRC().getIrcRelay("part")) return; String msg = getIRC().formatGameMessage(event.getPlayer(), "part"); getIRC().sendIrcMessage(msg); } @EventHandler public void onPlayerKick(PlayerKickEvent event) { if(!getIRC().getIrcRelay("kick")) return; String reason = "No reason"; if(event.getReason() != null) reason = event.getReason().replaceAll("(\r|\n)", " "); String msg = getIRC().formatGameMessage(event.getPlayer(), "kick"); getIRC().sendIrcMessage(msg.replace("%reason%", reason)); } }
package org.jboss.forge.addon.javaee.rest.ui; import java.util.Arrays; import java.util.List; import javax.inject.Inject; import javax.ws.rs.HttpMethod; import javax.ws.rs.container.ContainerRequestContext; import javax.ws.rs.container.ContainerResponseContext; import javax.ws.rs.container.ContainerResponseFilter; import javax.ws.rs.ext.Provider; import org.jboss.forge.addon.javaee.rest.RestFacet; import org.jboss.forge.addon.parser.java.facets.JavaSourceFacet; import org.jboss.forge.addon.parser.java.ui.AbstractJavaSourceCommand; import org.jboss.forge.addon.projects.Project; import org.jboss.forge.addon.ui.command.PrerequisiteCommandsProvider; import org.jboss.forge.addon.ui.context.UIBuilder; import org.jboss.forge.addon.ui.context.UIContext; import org.jboss.forge.addon.ui.context.UIExecutionContext; import org.jboss.forge.addon.ui.input.UIInput; import org.jboss.forge.addon.ui.input.UIInputMany; import org.jboss.forge.addon.ui.input.UISelectMany; import org.jboss.forge.addon.ui.metadata.UICommandMetadata; import org.jboss.forge.addon.ui.metadata.WithAttributes; import org.jboss.forge.addon.ui.result.NavigationResult; import org.jboss.forge.addon.ui.result.navigation.NavigationResultBuilder; import org.jboss.forge.addon.ui.util.Categories; import org.jboss.forge.addon.ui.util.Metadata; import org.jboss.forge.furnace.util.Lists; import org.jboss.forge.furnace.util.OperatingSystemUtils; import org.jboss.forge.furnace.util.Strings; import org.jboss.forge.roaster.model.source.JavaClassSource; import org.jboss.forge.roaster.model.source.MethodSource; public class CrossOriginResourceSharingFilterCommand extends AbstractJavaSourceCommand<JavaClassSource> implements PrerequisiteCommandsProvider { @Inject @WithAttributes(label = "Access-Control-Allow-Origin", defaultValue = "*", description = "The Access-Control-Allow-Origin header indicates whether a resource can be shared based by returning the value of the Origin request header, \"*\", or \"null\" in the response") private UIInput<String> accessControlAllowOrigin; @Inject @WithAttributes(label = "Access-Control-Allow-Methods", description = "The Access-Control-Allow-Methods header indicates, as part of the response to a preflight request, which methods can be used during the actual request.") private UISelectMany<String> accessControlAllowMethods; @Inject @WithAttributes(label = "Access-Control-Allow-Headers", description = "The Access-Control-Allow-Headers header indicates, as part of the response to a preflight request, which header field names can be used during the actual request") private UIInputMany<String> accessControlAllowHeaders; @Inject @WithAttributes(label = "Access-Control-Allow-Credentials", defaultValue = "true", description = "The Access-Control-Allow-Credentials header indicates whether the response to request can be exposed when the omit credentials flag is unset. When part of the response to a preflight request it indicates that the actual request can include user credentials.") private UIInput<Boolean> accessControlAllowCredentials; // @Inject // @WithAttributes(label = "Access-Control-Expose-Headers", description = // "The Access-Control-Expose-Headers header indicates which headers are safe to expose to the API of a CORS API specification.") // private UIInputMany<String> accessControlExposeHeaders; // @Inject // @WithAttributes(label = "Access-Control-Max-Age", defaultValue = "151200", description = // "The Access-Control-Max-Age header indicates how long the results of a preflight request can be cached in a preflight result cache.") // private UIInput<Integer> accessControlMaxAge; // @Inject // @WithAttributes(label = "Origin", description = // "The Origin header indicates where the cross-origin request or preflight request originates from.") // private UIInput<String> origin; // @Inject // @WithAttributes(label = "Access-Control-Request-Method", description = // "The Access-Control-Request-Method header indicates which method will be used in the actual request as part of the preflight request") // private UIInput<String> accessControlRequestMethod; // @Inject // @WithAttributes(label = "Access-Control-Request-Headers", description = // "The Access-Control-Request-Headers header indicates which headers will be used in the actual request as part of the preflight request") // private UIInputMany<String> accessControlRequestHeaders; @Override public void initializeUI(UIBuilder builder) throws Exception { super.initializeUI(builder); getNamed().setDefaultValue("NewCrossOriginResourceSharingFilter"); accessControlAllowHeaders.setValue(Arrays.asList("Content-Type", "User-Agent", "X-Requested-With", "X-Requested-By", "Cache-Control")); accessControlAllowMethods.setValueChoices(Arrays.asList(HttpMethod.GET, HttpMethod.POST, HttpMethod.PUT, HttpMethod.DELETE, HttpMethod.HEAD, HttpMethod.OPTIONS)); accessControlAllowMethods.setValue(Arrays.asList(HttpMethod.GET, HttpMethod.POST, HttpMethod.PUT, HttpMethod.DELETE)); builder.add(accessControlAllowMethods).add(accessControlAllowHeaders) .add(accessControlAllowOrigin).add(accessControlAllowCredentials); } @Override public UICommandMetadata getMetadata(UIContext context) { return Metadata.from(super.getMetadata(context), getClass()).name("REST: New " + getType()) .description("Generate a " + getType()) .category(Categories.create("Java EE", "JAX-RS")); } @Override protected String getType() { return "Cross Origin Resource Sharing Filter"; } @Override protected Class<JavaClassSource> getSourceType() { return JavaClassSource.class; } @Override protected String calculateDefaultPackage(UIContext context) { Project project = getSelectedProject(context); return project.getFacet(JavaSourceFacet.class).getBasePackage() + ".rest"; } @Override public JavaClassSource decorateSource(UIExecutionContext context, Project project, JavaClassSource source) throws Exception { source.addAnnotation(Provider.class); source.addInterface(ContainerResponseFilter.class); MethodSource<JavaClassSource> method = source.addMethod().setName("filter").setPublic().setReturnTypeVoid(); method.addAnnotation(Override.class); // FIXME java.lang.Override shouldn't be imported source.removeImport(Override.class); method.addParameter(ContainerRequestContext.class, "request"); method.addParameter(ContainerResponseContext.class, "response"); StringBuilder body = new StringBuilder(); { body.append("response.getHeaders().putSingle(\"Access-Control-Allow-Origin\",\"").append( accessControlAllowOrigin.getValue()).append("\");"); } body.append(OperatingSystemUtils.getLineSeparator()); { body.append("response.getHeaders().putSingle(\"Access-Control-Allow-Methods\",\""); List<String> list = Lists.toList(accessControlAllowMethods.getValue()); body.append(Strings.join(list.toArray(), ", ")); body.append("\");"); } body.append(OperatingSystemUtils.getLineSeparator()); { body.append("response.getHeaders().putSingle(\"Access-Control-Allow-Headers\",\""); List<String> list = Lists.toList(accessControlAllowHeaders.getValue()); body.append(Strings.join(list.toArray(), ", ")); body.append("\");"); } if (accessControlAllowCredentials.getValue()) { body.append("response.getHeaders().putSingle(\"Access-Control-Allow-Credentials\",\"true\");"); } method.setBody(body.toString()); return source; } @Override public NavigationResult getPrerequisiteCommands(UIContext context) { NavigationResultBuilder builder = NavigationResultBuilder.create(); Project project = getSelectedProject(context); if (!project.hasFacet(RestFacet.class)) { builder.add(RestSetupWizard.class); } return builder.build(); } }
package com.axiastudio.zoefx.core.db; import java.util.Map; public interface Database { void open(String persistenceUnit); void open(String persistenceUnit, Map<String, String> properties); public <E> Manager<E> createManager(Class<E> klass); }
package com.atlassian.jira.plugins.dvcs.spi.gitlab; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.EnumSet; import java.util.List; import java.util.Set; import javax.annotation.Resource; import org.apache.commons.lang.StringUtils; import org.gitlab.api.GitlabAPI; import org.gitlab.api.models.GitlabBranch; import org.gitlab.api.models.GitlabBranchCommit; import org.gitlab.api.models.GitlabCommit; import org.gitlab.api.models.GitlabCommitDiff; import org.gitlab.api.models.GitlabProject; import org.gitlab.api.models.GitlabProjectHook; import org.gitlab.api.models.GitlabUser; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.atlassian.jira.plugins.dvcs.model.AccountInfo; import com.atlassian.jira.plugins.dvcs.model.Branch; import com.atlassian.jira.plugins.dvcs.model.BranchHead; import com.atlassian.jira.plugins.dvcs.model.Changeset; import com.atlassian.jira.plugins.dvcs.model.ChangesetFile; import com.atlassian.jira.plugins.dvcs.model.ChangesetFileAction; import com.atlassian.jira.plugins.dvcs.model.ChangesetFileDetail; import com.atlassian.jira.plugins.dvcs.model.ChangesetFileDetailsEnvelope; import com.atlassian.jira.plugins.dvcs.model.DvcsUser; import com.atlassian.jira.plugins.dvcs.model.Group; import com.atlassian.jira.plugins.dvcs.model.Organization; import com.atlassian.jira.plugins.dvcs.model.Repository; import com.atlassian.jira.plugins.dvcs.service.BranchService; import com.atlassian.jira.plugins.dvcs.service.message.MessageAddress; import com.atlassian.jira.plugins.dvcs.service.message.MessagingService; import com.atlassian.jira.plugins.dvcs.service.remote.DvcsCommunicator; import com.atlassian.jira.plugins.dvcs.spi.gitlab.message.SynchronizeChangesetMessage; import com.atlassian.jira.plugins.dvcs.sync.GitlabSynchronizeChangesetMessageConsumer; import com.atlassian.jira.plugins.dvcs.sync.SynchronizationFlag; import com.google.common.base.Function; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Maps; public class GitlabCommunicator implements DvcsCommunicator { public static final String GITLAB = "gitlab"; private static final Logger LOG = LoggerFactory.getLogger(GitlabCommunicator.class); @Resource private MessagingService messagingService; @Resource private BranchService branchService; @Override public void ensureHookPresent(Repository repository, String postCommitUrl) { LOG.info("ensureHookPresent: repo={}, postCommitUrl={}", repository, postCommitUrl); GitlabAPI gitlabAPI = GitlabAPI.connect(repository.getOrgHostUrl(), repository.getCredential().getAccessToken()); try { GitlabProject project = gitlabAPI.getProject(getGitlabProjectId(repository)); List<GitlabProjectHook> projectHooks = gitlabAPI.getProjectHooks(project); for (GitlabProjectHook hook : projectHooks) { if (hook.getUrl().equals(postCommitUrl)) { LOG.info("Hook is already present"); return; } } gitlabAPI.addProjectHook(project, postCommitUrl); } catch (NumberFormatException e) { LOG.error("Problem with ensureHookPresent", e); } catch (IOException e) { LOG.error("Problem with ensureHookPresent", e); } } @Override public AccountInfo getAccountInfo(String hostUrl, String accountName) { LOG.info("getAccountInfo: url={}, name={}", hostUrl, accountName); // TODO Really verify that user exists return new AccountInfo(GITLAB); } @Override public String getBranchUrl(Repository repository, Branch branch) { LOG.info("getBranchUrl: repo={}, branch={}", repository, branch); // TODO Auto-generated method stub return null; } @Override public List<Branch> getBranches(Repository repository) { LOG.info("getBranches: repo={}", repository); List<Branch> branches = new ArrayList<Branch>(); GitlabAPI gitlabAPI = GitlabAPI.connect(repository.getOrgHostUrl(), repository.getCredential().getAccessToken()); try { GitlabProject project = gitlabAPI.getProject(getGitlabProjectId(repository)); List<GitlabBranch> glBranches = gitlabAPI.getBranches(project); for (GitlabBranch glBranch : glBranches) { List<BranchHead> branchHeads = new ArrayList<BranchHead>(); BranchHead branchTip = new BranchHead(glBranch.getName(), glBranch.getCommit().getId()); branchHeads.add(branchTip); Branch branch = new Branch(glBranch.getName()); branch.setHeads(branchHeads); branch.setRepositoryId(repository.getId()); branches.add(branch); } } catch (NumberFormatException e) { LOG.error("Problem while getBranches", e); } catch (IOException e) { LOG.error("Problem while getBranches", e); } return branches; } @Override public Changeset getChangeset(Repository repository, String node) { LOG.info("getChangeset: repo={}, node={}", repository, node); GitlabAPI gitlabAPI = GitlabAPI.connect(repository.getOrgHostUrl(), repository.getCredential().getAccessToken()); try { GitlabCommit commit = gitlabAPI.getCommit(getGitlabProjectId(repository), node); LOG.info("commit title={} description={}", commit.getTitle(), commit.getDescription()); Changeset changeset = new Changeset(repository.getId(), commit.getId(), commit.getTitle(), commit.getCreatedAt()); changeset.setAuthor(commit.getAuthorName()); changeset.setAuthorEmail(commit.getAuthorEmail()); changeset.setParents(commit.getParentIds()); List<ChangesetFile> files = new ArrayList<ChangesetFile>(); List<ChangesetFileDetail> fileDetails = new ArrayList<ChangesetFileDetail>(); List<GitlabCommitDiff> commitDiffs = gitlabAPI.getCommitDiffs(getGitlabProjectId(repository), commit.getId()); for (GitlabCommitDiff commitDiff : commitDiffs) { if (commitDiff.getNewFile()) { files.add(new ChangesetFile(ChangesetFileAction.ADDED, commitDiff.getNewPath())); fileDetails.add(new ChangesetFileDetail(ChangesetFileAction.ADDED, commitDiff.getNewPath(), 1, 1)); } else if (commitDiff.getDeletedFile()) { files.add(new ChangesetFile(ChangesetFileAction.REMOVED, commitDiff.getOldPath())); fileDetails.add(new ChangesetFileDetail(ChangesetFileAction.REMOVED, commitDiff.getOldPath(), 1, 1)); } else if (commitDiff.getRenamedFile()) { files.add(new ChangesetFile(ChangesetFileAction.REMOVED, commitDiff.getOldPath())); fileDetails.add(new ChangesetFileDetail(ChangesetFileAction.REMOVED, commitDiff.getOldPath(), 1, 1)); files.add(new ChangesetFile(ChangesetFileAction.ADDED, commitDiff.getNewPath())); fileDetails.add(new ChangesetFileDetail(ChangesetFileAction.ADDED, commitDiff.getNewPath(), 1, 1)); } else { int additions = StringUtils.countMatches(commitDiff.getDiff(), "\n+") - StringUtils.countMatches(commitDiff.getDiff(), "\n+++"); int deletions = StringUtils.countMatches(commitDiff.getDiff(), "\n-") - StringUtils.countMatches(commitDiff.getDiff(), "\n files.add(new ChangesetFile(ChangesetFileAction.MODIFIED, commitDiff.getNewPath())); fileDetails.add(new ChangesetFileDetail(ChangesetFileAction.MODIFIED, commitDiff.getNewPath(), additions, deletions)); } } changeset.setFiles(files); changeset.setFileDetails(fileDetails); changeset.setAllFileCount(files.size()); return changeset; } catch (IOException e) { LOG.error("Problem while getChangeset", e); } return null; } private String getGitlabProjectId(Repository repository) { return repository.getOrgName() + "/" + repository.getSlug(); } @Override public String getCommitUrl(Repository repository, Changeset changeset) { LOG.info("getCommitUrl: repo={}, changeset={}", repository, changeset); return repository.getRepositoryUrl() + "/commit/" + changeset.getNode(); } @Override public String getCreatePullRequestUrl(Repository repository, String sourceSlug, final String sourceBranch, String destinationSlug, final String destinationBranch, String eventSource) { LOG.info("getCreatePullRequestUrl: repo={}, sourceSlug={}, sourceBranch={}, destinationSlug={}, destinationBranch={}, eventSource={}", new Object[] { repository, sourceSlug, sourceBranch, destinationSlug, destinationBranch, eventSource}); // TODO Auto-generated method stub return null; } @Override public String getDvcsType() { return GITLAB; } @Override public String getFileCommitUrl(Repository repository, Changeset changeset, String file, int index) { LOG.info("getFileCommitUrl: repo={}, changeset={}, file={}, index={}", new Object[] { repository, changeset, file, index }); return repository.getRepositoryUrl() + "/commit/" + changeset.getNode() + "#diff-" + index; } @Override public ChangesetFileDetailsEnvelope getFileDetails(Repository repository, Changeset changeset) { LOG.info("getFileDetails: repo={}, changeset={}", repository, changeset); // TODO Auto-generated method stub return null; } @Override public List<Group> getGroupsForOrganization(Organization organization) { LOG.info("getGroupsForOrganization: organization={}"); // TODO Auto-generated method stub return null; } @Override public List<Repository> getRepositories(Organization organization, List<Repository> storedRepositories) { LOG.info("getRepositories: organization={}, storedRepositories={}", organization, storedRepositories); ImmutableMap<String, Repository> storedReposMap = Maps.uniqueIndex(storedRepositories, new Function<Repository, String>() { @Override public String apply(Repository r) { return r.getSlug(); } }); GitlabAPI gitlabAPI = GitlabAPI.connect(organization.getHostUrl(), organization.getCredential().getAccessToken()); try { List<GitlabProject> projects = gitlabAPI.getProjects(); List<Repository> repos = new ArrayList<Repository>(); for (GitlabProject gitlabProject : projects) { if (gitlabProject.getNamespace().getPath().equals(organization.getName())) { if (storedReposMap.containsKey(gitlabProject.getName())) { // Repo was already stored repos.add(storedReposMap.get(gitlabProject.getName())); } else { // Repo is new Repository repo = new Repository(); repo.setSlug(gitlabProject.getName()); repo.setName(gitlabProject.getName()); repos.add(repo); } } } return repos; } catch (IOException e) { LOG.error("Communication with GitLab failed", e); } return null; } @Override public DvcsUser getTokenOwner(Organization organization) { LOG.info("getTokenOwner: organization={}", organization); // TODO Auto-generated method stub return null; } @Override public DvcsUser getUser(Repository repository, String author) { LOG.info("getUser: repo={}, author={}", repository, author); GitlabAPI gitlabAPI = GitlabAPI.connect(repository.getOrgHostUrl(), repository.getCredential().getAccessToken()); try { List<GitlabUser> users = gitlabAPI.getUsers(); for (GitlabUser user : users) { if (author.equals(user.getName())) { String userUrl = repository.getOrgHostUrl() + "/u/" + user.getUsername(); DvcsUser dvcsUser = new DvcsUser(user.getUsername(), user.getName(), user.getName(), user.getAvatarUrl(), userUrl); return dvcsUser; } } } catch (IOException e) { LOG.error("Problem while getUser", e); } return null; } @Override public boolean isSyncDisabled(Repository repo, EnumSet<SynchronizationFlag> flags) { LOG.info("isSyncDisabled: repo={}, flags={}", repo, flags); // Never disable sync automatically return false; } @Override public void linkRepository(Repository repository, Set<String> withProjectkeys) { LOG.info("linkRepository: repo={}, withProjectKeys={}", repository, withProjectkeys); // Do nothing } @Override public void linkRepositoryIncremental(Repository repository, Set<String> withPossibleNewProjectkeys) { LOG.info("linkRepositoryIncremental: repo={}, withPossibleNewProjectKeys={}", repository, withPossibleNewProjectkeys); // Do nothing } @Override public void removePostcommitHook(Repository repository, String postCommitUrl) { LOG.info("removePostcommitHook: repo={}, postCommitUrl={}", repository, postCommitUrl); GitlabAPI gitlabAPI = GitlabAPI.connect(repository.getOrgHostUrl(), repository.getCredential().getAccessToken()); try { GitlabProject project = gitlabAPI.getProject(getGitlabProjectId(repository)); List<GitlabProjectHook> projectHooks = gitlabAPI.getProjectHooks(project); for (GitlabProjectHook hook : projectHooks) { if (hook.getUrl().equals(postCommitUrl)) { gitlabAPI.deleteProjectHook(project, hook.getId()); return; } } } catch (NumberFormatException e) { LOG.error("Problem with ensureHookPresent", e); } catch (IOException e) { LOG.error("Problem with ensureHookPresent", e); } } @Override public void startSynchronisation(Repository repo, EnumSet<SynchronizationFlag> flags, int auditId) { LOG.info("startSynchronisation: repo={}, flags={}, auditId={}", new Object[] { repo, flags, auditId }); final boolean softSync = flags.contains(SynchronizationFlag.SOFT_SYNC); final boolean webHookSync = flags.contains(SynchronizationFlag.WEBHOOK_SYNC); final boolean changestesSync = flags.contains(SynchronizationFlag.SYNC_CHANGESETS); final boolean pullRequestSync = flags.contains(SynchronizationFlag.SYNC_PULL_REQUESTS); String[] synchronizationTags = new String[] { messagingService.getTagForSynchronization(repo), messagingService.getTagForAuditSynchronization(auditId) }; if (changestesSync || softSync) { Date synchronizationStartedAt = new Date(); List<Branch> branches = getBranches(repo); for (Branch branch : branches) { for (BranchHead branchHead : branch.getHeads()) { SynchronizeChangesetMessage message = new SynchronizeChangesetMessage(repo, branch.getName(), branchHead.getHead(), synchronizationStartedAt, null, softSync, auditId, webHookSync); MessageAddress<SynchronizeChangesetMessage> key = messagingService.get( SynchronizeChangesetMessage.class, GitlabSynchronizeChangesetMessageConsumer.ADDRESS ); messagingService.publish(key, message, softSync ? MessagingService.SOFTSYNC_PRIORITY : MessagingService.DEFAULT_PRIORITY, messagingService.getTagForSynchronization(repo), messagingService.getTagForAuditSynchronization(auditId)); } } List<BranchHead> oldBranchHeads = branchService.getListOfBranchHeads(repo); branchService.updateBranchHeads(repo, branches, oldBranchHeads); branchService.updateBranches(repo, branches); } if (pullRequestSync) { LOG.info("Pull request sync not implemented yet"); /* GitlabPullRequestPageMessage message = new GitlabPullRequestPageMessage(null, auditId, softSync, repo, PagedRequest.PAGE_FIRST, PULLREQUEST_PAGE_SIZE, null, webHookSync); MessageAddress<GitlabPullRequestPageMessage> key = messagingService.get( GitlabPullRequestPageMessage.class, GitlabPullRequestPageMessageConsumer.ADDRESS ); messagingService.publish(key, message, messagingService.getTagForSynchronization(repo), messagingService.getTagForAuditSynchronization(auditId)); */ } } @Override public boolean supportsInvitation(Organization organization) { LOG.info("supportsInvitation: organization={}", organization); // No invitation support return false; } @Override public void inviteUser(Organization organization, Collection<String> groupSlugs, String userEmail) { LOG.info("inviteUser: organization={}, groupSlugs={}, userEmail={}", new Object[] { organization, groupSlugs, userEmail }); // No invitation support } }
package com.googlecode.kanbanik.client.modules.editworkflow; import java.util.ArrayList; import java.util.List; import com.google.gwt.user.client.ui.HorizontalPanel; import com.googlecode.kanbanik.client.KanbanikAsyncCallback; import com.googlecode.kanbanik.client.KanbanikServerCaller; import com.googlecode.kanbanik.client.ServerCommandInvokerManager; import com.googlecode.kanbanik.client.modules.KanbanikModule; import com.googlecode.kanbanik.client.modules.editworkflow.boards.BoardsBox; import com.googlecode.kanbanik.client.modules.editworkflow.workflow.WorkflowEditingComponent; import com.googlecode.kanbanik.dto.BoardDto; import com.googlecode.kanbanik.dto.BoardWithProjectsDto; import com.googlecode.kanbanik.dto.ListDto; import com.googlecode.kanbanik.dto.ProjectDto; import com.googlecode.kanbanik.dto.shell.SimpleParams; import com.googlecode.kanbanik.dto.shell.VoidParams; import com.googlecode.kanbanik.shared.ServerCommand; public class ConfigureWorkflowModule extends HorizontalPanel implements KanbanikModule { private BoardsBox boardsBox = new BoardsBox(this); private WorkflowEditingComponent workflowEditingComponent = new WorkflowEditingComponent();; public ConfigureWorkflowModule() { setStyleName("edit-workflow-module"); } public void initialize(final ModuleInitializeCallback initializedCallback) { add(boardsBox); new KanbanikServerCaller( new Runnable() { public void run() { ServerCommandInvokerManager.getInvoker().<VoidParams, SimpleParams<ListDto<BoardWithProjectsDto>>> invokeCommand( ServerCommand.GET_ALL_BOARDS_WITH_PROJECTS, new VoidParams(), new KanbanikAsyncCallback<SimpleParams<ListDto<BoardWithProjectsDto>>>() { @Override public void success(SimpleParams<ListDto<BoardWithProjectsDto>> result) { List<BoardWithProjectsDto> boards = result.getPayload().getList(); boardsBox.setBoards(boards); if (boards != null && boards.size() > 0) { selectedBoardChanged(result.getPayload().getList().iterator().next()); } initializedCallback.initialized(ConfigureWorkflowModule.this); } }); }}); setVisible(true); } public void selectedBoardChanged(final BoardWithProjectsDto selectedDto) { if (selectedDto == null) { // this means that no board is changed - e.g. the last one has been deleted removeEverithing(); return; } editBoard(selectedDto); } private void editBoard(final BoardWithProjectsDto boardWithProjects) { // well, this is a hack. It should listen to ProjectAddedMessage and update the projects. new KanbanikServerCaller( new Runnable() { public void run() { ServerCommandInvokerManager.getInvoker().<VoidParams, SimpleParams<ListDto<ProjectDto>>> invokeCommand( ServerCommand.GET_ALL_PROJECTS, new VoidParams(), new KanbanikAsyncCallback<SimpleParams<ListDto<ProjectDto>>>() { @Override public void success(SimpleParams<ListDto<ProjectDto>> result) { refreshProjectsOnBoard(boardWithProjects, result); removeEverithing(); workflowEditingComponent.initialize(boardWithProjects); add(workflowEditingComponent); boardsBox.editBoard(boardWithProjects, result.getPayload().getList()); } private void refreshProjectsOnBoard( final BoardWithProjectsDto boardWithProjects, SimpleParams<ListDto<ProjectDto>> result) { String boardId = boardWithProjects.getBoard().getId(); List<ProjectDto> projectsOnBoard = new ArrayList<ProjectDto>(); for (ProjectDto projectDto : result.getPayload().getList()) { for (BoardDto boardDto : projectDto.getBoards()) { if (boardDto.getId().equals(boardId)) { projectsOnBoard.add(projectDto); break; } } } boardWithProjects.setProjects(projectsOnBoard); } }); }}); } private void removeEverithing() { if (workflowEditingComponent != null) { remove(workflowEditingComponent); } } }
package com.onlinephotosubmission.csv_importer; import javax.net.ssl.HttpsURLConnection; import java.io.*; import java.net.HttpURLConnection; import java.net.URL; import java.nio.file.Files; import java.nio.file.Paths; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.List; import java.util.Properties; public class Main { public static String[] headerTypes = {"Email", "ID", "Campus", "Notes"}; private static String delimiter = ","; public static void main(String[] args) throws Exception { Properties properties = new Properties(); properties.load(new FileInputStream("config.properties")); File[] inputFiles = getCSVFilesFromDirectory(properties.getProperty("InputFile")); for (File inputFile : inputFiles) { String fileName = removeFileNameExtension(inputFile); List<String> lines = convertTextFileToListOfLines(inputFile.getAbsoluteFile().toString(), fileName, properties.getProperty("ReportFile")); List<CardHolder> cardHolders = convertLinesIntoCardHolders(lines); saveCardHolders(cardHolders, fileName, properties.getProperty("ReportFile"), properties); transferFileToCompleted(inputFile, properties.getProperty("CompletedFile")); } } private static String transferToCloudCard(CardHolder cardHolder, Properties properties) { try { URL url = new URL(properties.getProperty("URL") + "/api/people"); HttpsURLConnection connection = (HttpsURLConnection) url.openConnection(); connection.setDoOutput(true); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/json"); connection.setRequestProperty("X-Auth-Token", properties.getProperty("AccessToken")); connection.setRequestProperty("Accept", "application/json"); String input = "{ \"email\":\"" + cardHolder.getEmail() + "\"," + "\"organization\":{\"id\":" + properties.getProperty("ID") + "}," + "\"customFields\":{" + "\"Campus\":\"" + cardHolder.getCampus() + "\"," + "\"Notes\":\"" + cardHolder.getNotes() + "\"}, " + "\"identifier\":\"" + cardHolder.getID() + "\" }"; OutputStream outputStream = connection.getOutputStream(); outputStream.write(input.getBytes()); outputStream.flush(); if (connection.getResponseCode() != HttpURLConnection.HTTP_CREATED) { return "Failed : HTTP error code : " + connection.getResponseCode(); } connection.disconnect(); } catch (IOException e) { e.printStackTrace(); } return "Success"; } private static String removeFileNameExtension(File csvfile) { return csvfile.getName().replaceFirst("[.][^.]+$", ""); } private static File[] getCSVFilesFromDirectory(String filePath) { File dir = new File(filePath); return dir.listFiles(new FilenameFilter() { @Override public boolean accept(File dir1, String name) { return name.endsWith(".csv"); } }); } private static String getFileNameWithTimeStamp(String fileName) { LocalDateTime timeStamp = LocalDateTime.now(); DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH" + "\u02f8" + "mm" + "\u02f8" + "ss"); String formatDateTime = timeStamp.format(formatter); return fileName + "-" + formatDateTime + "-Report.csv"; } private static void transferFileToCompleted(File inputFile, String completedFile) { try { Files.move(Paths.get(inputFile.getAbsoluteFile().toString()), Paths.get(completedFile, inputFile.getName())); } catch (IOException e) { e.printStackTrace(); } } private static void saveCardHolders(List<CardHolder> cardHolders, String fileName, String fileLocation, Properties properties) { String content = ""; String header = "Status" + ", " + cardHolders.get(0) + "\n"; for (CardHolder cardHolder : dropHeaderFromList(cardHolders)) { String result; if (!cardHolder.validate()) { result = "failed validation"; } else { result = transferToCloudCard(cardHolder, properties); } content = content + result + ", " + cardHolder + "\n"; } try { String reportOutputPath = fileLocation + "/" + getFileNameWithTimeStamp(fileName); File file = new File(reportOutputPath); if (!file.exists()) { file.createNewFile(); } FileWriter fileWriter = new FileWriter(file.getAbsoluteFile()); BufferedWriter bufferedWriter = new BufferedWriter(fileWriter); bufferedWriter.write(header); bufferedWriter.write(content); bufferedWriter.close(); } catch (IOException e) { e.printStackTrace(); } } private static List<CardHolder> dropHeaderFromList(List<CardHolder> cardHolders) { return cardHolders.subList(1, cardHolders.size()); } public static void calculateIndexForOutput(String header) { String[] Header = header.split(delimiter); for (int i = 0; i < Header.length; i++) { for (int j = 0; j < headerTypes.length; j++) { if (headerTypes[ j ].equals(Header[ i ])) { if (i == 0) { CardHolder.setEmailIndex(j); } if (i == 1) { CardHolder.setIdIndex(j); } if (i == 2) { CardHolder.setCampusIndex(j); } if (i == 3) { CardHolder.setNotesIndex(j); } } } } } private static List<CardHolder> convertLinesIntoCardHolders(List<String> lines) { List<CardHolder> cardHolders = new ArrayList<CardHolder>(); for (String line : lines) { cardHolders.add(convertLineIntoCardholder(line)); } return cardHolders; } private static CardHolder convertLineIntoCardholder(String line) { CardHolder cardHolder = new CardHolder(delimiter, line); return cardHolder; } private static List<String> convertTextFileToListOfLines(String csvPath, String fileName, String arg) throws Exception { List<String> lines = null; try { BufferedReader bufferedReader = new BufferedReader(new FileReader(csvPath)); lines = new ArrayList<String>(); String line; int initialHeaderRead = 0; while ((line = bufferedReader.readLine()) != null) { if (initialHeaderRead == 0) { calculateIndexForOutput(line); initialHeaderRead++; } lines.add(line); } bufferedReader.close(); } catch (IOException e) { String reportOutputPath = arg + "/" + getFileNameWithTimeStamp(fileName); String failedRead = "Failed to read input file \n" + e.getMessage(); File file = new File(reportOutputPath); if (!file.exists()) { file.createNewFile(); } FileWriter fileWriter = new FileWriter(file.getAbsoluteFile()); BufferedWriter bufferedWriter = new BufferedWriter(fileWriter); bufferedWriter.write(failedRead); e.printStackTrace(); bufferedWriter.close(); throw new Exception(e); } return lines; } }
package org.eclipse.kura.net.admin.monitor; import java.util.Dictionary; import java.util.HashMap; import java.util.HashSet; import java.util.Hashtable; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import org.eclipse.kura.KuraException; import org.eclipse.kura.core.net.NetworkConfiguration; import org.eclipse.kura.core.net.modem.ModemInterfaceConfigImpl; import org.eclipse.kura.linux.net.dns.LinuxDns; import org.eclipse.kura.linux.net.dns.LinuxNamed; import org.eclipse.kura.linux.net.util.LinuxNetworkUtil; import org.eclipse.kura.net.IP4Address; import org.eclipse.kura.net.IPAddress; import org.eclipse.kura.net.NetConfig; import org.eclipse.kura.net.NetConfigIP4; import org.eclipse.kura.net.NetInterfaceAddressConfig; import org.eclipse.kura.net.NetInterfaceConfig; import org.eclipse.kura.net.NetInterfaceStatus; import org.eclipse.kura.net.NetInterfaceType; import org.eclipse.kura.net.NetworkPair; import org.eclipse.kura.net.admin.NetworkConfigurationService; import org.eclipse.kura.net.admin.event.NetworkConfigurationChangeEvent; import org.eclipse.kura.net.admin.event.NetworkStatusChangeEvent; import org.eclipse.kura.net.dhcp.DhcpServerConfig; import org.eclipse.kura.net.dns.DnsMonitorService; import org.eclipse.kura.net.dns.DnsServerConfigIP4; import org.osgi.service.component.ComponentContext; import org.osgi.service.event.Event; import org.osgi.service.event.EventConstants; import org.osgi.service.event.EventHandler; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class DnsMonitorServiceImpl implements DnsMonitorService, EventHandler { private static final Logger s_logger = LoggerFactory.getLogger(DnsMonitorServiceImpl.class); private final static String[] EVENT_TOPICS = new String[] { NetworkStatusChangeEvent.NETWORK_EVENT_STATUS_CHANGE_TOPIC, NetworkConfigurationChangeEvent.NETWORK_EVENT_CONFIG_CHANGE_TOPIC, }; private final static long THREAD_INTERVAL = 60000; private final static long THREAD_TERMINATION_TOUT = 1; // in seconds private static Future<?> s_monitorTask; private ExecutorService m_executor; private boolean m_enabled; private static boolean stopThread; private NetworkConfigurationService m_netConfigService; private NetworkConfiguration m_networkConfiguration; private Set<NetworkPair<IP4Address>> m_allowedNetworks; private Set<IP4Address> m_forwarders; public void setNetworkConfigurationService(NetworkConfigurationService netConfigService) { m_netConfigService = netConfigService; } public void unsetNetworkConfigurationService(NetworkConfigurationService netConfigService) { m_netConfigService = null; } protected void activate(ComponentContext componentContext) { s_logger.debug("Activating DnsProxyMonitor Service..."); Dictionary<String, String[]> d = new Hashtable<String, String[]>(); d.put(EventConstants.EVENT_TOPIC, EVENT_TOPICS); componentContext.getBundleContext().registerService(EventHandler.class.getName(), this, d); try { m_networkConfiguration = m_netConfigService.getNetworkConfiguration(); } catch (KuraException e) { s_logger.error("Could not get initial network configuration", e); } //FIXME - brute force handler for DNS updates // m_executorUtil = ExecutorUtil.getInstance(); m_executor = Executors.newSingleThreadExecutor(); stopThread = false; s_monitorTask = m_executor.submit(new Runnable() { @Override public void run() { while (!stopThread) { Thread.currentThread().setName("DnsMonitorServiceImpl"); Set<IPAddress> dnsServers = LinuxDns.getInstance().getDnServers(); // Check that resolv.conf matches what is configured Set<IPAddress> configuredServers = getConfiguredDnsServers(); if(!configuredServers.equals(dnsServers)) { setDnsServers(configuredServers); dnsServers = configuredServers; } Set<IP4Address> forwarders = new HashSet<IP4Address>(); if(dnsServers != null && !dnsServers.isEmpty()) { for(IPAddress dnsServer : dnsServers) { s_logger.debug("Found DNS Server: " + dnsServer.getHostAddress()); forwarders.add((IP4Address) dnsServer); } } if(forwarders != null && !forwarders.isEmpty()) { if(!forwarders.equals(m_forwarders)) { //there was a change - deal with it s_logger.info("Detected DNS resolv.conf change - restarting DNS proxy"); m_forwarders = forwarders; try { LinuxNamed linuxNamed = LinuxNamed.getInstance(); DnsServerConfigIP4 currentDnsServerConfig = linuxNamed.getDnsServerConfig(); DnsServerConfigIP4 newDnsServerConfig = new DnsServerConfigIP4(m_forwarders, m_allowedNetworks); if(currentDnsServerConfig.equals(newDnsServerConfig)) { s_logger.debug("DNS server config has changed - updating from " + currentDnsServerConfig + " to " + newDnsServerConfig); s_logger.debug("Disabling DNS proxy"); linuxNamed.disable(); s_logger.debug("Writing config"); linuxNamed.setConfig(newDnsServerConfig); if(m_enabled) { sleep(500); s_logger.debug("Starting DNS proxy"); linuxNamed.enable(); } else { s_logger.debug("DNS proxy not enabled"); } } } catch (KuraException e) { e.printStackTrace(); } } } try { Thread.sleep(THREAD_INTERVAL); } catch (InterruptedException e) { s_logger.debug(e.getMessage()); } } } }); } protected void deactivate(ComponentContext componentContext) { stopThread = true; if ((s_monitorTask != null) && (!s_monitorTask.isDone())) { s_logger.debug("Cancelling DnsMonitorServiceImpl task ..."); s_monitorTask.cancel(true); s_logger.info("DnsMonitorServiceImpl task cancelled? = {}", s_monitorTask.isDone()); s_monitorTask = null; } if (m_executor != null) { s_logger.debug("Terminating DnsMonitorServiceImpl Thread ..."); m_executor.shutdownNow(); try { m_executor.awaitTermination(THREAD_TERMINATION_TOUT, TimeUnit.SECONDS); } catch (InterruptedException e) { s_logger.warn("Interrupted", e); } s_logger.info("DnsMonitorServiceImpl Thread terminated? - {}", m_executor.isTerminated()); m_executor = null; } } @Override public void handleEvent(Event event) { s_logger.debug("handleEvent - topic: " + event.getTopic()); String topic = event.getTopic(); if (topic.equals(NetworkConfigurationChangeEvent.NETWORK_EVENT_CONFIG_CHANGE_TOPIC)) { NetworkConfigurationChangeEvent netConfigChangedEvent = (NetworkConfigurationChangeEvent)event; String [] propNames = netConfigChangedEvent.getPropertyNames(); if ((propNames != null) && (propNames.length > 0)) { Map<String, Object> props = new HashMap<String, Object>(); for (String propName : propNames) { Object prop = netConfigChangedEvent.getProperty(propName); if (prop != null) { props.put(propName, prop); } } try { m_networkConfiguration = new NetworkConfiguration(props); } catch (Exception e) { e.printStackTrace(); } } updateDnsResolverConfig(); updateDnsProxyConfig(); } else if (topic.equals(NetworkStatusChangeEvent.NETWORK_EVENT_STATUS_CHANGE_TOPIC)) { updateDnsResolverConfig(); updateDnsProxyConfig(); } } private void updateDnsResolverConfig() { s_logger.debug("Updating resolver config"); setDnsServers(getConfiguredDnsServers()); } private void updateDnsProxyConfig() { m_enabled = false; m_allowedNetworks = new HashSet<NetworkPair<IP4Address>>(); m_forwarders = new HashSet<IP4Address>(); if (m_networkConfiguration != null) { if (m_networkConfiguration.getNetInterfaceConfigs() != null) { List<NetInterfaceConfig<? extends NetInterfaceAddressConfig>> netInterfaceConfigs = m_networkConfiguration .getNetInterfaceConfigs(); for (NetInterfaceConfig<? extends NetInterfaceAddressConfig> netInterfaceConfig : netInterfaceConfigs) { if (netInterfaceConfig.getType() == NetInterfaceType.ETHERNET || netInterfaceConfig.getType() == NetInterfaceType.WIFI || netInterfaceConfig.getType() == NetInterfaceType.MODEM) { try { getAllowedNetworks(netInterfaceConfig); } catch (KuraException e) { s_logger.error("Error updating dns proxy", e); } } } } } Set<IPAddress> dnsServers = LinuxDns.getInstance().getDnServers(); if(dnsServers != null && !dnsServers.isEmpty()) { for(IPAddress dnsServer : dnsServers) { s_logger.debug("Found DNS Server: " + dnsServer.getHostAddress()); m_forwarders.add((IP4Address) dnsServer); } } try { LinuxNamed linuxNamed = LinuxNamed.getInstance(); s_logger.debug("Disabling DNS proxy"); linuxNamed.disable(); s_logger.debug("Writing config"); DnsServerConfigIP4 dnsServerConfigIP4 = new DnsServerConfigIP4(m_forwarders, m_allowedNetworks); linuxNamed.setConfig(dnsServerConfigIP4); if(m_enabled) { sleep(500); s_logger.debug("Starting DNS proxy"); linuxNamed.enable(); } else { s_logger.debug("DNS proxy not enabled"); } } catch (KuraException e) { e.printStackTrace(); } } private void getAllowedNetworks(NetInterfaceConfig<? extends NetInterfaceAddressConfig> netInterfaceConfig) throws KuraException { String interfaceName = netInterfaceConfig.getName(); s_logger.debug("Getting DNS proxy config for " + interfaceName); List<? extends NetInterfaceAddressConfig> netInterfaceAddressConfigs = null; netInterfaceAddressConfigs = netInterfaceConfig.getNetInterfaceAddresses(); if(netInterfaceAddressConfigs != null && netInterfaceAddressConfigs.size() > 0) { for(NetInterfaceAddressConfig netInterfaceAddressConfig : netInterfaceAddressConfigs) { List<NetConfig> netConfigs = netInterfaceAddressConfig.getConfigs(); if(netConfigs != null && netConfigs.size() > 0) { for(int i=0; i<netConfigs.size(); i++) { NetConfig netConfig = netConfigs.get(i); if(netConfig instanceof DhcpServerConfig) { if(((DhcpServerConfig) netConfig).isPassDns()) { s_logger.debug("Found an allowed network: " + ((DhcpServerConfig) netConfig).getRouterAddress() + "/" + ((DhcpServerConfig) netConfig).getPrefix()); m_enabled = true; //this is an 'allowed network' m_allowedNetworks.add(new NetworkPair<IP4Address>((IP4Address)((DhcpServerConfig) netConfig).getRouterAddress(), ((DhcpServerConfig) netConfig).getPrefix())); } } } } } } } private boolean isEnabledForWan(NetInterfaceConfig<? extends NetInterfaceAddressConfig> netInterfaceConfig) { for(NetInterfaceAddressConfig netInterfaceAddressConfig : netInterfaceConfig.getNetInterfaceAddresses()) { for(NetConfig netConfig : netInterfaceAddressConfig.getConfigs()) { if(netConfig instanceof NetConfigIP4) { return NetInterfaceStatus.netIPv4StatusEnabledWAN.equals(((NetConfigIP4) netConfig).getStatus()); } } } return false; } private void setDnsServers(Set<IPAddress> newServers) { LinuxDns linuxDns = LinuxDns.getInstance(); Set<IPAddress> currentServers = linuxDns.getDnServers(); if(newServers == null || newServers.isEmpty()) { s_logger.warn("Not Setting DNS servers to empty"); return; } if(currentServers != null && !currentServers.isEmpty()) { if(!currentServers.equals(newServers)) { s_logger.info("Change to DNS - setting dns servers: " + newServers); linuxDns.setDnServers(newServers); } else { s_logger.debug("No change to DNS servers - not updating"); } } else { s_logger.info("Current DNS servers are null - setting dns servers: " + newServers); linuxDns.setDnServers(newServers); } } // Get a list of dns servers for all WAN interfaces private Set<IPAddress> getConfiguredDnsServers() { LinkedHashSet<IPAddress> serverList = new LinkedHashSet<IPAddress>(); if(m_networkConfiguration!=null){ if(m_networkConfiguration.getNetInterfaceConfigs()!=null){ List<NetInterfaceConfig<? extends NetInterfaceAddressConfig>> netInterfaceConfigs = m_networkConfiguration.getNetInterfaceConfigs(); // If there are multiple WAN interfaces, their configured DNS servers are all included in no particular order for (NetInterfaceConfig<? extends NetInterfaceAddressConfig> netInterfaceConfig : netInterfaceConfigs) { if (netInterfaceConfig.getType() == NetInterfaceType.ETHERNET || netInterfaceConfig.getType() == NetInterfaceType.WIFI || netInterfaceConfig.getType() == NetInterfaceType.MODEM) { if(isEnabledForWan(netInterfaceConfig)) { try { Set<IPAddress> servers = getConfiguredDnsServers(netInterfaceConfig); s_logger.trace(netInterfaceConfig.getName() + " is WAN, adding its dns servers: " + servers); serverList.addAll(servers); } catch (KuraException e) { s_logger.error("Error adding dns servers for " + netInterfaceConfig.getName(), e); } } } } } } return serverList; } // Get a list of dns servers for the specified NetInterfaceConfig private Set<IPAddress> getConfiguredDnsServers(NetInterfaceConfig<? extends NetInterfaceAddressConfig> netInterfaceConfig) throws KuraException { String interfaceName = netInterfaceConfig.getName(); s_logger.trace("Getting dns servers for " + interfaceName); LinuxDns linuxDns = LinuxDns.getInstance(); LinkedHashSet<IPAddress> serverList = new LinkedHashSet<IPAddress>(); for(NetInterfaceAddressConfig netInterfaceAddressConfig : netInterfaceConfig.getNetInterfaceAddresses()) { for(NetConfig netConfig : netInterfaceAddressConfig.getConfigs()) { if(netConfig instanceof NetConfigIP4) { NetConfigIP4 netConfigIP4 = (NetConfigIP4) netConfig; List<IP4Address> userServers = netConfigIP4.getDnsServers(); if(netConfigIP4.isDhcp()) { // If DHCP but there are user defined entries, use those instead if(userServers != null && !userServers.isEmpty()) { s_logger.debug("Configured for DHCP with user-defined servers - adding: " + userServers); serverList.addAll(userServers); } else { if(netInterfaceConfig.getType().equals(NetInterfaceType.MODEM)) { // FIXME - don't like this // cannot use interfaceName here because it one config behind int pppNo = ((ModemInterfaceConfigImpl) netInterfaceConfig).getPppNum(); if (LinuxNetworkUtil.isUp("ppp"+pppNo)) { List<IPAddress> servers = linuxDns.getPppDnServers(); if (servers != null) { s_logger.debug("Adding PPP dns servers: " + servers); serverList.addAll(servers); } } } else { String currentAddress = LinuxNetworkUtil.getCurrentIpAddress(interfaceName); List<IPAddress> servers = linuxDns.getDhcpDnsServers(interfaceName, currentAddress); if (servers != null) { s_logger.debug("Configured for DHCP - adding DHCP servers: " + servers); serverList.addAll(servers); } } } } else { // If static, use the user defined entries s_logger.debug("Configured for static - adding user-defined servers: " + userServers); serverList.addAll(userServers); } } } } return serverList; } private static void sleep(int millis) { long start = System.currentTimeMillis(); long now = start; long end = start + millis; while(now < end) { try { Thread.sleep(end - now); } catch (InterruptedException e) { s_logger.debug("sleep interrupted: " + e); } now = System.currentTimeMillis(); } } }
package com.opencms.defaults; import com.opencms.template.*; import com.opencms.file.*; import java.util.*; import java.lang.reflect.*; import com.opencms.core.*; import com.opencms.core.exceptions.*; public abstract class A_CmsContentDefinition implements I_CmsContent, I_CmsConstants { /** * The owner of this resource. */ private int m_user; /** * The group of this resource. */ private String m_group; /** * The access flags of this resource. */ private int m_accessFlags; /** * applies the filter method * @returns an Vector containing the method */ public static Vector applyFilter(CmsObject cms, CmsFilterMethod filterMethod) throws Exception { return applyFilter(cms, filterMethod, null); } /** * applies the filter through the method object and the user parameters * @returns a vector with the filtered content */ public static Vector applyFilter(CmsObject cms, CmsFilterMethod filterMethod, String userParameter) throws Exception { Method method = filterMethod.getFilterMethod(); Object[] defaultParams = filterMethod.getDefaultParameter(); Vector allParameters = new Vector(); Object[] allParametersArray; Class[] paramTypes = method.getParameterTypes(); if( (paramTypes.length > 0) && (paramTypes[0] == CmsObject.class) ) { allParameters.addElement(cms); } for(int i = 0; i < defaultParams.length; i++) { allParameters.addElement(defaultParams[i]); } if (filterMethod.hasUserParameter()) { allParameters.addElement(userParameter); } allParametersArray = new Object[allParameters.size()]; allParameters.copyInto(allParametersArray); return (Vector) method.invoke(null, allParametersArray); } public void check(boolean finalcheck) throws CmsPlausibilizationException { // do nothing here, just an empty method for compatibility reasons. } /** * abstract delete method * for delete instance of content definition * must be overwritten in your content definition */ public abstract void delete(CmsObject cms) throws Exception; /** * Gets the getXXX methods * You have to override this method in your content definition. * @returns a Vector with the filed methods. */ public static Vector getFieldMethods(CmsObject cms) { return new Vector(); } /** * Gets the headlines of the table * You have to override this method in your content definition. * @returns a Vector with the colum names. */ public static Vector getFieldNames(CmsObject cms) { return new Vector(); } /** * Gets the filter methods. * You have to override this method in your content definition. * @returns a Vector of FilterMethod objects containing the methods, names and default parameters */ public static Vector getFilterMethods(CmsObject cms) { return new Vector(); } /** * Gets the lockstates * You have to override this method in your content definition, if you have overwritten * the isLockable method with true. * @returns a int with the lockstate */ public int getLockstate() { return -1; } /** * gets the unique Id of a content definition instance * @returns a string with the Id */ public abstract String getUniqueId(CmsObject cms) ; /** * Gets the url of the field entry * You have to override this method in your content definition, * if you wish to link urls to the field entries * @returns a String with the url */ public String getUrl() { return null; } /** * if the content definition objects should be lockable * this method has to be overwritten with value true * @returns a boolean */ public static boolean isLockable() { return false; } /** *Sets the lockstates * You have to override this method in your content definition, * if you have overwritten the isLockable method with true. * @sets the lockstate for the actual entry */ public void setLockstate(int lockstate) { } /** * abstract write method * must be overwritten in content definition */ public abstract void write(CmsObject cms) throws Exception; /** * returns true if the CD is readable for the current user * @retruns true */ public boolean isReadable() { return true; } /** * returns true if the CD is writeable for the current user * @retruns true */ public boolean isWriteable() { return true; } /** * set the owner of the CD * @param id of the owner */ public void setOwner(int userId) { m_user = userId; } /** * get the owner of the CD * @returns id of the owner (int) */ public int getOwner() { return m_user; } /** * set the group of the CD * @param the group ID */ public void setGroup(String group) { m_group = group; } /** * get the group of the CD * @returns the group ID */ public String getGroup() { return m_group; } /** * set the accessFlag for the CD * @param the accessFlag */ public void setAccessFlags(int accessFlags) { m_accessFlags = accessFlags; } /** * get the accessFlag for the CD * @returns the accessFlag */ public int getAccessFlags() { return m_accessFlags; } /** * has the current user the right to read the CD * @returns a boolean */ protected boolean hasReadAccess(CmsObject cms) throws CmsException { CmsUser currentUser = cms.getRequestContext().currentUser(); if ( !accessOther(C_ACCESS_PUBLIC_READ) && !accessOwner(cms, currentUser, C_ACCESS_OWNER_READ) && !accessGroup(cms, currentUser, C_ACCESS_GROUP_READ)) { return false; } return true; } /** * has the current user the right to write the CD * @returns a boolean */ protected boolean hasWriteAccess(CmsObject cms) throws CmsException { CmsUser currentUser = cms.getRequestContext().currentUser(); // check, if the resource is locked by the current user if( isLockable() && (getLockstate() != currentUser.getId()) ) { // resource is not locked by the current user, no writing allowed return(false); } // check the rights for the current resource if( ! ( accessOther(C_ACCESS_PUBLIC_WRITE) || accessOwner(cms, currentUser, C_ACCESS_OWNER_WRITE) || accessGroup(cms, currentUser, C_ACCESS_GROUP_WRITE) ) ) { // no write access to this resource! return false; } return true; } /** * Checks, if the owner may access this resource. * * @param cms the cmsObject * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param flags The flags to check. * * @return wether the user has access, or not. */ private boolean accessOwner(CmsObject cms, CmsUser currentUser, int flags) throws CmsException { // The Admin has always access if( cms.isAdmin() ) { return(true); } // is the resource owned by this user? if(getOwner() == currentUser.getId()) { if( (getAccessFlags() & flags) == flags ) { return true ; } } // the resource isn't accesible by the user. return false; } /** * Checks, if the group may access this resource. * * @param cms the cmsObject * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param flags The flags to check. * * @return wether the user has access, or not. */ private boolean accessGroup(CmsObject cms, CmsUser currentUser, int flags) throws CmsException { // is the user in the group for the resource? if(cms.userInGroup(currentUser.getName(), getGroup() )) { if( (getAccessFlags() & flags) == flags ) { return true; } } // the resource isn't accesible by the user. return false; } /** * Checks, if others may access this resource. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param flags The flags to check. * * @return wether the user has access, or not. */ private boolean accessOther( int flags ) throws CmsException { if ((getAccessFlags() & flags) == flags) { return true; } else { return false; } } /** * if the content definition objects should be displayed * in an extended list with projectflags and state * this method must be overwritten with value true * @returns a boolean */ public static boolean isExtendedList() { return false; } }
package com.example.beer.services; import java.net.HttpURLConnection; import javax.ejb.Stateless; import javax.inject.Inject; import javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import com.example.beer.dao.UserDAO; import com.example.beer.dto.TaskContainer; import com.example.beer.dto.UserDTO; import com.example.beer.dto.UserDTOContainer; import com.example.beer.model.User; import com.example.beer.model.WebUser; @Stateless @Path("user") public class UserManager { @Inject private UserDAO userDAO; @Inject private UserContext userContext; @POST @Path("login") @Consumes(MediaType.APPLICATION_JSON) public Response login(WebUser user) { User foundUser = userDAO.validateCredentials(user.getUsername(), user.getPassword()); if (foundUser != null) { userContext.setCurrentUser(foundUser); return Response.status(HttpURLConnection.HTTP_OK).build(); } return Response.status(HttpURLConnection.HTTP_UNAUTHORIZED).build(); } @POST @Path("logout") public Response logout() { userContext.setCurrentUser(null); return Response.status(HttpURLConnection.HTTP_OK).build(); } @POST @Path("register") @Consumes(MediaType.APPLICATION_JSON) public Response registerNewUser(User user) { User currentUser = userContext.getCurrentUser(); User foundUser = userDAO.getUserByName(user.getName()); if (currentUser != null && currentUser.isAdmin()) { if (foundUser == null) { userDAO.addUser(user); return Response.status(HttpURLConnection.HTTP_OK).build(); } else { return Response.status(HttpURLConnection.HTTP_CONFLICT).build(); } } return Response.status(HttpURLConnection.HTTP_FORBIDDEN).build(); } @GET @Produces(MediaType.APPLICATION_JSON) public Response getAllUsers() { User currentUser = userContext.getCurrentUser(); if (currentUser == null || !currentUser.isAdmin()) { return Response.status(HttpURLConnection.HTTP_FORBIDDEN).build(); } UserDTOContainer users = new UserDTOContainer(userDAO.getAllUsers()); return Response.ok(users).build(); } @GET @Path("{username}") @Produces(MediaType.APPLICATION_JSON) public Response getUserByName(@PathParam("username") String username) { User currentUser = userContext.getCurrentUser(); if (currentUser == null || !currentUser.isAdmin()) { return Response.status(HttpURLConnection.HTTP_FORBIDDEN).build(); } User user = userDAO.getUserByName(username); if (user == null) { return Response.status(HttpURLConnection.HTTP_NOT_FOUND).build(); } return Response.ok(new UserDTO(user)).build(); } @GET @Path("tasks/{userId}") @Produces(MediaType.APPLICATION_JSON) public Response getTasksForUser(@PathParam("userId") int userId) { User user = userDAO.getUserById(userId); if (user == null) { return Response.status(HttpURLConnection.HTTP_NOT_FOUND).build(); } User currentUser = userContext.getCurrentUser(); if (currentUser == null || !currentUser.isAdmin() && !currentUser.equals(user)) { return Response.status(HttpURLConnection.HTTP_FORBIDDEN).build(); } TaskContainer tasks = new TaskContainer(user.getTasks()); System.out.println(user.getTasks().size()); return Response.ok(tasks).build(); } }
import javax.sql.DataSource; import java.sql.Connection; import java.sql.Statement; import java.sql.ResultSet; import java.sql.SQLException; // Here are the dbcp-specific classes. // Note that they are only used in the setupDataSource // method. In normal use, your classes interact // only with the standard JDBC API import org.apache.commons.pool.ObjectPool; import org.apache.commons.pool.impl.GenericObjectPool; import org.apache.commons.dbcp.ConnectionFactory; import org.apache.commons.dbcp.PoolingDataSource; import org.apache.commons.dbcp.PoolableConnectionFactory; import org.apache.commons.dbcp.DriverManagerConnectionFactory; // Here's a simple example of how to use the PoolingDataSource. // In this example, we'll construct the PoolingDataSource manually, // just to show how the pieces fit together, but you could also // configure it using an external conifguration file in // JOCL format (and eventually Digester). // Note that this example is very similiar to the PoolingDriver // example. In fact, you could use the same pool in both a // PoolingDriver and a PoolingDataSource // To compile this example, you'll want: // * commons-pool.jar // * commons-dbcp.jar // * j2ee.jar (for the javax.sql classes) // in your classpath. // To run this example, you'll want: // * commons-collections.jar // * commons-pool.jar // * commons-dbcp.jar // * j2ee.jar (for the javax.sql classes) // * the classes for your (underlying) JDBC driver // in your classpath. // Invoke the class using two arguments: // * the connect string for your underlying JDBC driver // * the query you'd like to execute // You'll also want to ensure your underlying JDBC driver // is registered. You can use the "jdbc.drivers" // property to do this. // For example: // java -Djdbc.drivers=oracle.jdbc.driver.OracleDriver \ // -classpath commons-collections.jar:commons-pool.jar:commons-dbcp.jar:j2ee.jar:oracle-jdbc.jar:. \ // ManualPoolingDataSourceExample // "jdbc:oracle:thin:scott/tiger@myhost:1521:mysid" // "SELECT * FROM DUAL" public class ManualPoolingDataSourceExample { public static void main(String[] args) { // First we load the underlying JDBC driver. // You need this if you don't use the jdbc.drivers // system property. System.out.println("Loading underlying JDBC driver."); try { Class.forName("oracle.jdbc.driver.OracleDriver"); } catch (ClassNotFoundException e) { e.printStackTrace(); } System.out.println("Done."); // Then, we set up the PoolingDataSource. // Normally this would be handled auto-magically by // an external configuration, but in this example we'll // do it manually. System.out.println("Setting up data source."); DataSource dataSource = setupDataSource(args[0]); System.out.println("Done."); // Now, we can use JDBC DataSource as we normally would. Connection conn = null; Statement stmt = null; ResultSet rset = null; try { System.out.println("Creating connection."); conn = dataSource.getConnection(); System.out.println("Creating statement."); stmt = conn.createStatement(); System.out.println("Executing statement."); rset = stmt.executeQuery(args[1]); System.out.println("Results:"); int numcols = rset.getMetaData().getColumnCount(); while(rset.next()) { for(int i=1;i<=numcols;i++) { System.out.print("\t" + rset.getString(i)); } System.out.println(""); } } catch(SQLException e) { e.printStackTrace(); } finally { try { rset.close(); } catch(Exception e) { } try { stmt.close(); } catch(Exception e) { } try { conn.close(); } catch(Exception e) { } } } public static DataSource setupDataSource(String connectURI) { // First, we'll need a ObjectPool that serves as the // actual pool of connections. // We'll use a GenericObjectPool instance, although // any ObjectPool implementation will suffice. ObjectPool connectionPool = new GenericObjectPool(null); // Next, we'll create a ConnectionFactory that the // pool will use to create Connections. // We'll use the DriverManagerConnectionFactory, // using the connect string passed in the command line // arguments. ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(connectURI,null); // Now we'll create the PoolableConnectionFactory, which wraps // the classes that implement the pooling functionality. PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(connectionFactory,connectionPool,null,null,false,true); // Finally, we create the PoolingDriver itself, // passing in the object pool we created. PoolingDataSource dataSource = new PoolingDataSource(connectionPool); return dataSource; } }
package core; import java.util.ArrayList; import static config.Values.*; public class Wcm { public static ArrayList<Masume> null_wcm(){ return new ArrayList<Masume>(); } public static ArrayList<Masume> pl_hu_wcm(Banmen ban, Masume current){ ArrayList<Masume> result = new ArrayList<>(); if(isMovable(ban, new Masume(current.getX(), current.getY() - 1))){ result.add(new Masume(current.getX(), current.getY() - 1)); } return result; } public static ArrayList<Masume> pl_kyousha_wcm(Banmen ban, Masume current){ ArrayList<Masume> result = new ArrayList<>(); for(int y = current.getY()-1;y >= 1;y if(ban.is_empty(current.getX(), y)){ result.add(new Masume(current.getX(), y)); }else{ if(isMovable(ban, new Masume(current.getX(), y))){ result.add(new Masume(current.getX(), y)); } break; } } return result; } public static ArrayList<Masume> pl_keima_wcm(Banmen ban, Masume masume){ ArrayList<Masume> result = new ArrayList<>(); if(isMovable(ban, new Masume(masume.getX() - 1, masume.getY() - 2))){ result.add(new Masume(masume.getX() - 1, masume.getY() - 2)); } if(isMovable(ban, new Masume(masume.getX() + 1, masume.getY() - 2))){ result.add(new Masume(masume.getX() + 1, masume.getY() - 2)); } return result; } public static ArrayList<Masume> pl_gin_wcm(Banmen ban, Masume masume){ ArrayList<Masume> result = new ArrayList<>(); if(isMovable(ban, new Masume(masume.getX(), masume.getY() - 1))){ result.add(new Masume(masume.getX(), masume.getY() - 1)); } if(isMovable(ban, new Masume(masume.getX() - 1, masume.getY() - 1))){ result.add(new Masume(masume.getX() - 1, masume.getY() - 1)); } if(isMovable(ban, new Masume(masume.getX() + 1, masume.getY() - 1))){ result.add(new Masume(masume.getX() + 1, masume.getY() - 1)); } if(isMovable(ban, new Masume(masume.getX() - 1, masume.getY() + 1))){ result.add(new Masume(masume.getX() - 1, masume.getY() + 1)); } if(isMovable(ban, new Masume(masume.getX() + 1, masume.getY() + 1))){ result.add(new Masume(masume.getX() + 1, masume.getY() + 1)); } return result; } public static ArrayList<Masume> pl_kin_wcm(Banmen ban, Masume masume){ ArrayList<Masume> result = new ArrayList<>(); if(isMovable(ban, new Masume(masume.getX(), masume.getY() - 1))){ result.add(new Masume(masume.getX(), masume.getY() - 1)); } if(isMovable(ban, new Masume(masume.getX() - 1, masume.getY() - 1))){ result.add(new Masume(masume.getX() - 1, masume.getY() - 1)); } if(isMovable(ban, new Masume(masume.getX() + 1, masume.getY() - 1))){ result.add(new Masume(masume.getX() + 1, masume.getY() - 1)); } if(isMovable(ban, new Masume(masume.getX() - 1, masume.getY()))){ result.add(new Masume(masume.getX() - 1, masume.getY())); } if(isMovable(ban, new Masume(masume.getX() + 1, masume.getY()))){ result.add(new Masume(masume.getX() + 1, masume.getY())); } if(isMovable(ban, new Masume(masume.getX(), masume.getY() + 1))){ result.add(new Masume(masume.getX(), masume.getY() + 1)); } return result; } public static ArrayList<Masume> pl_ou_wcm(Banmen ban, Masume masume){ ArrayList<Masume> result = new ArrayList<>(); if(isMovable(ban, new Masume(masume.getX(), masume.getY() - 1))){ result.add(new Masume(masume.getX(), masume.getY() - 1)); } if(isMovable(ban, new Masume(masume.getX() - 1, masume.getY() - 1))){ result.add(new Masume(masume.getX() - 1, masume.getY() - 1)); } if(isMovable(ban, new Masume(masume.getX() + 1, masume.getY() - 1))){ result.add(new Masume(masume.getX() + 1, masume.getY() - 1)); } if(isMovable(ban, new Masume(masume.getX() - 1, masume.getY()))){ result.add(new Masume(masume.getX() - 1, masume.getY())); } if(isMovable(ban, new Masume(masume.getX() + 1, masume.getY()))){ result.add(new Masume(masume.getX() + 1, masume.getY())); } if(isMovable(ban, new Masume(masume.getX() - 1, masume.getY() + 1))){ result.add(new Masume(masume.getX() - 1, masume.getY() + 1)); } if(isMovable(ban, new Masume(masume.getX() + 1, masume.getY() + 1))){ result.add(new Masume(masume.getX() + 1, masume.getY() * 1)); } if(isMovable(ban, new Masume(masume.getX(), masume.getY() + 1))){ result.add(new Masume(masume.getX(), masume.getY() + 1)); } return result; } public static ArrayList<Masume> pl_hisha_wcm(Banmen ban, Masume masume){ ArrayList<Masume> result = new ArrayList<>(); int i = 1; while(isMovable(ban, new Masume(masume.getX(), masume.getY() - i))){ result.add(new Masume(masume.getX(), masume.getY() - i)); i++; } i = 1; while(isMovable(ban, new Masume(masume.getX(), masume.getY() + i))){ result.add(new Masume(masume.getX(), masume.getY() + i)); i++; } i = 1; while(isMovable(ban, new Masume(masume.getX() - i, masume.getY()))){ result.add(new Masume(masume.getX() - i, masume.getY())); i++; } i = 1; while(isMovable(ban, new Masume(masume.getX() + i, masume.getY()))){ result.add(new Masume(masume.getX() + i, masume.getY())); i++; } return result; } private static boolean isMine(Banmen ban, Masume masume){ return ban.get_system_ban_value(masume.getX(), masume.getY()) >= HU && ban.get_system_ban_value(masume.getX(), masume.getY()) <= OU; } private static boolean isAIs(Banmen ban, Masume masume){ return ban.get_system_ban_value(masume.getX(), masume.getY()) >= EN_HU && ban.get_system_ban_value(masume.getX(), masume.getY()) <= EN_OU; } private static boolean isMovable(Banmen ban, Masume masume){ if(!masume.is_safe()){ return false; } return isAIs(ban, masume) || ban.is_empty(masume); } }
package example; import java.util.EmptyStackException; import java.util.Stack; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Test; // tag::user_guide[] @DisplayName("A stack") class TestingAStackDemo { Stack<Object> stack; boolean isRun = false; @Test @DisplayName("is instantiated with new Stack()") void isInstantiatedWithNew() { new Stack<Object>(); } @Nested @DisplayName("when new") class WhenNew { @BeforeEach void init() { stack = new Stack<Object>(); } @Test @DisplayName("is empty") void isEmpty() { Assertions.assertTrue(stack.isEmpty()); } @Test @DisplayName("throws EmptyStackException when popped") void throwsExceptionWhenPopped() { Assertions.assertThrows(EmptyStackException.class, () -> stack.pop()); } @Test @DisplayName("throws EmptyStackException when peeked") void throwsExceptionWhenPeeked() { Assertions.assertThrows(EmptyStackException.class, () -> stack.peek()); } @Nested @DisplayName("after pushing an element") class AfterPushing { String anElement = "an element"; @BeforeEach void init() { stack.push(anElement); } @Test @DisplayName("it is no longer empty") void isEmpty() { Assertions.assertFalse(stack.isEmpty()); } @Test @DisplayName("returns the element when popped and is empty") void returnElementWhenPopped() { Assertions.assertEquals(anElement, stack.pop()); Assertions.assertTrue(stack.isEmpty()); } @Test @DisplayName("returns the element when peeked but remains not empty") void returnElementWhenPeeked() { Assertions.assertEquals(anElement, stack.peek()); Assertions.assertFalse(stack.isEmpty()); } } } } // end::user_guide[]
package com.smartnsoft.droid4me.ws; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.StringWriter; import java.io.UnsupportedEncodingException; import java.net.SocketException; import java.net.URLEncoder; import java.net.UnknownHostException; import java.util.Map; import java.util.Map.Entry; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.FactoryConfigurationError; import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.methods.HttpDelete; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpPut; import org.apache.http.client.methods.HttpRequestBase; import org.apache.http.impl.client.DefaultHttpClient; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.xml.sax.ContentHandler; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.XMLReader; import com.smartnsoft.droid4me.log.Logger; import com.smartnsoft.droid4me.log.LoggerFactory; public abstract class WebServiceCaller { /** * An HTTP method type. */ public static enum Verb { Get, Post, Put, Delete; } /** * Defines the way the HTTP method is run, and enables to link a call code with it. */ public final static class CallType { /** * The call code when not defined. */ public final static int NO_CALL_CODE = -1; public final static WebServiceCaller.CallType Get = new WebServiceCaller.CallType(WebServiceCaller.Verb.Get, WebServiceCaller.CallType.NO_CALL_CODE); public final static WebServiceCaller.CallType Post = new WebServiceCaller.CallType(WebServiceCaller.Verb.Post, WebServiceCaller.CallType.NO_CALL_CODE); public final static WebServiceCaller.CallType Put = new WebServiceCaller.CallType(WebServiceCaller.Verb.Put, WebServiceCaller.CallType.NO_CALL_CODE); public final static WebServiceCaller.CallType Delete = new WebServiceCaller.CallType(WebServiceCaller.Verb.Delete, WebServiceCaller.CallType.NO_CALL_CODE); /** * The HTTP method. */ public final WebServiceCaller.Verb verb; /** * A code that may associated with the call. */ public final int callCode; public CallType(WebServiceCaller.Verb verb, int callCode) { this.verb = verb; this.callCode = callCode; } @Override public String toString() { return verb.toString(); } } /** * The exception that will be thrown if any problem occurs during a web service call. */ public static class CallException extends Exception { private static final long serialVersionUID = 4869741128441615773L; private int statusCode; public CallException(String message, Throwable throwable) { super(message, throwable); } public CallException(String message) { super(message); } public CallException(Throwable throwable) { super(throwable); } public CallException(String message, int statusCode) { this(message, null, statusCode); } public CallException(Throwable throwable, int statusCode) { this(null, throwable, statusCode); } public CallException(String message, Throwable throwable, int statusCode) { super(message, throwable); this.statusCode = statusCode; } public int getStatusCode() { return statusCode; } /** * @return <code>true</code> is the current exception is linked to a connectivity problem with Internet. * @see #isConnectivityProblem(Throwable) */ public final boolean isConnectivityProblem() { return WebServiceCaller.CallException.isConnectivityProblem(this); } /** * Indicates whether the cause of the provided exception is due to a connectivity problem. * * @param throwable * the exception to test * @return <code>true</code> if the {@link Throwable} was triggered because of a connectivity problem with Internet */ public static boolean isConnectivityProblem(Throwable throwable) { Throwable cause; Throwable newThrowable = throwable; // We investigate over the whole cause stack while ((cause = newThrowable.getCause()) != null) { if (cause instanceof UnknownHostException || cause instanceof SocketException) { return true; } newThrowable = cause; } return false; } } protected final static Logger log = LoggerFactory.getInstance(WebServiceCaller.class); private static DocumentBuilder builder; private boolean isConnected = true; public static InputStream createInputStreamFromJson(JSONObject jsonObject) { return new ByteArrayInputStream(jsonObject.toString().getBytes()); } public static InputStream createInputStreamFromJson(JSONArray jsonArray) { return new ByteArrayInputStream(jsonArray.toString().getBytes()); } private static XMLReader getNewXmlReader() throws FactoryConfigurationError { final SAXParserFactory saxParserFactory = SAXParserFactory.newInstance(); XMLReader theReader = null; try { final SAXParser saxParser = saxParserFactory.newSAXParser(); try { theReader = saxParser.getXMLReader(); } catch (SAXException exception) { if (log.isFatalEnabled()) { log.fatal("Cannot create the SAX XML reader", exception); } } } catch (Exception exception) { if (log.isFatalEnabled()) { log.fatal("Cannot create the SAX parser", exception); } } return theReader; } /** * @return the value previously set by the {@link #setConnected(boolean)} method */ public boolean isConnected() { return isConnected; } /** * Enables to indicate that no Internet connectivity is available, or that the connectivity has been restored. The initial value is * <code>true</code>. */ public void setConnected(boolean isConnected) { this.isConnected = isConnected; } public final InputStream getInputStream(String uri) throws WebServiceCaller.CallException { return getInputStream(uri, WebServiceCaller.CallType.Get, null); } /** * Performs an HTTP request corresponding to the provided parameters. * * @param uri * the URI being requested * @param callType * the HTTP method * @param body * if the HTTP method is set to {@link WebServiceCaller.CallType#Post} or {@link WebServiceCaller.CallType#Put}, this is the body of the * request * @return the input stream of the HTTP method call; cannot be <code>null</code> * @throws WebServiceCaller.CallException * if the status code of the HTTP response does not belong to the [{@link HttpStatus.SC_OK}, {@link HttpStatus.SC_MULTI_STATUS}] range. * Also if a connection issue occurred: the exception will {@link Throwable#getCause() embed} the cause of the exception. If the * {@link #isConnected()} method returns <code>false</code>, no request will be attempted and a {@link WebServiceCaller.CallException} * exception will be thrown (embedding a {@link UnknownHostException} exception). */ public final InputStream getInputStream(String uri, WebServiceCaller.CallType callType, HttpEntity body) throws WebServiceCaller.CallException { if (isConnected == false) { throw new WebServiceCaller.CallException(new UnknownHostException("No connectivity")); } try { final HttpResponse response = performHttpRequest(uri, callType, body, 0); return getContent(uri, callType, response); } catch (WebServiceCaller.CallException exception) { throw exception; } catch (Exception exception) { throw new WebServiceCaller.CallException(exception); } } protected abstract String getUrlEncoding(); /** * @return the top XML element of the DOM */ protected final Element performHttpGetDom(String methodUriPrefix, String methodUriSuffix, Map<String, String> uriParameters) throws UnsupportedEncodingException, ClientProtocolException, IOException, CallException, IllegalStateException, SAXException { return performHttpGetDom(computeUri(methodUriPrefix, methodUriSuffix, uriParameters)); } /** * @see #performHttpGetDom(String, String, Map) */ protected final Element performHttpGetDom(String uri) throws UnsupportedEncodingException, ClientProtocolException, IOException, CallException, IllegalStateException, SAXException { final HttpResponse response = performHttpRequest(uri, WebServiceCaller.CallType.Get, null, 0); return WebServiceCaller.getDom(getContent(uri, WebServiceCaller.CallType.Get, response)); } protected final void performHttpGetSAX(String methodUriPrefix, String methodUriSuffix, Map<String, String> uriParameters, ContentHandler contentHandler) throws UnsupportedEncodingException, ClientProtocolException, IOException, IllegalStateException, SAXException, ParserConfigurationException, WebServiceCaller.CallException { parseSax(contentHandler, getInputStream(computeUri(methodUriPrefix, methodUriSuffix, uriParameters))); } protected final String performHttpGetJson(String methodUriPrefix, String methodUriSuffix, Map<String, String> uriParameters) throws ClientProtocolException, IllegalStateException, IOException, FactoryConfigurationError, ParserConfigurationException, SAXException, CallException, JSONException { return performHttpGetJson(computeUri(methodUriPrefix, methodUriSuffix, uriParameters)); } protected final String performHttpPostJson(String methodUriPrefix, String methodUriSuffix, HttpEntity postContents) throws UnsupportedEncodingException, ClientProtocolException, IllegalStateException, IOException, CallException, JSONException { return performHttpPostJson(computeUri(methodUriPrefix, methodUriSuffix, null), postContents); } protected final String performHttpPutJson(String methodUriPrefix, String methodUriSuffix, HttpEntity postContents) throws UnsupportedEncodingException, ClientProtocolException, IllegalStateException, IOException, CallException, JSONException { return performHttpPutJson(computeUri(methodUriPrefix, methodUriSuffix, null), postContents); } protected final String performHttpDeleteJson(String methodUriPrefix, String methodUriSuffix) throws UnsupportedEncodingException, ClientProtocolException, IllegalStateException, IOException, CallException, JSONException { return performHttpDeleteJson(computeUri(methodUriPrefix, methodUriSuffix, null)); } protected final String performHttpGetJson(String uri) throws UnsupportedEncodingException, ClientProtocolException, IOException, CallException, IllegalStateException, JSONException { final HttpResponse response = performHttpRequest(uri, WebServiceCaller.CallType.Get, null, 0); return getJson(getContent(uri, WebServiceCaller.CallType.Get, response)); } protected final String performHttpPostJson(String uri, HttpEntity body) throws UnsupportedEncodingException, ClientProtocolException, IOException, CallException, IllegalStateException, JSONException { final HttpResponse response = performHttpRequest(uri, WebServiceCaller.CallType.Post, body, 0); return getJson(getContent(uri, WebServiceCaller.CallType.Post, response)); } protected final String performHttpPutJson(String uri, HttpEntity body) throws UnsupportedEncodingException, ClientProtocolException, IOException, CallException, IllegalStateException, JSONException { final HttpResponse response = performHttpRequest(uri, WebServiceCaller.CallType.Put, body, 0); return getJson(getContent(uri, WebServiceCaller.CallType.Put, response)); } protected final String performHttpDeleteJson(String uri) throws UnsupportedEncodingException, ClientProtocolException, IOException, CallException, IllegalStateException, JSONException { final HttpResponse response = performHttpRequest(uri, WebServiceCaller.CallType.Delete, null, 0); return getJson(getContent(uri, WebServiceCaller.CallType.Delete, response)); } public static final String getString(InputStream inputStream) throws IOException { final StringWriter writer = new StringWriter(); final InputStreamReader streamReader = new InputStreamReader(inputStream); // The 8192 parameter is there to please Android at runtime and discard the // "INFO/global(16464): INFO: Default buffer size used in BufferedReader constructor. It would be better to be explicit if a 8k-char buffer is required." // log final BufferedReader buffer = new BufferedReader(streamReader, 8192); String line = ""; while (null != (line = buffer.readLine())) { writer.write(line); } return writer.toString(); } public static final String getJson(InputStream inputStream) throws JSONException { try { return WebServiceCaller.getString(inputStream); } catch (IOException exception) { throw new JSONException(exception.getMessage()); } } public static final Element getDom(InputStream inputStream) throws SAXException, IOException { return WebServiceCaller.parseDom(inputStream).getDocumentElement(); } public static Document parseDom(InputStream inputStream) throws SAXException, IOException { // TODO: make this thread-safe one day, even if it is very likely that it is not necessary at all if (WebServiceCaller.builder == null) { final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(false); factory.setValidating(false); try { WebServiceCaller.builder = factory.newDocumentBuilder(); } catch (ParserConfigurationException exception) { if (log.isFatalEnabled()) { log.fatal("Cannot create the DOM XML parser factories", exception); } } } return builder.parse(inputStream); } protected final Document parseDom(String uri, WebServiceCaller.CallType callType, HttpResponse response) throws CallException { try { return WebServiceCaller.parseDom(getContent(uri, callType, response)); } catch (IOException exception) { throw new WebServiceCaller.CallException("A I/O problem occurred while attempting to parse in DOM the HTTP response!", exception); } catch (SAXException exception) { throw new WebServiceCaller.CallException("Cannot parse properly in DOM the input stream!", exception); } } public final void parseSax(ContentHandler contentHandler, InputStream inputStream) throws FactoryConfigurationError, IOException, SAXException { // Now that multiple SAX parsings can be done in parallel, we create a new XML reader each time try { final XMLReader xmlReader = getNewXmlReader(); xmlReader.setContentHandler(contentHandler); final InputSource inputSource = new InputSource(inputStream); inputSource.setEncoding(getUrlEncoding()); xmlReader.parse(inputSource); } finally { try { inputStream.close(); } catch (IOException exception) { if (log.isWarnEnabled()) { log.warn("Could not properly close the input stream used for parsing the XML in SAX", exception); } } } } protected final HttpResponse performHttpGet(String methodUriPrefix, String methodUriSuffix, Map<String, String> uriParameters) throws UnsupportedEncodingException, IOException, ClientProtocolException, WebServiceCaller.CallException { return performHttpRequest(computeUri(methodUriPrefix, methodUriSuffix, uriParameters), WebServiceCaller.CallType.Get, null, 0); } protected final HttpResponse performHttpPost(String uri, HttpEntity body) throws UnsupportedEncodingException, IOException, ClientProtocolException, WebServiceCaller.CallException { return performHttpRequest(uri, WebServiceCaller.CallType.Post, body, 0); } protected final HttpResponse performHttpPut(String uri, HttpEntity body) throws UnsupportedEncodingException, IOException, ClientProtocolException, WebServiceCaller.CallException { return performHttpRequest(uri, WebServiceCaller.CallType.Put, body, 0); } private HttpResponse performHttpRequest(String uri, WebServiceCaller.CallType callType, HttpEntity body, int attemptsCount) throws UnsupportedEncodingException, IOException, ClientProtocolException, WebServiceCaller.CallException { if (uri == null) { throw new WebServiceCaller.CallException("Cannot perform an HTTP request with a null URI!"); } final long start = System.currentTimeMillis(); final HttpRequestBase request; switch (callType.verb) { default: case Get: request = new HttpGet(uri); break; case Post: final HttpPost httpPost = new HttpPost(uri); // final List<NameValuePair> values = new ArrayList<NameValuePair>(); // for (Entry<String, String> entry : postContents.entrySet()) // values.add(new BasicNameValuePair(entry.getKey(), entry.getValue())); // httpPost.setEntity(new UrlEncodedFormEntity(values, getUrlEncoding())); httpPost.setEntity(body); request = httpPost; break; case Put: final HttpPut httpPut = new HttpPut(uri); httpPut.setEntity(body); request = httpPut; break; case Delete: final HttpDelete httpDelete = new HttpDelete(uri); request = httpDelete; break; } if (log.isDebugEnabled()) { log.debug("Running the HTTP " + callType + " query '" + uri + "'"); } final DefaultHttpClient httpClient = getHttpClient(); onBeforeHttpRequestExecution(httpClient, request); final HttpResponse response = httpClient.execute(request); final long stop = System.currentTimeMillis(); final int statusCode = response.getStatusLine().getStatusCode(); if (log.isInfoEnabled()) { log.info("The call to the HTTP " + callType + " query '" + uri + "' took " + (stop - start) + " ms with status code " + statusCode); } if (!(statusCode >= HttpStatus.SC_OK && statusCode <= HttpStatus.SC_MULTI_STATUS)) { if (onStatusCodeNotOk(uri, callType, body, response, statusCode, attemptsCount + 1) == true) { return performHttpRequest(uri, callType, body, attemptsCount + 1); } } return response; } /** * Invoked when the result of the HTTP request is not <code>20X</code>. The default implementation logs the problem and throws an exception. * * @param uri * the URI of the HTTP call * @param callType * the type of the HTTP method * @param body * the body of the HTTP method when its a {@link WebServiceCaller.CallType#Post} or a {@link WebServiceCaller.CallType#Put} ; * <code>null</code> otherwise * @param response * the HTTP response * @param statusCode * the status code of the response, which is not <code>20X</code> * @param attemptsCount * the number of attempts that have been run for this HTTP method. Starts at <code>1</code> * @return <code>true</code> if you want the request to be re-run if it has failed * @throws WebServiceCaller.CallException * if you want the call to be considered as not OK */ protected boolean onStatusCodeNotOk(String uri, WebServiceCaller.CallType callType, HttpEntity body, HttpResponse response, int statusCode, int attemptsCount) throws WebServiceCaller.CallException { final String message = "The result code of the call to the web method '" + uri + "' is not OK (not 20X). Status: " + response.getStatusLine(); if (log.isErrorEnabled()) { log.error(message); } throw new WebServiceCaller.CallException(message, statusCode); } /** * This is the perfect place for customizing the HTTP request that is bound to be run. * * @param httpClient * the Apache HTTP client that will run the HTTP request * @param request * the HTTP request * @throws WebServiceCaller.CallException * in case the HTTP request cannot be eventually invoked properly */ protected void onBeforeHttpRequestExecution(DefaultHttpClient httpClient, HttpRequestBase request) throws WebServiceCaller.CallException { } /** * Invoked on every call, in order to extract the input stream from the response. * * <p> * If the content type is gzipped, this is the ideal place for unzipping it. * </p> * * @param uri * the web call initial URI * @param callType * the kind of request * @param response * the HTTP response * @return the (decoded) input stream of the response * @throws IOException * if some exception occurred while extracting the content of the response */ protected InputStream getContent(String uri, WebServiceCaller.CallType callType, HttpResponse response) throws IOException { return response.getEntity().getContent(); } /** * @param methodUriPrefix * the prefix of the URI * @param methodUriSuffix * the suffix of the URI, not containing the query parameters. A <code>/</code> will split the methodUriPrefix and methodUriSuffix * parameters in the final URI * @param uriParameters * a map of key/values that will be used as query parameters in the final URI * @return a properly encoded URI */ public final String computeUri(String methodUriPrefix, String methodUriSuffix, Map<String, String> uriParameters) { return WebServiceCaller.encodeUri(methodUriPrefix, methodUriSuffix, uriParameters, getUrlEncoding()); } public static String encodeUri(String methodUriPrefix, String methodUriSuffix, Map<String, String> uriParameters, String urlEnconding) { final StringBuffer buffer = new StringBuffer(methodUriPrefix); if (methodUriSuffix != null && methodUriSuffix.length() > 0) { buffer.append("/").append(methodUriSuffix); } boolean first = true; if (uriParameters != null) { for (Entry<String, String> entry : uriParameters.entrySet()) { if (first == true) { buffer.append("?"); first = false; } else { buffer.append("&"); } try { buffer.append(entry.getKey()).append("=").append(URLEncoder.encode(entry.getValue(), urlEnconding)); } catch (UnsupportedEncodingException exception) { if (log.isErrorEnabled()) { log.error("Cannot encode properly the URI", exception); } return null; } } } final String uri = buffer.toString(); return uri; } final public WSUriStreamParser.UrlWithCallTypeAndBody computeUrlWithCallTypeAndBody(String methodUriPrefix, String methodUriSuffix, Map<String, String> uriParameters) { return new WSUriStreamParser.UrlWithCallTypeAndBody(computeUri(methodUriPrefix, methodUriSuffix, uriParameters)); } /** * We cannot use the same object because of the multi-threading. */ protected DefaultHttpClient getHttpClient() { return new DefaultHttpClient(); } }
package com.valkryst.VTerminal.misc; import java.awt.Point; import java.util.ArrayList; import java.util.List; public final class ShapeAlgorithms { // Prevent users from creating an instance. private ShapeAlgorithms() {} /** * Constructs a list, containing the outline, of an ellipse's points * by using the Bresenham algorithm, * * @param x * The x-axis (column) coordinate of the top-left character. * * @param y * The y-axis (row) coordinate of the top-left character. * * @param width * The width. * * @param height * The height. * * @return * The list of points. */ public static List<Point> getEllipse(final int x, final int y, final int width, final int height) { final List<Point> points = new ArrayList<>(); int a2 = width * width; int b2 = height * height; int fa2 = 4 * a2; int fb2 = 4 * b2; int dx = 0; int dy = height; int sigma = 2 * b2 + a2 * (1 - 2 * height); while (b2 * dx <= a2 * dy) { points.add(new Point(x + dx, y + dy)); points.add(new Point(x - dx, y + dy)); points.add(new Point(x + dx, y - dy)); points.add(new Point(x - dx, y - dy)); if (sigma >= 0) { sigma += fa2 * (1 - dy); dy } sigma += b2 * ((4 * dx) + 6); dx++; } dx = width; dy = 0; sigma = 2 * a2 + b2 * (1 - 2 * width); while (a2 * dy <= b2 * dx) { points.add(new Point(x + dx, y + dy)); points.add(new Point(x - dx, y + dy)); points.add(new Point(x + dx, y - dy)); points.add(new Point(x - dx, y - dy)); if (sigma >= 0) { sigma += fb2 * (1 - dx); dx } sigma += a2 * ((4 * dy) + 6); dy++; } return points; } /** * Constructs a list, containing the path, of a line's points by * using the Bresenham algorithm, * * @param fromX * The x-axis (column) coordinate of the start point of the line. * * @param fromY * The y-axis (row) coordinate of the start point of the line. * * @param toX * The x-axis (column) coordinate of the end point of the line. * * @param toY * The y-axis (row) coordinate of the end point of the line. * * @return * The list of points. */ public static List<Point> getLine(int fromX, int fromY, final int toX, final int toY) { // Faster algorithm for vertical line: if (fromX == toX) { return getVerticalLine(fromX, fromY, toY); } // Faster algorithm for horizontal line: if (fromY == toY) { return getHorizontalLine(fromX, fromY, toX); } final List<Point> points = new ArrayList<>(); int m_new = 2 * (toY - fromY); int slope_error_new = m_new - (toX - fromX); for (int x = fromX, y = fromY ; x <= toX ; x++) { points.add(new Point(x, y)); slope_error_new += m_new; if (slope_error_new >= 0) { y++; slope_error_new -= 2 * (toX - fromX); } } return points; } /** * Constructs a list, containing the path, of a horizontal line's points, * * @param fromX * The x-axis (column) coordinate of the start point of the line. * * @param fromY * The y-axis (row) coordinate of the start point of the line. * * @param toX * The x-axis (column) coordinate of the end point of the line. * * @return * The list of points. */ public static List<Point> getHorizontalLine(final int fromX, final int fromY, final int toX) { final List<Point> points = new ArrayList<>(); if (fromX < toX) { for (int x = fromX; x < toX; x++) { points.add(new Point(x, fromY)); } } else { for (int x = toX; x < fromX; x++) { points.add(new Point(x, fromY)); } } return points; } /** * Constructs a list, containing the path, of a vertical line's points, * * @param fromX * The x-axis (column) coordinate of the start point of the line. * * @param fromY * The y-axis (row) coordinate of the start point of the line. * * @param toY * The y-axis (row) coordinate of the end point of the line. * * @return * The list of points. */ public static List<Point> getVerticalLine(final int fromX, final int fromY, final int toY) { final List<Point> points = new ArrayList<>(); if (fromY < toY) { for (int y = fromY; y < toY; y++) { points.add(new Point(fromX, y)); } } else { for (int y = toY; y < fromY; y++) { points.add(new Point(fromX, y)); } } return points; } /** * Constructs a list, containing the outline, of a rectangle's points, * * @param x * The x-axis (column) coordinate of the top-left character. * * @param y * The y-axis (row) coordinate of the top-left character. * * @param width * The width. * * @param height * The height. * * @return * The list of points. */ public static List<Point> getRectangle(final int x, final int y, final int width, final int height) { final List<Point> points = new ArrayList<>(); final int lastRow = y + height - 1; final int lastColumn = x + width - 1; // Corners: points.add(new Point(x, y)); points.add(new Point(lastColumn, y)); points.add(new Point(x, lastRow)); points.add(new Point(lastColumn, lastRow)); // Left/Right Sides: for (int i = 1 ; i < height - 1 ; i++) { points.add(new Point(x, y + i)); points.add(new Point(lastColumn, y + i)); } // Top/Bottom Sides: for (int i = 1 ; i < width - 1 ; i++) { points.add(new Point(x + i, y)); points.add(new Point(x + i, lastRow)); } return points; } }
package com.heanthor.printer.utils; import javax.imageio.ImageIO; import java.awt.*; import java.awt.color.ColorSpace; import java.awt.color.ICC_ColorSpace; import java.awt.color.ICC_Profile; import java.awt.image.*; import java.io.File; import java.io.IOException; import java.util.HashMap; /** * @author reedt */ public class ImageUtils { /** * @param i RenderedImage to save, such as a BufferedImage * @param filename Name to give the file (sans extension) e.g. "image01" * @param format Extension to give the file e.g. "png" * @return Success or failure of save operation */ public static boolean saveToFile(RenderedImage i, String filename, String format) { if (format.contains(".")) { throw new IllegalArgumentException("Format string format incorrect"); } if (filename.contains(".")) { throw new IllegalArgumentException("Filename format incorrect"); } try { return ImageIO.write(i, format, new File(filename + "." + format)); } catch (IOException e) { e.printStackTrace(); } return false; } public static BufferedImage loadImageFromFile(String filePath) { BufferedImage img = null; try { img = ImageIO.read(new File("strawberry.jpg")); } catch (IOException e) { e.printStackTrace(); } return img; } /** * Converts a given Image into a BufferedImage * * @param img The Image to be converted * @return The converted BufferedImage */ public static BufferedImage toBufferedImage(Image img) { if (img instanceof BufferedImage) { return (BufferedImage) img; } // Create a buffered image with transparency BufferedImage bimage = new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_ARGB); // Draw the image on to the buffered image Graphics2D bGr = bimage.createGraphics(); bGr.drawImage(img, 0, 0, null); bGr.dispose(); // Return the buffered image return bimage; } public static BufferedImage resizeImage(BufferedImage i, int newWidth, int newHeight) { return toBufferedImage(i.getScaledInstance(newWidth, newHeight, Image.SCALE_DEFAULT)); } /** * Approximate conversion from RGBA to CMYKA * * @param in BufferedImage to convert * @return Float array of [row][col][cmyka] pixel data. */ public static float[][][] rgbToCMYK(BufferedImage in) { long start = System.currentTimeMillis(); ColorConverter cc = new ColorConverter(); float[][][] result = cc.rgbToCMYK(in); long dur = System.currentTimeMillis() - start; System.out.println("Converted in " + dur + " milis."); return result; } /** * Convert between two color profiles */ private static class ColorConverter { private HashMap<RGBColor, CMYKColor> cache = new HashMap<>(); private float[][][] rgbToCMYK(BufferedImage in) { int[][] imageInBytes = intArrayFromBufferedImage(in); float[][][] cmykImage = new float[imageInBytes.length][imageInBytes[0].length][5]; for (int i = 0; i < imageInBytes.length; i++) { for (int j = 0; j < imageInBytes[i].length; j++) { int a = (imageInBytes[i][j] >> 24) & 0xff; int r = (imageInBytes[i][j] & (0xff << 16)) >> 16; int g = (imageInBytes[i][j] & (0xff << 8)) >> 8; int b = imageInBytes[i][j] & 0xff; // for CMYK alpha float alpha = (float) a / 255; RGBColor tempRGB = new RGBColor(r, g, b, a); // check cache before converting if (cache.containsKey(tempRGB)) { CMYKColor tempCMYK = cache.get(tempRGB); float[] temp = tempCMYK.getCMYKA(); cmykImage[i][j] = new float[]{temp[0], temp[1], temp[2], temp[3], alpha}; System.out.println("Use cache for " + tempRGB.toString()); } else { try { float[] cmyk = rgbToCmyk((float) r / 255, (float) g / 255, (float) b / 255, (float) a / 255); cmykImage[i][j] = new float[]{cmyk[0], cmyk[1], cmyk[2], cmyk[3], alpha}; CMYKColor cmykColor = new CMYKColor(cmyk[0], cmyk[1], cmyk[2], cmyk[3], alpha); cache.put(tempRGB, cmykColor); System.out.println("Convert " + tempRGB.toString() + " " + cmykColor.toString()); } catch (IOException e) { e.printStackTrace(); } } } } return cmykImage; } private int[][] intArrayFromBufferedImage(BufferedImage image) { final int[] pixels = ((DataBufferInt) image.getRaster().getDataBuffer()).getData(); final int width = image.getWidth(); final int height = image.getHeight(); final boolean hasAlphaChannel = image.getAlphaRaster() != null; int[][] result = new int[height][width]; if (hasAlphaChannel) { for (int pixel = 0, row = 0, col = 0; pixel < pixels.length; pixel++) { result[row][col] = pixels[pixel]; col++; if (col == width) { col = 0; row++; } } } else { for (int pixel = 0, row = 0, col = 0; pixel < pixels.length; pixel++) { int argb = 0; argb += -16777216; // 255 alpha argb += (pixels[pixel] & 0xff); // blue argb += ((pixels[pixel] >> 8) & 0xff) << 8; // green argb += ((pixels[pixel] >> 16) & 0xff) << 16; // red result[row][col] = argb; col++; if (col == width) { col = 0; row++; } } } return result; } private float[] rgbToCmyk(float... rgb) throws IOException { String path = "C:\\Users\\reedt\\Dropbox\\IntelliJ Git\\sidewalk-printer\\resources\\icc_profiles\\USWebCoatedSWOP.icc"; if (rgb.length != 4) { throw new IllegalArgumentException("Need RGBA"); } ColorSpace csrgb = ColorSpace.getInstance(ColorSpace.CS_sRGB); //System.out.println("Min: " + csrgb.getMinValue(0) + ", max: " + csrgb.getMaxValue(0)); float[] ciexyz = csrgb.toCIEXYZ(rgb); ColorSpace instance = new ICC_ColorSpace(ICC_Profile.getInstance(path)); return instance.fromCIEXYZ(ciexyz); } } /** * Encapsulate RBG color + alpha */ private static class RGBColor { private int r; private int g; private int b; private int a; RGBColor(int r, int g, int b, int a) { this.r = r; this.g = g; this.b = b; this.a = a; } public int[] getRGBA() { return new int[]{r, g, b, a}; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; RGBColor rgbColor = (RGBColor) o; return r == rgbColor.r && g == rgbColor.g && b == rgbColor.b && a == rgbColor.a; } @Override public int hashCode() { int result = r; result = 31 * result + g; result = 31 * result + b; result = 31 * result + a; return result; } @Override public String toString() { return "RGBA: (" + r + ", " + g + ", " + b + ", " + a + ")"; } } /** * Encapsulate CMYK color + alpha */ private static class CMYKColor { private float c; private float m; private float y; private float k; private float a; CMYKColor(float c, float m, float y, float k, float a) { this.c = c; this.m = m; this.y = y; this.k = k; this.a = a; } float[] getCMYKA() { return new float[]{c, m, y, k, a}; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; CMYKColor cmykColor = (CMYKColor) o; return c == cmykColor.c && m == cmykColor.m && y == cmykColor.y && k == cmykColor.k && a == cmykColor.a; } @Override public int hashCode() { float result = c; result = 31 * result + m; result = 31 * result + y; result = 31 * result + k; result = 31 * result + a; return (int) result; } @Override public String toString() { return "CMYK: (" + c + ", " + m + ", " + y + ", " + k + ", " + a + ")"; } } }
package com.valkryst.generator; import com.valkryst.VParser_CFG.ContextFreeGrammar; import java.util.List; public final class GrammarNameGenerator implements NameGenerator{ /** The CFG to generate names with. */ private final ContextFreeGrammar contextFreeGrammar; public GrammarNameGenerator(final List<String> rules) { contextFreeGrammar = new ContextFreeGrammar(rules); } @Override public String generateName(final int length) { String longestResult = ""; for (int i = 0 ; i < 100 ; i++) { final String tmp = contextFreeGrammar.run(); if (tmp.length() > longestResult.length()) { longestResult = tmp; } if (tmp.length() > length) { longestResult = tmp.substring(0, length); break; } if (tmp.length() == length) { longestResult = tmp; break; } } return longestResult; } }
package com.irccloud.android; import java.util.Timer; import java.util.TimerTask; import org.json.JSONObject; import android.annotation.SuppressLint; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.PackageManager.NameNotFoundException; import android.util.Log; import com.google.android.gcm.GCMBaseIntentService; import com.google.android.gcm.GCMRegistrar; public class GCMIntentService extends GCMBaseIntentService { public static final String GCM_ID = ""; public static int versionCode() { int code = 0; try { code = IRCCloudApplication.getInstance().getPackageManager().getPackageInfo("com.irccloud.android", 0).versionCode; } catch (NameNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } return code; } @Override protected void onError(Context context, String errorId) { Log.e("IRCCloud", "GCM Error: " + errorId); } @SuppressLint("NewApi") @Override protected void onMessage(Context context, Intent intent) { Log.i("IRCCloud", "Recieved GCM message!"); if(intent != null && intent.getExtras() != null) { Log.d("IRCCloud", "GCM K/V pairs: " + intent.getExtras().toString()); try { int cid = Integer.valueOf(intent.getStringExtra("cid")); int bid = Integer.valueOf(intent.getStringExtra("bid")); long eid = Long.valueOf(intent.getStringExtra("eid")); if(Notifications.getInstance().getNotification(eid) != null) { Log.d("IRCCloud", "A notification for this event already exists in the db, ignoring"); return; } String from = intent.getStringExtra("from_nick"); String msg = intent.getStringExtra("msg"); String chan = intent.getStringExtra("chan"); if(chan == null) chan = ""; String type = intent.getStringExtra("type"); String buffer_type = intent.getStringExtra("buffer_type"); String server_name = intent.getStringExtra("server_name"); if(server_name == null || server_name.length() == 0) server_name = intent.getStringExtra("server_hostname"); Notifications.Network network = Notifications.getInstance().getNetwork(cid); if(network == null) Notifications.getInstance().addNetwork(cid, server_name); Notifications.getInstance().deleteNotification(cid, bid, eid); Notifications.getInstance().addNotification(cid, bid, eid, from, msg, chan, buffer_type, type); if(buffer_type.equals("channel")) Notifications.getInstance().showNotifications(chan + ": <" + from + "> " + ColorFormatter.html_to_spanned(msg)); else Notifications.getInstance().showNotifications(from + ": " + ColorFormatter.html_to_spanned(msg)); } catch (Exception e) { e.printStackTrace(); Log.w("IRCCloud", "Unable to parse GCM message"); } } } public static void scheduleRegisterTimer(int delay) { final int retrydelay = delay; new Timer().schedule(new TimerTask() { @Override public void run() { boolean success = false; try { JSONObject result = NetworkConnection.getInstance().registerGCM(GCMRegistrar.getRegistrationId(IRCCloudApplication.getInstance().getApplicationContext())); if(result.has("success")) success = result.getBoolean("success"); } catch (Exception e) { e.printStackTrace(); } if(success) { SharedPreferences.Editor editor = IRCCloudApplication.getInstance().getApplicationContext().getSharedPreferences("prefs", 0).edit(); editor.putBoolean("gcm_registered", true); editor.commit(); } else { Log.e("IRCCloud", "Failed to register device ID, will retry in " + ((retrydelay*2)/1000) + " seconds"); //scheduleRegisterTimer(retrydelay * 2); } } }, delay); } @Override protected void onRegistered(Context context, String regId) { Log.i("IRCCloud", "GCM registered, id: " + regId); scheduleRegisterTimer(30000); SharedPreferences.Editor editor = getSharedPreferences("prefs", 0).edit(); editor.putInt("GCM_VERSION", versionCode()); editor.commit(); } @Override protected void onUnregistered(Context context, String regId) { Log.i("IRCCloud", "GCM unregistered, id: " + regId); SharedPreferences.Editor editor = getSharedPreferences("prefs", 0).edit(); editor.remove("gcm_registered"); editor.commit(); if(getSharedPreferences("prefs", 0).contains("session_key") && getSharedPreferences("prefs", 0).getInt("GCM_VERSION", 0) != versionCode()) GCMRegistrar.register(this, GCM_ID); } }
package me.nallar.patched.storage; import java.util.ArrayList; import java.util.List; import java.util.Set; import java.util.concurrent.locks.Lock; import java.util.logging.Level; import cpw.mods.fml.common.FMLLog; import me.nallar.tickthreading.Log; import me.nallar.tickthreading.patcher.Declare; import me.nallar.tickthreading.util.concurrent.TwoWayReentrantReadWriteLock; import net.minecraft.block.Block; import net.minecraft.entity.Entity; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.AxisAlignedBB; import net.minecraft.util.MathHelper; import net.minecraft.world.ChunkPosition; import net.minecraft.world.World; import net.minecraft.world.WorldServer; import net.minecraft.world.chunk.Chunk; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.event.entity.EntityEvent; import net.minecraftforge.event.world.ChunkEvent; import org.cliffc.high_scale_lib.NonBlockingHashMap; @SuppressWarnings ("unchecked") public abstract class PatchChunk extends Chunk { @Declare public boolean unloading_; @Declare public boolean alreadySavedAfterUnload_; public Lock entityListWriteLock; public Lock entityListReadLock; public PatchChunk(World par1World, int par2, int par3) { super(par1World, par2, par3); } private List<TileEntity> toInvalidate; public void construct() { chunkTileEntityMap = new NonBlockingHashMap(); toInvalidate = new ArrayList<TileEntity>(); TwoWayReentrantReadWriteLock twoWayReentrantReadWriteLock = new TwoWayReentrantReadWriteLock(); entityListWriteLock = twoWayReentrantReadWriteLock.writeLock(); entityListReadLock = twoWayReentrantReadWriteLock.readLock(); } @Override public String toString() { return "chunk at " + xPosition + ',' + zPosition; } @SuppressWarnings ("FieldRepeatedlyAccessedInMethod") // Patcher makes entityLists final @Override @Declare public void getEntitiesWithinAABBForEntity(Entity excludedEntity, AxisAlignedBB collisionArea, List collidingAABBs, int limit) { entityListReadLock.lock(); try { int var4 = MathHelper.floor_double((collisionArea.minY - World.MAX_ENTITY_RADIUS) / 16.0D); int var5 = MathHelper.floor_double((collisionArea.maxY + World.MAX_ENTITY_RADIUS) / 16.0D); if (var4 < 0) { var4 = 0; } if (var5 >= this.entityLists.length) { var5 = this.entityLists.length - 1; } for (int var6 = var4; var6 <= var5; ++var6) { List var7 = this.entityLists[var6]; for (Object aVar7 : var7) { Entity var9 = (Entity) aVar7; if (var9 != excludedEntity && var9.boundingBox.intersectsWith(collisionArea)) { collidingAABBs.add(var9); if (--limit == 0) { return; } Entity[] var10 = var9.getParts(); if (var10 != null) { for (Entity aVar10 : var10) { var9 = aVar10; if (var9 != excludedEntity && var9.boundingBox.intersectsWith(collisionArea)) { collidingAABBs.add(var9); if (--limit == 0) { return; } } } } } } } } finally { entityListReadLock.unlock(); } } @Override public void addTileEntity(TileEntity tileEntity) { int x = tileEntity.xCoord - this.xPosition * 16; int y = tileEntity.yCoord; int z = tileEntity.zCoord - this.zPosition * 16; if (this.isChunkLoaded) { this.setChunkBlockTileEntity(x, y, z, tileEntity); this.worldObj.addTileEntity(tileEntity); } else { ChunkPosition chunkPosition = new ChunkPosition(x, y, z); tileEntity.setWorldObj(this.worldObj); Block block = Block.blocksList[getBlockID(x, y, z)]; if (block != null && block.hasTileEntity(getBlockMetadata(x, y, z))) { TileEntity old = (TileEntity) chunkTileEntityMap.put(chunkPosition, tileEntity); if (old != null) { toInvalidate.add(old); } } } } @SuppressWarnings ("FieldRepeatedlyAccessedInMethod") // Patcher makes worldObj final @Override public void onChunkUnload() { Set<TileEntity> removalSet = worldObj.tileEntityRemovalSet; for (TileEntity var2 : (Iterable<TileEntity>) this.chunkTileEntityMap.values()) { removalSet.add(var2); } for (List entityList : this.entityLists) { this.worldObj.unloadEntities(entityList); } MinecraftForge.EVENT_BUS.post(new ChunkEvent.Unload(this)); } @Override public void onChunkLoad() { for (TileEntity tileEntity : toInvalidate) { tileEntity.invalidate(); } toInvalidate.clear(); } @SuppressWarnings ("FieldRepeatedlyAccessedInMethod") // Patcher makes worldObj final @Override @Declare public void threadUnsafeChunkLoad() { this.isChunkLoaded = true; worldObj.addTileEntity(this.chunkTileEntityMap.values()); for (List entityList : this.entityLists) { worldObj.addLoadedEntities(entityList); } MinecraftForge.EVENT_BUS.post(new ChunkEvent.Load(this)); } @SuppressWarnings ("FieldRepeatedlyAccessedInMethod") // Patcher makes x/zPosition and worldObj final @Override public void addEntity(Entity par1Entity) { int var2 = MathHelper.floor_double(par1Entity.posX / 16.0D); int var3 = MathHelper.floor_double(par1Entity.posZ / 16.0D); if (var2 != this.xPosition || var3 != this.zPosition) { FMLLog.log(Level.FINE, new Throwable(), "Entity %s added to the wrong chunk - expected x%d z%d, got x%d z%d", par1Entity.toString(), this.xPosition, this.zPosition, var2, var3); if (worldObj instanceof WorldServer) { Chunk correctChunk = ((WorldServer) worldObj).theChunkProviderServer.getChunkIfExists(xPosition, zPosition); if (correctChunk == this) { Log.severe("What?! This chunk isn't at the position it says it's at...: " + this + " was added at " + xPosition + ", " + zPosition); } else if (correctChunk != null) { correctChunk.addEntity(par1Entity); return; } } } this.hasEntities = true; int var4 = MathHelper.floor_double(par1Entity.posY / 16.0D); if (var4 < 0) { var4 = 0; } if (var4 >= this.entityLists.length) { var4 = this.entityLists.length - 1; } MinecraftForge.EVENT_BUS.post(new EntityEvent.EnteringChunk(par1Entity, this.xPosition, this.zPosition, par1Entity.chunkCoordX, par1Entity.chunkCoordZ)); par1Entity.addedToChunk = true; par1Entity.chunkCoordX = this.xPosition; par1Entity.chunkCoordY = var4; par1Entity.chunkCoordZ = this.zPosition; this.entityLists[var4].add(par1Entity); } }
package com.thaiopensource.relaxng; import com.thaiopensource.datatype.Datatype; import com.thaiopensource.datatype.DatatypeContext; class StringAtom extends Atom { private String str; private DatatypeContext dc; StringAtom(String str, DatatypeContext dc) { this.str = str; this.dc = dc; } boolean matchesString() { return true; } boolean matchesDatatypeValue(Datatype dt, Object obj) { return obj.equals(dt.createValue(str, dc)); } boolean matchesDatatype(Datatype dt) { return dt.allows(str, dc); } String getStringValue() { return str; } DatatypeContext getDatatypeContext() { return dc; } String getString() { return str; } }
package org.nuxeo.connect.client.jsf; import java.io.Serializable; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Properties; import java.util.TimeZone; import javax.faces.context.FacesContext; import javax.faces.model.SelectItem; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.jboss.seam.ScopeType; import org.jboss.seam.annotations.In; import org.jboss.seam.annotations.Name; import org.jboss.seam.annotations.Scope; import org.jboss.seam.faces.FacesMessages; import org.jboss.seam.international.StatusMessage; import org.nuxeo.connect.client.ui.SharedPackageListingsSettings; import org.nuxeo.connect.client.vindoz.InstallAfterRestart; import org.nuxeo.connect.client.we.StudioSnapshotHelper; import org.nuxeo.connect.data.DownloadablePackage; import org.nuxeo.connect.data.DownloadingPackage; import org.nuxeo.connect.packages.PackageManager; import org.nuxeo.connect.packages.dependencies.DependencyResolution; import org.nuxeo.connect.update.LocalPackage; import org.nuxeo.connect.update.PackageDependency; import org.nuxeo.connect.update.PackageState; import org.nuxeo.connect.update.PackageType; import org.nuxeo.connect.update.PackageUpdateService; import org.nuxeo.connect.update.ValidationStatus; import org.nuxeo.connect.update.task.Task; import org.nuxeo.ecm.admin.AdminViewManager; import org.nuxeo.ecm.admin.runtime.PlatformVersionHelper; import org.nuxeo.ecm.admin.setup.SetupWizardActionBean; import org.nuxeo.ecm.platform.ui.web.util.ComponentUtils; import org.nuxeo.ecm.webapp.seam.NuxeoSeamHotReloadContextKeeper; import org.nuxeo.launcher.config.ConfigurationGenerator; import org.nuxeo.runtime.api.Framework; /** * Manages JSF views for Package Management. * * @author <a href="mailto:td@nuxeo.com">Thierry Delprat</a> */ @Name("appsViews") @Scope(ScopeType.CONVERSATION) public class AppCenterViewsManager implements Serializable { private static final long serialVersionUID = 1L; protected static final Log log = LogFactory.getLog(AppCenterViewsManager.class); protected enum SnapshotStatus { downloading, saving, installing, error, completed, restartNeeded; } protected static final Map<String, String> view2PackageListName = new HashMap<String, String>() { private static final long serialVersionUID = 1L; { put("ConnectAppsUpdates", "updates"); put("ConnectAppsStudio", "studio"); put("ConnectAppsRemote", "remote"); put("ConnectAppsLocal", "local"); } }; @In(create = true) protected String currentAdminSubViewId; @In(create = true) protected NuxeoSeamHotReloadContextKeeper seamReloadContext; @In(create = true) protected SetupWizardActionBean setupWizardAction; @In(create = true, required = false) protected FacesMessages facesMessages; @In(create = true) protected Map<String, String> messages; protected String searchString; protected SnapshotStatus studioSnapshotStatus; protected int studioSnapshotDownloadProgress; protected boolean isStudioSnapshopUpdateInProgress = false; // FIXME: this should be persisted instead of being local to the seam // component, as other potential users will not see the same information in // the admin center protected Calendar lastStudioSnapshotUpdate; protected String studioSnapshotUpdateError; /** * Boolean indicating is Studio snapshot package validation should be done. * * @since 5.7.1 */ protected Boolean validateStudioSnapshot; /** * Last validation status of the Studio snapshot package * * @since 5.7.1 */ protected ValidationStatus studioSnapshotValidationStatus; public String getSearchString() { if (searchString == null) { return ""; } return searchString; } public void setSearchString(String searchString) { this.searchString = searchString; } public boolean getOnlyRemote() { return SharedPackageListingsSettings.instance().get("remote").isOnlyRemote(); } public void setOnlyRemote(boolean onlyRemote) { SharedPackageListingsSettings.instance().get("remote").setOnlyRemote( onlyRemote); } protected String getListName() { return view2PackageListName.get(currentAdminSubViewId); } public void setPlatformFilter(boolean doFilter) { SharedPackageListingsSettings.instance().get(getListName()).setPlatformFilter( doFilter); } public boolean getPlatformFilter() { return SharedPackageListingsSettings.instance().get(getListName()).getPlatformFilter(); } public String getPackageTypeFilter() { return SharedPackageListingsSettings.instance().get(getListName()).getPackageTypeFilter(); } public void setPackageTypeFilter(String filter) { SharedPackageListingsSettings.instance().get(getListName()).setPackageTypeFilter( filter); } public List<SelectItem> getPackageTypes() { List<SelectItem> types = new ArrayList<SelectItem>(); SelectItem allItem = new SelectItem("", "label.packagetype.all"); types.add(allItem); for (PackageType ptype : PackageType.values()) { // if (!ptype.equals(PackageType.STUDIO)) { SelectItem item = new SelectItem(ptype.getValue(), "label.packagetype." + ptype.getValue()); types.add(item); } return types; } public void flushCache() { PackageManager pm = Framework.getLocalService(PackageManager.class); pm.flushCache(); } /** * Method binding for the update button: needs to perform a real * redirection (as ajax context is broken after hot reload) and to provide * an outcome so that redirection through the URL service goes ok (even if * it just reset its navigation handler cache). * * @since 5.6 */ public String installStudioSnapshotAndRedirect() throws Exception { installStudioSnapshot(); return AdminViewManager.VIEW_ADMIN; } public void installStudioSnapshot() throws Exception { if (isStudioSnapshopUpdateInProgress) { return; } PackageManager pm = Framework.getLocalService(PackageManager.class); List<DownloadablePackage> pkgs = pm.listAllStudioRemotePackages(); DownloadablePackage snapshotPkg = StudioSnapshotHelper.getSnapshot(pkgs); studioSnapshotUpdateError = null; resetStudioSnapshotValidationStatus(); if (snapshotPkg != null) { isStudioSnapshopUpdateInProgress = true; try { StudioAutoInstaller studioAutoInstaller = new StudioAutoInstaller( pm, snapshotPkg.getId(), shouldValidateStudioSnapshot()); studioAutoInstaller.run(); } finally { isStudioSnapshopUpdateInProgress = false; } } else { studioSnapshotUpdateError = translate("label.studio.update.error.noSnapshotPackageFound"); } } public boolean isStudioSnapshopUpdateInProgress() { return isStudioSnapshopUpdateInProgress; } /** * Returns true if validation should be performed * * @since 5.7.1 */ public Boolean getValidateStudioSnapshot() { return validateStudioSnapshot; } /** * @since 5.7.1 */ public void setValidateStudioSnapshot(Boolean validateStudioSnapshot) { this.validateStudioSnapshot = validateStudioSnapshot; } /** * Returns true if Studio snapshot module should be validated. * <p> * Validation can be skipped by user, or can be globally disabled by * setting framework property "studio.snapshot.disablePkgValidation" to * true. * * @since 5.7.1 */ protected boolean shouldValidateStudioSnapshot() { if (Framework.isBooleanPropertyTrue("studio.snapshot.disablePkgValidation")) { return false; } return Boolean.TRUE.equals(getValidateStudioSnapshot()); } protected static String translate(String label, Object... params) { return ComponentUtils.translate(FacesContext.getCurrentInstance(), label, params); } protected String getLastUpdateDate() { DateFormat df = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US); df.setTimeZone(TimeZone.getTimeZone("GMT")); return df.format(lastStudioSnapshotUpdate.getTime()); } public String getStudioInstallationStatus() { String prefix = "label.studio.update.status."; if (studioSnapshotStatus == null) { // TODO: should initialize status according to Studio snapshot // package installation return translate(prefix + "noStatus"); } Object[] params = new Object[0]; if (SnapshotStatus.error.equals(studioSnapshotStatus)) { if (studioSnapshotUpdateError == null) { studioSnapshotUpdateError = "???"; } params = new Object[] { studioSnapshotUpdateError }; } else if (SnapshotStatus.downloading.equals(studioSnapshotStatus)) { params = new Object[] { String.valueOf(studioSnapshotDownloadProgress) }; } else if (SnapshotStatus.completed.equals(studioSnapshotStatus) || SnapshotStatus.restartNeeded.equals(studioSnapshotStatus)) { params = new Object[] { getLastUpdateDate() }; } return translate(prefix + studioSnapshotStatus.name(), params); } // TODO: plug a notifier for status to be shown to the user protected class StudioAutoInstaller implements Runnable { protected final String packageId; protected final PackageManager pm; /** * @since 5.7.1 */ protected final boolean validate; protected StudioAutoInstaller(PackageManager pm, String packageId, boolean validate) { this.pm = pm; this.packageId = packageId; this.validate = validate; } @Override public void run() { try { setStatus(SnapshotStatus.downloading, null); PackageUpdateService pus = Framework.getLocalService(PackageUpdateService.class); LocalPackage lpkg = pus.getPackage(packageId); boolean hadPackage = lpkg != null && PackageState.getByValue(lpkg.getState()).isInstalled(); String pkgId; // avoid downloading again the Studio package for debug, maybe // should avoid downloading it again if validation is skipped // too, in case package has changed (?) boolean avoidDownload = false; if (avoidDownload) { pkgId = packageId; } else { DownloadingPackage pkg = pm.download(packageId); while (!pkg.isCompleted()) { try { studioSnapshotDownloadProgress = pkg.getDownloadProgress(); Thread.sleep(100); log.debug("downloading studio snapshot package"); } catch (InterruptedException e) { // NOP } } log.debug("studio snapshot package download completed, starting installation"); try { Thread.sleep(200); } catch (InterruptedException e) { // NOP } setStatus(SnapshotStatus.saving, null); try { while (pus.getPackage(pkg.getId()) == null) { try { studioSnapshotDownloadProgress = pkg.getDownloadProgress(); Thread.sleep(50); log.debug("downloading studio snapshot package"); } catch (InterruptedException e) { // NOP } } } catch (Exception e) { log.error( "Error while sending studio snapshot to update manager", e); setStatus( SnapshotStatus.error, translate( "label.studio.update.downloading.error", e.getMessage())); return; } pkgId = pkg.getId(); } lpkg = pus.getPackage(pkgId); String[] targetPlatforms = lpkg.getTargetPlatforms(); PackageDependency[] pkgDeps = lpkg.getDependencies(); if (validate) { ValidationStatus status = new ValidationStatus(); // TODO: replace errors by internationalized labels if (!PlatformVersionHelper.isCompatible(targetPlatforms)) { status.addError(String.format( "This package is not validated for your current platform: %s", PlatformVersionHelper.getPlatformFilter())); } // check deps requirements if (pkgDeps != null && pkgDeps.length > 0) { DependencyResolution resolution = pm.resolveDependencies( pkgId, PlatformVersionHelper.getPlatformFilter()); if (resolution.isFailed() && PlatformVersionHelper.getPlatformFilter() != null) { // retry without PF filter ... resolution = pm.resolveDependencies(pkgId, null); } if (resolution.isFailed()) { status.addError(String.format( "Dependency check has failed for package '%s'", pkgId)); } else { List<String> pkgToInstall = resolution.getInstallPackageIds(); if (pkgToInstall != null && pkgToInstall.size() == 1 && packageId.equals(pkgToInstall.get(0))) { // ignore } else if (resolution.requireChanges()) { status.addError(resolution.toString().trim().replaceAll( "\n", "<br />")); } } } if (Framework.isDevModeSet() && hadPackage) { status.addWarning("Your previous installation of this Studio" + " package has already been uninstalled"); } if (status.hasErrors()) { setStatus( SnapshotStatus.error, translate("label.studio.update.validation.error"), status); return; } } if (Framework.isDevModeSet()) { setStatus(SnapshotStatus.installing, null); try { Task installTask = lpkg.getInstallTask(); installTask.run(new HashMap<String, String>()); lastStudioSnapshotUpdate = Calendar.getInstance(); setStatus(SnapshotStatus.completed, null); } catch (Exception e) { log.error("Error while installing studio snapshot", e); setStatus( SnapshotStatus.error, translate( "label.studio.update.installation.error", e.getMessage())); } } else { InstallAfterRestart.addPackageForInstallation(pkgId); lastStudioSnapshotUpdate = Calendar.getInstance(); setStatus(SnapshotStatus.restartNeeded, null); setupWizardAction.setNeedsRestart(true); } } catch (Exception e) { setStatus(SnapshotStatus.error, e.getMessage()); } } } protected void setStatus(SnapshotStatus status, String errorMessage) { studioSnapshotStatus = status; studioSnapshotUpdateError = errorMessage; } protected void setStatus(SnapshotStatus status, String errorMessage, ValidationStatus validationStatus) { setStatus(status, errorMessage); setStudioSnapshotValidationStatus(validationStatus); } /** * @since 5.7.1 */ public ValidationStatus getStudioSnapshotValidationStatus() { return studioSnapshotValidationStatus; } /** * @since 5.7.1 */ public void setStudioSnapshotValidationStatus(ValidationStatus status) { this.studioSnapshotValidationStatus = status; } /** * @since 5.7.1 */ public void resetStudioSnapshotValidationStatus() { setStudioSnapshotValidationStatus(null); } public void setDevMode(boolean value) { String feedbackCompId = "changeDevModeForm"; ConfigurationGenerator conf = setupWizardAction.getConfigurationGenerator(); boolean configurable = conf.isConfigurable(); if (!configurable) { facesMessages.addToControl( feedbackCompId, StatusMessage.Severity.ERROR, translate("label.setup.nuxeo.org.nuxeo.dev.changingDevModeNotConfigurable")); return; } Map<String, String> params = new HashMap<String, String>(); params.put(Framework.NUXEO_DEV_SYSTEM_PROP, Boolean.toString(value)); try { conf.saveFilteredConfiguration(params); Properties props = conf.getUserConfig(); conf.getServerConfigurator().dumpProperties(props); // force reload of framework properties to ensure it's immediately // taken into account by all code checking for // Framework#isDevModeSet Framework.getRuntime().reloadProperties(); if (value) { facesMessages.addToControl(feedbackCompId, StatusMessage.Severity.WARN, translate("label.admin.center.devMode.justActivated")); } else { facesMessages.addToControl(feedbackCompId, StatusMessage.Severity.INFO, translate("label.admin.center.devMode.justDisabled")); } } catch (Exception e) { log.error(e, e); facesMessages.addToControl( feedbackCompId, StatusMessage.Severity.ERROR, translate("label.admin.center.devMode.errorSaving", e.getMessage())); } finally { setupWizardAction.setNeedsRestart(true); setupWizardAction.resetParameters(); } } }
package com.thaiopensource.validate; import org.xml.sax.ContentHandler; import org.xml.sax.DTDHandler; /** * Validates an XML document with respect to a schema. The schema is * determined when the <code>Validator</code> is created and cannot be * changed. The XML document is provided to the <code>Validator</code> * by calling methods of the <code>ContentHandler</code> object returned * by <code>getContentHandler</code>; the methods must be called in * the sequence specified by the <code>ContentHandler</code> * interface. If the <code>getDTDHandler</code> method returns * a non-null object, then method calls must be made on it * reporting DTD information. * * <p>Any errors will be reported to the <code>ErrorHandler</code> * specified when the <code>Validator</code> was created. If, after the * call to the <code>endDocument</code> method, no errors have been * reported, then the XML document is valid. * * <p>A single <code>Validator</code> object is <em>not</em> safe for * concurrent access from multiple threads. A single * <code>ValidatorHandler</code> can be used to validate only a single * document at a time. * * <p>After completing validation of an XML document (i.e. after calling * the <code>endDocument</code> on the <code>ContentHandler</code>), * <code>reset</code> can be called to allow validation of another * document. The <code>reset</code> method may create new <code>ContentHandler</code> * and <code>DTDHandler</code> objects or may simply reinitialize the * state of the existing objects. Therefore, <code>getContentHandler</code> * and <code>getDTDHandler</code> must be called after <code>reset</code> * to retrieve the objects to which the XML document to be validated * must be provided. * * @author <a href="mailto:jjc@jclark.com">James Clark</a> */ public interface Validator { /** * Returns the ContentHandler that will receive the XML document. * Information about the XML document to be validated must be * reported by calling methods on the returned ContentHandler. * When validation of an XML document has been completed (either * endDocument() has been called or validation has been abandoned * prematurely), reset() must be called. If no calls are made * on the ContentHandler, then reset() need not be called. * Implementations should allocate resources that require * cleanup (e.g. threads, open files) lazily, typically * in startDocument(). * * This method does not change the state of the Validator: the same * object will always be returned unless <code>reset</code> is called. * * @see #reset() * @return a ContentHandler, never <code>null</code> */ ContentHandler getContentHandler(); /** * Returns a DTDHandler. Information about the DTD must be reported * by calling methods on the returned object, unless <code>null</code> * is returned. The same object will always be returned unless * <code>reset</code> is called: this method does not change the state * of the Validator. * * @return a DTDHandler, maybe <code>null</code> if DTD information is * not significant to the <code>Validator</code> */ DTDHandler getDTDHandler(); /** * Cleans up after validating a document. After completing validation * of a document, <code>reset</code> must be called. After calling * reset(), another document may be validated. Calling this method * may create new ContentHandler and DTDHandler objects or may simply * reinitialize the state of the existing objects. */ void reset(); }
package it.unibz.krdb.obda.owlrefplatform.core.abox; import it.unibz.krdb.obda.model.OBDADataFactory; import it.unibz.krdb.obda.model.impl.OBDADataFactoryImpl; import it.unibz.krdb.obda.owlrefplatform.core.ontology.*; import it.unibz.krdb.obda.owlrefplatform.core.ontology.imp.BasicDescriptionFactory; import it.unibz.krdb.obda.owlrefplatform.core.ontology.imp.DLLiterConceptInclusionImpl; import it.unibz.krdb.obda.owlrefplatform.core.ontology.imp.DLLiterRoleInclusionImpl; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.LinkedList; import java.util.List; /** * Prune Ontology for redundant assertions based on dependencies */ public class SemanticReduction { private static final Logger log = LoggerFactory.getLogger(SemanticReduction.class); private final DAG isa; private final DAG sigma; private final DAGChain isaChain; private final DAGChain sigmaChain; private final OBDADataFactory predicateFactory; private final DescriptionFactory descFactory; public SemanticReduction(DAG isa, DAG sigma) { this.isa = isa; this.sigma = sigma; this.isaChain = new DAGChain(isa); this.sigmaChain = new DAGChain(sigma); predicateFactory = OBDADataFactoryImpl.getInstance(); descFactory = new BasicDescriptionFactory(); } public List<Assertion> reduce() { log.debug("Starting semantic-reduction"); List<Assertion> rv = new LinkedList<Assertion>(); for (DAGNode node : isa.getClasses()) { // Ignore all edges from T if (node.getDescription().equals(DAG.thingConcept)) { continue; } for (DAGNode child : node.descendans) { if (!check_redundant(node, child)) { rv.add(new DLLiterConceptInclusionImpl( (ConceptDescription) child.getDescription(), (ConceptDescription) node.getDescription())); } } } for (DAGNode node : isa.getRoles()) { for (DAGNode child : node.descendans) { if (!check_redundant_role(node, child)) { rv.add(new DLLiterRoleInclusionImpl( (RoleDescription) child.getDescription(), (RoleDescription) node.getDescription())); } } } log.debug("Finished semantic-reduction {}", rv); return rv; } private boolean check_redundant_role(DAGNode parent, DAGNode child) { if (check_directly_redundant_role(parent, child)) return true; else { log.debug("Not directly redundant role {} {}", parent, child); for (DAGNode child_prime : parent.getChildren()) { if (!child_prime.equals(child) && check_directly_redundant_role(child_prime, child) && !check_redundant(child_prime, parent)) { return true; } } } log.debug("Not redundant role {} {}", parent, child); return false; } private boolean check_directly_redundant_role(DAGNode parent, DAGNode child) { RoleDescription parentDesc = (RoleDescription) parent.getDescription(); RoleDescription childDesc = (RoleDescription) child.getDescription(); ExistentialConceptDescription existParentDesc = descFactory.getExistentialConceptDescription( parentDesc.getPredicate(), parentDesc.isInverse() ); ExistentialConceptDescription existChildDesc = descFactory.getExistentialConceptDescription( childDesc.getPredicate(), childDesc.isInverse() ); DAGNode exists_parent = isa.getClassNode(existParentDesc); DAGNode exists_child = isa.getClassNode(existChildDesc); return check_directly_redundant(parent, child) && check_directly_redundant(exists_parent, exists_child); } private boolean check_redundant(DAGNode parent, DAGNode child) { if (check_directly_redundant(parent, child)) return true; else { for (DAGNode child_prime : parent.getChildren()) { if (!child_prime.equals(child) && check_directly_redundant(child_prime, child) && !check_redundant(child_prime, parent)) { return true; } } } return false; } private boolean check_directly_redundant(DAGNode parent, DAGNode child) { DAGNode sp = sigmaChain.chain().get(parent.getDescription()); DAGNode sc = sigmaChain.chain().get(child.getDescription()); DAGNode tc = isaChain.chain().get(child.getDescription()); if (sp == null || sc == null || tc == null) { return false; } return (sp.getChildren().contains(sc) && sc.descendans.containsAll(tc.descendans)); } }
package com.tzapps.tzpalette.data; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import android.graphics.Bitmap; public class PaletteData { private static final String TAG = "PaletteData"; private static final int THUMB_MAX_WIDTH = 500; private static final int THUMB_MAX_HEIGHT = 500; Bitmap mThumb; List<Integer> mColors; public PaletteData() { mThumb = null; mColors = new ArrayList<Integer>(); } public PaletteData(Bitmap thumb) { mThumb = thumb; mColors = new ArrayList<Integer>(); } public void setThumb(Bitmap thumb) { if (mThumb != null) mThumb.recycle(); int width = thumb.getWidth(); int height = thumb.getHeight(); int targetW = THUMB_MAX_WIDTH; int targetH = THUMB_MAX_HEIGHT; if (width <= targetW && height <= targetH) { mThumb = thumb; } else { float scale = 0.0f; if (width > height) { scale = ((float) targetW) / width; targetH = (int)Math.round(height * scale); } else { scale = ((float) targetH) / height; targetW = (int)Math.round(width * scale); } mThumb = Bitmap.createScaledBitmap(thumb, targetW, targetH, false); } } public Bitmap getThumb() { return mThumb; } public void addColor(int color) { mColors.add(color); } public void addColors(int[] colors, boolean reset) { if (colors == null) return; if (reset) mColors.clear(); for (int color : colors) addColor(color); } public int[] getColors() { int numOfColors = mColors.size(); int[] colors = new int[mColors.size()]; for (int i = 0; i < numOfColors; i++) { colors[i] = mColors.get(i); } Arrays.sort(colors); return colors; } public void clearColors() { mColors.clear(); } }
package org.eclipse.mylyn.bugzilla.tests; import java.io.File; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashSet; import java.util.List; import java.util.Set; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.mylyn.commons.net.AuthenticationCredentials; import org.eclipse.mylyn.commons.net.AuthenticationType; import org.eclipse.mylyn.internal.bugzilla.core.BugzillaAttribute; import org.eclipse.mylyn.internal.bugzilla.core.BugzillaClient; import org.eclipse.mylyn.internal.bugzilla.core.BugzillaCorePlugin; import org.eclipse.mylyn.internal.bugzilla.core.IBugzillaConstants; import org.eclipse.mylyn.internal.context.core.ContextCorePlugin; import org.eclipse.mylyn.internal.tasks.core.RepositoryQuery; import org.eclipse.mylyn.internal.tasks.core.data.FileTaskAttachmentSource; import org.eclipse.mylyn.internal.tasks.ui.TasksUiPlugin; import org.eclipse.mylyn.internal.tasks.ui.util.AttachmentUtil; import org.eclipse.mylyn.internal.tasks.ui.util.TasksUiInternal; import org.eclipse.mylyn.tasks.core.ITask; import org.eclipse.mylyn.tasks.core.ITask.PriorityLevel; import org.eclipse.mylyn.tasks.core.ITask.SynchronizationState; import org.eclipse.mylyn.tasks.core.data.ITaskDataWorkingCopy; import org.eclipse.mylyn.tasks.core.data.TaskAttachmentMapper; import org.eclipse.mylyn.tasks.core.data.TaskAttachmentPartSource; import org.eclipse.mylyn.tasks.core.data.TaskAttribute; import org.eclipse.mylyn.tasks.core.data.TaskAttributeMapper; import org.eclipse.mylyn.tasks.core.data.TaskCommentMapper; import org.eclipse.mylyn.tasks.core.data.TaskData; import org.eclipse.mylyn.tasks.core.data.TaskDataModel; import org.eclipse.mylyn.tasks.core.data.TaskMapper; import org.eclipse.mylyn.tasks.ui.TasksUi; public class BugzillaRepositoryConnectorTest2 extends AbstractBugzillaTest { public void testAttachToExistingReport() throws Exception { init222(); String taskNumber = "33"; ITask task = generateLocalTaskAndDownload(taskNumber); assertNotNull(task); TaskDataModel model = createModel(task); TaskData taskData = model.getTaskData(); assertNotNull(taskData); assertEquals(SynchronizationState.SYNCHRONIZED, task.getSynchronizationState()); assertEquals(taskNumber, taskData.getTaskId()); // int numAttached = taskData.getAttributeMapper() // .getAttributesByType(taskData, TaskAttribute.TYPE_ATTACHMENT) // .size(); // String fileName = "test-attach-" + System.currentTimeMillis() + ".txt"; assertNotNull(repository.getUserName()); assertNotNull(repository.getPassword()); TaskAttribute attrAttachment = taskData.getAttributeMapper().createTaskAttachment(taskData); TaskAttachmentMapper attachmentMapper = TaskAttachmentMapper.createFrom(attrAttachment); /* Initialize a local attachment */ attachmentMapper.setDescription("Test attachment " + new Date()); attachmentMapper.setContentType("text/plain"); attachmentMapper.setPatch(false); attachmentMapper.setComment("Automated JUnit attachment test"); /* Test attempt to upload a non-existent file */ String filePath = "/this/is/not/a/real-file"; TaskAttachmentPartSource source = new TaskAttachmentPartSource( new FileTaskAttachmentSource(new File(filePath)), "real-file"); BugzillaClient client = connector.getClientManager().getClient(repository, new NullProgressMonitor()); try { client.postAttachment(taskNumber, attachmentMapper.getComment(), attachmentMapper.getDescription(), "application/octet-stream", false, source, new NullProgressMonitor()); fail(); } catch (Exception e) { } // // attachmentHandler.uploadAttachment(repository, task, comment, // // summary, file, contentType, isPatch, proxySettings) // // assertFalse(attachmentHandler.uploadAttachment(attachment, // // repository.getUserName(), repository.getPassword(), // // Proxy.NO_PROXY)); // assertEquals(SynchronizationState.SYNCHRONIZED, task.getSynchronizationState()); // task = TasksUiInternal.createTask(repository, taskNumber, new NullProgressMonitor()); // TasksUiInternal.synchronizeTask(connector, task, true, null); // assertEquals(numAttached, taskData.getAttachments().size()); // /* Test attempt to upload an empty file */ // File attachFile = new File(fileName); // attachment.setFilePath(attachFile.getAbsolutePath()); // BufferedWriter write = new BufferedWriter(new FileWriter(attachFile)); // attachFile = new File(attachment.getFilePath()); // attachment.setFile(attachFile); // attachment.setFilename(attachFile.getName()); // // assertFalse(attachmentHandler.uploadAttachment(attachment, // // repository.getUserName(), repository.getPassword(), // // Proxy.NO_PROXY)); // try { // client.postAttachment(attachment.getReport().getTaskId(), attachment.getComment(), attachment, null); // fail(); // } catch (Exception e) { // task = TasksUiInternal.createTask(repository, taskNumber, new NullProgressMonitor()); // TasksUiInternal.synchronizeTask(connector, task, true, null); // taskData = TasksUiPlugin.getTaskDataStorageManager().getNewTaskData(task.getRepositoryUrl(), task.getTaskId()); // assertEquals(numAttached, taskData.getAttachments().size()); // /* Test uploading a proper file */ // write.write("test file"); // write.close(); // attachment.setFilePath(attachFile.getAbsolutePath()); // // assertTrue(attachmentHandler.uploadAttachment(attachment, // // repository.getUserName(), repository.getPassword(), // // Proxy.NO_PROXY)); // File fileToAttach = new File(attachment.getFilePath()); // assertTrue(fileToAttach.exists()); // attachment.setFile(fileToAttach); // attachment.setFilename(fileToAttach.getName()); // client.postAttachment(attachment.getReport().getTaskId(), attachment.getComment(), attachment, null); // task = TasksUiInternal.createTask(repository, taskNumber, new NullProgressMonitor()); // TasksUiInternal.synchronizeTask(connector, task, true, null); // taskData = TasksUiPlugin.getTaskDataStorageManager().getNewTaskData(task.getRepositoryUrl(), task.getTaskId()); // assertEquals(numAttached + 1, taskData.getAttachments().size()); // // use assertion to track clean-up // assertTrue(attachFile.delete()); } public void testDataRetrieval() throws CoreException, ParseException { init(IBugzillaConstants.TEST_BUGZILLA_30_URL); TaskData data = connector.getTaskData(repository, "2", new NullProgressMonitor()); assertNotNull(data); TaskMapper mapper = new TaskMapper(data); assertEquals("2", data.getTaskId()); assertEquals("New bug submit", mapper.getSummary()); assertEquals("Test new bug submission", mapper.getDescription()); assertEquals(PriorityLevel.P2, mapper.getPriorityLevel()); assertEquals("TestComponent", mapper.getComponent()); assertEquals("nhapke@cs.ubc.ca", mapper.getOwner()); assertEquals("TestProduct", mapper.getProduct()); assertEquals("PC", mapper.getTaskData() .getRoot() .getMappedAttribute(BugzillaAttribute.REP_PLATFORM.getKey()) .getValue()); assertEquals("Windows", mapper.getTaskData() .getRoot() .getMappedAttribute(BugzillaAttribute.OP_SYS.getKey()) .getValue()); assertEquals("ASSIGNED", mapper.getTaskData().getRoot().getMappedAttribute( BugzillaAttribute.BUG_STATUS.getKey()).getValue()); SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd HH:mm"); SimpleDateFormat format2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); assertEquals(format1.parse("2007-03-20 16:37"), mapper.getCreationDate()); assertEquals(format2.parse("2008-09-24 13:33:02"), mapper.getModificationDate()); //assertEquals("", mapper.getTaskUrl()); //assertEquals("bugzilla", mapper.getTaskKind()); //assertEquals("", mapper.getTaskKey()); // test comments List<TaskAttribute> comments = data.getAttributeMapper().getAttributesByType(data, TaskAttribute.TYPE_COMMENT); assertEquals(12, comments.size()); TaskCommentMapper commentMap = TaskCommentMapper.createFrom(comments.get(0)); assertEquals("Rob Elves", commentMap.getAuthor().getName()); assertEquals("Created an attachment (id=1)\ntest\n\ntest attachments", commentMap.getText()); commentMap = TaskCommentMapper.createFrom(comments.get(10)); assertEquals("Tests", commentMap.getAuthor().getName()); assertEquals("test", commentMap.getText()); } public void testMidAirCollision() throws Exception { init30(); String taskNumber = "5"; // Get the task ITask task = generateLocalTaskAndDownload(taskNumber); ITaskDataWorkingCopy workingCopy = TasksUiPlugin.getTaskDataManager().getWorkingCopy(task); TaskData taskData = workingCopy.getLocalData(); assertNotNull(taskData); // TasksUiPlugin.getTaskList().addTask(task); String newCommentText = "BugzillaRepositoryClientTest.testMidAirCollision(): test " + (new Date()).toString(); TaskAttribute attrNewComment = taskData.getRoot().getMappedAttribute(TaskAttribute.COMMENT_NEW); attrNewComment.setValue(newCommentText); Set<TaskAttribute> changed = new HashSet<TaskAttribute>(); changed.add(attrNewComment); TaskAttribute attrDeltaTs = taskData.getRoot().getMappedAttribute(TaskAttribute.DATE_MODIFICATION); attrDeltaTs.setValue("2007-01-01 00:00:00"); changed.add(attrDeltaTs); workingCopy.save(changed, new NullProgressMonitor()); try { // Submit changes submit(task, taskData, changed); fail("Mid-air collision expected"); } catch (CoreException e) { assertTrue(e.getStatus().getMessage().indexOf("Mid-air collision occurred while submitting") != -1); return; } fail("Mid-air collision expected"); } public void testAuthenticationCredentials() throws Exception { init218(); ITask task = generateLocalTaskAndDownload("3"); assertNotNull(task); TasksUiPlugin.getTaskActivityManager().activateTask(task); File sourceContextFile = ContextCorePlugin.getContextStore().getFileForContext(task.getHandleIdentifier()); assertEquals(SynchronizationState.SYNCHRONIZED, task.getSynchronizationState()); sourceContextFile.createNewFile(); sourceContextFile.deleteOnExit(); AuthenticationCredentials oldCreds = repository.getCredentials(AuthenticationType.REPOSITORY); AuthenticationCredentials wrongCreds = new AuthenticationCredentials("wrong", "wrong"); repository.setCredentials(AuthenticationType.REPOSITORY, wrongCreds, false); TasksUiPlugin.getRepositoryManager().notifyRepositorySettingsChanged(repository); TaskData taskData = TasksUiPlugin.getTaskDataManager().getTaskData(task); TaskAttributeMapper mapper = taskData.getAttributeMapper(); TaskAttribute attribute = mapper.createTaskAttachment(taskData); try { AttachmentUtil.postContext(connector, repository, task, "test", attribute, new NullProgressMonitor()); } catch (CoreException e) { assertEquals(SynchronizationState.SYNCHRONIZED, task.getSynchronizationState()); assertTrue(e.getStatus().getMessage().indexOf("invalid username or password") != -1); return; } finally { repository.setCredentials(AuthenticationType.REPOSITORY, oldCreds, false); TasksUiPlugin.getRepositoryManager().notifyRepositorySettingsChanged(repository); } fail("Should have failed due to invalid userid and password."); } public void testSynchronize() throws CoreException, Exception { init222(); // Get the task ITask task = generateLocalTaskAndDownload("3"); TasksUi.getTaskDataManager().discardEdits(task); TaskDataModel model = createModel(task); TaskData taskData = model.getTaskData(); assertNotNull(taskData); // int numComments = taskData.getAttributeMapper() // .getAttributesByType(taskData, TaskAttribute.TYPE_ATTACHMENT) // .size(); // Modify it String newCommentText = "BugzillaRepositoryClientTest.testSynchronize(): " + (new Date()).toString(); TaskAttribute attrNewComment = taskData.getRoot().getMappedAttribute(TaskAttribute.COMMENT_NEW); attrNewComment.setValue(newCommentText); model.attributeChanged(attrNewComment); model.save(new NullProgressMonitor()); assertEquals(SynchronizationState.OUTGOING, task.getSynchronizationState()); submit(model); assertEquals(SynchronizationState.SYNCHRONIZED, task.getSynchronizationState()); // TaskData taskData2 = workingCopy.getRepositoryData(); // TaskMapper taskData2Mapper = new TaskMapper(taskData2); // TaskMapper taskData1Mapper = new TaskMapper(taskData); // assertFalse(taskData2Mapper.getModificationDate().equals(taskData1Mapper.getModificationDate())); // // Still not read // assertFalse(taskData2.getLastModified().equals(task.getLastReadTimeStamp())); // TasksUiPlugin.getTaskDataManager().setTaskRead(task, true); // assertEquals(taskData2.getLastModified(), task.getLastReadTimeStamp()); // assertTrue(taskData2.getComments().size() > numComments); // // Has no outgoing changes or conflicts yet needs synch // // because task doesn't have bug report (new query hit) // // Result: retrieved with no incoming status // // task.setSyncState(SynchronizationState.SYNCHRONIZED); // TasksUiPlugin.getTaskDataStorageManager().remove(task.getRepositoryUrl(), task.getTaskId()); // TasksUiInternal.synchronizeTask(connector, task, false, null); // assertEquals(SynchronizationState.SYNCHRONIZED, task.getSynchronizationState()); // RepositoryTaskData bugReport2 = null; // bugReport2 = TasksUiPlugin.getTaskDataStorageManager() // .getNewTaskData(task.getRepositoryUrl(), task.getTaskId()); // assertNotNull(bugReport2); // assertEquals(task.getTaskId(), bugReport2.getTaskId()); // assertEquals(newCommentText, bugReport2.getComments().get(numComments).getText()); // // TODO: Test that comment was appended // // ArrayList<Comment> comments = task.getTaskData().getComments(); // // assertNotNull(comments); // // assertTrue(comments.size() > 0); // // Comment lastComment = comments.get(comments.size() - 1); // // assertEquals(newCommentText, lastComment.getText()); } public void testMissingHits() throws Exception { init(IBugzillaConstants.ECLIPSE_BUGZILLA_URL); //repository.setAuthenticationCredentials("username", "password"); String queryString = "https://bugs.eclipse.org/bugs/buglist.cgi?query_format=advanced&short_desc_type=allwordssubstr&short_desc=&classification=Tools&product=Mylyn&component=Bugzilla&long_desc_type=allwordssubstr&long_desc=&bug_file_loc_type=allwordssubstr&bug_file_loc=&status_whiteboard_type=allwordssubstr&status_whiteboard=&keywords_type=allwords&keywords=&bug_status=NEW&priority=P1&priority=P2&emailtype1=substring&email1=&emailtype2=substring&email2=&bugidtype=include&bug_id=&votes=&chfieldfrom=&chfieldto=Now&chfieldvalue=&cmdtype=doit&order=Reuse+same+sort+as+last+time&field0-0-0=noop&type0-0-0=noop&value0-0-0="; RepositoryQuery query = new RepositoryQuery(BugzillaCorePlugin.CONNECTOR_KIND, "test"); query.setRepositoryUrl(repository.getRepositoryUrl()); query.setUrl(queryString); TasksUiPlugin.getTaskList().addQuery(query); TasksUiInternal.synchronizeQuery(connector, query, null, true); for (ITask task : query.getChildren()) { assertTrue(task.getSynchronizationState() == SynchronizationState.INCOMING); TasksUiPlugin.getTaskDataManager().setTaskRead(task, true); assertTrue(task.getSynchronizationState() == SynchronizationState.SYNCHRONIZED); } repository.setSynchronizationTimeStamp("1970-01-01");//getSynchronizationTimeStamp(); TasksUiInternal.synchronizeQuery(connector, query, null, true); for (ITask task : query.getChildren()) { assertTrue(task.getSynchronizationState() == SynchronizationState.INCOMING); } } }
package org.exist.xquery; import org.exist.dom.DocumentSet; import org.exist.xquery.util.ExpressionDumper; import org.exist.xquery.value.BooleanValue; import org.exist.xquery.value.Item; import org.exist.xquery.value.Sequence; import org.exist.xquery.value.Type; /** * Implements the "castable as" XQuery expression. * * @author wolf */ public class CastableExpression extends AbstractExpression { private Expression expression; private int requiredCardinality; private final int requiredType; /** * * * @param requiredCardinality * @param context * @param expr * @param requiredType */ public CastableExpression(XQueryContext context, Expression expr, int requiredType, int requiredCardinality) { super(context); this.expression = expr; this.requiredType = requiredType; this.requiredCardinality = requiredCardinality; if (!Type.subTypeOf(expression.returnsType(), Type.ATOMIC)) expression = new Atomize(context, expression); } /* (non-Javadoc) * @see org.exist.xquery.CastExpression#returnsType() */ public int returnsType() { return Type.BOOLEAN; } /* (non-Javadoc) * @see org.exist.xquery.AbstractExpression#getCardinality() */ public int getCardinality() { return Cardinality.EXACTLY_ONE; } public int getDependencies() { return Dependency.CONTEXT_SET + Dependency.CONTEXT_ITEM; } /* (non-Javadoc) * @see org.exist.xquery.Expression#analyze(org.exist.xquery.Expression) */ public void analyze(AnalyzeContextInfo contextInfo) throws XPathException { contextInfo.setParent(this); expression.analyze(contextInfo); } /* (non-Javadoc) * @see org.exist.xquery.AbstractExpression#eval(org.exist.xquery.value.Sequence, org.exist.xquery.value.Item) */ public Sequence eval(Sequence contextSequence, Item contextItem) throws XPathException { if (context.getProfiler().isEnabled()) { context.getProfiler().start(this); context.getProfiler().message(this, Profiler.DEPENDENCIES, "DEPENDENCIES", Dependency.getDependenciesName(this.getDependencies())); if (contextSequence != null) context.getProfiler().message(this, Profiler.START_SEQUENCES, "CONTEXT SEQUENCE", contextSequence); if (contextItem != null) context.getProfiler().message(this, Profiler.START_SEQUENCES, "CONTEXT ITEM", contextItem.toSequence()); } if (requiredType == Type.ATOMIC) throw new XPathException(getASTNode(), "XPST0080: cannot convert to " + Type.getTypeName(Type.ATOMIC)); Sequence result; //... for the rationale //may be more complicated : let's see with following XQTS versions if (requiredType == Type.QNAME && Dependency.dependsOnVar(expression)) result = BooleanValue.FALSE; else { Sequence seq = expression.eval(contextSequence, contextItem); if(seq.isEmpty()) { //If ? is specified after the target type, the result of the cast expression is an empty sequence. if (Cardinality.checkCardinality(requiredCardinality, Cardinality.ZERO)) result = BooleanValue.TRUE; //If ? is not specified after the target type, a type error is raised [err:XPTY0004]. else //TODO : raise the error ? result = BooleanValue.FALSE; } else { try { seq.itemAt(0).convertTo(requiredType); //If ? is specified after the target type, the result of the cast expression is an empty sequence. if (Cardinality.checkCardinality(requiredCardinality, seq.getCardinality())) result = BooleanValue.TRUE; //If ? is not specified after the target type, a type error is raised [err:XPTY0004]. else result = BooleanValue.FALSE; //TODO : improve by *not* using a costly exception ? } catch(XPathException e) { result = BooleanValue.FALSE; } } } if (context.getProfiler().isEnabled()) context.getProfiler().end(this, "", result); return result; } /* (non-Javadoc) * @see org.exist.xquery.Expression#dump(org.exist.xquery.util.ExpressionDumper) */ public void dump(ExpressionDumper dumper) { expression.dump(dumper); dumper.display(" castable as "); dumper.display(Type.getTypeName(requiredType)); } public String toString() { StringBuffer result = new StringBuffer(); result.append(expression.toString()); result.append(" castable as "); result.append(Type.getTypeName(requiredType)); return result.toString(); } public void setContextDocSet(DocumentSet contextSet) { super.setContextDocSet(contextSet); expression.setContextDocSet(contextSet); } public void resetState() { super.resetState(); expression.resetState(); } }
package com.wakatime.intellij.plugin; import com.intellij.AppTopics; import com.intellij.ide.DataManager; import com.intellij.openapi.actionSystem.*; import com.intellij.openapi.application.ApplicationInfo; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.components.ApplicationComponent; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.editor.EditorFactory; import com.intellij.openapi.project.Project; import com.intellij.openapi.project.ProjectManager; import com.intellij.openapi.ui.Messages; import com.intellij.util.PlatformUtils; import com.intellij.util.messages.MessageBus; import com.intellij.util.messages.MessageBusConnection; import org.jetbrains.annotations.NotNull; import java.io.*; import java.util.ArrayList; import java.util.Arrays; import org.apache.log4j.Level; public class WakaTime implements ApplicationComponent { public static final String VERSION = "4.0.2"; public static final String CONFIG = ".wakatime.cfg"; public static final long FREQUENCY = 2; // minutes between pings public static final Logger log = Logger.getInstance("WakaTime"); public static String IDE_NAME; public static String IDE_VERSION; public static MessageBusConnection connection; public static Boolean DEBUG = false; public static Boolean READY = false; public static String lastFile = null; public static long lastTime = 0; public WakaTime() { } public void initComponent() { log.info("Initializing WakaTime plugin v" + VERSION + " (https://wakatime.com/)"); // Set runtime constants IDE_NAME = PlatformUtils.getPlatformPrefix(); IDE_VERSION = ApplicationInfo.getInstance().getFullVersion(); ApplicationManager.getApplication().executeOnPooledThread(new Runnable() { public void run() { ApplicationManager.getApplication().runReadAction(new Runnable() { public void run() { if (!Dependencies.isCLIInstalled()) { log.info("Downloading and installing wakatime-cli ..."); Dependencies.installCLI(); WakaTime.READY = true; log.info("Finished downloading and installing wakatime-cli."); } else if (Dependencies.isCLIOld()) { log.info("Upgrading wakatime-cli ..."); Dependencies.upgradeCLI(); WakaTime.READY = true; log.info("Finished upgrading wakatime-cli."); } else { WakaTime.READY = true; log.info("wakatime-cli is up to date."); } } }); } }); if (Dependencies.isPythonInstalled()) { WakaTime.DEBUG = WakaTime.isDebugEnabled(); if (WakaTime.DEBUG) { log.setLevel(Level.DEBUG); log.debug("Logging level set to DEBUG"); } log.debug("Python location: " + Dependencies.getPythonLocation()); log.debug("CLI location: " + Dependencies.getCLILocation()); // prompt for apiKey if it does not already exist if (ApiKey.getApiKey().equals("")) { Project project = ProjectManager.getInstance().getDefaultProject(); ApiKey apiKey = new ApiKey(project); apiKey.promptForApiKey(); } log.debug("Api Key: "+ApiKey.getApiKey()); // add WakaTime item to File menu ActionManager am = ActionManager.getInstance(); PluginMenu action = new PluginMenu(); am.registerAction("WakaTimeApiKey", action); DefaultActionGroup fileMenu = (DefaultActionGroup) am.getAction("FileMenu"); fileMenu.addSeparator(); fileMenu.add(action); // Setup message listeners MessageBus bus = ApplicationManager.getApplication().getMessageBus(); connection = bus.connect(); connection.subscribe(AppTopics.FILE_DOCUMENT_SYNC, new CustomSaveListener()); EditorFactory.getInstance().getEventMulticaster().addDocumentListener(new CustomDocumentListener()); log.info("Finished initializing WakaTime plugin"); } else { ApplicationManager.getApplication().executeOnPooledThread(new Runnable() { public void run() { ApplicationManager.getApplication().runReadAction(new Runnable() { public void run() { log.info("Python not found, downloading python..."); // download and install python Dependencies.installPython(); if (Dependencies.isPythonInstalled()) { log.info("Finished installing python..."); } else { ApplicationManager.getApplication().invokeLater(new Runnable(){ public void run(){ Messages.showErrorDialog("WakaTime requires Python to be installed.\nYou can install it from https: } }); } } }); } }); } } public void disposeComponent() { try { connection.disconnect(); } catch(Exception e) { } } public static void logFile(String file, boolean isWrite) { if (WakaTime.READY) { WakaTime.executeCLI(file, isWrite, 0); } } public static void executeCLI(String file, boolean isWrite, int tries) { ArrayList<String> cmds = new ArrayList<String>(); cmds.add(Dependencies.getPythonLocation()); cmds.add(Dependencies.getCLILocation()); cmds.add("--key"); cmds.add(ApiKey.getApiKey()); cmds.add("--file"); cmds.add(file); String project = WakaTime.getProjectName(); if (project != null) { cmds.add("--project"); cmds.add(project); } cmds.add("--plugin"); cmds.add(IDE_NAME+"/"+IDE_VERSION+" "+IDE_NAME+"-wakatime/"+VERSION); if (isWrite) cmds.add("--write"); try { log.debug("Executing CLI: " + Arrays.toString(cmds.toArray())); Process proc = Runtime.getRuntime().exec(cmds.toArray(new String[cmds.size()])); if (WakaTime.DEBUG) { BufferedReader stdInput = new BufferedReader(new InputStreamReader(proc.getInputStream())); BufferedReader stdError = new BufferedReader(new InputStreamReader(proc.getErrorStream())); proc.waitFor(); String s; while ((s = stdInput.readLine()) != null) { log.debug(s); } while ((s = stdError.readLine()) != null) { log.debug(s); } log.debug("Command finished with return value: "+proc.exitValue()); } } catch (Exception e) { if (tries < 3) { log.debug(e); try { Thread.sleep(30); } catch (InterruptedException e1) { log.error(e1); } WakaTime.executeCLI(file, isWrite, tries+1); } else { log.error(e); } } } public static String getProjectName() { DataContext dataContext = DataManager.getInstance().getDataContext(); if (dataContext != null) { Project project = null; try { project = PlatformDataKeys.PROJECT.getData(dataContext); } catch (NoClassDefFoundError e) { try { project = DataKeys.PROJECT.getData(dataContext); } catch (NoClassDefFoundError ex) { } } if (project != null) { return project.getName(); } } return null; } public static boolean enoughTimePassed(long currentTime) { return WakaTime.lastTime + FREQUENCY * 60 < currentTime; } public static Boolean isDebugEnabled() { Boolean debug = false; File userHome = new File(System.getProperty("user.home")); File configFile = new File(userHome, WakaTime.CONFIG); BufferedReader br = null; try { br = new BufferedReader(new FileReader(configFile.getAbsolutePath())); } catch (FileNotFoundException e1) {} if (br != null) { try { String line = br.readLine(); while (line != null) { String[] parts = line.split("="); if (parts.length == 2 && parts[0].trim().equals("debug") && parts[1].trim().toLowerCase().equals("true")) { debug = true; } line = br.readLine(); } } catch (IOException e) { e.printStackTrace(); } finally { try { br.close(); } catch (IOException e) { e.printStackTrace(); } } } return debug; } @NotNull public String getComponentName() { return "WakaTime"; } }
package org.metaborg.spoofax.meta.core.pluto.build.misc; import java.io.File; import org.apache.commons.vfs2.FileObject; import org.metaborg.core.language.ILanguageImpl; import org.metaborg.spoofax.core.unit.ISpoofaxInputUnit; import org.metaborg.spoofax.core.unit.ISpoofaxParseUnit; import org.metaborg.spoofax.meta.core.pluto.SpoofaxBuilder; import org.metaborg.spoofax.meta.core.pluto.SpoofaxBuilderFactory; import org.metaborg.spoofax.meta.core.pluto.SpoofaxBuilderFactoryFactory; import org.metaborg.spoofax.meta.core.pluto.SpoofaxContext; import org.metaborg.spoofax.meta.core.pluto.SpoofaxInput; import org.spoofax.interpreter.terms.IStrategoTerm; import org.sugarj.common.FileCommands; import build.pluto.builder.BuildRequest; import build.pluto.dependency.Origin; import build.pluto.output.Out; import build.pluto.output.OutputPersisted; import build.pluto.output.OutputTransient; import build.pluto.stamp.FileHashStamper; import build.pluto.stamp.Stamper; public class ParseFile extends SpoofaxBuilder<ParseFile.Input, Out<IStrategoTerm>> { public static class Input extends SpoofaxInput { private static final long serialVersionUID = -4790160594622807382L; public final File file; public final boolean persistResult; public final boolean silent; public final Origin requiredUnits; public Input(SpoofaxContext context, File file, boolean persistResult, Origin requiredUnits) { super(context); this.file = file; this.persistResult = persistResult; this.silent = false; this.requiredUnits = requiredUnits; } public Input(SpoofaxContext context, File file, boolean persistResult, boolean silent, Origin requiredUnits) { super(context); this.file = file; this.persistResult = persistResult; this.silent = silent; this.requiredUnits = requiredUnits; } } public final static SpoofaxBuilderFactory<Input, Out<IStrategoTerm>, ParseFile> factory = SpoofaxBuilderFactoryFactory.of(ParseFile.class, Input.class); public ParseFile(Input input) { super(input); } public static BuildRequest<Input, Out<IStrategoTerm>, ParseFile, SpoofaxBuilderFactory<Input, Out<IStrategoTerm>, ParseFile>> request(Input input) { return new BuildRequest<>(factory, input); } public static Origin origin(Input input) { return Origin.from(request(input)); } @Override protected String description(Input input) { return input.silent ? null : "Parse file " + input.file; } @Override protected Stamper defaultStamper() { return FileHashStamper.instance; } @Override public File persistentPath(Input input) { final String rel = input.file.getPath(); final String relname = rel.replace(File.separatorChar, '_').replace(':', '_'); return context.depPath("parse." + relname + ".dep"); } @Override protected Out<IStrategoTerm> build(Input input) throws Throwable { requireBuild(input.requiredUnits); require(input.file); if(!FileCommands.exists(input.file)) { return null; } final FileObject resource = context.resourceService().resolve(input.file); final ILanguageImpl language = context.languageIdentifierService().identify(resource); if(language == null) { return null; } final String text = context.sourceTextService().text(resource); final ISpoofaxInputUnit inputUnit = context.unitService().inputUnit(resource, text, language, null); final ISpoofaxParseUnit result = context.syntaxService().parse(inputUnit); if(!result.valid()) { return null; } return input.persistResult ? OutputPersisted.of(result.ast()) : OutputTransient.of(result.ast()); } }
package org.exist.xquery.test; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileFilter; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import org.exist.xmldb.XQueryService; import org.xmldb.api.DatabaseManager; import org.xmldb.api.base.Collection; import org.xmldb.api.base.Database; import org.xmldb.api.base.ResourceSet; import org.xmldb.api.base.XMLDBException; import org.xmldb.api.modules.CollectionManagementService; import org.xmldb.api.modules.XMLResource; /** * @author Wolfgang Meier (wolfgang@exist-db.org) */ public class XQueryUseCase { private final static String URI = "xmldb:exist: private final static String baseDir = "samples/xquery/use-cases"; private Collection root = null; /* * @see TestCase#setUp() */ protected void setUp() throws Exception { // initialize driver Class cl = Class.forName("org.exist.xmldb.DatabaseImpl"); Database database = (Database) cl.newInstance(); database.setProperty("create-database", "true"); DatabaseManager.registerDatabase(database); root = DatabaseManager.getCollection("xmldb:exist:///db", "admin", null); } public void doTest(String useCase) throws Exception { CollectionManagementService service = (CollectionManagementService) root.getService( "CollectionManagementService", "1.0"); root = service.createCollection(useCase); File file = new File(baseDir + File.separatorChar + useCase); if (!(file.canRead() && file.isDirectory())) throw new RuntimeException("Cannot read data for use-case " + useCase); setupData(file); processQueries(file); } protected void processQueries(File file) throws Exception { File[] files = file.listFiles(new FileFilter() { public boolean accept(File pathname) { return pathname.getName().startsWith("q") && pathname.getName().endsWith(".xq"); } }); for(int i = 0; i < files.length; i++) { System.err.println("processing use-case: " + files[i].getAbsolutePath()); System.err.println("========================================================================"); String query = readQuery(files[i]); System.err.println(query); System.err.println("_________________________________________________________________________________"); XQueryService service = (XQueryService)root.getService("XQueryService", "1.0"); ResourceSet results; try { results = service.query(query); for(int j = 0; j < results.getSize(); j++) { String output = (String)results.getResource(j).getContent(); System.err.println(output); } } catch (Exception e) { Throwable cause = e.getCause(); if ( cause == null ) cause = e; System.err.println( "Exception: " + e.getClass() + " - "+ cause ); for (int j = 0; j < 4; j++) { StackTraceElement el = cause.getStackTrace()[j]; System.err.println( el ); } e.getStackTrace(); // rethrow for JUnit reporting throw e; } System.err.println("========================================================================"); } } protected void setupData(File file) throws Exception { File[] files = file.listFiles(new FileFilter() { public boolean accept(File pathname) { return pathname.getName().endsWith(".xml"); } }); for (int i = 0; i < files.length; i++) { XMLResource res = (XMLResource) root.createResource(files[i].getName(), "XMLResource"); res.setContent(files[i]); root.storeResource(res); } } protected String readQuery(File f) throws IOException { ByteArrayOutputStream os = new ByteArrayOutputStream(); byte[] t = new byte[512]; InputStream is = new FileInputStream(f); int count = 0; while((count = is.read(t)) != -1) { os.write(t, 0, count); } return new String(os.toString("UTF-8")); } }